Release 5.22
[org-mode.git] / org.el
blob714995c0e52f8cab3034b946bec94543e7a8ccc9
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.22
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.22"
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 active. If %i is indented,
1508 the entire inserted text will be indented as well.
1509 %c content of the clipboard, or current kill ring head
1510 %^g prompt for tags, with completion on tags in target file
1511 %^G prompt for tags, with completion all tags in all agenda files
1512 %:keyword specific information for certain link types, see below
1513 %[pathname] insert the contents of the file given by `pathname'
1514 %(sexp) evaluate elisp `(sexp)' and replace with the result
1515 %! Store this note immediately after filling the template
1517 %? After completing the template, position cursor here.
1519 Apart from these general escapes, you can access information specific to the
1520 link type that is created. For example, calling `remember' in emails or gnus
1521 will record the author and the subject of the message, which you can access
1522 with %:author and %:subject, respectively. Here is a complete list of what
1523 is recorded for each link type.
1525 Link type | Available information
1526 -------------------+------------------------------------------------------
1527 bbdb | %:type %:name %:company
1528 vm, wl, mh, rmail | %:type %:subject %:message-id
1529 | %:from %:fromname %:fromaddress
1530 | %:to %:toname %:toaddress
1531 | %:fromto (either \"to NAME\" or \"from NAME\")
1532 gnus | %:group, for messages also all email fields
1533 w3, w3m | %:type %:url
1534 info | %:type %:file %:node
1535 calendar | %:type %:date"
1536 :group 'org-remember
1537 :get (lambda (var) ; Make sure all entries have 5 elements
1538 (mapcar (lambda (x)
1539 (if (not (stringp (car x))) (setq x (cons "" x)))
1540 (cond ((= (length x) 4) (append x '("")))
1541 ((= (length x) 3) (append x '("" "")))
1542 (t x)))
1543 (default-value var)))
1544 :type '(repeat
1545 :tag "enabled"
1546 (list :value ("" ?a "\n" nil nil)
1547 (string :tag "Name")
1548 (character :tag "Selection Key")
1549 (string :tag "Template")
1550 (choice
1551 (file :tag "Destination file")
1552 (const :tag "Prompt for file" nil))
1553 (choice
1554 (string :tag "Destination headline")
1555 (const :tag "Selection interface for heading")))))
1557 (defcustom org-reverse-note-order nil
1558 "Non-nil means, store new notes at the beginning of a file or entry.
1559 When nil, new notes will be filed to the end of a file or entry.
1560 This can also be a list with cons cells of regular expressions that
1561 are matched against file names, and values."
1562 :group 'org-remember
1563 :type '(choice
1564 (const :tag "Reverse always" t)
1565 (const :tag "Reverse never" nil)
1566 (repeat :tag "By file name regexp"
1567 (cons regexp boolean))))
1569 (defcustom org-refile-targets nil
1570 "Targets for refiling entries with \\[org-refile].
1571 This is list of cons cells. Each cell contains:
1572 - a specification of the files to be considered, either a list of files,
1573 or a symbol whose function or value fields will be used to retrieve
1574 a file name or a list of file names. Nil means, refile to a different
1575 heading in the current buffer.
1576 - A specification of how to find candidate refile targets. This may be
1577 any of
1578 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1579 This tag has to be present in all target headlines, inheritance will
1580 not be considered.
1581 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1582 todo keyword.
1583 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1584 headlines that are refiling targets.
1585 - a cons cell (:level . N). Any headline of level N is considered a target.
1586 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1587 ;; FIXME: what if there are a var and func with same name???
1588 :group 'org-remember
1589 :type '(repeat
1590 (cons
1591 (choice :value org-agenda-files
1592 (const :tag "All agenda files" org-agenda-files)
1593 (const :tag "Current buffer" nil)
1594 (function) (variable) (file))
1595 (choice :tag "Identify target headline by"
1596 (cons :tag "Specific tag" (const :tag) (string))
1597 (cons :tag "TODO keyword" (const :todo) (string))
1598 (cons :tag "Regular expression" (const :regexp) (regexp))
1599 (cons :tag "Level number" (const :level) (integer))
1600 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1602 (defcustom org-refile-use-outline-path nil
1603 "Non-nil means, provide refile targets as paths.
1604 So a level 3 headline will be available as level1/level2/level3.
1605 When the value is `file', also include the file name (without directory)
1606 into the path. When `full-file-path', include the full file path."
1607 :group 'org-remember
1608 :type '(choice
1609 (const :tag "Not" nil)
1610 (const :tag "Yes" t)
1611 (const :tag "Start with file name" file)
1612 (const :tag "Start with full file path" full-file-path)))
1614 (defgroup org-todo nil
1615 "Options concerning TODO items in Org-mode."
1616 :tag "Org TODO"
1617 :group 'org)
1619 (defgroup org-progress nil
1620 "Options concerning Progress logging in Org-mode."
1621 :tag "Org Progress"
1622 :group 'org-time)
1624 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1625 "List of TODO entry keyword sequences and their interpretation.
1626 \\<org-mode-map>This is a list of sequences.
1628 Each sequence starts with a symbol, either `sequence' or `type',
1629 indicating if the keywords should be interpreted as a sequence of
1630 action steps, or as different types of TODO items. The first
1631 keywords are states requiring action - these states will select a headline
1632 for inclusion into the global TODO list Org-mode produces. If one of
1633 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1634 signify that no further action is necessary. If \"|\" is not found,
1635 the last keyword is treated as the only DONE state of the sequence.
1637 The command \\[org-todo] cycles an entry through these states, and one
1638 additional state where no keyword is present. For details about this
1639 cycling, see the manual.
1641 TODO keywords and interpretation can also be set on a per-file basis with
1642 the special #+SEQ_TODO and #+TYP_TODO lines.
1644 Each keyword can optionally specify a character for fast state selection
1645 \(in combination with the variable `org-use-fast-todo-selection')
1646 and specifiers for state change logging, using the same syntax
1647 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1648 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1649 indicates to record a time stamp each time this state is selected.
1650 \"WAIT(w@)\" says that the user should in addition be prompted for a
1651 note, and \"WAIT(w@/@)\" says that a note should be taken both when
1652 entering and when leaving this state.
1654 For backward compatibility, this variable may also be just a list
1655 of keywords - in this case the interptetation (sequence or type) will be
1656 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1657 :group 'org-todo
1658 :group 'org-keywords
1659 :type '(choice
1660 (repeat :tag "Old syntax, just keywords"
1661 (string :tag "Keyword"))
1662 (repeat :tag "New syntax"
1663 (cons
1664 (choice
1665 :tag "Interpretation"
1666 (const :tag "Sequence (cycling hits every state)" sequence)
1667 (const :tag "Type (cycling directly to DONE)" type))
1668 (repeat
1669 (string :tag "Keyword"))))))
1671 (defvar org-todo-keywords-1 nil
1672 "All TODO and DONE keywords active in a buffer.")
1673 (make-variable-buffer-local 'org-todo-keywords-1)
1674 (defvar org-todo-keywords-for-agenda nil)
1675 (defvar org-done-keywords-for-agenda nil)
1676 (defvar org-not-done-keywords nil)
1677 (make-variable-buffer-local 'org-not-done-keywords)
1678 (defvar org-done-keywords nil)
1679 (make-variable-buffer-local 'org-done-keywords)
1680 (defvar org-todo-heads nil)
1681 (make-variable-buffer-local 'org-todo-heads)
1682 (defvar org-todo-sets nil)
1683 (make-variable-buffer-local 'org-todo-sets)
1684 (defvar org-todo-log-states nil)
1685 (make-variable-buffer-local 'org-todo-log-states)
1686 (defvar org-todo-kwd-alist nil)
1687 (make-variable-buffer-local 'org-todo-kwd-alist)
1688 (defvar org-todo-key-alist nil)
1689 (make-variable-buffer-local 'org-todo-key-alist)
1690 (defvar org-todo-key-trigger nil)
1691 (make-variable-buffer-local 'org-todo-key-trigger)
1693 (defcustom org-todo-interpretation 'sequence
1694 "Controls how TODO keywords are interpreted.
1695 This variable is in principle obsolete and is only used for
1696 backward compatibility, if the interpretation of todo keywords is
1697 not given already in `org-todo-keywords'. See that variable for
1698 more information."
1699 :group 'org-todo
1700 :group 'org-keywords
1701 :type '(choice (const sequence)
1702 (const type)))
1704 (defcustom org-use-fast-todo-selection 'prefix
1705 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1706 This variable describes if and under what circumstances the cycling
1707 mechanism for TODO keywords will be replaced by a single-key, direct
1708 selection scheme.
1710 When nil, fast selection is never used.
1712 When the symbol `prefix', it will be used when `org-todo' is called with
1713 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1714 in an agenda buffer.
1716 When t, fast selection is used by default. In this case, the prefix
1717 argument forces cycling instead.
1719 In all cases, the special interface is only used if access keys have actually
1720 been assigned by the user, i.e. if keywords in the configuration are followed
1721 by a letter in parenthesis, like TODO(t)."
1722 :group 'org-todo
1723 :type '(choice
1724 (const :tag "Never" nil)
1725 (const :tag "By default" t)
1726 (const :tag "Only with C-u C-c C-t" prefix)))
1728 (defcustom org-after-todo-state-change-hook nil
1729 "Hook which is run after the state of a TODO item was changed.
1730 The new state (a string with a TODO keyword, or nil) is available in the
1731 Lisp variable `state'."
1732 :group 'org-todo
1733 :type 'hook)
1735 (defcustom org-log-done nil
1736 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1737 When equal to the list (done), also prompt for a closing note.
1738 This can also be configured on a per-file basis by adding one of
1739 the following lines anywhere in the buffer:
1741 #+STARTUP: logdone
1742 #+STARTUP: lognotedone
1743 #+STARTUP: nologdone"
1744 :group 'org-todo
1745 :group 'org-progress
1746 :type '(choice
1747 (const :tag "No logging" nil)
1748 (const :tag "Record CLOSED timestamp" time)
1749 (const :tag "Record CLOSED timestamp with closing note." note)))
1751 ;; Normalize old uses of org-log-done.
1752 (cond
1753 ((eq org-log-done t) (setq org-log-done 'time))
1754 ((and (listp org-log-done) (memq 'done org-log-done))
1755 (setq org-log-done 'note)))
1757 ;; FIXME: document
1758 (defcustom org-log-note-clock-out nil
1759 "Non-nil means, recored a note when clocking out of an item.
1760 This can also be configured on a per-file basis by adding one of
1761 the following lines anywhere in the buffer:
1763 #+STARTUP: lognoteclock-out
1764 #+STARTUP: nolognoteclock-out"
1765 :group 'org-todo
1766 :group 'org-progress
1767 :type 'boolean)
1769 (defcustom org-log-done-with-time t
1770 "Non-nil means, the CLOSED time stamp will contain date and time.
1771 When nil, only the date will be recorded."
1772 :group 'org-progress
1773 :type 'boolean)
1775 (defcustom org-log-note-headings
1776 '((done . "CLOSING NOTE %t")
1777 (state . "State %-12s %t")
1778 (clock-out . ""))
1779 "Headings for notes added when clocking out or closing TODO items.
1780 The value is an alist, with the car being a symbol indicating the note
1781 context, and the cdr is the heading to be used. The heading may also be the
1782 empty string.
1783 %t in the heading will be replaced by a time stamp.
1784 %s will be replaced by the new TODO state, in double quotes.
1785 %u will be replaced by the user name.
1786 %U will be replaced by the full user name."
1787 :group 'org-todo
1788 :group 'org-progress
1789 :type '(list :greedy t
1790 (cons (const :tag "Heading when closing an item" done) string)
1791 (cons (const :tag
1792 "Heading when changing todo state (todo sequence only)"
1793 state) string)
1794 (cons (const :tag "Heading when clocking out" clock-out) string)))
1796 (defcustom org-log-states-order-reversed t
1797 "Non-nil means, the latest state change note will be directly after heading.
1798 When nil, the notes will be orderer according to time."
1799 :group 'org-todo
1800 :group 'org-progress
1801 :type 'boolean)
1803 (defcustom org-log-repeat 'time
1804 "Non-nil means, record moving through the DONE state when triggering repeat.
1805 An auto-repeating tasks is immediately switched back to TODO when marked
1806 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1807 the TODO keyword definition, or recording a cloing note by setting
1808 `org-log-done', there will be no record of the task moving trhough DONE.
1809 This variable forces taking a note anyway. Possible values are:
1811 nil Don't force a record
1812 time Record a time stamp
1813 note Record a note
1815 This option can also be set with on a per-file-basis with
1817 #+STARTUP: logrepeat
1818 #+STARTUP: lognoterepeat
1819 #+STARTUP: nologrepeat
1821 You can have local logging settings for a subtree by setting the LOGGING
1822 property to one or more of these keywords."
1823 :group 'org-todo
1824 :group 'org-progress
1825 :type '(choice
1826 (const :tag "Don't force a record" nil)
1827 (const :tag "Force recording the DONE state" time)
1828 (const :tag "Force recording a note with the DONE state" note)))
1830 (defcustom org-clock-into-drawer 2
1831 "Should clocking info be wrapped into a drawer?
1832 When t, clocking info will always be inserted into a :CLOCK: drawer.
1833 If necessary, the drawer will be created.
1834 When nil, the drawer will not be created, but used when present.
1835 When an integer and the number of clocking entries in an item
1836 reaches or exceeds this number, a drawer will be created."
1837 :group 'org-todo
1838 :group 'org-progress
1839 :type '(choice
1840 (const :tag "Always" t)
1841 (const :tag "Only when drawer exists" nil)
1842 (integer :tag "When at least N clock entries")))
1844 (defcustom org-clock-out-when-done t
1845 "When t, the clock will be stopped when the relevant entry is marked DONE.
1846 Nil means, clock will keep running until stopped explicitly with
1847 `C-c C-x C-o', or until the clock is started in a different item."
1848 :group 'org-progress
1849 :type 'boolean)
1851 (defcustom org-clock-in-switch-to-state nil
1852 "Set task to a special todo state while clocking it.
1853 The value should be the state to which the entry should be switched."
1854 :group 'org-progress
1855 :group 'org-todo
1856 :type '(choice
1857 (const :tag "Don't force a state" nil)
1858 (string :tag "State")))
1860 (defgroup org-priorities nil
1861 "Priorities in Org-mode."
1862 :tag "Org Priorities"
1863 :group 'org-todo)
1865 (defcustom org-highest-priority ?A
1866 "The highest priority of TODO items. A character like ?A, ?B etc.
1867 Must have a smaller ASCII number than `org-lowest-priority'."
1868 :group 'org-priorities
1869 :type 'character)
1871 (defcustom org-lowest-priority ?C
1872 "The lowest priority of TODO items. A character like ?A, ?B etc.
1873 Must have a larger ASCII number than `org-highest-priority'."
1874 :group 'org-priorities
1875 :type 'character)
1877 (defcustom org-default-priority ?B
1878 "The default priority of TODO items.
1879 This is the priority an item get if no explicit priority is given."
1880 :group 'org-priorities
1881 :type 'character)
1883 (defcustom org-priority-start-cycle-with-default t
1884 "Non-nil means, start with default priority when starting to cycle.
1885 When this is nil, the first step in the cycle will be (depending on the
1886 command used) one higher or lower that the default priority."
1887 :group 'org-priorities
1888 :type 'boolean)
1890 (defgroup org-time nil
1891 "Options concerning time stamps and deadlines in Org-mode."
1892 :tag "Org Time"
1893 :group 'org)
1895 (defcustom org-insert-labeled-timestamps-at-point nil
1896 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1897 When nil, these labeled time stamps are forces into the second line of an
1898 entry, just after the headline. When scheduling from the global TODO list,
1899 the time stamp will always be forced into the second line."
1900 :group 'org-time
1901 :type 'boolean)
1903 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1904 "Formats for `format-time-string' which are used for time stamps.
1905 It is not recommended to change this constant.")
1907 (defcustom org-time-stamp-rounding-minutes 0
1908 "Number of minutes to round time stamps to upon insertion.
1909 When zero, insert the time unmodified. Useful rounding numbers
1910 should be factors of 60, so for example 5, 10, 15.
1911 When this is not zero, you can still force an exact time-stamp by using
1912 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1913 :group 'org-time
1914 :type 'integer)
1916 (defcustom org-display-custom-times nil
1917 "Non-nil means, overlay custom formats over all time stamps.
1918 The formats are defined through the variable `org-time-stamp-custom-formats'.
1919 To turn this on on a per-file basis, insert anywhere in the file:
1920 #+STARTUP: customtime"
1921 :group 'org-time
1922 :set 'set-default
1923 :type 'sexp)
1924 (make-variable-buffer-local 'org-display-custom-times)
1926 (defcustom org-time-stamp-custom-formats
1927 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1928 "Custom formats for time stamps. See `format-time-string' for the syntax.
1929 These are overlayed over the default ISO format if the variable
1930 `org-display-custom-times' is set. Time like %H:%M should be at the
1931 end of the second format."
1932 :group 'org-time
1933 :type 'sexp)
1935 (defun org-time-stamp-format (&optional long inactive)
1936 "Get the right format for a time string."
1937 (let ((f (if long (cdr org-time-stamp-formats)
1938 (car org-time-stamp-formats))))
1939 (if inactive
1940 (concat "[" (substring f 1 -1) "]")
1941 f)))
1943 (defcustom org-read-date-prefer-future t
1944 "Non-nil means, assume future for incomplete date input from user.
1945 This affects the following situations:
1946 1. The user gives a day, but no month.
1947 For example, if today is the 15th, and you enter \"3\", Org-mode will
1948 read this as the third of *next* month. However, if you enter \"17\",
1949 it will be considered as *this* month.
1950 2. The user gives a month but not a year.
1951 For example, if it is april and you enter \"feb 2\", this will be read
1952 as feb 2, *next* year. \"May 5\", however, will be this year.
1954 When this option is nil, the current month and year will always be used
1955 as defaults."
1956 :group 'org-time
1957 :type 'boolean)
1959 (defcustom org-read-date-display-live t
1960 "Non-nil means, display current interpretation of date prompt live.
1961 This display will be in an overlay, in the minibuffer."
1962 :group 'org-time
1963 :type 'boolean)
1965 (defcustom org-read-date-popup-calendar t
1966 "Non-nil means, pop up a calendar when prompting for a date.
1967 In the calendar, the date can be selected with mouse-1. However, the
1968 minibuffer will also be active, and you can simply enter the date as well.
1969 When nil, only the minibuffer will be available."
1970 :group 'org-time
1971 :type 'boolean)
1972 (if (fboundp 'defvaralias)
1973 (defvaralias 'org-popup-calendar-for-date-prompt
1974 'org-read-date-popup-calendar))
1976 (defcustom org-extend-today-until 0
1977 "The hour when your day really ends.
1978 This has influence for the following applications:
1979 - When switching the agenda to \"today\". It it is still earlier than
1980 the time given here, the day recognized as TODAY is actually yesterday.
1981 - When a date is read from the user and it is still before the time given
1982 here, the current date and time will be assumed to be yesterday, 23:59.
1984 FIXME:
1985 IMPORTANT: This is still a very experimental feature, it may disappear
1986 again or it may be extended to mean more things."
1987 :group 'org-time
1988 :type 'number)
1990 (defcustom org-edit-timestamp-down-means-later nil
1991 "Non-nil means, S-down will increase the time in a time stamp.
1992 When nil, S-up will increase."
1993 :group 'org-time
1994 :type 'boolean)
1996 (defcustom org-calendar-follow-timestamp-change t
1997 "Non-nil means, make the calendar window follow timestamp changes.
1998 When a timestamp is modified and the calendar window is visible, it will be
1999 moved to the new date."
2000 :group 'org-time
2001 :type 'boolean)
2003 (defcustom org-clock-heading-function nil
2004 "When non-nil, should be a function to create `org-clock-heading'.
2005 This is the string shown in the mode line when a clock is running.
2006 The function is called with point at the beginning of the headline."
2007 :group 'org-time ; FIXME: Should we have a separate group????
2008 :type 'function)
2010 (defgroup org-tags nil
2011 "Options concerning tags in Org-mode."
2012 :tag "Org Tags"
2013 :group 'org)
2015 (defcustom org-tag-alist nil
2016 "List of tags allowed in Org-mode files.
2017 When this list is nil, Org-mode will base TAG input on what is already in the
2018 buffer.
2019 The value of this variable is an alist, the car of each entry must be a
2020 keyword as a string, the cdr may be a character that is used to select
2021 that tag through the fast-tag-selection interface.
2022 See the manual for details."
2023 :group 'org-tags
2024 :type '(repeat
2025 (choice
2026 (cons (string :tag "Tag name")
2027 (character :tag "Access char"))
2028 (const :tag "Start radio group" (:startgroup))
2029 (const :tag "End radio group" (:endgroup)))))
2031 (defcustom org-use-fast-tag-selection 'auto
2032 "Non-nil means, use fast tag selection scheme.
2033 This is a special interface to select and deselect tags with single keys.
2034 When nil, fast selection is never used.
2035 When the symbol `auto', fast selection is used if and only if selection
2036 characters for tags have been configured, either through the variable
2037 `org-tag-alist' or through a #+TAGS line in the buffer.
2038 When t, fast selection is always used and selection keys are assigned
2039 automatically if necessary."
2040 :group 'org-tags
2041 :type '(choice
2042 (const :tag "Always" t)
2043 (const :tag "Never" nil)
2044 (const :tag "When selection characters are configured" 'auto)))
2046 (defcustom org-fast-tag-selection-single-key nil
2047 "Non-nil means, fast tag selection exits after first change.
2048 When nil, you have to press RET to exit it.
2049 During fast tag selection, you can toggle this flag with `C-c'.
2050 This variable can also have the value `expert'. In this case, the window
2051 displaying the tags menu is not even shown, until you press C-c again."
2052 :group 'org-tags
2053 :type '(choice
2054 (const :tag "No" nil)
2055 (const :tag "Yes" t)
2056 (const :tag "Expert" expert)))
2058 (defvar org-fast-tag-selection-include-todo nil
2059 "Non-nil means, fast tags selection interface will also offer TODO states.
2060 This is an undocumented feature, you should not rely on it.")
2062 (defcustom org-tags-column -80
2063 "The column to which tags should be indented in a headline.
2064 If this number is positive, it specifies the column. If it is negative,
2065 it means that the tags should be flushright to that column. For example,
2066 -80 works well for a normal 80 character screen."
2067 :group 'org-tags
2068 :type 'integer)
2070 (defcustom org-auto-align-tags t
2071 "Non-nil means, realign tags after pro/demotion of TODO state change.
2072 These operations change the length of a headline and therefore shift
2073 the tags around. With this options turned on, after each such operation
2074 the tags are again aligned to `org-tags-column'."
2075 :group 'org-tags
2076 :type 'boolean)
2078 (defcustom org-use-tag-inheritance t
2079 "Non-nil means, tags in levels apply also for sublevels.
2080 When nil, only the tags directly given in a specific line apply there.
2081 If you turn off this option, you very likely want to turn on the
2082 companion option `org-tags-match-list-sublevels'."
2083 :group 'org-tags
2084 :type 'boolean)
2086 (defcustom org-tags-match-list-sublevels nil
2087 "Non-nil means list also sublevels of headlines matching tag search.
2088 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2089 the sublevels of a headline matching a tag search often also match
2090 the same search. Listing all of them can create very long lists.
2091 Setting this variable to nil causes subtrees of a match to be skipped.
2092 This option is off by default, because inheritance in on. If you turn
2093 inheritance off, you very likely want to turn this option on.
2095 As a special case, if the tag search is restricted to TODO items, the
2096 value of this variable is ignored and sublevels are always checked, to
2097 make sure all corresponding TODO items find their way into the list."
2098 :group 'org-tags
2099 :type 'boolean)
2101 (defvar org-tags-history nil
2102 "History of minibuffer reads for tags.")
2103 (defvar org-last-tags-completion-table nil
2104 "The last used completion table for tags.")
2105 (defvar org-after-tags-change-hook nil
2106 "Hook that is run after the tags in a line have changed.")
2108 (defgroup org-properties nil
2109 "Options concerning properties in Org-mode."
2110 :tag "Org Properties"
2111 :group 'org)
2113 (defcustom org-property-format "%-10s %s"
2114 "How property key/value pairs should be formatted by `indent-line'.
2115 When `indent-line' hits a property definition, it will format the line
2116 according to this format, mainly to make sure that the values are
2117 lined-up with respect to each other."
2118 :group 'org-properties
2119 :type 'string)
2121 (defcustom org-use-property-inheritance nil
2122 "Non-nil means, properties apply also for sublevels.
2123 This setting is only relevant during property searches, not when querying
2124 an entry with `org-entry-get'. To retrieve a property with inheritance,
2125 you need to call `org-entry-get' with the inheritance flag.
2126 Turning this on can cause significant overhead when doing a search, so
2127 this is turned off by default.
2128 When nil, only the properties directly given in the current entry count.
2129 The value may also be a list of properties that shouldhave inheritance.
2131 However, note that some special properties use inheritance under special
2132 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2133 and the properties ending in \"_ALL\" when they are used as descriptor
2134 for valid values of a property."
2135 :group 'org-properties
2136 :type '(choice
2137 (const :tag "Not" nil)
2138 (const :tag "Always" nil)
2139 (repeat :tag "Specific properties" (string :tag "Property"))))
2141 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2142 "The default column format, if no other format has been defined.
2143 This variable can be set on the per-file basis by inserting a line
2145 #+COLUMNS: %25ITEM ....."
2146 :group 'org-properties
2147 :type 'string)
2149 (defcustom org-global-properties nil
2150 "List of property/value pairs that can be inherited by any entry.
2151 You can set buffer-local values for this by adding lines like
2153 #+PROPERTY: NAME VALUE"
2154 :group 'org-properties
2155 :type '(repeat
2156 (cons (string :tag "Property")
2157 (string :tag "Value"))))
2159 (defvar org-local-properties nil
2160 "List of property/value pairs that can be inherited by any entry.
2161 Valid for the current buffer.
2162 This variable is populated from #+PROPERTY lines.")
2164 (defgroup org-agenda nil
2165 "Options concerning agenda views in Org-mode."
2166 :tag "Org Agenda"
2167 :group 'org)
2169 (defvar org-category nil
2170 "Variable used by org files to set a category for agenda display.
2171 Such files should use a file variable to set it, for example
2173 # -*- mode: org; org-category: \"ELisp\"
2175 or contain a special line
2177 #+CATEGORY: ELisp
2179 If the file does not specify a category, then file's base name
2180 is used instead.")
2181 (make-variable-buffer-local 'org-category)
2183 (defcustom org-agenda-files nil
2184 "The files to be used for agenda display.
2185 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2186 \\[org-remove-file]. You can also use customize to edit the list.
2188 If an entry is a directory, all files in that directory that are matched by
2189 `org-agenda-file-regexp' will be part of the file list.
2191 If the value of the variable is not a list but a single file name, then
2192 the list of agenda files is actually stored and maintained in that file, one
2193 agenda file per line."
2194 :group 'org-agenda
2195 :type '(choice
2196 (repeat :tag "List of files and directories" file)
2197 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2199 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2200 "Regular expression to match files for `org-agenda-files'.
2201 If any element in the list in that variable contains a directory instead
2202 of a normal file, all files in that directory that are matched by this
2203 regular expression will be included."
2204 :group 'org-agenda
2205 :type 'regexp)
2207 (defcustom org-agenda-skip-unavailable-files nil
2208 "t means to just skip non-reachable files in `org-agenda-files'.
2209 Nil means to remove them, after a query, from the list."
2210 :group 'org-agenda
2211 :type 'boolean)
2213 (defcustom org-agenda-multi-occur-extra-files nil
2214 "List of extra files to be searched by `org-occur-in-agenda-files'.
2215 The files in `org-agenda-files' are always searched."
2216 :group 'org-agenda
2217 :type '(repeat file))
2219 (defcustom org-agenda-confirm-kill 1
2220 "When set, remote killing from the agenda buffer needs confirmation.
2221 When t, a confirmation is always needed. When a number N, confirmation is
2222 only needed when the text to be killed contains more than N non-white lines."
2223 :group 'org-agenda
2224 :type '(choice
2225 (const :tag "Never" nil)
2226 (const :tag "Always" t)
2227 (number :tag "When more than N lines")))
2229 (defcustom org-calendar-to-agenda-key [?c]
2230 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2231 The command `org-calendar-goto-agenda' will be bound to this key. The
2232 default is the character `c' because then `c' can be used to switch back and
2233 forth between agenda and calendar."
2234 :group 'org-agenda
2235 :type 'sexp)
2237 (defcustom org-agenda-compact-blocks nil
2238 "Non-nil means, make the block agenda more compact.
2239 This is done by leaving out unnecessary lines."
2240 :group 'org-agenda
2241 :type nil)
2243 (defgroup org-agenda-export nil
2244 "Options concerning exporting agenda views in Org-mode."
2245 :tag "Org Agenda Export"
2246 :group 'org-agenda)
2248 (defcustom org-agenda-with-colors t
2249 "Non-nil means, use colors in agenda views."
2250 :group 'org-agenda-export
2251 :type 'boolean)
2253 (defcustom org-agenda-exporter-settings nil
2254 "Alist of variable/value pairs that should be active during agenda export.
2255 This is a good place to set uptions for ps-print and for htmlize."
2256 :group 'org-agenda-export
2257 :type '(repeat
2258 (list
2259 (variable)
2260 (sexp :tag "Value"))))
2262 (defcustom org-agenda-export-html-style ""
2263 "The style specification for exported HTML Agenda files.
2264 If this variable contains a string, it will replace the default <style>
2265 section as produced by `htmlize'.
2266 Since there are different ways of setting style information, this variable
2267 needs to contain the full HTML structure to provide a style, including the
2268 surrounding HTML tags. The style specifications should include definitions
2269 the fonts used by the agenda, here is an example:
2271 <style type=\"text/css\">
2272 p { font-weight: normal; color: gray; }
2273 .org-agenda-structure {
2274 font-size: 110%;
2275 color: #003399;
2276 font-weight: 600;
2278 .org-todo {
2279 color: #cc6666;Week-agenda:
2280 font-weight: bold;
2282 .org-done {
2283 color: #339933;
2285 .title { text-align: center; }
2286 .todo, .deadline { color: red; }
2287 .done { color: green; }
2288 </style>
2290 or, if you want to keep the style in a file,
2292 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2294 As the value of this option simply gets inserted into the HTML <head> header,
2295 you can \"misuse\" it to also add other text to the header. However,
2296 <style>...</style> is required, if not present the variable will be ignored."
2297 :group 'org-agenda-export
2298 :group 'org-export-html
2299 :type 'string)
2301 (defgroup org-agenda-custom-commands nil
2302 "Options concerning agenda views in Org-mode."
2303 :tag "Org Agenda Custom Commands"
2304 :group 'org-agenda)
2306 (defcustom org-agenda-custom-commands nil
2307 "Custom commands for the agenda.
2308 These commands will be offered on the splash screen displayed by the
2309 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2311 (key desc type match options files)
2313 key The key (one or more characters as a string) to be associated
2314 with the command.
2315 desc A description of the commend, when omitted or nil, a default
2316 description is built using MATCH.
2317 type The command type, any of the following symbols:
2318 todo Entries with a specific TODO keyword, in all agenda files.
2319 tags Tags match in all agenda files.
2320 tags-todo Tags match in all agenda files, TODO entries only.
2321 todo-tree Sparse tree of specific TODO keyword in *current* file.
2322 tags-tree Sparse tree with all tags matches in *current* file.
2323 occur-tree Occur sparse tree for *current* file.
2324 ... A user-defined function.
2325 match What to search for:
2326 - a single keyword for TODO keyword searches
2327 - a tags match expression for tags searches
2328 - a regular expression for occur searches
2329 options A list of option settings, similar to that in a let form, so like
2330 this: ((opt1 val1) (opt2 val2) ...)
2331 files A list of files file to write the produced agenda buffer to
2332 with the command `org-store-agenda-views'.
2333 If a file name ends in \".html\", an HTML version of the buffer
2334 is written out. If it ends in \".ps\", a postscript version is
2335 produced. Otherwide, only the plain text is written to the file.
2337 You can also define a set of commands, to create a composite agenda buffer.
2338 In this case, an entry looks like this:
2340 (key desc (cmd1 cmd2 ...) general-options file)
2342 where
2344 desc A description string to be displayed in the dispatcher menu.
2345 cmd An agenda command, similar to the above. However, tree commands
2346 are no allowed, but instead you can get agenda and global todo list.
2347 So valid commands for a set are:
2348 (agenda)
2349 (alltodo)
2350 (stuck)
2351 (todo \"match\" options files)
2352 (tags \"match\" options files)
2353 (tags-todo \"match\" options files)
2355 Each command can carry a list of options, and another set of options can be
2356 given for the whole set of commands. Individual command options take
2357 precedence over the general options.
2359 When using several characters as key to a command, the first characters
2360 are prefix commands. For the dispatcher to display useful information, you
2361 should provide a description for the prefix, like
2363 (setq org-agenda-custom-commands
2364 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2365 (\"hl\" tags \"+HOME+Lisa\")
2366 (\"hp\" tags \"+HOME+Peter\")
2367 (\"hk\" tags \"+HOME+Kim\")))"
2368 :group 'org-agenda-custom-commands
2369 :type '(repeat
2370 (choice :value ("a" "" tags "" nil)
2371 (list :tag "Single command"
2372 (string :tag "Access Key(s) ")
2373 (option (string :tag "Description"))
2374 (choice
2375 (const :tag "Agenda" agenda)
2376 (const :tag "TODO list" alltodo)
2377 (const :tag "Stuck projects" stuck)
2378 (const :tag "Tags search (all agenda files)" tags)
2379 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2380 (const :tag "TODO keyword search (all agenda files)" todo)
2381 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2382 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2383 (const :tag "Occur tree (current buffer)" occur-tree)
2384 (sexp :tag "Other, user-defined function"))
2385 (string :tag "Match")
2386 (repeat :tag "Local options"
2387 (list (variable :tag "Option") (sexp :tag "Value")))
2388 (option (repeat :tag "Export" (file :tag "Export to"))))
2389 (list :tag "Command series, all agenda files"
2390 (string :tag "Access Key(s)")
2391 (string :tag "Description ")
2392 (repeat
2393 (choice
2394 (const :tag "Agenda" (agenda))
2395 (const :tag "TODO list" (alltodo))
2396 (const :tag "Stuck projects" (stuck))
2397 (list :tag "Tags search"
2398 (const :format "" tags)
2399 (string :tag "Match")
2400 (repeat :tag "Local options"
2401 (list (variable :tag "Option")
2402 (sexp :tag "Value"))))
2404 (list :tag "Tags search, TODO entries only"
2405 (const :format "" tags-todo)
2406 (string :tag "Match")
2407 (repeat :tag "Local options"
2408 (list (variable :tag "Option")
2409 (sexp :tag "Value"))))
2411 (list :tag "TODO keyword search"
2412 (const :format "" todo)
2413 (string :tag "Match")
2414 (repeat :tag "Local options"
2415 (list (variable :tag "Option")
2416 (sexp :tag "Value"))))
2418 (list :tag "Other, user-defined function"
2419 (symbol :tag "function")
2420 (string :tag "Match")
2421 (repeat :tag "Local options"
2422 (list (variable :tag "Option")
2423 (sexp :tag "Value"))))))
2425 (repeat :tag "General options"
2426 (list (variable :tag "Option")
2427 (sexp :tag "Value")))
2428 (option (repeat :tag "Export" (file :tag "Export to"))))
2429 (cons :tag "Prefix key documentation"
2430 (string :tag "Access Key(s)")
2431 (string :tag "Description ")))))
2433 (defcustom org-stuck-projects
2434 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2435 "How to identify stuck projects.
2436 This is a list of four items:
2437 1. A tags/todo matcher string that is used to identify a project.
2438 The entire tree below a headline matched by this is considered one project.
2439 2. A list of TODO keywords identifying non-stuck projects.
2440 If the project subtree contains any headline with one of these todo
2441 keywords, the project is considered to be not stuck. If you specify
2442 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2443 3. A list of tags identifying non-stuck projects.
2444 If the project subtree contains any headline with one of these tags,
2445 the project is considered to be not stuck. If you specify \"*\" as
2446 a tag, any tag will mark the project unstuck.
2447 4. An arbitrary regular expression matching non-stuck projects.
2449 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2450 or `C-c a #' to produce the list."
2451 :group 'org-agenda-custom-commands
2452 :type '(list
2453 (string :tag "Tags/TODO match to identify a project")
2454 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2455 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2456 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2459 (defgroup org-agenda-skip nil
2460 "Options concerning skipping parts of agenda files."
2461 :tag "Org Agenda Skip"
2462 :group 'org-agenda)
2464 (defcustom org-agenda-todo-list-sublevels t
2465 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2466 When nil, the sublevels of a TODO entry are not checked, resulting in
2467 potentially much shorter TODO lists."
2468 :group 'org-agenda-skip
2469 :group 'org-todo
2470 :type 'boolean)
2472 (defcustom org-agenda-todo-ignore-with-date nil
2473 "Non-nil means, don't show entries with a date in the global todo list.
2474 You can use this if you prefer to mark mere appointments with a TODO keyword,
2475 but don't want them to show up in the TODO list.
2476 When this is set, it also covers deadlines and scheduled items, the settings
2477 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2478 will be ignored."
2479 :group 'org-agenda-skip
2480 :group 'org-todo
2481 :type 'boolean)
2483 (defcustom org-agenda-todo-ignore-scheduled nil
2484 "Non-nil means, don't show scheduled entries in the global todo list.
2485 The idea behind this is that by scheduling it, you have already taken care
2486 of this item.
2487 See also `org-agenda-todo-ignore-with-date'."
2488 :group 'org-agenda-skip
2489 :group 'org-todo
2490 :type 'boolean)
2492 (defcustom org-agenda-todo-ignore-deadlines nil
2493 "Non-nil means, don't show near deadline entries in the global todo list.
2494 Near means closer than `org-deadline-warning-days' days.
2495 The idea behind this is that such items will appear in the agenda anyway.
2496 See also `org-agenda-todo-ignore-with-date'."
2497 :group 'org-agenda-skip
2498 :group 'org-todo
2499 :type 'boolean)
2501 (defcustom org-agenda-skip-scheduled-if-done nil
2502 "Non-nil means don't show scheduled items in agenda when they are done.
2503 This is relevant for the daily/weekly agenda, not for the TODO list. And
2504 it applies only to the actual date of the scheduling. Warnings about
2505 an item with a past scheduling dates are always turned off when the item
2506 is DONE."
2507 :group 'org-agenda-skip
2508 :type 'boolean)
2510 (defcustom org-agenda-skip-deadline-if-done nil
2511 "Non-nil means don't show deadines when the corresponding item is done.
2512 When nil, the deadline is still shown and should give you a happy feeling.
2513 This is relevant for the daily/weekly agenda. And it applied only to the
2514 actualy date of the deadline. Warnings about approching and past-due
2515 deadlines are always turned off when the item is DONE."
2516 :group 'org-agenda-skip
2517 :type 'boolean)
2519 (defcustom org-agenda-skip-timestamp-if-done nil
2520 "Non-nil means don't select item by timestamp or -range if it is DONE."
2521 :group 'org-agenda-skip
2522 :type 'boolean)
2524 (defcustom org-timeline-show-empty-dates 3
2525 "Non-nil means, `org-timeline' also shows dates without an entry.
2526 When nil, only the days which actually have entries are shown.
2527 When t, all days between the first and the last date are shown.
2528 When an integer, show also empty dates, but if there is a gap of more than
2529 N days, just insert a special line indicating the size of the gap."
2530 :group 'org-agenda-skip
2531 :type '(choice
2532 (const :tag "None" nil)
2533 (const :tag "All" t)
2534 (number :tag "at most")))
2537 (defgroup org-agenda-startup nil
2538 "Options concerning initial settings in the Agenda in Org Mode."
2539 :tag "Org Agenda Startup"
2540 :group 'org-agenda)
2542 (defcustom org-finalize-agenda-hook nil
2543 "Hook run just before displaying an agenda buffer."
2544 :group 'org-agenda-startup
2545 :type 'hook)
2547 (defcustom org-agenda-mouse-1-follows-link nil
2548 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2549 A longer mouse click will still set point. Does not wortk on XEmacs.
2550 Needs to be set before org.el is loaded."
2551 :group 'org-agenda-startup
2552 :type 'boolean)
2554 (defcustom org-agenda-start-with-follow-mode nil
2555 "The initial value of follow-mode in a newly created agenda window."
2556 :group 'org-agenda-startup
2557 :type 'boolean)
2559 (defgroup org-agenda-windows nil
2560 "Options concerning the windows used by the Agenda in Org Mode."
2561 :tag "Org Agenda Windows"
2562 :group 'org-agenda)
2564 (defcustom org-agenda-window-setup 'reorganize-frame
2565 "How the agenda buffer should be displayed.
2566 Possible values for this option are:
2568 current-window Show agenda in the current window, keeping all other windows.
2569 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2570 other-window Use `switch-to-buffer-other-window' to display agenda.
2571 reorganize-frame Show only two windows on the current frame, the current
2572 window and the agenda.
2573 See also the variable `org-agenda-restore-windows-after-quit'."
2574 :group 'org-agenda-windows
2575 :type '(choice
2576 (const current-window)
2577 (const other-frame)
2578 (const other-window)
2579 (const reorganize-frame)))
2581 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2582 "The min and max height of the agenda window as a fraction of frame height.
2583 The value of the variable is a cons cell with two numbers between 0 and 1.
2584 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2585 :group 'org-agenda-windows
2586 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2588 (defcustom org-agenda-restore-windows-after-quit nil
2589 "Non-nil means, restore window configuration open exiting agenda.
2590 Before the window configuration is changed for displaying the agenda,
2591 the current status is recorded. When the agenda is exited with
2592 `q' or `x' and this option is set, the old state is restored. If
2593 `org-agenda-window-setup' is `other-frame', the value of this
2594 option will be ignored.."
2595 :group 'org-agenda-windows
2596 :type 'boolean)
2598 (defcustom org-indirect-buffer-display 'other-window
2599 "How should indirect tree buffers be displayed?
2600 This applies to indirect buffers created with the commands
2601 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2602 Valid values are:
2603 current-window Display in the current window
2604 other-window Just display in another window.
2605 dedicated-frame Create one new frame, and re-use it each time.
2606 new-frame Make a new frame each time. Note that in this case
2607 previously-made indirect buffers are kept, and you need to
2608 kill these buffers yourself."
2609 :group 'org-structure
2610 :group 'org-agenda-windows
2611 :type '(choice
2612 (const :tag "In current window" current-window)
2613 (const :tag "In current frame, other window" other-window)
2614 (const :tag "Each time a new frame" new-frame)
2615 (const :tag "One dedicated frame" dedicated-frame)))
2617 (defgroup org-agenda-daily/weekly nil
2618 "Options concerning the daily/weekly agenda."
2619 :tag "Org Agenda Daily/Weekly"
2620 :group 'org-agenda)
2622 (defcustom org-agenda-ndays 7
2623 "Number of days to include in overview display.
2624 Should be 1 or 7."
2625 :group 'org-agenda-daily/weekly
2626 :type 'number)
2628 (defcustom org-agenda-start-on-weekday 1
2629 "Non-nil means, start the overview always on the specified weekday.
2630 0 denotes Sunday, 1 denotes Monday etc.
2631 When nil, always start on the current day."
2632 :group 'org-agenda-daily/weekly
2633 :type '(choice (const :tag "Today" nil)
2634 (number :tag "Weekday No.")))
2636 (defcustom org-agenda-show-all-dates t
2637 "Non-nil means, `org-agenda' shows every day in the selected range.
2638 When nil, only the days which actually have entries are shown."
2639 :group 'org-agenda-daily/weekly
2640 :type 'boolean)
2642 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2643 "Format string for displaying dates in the agenda.
2644 Used by the daily/weekly agenda and by the timeline. This should be
2645 a format string understood by `format-time-string', or a function returning
2646 the formatted date as a string. The function must take a single argument,
2647 a calendar-style date list like (month day year)."
2648 :group 'org-agenda-daily/weekly
2649 :type '(choice
2650 (string :tag "Format string")
2651 (function :tag "Function")))
2653 (defun org-agenda-format-date-aligned (date)
2654 "Format a date string for display in the daily/weekly agenda, or timeline.
2655 This function makes sure that dates are aligned for easy reading."
2656 (format "%-9s %2d %s %4d"
2657 (calendar-day-name date)
2658 (extract-calendar-day date)
2659 (calendar-month-name (extract-calendar-month date))
2660 (extract-calendar-year date)))
2662 (defcustom org-agenda-include-diary nil
2663 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2664 :group 'org-agenda-daily/weekly
2665 :type 'boolean)
2667 (defcustom org-agenda-include-all-todo nil
2668 "Set means weekly/daily agenda will always contain all TODO entries.
2669 The TODO entries will be listed at the top of the agenda, before
2670 the entries for specific days."
2671 :group 'org-agenda-daily/weekly
2672 :type 'boolean)
2674 (defcustom org-agenda-repeating-timestamp-show-all t
2675 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2676 When nil, only one occurence is shown, either today or the
2677 nearest into the future."
2678 :group 'org-agenda-daily/weekly
2679 :type 'boolean)
2681 (defcustom org-deadline-warning-days 14
2682 "No. of days before expiration during which a deadline becomes active.
2683 This variable governs the display in sparse trees and in the agenda.
2684 When negative, it means use this number (the absolute value of it)
2685 even if a deadline has a different individual lead time specified."
2686 :group 'org-time
2687 :group 'org-agenda-daily/weekly
2688 :type 'number)
2690 (defcustom org-scheduled-past-days 10000
2691 "No. of days to continue listing scheduled items that are not marked DONE.
2692 When an item is scheduled on a date, it shows up in the agenda on this
2693 day and will be listed until it is marked done for the number of days
2694 given here."
2695 :group 'org-agenda-daily/weekly
2696 :type 'number)
2698 (defgroup org-agenda-time-grid nil
2699 "Options concerning the time grid in the Org-mode Agenda."
2700 :tag "Org Agenda Time Grid"
2701 :group 'org-agenda)
2703 (defcustom org-agenda-use-time-grid t
2704 "Non-nil means, show a time grid in the agenda schedule.
2705 A time grid is a set of lines for specific times (like every two hours between
2706 8:00 and 20:00). The items scheduled for a day at specific times are
2707 sorted in between these lines.
2708 For details about when the grid will be shown, and what it will look like, see
2709 the variable `org-agenda-time-grid'."
2710 :group 'org-agenda-time-grid
2711 :type 'boolean)
2713 (defcustom org-agenda-time-grid
2714 '((daily today require-timed)
2715 "----------------"
2716 (800 1000 1200 1400 1600 1800 2000))
2718 "The settings for time grid for agenda display.
2719 This is a list of three items. The first item is again a list. It contains
2720 symbols specifying conditions when the grid should be displayed:
2722 daily if the agenda shows a single day
2723 weekly if the agenda shows an entire week
2724 today show grid on current date, independent of daily/weekly display
2725 require-timed show grid only if at least one item has a time specification
2727 The second item is a string which will be places behing the grid time.
2729 The third item is a list of integers, indicating the times that should have
2730 a grid line."
2731 :group 'org-agenda-time-grid
2732 :type
2733 '(list
2734 (set :greedy t :tag "Grid Display Options"
2735 (const :tag "Show grid in single day agenda display" daily)
2736 (const :tag "Show grid in weekly agenda display" weekly)
2737 (const :tag "Always show grid for today" today)
2738 (const :tag "Show grid only if any timed entries are present"
2739 require-timed)
2740 (const :tag "Skip grid times already present in an entry"
2741 remove-match))
2742 (string :tag "Grid String")
2743 (repeat :tag "Grid Times" (integer :tag "Time"))))
2745 (defgroup org-agenda-sorting nil
2746 "Options concerning sorting in the Org-mode Agenda."
2747 :tag "Org Agenda Sorting"
2748 :group 'org-agenda)
2750 (defconst org-sorting-choice
2751 '(choice
2752 (const time-up) (const time-down)
2753 (const category-keep) (const category-up) (const category-down)
2754 (const tag-down) (const tag-up)
2755 (const priority-up) (const priority-down))
2756 "Sorting choices.")
2758 (defcustom org-agenda-sorting-strategy
2759 '((agenda time-up category-keep priority-down)
2760 (todo category-keep priority-down)
2761 (tags category-keep priority-down))
2762 "Sorting structure for the agenda items of a single day.
2763 This is a list of symbols which will be used in sequence to determine
2764 if an entry should be listed before another entry. The following
2765 symbols are recognized:
2767 time-up Put entries with time-of-day indications first, early first
2768 time-down Put entries with time-of-day indications first, late first
2769 category-keep Keep the default order of categories, corresponding to the
2770 sequence in `org-agenda-files'.
2771 category-up Sort alphabetically by category, A-Z.
2772 category-down Sort alphabetically by category, Z-A.
2773 tag-up Sort alphabetically by last tag, A-Z.
2774 tag-down Sort alphabetically by last tag, Z-A.
2775 priority-up Sort numerically by priority, high priority last.
2776 priority-down Sort numerically by priority, high priority first.
2778 The different possibilities will be tried in sequence, and testing stops
2779 if one comparison returns a \"not-equal\". For example, the default
2780 '(time-up category-keep priority-down)
2781 means: Pull out all entries having a specified time of day and sort them,
2782 in order to make a time schedule for the current day the first thing in the
2783 agenda listing for the day. Of the entries without a time indication, keep
2784 the grouped in categories, don't sort the categories, but keep them in
2785 the sequence given in `org-agenda-files'. Within each category sort by
2786 priority.
2788 Leaving out `category-keep' would mean that items will be sorted across
2789 categories by priority.
2791 Instead of a single list, this can also be a set of list for specific
2792 contents, with a context symbol in the car of the list, any of
2793 `agenda', `todo', `tags' for the corresponding agenda views."
2794 :group 'org-agenda-sorting
2795 :type `(choice
2796 (repeat :tag "General" ,org-sorting-choice)
2797 (list :tag "Individually"
2798 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2799 (repeat ,org-sorting-choice))
2800 (cons (const :tag "Strategy for TODO lists" todo)
2801 (repeat ,org-sorting-choice))
2802 (cons (const :tag "Strategy for Tags matches" tags)
2803 (repeat ,org-sorting-choice)))))
2805 (defcustom org-sort-agenda-notime-is-late t
2806 "Non-nil means, items without time are considered late.
2807 This is only relevant for sorting. When t, items which have no explicit
2808 time like 15:30 will be considered as 99:01, i.e. later than any items which
2809 do have a time. When nil, the default time is before 0:00. You can use this
2810 option to decide if the schedule for today should come before or after timeless
2811 agenda entries."
2812 :group 'org-agenda-sorting
2813 :type 'boolean)
2815 (defgroup org-agenda-line-format nil
2816 "Options concerning the entry prefix in the Org-mode agenda display."
2817 :tag "Org Agenda Line Format"
2818 :group 'org-agenda)
2820 (defcustom org-agenda-prefix-format
2821 '((agenda . " %-12:c%?-12t% s")
2822 (timeline . " % s")
2823 (todo . " %-12:c")
2824 (tags . " %-12:c"))
2825 "Format specifications for the prefix of items in the agenda views.
2826 An alist with four entries, for the different agenda types. The keys to the
2827 sublists are `agenda', `timeline', `todo', and `tags'. The values
2828 are format strings.
2829 This format works similar to a printf format, with the following meaning:
2831 %c the category of the item, \"Diary\" for entries from the diary, or
2832 as given by the CATEGORY keyword or derived from the file name.
2833 %T the *last* tag of the item. Last because inherited tags come
2834 first in the list.
2835 %t the time-of-day specification if one applies to the entry, in the
2836 format HH:MM
2837 %s Scheduling/Deadline information, a short string
2839 All specifiers work basically like the standard `%s' of printf, but may
2840 contain two additional characters: A question mark just after the `%' and
2841 a whitespace/punctuation character just before the final letter.
2843 If the first character after `%' is a question mark, the entire field
2844 will only be included if the corresponding value applies to the
2845 current entry. This is useful for fields which should have fixed
2846 width when present, but zero width when absent. For example,
2847 \"%?-12t\" will result in a 12 character time field if a time of the
2848 day is specified, but will completely disappear in entries which do
2849 not contain a time.
2851 If there is punctuation or whitespace character just before the final
2852 format letter, this character will be appended to the field value if
2853 the value is not empty. For example, the format \"%-12:c\" leads to
2854 \"Diary: \" if the category is \"Diary\". If the category were be
2855 empty, no additional colon would be interted.
2857 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2858 - Indent the line with two space characters
2859 - Give the category in a 12 chars wide field, padded with whitespace on
2860 the right (because of `-'). Append a colon if there is a category
2861 (because of `:').
2862 - If there is a time-of-day, put it into a 12 chars wide field. If no
2863 time, don't put in an empty field, just skip it (because of '?').
2864 - Finally, put the scheduling information and append a whitespace.
2866 As another example, if you don't want the time-of-day of entries in
2867 the prefix, you could use:
2869 (setq org-agenda-prefix-format \" %-11:c% s\")
2871 See also the variables `org-agenda-remove-times-when-in-prefix' and
2872 `org-agenda-remove-tags'."
2873 :type '(choice
2874 (string :tag "General format")
2875 (list :greedy t :tag "View dependent"
2876 (cons (const agenda) (string :tag "Format"))
2877 (cons (const timeline) (string :tag "Format"))
2878 (cons (const todo) (string :tag "Format"))
2879 (cons (const tags) (string :tag "Format"))))
2880 :group 'org-agenda-line-format)
2882 (defvar org-prefix-format-compiled nil
2883 "The compiled version of the most recently used prefix format.
2884 See the variable `org-agenda-prefix-format'.")
2886 (defcustom org-agenda-todo-keyword-format "%-1s"
2887 "Format for the TODO keyword in agenda lines.
2888 Set this to something like \"%-12s\" if you want all TODO keywords
2889 to occupy a fixed space in the agenda display."
2890 :group 'org-agenda-line-format
2891 :type 'string)
2893 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2894 "Text preceeding scheduled items in the agenda view.
2895 This is a list with two strings. The first applies when the item is
2896 scheduled on the current day. The second applies when it has been scheduled
2897 previously, it may contain a %d to capture how many days ago the item was
2898 scheduled."
2899 :group 'org-agenda-line-format
2900 :type '(list
2901 (string :tag "Scheduled today ")
2902 (string :tag "Scheduled previously")))
2904 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2905 "Text preceeding deadline items in the agenda view.
2906 This is a list with two strings. The first applies when the item has its
2907 deadline on the current day. The second applies when it is in the past or
2908 in the future, it may contain %d to capture how many days away the deadline
2909 is (was)."
2910 :group 'org-agenda-line-format
2911 :type '(list
2912 (string :tag "Deadline today ")
2913 (string :tag "Deadline relative")))
2915 (defcustom org-agenda-remove-times-when-in-prefix t
2916 "Non-nil means, remove duplicate time specifications in agenda items.
2917 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2918 time-of-day specification in a headline or diary entry is extracted and
2919 placed into the prefix. If this option is non-nil, the original specification
2920 \(a timestamp or -range, or just a plain time(range) specification like
2921 11:30-4pm) will be removed for agenda display. This makes the agenda less
2922 cluttered.
2923 The option can be t or nil. It may also be the symbol `beg', indicating
2924 that the time should only be removed what it is located at the beginning of
2925 the headline/diary entry."
2926 :group 'org-agenda-line-format
2927 :type '(choice
2928 (const :tag "Always" t)
2929 (const :tag "Never" nil)
2930 (const :tag "When at beginning of entry" beg)))
2933 (defcustom org-agenda-default-appointment-duration nil
2934 "Default duration for appointments that only have a starting time.
2935 When nil, no duration is specified in such cases.
2936 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2937 :group 'org-agenda-line-format
2938 :type '(choice
2939 (integer :tag "Minutes")
2940 (const :tag "No default duration")))
2943 (defcustom org-agenda-remove-tags nil
2944 "Non-nil means, remove the tags from the headline copy in the agenda.
2945 When this is the symbol `prefix', only remove tags when
2946 `org-agenda-prefix-format' contains a `%T' specifier."
2947 :group 'org-agenda-line-format
2948 :type '(choice
2949 (const :tag "Always" t)
2950 (const :tag "Never" nil)
2951 (const :tag "When prefix format contains %T" prefix)))
2953 (if (fboundp 'defvaralias)
2954 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2955 'org-agenda-remove-tags))
2957 (defcustom org-agenda-tags-column -80
2958 "Shift tags in agenda items to this column.
2959 If this number is positive, it specifies the column. If it is negative,
2960 it means that the tags should be flushright to that column. For example,
2961 -80 works well for a normal 80 character screen."
2962 :group 'org-agenda-line-format
2963 :type 'integer)
2965 (if (fboundp 'defvaralias)
2966 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2968 (defcustom org-agenda-fontify-priorities t
2969 "Non-nil means, highlight low and high priorities in agenda.
2970 When t, the highest priority entries are bold, lowest priority italic.
2971 This may also be an association list of priority faces. The face may be
2972 a names face, or a list like `(:background \"Red\")'."
2973 :group 'org-agenda-line-format
2974 :type '(choice
2975 (const :tag "Never" nil)
2976 (const :tag "Defaults" t)
2977 (repeat :tag "Specify"
2978 (list (character :tag "Priority" :value ?A)
2979 (sexp :tag "face")))))
2981 (defgroup org-latex nil
2982 "Options for embedding LaTeX code into Org-mode"
2983 :tag "Org LaTeX"
2984 :group 'org)
2986 (defcustom org-format-latex-options
2987 '(:foreground default :background default :scale 1.0
2988 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2989 :matchers ("begin" "$" "$$" "\\(" "\\["))
2990 "Options for creating images from LaTeX fragments.
2991 This is a property list with the following properties:
2992 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2993 `default' means use the forground of the default face.
2994 :background the background color, or \"Transparent\".
2995 `default' means use the background of the default face.
2996 :scale a scaling factor for the size of the images
2997 :html-foreground, :html-background, :html-scale
2998 The same numbers for HTML export.
2999 :matchers a list indicating which matchers should be used to
3000 find LaTeX fragments. Valid members of this list are:
3001 \"begin\" find environments
3002 \"$\" find math expressions surrounded by $...$
3003 \"$$\" find math expressions surrounded by $$....$$
3004 \"\\(\" find math expressions surrounded by \\(...\\)
3005 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3006 :group 'org-latex
3007 :type 'plist)
3009 (defcustom org-format-latex-header "\\documentclass{article}
3010 \\usepackage{fullpage} % do not remove
3011 \\usepackage{amssymb}
3012 \\usepackage[usenames]{color}
3013 \\usepackage{amsmath}
3014 \\usepackage{latexsym}
3015 \\usepackage[mathscr]{eucal}
3016 \\pagestyle{empty} % do not remove"
3017 "The document header used for processing LaTeX fragments."
3018 :group 'org-latex
3019 :type 'string)
3021 (defgroup org-export nil
3022 "Options for exporting org-listings."
3023 :tag "Org Export"
3024 :group 'org)
3026 (defgroup org-export-general nil
3027 "General options for exporting Org-mode files."
3028 :tag "Org Export General"
3029 :group 'org-export)
3031 ;; FIXME
3032 (defvar org-export-publishing-directory nil)
3034 (defcustom org-export-with-special-strings t
3035 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3036 When this option is turned on, these strings will be exported as:
3038 Org HTML LaTeX
3039 -----+----------+--------
3040 \\- &shy; \\-
3041 -- &ndash; --
3042 --- &mdash; ---
3043 ... &hellip; \ldots
3045 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3046 :group 'org-export-translation
3047 :type 'boolean)
3049 (defcustom org-export-language-setup
3050 '(("en" "Author" "Date" "Table of Contents")
3051 ("cs" "Autor" "Datum" "Obsah")
3052 ("da" "Ophavsmand" "Dato" "Indhold")
3053 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3054 ("es" "Autor" "Fecha" "\xcdndice")
3055 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3056 ("it" "Autore" "Data" "Indice")
3057 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3058 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3059 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3060 "Terms used in export text, translated to different languages.
3061 Use the variable `org-export-default-language' to set the language,
3062 or use the +OPTION lines for a per-file setting."
3063 :group 'org-export-general
3064 :type '(repeat
3065 (list
3066 (string :tag "HTML language tag")
3067 (string :tag "Author")
3068 (string :tag "Date")
3069 (string :tag "Table of Contents"))))
3071 (defcustom org-export-default-language "en"
3072 "The default language of HTML export, as a string.
3073 This should have an association in `org-export-language-setup'."
3074 :group 'org-export-general
3075 :type 'string)
3077 (defcustom org-export-skip-text-before-1st-heading t
3078 "Non-nil means, skip all text before the first headline when exporting.
3079 When nil, that text is exported as well."
3080 :group 'org-export-general
3081 :type 'boolean)
3083 (defcustom org-export-headline-levels 3
3084 "The last level which is still exported as a headline.
3085 Inferior levels will produce itemize lists when exported.
3086 Note that a numeric prefix argument to an exporter function overrides
3087 this setting.
3089 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3090 :group 'org-export-general
3091 :type 'number)
3093 (defcustom org-export-with-section-numbers t
3094 "Non-nil means, add section numbers to headlines when exporting.
3096 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3097 :group 'org-export-general
3098 :type 'boolean)
3100 (defcustom org-export-with-toc t
3101 "Non-nil means, create a table of contents in exported files.
3102 The TOC contains headlines with levels up to`org-export-headline-levels'.
3103 When an integer, include levels up to N in the toc, this may then be
3104 different from `org-export-headline-levels', but it will not be allowed
3105 to be larger than the number of headline levels.
3106 When nil, no table of contents is made.
3108 Headlines which contain any TODO items will be marked with \"(*)\" in
3109 ASCII export, and with red color in HTML output, if the option
3110 `org-export-mark-todo-in-toc' is set.
3112 In HTML output, the TOC will be clickable.
3114 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3115 or \"toc:3\"."
3116 :group 'org-export-general
3117 :type '(choice
3118 (const :tag "No Table of Contents" nil)
3119 (const :tag "Full Table of Contents" t)
3120 (integer :tag "TOC to level")))
3122 (defcustom org-export-mark-todo-in-toc nil
3123 "Non-nil means, mark TOC lines that contain any open TODO items."
3124 :group 'org-export-general
3125 :type 'boolean)
3127 (defcustom org-export-preserve-breaks nil
3128 "Non-nil means, preserve all line breaks when exporting.
3129 Normally, in HTML output paragraphs will be reformatted. In ASCII
3130 export, line breaks will always be preserved, regardless of this variable.
3132 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3133 :group 'org-export-general
3134 :type 'boolean)
3136 (defcustom org-export-with-archived-trees 'headline
3137 "Whether subtrees with the ARCHIVE tag should be exported.
3138 This can have three different values
3139 nil Do not export, pretend this tree is not present
3140 t Do export the entire tree
3141 headline Only export the headline, but skip the tree below it."
3142 :group 'org-export-general
3143 :group 'org-archive
3144 :type '(choice
3145 (const :tag "not at all" nil)
3146 (const :tag "headline only" 'headline)
3147 (const :tag "entirely" t)))
3149 (defcustom org-export-author-info t
3150 "Non-nil means, insert author name and email into the exported file.
3152 This option can also be set with the +OPTIONS line,
3153 e.g. \"author-info:nil\"."
3154 :group 'org-export-general
3155 :type 'boolean)
3157 (defcustom org-export-time-stamp-file t
3158 "Non-nil means, insert a time stamp into the exported file.
3159 The time stamp shows when the file was created.
3161 This option can also be set with the +OPTIONS line,
3162 e.g. \"timestamp:nil\"."
3163 :group 'org-export-general
3164 :type 'boolean)
3166 (defcustom org-export-with-timestamps t
3167 "If nil, do not export time stamps and associated keywords."
3168 :group 'org-export-general
3169 :type 'boolean)
3171 (defcustom org-export-remove-timestamps-from-toc t
3172 "If nil, remove timestamps from the table of contents entries."
3173 :group 'org-export-general
3174 :type 'boolean)
3176 (defcustom org-export-with-tags 'not-in-toc
3177 "If nil, do not export tags, just remove them from headlines.
3178 If this is the symbol `not-in-toc', tags will be removed from table of
3179 contents entries, but still be shown in the headlines of the document.
3181 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3182 :group 'org-export-general
3183 :type '(choice
3184 (const :tag "Off" nil)
3185 (const :tag "Not in TOC" not-in-toc)
3186 (const :tag "On" t)))
3188 (defcustom org-export-with-drawers nil
3189 "Non-nil means, export with drawers like the property drawer.
3190 When t, all drawers are exported. This may also be a list of
3191 drawer names to export."
3192 :group 'org-export-general
3193 :type '(choice
3194 (const :tag "All drawers" t)
3195 (const :tag "None" nil)
3196 (repeat :tag "Selected drawers"
3197 (string :tag "Drawer name"))))
3199 (defgroup org-export-translation nil
3200 "Options for translating special ascii sequences for the export backends."
3201 :tag "Org Export Translation"
3202 :group 'org-export)
3204 (defcustom org-export-with-emphasize t
3205 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3206 If the export target supports emphasizing text, the word will be
3207 typeset in bold, italic, or underlined, respectively. Works only for
3208 single words, but you can say: I *really* *mean* *this*.
3209 Not all export backends support this.
3211 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3212 :group 'org-export-translation
3213 :type 'boolean)
3215 (defcustom org-export-with-footnotes t
3216 "If nil, export [1] as a footnote marker.
3217 Lines starting with [1] will be formatted as footnotes.
3219 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3220 :group 'org-export-translation
3221 :type 'boolean)
3223 (defcustom org-export-with-sub-superscripts t
3224 "Non-nil means, interpret \"_\" and \"^\" for export.
3225 When this option is turned on, you can use TeX-like syntax for sub- and
3226 superscripts. Several characters after \"_\" or \"^\" will be
3227 considered as a single item - so grouping with {} is normally not
3228 needed. For example, the following things will be parsed as single
3229 sub- or superscripts.
3231 10^24 or 10^tau several digits will be considered 1 item.
3232 10^-12 or 10^-tau a leading sign with digits or a word
3233 x^2-y^3 will be read as x^2 - y^3, because items are
3234 terminated by almost any nonword/nondigit char.
3235 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3237 Still, ambiguity is possible - so when in doubt use {} to enclose the
3238 sub/superscript. If you set this variable to the symbol `{}',
3239 the braces are *required* in order to trigger interpretations as
3240 sub/superscript. This can be helpful in documents that need \"_\"
3241 frequently in plain text.
3243 Not all export backends support this, but HTML does.
3245 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3246 :group 'org-export-translation
3247 :type '(choice
3248 (const :tag "Always interpret" t)
3249 (const :tag "Only with braces" {})
3250 (const :tag "Never interpret" nil)))
3252 (defcustom org-export-with-special-strings t
3253 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3254 When this option is turned on, these strings will be exported as:
3256 \\- : &shy;
3257 -- : &ndash;
3258 --- : &mdash;
3260 Not all export backends support this, but HTML does.
3262 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3263 :group 'org-export-translation
3264 :type 'boolean)
3266 (defcustom org-export-with-TeX-macros t
3267 "Non-nil means, interpret simple TeX-like macros when exporting.
3268 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3269 No only real TeX macros will work here, but the standard HTML entities
3270 for math can be used as macro names as well. For a list of supported
3271 names in HTML export, see the constant `org-html-entities'.
3272 Not all export backends support this.
3274 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3275 :group 'org-export-translation
3276 :group 'org-export-latex
3277 :type 'boolean)
3279 (defcustom org-export-with-LaTeX-fragments nil
3280 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3281 When set, the exporter will find LaTeX environments if the \\begin line is
3282 the first non-white thing on a line. It will also find the math delimiters
3283 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3284 display math.
3286 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3287 :group 'org-export-translation
3288 :group 'org-export-latex
3289 :type 'boolean)
3291 (defcustom org-export-with-fixed-width t
3292 "Non-nil means, lines starting with \":\" will be in fixed width font.
3293 This can be used to have pre-formatted text, fragments of code etc. For
3294 example:
3295 : ;; Some Lisp examples
3296 : (while (defc cnt)
3297 : (ding))
3298 will be looking just like this in also HTML. See also the QUOTE keyword.
3299 Not all export backends support this.
3301 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3302 :group 'org-export-translation
3303 :type 'boolean)
3305 (defcustom org-match-sexp-depth 3
3306 "Number of stacked braces for sub/superscript matching.
3307 This has to be set before loading org.el to be effective."
3308 :group 'org-export-translation
3309 :type 'integer)
3311 (defgroup org-export-tables nil
3312 "Options for exporting tables in Org-mode."
3313 :tag "Org Export Tables"
3314 :group 'org-export)
3316 (defcustom org-export-with-tables t
3317 "If non-nil, lines starting with \"|\" define a table.
3318 For example:
3320 | Name | Address | Birthday |
3321 |-------------+----------+-----------|
3322 | Arthur Dent | England | 29.2.2100 |
3324 Not all export backends support this.
3326 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3327 :group 'org-export-tables
3328 :type 'boolean)
3330 (defcustom org-export-highlight-first-table-line t
3331 "Non-nil means, highlight the first table line.
3332 In HTML export, this means use <th> instead of <td>.
3333 In tables created with table.el, this applies to the first table line.
3334 In Org-mode tables, all lines before the first horizontal separator
3335 line will be formatted with <th> tags."
3336 :group 'org-export-tables
3337 :type 'boolean)
3339 (defcustom org-export-table-remove-special-lines t
3340 "Remove special lines and marking characters in calculating tables.
3341 This removes the special marking character column from tables that are set
3342 up for spreadsheet calculations. It also removes the entire lines
3343 marked with `!', `_', or `^'. The lines with `$' are kept, because
3344 the values of constants may be useful to have."
3345 :group 'org-export-tables
3346 :type 'boolean)
3348 (defcustom org-export-prefer-native-exporter-for-tables nil
3349 "Non-nil means, always export tables created with table.el natively.
3350 Natively means, use the HTML code generator in table.el.
3351 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3352 the table does not use row- or column-spanning). This has the
3353 advantage, that the automatic HTML conversions for math symbols and
3354 sub/superscripts can be applied. Org-mode's HTML generator is also
3355 much faster."
3356 :group 'org-export-tables
3357 :type 'boolean)
3359 (defgroup org-export-ascii nil
3360 "Options specific for ASCII export of Org-mode files."
3361 :tag "Org Export ASCII"
3362 :group 'org-export)
3364 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3365 "Characters for underlining headings in ASCII export.
3366 In the given sequence, these characters will be used for level 1, 2, ..."
3367 :group 'org-export-ascii
3368 :type '(repeat character))
3370 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3371 "Bullet characters for headlines converted to lists in ASCII export.
3372 The first character is used for the first lest level generated in this
3373 way, and so on. If there are more levels than characters given here,
3374 the list will be repeated.
3375 Note that plain lists will keep the same bullets as the have in the
3376 Org-mode file."
3377 :group 'org-export-ascii
3378 :type '(repeat character))
3380 (defgroup org-export-xml nil
3381 "Options specific for XML export of Org-mode files."
3382 :tag "Org Export XML"
3383 :group 'org-export)
3385 (defgroup org-export-html nil
3386 "Options specific for HTML export of Org-mode files."
3387 :tag "Org Export HTML"
3388 :group 'org-export)
3390 (defcustom org-export-html-coding-system nil
3392 :group 'org-export-html
3393 :type 'coding-system)
3395 (defcustom org-export-html-extension "html"
3396 "The extension for exported HTML files."
3397 :group 'org-export-html
3398 :type 'string)
3400 (defcustom org-export-html-style
3401 "<style type=\"text/css\">
3402 html {
3403 font-family: Times, serif;
3404 font-size: 12pt;
3406 .title { text-align: center; }
3407 .todo { color: red; }
3408 .done { color: green; }
3409 .timestamp { color: grey }
3410 .timestamp-kwd { color: CadetBlue }
3411 .tag { background-color:lightblue; font-weight:normal }
3412 .target { background-color: lavender; }
3413 pre {
3414 border: 1pt solid #AEBDCC;
3415 background-color: #F3F5F7;
3416 padding: 5pt;
3417 font-family: courier, monospace;
3419 table { border-collapse: collapse; }
3420 td, th {
3421 vertical-align: top;
3422 <!--border: 1pt solid #ADB9CC;-->
3424 </style>"
3425 "The default style specification for exported HTML files.
3426 Since there are different ways of setting style information, this variable
3427 needs to contain the full HTML structure to provide a style, including the
3428 surrounding HTML tags. The style specifications should include definitions
3429 for new classes todo, done, title, and deadline. For example, legal values
3430 would be:
3432 <style type=\"text/css\">
3433 p { font-weight: normal; color: gray; }
3434 h1 { color: black; }
3435 .title { text-align: center; }
3436 .todo, .deadline { color: red; }
3437 .done { color: green; }
3438 </style>
3440 or, if you want to keep the style in a file,
3442 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3444 As the value of this option simply gets inserted into the HTML <head> header,
3445 you can \"misuse\" it to add arbitrary text to the header."
3446 :group 'org-export-html
3447 :type 'string)
3450 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3451 "Format for typesetting the document title in HTML export."
3452 :group 'org-export-html
3453 :type 'string)
3455 (defcustom org-export-html-toplevel-hlevel 2
3456 "The <H> level for level 1 headings in HTML export."
3457 :group 'org-export-html
3458 :type 'string)
3460 (defcustom org-export-html-link-org-files-as-html t
3461 "Non-nil means, make file links to `file.org' point to `file.html'.
3462 When org-mode is exporting an org-mode file to HTML, links to
3463 non-html files are directly put into a href tag in HTML.
3464 However, links to other Org-mode files (recognized by the
3465 extension `.org.) should become links to the corresponding html
3466 file, assuming that the linked org-mode file will also be
3467 converted to HTML.
3468 When nil, the links still point to the plain `.org' file."
3469 :group 'org-export-html
3470 :type 'boolean)
3472 (defcustom org-export-html-inline-images 'maybe
3473 "Non-nil means, inline images into exported HTML pages.
3474 This is done using an <img> tag. When nil, an anchor with href is used to
3475 link to the image. If this option is `maybe', then images in links with
3476 an empty description will be inlined, while images with a description will
3477 be linked only."
3478 :group 'org-export-html
3479 :type '(choice (const :tag "Never" nil)
3480 (const :tag "Always" t)
3481 (const :tag "When there is no description" maybe)))
3483 ;; FIXME: rename
3484 (defcustom org-export-html-expand t
3485 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3486 When nil, these tags will be exported as plain text and therefore
3487 not be interpreted by a browser.
3489 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3490 :group 'org-export-html
3491 :type 'boolean)
3493 (defcustom org-export-html-table-tag
3494 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3495 "The HTML tag that is used to start a table.
3496 This must be a <table> tag, but you may change the options like
3497 borders and spacing."
3498 :group 'org-export-html
3499 :type 'string)
3501 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3502 "The opening tag for table header fields.
3503 This is customizable so that alignment options can be specified."
3504 :group 'org-export-tables
3505 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3507 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3508 "The opening tag for table data fields.
3509 This is customizable so that alignment options can be specified."
3510 :group 'org-export-tables
3511 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3513 (defcustom org-export-html-with-timestamp nil
3514 "If non-nil, write `org-export-html-html-helper-timestamp'
3515 into the exported HTML text. Otherwise, the buffer will just be saved
3516 to a file."
3517 :group 'org-export-html
3518 :type 'boolean)
3520 (defcustom org-export-html-html-helper-timestamp
3521 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3522 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3523 :group 'org-export-html
3524 :type 'string)
3526 (defgroup org-export-icalendar nil
3527 "Options specific for iCalendar export of Org-mode files."
3528 :tag "Org Export iCalendar"
3529 :group 'org-export)
3531 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3532 "The file name for the iCalendar file covering all agenda files.
3533 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3534 The file name should be absolute, the file will be overwritten without warning."
3535 :group 'org-export-icalendar
3536 :type 'file)
3538 (defcustom org-icalendar-include-todo nil
3539 "Non-nil means, export to iCalendar files should also cover TODO items."
3540 :group 'org-export-icalendar
3541 :type '(choice
3542 (const :tag "None" nil)
3543 (const :tag "Unfinished" t)
3544 (const :tag "All" all)))
3546 (defcustom org-icalendar-include-sexps t
3547 "Non-nil means, export to iCalendar files should also cover sexp entries.
3548 These are entries like in the diary, but directly in an Org-mode file."
3549 :group 'org-export-icalendar
3550 :type 'boolean)
3552 (defcustom org-icalendar-include-body 100
3553 "Amount of text below headline to be included in iCalendar export.
3554 This is a number of characters that should maximally be included.
3555 Properties, scheduling and clocking lines will always be removed.
3556 The text will be inserted into the DESCRIPTION field."
3557 :group 'org-export-icalendar
3558 :type '(choice
3559 (const :tag "Nothing" nil)
3560 (const :tag "Everything" t)
3561 (integer :tag "Max characters")))
3563 (defcustom org-icalendar-combined-name "OrgMode"
3564 "Calendar name for the combined iCalendar representing all agenda files."
3565 :group 'org-export-icalendar
3566 :type 'string)
3568 (defgroup org-font-lock nil
3569 "Font-lock settings for highlighting in Org-mode."
3570 :tag "Org Font Lock"
3571 :group 'org)
3573 (defcustom org-level-color-stars-only nil
3574 "Non-nil means fontify only the stars in each headline.
3575 When nil, the entire headline is fontified.
3576 Changing it requires restart of `font-lock-mode' to become effective
3577 also in regions already fontified."
3578 :group 'org-font-lock
3579 :type 'boolean)
3581 (defcustom org-hide-leading-stars nil
3582 "Non-nil means, hide the first N-1 stars in a headline.
3583 This works by using the face `org-hide' for these stars. This
3584 face is white for a light background, and black for a dark
3585 background. You may have to customize the face `org-hide' to
3586 make this work.
3587 Changing it requires restart of `font-lock-mode' to become effective
3588 also in regions already fontified.
3589 You may also set this on a per-file basis by adding one of the following
3590 lines to the buffer:
3592 #+STARTUP: hidestars
3593 #+STARTUP: showstars"
3594 :group 'org-font-lock
3595 :type 'boolean)
3597 (defcustom org-fontify-done-headline nil
3598 "Non-nil means, change the face of a headline if it is marked DONE.
3599 Normally, only the TODO/DONE keyword indicates the state of a headline.
3600 When this is non-nil, the headline after the keyword is set to the
3601 `org-headline-done' as an additional indication."
3602 :group 'org-font-lock
3603 :type 'boolean)
3605 (defcustom org-fontify-emphasized-text t
3606 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3607 Changing this variable requires a restart of Emacs to take effect."
3608 :group 'org-font-lock
3609 :type 'boolean)
3611 (defcustom org-highlight-latex-fragments-and-specials nil
3612 "Non-nil means, fontify what is treated specially by the exporters."
3613 :group 'org-font-lock
3614 :type 'boolean)
3616 (defcustom org-hide-emphasis-markers nil
3617 "Non-nil mean font-lock should hide the emphasis marker characters."
3618 :group 'org-font-lock
3619 :type 'boolean)
3621 (defvar org-emph-re nil
3622 "Regular expression for matching emphasis.")
3623 (defvar org-verbatim-re nil
3624 "Regular expression for matching verbatim text.")
3625 (defvar org-emphasis-regexp-components) ; defined just below
3626 (defvar org-emphasis-alist) ; defined just below
3627 (defun org-set-emph-re (var val)
3628 "Set variable and compute the emphasis regular expression."
3629 (set var val)
3630 (when (and (boundp 'org-emphasis-alist)
3631 (boundp 'org-emphasis-regexp-components)
3632 org-emphasis-alist org-emphasis-regexp-components)
3633 (let* ((e org-emphasis-regexp-components)
3634 (pre (car e))
3635 (post (nth 1 e))
3636 (border (nth 2 e))
3637 (body (nth 3 e))
3638 (nl (nth 4 e))
3639 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3640 (body1 (concat body "*?"))
3641 (markers (mapconcat 'car org-emphasis-alist ""))
3642 (vmarkers (mapconcat
3643 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3644 org-emphasis-alist "")))
3645 ;; make sure special characters appear at the right position in the class
3646 (if (string-match "\\^" markers)
3647 (setq markers (concat (replace-match "" t t markers) "^")))
3648 (if (string-match "-" markers)
3649 (setq markers (concat (replace-match "" t t markers) "-")))
3650 (if (string-match "\\^" vmarkers)
3651 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3652 (if (string-match "-" vmarkers)
3653 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3654 (if (> nl 0)
3655 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3656 (int-to-string nl) "\\}")))
3657 ;; Make the regexp
3658 (setq org-emph-re
3659 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3660 "\\("
3661 "\\([" markers "]\\)"
3662 "\\("
3663 "[^" border "]\\|"
3664 "[^" border (if (and nil stacked) markers) "]"
3665 body1
3666 "[^" border (if (and nil stacked) markers) "]"
3667 "\\)"
3668 "\\3\\)"
3669 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3670 (setq org-verbatim-re
3671 (concat "\\([" pre "]\\|^\\)"
3672 "\\("
3673 "\\([" vmarkers "]\\)"
3674 "\\("
3675 "[^" border "]\\|"
3676 "[^" border "]"
3677 body1
3678 "[^" border "]"
3679 "\\)"
3680 "\\3\\)"
3681 "\\([" post "]\\|$\\)")))))
3683 (defcustom org-emphasis-regexp-components
3684 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3685 "Components used to build the regular expression for emphasis.
3686 This is a list with 6 entries. Terminology: In an emphasis string
3687 like \" *strong word* \", we call the initial space PREMATCH, the final
3688 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3689 and \"trong wor\" is the body. The different components in this variable
3690 specify what is allowed/forbidden in each part:
3692 pre Chars allowed as prematch. Beginning of line will be allowed too.
3693 post Chars allowed as postmatch. End of line will be allowed too.
3694 border The chars *forbidden* as border characters.
3695 body-regexp A regexp like \".\" to match a body character. Don't use
3696 non-shy groups here, and don't allow newline here.
3697 newline The maximum number of newlines allowed in an emphasis exp.
3699 Use customize to modify this, or restart Emacs after changing it."
3700 :group 'org-font-lock
3701 :set 'org-set-emph-re
3702 :type '(list
3703 (sexp :tag "Allowed chars in pre ")
3704 (sexp :tag "Allowed chars in post ")
3705 (sexp :tag "Forbidden chars in border ")
3706 (sexp :tag "Regexp for body ")
3707 (integer :tag "number of newlines allowed")
3708 (option (boolean :tag "Stacking (DISABLED) "))))
3710 (defcustom org-emphasis-alist
3711 '(("*" bold "<b>" "</b>")
3712 ("/" italic "<i>" "</i>")
3713 ("_" underline "<u>" "</u>")
3714 ("=" org-code "<code>" "</code>" verbatim)
3715 ("~" org-verbatim "" "" verbatim)
3716 ("+" (:strike-through t) "<del>" "</del>")
3718 "Special syntax for emphasized text.
3719 Text starting and ending with a special character will be emphasized, for
3720 example *bold*, _underlined_ and /italic/. This variable sets the marker
3721 characters, the face to be used by font-lock for highlighting in Org-mode
3722 Emacs buffers, and the HTML tags to be used for this.
3723 Use customize to modify this, or restart Emacs after changing it."
3724 :group 'org-font-lock
3725 :set 'org-set-emph-re
3726 :type '(repeat
3727 (list
3728 (string :tag "Marker character")
3729 (choice
3730 (face :tag "Font-lock-face")
3731 (plist :tag "Face property list"))
3732 (string :tag "HTML start tag")
3733 (string :tag "HTML end tag")
3734 (option (const verbatim)))))
3736 ;;; The faces
3738 (defgroup org-faces nil
3739 "Faces in Org-mode."
3740 :tag "Org Faces"
3741 :group 'org-font-lock)
3743 (defun org-compatible-face (inherits specs)
3744 "Make a compatible face specification.
3745 If INHERITS is an existing face and if the Emacs version supports it,
3746 just inherit the face. If not, use SPECS to define the face.
3747 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3748 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3749 to the top of the list. The `min-colors' attribute will be removed from
3750 any other entries, and any resulting duplicates will be removed entirely."
3751 (cond
3752 ((and inherits (facep inherits)
3753 (not (featurep 'xemacs)) (> emacs-major-version 22))
3754 ;; In Emacs 23, we use inheritance where possible.
3755 ;; We only do this in Emacs 23, because only there the outline
3756 ;; faces have been changed to the original org-mode-level-faces.
3757 (list (list t :inherit inherits)))
3758 ((or (featurep 'xemacs) (< emacs-major-version 22))
3759 ;; These do not understand the `min-colors' attribute.
3760 (let (r e a)
3761 (while (setq e (pop specs))
3762 (cond
3763 ((memq (car e) '(t default)) (push e r))
3764 ((setq a (member '(min-colors 8) (car e)))
3765 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3766 (cdr e)))))
3767 ((setq a (assq 'min-colors (car e)))
3768 (setq e (cons (delq a (car e)) (cdr e)))
3769 (or (assoc (car e) r) (push e r)))
3770 (t (or (assoc (car e) r) (push e r)))))
3771 (nreverse r)))
3772 (t specs)))
3773 (put 'org-compatible-face 'lisp-indent-function 1)
3775 (defface org-hide
3776 '((((background light)) (:foreground "white"))
3777 (((background dark)) (:foreground "black")))
3778 "Face used to hide leading stars in headlines.
3779 The forground color of this face should be equal to the background
3780 color of the frame."
3781 :group 'org-faces)
3783 (defface org-level-1 ;; font-lock-function-name-face
3784 (org-compatible-face 'outline-1
3785 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3786 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3787 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3788 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3789 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3790 (t (:bold t))))
3791 "Face used for level 1 headlines."
3792 :group 'org-faces)
3794 (defface org-level-2 ;; font-lock-variable-name-face
3795 (org-compatible-face 'outline-2
3796 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3797 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3798 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3799 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3800 (t (:bold t))))
3801 "Face used for level 2 headlines."
3802 :group 'org-faces)
3804 (defface org-level-3 ;; font-lock-keyword-face
3805 (org-compatible-face 'outline-3
3806 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3807 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3808 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3809 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3810 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3811 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3812 (t (:bold t))))
3813 "Face used for level 3 headlines."
3814 :group 'org-faces)
3816 (defface org-level-4 ;; font-lock-comment-face
3817 (org-compatible-face 'outline-4
3818 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3819 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3820 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3821 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3822 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3823 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3824 (t (:bold t))))
3825 "Face used for level 4 headlines."
3826 :group 'org-faces)
3828 (defface org-level-5 ;; font-lock-type-face
3829 (org-compatible-face 'outline-5
3830 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3831 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3832 (((class color) (min-colors 8)) (:foreground "green"))))
3833 "Face used for level 5 headlines."
3834 :group 'org-faces)
3836 (defface org-level-6 ;; font-lock-constant-face
3837 (org-compatible-face 'outline-6
3838 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3839 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3840 (((class color) (min-colors 8)) (:foreground "magenta"))))
3841 "Face used for level 6 headlines."
3842 :group 'org-faces)
3844 (defface org-level-7 ;; font-lock-builtin-face
3845 (org-compatible-face 'outline-7
3846 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3847 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3848 (((class color) (min-colors 8)) (:foreground "blue"))))
3849 "Face used for level 7 headlines."
3850 :group 'org-faces)
3852 (defface org-level-8 ;; font-lock-string-face
3853 (org-compatible-face 'outline-8
3854 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3855 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3856 (((class color) (min-colors 8)) (:foreground "green"))))
3857 "Face used for level 8 headlines."
3858 :group 'org-faces)
3860 (defface org-special-keyword ;; font-lock-string-face
3861 (org-compatible-face nil
3862 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3863 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3864 (t (:italic t))))
3865 "Face used for special keywords."
3866 :group 'org-faces)
3868 (defface org-drawer ;; font-lock-function-name-face
3869 (org-compatible-face nil
3870 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3871 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3872 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3873 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3874 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3875 (t (:bold t))))
3876 "Face used for drawers."
3877 :group 'org-faces)
3879 (defface org-property-value nil
3880 "Face used for the value of a property."
3881 :group 'org-faces)
3883 (defface org-column
3884 (org-compatible-face nil
3885 '((((class color) (min-colors 16) (background light))
3886 (:background "grey90"))
3887 (((class color) (min-colors 16) (background dark))
3888 (:background "grey30"))
3889 (((class color) (min-colors 8))
3890 (:background "cyan" :foreground "black"))
3891 (t (:inverse-video t))))
3892 "Face for column display of entry properties."
3893 :group 'org-faces)
3895 (when (fboundp 'set-face-attribute)
3896 ;; Make sure that a fixed-width face is used when we have a column table.
3897 (set-face-attribute 'org-column nil
3898 :height (face-attribute 'default :height)
3899 :family (face-attribute 'default :family)))
3901 (defface org-warning
3902 (org-compatible-face 'font-lock-warning-face
3903 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3904 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3905 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3906 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3907 (t (:bold t))))
3908 "Face for deadlines and TODO keywords."
3909 :group 'org-faces)
3911 (defface org-archived ; similar to shadow
3912 (org-compatible-face 'shadow
3913 '((((class color grayscale) (min-colors 88) (background light))
3914 (:foreground "grey50"))
3915 (((class color grayscale) (min-colors 88) (background dark))
3916 (:foreground "grey70"))
3917 (((class color) (min-colors 8) (background light))
3918 (:foreground "green"))
3919 (((class color) (min-colors 8) (background dark))
3920 (:foreground "yellow"))))
3921 "Face for headline with the ARCHIVE tag."
3922 :group 'org-faces)
3924 (defface org-link
3925 '((((class color) (background light)) (:foreground "Purple" :underline t))
3926 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3927 (t (:underline t)))
3928 "Face for links."
3929 :group 'org-faces)
3931 (defface org-ellipsis
3932 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3933 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3934 (t (:strike-through t)))
3935 "Face for the ellipsis in folded text."
3936 :group 'org-faces)
3938 (defface org-target
3939 '((((class color) (background light)) (:underline t))
3940 (((class color) (background dark)) (:underline t))
3941 (t (:underline t)))
3942 "Face for links."
3943 :group 'org-faces)
3945 (defface org-date
3946 '((((class color) (background light)) (:foreground "Purple" :underline t))
3947 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3948 (t (:underline t)))
3949 "Face for links."
3950 :group 'org-faces)
3952 (defface org-sexp-date
3953 '((((class color) (background light)) (:foreground "Purple"))
3954 (((class color) (background dark)) (:foreground "Cyan"))
3955 (t (:underline t)))
3956 "Face for links."
3957 :group 'org-faces)
3959 (defface org-tag
3960 '((t (:bold t)))
3961 "Face for tags."
3962 :group 'org-faces)
3964 (defface org-todo ; font-lock-warning-face
3965 (org-compatible-face nil
3966 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3967 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3968 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3969 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3970 (t (:inverse-video t :bold t))))
3971 "Face for TODO keywords."
3972 :group 'org-faces)
3974 (defface org-done ;; font-lock-type-face
3975 (org-compatible-face nil
3976 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3977 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3978 (((class color) (min-colors 8)) (:foreground "green"))
3979 (t (:bold t))))
3980 "Face used for todo keywords that indicate DONE items."
3981 :group 'org-faces)
3983 (defface org-headline-done ;; font-lock-string-face
3984 (org-compatible-face nil
3985 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3986 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3987 (((class color) (min-colors 8) (background light)) (:bold nil))))
3988 "Face used to indicate that a headline is DONE.
3989 This face is only used if `org-fontify-done-headline' is set. If applies
3990 to the part of the headline after the DONE keyword."
3991 :group 'org-faces)
3993 (defcustom org-todo-keyword-faces nil
3994 "Faces for specific TODO keywords.
3995 This is a list of cons cells, with TODO keywords in the car
3996 and faces in the cdr. The face can be a symbol, or a property
3997 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3998 :group 'org-faces
3999 :group 'org-todo
4000 :type '(repeat
4001 (cons
4002 (string :tag "keyword")
4003 (sexp :tag "face"))))
4005 (defface org-table ;; font-lock-function-name-face
4006 (org-compatible-face nil
4007 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4008 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4009 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4010 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4011 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4012 (((class color) (min-colors 8) (background dark)))))
4013 "Face used for tables."
4014 :group 'org-faces)
4016 (defface org-formula
4017 (org-compatible-face nil
4018 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4019 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4020 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4021 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4022 (t (:bold t :italic t))))
4023 "Face for formulas."
4024 :group 'org-faces)
4026 (defface org-code
4027 (org-compatible-face nil
4028 '((((class color grayscale) (min-colors 88) (background light))
4029 (:foreground "grey50"))
4030 (((class color grayscale) (min-colors 88) (background dark))
4031 (:foreground "grey70"))
4032 (((class color) (min-colors 8) (background light))
4033 (:foreground "green"))
4034 (((class color) (min-colors 8) (background dark))
4035 (:foreground "yellow"))))
4036 "Face for fixed-with text like code snippets."
4037 :group 'org-faces
4038 :version "22.1")
4040 (defface org-verbatim
4041 (org-compatible-face nil
4042 '((((class color grayscale) (min-colors 88) (background light))
4043 (:foreground "grey50" :underline t))
4044 (((class color grayscale) (min-colors 88) (background dark))
4045 (:foreground "grey70" :underline t))
4046 (((class color) (min-colors 8) (background light))
4047 (:foreground "green" :underline t))
4048 (((class color) (min-colors 8) (background dark))
4049 (:foreground "yellow" :underline t))))
4050 "Face for fixed-with text like code snippets."
4051 :group 'org-faces
4052 :version "22.1")
4054 (defface org-agenda-structure ;; font-lock-function-name-face
4055 (org-compatible-face nil
4056 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4057 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4058 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4059 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4060 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4061 (t (:bold t))))
4062 "Face used in agenda for captions and dates."
4063 :group 'org-faces)
4065 (defface org-scheduled-today
4066 (org-compatible-face nil
4067 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4068 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4069 (((class color) (min-colors 8)) (:foreground "green"))
4070 (t (:bold t :italic t))))
4071 "Face for items scheduled for a certain day."
4072 :group 'org-faces)
4074 (defface org-scheduled-previously
4075 (org-compatible-face nil
4076 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4077 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4078 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4079 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4080 (t (:bold t))))
4081 "Face for items scheduled previously, and not yet done."
4082 :group 'org-faces)
4084 (defface org-upcoming-deadline
4085 (org-compatible-face nil
4086 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4087 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4088 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4089 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4090 (t (:bold t))))
4091 "Face for items scheduled previously, and not yet done."
4092 :group 'org-faces)
4094 (defcustom org-agenda-deadline-faces
4095 '((1.0 . org-warning)
4096 (0.5 . org-upcoming-deadline)
4097 (0.0 . default))
4098 "Faces for showing deadlines in the agenda.
4099 This is a list of cons cells. The cdr of each cell is a face to be used,
4100 and it can also just be like '(:foreground \"yellow\").
4101 Each car is a fraction of the head-warning time that must have passed for
4102 this the face in the cdr to be used for display. The numbers must be
4103 given in descending order. The head-warning time is normally taken
4104 from `org-deadline-warning-days', but can also be specified in the deadline
4105 timestamp itself, like this:
4107 DEADLINE: <2007-08-13 Mon -8d>
4109 You may use d for days, w for weeks, m for months and y for years. Months
4110 and years will only be treated in an approximate fashion (30.4 days for a
4111 month and 365.24 days for a year)."
4112 :group 'org-faces
4113 :group 'org-agenda-daily/weekly
4114 :type '(repeat
4115 (cons
4116 (number :tag "Fraction of head-warning time passed")
4117 (sexp :tag "Face"))))
4119 ;; FIXME: this is not a good face yet.
4120 (defface org-agenda-restriction-lock
4121 (org-compatible-face nil
4122 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4123 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4124 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4125 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4126 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4127 (t (:inverse-video t))))
4128 "Face for showing the agenda restriction lock."
4129 :group 'org-faces)
4131 (defface org-time-grid ;; font-lock-variable-name-face
4132 (org-compatible-face nil
4133 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4134 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4135 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4136 "Face used for time grids."
4137 :group 'org-faces)
4139 (defconst org-level-faces
4140 '(org-level-1 org-level-2 org-level-3 org-level-4
4141 org-level-5 org-level-6 org-level-7 org-level-8
4144 (defcustom org-n-level-faces (length org-level-faces)
4145 "The number different faces to be used for headlines.
4146 Org-mode defines 8 different headline faces, so this can be at most 8.
4147 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4148 :type 'number
4149 :group 'org-faces)
4151 ;;; Functions and variables from ther packages
4152 ;; Declared here to avoid compiler warnings
4154 (eval-and-compile
4155 (unless (fboundp 'declare-function)
4156 (defmacro declare-function (fn file &optional arglist fileonly))))
4158 ;; XEmacs only
4159 (defvar outline-mode-menu-heading)
4160 (defvar outline-mode-menu-show)
4161 (defvar outline-mode-menu-hide)
4162 (defvar zmacs-regions) ; XEmacs regions
4164 ;; Emacs only
4165 (defvar mark-active)
4167 ;; Various packages
4168 ;; FIXME: get the argument lists for the UNKNOWN stuff
4169 (declare-function add-to-diary-list "diary-lib"
4170 (date string specifier &optional marker globcolor literal))
4171 (declare-function table--at-cell-p "table" (position &optional object at-column))
4172 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4173 (declare-function Info-goto-node "info" (nodename &optional fork))
4174 (declare-function bbdb "ext:bbdb-com" (string elidep))
4175 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4176 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4177 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4178 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4179 (declare-function bbdb-record-name "ext:bbdb" (record))
4180 (declare-function bibtex-beginning-of-entry "bibtex" ())
4181 (declare-function bibtex-generate-autokey "bibtex" ())
4182 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4183 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4184 (defvar calc-embedded-close-formula)
4185 (defvar calc-embedded-open-formula)
4186 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4187 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4188 (declare-function calendar-check-holidays "holidays" (date))
4189 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4190 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4191 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4192 (declare-function calendar-forward-day "cal-move" (arg))
4193 (declare-function calendar-french-date-string "cal-french" (&optional date))
4194 (declare-function calendar-goto-date "cal-move" (date))
4195 (declare-function calendar-goto-today "cal-move" ())
4196 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4197 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4198 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4199 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4200 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4201 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4202 (defvar calendar-mode-map)
4203 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4204 (declare-function cdlatex-tab "ext:cdlatex" ())
4205 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4206 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4207 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4208 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4209 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4210 (defvar font-lock-unfontify-region-function)
4211 (declare-function gnus-article-show-summary "gnus-art" ())
4212 (declare-function gnus-summary-last-subject "gnus-sum" ())
4213 (defvar gnus-other-frame-object)
4214 (defvar gnus-group-name)
4215 (defvar gnus-article-current)
4216 (defvar Info-current-file)
4217 (defvar Info-current-node)
4218 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4219 (declare-function mh-find-path "mh-utils" ())
4220 (declare-function mh-get-header-field "mh-utils" (field))
4221 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4222 (declare-function mh-header-display "mh-show" ())
4223 (declare-function mh-index-previous-folder "mh-search" ())
4224 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4225 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4226 (declare-function mh-search-choose "mh-search" (&optional searcher))
4227 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4228 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4229 (declare-function mh-show-header-display "mh-show" t t)
4230 (declare-function mh-show-msg "mh-show" (msg))
4231 (declare-function mh-show-show "mh-show" t t)
4232 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4233 (defvar mh-progs)
4234 (defvar mh-current-folder)
4235 (defvar mh-show-folder-buffer)
4236 (defvar mh-index-folder)
4237 (defvar mh-searcher)
4238 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4239 (declare-function parse-time-string "parse-time" (string))
4240 (declare-function remember "remember" (&optional initial))
4241 (declare-function remember-buffer-desc "remember" ())
4242 (declare-function remember-finalize "remember" ())
4243 (defvar remember-save-after-remembering)
4244 (defvar remember-data-file)
4245 (defvar remember-register)
4246 (defvar remember-buffer)
4247 (defvar remember-handler-functions)
4248 (defvar remember-annotation-functions)
4249 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4250 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4251 (declare-function rmail-what-message "rmail" ())
4252 (defvar rmail-current-message)
4253 (defvar texmathp-why)
4254 (declare-function vm-beginning-of-message "ext:vm-page" ())
4255 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4256 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4257 (declare-function vm-isearch-narrow "ext:vm-search" ())
4258 (declare-function vm-isearch-update "ext:vm-search" ())
4259 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4260 (declare-function vm-su-message-id "ext:vm-summary" (m))
4261 (declare-function vm-su-subject "ext:vm-summary" (m))
4262 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4263 (defvar vm-message-pointer)
4264 (defvar vm-folder-directory)
4265 (defvar w3m-current-url)
4266 (defvar w3m-current-title)
4267 ;; backward compatibility to old version of wl
4268 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4269 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4270 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4271 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4272 (declare-function wl-summary-line-from "ext:wl-summary" ())
4273 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4274 (declare-function wl-summary-message-number "ext:wl-summary" ())
4275 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4276 (defvar wl-summary-buffer-elmo-folder)
4277 (defvar wl-summary-buffer-folder-name)
4278 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4280 (defvar org-latex-regexps)
4281 (defvar constants-unit-system)
4283 ;;; Variables for pre-computed regular expressions, all buffer local
4285 (defvar org-drawer-regexp nil
4286 "Matches first line of a hidden block.")
4287 (make-variable-buffer-local 'org-drawer-regexp)
4288 (defvar org-todo-regexp nil
4289 "Matches any of the TODO state keywords.")
4290 (make-variable-buffer-local 'org-todo-regexp)
4291 (defvar org-not-done-regexp nil
4292 "Matches any of the TODO state keywords except the last one.")
4293 (make-variable-buffer-local 'org-not-done-regexp)
4294 (defvar org-todo-line-regexp nil
4295 "Matches a headline and puts TODO state into group 2 if present.")
4296 (make-variable-buffer-local 'org-todo-line-regexp)
4297 (defvar org-complex-heading-regexp nil
4298 "Matches a headline and puts everything into groups:
4299 group 1: the stars
4300 group 2: The todo keyword, maybe
4301 group 3: Priority cookie
4302 group 4: True headline
4303 group 5: Tags")
4304 (make-variable-buffer-local 'org-complex-heading-regexp)
4305 (defvar org-todo-line-tags-regexp nil
4306 "Matches a headline and puts TODO state into group 2 if present.
4307 Also put tags into group 4 if tags are present.")
4308 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4309 (defvar org-nl-done-regexp nil
4310 "Matches newline followed by a headline with the DONE keyword.")
4311 (make-variable-buffer-local 'org-nl-done-regexp)
4312 (defvar org-looking-at-done-regexp nil
4313 "Matches the DONE keyword a point.")
4314 (make-variable-buffer-local 'org-looking-at-done-regexp)
4315 (defvar org-ds-keyword-length 12
4316 "Maximum length of the Deadline and SCHEDULED keywords.")
4317 (make-variable-buffer-local 'org-ds-keyword-length)
4318 (defvar org-deadline-regexp nil
4319 "Matches the DEADLINE keyword.")
4320 (make-variable-buffer-local 'org-deadline-regexp)
4321 (defvar org-deadline-time-regexp nil
4322 "Matches the DEADLINE keyword together with a time stamp.")
4323 (make-variable-buffer-local 'org-deadline-time-regexp)
4324 (defvar org-deadline-line-regexp nil
4325 "Matches the DEADLINE keyword and the rest of the line.")
4326 (make-variable-buffer-local 'org-deadline-line-regexp)
4327 (defvar org-scheduled-regexp nil
4328 "Matches the SCHEDULED keyword.")
4329 (make-variable-buffer-local 'org-scheduled-regexp)
4330 (defvar org-scheduled-time-regexp nil
4331 "Matches the SCHEDULED keyword together with a time stamp.")
4332 (make-variable-buffer-local 'org-scheduled-time-regexp)
4333 (defvar org-closed-time-regexp nil
4334 "Matches the CLOSED keyword together with a time stamp.")
4335 (make-variable-buffer-local 'org-closed-time-regexp)
4337 (defvar org-keyword-time-regexp nil
4338 "Matches any of the 4 keywords, together with the time stamp.")
4339 (make-variable-buffer-local 'org-keyword-time-regexp)
4340 (defvar org-keyword-time-not-clock-regexp nil
4341 "Matches any of the 3 keywords, together with the time stamp.")
4342 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4343 (defvar org-maybe-keyword-time-regexp nil
4344 "Matches a timestamp, possibly preceeded by a keyword.")
4345 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4346 (defvar org-planning-or-clock-line-re nil
4347 "Matches a line with planning or clock info.")
4348 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4350 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4351 rear-nonsticky t mouse-map t fontified t)
4352 "Properties to remove when a string without properties is wanted.")
4354 (defsubst org-match-string-no-properties (num &optional string)
4355 (if (featurep 'xemacs)
4356 (let ((s (match-string num string)))
4357 (remove-text-properties 0 (length s) org-rm-props s)
4359 (match-string-no-properties num string)))
4361 (defsubst org-no-properties (s)
4362 (if (fboundp 'set-text-properties)
4363 (set-text-properties 0 (length s) nil s)
4364 (remove-text-properties 0 (length s) org-rm-props s))
4367 (defsubst org-get-alist-option (option key)
4368 (cond ((eq key t) t)
4369 ((eq option t) t)
4370 ((assoc key option) (cdr (assoc key option)))
4371 (t (cdr (assq 'default option)))))
4373 (defsubst org-inhibit-invisibility ()
4374 "Modified `buffer-invisibility-spec' for Emacs 21.
4375 Some ops with invisible text do not work correctly on Emacs 21. For these
4376 we turn off invisibility temporarily. Use this in a `let' form."
4377 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4379 (defsubst org-set-local (var value)
4380 "Make VAR local in current buffer and set it to VALUE."
4381 (set (make-variable-buffer-local var) value))
4383 (defsubst org-mode-p ()
4384 "Check if the current buffer is in Org-mode."
4385 (eq major-mode 'org-mode))
4387 (defsubst org-last (list)
4388 "Return the last element of LIST."
4389 (car (last list)))
4391 (defun org-let (list &rest body)
4392 (eval (cons 'let (cons list body))))
4393 (put 'org-let 'lisp-indent-function 1)
4395 (defun org-let2 (list1 list2 &rest body)
4396 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4397 (put 'org-let2 'lisp-indent-function 2)
4398 (defconst org-startup-options
4399 '(("fold" org-startup-folded t)
4400 ("overview" org-startup-folded t)
4401 ("nofold" org-startup-folded nil)
4402 ("showall" org-startup-folded nil)
4403 ("content" org-startup-folded content)
4404 ("hidestars" org-hide-leading-stars t)
4405 ("showstars" org-hide-leading-stars nil)
4406 ("odd" org-odd-levels-only t)
4407 ("oddeven" org-odd-levels-only nil)
4408 ("align" org-startup-align-all-tables t)
4409 ("noalign" org-startup-align-all-tables nil)
4410 ("customtime" org-display-custom-times t)
4411 ("logdone" org-log-done time)
4412 ("lognotedone" org-log-done note)
4413 ("nologdone" org-log-done nil)
4414 ("lognoteclock-out" org-log-note-clock-out t)
4415 ("nolognoteclock-out" org-log-note-clock-out nil)
4416 ("logrepeat" org-log-repeat state)
4417 ("lognoterepeat" org-log-repeat note)
4418 ("nologrepeat" org-log-repeat nil)
4419 ("constcgs" constants-unit-system cgs)
4420 ("constSI" constants-unit-system SI))
4421 "Variable associated with STARTUP options for org-mode.
4422 Each element is a list of three items: The startup options as written
4423 in the #+STARTUP line, the corresponding variable, and the value to
4424 set this variable to if the option is found. An optional forth element PUSH
4425 means to push this value onto the list in the variable.")
4427 (defun org-set-regexps-and-options ()
4428 "Precompute regular expressions for current buffer."
4429 (when (org-mode-p)
4430 (org-set-local 'org-todo-kwd-alist nil)
4431 (org-set-local 'org-todo-key-alist nil)
4432 (org-set-local 'org-todo-key-trigger nil)
4433 (org-set-local 'org-todo-keywords-1 nil)
4434 (org-set-local 'org-done-keywords nil)
4435 (org-set-local 'org-todo-heads nil)
4436 (org-set-local 'org-todo-sets nil)
4437 (org-set-local 'org-todo-log-states nil)
4438 (let ((re (org-make-options-regexp
4439 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4440 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4441 "CONSTANTS" "PROPERTY" "DRAWERS")))
4442 (splitre "[ \t]+")
4443 kwds kws0 kwsa key log value cat arch tags const links hw dws
4444 tail sep kws1 prio props drawers)
4445 (save-excursion
4446 (save-restriction
4447 (widen)
4448 (goto-char (point-min))
4449 (while (re-search-forward re nil t)
4450 (setq key (match-string 1) value (org-match-string-no-properties 2))
4451 (cond
4452 ((equal key "CATEGORY")
4453 (if (string-match "[ \t]+$" value)
4454 (setq value (replace-match "" t t value)))
4455 (setq cat value))
4456 ((member key '("SEQ_TODO" "TODO"))
4457 (push (cons 'sequence (org-split-string value splitre)) kwds))
4458 ((equal key "TYP_TODO")
4459 (push (cons 'type (org-split-string value splitre)) kwds))
4460 ((equal key "TAGS")
4461 (setq tags (append tags (org-split-string value splitre))))
4462 ((equal key "COLUMNS")
4463 (org-set-local 'org-columns-default-format value))
4464 ((equal key "LINK")
4465 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4466 (push (cons (match-string 1 value)
4467 (org-trim (match-string 2 value)))
4468 links)))
4469 ((equal key "PRIORITIES")
4470 (setq prio (org-split-string value " +")))
4471 ((equal key "PROPERTY")
4472 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4473 (push (cons (match-string 1 value) (match-string 2 value))
4474 props)))
4475 ((equal key "DRAWERS")
4476 (setq drawers (org-split-string value splitre)))
4477 ((equal key "CONSTANTS")
4478 (setq const (append const (org-split-string value splitre))))
4479 ((equal key "STARTUP")
4480 (let ((opts (org-split-string value splitre))
4481 l var val)
4482 (while (setq l (pop opts))
4483 (when (setq l (assoc l org-startup-options))
4484 (setq var (nth 1 l) val (nth 2 l))
4485 (if (not (nth 3 l))
4486 (set (make-local-variable var) val)
4487 (if (not (listp (symbol-value var)))
4488 (set (make-local-variable var) nil))
4489 (set (make-local-variable var) (symbol-value var))
4490 (add-to-list var val))))))
4491 ((equal key "ARCHIVE")
4492 (string-match " *$" value)
4493 (setq arch (replace-match "" t t value))
4494 (remove-text-properties 0 (length arch)
4495 '(face t fontified t) arch)))
4497 (when cat
4498 (org-set-local 'org-category (intern cat))
4499 (push (cons "CATEGORY" cat) props))
4500 (when prio
4501 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4502 (setq prio (mapcar 'string-to-char prio))
4503 (org-set-local 'org-highest-priority (nth 0 prio))
4504 (org-set-local 'org-lowest-priority (nth 1 prio))
4505 (org-set-local 'org-default-priority (nth 2 prio)))
4506 (and props (org-set-local 'org-local-properties (nreverse props)))
4507 (and drawers (org-set-local 'org-drawers drawers))
4508 (and arch (org-set-local 'org-archive-location arch))
4509 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4510 ;; Process the TODO keywords
4511 (unless kwds
4512 ;; Use the global values as if they had been given locally.
4513 (setq kwds (default-value 'org-todo-keywords))
4514 (if (stringp (car kwds))
4515 (setq kwds (list (cons org-todo-interpretation
4516 (default-value 'org-todo-keywords)))))
4517 (setq kwds (reverse kwds)))
4518 (setq kwds (nreverse kwds))
4519 (let (inter kws kw)
4520 (while (setq kws (pop kwds))
4521 (setq inter (pop kws) sep (member "|" kws)
4522 kws0 (delete "|" (copy-sequence kws))
4523 kwsa nil
4524 kws1 (mapcar
4525 (lambda (x)
4526 ;; 1 2
4527 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4528 (progn
4529 (setq kw (match-string 1 x)
4530 key (and (match-end 2) (match-string 2 x))
4531 log (org-extract-log-state-settings x))
4532 (push (cons kw (and key (string-to-char key))) kwsa)
4533 (and log (push log org-todo-log-states))
4535 (error "Invalid TODO keyword %s" x)))
4536 kws0)
4537 kwsa (if kwsa (append '((:startgroup))
4538 (nreverse kwsa)
4539 '((:endgroup))))
4540 hw (car kws1)
4541 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4542 tail (list inter hw (car dws) (org-last dws)))
4543 (add-to-list 'org-todo-heads hw 'append)
4544 (push kws1 org-todo-sets)
4545 (setq org-done-keywords (append org-done-keywords dws nil))
4546 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4547 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4548 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4549 (setq org-todo-sets (nreverse org-todo-sets)
4550 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4551 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4552 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4553 ;; Process the constants
4554 (when const
4555 (let (e cst)
4556 (while (setq e (pop const))
4557 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4558 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4559 (setq org-table-formula-constants-local cst)))
4561 ;; Process the tags.
4562 (when tags
4563 (let (e tgs)
4564 (while (setq e (pop tags))
4565 (cond
4566 ((equal e "{") (push '(:startgroup) tgs))
4567 ((equal e "}") (push '(:endgroup) tgs))
4568 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4569 (push (cons (match-string 1 e)
4570 (string-to-char (match-string 2 e)))
4571 tgs))
4572 (t (push (list e) tgs))))
4573 (org-set-local 'org-tag-alist nil)
4574 (while (setq e (pop tgs))
4575 (or (and (stringp (car e))
4576 (assoc (car e) org-tag-alist))
4577 (push e org-tag-alist))))))
4579 ;; Compute the regular expressions and other local variables
4580 (if (not org-done-keywords)
4581 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4582 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4583 (length org-scheduled-string)))
4584 org-drawer-regexp
4585 (concat "^[ \t]*:\\("
4586 (mapconcat 'regexp-quote org-drawers "\\|")
4587 "\\):[ \t]*$")
4588 org-not-done-keywords
4589 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4590 org-todo-regexp
4591 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4592 "\\|") "\\)\\>")
4593 org-not-done-regexp
4594 (concat "\\<\\("
4595 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4596 "\\)\\>")
4597 org-todo-line-regexp
4598 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4599 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4600 "\\)\\>\\)?[ \t]*\\(.*\\)")
4601 org-complex-heading-regexp
4602 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4603 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4604 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4605 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4606 org-nl-done-regexp
4607 (concat "\n\\*+[ \t]+"
4608 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4609 "\\)" "\\>")
4610 org-todo-line-tags-regexp
4611 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4612 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4613 (org-re
4614 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4615 org-looking-at-done-regexp
4616 (concat "^" "\\(?:"
4617 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4618 "\\>")
4619 org-deadline-regexp (concat "\\<" org-deadline-string)
4620 org-deadline-time-regexp
4621 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4622 org-deadline-line-regexp
4623 (concat "\\<\\(" org-deadline-string "\\).*")
4624 org-scheduled-regexp
4625 (concat "\\<" org-scheduled-string)
4626 org-scheduled-time-regexp
4627 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4628 org-closed-time-regexp
4629 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4630 org-keyword-time-regexp
4631 (concat "\\<\\(" org-scheduled-string
4632 "\\|" org-deadline-string
4633 "\\|" org-closed-string
4634 "\\|" org-clock-string "\\)"
4635 " *[[<]\\([^]>]+\\)[]>]")
4636 org-keyword-time-not-clock-regexp
4637 (concat "\\<\\(" org-scheduled-string
4638 "\\|" org-deadline-string
4639 "\\|" org-closed-string
4640 "\\)"
4641 " *[[<]\\([^]>]+\\)[]>]")
4642 org-maybe-keyword-time-regexp
4643 (concat "\\(\\<\\(" org-scheduled-string
4644 "\\|" org-deadline-string
4645 "\\|" org-closed-string
4646 "\\|" org-clock-string "\\)\\)?"
4647 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4648 org-planning-or-clock-line-re
4649 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4650 "\\|" org-deadline-string
4651 "\\|" org-closed-string "\\|" org-clock-string
4652 "\\)\\>\\)")
4654 (org-compute-latex-and-specials-regexp)
4655 (org-set-font-lock-defaults)))
4657 (defun org-extract-log-state-settings (x)
4658 "Extract the log state setting from a TODO keyword string.
4659 This will extract info from a string like \"WAIT(w@/!)\"."
4660 (let (kw key log1 log2)
4661 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4662 (setq kw (match-string 1 x)
4663 key (and (match-end 2) (match-string 2 x))
4664 log1 (and (match-end 3) (match-string 3 x))
4665 log2 (and (match-end 4) (match-string 4 x)))
4666 (and (or log1 log2)
4667 (list kw
4668 (and log1 (if (equal log1 "!") 'time 'note))
4669 (and log2 (if (equal log2 "!") 'time 'note)))))))
4671 (defun org-remove-keyword-keys (list)
4672 (mapcar (lambda (x)
4673 (if (string-match "(..?)$" x)
4674 (substring x 0 (match-beginning 0))
4676 list))
4678 ;; FIXME: this could be done much better, using second characters etc.
4679 (defun org-assign-fast-keys (alist)
4680 "Assign fast keys to a keyword-key alist.
4681 Respect keys that are already there."
4682 (let (new e k c c1 c2 (char ?a))
4683 (while (setq e (pop alist))
4684 (cond
4685 ((equal e '(:startgroup)) (push e new))
4686 ((equal e '(:endgroup)) (push e new))
4688 (setq k (car e) c2 nil)
4689 (if (cdr e)
4690 (setq c (cdr e))
4691 ;; automatically assign a character.
4692 (setq c1 (string-to-char
4693 (downcase (substring
4694 k (if (= (string-to-char k) ?@) 1 0)))))
4695 (if (or (rassoc c1 new) (rassoc c1 alist))
4696 (while (or (rassoc char new) (rassoc char alist))
4697 (setq char (1+ char)))
4698 (setq c2 c1))
4699 (setq c (or c2 char)))
4700 (push (cons k c) new))))
4701 (nreverse new)))
4703 ;;; Some variables ujsed in various places
4705 (defvar org-window-configuration nil
4706 "Used in various places to store a window configuration.")
4707 (defvar org-finish-function nil
4708 "Function to be called when `C-c C-c' is used.
4709 This is for getting out of special buffers like remember.")
4712 ;; FIXME: Occasionally check by commenting these, to make sure
4713 ;; no other functions uses these, forgetting to let-bind them.
4714 (defvar entry)
4715 (defvar state)
4716 (defvar last-state)
4717 (defvar date)
4718 (defvar description)
4720 ;; Defined somewhere in this file, but used before definition.
4721 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4722 (defvar org-agenda-buffer-name)
4723 (defvar org-agenda-undo-list)
4724 (defvar org-agenda-pending-undo-list)
4725 (defvar org-agenda-overriding-header)
4726 (defvar orgtbl-mode)
4727 (defvar org-html-entities)
4728 (defvar org-struct-menu)
4729 (defvar org-org-menu)
4730 (defvar org-tbl-menu)
4731 (defvar org-agenda-keymap)
4733 ;;;; Emacs/XEmacs compatibility
4735 ;; Overlay compatibility functions
4736 (defun org-make-overlay (beg end &optional buffer)
4737 (if (featurep 'xemacs)
4738 (make-extent beg end buffer)
4739 (make-overlay beg end buffer)))
4740 (defun org-delete-overlay (ovl)
4741 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4742 (defun org-detach-overlay (ovl)
4743 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4744 (defun org-move-overlay (ovl beg end &optional buffer)
4745 (if (featurep 'xemacs)
4746 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4747 (move-overlay ovl beg end buffer)))
4748 (defun org-overlay-put (ovl prop value)
4749 (if (featurep 'xemacs)
4750 (set-extent-property ovl prop value)
4751 (overlay-put ovl prop value)))
4752 (defun org-overlay-display (ovl text &optional face evap)
4753 "Make overlay OVL display TEXT with face FACE."
4754 (if (featurep 'xemacs)
4755 (let ((gl (make-glyph text)))
4756 (and face (set-glyph-face gl face))
4757 (set-extent-property ovl 'invisible t)
4758 (set-extent-property ovl 'end-glyph gl))
4759 (overlay-put ovl 'display text)
4760 (if face (overlay-put ovl 'face face))
4761 (if evap (overlay-put ovl 'evaporate t))))
4762 (defun org-overlay-before-string (ovl text &optional face evap)
4763 "Make overlay OVL display TEXT with face FACE."
4764 (if (featurep 'xemacs)
4765 (let ((gl (make-glyph text)))
4766 (and face (set-glyph-face gl face))
4767 (set-extent-property ovl 'begin-glyph gl))
4768 (if face (org-add-props text nil 'face face))
4769 (overlay-put ovl 'before-string text)
4770 (if evap (overlay-put ovl 'evaporate t))))
4771 (defun org-overlay-get (ovl prop)
4772 (if (featurep 'xemacs)
4773 (extent-property ovl prop)
4774 (overlay-get ovl prop)))
4775 (defun org-overlays-at (pos)
4776 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4777 (defun org-overlays-in (&optional start end)
4778 (if (featurep 'xemacs)
4779 (extent-list nil start end)
4780 (overlays-in start end)))
4781 (defun org-overlay-start (o)
4782 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4783 (defun org-overlay-end (o)
4784 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4785 (defun org-find-overlays (prop &optional pos delete)
4786 "Find all overlays specifying PROP at POS or point.
4787 If DELETE is non-nil, delete all those overlays."
4788 (let ((overlays (org-overlays-at (or pos (point))))
4789 ov found)
4790 (while (setq ov (pop overlays))
4791 (if (org-overlay-get ov prop)
4792 (if delete (org-delete-overlay ov) (push ov found))))
4793 found))
4795 ;; Region compatibility
4797 (defun org-add-hook (hook function &optional append local)
4798 "Add-hook, compatible with both Emacsen."
4799 (if (and local (featurep 'xemacs))
4800 (add-local-hook hook function append)
4801 (add-hook hook function append local)))
4803 (defvar org-ignore-region nil
4804 "To temporarily disable the active region.")
4806 (defun org-region-active-p ()
4807 "Is `transient-mark-mode' on and the region active?
4808 Works on both Emacs and XEmacs."
4809 (if org-ignore-region
4811 (if (featurep 'xemacs)
4812 (and zmacs-regions (region-active-p))
4813 (if (fboundp 'use-region-p)
4814 (use-region-p)
4815 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4817 ;; Invisibility compatibility
4819 (defun org-add-to-invisibility-spec (arg)
4820 "Add elements to `buffer-invisibility-spec'.
4821 See documentation for `buffer-invisibility-spec' for the kind of elements
4822 that can be added."
4823 (cond
4824 ((fboundp 'add-to-invisibility-spec)
4825 (add-to-invisibility-spec arg))
4826 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4827 (setq buffer-invisibility-spec (list arg)))
4829 (setq buffer-invisibility-spec
4830 (cons arg buffer-invisibility-spec)))))
4832 (defun org-remove-from-invisibility-spec (arg)
4833 "Remove elements from `buffer-invisibility-spec'."
4834 (if (fboundp 'remove-from-invisibility-spec)
4835 (remove-from-invisibility-spec arg)
4836 (if (consp buffer-invisibility-spec)
4837 (setq buffer-invisibility-spec
4838 (delete arg buffer-invisibility-spec)))))
4840 (defun org-in-invisibility-spec-p (arg)
4841 "Is ARG a member of `buffer-invisibility-spec'?"
4842 (if (consp buffer-invisibility-spec)
4843 (member arg buffer-invisibility-spec)
4844 nil))
4846 ;;;; Define the Org-mode
4848 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4849 (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."))
4852 ;; We use a before-change function to check if a table might need
4853 ;; an update.
4854 (defvar org-table-may-need-update t
4855 "Indicates that a table might need an update.
4856 This variable is set by `org-before-change-function'.
4857 `org-table-align' sets it back to nil.")
4858 (defvar org-mode-map)
4859 (defvar org-mode-hook nil)
4860 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4861 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4862 (defvar org-table-buffer-is-an nil)
4863 (defconst org-outline-regexp "\\*+ ")
4865 ;;;###autoload
4866 (define-derived-mode org-mode outline-mode "Org"
4867 "Outline-based notes management and organizer, alias
4868 \"Carsten's outline-mode for keeping track of everything.\"
4870 Org-mode develops organizational tasks around a NOTES file which
4871 contains information about projects as plain text. Org-mode is
4872 implemented on top of outline-mode, which is ideal to keep the content
4873 of large files well structured. It supports ToDo items, deadlines and
4874 time stamps, which magically appear in the diary listing of the Emacs
4875 calendar. Tables are easily created with a built-in table editor.
4876 Plain text URL-like links connect to websites, emails (VM), Usenet
4877 messages (Gnus), BBDB entries, and any files related to the project.
4878 For printing and sharing of notes, an Org-mode file (or a part of it)
4879 can be exported as a structured ASCII or HTML file.
4881 The following commands are available:
4883 \\{org-mode-map}"
4885 ;; Get rid of Outline menus, they are not needed
4886 ;; Need to do this here because define-derived-mode sets up
4887 ;; the keymap so late. Still, it is a waste to call this each time
4888 ;; we switch another buffer into org-mode.
4889 (if (featurep 'xemacs)
4890 (when (boundp 'outline-mode-menu-heading)
4891 ;; Assume this is Greg's port, it used easymenu
4892 (easy-menu-remove outline-mode-menu-heading)
4893 (easy-menu-remove outline-mode-menu-show)
4894 (easy-menu-remove outline-mode-menu-hide))
4895 (define-key org-mode-map [menu-bar headings] 'undefined)
4896 (define-key org-mode-map [menu-bar hide] 'undefined)
4897 (define-key org-mode-map [menu-bar show] 'undefined))
4899 (easy-menu-add org-org-menu)
4900 (easy-menu-add org-tbl-menu)
4901 (org-install-agenda-files-menu)
4902 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4903 (org-add-to-invisibility-spec '(org-cwidth))
4904 (when (featurep 'xemacs)
4905 (org-set-local 'line-move-ignore-invisible t))
4906 (org-set-local 'outline-regexp org-outline-regexp)
4907 (org-set-local 'outline-level 'org-outline-level)
4908 (when (and org-ellipsis
4909 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4910 (fboundp 'make-glyph-code))
4911 (unless org-display-table
4912 (setq org-display-table (make-display-table)))
4913 (set-display-table-slot
4914 org-display-table 4
4915 (vconcat (mapcar
4916 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4917 org-ellipsis)))
4918 (if (stringp org-ellipsis) org-ellipsis "..."))))
4919 (setq buffer-display-table org-display-table))
4920 (org-set-regexps-and-options)
4921 ;; Calc embedded
4922 (org-set-local 'calc-embedded-open-mode "# ")
4923 (modify-syntax-entry ?# "<")
4924 (modify-syntax-entry ?@ "w")
4925 (if org-startup-truncated (setq truncate-lines t))
4926 (org-set-local 'font-lock-unfontify-region-function
4927 'org-unfontify-region)
4928 ;; Activate before-change-function
4929 (org-set-local 'org-table-may-need-update t)
4930 (org-add-hook 'before-change-functions 'org-before-change-function nil
4931 'local)
4932 ;; Check for running clock before killing a buffer
4933 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4934 ;; Paragraphs and auto-filling
4935 (org-set-autofill-regexps)
4936 (setq indent-line-function 'org-indent-line-function)
4937 (org-update-radio-target-regexp)
4939 ;; Comment characters
4940 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4941 (org-set-local 'comment-padding " ")
4943 ;; Align options lines
4944 (org-set-local
4945 'align-mode-rules-list
4946 '((org-in-buffer-settings
4947 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4948 (modes . '(org-mode)))))
4950 ;; Imenu
4951 (org-set-local 'imenu-create-index-function
4952 'org-imenu-get-tree)
4954 ;; Make isearch reveal context
4955 (if (or (featurep 'xemacs)
4956 (not (boundp 'outline-isearch-open-invisible-function)))
4957 ;; Emacs 21 and XEmacs make use of the hook
4958 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4959 ;; Emacs 22 deals with this through a special variable
4960 (org-set-local 'outline-isearch-open-invisible-function
4961 (lambda (&rest ignore) (org-show-context 'isearch))))
4963 ;; If empty file that did not turn on org-mode automatically, make it to.
4964 (if (and org-insert-mode-line-in-empty-file
4965 (interactive-p)
4966 (= (point-min) (point-max)))
4967 (insert "# -*- mode: org -*-\n\n"))
4969 (unless org-inhibit-startup
4970 (when org-startup-align-all-tables
4971 (let ((bmp (buffer-modified-p)))
4972 (org-table-map-tables 'org-table-align)
4973 (set-buffer-modified-p bmp)))
4974 (org-cycle-hide-drawers 'all)
4975 (cond
4976 ((eq org-startup-folded t)
4977 (org-cycle '(4)))
4978 ((eq org-startup-folded 'content)
4979 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4980 (org-cycle '(4)) (org-cycle '(4)))))))
4982 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4984 (defsubst org-call-with-arg (command arg)
4985 "Call COMMAND interactively, but pretend prefix are was ARG."
4986 (let ((current-prefix-arg arg)) (call-interactively command)))
4988 (defsubst org-current-line (&optional pos)
4989 (save-excursion
4990 (and pos (goto-char pos))
4991 ;; works also in narrowed buffer, because we start at 1, not point-min
4992 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4994 (defun org-current-time ()
4995 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4996 (if (> org-time-stamp-rounding-minutes 0)
4997 (let ((r org-time-stamp-rounding-minutes)
4998 (time (decode-time)))
4999 (apply 'encode-time
5000 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5001 (nthcdr 2 time))))
5002 (current-time)))
5004 (defun org-add-props (string plist &rest props)
5005 "Add text properties to entire string, from beginning to end.
5006 PLIST may be a list of properties, PROPS are individual properties and values
5007 that will be added to PLIST. Returns the string that was modified."
5008 (add-text-properties
5009 0 (length string) (if props (append plist props) plist) string)
5010 string)
5011 (put 'org-add-props 'lisp-indent-function 2)
5014 ;;;; Font-Lock stuff, including the activators
5016 (defvar org-mouse-map (make-sparse-keymap))
5017 (org-defkey org-mouse-map
5018 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5019 (org-defkey org-mouse-map
5020 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5021 (when org-mouse-1-follows-link
5022 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5023 (when org-tab-follows-link
5024 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5025 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5026 (when org-return-follows-link
5027 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5028 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5030 (require 'font-lock)
5032 (defconst org-non-link-chars "]\t\n\r<>")
5033 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5034 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5035 (defvar org-link-re-with-space nil
5036 "Matches a link with spaces, optional angular brackets around it.")
5037 (defvar org-link-re-with-space2 nil
5038 "Matches a link with spaces, optional angular brackets around it.")
5039 (defvar org-angle-link-re nil
5040 "Matches link with angular brackets, spaces are allowed.")
5041 (defvar org-plain-link-re nil
5042 "Matches plain link, without spaces.")
5043 (defvar org-bracket-link-regexp nil
5044 "Matches a link in double brackets.")
5045 (defvar org-bracket-link-analytic-regexp nil
5046 "Regular expression used to analyze links.
5047 Here is what the match groups contain after a match:
5048 1: http:
5049 2: http
5050 3: path
5051 4: [desc]
5052 5: desc")
5053 (defvar org-any-link-re nil
5054 "Regular expression matching any link.")
5056 (defun org-make-link-regexps ()
5057 "Update the link regular expressions.
5058 This should be called after the variable `org-link-types' has changed."
5059 (setq org-link-re-with-space
5060 (concat
5061 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5062 "\\([^" org-non-link-chars " ]"
5063 "[^" org-non-link-chars "]*"
5064 "[^" org-non-link-chars " ]\\)>?")
5065 org-link-re-with-space2
5066 (concat
5067 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5068 "\\([^" org-non-link-chars " ]"
5069 "[^]\t\n\r]*"
5070 "[^" org-non-link-chars " ]\\)>?")
5071 org-angle-link-re
5072 (concat
5073 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5074 "\\([^" org-non-link-chars " ]"
5075 "[^" org-non-link-chars "]*"
5076 "\\)>")
5077 org-plain-link-re
5078 (concat
5079 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5080 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5081 org-bracket-link-regexp
5082 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5083 org-bracket-link-analytic-regexp
5084 (concat
5085 "\\[\\["
5086 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5087 "\\([^]]+\\)"
5088 "\\]"
5089 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5090 "\\]")
5091 org-any-link-re
5092 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5093 org-angle-link-re "\\)\\|\\("
5094 org-plain-link-re "\\)")))
5096 (org-make-link-regexps)
5098 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5099 "Regular expression for fast time stamp matching.")
5100 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5101 "Regular expression for fast time stamp matching.")
5102 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5103 "Regular expression matching time strings for analysis.
5104 This one does not require the space after the date.")
5105 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5106 "Regular expression matching time strings for analysis.")
5107 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5108 "Regular expression matching time stamps, with groups.")
5109 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5110 "Regular expression matching time stamps (also [..]), with groups.")
5111 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5112 "Regular expression matching a time stamp range.")
5113 (defconst org-tr-regexp-both
5114 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5115 "Regular expression matching a time stamp range.")
5116 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5117 org-ts-regexp "\\)?")
5118 "Regular expression matching a time stamp or time stamp range.")
5119 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5120 org-ts-regexp-both "\\)?")
5121 "Regular expression matching a time stamp or time stamp range.
5122 The time stamps may be either active or inactive.")
5124 (defvar org-emph-face nil)
5126 (defun org-do-emphasis-faces (limit)
5127 "Run through the buffer and add overlays to links."
5128 (let (rtn)
5129 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5130 (if (not (= (char-after (match-beginning 3))
5131 (char-after (match-beginning 4))))
5132 (progn
5133 (setq rtn t)
5134 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5135 'face
5136 (nth 1 (assoc (match-string 3)
5137 org-emphasis-alist)))
5138 (add-text-properties (match-beginning 2) (match-end 2)
5139 '(font-lock-multiline t))
5140 (when org-hide-emphasis-markers
5141 (add-text-properties (match-end 4) (match-beginning 5)
5142 '(invisible org-link))
5143 (add-text-properties (match-beginning 3) (match-end 3)
5144 '(invisible org-link)))))
5145 (backward-char 1))
5146 rtn))
5148 (defun org-emphasize (&optional char)
5149 "Insert or change an emphasis, i.e. a font like bold or italic.
5150 If there is an active region, change that region to a new emphasis.
5151 If there is no region, just insert the marker characters and position
5152 the cursor between them.
5153 CHAR should be either the marker character, or the first character of the
5154 HTML tag associated with that emphasis. If CHAR is a space, the means
5155 to remove the emphasis of the selected region.
5156 If char is not given (for example in an interactive call) it
5157 will be prompted for."
5158 (interactive)
5159 (let ((eal org-emphasis-alist) e det
5160 (erc org-emphasis-regexp-components)
5161 (prompt "")
5162 (string "") beg end move tag c s)
5163 (if (org-region-active-p)
5164 (setq beg (region-beginning) end (region-end)
5165 string (buffer-substring beg end))
5166 (setq move t))
5168 (while (setq e (pop eal))
5169 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5170 c (aref tag 0))
5171 (push (cons c (string-to-char (car e))) det)
5172 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5173 (substring tag 1)))))
5174 (unless char
5175 (message "%s" (concat "Emphasis marker or tag:" prompt))
5176 (setq char (read-char-exclusive)))
5177 (setq char (or (cdr (assoc char det)) char))
5178 (if (equal char ?\ )
5179 (setq s "" move nil)
5180 (unless (assoc (char-to-string char) org-emphasis-alist)
5181 (error "No such emphasis marker: \"%c\"" char))
5182 (setq s (char-to-string char)))
5183 (while (and (> (length string) 1)
5184 (equal (substring string 0 1) (substring string -1))
5185 (assoc (substring string 0 1) org-emphasis-alist))
5186 (setq string (substring string 1 -1)))
5187 (setq string (concat s string s))
5188 (if beg (delete-region beg end))
5189 (unless (or (bolp)
5190 (string-match (concat "[" (nth 0 erc) "\n]")
5191 (char-to-string (char-before (point)))))
5192 (insert " "))
5193 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5194 (char-to-string (char-after (point))))
5195 (insert " ") (backward-char 1))
5196 (insert string)
5197 (and move (backward-char 1))))
5199 (defconst org-nonsticky-props
5200 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5203 (defun org-activate-plain-links (limit)
5204 "Run through the buffer and add overlays to links."
5205 (catch 'exit
5206 (let (f)
5207 (while (re-search-forward org-plain-link-re limit t)
5208 (setq f (get-text-property (match-beginning 0) 'face))
5209 (if (or (eq f 'org-tag)
5210 (and (listp f) (memq 'org-tag f)))
5212 (add-text-properties (match-beginning 0) (match-end 0)
5213 (list 'mouse-face 'highlight
5214 'rear-nonsticky org-nonsticky-props
5215 'keymap org-mouse-map
5217 (throw 'exit t))))))
5219 (defun org-activate-code (limit)
5220 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5221 (unless (get-text-property (match-beginning 1) 'face)
5222 (remove-text-properties (match-beginning 0) (match-end 0)
5223 '(display t invisible t intangible t))
5224 t)))
5226 (defun org-activate-angle-links (limit)
5227 "Run through the buffer and add overlays to links."
5228 (if (re-search-forward org-angle-link-re limit t)
5229 (progn
5230 (add-text-properties (match-beginning 0) (match-end 0)
5231 (list 'mouse-face 'highlight
5232 'rear-nonsticky org-nonsticky-props
5233 'keymap org-mouse-map
5235 t)))
5237 (defmacro org-maybe-intangible (props)
5238 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5239 In emacs 21, invisible text is not avoided by the command loop, so the
5240 intangible property is needed to make sure point skips this text.
5241 In Emacs 22, this is not necessary. The intangible text property has
5242 led to problems with flyspell. These problems are fixed in flyspell.el,
5243 but we still avoid setting the property in Emacs 22 and later.
5244 We use a macro so that the test can happen at compilation time."
5245 (if (< emacs-major-version 22)
5246 `(append '(intangible t) ,props)
5247 props))
5249 (defun org-activate-bracket-links (limit)
5250 "Run through the buffer and add overlays to bracketed links."
5251 (if (re-search-forward org-bracket-link-regexp limit t)
5252 (let* ((help (concat "LINK: "
5253 (org-match-string-no-properties 1)))
5254 ;; FIXME: above we should remove the escapes.
5255 ;; but that requires another match, protecting match data,
5256 ;; a lot of overhead for font-lock.
5257 (ip (org-maybe-intangible
5258 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5259 'keymap org-mouse-map 'mouse-face 'highlight
5260 'font-lock-multiline t 'help-echo help)))
5261 (vp (list 'rear-nonsticky org-nonsticky-props
5262 'keymap org-mouse-map 'mouse-face 'highlight
5263 ' font-lock-multiline t 'help-echo help)))
5264 ;; We need to remove the invisible property here. Table narrowing
5265 ;; may have made some of this invisible.
5266 (remove-text-properties (match-beginning 0) (match-end 0)
5267 '(invisible nil))
5268 (if (match-end 3)
5269 (progn
5270 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5271 (add-text-properties (match-beginning 3) (match-end 3) vp)
5272 (add-text-properties (match-end 3) (match-end 0) ip))
5273 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5274 (add-text-properties (match-beginning 1) (match-end 1) vp)
5275 (add-text-properties (match-end 1) (match-end 0) ip))
5276 t)))
5278 (defun org-activate-dates (limit)
5279 "Run through the buffer and add overlays to dates."
5280 (if (re-search-forward org-tsr-regexp-both limit t)
5281 (progn
5282 (add-text-properties (match-beginning 0) (match-end 0)
5283 (list 'mouse-face 'highlight
5284 'rear-nonsticky org-nonsticky-props
5285 'keymap org-mouse-map))
5286 (when org-display-custom-times
5287 (if (match-end 3)
5288 (org-display-custom-time (match-beginning 3) (match-end 3)))
5289 (org-display-custom-time (match-beginning 1) (match-end 1)))
5290 t)))
5292 (defvar org-target-link-regexp nil
5293 "Regular expression matching radio targets in plain text.")
5294 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5295 "Regular expression matching a link target.")
5296 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5297 "Regular expression matching a radio target.")
5298 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5299 "Regular expression matching any target.")
5301 (defun org-activate-target-links (limit)
5302 "Run through the buffer and add overlays to target matches."
5303 (when org-target-link-regexp
5304 (let ((case-fold-search t))
5305 (if (re-search-forward org-target-link-regexp limit t)
5306 (progn
5307 (add-text-properties (match-beginning 0) (match-end 0)
5308 (list 'mouse-face 'highlight
5309 'rear-nonsticky org-nonsticky-props
5310 'keymap org-mouse-map
5311 'help-echo "Radio target link"
5312 'org-linked-text t))
5313 t)))))
5315 (defun org-update-radio-target-regexp ()
5316 "Find all radio targets in this file and update the regular expression."
5317 (interactive)
5318 (when (memq 'radio org-activate-links)
5319 (setq org-target-link-regexp
5320 (org-make-target-link-regexp (org-all-targets 'radio)))
5321 (org-restart-font-lock)))
5323 (defun org-hide-wide-columns (limit)
5324 (let (s e)
5325 (setq s (text-property-any (point) (or limit (point-max))
5326 'org-cwidth t))
5327 (when s
5328 (setq e (next-single-property-change s 'org-cwidth))
5329 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5330 (goto-char e)
5331 t)))
5333 (defvar org-latex-and-specials-regexp nil
5334 "Regular expression for highlighting export special stuff.")
5335 (defvar org-match-substring-regexp)
5336 (defvar org-match-substring-with-braces-regexp)
5337 (defvar org-export-html-special-string-regexps)
5339 (defun org-compute-latex-and-specials-regexp ()
5340 "Compute regular expression for stuff treated specially by exporters."
5341 (if (not org-highlight-latex-fragments-and-specials)
5342 (org-set-local 'org-latex-and-specials-regexp nil)
5343 (let*
5344 ((matchers (plist-get org-format-latex-options :matchers))
5345 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5346 org-latex-regexps)))
5347 (options (org-combine-plists (org-default-export-plist)
5348 (org-infile-export-plist)))
5349 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5350 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5351 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5352 (org-export-html-expand (plist-get options :expand-quoted-html))
5353 (org-export-with-special-strings (plist-get options :special-strings))
5354 (re-sub
5355 (cond
5356 ((equal org-export-with-sub-superscripts '{})
5357 (list org-match-substring-with-braces-regexp))
5358 (org-export-with-sub-superscripts
5359 (list org-match-substring-regexp))
5360 (t nil)))
5361 (re-latex
5362 (if org-export-with-LaTeX-fragments
5363 (mapcar (lambda (x) (nth 1 x)) latexs)))
5364 (re-macros
5365 (if org-export-with-TeX-macros
5366 (list (concat "\\\\"
5367 (regexp-opt
5368 (append (mapcar 'car org-html-entities)
5369 (if (boundp 'org-latex-entities)
5370 org-latex-entities nil))
5371 'words))) ; FIXME
5373 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5374 (re-special (if org-export-with-special-strings
5375 (mapcar (lambda (x) (car x))
5376 org-export-html-special-string-regexps)))
5377 (re-rest
5378 (delq nil
5379 (list
5380 (if org-export-html-expand "@<[^>\n]+>")
5381 ))))
5382 (org-set-local
5383 'org-latex-and-specials-regexp
5384 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5385 re-rest) "\\|")))))
5387 (defface org-latex-and-export-specials
5388 (let ((font (cond ((assq :inherit custom-face-attributes)
5389 '(:inherit underline))
5390 (t '(:underline t)))))
5391 `((((class grayscale) (background light))
5392 (:foreground "DimGray" ,@font))
5393 (((class grayscale) (background dark))
5394 (:foreground "LightGray" ,@font))
5395 (((class color) (background light))
5396 (:foreground "SaddleBrown"))
5397 (((class color) (background dark))
5398 (:foreground "burlywood"))
5399 (t (,@font))))
5400 "Face used to highlight math latex and other special exporter stuff."
5401 :group 'org-faces)
5403 (defun org-do-latex-and-special-faces (limit)
5404 "Run through the buffer and add overlays to links."
5405 (when org-latex-and-specials-regexp
5406 (let (rtn d)
5407 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5408 limit t))
5409 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5410 'face))
5411 '(org-code org-verbatim underline)))
5412 (progn
5413 (setq rtn t
5414 d (cond ((member (char-after (1+ (match-beginning 0)))
5415 '(?_ ?^)) 1)
5416 (t 0)))
5417 (font-lock-prepend-text-property
5418 (+ d (match-beginning 0)) (match-end 0)
5419 'face 'org-latex-and-export-specials)
5420 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5421 '(font-lock-multiline t)))))
5422 rtn)))
5424 (defun org-restart-font-lock ()
5425 "Restart font-lock-mode, to force refontification."
5426 (when (and (boundp 'font-lock-mode) font-lock-mode)
5427 (font-lock-mode -1)
5428 (font-lock-mode 1)))
5430 (defun org-all-targets (&optional radio)
5431 "Return a list of all targets in this file.
5432 With optional argument RADIO, only find radio targets."
5433 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5434 rtn)
5435 (save-excursion
5436 (goto-char (point-min))
5437 (while (re-search-forward re nil t)
5438 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5439 rtn)))
5441 (defun org-make-target-link-regexp (targets)
5442 "Make regular expression matching all strings in TARGETS.
5443 The regular expression finds the targets also if there is a line break
5444 between words."
5445 (and targets
5446 (concat
5447 "\\<\\("
5448 (mapconcat
5449 (lambda (x)
5450 (while (string-match " +" x)
5451 (setq x (replace-match "\\s-+" t t x)))
5453 targets
5454 "\\|")
5455 "\\)\\>")))
5457 (defun org-activate-tags (limit)
5458 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5459 (progn
5460 (add-text-properties (match-beginning 1) (match-end 1)
5461 (list 'mouse-face 'highlight
5462 'rear-nonsticky org-nonsticky-props
5463 'keymap org-mouse-map))
5464 t)))
5466 (defun org-outline-level ()
5467 (save-excursion
5468 (looking-at outline-regexp)
5469 (if (match-beginning 1)
5470 (+ (org-get-string-indentation (match-string 1)) 1000)
5471 (1- (- (match-end 0) (match-beginning 0))))))
5473 (defvar org-font-lock-keywords nil)
5475 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5476 "Regular expression matching a property line.")
5478 (defun org-set-font-lock-defaults ()
5479 (let* ((em org-fontify-emphasized-text)
5480 (lk org-activate-links)
5481 (org-font-lock-extra-keywords
5482 (list
5483 ;; Headlines
5484 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5485 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5486 ;; Table lines
5487 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5488 (1 'org-table t))
5489 ;; Table internals
5490 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5491 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5492 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5493 ;; Drawers
5494 (list org-drawer-regexp '(0 'org-special-keyword t))
5495 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5496 ;; Properties
5497 (list org-property-re
5498 '(1 'org-special-keyword t)
5499 '(3 'org-property-value t))
5500 (if org-format-transports-properties-p
5501 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5502 ;; Links
5503 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5504 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5505 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5506 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5507 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5508 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5509 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5510 '(org-hide-wide-columns (0 nil append))
5511 ;; TODO lines
5512 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5513 '(1 (org-get-todo-face 1) t))
5514 ;; DONE
5515 (if org-fontify-done-headline
5516 (list (concat "^[*]+ +\\<\\("
5517 (mapconcat 'regexp-quote org-done-keywords "\\|")
5518 "\\)\\(.*\\)")
5519 '(2 'org-headline-done t))
5520 nil)
5521 ;; Priorities
5522 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5523 ;; Special keywords
5524 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5525 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5526 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5527 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5528 ;; Emphasis
5529 (if em
5530 (if (featurep 'xemacs)
5531 '(org-do-emphasis-faces (0 nil append))
5532 '(org-do-emphasis-faces)))
5533 ;; Checkboxes
5534 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5535 2 'bold prepend)
5536 (if org-provide-checkbox-statistics
5537 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5538 (0 (org-get-checkbox-statistics-face) t)))
5539 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5540 '(1 'org-archived prepend))
5541 ;; Specials
5542 '(org-do-latex-and-special-faces)
5543 ;; Code
5544 '(org-activate-code (1 'org-code t))
5545 ;; COMMENT
5546 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5547 "\\|" org-quote-string "\\)\\>")
5548 '(1 'org-special-keyword t))
5549 '("^#.*" (0 'font-lock-comment-face t))
5551 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5552 ;; Now set the full font-lock-keywords
5553 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5554 (org-set-local 'font-lock-defaults
5555 '(org-font-lock-keywords t nil nil backward-paragraph))
5556 (kill-local-variable 'font-lock-keywords) nil))
5558 (defvar org-m nil)
5559 (defvar org-l nil)
5560 (defvar org-f nil)
5561 (defun org-get-level-face (n)
5562 "Get the right face for match N in font-lock matching of healdines."
5563 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5564 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5565 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5566 (cond
5567 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5568 ((eq n 2) org-f)
5569 (t (if org-level-color-stars-only nil org-f))))
5571 (defun org-get-todo-face (kwd)
5572 "Get the right face for a TODO keyword KWD.
5573 If KWD is a number, get the corresponding match group."
5574 (if (numberp kwd) (setq kwd (match-string kwd)))
5575 (or (cdr (assoc kwd org-todo-keyword-faces))
5576 (and (member kwd org-done-keywords) 'org-done)
5577 'org-todo))
5579 (defun org-unfontify-region (beg end &optional maybe_loudly)
5580 "Remove fontification and activation overlays from links."
5581 (font-lock-default-unfontify-region beg end)
5582 (let* ((buffer-undo-list t)
5583 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5584 (inhibit-modification-hooks t)
5585 deactivate-mark buffer-file-name buffer-file-truename)
5586 (remove-text-properties beg end
5587 '(mouse-face t keymap t org-linked-text t
5588 invisible t intangible t))))
5590 ;;;; Visibility cycling, including org-goto and indirect buffer
5592 ;;; Cycling
5594 (defvar org-cycle-global-status nil)
5595 (make-variable-buffer-local 'org-cycle-global-status)
5596 (defvar org-cycle-subtree-status nil)
5597 (make-variable-buffer-local 'org-cycle-subtree-status)
5599 ;;;###autoload
5600 (defun org-cycle (&optional arg)
5601 "Visibility cycling for Org-mode.
5603 - When this function is called with a prefix argument, rotate the entire
5604 buffer through 3 states (global cycling)
5605 1. OVERVIEW: Show only top-level headlines.
5606 2. CONTENTS: Show all headlines of all levels, but no body text.
5607 3. SHOW ALL: Show everything.
5609 - When point is at the beginning of a headline, rotate the subtree started
5610 by this line through 3 different states (local cycling)
5611 1. FOLDED: Only the main headline is shown.
5612 2. CHILDREN: The main headline and the direct children are shown.
5613 From this state, you can move to one of the children
5614 and zoom in further.
5615 3. SUBTREE: Show the entire subtree, including body text.
5617 - When there is a numeric prefix, go up to a heading with level ARG, do
5618 a `show-subtree' and return to the previous cursor position. If ARG
5619 is negative, go up that many levels.
5621 - When point is not at the beginning of a headline, execute
5622 `indent-relative', like TAB normally does. See the option
5623 `org-cycle-emulate-tab' for details.
5625 - Special case: if point is at the beginning of the buffer and there is
5626 no headline in line 1, this function will act as if called with prefix arg.
5627 But only if also the variable `org-cycle-global-at-bob' is t."
5628 (interactive "P")
5629 (let* ((outline-regexp
5630 (if (and (org-mode-p) org-cycle-include-plain-lists)
5631 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5632 outline-regexp))
5633 (bob-special (and org-cycle-global-at-bob (bobp)
5634 (not (looking-at outline-regexp))))
5635 (org-cycle-hook
5636 (if bob-special
5637 (delq 'org-optimize-window-after-visibility-change
5638 (copy-sequence org-cycle-hook))
5639 org-cycle-hook))
5640 (pos (point)))
5642 (if (or bob-special (equal arg '(4)))
5643 ;; special case: use global cycling
5644 (setq arg t))
5646 (cond
5648 ((org-at-table-p 'any)
5649 ;; Enter the table or move to the next field in the table
5650 (or (org-table-recognize-table.el)
5651 (progn
5652 (if arg (org-table-edit-field t)
5653 (org-table-justify-field-maybe)
5654 (call-interactively 'org-table-next-field)))))
5656 ((eq arg t) ;; Global cycling
5658 (cond
5659 ((and (eq last-command this-command)
5660 (eq org-cycle-global-status 'overview))
5661 ;; We just created the overview - now do table of contents
5662 ;; This can be slow in very large buffers, so indicate action
5663 (message "CONTENTS...")
5664 (org-content)
5665 (message "CONTENTS...done")
5666 (setq org-cycle-global-status 'contents)
5667 (run-hook-with-args 'org-cycle-hook 'contents))
5669 ((and (eq last-command this-command)
5670 (eq org-cycle-global-status 'contents))
5671 ;; We just showed the table of contents - now show everything
5672 (show-all)
5673 (message "SHOW ALL")
5674 (setq org-cycle-global-status 'all)
5675 (run-hook-with-args 'org-cycle-hook 'all))
5678 ;; Default action: go to overview
5679 (org-overview)
5680 (message "OVERVIEW")
5681 (setq org-cycle-global-status 'overview)
5682 (run-hook-with-args 'org-cycle-hook 'overview))))
5684 ((and org-drawers org-drawer-regexp
5685 (save-excursion
5686 (beginning-of-line 1)
5687 (looking-at org-drawer-regexp)))
5688 ;; Toggle block visibility
5689 (org-flag-drawer
5690 (not (get-char-property (match-end 0) 'invisible))))
5692 ((integerp arg)
5693 ;; Show-subtree, ARG levels up from here.
5694 (save-excursion
5695 (org-back-to-heading)
5696 (outline-up-heading (if (< arg 0) (- arg)
5697 (- (funcall outline-level) arg)))
5698 (org-show-subtree)))
5700 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5701 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5702 ;; At a heading: rotate between three different views
5703 (org-back-to-heading)
5704 (let ((goal-column 0) eoh eol eos)
5705 ;; First, some boundaries
5706 (save-excursion
5707 (org-back-to-heading)
5708 (save-excursion
5709 (beginning-of-line 2)
5710 (while (and (not (eobp)) ;; this is like `next-line'
5711 (get-char-property (1- (point)) 'invisible))
5712 (beginning-of-line 2)) (setq eol (point)))
5713 (outline-end-of-heading) (setq eoh (point))
5714 (org-end-of-subtree t)
5715 (unless (eobp)
5716 (skip-chars-forward " \t\n")
5717 (beginning-of-line 1) ; in case this is an item
5719 (setq eos (1- (point))))
5720 ;; Find out what to do next and set `this-command'
5721 (cond
5722 ((= eos eoh)
5723 ;; Nothing is hidden behind this heading
5724 (message "EMPTY ENTRY")
5725 (setq org-cycle-subtree-status nil)
5726 (save-excursion
5727 (goto-char eos)
5728 (outline-next-heading)
5729 (if (org-invisible-p) (org-flag-heading nil))))
5730 ((or (>= eol eos)
5731 (not (string-match "\\S-" (buffer-substring eol eos))))
5732 ;; Entire subtree is hidden in one line: open it
5733 (org-show-entry)
5734 (show-children)
5735 (message "CHILDREN")
5736 (save-excursion
5737 (goto-char eos)
5738 (outline-next-heading)
5739 (if (org-invisible-p) (org-flag-heading nil)))
5740 (setq org-cycle-subtree-status 'children)
5741 (run-hook-with-args 'org-cycle-hook 'children))
5742 ((and (eq last-command this-command)
5743 (eq org-cycle-subtree-status 'children))
5744 ;; We just showed the children, now show everything.
5745 (org-show-subtree)
5746 (message "SUBTREE")
5747 (setq org-cycle-subtree-status 'subtree)
5748 (run-hook-with-args 'org-cycle-hook 'subtree))
5750 ;; Default action: hide the subtree.
5751 (hide-subtree)
5752 (message "FOLDED")
5753 (setq org-cycle-subtree-status 'folded)
5754 (run-hook-with-args 'org-cycle-hook 'folded)))))
5756 ;; TAB emulation
5757 (buffer-read-only (org-back-to-heading))
5759 ((org-try-cdlatex-tab))
5761 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5762 (or (not (bolp))
5763 (not (looking-at outline-regexp))))
5764 (call-interactively (global-key-binding "\t")))
5766 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5767 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5768 (or (and (eq org-cycle-emulate-tab 'white)
5769 (= (match-end 0) (point-at-eol)))
5770 (and (eq org-cycle-emulate-tab 'whitestart)
5771 (>= (match-end 0) pos))))
5773 (eq org-cycle-emulate-tab t))
5774 ; (if (and (looking-at "[ \n\r\t]")
5775 ; (string-match "^[ \t]*$" (buffer-substring
5776 ; (point-at-bol) (point))))
5777 ; (progn
5778 ; (beginning-of-line 1)
5779 ; (and (looking-at "[ \t]+") (replace-match ""))))
5780 (call-interactively (global-key-binding "\t")))
5782 (t (save-excursion
5783 (org-back-to-heading)
5784 (org-cycle))))))
5786 ;;;###autoload
5787 (defun org-global-cycle (&optional arg)
5788 "Cycle the global visibility. For details see `org-cycle'."
5789 (interactive "P")
5790 (let ((org-cycle-include-plain-lists
5791 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5792 (if (integerp arg)
5793 (progn
5794 (show-all)
5795 (hide-sublevels arg)
5796 (setq org-cycle-global-status 'contents))
5797 (org-cycle '(4)))))
5799 (defun org-overview ()
5800 "Switch to overview mode, shoing only top-level headlines.
5801 Really, this shows all headlines with level equal or greater than the level
5802 of the first headline in the buffer. This is important, because if the
5803 first headline is not level one, then (hide-sublevels 1) gives confusing
5804 results."
5805 (interactive)
5806 (let ((level (save-excursion
5807 (goto-char (point-min))
5808 (if (re-search-forward (concat "^" outline-regexp) nil t)
5809 (progn
5810 (goto-char (match-beginning 0))
5811 (funcall outline-level))))))
5812 (and level (hide-sublevels level))))
5814 (defun org-content (&optional arg)
5815 "Show all headlines in the buffer, like a table of contents.
5816 With numerical argument N, show content up to level N."
5817 (interactive "P")
5818 (save-excursion
5819 ;; Visit all headings and show their offspring
5820 (and (integerp arg) (org-overview))
5821 (goto-char (point-max))
5822 (catch 'exit
5823 (while (and (progn (condition-case nil
5824 (outline-previous-visible-heading 1)
5825 (error (goto-char (point-min))))
5827 (looking-at outline-regexp))
5828 (if (integerp arg)
5829 (show-children (1- arg))
5830 (show-branches))
5831 (if (bobp) (throw 'exit nil))))))
5834 (defun org-optimize-window-after-visibility-change (state)
5835 "Adjust the window after a change in outline visibility.
5836 This function is the default value of the hook `org-cycle-hook'."
5837 (when (get-buffer-window (current-buffer))
5838 (cond
5839 ; ((eq state 'overview) (org-first-headline-recenter 1))
5840 ; ((eq state 'overview) (org-beginning-of-line))
5841 ((eq state 'content) nil)
5842 ((eq state 'all) nil)
5843 ((eq state 'folded) nil)
5844 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5845 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5847 (defun org-compact-display-after-subtree-move ()
5848 (let (beg end)
5849 (save-excursion
5850 (if (org-up-heading-safe)
5851 (progn
5852 (hide-subtree)
5853 (show-entry)
5854 (show-children)
5855 (org-cycle-show-empty-lines 'children)
5856 (org-cycle-hide-drawers 'children))
5857 (org-overview)))))
5859 (defun org-cycle-show-empty-lines (state)
5860 "Show empty lines above all visible headlines.
5861 The region to be covered depends on STATE when called through
5862 `org-cycle-hook'. Lisp program can use t for STATE to get the
5863 entire buffer covered. Note that an empty line is only shown if there
5864 are at least `org-cycle-separator-lines' empty lines before the headeline."
5865 (when (> org-cycle-separator-lines 0)
5866 (save-excursion
5867 (let* ((n org-cycle-separator-lines)
5868 (re (cond
5869 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5870 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5871 (t (let ((ns (number-to-string (- n 2))))
5872 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5873 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5874 beg end)
5875 (cond
5876 ((memq state '(overview contents t))
5877 (setq beg (point-min) end (point-max)))
5878 ((memq state '(children folded))
5879 (setq beg (point) end (progn (org-end-of-subtree t t)
5880 (beginning-of-line 2)
5881 (point)))))
5882 (when beg
5883 (goto-char beg)
5884 (while (re-search-forward re end t)
5885 (if (not (get-char-property (match-end 1) 'invisible))
5886 (outline-flag-region
5887 (match-beginning 1) (match-end 1) nil)))))))
5888 ;; Never hide empty lines at the end of the file.
5889 (save-excursion
5890 (goto-char (point-max))
5891 (outline-previous-heading)
5892 (outline-end-of-heading)
5893 (if (and (looking-at "[ \t\n]+")
5894 (= (match-end 0) (point-max)))
5895 (outline-flag-region (point) (match-end 0) nil))))
5897 (defun org-subtree-end-visible-p ()
5898 "Is the end of the current subtree visible?"
5899 (pos-visible-in-window-p
5900 (save-excursion (org-end-of-subtree t) (point))))
5902 (defun org-first-headline-recenter (&optional N)
5903 "Move cursor to the first headline and recenter the headline.
5904 Optional argument N means, put the headline into the Nth line of the window."
5905 (goto-char (point-min))
5906 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5907 (beginning-of-line)
5908 (recenter (prefix-numeric-value N))))
5910 ;;; Org-goto
5912 (defvar org-goto-window-configuration nil)
5913 (defvar org-goto-marker nil)
5914 (defvar org-goto-map
5915 (let ((map (make-sparse-keymap)))
5916 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5917 (while (setq cmd (pop cmds))
5918 (substitute-key-definition cmd cmd map global-map)))
5919 (suppress-keymap map)
5920 (org-defkey map "\C-m" 'org-goto-ret)
5921 (org-defkey map [(return)] 'org-goto-ret)
5922 (org-defkey map [(left)] 'org-goto-left)
5923 (org-defkey map [(right)] 'org-goto-right)
5924 (org-defkey map [(control ?g)] 'org-goto-quit)
5925 (org-defkey map "\C-i" 'org-cycle)
5926 (org-defkey map [(tab)] 'org-cycle)
5927 (org-defkey map [(down)] 'outline-next-visible-heading)
5928 (org-defkey map [(up)] 'outline-previous-visible-heading)
5929 (if org-goto-auto-isearch
5930 (if (fboundp 'define-key-after)
5931 (define-key-after map [t] 'org-goto-local-auto-isearch)
5932 nil)
5933 (org-defkey map "q" 'org-goto-quit)
5934 (org-defkey map "n" 'outline-next-visible-heading)
5935 (org-defkey map "p" 'outline-previous-visible-heading)
5936 (org-defkey map "f" 'outline-forward-same-level)
5937 (org-defkey map "b" 'outline-backward-same-level)
5938 (org-defkey map "u" 'outline-up-heading))
5939 (org-defkey map "/" 'org-occur)
5940 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5941 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5942 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5943 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5944 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5945 map))
5947 (defconst org-goto-help
5948 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5949 RET=jump to location [Q]uit and return to previous location
5950 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5952 (defvar org-goto-start-pos) ; dynamically scoped parameter
5954 (defun org-goto (&optional alternative-interface)
5955 "Look up a different location in the current file, keeping current visibility.
5957 When you want look-up or go to a different location in a document, the
5958 fastest way is often to fold the entire buffer and then dive into the tree.
5959 This method has the disadvantage, that the previous location will be folded,
5960 which may not be what you want.
5962 This command works around this by showing a copy of the current buffer
5963 in an indirect buffer, in overview mode. You can dive into the tree in
5964 that copy, use org-occur and incremental search to find a location.
5965 When pressing RET or `Q', the command returns to the original buffer in
5966 which the visibility is still unchanged. After RET is will also jump to
5967 the location selected in the indirect buffer and expose the
5968 the headline hierarchy above."
5969 (interactive "P")
5970 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
5971 (org-refile-use-outline-path t)
5972 (interface
5973 (if (not alternative-interface)
5974 org-goto-interface
5975 (if (eq org-goto-interface 'outline)
5976 'outline-path-completion
5977 'outline)))
5978 (org-goto-start-pos (point))
5979 (selected-point
5980 (if (eq interface 'outline)
5981 (car (org-get-location (current-buffer) org-goto-help))
5982 (nth 3 (org-refile-get-location "Goto: ")))))
5983 (if selected-point
5984 (progn
5985 (org-mark-ring-push org-goto-start-pos)
5986 (goto-char selected-point)
5987 (if (or (org-invisible-p) (org-invisible-p2))
5988 (org-show-context 'org-goto)))
5989 (message "Quit"))))
5991 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5992 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5993 (defvar org-goto-local-auto-isearch-map) ; defined below
5995 (defun org-get-location (buf help)
5996 "Let the user select a location in the Org-mode buffer BUF.
5997 This function uses a recursive edit. It returns the selected position
5998 or nil."
5999 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6000 (isearch-hide-immediately nil)
6001 (isearch-search-fun-function
6002 (lambda () 'org-goto-local-search-forward-headings))
6003 (org-goto-selected-point org-goto-exit-command))
6004 (save-excursion
6005 (save-window-excursion
6006 (delete-other-windows)
6007 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6008 (switch-to-buffer
6009 (condition-case nil
6010 (make-indirect-buffer (current-buffer) "*org-goto*")
6011 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6012 (with-output-to-temp-buffer "*Help*"
6013 (princ help))
6014 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6015 (setq buffer-read-only nil)
6016 (let ((org-startup-truncated t)
6017 (org-startup-folded nil)
6018 (org-startup-align-all-tables nil))
6019 (org-mode)
6020 (org-overview))
6021 (setq buffer-read-only t)
6022 (if (and (boundp 'org-goto-start-pos)
6023 (integer-or-marker-p org-goto-start-pos))
6024 (let ((org-show-hierarchy-above t)
6025 (org-show-siblings t)
6026 (org-show-following-heading t))
6027 (goto-char org-goto-start-pos)
6028 (and (org-invisible-p) (org-show-context)))
6029 (goto-char (point-min)))
6030 (org-beginning-of-line)
6031 (message "Select location and press RET")
6032 (use-local-map org-goto-map)
6033 (recursive-edit)
6035 (kill-buffer "*org-goto*")
6036 (cons org-goto-selected-point org-goto-exit-command)))
6038 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6039 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6040 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6041 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6043 (defun org-goto-local-search-forward-headings (string bound noerror)
6044 "Search and make sure that anu matches are in headlines."
6045 (catch 'return
6046 (while (search-forward string bound noerror)
6047 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6048 (and (member :headline context)
6049 (not (member :tags context))))
6050 (throw 'return (point))))))
6052 (defun org-goto-local-auto-isearch ()
6053 "Start isearch."
6054 (interactive)
6055 (goto-char (point-min))
6056 (let ((keys (this-command-keys)))
6057 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6058 (isearch-mode t)
6059 (isearch-process-search-char (string-to-char keys)))))
6061 (defun org-goto-ret (&optional arg)
6062 "Finish `org-goto' by going to the new location."
6063 (interactive "P")
6064 (setq org-goto-selected-point (point)
6065 org-goto-exit-command 'return)
6066 (throw 'exit nil))
6068 (defun org-goto-left ()
6069 "Finish `org-goto' by going to the new location."
6070 (interactive)
6071 (if (org-on-heading-p)
6072 (progn
6073 (beginning-of-line 1)
6074 (setq org-goto-selected-point (point)
6075 org-goto-exit-command 'left)
6076 (throw 'exit nil))
6077 (error "Not on a heading")))
6079 (defun org-goto-right ()
6080 "Finish `org-goto' by going to the new location."
6081 (interactive)
6082 (if (org-on-heading-p)
6083 (progn
6084 (setq org-goto-selected-point (point)
6085 org-goto-exit-command 'right)
6086 (throw 'exit nil))
6087 (error "Not on a heading")))
6089 (defun org-goto-quit ()
6090 "Finish `org-goto' without cursor motion."
6091 (interactive)
6092 (setq org-goto-selected-point nil)
6093 (setq org-goto-exit-command 'quit)
6094 (throw 'exit nil))
6096 ;;; Indirect buffer display of subtrees
6098 (defvar org-indirect-dedicated-frame nil
6099 "This is the frame being used for indirect tree display.")
6100 (defvar org-last-indirect-buffer nil)
6102 (defun org-tree-to-indirect-buffer (&optional arg)
6103 "Create indirect buffer and narrow it to current subtree.
6104 With numerical prefix ARG, go up to this level and then take that tree.
6105 If ARG is negative, go up that many levels.
6106 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6107 indirect buffer previously made with this command, to avoid proliferation of
6108 indirect buffers. However, when you call the command with a `C-u' prefix, or
6109 when `org-indirect-buffer-display' is `new-frame', the last buffer
6110 is kept so that you can work with several indirect buffers at the same time.
6111 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6112 requests that a new frame be made for the new buffer, so that the dedicated
6113 frame is not changed."
6114 (interactive "P")
6115 (let ((cbuf (current-buffer))
6116 (cwin (selected-window))
6117 (pos (point))
6118 beg end level heading ibuf)
6119 (save-excursion
6120 (org-back-to-heading t)
6121 (when (numberp arg)
6122 (setq level (org-outline-level))
6123 (if (< arg 0) (setq arg (+ level arg)))
6124 (while (> (setq level (org-outline-level)) arg)
6125 (outline-up-heading 1 t)))
6126 (setq beg (point)
6127 heading (org-get-heading))
6128 (org-end-of-subtree t) (setq end (point)))
6129 (if (and (buffer-live-p org-last-indirect-buffer)
6130 (not (eq org-indirect-buffer-display 'new-frame))
6131 (not arg))
6132 (kill-buffer org-last-indirect-buffer))
6133 (setq ibuf (org-get-indirect-buffer cbuf)
6134 org-last-indirect-buffer ibuf)
6135 (cond
6136 ((or (eq org-indirect-buffer-display 'new-frame)
6137 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6138 (select-frame (make-frame))
6139 (delete-other-windows)
6140 (switch-to-buffer ibuf)
6141 (org-set-frame-title heading))
6142 ((eq org-indirect-buffer-display 'dedicated-frame)
6143 (raise-frame
6144 (select-frame (or (and org-indirect-dedicated-frame
6145 (frame-live-p org-indirect-dedicated-frame)
6146 org-indirect-dedicated-frame)
6147 (setq org-indirect-dedicated-frame (make-frame)))))
6148 (delete-other-windows)
6149 (switch-to-buffer ibuf)
6150 (org-set-frame-title (concat "Indirect: " heading)))
6151 ((eq org-indirect-buffer-display 'current-window)
6152 (switch-to-buffer ibuf))
6153 ((eq org-indirect-buffer-display 'other-window)
6154 (pop-to-buffer ibuf))
6155 (t (error "Invalid value.")))
6156 (if (featurep 'xemacs)
6157 (save-excursion (org-mode) (turn-on-font-lock)))
6158 (narrow-to-region beg end)
6159 (show-all)
6160 (goto-char pos)
6161 (and (window-live-p cwin) (select-window cwin))))
6163 (defun org-get-indirect-buffer (&optional buffer)
6164 (setq buffer (or buffer (current-buffer)))
6165 (let ((n 1) (base (buffer-name buffer)) bname)
6166 (while (buffer-live-p
6167 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6168 (setq n (1+ n)))
6169 (condition-case nil
6170 (make-indirect-buffer buffer bname 'clone)
6171 (error (make-indirect-buffer buffer bname)))))
6173 (defun org-set-frame-title (title)
6174 "Set the title of the current frame to the string TITLE."
6175 ;; FIXME: how to name a single frame in XEmacs???
6176 (unless (featurep 'xemacs)
6177 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6179 ;;;; Structure editing
6181 ;;; Inserting headlines
6183 (defun org-insert-heading (&optional force-heading)
6184 "Insert a new heading or item with same depth at point.
6185 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6186 If point is at the beginning of a headline, insert a sibling before the
6187 current headline. If point is not at the beginning, do not split the line,
6188 but create the new hedline after the current line."
6189 (interactive "P")
6190 (if (= (buffer-size) 0)
6191 (insert "\n* ")
6192 (when (or force-heading (not (org-insert-item)))
6193 (let* ((head (save-excursion
6194 (condition-case nil
6195 (progn
6196 (org-back-to-heading)
6197 (match-string 0))
6198 (error "*"))))
6199 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6200 pos)
6201 (cond
6202 ((and (org-on-heading-p) (bolp)
6203 (or (bobp)
6204 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6205 ;; insert before the current line
6206 (open-line (if blank 2 1)))
6207 ((and (bolp)
6208 (or (bobp)
6209 (save-excursion
6210 (backward-char 1) (not (org-invisible-p)))))
6211 ;; insert right here
6212 nil)
6214 ;; in the middle of the line
6215 (org-show-entry)
6216 (end-of-line 1)
6217 (newline (if blank 2 1))))
6218 (insert head) (just-one-space)
6219 (setq pos (point))
6220 (end-of-line 1)
6221 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6222 (run-hooks 'org-insert-heading-hook)))))
6224 (defun org-insert-heading-after-current ()
6225 "Insert a new heading with same level as current, after current subtree."
6226 (interactive)
6227 (org-back-to-heading)
6228 (org-insert-heading)
6229 (org-move-subtree-down)
6230 (end-of-line 1))
6232 (defun org-insert-todo-heading (arg)
6233 "Insert a new heading with the same level and TODO state as current heading.
6234 If the heading has no TODO state, or if the state is DONE, use the first
6235 state (TODO by default). Also with prefix arg, force first state."
6236 (interactive "P")
6237 (when (not (org-insert-item 'checkbox))
6238 (org-insert-heading)
6239 (save-excursion
6240 (org-back-to-heading)
6241 (outline-previous-heading)
6242 (looking-at org-todo-line-regexp))
6243 (if (or arg
6244 (not (match-beginning 2))
6245 (member (match-string 2) org-done-keywords))
6246 (insert (car org-todo-keywords-1) " ")
6247 (insert (match-string 2) " "))))
6249 (defun org-insert-subheading (arg)
6250 "Insert a new subheading and demote it.
6251 Works for outline headings and for plain lists alike."
6252 (interactive "P")
6253 (org-insert-heading arg)
6254 (cond
6255 ((org-on-heading-p) (org-do-demote))
6256 ((org-at-item-p) (org-indent-item 1))))
6258 (defun org-insert-todo-subheading (arg)
6259 "Insert a new subheading with TODO keyword or checkbox and demote it.
6260 Works for outline headings and for plain lists alike."
6261 (interactive "P")
6262 (org-insert-todo-heading arg)
6263 (cond
6264 ((org-on-heading-p) (org-do-demote))
6265 ((org-at-item-p) (org-indent-item 1))))
6267 ;;; Promotion and Demotion
6269 (defun org-promote-subtree ()
6270 "Promote the entire subtree.
6271 See also `org-promote'."
6272 (interactive)
6273 (save-excursion
6274 (org-map-tree 'org-promote))
6275 (org-fix-position-after-promote))
6277 (defun org-demote-subtree ()
6278 "Demote the entire subtree. See `org-demote'.
6279 See also `org-promote'."
6280 (interactive)
6281 (save-excursion
6282 (org-map-tree 'org-demote))
6283 (org-fix-position-after-promote))
6286 (defun org-do-promote ()
6287 "Promote the current heading higher up the tree.
6288 If the region is active in `transient-mark-mode', promote all headings
6289 in the region."
6290 (interactive)
6291 (save-excursion
6292 (if (org-region-active-p)
6293 (org-map-region 'org-promote (region-beginning) (region-end))
6294 (org-promote)))
6295 (org-fix-position-after-promote))
6297 (defun org-do-demote ()
6298 "Demote the current heading lower down the tree.
6299 If the region is active in `transient-mark-mode', demote all headings
6300 in the region."
6301 (interactive)
6302 (save-excursion
6303 (if (org-region-active-p)
6304 (org-map-region 'org-demote (region-beginning) (region-end))
6305 (org-demote)))
6306 (org-fix-position-after-promote))
6308 (defun org-fix-position-after-promote ()
6309 "Make sure that after pro/demotion cursor position is right."
6310 (let ((pos (point)))
6311 (when (save-excursion
6312 (beginning-of-line 1)
6313 (looking-at org-todo-line-regexp)
6314 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6315 (cond ((eobp) (insert " "))
6316 ((eolp) (insert " "))
6317 ((equal (char-after) ?\ ) (forward-char 1))))))
6319 (defun org-reduced-level (l)
6320 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6322 (defun org-get-legal-level (level &optional change)
6323 "Rectify a level change under the influence of `org-odd-levels-only'
6324 LEVEL is a current level, CHANGE is by how much the level should be
6325 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6326 even level numbers will become the next higher odd number."
6327 (if org-odd-levels-only
6328 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6329 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6330 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6331 (max 1 (+ level change))))
6333 (defun org-promote ()
6334 "Promote the current heading higher up the tree.
6335 If the region is active in `transient-mark-mode', promote all headings
6336 in the region."
6337 (org-back-to-heading t)
6338 (let* ((level (save-match-data (funcall outline-level)))
6339 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6340 (diff (abs (- level (length up-head) -1))))
6341 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6342 (replace-match up-head nil t)
6343 ;; Fixup tag positioning
6344 (and org-auto-align-tags (org-set-tags nil t))
6345 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6347 (defun org-demote ()
6348 "Demote the current heading lower down the tree.
6349 If the region is active in `transient-mark-mode', demote all headings
6350 in the region."
6351 (org-back-to-heading t)
6352 (let* ((level (save-match-data (funcall outline-level)))
6353 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6354 (diff (abs (- level (length down-head) -1))))
6355 (replace-match down-head nil t)
6356 ;; Fixup tag positioning
6357 (and org-auto-align-tags (org-set-tags nil t))
6358 (if org-adapt-indentation (org-fixup-indentation diff))))
6360 (defun org-map-tree (fun)
6361 "Call FUN for every heading underneath the current one."
6362 (org-back-to-heading)
6363 (let ((level (funcall outline-level)))
6364 (save-excursion
6365 (funcall fun)
6366 (while (and (progn
6367 (outline-next-heading)
6368 (> (funcall outline-level) level))
6369 (not (eobp)))
6370 (funcall fun)))))
6372 (defun org-map-region (fun beg end)
6373 "Call FUN for every heading between BEG and END."
6374 (let ((org-ignore-region t))
6375 (save-excursion
6376 (setq end (copy-marker end))
6377 (goto-char beg)
6378 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6379 (< (point) end))
6380 (funcall fun))
6381 (while (and (progn
6382 (outline-next-heading)
6383 (< (point) end))
6384 (not (eobp)))
6385 (funcall fun)))))
6387 (defun org-fixup-indentation (diff)
6388 "Change the indentation in the current entry by DIFF
6389 However, if any line in the current entry has no indentation, or if it
6390 would end up with no indentation after the change, nothing at all is done."
6391 (save-excursion
6392 (let ((end (save-excursion (outline-next-heading)
6393 (point-marker)))
6394 (prohibit (if (> diff 0)
6395 "^\\S-"
6396 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6397 col)
6398 (unless (save-excursion (end-of-line 1)
6399 (re-search-forward prohibit end t))
6400 (while (and (< (point) end)
6401 (re-search-forward "^[ \t]+" end t))
6402 (goto-char (match-end 0))
6403 (setq col (current-column))
6404 (if (< diff 0) (replace-match ""))
6405 (indent-to (+ diff col))))
6406 (move-marker end nil))))
6408 (defun org-convert-to-odd-levels ()
6409 "Convert an org-mode file with all levels allowed to one with odd levels.
6410 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6411 level 5 etc."
6412 (interactive)
6413 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6414 (let ((org-odd-levels-only nil) n)
6415 (save-excursion
6416 (goto-char (point-min))
6417 (while (re-search-forward "^\\*\\*+ " nil t)
6418 (setq n (- (length (match-string 0)) 2))
6419 (while (>= (setq n (1- n)) 0)
6420 (org-demote))
6421 (end-of-line 1))))))
6424 (defun org-convert-to-oddeven-levels ()
6425 "Convert an org-mode file with only odd levels to one with odd and even levels.
6426 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6427 section with an even level, conversion would destroy the structure of the file. An error
6428 is signaled in this case."
6429 (interactive)
6430 (goto-char (point-min))
6431 ;; First check if there are no even levels
6432 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6433 (org-show-context t)
6434 (error "Not all levels are odd in this file. Conversion not possible."))
6435 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6436 (let ((org-odd-levels-only nil) n)
6437 (save-excursion
6438 (goto-char (point-min))
6439 (while (re-search-forward "^\\*\\*+ " nil t)
6440 (setq n (/ (1- (length (match-string 0))) 2))
6441 (while (>= (setq n (1- n)) 0)
6442 (org-promote))
6443 (end-of-line 1))))))
6445 (defun org-tr-level (n)
6446 "Make N odd if required."
6447 (if org-odd-levels-only (1+ (/ n 2)) n))
6449 ;;; Vertical tree motion, cutting and pasting of subtrees
6451 (defun org-move-subtree-up (&optional arg)
6452 "Move the current subtree up past ARG headlines of the same level."
6453 (interactive "p")
6454 (org-move-subtree-down (- (prefix-numeric-value arg))))
6456 (defun org-move-subtree-down (&optional arg)
6457 "Move the current subtree down past ARG headlines of the same level."
6458 (interactive "p")
6459 (setq arg (prefix-numeric-value arg))
6460 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6461 'outline-get-last-sibling))
6462 (ins-point (make-marker))
6463 (cnt (abs arg))
6464 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6465 ;; Select the tree
6466 (org-back-to-heading)
6467 (setq beg0 (point))
6468 (save-excursion
6469 (setq ne-beg (org-back-over-empty-lines))
6470 (setq beg (point)))
6471 (save-match-data
6472 (save-excursion (outline-end-of-heading)
6473 (setq folded (org-invisible-p)))
6474 (outline-end-of-subtree))
6475 (outline-next-heading)
6476 (setq ne-end (org-back-over-empty-lines))
6477 (setq end (point))
6478 (goto-char beg0)
6479 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6480 ;; include less whitespace
6481 (save-excursion
6482 (goto-char beg)
6483 (forward-line (- ne-beg ne-end))
6484 (setq beg (point))))
6485 ;; Find insertion point, with error handling
6486 (while (> cnt 0)
6487 (or (and (funcall movfunc) (looking-at outline-regexp))
6488 (progn (goto-char beg0)
6489 (error "Cannot move past superior level or buffer limit")))
6490 (setq cnt (1- cnt)))
6491 (if (> arg 0)
6492 ;; Moving forward - still need to move over subtree
6493 (progn (org-end-of-subtree t t)
6494 (save-excursion
6495 (org-back-over-empty-lines)
6496 (or (bolp) (newline)))))
6497 (setq ne-ins (org-back-over-empty-lines))
6498 (move-marker ins-point (point))
6499 (setq txt (buffer-substring beg end))
6500 (delete-region beg end)
6501 (outline-flag-region (1- beg) beg nil)
6502 (outline-flag-region (1- (point)) (point) nil)
6503 (insert txt)
6504 (or (bolp) (insert "\n"))
6505 (setq ins-end (point))
6506 (goto-char ins-point)
6507 (org-skip-whitespace)
6508 (when (and (< arg 0)
6509 (org-first-sibling-p)
6510 (> ne-ins ne-beg))
6511 ;; Move whitespace back to beginning
6512 (save-excursion
6513 (goto-char ins-end)
6514 (let ((kill-whole-line t))
6515 (kill-line (- ne-ins ne-beg)) (point)))
6516 (insert (make-string (- ne-ins ne-beg) ?\n)))
6517 (move-marker ins-point nil)
6518 (org-compact-display-after-subtree-move)
6519 (unless folded
6520 (org-show-entry)
6521 (show-children)
6522 (org-cycle-hide-drawers 'children))))
6524 (defvar org-subtree-clip ""
6525 "Clipboard for cut and paste of subtrees.
6526 This is actually only a copy of the kill, because we use the normal kill
6527 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6529 (defvar org-subtree-clip-folded nil
6530 "Was the last copied subtree folded?
6531 This is used to fold the tree back after pasting.")
6533 (defun org-cut-subtree (&optional n)
6534 "Cut the current subtree into the clipboard.
6535 With prefix arg N, cut this many sequential subtrees.
6536 This is a short-hand for marking the subtree and then cutting it."
6537 (interactive "p")
6538 (org-copy-subtree n 'cut))
6540 (defun org-copy-subtree (&optional n cut)
6541 "Cut the current subtree into the clipboard.
6542 With prefix arg N, cut this many sequential subtrees.
6543 This is a short-hand for marking the subtree and then copying it.
6544 If CUT is non-nil, actually cut the subtree."
6545 (interactive "p")
6546 (let (beg end folded (beg0 (point)))
6547 (if (interactive-p)
6548 (org-back-to-heading nil) ; take what looks like a subtree
6549 (org-back-to-heading t)) ; take what is really there
6550 (org-back-over-empty-lines)
6551 (setq beg (point))
6552 (skip-chars-forward " \t\r\n")
6553 (save-match-data
6554 (save-excursion (outline-end-of-heading)
6555 (setq folded (org-invisible-p)))
6556 (condition-case nil
6557 (outline-forward-same-level (1- n))
6558 (error nil))
6559 (org-end-of-subtree t t))
6560 (org-back-over-empty-lines)
6561 (setq end (point))
6562 (goto-char beg0)
6563 (when (> end beg)
6564 (setq org-subtree-clip-folded folded)
6565 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6566 (setq org-subtree-clip (current-kill 0))
6567 (message "%s: Subtree(s) with %d characters"
6568 (if cut "Cut" "Copied")
6569 (length org-subtree-clip)))))
6571 (defun org-paste-subtree (&optional level tree)
6572 "Paste the clipboard as a subtree, with modification of headline level.
6573 The entire subtree is promoted or demoted in order to match a new headline
6574 level. By default, the new level is derived from the visible headings
6575 before and after the insertion point, and taken to be the inferior headline
6576 level of the two. So if the previous visible heading is level 3 and the
6577 next is level 4 (or vice versa), level 4 will be used for insertion.
6578 This makes sure that the subtree remains an independent subtree and does
6579 not swallow low level entries.
6581 You can also force a different level, either by using a numeric prefix
6582 argument, or by inserting the heading marker by hand. For example, if the
6583 cursor is after \"*****\", then the tree will be shifted to level 5.
6585 If you want to insert the tree as is, just use \\[yank].
6587 If optional TREE is given, use this text instead of the kill ring."
6588 (interactive "P")
6589 (unless (org-kill-is-subtree-p tree)
6590 (error "%s"
6591 (substitute-command-keys
6592 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6593 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6594 (^re (concat "^\\(" outline-regexp "\\)"))
6595 (re (concat "\\(" outline-regexp "\\)"))
6596 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6598 (old-level (if (string-match ^re txt)
6599 (- (match-end 0) (match-beginning 0) 1)
6600 -1))
6601 (force-level (cond (level (prefix-numeric-value level))
6602 ((string-match
6603 ^re_ (buffer-substring (point-at-bol) (point)))
6604 (- (match-end 1) (match-beginning 1)))
6605 (t nil)))
6606 (previous-level (save-excursion
6607 (condition-case nil
6608 (progn
6609 (outline-previous-visible-heading 1)
6610 (if (looking-at re)
6611 (- (match-end 0) (match-beginning 0) 1)
6613 (error 1))))
6614 (next-level (save-excursion
6615 (condition-case nil
6616 (progn
6617 (or (looking-at outline-regexp)
6618 (outline-next-visible-heading 1))
6619 (if (looking-at re)
6620 (- (match-end 0) (match-beginning 0) 1)
6622 (error 1))))
6623 (new-level (or force-level (max previous-level next-level)))
6624 (shift (if (or (= old-level -1)
6625 (= new-level -1)
6626 (= old-level new-level))
6628 (- new-level old-level)))
6629 (delta (if (> shift 0) -1 1))
6630 (func (if (> shift 0) 'org-demote 'org-promote))
6631 (org-odd-levels-only nil)
6632 beg end)
6633 ;; Remove the forced level indicator
6634 (if force-level
6635 (delete-region (point-at-bol) (point)))
6636 ;; Paste
6637 (beginning-of-line 1)
6638 (org-back-over-empty-lines) ;; FIXME: correct fix????
6639 (setq beg (point))
6640 (insert-before-markers txt) ;; FIXME: correct fix????
6641 (unless (string-match "\n\\'" txt) (insert "\n"))
6642 (setq end (point))
6643 (goto-char beg)
6644 (skip-chars-forward " \t\n\r")
6645 (setq beg (point))
6646 ;; Shift if necessary
6647 (unless (= shift 0)
6648 (save-restriction
6649 (narrow-to-region beg end)
6650 (while (not (= shift 0))
6651 (org-map-region func (point-min) (point-max))
6652 (setq shift (+ delta shift)))
6653 (goto-char (point-min))))
6654 (when (interactive-p)
6655 (message "Clipboard pasted as level %d subtree" new-level))
6656 (if (and kill-ring
6657 (eq org-subtree-clip (current-kill 0))
6658 org-subtree-clip-folded)
6659 ;; The tree was folded before it was killed/copied
6660 (hide-subtree))))
6662 (defun org-kill-is-subtree-p (&optional txt)
6663 "Check if the current kill is an outline subtree, or a set of trees.
6664 Returns nil if kill does not start with a headline, or if the first
6665 headline level is not the largest headline level in the tree.
6666 So this will actually accept several entries of equal levels as well,
6667 which is OK for `org-paste-subtree'.
6668 If optional TXT is given, check this string instead of the current kill."
6669 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6670 (start-level (and kill
6671 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6672 org-outline-regexp "\\)")
6673 kill)
6674 (- (match-end 2) (match-beginning 2) 1)))
6675 (re (concat "^" org-outline-regexp))
6676 (start (1+ (match-beginning 2))))
6677 (if (not start-level)
6678 (progn
6679 nil) ;; does not even start with a heading
6680 (catch 'exit
6681 (while (setq start (string-match re kill (1+ start)))
6682 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6683 (throw 'exit nil)))
6684 t))))
6686 (defun org-narrow-to-subtree ()
6687 "Narrow buffer to the current subtree."
6688 (interactive)
6689 (save-excursion
6690 (save-match-data
6691 (narrow-to-region
6692 (progn (org-back-to-heading) (point))
6693 (progn (org-end-of-subtree t t) (point))))))
6696 ;;; Outline Sorting
6698 (defun org-sort (with-case)
6699 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6700 Optional argument WITH-CASE means sort case-sensitively."
6701 (interactive "P")
6702 (if (org-at-table-p)
6703 (org-call-with-arg 'org-table-sort-lines with-case)
6704 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6706 (defvar org-priority-regexp) ; defined later in the file
6708 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6709 "Sort entries on a certain level of an outline tree.
6710 If there is an active region, the entries in the region are sorted.
6711 Else, if the cursor is before the first entry, sort the top-level items.
6712 Else, the children of the entry at point are sorted.
6714 Sorting can be alphabetically, numerically, and by date/time as given by
6715 the first time stamp in the entry. The command prompts for the sorting
6716 type unless it has been given to the function through the SORTING-TYPE
6717 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6718 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6719 called with point at the beginning of the record. It must return either
6720 a string or a number that should serve as the sorting key for that record.
6722 Comparing entries ignores case by default. However, with an optional argument
6723 WITH-CASE, the sorting considers case as well."
6724 (interactive "P")
6725 (let ((case-func (if with-case 'identity 'downcase))
6726 start beg end stars re re2
6727 txt what tmp plain-list-p)
6728 ;; Find beginning and end of region to sort
6729 (cond
6730 ((org-region-active-p)
6731 ;; we will sort the region
6732 (setq end (region-end)
6733 what "region")
6734 (goto-char (region-beginning))
6735 (if (not (org-on-heading-p)) (outline-next-heading))
6736 (setq start (point)))
6737 ((org-at-item-p)
6738 ;; we will sort this plain list
6739 (org-beginning-of-item-list) (setq start (point))
6740 (org-end-of-item-list) (setq end (point))
6741 (goto-char start)
6742 (setq plain-list-p t
6743 what "plain list"))
6744 ((or (org-on-heading-p)
6745 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6746 ;; we will sort the children of the current headline
6747 (org-back-to-heading)
6748 (setq start (point)
6749 end (progn (org-end-of-subtree t t)
6750 (org-back-over-empty-lines)
6751 (point))
6752 what "children")
6753 (goto-char start)
6754 (show-subtree)
6755 (outline-next-heading))
6757 ;; we will sort the top-level entries in this file
6758 (goto-char (point-min))
6759 (or (org-on-heading-p) (outline-next-heading))
6760 (setq start (point) end (point-max) what "top-level")
6761 (goto-char start)
6762 (show-all)))
6764 (setq beg (point))
6765 (if (>= beg end) (error "Nothing to sort"))
6767 (unless plain-list-p
6768 (looking-at "\\(\\*+\\)")
6769 (setq stars (match-string 1)
6770 re (concat "^" (regexp-quote stars) " +")
6771 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6772 txt (buffer-substring beg end))
6773 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6774 (if (and (not (equal stars "*")) (string-match re2 txt))
6775 (error "Region to sort contains a level above the first entry")))
6777 (unless sorting-type
6778 (message
6779 (if plain-list-p
6780 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6781 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6782 what)
6783 (setq sorting-type (read-char-exclusive))
6785 (and (= (downcase sorting-type) ?f)
6786 (setq getkey-func
6787 (completing-read "Sort using function: "
6788 obarray 'fboundp t nil nil))
6789 (setq getkey-func (intern getkey-func)))
6791 (and (= (downcase sorting-type) ?r)
6792 (setq property
6793 (completing-read "Property: "
6794 (mapcar 'list (org-buffer-property-keys t))
6795 nil t))))
6797 (message "Sorting entries...")
6799 (save-restriction
6800 (narrow-to-region start end)
6802 (let ((dcst (downcase sorting-type))
6803 (now (current-time)))
6804 (sort-subr
6805 (/= dcst sorting-type)
6806 ;; This function moves to the beginning character of the "record" to
6807 ;; be sorted.
6808 (if plain-list-p
6809 (lambda nil
6810 (if (org-at-item-p) t (goto-char (point-max))))
6811 (lambda nil
6812 (if (re-search-forward re nil t)
6813 (goto-char (match-beginning 0))
6814 (goto-char (point-max)))))
6815 ;; This function moves to the last character of the "record" being
6816 ;; sorted.
6817 (if plain-list-p
6818 'org-end-of-item
6819 (lambda nil
6820 (save-match-data
6821 (condition-case nil
6822 (outline-forward-same-level 1)
6823 (error
6824 (goto-char (point-max)))))))
6826 ;; This function returns the value that gets sorted against.
6827 (if plain-list-p
6828 (lambda nil
6829 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6830 (cond
6831 ((= dcst ?n)
6832 (string-to-number (buffer-substring (match-end 0)
6833 (point-at-eol))))
6834 ((= dcst ?a)
6835 (buffer-substring (match-end 0) (point-at-eol)))
6836 ((= dcst ?t)
6837 (if (re-search-forward org-ts-regexp
6838 (point-at-eol) t)
6839 (org-time-string-to-time (match-string 0))
6840 now))
6841 ((= dcst ?f)
6842 (if getkey-func
6843 (progn
6844 (setq tmp (funcall getkey-func))
6845 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6846 tmp)
6847 (error "Invalid key function `%s'" getkey-func)))
6848 (t (error "Invalid sorting type `%c'" sorting-type)))))
6849 (lambda nil
6850 (cond
6851 ((= dcst ?n)
6852 (if (looking-at outline-regexp)
6853 (string-to-number (buffer-substring (match-end 0)
6854 (point-at-eol)))
6855 nil))
6856 ((= dcst ?a)
6857 (funcall case-func (buffer-substring (point-at-bol)
6858 (point-at-eol))))
6859 ((= dcst ?t)
6860 (if (re-search-forward org-ts-regexp
6861 (save-excursion
6862 (forward-line 2)
6863 (point)) t)
6864 (org-time-string-to-time (match-string 0))
6865 now))
6866 ((= dcst ?p)
6867 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6868 (string-to-char (match-string 2))
6869 org-default-priority))
6870 ((= dcst ?r)
6871 (or (org-entry-get nil property) ""))
6872 ((= dcst ?f)
6873 (if getkey-func
6874 (progn
6875 (setq tmp (funcall getkey-func))
6876 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6877 tmp)
6878 (error "Invalid key function `%s'" getkey-func)))
6879 (t (error "Invalid sorting type `%c'" sorting-type)))))
6881 (cond
6882 ((= dcst ?a) 'string<)
6883 ((= dcst ?t) 'time-less-p)
6884 (t nil)))))
6885 (message "Sorting entries...done")))
6887 (defun org-do-sort (table what &optional with-case sorting-type)
6888 "Sort TABLE of WHAT according to SORTING-TYPE.
6889 The user will be prompted for the SORTING-TYPE if the call to this
6890 function does not specify it. WHAT is only for the prompt, to indicate
6891 what is being sorted. The sorting key will be extracted from
6892 the car of the elements of the table.
6893 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6894 (unless sorting-type
6895 (message
6896 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6897 what)
6898 (setq sorting-type (read-char-exclusive)))
6899 (let ((dcst (downcase sorting-type))
6900 extractfun comparefun)
6901 ;; Define the appropriate functions
6902 (cond
6903 ((= dcst ?n)
6904 (setq extractfun 'string-to-number
6905 comparefun (if (= dcst sorting-type) '< '>)))
6906 ((= dcst ?a)
6907 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6908 (lambda(x) (downcase (org-sort-remove-invisible x))))
6909 comparefun (if (= dcst sorting-type)
6910 'string<
6911 (lambda (a b) (and (not (string< a b))
6912 (not (string= a b)))))))
6913 ((= dcst ?t)
6914 (setq extractfun
6915 (lambda (x)
6916 (if (string-match org-ts-regexp x)
6917 (time-to-seconds
6918 (org-time-string-to-time (match-string 0 x)))
6920 comparefun (if (= dcst sorting-type) '< '>)))
6921 (t (error "Invalid sorting type `%c'" sorting-type)))
6923 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6924 table)
6925 (lambda (a b) (funcall comparefun (car a) (car b))))))
6927 ;;;; Plain list items, including checkboxes
6929 ;;; Plain list items
6931 (defun org-at-item-p ()
6932 "Is point in a line starting a hand-formatted item?"
6933 (let ((llt org-plain-list-ordered-item-terminator))
6934 (save-excursion
6935 (goto-char (point-at-bol))
6936 (looking-at
6937 (cond
6938 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6939 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6940 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6941 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6943 (defun org-in-item-p ()
6944 "It the cursor inside a plain list item.
6945 Does not have to be the first line."
6946 (save-excursion
6947 (condition-case nil
6948 (progn
6949 (org-beginning-of-item)
6950 (org-at-item-p)
6952 (error nil))))
6954 (defun org-insert-item (&optional checkbox)
6955 "Insert a new item at the current level.
6956 Return t when things worked, nil when we are not in an item."
6957 (when (save-excursion
6958 (condition-case nil
6959 (progn
6960 (org-beginning-of-item)
6961 (org-at-item-p)
6962 (if (org-invisible-p) (error "Invisible item"))
6964 (error nil)))
6965 (let* ((bul (match-string 0))
6966 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6967 (match-end 0)))
6968 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6969 pos)
6970 (cond
6971 ((and (org-at-item-p) (<= (point) eow))
6972 ;; before the bullet
6973 (beginning-of-line 1)
6974 (open-line (if blank 2 1)))
6975 ((<= (point) eow)
6976 (beginning-of-line 1))
6977 (t (newline (if blank 2 1))))
6978 (insert bul (if checkbox "[ ]" ""))
6979 (just-one-space)
6980 (setq pos (point))
6981 (end-of-line 1)
6982 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6983 (org-maybe-renumber-ordered-list)
6984 (and checkbox (org-update-checkbox-count-maybe))
6987 ;;; Checkboxes
6989 (defun org-at-item-checkbox-p ()
6990 "Is point at a line starting a plain-list item with a checklet?"
6991 (and (org-at-item-p)
6992 (save-excursion
6993 (goto-char (match-end 0))
6994 (skip-chars-forward " \t")
6995 (looking-at "\\[[- X]\\]"))))
6997 (defun org-toggle-checkbox (&optional arg)
6998 "Toggle the checkbox in the current line."
6999 (interactive "P")
7000 (catch 'exit
7001 (let (beg end status (firstnew 'unknown))
7002 (cond
7003 ((org-region-active-p)
7004 (setq beg (region-beginning) end (region-end)))
7005 ((org-on-heading-p)
7006 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7007 ((org-at-item-checkbox-p)
7008 (let ((pos (point)))
7009 (replace-match
7010 (cond (arg "[-]")
7011 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7012 (t "[ ]"))
7013 t t)
7014 (goto-char pos))
7015 (throw 'exit t))
7016 (t (error "Not at a checkbox or heading, and no active region")))
7017 (save-excursion
7018 (goto-char beg)
7019 (while (< (point) end)
7020 (when (org-at-item-checkbox-p)
7021 (setq status (equal (match-string 0) "[X]"))
7022 (when (eq firstnew 'unknown)
7023 (setq firstnew (not status)))
7024 (replace-match
7025 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7026 (beginning-of-line 2)))))
7027 (org-update-checkbox-count-maybe))
7029 (defun org-update-checkbox-count-maybe ()
7030 "Update checkbox statistics unless turned off by user."
7031 (when org-provide-checkbox-statistics
7032 (org-update-checkbox-count)))
7034 (defun org-update-checkbox-count (&optional all)
7035 "Update the checkbox statistics in the current section.
7036 This will find all statistic cookies like [57%] and [6/12] and update them
7037 with the current numbers. With optional prefix argument ALL, do this for
7038 the whole buffer."
7039 (interactive "P")
7040 (save-excursion
7041 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7042 (beg (condition-case nil
7043 (progn (outline-back-to-heading) (point))
7044 (error (point-min))))
7045 (end (move-marker (make-marker)
7046 (progn (outline-next-heading) (point))))
7047 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7048 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7049 (re-find (concat re "\\|" re-box))
7050 beg-cookie end-cookie is-percent c-on c-off lim
7051 eline curr-ind next-ind continue-from startsearch
7052 (cstat 0)
7054 (when all
7055 (goto-char (point-min))
7056 (outline-next-heading)
7057 (setq beg (point) end (point-max)))
7058 (goto-char end)
7059 ;; find each statistic cookie
7060 (while (re-search-backward re-find beg t)
7061 (setq beg-cookie (match-beginning 1)
7062 end-cookie (match-end 1)
7063 cstat (+ cstat (if end-cookie 1 0))
7064 startsearch (point-at-eol)
7065 continue-from (point-at-bol)
7066 is-percent (match-beginning 2)
7067 lim (cond
7068 ((org-on-heading-p) (outline-next-heading) (point))
7069 ((org-at-item-p) (org-end-of-item) (point))
7070 (t nil))
7071 c-on 0
7072 c-off 0)
7073 (when lim
7074 ;; find first checkbox for this cookie and gather
7075 ;; statistics from all that are at this indentation level
7076 (goto-char startsearch)
7077 (if (re-search-forward re-box lim t)
7078 (progn
7079 (org-beginning-of-item)
7080 (setq curr-ind (org-get-indentation))
7081 (setq next-ind curr-ind)
7082 (while (= curr-ind next-ind)
7083 (save-excursion (end-of-line) (setq eline (point)))
7084 (if (re-search-forward re-box eline t)
7085 (if (member (match-string 2) '("[ ]" "[-]"))
7086 (setq c-off (1+ c-off))
7087 (setq c-on (1+ c-on))
7090 (org-end-of-item)
7091 (setq next-ind (org-get-indentation))
7093 (goto-char continue-from)
7094 ;; update cookie
7095 (when end-cookie
7096 (delete-region beg-cookie end-cookie)
7097 (goto-char beg-cookie)
7098 (insert
7099 (if is-percent
7100 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7101 (format "[%d/%d]" c-on (+ c-on c-off)))))
7102 ;; update items checkbox if it has one
7103 (when (org-at-item-p)
7104 (org-beginning-of-item)
7105 (when (and (> (+ c-on c-off) 0)
7106 (re-search-forward re-box (point-at-eol) t))
7107 (setq beg-cookie (match-beginning 2)
7108 end-cookie (match-end 2))
7109 (delete-region beg-cookie end-cookie)
7110 (goto-char beg-cookie)
7111 (cond ((= c-off 0) (insert "[X]"))
7112 ((= c-on 0) (insert "[ ]"))
7113 (t (insert "[-]")))
7115 (goto-char continue-from))
7116 (when (interactive-p)
7117 (message "Checkbox satistics updated %s (%d places)"
7118 (if all "in entire file" "in current outline entry") cstat)))))
7120 (defun org-get-checkbox-statistics-face ()
7121 "Select the face for checkbox statistics.
7122 The face will be `org-done' when all relevant boxes are checked. Otherwise
7123 it will be `org-todo'."
7124 (if (match-end 1)
7125 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7126 (if (and (> (match-end 2) (match-beginning 2))
7127 (equal (match-string 2) (match-string 3)))
7128 'org-done
7129 'org-todo)))
7131 (defun org-get-indentation (&optional line)
7132 "Get the indentation of the current line, interpreting tabs.
7133 When LINE is given, assume it represents a line and compute its indentation."
7134 (if line
7135 (if (string-match "^ *" (org-remove-tabs line))
7136 (match-end 0))
7137 (save-excursion
7138 (beginning-of-line 1)
7139 (skip-chars-forward " \t")
7140 (current-column))))
7142 (defun org-remove-tabs (s &optional width)
7143 "Replace tabulators in S with spaces.
7144 Assumes that s is a single line, starting in column 0."
7145 (setq width (or width tab-width))
7146 (while (string-match "\t" s)
7147 (setq s (replace-match
7148 (make-string
7149 (- (* width (/ (+ (match-beginning 0) width) width))
7150 (match-beginning 0)) ?\ )
7151 t t s)))
7154 (defun org-fix-indentation (line ind)
7155 "Fix indentation in LINE.
7156 IND is a cons cell with target and minimum indentation.
7157 If the current indenation in LINE is smaller than the minimum,
7158 leave it alone. If it is larger than ind, set it to the target."
7159 (let* ((l (org-remove-tabs line))
7160 (i (org-get-indentation l))
7161 (i1 (car ind)) (i2 (cdr ind)))
7162 (if (>= i i2) (setq l (substring line i2)))
7163 (if (> i1 0)
7164 (concat (make-string i1 ?\ ) l)
7165 l)))
7167 (defcustom org-empty-line-terminates-plain-lists nil
7168 "Non-nil means, an empty line ends all plain list levels.
7169 When nil, empty lines are part of the preceeding item."
7170 :group 'org-plain-lists
7171 :type 'boolean)
7173 (defun org-beginning-of-item ()
7174 "Go to the beginning of the current hand-formatted item.
7175 If the cursor is not in an item, throw an error."
7176 (interactive)
7177 (let ((pos (point))
7178 (limit (save-excursion
7179 (condition-case nil
7180 (progn
7181 (org-back-to-heading)
7182 (beginning-of-line 2) (point))
7183 (error (point-min)))))
7184 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7185 ind ind1)
7186 (if (org-at-item-p)
7187 (beginning-of-line 1)
7188 (beginning-of-line 1)
7189 (skip-chars-forward " \t")
7190 (setq ind (current-column))
7191 (if (catch 'exit
7192 (while t
7193 (beginning-of-line 0)
7194 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7196 (if (looking-at "[ \t]*$")
7197 (setq ind1 ind-empty)
7198 (skip-chars-forward " \t")
7199 (setq ind1 (current-column)))
7200 (if (< ind1 ind)
7201 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7203 (goto-char pos)
7204 (error "Not in an item")))))
7206 (defun org-end-of-item ()
7207 "Go to the end of the current hand-formatted item.
7208 If the cursor is not in an item, throw an error."
7209 (interactive)
7210 (let* ((pos (point))
7211 ind1
7212 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7213 (limit (save-excursion (outline-next-heading) (point)))
7214 (ind (save-excursion
7215 (org-beginning-of-item)
7216 (skip-chars-forward " \t")
7217 (current-column)))
7218 (end (catch 'exit
7219 (while t
7220 (beginning-of-line 2)
7221 (if (eobp) (throw 'exit (point)))
7222 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7223 (if (looking-at "[ \t]*$")
7224 (setq ind1 ind-empty)
7225 (skip-chars-forward " \t")
7226 (setq ind1 (current-column)))
7227 (if (<= ind1 ind)
7228 (throw 'exit (point-at-bol)))))))
7229 (if end
7230 (goto-char end)
7231 (goto-char pos)
7232 (error "Not in an item"))))
7234 (defun org-next-item ()
7235 "Move to the beginning of the next item in the current plain list.
7236 Error if not at a plain list, or if this is the last item in the list."
7237 (interactive)
7238 (let (ind ind1 (pos (point)))
7239 (org-beginning-of-item)
7240 (setq ind (org-get-indentation))
7241 (org-end-of-item)
7242 (setq ind1 (org-get-indentation))
7243 (unless (and (org-at-item-p) (= ind ind1))
7244 (goto-char pos)
7245 (error "On last item"))))
7247 (defun org-previous-item ()
7248 "Move to the beginning of the previous item in the current plain list.
7249 Error if not at a plain list, or if this is the first item in the list."
7250 (interactive)
7251 (let (beg ind ind1 (pos (point)))
7252 (org-beginning-of-item)
7253 (setq beg (point))
7254 (setq ind (org-get-indentation))
7255 (goto-char beg)
7256 (catch 'exit
7257 (while t
7258 (beginning-of-line 0)
7259 (if (looking-at "[ \t]*$")
7261 (if (<= (setq ind1 (org-get-indentation)) ind)
7262 (throw 'exit t)))))
7263 (condition-case nil
7264 (if (or (not (org-at-item-p))
7265 (< ind1 (1- ind)))
7266 (error "")
7267 (org-beginning-of-item))
7268 (error (goto-char pos)
7269 (error "On first item")))))
7271 (defun org-first-list-item-p ()
7272 "Is this heading the item in a plain list?"
7273 (unless (org-at-item-p)
7274 (error "Not at a plain list item"))
7275 (org-beginning-of-item)
7276 (= (point) (save-excursion (org-beginning-of-item-list))))
7278 (defun org-move-item-down ()
7279 "Move the plain list item at point down, i.e. swap with following item.
7280 Subitems (items with larger indentation) are considered part of the item,
7281 so this really moves item trees."
7282 (interactive)
7283 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7284 (org-beginning-of-item)
7285 (setq beg0 (point))
7286 (save-excursion
7287 (setq ne-beg (org-back-over-empty-lines))
7288 (setq beg (point)))
7289 (goto-char beg0)
7290 (setq ind (org-get-indentation))
7291 (org-end-of-item)
7292 (setq end0 (point))
7293 (setq ind1 (org-get-indentation))
7294 (setq ne-end (org-back-over-empty-lines))
7295 (setq end (point))
7296 (goto-char beg0)
7297 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7298 ;; include less whitespace
7299 (save-excursion
7300 (goto-char beg)
7301 (forward-line (- ne-beg ne-end))
7302 (setq beg (point))))
7303 (goto-char end0)
7304 (if (and (org-at-item-p) (= ind ind1))
7305 (progn
7306 (org-end-of-item)
7307 (org-back-over-empty-lines)
7308 (setq txt (buffer-substring beg end))
7309 (save-excursion
7310 (delete-region beg end))
7311 (setq pos (point))
7312 (insert txt)
7313 (goto-char pos) (org-skip-whitespace)
7314 (org-maybe-renumber-ordered-list))
7315 (goto-char pos)
7316 (error "Cannot move this item further down"))))
7318 (defun org-move-item-up (arg)
7319 "Move the plain list item at point up, i.e. swap with previous item.
7320 Subitems (items with larger indentation) are considered part of the item,
7321 so this really moves item trees."
7322 (interactive "p")
7323 (let (beg beg0 end ind ind1 (pos (point)) txt
7324 ne-beg ne-ins ins-end)
7325 (org-beginning-of-item)
7326 (setq beg0 (point))
7327 (setq ind (org-get-indentation))
7328 (save-excursion
7329 (setq ne-beg (org-back-over-empty-lines))
7330 (setq beg (point)))
7331 (goto-char beg0)
7332 (org-end-of-item)
7333 (setq end (point))
7334 (goto-char beg0)
7335 (catch 'exit
7336 (while t
7337 (beginning-of-line 0)
7338 (if (looking-at "[ \t]*$")
7339 (if org-empty-line-terminates-plain-lists
7340 (progn
7341 (goto-char pos)
7342 (error "Cannot move this item further up"))
7343 nil)
7344 (if (<= (setq ind1 (org-get-indentation)) ind)
7345 (throw 'exit t)))))
7346 (condition-case nil
7347 (org-beginning-of-item)
7348 (error (goto-char beg)
7349 (error "Cannot move this item further up")))
7350 (setq ind1 (org-get-indentation))
7351 (if (and (org-at-item-p) (= ind ind1))
7352 (progn
7353 (setq ne-ins (org-back-over-empty-lines))
7354 (setq txt (buffer-substring beg end))
7355 (save-excursion
7356 (delete-region beg end))
7357 (setq pos (point))
7358 (insert txt)
7359 (setq ins-end (point))
7360 (goto-char pos) (org-skip-whitespace)
7362 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7363 ;; Move whitespace back to beginning
7364 (save-excursion
7365 (goto-char ins-end)
7366 (let ((kill-whole-line t))
7367 (kill-line (- ne-ins ne-beg)) (point)))
7368 (insert (make-string (- ne-ins ne-beg) ?\n)))
7370 (org-maybe-renumber-ordered-list))
7371 (goto-char pos)
7372 (error "Cannot move this item further up"))))
7374 (defun org-maybe-renumber-ordered-list ()
7375 "Renumber the ordered list at point if setup allows it.
7376 This tests the user option `org-auto-renumber-ordered-lists' before
7377 doing the renumbering."
7378 (interactive)
7379 (when (and org-auto-renumber-ordered-lists
7380 (org-at-item-p))
7381 (if (match-beginning 3)
7382 (org-renumber-ordered-list 1)
7383 (org-fix-bullet-type))))
7385 (defun org-maybe-renumber-ordered-list-safe ()
7386 (condition-case nil
7387 (save-excursion
7388 (org-maybe-renumber-ordered-list))
7389 (error nil)))
7391 (defun org-cycle-list-bullet (&optional which)
7392 "Cycle through the different itemize/enumerate bullets.
7393 This cycle the entire list level through the sequence:
7395 `-' -> `+' -> `*' -> `1.' -> `1)'
7397 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7398 0 meand `-', 1 means `+' etc."
7399 (interactive "P")
7400 (org-preserve-lc
7401 (org-beginning-of-item-list)
7402 (org-at-item-p)
7403 (beginning-of-line 1)
7404 (let ((current (match-string 0))
7405 (prevp (eq which 'previous))
7406 new)
7407 (setq new (cond
7408 ((and (numberp which)
7409 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7410 ((string-match "-" current) (if prevp "1)" "+"))
7411 ((string-match "\\+" current)
7412 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7413 ((string-match "\\*" current) (if prevp "+" "1."))
7414 ((string-match "\\." current) (if prevp "*" "1)"))
7415 ((string-match ")" current) (if prevp "1." "-"))
7416 (t (error "This should not happen"))))
7417 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7418 (org-fix-bullet-type)
7419 (org-maybe-renumber-ordered-list))))
7421 (defun org-get-string-indentation (s)
7422 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7423 (let ((n -1) (i 0) (w tab-width) c)
7424 (catch 'exit
7425 (while (< (setq n (1+ n)) (length s))
7426 (setq c (aref s n))
7427 (cond ((= c ?\ ) (setq i (1+ i)))
7428 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7429 (t (throw 'exit t)))))
7432 (defun org-renumber-ordered-list (arg)
7433 "Renumber an ordered plain list.
7434 Cursor needs to be in the first line of an item, the line that starts
7435 with something like \"1.\" or \"2)\"."
7436 (interactive "p")
7437 (unless (and (org-at-item-p)
7438 (match-beginning 3))
7439 (error "This is not an ordered list"))
7440 (let ((line (org-current-line))
7441 (col (current-column))
7442 (ind (org-get-string-indentation
7443 (buffer-substring (point-at-bol) (match-beginning 3))))
7444 ;; (term (substring (match-string 3) -1))
7445 ind1 (n (1- arg))
7446 fmt)
7447 ;; find where this list begins
7448 (org-beginning-of-item-list)
7449 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7450 (setq fmt (concat "%d" (match-string 1)))
7451 (beginning-of-line 0)
7452 ;; walk forward and replace these numbers
7453 (catch 'exit
7454 (while t
7455 (catch 'next
7456 (beginning-of-line 2)
7457 (if (eobp) (throw 'exit nil))
7458 (if (looking-at "[ \t]*$") (throw 'next nil))
7459 (skip-chars-forward " \t") (setq ind1 (current-column))
7460 (if (> ind1 ind) (throw 'next t))
7461 (if (< ind1 ind) (throw 'exit t))
7462 (if (not (org-at-item-p)) (throw 'exit nil))
7463 (delete-region (match-beginning 2) (match-end 2))
7464 (goto-char (match-beginning 2))
7465 (insert (format fmt (setq n (1+ n)))))))
7466 (goto-line line)
7467 (move-to-column col)))
7469 (defun org-fix-bullet-type ()
7470 "Make sure all items in this list have the same bullet as the firsst item."
7471 (interactive)
7472 (unless (org-at-item-p) (error "This is not a list"))
7473 (let ((line (org-current-line))
7474 (col (current-column))
7475 (ind (current-indentation))
7476 ind1 bullet)
7477 ;; find where this list begins
7478 (org-beginning-of-item-list)
7479 (beginning-of-line 1)
7480 ;; find out what the bullet type is
7481 (looking-at "[ \t]*\\(\\S-+\\)")
7482 (setq bullet (match-string 1))
7483 ;; walk forward and replace these numbers
7484 (beginning-of-line 0)
7485 (catch 'exit
7486 (while t
7487 (catch 'next
7488 (beginning-of-line 2)
7489 (if (eobp) (throw 'exit nil))
7490 (if (looking-at "[ \t]*$") (throw 'next nil))
7491 (skip-chars-forward " \t") (setq ind1 (current-column))
7492 (if (> ind1 ind) (throw 'next t))
7493 (if (< ind1 ind) (throw 'exit t))
7494 (if (not (org-at-item-p)) (throw 'exit nil))
7495 (skip-chars-forward " \t")
7496 (looking-at "\\S-+")
7497 (replace-match bullet))))
7498 (goto-line line)
7499 (move-to-column col)
7500 (if (string-match "[0-9]" bullet)
7501 (org-renumber-ordered-list 1))))
7503 (defun org-beginning-of-item-list ()
7504 "Go to the beginning of the current item list.
7505 I.e. to the first item in this list."
7506 (interactive)
7507 (org-beginning-of-item)
7508 (let ((pos (point-at-bol))
7509 (ind (org-get-indentation))
7510 ind1)
7511 ;; find where this list begins
7512 (catch 'exit
7513 (while t
7514 (catch 'next
7515 (beginning-of-line 0)
7516 (if (looking-at "[ \t]*$")
7517 (throw (if (bobp) 'exit 'next) t))
7518 (skip-chars-forward " \t") (setq ind1 (current-column))
7519 (if (or (< ind1 ind)
7520 (and (= ind1 ind)
7521 (not (org-at-item-p)))
7522 (bobp))
7523 (throw 'exit t)
7524 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7525 (goto-char pos)))
7528 (defun org-end-of-item-list ()
7529 "Go to the end of the current item list.
7530 I.e. to the text after the last item."
7531 (interactive)
7532 (org-beginning-of-item)
7533 (let ((pos (point-at-bol))
7534 (ind (org-get-indentation))
7535 ind1)
7536 ;; find where this list begins
7537 (catch 'exit
7538 (while t
7539 (catch 'next
7540 (beginning-of-line 2)
7541 (if (looking-at "[ \t]*$")
7542 (throw (if (eobp) 'exit 'next) t))
7543 (skip-chars-forward " \t") (setq ind1 (current-column))
7544 (if (or (< ind1 ind)
7545 (and (= ind1 ind)
7546 (not (org-at-item-p)))
7547 (eobp))
7548 (progn
7549 (setq pos (point-at-bol))
7550 (throw 'exit t))))))
7551 (goto-char pos)))
7554 (defvar org-last-indent-begin-marker (make-marker))
7555 (defvar org-last-indent-end-marker (make-marker))
7557 (defun org-outdent-item (arg)
7558 "Outdent a local list item."
7559 (interactive "p")
7560 (org-indent-item (- arg)))
7562 (defun org-indent-item (arg)
7563 "Indent a local list item."
7564 (interactive "p")
7565 (unless (org-at-item-p)
7566 (error "Not on an item"))
7567 (save-excursion
7568 (let (beg end ind ind1 tmp delta ind-down ind-up)
7569 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7570 (setq beg org-last-indent-begin-marker
7571 end org-last-indent-end-marker)
7572 (org-beginning-of-item)
7573 (setq beg (move-marker org-last-indent-begin-marker (point)))
7574 (org-end-of-item)
7575 (setq end (move-marker org-last-indent-end-marker (point))))
7576 (goto-char beg)
7577 (setq tmp (org-item-indent-positions)
7578 ind (car tmp)
7579 ind-down (nth 2 tmp)
7580 ind-up (nth 1 tmp)
7581 delta (if (> arg 0)
7582 (if ind-down (- ind-down ind) 2)
7583 (if ind-up (- ind-up ind) -2)))
7584 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7585 (while (< (point) end)
7586 (beginning-of-line 1)
7587 (skip-chars-forward " \t") (setq ind1 (current-column))
7588 (delete-region (point-at-bol) (point))
7589 (or (eolp) (indent-to-column (+ ind1 delta)))
7590 (beginning-of-line 2))))
7591 (org-fix-bullet-type)
7592 (org-maybe-renumber-ordered-list-safe)
7593 (save-excursion
7594 (beginning-of-line 0)
7595 (condition-case nil (org-beginning-of-item) (error nil))
7596 (org-maybe-renumber-ordered-list-safe)))
7598 (defun org-item-indent-positions ()
7599 "Return indentation for plain list items.
7600 This returns a list with three values: The current indentation, the
7601 parent indentation and the indentation a child should habe.
7602 Assumes cursor in item line."
7603 (let* ((bolpos (point-at-bol))
7604 (ind (org-get-indentation))
7605 ind-down ind-up pos)
7606 (save-excursion
7607 (org-beginning-of-item-list)
7608 (skip-chars-backward "\n\r \t")
7609 (when (org-in-item-p)
7610 (org-beginning-of-item)
7611 (setq ind-up (org-get-indentation))))
7612 (setq pos (point))
7613 (save-excursion
7614 (cond
7615 ((and (condition-case nil (progn (org-previous-item) t)
7616 (error nil))
7617 (or (forward-char 1) t)
7618 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7619 (setq ind-down (org-get-indentation)))
7620 ((and (goto-char pos)
7621 (org-at-item-p))
7622 (goto-char (match-end 0))
7623 (skip-chars-forward " \t")
7624 (setq ind-down (current-column)))))
7625 (list ind ind-up ind-down)))
7627 ;;; The orgstruct minor mode
7629 ;; Define a minor mode which can be used in other modes in order to
7630 ;; integrate the org-mode structure editing commands.
7632 ;; This is really a hack, because the org-mode structure commands use
7633 ;; keys which normally belong to the major mode. Here is how it
7634 ;; works: The minor mode defines all the keys necessary to operate the
7635 ;; structure commands, but wraps the commands into a function which
7636 ;; tests if the cursor is currently at a headline or a plain list
7637 ;; item. If that is the case, the structure command is used,
7638 ;; temporarily setting many Org-mode variables like regular
7639 ;; expressions for filling etc. However, when any of those keys is
7640 ;; used at a different location, function uses `key-binding' to look
7641 ;; up if the key has an associated command in another currently active
7642 ;; keymap (minor modes, major mode, global), and executes that
7643 ;; command. There might be problems if any of the keys is otherwise
7644 ;; used as a prefix key.
7646 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7647 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7648 ;; addresses this by checking explicitly for both bindings.
7650 (defvar orgstruct-mode-map (make-sparse-keymap)
7651 "Keymap for the minor `orgstruct-mode'.")
7653 (defvar org-local-vars nil
7654 "List of local variables, for use by `orgstruct-mode'")
7656 ;;;###autoload
7657 (define-minor-mode orgstruct-mode
7658 "Toggle the minor more `orgstruct-mode'.
7659 This mode is for using Org-mode structure commands in other modes.
7660 The following key behave as if Org-mode was active, if the cursor
7661 is on a headline, or on a plain list item (both in the definition
7662 of Org-mode).
7664 M-up Move entry/item up
7665 M-down Move entry/item down
7666 M-left Promote
7667 M-right Demote
7668 M-S-up Move entry/item up
7669 M-S-down Move entry/item down
7670 M-S-left Promote subtree
7671 M-S-right Demote subtree
7672 M-q Fill paragraph and items like in Org-mode
7673 C-c ^ Sort entries
7674 C-c - Cycle list bullet
7675 TAB Cycle item visibility
7676 M-RET Insert new heading/item
7677 S-M-RET Insert new TODO heading / Chekbox item
7678 C-c C-c Set tags / toggle checkbox"
7679 nil " OrgStruct" nil
7680 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7682 ;;;###autoload
7683 (defun turn-on-orgstruct ()
7684 "Unconditionally turn on `orgstruct-mode'."
7685 (orgstruct-mode 1))
7687 ;;;###autoload
7688 (defun turn-on-orgstruct++ ()
7689 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7690 In addition to setting orgstruct-mode, this also exports all indentation and
7691 autofilling variables from org-mode into the buffer. Note that turning
7692 off orgstruct-mode will *not* remove these additional settings."
7693 (orgstruct-mode 1)
7694 (let (var val)
7695 (mapc
7696 (lambda (x)
7697 (when (string-match
7698 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7699 (symbol-name (car x)))
7700 (setq var (car x) val (nth 1 x))
7701 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7702 org-local-vars)))
7704 (defun orgstruct-error ()
7705 "Error when there is no default binding for a structure key."
7706 (interactive)
7707 (error "This key has no function outside structure elements"))
7709 (defun orgstruct-setup ()
7710 "Setup orgstruct keymaps."
7711 (let ((nfunc 0)
7712 (bindings
7713 (list
7714 '([(meta up)] org-metaup)
7715 '([(meta down)] org-metadown)
7716 '([(meta left)] org-metaleft)
7717 '([(meta right)] org-metaright)
7718 '([(meta shift up)] org-shiftmetaup)
7719 '([(meta shift down)] org-shiftmetadown)
7720 '([(meta shift left)] org-shiftmetaleft)
7721 '([(meta shift right)] org-shiftmetaright)
7722 '([(shift up)] org-shiftup)
7723 '([(shift down)] org-shiftdown)
7724 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7725 '("\M-q" fill-paragraph)
7726 '("\C-c^" org-sort)
7727 '("\C-c-" org-cycle-list-bullet)))
7728 elt key fun cmd)
7729 (while (setq elt (pop bindings))
7730 (setq nfunc (1+ nfunc))
7731 (setq key (org-key (car elt))
7732 fun (nth 1 elt)
7733 cmd (orgstruct-make-binding fun nfunc key))
7734 (org-defkey orgstruct-mode-map key cmd))
7736 ;; Special treatment needed for TAB and RET
7737 (org-defkey orgstruct-mode-map [(tab)]
7738 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7739 (org-defkey orgstruct-mode-map "\C-i"
7740 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7742 (org-defkey orgstruct-mode-map "\M-\C-m"
7743 (orgstruct-make-binding 'org-insert-heading 105
7744 "\M-\C-m" [(meta return)]))
7745 (org-defkey orgstruct-mode-map [(meta return)]
7746 (orgstruct-make-binding 'org-insert-heading 106
7747 [(meta return)] "\M-\C-m"))
7749 (org-defkey orgstruct-mode-map [(shift meta return)]
7750 (orgstruct-make-binding 'org-insert-todo-heading 107
7751 [(meta return)] "\M-\C-m"))
7753 (unless org-local-vars
7754 (setq org-local-vars (org-get-local-variables)))
7758 (defun orgstruct-make-binding (fun n &rest keys)
7759 "Create a function for binding in the structure minor mode.
7760 FUN is the command to call inside a table. N is used to create a unique
7761 command name. KEYS are keys that should be checked in for a command
7762 to execute outside of tables."
7763 (eval
7764 (list 'defun
7765 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7766 '(arg)
7767 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7768 "Outside of structure, run the binding of `"
7769 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7770 "'.")
7771 '(interactive "p")
7772 (list 'if
7773 '(org-context-p 'headline 'item)
7774 (list 'org-run-like-in-org-mode (list 'quote fun))
7775 (list 'let '(orgstruct-mode)
7776 (list 'call-interactively
7777 (append '(or)
7778 (mapcar (lambda (k)
7779 (list 'key-binding k))
7780 keys)
7781 '('orgstruct-error))))))))
7783 (defun org-context-p (&rest contexts)
7784 "Check if local context is and of CONTEXTS.
7785 Possible values in the list of contexts are `table', `headline', and `item'."
7786 (let ((pos (point)))
7787 (goto-char (point-at-bol))
7788 (prog1 (or (and (memq 'table contexts)
7789 (looking-at "[ \t]*|"))
7790 (and (memq 'headline contexts)
7791 (looking-at "\\*+"))
7792 (and (memq 'item contexts)
7793 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7794 (goto-char pos))))
7796 (defun org-get-local-variables ()
7797 "Return a list of all local variables in an org-mode buffer."
7798 (let (varlist)
7799 (with-current-buffer (get-buffer-create "*Org tmp*")
7800 (erase-buffer)
7801 (org-mode)
7802 (setq varlist (buffer-local-variables)))
7803 (kill-buffer "*Org tmp*")
7804 (delq nil
7805 (mapcar
7806 (lambda (x)
7807 (setq x
7808 (if (symbolp x)
7809 (list x)
7810 (list (car x) (list 'quote (cdr x)))))
7811 (if (string-match
7812 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7813 (symbol-name (car x)))
7814 x nil))
7815 varlist))))
7817 ;;;###autoload
7818 (defun org-run-like-in-org-mode (cmd)
7819 (unless org-local-vars
7820 (setq org-local-vars (org-get-local-variables)))
7821 (eval (list 'let org-local-vars
7822 (list 'call-interactively (list 'quote cmd)))))
7824 ;;;; Archiving
7826 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7828 (defun org-archive-subtree (&optional find-done)
7829 "Move the current subtree to the archive.
7830 The archive can be a certain top-level heading in the current file, or in
7831 a different file. The tree will be moved to that location, the subtree
7832 heading be marked DONE, and the current time will be added.
7834 When called with prefix argument FIND-DONE, find whole trees without any
7835 open TODO items and archive them (after getting confirmation from the user).
7836 If the cursor is not at a headline when this comand is called, try all level
7837 1 trees. If the cursor is on a headline, only try the direct children of
7838 this heading."
7839 (interactive "P")
7840 (if find-done
7841 (org-archive-all-done)
7842 ;; Save all relevant TODO keyword-relatex variables
7844 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7845 (tr-org-todo-keywords-1 org-todo-keywords-1)
7846 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7847 (tr-org-done-keywords org-done-keywords)
7848 (tr-org-todo-regexp org-todo-regexp)
7849 (tr-org-todo-line-regexp org-todo-line-regexp)
7850 (tr-org-odd-levels-only org-odd-levels-only)
7851 (this-buffer (current-buffer))
7852 (org-archive-location org-archive-location)
7853 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7854 ;; start of variables that will be used for saving context
7855 ;; The compiler complains about them - keep them anyway!
7856 (file (abbreviate-file-name (buffer-file-name)))
7857 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7858 (time (format-time-string
7859 (substring (cdr org-time-stamp-formats) 1 -1)
7860 (current-time)))
7861 afile heading buffer level newfile-p
7862 category todo priority
7863 ;; start of variables that will be used for savind context
7864 ltags itags prop)
7866 ;; Try to find a local archive location
7867 (save-excursion
7868 (save-restriction
7869 (widen)
7870 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7871 (if (and prop (string-match "\\S-" prop))
7872 (setq org-archive-location prop)
7873 (if (or (re-search-backward re nil t)
7874 (re-search-forward re nil t))
7875 (setq org-archive-location (match-string 1))))))
7877 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7878 (progn
7879 (setq afile (format (match-string 1 org-archive-location)
7880 (file-name-nondirectory buffer-file-name))
7881 heading (match-string 2 org-archive-location)))
7882 (error "Invalid `org-archive-location'"))
7883 (if (> (length afile) 0)
7884 (setq newfile-p (not (file-exists-p afile))
7885 buffer (find-file-noselect afile))
7886 (setq buffer (current-buffer)))
7887 (unless buffer
7888 (error "Cannot access file \"%s\"" afile))
7889 (if (and (> (length heading) 0)
7890 (string-match "^\\*+" heading))
7891 (setq level (match-end 0))
7892 (setq heading nil level 0))
7893 (save-excursion
7894 (org-back-to-heading t)
7895 ;; Get context information that will be lost by moving the tree
7896 (org-refresh-category-properties)
7897 (setq category (org-get-category)
7898 todo (and (looking-at org-todo-line-regexp)
7899 (match-string 2))
7900 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7901 ltags (org-get-tags)
7902 itags (org-delete-all ltags (org-get-tags-at)))
7903 (setq ltags (mapconcat 'identity ltags " ")
7904 itags (mapconcat 'identity itags " "))
7905 ;; We first only copy, in case something goes wrong
7906 ;; we need to protect this-command, to avoid kill-region sets it,
7907 ;; which would lead to duplication of subtrees
7908 (let (this-command) (org-copy-subtree))
7909 (set-buffer buffer)
7910 ;; Enforce org-mode for the archive buffer
7911 (if (not (org-mode-p))
7912 ;; Force the mode for future visits.
7913 (let ((org-insert-mode-line-in-empty-file t)
7914 (org-inhibit-startup t))
7915 (call-interactively 'org-mode)))
7916 (when newfile-p
7917 (goto-char (point-max))
7918 (insert (format "\nArchived entries from file %s\n\n"
7919 (buffer-file-name this-buffer))))
7920 ;; Force the TODO keywords of the original buffer
7921 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7922 (org-todo-keywords-1 tr-org-todo-keywords-1)
7923 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7924 (org-done-keywords tr-org-done-keywords)
7925 (org-todo-regexp tr-org-todo-regexp)
7926 (org-todo-line-regexp tr-org-todo-line-regexp)
7927 (org-odd-levels-only
7928 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7929 org-odd-levels-only
7930 tr-org-odd-levels-only)))
7931 (goto-char (point-min))
7932 (if heading
7933 (progn
7934 (if (re-search-forward
7935 (concat "^" (regexp-quote heading)
7936 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7937 nil t)
7938 (goto-char (match-end 0))
7939 ;; Heading not found, just insert it at the end
7940 (goto-char (point-max))
7941 (or (bolp) (insert "\n"))
7942 (insert "\n" heading "\n")
7943 (end-of-line 0))
7944 ;; Make the subtree visible
7945 (show-subtree)
7946 (org-end-of-subtree t)
7947 (skip-chars-backward " \t\r\n")
7948 (and (looking-at "[ \t\r\n]*")
7949 (replace-match "\n\n")))
7950 ;; No specific heading, just go to end of file.
7951 (goto-char (point-max)) (insert "\n"))
7952 ;; Paste
7953 (org-paste-subtree (org-get-legal-level level 1))
7955 ;; Mark the entry as done
7956 (when (and org-archive-mark-done
7957 (looking-at org-todo-line-regexp)
7958 (or (not (match-end 2))
7959 (not (member (match-string 2) org-done-keywords))))
7960 (let (org-log-done org-todo-log-states)
7961 (org-todo
7962 (car (or (member org-archive-mark-done org-done-keywords)
7963 org-done-keywords)))))
7965 ;; Add the context info
7966 (when org-archive-save-context-info
7967 (let ((l org-archive-save-context-info) e n v)
7968 (while (setq e (pop l))
7969 (when (and (setq v (symbol-value e))
7970 (stringp v) (string-match "\\S-" v))
7971 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7972 (org-entry-put (point) n v)))))
7974 ;; Save the buffer, if it is not the same buffer.
7975 (if (not (eq this-buffer buffer)) (save-buffer))))
7976 ;; Here we are back in the original buffer. Everything seems to have
7977 ;; worked. So now cut the tree and finish up.
7978 (let (this-command) (org-cut-subtree))
7979 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7980 (message "Subtree archived %s"
7981 (if (eq this-buffer buffer)
7982 (concat "under heading: " heading)
7983 (concat "in file: " (abbreviate-file-name afile)))))))
7985 (defun org-refresh-category-properties ()
7986 "Refresh category text properties in teh buffer."
7987 (let ((def-cat (cond
7988 ((null org-category)
7989 (if buffer-file-name
7990 (file-name-sans-extension
7991 (file-name-nondirectory buffer-file-name))
7992 "???"))
7993 ((symbolp org-category) (symbol-name org-category))
7994 (t org-category)))
7995 beg end cat pos optionp)
7996 (org-unmodified
7997 (save-excursion
7998 (save-restriction
7999 (widen)
8000 (goto-char (point-min))
8001 (put-text-property (point) (point-max) 'org-category def-cat)
8002 (while (re-search-forward
8003 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8004 (setq pos (match-end 0)
8005 optionp (equal (char-after (match-beginning 0)) ?#)
8006 cat (org-trim (match-string 2)))
8007 (if optionp
8008 (setq beg (point-at-bol) end (point-max))
8009 (org-back-to-heading t)
8010 (setq beg (point) end (org-end-of-subtree t t)))
8011 (put-text-property beg end 'org-category cat)
8012 (goto-char pos)))))))
8014 (defun org-archive-all-done (&optional tag)
8015 "Archive sublevels of the current tree without open TODO items.
8016 If the cursor is not on a headline, try all level 1 trees. If
8017 it is on a headline, try all direct children.
8018 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8019 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8020 (rea (concat ".*:" org-archive-tag ":"))
8021 (begm (make-marker))
8022 (endm (make-marker))
8023 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8024 "Move subtree to archive (no open TODO items)? "))
8025 beg end (cntarch 0))
8026 (if (org-on-heading-p)
8027 (progn
8028 (setq re1 (concat "^" (regexp-quote
8029 (make-string
8030 (1+ (- (match-end 0) (match-beginning 0) 1))
8031 ?*))
8032 " "))
8033 (move-marker begm (point))
8034 (move-marker endm (org-end-of-subtree t)))
8035 (setq re1 "^* ")
8036 (move-marker begm (point-min))
8037 (move-marker endm (point-max)))
8038 (save-excursion
8039 (goto-char begm)
8040 (while (re-search-forward re1 endm t)
8041 (setq beg (match-beginning 0)
8042 end (save-excursion (org-end-of-subtree t) (point)))
8043 (goto-char beg)
8044 (if (re-search-forward re end t)
8045 (goto-char end)
8046 (goto-char beg)
8047 (if (and (or (not tag) (not (looking-at rea)))
8048 (y-or-n-p question))
8049 (progn
8050 (if tag
8051 (org-toggle-tag org-archive-tag 'on)
8052 (org-archive-subtree))
8053 (setq cntarch (1+ cntarch)))
8054 (goto-char end)))))
8055 (message "%d trees archived" cntarch)))
8057 (defun org-cycle-hide-drawers (state)
8058 "Re-hide all drawers after a visibility state change."
8059 (when (and (org-mode-p)
8060 (not (memq state '(overview folded))))
8061 (save-excursion
8062 (let* ((globalp (memq state '(contents all)))
8063 (beg (if globalp (point-min) (point)))
8064 (end (if globalp (point-max) (org-end-of-subtree t))))
8065 (goto-char beg)
8066 (while (re-search-forward org-drawer-regexp end t)
8067 (org-flag-drawer t))))))
8069 (defun org-flag-drawer (flag)
8070 (save-excursion
8071 (beginning-of-line 1)
8072 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8073 (let ((b (match-end 0))
8074 (outline-regexp org-outline-regexp))
8075 (if (re-search-forward
8076 "^[ \t]*:END:"
8077 (save-excursion (outline-next-heading) (point)) t)
8078 (outline-flag-region b (point-at-eol) flag)
8079 (error ":END: line missing"))))))
8081 (defun org-cycle-hide-archived-subtrees (state)
8082 "Re-hide all archived subtrees after a visibility state change."
8083 (when (and (not org-cycle-open-archived-trees)
8084 (not (memq state '(overview folded))))
8085 (save-excursion
8086 (let* ((globalp (memq state '(contents all)))
8087 (beg (if globalp (point-min) (point)))
8088 (end (if globalp (point-max) (org-end-of-subtree t))))
8089 (org-hide-archived-subtrees beg end)
8090 (goto-char beg)
8091 (if (looking-at (concat ".*:" org-archive-tag ":"))
8092 (message "%s" (substitute-command-keys
8093 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8095 (defun org-force-cycle-archived ()
8096 "Cycle subtree even if it is archived."
8097 (interactive)
8098 (setq this-command 'org-cycle)
8099 (let ((org-cycle-open-archived-trees t))
8100 (call-interactively 'org-cycle)))
8102 (defun org-hide-archived-subtrees (beg end)
8103 "Re-hide all archived subtrees after a visibility state change."
8104 (save-excursion
8105 (let* ((re (concat ":" org-archive-tag ":")))
8106 (goto-char beg)
8107 (while (re-search-forward re end t)
8108 (and (org-on-heading-p) (hide-subtree))
8109 (org-end-of-subtree t)))))
8111 (defun org-toggle-tag (tag &optional onoff)
8112 "Toggle the tag TAG for the current line.
8113 If ONOFF is `on' or `off', don't toggle but set to this state."
8114 (unless (org-on-heading-p t) (error "Not on headling"))
8115 (let (res current)
8116 (save-excursion
8117 (beginning-of-line)
8118 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8119 (point-at-eol) t)
8120 (progn
8121 (setq current (match-string 1))
8122 (replace-match ""))
8123 (setq current ""))
8124 (setq current (nreverse (org-split-string current ":")))
8125 (cond
8126 ((eq onoff 'on)
8127 (setq res t)
8128 (or (member tag current) (push tag current)))
8129 ((eq onoff 'off)
8130 (or (not (member tag current)) (setq current (delete tag current))))
8131 (t (if (member tag current)
8132 (setq current (delete tag current))
8133 (setq res t)
8134 (push tag current))))
8135 (end-of-line 1)
8136 (if current
8137 (progn
8138 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8139 (org-set-tags nil t))
8140 (delete-horizontal-space))
8141 (run-hooks 'org-after-tags-change-hook))
8142 res))
8144 (defun org-toggle-archive-tag (&optional arg)
8145 "Toggle the archive tag for the current headline.
8146 With prefix ARG, check all children of current headline and offer tagging
8147 the children that do not contain any open TODO items."
8148 (interactive "P")
8149 (if arg
8150 (org-archive-all-done 'tag)
8151 (let (set)
8152 (save-excursion
8153 (org-back-to-heading t)
8154 (setq set (org-toggle-tag org-archive-tag))
8155 (when set (hide-subtree)))
8156 (and set (beginning-of-line 1))
8157 (message "Subtree %s" (if set "archived" "unarchived")))))
8160 ;;;; Tables
8162 ;;; The table editor
8164 ;; Watch out: Here we are talking about two different kind of tables.
8165 ;; Most of the code is for the tables created with the Org-mode table editor.
8166 ;; Sometimes, we talk about tables created and edited with the table.el
8167 ;; Emacs package. We call the former org-type tables, and the latter
8168 ;; table.el-type tables.
8170 (defun org-before-change-function (beg end)
8171 "Every change indicates that a table might need an update."
8172 (setq org-table-may-need-update t))
8174 (defconst org-table-line-regexp "^[ \t]*|"
8175 "Detects an org-type table line.")
8176 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8177 "Detects an org-type table line.")
8178 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8179 "Detects a table line marked for automatic recalculation.")
8180 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8181 "Detects a table line marked for automatic recalculation.")
8182 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8183 "Detects a table line marked for automatic recalculation.")
8184 (defconst org-table-hline-regexp "^[ \t]*|-"
8185 "Detects an org-type table hline.")
8186 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8187 "Detects a table-type table hline.")
8188 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8189 "Detects an org-type or table-type table.")
8190 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8191 "Searching from within a table (any type) this finds the first line
8192 outside the table.")
8193 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8194 "Searching from within a table (any type) this finds the first line
8195 outside the table.")
8197 (defvar org-table-last-highlighted-reference nil)
8198 (defvar org-table-formula-history nil)
8200 (defvar org-table-column-names nil
8201 "Alist with column names, derived from the `!' line.")
8202 (defvar org-table-column-name-regexp nil
8203 "Regular expression matching the current column names.")
8204 (defvar org-table-local-parameters nil
8205 "Alist with parameter names, derived from the `$' line.")
8206 (defvar org-table-named-field-locations nil
8207 "Alist with locations of named fields.")
8209 (defvar org-table-current-line-types nil
8210 "Table row types, non-nil only for the duration of a comand.")
8211 (defvar org-table-current-begin-line nil
8212 "Table begin line, non-nil only for the duration of a comand.")
8213 (defvar org-table-current-begin-pos nil
8214 "Table begin position, non-nil only for the duration of a comand.")
8215 (defvar org-table-dlines nil
8216 "Vector of data line line numbers in the current table.")
8217 (defvar org-table-hlines nil
8218 "Vector of hline line numbers in the current table.")
8220 (defconst org-table-range-regexp
8221 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8222 ;; 1 2 3 4 5
8223 "Regular expression for matching ranges in formulas.")
8225 (defconst org-table-range-regexp2
8226 (concat
8227 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8228 "\\.\\."
8229 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8230 "Match a range for reference display.")
8232 (defconst org-table-translate-regexp
8233 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8234 "Match a reference that needs translation, for reference display.")
8236 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8238 (defun org-table-create-with-table.el ()
8239 "Use the table.el package to insert a new table.
8240 If there is already a table at point, convert between Org-mode tables
8241 and table.el tables."
8242 (interactive)
8243 (require 'table)
8244 (cond
8245 ((org-at-table.el-p)
8246 (if (y-or-n-p "Convert table to Org-mode table? ")
8247 (org-table-convert)))
8248 ((org-at-table-p)
8249 (if (y-or-n-p "Convert table to table.el table? ")
8250 (org-table-convert)))
8251 (t (call-interactively 'table-insert))))
8253 (defun org-table-create-or-convert-from-region (arg)
8254 "Convert region to table, or create an empty table.
8255 If there is an active region, convert it to a table, using the function
8256 `org-table-convert-region'. See the documentation of that function
8257 to learn how the prefix argument is interpreted to determine the field
8258 separator.
8259 If there is no such region, create an empty table with `org-table-create'."
8260 (interactive "P")
8261 (if (org-region-active-p)
8262 (org-table-convert-region (region-beginning) (region-end) arg)
8263 (org-table-create arg)))
8265 (defun org-table-create (&optional size)
8266 "Query for a size and insert a table skeleton.
8267 SIZE is a string Columns x Rows like for example \"3x2\"."
8268 (interactive "P")
8269 (unless size
8270 (setq size (read-string
8271 (concat "Table size Columns x Rows [e.g. "
8272 org-table-default-size "]: ")
8273 "" nil org-table-default-size)))
8275 (let* ((pos (point))
8276 (indent (make-string (current-column) ?\ ))
8277 (split (org-split-string size " *x *"))
8278 (rows (string-to-number (nth 1 split)))
8279 (columns (string-to-number (car split)))
8280 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8281 "\n")))
8282 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8283 (point-at-bol) (point)))
8284 (beginning-of-line 1)
8285 (newline))
8286 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8287 (dotimes (i rows) (insert line))
8288 (goto-char pos)
8289 (if (> rows 1)
8290 ;; Insert a hline after the first row.
8291 (progn
8292 (end-of-line 1)
8293 (insert "\n|-")
8294 (goto-char pos)))
8295 (org-table-align)))
8297 (defun org-table-convert-region (beg0 end0 &optional separator)
8298 "Convert region to a table.
8299 The region goes from BEG0 to END0, but these borders will be moved
8300 slightly, to make sure a beginning of line in the first line is included.
8302 SEPARATOR specifies the field separator in the lines. It can have the
8303 following values:
8305 '(4) Use the comma as a field separator
8306 '(16) Use a TAB as field separator
8307 integer When a number, use that many spaces as field separator
8308 nil When nil, the command tries to be smart and figure out the
8309 separator in the following way:
8310 - when each line contains a TAB, assume TAB-separated material
8311 - when each line contains a comme, assume CSV material
8312 - else, assume one or more SPACE charcters as separator."
8313 (interactive "rP")
8314 (let* ((beg (min beg0 end0))
8315 (end (max beg0 end0))
8317 (goto-char beg)
8318 (beginning-of-line 1)
8319 (setq beg (move-marker (make-marker) (point)))
8320 (goto-char end)
8321 (if (bolp) (backward-char 1) (end-of-line 1))
8322 (setq end (move-marker (make-marker) (point)))
8323 ;; Get the right field separator
8324 (unless separator
8325 (goto-char beg)
8326 (setq separator
8327 (cond
8328 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8329 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8330 (t 1))))
8331 (setq re (cond
8332 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8333 ((equal separator '(16)) "^\\|\t")
8334 ((integerp separator)
8335 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8336 (t (error "This should not happen"))))
8337 (goto-char beg)
8338 (while (re-search-forward re end t)
8339 (replace-match "| " t t))
8340 (goto-char beg)
8341 (insert " ")
8342 (org-table-align)))
8344 (defun org-table-import (file arg)
8345 "Import FILE as a table.
8346 The file is assumed to be tab-separated. Such files can be produced by most
8347 spreadsheet and database applications. If no tabs (at least one per line)
8348 are found, lines will be split on whitespace into fields."
8349 (interactive "f\nP")
8350 (or (bolp) (newline))
8351 (let ((beg (point))
8352 (pm (point-max)))
8353 (insert-file-contents file)
8354 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8356 (defun org-table-export ()
8357 "Export table as a tab-separated file.
8358 Such a file can be imported into a spreadsheet program like Excel."
8359 (interactive)
8360 (let* ((beg (org-table-begin))
8361 (end (org-table-end))
8362 (table (buffer-substring beg end))
8363 (file (read-file-name "Export table to: "))
8364 buf)
8365 (unless (or (not (file-exists-p file))
8366 (y-or-n-p (format "Overwrite file %s? " file)))
8367 (error "Abort"))
8368 (with-current-buffer (find-file-noselect file)
8369 (setq buf (current-buffer))
8370 (erase-buffer)
8371 (fundamental-mode)
8372 (insert table)
8373 (goto-char (point-min))
8374 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8375 (replace-match "" t t)
8376 (end-of-line 1))
8377 (goto-char (point-min))
8378 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8379 (replace-match "" t t)
8380 (goto-char (min (1+ (point)) (point-max))))
8381 (goto-char (point-min))
8382 (while (re-search-forward "^-[-+]*$" nil t)
8383 (replace-match "")
8384 (if (looking-at "\n")
8385 (delete-char 1)))
8386 (goto-char (point-min))
8387 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8388 (replace-match "\t" t t))
8389 (save-buffer))
8390 (kill-buffer buf)))
8392 (defvar org-table-aligned-begin-marker (make-marker)
8393 "Marker at the beginning of the table last aligned.
8394 Used to check if cursor still is in that table, to minimize realignment.")
8395 (defvar org-table-aligned-end-marker (make-marker)
8396 "Marker at the end of the table last aligned.
8397 Used to check if cursor still is in that table, to minimize realignment.")
8398 (defvar org-table-last-alignment nil
8399 "List of flags for flushright alignment, from the last re-alignment.
8400 This is being used to correctly align a single field after TAB or RET.")
8401 (defvar org-table-last-column-widths nil
8402 "List of max width of fields in each column.
8403 This is being used to correctly align a single field after TAB or RET.")
8404 (defvar org-table-overlay-coordinates nil
8405 "Overlay coordinates after each align of a table.")
8406 (make-variable-buffer-local 'org-table-overlay-coordinates)
8408 (defvar org-last-recalc-line nil)
8409 (defconst org-narrow-column-arrow "=>"
8410 "Used as display property in narrowed table columns.")
8412 (defun org-table-align ()
8413 "Align the table at point by aligning all vertical bars."
8414 (interactive)
8415 (let* (
8416 ;; Limits of table
8417 (beg (org-table-begin))
8418 (end (org-table-end))
8419 ;; Current cursor position
8420 (linepos (org-current-line))
8421 (colpos (org-table-current-column))
8422 (winstart (window-start))
8423 (winstartline (org-current-line (min winstart (1- (point-max)))))
8424 lines (new "") lengths l typenums ty fields maxfields i
8425 column
8426 (indent "") cnt frac
8427 rfmt hfmt
8428 (spaces '(1 . 1))
8429 (sp1 (car spaces))
8430 (sp2 (cdr spaces))
8431 (rfmt1 (concat
8432 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8433 (hfmt1 (concat
8434 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8435 emptystrings links dates emph narrow fmax f1 len c e)
8436 (untabify beg end)
8437 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8438 ;; Check if we have links or dates
8439 (goto-char beg)
8440 (setq links (re-search-forward org-bracket-link-regexp end t))
8441 (goto-char beg)
8442 (setq emph (and org-hide-emphasis-markers
8443 (re-search-forward org-emph-re end t)))
8444 (goto-char beg)
8445 (setq dates (and org-display-custom-times
8446 (re-search-forward org-ts-regexp-both end t)))
8447 ;; Make sure the link properties are right
8448 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8449 ;; Make sure the date properties are right
8450 (when dates (goto-char beg) (while (org-activate-dates end)))
8451 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8453 ;; Check if we are narrowing any columns
8454 (goto-char beg)
8455 (setq narrow (and org-format-transports-properties-p
8456 (re-search-forward "<[0-9]+>" end t)))
8457 ;; Get the rows
8458 (setq lines (org-split-string
8459 (buffer-substring beg end) "\n"))
8460 ;; Store the indentation of the first line
8461 (if (string-match "^ *" (car lines))
8462 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8463 ;; Mark the hlines by setting the corresponding element to nil
8464 ;; At the same time, we remove trailing space.
8465 (setq lines (mapcar (lambda (l)
8466 (if (string-match "^ *|-" l)
8468 (if (string-match "[ \t]+$" l)
8469 (substring l 0 (match-beginning 0))
8470 l)))
8471 lines))
8472 ;; Get the data fields by splitting the lines.
8473 (setq fields (mapcar
8474 (lambda (l)
8475 (org-split-string l " *| *"))
8476 (delq nil (copy-sequence lines))))
8477 ;; How many fields in the longest line?
8478 (condition-case nil
8479 (setq maxfields (apply 'max (mapcar 'length fields)))
8480 (error
8481 (kill-region beg end)
8482 (org-table-create org-table-default-size)
8483 (error "Empty table - created default table")))
8484 ;; A list of empty strings to fill any short rows on output
8485 (setq emptystrings (make-list maxfields ""))
8486 ;; Check for special formatting.
8487 (setq i -1)
8488 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8489 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8490 ;; Check if there is an explicit width specified
8491 (when narrow
8492 (setq c column fmax nil)
8493 (while c
8494 (setq e (pop c))
8495 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8496 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8497 ;; Find fields that are wider than fmax, and shorten them
8498 (when fmax
8499 (loop for xx in column do
8500 (when (and (stringp xx)
8501 (> (org-string-width xx) fmax))
8502 (org-add-props xx nil
8503 'help-echo
8504 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8505 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8506 (unless (> f1 1)
8507 (error "Cannot narrow field starting with wide link \"%s\""
8508 (match-string 0 xx)))
8509 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8510 (add-text-properties (- f1 2) f1
8511 (list 'display org-narrow-column-arrow)
8512 xx)))))
8513 ;; Get the maximum width for each column
8514 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8515 ;; Get the fraction of numbers, to decide about alignment of the column
8516 (setq cnt 0 frac 0.0)
8517 (loop for x in column do
8518 (if (equal x "")
8520 (setq frac ( / (+ (* frac cnt)
8521 (if (string-match org-table-number-regexp x) 1 0))
8522 (setq cnt (1+ cnt))))))
8523 (push (>= frac org-table-number-fraction) typenums))
8524 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8526 ;; Store the alignment of this table, for later editing of single fields
8527 (setq org-table-last-alignment typenums
8528 org-table-last-column-widths lengths)
8530 ;; With invisible characters, `format' does not get the field width right
8531 ;; So we need to make these fields wide by hand.
8532 (when (or links emph)
8533 (loop for i from 0 upto (1- maxfields) do
8534 (setq len (nth i lengths))
8535 (loop for j from 0 upto (1- (length fields)) do
8536 (setq c (nthcdr i (car (nthcdr j fields))))
8537 (if (and (stringp (car c))
8538 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8539 ; (string-match org-bracket-link-regexp (car c))
8540 (< (org-string-width (car c)) len))
8541 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8543 ;; Compute the formats needed for output of the table
8544 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8545 (while (setq l (pop lengths))
8546 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8547 (setq rfmt (concat rfmt (format rfmt1 ty l))
8548 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8549 (setq rfmt (concat rfmt "\n")
8550 hfmt (concat (substring hfmt 0 -1) "|\n"))
8552 (setq new (mapconcat
8553 (lambda (l)
8554 (if l (apply 'format rfmt
8555 (append (pop fields) emptystrings))
8556 hfmt))
8557 lines ""))
8558 ;; Replace the old one
8559 (delete-region beg end)
8560 (move-marker end nil)
8561 (move-marker org-table-aligned-begin-marker (point))
8562 (insert new)
8563 (move-marker org-table-aligned-end-marker (point))
8564 (when (and orgtbl-mode (not (org-mode-p)))
8565 (goto-char org-table-aligned-begin-marker)
8566 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8567 ;; Try to move to the old location
8568 (goto-line winstartline)
8569 (setq winstart (point-at-bol))
8570 (goto-line linepos)
8571 (set-window-start (selected-window) winstart 'noforce)
8572 (org-table-goto-column colpos)
8573 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8574 (setq org-table-may-need-update nil)
8577 (defun org-string-width (s)
8578 "Compute width of string, ignoring invisible characters.
8579 This ignores character with invisibility property `org-link', and also
8580 characters with property `org-cwidth', because these will become invisible
8581 upon the next fontification round."
8582 (let (b l)
8583 (when (or (eq t buffer-invisibility-spec)
8584 (assq 'org-link buffer-invisibility-spec))
8585 (while (setq b (text-property-any 0 (length s)
8586 'invisible 'org-link s))
8587 (setq s (concat (substring s 0 b)
8588 (substring s (or (next-single-property-change
8589 b 'invisible s) (length s)))))))
8590 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8591 (setq s (concat (substring s 0 b)
8592 (substring s (or (next-single-property-change
8593 b 'org-cwidth s) (length s))))))
8594 (setq l (string-width s) b -1)
8595 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8596 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8599 (defun org-table-begin (&optional table-type)
8600 "Find the beginning of the table and return its position.
8601 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8602 (save-excursion
8603 (if (not (re-search-backward
8604 (if table-type org-table-any-border-regexp
8605 org-table-border-regexp)
8606 nil t))
8607 (progn (goto-char (point-min)) (point))
8608 (goto-char (match-beginning 0))
8609 (beginning-of-line 2)
8610 (point))))
8612 (defun org-table-end (&optional table-type)
8613 "Find the end of the table and return its position.
8614 With argument TABLE-TYPE, go to the end of a table.el-type table."
8615 (save-excursion
8616 (if (not (re-search-forward
8617 (if table-type org-table-any-border-regexp
8618 org-table-border-regexp)
8619 nil t))
8620 (goto-char (point-max))
8621 (goto-char (match-beginning 0)))
8622 (point-marker)))
8624 (defun org-table-justify-field-maybe (&optional new)
8625 "Justify the current field, text to left, number to right.
8626 Optional argument NEW may specify text to replace the current field content."
8627 (cond
8628 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8629 ((org-at-table-hline-p))
8630 ((and (not new)
8631 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8632 (current-buffer)))
8633 (< (point) org-table-aligned-begin-marker)
8634 (>= (point) org-table-aligned-end-marker)))
8635 ;; This is not the same table, force a full re-align
8636 (setq org-table-may-need-update t))
8637 (t ;; realign the current field, based on previous full realign
8638 (let* ((pos (point)) s
8639 (col (org-table-current-column))
8640 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8641 l f n o e)
8642 (when (> col 0)
8643 (skip-chars-backward "^|\n")
8644 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8645 (progn
8646 (setq s (match-string 1)
8647 o (match-string 0)
8648 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8649 e (not (= (match-beginning 2) (match-end 2))))
8650 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8651 l (if e "|" (setq org-table-may-need-update t) ""))
8652 n (format f s))
8653 (if new
8654 (if (<= (length new) l) ;; FIXME: length -> str-width?
8655 (setq n (format f new))
8656 (setq n (concat new "|") org-table-may-need-update t)))
8657 (or (equal n o)
8658 (let (org-table-may-need-update)
8659 (replace-match n t t))))
8660 (setq org-table-may-need-update t))
8661 (goto-char pos))))))
8663 (defun org-table-next-field ()
8664 "Go to the next field in the current table, creating new lines as needed.
8665 Before doing so, re-align the table if necessary."
8666 (interactive)
8667 (org-table-maybe-eval-formula)
8668 (org-table-maybe-recalculate-line)
8669 (if (and org-table-automatic-realign
8670 org-table-may-need-update)
8671 (org-table-align))
8672 (let ((end (org-table-end)))
8673 (if (org-at-table-hline-p)
8674 (end-of-line 1))
8675 (condition-case nil
8676 (progn
8677 (re-search-forward "|" end)
8678 (if (looking-at "[ \t]*$")
8679 (re-search-forward "|" end))
8680 (if (and (looking-at "-")
8681 org-table-tab-jumps-over-hlines
8682 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8683 (goto-char (match-beginning 1)))
8684 (if (looking-at "-")
8685 (progn
8686 (beginning-of-line 0)
8687 (org-table-insert-row 'below))
8688 (if (looking-at " ") (forward-char 1))))
8689 (error
8690 (org-table-insert-row 'below)))))
8692 (defun org-table-previous-field ()
8693 "Go to the previous field in the table.
8694 Before doing so, re-align the table if necessary."
8695 (interactive)
8696 (org-table-justify-field-maybe)
8697 (org-table-maybe-recalculate-line)
8698 (if (and org-table-automatic-realign
8699 org-table-may-need-update)
8700 (org-table-align))
8701 (if (org-at-table-hline-p)
8702 (end-of-line 1))
8703 (re-search-backward "|" (org-table-begin))
8704 (re-search-backward "|" (org-table-begin))
8705 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8706 (re-search-backward "|" (org-table-begin)))
8707 (if (looking-at "| ?")
8708 (goto-char (match-end 0))))
8710 (defun org-table-next-row ()
8711 "Go to the next row (same column) in the current table.
8712 Before doing so, re-align the table if necessary."
8713 (interactive)
8714 (org-table-maybe-eval-formula)
8715 (org-table-maybe-recalculate-line)
8716 (if (or (looking-at "[ \t]*$")
8717 (save-excursion (skip-chars-backward " \t") (bolp)))
8718 (newline)
8719 (if (and org-table-automatic-realign
8720 org-table-may-need-update)
8721 (org-table-align))
8722 (let ((col (org-table-current-column)))
8723 (beginning-of-line 2)
8724 (if (or (not (org-at-table-p))
8725 (org-at-table-hline-p))
8726 (progn
8727 (beginning-of-line 0)
8728 (org-table-insert-row 'below)))
8729 (org-table-goto-column col)
8730 (skip-chars-backward "^|\n\r")
8731 (if (looking-at " ") (forward-char 1)))))
8733 (defun org-table-copy-down (n)
8734 "Copy a field down in the current column.
8735 If the field at the cursor is empty, copy into it the content of the nearest
8736 non-empty field above. With argument N, use the Nth non-empty field.
8737 If the current field is not empty, it is copied down to the next row, and
8738 the cursor is moved with it. Therefore, repeating this command causes the
8739 column to be filled row-by-row.
8740 If the variable `org-table-copy-increment' is non-nil and the field is an
8741 integer or a timestamp, it will be incremented while copying. In the case of
8742 a timestamp, if the cursor is on the year, change the year. If it is on the
8743 month or the day, change that. Point will stay on the current date field
8744 in order to easily repeat the interval."
8745 (interactive "p")
8746 (let* ((colpos (org-table-current-column))
8747 (col (current-column))
8748 (field (org-table-get-field))
8749 (non-empty (string-match "[^ \t]" field))
8750 (beg (org-table-begin))
8751 txt)
8752 (org-table-check-inside-data-field)
8753 (if non-empty
8754 (progn
8755 (setq txt (org-trim field))
8756 (org-table-next-row)
8757 (org-table-blank-field))
8758 (save-excursion
8759 (setq txt
8760 (catch 'exit
8761 (while (progn (beginning-of-line 1)
8762 (re-search-backward org-table-dataline-regexp
8763 beg t))
8764 (org-table-goto-column colpos t)
8765 (if (and (looking-at
8766 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8767 (= (setq n (1- n)) 0))
8768 (throw 'exit (match-string 1))))))))
8769 (if txt
8770 (progn
8771 (if (and org-table-copy-increment
8772 (string-match "^[0-9]+$" txt))
8773 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8774 (insert txt)
8775 (move-to-column col)
8776 (if (and org-table-copy-increment (org-at-timestamp-p t))
8777 (org-timestamp-up 1)
8778 (org-table-maybe-recalculate-line))
8779 (org-table-align)
8780 (move-to-column col))
8781 (error "No non-empty field found"))))
8783 (defun org-table-check-inside-data-field ()
8784 "Is point inside a table data field?
8785 I.e. not on a hline or before the first or after the last column?
8786 This actually throws an error, so it aborts the current command."
8787 (if (or (not (org-at-table-p))
8788 (= (org-table-current-column) 0)
8789 (org-at-table-hline-p)
8790 (looking-at "[ \t]*$"))
8791 (error "Not in table data field")))
8793 (defvar org-table-clip nil
8794 "Clipboard for table regions.")
8796 (defun org-table-blank-field ()
8797 "Blank the current table field or active region."
8798 (interactive)
8799 (org-table-check-inside-data-field)
8800 (if (and (interactive-p) (org-region-active-p))
8801 (let (org-table-clip)
8802 (org-table-cut-region (region-beginning) (region-end)))
8803 (skip-chars-backward "^|")
8804 (backward-char 1)
8805 (if (looking-at "|[^|\n]+")
8806 (let* ((pos (match-beginning 0))
8807 (match (match-string 0))
8808 (len (org-string-width match)))
8809 (replace-match (concat "|" (make-string (1- len) ?\ )))
8810 (goto-char (+ 2 pos))
8811 (substring match 1)))))
8813 (defun org-table-get-field (&optional n replace)
8814 "Return the value of the field in column N of current row.
8815 N defaults to current field.
8816 If REPLACE is a string, replace field with this value. The return value
8817 is always the old value."
8818 (and n (org-table-goto-column n))
8819 (skip-chars-backward "^|\n")
8820 (backward-char 1)
8821 (if (looking-at "|[^|\r\n]*")
8822 (let* ((pos (match-beginning 0))
8823 (val (buffer-substring (1+ pos) (match-end 0))))
8824 (if replace
8825 (replace-match (concat "|" replace) t t))
8826 (goto-char (min (point-at-eol) (+ 2 pos)))
8827 val)
8828 (forward-char 1) ""))
8830 (defun org-table-field-info (arg)
8831 "Show info about the current field, and highlight any reference at point."
8832 (interactive "P")
8833 (org-table-get-specials)
8834 (save-excursion
8835 (let* ((pos (point))
8836 (col (org-table-current-column))
8837 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8838 (name (car (rassoc (list (org-current-line) col)
8839 org-table-named-field-locations)))
8840 (eql (org-table-get-stored-formulas))
8841 (dline (org-table-current-dline))
8842 (ref (format "@%d$%d" dline col))
8843 (ref1 (org-table-convert-refs-to-an ref))
8844 (fequation (or (assoc name eql) (assoc ref eql)))
8845 (cequation (assoc (int-to-string col) eql))
8846 (eqn (or fequation cequation)))
8847 (goto-char pos)
8848 (condition-case nil
8849 (org-table-show-reference 'local)
8850 (error nil))
8851 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8852 dline col
8853 (if cname (concat " or $" cname) "")
8854 dline col ref1
8855 (if name (concat " or $" name) "")
8856 ;; FIXME: formula info not correct if special table line
8857 (if eqn
8858 (concat ", formula: "
8859 (org-table-formula-to-user
8860 (concat
8861 (if (string-match "^[$@]"(car eqn)) "" "$")
8862 (car eqn) "=" (cdr eqn))))
8863 "")))))
8865 (defun org-table-current-column ()
8866 "Find out which column we are in.
8867 When called interactively, column is also displayed in echo area."
8868 (interactive)
8869 (if (interactive-p) (org-table-check-inside-data-field))
8870 (save-excursion
8871 (let ((cnt 0) (pos (point)))
8872 (beginning-of-line 1)
8873 (while (search-forward "|" pos t)
8874 (setq cnt (1+ cnt)))
8875 (if (interactive-p) (message "This is table column %d" cnt))
8876 cnt)))
8878 (defun org-table-current-dline ()
8879 "Find out what table data line we are in.
8880 Only datalins count for this."
8881 (interactive)
8882 (if (interactive-p) (org-table-check-inside-data-field))
8883 (save-excursion
8884 (let ((cnt 0) (pos (point)))
8885 (goto-char (org-table-begin))
8886 (while (<= (point) pos)
8887 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8888 (beginning-of-line 2))
8889 (if (interactive-p) (message "This is table line %d" cnt))
8890 cnt)))
8892 (defun org-table-goto-column (n &optional on-delim force)
8893 "Move the cursor to the Nth column in the current table line.
8894 With optional argument ON-DELIM, stop with point before the left delimiter
8895 of the field.
8896 If there are less than N fields, just go to after the last delimiter.
8897 However, when FORCE is non-nil, create new columns if necessary."
8898 (interactive "p")
8899 (let ((pos (point-at-eol)))
8900 (beginning-of-line 1)
8901 (when (> n 0)
8902 (while (and (> (setq n (1- n)) -1)
8903 (or (search-forward "|" pos t)
8904 (and force
8905 (progn (end-of-line 1)
8906 (skip-chars-backward "^|")
8907 (insert " | "))))))
8908 ; (backward-char 2) t)))))
8909 (when (and force (not (looking-at ".*|")))
8910 (save-excursion (end-of-line 1) (insert " | ")))
8911 (if on-delim
8912 (backward-char 1)
8913 (if (looking-at " ") (forward-char 1))))))
8915 (defun org-at-table-p (&optional table-type)
8916 "Return t if the cursor is inside an org-type table.
8917 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8918 (if org-enable-table-editor
8919 (save-excursion
8920 (beginning-of-line 1)
8921 (looking-at (if table-type org-table-any-line-regexp
8922 org-table-line-regexp)))
8923 nil))
8925 (defun org-at-table.el-p ()
8926 "Return t if and only if we are at a table.el table."
8927 (and (org-at-table-p 'any)
8928 (save-excursion
8929 (goto-char (org-table-begin 'any))
8930 (looking-at org-table1-hline-regexp))))
8932 (defun org-table-recognize-table.el ()
8933 "If there is a table.el table nearby, recognize it and move into it."
8934 (if org-table-tab-recognizes-table.el
8935 (if (org-at-table.el-p)
8936 (progn
8937 (beginning-of-line 1)
8938 (if (looking-at org-table-dataline-regexp)
8940 (if (looking-at org-table1-hline-regexp)
8941 (progn
8942 (beginning-of-line 2)
8943 (if (looking-at org-table-any-border-regexp)
8944 (beginning-of-line -1)))))
8945 (if (re-search-forward "|" (org-table-end t) t)
8946 (progn
8947 (require 'table)
8948 (if (table--at-cell-p (point))
8950 (message "recognizing table.el table...")
8951 (table-recognize-table)
8952 (message "recognizing table.el table...done")))
8953 (error "This should not happen..."))
8955 nil)
8956 nil))
8958 (defun org-at-table-hline-p ()
8959 "Return t if the cursor is inside a hline in a table."
8960 (if org-enable-table-editor
8961 (save-excursion
8962 (beginning-of-line 1)
8963 (looking-at org-table-hline-regexp))
8964 nil))
8966 (defun org-table-insert-column ()
8967 "Insert a new column into the table."
8968 (interactive)
8969 (if (not (org-at-table-p))
8970 (error "Not at a table"))
8971 (org-table-find-dataline)
8972 (let* ((col (max 1 (org-table-current-column)))
8973 (beg (org-table-begin))
8974 (end (org-table-end))
8975 ;; Current cursor position
8976 (linepos (org-current-line))
8977 (colpos col))
8978 (goto-char beg)
8979 (while (< (point) end)
8980 (if (org-at-table-hline-p)
8982 (org-table-goto-column col t)
8983 (insert "| "))
8984 (beginning-of-line 2))
8985 (move-marker end nil)
8986 (goto-line linepos)
8987 (org-table-goto-column colpos)
8988 (org-table-align)
8989 (org-table-fix-formulas "$" nil (1- col) 1)))
8991 (defun org-table-find-dataline ()
8992 "Find a dataline in the current table, which is needed for column commands."
8993 (if (and (org-at-table-p)
8994 (not (org-at-table-hline-p)))
8996 (let ((col (current-column))
8997 (end (org-table-end)))
8998 (move-to-column col)
8999 (while (and (< (point) end)
9000 (or (not (= (current-column) col))
9001 (org-at-table-hline-p)))
9002 (beginning-of-line 2)
9003 (move-to-column col))
9004 (if (and (org-at-table-p)
9005 (not (org-at-table-hline-p)))
9007 (error
9008 "Please position cursor in a data line for column operations")))))
9010 (defun org-table-delete-column ()
9011 "Delete a column from the table."
9012 (interactive)
9013 (if (not (org-at-table-p))
9014 (error "Not at a table"))
9015 (org-table-find-dataline)
9016 (org-table-check-inside-data-field)
9017 (let* ((col (org-table-current-column))
9018 (beg (org-table-begin))
9019 (end (org-table-end))
9020 ;; Current cursor position
9021 (linepos (org-current-line))
9022 (colpos col))
9023 (goto-char beg)
9024 (while (< (point) end)
9025 (if (org-at-table-hline-p)
9027 (org-table-goto-column col t)
9028 (and (looking-at "|[^|\n]+|")
9029 (replace-match "|")))
9030 (beginning-of-line 2))
9031 (move-marker end nil)
9032 (goto-line linepos)
9033 (org-table-goto-column colpos)
9034 (org-table-align)
9035 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9036 col -1 col)))
9038 (defun org-table-move-column-right ()
9039 "Move column to the right."
9040 (interactive)
9041 (org-table-move-column nil))
9042 (defun org-table-move-column-left ()
9043 "Move column to the left."
9044 (interactive)
9045 (org-table-move-column 'left))
9047 (defun org-table-move-column (&optional left)
9048 "Move the current column to the right. With arg LEFT, move to the left."
9049 (interactive "P")
9050 (if (not (org-at-table-p))
9051 (error "Not at a table"))
9052 (org-table-find-dataline)
9053 (org-table-check-inside-data-field)
9054 (let* ((col (org-table-current-column))
9055 (col1 (if left (1- col) col))
9056 (beg (org-table-begin))
9057 (end (org-table-end))
9058 ;; Current cursor position
9059 (linepos (org-current-line))
9060 (colpos (if left (1- col) (1+ col))))
9061 (if (and left (= col 1))
9062 (error "Cannot move column further left"))
9063 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9064 (error "Cannot move column further right"))
9065 (goto-char beg)
9066 (while (< (point) end)
9067 (if (org-at-table-hline-p)
9069 (org-table-goto-column col1 t)
9070 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9071 (replace-match "|\\2|\\1|")))
9072 (beginning-of-line 2))
9073 (move-marker end nil)
9074 (goto-line linepos)
9075 (org-table-goto-column colpos)
9076 (org-table-align)
9077 (org-table-fix-formulas
9078 "$" (list (cons (number-to-string col) (number-to-string colpos))
9079 (cons (number-to-string colpos) (number-to-string col))))))
9081 (defun org-table-move-row-down ()
9082 "Move table row down."
9083 (interactive)
9084 (org-table-move-row nil))
9085 (defun org-table-move-row-up ()
9086 "Move table row up."
9087 (interactive)
9088 (org-table-move-row 'up))
9090 (defun org-table-move-row (&optional up)
9091 "Move the current table line down. With arg UP, move it up."
9092 (interactive "P")
9093 (let* ((col (current-column))
9094 (pos (point))
9095 (hline1p (save-excursion (beginning-of-line 1)
9096 (looking-at org-table-hline-regexp)))
9097 (dline1 (org-table-current-dline))
9098 (dline2 (+ dline1 (if up -1 1)))
9099 (tonew (if up 0 2))
9100 txt hline2p)
9101 (beginning-of-line tonew)
9102 (unless (org-at-table-p)
9103 (goto-char pos)
9104 (error "Cannot move row further"))
9105 (setq hline2p (looking-at org-table-hline-regexp))
9106 (goto-char pos)
9107 (beginning-of-line 1)
9108 (setq pos (point))
9109 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9110 (delete-region (point) (1+ (point-at-eol)))
9111 (beginning-of-line tonew)
9112 (insert txt)
9113 (beginning-of-line 0)
9114 (move-to-column col)
9115 (unless (or hline1p hline2p)
9116 (org-table-fix-formulas
9117 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9118 (cons (number-to-string dline2) (number-to-string dline1)))))))
9120 (defun org-table-insert-row (&optional arg)
9121 "Insert a new row above the current line into the table.
9122 With prefix ARG, insert below the current line."
9123 (interactive "P")
9124 (if (not (org-at-table-p))
9125 (error "Not at a table"))
9126 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9127 (new (org-table-clean-line line)))
9128 ;; Fix the first field if necessary
9129 (if (string-match "^[ \t]*| *[#$] *|" line)
9130 (setq new (replace-match (match-string 0 line) t t new)))
9131 (beginning-of-line (if arg 2 1))
9132 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9133 (beginning-of-line 0)
9134 (re-search-forward "| ?" (point-at-eol) t)
9135 (and (or org-table-may-need-update org-table-overlay-coordinates)
9136 (org-table-align))
9137 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9139 (defun org-table-insert-hline (&optional above)
9140 "Insert a horizontal-line below the current line into the table.
9141 With prefix ABOVE, insert above the current line."
9142 (interactive "P")
9143 (if (not (org-at-table-p))
9144 (error "Not at a table"))
9145 (let ((line (org-table-clean-line
9146 (buffer-substring (point-at-bol) (point-at-eol))))
9147 (col (current-column)))
9148 (while (string-match "|\\( +\\)|" line)
9149 (setq line (replace-match
9150 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9151 ?-) "|") t t line)))
9152 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9153 (beginning-of-line (if above 1 2))
9154 (insert line "\n")
9155 (beginning-of-line (if above 1 -1))
9156 (move-to-column col)
9157 (and org-table-overlay-coordinates (org-table-align))))
9159 (defun org-table-hline-and-move (&optional same-column)
9160 "Insert a hline and move to the row below that line."
9161 (interactive "P")
9162 (let ((col (org-table-current-column)))
9163 (org-table-maybe-eval-formula)
9164 (org-table-maybe-recalculate-line)
9165 (org-table-insert-hline)
9166 (end-of-line 2)
9167 (if (looking-at "\n[ \t]*|-")
9168 (progn (insert "\n|") (org-table-align))
9169 (org-table-next-field))
9170 (if same-column (org-table-goto-column col))))
9172 (defun org-table-clean-line (s)
9173 "Convert a table line S into a string with only \"|\" and space.
9174 In particular, this does handle wide and invisible characters."
9175 (if (string-match "^[ \t]*|-" s)
9176 ;; It's a hline, just map the characters
9177 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9178 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9179 (setq s (replace-match
9180 (concat "|" (make-string (org-string-width (match-string 1 s))
9181 ?\ ) "|")
9182 t t s)))
9185 (defun org-table-kill-row ()
9186 "Delete the current row or horizontal line from the table."
9187 (interactive)
9188 (if (not (org-at-table-p))
9189 (error "Not at a table"))
9190 (let ((col (current-column))
9191 (dline (org-table-current-dline)))
9192 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9193 (if (not (org-at-table-p)) (beginning-of-line 0))
9194 (move-to-column col)
9195 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9196 dline -1 dline)))
9198 (defun org-table-sort-lines (with-case &optional sorting-type)
9199 "Sort table lines according to the column at point.
9201 The position of point indicates the column to be used for
9202 sorting, and the range of lines is the range between the nearest
9203 horizontal separator lines, or the entire table of no such lines
9204 exist. If point is before the first column, you will be prompted
9205 for the sorting column. If there is an active region, the mark
9206 specifies the first line and the sorting column, while point
9207 should be in the last line to be included into the sorting.
9209 The command then prompts for the sorting type which can be
9210 alphabetically, numerically, or by time (as given in a time stamp
9211 in the field). Sorting in reverse order is also possible.
9213 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9215 If SORTING-TYPE is specified when this function is called from a Lisp
9216 program, no prompting will take place. SORTING-TYPE must be a character,
9217 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9218 should be done in reverse order."
9219 (interactive "P")
9220 (let* ((thisline (org-current-line))
9221 (thiscol (org-table-current-column))
9222 beg end bcol ecol tend tbeg column lns pos)
9223 (when (equal thiscol 0)
9224 (if (interactive-p)
9225 (setq thiscol
9226 (string-to-number
9227 (read-string "Use column N for sorting: ")))
9228 (setq thiscol 1))
9229 (org-table-goto-column thiscol))
9230 (org-table-check-inside-data-field)
9231 (if (org-region-active-p)
9232 (progn
9233 (setq beg (region-beginning) end (region-end))
9234 (goto-char beg)
9235 (setq column (org-table-current-column)
9236 beg (point-at-bol))
9237 (goto-char end)
9238 (setq end (point-at-bol 2)))
9239 (setq column (org-table-current-column)
9240 pos (point)
9241 tbeg (org-table-begin)
9242 tend (org-table-end))
9243 (if (re-search-backward org-table-hline-regexp tbeg t)
9244 (setq beg (point-at-bol 2))
9245 (goto-char tbeg)
9246 (setq beg (point-at-bol 1)))
9247 (goto-char pos)
9248 (if (re-search-forward org-table-hline-regexp tend t)
9249 (setq end (point-at-bol 1))
9250 (goto-char tend)
9251 (setq end (point-at-bol))))
9252 (setq beg (move-marker (make-marker) beg)
9253 end (move-marker (make-marker) end))
9254 (untabify beg end)
9255 (goto-char beg)
9256 (org-table-goto-column column)
9257 (skip-chars-backward "^|")
9258 (setq bcol (current-column))
9259 (org-table-goto-column (1+ column))
9260 (skip-chars-backward "^|")
9261 (setq ecol (1- (current-column)))
9262 (org-table-goto-column column)
9263 (setq lns (mapcar (lambda(x) (cons
9264 (org-sort-remove-invisible
9265 (nth (1- column)
9266 (org-split-string x "[ \t]*|[ \t]*")))
9268 (org-split-string (buffer-substring beg end) "\n")))
9269 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9270 (delete-region beg end)
9271 (move-marker beg nil)
9272 (move-marker end nil)
9273 (insert (mapconcat 'cdr lns "\n") "\n")
9274 (goto-line thisline)
9275 (org-table-goto-column thiscol)
9276 (message "%d lines sorted, based on column %d" (length lns) column)))
9278 ;; FIXME: maybe we will not need this? Table sorting is broken....
9279 (defun org-sort-remove-invisible (s)
9280 (remove-text-properties 0 (length s) org-rm-props s)
9281 (while (string-match org-bracket-link-regexp s)
9282 (setq s (replace-match (if (match-end 2)
9283 (match-string 3 s)
9284 (match-string 1 s)) t t s)))
9287 (defun org-table-cut-region (beg end)
9288 "Copy region in table to the clipboard and blank all relevant fields."
9289 (interactive "r")
9290 (org-table-copy-region beg end 'cut))
9292 (defun org-table-copy-region (beg end &optional cut)
9293 "Copy rectangular region in table to clipboard.
9294 A special clipboard is used which can only be accessed
9295 with `org-table-paste-rectangle'."
9296 (interactive "rP")
9297 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9298 region cols
9299 (rpl (if cut " " nil)))
9300 (goto-char beg)
9301 (org-table-check-inside-data-field)
9302 (setq l01 (org-current-line)
9303 c01 (org-table-current-column))
9304 (goto-char end)
9305 (org-table-check-inside-data-field)
9306 (setq l02 (org-current-line)
9307 c02 (org-table-current-column))
9308 (setq l1 (min l01 l02) l2 (max l01 l02)
9309 c1 (min c01 c02) c2 (max c01 c02))
9310 (catch 'exit
9311 (while t
9312 (catch 'nextline
9313 (if (> l1 l2) (throw 'exit t))
9314 (goto-line l1)
9315 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9316 (setq cols nil ic1 c1 ic2 c2)
9317 (while (< ic1 (1+ ic2))
9318 (push (org-table-get-field ic1 rpl) cols)
9319 (setq ic1 (1+ ic1)))
9320 (push (nreverse cols) region)
9321 (setq l1 (1+ l1)))))
9322 (setq org-table-clip (nreverse region))
9323 (if cut (org-table-align))
9324 org-table-clip))
9326 (defun org-table-paste-rectangle ()
9327 "Paste a rectangular region into a table.
9328 The upper right corner ends up in the current field. All involved fields
9329 will be overwritten. If the rectangle does not fit into the present table,
9330 the table is enlarged as needed. The process ignores horizontal separator
9331 lines."
9332 (interactive)
9333 (unless (and org-table-clip (listp org-table-clip))
9334 (error "First cut/copy a region to paste!"))
9335 (org-table-check-inside-data-field)
9336 (let* ((clip org-table-clip)
9337 (line (org-current-line))
9338 (col (org-table-current-column))
9339 (org-enable-table-editor t)
9340 (org-table-automatic-realign nil)
9341 c cols field)
9342 (while (setq cols (pop clip))
9343 (while (org-at-table-hline-p) (beginning-of-line 2))
9344 (if (not (org-at-table-p))
9345 (progn (end-of-line 0) (org-table-next-field)))
9346 (setq c col)
9347 (while (setq field (pop cols))
9348 (org-table-goto-column c nil 'force)
9349 (org-table-get-field nil field)
9350 (setq c (1+ c)))
9351 (beginning-of-line 2))
9352 (goto-line line)
9353 (org-table-goto-column col)
9354 (org-table-align)))
9356 (defun org-table-convert ()
9357 "Convert from `org-mode' table to table.el and back.
9358 Obviously, this only works within limits. When an Org-mode table is
9359 converted to table.el, all horizontal separator lines get lost, because
9360 table.el uses these as cell boundaries and has no notion of horizontal lines.
9361 A table.el table can be converted to an Org-mode table only if it does not
9362 do row or column spanning. Multiline cells will become multiple cells.
9363 Beware, Org-mode does not test if the table can be successfully converted - it
9364 blindly applies a recipe that works for simple tables."
9365 (interactive)
9366 (require 'table)
9367 (if (org-at-table.el-p)
9368 ;; convert to Org-mode table
9369 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9370 (end (move-marker (make-marker) (org-table-end t))))
9371 (table-unrecognize-region beg end)
9372 (goto-char beg)
9373 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9374 (replace-match ""))
9375 (goto-char beg))
9376 (if (org-at-table-p)
9377 ;; convert to table.el table
9378 (let ((beg (move-marker (make-marker) (org-table-begin)))
9379 (end (move-marker (make-marker) (org-table-end))))
9380 ;; first, get rid of all horizontal lines
9381 (goto-char beg)
9382 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9383 (replace-match ""))
9384 ;; insert a hline before first
9385 (goto-char beg)
9386 (org-table-insert-hline 'above)
9387 (beginning-of-line -1)
9388 ;; insert a hline after each line
9389 (while (progn (beginning-of-line 3) (< (point) end))
9390 (org-table-insert-hline))
9391 (goto-char beg)
9392 (setq end (move-marker end (org-table-end)))
9393 ;; replace "+" at beginning and ending of hlines
9394 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9395 (replace-match "\\1+-"))
9396 (goto-char beg)
9397 (while (re-search-forward "-|[ \t]*$" end t)
9398 (replace-match "-+"))
9399 (goto-char beg)))))
9401 (defun org-table-wrap-region (arg)
9402 "Wrap several fields in a column like a paragraph.
9403 This is useful if you'd like to spread the contents of a field over several
9404 lines, in order to keep the table compact.
9406 If there is an active region, and both point and mark are in the same column,
9407 the text in the column is wrapped to minimum width for the given number of
9408 lines. Generally, this makes the table more compact. A prefix ARG may be
9409 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9410 formats the selected text to two lines. If the region was longer than two
9411 lines, the remaining lines remain empty. A negative prefix argument reduces
9412 the current number of lines by that amount. The wrapped text is pasted back
9413 into the table. If you formatted it to more lines than it was before, fields
9414 further down in the table get overwritten - so you might need to make space in
9415 the table first.
9417 If there is no region, the current field is split at the cursor position and
9418 the text fragment to the right of the cursor is prepended to the field one
9419 line down.
9421 If there is no region, but you specify a prefix ARG, the current field gets
9422 blank, and the content is appended to the field above."
9423 (interactive "P")
9424 (org-table-check-inside-data-field)
9425 (if (org-region-active-p)
9426 ;; There is a region: fill as a paragraph
9427 (let* ((beg (region-beginning))
9428 (cline (save-excursion (goto-char beg) (org-current-line)))
9429 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9430 nlines)
9431 (org-table-cut-region (region-beginning) (region-end))
9432 (if (> (length (car org-table-clip)) 1)
9433 (error "Region must be limited to single column"))
9434 (setq nlines (if arg
9435 (if (< arg 1)
9436 (+ (length org-table-clip) arg)
9437 arg)
9438 (length org-table-clip)))
9439 (setq org-table-clip
9440 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9441 nil nlines)))
9442 (goto-line cline)
9443 (org-table-goto-column ccol)
9444 (org-table-paste-rectangle))
9445 ;; No region, split the current field at point
9446 (if arg
9447 ;; combine with field above
9448 (let ((s (org-table-blank-field))
9449 (col (org-table-current-column)))
9450 (beginning-of-line 0)
9451 (while (org-at-table-hline-p) (beginning-of-line 0))
9452 (org-table-goto-column col)
9453 (skip-chars-forward "^|")
9454 (skip-chars-backward " ")
9455 (insert " " (org-trim s))
9456 (org-table-align))
9457 ;; split field
9458 (when (looking-at "\\([^|]+\\)+|")
9459 (let ((s (match-string 1)))
9460 (replace-match " |")
9461 (goto-char (match-beginning 0))
9462 (org-table-next-row)
9463 (insert (org-trim s) " ")
9464 (org-table-align))))))
9466 (defvar org-field-marker nil)
9468 (defun org-table-edit-field (arg)
9469 "Edit table field in a different window.
9470 This is mainly useful for fields that contain hidden parts.
9471 When called with a \\[universal-argument] prefix, just make the full field visible so that
9472 it can be edited in place."
9473 (interactive "P")
9474 (if arg
9475 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9476 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9477 (remove-text-properties b e '(org-cwidth t invisible t
9478 display t intangible t))
9479 (if (and (boundp 'font-lock-mode) font-lock-mode)
9480 (font-lock-fontify-block)))
9481 (let ((pos (move-marker (make-marker) (point)))
9482 (field (org-table-get-field))
9483 (cw (current-window-configuration))
9485 (org-switch-to-buffer-other-window "*Org tmp*")
9486 (erase-buffer)
9487 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9488 (let ((org-inhibit-startup t)) (org-mode))
9489 (goto-char (setq p (point-max)))
9490 (insert (org-trim field))
9491 (remove-text-properties p (point-max)
9492 '(invisible t org-cwidth t display t
9493 intangible t))
9494 (goto-char p)
9495 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9496 (org-set-local 'org-window-configuration cw)
9497 (org-set-local 'org-field-marker pos)
9498 (message "Edit and finish with C-c C-c"))))
9500 (defun org-table-finish-edit-field ()
9501 "Finish editing a table data field.
9502 Remove all newline characters, insert the result into the table, realign
9503 the table and kill the editing buffer."
9504 (let ((pos org-field-marker)
9505 (cw org-window-configuration)
9506 (cb (current-buffer))
9507 text)
9508 (goto-char (point-min))
9509 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9510 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9511 (replace-match " "))
9512 (setq text (org-trim (buffer-string)))
9513 (set-window-configuration cw)
9514 (kill-buffer cb)
9515 (select-window (get-buffer-window (marker-buffer pos)))
9516 (goto-char pos)
9517 (move-marker pos nil)
9518 (org-table-check-inside-data-field)
9519 (org-table-get-field nil text)
9520 (org-table-align)
9521 (message "New field value inserted")))
9523 (defun org-trim (s)
9524 "Remove whitespace at beginning and end of string."
9525 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9526 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9529 (defun org-wrap (string &optional width lines)
9530 "Wrap string to either a number of lines, or a width in characters.
9531 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9532 that costs. If there is a word longer than WIDTH, the text is actually
9533 wrapped to the length of that word.
9534 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9535 many lines, whatever width that takes.
9536 The return value is a list of lines, without newlines at the end."
9537 (let* ((words (org-split-string string "[ \t\n]+"))
9538 (maxword (apply 'max (mapcar 'org-string-width words)))
9539 w ll)
9540 (cond (width
9541 (org-do-wrap words (max maxword width)))
9542 (lines
9543 (setq w maxword)
9544 (setq ll (org-do-wrap words maxword))
9545 (if (<= (length ll) lines)
9547 (setq ll words)
9548 (while (> (length ll) lines)
9549 (setq w (1+ w))
9550 (setq ll (org-do-wrap words w)))
9551 ll))
9552 (t (error "Cannot wrap this")))))
9555 (defun org-do-wrap (words width)
9556 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9557 (let (lines line)
9558 (while words
9559 (setq line (pop words))
9560 (while (and words (< (+ (length line) (length (car words))) width))
9561 (setq line (concat line " " (pop words))))
9562 (setq lines (push line lines)))
9563 (nreverse lines)))
9565 (defun org-split-string (string &optional separators)
9566 "Splits STRING into substrings at SEPARATORS.
9567 No empty strings are returned if there are matches at the beginning
9568 and end of string."
9569 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9570 (start 0)
9571 notfirst
9572 (list nil))
9573 (while (and (string-match rexp string
9574 (if (and notfirst
9575 (= start (match-beginning 0))
9576 (< start (length string)))
9577 (1+ start) start))
9578 (< (match-beginning 0) (length string)))
9579 (setq notfirst t)
9580 (or (eq (match-beginning 0) 0)
9581 (and (eq (match-beginning 0) (match-end 0))
9582 (eq (match-beginning 0) start))
9583 (setq list
9584 (cons (substring string start (match-beginning 0))
9585 list)))
9586 (setq start (match-end 0)))
9587 (or (eq start (length string))
9588 (setq list
9589 (cons (substring string start)
9590 list)))
9591 (nreverse list)))
9593 (defun org-table-map-tables (function)
9594 "Apply FUNCTION to the start of all tables in the buffer."
9595 (save-excursion
9596 (save-restriction
9597 (widen)
9598 (goto-char (point-min))
9599 (while (re-search-forward org-table-any-line-regexp nil t)
9600 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9601 (beginning-of-line 1)
9602 (if (looking-at org-table-line-regexp)
9603 (save-excursion (funcall function)))
9604 (re-search-forward org-table-any-border-regexp nil 1))))
9605 (message "Mapping tables: done"))
9607 (defvar org-timecnt) ; dynamically scoped parameter
9609 (defun org-table-sum (&optional beg end nlast)
9610 "Sum numbers in region of current table column.
9611 The result will be displayed in the echo area, and will be available
9612 as kill to be inserted with \\[yank].
9614 If there is an active region, it is interpreted as a rectangle and all
9615 numbers in that rectangle will be summed. If there is no active
9616 region and point is located in a table column, sum all numbers in that
9617 column.
9619 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9620 numbers are assumed to be times as well (in decimal hours) and the
9621 numbers are added as such.
9623 If NLAST is a number, only the NLAST fields will actually be summed."
9624 (interactive)
9625 (save-excursion
9626 (let (col (org-timecnt 0) diff h m s org-table-clip)
9627 (cond
9628 ((and beg end)) ; beg and end given explicitly
9629 ((org-region-active-p)
9630 (setq beg (region-beginning) end (region-end)))
9632 (setq col (org-table-current-column))
9633 (goto-char (org-table-begin))
9634 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9635 (error "No table data"))
9636 (org-table-goto-column col)
9637 (setq beg (point))
9638 (goto-char (org-table-end))
9639 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9640 (error "No table data"))
9641 (org-table-goto-column col)
9642 (setq end (point))))
9643 (let* ((items (apply 'append (org-table-copy-region beg end)))
9644 (items1 (cond ((not nlast) items)
9645 ((>= nlast (length items)) items)
9646 (t (setq items (reverse items))
9647 (setcdr (nthcdr (1- nlast) items) nil)
9648 (nreverse items))))
9649 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9650 items1)))
9651 (res (apply '+ numbers))
9652 (sres (if (= org-timecnt 0)
9653 (format "%g" res)
9654 (setq diff (* 3600 res)
9655 h (floor (/ diff 3600)) diff (mod diff 3600)
9656 m (floor (/ diff 60)) diff (mod diff 60)
9657 s diff)
9658 (format "%d:%02d:%02d" h m s))))
9659 (kill-new sres)
9660 (if (interactive-p)
9661 (message "%s"
9662 (substitute-command-keys
9663 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9664 (length numbers) sres))))
9665 sres))))
9667 (defun org-table-get-number-for-summing (s)
9668 (let (n)
9669 (if (string-match "^ *|? *" s)
9670 (setq s (replace-match "" nil nil s)))
9671 (if (string-match " *|? *$" s)
9672 (setq s (replace-match "" nil nil s)))
9673 (setq n (string-to-number s))
9674 (cond
9675 ((and (string-match "0" s)
9676 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9677 ((string-match "\\`[ \t]+\\'" s) nil)
9678 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9679 (let ((h (string-to-number (or (match-string 1 s) "0")))
9680 (m (string-to-number (or (match-string 2 s) "0")))
9681 (s (string-to-number (or (match-string 4 s) "0"))))
9682 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9683 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9684 ((equal n 0) nil)
9685 (t n))))
9687 (defun org-table-current-field-formula (&optional key noerror)
9688 "Return the formula active for the current field.
9689 Assumes that specials are in place.
9690 If KEY is given, return the key to this formula.
9691 Otherwise return the formula preceeded with \"=\" or \":=\"."
9692 (let* ((name (car (rassoc (list (org-current-line)
9693 (org-table-current-column))
9694 org-table-named-field-locations)))
9695 (col (org-table-current-column))
9696 (scol (int-to-string col))
9697 (ref (format "@%d$%d" (org-table-current-dline) col))
9698 (stored-list (org-table-get-stored-formulas noerror))
9699 (ass (or (assoc name stored-list)
9700 (assoc ref stored-list)
9701 (assoc scol stored-list))))
9702 (if key
9703 (car ass)
9704 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9705 (cdr ass))))))
9707 (defun org-table-get-formula (&optional equation named)
9708 "Read a formula from the minibuffer, offer stored formula as default.
9709 When NAMED is non-nil, look for a named equation."
9710 (let* ((stored-list (org-table-get-stored-formulas))
9711 (name (car (rassoc (list (org-current-line)
9712 (org-table-current-column))
9713 org-table-named-field-locations)))
9714 (ref (format "@%d$%d" (org-table-current-dline)
9715 (org-table-current-column)))
9716 (refass (assoc ref stored-list))
9717 (scol (if named
9718 (if name name ref)
9719 (int-to-string (org-table-current-column))))
9720 (dummy (and (or name refass) (not named)
9721 (not (y-or-n-p "Replace field formula with column formula? " ))
9722 (error "Abort")))
9723 (name (or name ref))
9724 (org-table-may-need-update nil)
9725 (stored (cdr (assoc scol stored-list)))
9726 (eq (cond
9727 ((and stored equation (string-match "^ *=? *$" equation))
9728 stored)
9729 ((stringp equation)
9730 equation)
9731 (t (org-table-formula-from-user
9732 (read-string
9733 (org-table-formula-to-user
9734 (format "%s formula %s%s="
9735 (if named "Field" "Column")
9736 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9737 scol))
9738 (if stored (org-table-formula-to-user stored) "")
9739 'org-table-formula-history
9740 )))))
9741 mustsave)
9742 (when (not (string-match "\\S-" eq))
9743 ;; remove formula
9744 (setq stored-list (delq (assoc scol stored-list) stored-list))
9745 (org-table-store-formulas stored-list)
9746 (error "Formula removed"))
9747 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9748 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9749 (if (and name (not named))
9750 ;; We set the column equation, delete the named one.
9751 (setq stored-list (delq (assoc name stored-list) stored-list)
9752 mustsave t))
9753 (if stored
9754 (setcdr (assoc scol stored-list) eq)
9755 (setq stored-list (cons (cons scol eq) stored-list)))
9756 (if (or mustsave (not (equal stored eq)))
9757 (org-table-store-formulas stored-list))
9758 eq))
9760 (defun org-table-store-formulas (alist)
9761 "Store the list of formulas below the current table."
9762 (setq alist (sort alist 'org-table-formula-less-p))
9763 (save-excursion
9764 (goto-char (org-table-end))
9765 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9766 (progn
9767 ;; don't overwrite TBLFM, we might use text properties to store stuff
9768 (goto-char (match-beginning 2))
9769 (delete-region (match-beginning 2) (match-end 0)))
9770 (insert "#+TBLFM:"))
9771 (insert " "
9772 (mapconcat (lambda (x)
9773 (concat
9774 (if (equal (string-to-char (car x)) ?@) "" "$")
9775 (car x) "=" (cdr x)))
9776 alist "::")
9777 "\n")))
9779 (defsubst org-table-formula-make-cmp-string (a)
9780 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9781 (concat
9782 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9783 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9784 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9786 (defun org-table-formula-less-p (a b)
9787 "Compare two formulas for sorting."
9788 (let ((as (org-table-formula-make-cmp-string (car a)))
9789 (bs (org-table-formula-make-cmp-string (car b))))
9790 (and as bs (string< as bs))))
9792 (defun org-table-get-stored-formulas (&optional noerror)
9793 "Return an alist with the stored formulas directly after current table."
9794 (interactive)
9795 (let (scol eq eq-alist strings string seen)
9796 (save-excursion
9797 (goto-char (org-table-end))
9798 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9799 (setq strings (org-split-string (match-string 2) " *:: *"))
9800 (while (setq string (pop strings))
9801 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9802 (setq scol (if (match-end 2)
9803 (match-string 2 string)
9804 (match-string 1 string))
9805 eq (match-string 3 string)
9806 eq-alist (cons (cons scol eq) eq-alist))
9807 (if (member scol seen)
9808 (if noerror
9809 (progn
9810 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9811 (ding)
9812 (sit-for 2))
9813 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9814 (push scol seen))))))
9815 (nreverse eq-alist)))
9817 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9818 "Modify the equations after the table structure has been edited.
9819 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9820 For all numbers larger than LIMIT, shift them by DELTA."
9821 (save-excursion
9822 (goto-char (org-table-end))
9823 (when (looking-at "#\\+TBLFM:")
9824 (let ((re (concat key "\\([0-9]+\\)"))
9825 (re2
9826 (when remove
9827 (if (equal key "$")
9828 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9829 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9830 s n a)
9831 (when remove
9832 (while (re-search-forward re2 (point-at-eol) t)
9833 (replace-match "")))
9834 (while (re-search-forward re (point-at-eol) t)
9835 (setq s (match-string 1) n (string-to-number s))
9836 (cond
9837 ((setq a (assoc s replace))
9838 (replace-match (concat key (cdr a)) t t))
9839 ((and limit (> n limit))
9840 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9842 (defun org-table-get-specials ()
9843 "Get the column names and local parameters for this table."
9844 (save-excursion
9845 (let ((beg (org-table-begin)) (end (org-table-end))
9846 names name fields fields1 field cnt
9847 c v l line col types dlines hlines)
9848 (setq org-table-column-names nil
9849 org-table-local-parameters nil
9850 org-table-named-field-locations nil
9851 org-table-current-begin-line nil
9852 org-table-current-begin-pos nil
9853 org-table-current-line-types nil)
9854 (goto-char beg)
9855 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9856 (setq names (org-split-string (match-string 1) " *| *")
9857 cnt 1)
9858 (while (setq name (pop names))
9859 (setq cnt (1+ cnt))
9860 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9861 (push (cons name (int-to-string cnt)) org-table-column-names))))
9862 (setq org-table-column-names (nreverse org-table-column-names))
9863 (setq org-table-column-name-regexp
9864 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9865 (goto-char beg)
9866 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9867 (setq fields (org-split-string (match-string 1) " *| *"))
9868 (while (setq field (pop fields))
9869 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9870 (push (cons (match-string 1 field) (match-string 2 field))
9871 org-table-local-parameters))))
9872 (goto-char beg)
9873 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9874 (setq c (match-string 1)
9875 fields (org-split-string (match-string 2) " *| *"))
9876 (save-excursion
9877 (beginning-of-line (if (equal c "_") 2 0))
9878 (setq line (org-current-line) col 1)
9879 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9880 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9881 (while (and fields1 (setq field (pop fields)))
9882 (setq v (pop fields1) col (1+ col))
9883 (when (and (stringp field) (stringp v)
9884 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9885 (push (cons field v) org-table-local-parameters)
9886 (push (list field line col) org-table-named-field-locations))))
9887 ;; Analyse the line types
9888 (goto-char beg)
9889 (setq org-table-current-begin-line (org-current-line)
9890 org-table-current-begin-pos (point)
9891 l org-table-current-begin-line)
9892 (while (looking-at "[ \t]*|\\(-\\)?")
9893 (push (if (match-end 1) 'hline 'dline) types)
9894 (if (match-end 1) (push l hlines) (push l dlines))
9895 (beginning-of-line 2)
9896 (setq l (1+ l)))
9897 (setq org-table-current-line-types (apply 'vector (nreverse types))
9898 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9899 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9901 (defun org-table-maybe-eval-formula ()
9902 "Check if the current field starts with \"=\" or \":=\".
9903 If yes, store the formula and apply it."
9904 ;; We already know we are in a table. Get field will only return a formula
9905 ;; when appropriate. It might return a separator line, but no problem.
9906 (when org-table-formula-evaluate-inline
9907 (let* ((field (org-trim (or (org-table-get-field) "")))
9908 named eq)
9909 (when (string-match "^:?=\\(.*\\)" field)
9910 (setq named (equal (string-to-char field) ?:)
9911 eq (match-string 1 field))
9912 (if (or (fboundp 'calc-eval)
9913 (equal (substring eq 0 (min 2 (length eq))) "'("))
9914 (org-table-eval-formula (if named '(4) nil)
9915 (org-table-formula-from-user eq))
9916 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9918 (defvar org-recalc-commands nil
9919 "List of commands triggering the recalculation of a line.
9920 Will be filled automatically during use.")
9922 (defvar org-recalc-marks
9923 '((" " . "Unmarked: no special line, no automatic recalculation")
9924 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9925 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9926 ("!" . "Column name definition line. Reference in formula as $name.")
9927 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9928 ("_" . "Names for values in row below this one.")
9929 ("^" . "Names for values in row above this one.")))
9931 (defun org-table-rotate-recalc-marks (&optional newchar)
9932 "Rotate the recalculation mark in the first column.
9933 If in any row, the first field is not consistent with a mark,
9934 insert a new column for the markers.
9935 When there is an active region, change all the lines in the region,
9936 after prompting for the marking character.
9937 After each change, a message will be displayed indicating the meaning
9938 of the new mark."
9939 (interactive)
9940 (unless (org-at-table-p) (error "Not at a table"))
9941 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9942 (beg (org-table-begin))
9943 (end (org-table-end))
9944 (l (org-current-line))
9945 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9946 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9947 (have-col
9948 (save-excursion
9949 (goto-char beg)
9950 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9951 (col (org-table-current-column))
9952 (forcenew (car (assoc newchar org-recalc-marks)))
9953 epos new)
9954 (when l1
9955 (message "Change region to what mark? Type # * ! $ or SPC: ")
9956 (setq newchar (char-to-string (read-char-exclusive))
9957 forcenew (car (assoc newchar org-recalc-marks))))
9958 (if (and newchar (not forcenew))
9959 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9960 newchar))
9961 (if l1 (goto-line l1))
9962 (save-excursion
9963 (beginning-of-line 1)
9964 (unless (looking-at org-table-dataline-regexp)
9965 (error "Not at a table data line")))
9966 (unless have-col
9967 (org-table-goto-column 1)
9968 (org-table-insert-column)
9969 (org-table-goto-column (1+ col)))
9970 (setq epos (point-at-eol))
9971 (save-excursion
9972 (beginning-of-line 1)
9973 (org-table-get-field
9974 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9975 (concat " "
9976 (setq new (or forcenew
9977 (cadr (member (match-string 1) marks))))
9978 " ")
9979 " # ")))
9980 (if (and l1 l2)
9981 (progn
9982 (goto-line l1)
9983 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9984 (and (looking-at org-table-dataline-regexp)
9985 (org-table-get-field 1 (concat " " new " "))))
9986 (goto-line l1)))
9987 (if (not (= epos (point-at-eol))) (org-table-align))
9988 (goto-line l)
9989 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
9991 (defun org-table-maybe-recalculate-line ()
9992 "Recompute the current line if marked for it, and if we haven't just done it."
9993 (interactive)
9994 (and org-table-allow-automatic-line-recalculation
9995 (not (and (memq last-command org-recalc-commands)
9996 (equal org-last-recalc-line (org-current-line))))
9997 (save-excursion (beginning-of-line 1)
9998 (looking-at org-table-auto-recalculate-regexp))
9999 (org-table-recalculate) t))
10001 (defvar org-table-formula-debug nil
10002 "Non-nil means, debug table formulas.
10003 When nil, simply write \"#ERROR\" in corrupted fields.")
10004 (make-variable-buffer-local 'org-table-formula-debug)
10006 (defvar modes)
10007 (defsubst org-set-calc-mode (var &optional value)
10008 (if (stringp var)
10009 (setq var (assoc var '(("D" calc-angle-mode deg)
10010 ("R" calc-angle-mode rad)
10011 ("F" calc-prefer-frac t)
10012 ("S" calc-symbolic-mode t)))
10013 value (nth 2 var) var (nth 1 var)))
10014 (if (memq var modes)
10015 (setcar (cdr (memq var modes)) value)
10016 (cons var (cons value modes)))
10017 modes)
10019 (defun org-table-eval-formula (&optional arg equation
10020 suppress-align suppress-const
10021 suppress-store suppress-analysis)
10022 "Replace the table field value at the cursor by the result of a calculation.
10024 This function makes use of Dave Gillespie's Calc package, in my view the
10025 most exciting program ever written for GNU Emacs. So you need to have Calc
10026 installed in order to use this function.
10028 In a table, this command replaces the value in the current field with the
10029 result of a formula. It also installs the formula as the \"current\" column
10030 formula, by storing it in a special line below the table. When called
10031 with a `C-u' prefix, the current field must ba a named field, and the
10032 formula is installed as valid in only this specific field.
10034 When called with two `C-u' prefixes, insert the active equation
10035 for the field back into the current field, so that it can be
10036 edited there. This is useful in order to use \\[org-table-show-reference]
10037 to check the referenced fields.
10039 When called, the command first prompts for a formula, which is read in
10040 the minibuffer. Previously entered formulas are available through the
10041 history list, and the last used formula is offered as a default.
10042 These stored formulas are adapted correctly when moving, inserting, or
10043 deleting columns with the corresponding commands.
10045 The formula can be any algebraic expression understood by the Calc package.
10046 For details, see the Org-mode manual.
10048 This function can also be called from Lisp programs and offers
10049 additional arguments: EQUATION can be the formula to apply. If this
10050 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10051 used to speed-up recursive calls by by-passing unnecessary aligns.
10052 SUPPRESS-CONST suppresses the interpretation of constants in the
10053 formula, assuming that this has been done already outside the function.
10054 SUPPRESS-STORE means the formula should not be stored, either because
10055 it is already stored, or because it is a modified equation that should
10056 not overwrite the stored one."
10057 (interactive "P")
10058 (org-table-check-inside-data-field)
10059 (or suppress-analysis (org-table-get-specials))
10060 (if (equal arg '(16))
10061 (let ((eq (org-table-current-field-formula)))
10062 (or eq (error "No equation active for current field"))
10063 (org-table-get-field nil eq)
10064 (org-table-align)
10065 (setq org-table-may-need-update t))
10066 (let* (fields
10067 (ndown (if (integerp arg) arg 1))
10068 (org-table-automatic-realign nil)
10069 (case-fold-search nil)
10070 (down (> ndown 1))
10071 (formula (if (and equation suppress-store)
10072 equation
10073 (org-table-get-formula equation (equal arg '(4)))))
10074 (n0 (org-table-current-column))
10075 (modes (copy-sequence org-calc-default-modes))
10076 (numbers nil) ; was a variable, now fixed default
10077 (keep-empty nil)
10078 n form form0 bw fmt x ev orig c lispp literal)
10079 ;; Parse the format string. Since we have a lot of modes, this is
10080 ;; a lot of work. However, I think calc still uses most of the time.
10081 (if (string-match ";" formula)
10082 (let ((tmp (org-split-string formula ";")))
10083 (setq formula (car tmp)
10084 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10085 (nth 1 tmp)))
10086 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10087 (setq c (string-to-char (match-string 1 fmt))
10088 n (string-to-number (match-string 2 fmt)))
10089 (if (= c ?p)
10090 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10091 (setq modes (org-set-calc-mode
10092 'calc-float-format
10093 (list (cdr (assoc c '((?n . float) (?f . fix)
10094 (?s . sci) (?e . eng))))
10095 n))))
10096 (setq fmt (replace-match "" t t fmt)))
10097 (if (string-match "[NT]" fmt)
10098 (setq numbers (equal (match-string 0 fmt) "N")
10099 fmt (replace-match "" t t fmt)))
10100 (if (string-match "L" fmt)
10101 (setq literal t
10102 fmt (replace-match "" t t fmt)))
10103 (if (string-match "E" fmt)
10104 (setq keep-empty t
10105 fmt (replace-match "" t t fmt)))
10106 (while (string-match "[DRFS]" fmt)
10107 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10108 (setq fmt (replace-match "" t t fmt)))
10109 (unless (string-match "\\S-" fmt)
10110 (setq fmt nil))))
10111 (if (and (not suppress-const) org-table-formula-use-constants)
10112 (setq formula (org-table-formula-substitute-names formula)))
10113 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10114 (while (> ndown 0)
10115 (setq fields (org-split-string
10116 (org-no-properties
10117 (buffer-substring (point-at-bol) (point-at-eol)))
10118 " *| *"))
10119 (if (eq numbers t)
10120 (setq fields (mapcar
10121 (lambda (x) (number-to-string (string-to-number x)))
10122 fields)))
10123 (setq ndown (1- ndown))
10124 (setq form (copy-sequence formula)
10125 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10126 (if (and lispp literal) (setq lispp 'literal))
10127 ;; Check for old vertical references
10128 (setq form (org-rewrite-old-row-references form))
10129 ;; Insert complex ranges
10130 (while (string-match org-table-range-regexp form)
10131 (setq form
10132 (replace-match
10133 (save-match-data
10134 (org-table-make-reference
10135 (org-table-get-range (match-string 0 form) nil n0)
10136 keep-empty numbers lispp))
10137 t t form)))
10138 ;; Insert simple ranges
10139 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10140 (setq form
10141 (replace-match
10142 (save-match-data
10143 (org-table-make-reference
10144 (org-sublist
10145 fields (string-to-number (match-string 1 form))
10146 (string-to-number (match-string 2 form)))
10147 keep-empty numbers lispp))
10148 t t form)))
10149 (setq form0 form)
10150 ;; Insert the references to fields in same row
10151 (while (string-match "\\$\\([0-9]+\\)" form)
10152 (setq n (string-to-number (match-string 1 form))
10153 x (nth (1- (if (= n 0) n0 n)) fields))
10154 (unless x (error "Invalid field specifier \"%s\""
10155 (match-string 0 form)))
10156 (setq form (replace-match
10157 (save-match-data
10158 (org-table-make-reference x nil numbers lispp))
10159 t t form)))
10161 (if lispp
10162 (setq ev (condition-case nil
10163 (eval (eval (read form)))
10164 (error "#ERROR"))
10165 ev (if (numberp ev) (number-to-string ev) ev))
10166 (or (fboundp 'calc-eval)
10167 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10168 (setq ev (calc-eval (cons form modes)
10169 (if numbers 'num))))
10171 (when org-table-formula-debug
10172 (with-output-to-temp-buffer "*Substitution History*"
10173 (princ (format "Substitution history of formula
10174 Orig: %s
10175 $xyz-> %s
10176 @r$c-> %s
10177 $1-> %s\n" orig formula form0 form))
10178 (if (listp ev)
10179 (princ (format " %s^\nError: %s"
10180 (make-string (car ev) ?\-) (nth 1 ev)))
10181 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10182 ev (or fmt "NONE")
10183 (if fmt (format fmt (string-to-number ev)) ev)))))
10184 (setq bw (get-buffer-window "*Substitution History*"))
10185 (shrink-window-if-larger-than-buffer bw)
10186 (unless (and (interactive-p) (not ndown))
10187 (unless (let (inhibit-redisplay)
10188 (y-or-n-p "Debugging Formula. Continue to next? "))
10189 (org-table-align)
10190 (error "Abort"))
10191 (delete-window bw)
10192 (message "")))
10193 (if (listp ev) (setq fmt nil ev "#ERROR"))
10194 (org-table-justify-field-maybe
10195 (if fmt (format fmt (string-to-number ev)) ev))
10196 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10197 (call-interactively 'org-return)
10198 (setq ndown 0)))
10199 (and down (org-table-maybe-recalculate-line))
10200 (or suppress-align (and org-table-may-need-update
10201 (org-table-align))))))
10203 (defun org-table-put-field-property (prop value)
10204 (save-excursion
10205 (put-text-property (progn (skip-chars-backward "^|") (point))
10206 (progn (skip-chars-forward "^|") (point))
10207 prop value)))
10209 (defun org-table-get-range (desc &optional tbeg col highlight)
10210 "Get a calc vector from a column, accorting to descriptor DESC.
10211 Optional arguments TBEG and COL can give the beginning of the table and
10212 the current column, to avoid unnecessary parsing.
10213 HIGHLIGHT means, just highlight the range."
10214 (if (not (equal (string-to-char desc) ?@))
10215 (setq desc (concat "@" desc)))
10216 (save-excursion
10217 (or tbeg (setq tbeg (org-table-begin)))
10218 (or col (setq col (org-table-current-column)))
10219 (let ((thisline (org-current-line))
10220 beg end c1 c2 r1 r2 rangep tmp)
10221 (unless (string-match org-table-range-regexp desc)
10222 (error "Invalid table range specifier `%s'" desc))
10223 (setq rangep (match-end 3)
10224 r1 (and (match-end 1) (match-string 1 desc))
10225 r2 (and (match-end 4) (match-string 4 desc))
10226 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10227 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10229 (and c1 (setq c1 (+ (string-to-number c1)
10230 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10231 (and c2 (setq c2 (+ (string-to-number c2)
10232 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10233 (if (equal r1 "") (setq r1 nil))
10234 (if (equal r2 "") (setq r2 nil))
10235 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10236 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10237 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10238 (if (not r1) (setq r1 thisline))
10239 (if (not r2) (setq r2 thisline))
10240 (if (not c1) (setq c1 col))
10241 (if (not c2) (setq c2 col))
10242 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10243 ;; just one field
10244 (progn
10245 (goto-line r1)
10246 (while (not (looking-at org-table-dataline-regexp))
10247 (beginning-of-line 2))
10248 (prog1 (org-trim (org-table-get-field c1))
10249 (if highlight (org-table-highlight-rectangle (point) (point)))))
10250 ;; A range, return a vector
10251 ;; First sort the numbers to get a regular ractangle
10252 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10253 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10254 (goto-line r1)
10255 (while (not (looking-at org-table-dataline-regexp))
10256 (beginning-of-line 2))
10257 (org-table-goto-column c1)
10258 (setq beg (point))
10259 (goto-line r2)
10260 (while (not (looking-at org-table-dataline-regexp))
10261 (beginning-of-line 0))
10262 (org-table-goto-column c2)
10263 (setq end (point))
10264 (if highlight
10265 (org-table-highlight-rectangle
10266 beg (progn (skip-chars-forward "^|\n") (point))))
10267 ;; return string representation of calc vector
10268 (mapcar 'org-trim
10269 (apply 'append (org-table-copy-region beg end)))))))
10271 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10272 "Analyze descriptor DESC and retrieve the corresponding line number.
10273 The cursor is currently in line CLINE, the table begins in line BLINE,
10274 and TABLE is a vector with line types."
10275 (if (string-match "^[0-9]+$" desc)
10276 (aref org-table-dlines (string-to-number desc))
10277 (setq cline (or cline (org-current-line))
10278 bline (or bline org-table-current-begin-line)
10279 table (or table org-table-current-line-types))
10280 (if (or
10281 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10282 ;; 1 2 3 4 5 6
10283 (and (not (match-end 3)) (not (match-end 6)))
10284 (and (match-end 3) (match-end 6) (not (match-end 5))))
10285 (error "invalid row descriptor `%s'" desc))
10286 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10287 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10288 (odir (and (match-end 5) (match-string 5 desc)))
10289 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10290 (i (- cline bline))
10291 (rel (and (match-end 6)
10292 (or (and (match-end 1) (not (match-end 3)))
10293 (match-end 5)))))
10294 (if (and hn (not hdir))
10295 (progn
10296 (setq i 0 hdir "+")
10297 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10298 (if (and (not hn) on (not odir))
10299 (error "should never happen");;(aref org-table-dlines on)
10300 (if (and hn (> hn 0))
10301 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10302 (if on
10303 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10304 (+ bline i)))))
10306 (defun org-find-row-type (table i type backwards relative n)
10307 (let ((l (length table)))
10308 (while (> n 0)
10309 (while (and (setq i (+ i (if backwards -1 1)))
10310 (>= i 0) (< i l)
10311 (not (eq (aref table i) type))
10312 (if (and relative (eq (aref table i) 'hline))
10313 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10314 t)))
10315 (setq n (1- n)))
10316 (if (or (< i 0) (>= i l))
10317 (error "Row descriptior leads outside table")
10318 i)))
10320 (defun org-rewrite-old-row-references (s)
10321 (if (string-match "&[-+0-9I]" s)
10322 (error "Formula contains old &row reference, please rewrite using @-syntax")
10325 (defun org-table-make-reference (elements keep-empty numbers lispp)
10326 "Convert list ELEMENTS to something appropriate to insert into formula.
10327 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10328 NUMBERS indicates that everything should be converted to numbers.
10329 LISPP means to return something appropriate for a Lisp list."
10330 (if (stringp elements) ; just a single val
10331 (if lispp
10332 (if (eq lispp 'literal)
10333 elements
10334 (prin1-to-string (if numbers (string-to-number elements) elements)))
10335 (if (equal elements "") (setq elements "0"))
10336 (if numbers (number-to-string (string-to-number elements)) elements))
10337 (unless keep-empty
10338 (setq elements
10339 (delq nil
10340 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10341 elements))))
10342 (setq elements (or elements '("0")))
10343 (if lispp
10344 (mapconcat
10345 (lambda (x)
10346 (if (eq lispp 'literal)
10348 (prin1-to-string (if numbers (string-to-number x) x))))
10349 elements " ")
10350 (concat "[" (mapconcat
10351 (lambda (x)
10352 (if numbers (number-to-string (string-to-number x)) x))
10353 elements
10354 ",") "]"))))
10356 (defun org-table-recalculate (&optional all noalign)
10357 "Recalculate the current table line by applying all stored formulas.
10358 With prefix arg ALL, do this for all lines in the table."
10359 (interactive "P")
10360 (or (memq this-command org-recalc-commands)
10361 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10362 (unless (org-at-table-p) (error "Not at a table"))
10363 (if (equal all '(16))
10364 (org-table-iterate)
10365 (org-table-get-specials)
10366 (let* ((eqlist (sort (org-table-get-stored-formulas)
10367 (lambda (a b) (string< (car a) (car b)))))
10368 (inhibit-redisplay (not debug-on-error))
10369 (line-re org-table-dataline-regexp)
10370 (thisline (org-current-line))
10371 (thiscol (org-table-current-column))
10372 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10373 ;; Insert constants in all formulas
10374 (setq eqlist
10375 (mapcar (lambda (x)
10376 (setcdr x (org-table-formula-substitute-names (cdr x)))
10378 eqlist))
10379 ;; Split the equation list
10380 (while (setq eq (pop eqlist))
10381 (if (<= (string-to-char (car eq)) ?9)
10382 (push eq eqlnum)
10383 (push eq eqlname)))
10384 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10385 (if all
10386 (progn
10387 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10388 (goto-char (setq beg (org-table-begin)))
10389 (if (re-search-forward org-table-calculate-mark-regexp end t)
10390 ;; This is a table with marked lines, compute selected lines
10391 (setq line-re org-table-recalculate-regexp)
10392 ;; Move forward to the first non-header line
10393 (if (and (re-search-forward org-table-dataline-regexp end t)
10394 (re-search-forward org-table-hline-regexp end t)
10395 (re-search-forward org-table-dataline-regexp end t))
10396 (setq beg (match-beginning 0))
10397 nil))) ;; just leave beg where it is
10398 (setq beg (point-at-bol)
10399 end (move-marker (make-marker) (1+ (point-at-eol)))))
10400 (goto-char beg)
10401 (and all (message "Re-applying formulas to full table..."))
10403 ;; First find the named fields, and mark them untouchanble
10404 (remove-text-properties beg end '(org-untouchable t))
10405 (while (setq eq (pop eqlname))
10406 (setq name (car eq)
10407 a (assoc name org-table-named-field-locations))
10408 (and (not a)
10409 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10410 (setq a (list name
10411 (aref org-table-dlines
10412 (string-to-number (match-string 1 name)))
10413 (string-to-number (match-string 2 name)))))
10414 (when (and a (or all (equal (nth 1 a) thisline)))
10415 (message "Re-applying formula to field: %s" name)
10416 (goto-line (nth 1 a))
10417 (org-table-goto-column (nth 2 a))
10418 (push (append a (list (cdr eq))) eqlname1)
10419 (org-table-put-field-property :org-untouchable t)))
10421 ;; Now evauluate the column formulas, but skip fields covered by
10422 ;; field formulas
10423 (goto-char beg)
10424 (while (re-search-forward line-re end t)
10425 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10426 ;; Unprotected line, recalculate
10427 (and all (message "Re-applying formulas to full table...(line %d)"
10428 (setq cnt (1+ cnt))))
10429 (setq org-last-recalc-line (org-current-line))
10430 (setq eql eqlnum)
10431 (while (setq entry (pop eql))
10432 (goto-line org-last-recalc-line)
10433 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10434 (unless (get-text-property (point) :org-untouchable)
10435 (org-table-eval-formula nil (cdr entry)
10436 'noalign 'nocst 'nostore 'noanalysis)))))
10438 ;; Now evaluate the field formulas
10439 (while (setq eq (pop eqlname1))
10440 (message "Re-applying formula to field: %s" (car eq))
10441 (goto-line (nth 1 eq))
10442 (org-table-goto-column (nth 2 eq))
10443 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10444 'nostore 'noanalysis))
10446 (goto-line thisline)
10447 (org-table-goto-column thiscol)
10448 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10449 (or noalign (and org-table-may-need-update (org-table-align))
10450 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10452 ;; back to initial position
10453 (message "Re-applying formulas...done")
10454 (goto-line thisline)
10455 (org-table-goto-column thiscol)
10456 (or noalign (and org-table-may-need-update (org-table-align))
10457 (and all (message "Re-applying formulas...done"))))))
10459 (defun org-table-iterate (&optional arg)
10460 "Recalculate the table until it does not change anymore."
10461 (interactive "P")
10462 (let ((imax (if arg (prefix-numeric-value arg) 10))
10463 (i 0)
10464 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10465 thistbl)
10466 (catch 'exit
10467 (while (< i imax)
10468 (setq i (1+ i))
10469 (org-table-recalculate 'all)
10470 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10471 (if (not (string= lasttbl thistbl))
10472 (setq lasttbl thistbl)
10473 (if (> i 1)
10474 (message "Convergence after %d iterations" i)
10475 (message "Table was already stable"))
10476 (throw 'exit t)))
10477 (error "No convergence after %d iterations" i))))
10479 (defun org-table-formula-substitute-names (f)
10480 "Replace $const with values in string F."
10481 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10482 ;; First, check for column names
10483 (while (setq start (string-match org-table-column-name-regexp f start))
10484 (setq start (1+ start))
10485 (setq a (assoc (match-string 1 f) org-table-column-names))
10486 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10487 ;; Parameters and constants
10488 (setq start 0)
10489 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10490 (setq start (1+ start))
10491 (if (setq a (save-match-data
10492 (org-table-get-constant (match-string 1 f))))
10493 (setq f (replace-match
10494 (concat (if pp "(") a (if pp ")")) t t f))))
10495 (if org-table-formula-debug
10496 (put-text-property 0 (length f) :orig-formula f1 f))
10499 (defun org-table-get-constant (const)
10500 "Find the value for a parameter or constant in a formula.
10501 Parameters get priority."
10502 (or (cdr (assoc const org-table-local-parameters))
10503 (cdr (assoc const org-table-formula-constants-local))
10504 (cdr (assoc const org-table-formula-constants))
10505 (and (fboundp 'constants-get) (constants-get const))
10506 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10507 (org-entry-get nil (substring const 5) 'inherit))
10508 "#UNDEFINED_NAME"))
10510 (defvar org-table-fedit-map
10511 (let ((map (make-sparse-keymap)))
10512 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10513 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10514 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10515 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10516 (org-defkey map "\C-c?" 'org-table-show-reference)
10517 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10518 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10519 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10520 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10521 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10522 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10523 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10524 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10525 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10526 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10527 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10528 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10529 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10530 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10531 map))
10533 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10534 '("Edit-Formulas"
10535 ["Finish and Install" org-table-fedit-finish t]
10536 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10537 ["Abort" org-table-fedit-abort t]
10538 "--"
10539 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10540 ["Complete Lisp Symbol" lisp-complete-symbol t]
10541 "--"
10542 "Shift Reference at Point"
10543 ["Up" org-table-fedit-ref-up t]
10544 ["Down" org-table-fedit-ref-down t]
10545 ["Left" org-table-fedit-ref-left t]
10546 ["Right" org-table-fedit-ref-right t]
10548 "Change Test Row for Column Formulas"
10549 ["Up" org-table-fedit-line-up t]
10550 ["Down" org-table-fedit-line-down t]
10551 "--"
10552 ["Scroll Table Window" org-table-fedit-scroll t]
10553 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10554 ["Show Table Grid" org-table-fedit-toggle-coordinates
10555 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10556 org-table-overlay-coordinates)]
10557 "--"
10558 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10559 :style toggle :selected org-table-buffer-is-an]))
10561 (defvar org-pos)
10563 (defun org-table-edit-formulas ()
10564 "Edit the formulas of the current table in a separate buffer."
10565 (interactive)
10566 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10567 (beginning-of-line 0))
10568 (unless (org-at-table-p) (error "Not at a table"))
10569 (org-table-get-specials)
10570 (let ((key (org-table-current-field-formula 'key 'noerror))
10571 (eql (sort (org-table-get-stored-formulas 'noerror)
10572 'org-table-formula-less-p))
10573 (pos (move-marker (make-marker) (point)))
10574 (startline 1)
10575 (wc (current-window-configuration))
10576 (titles '((column . "# Column Formulas\n")
10577 (field . "# Field Formulas\n")
10578 (named . "# Named Field Formulas\n")))
10579 entry s type title)
10580 (org-switch-to-buffer-other-window "*Edit Formulas*")
10581 (erase-buffer)
10582 ;; Keep global-font-lock-mode from turning on font-lock-mode
10583 (let ((font-lock-global-modes '(not fundamental-mode)))
10584 (fundamental-mode))
10585 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10586 (org-set-local 'org-pos pos)
10587 (org-set-local 'org-window-configuration wc)
10588 (use-local-map org-table-fedit-map)
10589 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10590 (easy-menu-add org-table-fedit-menu)
10591 (setq startline (org-current-line))
10592 (while (setq entry (pop eql))
10593 (setq type (cond
10594 ((equal (string-to-char (car entry)) ?@) 'field)
10595 ((string-match "^[0-9]" (car entry)) 'column)
10596 (t 'named)))
10597 (when (setq title (assq type titles))
10598 (or (bobp) (insert "\n"))
10599 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10600 (setq titles (delq title titles)))
10601 (if (equal key (car entry)) (setq startline (org-current-line)))
10602 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10603 (car entry) " = " (cdr entry) "\n"))
10604 (remove-text-properties 0 (length s) '(face nil) s)
10605 (insert s))
10606 (if (eq org-table-use-standard-references t)
10607 (org-table-fedit-toggle-ref-type))
10608 (goto-line startline)
10609 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10611 (defun org-table-fedit-post-command ()
10612 (when (not (memq this-command '(lisp-complete-symbol)))
10613 (let ((win (selected-window)))
10614 (save-excursion
10615 (condition-case nil
10616 (org-table-show-reference)
10617 (error nil))
10618 (select-window win)))))
10620 (defun org-table-formula-to-user (s)
10621 "Convert a formula from internal to user representation."
10622 (if (eq org-table-use-standard-references t)
10623 (org-table-convert-refs-to-an s)
10626 (defun org-table-formula-from-user (s)
10627 "Convert a formula from user to internal representation."
10628 (if org-table-use-standard-references
10629 (org-table-convert-refs-to-rc s)
10632 (defun org-table-convert-refs-to-rc (s)
10633 "Convert spreadsheet references from AB7 to @7$28.
10634 Works for single references, but also for entire formulas and even the
10635 full TBLFM line."
10636 (let ((start 0))
10637 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10638 (cond
10639 ((match-end 3)
10640 ;; format match, just advance
10641 (setq start (match-end 0)))
10642 ((and (> (match-beginning 0) 0)
10643 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10644 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10645 ;; 3.e5 or something like this.
10646 (setq start (match-end 0)))
10648 (setq start (match-beginning 0)
10649 s (replace-match
10650 (if (equal (match-string 2 s) "&")
10651 (format "$%d" (org-letters-to-number (match-string 1 s)))
10652 (format "@%d$%d"
10653 (string-to-number (match-string 2 s))
10654 (org-letters-to-number (match-string 1 s))))
10655 t t s)))))
10658 (defun org-table-convert-refs-to-an (s)
10659 "Convert spreadsheet references from to @7$28 to AB7.
10660 Works for single references, but also for entire formulas and even the
10661 full TBLFM line."
10662 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10663 (setq s (replace-match
10664 (format "%s%d"
10665 (org-number-to-letters
10666 (string-to-number (match-string 2 s)))
10667 (string-to-number (match-string 1 s)))
10668 t t s)))
10669 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10670 (setq s (replace-match (concat "\\1"
10671 (org-number-to-letters
10672 (string-to-number (match-string 2 s))) "&")
10673 t nil s)))
10676 (defun org-letters-to-number (s)
10677 "Convert a base 26 number represented by letters into an integer.
10678 For example: AB -> 28."
10679 (let ((n 0))
10680 (setq s (upcase s))
10681 (while (> (length s) 0)
10682 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10683 s (substring s 1)))
10686 (defun org-number-to-letters (n)
10687 "Convert an integer into a base 26 number represented by letters.
10688 For example: 28 -> AB."
10689 (let ((s ""))
10690 (while (> n 0)
10691 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10692 n (/ (1- n) 26)))
10695 (defun org-table-fedit-convert-buffer (function)
10696 "Convert all references in this buffer, using FUNTION."
10697 (let ((line (org-current-line)))
10698 (goto-char (point-min))
10699 (while (not (eobp))
10700 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10701 (delete-region (point) (point-at-eol))
10702 (or (eobp) (forward-char 1)))
10703 (goto-line line)))
10705 (defun org-table-fedit-toggle-ref-type ()
10706 "Convert all references in the buffer from B3 to @3$2 and back."
10707 (interactive)
10708 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10709 (org-table-fedit-convert-buffer
10710 (if org-table-buffer-is-an
10711 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10712 (message "Reference type switched to %s"
10713 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10715 (defun org-table-fedit-ref-up ()
10716 "Shift the reference at point one row/hline up."
10717 (interactive)
10718 (org-table-fedit-shift-reference 'up))
10719 (defun org-table-fedit-ref-down ()
10720 "Shift the reference at point one row/hline down."
10721 (interactive)
10722 (org-table-fedit-shift-reference 'down))
10723 (defun org-table-fedit-ref-left ()
10724 "Shift the reference at point one field to the left."
10725 (interactive)
10726 (org-table-fedit-shift-reference 'left))
10727 (defun org-table-fedit-ref-right ()
10728 "Shift the reference at point one field to the right."
10729 (interactive)
10730 (org-table-fedit-shift-reference 'right))
10732 (defun org-table-fedit-shift-reference (dir)
10733 (cond
10734 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10735 (if (memq dir '(left right))
10736 (org-rematch-and-replace 1 (eq dir 'left))
10737 (error "Cannot shift reference in this direction")))
10738 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10739 ;; A B3-like reference
10740 (if (memq dir '(up down))
10741 (org-rematch-and-replace 2 (eq dir 'up))
10742 (org-rematch-and-replace 1 (eq dir 'left))))
10743 ((org-at-regexp-p
10744 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10745 ;; An internal reference
10746 (if (memq dir '(up down))
10747 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10748 (org-rematch-and-replace 5 (eq dir 'left))))))
10750 (defun org-rematch-and-replace (n &optional decr hline)
10751 "Re-match the group N, and replace it with the shifted refrence."
10752 (or (match-end n) (error "Cannot shift reference in this direction"))
10753 (goto-char (match-beginning n))
10754 (and (looking-at (regexp-quote (match-string n)))
10755 (replace-match (org-shift-refpart (match-string 0) decr hline)
10756 t t)))
10758 (defun org-shift-refpart (ref &optional decr hline)
10759 "Shift a refrence part REF.
10760 If DECR is set, decrease the references row/column, else increase.
10761 If HLINE is set, this may be a hline reference, it certainly is not
10762 a translation reference."
10763 (save-match-data
10764 (let* ((sign (string-match "^[-+]" ref)) n)
10766 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10767 (cond
10768 ((and hline (string-match "^I+" ref))
10769 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10770 (setq n (+ n (if decr -1 1)))
10771 (if (= n 0) (setq n (+ n (if decr -1 1))))
10772 (if sign
10773 (setq sign (if (< n 0) "-" "+") n (abs n))
10774 (setq n (max 1 n)))
10775 (concat sign (make-string n ?I)))
10777 ((string-match "^[0-9]+" ref)
10778 (setq n (string-to-number (concat sign ref)))
10779 (setq n (+ n (if decr -1 1)))
10780 (if sign
10781 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10782 (number-to-string (max 1 n))))
10784 ((string-match "^[a-zA-Z]+" ref)
10785 (org-number-to-letters
10786 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10788 (t (error "Cannot shift reference"))))))
10790 (defun org-table-fedit-toggle-coordinates ()
10791 "Toggle the display of coordinates in the refrenced table."
10792 (interactive)
10793 (let ((pos (marker-position org-pos)))
10794 (with-current-buffer (marker-buffer org-pos)
10795 (save-excursion
10796 (goto-char pos)
10797 (org-table-toggle-coordinate-overlays)))))
10799 (defun org-table-fedit-finish (&optional arg)
10800 "Parse the buffer for formula definitions and install them.
10801 With prefix ARG, apply the new formulas to the table."
10802 (interactive "P")
10803 (org-table-remove-rectangle-highlight)
10804 (if org-table-use-standard-references
10805 (progn
10806 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10807 (setq org-table-buffer-is-an nil)))
10808 (let ((pos org-pos) eql var form)
10809 (goto-char (point-min))
10810 (while (re-search-forward
10811 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10812 nil t)
10813 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10814 form (match-string 3))
10815 (setq form (org-trim form))
10816 (when (not (equal form ""))
10817 (while (string-match "[ \t]*\n[ \t]*" form)
10818 (setq form (replace-match " " t t form)))
10819 (when (assoc var eql)
10820 (error "Double formulas for %s" var))
10821 (push (cons var form) eql)))
10822 (setq org-pos nil)
10823 (set-window-configuration org-window-configuration)
10824 (select-window (get-buffer-window (marker-buffer pos)))
10825 (goto-char pos)
10826 (unless (org-at-table-p)
10827 (error "Lost table position - cannot install formulae"))
10828 (org-table-store-formulas eql)
10829 (move-marker pos nil)
10830 (kill-buffer "*Edit Formulas*")
10831 (if arg
10832 (org-table-recalculate 'all)
10833 (message "New formulas installed - press C-u C-c C-c to apply."))))
10835 (defun org-table-fedit-abort ()
10836 "Abort editing formulas, without installing the changes."
10837 (interactive)
10838 (org-table-remove-rectangle-highlight)
10839 (let ((pos org-pos))
10840 (set-window-configuration org-window-configuration)
10841 (select-window (get-buffer-window (marker-buffer pos)))
10842 (goto-char pos)
10843 (move-marker pos nil)
10844 (message "Formula editing aborted without installing changes")))
10846 (defun org-table-fedit-lisp-indent ()
10847 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10848 (interactive)
10849 (let ((pos (point)) beg end ind)
10850 (beginning-of-line 1)
10851 (cond
10852 ((looking-at "[ \t]")
10853 (goto-char pos)
10854 (call-interactively 'lisp-indent-line))
10855 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10856 ((not (fboundp 'pp-buffer))
10857 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10858 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10859 (goto-char (- (match-end 0) 2))
10860 (setq beg (point))
10861 (setq ind (make-string (current-column) ?\ ))
10862 (condition-case nil (forward-sexp 1)
10863 (error
10864 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10865 (setq end (point))
10866 (save-restriction
10867 (narrow-to-region beg end)
10868 (if (eq last-command this-command)
10869 (progn
10870 (goto-char (point-min))
10871 (setq this-command nil)
10872 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10873 (replace-match " ")))
10874 (pp-buffer)
10875 (untabify (point-min) (point-max))
10876 (goto-char (1+ (point-min)))
10877 (while (re-search-forward "^." nil t)
10878 (beginning-of-line 1)
10879 (insert ind))
10880 (goto-char (point-max))
10881 (backward-delete-char 1)))
10882 (goto-char beg))
10883 (t nil))))
10885 (defvar org-show-positions nil)
10887 (defun org-table-show-reference (&optional local)
10888 "Show the location/value of the $ expression at point."
10889 (interactive)
10890 (org-table-remove-rectangle-highlight)
10891 (catch 'exit
10892 (let ((pos (if local (point) org-pos))
10893 (face2 'highlight)
10894 (org-inhibit-highlight-removal t)
10895 (win (selected-window))
10896 (org-show-positions nil)
10897 var name e what match dest)
10898 (if local (org-table-get-specials))
10899 (setq what (cond
10900 ((or (org-at-regexp-p org-table-range-regexp2)
10901 (org-at-regexp-p org-table-translate-regexp)
10902 (org-at-regexp-p org-table-range-regexp))
10903 (setq match
10904 (save-match-data
10905 (org-table-convert-refs-to-rc (match-string 0))))
10906 'range)
10907 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10908 ((org-at-regexp-p "\\$[0-9]+") 'column)
10909 ((not local) nil)
10910 (t (error "No reference at point")))
10911 match (and what (or match (match-string 0))))
10912 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10913 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10914 'secondary-selection))
10915 (org-add-hook 'before-change-functions
10916 'org-table-remove-rectangle-highlight)
10917 (if (eq what 'name) (setq var (substring match 1)))
10918 (when (eq what 'range)
10919 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10920 (setq match (org-table-formula-substitute-names match)))
10921 (unless local
10922 (save-excursion
10923 (end-of-line 1)
10924 (re-search-backward "^\\S-" nil t)
10925 (beginning-of-line 1)
10926 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10927 (setq dest
10928 (save-match-data
10929 (org-table-convert-refs-to-rc (match-string 1))))
10930 (org-table-add-rectangle-overlay
10931 (match-beginning 1) (match-end 1) face2))))
10932 (if (and (markerp pos) (marker-buffer pos))
10933 (if (get-buffer-window (marker-buffer pos))
10934 (select-window (get-buffer-window (marker-buffer pos)))
10935 (org-switch-to-buffer-other-window (get-buffer-window
10936 (marker-buffer pos)))))
10937 (goto-char pos)
10938 (org-table-force-dataline)
10939 (when dest
10940 (setq name (substring dest 1))
10941 (cond
10942 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10943 (setq e (assoc name org-table-named-field-locations))
10944 (goto-line (nth 1 e))
10945 (org-table-goto-column (nth 2 e)))
10946 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10947 (let ((l (string-to-number (match-string 1 dest)))
10948 (c (string-to-number (match-string 2 dest))))
10949 (goto-line (aref org-table-dlines l))
10950 (org-table-goto-column c)))
10951 (t (org-table-goto-column (string-to-number name))))
10952 (move-marker pos (point))
10953 (org-table-highlight-rectangle nil nil face2))
10954 (cond
10955 ((equal dest match))
10956 ((not match))
10957 ((eq what 'range)
10958 (condition-case nil
10959 (save-excursion
10960 (org-table-get-range match nil nil 'highlight))
10961 (error nil)))
10962 ((setq e (assoc var org-table-named-field-locations))
10963 (goto-line (nth 1 e))
10964 (org-table-goto-column (nth 2 e))
10965 (org-table-highlight-rectangle (point) (point))
10966 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10967 ((setq e (assoc var org-table-column-names))
10968 (org-table-goto-column (string-to-number (cdr e)))
10969 (org-table-highlight-rectangle (point) (point))
10970 (goto-char (org-table-begin))
10971 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10972 (org-table-end) t)
10973 (progn
10974 (goto-char (match-beginning 1))
10975 (org-table-highlight-rectangle)
10976 (message "Named column (column %s)" (cdr e)))
10977 (error "Column name not found")))
10978 ((eq what 'column)
10979 ;; column number
10980 (org-table-goto-column (string-to-number (substring match 1)))
10981 (org-table-highlight-rectangle (point) (point))
10982 (message "Column %s" (substring match 1)))
10983 ((setq e (assoc var org-table-local-parameters))
10984 (goto-char (org-table-begin))
10985 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10986 (progn
10987 (goto-char (match-beginning 1))
10988 (org-table-highlight-rectangle)
10989 (message "Local parameter."))
10990 (error "Parameter not found")))
10992 (cond
10993 ((not var) (error "No reference at point"))
10994 ((setq e (assoc var org-table-formula-constants-local))
10995 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10996 var (cdr e)))
10997 ((setq e (assoc var org-table-formula-constants))
10998 (message "Constant: $%s=%s in `org-table-formula-constants'."
10999 var (cdr e)))
11000 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11001 (message "Constant: $%s=%s, from `constants.el'%s."
11002 var e (format " (%s units)" constants-unit-system)))
11003 (t (error "Undefined name $%s" var)))))
11004 (goto-char pos)
11005 (when (and org-show-positions
11006 (not (memq this-command '(org-table-fedit-scroll
11007 org-table-fedit-scroll-down))))
11008 (push pos org-show-positions)
11009 (push org-table-current-begin-pos org-show-positions)
11010 (let ((min (apply 'min org-show-positions))
11011 (max (apply 'max org-show-positions)))
11012 (goto-char min) (recenter 0)
11013 (goto-char max)
11014 (or (pos-visible-in-window-p max) (recenter -1))))
11015 (select-window win))))
11017 (defun org-table-force-dataline ()
11018 "Make sure the cursor is in a dataline in a table."
11019 (unless (save-excursion
11020 (beginning-of-line 1)
11021 (looking-at org-table-dataline-regexp))
11022 (let* ((re org-table-dataline-regexp)
11023 (p1 (save-excursion (re-search-forward re nil 'move)))
11024 (p2 (save-excursion (re-search-backward re nil 'move))))
11025 (cond ((and p1 p2)
11026 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11027 p1 p2)))
11028 ((or p1 p2) (goto-char (or p1 p2)))
11029 (t (error "No table dataline around here"))))))
11031 (defun org-table-fedit-line-up ()
11032 "Move cursor one line up in the window showing the table."
11033 (interactive)
11034 (org-table-fedit-move 'previous-line))
11036 (defun org-table-fedit-line-down ()
11037 "Move cursor one line down in the window showing the table."
11038 (interactive)
11039 (org-table-fedit-move 'next-line))
11041 (defun org-table-fedit-move (command)
11042 "Move the cursor in the window shoinw the table.
11043 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11044 (let ((org-table-allow-automatic-line-recalculation nil)
11045 (pos org-pos) (win (selected-window)) p)
11046 (select-window (get-buffer-window (marker-buffer org-pos)))
11047 (setq p (point))
11048 (call-interactively command)
11049 (while (and (org-at-table-p)
11050 (org-at-table-hline-p))
11051 (call-interactively command))
11052 (or (org-at-table-p) (goto-char p))
11053 (move-marker pos (point))
11054 (select-window win)))
11056 (defun org-table-fedit-scroll (N)
11057 (interactive "p")
11058 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11059 (scroll-other-window N)))
11061 (defun org-table-fedit-scroll-down (N)
11062 (interactive "p")
11063 (org-table-fedit-scroll (- N)))
11065 (defvar org-table-rectangle-overlays nil)
11067 (defun org-table-add-rectangle-overlay (beg end &optional face)
11068 "Add a new overlay."
11069 (let ((ov (org-make-overlay beg end)))
11070 (org-overlay-put ov 'face (or face 'secondary-selection))
11071 (push ov org-table-rectangle-overlays)))
11073 (defun org-table-highlight-rectangle (&optional beg end face)
11074 "Highlight rectangular region in a table."
11075 (setq beg (or beg (point)) end (or end (point)))
11076 (let ((b (min beg end))
11077 (e (max beg end))
11078 l1 c1 l2 c2 tmp)
11079 (and (boundp 'org-show-positions)
11080 (setq org-show-positions (cons b (cons e org-show-positions))))
11081 (goto-char (min beg end))
11082 (setq l1 (org-current-line)
11083 c1 (org-table-current-column))
11084 (goto-char (max beg end))
11085 (setq l2 (org-current-line)
11086 c2 (org-table-current-column))
11087 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11088 (goto-line l1)
11089 (beginning-of-line 1)
11090 (loop for line from l1 to l2 do
11091 (when (looking-at org-table-dataline-regexp)
11092 (org-table-goto-column c1)
11093 (skip-chars-backward "^|\n") (setq beg (point))
11094 (org-table-goto-column c2)
11095 (skip-chars-forward "^|\n") (setq end (point))
11096 (org-table-add-rectangle-overlay beg end face))
11097 (beginning-of-line 2))
11098 (goto-char b))
11099 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11101 (defun org-table-remove-rectangle-highlight (&rest ignore)
11102 "Remove the rectangle overlays."
11103 (unless org-inhibit-highlight-removal
11104 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11105 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11106 (setq org-table-rectangle-overlays nil)))
11108 (defvar org-table-coordinate-overlays nil
11109 "Collects the cooordinate grid overlays, so that they can be removed.")
11110 (make-variable-buffer-local 'org-table-coordinate-overlays)
11112 (defun org-table-overlay-coordinates ()
11113 "Add overlays to the table at point, to show row/column coordinates."
11114 (interactive)
11115 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11116 (setq org-table-coordinate-overlays nil)
11117 (save-excursion
11118 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11119 (goto-char (org-table-begin))
11120 (while (org-at-table-p)
11121 (setq eol (point-at-eol))
11122 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11123 (push ov org-table-coordinate-overlays)
11124 (setq hline (looking-at org-table-hline-regexp))
11125 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11126 (format "%4d" (setq id (1+ id)))))
11127 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11128 (when hline
11129 (setq ic 0)
11130 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11131 (setq beg (1+ (match-beginning 0))
11132 ic (1+ ic)
11133 s1 (concat "$" (int-to-string ic))
11134 s2 (org-number-to-letters ic)
11135 str (if (eq org-table-use-standard-references t) s2 s1))
11136 (setq ov (org-make-overlay beg (+ beg (length str))))
11137 (push ov org-table-coordinate-overlays)
11138 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11139 (beginning-of-line 2)))))
11141 (defun org-table-toggle-coordinate-overlays ()
11142 "Toggle the display of Row/Column numbers in tables."
11143 (interactive)
11144 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11145 (message "Row/Column number display turned %s"
11146 (if org-table-overlay-coordinates "on" "off"))
11147 (if (and (org-at-table-p) org-table-overlay-coordinates)
11148 (org-table-align))
11149 (unless org-table-overlay-coordinates
11150 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11151 (setq org-table-coordinate-overlays nil)))
11153 (defun org-table-toggle-formula-debugger ()
11154 "Toggle the formula debugger in tables."
11155 (interactive)
11156 (setq org-table-formula-debug (not org-table-formula-debug))
11157 (message "Formula debugging has been turned %s"
11158 (if org-table-formula-debug "on" "off")))
11160 ;;; The orgtbl minor mode
11162 ;; Define a minor mode which can be used in other modes in order to
11163 ;; integrate the org-mode table editor.
11165 ;; This is really a hack, because the org-mode table editor uses several
11166 ;; keys which normally belong to the major mode, for example the TAB and
11167 ;; RET keys. Here is how it works: The minor mode defines all the keys
11168 ;; necessary to operate the table editor, but wraps the commands into a
11169 ;; function which tests if the cursor is currently inside a table. If that
11170 ;; is the case, the table editor command is executed. However, when any of
11171 ;; those keys is used outside a table, the function uses `key-binding' to
11172 ;; look up if the key has an associated command in another currently active
11173 ;; keymap (minor modes, major mode, global), and executes that command.
11174 ;; There might be problems if any of the keys used by the table editor is
11175 ;; otherwise used as a prefix key.
11177 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11178 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11179 ;; addresses this by checking explicitly for both bindings.
11181 ;; The optimized version (see variable `orgtbl-optimized') takes over
11182 ;; all keys which are bound to `self-insert-command' in the *global map*.
11183 ;; Some modes bind other commands to simple characters, for example
11184 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11185 ;; active, this binding is ignored inside tables and replaced with a
11186 ;; modified self-insert.
11188 (defvar orgtbl-mode nil
11189 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11190 table editor in arbitrary modes.")
11191 (make-variable-buffer-local 'orgtbl-mode)
11193 (defvar orgtbl-mode-map (make-keymap)
11194 "Keymap for `orgtbl-mode'.")
11196 ;;;###autoload
11197 (defun turn-on-orgtbl ()
11198 "Unconditionally turn on `orgtbl-mode'."
11199 (orgtbl-mode 1))
11201 (defvar org-old-auto-fill-inhibit-regexp nil
11202 "Local variable used by `orgtbl-mode'")
11204 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11205 "Matches a line belonging to an orgtbl.")
11207 (defconst orgtbl-extra-font-lock-keywords
11208 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11209 0 (quote 'org-table) 'prepend))
11210 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11212 ;;;###autoload
11213 (defun orgtbl-mode (&optional arg)
11214 "The `org-mode' table editor as a minor mode for use in other modes."
11215 (interactive)
11216 (if (org-mode-p)
11217 ;; Exit without error, in case some hook functions calls this
11218 ;; by accident in org-mode.
11219 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11220 (setq orgtbl-mode
11221 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11222 (if orgtbl-mode
11223 (progn
11224 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11225 ;; Make sure we are first in minor-mode-map-alist
11226 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11227 (and c (setq minor-mode-map-alist
11228 (cons c (delq c minor-mode-map-alist)))))
11229 (org-set-local (quote org-table-may-need-update) t)
11230 (org-add-hook 'before-change-functions 'org-before-change-function
11231 nil 'local)
11232 (org-set-local 'org-old-auto-fill-inhibit-regexp
11233 auto-fill-inhibit-regexp)
11234 (org-set-local 'auto-fill-inhibit-regexp
11235 (if auto-fill-inhibit-regexp
11236 (concat orgtbl-line-start-regexp "\\|"
11237 auto-fill-inhibit-regexp)
11238 orgtbl-line-start-regexp))
11239 (org-add-to-invisibility-spec '(org-cwidth))
11240 (when (fboundp 'font-lock-add-keywords)
11241 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11242 (org-restart-font-lock))
11243 (easy-menu-add orgtbl-mode-menu)
11244 (run-hooks 'orgtbl-mode-hook))
11245 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11246 (org-cleanup-narrow-column-properties)
11247 (org-remove-from-invisibility-spec '(org-cwidth))
11248 (remove-hook 'before-change-functions 'org-before-change-function t)
11249 (when (fboundp 'font-lock-remove-keywords)
11250 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11251 (org-restart-font-lock))
11252 (easy-menu-remove orgtbl-mode-menu)
11253 (force-mode-line-update 'all))))
11255 (defun org-cleanup-narrow-column-properties ()
11256 "Remove all properties related to narrow-column invisibility."
11257 (let ((s 1))
11258 (while (setq s (text-property-any s (point-max)
11259 'display org-narrow-column-arrow))
11260 (remove-text-properties s (1+ s) '(display t)))
11261 (setq s 1)
11262 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11263 (remove-text-properties s (1+ s) '(org-cwidth t)))
11264 (setq s 1)
11265 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11266 (remove-text-properties s (1+ s) '(invisible t)))))
11268 ;; Install it as a minor mode.
11269 (put 'orgtbl-mode :included t)
11270 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11271 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11273 (defun orgtbl-make-binding (fun n &rest keys)
11274 "Create a function for binding in the table minor mode.
11275 FUN is the command to call inside a table. N is used to create a unique
11276 command name. KEYS are keys that should be checked in for a command
11277 to execute outside of tables."
11278 (eval
11279 (list 'defun
11280 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11281 '(arg)
11282 (concat "In tables, run `" (symbol-name fun) "'.\n"
11283 "Outside of tables, run the binding of `"
11284 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11285 "'.")
11286 '(interactive "p")
11287 (list 'if
11288 '(org-at-table-p)
11289 (list 'call-interactively (list 'quote fun))
11290 (list 'let '(orgtbl-mode)
11291 (list 'call-interactively
11292 (append '(or)
11293 (mapcar (lambda (k)
11294 (list 'key-binding k))
11295 keys)
11296 '('orgtbl-error))))))))
11298 (defun orgtbl-error ()
11299 "Error when there is no default binding for a table key."
11300 (interactive)
11301 (error "This key has no function outside tables"))
11303 (defun orgtbl-setup ()
11304 "Setup orgtbl keymaps."
11305 (let ((nfunc 0)
11306 (bindings
11307 (list
11308 '([(meta shift left)] org-table-delete-column)
11309 '([(meta left)] org-table-move-column-left)
11310 '([(meta right)] org-table-move-column-right)
11311 '([(meta shift right)] org-table-insert-column)
11312 '([(meta shift up)] org-table-kill-row)
11313 '([(meta shift down)] org-table-insert-row)
11314 '([(meta up)] org-table-move-row-up)
11315 '([(meta down)] org-table-move-row-down)
11316 '("\C-c\C-w" org-table-cut-region)
11317 '("\C-c\M-w" org-table-copy-region)
11318 '("\C-c\C-y" org-table-paste-rectangle)
11319 '("\C-c-" org-table-insert-hline)
11320 '("\C-c}" org-table-toggle-coordinate-overlays)
11321 '("\C-c{" org-table-toggle-formula-debugger)
11322 '("\C-m" org-table-next-row)
11323 '([(shift return)] org-table-copy-down)
11324 '("\C-c\C-q" org-table-wrap-region)
11325 '("\C-c?" org-table-field-info)
11326 '("\C-c " org-table-blank-field)
11327 '("\C-c+" org-table-sum)
11328 '("\C-c=" org-table-eval-formula)
11329 '("\C-c'" org-table-edit-formulas)
11330 '("\C-c`" org-table-edit-field)
11331 '("\C-c*" org-table-recalculate)
11332 '("\C-c|" org-table-create-or-convert-from-region)
11333 '("\C-c^" org-table-sort-lines)
11334 '([(control ?#)] org-table-rotate-recalc-marks)))
11335 elt key fun cmd)
11336 (while (setq elt (pop bindings))
11337 (setq nfunc (1+ nfunc))
11338 (setq key (org-key (car elt))
11339 fun (nth 1 elt)
11340 cmd (orgtbl-make-binding fun nfunc key))
11341 (org-defkey orgtbl-mode-map key cmd))
11343 ;; Special treatment needed for TAB and RET
11344 (org-defkey orgtbl-mode-map [(return)]
11345 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11346 (org-defkey orgtbl-mode-map "\C-m"
11347 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11349 (org-defkey orgtbl-mode-map [(tab)]
11350 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11351 (org-defkey orgtbl-mode-map "\C-i"
11352 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11354 (org-defkey orgtbl-mode-map [(shift tab)]
11355 (orgtbl-make-binding 'org-table-previous-field 104
11356 [(shift tab)] [(tab)] "\C-i"))
11358 (org-defkey orgtbl-mode-map "\M-\C-m"
11359 (orgtbl-make-binding 'org-table-wrap-region 105
11360 "\M-\C-m" [(meta return)]))
11361 (org-defkey orgtbl-mode-map [(meta return)]
11362 (orgtbl-make-binding 'org-table-wrap-region 106
11363 [(meta return)] "\M-\C-m"))
11365 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11366 (when orgtbl-optimized
11367 ;; If the user wants maximum table support, we need to hijack
11368 ;; some standard editing functions
11369 (org-remap orgtbl-mode-map
11370 'self-insert-command 'orgtbl-self-insert-command
11371 'delete-char 'org-delete-char
11372 'delete-backward-char 'org-delete-backward-char)
11373 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11374 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11375 '("OrgTbl"
11376 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11377 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11378 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11379 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11380 "--"
11381 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11382 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11383 ["Copy Field from Above"
11384 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11385 "--"
11386 ("Column"
11387 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11388 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11389 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11390 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11391 ("Row"
11392 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11393 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11394 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11395 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11396 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11397 "--"
11398 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11399 ("Rectangle"
11400 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11401 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11402 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11403 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11404 "--"
11405 ("Radio tables"
11406 ["Insert table template" orgtbl-insert-radio-table
11407 (assq major-mode orgtbl-radio-table-templates)]
11408 ["Comment/uncomment table" orgtbl-toggle-comment t])
11409 "--"
11410 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11411 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11412 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11413 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11414 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11415 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11416 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11417 ["Sum Column/Rectangle" org-table-sum
11418 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11419 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11420 ["Debug Formulas"
11421 org-table-toggle-formula-debugger :active (org-at-table-p)
11422 :keys "C-c {"
11423 :style toggle :selected org-table-formula-debug]
11424 ["Show Col/Row Numbers"
11425 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11426 :keys "C-c }"
11427 :style toggle :selected org-table-overlay-coordinates]
11431 (defun orgtbl-ctrl-c-ctrl-c (arg)
11432 "If the cursor is inside a table, realign the table.
11433 It it is a table to be sent away to a receiver, do it.
11434 With prefix arg, also recompute table."
11435 (interactive "P")
11436 (let ((pos (point)) action)
11437 (save-excursion
11438 (beginning-of-line 1)
11439 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11440 ((looking-at "[ \t]*|") pos)
11441 ((looking-at "#\\+TBLFM:") 'recalc))))
11442 (cond
11443 ((integerp action)
11444 (goto-char action)
11445 (org-table-maybe-eval-formula)
11446 (if arg
11447 (call-interactively 'org-table-recalculate)
11448 (org-table-maybe-recalculate-line))
11449 (call-interactively 'org-table-align)
11450 (orgtbl-send-table 'maybe))
11451 ((eq action 'recalc)
11452 (save-excursion
11453 (beginning-of-line 1)
11454 (skip-chars-backward " \r\n\t")
11455 (if (org-at-table-p)
11456 (org-call-with-arg 'org-table-recalculate t))))
11457 (t (let (orgtbl-mode)
11458 (call-interactively (key-binding "\C-c\C-c")))))))
11460 (defun orgtbl-tab (arg)
11461 "Justification and field motion for `orgtbl-mode'."
11462 (interactive "P")
11463 (if arg (org-table-edit-field t)
11464 (org-table-justify-field-maybe)
11465 (org-table-next-field)))
11467 (defun orgtbl-ret ()
11468 "Justification and field motion for `orgtbl-mode'."
11469 (interactive)
11470 (org-table-justify-field-maybe)
11471 (org-table-next-row))
11473 (defun orgtbl-self-insert-command (N)
11474 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11475 If the cursor is in a table looking at whitespace, the whitespace is
11476 overwritten, and the table is not marked as requiring realignment."
11477 (interactive "p")
11478 (if (and (org-at-table-p)
11480 (and org-table-auto-blank-field
11481 (member last-command
11482 '(orgtbl-hijacker-command-100
11483 orgtbl-hijacker-command-101
11484 orgtbl-hijacker-command-102
11485 orgtbl-hijacker-command-103
11486 orgtbl-hijacker-command-104
11487 orgtbl-hijacker-command-105))
11488 (org-table-blank-field))
11490 (eq N 1)
11491 (looking-at "[^|\n]* +|"))
11492 (let (org-table-may-need-update)
11493 (goto-char (1- (match-end 0)))
11494 (delete-backward-char 1)
11495 (goto-char (match-beginning 0))
11496 (self-insert-command N))
11497 (setq org-table-may-need-update t)
11498 (let (orgtbl-mode)
11499 (call-interactively (key-binding (vector last-input-event))))))
11501 (defun org-force-self-insert (N)
11502 "Needed to enforce self-insert under remapping."
11503 (interactive "p")
11504 (self-insert-command N))
11506 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11507 "Regula expression matching exponentials as produced by calc.")
11509 (defvar org-table-clean-did-remove-column nil)
11511 (defun orgtbl-export (table target)
11512 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11513 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11514 org-table-last-alignment org-table-last-column-widths
11515 maxcol column)
11516 (if (not (fboundp func))
11517 (error "Cannot export orgtbl table to %s" target))
11518 (setq lines (org-table-clean-before-export lines))
11519 (setq table
11520 (mapcar
11521 (lambda (x)
11522 (if (string-match org-table-hline-regexp x)
11523 'hline
11524 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11525 lines))
11526 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11527 table)))
11528 (loop for i from (1- maxcol) downto 0 do
11529 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11530 (setq column (delq nil column))
11531 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11532 (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))
11533 (funcall func table nil)))
11535 (defun orgtbl-send-table (&optional maybe)
11536 "Send a tranformed version of this table to the receiver position.
11537 With argument MAYBE, fail quietly if no transformation is defined for
11538 this table."
11539 (interactive)
11540 (catch 'exit
11541 (unless (org-at-table-p) (error "Not at a table"))
11542 ;; when non-interactive, we assume align has just happened.
11543 (when (interactive-p) (org-table-align))
11544 (save-excursion
11545 (goto-char (org-table-begin))
11546 (beginning-of-line 0)
11547 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11548 (if maybe
11549 (throw 'exit nil)
11550 (error "Don't know how to transform this table."))))
11551 (let* ((name (match-string 1))
11553 (transform (intern (match-string 2)))
11554 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11555 (skip (plist-get params :skip))
11556 (skipcols (plist-get params :skipcols))
11557 (txt (buffer-substring-no-properties
11558 (org-table-begin) (org-table-end)))
11559 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11560 (lines (org-table-clean-before-export lines))
11561 (i0 (if org-table-clean-did-remove-column 2 1))
11562 (table (mapcar
11563 (lambda (x)
11564 (if (string-match org-table-hline-regexp x)
11565 'hline
11566 (org-remove-by-index
11567 (org-split-string (org-trim x) "\\s-*|\\s-*")
11568 skipcols i0)))
11569 lines))
11570 (fun (if (= i0 2) 'cdr 'identity))
11571 (org-table-last-alignment
11572 (org-remove-by-index (funcall fun org-table-last-alignment)
11573 skipcols i0))
11574 (org-table-last-column-widths
11575 (org-remove-by-index (funcall fun org-table-last-column-widths)
11576 skipcols i0)))
11578 (unless (fboundp transform)
11579 (error "No such transformation function %s" transform))
11580 (setq txt (funcall transform table params))
11581 ;; Find the insertion place
11582 (save-excursion
11583 (goto-char (point-min))
11584 (unless (re-search-forward
11585 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11586 (error "Don't know where to insert translated table"))
11587 (goto-char (match-beginning 0))
11588 (beginning-of-line 2)
11589 (setq beg (point))
11590 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11591 (error "Cannot find end of insertion region"))
11592 (beginning-of-line 1)
11593 (delete-region beg (point))
11594 (goto-char beg)
11595 (insert txt "\n"))
11596 (message "Table converted and installed at receiver location"))))
11598 (defun org-remove-by-index (list indices &optional i0)
11599 "Remove the elements in LIST with indices in INDICES.
11600 First element has index 0, or I0 if given."
11601 (if (not indices)
11602 list
11603 (if (integerp indices) (setq indices (list indices)))
11604 (setq i0 (1- (or i0 0)))
11605 (delq :rm (mapcar (lambda (x)
11606 (setq i0 (1+ i0))
11607 (if (memq i0 indices) :rm x))
11608 list))))
11610 (defun orgtbl-toggle-comment ()
11611 "Comment or uncomment the orgtbl at point."
11612 (interactive)
11613 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11614 (re2 (concat "^" orgtbl-line-start-regexp))
11615 (commented (save-excursion (beginning-of-line 1)
11616 (cond ((looking-at re1) t)
11617 ((looking-at re2) nil)
11618 (t (error "Not at an org table")))))
11619 (re (if commented re1 re2))
11620 beg end)
11621 (save-excursion
11622 (beginning-of-line 1)
11623 (while (looking-at re) (beginning-of-line 0))
11624 (beginning-of-line 2)
11625 (setq beg (point))
11626 (while (looking-at re) (beginning-of-line 2))
11627 (setq end (point)))
11628 (comment-region beg end (if commented '(4) nil))))
11630 (defun orgtbl-insert-radio-table ()
11631 "Insert a radio table template appropriate for this major mode."
11632 (interactive)
11633 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11634 (txt (nth 1 e))
11635 name pos)
11636 (unless e (error "No radio table setup defined for %s" major-mode))
11637 (setq name (read-string "Table name: "))
11638 (while (string-match "%n" txt)
11639 (setq txt (replace-match name t t txt)))
11640 (or (bolp) (insert "\n"))
11641 (setq pos (point))
11642 (insert txt)
11643 (goto-char pos)))
11645 (defun org-get-param (params header i sym &optional hsym)
11646 "Get parameter value for symbol SYM.
11647 If this is a header line, actually get the value for the symbol with an
11648 additional \"h\" inserted after the colon.
11649 If the value is a protperty list, get the element for the current column.
11650 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11651 (let ((val (plist-get params sym)))
11652 (and hsym header (setq val (or (plist-get params hsym) val)))
11653 (if (consp val) (plist-get val i) val)))
11655 (defun orgtbl-to-generic (table params)
11656 "Convert the orgtbl-mode TABLE to some other format.
11657 This generic routine can be used for many standard cases.
11658 TABLE is a list, each entry either the symbol `hline' for a horizontal
11659 separator line, or a list of fields for that line.
11660 PARAMS is a property list of parameters that can influence the conversion.
11661 For the generic converter, some parameters are obligatory: You need to
11662 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11663 :splice, you must have :tstart and :tend.
11665 Valid parameters are
11667 :tstart String to start the table. Ignored when :splice is t.
11668 :tend String to end the table. Ignored when :splice is t.
11670 :splice When set to t, return only table body lines, don't wrap
11671 them into :tstart and :tend. Default is nil.
11673 :hline String to be inserted on horizontal separation lines.
11674 May be nil to ignore hlines.
11676 :lstart String to start a new table line.
11677 :lend String to end a table line
11678 :sep Separator between two fields
11679 :lfmt Format for entire line, with enough %s to capture all fields.
11680 If this is present, :lstart, :lend, and :sep are ignored.
11681 :fmt A format to be used to wrap the field, should contain
11682 %s for the original field value. For example, to wrap
11683 everything in dollars, you could use :fmt \"$%s$\".
11684 This may also be a property list with column numbers and
11685 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11687 :hlstart :hlend :hlsep :hlfmt :hfmt
11688 Same as above, specific for the header lines in the table.
11689 All lines before the first hline are treated as header.
11690 If any of these is not present, the data line value is used.
11692 :efmt Use this format to print numbers with exponentials.
11693 The format should have %s twice for inserting mantissa
11694 and exponent, for example \"%s\\\\times10^{%s}\". This
11695 may also be a property list with column numbers and
11696 formats. :fmt will still be applied after :efmt.
11698 In addition to this, the parameters :skip and :skipcols are always handled
11699 directly by `orgtbl-send-table'. See manual."
11700 (interactive)
11701 (let* ((p params)
11702 (splicep (plist-get p :splice))
11703 (hline (plist-get p :hline))
11704 rtn line i fm efm lfmt h)
11706 ;; Do we have a header?
11707 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11708 (setq h t))
11710 ;; Put header
11711 (unless splicep
11712 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11714 ;; Now loop over all lines
11715 (while (setq line (pop table))
11716 (if (eq line 'hline)
11717 ;; A horizontal separator line
11718 (progn (if hline (push hline rtn))
11719 (setq h nil)) ; no longer in header
11720 ;; A normal line. Convert the fields, push line onto the result list
11721 (setq i 0)
11722 (setq line
11723 (mapcar
11724 (lambda (f)
11725 (setq i (1+ i)
11726 fm (org-get-param p h i :fmt :hfmt)
11727 efm (org-get-param p h i :efmt))
11728 (if (and efm (string-match orgtbl-exp-regexp f))
11729 (setq f (format
11730 efm (match-string 1 f) (match-string 2 f))))
11731 (if fm (setq f (format fm f)))
11733 line))
11734 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11735 (push (apply 'format lfmt line) rtn)
11736 (push (concat
11737 (org-get-param p h i :lstart :hlstart)
11738 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11739 (org-get-param p h i :lend :hlend))
11740 rtn))))
11742 (unless splicep
11743 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11745 (mapconcat 'identity (nreverse rtn) "\n")))
11747 (defun orgtbl-to-latex (table params)
11748 "Convert the orgtbl-mode TABLE to LaTeX.
11749 TABLE is a list, each entry either the symbol `hline' for a horizontal
11750 separator line, or a list of fields for that line.
11751 PARAMS is a property list of parameters that can influence the conversion.
11752 Supports all parameters from `orgtbl-to-generic'. Most important for
11753 LaTeX are:
11755 :splice When set to t, return only table body lines, don't wrap
11756 them into a tabular environment. Default is nil.
11758 :fmt A format to be used to wrap the field, should contain %s for the
11759 original field value. For example, to wrap everything in dollars,
11760 use :fmt \"$%s$\". This may also be a property list with column
11761 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11763 :efmt Format for transforming numbers with exponentials. The format
11764 should have %s twice for inserting mantissa and exponent, for
11765 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11766 This may also be a property list with column numbers and formats.
11768 The general parameters :skip and :skipcols have already been applied when
11769 this function is called."
11770 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11771 org-table-last-alignment ""))
11772 (params2
11773 (list
11774 :tstart (concat "\\begin{tabular}{" alignment "}")
11775 :tend "\\end{tabular}"
11776 :lstart "" :lend " \\\\" :sep " & "
11777 :efmt "%s\\,(%s)" :hline "\\hline")))
11778 (orgtbl-to-generic table (org-combine-plists params2 params))))
11780 (defun orgtbl-to-html (table params)
11781 "Convert the orgtbl-mode TABLE to LaTeX.
11782 TABLE is a list, each entry either the symbol `hline' for a horizontal
11783 separator line, or a list of fields for that line.
11784 PARAMS is a property list of parameters that can influence the conversion.
11785 Currently this function recognizes the following parameters:
11787 :splice When set to t, return only table body lines, don't wrap
11788 them into a <table> environment. Default is nil.
11790 The general parameters :skip and :skipcols have already been applied when
11791 this function is called. The function does *not* use `orgtbl-to-generic',
11792 so you cannot specify parameters for it."
11793 (let* ((splicep (plist-get params :splice))
11794 html)
11795 ;; Just call the formatter we already have
11796 ;; We need to make text lines for it, so put the fields back together.
11797 (setq html (org-format-org-table-html
11798 (mapcar
11799 (lambda (x)
11800 (if (eq x 'hline)
11801 "|----+----|"
11802 (concat "| " (mapconcat 'identity x " | ") " |")))
11803 table)
11804 splicep))
11805 (if (string-match "\n+\\'" html)
11806 (setq html (replace-match "" t t html)))
11807 html))
11809 (defun orgtbl-to-texinfo (table params)
11810 "Convert the orgtbl-mode TABLE to TeXInfo.
11811 TABLE is a list, each entry either the symbol `hline' for a horizontal
11812 separator line, or a list of fields for that line.
11813 PARAMS is a property list of parameters that can influence the conversion.
11814 Supports all parameters from `orgtbl-to-generic'. Most important for
11815 TeXInfo are:
11817 :splice nil/t When set to t, return only table body lines, don't wrap
11818 them into a multitable environment. Default is nil.
11820 :fmt fmt A format to be used to wrap the field, should contain
11821 %s for the original field value. For example, to wrap
11822 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11823 This may also be a property list with column numbers and
11824 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11826 :cf \"f1 f2..\" The column fractions for the table. By default these
11827 are computed automatically from the width of the columns
11828 under org-mode.
11830 The general parameters :skip and :skipcols have already been applied when
11831 this function is called."
11832 (let* ((total (float (apply '+ org-table-last-column-widths)))
11833 (colfrac (or (plist-get params :cf)
11834 (mapconcat
11835 (lambda (x) (format "%.3f" (/ (float x) total)))
11836 org-table-last-column-widths " ")))
11837 (params2
11838 (list
11839 :tstart (concat "@multitable @columnfractions " colfrac)
11840 :tend "@end multitable"
11841 :lstart "@item " :lend "" :sep " @tab "
11842 :hlstart "@headitem ")))
11843 (orgtbl-to-generic table (org-combine-plists params2 params))))
11845 ;;;; Link Stuff
11847 ;;; Link abbreviations
11849 (defun org-link-expand-abbrev (link)
11850 "Apply replacements as defined in `org-link-abbrev-alist."
11851 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11852 (let* ((key (match-string 1 link))
11853 (as (or (assoc key org-link-abbrev-alist-local)
11854 (assoc key org-link-abbrev-alist)))
11855 (tag (and (match-end 2) (match-string 3 link)))
11856 rpl)
11857 (if (not as)
11858 link
11859 (setq rpl (cdr as))
11860 (cond
11861 ((symbolp rpl) (funcall rpl tag))
11862 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11863 (t (concat rpl tag)))))
11864 link))
11866 ;;; Storing and inserting links
11868 (defvar org-insert-link-history nil
11869 "Minibuffer history for links inserted with `org-insert-link'.")
11871 (defvar org-stored-links nil
11872 "Contains the links stored with `org-store-link'.")
11874 (defvar org-store-link-plist nil
11875 "Plist with info about the most recently link created with `org-store-link'.")
11877 (defvar org-link-protocols nil
11878 "Link protocols added to Org-mode using `org-add-link-type'.")
11880 (defvar org-store-link-functions nil
11881 "List of functions that are called to create and store a link.
11882 Each function will be called in turn until one returns a non-nil
11883 value. Each function should check if it is responsible for creating
11884 this link (for example by looking at the major mode).
11885 If not, it must exit and return nil.
11886 If yes, it should return a non-nil value after a calling
11887 `org-store-link-props' with a list of properties and values.
11888 Special properties are:
11890 :type The link prefix. like \"http\". This must be given.
11891 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11892 This is obligatory as well.
11893 :description Optional default description for the second pair
11894 of brackets in an Org-mode link. The user can still change
11895 this when inserting this link into an Org-mode buffer.
11897 In addition to these, any additional properties can be specified
11898 and then used in remember templates.")
11900 (defun org-add-link-type (type &optional follow publish)
11901 "Add TYPE to the list of `org-link-types'.
11902 Re-compute all regular expressions depending on `org-link-types'
11903 FOLLOW and PUBLISH are two functions. Both take the link path as
11904 an argument.
11905 FOLLOW should do whatever is necessary to follow the link, for example
11906 to find a file or display a mail message.
11908 PUBLISH takes the path and retuns the string that should be used when
11909 this document is published. FIMXE: This is actually not yet implemented."
11910 (add-to-list 'org-link-types type t)
11911 (org-make-link-regexps)
11912 (add-to-list 'org-link-protocols
11913 (list type follow publish)))
11915 (defun org-add-agenda-custom-command (entry)
11916 "Replace or add a command in `org-agenda-custom-commands'.
11917 This is mostly for hacking and trying a new command - once the command
11918 works you probably want to add it to `org-agenda-custom-commands' for good."
11919 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11920 (if ass
11921 (setcdr ass (cdr entry))
11922 (push entry org-agenda-custom-commands))))
11924 ;;;###autoload
11925 (defun org-store-link (arg)
11926 "\\<org-mode-map>Store an org-link to the current location.
11927 This link is added to `org-stored-links' and can later be inserted
11928 into an org-buffer with \\[org-insert-link].
11930 For some link types, a prefix arg is interpreted:
11931 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11932 For file links, arg negates `org-context-in-file-links'."
11933 (interactive "P")
11934 (setq org-store-link-plist nil) ; reset
11935 (let (link cpltxt desc description search txt)
11936 (cond
11938 ((run-hook-with-args-until-success 'org-store-link-functions)
11939 (setq link (plist-get org-store-link-plist :link)
11940 desc (or (plist-get org-store-link-plist :description) link)))
11942 ((eq major-mode 'bbdb-mode)
11943 (let ((name (bbdb-record-name (bbdb-current-record)))
11944 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11945 (setq cpltxt (concat "bbdb:" (or name company))
11946 link (org-make-link cpltxt))
11947 (org-store-link-props :type "bbdb" :name name :company company)))
11949 ((eq major-mode 'Info-mode)
11950 (setq link (org-make-link "info:"
11951 (file-name-nondirectory Info-current-file)
11952 ":" Info-current-node))
11953 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11954 ":" Info-current-node))
11955 (org-store-link-props :type "info" :file Info-current-file
11956 :node Info-current-node))
11958 ((eq major-mode 'calendar-mode)
11959 (let ((cd (calendar-cursor-to-date)))
11960 (setq link
11961 (format-time-string
11962 (car org-time-stamp-formats)
11963 (apply 'encode-time
11964 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11965 nil nil nil))))
11966 (org-store-link-props :type "calendar" :date cd)))
11968 ((or (eq major-mode 'vm-summary-mode)
11969 (eq major-mode 'vm-presentation-mode))
11970 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11971 (vm-follow-summary-cursor)
11972 (save-excursion
11973 (vm-select-folder-buffer)
11974 (let* ((message (car vm-message-pointer))
11975 (folder buffer-file-name)
11976 (subject (vm-su-subject message))
11977 (to (vm-get-header-contents message "To"))
11978 (from (vm-get-header-contents message "From"))
11979 (message-id (vm-su-message-id message)))
11980 (org-store-link-props :type "vm" :from from :to to :subject subject
11981 :message-id message-id)
11982 (setq message-id (org-remove-angle-brackets message-id))
11983 (setq folder (abbreviate-file-name folder))
11984 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11985 folder)
11986 (setq folder (replace-match "" t t folder)))
11987 (setq cpltxt (org-email-link-description))
11988 (setq link (org-make-link "vm:" folder "#" message-id)))))
11990 ((eq major-mode 'wl-summary-mode)
11991 (let* ((msgnum (wl-summary-message-number))
11992 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11993 msgnum 'message-id))
11994 (wl-message-entity
11995 (if (fboundp 'elmo-message-entity)
11996 (elmo-message-entity
11997 wl-summary-buffer-elmo-folder msgnum)
11998 (elmo-msgdb-overview-get-entity
11999 msgnum (wl-summary-buffer-msgdb))))
12000 (from (wl-summary-line-from))
12001 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12002 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12003 (wl-summary-line-subject))))
12004 (org-store-link-props :type "wl" :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 "wl:" wl-summary-buffer-folder-name
12009 "#" message-id))))
12011 ((or (equal major-mode 'mh-folder-mode)
12012 (equal major-mode 'mh-show-mode))
12013 (let ((from (org-mhe-get-header "From:"))
12014 (to (org-mhe-get-header "To:"))
12015 (message-id (org-mhe-get-header "Message-Id:"))
12016 (subject (org-mhe-get-header "Subject:")))
12017 (org-store-link-props :type "mh" :from from :to to
12018 :subject subject :message-id message-id)
12019 (setq cpltxt (org-email-link-description))
12020 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12021 (org-remove-angle-brackets message-id)))))
12023 ((or (eq major-mode 'rmail-mode)
12024 (eq major-mode 'rmail-summary-mode))
12025 (save-window-excursion
12026 (save-restriction
12027 (when (eq major-mode 'rmail-summary-mode)
12028 (rmail-show-message rmail-current-message))
12029 (rmail-narrow-to-non-pruned-header)
12030 (let ((folder buffer-file-name)
12031 (message-id (mail-fetch-field "message-id"))
12032 (from (mail-fetch-field "from"))
12033 (to (mail-fetch-field "to"))
12034 (subject (mail-fetch-field "subject")))
12035 (org-store-link-props
12036 :type "rmail" :from from :to to
12037 :subject subject :message-id message-id)
12038 (setq message-id (org-remove-angle-brackets message-id))
12039 (setq cpltxt (org-email-link-description))
12040 (setq link (org-make-link "rmail:" folder "#" message-id)))
12041 (rmail-show-message rmail-current-message))))
12043 ((eq major-mode 'gnus-group-mode)
12044 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12045 (gnus-group-group-name)) ; version
12046 ((fboundp 'gnus-group-name)
12047 (gnus-group-name))
12048 (t "???"))))
12049 (unless group (error "Not on a group"))
12050 (org-store-link-props :type "gnus" :group group)
12051 (setq cpltxt (concat
12052 (if (org-xor arg org-usenet-links-prefer-google)
12053 "http://groups.google.com/groups?group="
12054 "gnus:")
12055 group)
12056 link (org-make-link cpltxt))))
12058 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12059 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12060 (let* ((group gnus-newsgroup-name)
12061 (article (gnus-summary-article-number))
12062 (header (gnus-summary-article-header article))
12063 (from (mail-header-from header))
12064 (message-id (mail-header-id header))
12065 (date (mail-header-date header))
12066 (subject (gnus-summary-subject-string)))
12067 (org-store-link-props :type "gnus" :from from :subject subject
12068 :message-id message-id :group group)
12069 (setq cpltxt (org-email-link-description))
12070 (if (org-xor arg org-usenet-links-prefer-google)
12071 (setq link
12072 (concat
12073 cpltxt "\n "
12074 (format "http://groups.google.com/groups?as_umsgid=%s"
12075 (org-fixup-message-id-for-http message-id))))
12076 (setq link (org-make-link "gnus:" group
12077 "#" (number-to-string article))))))
12079 ((eq major-mode 'w3-mode)
12080 (setq cpltxt (url-view-url t)
12081 link (org-make-link cpltxt))
12082 (org-store-link-props :type "w3" :url (url-view-url t)))
12084 ((eq major-mode 'w3m-mode)
12085 (setq cpltxt (or w3m-current-title w3m-current-url)
12086 link (org-make-link w3m-current-url))
12087 (org-store-link-props :type "w3m" :url (url-view-url t)))
12089 ((setq search (run-hook-with-args-until-success
12090 'org-create-file-search-functions))
12091 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12092 "::" search))
12093 (setq cpltxt (or description link)))
12095 ((eq major-mode 'image-mode)
12096 (setq cpltxt (concat "file:"
12097 (abbreviate-file-name buffer-file-name))
12098 link (org-make-link cpltxt))
12099 (org-store-link-props :type "image" :file buffer-file-name))
12101 ((eq major-mode 'dired-mode)
12102 ;; link to the file in the current line
12103 (setq cpltxt (concat "file:"
12104 (abbreviate-file-name
12105 (expand-file-name
12106 (dired-get-filename nil t))))
12107 link (org-make-link cpltxt)))
12109 ((and buffer-file-name (org-mode-p))
12110 ;; Just link to current headline
12111 (setq cpltxt (concat "file:"
12112 (abbreviate-file-name buffer-file-name)))
12113 ;; Add a context search string
12114 (when (org-xor org-context-in-file-links arg)
12115 ;; Check if we are on a target
12116 (if (org-in-regexp "<<\\(.*?\\)>>")
12117 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12118 (setq txt (cond
12119 ((org-on-heading-p) nil)
12120 ((org-region-active-p)
12121 (buffer-substring (region-beginning) (region-end)))
12122 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12123 (when (or (null txt) (string-match "\\S-" txt))
12124 (setq cpltxt
12125 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12126 desc "NONE"))))
12127 (if (string-match "::\\'" cpltxt)
12128 (setq cpltxt (substring cpltxt 0 -2)))
12129 (setq link (org-make-link cpltxt)))
12131 ((buffer-file-name (buffer-base-buffer))
12132 ;; Just link to this file here.
12133 (setq cpltxt (concat "file:"
12134 (abbreviate-file-name
12135 (buffer-file-name (buffer-base-buffer)))))
12136 ;; Add a context string
12137 (when (org-xor org-context-in-file-links arg)
12138 (setq txt (if (org-region-active-p)
12139 (buffer-substring (region-beginning) (region-end))
12140 (buffer-substring (point-at-bol) (point-at-eol))))
12141 ;; Only use search option if there is some text.
12142 (when (string-match "\\S-" txt)
12143 (setq cpltxt
12144 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12145 desc "NONE")))
12146 (setq link (org-make-link cpltxt)))
12148 ((interactive-p)
12149 (error "Cannot link to a buffer which is not visiting a file"))
12151 (t (setq link nil)))
12153 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12154 (setq link (or link cpltxt)
12155 desc (or desc cpltxt))
12156 (if (equal desc "NONE") (setq desc nil))
12158 (if (and (interactive-p) link)
12159 (progn
12160 (setq org-stored-links
12161 (cons (list link desc) org-stored-links))
12162 (message "Stored: %s" (or desc link)))
12163 (and link (org-make-link-string link desc)))))
12165 (defun org-store-link-props (&rest plist)
12166 "Store link properties, extract names and addresses."
12167 (let (x adr)
12168 (when (setq x (plist-get plist :from))
12169 (setq adr (mail-extract-address-components x))
12170 (plist-put plist :fromname (car adr))
12171 (plist-put plist :fromaddress (nth 1 adr)))
12172 (when (setq x (plist-get plist :to))
12173 (setq adr (mail-extract-address-components x))
12174 (plist-put plist :toname (car adr))
12175 (plist-put plist :toaddress (nth 1 adr))))
12176 (let ((from (plist-get plist :from))
12177 (to (plist-get plist :to)))
12178 (when (and from to org-from-is-user-regexp)
12179 (plist-put plist :fromto
12180 (if (string-match org-from-is-user-regexp from)
12181 (concat "to %t")
12182 (concat "from %f")))))
12183 (setq org-store-link-plist plist))
12185 (defun org-email-link-description (&optional fmt)
12186 "Return the description part of an email link.
12187 This takes information from `org-store-link-plist' and formats it
12188 according to FMT (default from `org-email-link-description-format')."
12189 (setq fmt (or fmt org-email-link-description-format))
12190 (let* ((p org-store-link-plist)
12191 (to (plist-get p :toaddress))
12192 (from (plist-get p :fromaddress))
12193 (table
12194 (list
12195 (cons "%c" (plist-get p :fromto))
12196 (cons "%F" (plist-get p :from))
12197 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12198 (cons "%T" (plist-get p :to))
12199 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12200 (cons "%s" (plist-get p :subject))
12201 (cons "%m" (plist-get p :message-id)))))
12202 (when (string-match "%c" fmt)
12203 ;; Check if the user wrote this message
12204 (if (and org-from-is-user-regexp from to
12205 (save-match-data (string-match org-from-is-user-regexp from)))
12206 (setq fmt (replace-match "to %t" t t fmt))
12207 (setq fmt (replace-match "from %f" t t fmt))))
12208 (org-replace-escapes fmt table)))
12210 (defun org-make-org-heading-search-string (&optional string heading)
12211 "Make search string for STRING or current headline."
12212 (interactive)
12213 (let ((s (or string (org-get-heading))))
12214 (unless (and string (not heading))
12215 ;; We are using a headline, clean up garbage in there.
12216 (if (string-match org-todo-regexp s)
12217 (setq s (replace-match "" t t s)))
12218 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12219 (setq s (replace-match "" t t s)))
12220 (setq s (org-trim s))
12221 (if (string-match (concat "^\\(" org-quote-string "\\|"
12222 org-comment-string "\\)") s)
12223 (setq s (replace-match "" t t s)))
12224 (while (string-match org-ts-regexp s)
12225 (setq s (replace-match "" t t s))))
12226 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12227 (setq s (replace-match " " t t s)))
12228 (or string (setq s (concat "*" s))) ; Add * for headlines
12229 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12231 (defun org-make-link (&rest strings)
12232 "Concatenate STRINGS."
12233 (apply 'concat strings))
12235 (defun org-make-link-string (link &optional description)
12236 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12237 (unless (string-match "\\S-" link)
12238 (error "Empty link"))
12239 (when (stringp description)
12240 ;; Remove brackets from the description, they are fatal.
12241 (while (string-match "\\[" description)
12242 (setq description (replace-match "{" t t description)))
12243 (while (string-match "\\]" description)
12244 (setq description (replace-match "}" t t description))))
12245 (when (equal (org-link-escape link) description)
12246 ;; No description needed, it is identical
12247 (setq description nil))
12248 (when (and (not description)
12249 (not (equal link (org-link-escape link))))
12250 (setq description link))
12251 (concat "[[" (org-link-escape link) "]"
12252 (if description (concat "[" description "]") "")
12253 "]"))
12255 (defconst org-link-escape-chars
12256 '((?\ . "%20")
12257 (?\[ . "%5B")
12258 (?\] . "%5D")
12259 (?\340 . "%E0") ; `a
12260 (?\342 . "%E2") ; ^a
12261 (?\347 . "%E7") ; ,c
12262 (?\350 . "%E8") ; `e
12263 (?\351 . "%E9") ; 'e
12264 (?\352 . "%EA") ; ^e
12265 (?\356 . "%EE") ; ^i
12266 (?\364 . "%F4") ; ^o
12267 (?\371 . "%F9") ; `u
12268 (?\373 . "%FB") ; ^u
12269 (?\; . "%3B")
12270 (?? . "%3F")
12271 (?= . "%3D")
12272 (?+ . "%2B")
12274 "Association list of escapes for some characters problematic in links.
12275 This is the list that is used for internal purposes.")
12277 (defconst org-link-escape-chars-browser
12278 '((?\ . "%20")) ; 32 for the SPC char
12279 "Association list of escapes for some characters problematic in links.
12280 This is the list that is used before handing over to the browser.")
12282 (defun org-link-escape (text &optional table)
12283 "Escape charaters in TEXT that are problematic for links."
12284 (setq table (or table org-link-escape-chars))
12285 (when text
12286 (let ((re (mapconcat (lambda (x) (regexp-quote
12287 (char-to-string (car x))))
12288 table "\\|")))
12289 (while (string-match re text)
12290 (setq text
12291 (replace-match
12292 (cdr (assoc (string-to-char (match-string 0 text))
12293 table))
12294 t t text)))
12295 text)))
12297 (defun org-link-unescape (text &optional table)
12298 "Reverse the action of `org-link-escape'."
12299 (setq table (or table org-link-escape-chars))
12300 (when text
12301 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12302 table "\\|")))
12303 (while (string-match re text)
12304 (setq text
12305 (replace-match
12306 (char-to-string (car (rassoc (match-string 0 text) table)))
12307 t t text)))
12308 text)))
12310 (defun org-xor (a b)
12311 "Exclusive or."
12312 (if a (not b) b))
12314 (defun org-get-header (header)
12315 "Find a header field in the current buffer."
12316 (save-excursion
12317 (goto-char (point-min))
12318 (let ((case-fold-search t) s)
12319 (cond
12320 ((eq header 'from)
12321 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12322 (setq s (match-string 1)))
12323 (while (string-match "\"" s)
12324 (setq s (replace-match "" t t s)))
12325 (if (string-match "[<(].*" s)
12326 (setq s (replace-match "" t t s))))
12327 ((eq header 'message-id)
12328 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12329 (setq s (match-string 1))))
12330 ((eq header 'subject)
12331 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12332 (setq s (match-string 1)))))
12333 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12334 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12335 s)))
12338 (defun org-fixup-message-id-for-http (s)
12339 "Replace special characters in a message id, so it can be used in an http query."
12340 (while (string-match "<" s)
12341 (setq s (replace-match "%3C" t t s)))
12342 (while (string-match ">" s)
12343 (setq s (replace-match "%3E" t t s)))
12344 (while (string-match "@" s)
12345 (setq s (replace-match "%40" t t s)))
12348 ;;;###autoload
12349 (defun org-insert-link-global ()
12350 "Insert a link like Org-mode does.
12351 This command can be called in any mode to insert a link in Org-mode syntax."
12352 (interactive)
12353 (org-run-like-in-org-mode 'org-insert-link))
12355 (defun org-insert-link (&optional complete-file)
12356 "Insert a link. At the prompt, enter the link.
12358 Completion can be used to select a link previously stored with
12359 `org-store-link'. When the empty string is entered (i.e. if you just
12360 press RET at the prompt), the link defaults to the most recently
12361 stored link. As SPC triggers completion in the minibuffer, you need to
12362 use M-SPC or C-q SPC to force the insertion of a space character.
12364 You will also be prompted for a description, and if one is given, it will
12365 be displayed in the buffer instead of the link.
12367 If there is already a link at point, this command will allow you to edit link
12368 and description parts.
12370 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12371 selected using completion. The path to the file will be relative to
12372 the current directory if the file is in the current directory or a
12373 subdirectory. Otherwise, the link will be the absolute path as
12374 completed in the minibuffer (i.e. normally ~/path/to/file).
12376 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12377 is in the current directory or below.
12378 With three \\[universal-argument] prefixes, negate the meaning of
12379 `org-keep-stored-link-after-insertion'."
12380 (interactive "P")
12381 (let* ((wcf (current-window-configuration))
12382 (region (if (org-region-active-p)
12383 (buffer-substring (region-beginning) (region-end))))
12384 (remove (and region (list (region-beginning) (region-end))))
12385 (desc region)
12386 tmphist ; byte-compile incorrectly complains about this
12387 link entry file)
12388 (cond
12389 ((org-in-regexp org-bracket-link-regexp 1)
12390 ;; We do have a link at point, and we are going to edit it.
12391 (setq remove (list (match-beginning 0) (match-end 0)))
12392 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12393 (setq link (read-string "Link: "
12394 (org-link-unescape
12395 (org-match-string-no-properties 1)))))
12396 ((or (org-in-regexp org-angle-link-re)
12397 (org-in-regexp org-plain-link-re))
12398 ;; Convert to bracket link
12399 (setq remove (list (match-beginning 0) (match-end 0))
12400 link (read-string "Link: "
12401 (org-remove-angle-brackets (match-string 0)))))
12402 ((equal complete-file '(4))
12403 ;; Completing read for file names.
12404 (setq file (read-file-name "File: "))
12405 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12406 (pwd1 (file-name-as-directory (abbreviate-file-name
12407 (expand-file-name ".")))))
12408 (cond
12409 ((equal complete-file '(16))
12410 (setq link (org-make-link
12411 "file:"
12412 (abbreviate-file-name (expand-file-name file)))))
12413 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12414 (setq link (org-make-link "file:" (match-string 1 file))))
12415 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12416 (expand-file-name file))
12417 (setq link (org-make-link
12418 "file:" (match-string 1 (expand-file-name file)))))
12419 (t (setq link (org-make-link "file:" file))))))
12421 ;; Read link, with completion for stored links.
12422 (with-output-to-temp-buffer "*Org Links*"
12423 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12424 (when org-stored-links
12425 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12426 (princ (mapconcat
12427 (lambda (x)
12428 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12429 (reverse org-stored-links) "\n"))))
12430 (let ((cw (selected-window)))
12431 (select-window (get-buffer-window "*Org Links*"))
12432 (shrink-window-if-larger-than-buffer)
12433 (setq truncate-lines t)
12434 (select-window cw))
12435 ;; Fake a link history, containing the stored links.
12436 (setq tmphist (append (mapcar 'car org-stored-links)
12437 org-insert-link-history))
12438 (unwind-protect
12439 (setq link (org-completing-read
12440 "Link: "
12441 (append
12442 (mapcar (lambda (x) (list (concat (car x) ":")))
12443 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12444 (mapcar (lambda (x) (list (concat x ":")))
12445 org-link-types))
12446 nil nil nil
12447 'tmphist
12448 (or (car (car org-stored-links)))))
12449 (set-window-configuration wcf)
12450 (kill-buffer "*Org Links*"))
12451 (setq entry (assoc link org-stored-links))
12452 (or entry (push link org-insert-link-history))
12453 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12454 (not org-keep-stored-link-after-insertion))
12455 (setq org-stored-links (delq (assoc link org-stored-links)
12456 org-stored-links)))
12457 (setq desc (or desc (nth 1 entry)))))
12459 (if (string-match org-plain-link-re link)
12460 ;; URL-like link, normalize the use of angular brackets.
12461 (setq link (org-make-link (org-remove-angle-brackets link))))
12463 ;; Check if we are linking to the current file with a search option
12464 ;; If yes, simplify the link by using only the search option.
12465 (when (and buffer-file-name
12466 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12467 (let* ((path (match-string 1 link))
12468 (case-fold-search nil)
12469 (search (match-string 2 link)))
12470 (save-match-data
12471 (if (equal (file-truename buffer-file-name) (file-truename path))
12472 ;; We are linking to this same file, with a search option
12473 (setq link search)))))
12475 ;; Check if we can/should use a relative path. If yes, simplify the link
12476 (when (string-match "\\<file:\\(.*\\)" link)
12477 (let* ((path (match-string 1 link))
12478 (origpath path)
12479 (case-fold-search nil))
12480 (cond
12481 ((eq org-link-file-path-type 'absolute)
12482 (setq path (abbreviate-file-name (expand-file-name path))))
12483 ((eq org-link-file-path-type 'noabbrev)
12484 (setq path (expand-file-name path)))
12485 ((eq org-link-file-path-type 'relative)
12486 (setq path (file-relative-name path)))
12488 (save-match-data
12489 (if (string-match (concat "^" (regexp-quote
12490 (file-name-as-directory
12491 (expand-file-name "."))))
12492 (expand-file-name path))
12493 ;; We are linking a file with relative path name.
12494 (setq path (substring (expand-file-name path)
12495 (match-end 0)))))))
12496 (setq link (concat "file:" path))
12497 (if (equal desc origpath)
12498 (setq desc path))))
12500 (setq desc (read-string "Description: " desc))
12501 (unless (string-match "\\S-" desc) (setq desc nil))
12502 (if remove (apply 'delete-region remove))
12503 (insert (org-make-link-string link desc))))
12505 (defun org-completing-read (&rest args)
12506 (let ((minibuffer-local-completion-map
12507 (copy-keymap minibuffer-local-completion-map)))
12508 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12509 (apply 'completing-read args)))
12511 ;;; Opening/following a link
12512 (defvar org-link-search-failed nil)
12514 (defun org-next-link ()
12515 "Move forward to the next link.
12516 If the link is in hidden text, expose it."
12517 (interactive)
12518 (when (and org-link-search-failed (eq this-command last-command))
12519 (goto-char (point-min))
12520 (message "Link search wrapped back to beginning of buffer"))
12521 (setq org-link-search-failed nil)
12522 (let* ((pos (point))
12523 (ct (org-context))
12524 (a (assoc :link ct)))
12525 (if a (goto-char (nth 2 a)))
12526 (if (re-search-forward org-any-link-re nil t)
12527 (progn
12528 (goto-char (match-beginning 0))
12529 (if (org-invisible-p) (org-show-context)))
12530 (goto-char pos)
12531 (setq org-link-search-failed t)
12532 (error "No further link found"))))
12534 (defun org-previous-link ()
12535 "Move backward to the previous link.
12536 If the link is in hidden text, expose it."
12537 (interactive)
12538 (when (and org-link-search-failed (eq this-command last-command))
12539 (goto-char (point-max))
12540 (message "Link search wrapped back to end of buffer"))
12541 (setq org-link-search-failed nil)
12542 (let* ((pos (point))
12543 (ct (org-context))
12544 (a (assoc :link ct)))
12545 (if a (goto-char (nth 1 a)))
12546 (if (re-search-backward org-any-link-re nil t)
12547 (progn
12548 (goto-char (match-beginning 0))
12549 (if (org-invisible-p) (org-show-context)))
12550 (goto-char pos)
12551 (setq org-link-search-failed t)
12552 (error "No further link found"))))
12554 (defun org-find-file-at-mouse (ev)
12555 "Open file link or URL at mouse."
12556 (interactive "e")
12557 (mouse-set-point ev)
12558 (org-open-at-point 'in-emacs))
12560 (defun org-open-at-mouse (ev)
12561 "Open file link or URL at mouse."
12562 (interactive "e")
12563 (mouse-set-point ev)
12564 (org-open-at-point))
12566 (defvar org-window-config-before-follow-link nil
12567 "The window configuration before following a link.
12568 This is saved in case the need arises to restore it.")
12570 (defvar org-open-link-marker (make-marker)
12571 "Marker pointing to the location where `org-open-at-point; was called.")
12573 ;;;###autoload
12574 (defun org-open-at-point-global ()
12575 "Follow a link like Org-mode does.
12576 This command can be called in any mode to follow a link that has
12577 Org-mode syntax."
12578 (interactive)
12579 (org-run-like-in-org-mode 'org-open-at-point))
12581 (defun org-open-at-point (&optional in-emacs)
12582 "Open link at or after point.
12583 If there is no link at point, this function will search forward up to
12584 the end of the current subtree.
12585 Normally, files will be opened by an appropriate application. If the
12586 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12587 (interactive "P")
12588 (catch 'abort
12589 (move-marker org-open-link-marker (point))
12590 (setq org-window-config-before-follow-link (current-window-configuration))
12591 (org-remove-occur-highlights nil nil t)
12592 (if (org-at-timestamp-p t)
12593 (org-follow-timestamp-link)
12594 (let (type path link line search (pos (point)))
12595 (catch 'match
12596 (save-excursion
12597 (skip-chars-forward "^]\n\r")
12598 (when (org-in-regexp org-bracket-link-regexp)
12599 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12600 (while (string-match " *\n *" link)
12601 (setq link (replace-match " " t t link)))
12602 (setq link (org-link-expand-abbrev link))
12603 (if (string-match org-link-re-with-space2 link)
12604 (setq type (match-string 1 link) path (match-string 2 link))
12605 (setq type "thisfile" path link))
12606 (throw 'match t)))
12608 (when (get-text-property (point) 'org-linked-text)
12609 (setq type "thisfile"
12610 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12611 (1+ (point)) (point))
12612 path (buffer-substring
12613 (previous-single-property-change pos 'org-linked-text)
12614 (next-single-property-change pos 'org-linked-text)))
12615 (throw 'match t))
12617 (save-excursion
12618 (when (or (org-in-regexp org-angle-link-re)
12619 (org-in-regexp org-plain-link-re))
12620 (setq type (match-string 1) path (match-string 2))
12621 (throw 'match t)))
12622 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12623 (setq type "tree-match"
12624 path (match-string 1))
12625 (throw 'match t))
12626 (save-excursion
12627 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12628 (setq type "tags"
12629 path (match-string 1))
12630 (while (string-match ":" path)
12631 (setq path (replace-match "+" t t path)))
12632 (throw 'match t))))
12633 (unless path
12634 (error "No link found"))
12635 ;; Remove any trailing spaces in path
12636 (if (string-match " +\\'" path)
12637 (setq path (replace-match "" t t path)))
12639 (cond
12641 ((assoc type org-link-protocols)
12642 (funcall (nth 1 (assoc type org-link-protocols)) path))
12644 ((equal type "mailto")
12645 (let ((cmd (car org-link-mailto-program))
12646 (args (cdr org-link-mailto-program)) args1
12647 (address path) (subject "") a)
12648 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12649 (setq address (match-string 1 path)
12650 subject (org-link-escape (match-string 2 path))))
12651 (while args
12652 (cond
12653 ((not (stringp (car args))) (push (pop args) args1))
12654 (t (setq a (pop args))
12655 (if (string-match "%a" a)
12656 (setq a (replace-match address t t a)))
12657 (if (string-match "%s" a)
12658 (setq a (replace-match subject t t a)))
12659 (push a args1))))
12660 (apply cmd (nreverse args1))))
12662 ((member type '("http" "https" "ftp" "news"))
12663 (browse-url (concat type ":" (org-link-escape
12664 path org-link-escape-chars-browser))))
12666 ((member type '("message"))
12667 (browse-url (concat type ":" path)))
12669 ((string= type "tags")
12670 (org-tags-view in-emacs path))
12671 ((string= type "thisfile")
12672 (if in-emacs
12673 (switch-to-buffer-other-window
12674 (org-get-buffer-for-internal-link (current-buffer)))
12675 (org-mark-ring-push))
12676 (let ((cmd `(org-link-search
12677 ,path
12678 ,(cond ((equal in-emacs '(4)) 'occur)
12679 ((equal in-emacs '(16)) 'org-occur)
12680 (t nil))
12681 ,pos)))
12682 (condition-case nil (eval cmd)
12683 (error (progn (widen) (eval cmd))))))
12685 ((string= type "tree-match")
12686 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12688 ((string= type "file")
12689 (if (string-match "::\\([0-9]+\\)\\'" path)
12690 (setq line (string-to-number (match-string 1 path))
12691 path (substring path 0 (match-beginning 0)))
12692 (if (string-match "::\\(.+\\)\\'" path)
12693 (setq search (match-string 1 path)
12694 path (substring path 0 (match-beginning 0)))))
12695 (if (string-match "[*?{]" (file-name-nondirectory path))
12696 (dired path)
12697 (org-open-file path in-emacs line search)))
12699 ((string= type "news")
12700 (org-follow-gnus-link path))
12702 ((string= type "bbdb")
12703 (org-follow-bbdb-link path))
12705 ((string= type "info")
12706 (org-follow-info-link path))
12708 ((string= type "gnus")
12709 (let (group article)
12710 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12711 (error "Error in Gnus link"))
12712 (setq group (match-string 1 path)
12713 article (match-string 3 path))
12714 (org-follow-gnus-link group article)))
12716 ((string= type "vm")
12717 (let (folder article)
12718 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12719 (error "Error in VM link"))
12720 (setq folder (match-string 1 path)
12721 article (match-string 3 path))
12722 ;; in-emacs is the prefix arg, will be interpreted as read-only
12723 (org-follow-vm-link folder article in-emacs)))
12725 ((string= type "wl")
12726 (let (folder article)
12727 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12728 (error "Error in Wanderlust link"))
12729 (setq folder (match-string 1 path)
12730 article (match-string 3 path))
12731 (org-follow-wl-link folder article)))
12733 ((string= type "mhe")
12734 (let (folder article)
12735 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12736 (error "Error in MHE link"))
12737 (setq folder (match-string 1 path)
12738 article (match-string 3 path))
12739 (org-follow-mhe-link folder article)))
12741 ((string= type "rmail")
12742 (let (folder article)
12743 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12744 (error "Error in RMAIL link"))
12745 (setq folder (match-string 1 path)
12746 article (match-string 3 path))
12747 (org-follow-rmail-link folder article)))
12749 ((string= type "shell")
12750 (let ((cmd path))
12751 (if (or (not org-confirm-shell-link-function)
12752 (funcall org-confirm-shell-link-function
12753 (format "Execute \"%s\" in shell? "
12754 (org-add-props cmd nil
12755 'face 'org-warning))))
12756 (progn
12757 (message "Executing %s" cmd)
12758 (shell-command cmd))
12759 (error "Abort"))))
12761 ((string= type "elisp")
12762 (let ((cmd path))
12763 (if (or (not org-confirm-elisp-link-function)
12764 (funcall org-confirm-elisp-link-function
12765 (format "Execute \"%s\" as elisp? "
12766 (org-add-props cmd nil
12767 'face 'org-warning))))
12768 (message "%s => %s" cmd (eval (read cmd)))
12769 (error "Abort"))))
12772 (browse-url-at-point)))))
12773 (move-marker org-open-link-marker nil)))
12775 ;;; File search
12777 (defvar org-create-file-search-functions nil
12778 "List of functions to construct the right search string for a file link.
12779 These functions are called in turn with point at the location to
12780 which the link should point.
12782 A function in the hook should first test if it would like to
12783 handle this file type, for example by checking the major-mode or
12784 the file extension. If it decides not to handle this file, it
12785 should just return nil to give other functions a chance. If it
12786 does handle the file, it must return the search string to be used
12787 when following the link. The search string will be part of the
12788 file link, given after a double colon, and `org-open-at-point'
12789 will automatically search for it. If special measures must be
12790 taken to make the search successful, another function should be
12791 added to the companion hook `org-execute-file-search-functions',
12792 which see.
12794 A function in this hook may also use `setq' to set the variable
12795 `description' to provide a suggestion for the descriptive text to
12796 be used for this link when it gets inserted into an Org-mode
12797 buffer with \\[org-insert-link].")
12799 (defvar org-execute-file-search-functions nil
12800 "List of functions to execute a file search triggered by a link.
12802 Functions added to this hook must accept a single argument, the
12803 search string that was part of the file link, the part after the
12804 double colon. The function must first check if it would like to
12805 handle this search, for example by checking the major-mode or the
12806 file extension. If it decides not to handle this search, it
12807 should just return nil to give other functions a chance. If it
12808 does handle the search, it must return a non-nil value to keep
12809 other functions from trying.
12811 Each function can access the current prefix argument through the
12812 variable `current-prefix-argument'. Note that a single prefix is
12813 used to force opening a link in Emacs, so it may be good to only
12814 use a numeric or double prefix to guide the search function.
12816 In case this is needed, a function in this hook can also restore
12817 the window configuration before `org-open-at-point' was called using:
12819 (set-window-configuration org-window-config-before-follow-link)")
12821 (defun org-link-search (s &optional type avoid-pos)
12822 "Search for a link search option.
12823 If S is surrounded by forward slashes, it is interpreted as a
12824 regular expression. In org-mode files, this will create an `org-occur'
12825 sparse tree. In ordinary files, `occur' will be used to list matches.
12826 If the current buffer is in `dired-mode', grep will be used to search
12827 in all files. If AVOID-POS is given, ignore matches near that position."
12828 (let ((case-fold-search t)
12829 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12830 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12831 (append '(("") (" ") ("\t") ("\n"))
12832 org-emphasis-alist)
12833 "\\|") "\\)"))
12834 (pos (point))
12835 (pre "") (post "")
12836 words re0 re1 re2 re3 re4 re5 re2a reall)
12837 (cond
12838 ;; First check if there are any special
12839 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12840 ;; Now try the builtin stuff
12841 ((save-excursion
12842 (goto-char (point-min))
12843 (and
12844 (re-search-forward
12845 (concat "<<" (regexp-quote s0) ">>") nil t)
12846 (setq pos (match-beginning 0))))
12847 ;; There is an exact target for this
12848 (goto-char pos))
12849 ((string-match "^/\\(.*\\)/$" s)
12850 ;; A regular expression
12851 (cond
12852 ((org-mode-p)
12853 (org-occur (match-string 1 s)))
12854 ;;((eq major-mode 'dired-mode)
12855 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12856 (t (org-do-occur (match-string 1 s)))))
12858 ;; A normal search strings
12859 (when (equal (string-to-char s) ?*)
12860 ;; Anchor on headlines, post may include tags.
12861 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12862 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12863 s (substring s 1)))
12864 (remove-text-properties
12865 0 (length s)
12866 '(face nil mouse-face nil keymap nil fontified nil) s)
12867 ;; Make a series of regular expressions to find a match
12868 (setq words (org-split-string s "[ \n\r\t]+")
12869 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12870 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12871 "\\)" markers)
12872 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12873 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12874 re1 (concat pre re2 post)
12875 re3 (concat pre re4 post)
12876 re5 (concat pre ".*" re4)
12877 re2 (concat pre re2)
12878 re2a (concat pre re2a)
12879 re4 (concat pre re4)
12880 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12881 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12882 re5 "\\)"
12884 (cond
12885 ((eq type 'org-occur) (org-occur reall))
12886 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12887 (t (goto-char (point-min))
12888 (if (or (org-search-not-self 1 re0 nil t)
12889 (org-search-not-self 1 re1 nil t)
12890 (org-search-not-self 1 re2 nil t)
12891 (org-search-not-self 1 re2a nil t)
12892 (org-search-not-self 1 re3 nil t)
12893 (org-search-not-self 1 re4 nil t)
12894 (org-search-not-self 1 re5 nil t)
12896 (goto-char (match-beginning 1))
12897 (goto-char pos)
12898 (error "No match")))))
12900 ;; Normal string-search
12901 (goto-char (point-min))
12902 (if (search-forward s nil t)
12903 (goto-char (match-beginning 0))
12904 (error "No match"))))
12905 (and (org-mode-p) (org-show-context 'link-search))))
12907 (defun org-search-not-self (group &rest args)
12908 "Execute `re-search-forward', but only accept matches that do not
12909 enclose the position of `org-open-link-marker'."
12910 (let ((m org-open-link-marker))
12911 (catch 'exit
12912 (while (apply 're-search-forward args)
12913 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12914 (goto-char (match-end group))
12915 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12916 (> (match-beginning 0) (marker-position m))
12917 (< (match-end 0) (marker-position m)))
12918 (save-match-data
12919 (or (not (org-in-regexp
12920 org-bracket-link-analytic-regexp 1))
12921 (not (match-end 4)) ; no description
12922 (and (<= (match-beginning 4) (point))
12923 (>= (match-end 4) (point))))))
12924 (throw 'exit (point))))))))
12926 (defun org-get-buffer-for-internal-link (buffer)
12927 "Return a buffer to be used for displaying the link target of internal links."
12928 (cond
12929 ((not org-display-internal-link-with-indirect-buffer)
12930 buffer)
12931 ((string-match "(Clone)$" (buffer-name buffer))
12932 (message "Buffer is already a clone, not making another one")
12933 ;; we also do not modify visibility in this case
12934 buffer)
12935 (t ; make a new indirect buffer for displaying the link
12936 (let* ((bn (buffer-name buffer))
12937 (ibn (concat bn "(Clone)"))
12938 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12939 (with-current-buffer ib (org-overview))
12940 ib))))
12942 (defun org-do-occur (regexp &optional cleanup)
12943 "Call the Emacs command `occur'.
12944 If CLEANUP is non-nil, remove the printout of the regular expression
12945 in the *Occur* buffer. This is useful if the regex is long and not useful
12946 to read."
12947 (occur regexp)
12948 (when cleanup
12949 (let ((cwin (selected-window)) win beg end)
12950 (when (setq win (get-buffer-window "*Occur*"))
12951 (select-window win))
12952 (goto-char (point-min))
12953 (when (re-search-forward "match[a-z]+" nil t)
12954 (setq beg (match-end 0))
12955 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12956 (setq end (1- (match-beginning 0)))))
12957 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12958 (goto-char (point-min))
12959 (select-window cwin))))
12961 ;;; The mark ring for links jumps
12963 (defvar org-mark-ring nil
12964 "Mark ring for positions before jumps in Org-mode.")
12965 (defvar org-mark-ring-last-goto nil
12966 "Last position in the mark ring used to go back.")
12967 ;; Fill and close the ring
12968 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12969 (loop for i from 1 to org-mark-ring-length do
12970 (push (make-marker) org-mark-ring))
12971 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12972 org-mark-ring)
12974 (defun org-mark-ring-push (&optional pos buffer)
12975 "Put the current position or POS into the mark ring and rotate it."
12976 (interactive)
12977 (setq pos (or pos (point)))
12978 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12979 (move-marker (car org-mark-ring)
12980 (or pos (point))
12981 (or buffer (current-buffer)))
12982 (message "%s"
12983 (substitute-command-keys
12984 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12986 (defun org-mark-ring-goto (&optional n)
12987 "Jump to the previous position in the mark ring.
12988 With prefix arg N, jump back that many stored positions. When
12989 called several times in succession, walk through the entire ring.
12990 Org-mode commands jumping to a different position in the current file,
12991 or to another Org-mode file, automatically push the old position
12992 onto the ring."
12993 (interactive "p")
12994 (let (p m)
12995 (if (eq last-command this-command)
12996 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12997 (setq p org-mark-ring))
12998 (setq org-mark-ring-last-goto p)
12999 (setq m (car p))
13000 (switch-to-buffer (marker-buffer m))
13001 (goto-char m)
13002 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13004 (defun org-remove-angle-brackets (s)
13005 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13006 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13008 (defun org-add-angle-brackets (s)
13009 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13010 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13013 ;;; Following specific links
13015 (defun org-follow-timestamp-link ()
13016 (cond
13017 ((org-at-date-range-p t)
13018 (let ((org-agenda-start-on-weekday)
13019 (t1 (match-string 1))
13020 (t2 (match-string 2)))
13021 (setq t1 (time-to-days (org-time-string-to-time t1))
13022 t2 (time-to-days (org-time-string-to-time t2)))
13023 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13024 ((org-at-timestamp-p t)
13025 (org-agenda-list nil (time-to-days (org-time-string-to-time
13026 (substring (match-string 1) 0 10)))
13028 (t (error "This should not happen"))))
13031 (defun org-follow-bbdb-link (name)
13032 "Follow a BBDB link to NAME."
13033 (require 'bbdb)
13034 (let ((inhibit-redisplay (not debug-on-error))
13035 (bbdb-electric-p nil))
13036 (catch 'exit
13037 ;; Exact match on name
13038 (bbdb-name (concat "\\`" name "\\'") nil)
13039 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13040 ;; Exact match on name
13041 (bbdb-company (concat "\\`" name "\\'") nil)
13042 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13043 ;; Partial match on name
13044 (bbdb-name name nil)
13045 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13046 ;; Partial match on company
13047 (bbdb-company name nil)
13048 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13049 ;; General match including network address and notes
13050 (bbdb name nil)
13051 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13052 (delete-window (get-buffer-window "*BBDB*"))
13053 (error "No matching BBDB record")))))
13055 (defun org-follow-info-link (name)
13056 "Follow an info file & node link to NAME."
13057 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13058 (string-match "\\(.*\\)" name))
13059 (progn
13060 (require 'info)
13061 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13062 (Info-find-node (match-string 1 name) (match-string 2 name))
13063 (Info-find-node (match-string 1 name) "Top")))
13064 (message "Could not open: %s" name)))
13066 (defun org-follow-gnus-link (&optional group article)
13067 "Follow a Gnus link to GROUP and ARTICLE."
13068 (require 'gnus)
13069 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13070 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13071 (cond ((and group article)
13072 (gnus-group-read-group 1 nil group)
13073 (gnus-summary-goto-article (string-to-number article) nil t))
13074 (group (gnus-group-jump-to-group group))))
13076 (defun org-follow-vm-link (&optional folder article readonly)
13077 "Follow a VM link to FOLDER and ARTICLE."
13078 (require 'vm)
13079 (setq article (org-add-angle-brackets article))
13080 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13081 ;; ange-ftp or efs or tramp access
13082 (let ((user (or (match-string 1 folder) (user-login-name)))
13083 (host (match-string 2 folder))
13084 (file (match-string 3 folder)))
13085 (cond
13086 ((featurep 'tramp)
13087 ;; use tramp to access the file
13088 (if (featurep 'xemacs)
13089 (setq folder (format "[%s@%s]%s" user host file))
13090 (setq folder (format "/%s@%s:%s" user host file))))
13092 ;; use ange-ftp or efs
13093 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13094 (setq folder (format "/%s@%s:%s" user host file))))))
13095 (when folder
13096 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13097 (sit-for 0.1)
13098 (when article
13099 (vm-select-folder-buffer)
13100 (widen)
13101 (let ((case-fold-search t))
13102 (goto-char (point-min))
13103 (if (not (re-search-forward
13104 (concat "^" "message-id: *" (regexp-quote article))))
13105 (error "Could not find the specified message in this folder"))
13106 (vm-isearch-update)
13107 (vm-isearch-narrow)
13108 (vm-beginning-of-message)
13109 (vm-summarize)))))
13111 (defun org-follow-wl-link (folder article)
13112 "Follow a Wanderlust link to FOLDER and ARTICLE."
13113 (if (and (string= folder "%")
13114 article
13115 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13116 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13117 ;; Thus, we recompose folder and article ids.
13118 (setq folder (format "%s#%s" folder (match-string 1 article))
13119 article (match-string 3 article)))
13120 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13121 (error "No such folder: %s" folder))
13122 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13123 (and article
13124 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13125 (wl-summary-redisplay)))
13127 (defun org-follow-rmail-link (folder article)
13128 "Follow an RMAIL link to FOLDER and ARTICLE."
13129 (setq article (org-add-angle-brackets article))
13130 (let (message-number)
13131 (save-excursion
13132 (save-window-excursion
13133 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13134 (setq message-number
13135 (save-restriction
13136 (widen)
13137 (goto-char (point-max))
13138 (if (re-search-backward
13139 (concat "^Message-ID:\\s-+" (regexp-quote
13140 (or article "")))
13141 nil t)
13142 (rmail-what-message))))))
13143 (if message-number
13144 (progn
13145 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13146 (rmail-show-message message-number)
13147 message-number)
13148 (error "Message not found"))))
13150 ;;; mh-e integration based on planner-mode
13151 (defun org-mhe-get-message-real-folder ()
13152 "Return the name of the current message real folder, so if you use
13153 sequences, it will now work."
13154 (save-excursion
13155 (let* ((folder
13156 (if (equal major-mode 'mh-folder-mode)
13157 mh-current-folder
13158 ;; Refer to the show buffer
13159 mh-show-folder-buffer))
13160 (end-index
13161 (if (boundp 'mh-index-folder)
13162 (min (length mh-index-folder) (length folder))))
13164 ;; a simple test on mh-index-data does not work, because
13165 ;; mh-index-data is always nil in a show buffer.
13166 (if (and (boundp 'mh-index-folder)
13167 (string= mh-index-folder (substring folder 0 end-index)))
13168 (if (equal major-mode 'mh-show-mode)
13169 (save-window-excursion
13170 (let (pop-up-frames)
13171 (when (buffer-live-p (get-buffer folder))
13172 (progn
13173 (pop-to-buffer folder)
13174 (org-mhe-get-message-folder-from-index)
13177 (org-mhe-get-message-folder-from-index)
13179 folder
13183 (defun org-mhe-get-message-folder-from-index ()
13184 "Returns the name of the message folder in a index folder buffer."
13185 (save-excursion
13186 (mh-index-previous-folder)
13187 (re-search-forward "^\\(+.*\\)$" nil t)
13188 (message "%s" (match-string 1))))
13190 (defun org-mhe-get-message-folder ()
13191 "Return the name of the current message folder. Be careful if you
13192 use sequences."
13193 (save-excursion
13194 (if (equal major-mode 'mh-folder-mode)
13195 mh-current-folder
13196 ;; Refer to the show buffer
13197 mh-show-folder-buffer)))
13199 (defun org-mhe-get-message-num ()
13200 "Return the number of the current message. Be careful if you
13201 use sequences."
13202 (save-excursion
13203 (if (equal major-mode 'mh-folder-mode)
13204 (mh-get-msg-num nil)
13205 ;; Refer to the show buffer
13206 (mh-show-buffer-message-number))))
13208 (defun org-mhe-get-header (header)
13209 "Return a header of the message in folder mode. This will create a
13210 show buffer for the corresponding message. If you have a more clever
13211 idea..."
13212 (let* ((folder (org-mhe-get-message-folder))
13213 (num (org-mhe-get-message-num))
13214 (buffer (get-buffer-create (concat "show-" folder)))
13215 (header-field))
13216 (with-current-buffer buffer
13217 (mh-display-msg num folder)
13218 (if (equal major-mode 'mh-folder-mode)
13219 (mh-header-display)
13220 (mh-show-header-display))
13221 (set-buffer buffer)
13222 (setq header-field (mh-get-header-field header))
13223 (if (equal major-mode 'mh-folder-mode)
13224 (mh-show)
13225 (mh-show-show))
13226 header-field)))
13228 (defun org-follow-mhe-link (folder article)
13229 "Follow an MHE link to FOLDER and ARTICLE.
13230 If ARTICLE is nil FOLDER is shown. If the configuration variable
13231 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13232 ARTICLE is searched in all folders. Indexed searches (swish++,
13233 namazu, and others supported by MH-E) will always search in all
13234 folders."
13235 (require 'mh-e)
13236 (require 'mh-search)
13237 (require 'mh-utils)
13238 (mh-find-path)
13239 (if (not article)
13240 (mh-visit-folder (mh-normalize-folder-name folder))
13241 (setq article (org-add-angle-brackets article))
13242 (mh-search-choose)
13243 (if (equal mh-searcher 'pick)
13244 (progn
13245 (mh-search folder (list "--message-id" article))
13246 (when (and org-mhe-search-all-folders
13247 (not (org-mhe-get-message-real-folder)))
13248 (kill-this-buffer)
13249 (mh-search "+" (list "--message-id" article))))
13250 (mh-search "+" article))
13251 (if (org-mhe-get-message-real-folder)
13252 (mh-show-msg 1)
13253 (kill-this-buffer)
13254 (error "Message not found"))))
13256 ;;; BibTeX links
13258 ;; Use the custom search meachnism to construct and use search strings for
13259 ;; file links to BibTeX database entries.
13261 (defun org-create-file-search-in-bibtex ()
13262 "Create the search string and description for a BibTeX database entry."
13263 (when (eq major-mode 'bibtex-mode)
13264 ;; yes, we want to construct this search string.
13265 ;; Make a good description for this entry, using names, year and the title
13266 ;; Put it into the `description' variable which is dynamically scoped.
13267 (let ((bibtex-autokey-names 1)
13268 (bibtex-autokey-names-stretch 1)
13269 (bibtex-autokey-name-case-convert-function 'identity)
13270 (bibtex-autokey-name-separator " & ")
13271 (bibtex-autokey-additional-names " et al.")
13272 (bibtex-autokey-year-length 4)
13273 (bibtex-autokey-name-year-separator " ")
13274 (bibtex-autokey-titlewords 3)
13275 (bibtex-autokey-titleword-separator " ")
13276 (bibtex-autokey-titleword-case-convert-function 'identity)
13277 (bibtex-autokey-titleword-length 'infty)
13278 (bibtex-autokey-year-title-separator ": "))
13279 (setq description (bibtex-generate-autokey)))
13280 ;; Now parse the entry, get the key and return it.
13281 (save-excursion
13282 (bibtex-beginning-of-entry)
13283 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13285 (defun org-execute-file-search-in-bibtex (s)
13286 "Find the link search string S as a key for a database entry."
13287 (when (eq major-mode 'bibtex-mode)
13288 ;; Yes, we want to do the search in this file.
13289 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13290 (goto-char (point-min))
13291 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13292 (regexp-quote s) "[ \t\n]*,") nil t)
13293 (goto-char (match-beginning 0)))
13294 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13295 ;; Use double prefix to indicate that any web link should be browsed
13296 (let ((b (current-buffer)) (p (point)))
13297 ;; Restore the window configuration because we just use the web link
13298 (set-window-configuration org-window-config-before-follow-link)
13299 (save-excursion (set-buffer b) (goto-char p)
13300 (bibtex-url)))
13301 (recenter 0)) ; Move entry start to beginning of window
13302 ;; return t to indicate that the search is done.
13305 ;; Finally add the functions to the right hooks.
13306 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13307 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13309 ;; end of Bibtex link setup
13311 ;;; Following file links
13313 (defun org-open-file (path &optional in-emacs line search)
13314 "Open the file at PATH.
13315 First, this expands any special file name abbreviations. Then the
13316 configuration variable `org-file-apps' is checked if it contains an
13317 entry for this file type, and if yes, the corresponding command is launched.
13318 If no application is found, Emacs simply visits the file.
13319 With optional argument IN-EMACS, Emacs will visit the file.
13320 Optional LINE specifies a line to go to, optional SEARCH a string to
13321 search for. If LINE or SEARCH is given, the file will always be
13322 opened in Emacs.
13323 If the file does not exist, an error is thrown."
13324 (setq in-emacs (or in-emacs line search))
13325 (let* ((file (if (equal path "")
13326 buffer-file-name
13327 (substitute-in-file-name (expand-file-name path))))
13328 (apps (append org-file-apps (org-default-apps)))
13329 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13330 (dirp (if remp nil (file-directory-p file)))
13331 (dfile (downcase file))
13332 (old-buffer (current-buffer))
13333 (old-pos (point))
13334 (old-mode major-mode)
13335 ext cmd)
13336 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13337 (setq ext (match-string 1 dfile))
13338 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13339 (setq ext (match-string 1 dfile))))
13340 (if in-emacs
13341 (setq cmd 'emacs)
13342 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13343 (and dirp (cdr (assoc 'directory apps)))
13344 (cdr (assoc ext apps))
13345 (cdr (assoc t apps)))))
13346 (when (eq cmd 'mailcap)
13347 (require 'mailcap)
13348 (mailcap-parse-mailcaps)
13349 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13350 (command (mailcap-mime-info mime-type)))
13351 (if (stringp command)
13352 (setq cmd command)
13353 (setq cmd 'emacs))))
13354 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13355 (not (file-exists-p file))
13356 (not org-open-non-existing-files))
13357 (error "No such file: %s" file))
13358 (cond
13359 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13360 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13361 (while (string-match "['\"]%s['\"]" cmd)
13362 (setq cmd (replace-match "%s" t t cmd)))
13363 (while (string-match "%s" cmd)
13364 (setq cmd (replace-match
13365 (save-match-data (shell-quote-argument file))
13366 t t cmd)))
13367 (save-window-excursion
13368 (start-process-shell-command cmd nil cmd)))
13369 ((or (stringp cmd)
13370 (eq cmd 'emacs))
13371 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13372 (widen)
13373 (if line (goto-line line)
13374 (if search (org-link-search search))))
13375 ((consp cmd)
13376 (eval cmd))
13377 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13378 (and (org-mode-p) (eq old-mode 'org-mode)
13379 (or (not (equal old-buffer (current-buffer)))
13380 (not (equal old-pos (point))))
13381 (org-mark-ring-push old-pos old-buffer))))
13383 (defun org-default-apps ()
13384 "Return the default applications for this operating system."
13385 (cond
13386 ((eq system-type 'darwin)
13387 org-file-apps-defaults-macosx)
13388 ((eq system-type 'windows-nt)
13389 org-file-apps-defaults-windowsnt)
13390 (t org-file-apps-defaults-gnu)))
13392 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13393 (defun org-file-remote-p (file)
13394 "Test whether FILE specifies a location on a remote system.
13395 Return non-nil if the location is indeed remote.
13397 For example, the filename \"/user@host:/foo\" specifies a location
13398 on the system \"/user@host:\"."
13399 (cond ((fboundp 'file-remote-p)
13400 (file-remote-p file))
13401 ((fboundp 'tramp-handle-file-remote-p)
13402 (tramp-handle-file-remote-p file))
13403 ((and (boundp 'ange-ftp-name-format)
13404 (string-match (car ange-ftp-name-format) file))
13406 (t nil)))
13409 ;;;; Hooks for remember.el, and refiling
13411 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13412 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13414 ;;;###autoload
13415 (defun org-remember-insinuate ()
13416 "Setup remember.el for use wiht Org-mode."
13417 (require 'remember)
13418 (setq remember-annotation-functions '(org-remember-annotation))
13419 (setq remember-handler-functions '(org-remember-handler))
13420 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13422 ;;;###autoload
13423 (defun org-remember-annotation ()
13424 "Return a link to the current location as an annotation for remember.el.
13425 If you are using Org-mode files as target for data storage with
13426 remember.el, then the annotations should include a link compatible with the
13427 conventions in Org-mode. This function returns such a link."
13428 (org-store-link nil))
13430 (defconst org-remember-help
13431 "Select a destination location for the note.
13432 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13433 RET on headline -> Store as sublevel entry to current headline
13434 RET at beg-of-buf -> Append to file as level 2 headline
13435 <left>/<right> -> before/after current headline, same headings level")
13437 (defvar org-remember-previous-location nil)
13438 (defvar org-force-remember-template-char) ;; dynamically scoped
13440 (defun org-select-remember-template (&optional use-char)
13441 (when org-remember-templates
13442 (let* ((templates (mapcar (lambda (x)
13443 (if (stringp (car x))
13444 (append (list (nth 1 x) (car x)) (cddr x))
13445 (append (list (car x) "") (cdr x))))
13446 org-remember-templates))
13447 (char (or use-char
13448 (cond
13449 ((= (length templates) 1)
13450 (caar templates))
13451 ((and (boundp 'org-force-remember-template-char)
13452 org-force-remember-template-char)
13453 (if (stringp org-force-remember-template-char)
13454 (string-to-char org-force-remember-template-char)
13455 org-force-remember-template-char))
13457 (message "Select template: %s"
13458 (mapconcat
13459 (lambda (x)
13460 (cond
13461 ((not (string-match "\\S-" (nth 1 x)))
13462 (format "[%c]" (car x)))
13463 ((equal (downcase (car x))
13464 (downcase (aref (nth 1 x) 0)))
13465 (format "[%c]%s" (car x)
13466 (substring (nth 1 x) 1)))
13467 (t (format "[%c]%s" (car x) (nth 1 x)))))
13468 templates " "))
13469 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13470 (when (equal char0 ?\C-g)
13471 (jump-to-register remember-register)
13472 (kill-buffer remember-buffer))
13473 char0))))))
13474 (cddr (assoc char templates)))))
13476 (defvar x-last-selected-text)
13477 (defvar x-last-selected-text-primary)
13479 ;;;###autoload
13480 (defun org-remember-apply-template (&optional use-char skip-interactive)
13481 "Initialize *remember* buffer with template, invoke `org-mode'.
13482 This function should be placed into `remember-mode-hook' and in fact requires
13483 to be run from that hook to function properly."
13484 (if org-remember-templates
13485 (let* ((entry (org-select-remember-template use-char))
13486 (tpl (car entry))
13487 (plist-p (if org-store-link-plist t nil))
13488 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13489 (string-match "\\S-" (nth 1 entry)))
13490 (nth 1 entry)
13491 org-default-notes-file))
13492 (headline (nth 2 entry))
13493 (v-c (or (and (eq window-system 'x)
13494 (fboundp 'x-cut-buffer-or-selection-value)
13495 (x-cut-buffer-or-selection-value))
13496 (org-bound-and-true-p x-last-selected-text)
13497 (org-bound-and-true-p x-last-selected-text-primary)
13498 (and (> (length kill-ring) 0) (current-kill 0))))
13499 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13500 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13501 (v-u (concat "[" (substring v-t 1 -1) "]"))
13502 (v-U (concat "[" (substring v-T 1 -1) "]"))
13503 ;; `initial' and `annotation' are bound in `remember'
13504 (v-i (if (boundp 'initial) initial))
13505 (v-a (if (and (boundp 'annotation) annotation)
13506 (if (equal annotation "[[]]") "" annotation)
13507 ""))
13508 (v-A (if (and v-a
13509 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13510 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13511 v-a))
13512 (v-n user-full-name)
13513 (org-startup-folded nil)
13514 org-time-was-given org-end-time-was-given x
13515 prompt completions char time pos default histvar)
13516 (setq org-store-link-plist
13517 (append (list :annotation v-a :initial v-i)
13518 org-store-link-plist))
13519 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13520 (erase-buffer)
13521 (insert (substitute-command-keys
13522 (format
13523 "## Filing location: Select interactively, default, or last used:
13524 ## %s to select file and header location interactively.
13525 ## %s \"%s\" -> \"* %s\"
13526 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13527 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13528 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13529 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13530 (abbreviate-file-name (or file org-default-notes-file))
13531 (or headline "")
13532 (or (car org-remember-previous-location) "???")
13533 (or (cdr org-remember-previous-location) "???"))))
13534 (insert tpl) (goto-char (point-min))
13535 ;; Simple %-escapes
13536 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13537 (when (and initial (equal (match-string 0) "%i"))
13538 (save-match-data
13539 (let* ((lead (buffer-substring
13540 (point-at-bol) (match-beginning 0))))
13541 (setq v-i (mapconcat 'identity
13542 (org-split-string initial "\n")
13543 (concat "\n" lead))))))
13544 (replace-match
13545 (or (eval (intern (concat "v-" (match-string 1)))) "")
13546 t t))
13548 ;; %[] Insert contents of a file.
13549 (goto-char (point-min))
13550 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13551 (let ((start (match-beginning 0))
13552 (end (match-end 0))
13553 (filename (expand-file-name (match-string 1))))
13554 (goto-char start)
13555 (delete-region start end)
13556 (condition-case error
13557 (insert-file-contents filename)
13558 (error (insert (format "%%![Couldn't insert %s: %s]"
13559 filename error))))))
13560 ;; %() embedded elisp
13561 (goto-char (point-min))
13562 (while (re-search-forward "%\\((.+)\\)" nil t)
13563 (goto-char (match-beginning 0))
13564 (let ((template-start (point)))
13565 (forward-char 1)
13566 (let ((result
13567 (condition-case error
13568 (eval (read (current-buffer)))
13569 (error (format "%%![Error: %s]" error)))))
13570 (delete-region template-start (point))
13571 (insert result))))
13573 ;; From the property list
13574 (when plist-p
13575 (goto-char (point-min))
13576 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13577 (and (setq x (or (plist-get org-store-link-plist
13578 (intern (match-string 1))) ""))
13579 (replace-match x t t))))
13581 ;; Turn on org-mode in the remember buffer, set local variables
13582 (org-mode)
13583 (org-set-local 'org-finish-function 'org-remember-finalize)
13584 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13585 (org-set-local 'org-default-notes-file file))
13586 (if (and headline (stringp headline) (string-match "\\S-" headline))
13587 (org-set-local 'org-remember-default-headline headline))
13588 ;; Interactive template entries
13589 (goto-char (point-min))
13590 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13591 (setq char (if (match-end 3) (match-string 3))
13592 prompt (if (match-end 2) (match-string 2)))
13593 (goto-char (match-beginning 0))
13594 (replace-match "")
13595 (setq completions nil default nil)
13596 (when prompt
13597 (setq completions (org-split-string prompt "|")
13598 prompt (pop completions)
13599 default (car completions)
13600 histvar (intern (concat
13601 "org-remember-template-prompt-history::"
13602 (or prompt "")))
13603 completions (mapcar 'list completions)))
13604 (cond
13605 ((member char '("G" "g"))
13606 (let* ((org-last-tags-completion-table
13607 (org-global-tags-completion-table
13608 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13609 (org-add-colon-after-tag-completion t)
13610 (ins (completing-read
13611 (if prompt (concat prompt ": ") "Tags: ")
13612 'org-tags-completion-function nil nil nil
13613 'org-tags-history)))
13614 (setq ins (mapconcat 'identity
13615 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13616 ":"))
13617 (when (string-match "\\S-" ins)
13618 (or (equal (char-before) ?:) (insert ":"))
13619 (insert ins)
13620 (or (equal (char-after) ?:) (insert ":")))))
13621 (char
13622 (setq org-time-was-given (equal (upcase char) char))
13623 (setq time (org-read-date (equal (upcase char) "U") t nil
13624 prompt))
13625 (org-insert-time-stamp time org-time-was-given
13626 (member char '("u" "U"))
13627 nil nil (list org-end-time-was-given)))
13629 (insert (org-completing-read
13630 (concat (if prompt prompt "Enter string")
13631 (if default (concat " [" default "]"))
13632 ": ")
13633 completions nil nil nil histvar default)))))
13634 (goto-char (point-min))
13635 (if (re-search-forward "%\\?" nil t)
13636 (replace-match "")
13637 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13638 (org-mode)
13639 (org-set-local 'org-finish-function 'org-remember-finalize))
13640 (when (save-excursion
13641 (goto-char (point-min))
13642 (re-search-forward "%!" nil t))
13643 (replace-match "")
13644 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13646 (defun org-remember-finish-immediately ()
13647 "File remember note immediately.
13648 This should be run in `post-command-hook' and will remove itself
13649 from that hook."
13650 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13651 (when org-finish-function
13652 (funcall org-finish-function)))
13654 (defvar org-clock-marker) ; Defined below
13655 (defun org-remember-finalize ()
13656 "Finalize the remember process."
13657 (unless (fboundp 'remember-finalize)
13658 (defalias 'remember-finalize 'remember-buffer))
13659 (when (and org-clock-marker
13660 (equal (marker-buffer org-clock-marker) (current-buffer)))
13661 ;; FIXME: test this, this is w/o notetaking!
13662 (let (org-log-note-clock-out) (org-clock-out)))
13663 (when buffer-file-name
13664 (save-buffer)
13665 (setq buffer-file-name nil))
13666 (remember-finalize))
13668 ;;;###autoload
13669 (defun org-remember (&optional goto org-force-remember-template-char)
13670 "Call `remember'. If this is already a remember buffer, re-apply template.
13671 If there is an active region, make sure remember uses it as initial content
13672 of the remember buffer.
13674 When called interactively with a `C-u' prefix argument GOTO, don't remember
13675 anything, just go to the file/headline where the selected template usually
13676 stores its notes. With a double prefix arg `C-u C-u', go to the last
13677 note stored by remember.
13679 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13680 associated with a template in `org-remember-templates'."
13681 (interactive "P")
13682 (cond
13683 ((equal goto '(4)) (org-go-to-remember-target))
13684 ((equal goto '(16)) (org-remember-goto-last-stored))
13686 (if (memq org-finish-function '(remember-buffer remember-finalize))
13687 (progn
13688 (when (< (length org-remember-templates) 2)
13689 (error "No other template available"))
13690 (erase-buffer)
13691 (let ((annotation (plist-get org-store-link-plist :annotation))
13692 (initial (plist-get org-store-link-plist :initial)))
13693 (org-remember-apply-template))
13694 (message "Press C-c C-c to remember data"))
13695 (if (org-region-active-p)
13696 (remember (buffer-substring (point) (mark)))
13697 (call-interactively 'remember))))))
13699 (defun org-remember-goto-last-stored ()
13700 "Go to the location where the last remember note was stored."
13701 (interactive)
13702 (bookmark-jump "org-remember-last-stored")
13703 (message "This is the last note stored by remember"))
13705 (defun org-go-to-remember-target (&optional template-key)
13706 "Go to the target location of a remember template.
13707 The user is queried for the template."
13708 (interactive)
13709 (let* ((entry (org-select-remember-template template-key))
13710 (file (nth 1 entry))
13711 (heading (nth 2 entry))
13712 visiting)
13713 (unless (and file (stringp file) (string-match "\\S-" file))
13714 (setq file org-default-notes-file))
13715 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13716 (setq heading org-remember-default-headline))
13717 (setq visiting (org-find-base-buffer-visiting file))
13718 (if (not visiting) (find-file-noselect file))
13719 (switch-to-buffer (or visiting (get-file-buffer file)))
13720 (widen)
13721 (goto-char (point-min))
13722 (if (re-search-forward
13723 (concat "^\\*+[ \t]+" (regexp-quote heading)
13724 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13725 nil t)
13726 (goto-char (match-beginning 0))
13727 (error "Target headline not found: %s" heading))))
13729 (defvar org-note-abort nil) ; dynamically scoped
13731 ;;;###autoload
13732 (defun org-remember-handler ()
13733 "Store stuff from remember.el into an org file.
13734 First prompts for an org file. If the user just presses return, the value
13735 of `org-default-notes-file' is used.
13736 Then the command offers the headings tree of the selected file in order to
13737 file the text at a specific location.
13738 You can either immediately press RET to get the note appended to the
13739 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13740 find a better place. Then press RET or <left> or <right> in insert the note.
13742 Key Cursor position Note gets inserted
13743 -----------------------------------------------------------------------------
13744 RET buffer-start as level 1 heading at end of file
13745 RET on headline as sublevel of the heading at cursor
13746 RET no heading at cursor position, level taken from context.
13747 Or use prefix arg to specify level manually.
13748 <left> on headline as same level, before current heading
13749 <right> on headline as same level, after current heading
13751 So the fastest way to store the note is to press RET RET to append it to
13752 the default file. This way your current train of thought is not
13753 interrupted, in accordance with the principles of remember.el.
13754 You can also get the fast execution without prompting by using
13755 C-u C-c C-c to exit the remember buffer. See also the variable
13756 `org-remember-store-without-prompt'.
13758 Before being stored away, the function ensures that the text has a
13759 headline, i.e. a first line that starts with a \"*\". If not, a headline
13760 is constructed from the current date and some additional data.
13762 If the variable `org-adapt-indentation' is non-nil, the entire text is
13763 also indented so that it starts in the same column as the headline
13764 \(i.e. after the stars).
13766 See also the variable `org-reverse-note-order'."
13767 (goto-char (point-min))
13768 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13769 (replace-match ""))
13770 (goto-char (point-max))
13771 (beginning-of-line 1)
13772 (while (looking-at "[ \t]*$\\|##.*")
13773 (delete-region (1- (point)) (point-max))
13774 (beginning-of-line 1))
13775 (catch 'quit
13776 (if org-note-abort (throw 'quit nil))
13777 (let* ((txt (buffer-substring (point-min) (point-max)))
13778 (fastp (org-xor (equal current-prefix-arg '(4))
13779 org-remember-store-without-prompt))
13780 (file (cond
13781 (fastp org-default-notes-file)
13782 ((and (eq org-remember-interactive-interface 'refile)
13783 org-refile-targets)
13784 org-default-notes-file)
13785 ((not (and (equal current-prefix-arg '(16))
13786 org-remember-previous-location))
13787 (org-get-org-file))))
13788 (heading org-remember-default-headline)
13789 (visiting (and file (org-find-base-buffer-visiting file)))
13790 (org-startup-folded nil)
13791 (org-startup-align-all-tables nil)
13792 (org-goto-start-pos 1)
13793 spos exitcmd level indent reversed)
13794 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13795 (setq file (car org-remember-previous-location)
13796 heading (cdr org-remember-previous-location)
13797 fastp t))
13798 (setq current-prefix-arg nil)
13799 (if (string-match "[ \t\n]+\\'" txt)
13800 (setq txt (replace-match "" t t txt)))
13801 ;; Modify text so that it becomes a nice subtree which can be inserted
13802 ;; into an org tree.
13803 (let* ((lines (split-string txt "\n"))
13804 first)
13805 (setq first (car lines) lines (cdr lines))
13806 (if (string-match "^\\*+ " first)
13807 ;; Is already a headline
13808 (setq indent nil)
13809 ;; We need to add a headline: Use time and first buffer line
13810 (setq lines (cons first lines)
13811 first (concat "* " (current-time-string)
13812 " (" (remember-buffer-desc) ")")
13813 indent " "))
13814 (if (and org-adapt-indentation indent)
13815 (setq lines (mapcar
13816 (lambda (x)
13817 (if (string-match "\\S-" x)
13818 (concat indent x) x))
13819 lines)))
13820 (setq txt (concat first "\n"
13821 (mapconcat 'identity lines "\n"))))
13822 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13823 (setq txt (replace-match "\n\n" t t txt))
13824 (if (string-match "[ \t\n]*\\'" txt)
13825 (setq txt (replace-match "\n" t t txt))))
13826 ;; Put the modified text back into the remember buffer, for refile.
13827 (erase-buffer)
13828 (insert txt)
13829 (goto-char (point-min))
13830 (when (and (eq org-remember-interactive-interface 'refile)
13831 (not fastp))
13832 (org-refile nil (or visiting (find-file-noselect file)))
13833 (throw 'quit t))
13834 ;; Find the file
13835 (if (not visiting) (find-file-noselect file))
13836 (with-current-buffer (or visiting (get-file-buffer file))
13837 (unless (org-mode-p)
13838 (error "Target files for remember notes must be in Org-mode"))
13839 (save-excursion
13840 (save-restriction
13841 (widen)
13842 (and (goto-char (point-min))
13843 (not (re-search-forward "^\\* " nil t))
13844 (insert "\n* " (or heading "Notes") "\n"))
13845 (setq reversed (org-notes-order-reversed-p))
13847 ;; Find the default location
13848 (when (and heading (stringp heading) (string-match "\\S-" heading))
13849 (goto-char (point-min))
13850 (if (re-search-forward
13851 (concat "^\\*+[ \t]+" (regexp-quote heading)
13852 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13853 nil t)
13854 (setq org-goto-start-pos (match-beginning 0))
13855 (when fastp
13856 (goto-char (point-max))
13857 (unless (bolp) (newline))
13858 (insert "* " heading "\n")
13859 (setq org-goto-start-pos (point-at-bol 0)))))
13861 ;; Ask the User for a location, using the appropriate interface
13862 (cond
13863 (fastp (setq spos org-goto-start-pos
13864 exitcmd 'return))
13865 ((eq org-remember-interactive-interface 'outline)
13866 (setq spos (org-get-location (current-buffer)
13867 org-remember-help)
13868 exitcmd (cdr spos)
13869 spos (car spos)))
13870 ((eq org-remember-interactive-interface 'outline-path-completion)
13871 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13872 (org-refile-use-outline-path t))
13873 (setq spos (org-refile-get-location "Heading: ")
13874 exitcmd 'return
13875 spos (nth 3 spos))))
13876 (t (error "this should not hapen")))
13877 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13878 ; not handle this note
13879 (goto-char spos)
13880 (cond ((org-on-heading-p t)
13881 (org-back-to-heading t)
13882 (setq level (funcall outline-level))
13883 (cond
13884 ((eq exitcmd 'return)
13885 ;; sublevel of current
13886 (setq org-remember-previous-location
13887 (cons (abbreviate-file-name file)
13888 (org-get-heading 'notags)))
13889 (if reversed
13890 (outline-next-heading)
13891 (org-end-of-subtree t)
13892 (if (not (bolp))
13893 (if (looking-at "[ \t]*\n")
13894 (beginning-of-line 2)
13895 (end-of-line 1)
13896 (insert "\n"))))
13897 (bookmark-set "org-remember-last-stored")
13898 (org-paste-subtree (org-get-legal-level level 1) txt))
13899 ((eq exitcmd 'left)
13900 ;; before current
13901 (bookmark-set "org-remember-last-stored")
13902 (org-paste-subtree level txt))
13903 ((eq exitcmd 'right)
13904 ;; after current
13905 (org-end-of-subtree t)
13906 (bookmark-set "org-remember-last-stored")
13907 (org-paste-subtree level txt))
13908 (t (error "This should not happen"))))
13910 ((and (bobp) (not reversed))
13911 ;; Put it at the end, one level below level 1
13912 (save-restriction
13913 (widen)
13914 (goto-char (point-max))
13915 (if (not (bolp)) (newline))
13916 (bookmark-set "org-remember-last-stored")
13917 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13919 ((and (bobp) reversed)
13920 ;; Put it at the start, as level 1
13921 (save-restriction
13922 (widen)
13923 (goto-char (point-min))
13924 (re-search-forward "^\\*+ " nil t)
13925 (beginning-of-line 1)
13926 (bookmark-set "org-remember-last-stored")
13927 (org-paste-subtree 1 txt)))
13929 ;; Put it right there, with automatic level determined by
13930 ;; org-paste-subtree or from prefix arg
13931 (bookmark-set "org-remember-last-stored")
13932 (org-paste-subtree
13933 (if (numberp current-prefix-arg) current-prefix-arg)
13934 txt)))
13935 (when remember-save-after-remembering
13936 (save-buffer)
13937 (if (not visiting) (kill-buffer (current-buffer)))))))))
13939 t) ;; return t to indicate that we took care of this note.
13941 (defun org-get-org-file ()
13942 "Read a filename, with default directory `org-directory'."
13943 (let ((default (or org-default-notes-file remember-data-file)))
13944 (read-file-name (format "File name [%s]: " default)
13945 (file-name-as-directory org-directory)
13946 default)))
13948 (defun org-notes-order-reversed-p ()
13949 "Check if the current file should receive notes in reversed order."
13950 (cond
13951 ((not org-reverse-note-order) nil)
13952 ((eq t org-reverse-note-order) t)
13953 ((not (listp org-reverse-note-order)) nil)
13954 (t (catch 'exit
13955 (let ((all org-reverse-note-order)
13956 entry)
13957 (while (setq entry (pop all))
13958 (if (string-match (car entry) buffer-file-name)
13959 (throw 'exit (cdr entry))))
13960 nil)))))
13962 ;;; Refiling
13964 (defvar org-refile-target-table nil
13965 "The list of refile targets, created by `org-refile'.")
13967 (defvar org-agenda-new-buffers nil
13968 "Buffers created to visit agenda files.")
13970 (defun org-get-refile-targets (&optional default-buffer)
13971 "Produce a table with refile targets."
13972 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13973 targets txt re files f desc descre)
13974 (with-current-buffer (or default-buffer (current-buffer))
13975 (while (setq entry (pop entries))
13976 (setq files (car entry) desc (cdr entry))
13977 (cond
13978 ((null files) (setq files (list (current-buffer))))
13979 ((eq files 'org-agenda-files)
13980 (setq files (org-agenda-files 'unrestricted)))
13981 ((and (symbolp files) (fboundp files))
13982 (setq files (funcall files)))
13983 ((and (symbolp files) (boundp files))
13984 (setq files (symbol-value files))))
13985 (if (stringp files) (setq files (list files)))
13986 (cond
13987 ((eq (car desc) :tag)
13988 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13989 ((eq (car desc) :todo)
13990 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13991 ((eq (car desc) :regexp)
13992 (setq descre (cdr desc)))
13993 ((eq (car desc) :level)
13994 (setq descre (concat "^\\*\\{" (number-to-string
13995 (if org-odd-levels-only
13996 (1- (* 2 (cdr desc)))
13997 (cdr desc)))
13998 "\\}[ \t]")))
13999 ((eq (car desc) :maxlevel)
14000 (setq descre (concat "^\\*\\{1," (number-to-string
14001 (if org-odd-levels-only
14002 (1- (* 2 (cdr desc)))
14003 (cdr desc)))
14004 "\\}[ \t]")))
14005 (t (error "Bad refiling target description %s" desc)))
14006 (while (setq f (pop files))
14007 (save-excursion
14008 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14009 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14010 (save-excursion
14011 (save-restriction
14012 (widen)
14013 (goto-char (point-min))
14014 (while (re-search-forward descre nil t)
14015 (goto-char (point-at-bol))
14016 (when (looking-at org-complex-heading-regexp)
14017 (setq txt (match-string 4)
14018 re (concat "^" (regexp-quote
14019 (buffer-substring (match-beginning 1)
14020 (match-end 4)))))
14021 (if (match-end 5) (setq re (concat re "[ \t]+"
14022 (regexp-quote
14023 (match-string 5)))))
14024 (setq re (concat re "[ \t]*$"))
14025 (when org-refile-use-outline-path
14026 (setq txt (mapconcat 'identity
14027 (append
14028 (if (eq org-refile-use-outline-path 'file)
14029 (list (file-name-nondirectory
14030 (buffer-file-name (buffer-base-buffer))))
14031 (if (eq org-refile-use-outline-path 'full-file-path)
14032 (list (buffer-file-name (buffer-base-buffer)))))
14033 (org-get-outline-path)
14034 (list txt))
14035 "/")))
14036 (push (list txt f re (point)) targets))
14037 (goto-char (point-at-eol))))))))
14038 (nreverse targets))))
14040 (defun org-get-outline-path ()
14041 "Return the outline path to the current entry, as a list."
14042 (let (rtn)
14043 (save-excursion
14044 (while (org-up-heading-safe)
14045 (when (looking-at org-complex-heading-regexp)
14046 (push (org-match-string-no-properties 4) rtn)))
14047 rtn)))
14049 (defvar org-refile-history nil
14050 "History for refiling operations.")
14052 (defun org-refile (&optional goto default-buffer)
14053 "Move the entry at point to another heading.
14054 The list of target headings is compiled using the information in
14055 `org-refile-targets', which see. This list is created upon first use, and
14056 you can update it by calling this command with a double prefix (`C-u C-u').
14057 FIXME: Can we find a better way of updating?
14059 At the target location, the entry is filed as a subitem of the target heading.
14060 Depending on `org-reverse-note-order', the new subitem will either be the
14061 first of the last subitem.
14063 With prefix arg GOTO, the command will only visit the target location,
14064 not actually move anything.
14065 With a double prefix `C-c C-c', go to the location where the last refiling
14066 operation has put the subtree.
14068 With a double prefix argument, the command can be used to jump to any
14069 heading in the current buffer."
14070 (interactive "P")
14071 (let* ((cbuf (current-buffer))
14072 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14073 pos it nbuf file re level reversed)
14074 (if (equal goto '(16))
14075 (org-refile-goto-last-stored)
14076 (when (setq it (org-refile-get-location
14077 (if goto "Goto: " "Refile to: ") default-buffer))
14078 (setq file (nth 1 it)
14079 re (nth 2 it)
14080 pos (nth 3 it))
14081 (setq nbuf (or (find-buffer-visiting file)
14082 (find-file-noselect file)))
14083 (if goto
14084 (progn
14085 (switch-to-buffer nbuf)
14086 (goto-char pos)
14087 (org-show-context 'org-goto))
14088 (org-copy-special)
14089 (save-excursion
14090 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14091 (find-file-noselect file))))
14092 (setq reversed (org-notes-order-reversed-p))
14093 (save-excursion
14094 (save-restriction
14095 (widen)
14096 (goto-char pos)
14097 (looking-at outline-regexp)
14098 (setq level (org-get-legal-level (funcall outline-level) 1))
14099 (goto-char
14100 (if reversed
14101 (outline-next-heading)
14102 (or (save-excursion (outline-get-next-sibling))
14103 (org-end-of-subtree t t)
14104 (point-max))))
14105 (bookmark-set "org-refile-last-stored")
14106 (org-paste-subtree level))))
14107 (org-cut-special)
14108 (message "Entry refiled to \"%s\"" (car it)))))))
14110 (defun org-refile-goto-last-stored ()
14111 "Go to the location where the last refile was stored."
14112 (interactive)
14113 (bookmark-jump "org-refile-last-stored")
14114 (message "This is the location of the last refile"))
14116 (defun org-refile-get-location (&optional prompt default-buffer)
14117 "Prompt the user for a refile location, using PROMPT."
14118 (let ((org-refile-targets org-refile-targets)
14119 (org-refile-use-outline-path org-refile-use-outline-path))
14120 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14121 (unless org-refile-target-table
14122 (error "No refile targets"))
14123 (let* ((cbuf (current-buffer))
14124 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14125 (fname (and filename (file-truename filename)))
14126 (tbl (mapcar
14127 (lambda (x)
14128 (if (not (equal fname (file-truename (nth 1 x))))
14129 (cons (concat (car x) " (" (file-name-nondirectory
14130 (nth 1 x)) ")")
14131 (cdr x))
14133 org-refile-target-table))
14134 (completion-ignore-case t))
14135 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14136 tbl)))
14138 ;;;; Dynamic blocks
14140 (defun org-find-dblock (name)
14141 "Find the first dynamic block with name NAME in the buffer.
14142 If not found, stay at current position and return nil."
14143 (let (pos)
14144 (save-excursion
14145 (goto-char (point-min))
14146 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14147 nil t)
14148 (match-beginning 0))))
14149 (if pos (goto-char pos))
14150 pos))
14152 (defconst org-dblock-start-re
14153 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14154 "Matches the startline of a dynamic block, with parameters.")
14156 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14157 "Matches the end of a dyhamic block.")
14159 (defun org-create-dblock (plist)
14160 "Create a dynamic block section, with parameters taken from PLIST.
14161 PLIST must containe a :name entry which is used as name of the block."
14162 (unless (bolp) (newline))
14163 (let ((name (plist-get plist :name)))
14164 (insert "#+BEGIN: " name)
14165 (while plist
14166 (if (eq (car plist) :name)
14167 (setq plist (cddr plist))
14168 (insert " " (prin1-to-string (pop plist)))))
14169 (insert "\n\n#+END:\n")
14170 (beginning-of-line -2)))
14172 (defun org-prepare-dblock ()
14173 "Prepare dynamic block for refresh.
14174 This empties the block, puts the cursor at the insert position and returns
14175 the property list including an extra property :name with the block name."
14176 (unless (looking-at org-dblock-start-re)
14177 (error "Not at a dynamic block"))
14178 (let* ((begdel (1+ (match-end 0)))
14179 (name (org-no-properties (match-string 1)))
14180 (params (append (list :name name)
14181 (read (concat "(" (match-string 3) ")")))))
14182 (unless (re-search-forward org-dblock-end-re nil t)
14183 (error "Dynamic block not terminated"))
14184 (delete-region begdel (match-beginning 0))
14185 (goto-char begdel)
14186 (open-line 1)
14187 params))
14189 (defun org-map-dblocks (&optional command)
14190 "Apply COMMAND to all dynamic blocks in the current buffer.
14191 If COMMAND is not given, use `org-update-dblock'."
14192 (let ((cmd (or command 'org-update-dblock))
14193 pos)
14194 (save-excursion
14195 (goto-char (point-min))
14196 (while (re-search-forward org-dblock-start-re nil t)
14197 (goto-char (setq pos (match-beginning 0)))
14198 (condition-case nil
14199 (funcall cmd)
14200 (error (message "Error during update of dynamic block")))
14201 (goto-char pos)
14202 (unless (re-search-forward org-dblock-end-re nil t)
14203 (error "Dynamic block not terminated"))))))
14205 (defun org-dblock-update (&optional arg)
14206 "User command for updating dynamic blocks.
14207 Update the dynamic block at point. With prefix ARG, update all dynamic
14208 blocks in the buffer."
14209 (interactive "P")
14210 (if arg
14211 (org-update-all-dblocks)
14212 (or (looking-at org-dblock-start-re)
14213 (org-beginning-of-dblock))
14214 (org-update-dblock)))
14216 (defun org-update-dblock ()
14217 "Update the dynamic block at point
14218 This means to empty the block, parse for parameters and then call
14219 the correct writing function."
14220 (save-window-excursion
14221 (let* ((pos (point))
14222 (line (org-current-line))
14223 (params (org-prepare-dblock))
14224 (name (plist-get params :name))
14225 (cmd (intern (concat "org-dblock-write:" name))))
14226 (message "Updating dynamic block `%s' at line %d..." name line)
14227 (funcall cmd params)
14228 (message "Updating dynamic block `%s' at line %d...done" name line)
14229 (goto-char pos))))
14231 (defun org-beginning-of-dblock ()
14232 "Find the beginning of the dynamic block at point.
14233 Error if there is no scuh block at point."
14234 (let ((pos (point))
14235 beg)
14236 (end-of-line 1)
14237 (if (and (re-search-backward org-dblock-start-re nil t)
14238 (setq beg (match-beginning 0))
14239 (re-search-forward org-dblock-end-re nil t)
14240 (> (match-end 0) pos))
14241 (goto-char beg)
14242 (goto-char pos)
14243 (error "Not in a dynamic block"))))
14245 (defun org-update-all-dblocks ()
14246 "Update all dynamic blocks in the buffer.
14247 This function can be used in a hook."
14248 (when (org-mode-p)
14249 (org-map-dblocks 'org-update-dblock)))
14252 ;;;; Completion
14254 (defconst org-additional-option-like-keywords
14255 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14256 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14257 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14259 (defun org-complete (&optional arg)
14260 "Perform completion on word at point.
14261 At the beginning of a headline, this completes TODO keywords as given in
14262 `org-todo-keywords'.
14263 If the current word is preceded by a backslash, completes the TeX symbols
14264 that are supported for HTML support.
14265 If the current word is preceded by \"#+\", completes special words for
14266 setting file options.
14267 In the line after \"#+STARTUP:, complete valid keywords.\"
14268 At all other locations, this simply calls the value of
14269 `org-completion-fallback-command'."
14270 (interactive "P")
14271 (org-without-partial-completion
14272 (catch 'exit
14273 (let* ((end (point))
14274 (beg1 (save-excursion
14275 (skip-chars-backward (org-re "[:alnum:]_@"))
14276 (point)))
14277 (beg (save-excursion
14278 (skip-chars-backward "a-zA-Z0-9_:$")
14279 (point)))
14280 (confirm (lambda (x) (stringp (car x))))
14281 (searchhead (equal (char-before beg) ?*))
14282 (tag (and (equal (char-before beg1) ?:)
14283 (equal (char-after (point-at-bol)) ?*)))
14284 (prop (and (equal (char-before beg1) ?:)
14285 (not (equal (char-after (point-at-bol)) ?*))))
14286 (texp (equal (char-before beg) ?\\))
14287 (link (equal (char-before beg) ?\[))
14288 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14289 beg)
14290 "#+"))
14291 (startup (string-match "^#\\+STARTUP:.*"
14292 (buffer-substring (point-at-bol) (point))))
14293 (completion-ignore-case opt)
14294 (type nil)
14295 (tbl nil)
14296 (table (cond
14297 (opt
14298 (setq type :opt)
14299 (append
14300 (mapcar
14301 (lambda (x)
14302 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14303 (cons (match-string 2 x) (match-string 1 x)))
14304 (org-split-string (org-get-current-options) "\n"))
14305 (mapcar 'list org-additional-option-like-keywords)))
14306 (startup
14307 (setq type :startup)
14308 org-startup-options)
14309 (link (append org-link-abbrev-alist-local
14310 org-link-abbrev-alist))
14311 (texp
14312 (setq type :tex)
14313 org-html-entities)
14314 ((string-match "\\`\\*+[ \t]+\\'"
14315 (buffer-substring (point-at-bol) beg))
14316 (setq type :todo)
14317 (mapcar 'list org-todo-keywords-1))
14318 (searchhead
14319 (setq type :searchhead)
14320 (save-excursion
14321 (goto-char (point-min))
14322 (while (re-search-forward org-todo-line-regexp nil t)
14323 (push (list
14324 (org-make-org-heading-search-string
14325 (match-string 3) t))
14326 tbl)))
14327 tbl)
14328 (tag (setq type :tag beg beg1)
14329 (or org-tag-alist (org-get-buffer-tags)))
14330 (prop (setq type :prop beg beg1)
14331 (mapcar 'list (org-buffer-property-keys nil t t)))
14332 (t (progn
14333 (call-interactively org-completion-fallback-command)
14334 (throw 'exit nil)))))
14335 (pattern (buffer-substring-no-properties beg end))
14336 (completion (try-completion pattern table confirm)))
14337 (cond ((eq completion t)
14338 (if (not (assoc (upcase pattern) table))
14339 (message "Already complete")
14340 (if (equal type :opt)
14341 (insert (substring (cdr (assoc (upcase pattern) table))
14342 (length pattern)))
14343 (if (memq type '(:tag :prop)) (insert ":")))))
14344 ((null completion)
14345 (message "Can't find completion for \"%s\"" pattern)
14346 (ding))
14347 ((not (string= pattern completion))
14348 (delete-region beg end)
14349 (if (string-match " +$" completion)
14350 (setq completion (replace-match "" t t completion)))
14351 (insert completion)
14352 (if (get-buffer-window "*Completions*")
14353 (delete-window (get-buffer-window "*Completions*")))
14354 (if (assoc completion table)
14355 (if (eq type :todo) (insert " ")
14356 (if (memq type '(:tag :prop)) (insert ":"))))
14357 (if (and (equal type :opt) (assoc completion table))
14358 (message "%s" (substitute-command-keys
14359 "Press \\[org-complete] again to insert example settings"))))
14361 (message "Making completion list...")
14362 (let ((list (sort (all-completions pattern table confirm)
14363 'string<)))
14364 (with-output-to-temp-buffer "*Completions*"
14365 (condition-case nil
14366 ;; Protection needed for XEmacs and emacs 21
14367 (display-completion-list list pattern)
14368 (error (display-completion-list list)))))
14369 (message "Making completion list...%s" "done")))))))
14371 ;;;; TODO, DEADLINE, Comments
14373 (defun org-toggle-comment ()
14374 "Change the COMMENT state of an entry."
14375 (interactive)
14376 (save-excursion
14377 (org-back-to-heading)
14378 (let (case-fold-search)
14379 (if (looking-at (concat outline-regexp
14380 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14381 (replace-match "" t t nil 1)
14382 (if (looking-at outline-regexp)
14383 (progn
14384 (goto-char (match-end 0))
14385 (insert org-comment-string " ")))))))
14387 (defvar org-last-todo-state-is-todo nil
14388 "This is non-nil when the last TODO state change led to a TODO state.
14389 If the last change removed the TODO tag or switched to DONE, then
14390 this is nil.")
14392 (defvar org-setting-tags nil) ; dynamically skiped
14394 ;; FIXME: better place
14395 (defun org-property-or-variable-value (var &optional inherit)
14396 "Check if there is a property fixing the value of VAR.
14397 If yes, return this value. If not, return the current value of the variable."
14398 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14399 (if (and prop (stringp prop) (string-match "\\S-" prop))
14400 (read prop)
14401 (symbol-value var))))
14403 (defun org-parse-local-options (string var)
14404 "Parse STRING for startup setting relevant for variable VAR."
14405 (let ((rtn (symbol-value var))
14406 e opts)
14407 (save-match-data
14408 (if (or (not string) (not (string-match "\\S-" string)))
14410 (setq opts (delq nil (mapcar (lambda (x)
14411 (setq e (assoc x org-startup-options))
14412 (if (eq (nth 1 e) var) e nil))
14413 (org-split-string string "[ \t]+"))))
14414 (if (not opts)
14416 (setq rtn nil)
14417 (while (setq e (pop opts))
14418 (if (not (nth 3 e))
14419 (setq rtn (nth 2 e))
14420 (if (not (listp rtn)) (setq rtn nil))
14421 (push (nth 2 e) rtn)))
14422 rtn)))))
14424 (defvar org-blocker-hook nil
14425 "Hook for functions that are allowed to block a state change.
14427 Each function gets as its single argument a property list, see
14428 `org-trigger-hook' for more information about this list.
14430 If any of the functions in this hook returns nil, the state change
14431 is blocked.")
14433 (defvar org-trigger-hook nil
14434 "Hook for functions that are triggered by a state change.
14436 Each function gets as its single argument a property list with at least
14437 the following elements:
14439 (:type type-of-change :position pos-at-entry-start
14440 :from old-state :to new-state)
14442 Depending on the type, more properties may be present.
14444 This mechanism is currently implemented for:
14446 TODO state changes
14447 ------------------
14448 :type todo-state-change
14449 :from previous state (keyword as a string), or nil
14450 :to new state (keyword as a string), or nil")
14453 (defun org-todo (&optional arg)
14454 "Change the TODO state of an item.
14455 The state of an item is given by a keyword at the start of the heading,
14456 like
14457 *** TODO Write paper
14458 *** DONE Call mom
14460 The different keywords are specified in the variable `org-todo-keywords'.
14461 By default the available states are \"TODO\" and \"DONE\".
14462 So for this example: when the item starts with TODO, it is changed to DONE.
14463 When it starts with DONE, the DONE is removed. And when neither TODO nor
14464 DONE are present, add TODO at the beginning of the heading.
14466 With C-u prefix arg, use completion to determine the new state.
14467 With numeric prefix arg, switch to that state.
14469 For calling through lisp, arg is also interpreted in the following way:
14470 'none -> empty state
14471 \"\"(empty string) -> switch to empty state
14472 'done -> switch to DONE
14473 'nextset -> switch to the next set of keywords
14474 'previousset -> switch to the previous set of keywords
14475 \"WAITING\" -> switch to the specified keyword, but only if it
14476 really is a member of `org-todo-keywords'."
14477 (interactive "P")
14478 (save-excursion
14479 (catch 'exit
14480 (org-back-to-heading)
14481 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14482 (or (looking-at (concat " +" org-todo-regexp " *"))
14483 (looking-at " *"))
14484 (let* ((match-data (match-data))
14485 (startpos (point-at-bol))
14486 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14487 (org-log-done org-log-done)
14488 (org-log-repeat org-log-repeat)
14489 (org-todo-log-states org-todo-log-states)
14490 (this (match-string 1))
14491 (hl-pos (match-beginning 0))
14492 (head (org-get-todo-sequence-head this))
14493 (ass (assoc head org-todo-kwd-alist))
14494 (interpret (nth 1 ass))
14495 (done-word (nth 3 ass))
14496 (final-done-word (nth 4 ass))
14497 (last-state (or this ""))
14498 (completion-ignore-case t)
14499 (member (member this org-todo-keywords-1))
14500 (tail (cdr member))
14501 (state (cond
14502 ((and org-todo-key-trigger
14503 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14504 (and (not arg) org-use-fast-todo-selection
14505 (not (eq org-use-fast-todo-selection 'prefix)))))
14506 ;; Use fast selection
14507 (org-fast-todo-selection))
14508 ((and (equal arg '(4))
14509 (or (not org-use-fast-todo-selection)
14510 (not org-todo-key-trigger)))
14511 ;; Read a state with completion
14512 (completing-read "State: " (mapcar (lambda(x) (list x))
14513 org-todo-keywords-1)
14514 nil t))
14515 ((eq arg 'right)
14516 (if this
14517 (if tail (car tail) nil)
14518 (car org-todo-keywords-1)))
14519 ((eq arg 'left)
14520 (if (equal member org-todo-keywords-1)
14522 (if this
14523 (nth (- (length org-todo-keywords-1) (length tail) 2)
14524 org-todo-keywords-1)
14525 (org-last org-todo-keywords-1))))
14526 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14527 (setq arg nil))) ; hack to fall back to cycling
14528 (arg
14529 ;; user or caller requests a specific state
14530 (cond
14531 ((equal arg "") nil)
14532 ((eq arg 'none) nil)
14533 ((eq arg 'done) (or done-word (car org-done-keywords)))
14534 ((eq arg 'nextset)
14535 (or (car (cdr (member head org-todo-heads)))
14536 (car org-todo-heads)))
14537 ((eq arg 'previousset)
14538 (let ((org-todo-heads (reverse org-todo-heads)))
14539 (or (car (cdr (member head org-todo-heads)))
14540 (car org-todo-heads))))
14541 ((car (member arg org-todo-keywords-1)))
14542 ((nth (1- (prefix-numeric-value arg))
14543 org-todo-keywords-1))))
14544 ((null member) (or head (car org-todo-keywords-1)))
14545 ((equal this final-done-word) nil) ;; -> make empty
14546 ((null tail) nil) ;; -> first entry
14547 ((eq interpret 'sequence)
14548 (car tail))
14549 ((memq interpret '(type priority))
14550 (if (eq this-command last-command)
14551 (car tail)
14552 (if (> (length tail) 0)
14553 (or done-word (car org-done-keywords))
14554 nil)))
14555 (t nil)))
14556 (next (if state (concat " " state " ") " "))
14557 (change-plist (list :type 'todo-state-change :from this :to state
14558 :position startpos))
14559 dolog now-done-p)
14560 (when org-blocker-hook
14561 (unless (save-excursion
14562 (save-match-data
14563 (run-hook-with-args-until-failure
14564 'org-blocker-hook change-plist)))
14565 (if (interactive-p)
14566 (error "TODO state change from %s to %s blocked" this state)
14567 ;; fail silently
14568 (message "TODO state change from %s to %s blocked" this state)
14569 (throw 'exit nil))))
14570 (store-match-data match-data)
14571 (replace-match next t t)
14572 (unless (pos-visible-in-window-p hl-pos)
14573 (message "TODO state changed to %s" (org-trim next)))
14574 (unless head
14575 (setq head (org-get-todo-sequence-head state)
14576 ass (assoc head org-todo-kwd-alist)
14577 interpret (nth 1 ass)
14578 done-word (nth 3 ass)
14579 final-done-word (nth 4 ass)))
14580 (when (memq arg '(nextset previousset))
14581 (message "Keyword-Set %d/%d: %s"
14582 (- (length org-todo-sets) -1
14583 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14584 (length org-todo-sets)
14585 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14586 (setq org-last-todo-state-is-todo
14587 (not (member state org-done-keywords)))
14588 (setq now-done-p (and (member state org-done-keywords)
14589 (not (member this org-done-keywords))))
14590 (and logging (org-local-logging logging))
14591 (when (and (or org-todo-log-states org-log-done)
14592 (not (memq arg '(nextset previousset))))
14593 ;; we need to look at recording a time and note
14594 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14595 (nth 2 (assoc this org-todo-log-states))))
14596 (when (and state
14597 (member state org-not-done-keywords)
14598 (not (member this org-not-done-keywords)))
14599 ;; This is now a todo state and was not one before
14600 ;; If there was a CLOSED time stamp, get rid of it.
14601 (org-add-planning-info nil nil 'closed))
14602 (when (and now-done-p org-log-done)
14603 ;; It is now done, and it was not done before
14604 (org-add-planning-info 'closed (org-current-time))
14605 (if (and (not dolog) (eq 'note org-log-done))
14606 (org-add-log-maybe 'done state 'findpos 'note)))
14607 (when (and state dolog)
14608 ;; This is a non-nil state, and we need to log it
14609 (org-add-log-maybe 'state state 'findpos dolog)))
14610 ;; Fixup tag positioning
14611 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14612 (run-hooks 'org-after-todo-state-change-hook)
14613 (if (and arg (not (member state org-done-keywords)))
14614 (setq head (org-get-todo-sequence-head state)))
14615 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14616 ;; Do we need to trigger a repeat?
14617 (when now-done-p (org-auto-repeat-maybe state))
14618 ;; Fixup cursor location if close to the keyword
14619 (if (and (outline-on-heading-p)
14620 (not (bolp))
14621 (save-excursion (beginning-of-line 1)
14622 (looking-at org-todo-line-regexp))
14623 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14624 (progn
14625 (goto-char (or (match-end 2) (match-end 1)))
14626 (just-one-space)))
14627 (when org-trigger-hook
14628 (save-excursion
14629 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14631 (defun org-local-logging (value)
14632 "Get logging settings from a property VALUE."
14633 (let* (words w a)
14634 ;; directly set the variables, they are already local.
14635 (setq org-log-done nil
14636 org-log-repeat nil
14637 org-todo-log-states nil)
14638 (setq words (org-split-string value))
14639 (while (setq w (pop words))
14640 (cond
14641 ((setq a (assoc w org-startup-options))
14642 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14643 (set (nth 1 a) (nth 2 a))))
14644 ((setq a (org-extract-log-state-settings w))
14645 (and (member (car a) org-todo-keywords-1)
14646 (push a org-todo-log-states)))))))
14648 (defun org-get-todo-sequence-head (kwd)
14649 "Return the head of the TODO sequence to which KWD belongs.
14650 If KWD is not set, check if there is a text property remembering the
14651 right sequence."
14652 (let (p)
14653 (cond
14654 ((not kwd)
14655 (or (get-text-property (point-at-bol) 'org-todo-head)
14656 (progn
14657 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14658 nil (point-at-eol)))
14659 (get-text-property p 'org-todo-head))))
14660 ((not (member kwd org-todo-keywords-1))
14661 (car org-todo-keywords-1))
14662 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14664 (defun org-fast-todo-selection ()
14665 "Fast TODO keyword selection with single keys.
14666 Returns the new TODO keyword, or nil if no state change should occur."
14667 (let* ((fulltable org-todo-key-alist)
14668 (done-keywords org-done-keywords) ;; needed for the faces.
14669 (maxlen (apply 'max (mapcar
14670 (lambda (x)
14671 (if (stringp (car x)) (string-width (car x)) 0))
14672 fulltable)))
14673 (expert nil)
14674 (fwidth (+ maxlen 3 1 3))
14675 (ncol (/ (- (window-width) 4) fwidth))
14676 tg cnt e c tbl
14677 groups ingroup)
14678 (save-window-excursion
14679 (if expert
14680 (set-buffer (get-buffer-create " *Org todo*"))
14681 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14682 (erase-buffer)
14683 (org-set-local 'org-done-keywords done-keywords)
14684 (setq tbl fulltable cnt 0)
14685 (while (setq e (pop tbl))
14686 (cond
14687 ((equal e '(:startgroup))
14688 (push '() groups) (setq ingroup t)
14689 (when (not (= cnt 0))
14690 (setq cnt 0)
14691 (insert "\n"))
14692 (insert "{ "))
14693 ((equal e '(:endgroup))
14694 (setq ingroup nil cnt 0)
14695 (insert "}\n"))
14697 (setq tg (car e) c (cdr e))
14698 (if ingroup (push tg (car groups)))
14699 (setq tg (org-add-props tg nil 'face
14700 (org-get-todo-face tg)))
14701 (if (and (= cnt 0) (not ingroup)) (insert " "))
14702 (insert "[" c "] " tg (make-string
14703 (- fwidth 4 (length tg)) ?\ ))
14704 (when (= (setq cnt (1+ cnt)) ncol)
14705 (insert "\n")
14706 (if ingroup (insert " "))
14707 (setq cnt 0)))))
14708 (insert "\n")
14709 (goto-char (point-min))
14710 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14711 (fit-window-to-buffer))
14712 (message "[a-z..]:Set [SPC]:clear")
14713 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14714 (cond
14715 ((or (= c ?\C-g)
14716 (and (= c ?q) (not (rassoc c fulltable))))
14717 (setq quit-flag t))
14718 ((= c ?\ ) nil)
14719 ((setq e (rassoc c fulltable) tg (car e))
14721 (t (setq quit-flag t))))))
14723 (defun org-get-repeat ()
14724 "Check if tere is a deadline/schedule with repeater in this entry."
14725 (save-match-data
14726 (save-excursion
14727 (org-back-to-heading t)
14728 (if (re-search-forward
14729 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14730 (match-string 1)))))
14732 (defvar org-last-changed-timestamp)
14733 (defvar org-log-post-message)
14734 (defvar org-log-note-purpose)
14735 (defun org-auto-repeat-maybe (done-word)
14736 "Check if the current headline contains a repeated deadline/schedule.
14737 If yes, set TODO state back to what it was and change the base date
14738 of repeating deadline/scheduled time stamps to new date.
14739 This function should be run in the `org-after-todo-state-change-hook'."
14740 ;; last-state is dynamically scoped into this function
14741 (let* ((repeat (org-get-repeat))
14742 (aa (assoc last-state org-todo-kwd-alist))
14743 (interpret (nth 1 aa))
14744 (head (nth 2 aa))
14745 (whata '(("d" . day) ("m" . month) ("y" . year)))
14746 (msg "Entry repeats: ")
14747 (org-log-done nil)
14748 re type n what ts)
14749 (when repeat
14750 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14751 (org-todo (if (eq interpret 'type) last-state head))
14752 (when (and org-log-repeat
14753 (or (not (memq 'org-add-log-note
14754 (default-value 'post-command-hook)))
14755 (eq org-log-note-purpose 'done)))
14756 ;; Make sure a note is taken;
14757 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14758 'findpos org-log-repeat))
14759 (org-back-to-heading t)
14760 (org-add-planning-info nil nil 'closed)
14761 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14762 org-deadline-time-regexp "\\)\\|\\("
14763 org-ts-regexp "\\)"))
14764 (while (re-search-forward
14765 re (save-excursion (outline-next-heading) (point)) t)
14766 (setq type (if (match-end 1) org-scheduled-string
14767 (if (match-end 3) org-deadline-string "Plain:"))
14768 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14769 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14770 (setq n (string-to-number (match-string 1 ts))
14771 what (match-string 2 ts))
14772 (if (equal what "w") (setq n (* n 7) what "d"))
14773 (org-timestamp-change n (cdr (assoc what whata)))
14774 (setq msg (concat msg type org-last-changed-timestamp " "))))
14775 (setq org-log-post-message msg)
14776 (message "%s" msg))))
14778 (defun org-show-todo-tree (arg)
14779 "Make a compact tree which shows all headlines marked with TODO.
14780 The tree will show the lines where the regexp matches, and all higher
14781 headlines above the match.
14782 With \\[universal-argument] prefix, also show the DONE entries.
14783 With a numeric prefix N, construct a sparse tree for the Nth element
14784 of `org-todo-keywords-1'."
14785 (interactive "P")
14786 (let ((case-fold-search nil)
14787 (kwd-re
14788 (cond ((null arg) org-not-done-regexp)
14789 ((equal arg '(4))
14790 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14791 (mapcar 'list org-todo-keywords-1))))
14792 (concat "\\("
14793 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14794 "\\)\\>")))
14795 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14796 (regexp-quote (nth (1- (prefix-numeric-value arg))
14797 org-todo-keywords-1)))
14798 (t (error "Invalid prefix argument: %s" arg)))))
14799 (message "%d TODO entries found"
14800 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14802 (defun org-deadline (&optional remove)
14803 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14804 With argument REMOVE, remove any deadline from the item."
14805 (interactive "P")
14806 (if remove
14807 (progn
14808 (org-remove-timestamp-with-keyword org-deadline-string)
14809 (message "Item no longer has a deadline."))
14810 (org-add-planning-info 'deadline nil 'closed)))
14812 (defun org-schedule (&optional remove)
14813 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14814 With argument REMOVE, remove any scheduling date from the item."
14815 (interactive "P")
14816 (if remove
14817 (progn
14818 (org-remove-timestamp-with-keyword org-scheduled-string)
14819 (message "Item is no longer scheduled."))
14820 (org-add-planning-info 'scheduled nil 'closed)))
14822 (defun org-remove-timestamp-with-keyword (keyword)
14823 "Remove all time stamps with KEYWORD in the current entry."
14824 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14825 beg)
14826 (save-excursion
14827 (org-back-to-heading t)
14828 (setq beg (point))
14829 (org-end-of-subtree t t)
14830 (while (re-search-backward re beg t)
14831 (replace-match "")
14832 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14833 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14835 (defun org-add-planning-info (what &optional time &rest remove)
14836 "Insert new timestamp with keyword in the line directly after the headline.
14837 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14838 If non is given, the user is prompted for a date.
14839 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14840 be removed."
14841 (interactive)
14842 (let (org-time-was-given org-end-time-was-given)
14843 (when what (setq time (or time (org-read-date nil 'to-time))))
14844 (when (and org-insert-labeled-timestamps-at-point
14845 (member what '(scheduled deadline)))
14846 (insert
14847 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14848 (org-insert-time-stamp time org-time-was-given
14849 nil nil nil (list org-end-time-was-given))
14850 (setq what nil))
14851 (save-excursion
14852 (save-restriction
14853 (let (col list elt ts buffer-invisibility-spec)
14854 (org-back-to-heading t)
14855 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14856 (goto-char (match-end 1))
14857 (setq col (current-column))
14858 (goto-char (match-end 0))
14859 (if (eobp) (insert "\n") (forward-char 1))
14860 (if (and (not (looking-at outline-regexp))
14861 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14862 "[^\r\n]*"))
14863 (not (equal (match-string 1) org-clock-string)))
14864 (narrow-to-region (match-beginning 0) (match-end 0))
14865 (insert-before-markers "\n")
14866 (backward-char 1)
14867 (narrow-to-region (point) (point))
14868 (indent-to-column col))
14869 ;; Check if we have to remove something.
14870 (setq list (cons what remove))
14871 (while list
14872 (setq elt (pop list))
14873 (goto-char (point-min))
14874 (when (or (and (eq elt 'scheduled)
14875 (re-search-forward org-scheduled-time-regexp nil t))
14876 (and (eq elt 'deadline)
14877 (re-search-forward org-deadline-time-regexp nil t))
14878 (and (eq elt 'closed)
14879 (re-search-forward org-closed-time-regexp nil t)))
14880 (replace-match "")
14881 (if (looking-at "--+<[^>]+>") (replace-match ""))
14882 (if (looking-at " +") (replace-match ""))))
14883 (goto-char (point-max))
14884 (when what
14885 (insert
14886 (if (not (equal (char-before) ?\ )) " " "")
14887 (cond ((eq what 'scheduled) org-scheduled-string)
14888 ((eq what 'deadline) org-deadline-string)
14889 ((eq what 'closed) org-closed-string))
14890 " ")
14891 (setq ts (org-insert-time-stamp
14892 time
14893 (or org-time-was-given
14894 (and (eq what 'closed) org-log-done-with-time))
14895 (eq what 'closed)
14896 nil nil (list org-end-time-was-given)))
14897 (end-of-line 1))
14898 (goto-char (point-min))
14899 (widen)
14900 (if (looking-at "[ \t]+\r?\n")
14901 (replace-match ""))
14902 ts)))))
14904 (defvar org-log-note-marker (make-marker))
14905 (defvar org-log-note-purpose nil)
14906 (defvar org-log-note-state nil)
14907 (defvar org-log-note-how nil)
14908 (defvar org-log-note-window-configuration nil)
14909 (defvar org-log-note-return-to (make-marker))
14910 (defvar org-log-post-message nil
14911 "Message to be displayed after a log note has been stored.
14912 The auto-repeater uses this.")
14914 (defun org-add-log-maybe (&optional purpose state findpos how)
14915 "Set up the post command hook to take a note.
14916 If this is about to TODO state change, the new state is expected in STATE.
14917 When FINDPOS is non-nil, find the correct position for the note in
14918 the current entry. If not, assume that it can be inserted at point."
14919 (save-excursion
14920 (when findpos
14921 (org-back-to-heading t)
14922 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14923 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14924 "[^\r\n]*\\)?"))
14925 (goto-char (match-end 0))
14926 (unless org-log-states-order-reversed
14927 (and (= (char-after) ?\n) (forward-char 1))
14928 (org-skip-over-state-notes)
14929 (skip-chars-backward " \t\n\r")))
14930 (move-marker org-log-note-marker (point))
14931 (setq org-log-note-purpose purpose
14932 org-log-note-state state
14933 org-log-note-how how)
14934 (add-hook 'post-command-hook 'org-add-log-note 'append)))
14936 (defun org-skip-over-state-notes ()
14937 "Skip past the list of State notes in an entry."
14938 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14939 (while (looking-at "[ \t]*- State")
14940 (condition-case nil
14941 (org-next-item)
14942 (error (org-end-of-item)))))
14944 (defun org-add-log-note (&optional purpose)
14945 "Pop up a window for taking a note, and add this note later at point."
14946 (remove-hook 'post-command-hook 'org-add-log-note)
14947 (setq org-log-note-window-configuration (current-window-configuration))
14948 (delete-other-windows)
14949 (move-marker org-log-note-return-to (point))
14950 (switch-to-buffer (marker-buffer org-log-note-marker))
14951 (goto-char org-log-note-marker)
14952 (org-switch-to-buffer-other-window "*Org Note*")
14953 (erase-buffer)
14954 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
14955 (org-store-log-note)
14956 (let ((org-inhibit-startup t)) (org-mode))
14957 (insert (format "# Insert note for %s.
14958 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14959 (cond
14960 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14961 ((eq org-log-note-purpose 'done) "closed todo item")
14962 ((eq org-log-note-purpose 'state)
14963 (format "state change to \"%s\"" org-log-note-state))
14964 (t (error "This should not happen")))))
14965 (org-set-local 'org-finish-function 'org-store-log-note)))
14967 (defun org-store-log-note ()
14968 "Finish taking a log note, and insert it to where it belongs."
14969 (let ((txt (buffer-string))
14970 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14971 lines ind)
14972 (kill-buffer (current-buffer))
14973 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14974 (setq txt (replace-match "" t t txt)))
14975 (if (string-match "\\s-+\\'" txt)
14976 (setq txt (replace-match "" t t txt)))
14977 (setq lines (org-split-string txt "\n"))
14978 (when (and note (string-match "\\S-" note))
14979 (setq note
14980 (org-replace-escapes
14981 note
14982 (list (cons "%u" (user-login-name))
14983 (cons "%U" user-full-name)
14984 (cons "%t" (format-time-string
14985 (org-time-stamp-format 'long 'inactive)
14986 (current-time)))
14987 (cons "%s" (if org-log-note-state
14988 (concat "\"" org-log-note-state "\"")
14989 "")))))
14990 (if lines (setq note (concat note " \\\\")))
14991 (push note lines))
14992 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14993 (when lines
14994 (save-excursion
14995 (set-buffer (marker-buffer org-log-note-marker))
14996 (save-excursion
14997 (goto-char org-log-note-marker)
14998 (move-marker org-log-note-marker nil)
14999 (end-of-line 1)
15000 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15001 (indent-relative nil)
15002 (insert "- " (pop lines))
15003 (org-indent-line-function)
15004 (beginning-of-line 1)
15005 (looking-at "[ \t]*")
15006 (setq ind (concat (match-string 0) " "))
15007 (end-of-line 1)
15008 (while lines (insert "\n" ind (pop lines)))))))
15009 (set-window-configuration org-log-note-window-configuration)
15010 (with-current-buffer (marker-buffer org-log-note-return-to)
15011 (goto-char org-log-note-return-to))
15012 (move-marker org-log-note-return-to nil)
15013 (and org-log-post-message (message "%s" org-log-post-message)))
15015 ;; FIXME: what else would be useful?
15016 ;; - priority
15017 ;; - date
15019 (defun org-sparse-tree (&optional arg)
15020 "Create a sparse tree, prompt for the details.
15021 This command can create sparse trees. You first need to select the type
15022 of match used to create the tree:
15024 t Show entries with a specific TODO keyword.
15025 T Show entries selected by a tags match.
15026 p Enter a property name and its value (both with completion on existing
15027 names/values) and show entries with that property.
15028 r Show entries matching a regular expression
15029 d Show deadlines due within `org-deadline-warning-days'."
15030 (interactive "P")
15031 (let (ans kwd value)
15032 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15033 (setq ans (read-char-exclusive))
15034 (cond
15035 ((equal ans ?d)
15036 (call-interactively 'org-check-deadlines))
15037 ((equal ans ?b)
15038 (call-interactively 'org-check-before-date))
15039 ((equal ans ?t)
15040 (org-show-todo-tree '(4)))
15041 ((equal ans ?T)
15042 (call-interactively 'org-tags-sparse-tree))
15043 ((member ans '(?p ?P))
15044 (setq kwd (completing-read "Property: "
15045 (mapcar 'list (org-buffer-property-keys))))
15046 (setq value (completing-read "Value: "
15047 (mapcar 'list (org-property-values kwd))))
15048 (unless (string-match "\\`{.*}\\'" value)
15049 (setq value (concat "\"" value "\"")))
15050 (org-tags-sparse-tree arg (concat kwd "=" value)))
15051 ((member ans '(?r ?R ?/))
15052 (call-interactively 'org-occur))
15053 (t (error "No such sparse tree command \"%c\"" ans)))))
15055 (defvar org-occur-highlights nil)
15056 (make-variable-buffer-local 'org-occur-highlights)
15058 (defun org-occur (regexp &optional keep-previous callback)
15059 "Make a compact tree which shows all matches of REGEXP.
15060 The tree will show the lines where the regexp matches, and all higher
15061 headlines above the match. It will also show the heading after the match,
15062 to make sure editing the matching entry is easy.
15063 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15064 call to `org-occur' will be kept, to allow stacking of calls to this
15065 command.
15066 If CALLBACK is non-nil, it is a function which is called to confirm
15067 that the match should indeed be shown."
15068 (interactive "sRegexp: \nP")
15069 (or keep-previous (org-remove-occur-highlights nil nil t))
15070 (let ((cnt 0))
15071 (save-excursion
15072 (goto-char (point-min))
15073 (if (or (not keep-previous) ; do not want to keep
15074 (not org-occur-highlights)) ; no previous matches
15075 ;; hide everything
15076 (org-overview))
15077 (while (re-search-forward regexp nil t)
15078 (when (or (not callback)
15079 (save-match-data (funcall callback)))
15080 (setq cnt (1+ cnt))
15081 (when org-highlight-sparse-tree-matches
15082 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15083 (org-show-context 'occur-tree))))
15084 (when org-remove-highlights-with-change
15085 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15086 nil 'local))
15087 (unless org-sparse-tree-open-archived-trees
15088 (org-hide-archived-subtrees (point-min) (point-max)))
15089 (run-hooks 'org-occur-hook)
15090 (if (interactive-p)
15091 (message "%d match(es) for regexp %s" cnt regexp))
15092 cnt))
15094 (defun org-show-context (&optional key)
15095 "Make sure point and context and visible.
15096 How much context is shown depends upon the variables
15097 `org-show-hierarchy-above', `org-show-following-heading'. and
15098 `org-show-siblings'."
15099 (let ((heading-p (org-on-heading-p t))
15100 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15101 (following-p (org-get-alist-option org-show-following-heading key))
15102 (entry-p (org-get-alist-option org-show-entry-below key))
15103 (siblings-p (org-get-alist-option org-show-siblings key)))
15104 (catch 'exit
15105 ;; Show heading or entry text
15106 (if (and heading-p (not entry-p))
15107 (org-flag-heading nil) ; only show the heading
15108 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15109 (org-show-hidden-entry))) ; show entire entry
15110 (when following-p
15111 ;; Show next sibling, or heading below text
15112 (save-excursion
15113 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15114 (org-flag-heading nil))))
15115 (when siblings-p (org-show-siblings))
15116 (when hierarchy-p
15117 ;; show all higher headings, possibly with siblings
15118 (save-excursion
15119 (while (and (condition-case nil
15120 (progn (org-up-heading-all 1) t)
15121 (error nil))
15122 (not (bobp)))
15123 (org-flag-heading nil)
15124 (when siblings-p (org-show-siblings))))))))
15126 (defun org-reveal (&optional siblings)
15127 "Show current entry, hierarchy above it, and the following headline.
15128 This can be used to show a consistent set of context around locations
15129 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15130 not t for the search context.
15132 With optional argument SIBLINGS, on each level of the hierarchy all
15133 siblings are shown. This repairs the tree structure to what it would
15134 look like when opened with hierarchical calls to `org-cycle'."
15135 (interactive "P")
15136 (let ((org-show-hierarchy-above t)
15137 (org-show-following-heading t)
15138 (org-show-siblings (if siblings t org-show-siblings)))
15139 (org-show-context nil)))
15141 (defun org-highlight-new-match (beg end)
15142 "Highlight from BEG to END and mark the highlight is an occur headline."
15143 (let ((ov (org-make-overlay beg end)))
15144 (org-overlay-put ov 'face 'secondary-selection)
15145 (push ov org-occur-highlights)))
15147 (defun org-remove-occur-highlights (&optional beg end noremove)
15148 "Remove the occur highlights from the buffer.
15149 BEG and END are ignored. If NOREMOVE is nil, remove this function
15150 from the `before-change-functions' in the current buffer."
15151 (interactive)
15152 (unless org-inhibit-highlight-removal
15153 (mapc 'org-delete-overlay org-occur-highlights)
15154 (setq org-occur-highlights nil)
15155 (unless noremove
15156 (remove-hook 'before-change-functions
15157 'org-remove-occur-highlights 'local))))
15159 ;;;; Priorities
15161 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15162 "Regular expression matching the priority indicator.")
15164 (defvar org-remove-priority-next-time nil)
15166 (defun org-priority-up ()
15167 "Increase the priority of the current item."
15168 (interactive)
15169 (org-priority 'up))
15171 (defun org-priority-down ()
15172 "Decrease the priority of the current item."
15173 (interactive)
15174 (org-priority 'down))
15176 (defun org-priority (&optional action)
15177 "Change the priority of an item by ARG.
15178 ACTION can be `set', `up', `down', or a character."
15179 (interactive)
15180 (setq action (or action 'set))
15181 (let (current new news have remove)
15182 (save-excursion
15183 (org-back-to-heading)
15184 (if (looking-at org-priority-regexp)
15185 (setq current (string-to-char (match-string 2))
15186 have t)
15187 (setq current org-default-priority))
15188 (cond
15189 ((or (eq action 'set) (integerp action))
15190 (if (integerp action)
15191 (setq new action)
15192 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15193 (setq new (read-char-exclusive)))
15194 (if (and (= (upcase org-highest-priority) org-highest-priority)
15195 (= (upcase org-lowest-priority) org-lowest-priority))
15196 (setq new (upcase new)))
15197 (cond ((equal new ?\ ) (setq remove t))
15198 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15199 (error "Priority must be between `%c' and `%c'"
15200 org-highest-priority org-lowest-priority))))
15201 ((eq action 'up)
15202 (if (and (not have) (eq last-command this-command))
15203 (setq new org-lowest-priority)
15204 (setq new (if (and org-priority-start-cycle-with-default (not have))
15205 org-default-priority (1- current)))))
15206 ((eq action 'down)
15207 (if (and (not have) (eq last-command this-command))
15208 (setq new org-highest-priority)
15209 (setq new (if (and org-priority-start-cycle-with-default (not have))
15210 org-default-priority (1+ current)))))
15211 (t (error "Invalid action")))
15212 (if (or (< (upcase new) org-highest-priority)
15213 (> (upcase new) org-lowest-priority))
15214 (setq remove t))
15215 (setq news (format "%c" new))
15216 (if have
15217 (if remove
15218 (replace-match "" t t nil 1)
15219 (replace-match news t t nil 2))
15220 (if remove
15221 (error "No priority cookie found in line")
15222 (looking-at org-todo-line-regexp)
15223 (if (match-end 2)
15224 (progn
15225 (goto-char (match-end 2))
15226 (insert " [#" news "]"))
15227 (goto-char (match-beginning 3))
15228 (insert "[#" news "] ")))))
15229 (org-preserve-lc (org-set-tags nil 'align))
15230 (if remove
15231 (message "Priority removed")
15232 (message "Priority of current item set to %s" news))))
15235 (defun org-get-priority (s)
15236 "Find priority cookie and return priority."
15237 (save-match-data
15238 (if (not (string-match org-priority-regexp s))
15239 (* 1000 (- org-lowest-priority org-default-priority))
15240 (* 1000 (- org-lowest-priority
15241 (string-to-char (match-string 2 s)))))))
15243 ;;;; Tags
15245 (defun org-scan-tags (action matcher &optional todo-only)
15246 "Scan headline tags with inheritance and produce output ACTION.
15247 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15248 evaluated, testing if a given set of tags qualifies a headline for
15249 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15250 are included in the output."
15251 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15252 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15253 (org-re
15254 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15255 (props (list 'face nil
15256 'done-face 'org-done
15257 'undone-face nil
15258 'mouse-face 'highlight
15259 'org-not-done-regexp org-not-done-regexp
15260 'org-todo-regexp org-todo-regexp
15261 'keymap org-agenda-keymap
15262 'help-echo
15263 (format "mouse-2 or RET jump to org file %s"
15264 (abbreviate-file-name
15265 (or (buffer-file-name (buffer-base-buffer))
15266 (buffer-name (buffer-base-buffer)))))))
15267 (case-fold-search nil)
15268 lspos
15269 tags tags-list tags-alist (llast 0) rtn level category i txt
15270 todo marker entry priority)
15271 (save-excursion
15272 (goto-char (point-min))
15273 (when (eq action 'sparse-tree)
15274 (org-overview)
15275 (org-remove-occur-highlights))
15276 (while (re-search-forward re nil t)
15277 (catch :skip
15278 (setq todo (if (match-end 1) (match-string 2))
15279 tags (if (match-end 4) (match-string 4)))
15280 (goto-char (setq lspos (1+ (match-beginning 0))))
15281 (setq level (org-reduced-level (funcall outline-level))
15282 category (org-get-category))
15283 (setq i llast llast level)
15284 ;; remove tag lists from same and sublevels
15285 (while (>= i level)
15286 (when (setq entry (assoc i tags-alist))
15287 (setq tags-alist (delete entry tags-alist)))
15288 (setq i (1- i)))
15289 ;; add the nex tags
15290 (when tags
15291 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15292 tags-alist
15293 (cons (cons level tags) tags-alist)))
15294 ;; compile tags for current headline
15295 (setq tags-list
15296 (if org-use-tag-inheritance
15297 (apply 'append (mapcar 'cdr tags-alist))
15298 tags))
15299 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15300 (eval matcher)
15301 (or (not org-agenda-skip-archived-trees)
15302 (not (member org-archive-tag tags-list))))
15303 (and (eq action 'agenda) (org-agenda-skip))
15304 ;; list this headline
15306 (if (eq action 'sparse-tree)
15307 (progn
15308 (and org-highlight-sparse-tree-matches
15309 (org-get-heading) (match-end 0)
15310 (org-highlight-new-match
15311 (match-beginning 0) (match-beginning 1)))
15312 (org-show-context 'tags-tree))
15313 (setq txt (org-format-agenda-item
15315 (concat
15316 (if org-tags-match-list-sublevels
15317 (make-string (1- level) ?.) "")
15318 (org-get-heading))
15319 category tags-list)
15320 priority (org-get-priority txt))
15321 (goto-char lspos)
15322 (setq marker (org-agenda-new-marker))
15323 (org-add-props txt props
15324 'org-marker marker 'org-hd-marker marker 'org-category category
15325 'priority priority 'type "tagsmatch")
15326 (push txt rtn))
15327 ;; if we are to skip sublevels, jump to end of subtree
15328 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15329 (when (and (eq action 'sparse-tree)
15330 (not org-sparse-tree-open-archived-trees))
15331 (org-hide-archived-subtrees (point-min) (point-max)))
15332 (nreverse rtn)))
15334 (defvar todo-only) ;; dynamically scoped
15336 (defun org-tags-sparse-tree (&optional todo-only match)
15337 "Create a sparse tree according to tags string MATCH.
15338 MATCH can contain positive and negative selection of tags, like
15339 \"+WORK+URGENT-WITHBOSS\".
15340 If optional argument TODO_ONLY is non-nil, only select lines that are
15341 also TODO lines."
15342 (interactive "P")
15343 (org-prepare-agenda-buffers (list (current-buffer)))
15344 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15346 (defvar org-cached-props nil)
15347 (defun org-cached-entry-get (pom property)
15348 (if (or (eq t org-use-property-inheritance)
15349 (member property org-use-property-inheritance))
15350 ;; Caching is not possible, check it directly
15351 (org-entry-get pom property 'inherit)
15352 ;; Get all properties, so that we can do complicated checks easily
15353 (cdr (assoc property (or org-cached-props
15354 (setq org-cached-props
15355 (org-entry-properties pom)))))))
15357 (defun org-global-tags-completion-table (&optional files)
15358 "Return the list of all tags in all agenda buffer/files."
15359 (save-excursion
15360 (org-uniquify
15361 (delq nil
15362 (apply 'append
15363 (mapcar
15364 (lambda (file)
15365 (set-buffer (find-file-noselect file))
15366 (append (org-get-buffer-tags)
15367 (mapcar (lambda (x) (if (stringp (car-safe x))
15368 (list (car-safe x)) nil))
15369 org-tag-alist)))
15370 (if (and files (car files))
15371 files
15372 (org-agenda-files))))))))
15374 (defun org-make-tags-matcher (match)
15375 "Create the TAGS//TODO matcher form for the selection string MATCH."
15376 ;; todo-only is scoped dynamically into this function, and the function
15377 ;; may change it it the matcher asksk for it.
15378 (unless match
15379 ;; Get a new match request, with completion
15380 (let ((org-last-tags-completion-table
15381 (org-global-tags-completion-table)))
15382 (setq match (completing-read
15383 "Match: " 'org-tags-completion-function nil nil nil
15384 'org-tags-history))))
15386 ;; Parse the string and create a lisp form
15387 (let ((match0 match)
15388 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15389 minus tag mm
15390 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15391 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15392 (if (string-match "/+" match)
15393 ;; match contains also a todo-matching request
15394 (progn
15395 (setq tagsmatch (substring match 0 (match-beginning 0))
15396 todomatch (substring match (match-end 0)))
15397 (if (string-match "^!" todomatch)
15398 (setq todo-only t todomatch (substring todomatch 1)))
15399 (if (string-match "^\\s-*$" todomatch)
15400 (setq todomatch nil)))
15401 ;; only matching tags
15402 (setq tagsmatch match todomatch nil))
15404 ;; Make the tags matcher
15405 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15406 (setq tagsmatcher t)
15407 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15408 (while (setq term (pop orterms))
15409 (while (and (equal (substring term -1) "\\") orterms)
15410 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15411 (while (string-match re term)
15412 (setq minus (and (match-end 1)
15413 (equal (match-string 1 term) "-"))
15414 tag (match-string 2 term)
15415 re-p (equal (string-to-char tag) ?{)
15416 level-p (match-end 3)
15417 prop-p (match-end 4)
15418 mm (cond
15419 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15420 (level-p `(= level ,(string-to-number
15421 (match-string 3 term))))
15422 (prop-p
15423 (setq pn (match-string 4 term)
15424 pv (match-string 5 term)
15425 cat-p (equal pn "CATEGORY")
15426 re-p (equal (string-to-char pv) ?{)
15427 pv (substring pv 1 -1))
15428 (if (equal pn "CATEGORY")
15429 (setq gv '(get-text-property (point) 'org-category))
15430 (setq gv `(org-cached-entry-get nil ,pn)))
15431 (if re-p
15432 `(string-match ,pv (or ,gv ""))
15433 `(equal ,pv (or ,gv ""))))
15434 (t `(member ,(downcase tag) tags-list)))
15435 mm (if minus (list 'not mm) mm)
15436 term (substring term (match-end 0)))
15437 (push mm tagsmatcher))
15438 (push (if (> (length tagsmatcher) 1)
15439 (cons 'and tagsmatcher)
15440 (car tagsmatcher))
15441 orlist)
15442 (setq tagsmatcher nil))
15443 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15444 (setq tagsmatcher
15445 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15447 ;; Make the todo matcher
15448 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15449 (setq todomatcher t)
15450 (setq orterms (org-split-string todomatch "|") orlist nil)
15451 (while (setq term (pop orterms))
15452 (while (string-match re term)
15453 (setq minus (and (match-end 1)
15454 (equal (match-string 1 term) "-"))
15455 kwd (match-string 2 term)
15456 re-p (equal (string-to-char kwd) ?{)
15457 term (substring term (match-end 0))
15458 mm (if re-p
15459 `(string-match ,(substring kwd 1 -1) todo)
15460 (list 'equal 'todo kwd))
15461 mm (if minus (list 'not mm) mm))
15462 (push mm todomatcher))
15463 (push (if (> (length todomatcher) 1)
15464 (cons 'and todomatcher)
15465 (car todomatcher))
15466 orlist)
15467 (setq todomatcher nil))
15468 (setq todomatcher (if (> (length orlist) 1)
15469 (cons 'or orlist) (car orlist))))
15471 ;; Return the string and lisp forms of the matcher
15472 (setq matcher (if todomatcher
15473 (list 'and tagsmatcher todomatcher)
15474 tagsmatcher))
15475 (cons match0 matcher)))
15477 (defun org-match-any-p (re list)
15478 "Does re match any element of list?"
15479 (setq list (mapcar (lambda (x) (string-match re x)) list))
15480 (delq nil list))
15482 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15483 (defvar org-tags-overlay (org-make-overlay 1 1))
15484 (org-detach-overlay org-tags-overlay)
15486 (defun org-align-tags-here (to-col)
15487 ;; Assumes that this is a headline
15488 (let ((pos (point)) (col (current-column)) tags)
15489 (beginning-of-line 1)
15490 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15491 (< pos (match-beginning 2)))
15492 (progn
15493 (setq tags (match-string 2))
15494 (goto-char (match-beginning 1))
15495 (insert " ")
15496 (delete-region (point) (1+ (match-end 0)))
15497 (backward-char 1)
15498 (move-to-column
15499 (max (1+ (current-column))
15500 (1+ col)
15501 (if (> to-col 0)
15502 to-col
15503 (- (abs to-col) (length tags))))
15505 (insert tags)
15506 (move-to-column (min (current-column) col) t))
15507 (goto-char pos))))
15509 (defun org-set-tags (&optional arg just-align)
15510 "Set the tags for the current headline.
15511 With prefix ARG, realign all tags in headings in the current buffer."
15512 (interactive "P")
15513 (let* ((re (concat "^" outline-regexp))
15514 (current (org-get-tags-string))
15515 (col (current-column))
15516 (org-setting-tags t)
15517 table current-tags inherited-tags ; computed below when needed
15518 tags p0 c0 c1 rpl)
15519 (if arg
15520 (save-excursion
15521 (goto-char (point-min))
15522 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15523 (while (re-search-forward re nil t)
15524 (org-set-tags nil t)
15525 (end-of-line 1)))
15526 (message "All tags realigned to column %d" org-tags-column))
15527 (if just-align
15528 (setq tags current)
15529 ;; Get a new set of tags from the user
15530 (save-excursion
15531 (setq table (or org-tag-alist (org-get-buffer-tags))
15532 org-last-tags-completion-table table
15533 current-tags (org-split-string current ":")
15534 inherited-tags (nreverse
15535 (nthcdr (length current-tags)
15536 (nreverse (org-get-tags-at))))
15537 tags
15538 (if (or (eq t org-use-fast-tag-selection)
15539 (and org-use-fast-tag-selection
15540 (delq nil (mapcar 'cdr table))))
15541 (org-fast-tag-selection
15542 current-tags inherited-tags table
15543 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15544 (let ((org-add-colon-after-tag-completion t))
15545 (org-trim
15546 (org-without-partial-completion
15547 (completing-read "Tags: " 'org-tags-completion-function
15548 nil nil current 'org-tags-history)))))))
15549 (while (string-match "[-+&]+" tags)
15550 ;; No boolean logic, just a list
15551 (setq tags (replace-match ":" t t tags))))
15553 (if (string-match "\\`[\t ]*\\'" tags)
15554 (setq tags "")
15555 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15556 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15558 ;; Insert new tags at the correct column
15559 (beginning-of-line 1)
15560 (cond
15561 ((and (equal current "") (equal tags "")))
15562 ((re-search-forward
15563 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15564 (point-at-eol) t)
15565 (if (equal tags "")
15566 (setq rpl "")
15567 (goto-char (match-beginning 0))
15568 (setq c0 (current-column) p0 (point)
15569 c1 (max (1+ c0) (if (> org-tags-column 0)
15570 org-tags-column
15571 (- (- org-tags-column) (length tags))))
15572 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15573 (replace-match rpl t t)
15574 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15575 tags)
15576 (t (error "Tags alignment failed")))
15577 (move-to-column col)
15578 (unless just-align
15579 (run-hooks 'org-after-tags-change-hook)))))
15581 (defun org-change-tag-in-region (beg end tag off)
15582 "Add or remove TAG for each entry in the region.
15583 This works in the agenda, and also in an org-mode buffer."
15584 (interactive
15585 (list (region-beginning) (region-end)
15586 (let ((org-last-tags-completion-table
15587 (if (org-mode-p)
15588 (org-get-buffer-tags)
15589 (org-global-tags-completion-table))))
15590 (completing-read
15591 "Tag: " 'org-tags-completion-function nil nil nil
15592 'org-tags-history))
15593 (progn
15594 (message "[s]et or [r]emove? ")
15595 (equal (read-char-exclusive) ?r))))
15596 (if (fboundp 'deactivate-mark) (deactivate-mark))
15597 (let ((agendap (equal major-mode 'org-agenda-mode))
15598 l1 l2 m buf pos newhead (cnt 0))
15599 (goto-char end)
15600 (setq l2 (1- (org-current-line)))
15601 (goto-char beg)
15602 (setq l1 (org-current-line))
15603 (loop for l from l1 to l2 do
15604 (goto-line l)
15605 (setq m (get-text-property (point) 'org-hd-marker))
15606 (when (or (and (org-mode-p) (org-on-heading-p))
15607 (and agendap m))
15608 (setq buf (if agendap (marker-buffer m) (current-buffer))
15609 pos (if agendap m (point)))
15610 (with-current-buffer buf
15611 (save-excursion
15612 (save-restriction
15613 (goto-char pos)
15614 (setq cnt (1+ cnt))
15615 (org-toggle-tag tag (if off 'off 'on))
15616 (setq newhead (org-get-heading)))))
15617 (and agendap (org-agenda-change-all-lines newhead m))))
15618 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15620 (defun org-tags-completion-function (string predicate &optional flag)
15621 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15622 (confirm (lambda (x) (stringp (car x)))))
15623 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15624 (setq s1 (match-string 1 string)
15625 s2 (match-string 2 string))
15626 (setq s1 "" s2 string))
15627 (cond
15628 ((eq flag nil)
15629 ;; try completion
15630 (setq rtn (try-completion s2 ctable confirm))
15631 (if (stringp rtn)
15632 (setq rtn
15633 (concat s1 s2 (substring rtn (length s2))
15634 (if (and org-add-colon-after-tag-completion
15635 (assoc rtn ctable))
15636 ":" ""))))
15637 rtn)
15638 ((eq flag t)
15639 ;; all-completions
15640 (all-completions s2 ctable confirm)
15642 ((eq flag 'lambda)
15643 ;; exact match?
15644 (assoc s2 ctable)))
15647 (defun org-fast-tag-insert (kwd tags face &optional end)
15648 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15649 (insert (format "%-12s" (concat kwd ":"))
15650 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15651 (or end "")))
15653 (defun org-fast-tag-show-exit (flag)
15654 (save-excursion
15655 (goto-line 3)
15656 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15657 (replace-match ""))
15658 (when flag
15659 (end-of-line 1)
15660 (move-to-column (- (window-width) 19) t)
15661 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15663 (defun org-set-current-tags-overlay (current prefix)
15664 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15665 (if (featurep 'xemacs)
15666 (org-overlay-display org-tags-overlay (concat prefix s)
15667 'secondary-selection)
15668 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15669 (org-overlay-display org-tags-overlay (concat prefix s)))))
15671 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15672 "Fast tag selection with single keys.
15673 CURRENT is the current list of tags in the headline, INHERITED is the
15674 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15675 possibly with grouping information. TODO-TABLE is a similar table with
15676 TODO keywords, should these have keys assigned to them.
15677 If the keys are nil, a-z are automatically assigned.
15678 Returns the new tags string, or nil to not change the current settings."
15679 (let* ((fulltable (append table todo-table))
15680 (maxlen (apply 'max (mapcar
15681 (lambda (x)
15682 (if (stringp (car x)) (string-width (car x)) 0))
15683 fulltable)))
15684 (buf (current-buffer))
15685 (expert (eq org-fast-tag-selection-single-key 'expert))
15686 (buffer-tags nil)
15687 (fwidth (+ maxlen 3 1 3))
15688 (ncol (/ (- (window-width) 4) fwidth))
15689 (i-face 'org-done)
15690 (c-face 'org-todo)
15691 tg cnt e c char c1 c2 ntable tbl rtn
15692 ov-start ov-end ov-prefix
15693 (exit-after-next org-fast-tag-selection-single-key)
15694 (done-keywords org-done-keywords)
15695 groups ingroup)
15696 (save-excursion
15697 (beginning-of-line 1)
15698 (if (looking-at
15699 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15700 (setq ov-start (match-beginning 1)
15701 ov-end (match-end 1)
15702 ov-prefix "")
15703 (setq ov-start (1- (point-at-eol))
15704 ov-end (1+ ov-start))
15705 (skip-chars-forward "^\n\r")
15706 (setq ov-prefix
15707 (concat
15708 (buffer-substring (1- (point)) (point))
15709 (if (> (current-column) org-tags-column)
15711 (make-string (- org-tags-column (current-column)) ?\ ))))))
15712 (org-move-overlay org-tags-overlay ov-start ov-end)
15713 (save-window-excursion
15714 (if expert
15715 (set-buffer (get-buffer-create " *Org tags*"))
15716 (delete-other-windows)
15717 (split-window-vertically)
15718 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15719 (erase-buffer)
15720 (org-set-local 'org-done-keywords done-keywords)
15721 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15722 (org-fast-tag-insert "Current" current c-face "\n\n")
15723 (org-fast-tag-show-exit exit-after-next)
15724 (org-set-current-tags-overlay current ov-prefix)
15725 (setq tbl fulltable char ?a cnt 0)
15726 (while (setq e (pop tbl))
15727 (cond
15728 ((equal e '(:startgroup))
15729 (push '() groups) (setq ingroup t)
15730 (when (not (= cnt 0))
15731 (setq cnt 0)
15732 (insert "\n"))
15733 (insert "{ "))
15734 ((equal e '(:endgroup))
15735 (setq ingroup nil cnt 0)
15736 (insert "}\n"))
15738 (setq tg (car e) c2 nil)
15739 (if (cdr e)
15740 (setq c (cdr e))
15741 ;; automatically assign a character.
15742 (setq c1 (string-to-char
15743 (downcase (substring
15744 tg (if (= (string-to-char tg) ?@) 1 0)))))
15745 (if (or (rassoc c1 ntable) (rassoc c1 table))
15746 (while (or (rassoc char ntable) (rassoc char table))
15747 (setq char (1+ char)))
15748 (setq c2 c1))
15749 (setq c (or c2 char)))
15750 (if ingroup (push tg (car groups)))
15751 (setq tg (org-add-props tg nil 'face
15752 (cond
15753 ((not (assoc tg table))
15754 (org-get-todo-face tg))
15755 ((member tg current) c-face)
15756 ((member tg inherited) i-face)
15757 (t nil))))
15758 (if (and (= cnt 0) (not ingroup)) (insert " "))
15759 (insert "[" c "] " tg (make-string
15760 (- fwidth 4 (length tg)) ?\ ))
15761 (push (cons tg c) ntable)
15762 (when (= (setq cnt (1+ cnt)) ncol)
15763 (insert "\n")
15764 (if ingroup (insert " "))
15765 (setq cnt 0)))))
15766 (setq ntable (nreverse ntable))
15767 (insert "\n")
15768 (goto-char (point-min))
15769 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15770 (fit-window-to-buffer))
15771 (setq rtn
15772 (catch 'exit
15773 (while t
15774 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15775 (if groups " [!] no groups" " [!]groups")
15776 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15777 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15778 (cond
15779 ((= c ?\r) (throw 'exit t))
15780 ((= c ?!)
15781 (setq groups (not groups))
15782 (goto-char (point-min))
15783 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15784 ((= c ?\C-c)
15785 (if (not expert)
15786 (org-fast-tag-show-exit
15787 (setq exit-after-next (not exit-after-next)))
15788 (setq expert nil)
15789 (delete-other-windows)
15790 (split-window-vertically)
15791 (org-switch-to-buffer-other-window " *Org tags*")
15792 (and (fboundp 'fit-window-to-buffer)
15793 (fit-window-to-buffer))))
15794 ((or (= c ?\C-g)
15795 (and (= c ?q) (not (rassoc c ntable))))
15796 (org-detach-overlay org-tags-overlay)
15797 (setq quit-flag t))
15798 ((= c ?\ )
15799 (setq current nil)
15800 (if exit-after-next (setq exit-after-next 'now)))
15801 ((= c ?\t)
15802 (condition-case nil
15803 (setq tg (completing-read
15804 "Tag: "
15805 (or buffer-tags
15806 (with-current-buffer buf
15807 (org-get-buffer-tags)))))
15808 (quit (setq tg "")))
15809 (when (string-match "\\S-" tg)
15810 (add-to-list 'buffer-tags (list tg))
15811 (if (member tg current)
15812 (setq current (delete tg current))
15813 (push tg current)))
15814 (if exit-after-next (setq exit-after-next 'now)))
15815 ((setq e (rassoc c todo-table) tg (car e))
15816 (with-current-buffer buf
15817 (save-excursion (org-todo tg)))
15818 (if exit-after-next (setq exit-after-next 'now)))
15819 ((setq e (rassoc c ntable) tg (car e))
15820 (if (member tg current)
15821 (setq current (delete tg current))
15822 (loop for g in groups do
15823 (if (member tg g)
15824 (mapc (lambda (x)
15825 (setq current (delete x current)))
15826 g)))
15827 (push tg current))
15828 (if exit-after-next (setq exit-after-next 'now))))
15830 ;; Create a sorted list
15831 (setq current
15832 (sort current
15833 (lambda (a b)
15834 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15835 (if (eq exit-after-next 'now) (throw 'exit t))
15836 (goto-char (point-min))
15837 (beginning-of-line 2)
15838 (delete-region (point) (point-at-eol))
15839 (org-fast-tag-insert "Current" current c-face)
15840 (org-set-current-tags-overlay current ov-prefix)
15841 (while (re-search-forward
15842 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15843 (setq tg (match-string 1))
15844 (add-text-properties
15845 (match-beginning 1) (match-end 1)
15846 (list 'face
15847 (cond
15848 ((member tg current) c-face)
15849 ((member tg inherited) i-face)
15850 (t (get-text-property (match-beginning 1) 'face))))))
15851 (goto-char (point-min)))))
15852 (org-detach-overlay org-tags-overlay)
15853 (if rtn
15854 (mapconcat 'identity current ":")
15855 nil))))
15857 (defun org-get-tags-string ()
15858 "Get the TAGS string in the current headline."
15859 (unless (org-on-heading-p t)
15860 (error "Not on a heading"))
15861 (save-excursion
15862 (beginning-of-line 1)
15863 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15864 (org-match-string-no-properties 1)
15865 "")))
15867 (defun org-get-tags ()
15868 "Get the list of tags specified in the current headline."
15869 (org-split-string (org-get-tags-string) ":"))
15871 (defun org-get-buffer-tags ()
15872 "Get a table of all tags used in the buffer, for completion."
15873 (let (tags)
15874 (save-excursion
15875 (goto-char (point-min))
15876 (while (re-search-forward
15877 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15878 (when (equal (char-after (point-at-bol 0)) ?*)
15879 (mapc (lambda (x) (add-to-list 'tags x))
15880 (org-split-string (org-match-string-no-properties 1) ":")))))
15881 (mapcar 'list tags)))
15884 ;;;; Properties
15886 ;;; Setting and retrieving properties
15888 (defconst org-special-properties
15889 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15890 "TIMESTAMP" "TIMESTAMP_IA")
15891 "The special properties valid in Org-mode.
15893 These are properties that are not defined in the property drawer,
15894 but in some other way.")
15896 (defconst org-default-properties
15897 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15898 "LOCATION" "LOGGING" "COLUMNS")
15899 "Some properties that are used by Org-mode for various purposes.
15900 Being in this list makes sure that they are offered for completion.")
15902 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15903 "Regular expression matching the first line of a property drawer.")
15905 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15906 "Regular expression matching the first line of a property drawer.")
15908 (defun org-property-action ()
15909 "Do an action on properties."
15910 (interactive)
15911 (let (c)
15912 (org-at-property-p)
15913 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15914 (setq c (read-char-exclusive))
15915 (cond
15916 ((equal c ?s)
15917 (call-interactively 'org-set-property))
15918 ((equal c ?d)
15919 (call-interactively 'org-delete-property))
15920 ((equal c ?D)
15921 (call-interactively 'org-delete-property-globally))
15922 ((equal c ?c)
15923 (call-interactively 'org-compute-property-at-point))
15924 (t (error "No such property action %c" c)))))
15926 (defun org-at-property-p ()
15927 "Is the cursor in a property line?"
15928 ;; FIXME: Does not check if we are actually in the drawer.
15929 ;; FIXME: also returns true on any drawers.....
15930 ;; This is used by C-c C-c for property action.
15931 (save-excursion
15932 (beginning-of-line 1)
15933 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15935 (defmacro org-with-point-at (pom &rest body)
15936 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15937 (declare (indent 1) (debug t))
15938 `(save-excursion
15939 (if (markerp pom) (set-buffer (marker-buffer pom)))
15940 (save-excursion
15941 (goto-char (or pom (point)))
15942 ,@body)))
15944 (defun org-get-property-block (&optional beg end force)
15945 "Return the (beg . end) range of the body of the property drawer.
15946 BEG and END can be beginning and end of subtree, if not given
15947 they will be found.
15948 If the drawer does not exist and FORCE is non-nil, create the drawer."
15949 (catch 'exit
15950 (save-excursion
15951 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15952 (end (or end (progn (outline-next-heading) (point)))))
15953 (goto-char beg)
15954 (if (re-search-forward org-property-start-re end t)
15955 (setq beg (1+ (match-end 0)))
15956 (if force
15957 (save-excursion
15958 (org-insert-property-drawer)
15959 (setq end (progn (outline-next-heading) (point))))
15960 (throw 'exit nil))
15961 (goto-char beg)
15962 (if (re-search-forward org-property-start-re end t)
15963 (setq beg (1+ (match-end 0)))))
15964 (if (re-search-forward org-property-end-re end t)
15965 (setq end (match-beginning 0))
15966 (or force (throw 'exit nil))
15967 (goto-char beg)
15968 (setq end beg)
15969 (org-indent-line-function)
15970 (insert ":END:\n"))
15971 (cons beg end)))))
15973 (defun org-entry-properties (&optional pom which)
15974 "Get all properties of the entry at point-or-marker POM.
15975 This includes the TODO keyword, the tags, time strings for deadline,
15976 scheduled, and clocking, and any additional properties defined in the
15977 entry. The return value is an alist, keys may occur multiple times
15978 if the property key was used several times.
15979 POM may also be nil, in which case the current entry is used.
15980 If WHICH is nil or `all', get all properties. If WHICH is
15981 `special' or `standard', only get that subclass."
15982 (setq which (or which 'all))
15983 (org-with-point-at pom
15984 (let ((clockstr (substring org-clock-string 0 -1))
15985 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15986 beg end range props sum-props key value string clocksum)
15987 (save-excursion
15988 (when (condition-case nil (org-back-to-heading t) (error nil))
15989 (setq beg (point))
15990 (setq sum-props (get-text-property (point) 'org-summaries))
15991 (setq clocksum (get-text-property (point) :org-clock-minutes))
15992 (outline-next-heading)
15993 (setq end (point))
15994 (when (memq which '(all special))
15995 ;; Get the special properties, like TODO and tags
15996 (goto-char beg)
15997 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15998 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15999 (when (looking-at org-priority-regexp)
16000 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16001 (when (and (setq value (org-get-tags-string))
16002 (string-match "\\S-" value))
16003 (push (cons "TAGS" value) props))
16004 (when (setq value (org-get-tags-at))
16005 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16006 props))
16007 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16008 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16009 string (if (equal key clockstr)
16010 (org-no-properties
16011 (org-trim
16012 (buffer-substring
16013 (match-beginning 3) (goto-char (point-at-eol)))))
16014 (substring (org-match-string-no-properties 3) 1 -1)))
16015 (unless key
16016 (if (= (char-after (match-beginning 3)) ?\[)
16017 (setq key "TIMESTAMP_IA")
16018 (setq key "TIMESTAMP")))
16019 (when (or (equal key clockstr) (not (assoc key props)))
16020 (push (cons key string) props)))
16024 (when (memq which '(all standard))
16025 ;; Get the standard properties, like :PORP: ...
16026 (setq range (org-get-property-block beg end))
16027 (when range
16028 (goto-char (car range))
16029 (while (re-search-forward
16030 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16031 (cdr range) t)
16032 (setq key (org-match-string-no-properties 1)
16033 value (org-trim (or (org-match-string-no-properties 2) "")))
16034 (unless (member key excluded)
16035 (push (cons key (or value "")) props)))))
16036 (if clocksum
16037 (push (cons "CLOCKSUM"
16038 (org-column-number-to-string (/ (float clocksum) 60.)
16039 'add_times))
16040 props))
16041 (append sum-props (nreverse props)))))))
16043 (defun org-entry-get (pom property &optional inherit)
16044 "Get value of PROPERTY for entry at point-or-marker POM.
16045 If INHERIT is non-nil and the entry does not have the property,
16046 then also check higher levels of the hierarchy.
16047 If the property is present but empty, the return value is the empty string.
16048 If the property is not present at all, nil is returned."
16049 (org-with-point-at pom
16050 (if inherit
16051 (org-entry-get-with-inheritance property)
16052 (if (member property org-special-properties)
16053 ;; We need a special property. Use brute force, get all properties.
16054 (cdr (assoc property (org-entry-properties nil 'special)))
16055 (let ((range (org-get-property-block)))
16056 (if (and range
16057 (goto-char (car range))
16058 (re-search-forward
16059 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16060 (cdr range) t))
16061 ;; Found the property, return it.
16062 (if (match-end 1)
16063 (org-match-string-no-properties 1)
16064 "")))))))
16066 (defun org-entry-delete (pom property)
16067 "Delete the property PROPERTY from entry at point-or-marker POM."
16068 (org-with-point-at pom
16069 (if (member property org-special-properties)
16070 nil ; cannot delete these properties.
16071 (let ((range (org-get-property-block)))
16072 (if (and range
16073 (goto-char (car range))
16074 (re-search-forward
16075 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16076 (cdr range) t))
16077 (progn
16078 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16080 nil)))))
16082 ;; Multi-values properties are properties that contain multiple values
16083 ;; These values are assumed to be single words, separated by whitespace.
16084 (defun org-entry-add-to-multivalued-property (pom property value)
16085 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16086 (let* ((old (org-entry-get pom property))
16087 (values (and old (org-split-string old "[ \t]"))))
16088 (unless (member value values)
16089 (setq values (cons value values))
16090 (org-entry-put pom property
16091 (mapconcat 'identity values " ")))))
16093 (defun org-entry-remove-from-multivalued-property (pom property value)
16094 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16095 (let* ((old (org-entry-get pom property))
16096 (values (and old (org-split-string old "[ \t]"))))
16097 (when (member value values)
16098 (setq values (delete value values))
16099 (org-entry-put pom property
16100 (mapconcat 'identity values " ")))))
16102 (defun org-entry-member-in-multivalued-property (pom property value)
16103 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16104 (let* ((old (org-entry-get pom property))
16105 (values (and old (org-split-string old "[ \t]"))))
16106 (member value values)))
16108 (defvar org-entry-property-inherited-from (make-marker))
16110 (defun org-entry-get-with-inheritance (property)
16111 "Get entry property, and search higher levels if not present."
16112 (let (tmp)
16113 (save-excursion
16114 (save-restriction
16115 (widen)
16116 (catch 'ex
16117 (while t
16118 (when (setq tmp (org-entry-get nil property))
16119 (org-back-to-heading t)
16120 (move-marker org-entry-property-inherited-from (point))
16121 (throw 'ex tmp))
16122 (or (org-up-heading-safe) (throw 'ex nil)))))
16123 (or tmp (cdr (assoc property org-local-properties))
16124 (cdr (assoc property org-global-properties))))))
16126 (defun org-entry-put (pom property value)
16127 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16128 (org-with-point-at pom
16129 (org-back-to-heading t)
16130 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16131 range)
16132 (cond
16133 ((equal property "TODO")
16134 (when (and (stringp value) (string-match "\\S-" value)
16135 (not (member value org-todo-keywords-1)))
16136 (error "\"%s\" is not a valid TODO state" value))
16137 (if (or (not value)
16138 (not (string-match "\\S-" value)))
16139 (setq value 'none))
16140 (org-todo value)
16141 (org-set-tags nil 'align))
16142 ((equal property "PRIORITY")
16143 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16144 (string-to-char value) ?\ ))
16145 (org-set-tags nil 'align))
16146 ((equal property "SCHEDULED")
16147 (if (re-search-forward org-scheduled-time-regexp end t)
16148 (cond
16149 ((eq value 'earlier) (org-timestamp-change -1 'day))
16150 ((eq value 'later) (org-timestamp-change 1 'day))
16151 (t (call-interactively 'org-schedule)))
16152 (call-interactively 'org-schedule)))
16153 ((equal property "DEADLINE")
16154 (if (re-search-forward org-deadline-time-regexp end t)
16155 (cond
16156 ((eq value 'earlier) (org-timestamp-change -1 'day))
16157 ((eq value 'later) (org-timestamp-change 1 'day))
16158 (t (call-interactively 'org-deadline)))
16159 (call-interactively 'org-deadline)))
16160 ((member property org-special-properties)
16161 (error "The %s property can not yet be set with `org-entry-put'"
16162 property))
16163 (t ; a non-special property
16164 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16165 (setq range (org-get-property-block beg end 'force))
16166 (goto-char (car range))
16167 (if (re-search-forward
16168 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16169 (progn
16170 (delete-region (match-beginning 1) (match-end 1))
16171 (goto-char (match-beginning 1)))
16172 (goto-char (cdr range))
16173 (insert "\n")
16174 (backward-char 1)
16175 (org-indent-line-function)
16176 (insert ":" property ":"))
16177 (and value (insert " " value))
16178 (org-indent-line-function)))))))
16180 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16181 "Get all property keys in the current buffer.
16182 With INCLUDE-SPECIALS, also list the special properties that relect things
16183 like tags and TODO state.
16184 With INCLUDE-DEFAULTS, also include properties that has special meaning
16185 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16186 With INCLUDE-COLUMNS, also include property names given in COLUMN
16187 formats in the current buffer."
16188 (let (rtn range cfmt cols s p)
16189 (save-excursion
16190 (save-restriction
16191 (widen)
16192 (goto-char (point-min))
16193 (while (re-search-forward org-property-start-re nil t)
16194 (setq range (org-get-property-block))
16195 (goto-char (car range))
16196 (while (re-search-forward
16197 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16198 (cdr range) t)
16199 (add-to-list 'rtn (org-match-string-no-properties 1)))
16200 (outline-next-heading))))
16202 (when include-specials
16203 (setq rtn (append org-special-properties rtn)))
16205 (when include-defaults
16206 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16208 (when include-columns
16209 (save-excursion
16210 (save-restriction
16211 (widen)
16212 (goto-char (point-min))
16213 (while (re-search-forward
16214 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16215 nil t)
16216 (setq cfmt (match-string 2) s 0)
16217 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16218 cfmt s)
16219 (setq s (match-end 0)
16220 p (match-string 1 cfmt))
16221 (unless (or (equal p "ITEM")
16222 (member p org-special-properties))
16223 (add-to-list 'rtn (match-string 1 cfmt))))))))
16225 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16227 (defun org-property-values (key)
16228 "Return a list of all values of property KEY."
16229 (save-excursion
16230 (save-restriction
16231 (widen)
16232 (goto-char (point-min))
16233 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16234 values)
16235 (while (re-search-forward re nil t)
16236 (add-to-list 'values (org-trim (match-string 1))))
16237 (delete "" values)))))
16239 (defun org-insert-property-drawer ()
16240 "Insert a property drawer into the current entry."
16241 (interactive)
16242 (org-back-to-heading t)
16243 (looking-at outline-regexp)
16244 (let ((indent (- (match-end 0)(match-beginning 0)))
16245 (beg (point))
16246 (re (concat "^[ \t]*" org-keyword-time-regexp))
16247 end hiddenp)
16248 (outline-next-heading)
16249 (setq end (point))
16250 (goto-char beg)
16251 (while (re-search-forward re end t))
16252 (setq hiddenp (org-invisible-p))
16253 (end-of-line 1)
16254 (and (equal (char-after) ?\n) (forward-char 1))
16255 (org-skip-over-state-notes)
16256 (skip-chars-backward " \t\n\r")
16257 (if (eq (char-before) ?*) (forward-char 1))
16258 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16259 (beginning-of-line 0)
16260 (indent-to-column indent)
16261 (beginning-of-line 2)
16262 (indent-to-column indent)
16263 (beginning-of-line 0)
16264 (if hiddenp
16265 (save-excursion
16266 (org-back-to-heading t)
16267 (hide-entry))
16268 (org-flag-drawer t))))
16270 (defun org-set-property (property value)
16271 "In the current entry, set PROPERTY to VALUE.
16272 When called interactively, this will prompt for a property name, offering
16273 completion on existing and default properties. And then it will prompt
16274 for a value, offering competion either on allowed values (via an inherited
16275 xxx_ALL property) or on existing values in other instances of this property
16276 in the current file."
16277 (interactive
16278 (let* ((prop (completing-read
16279 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16280 (cur (org-entry-get nil prop))
16281 (allowed (org-property-get-allowed-values nil prop 'table))
16282 (existing (mapcar 'list (org-property-values prop)))
16283 (val (if allowed
16284 (completing-read "Value: " allowed nil 'req-match)
16285 (completing-read
16286 (concat "Value" (if (and cur (string-match "\\S-" cur))
16287 (concat "[" cur "]") "")
16288 ": ")
16289 existing nil nil "" nil cur))))
16290 (list prop (if (equal val "") cur val))))
16291 (unless (equal (org-entry-get nil property) value)
16292 (org-entry-put nil property value)))
16294 (defun org-delete-property (property)
16295 "In the current entry, delete PROPERTY."
16296 (interactive
16297 (let* ((prop (completing-read
16298 "Property: " (org-entry-properties nil 'standard))))
16299 (list prop)))
16300 (message "Property %s %s" property
16301 (if (org-entry-delete nil property)
16302 "deleted"
16303 "was not present in the entry")))
16305 (defun org-delete-property-globally (property)
16306 "Remove PROPERTY globally, from all entries."
16307 (interactive
16308 (let* ((prop (completing-read
16309 "Globally remove property: "
16310 (mapcar 'list (org-buffer-property-keys)))))
16311 (list prop)))
16312 (save-excursion
16313 (save-restriction
16314 (widen)
16315 (goto-char (point-min))
16316 (let ((cnt 0))
16317 (while (re-search-forward
16318 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16319 nil t)
16320 (setq cnt (1+ cnt))
16321 (replace-match ""))
16322 (message "Property \"%s\" removed from %d entries" property cnt)))))
16324 (defvar org-columns-current-fmt-compiled) ; defined below
16326 (defun org-compute-property-at-point ()
16327 "Compute the property at point.
16328 This looks for an enclosing column format, extracts the operator and
16329 then applies it to the proerty in the column format's scope."
16330 (interactive)
16331 (unless (org-at-property-p)
16332 (error "Not at a property"))
16333 (let ((prop (org-match-string-no-properties 2)))
16334 (org-columns-get-format-and-top-level)
16335 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16336 (error "No operator defined for property %s" prop))
16337 (org-columns-compute prop)))
16339 (defun org-property-get-allowed-values (pom property &optional table)
16340 "Get allowed values for the property PROPERTY.
16341 When TABLE is non-nil, return an alist that can directly be used for
16342 completion."
16343 (let (vals)
16344 (cond
16345 ((equal property "TODO")
16346 (setq vals (org-with-point-at pom
16347 (append org-todo-keywords-1 '("")))))
16348 ((equal property "PRIORITY")
16349 (let ((n org-lowest-priority))
16350 (while (>= n org-highest-priority)
16351 (push (char-to-string n) vals)
16352 (setq n (1- n)))))
16353 ((member property org-special-properties))
16355 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16357 (when (and vals (string-match "\\S-" vals))
16358 (setq vals (car (read-from-string (concat "(" vals ")"))))
16359 (setq vals (mapcar (lambda (x)
16360 (cond ((stringp x) x)
16361 ((numberp x) (number-to-string x))
16362 ((symbolp x) (symbol-name x))
16363 (t "???")))
16364 vals)))))
16365 (if table (mapcar 'list vals) vals)))
16367 (defun org-property-previous-allowed-value (&optional previous)
16368 "Switch to the next allowed value for this property."
16369 (interactive)
16370 (org-property-next-allowed-value t))
16372 (defun org-property-next-allowed-value (&optional previous)
16373 "Switch to the next allowed value for this property."
16374 (interactive)
16375 (unless (org-at-property-p)
16376 (error "Not at a property"))
16377 (let* ((key (match-string 2))
16378 (value (match-string 3))
16379 (allowed (or (org-property-get-allowed-values (point) key)
16380 (and (member value '("[ ]" "[-]" "[X]"))
16381 '("[ ]" "[X]"))))
16382 nval)
16383 (unless allowed
16384 (error "Allowed values for this property have not been defined"))
16385 (if previous (setq allowed (reverse allowed)))
16386 (if (member value allowed)
16387 (setq nval (car (cdr (member value allowed)))))
16388 (setq nval (or nval (car allowed)))
16389 (if (equal nval value)
16390 (error "Only one allowed value for this property"))
16391 (org-at-property-p)
16392 (replace-match (concat " :" key ": " nval) t t)
16393 (org-indent-line-function)
16394 (beginning-of-line 1)
16395 (skip-chars-forward " \t")))
16397 (defun org-find-entry-with-id (ident)
16398 "Locate the entry that contains the ID property with exact value IDENT.
16399 IDENT can be a string, a symbol or a number, this function will search for
16400 the string representation of it.
16401 Return the position where this entry starts, or nil if there is no such entry."
16402 (let ((id (cond
16403 ((stringp ident) ident)
16404 ((symbol-name ident) (symbol-name ident))
16405 ((numberp ident) (number-to-string ident))
16406 (t (error "IDENT %s must be a string, symbol or number" ident))))
16407 (case-fold-search nil))
16408 (save-excursion
16409 (save-restriction
16410 (goto-char (point-min))
16411 (when (re-search-forward
16412 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16413 nil t)
16414 (org-back-to-heading)
16415 (point))))))
16417 ;;; Column View
16419 (defvar org-columns-overlays nil
16420 "Holds the list of current column overlays.")
16422 (defvar org-columns-current-fmt nil
16423 "Local variable, holds the currently active column format.")
16424 (defvar org-columns-current-fmt-compiled nil
16425 "Local variable, holds the currently active column format.
16426 This is the compiled version of the format.")
16427 (defvar org-columns-current-widths nil
16428 "Loval variable, holds the currently widths of fields.")
16429 (defvar org-columns-current-maxwidths nil
16430 "Loval variable, holds the currently active maximum column widths.")
16431 (defvar org-columns-begin-marker (make-marker)
16432 "Points to the position where last a column creation command was called.")
16433 (defvar org-columns-top-level-marker (make-marker)
16434 "Points to the position where current columns region starts.")
16436 (defvar org-columns-map (make-sparse-keymap)
16437 "The keymap valid in column display.")
16439 (defun org-columns-content ()
16440 "Switch to contents view while in columns view."
16441 (interactive)
16442 (org-overview)
16443 (org-content))
16445 (org-defkey org-columns-map "c" 'org-columns-content)
16446 (org-defkey org-columns-map "o" 'org-overview)
16447 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16448 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16449 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16450 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16451 (org-defkey org-columns-map "v" 'org-columns-show-value)
16452 (org-defkey org-columns-map "q" 'org-columns-quit)
16453 (org-defkey org-columns-map "r" 'org-columns-redo)
16454 (org-defkey org-columns-map "g" 'org-columns-redo)
16455 (org-defkey org-columns-map [left] 'backward-char)
16456 (org-defkey org-columns-map "\M-b" 'backward-char)
16457 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16458 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16459 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16460 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16461 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16462 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16463 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16464 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16465 (org-defkey org-columns-map "<" 'org-columns-narrow)
16466 (org-defkey org-columns-map ">" 'org-columns-widen)
16467 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16468 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16469 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16470 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16472 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16473 '("Column"
16474 ["Edit property" org-columns-edit-value t]
16475 ["Next allowed value" org-columns-next-allowed-value t]
16476 ["Previous allowed value" org-columns-previous-allowed-value t]
16477 ["Show full value" org-columns-show-value t]
16478 ["Edit allowed values" org-columns-edit-allowed t]
16479 "--"
16480 ["Edit column attributes" org-columns-edit-attributes t]
16481 ["Increase column width" org-columns-widen t]
16482 ["Decrease column width" org-columns-narrow t]
16483 "--"
16484 ["Move column right" org-columns-move-right t]
16485 ["Move column left" org-columns-move-left t]
16486 ["Add column" org-columns-new t]
16487 ["Delete column" org-columns-delete t]
16488 "--"
16489 ["CONTENTS" org-columns-content t]
16490 ["OVERVIEW" org-overview t]
16491 ["Refresh columns display" org-columns-redo t]
16492 "--"
16493 ["Open link" org-columns-open-link t]
16494 "--"
16495 ["Quit" org-columns-quit t]))
16497 (defun org-columns-new-overlay (beg end &optional string face)
16498 "Create a new column overlay and add it to the list."
16499 (let ((ov (org-make-overlay beg end)))
16500 (org-overlay-put ov 'face (or face 'secondary-selection))
16501 (org-overlay-display ov string face)
16502 (push ov org-columns-overlays)
16503 ov))
16505 (defun org-columns-display-here (&optional props)
16506 "Overlay the current line with column display."
16507 (interactive)
16508 (let* ((fmt org-columns-current-fmt-compiled)
16509 (beg (point-at-bol))
16510 (level-face (save-excursion
16511 (beginning-of-line 1)
16512 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16513 (org-get-level-face 2))))
16514 (color (list :foreground
16515 (face-attribute (or level-face 'default) :foreground)))
16516 props pom property ass width f string ov column val modval)
16517 ;; Check if the entry is in another buffer.
16518 (unless props
16519 (if (eq major-mode 'org-agenda-mode)
16520 (setq pom (or (get-text-property (point) 'org-hd-marker)
16521 (get-text-property (point) 'org-marker))
16522 props (if pom (org-entry-properties pom) nil))
16523 (setq props (org-entry-properties nil))))
16524 ;; Walk the format
16525 (while (setq column (pop fmt))
16526 (setq property (car column)
16527 ass (if (equal property "ITEM")
16528 (cons "ITEM"
16529 (save-match-data
16530 (org-no-properties
16531 (org-remove-tabs
16532 (buffer-substring-no-properties
16533 (point-at-bol) (point-at-eol))))))
16534 (assoc property props))
16535 width (or (cdr (assoc property org-columns-current-maxwidths))
16536 (nth 2 column)
16537 (length property))
16538 f (format "%%-%d.%ds | " width width)
16539 val (or (cdr ass) "")
16540 modval (if (equal property "ITEM")
16541 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16542 string (format f (or modval val)))
16543 ;; Create the overlay
16544 (org-unmodified
16545 (setq ov (org-columns-new-overlay
16546 beg (setq beg (1+ beg)) string
16547 (list color 'org-column)))
16548 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16549 (org-overlay-put ov 'keymap org-columns-map)
16550 (org-overlay-put ov 'org-columns-key property)
16551 (org-overlay-put ov 'org-columns-value (cdr ass))
16552 (org-overlay-put ov 'org-columns-value-modified modval)
16553 (org-overlay-put ov 'org-columns-pom pom)
16554 (org-overlay-put ov 'org-columns-format f))
16555 (if (or (not (char-after beg))
16556 (equal (char-after beg) ?\n))
16557 (let ((inhibit-read-only t))
16558 (save-excursion
16559 (goto-char beg)
16560 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16561 ;; Make the rest of the line disappear.
16562 (org-unmodified
16563 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16564 (org-overlay-put ov 'invisible t)
16565 (org-overlay-put ov 'keymap org-columns-map)
16566 (org-overlay-put ov 'intangible t)
16567 (push ov org-columns-overlays)
16568 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16569 (org-overlay-put ov 'keymap org-columns-map)
16570 (push ov org-columns-overlays)
16571 (let ((inhibit-read-only t))
16572 (put-text-property (max (point-min) (1- (point-at-bol)))
16573 (min (point-max) (1+ (point-at-eol)))
16574 'read-only "Type `e' to edit property")))))
16576 (defvar org-previous-header-line-format nil
16577 "The header line format before column view was turned on.")
16578 (defvar org-columns-inhibit-recalculation nil
16579 "Inhibit recomputing of columns on column view startup.")
16582 (defvar header-line-format)
16583 (defun org-columns-display-here-title ()
16584 "Overlay the newline before the current line with the table title."
16585 (interactive)
16586 (let ((fmt org-columns-current-fmt-compiled)
16587 string (title "")
16588 property width f column str widths)
16589 (while (setq column (pop fmt))
16590 (setq property (car column)
16591 str (or (nth 1 column) property)
16592 width (or (cdr (assoc property org-columns-current-maxwidths))
16593 (nth 2 column)
16594 (length str))
16595 widths (push width widths)
16596 f (format "%%-%d.%ds | " width width)
16597 string (format f str)
16598 title (concat title string)))
16599 (setq title (concat
16600 (org-add-props " " nil 'display '(space :align-to 0))
16601 (org-add-props title nil 'face '(:weight bold :underline t))))
16602 (org-set-local 'org-previous-header-line-format header-line-format)
16603 (org-set-local 'org-columns-current-widths (nreverse widths))
16604 (setq header-line-format title)))
16606 (defun org-columns-remove-overlays ()
16607 "Remove all currently active column overlays."
16608 (interactive)
16609 (when (marker-buffer org-columns-begin-marker)
16610 (with-current-buffer (marker-buffer org-columns-begin-marker)
16611 (when (local-variable-p 'org-previous-header-line-format)
16612 (setq header-line-format org-previous-header-line-format)
16613 (kill-local-variable 'org-previous-header-line-format))
16614 (move-marker org-columns-begin-marker nil)
16615 (move-marker org-columns-top-level-marker nil)
16616 (org-unmodified
16617 (mapc 'org-delete-overlay org-columns-overlays)
16618 (setq org-columns-overlays nil)
16619 (let ((inhibit-read-only t))
16620 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16622 (defun org-columns-cleanup-item (item fmt)
16623 "Remove from ITEM what is a column in the format FMT."
16624 (if (not org-complex-heading-regexp)
16625 item
16626 (when (string-match org-complex-heading-regexp item)
16627 (concat
16628 (org-add-props (concat (match-string 1 item) " ") nil
16629 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16630 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16631 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16632 " " (match-string 4 item)
16633 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16635 (defun org-columns-show-value ()
16636 "Show the full value of the property."
16637 (interactive)
16638 (let ((value (get-char-property (point) 'org-columns-value)))
16639 (message "Value is: %s" (or value ""))))
16641 (defun org-columns-quit ()
16642 "Remove the column overlays and in this way exit column editing."
16643 (interactive)
16644 (org-unmodified
16645 (org-columns-remove-overlays)
16646 (let ((inhibit-read-only t))
16647 (remove-text-properties (point-min) (point-max) '(read-only t))))
16648 (when (eq major-mode 'org-agenda-mode)
16649 (message
16650 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16652 (defun org-columns-check-computed ()
16653 "Check if this column value is computed.
16654 If yes, throw an error indicating that changing it does not make sense."
16655 (let ((val (get-char-property (point) 'org-columns-value)))
16656 (when (and (stringp val)
16657 (get-char-property 0 'org-computed val))
16658 (error "This value is computed from the entry's children"))))
16660 (defun org-columns-todo (&optional arg)
16661 "Change the TODO state during column view."
16662 (interactive "P")
16663 (org-columns-edit-value "TODO"))
16665 (defun org-columns-set-tags-or-toggle (&optional arg)
16666 "Toggle checkbox at point, or set tags for current headline."
16667 (interactive "P")
16668 (if (string-match "\\`\\[[ xX-]\\]\\'"
16669 (get-char-property (point) 'org-columns-value))
16670 (org-columns-next-allowed-value)
16671 (org-columns-edit-value "TAGS")))
16673 (defun org-columns-edit-value (&optional key)
16674 "Edit the value of the property at point in column view.
16675 Where possible, use the standard interface for changing this line."
16676 (interactive)
16677 (org-columns-check-computed)
16678 (let* ((external-key key)
16679 (col (current-column))
16680 (key (or key (get-char-property (point) 'org-columns-key)))
16681 (value (get-char-property (point) 'org-columns-value))
16682 (bol (point-at-bol)) (eol (point-at-eol))
16683 (pom (or (get-text-property bol 'org-hd-marker)
16684 (point))) ; keep despite of compiler waring
16685 (line-overlays
16686 (delq nil (mapcar (lambda (x)
16687 (and (eq (overlay-buffer x) (current-buffer))
16688 (>= (overlay-start x) bol)
16689 (<= (overlay-start x) eol)
16691 org-columns-overlays)))
16692 nval eval allowed)
16693 (cond
16694 ((equal key "CLOCKSUM")
16695 (error "This special column cannot be edited"))
16696 ((equal key "ITEM")
16697 (setq eval '(org-with-point-at pom
16698 (org-edit-headline))))
16699 ((equal key "TODO")
16700 (setq eval '(org-with-point-at pom
16701 (let ((current-prefix-arg
16702 (if external-key current-prefix-arg '(4))))
16703 (call-interactively 'org-todo)))))
16704 ((equal key "PRIORITY")
16705 (setq eval '(org-with-point-at pom
16706 (call-interactively 'org-priority))))
16707 ((equal key "TAGS")
16708 (setq eval '(org-with-point-at pom
16709 (let ((org-fast-tag-selection-single-key
16710 (if (eq org-fast-tag-selection-single-key 'expert)
16711 t org-fast-tag-selection-single-key)))
16712 (call-interactively 'org-set-tags)))))
16713 ((equal key "DEADLINE")
16714 (setq eval '(org-with-point-at pom
16715 (call-interactively 'org-deadline))))
16716 ((equal key "SCHEDULED")
16717 (setq eval '(org-with-point-at pom
16718 (call-interactively 'org-schedule))))
16720 (setq allowed (org-property-get-allowed-values pom key 'table))
16721 (if allowed
16722 (setq nval (completing-read "Value: " allowed nil t))
16723 (setq nval (read-string "Edit: " value)))
16724 (setq nval (org-trim nval))
16725 (when (not (equal nval value))
16726 (setq eval '(org-entry-put pom key nval)))))
16727 (when eval
16728 (let ((inhibit-read-only t))
16729 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16730 (unwind-protect
16731 (progn
16732 (setq org-columns-overlays
16733 (org-delete-all line-overlays org-columns-overlays))
16734 (mapc 'org-delete-overlay line-overlays)
16735 (org-columns-eval eval))
16736 (org-columns-display-here))))
16737 (move-to-column col)
16738 (if (and (org-mode-p)
16739 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16740 (org-columns-update key))))
16742 (defun org-edit-headline () ; FIXME: this is not columns specific
16743 "Edit the current headline, the part without TODO keyword, TAGS."
16744 (org-back-to-heading)
16745 (when (looking-at org-todo-line-regexp)
16746 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16747 (txt (match-string 3))
16748 (post "")
16749 txt2)
16750 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16751 (setq post (match-string 0 txt)
16752 txt (substring txt 0 (match-beginning 0))))
16753 (setq txt2 (read-string "Edit: " txt))
16754 (when (not (equal txt txt2))
16755 (beginning-of-line 1)
16756 (insert pre txt2 post)
16757 (delete-region (point) (point-at-eol))
16758 (org-set-tags nil t)))))
16760 (defun org-columns-edit-allowed ()
16761 "Edit the list of allowed values for the current property."
16762 (interactive)
16763 (let* ((key (get-char-property (point) 'org-columns-key))
16764 (key1 (concat key "_ALL"))
16765 (allowed (org-entry-get (point) key1 t))
16766 nval)
16767 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16768 (setq nval (read-string "Allowed: " allowed))
16769 (org-entry-put
16770 (cond ((marker-position org-entry-property-inherited-from)
16771 org-entry-property-inherited-from)
16772 ((marker-position org-columns-top-level-marker)
16773 org-columns-top-level-marker))
16774 key1 nval)))
16776 (defmacro org-no-warnings (&rest body)
16777 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16779 (defun org-columns-eval (form)
16780 (let (hidep)
16781 (save-excursion
16782 (beginning-of-line 1)
16783 ;; `next-line' is needed here, because it skips invisible line.
16784 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16785 (setq hidep (org-on-heading-p 1)))
16786 (eval form)
16787 (and hidep (hide-entry))))
16789 (defun org-columns-previous-allowed-value ()
16790 "Switch to the previous allowed value for this column."
16791 (interactive)
16792 (org-columns-next-allowed-value t))
16794 (defun org-columns-next-allowed-value (&optional previous)
16795 "Switch to the next allowed value for this column."
16796 (interactive)
16797 (org-columns-check-computed)
16798 (let* ((col (current-column))
16799 (key (get-char-property (point) 'org-columns-key))
16800 (value (get-char-property (point) 'org-columns-value))
16801 (bol (point-at-bol)) (eol (point-at-eol))
16802 (pom (or (get-text-property bol 'org-hd-marker)
16803 (point))) ; keep despite of compiler waring
16804 (line-overlays
16805 (delq nil (mapcar (lambda (x)
16806 (and (eq (overlay-buffer x) (current-buffer))
16807 (>= (overlay-start x) bol)
16808 (<= (overlay-start x) eol)
16810 org-columns-overlays)))
16811 (allowed (or (org-property-get-allowed-values pom key)
16812 (and (memq
16813 (nth 4 (assoc key org-columns-current-fmt-compiled))
16814 '(checkbox checkbox-n-of-m checkbox-percent))
16815 '("[ ]" "[X]"))))
16816 nval)
16817 (when (equal key "ITEM")
16818 (error "Cannot edit item headline from here"))
16819 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16820 (error "Allowed values for this property have not been defined"))
16821 (if (member key '("SCHEDULED" "DEADLINE"))
16822 (setq nval (if previous 'earlier 'later))
16823 (if previous (setq allowed (reverse allowed)))
16824 (if (member value allowed)
16825 (setq nval (car (cdr (member value allowed)))))
16826 (setq nval (or nval (car allowed)))
16827 (if (equal nval value)
16828 (error "Only one allowed value for this property")))
16829 (let ((inhibit-read-only t))
16830 (remove-text-properties (1- bol) eol '(read-only t))
16831 (unwind-protect
16832 (progn
16833 (setq org-columns-overlays
16834 (org-delete-all line-overlays org-columns-overlays))
16835 (mapc 'org-delete-overlay line-overlays)
16836 (org-columns-eval '(org-entry-put pom key nval)))
16837 (org-columns-display-here)))
16838 (move-to-column col)
16839 (if (and (org-mode-p)
16840 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16841 (org-columns-update key))))
16843 (defun org-verify-version (task)
16844 (cond
16845 ((eq task 'columns)
16846 (if (or (featurep 'xemacs)
16847 (< emacs-major-version 22))
16848 (error "Emacs 22 is required for the columns feature")))))
16850 (defun org-columns-open-link (&optional arg)
16851 (interactive "P")
16852 (let ((value (get-char-property (point) 'org-columns-value)))
16853 (org-open-link-from-string value arg)))
16855 (defun org-open-link-from-string (s &optional arg)
16856 "Open a link in the string S, as if it was in Org-mode."
16857 (interactive)
16858 (with-temp-buffer
16859 (let ((org-inhibit-startup t))
16860 (org-mode)
16861 (insert s)
16862 (goto-char (point-min))
16863 (org-open-at-point arg))))
16865 (defun org-columns-get-format-and-top-level ()
16866 (let (fmt)
16867 (when (condition-case nil (org-back-to-heading) (error nil))
16868 (move-marker org-entry-property-inherited-from nil)
16869 (setq fmt (org-entry-get nil "COLUMNS" t)))
16870 (setq fmt (or fmt org-columns-default-format))
16871 (org-set-local 'org-columns-current-fmt fmt)
16872 (org-columns-compile-format fmt)
16873 (if (marker-position org-entry-property-inherited-from)
16874 (move-marker org-columns-top-level-marker
16875 org-entry-property-inherited-from)
16876 (move-marker org-columns-top-level-marker (point)))
16877 fmt))
16879 (defun org-columns ()
16880 "Turn on column view on an org-mode file."
16881 (interactive)
16882 (org-verify-version 'columns)
16883 (org-columns-remove-overlays)
16884 (move-marker org-columns-begin-marker (point))
16885 (let (beg end fmt cache maxwidths)
16886 (setq fmt (org-columns-get-format-and-top-level))
16887 (save-excursion
16888 (goto-char org-columns-top-level-marker)
16889 (setq beg (point))
16890 (unless org-columns-inhibit-recalculation
16891 (org-columns-compute-all))
16892 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16893 (point-max)))
16894 ;; Get and cache the properties
16895 (goto-char beg)
16896 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16897 (save-excursion
16898 (save-restriction
16899 (narrow-to-region beg end)
16900 (org-clock-sum))))
16901 (while (re-search-forward (concat "^" outline-regexp) end t)
16902 (push (cons (org-current-line) (org-entry-properties)) cache))
16903 (when cache
16904 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16905 (org-set-local 'org-columns-current-maxwidths maxwidths)
16906 (org-columns-display-here-title)
16907 (mapc (lambda (x)
16908 (goto-line (car x))
16909 (org-columns-display-here (cdr x)))
16910 cache)))))
16912 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16913 "Insert a new column, to the leeft o the current column."
16914 (interactive)
16915 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16916 cell)
16917 (setq prop (completing-read
16918 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
16919 nil nil prop))
16920 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16921 (setq width (read-string "Column width: " (if width (number-to-string width))))
16922 (if (string-match "\\S-" width)
16923 (setq width (string-to-number width))
16924 (setq width nil))
16925 (setq fmt (completing-read "Summary [none]: "
16926 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
16927 nil t))
16928 (if (string-match "\\S-" fmt)
16929 (setq fmt (intern fmt))
16930 (setq fmt nil))
16931 (if (eq fmt 'none) (setq fmt nil))
16932 (if editp
16933 (progn
16934 (setcar editp prop)
16935 (setcdr editp (list title width nil fmt)))
16936 (setq cell (nthcdr (1- (current-column))
16937 org-columns-current-fmt-compiled))
16938 (setcdr cell (cons (list prop title width nil fmt)
16939 (cdr cell))))
16940 (org-columns-store-format)
16941 (org-columns-redo)))
16943 (defun org-columns-delete ()
16944 "Delete the column at point from columns view."
16945 (interactive)
16946 (let* ((n (current-column))
16947 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16948 (when (y-or-n-p
16949 (format "Are you sure you want to remove column \"%s\"? " title))
16950 (setq org-columns-current-fmt-compiled
16951 (delq (nth n org-columns-current-fmt-compiled)
16952 org-columns-current-fmt-compiled))
16953 (org-columns-store-format)
16954 (org-columns-redo)
16955 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16956 (backward-char 1)))))
16958 (defun org-columns-edit-attributes ()
16959 "Edit the attributes of the current column."
16960 (interactive)
16961 (let* ((n (current-column))
16962 (info (nth n org-columns-current-fmt-compiled)))
16963 (apply 'org-columns-new info)))
16965 (defun org-columns-widen (arg)
16966 "Make the column wider by ARG characters."
16967 (interactive "p")
16968 (let* ((n (current-column))
16969 (entry (nth n org-columns-current-fmt-compiled))
16970 (width (or (nth 2 entry)
16971 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16972 (setq width (max 1 (+ width arg)))
16973 (setcar (nthcdr 2 entry) width)
16974 (org-columns-store-format)
16975 (org-columns-redo)))
16977 (defun org-columns-narrow (arg)
16978 "Make the column nrrower by ARG characters."
16979 (interactive "p")
16980 (org-columns-widen (- arg)))
16982 (defun org-columns-move-right ()
16983 "Swap this column with the one to the right."
16984 (interactive)
16985 (let* ((n (current-column))
16986 (cell (nthcdr n org-columns-current-fmt-compiled))
16988 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16989 (error "Cannot shift this column further to the right"))
16990 (setq e (car cell))
16991 (setcar cell (car (cdr cell)))
16992 (setcdr cell (cons e (cdr (cdr cell))))
16993 (org-columns-store-format)
16994 (org-columns-redo)
16995 (forward-char 1)))
16997 (defun org-columns-move-left ()
16998 "Swap this column with the one to the left."
16999 (interactive)
17000 (let* ((n (current-column)))
17001 (when (= n 0)
17002 (error "Cannot shift this column further to the left"))
17003 (backward-char 1)
17004 (org-columns-move-right)
17005 (backward-char 1)))
17007 (defun org-columns-store-format ()
17008 "Store the text version of the current columns format in appropriate place.
17009 This is either in the COLUMNS property of the node starting the current column
17010 display, or in the #+COLUMNS line of the current buffer."
17011 (let (fmt (cnt 0))
17012 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17013 (org-set-local 'org-columns-current-fmt fmt)
17014 (if (marker-position org-columns-top-level-marker)
17015 (save-excursion
17016 (goto-char org-columns-top-level-marker)
17017 (if (and (org-at-heading-p)
17018 (org-entry-get nil "COLUMNS"))
17019 (org-entry-put nil "COLUMNS" fmt)
17020 (goto-char (point-min))
17021 ;; Overwrite all #+COLUMNS lines....
17022 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17023 (setq cnt (1+ cnt))
17024 (replace-match (concat "#+COLUMNS: " fmt) t t))
17025 (unless (> cnt 0)
17026 (goto-char (point-min))
17027 (or (org-on-heading-p t) (outline-next-heading))
17028 (let ((inhibit-read-only t))
17029 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17030 (org-set-local 'org-columns-default-format fmt))))))
17032 (defvar org-overriding-columns-format nil
17033 "When set, overrides any other definition.")
17034 (defvar org-agenda-view-columns-initially nil
17035 "When set, switch to columns view immediately after creating the agenda.")
17037 (defun org-agenda-columns ()
17038 "Turn on column view in the agenda."
17039 (interactive)
17040 (org-verify-version 'columns)
17041 (org-columns-remove-overlays)
17042 (move-marker org-columns-begin-marker (point))
17043 (let (fmt cache maxwidths m)
17044 (cond
17045 ((and (local-variable-p 'org-overriding-columns-format)
17046 org-overriding-columns-format)
17047 (setq fmt org-overriding-columns-format))
17048 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17049 (setq fmt (org-entry-get m "COLUMNS" t)))
17050 ((and (boundp 'org-columns-current-fmt)
17051 (local-variable-p 'org-columns-current-fmt)
17052 org-columns-current-fmt)
17053 (setq fmt org-columns-current-fmt))
17054 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17055 (setq m (get-text-property m 'org-hd-marker))
17056 (setq fmt (org-entry-get m "COLUMNS" t))))
17057 (setq fmt (or fmt org-columns-default-format))
17058 (org-set-local 'org-columns-current-fmt fmt)
17059 (org-columns-compile-format fmt)
17060 (save-excursion
17061 ;; Get and cache the properties
17062 (goto-char (point-min))
17063 (while (not (eobp))
17064 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17065 (get-text-property (point) 'org-marker)))
17066 (push (cons (org-current-line) (org-entry-properties m)) cache))
17067 (beginning-of-line 2))
17068 (when cache
17069 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17070 (org-set-local 'org-columns-current-maxwidths maxwidths)
17071 (org-columns-display-here-title)
17072 (mapc (lambda (x)
17073 (goto-line (car x))
17074 (org-columns-display-here (cdr x)))
17075 cache)))))
17077 (defun org-columns-get-autowidth-alist (s cache)
17078 "Derive the maximum column widths from the format and the cache."
17079 (let ((start 0) rtn)
17080 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17081 (push (cons (match-string 1 s) 1) rtn)
17082 (setq start (match-end 0)))
17083 (mapc (lambda (x)
17084 (setcdr x (apply 'max
17085 (mapcar
17086 (lambda (y)
17087 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17088 cache))))
17089 rtn)
17090 rtn))
17092 (defun org-columns-compute-all ()
17093 "Compute all columns that have operators defined."
17094 (org-unmodified
17095 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17096 (let ((columns org-columns-current-fmt-compiled) col)
17097 (while (setq col (pop columns))
17098 (when (nth 3 col)
17099 (save-excursion
17100 (org-columns-compute (car col)))))))
17102 (defun org-columns-update (property)
17103 "Recompute PROPERTY, and update the columns display for it."
17104 (org-columns-compute property)
17105 (let (fmt val pos)
17106 (save-excursion
17107 (mapc (lambda (ov)
17108 (when (equal (org-overlay-get ov 'org-columns-key) property)
17109 (setq pos (org-overlay-start ov))
17110 (goto-char pos)
17111 (when (setq val (cdr (assoc property
17112 (get-text-property
17113 (point-at-bol) 'org-summaries))))
17114 (setq fmt (org-overlay-get ov 'org-columns-format))
17115 (org-overlay-put ov 'org-columns-value val)
17116 (org-overlay-put ov 'display (format fmt val)))))
17117 org-columns-overlays))))
17119 (defun org-columns-compute (property)
17120 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17121 (interactive)
17122 (let* ((re (concat "^" outline-regexp))
17123 (lmax 30) ; Does anyone use deeper levels???
17124 (lsum (make-vector lmax 0))
17125 (lflag (make-vector lmax nil))
17126 (level 0)
17127 (ass (assoc property org-columns-current-fmt-compiled))
17128 (format (nth 4 ass))
17129 (printf (nth 5 ass))
17130 (beg org-columns-top-level-marker)
17131 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17132 (save-excursion
17133 ;; Find the region to compute
17134 (goto-char beg)
17135 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17136 (goto-char end)
17137 ;; Walk the tree from the back and do the computations
17138 (while (re-search-backward re beg t)
17139 (setq sumpos (match-beginning 0)
17140 last-level level
17141 level (org-outline-level)
17142 val (org-entry-get nil property)
17143 valflag (and val (string-match "\\S-" val)))
17144 (cond
17145 ((< level last-level)
17146 ;; put the sum of lower levels here as a property
17147 (setq sum (aref lsum last-level) ; current sum
17148 flag (aref lflag last-level) ; any valid entries from children?
17149 str (org-column-number-to-string sum format printf)
17150 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17151 useval (if flag str1 (if valflag val ""))
17152 sum-alist (get-text-property sumpos 'org-summaries))
17153 (if (assoc property sum-alist)
17154 (setcdr (assoc property sum-alist) useval)
17155 (push (cons property useval) sum-alist)
17156 (org-unmodified
17157 (add-text-properties sumpos (1+ sumpos)
17158 (list 'org-summaries sum-alist))))
17159 (when val
17160 (org-entry-put nil property (if flag str val)))
17161 ;; add current to current level accumulator
17162 (when (or flag valflag)
17163 (aset lsum level (+ (aref lsum level)
17164 (if flag sum (org-column-string-to-number
17165 (if flag str val) format))))
17166 (aset lflag level t))
17167 ;; clear accumulators for deeper levels
17168 (loop for l from (1+ level) to (1- lmax) do
17169 (aset lsum l 0)
17170 (aset lflag l nil)))
17171 ((>= level last-level)
17172 ;; add what we have here to the accumulator for this level
17173 (aset lsum level (+ (aref lsum level)
17174 (org-column-string-to-number (or val "0") format)))
17175 (and valflag (aset lflag level t)))
17176 (t (error "This should not happen")))))))
17178 (defun org-columns-redo ()
17179 "Construct the column display again."
17180 (interactive)
17181 (message "Recomputing columns...")
17182 (save-excursion
17183 (if (marker-position org-columns-begin-marker)
17184 (goto-char org-columns-begin-marker))
17185 (org-columns-remove-overlays)
17186 (if (org-mode-p)
17187 (call-interactively 'org-columns)
17188 (call-interactively 'org-agenda-columns)))
17189 (message "Recomputing columns...done"))
17191 (defun org-columns-not-in-agenda ()
17192 (if (eq major-mode 'org-agenda-mode)
17193 (error "This command is only allowed in Org-mode buffers")))
17196 (defun org-string-to-number (s)
17197 "Convert string to number, and interpret hh:mm:ss."
17198 (if (not (string-match ":" s))
17199 (string-to-number s)
17200 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17201 (while l
17202 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17203 sum)))
17205 (defun org-column-number-to-string (n fmt &optional printf)
17206 "Convert a computed column number to a string value, according to FMT."
17207 (cond
17208 ((eq fmt 'add_times)
17209 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17210 (format "%d:%02d" h m)))
17211 ((eq fmt 'checkbox)
17212 (cond ((= n (floor n)) "[X]")
17213 ((> n 1.) "[-]")
17214 (t "[ ]")))
17215 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17216 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17217 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17218 (printf (format printf n))
17219 ((eq fmt 'currency)
17220 (format "%.2f" n))
17221 (t (number-to-string n))))
17223 (defun org-nofm-to-completion (n m &optional percent)
17224 (if (not percent)
17225 (format "[%d/%d]" n m)
17226 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17228 (defun org-column-string-to-number (s fmt)
17229 "Convert a column value to a number that can be used for column computing."
17230 (cond
17231 ((string-match ":" s)
17232 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17233 (while l
17234 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17235 sum))
17236 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17237 (if (equal s "[X]") 1. 0.000001))
17238 (t (string-to-number s))))
17240 (defun org-columns-uncompile-format (cfmt)
17241 "Turn the compiled columns format back into a string representation."
17242 (let ((rtn "") e s prop title op width fmt printf)
17243 (while (setq e (pop cfmt))
17244 (setq prop (car e)
17245 title (nth 1 e)
17246 width (nth 2 e)
17247 op (nth 3 e)
17248 fmt (nth 4 e)
17249 printf (nth 5 e))
17250 (cond
17251 ((eq fmt 'add_times) (setq op ":"))
17252 ((eq fmt 'checkbox) (setq op "X"))
17253 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17254 ((eq fmt 'checkbox-percent) (setq op "X%"))
17255 ((eq fmt 'add_numbers) (setq op "+"))
17256 ((eq fmt 'currency) (setq op "$")))
17257 (if (and op printf) (setq op (concat op ";" printf)))
17258 (if (equal title prop) (setq title nil))
17259 (setq s (concat "%" (if width (number-to-string width))
17260 prop
17261 (if title (concat "(" title ")"))
17262 (if op (concat "{" op "}"))))
17263 (setq rtn (concat rtn " " s)))
17264 (org-trim rtn)))
17266 (defun org-columns-compile-format (fmt)
17267 "Turn a column format string into an alist of specifications.
17268 The alist has one entry for each column in the format. The elements of
17269 that list are:
17270 property the property
17271 title the title field for the columns
17272 width the column width in characters, can be nil for automatic
17273 operator the operator if any
17274 format the output format for computed results, derived from operator
17275 printf a printf format for computed values"
17276 (let ((start 0) width prop title op f printf)
17277 (setq org-columns-current-fmt-compiled nil)
17278 (while (string-match
17279 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17280 fmt start)
17281 (setq start (match-end 0)
17282 width (match-string 1 fmt)
17283 prop (match-string 2 fmt)
17284 title (or (match-string 3 fmt) prop)
17285 op (match-string 4 fmt)
17286 f nil
17287 printf nil)
17288 (if width (setq width (string-to-number width)))
17289 (when (and op (string-match ";" op))
17290 (setq printf (substring op (match-end 0))
17291 op (substring op 0 (match-beginning 0))))
17292 (cond
17293 ((equal op "+") (setq f 'add_numbers))
17294 ((equal op "$") (setq f 'currency))
17295 ((equal op ":") (setq f 'add_times))
17296 ((equal op "X") (setq f 'checkbox))
17297 ((equal op "X/") (setq f 'checkbox-n-of-m))
17298 ((equal op "X%") (setq f 'checkbox-percent))
17300 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17301 (setq org-columns-current-fmt-compiled
17302 (nreverse org-columns-current-fmt-compiled))))
17305 ;;; Dynamic block for Column view
17307 (defun org-columns-capture-view ()
17308 "Get the column view of the current buffer and return it as a list.
17309 The list will contains the title row and all other rows. Each row is
17310 a list of fields."
17311 (save-excursion
17312 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17313 (n (length title)) row tbl)
17314 (goto-char (point-min))
17315 (while (re-search-forward "^\\*+ " nil t)
17316 (when (get-char-property (match-beginning 0) 'org-columns-key)
17317 (setq row nil)
17318 (loop for i from 0 to (1- n) do
17319 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17320 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17322 row))
17323 (setq row (nreverse row))
17324 (push row tbl)))
17325 (append (list title 'hline) (nreverse tbl)))))
17327 (defun org-dblock-write:columnview (params)
17328 "Write the column view table.
17329 PARAMS is a property list of parameters:
17331 :width enforce same column widths with <N> specifiers.
17332 :id the :ID: property of the entry where the columns view
17333 should be built, as a string. When `local', call locally.
17334 When `global' call column view with the cursor at the beginning
17335 of the buffer (usually this means that the whole buffer switches
17336 to column view).
17337 :hlines When t, insert a hline before each item. When a number, insert
17338 a hline before each level <= that number.
17339 :vlines When t, make each column a colgroup to enforce vertical lines."
17340 (let ((pos (move-marker (make-marker) (point)))
17341 (hlines (plist-get params :hlines))
17342 (vlines (plist-get params :vlines))
17343 tbl id idpos nfields tmp)
17344 (save-excursion
17345 (save-restriction
17346 (when (setq id (plist-get params :id))
17347 (cond ((not id) nil)
17348 ((eq id 'global) (goto-char (point-min)))
17349 ((eq id 'local) nil)
17350 ((setq idpos (org-find-entry-with-id id))
17351 (goto-char idpos))
17352 (t (error "Cannot find entry with :ID: %s" id))))
17353 (org-columns)
17354 (setq tbl (org-columns-capture-view))
17355 (setq nfields (length (car tbl)))
17356 (org-columns-quit)))
17357 (goto-char pos)
17358 (move-marker pos nil)
17359 (when tbl
17360 (when (plist-get params :hlines)
17361 (setq tmp nil)
17362 (while tbl
17363 (if (eq (car tbl) 'hline)
17364 (push (pop tbl) tmp)
17365 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17366 (if (and (not (eq (car tmp) 'hline))
17367 (or (eq hlines t)
17368 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17369 (push 'hline tmp)))
17370 (push (pop tbl) tmp)))
17371 (setq tbl (nreverse tmp)))
17372 (when vlines
17373 (setq tbl (mapcar (lambda (x)
17374 (if (eq 'hline x) x (cons "" x)))
17375 tbl))
17376 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17377 (setq pos (point))
17378 (insert (org-listtable-to-string tbl))
17379 (when (plist-get params :width)
17380 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17381 org-columns-current-widths "|")))
17382 (goto-char pos)
17383 (org-table-align))))
17385 (defun org-listtable-to-string (tbl)
17386 "Convert a listtable TBL to a string that contains the Org-mode table.
17387 The table still need to be alligned. The resulting string has no leading
17388 and tailing newline characters."
17389 (mapconcat
17390 (lambda (x)
17391 (cond
17392 ((listp x)
17393 (concat "|" (mapconcat 'identity x "|") "|"))
17394 ((eq x 'hline) "|-|")
17395 (t (error "Garbage in listtable: %s" x))))
17396 tbl "\n"))
17398 (defun org-insert-columns-dblock ()
17399 "Create a dynamic block capturing a column view table."
17400 (interactive)
17401 (let ((defaults '(:name "columnview" :hlines 1))
17402 (id (completing-read
17403 "Capture columns (local, global, entry with :ID: property) [local]: "
17404 (append '(("global") ("local"))
17405 (mapcar 'list (org-property-values "ID"))))))
17406 (if (equal id "") (setq id 'local))
17407 (if (equal id "global") (setq id 'global))
17408 (setq defaults (append defaults (list :id id)))
17409 (org-create-dblock defaults)
17410 (org-update-dblock)))
17412 ;;;; Timestamps
17414 (defvar org-last-changed-timestamp nil)
17415 (defvar org-time-was-given) ; dynamically scoped parameter
17416 (defvar org-end-time-was-given) ; dynamically scoped parameter
17417 (defvar org-ts-what) ; dynamically scoped parameter
17419 (defun org-time-stamp (arg)
17420 "Prompt for a date/time and insert a time stamp.
17421 If the user specifies a time like HH:MM, or if this command is called
17422 with a prefix argument, the time stamp will contain date and time.
17423 Otherwise, only the date will be included. All parts of a date not
17424 specified by the user will be filled in from the current date/time.
17425 So if you press just return without typing anything, the time stamp
17426 will represent the current date/time. If there is already a timestamp
17427 at the cursor, it will be modified."
17428 (interactive "P")
17429 (let* ((ts nil)
17430 (default-time
17431 ;; Default time is either today, or, when entering a range,
17432 ;; the range start.
17433 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17434 (save-excursion
17435 (re-search-backward
17436 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17437 (- (point) 20) t)))
17438 (apply 'encode-time (org-parse-time-string (match-string 1)))
17439 (current-time)))
17440 (default-input (and ts (org-get-compact-tod ts)))
17441 org-time-was-given org-end-time-was-given time)
17442 (cond
17443 ((and (org-at-timestamp-p)
17444 (eq last-command 'org-time-stamp)
17445 (eq this-command 'org-time-stamp))
17446 (insert "--")
17447 (setq time (let ((this-command this-command))
17448 (org-read-date arg 'totime nil nil default-time default-input)))
17449 (org-insert-time-stamp time (or org-time-was-given arg)))
17450 ((org-at-timestamp-p)
17451 (setq time (let ((this-command this-command))
17452 (org-read-date arg 'totime nil nil default-time default-input)))
17453 (when (org-at-timestamp-p) ; just to get the match data
17454 (replace-match "")
17455 (setq org-last-changed-timestamp
17456 (org-insert-time-stamp
17457 time (or org-time-was-given arg)
17458 nil nil nil (list org-end-time-was-given))))
17459 (message "Timestamp updated"))
17461 (setq time (let ((this-command this-command))
17462 (org-read-date arg 'totime nil nil default-time default-input)))
17463 (org-insert-time-stamp time (or org-time-was-given arg)
17464 nil nil nil (list org-end-time-was-given))))))
17466 ;; FIXME: can we use this for something else????
17467 ;; like computing time differences?????
17468 (defun org-get-compact-tod (s)
17469 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17470 (let* ((t1 (match-string 1 s))
17471 (h1 (string-to-number (match-string 2 s)))
17472 (m1 (string-to-number (match-string 3 s)))
17473 (t2 (and (match-end 4) (match-string 5 s)))
17474 (h2 (and t2 (string-to-number (match-string 6 s))))
17475 (m2 (and t2 (string-to-number (match-string 7 s))))
17476 dh dm)
17477 (if (not t2)
17479 (setq dh (- h2 h1) dm (- m2 m1))
17480 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17481 (concat t1 "+" (number-to-string dh)
17482 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17484 (defun org-time-stamp-inactive (&optional arg)
17485 "Insert an inactive time stamp.
17486 An inactive time stamp is enclosed in square brackets instead of angle
17487 brackets. It is inactive in the sense that it does not trigger agenda entries,
17488 does not link to the calendar and cannot be changed with the S-cursor keys.
17489 So these are more for recording a certain time/date."
17490 (interactive "P")
17491 (let (org-time-was-given org-end-time-was-given time)
17492 (setq time (org-read-date arg 'totime))
17493 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17494 nil nil (list org-end-time-was-given))))
17496 (defvar org-date-ovl (org-make-overlay 1 1))
17497 (org-overlay-put org-date-ovl 'face 'org-warning)
17498 (org-detach-overlay org-date-ovl)
17500 (defvar org-ans1) ; dynamically scoped parameter
17501 (defvar org-ans2) ; dynamically scoped parameter
17503 (defvar org-plain-time-of-day-regexp) ; defined below
17505 (defvar org-read-date-overlay nil)
17506 (defvar org-dcst nil) ; dynamically scoped
17508 (defun org-read-date (&optional with-time to-time from-string prompt
17509 default-time default-input)
17510 "Read a date, possibly a time, and make things smooth for the user.
17511 The prompt will suggest to enter an ISO date, but you can also enter anything
17512 which will at least partially be understood by `parse-time-string'.
17513 Unrecognized parts of the date will default to the current day, month, year,
17514 hour and minute. If this command is called to replace a timestamp at point,
17515 of to enter the second timestamp of a range, the default time is taken from the
17516 existing stamp. For example,
17517 3-2-5 --> 2003-02-05
17518 feb 15 --> currentyear-02-15
17519 sep 12 9 --> 2009-09-12
17520 12:45 --> today 12:45
17521 22 sept 0:34 --> currentyear-09-22 0:34
17522 12 --> currentyear-currentmonth-12
17523 Fri --> nearest Friday (today or later)
17524 etc.
17526 Furthermore you can specify a relative date by giving, as the *first* thing
17527 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17528 change in days weeks, months, years.
17529 With a single plus or minus, the date is relative to today. With a double
17530 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17531 +4d --> four days from today
17532 +4 --> same as above
17533 +2w --> two weeks from today
17534 ++5 --> five days from default date
17536 The function understands only English month and weekday abbreviations,
17537 but this can be configured with the variables `parse-time-months' and
17538 `parse-time-weekdays'.
17540 While prompting, a calendar is popped up - you can also select the
17541 date with the mouse (button 1). The calendar shows a period of three
17542 months. To scroll it to other months, use the keys `>' and `<'.
17543 If you don't like the calendar, turn it off with
17544 \(setq org-read-date-popup-calendar nil)
17546 With optional argument TO-TIME, the date will immediately be converted
17547 to an internal time.
17548 With an optional argument WITH-TIME, the prompt will suggest to also
17549 insert a time. Note that when WITH-TIME is not set, you can still
17550 enter a time, and this function will inform the calling routine about
17551 this change. The calling routine may then choose to change the format
17552 used to insert the time stamp into the buffer to include the time.
17553 With optional argument FROM-STRING, read from this string instead from
17554 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17555 the time/date that is used for everything that is not specified by the
17556 user."
17557 (require 'parse-time)
17558 (let* ((org-time-stamp-rounding-minutes
17559 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17560 (org-dcst org-display-custom-times)
17561 (ct (org-current-time))
17562 (def (or default-time ct))
17563 (defdecode (decode-time def))
17564 (dummy (progn
17565 (when (< (nth 2 defdecode) org-extend-today-until)
17566 (setcar (nthcdr 2 defdecode) -1)
17567 (setcar (nthcdr 1 defdecode) 59)
17568 (setq def (apply 'encode-time defdecode)
17569 defdecode (decode-time def)))))
17570 (calendar-move-hook nil)
17571 (view-diary-entries-initially nil)
17572 (view-calendar-holidays-initially nil)
17573 (timestr (format-time-string
17574 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17575 (prompt (concat (if prompt (concat prompt " ") "")
17576 (format "Date+time [%s]: " timestr)))
17577 ans (org-ans0 "") org-ans1 org-ans2 final)
17579 (cond
17580 (from-string (setq ans from-string))
17581 (org-read-date-popup-calendar
17582 (save-excursion
17583 (save-window-excursion
17584 (calendar)
17585 (calendar-forward-day (- (time-to-days def)
17586 (calendar-absolute-from-gregorian
17587 (calendar-current-date))))
17588 (org-eval-in-calendar nil t)
17589 (let* ((old-map (current-local-map))
17590 (map (copy-keymap calendar-mode-map))
17591 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17592 (org-defkey map (kbd "RET") 'org-calendar-select)
17593 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17594 'org-calendar-select-mouse)
17595 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17596 'org-calendar-select-mouse)
17597 (org-defkey minibuffer-local-map [(meta shift left)]
17598 (lambda () (interactive)
17599 (org-eval-in-calendar '(calendar-backward-month 1))))
17600 (org-defkey minibuffer-local-map [(meta shift right)]
17601 (lambda () (interactive)
17602 (org-eval-in-calendar '(calendar-forward-month 1))))
17603 (org-defkey minibuffer-local-map [(meta shift up)]
17604 (lambda () (interactive)
17605 (org-eval-in-calendar '(calendar-backward-year 1))))
17606 (org-defkey minibuffer-local-map [(meta shift down)]
17607 (lambda () (interactive)
17608 (org-eval-in-calendar '(calendar-forward-year 1))))
17609 (org-defkey minibuffer-local-map [(shift up)]
17610 (lambda () (interactive)
17611 (org-eval-in-calendar '(calendar-backward-week 1))))
17612 (org-defkey minibuffer-local-map [(shift down)]
17613 (lambda () (interactive)
17614 (org-eval-in-calendar '(calendar-forward-week 1))))
17615 (org-defkey minibuffer-local-map [(shift left)]
17616 (lambda () (interactive)
17617 (org-eval-in-calendar '(calendar-backward-day 1))))
17618 (org-defkey minibuffer-local-map [(shift right)]
17619 (lambda () (interactive)
17620 (org-eval-in-calendar '(calendar-forward-day 1))))
17621 (org-defkey minibuffer-local-map ">"
17622 (lambda () (interactive)
17623 (org-eval-in-calendar '(scroll-calendar-left 1))))
17624 (org-defkey minibuffer-local-map "<"
17625 (lambda () (interactive)
17626 (org-eval-in-calendar '(scroll-calendar-right 1))))
17627 (unwind-protect
17628 (progn
17629 (use-local-map map)
17630 (add-hook 'post-command-hook 'org-read-date-display)
17631 (setq org-ans0 (read-string prompt default-input nil nil))
17632 ;; org-ans0: from prompt
17633 ;; org-ans1: from mouse click
17634 ;; org-ans2: from calendar motion
17635 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17636 (remove-hook 'post-command-hook 'org-read-date-display)
17637 (use-local-map old-map)
17638 (when org-read-date-overlay
17639 (org-delete-overlay org-read-date-overlay)
17640 (setq org-read-date-overlay nil)))))))
17642 (t ; Naked prompt only
17643 (unwind-protect
17644 (setq ans (read-string prompt default-input nil timestr))
17645 (when org-read-date-overlay
17646 (org-delete-overlay org-read-date-overlay)
17647 (setq org-read-date-overlay nil)))))
17649 (setq final (org-read-date-analyze ans def defdecode))
17651 (if to-time
17652 (apply 'encode-time final)
17653 (if (and (boundp 'org-time-was-given) org-time-was-given)
17654 (format "%04d-%02d-%02d %02d:%02d"
17655 (nth 5 final) (nth 4 final) (nth 3 final)
17656 (nth 2 final) (nth 1 final))
17657 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17658 (defvar def)
17659 (defvar defdecode)
17660 (defvar with-time)
17661 (defun org-read-date-display ()
17662 "Display the currrent date prompt interpretation in the minibuffer."
17663 (when org-read-date-display-live
17664 (when org-read-date-overlay
17665 (org-delete-overlay org-read-date-overlay))
17666 (let ((p (point)))
17667 (end-of-line 1)
17668 (while (not (equal (buffer-substring
17669 (max (point-min) (- (point) 4)) (point))
17670 " "))
17671 (insert " "))
17672 (goto-char p))
17673 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17674 " " (or org-ans1 org-ans2)))
17675 (org-end-time-was-given nil)
17676 (f (org-read-date-analyze ans def defdecode))
17677 (fmts (if org-dcst
17678 org-time-stamp-custom-formats
17679 org-time-stamp-formats))
17680 (fmt (if (or with-time
17681 (and (boundp 'org-time-was-given) org-time-was-given))
17682 (cdr fmts)
17683 (car fmts)))
17684 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17685 (when (and org-end-time-was-given
17686 (string-match org-plain-time-of-day-regexp txt))
17687 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17688 org-end-time-was-given
17689 (substring txt (match-end 0)))))
17690 (setq org-read-date-overlay
17691 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17692 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17694 (defun org-read-date-analyze (ans def defdecode)
17695 "Analyze the combined answer of the date prompt."
17696 ;; FIXME: cleanup and comment
17697 (let (delta deltan deltaw deltadef year month day
17698 hour minute second wday pm h2 m2 tl wday1)
17700 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17701 (setq ans (replace-match "" t t ans)
17702 deltan (car delta)
17703 deltaw (nth 1 delta)
17704 deltadef (nth 2 delta)))
17706 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17707 (when (string-match
17708 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17709 (setq year (if (match-end 2)
17710 (string-to-number (match-string 2 ans))
17711 (string-to-number (format-time-string "%Y")))
17712 month (string-to-number (match-string 3 ans))
17713 day (string-to-number (match-string 4 ans)))
17714 (if (< year 100) (setq year (+ 2000 year)))
17715 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17716 t nil ans)))
17717 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17718 ;; If there is a time with am/pm, and *no* time without it, we convert
17719 ;; so that matching will be successful.
17720 (loop for i from 1 to 2 do ; twice, for end time as well
17721 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17722 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17723 (setq hour (string-to-number (match-string 1 ans))
17724 minute (if (match-end 3)
17725 (string-to-number (match-string 3 ans))
17727 pm (equal ?p
17728 (string-to-char (downcase (match-string 4 ans)))))
17729 (if (and (= hour 12) (not pm))
17730 (setq hour 0)
17731 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17732 (setq ans (replace-match (format "%02d:%02d" hour minute)
17733 t t ans))))
17735 ;; Check if a time range is given as a duration
17736 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17737 (setq hour (string-to-number (match-string 1 ans))
17738 h2 (+ hour (string-to-number (match-string 3 ans)))
17739 minute (string-to-number (match-string 2 ans))
17740 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17741 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17742 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17744 ;; Check if there is a time range
17745 (when (boundp 'org-end-time-was-given)
17746 (setq org-time-was-given nil)
17747 (when (and (string-match org-plain-time-of-day-regexp ans)
17748 (match-end 8))
17749 (setq org-end-time-was-given (match-string 8 ans))
17750 (setq ans (concat (substring ans 0 (match-beginning 7))
17751 (substring ans (match-end 7))))))
17753 (setq tl (parse-time-string ans)
17754 day (or (nth 3 tl) (nth 3 defdecode))
17755 month (or (nth 4 tl)
17756 (if (and org-read-date-prefer-future
17757 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17758 (1+ (nth 4 defdecode))
17759 (nth 4 defdecode)))
17760 year (or (nth 5 tl)
17761 (if (and org-read-date-prefer-future
17762 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17763 (1+ (nth 5 defdecode))
17764 (nth 5 defdecode)))
17765 hour (or (nth 2 tl) (nth 2 defdecode))
17766 minute (or (nth 1 tl) (nth 1 defdecode))
17767 second (or (nth 0 tl) 0)
17768 wday (nth 6 tl))
17769 (when deltan
17770 (unless deltadef
17771 (let ((now (decode-time (current-time))))
17772 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17773 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17774 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17775 ((equal deltaw "m") (setq month (+ month deltan)))
17776 ((equal deltaw "y") (setq year (+ year deltan)))))
17777 (when (and wday (not (nth 3 tl)))
17778 ;; Weekday was given, but no day, so pick that day in the week
17779 ;; on or after the derived date.
17780 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17781 (unless (equal wday wday1)
17782 (setq day (+ day (% (- wday wday1 -7) 7)))))
17783 (if (and (boundp 'org-time-was-given)
17784 (nth 2 tl))
17785 (setq org-time-was-given t))
17786 (if (< year 100) (setq year (+ 2000 year)))
17787 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17788 (list second minute hour day month year)))
17790 (defvar parse-time-weekdays)
17792 (defun org-read-date-get-relative (s today default)
17793 "Check string S for special relative date string.
17794 TODAY and DEFAULT are internal times, for today and for a default.
17795 Return shift list (N what def-flag)
17796 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17797 N is the number of WHATs to shift.
17798 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17799 the DEFAULT date rather than TODAY."
17800 (when (string-match
17801 (concat
17802 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17803 "\\([0-9]+\\)?"
17804 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17805 "\\([ \t]\\|$\\)") s)
17806 (let* ((dir (if (match-end 1)
17807 (string-to-char (substring (match-string 1 s) -1))
17808 ?+))
17809 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17810 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17811 (what (if (match-end 3) (match-string 3 s) "d"))
17812 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17813 (date (if rel default today))
17814 (wday (nth 6 (decode-time date)))
17815 delta)
17816 (if wday1
17817 (progn
17818 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17819 (if (= dir ?-) (setq delta (- delta 7)))
17820 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17821 (list delta "d" rel))
17822 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17824 (defun org-eval-in-calendar (form &optional keepdate)
17825 "Eval FORM in the calendar window and return to current window.
17826 Also, store the cursor date in variable org-ans2."
17827 (let ((sw (selected-window)))
17828 (select-window (get-buffer-window "*Calendar*"))
17829 (eval form)
17830 (when (and (not keepdate) (calendar-cursor-to-date))
17831 (let* ((date (calendar-cursor-to-date))
17832 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17833 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17834 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17835 (select-window sw)))
17837 ; ;; Update the prompt to show new default date
17838 ; (save-excursion
17839 ; (goto-char (point-min))
17840 ; (when (and org-ans2
17841 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17842 ; (get-text-property (match-end 0) 'field))
17843 ; (let ((inhibit-read-only t))
17844 ; (replace-match (concat "[" org-ans2 "]") t t)
17845 ; (add-text-properties (point-min) (1+ (match-end 0))
17846 ; (text-properties-at (1+ (point-min)))))))))
17848 (defun org-calendar-select ()
17849 "Return to `org-read-date' with the date currently selected.
17850 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17851 (interactive)
17852 (when (calendar-cursor-to-date)
17853 (let* ((date (calendar-cursor-to-date))
17854 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17855 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17856 (if (active-minibuffer-window) (exit-minibuffer))))
17858 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17859 "Insert a date stamp for the date given by the internal TIME.
17860 WITH-HM means, use the stamp format that includes the time of the day.
17861 INACTIVE means use square brackets instead of angular ones, so that the
17862 stamp will not contribute to the agenda.
17863 PRE and POST are optional strings to be inserted before and after the
17864 stamp.
17865 The command returns the inserted time stamp."
17866 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17867 stamp)
17868 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17869 (insert-before-markers (or pre ""))
17870 (insert-before-markers (setq stamp (format-time-string fmt time)))
17871 (when (listp extra)
17872 (setq extra (car extra))
17873 (if (and (stringp extra)
17874 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17875 (setq extra (format "-%02d:%02d"
17876 (string-to-number (match-string 1 extra))
17877 (string-to-number (match-string 2 extra))))
17878 (setq extra nil)))
17879 (when extra
17880 (backward-char 1)
17881 (insert-before-markers extra)
17882 (forward-char 1))
17883 (insert-before-markers (or post ""))
17884 stamp))
17886 (defun org-toggle-time-stamp-overlays ()
17887 "Toggle the use of custom time stamp formats."
17888 (interactive)
17889 (setq org-display-custom-times (not org-display-custom-times))
17890 (unless org-display-custom-times
17891 (let ((p (point-min)) (bmp (buffer-modified-p)))
17892 (while (setq p (next-single-property-change p 'display))
17893 (if (and (get-text-property p 'display)
17894 (eq (get-text-property p 'face) 'org-date))
17895 (remove-text-properties
17896 p (setq p (next-single-property-change p 'display))
17897 '(display t))))
17898 (set-buffer-modified-p bmp)))
17899 (if (featurep 'xemacs)
17900 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17901 (org-restart-font-lock)
17902 (setq org-table-may-need-update t)
17903 (if org-display-custom-times
17904 (message "Time stamps are overlayed with custom format")
17905 (message "Time stamp overlays removed")))
17907 (defun org-display-custom-time (beg end)
17908 "Overlay modified time stamp format over timestamp between BED and END."
17909 (let* ((ts (buffer-substring beg end))
17910 t1 w1 with-hm tf time str w2 (off 0))
17911 (save-match-data
17912 (setq t1 (org-parse-time-string ts t))
17913 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17914 (setq off (- (match-end 0) (match-beginning 0)))))
17915 (setq end (- end off))
17916 (setq w1 (- end beg)
17917 with-hm (and (nth 1 t1) (nth 2 t1))
17918 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17919 time (org-fix-decoded-time t1)
17920 str (org-add-props
17921 (format-time-string
17922 (substring tf 1 -1) (apply 'encode-time time))
17923 nil 'mouse-face 'highlight)
17924 w2 (length str))
17925 (if (not (= w2 w1))
17926 (add-text-properties (1+ beg) (+ 2 beg)
17927 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17928 (if (featurep 'xemacs)
17929 (progn
17930 (put-text-property beg end 'invisible t)
17931 (put-text-property beg end 'end-glyph (make-glyph str)))
17932 (put-text-property beg end 'display str))))
17934 (defun org-translate-time (string)
17935 "Translate all timestamps in STRING to custom format.
17936 But do this only if the variable `org-display-custom-times' is set."
17937 (when org-display-custom-times
17938 (save-match-data
17939 (let* ((start 0)
17940 (re org-ts-regexp-both)
17941 t1 with-hm inactive tf time str beg end)
17942 (while (setq start (string-match re string start))
17943 (setq beg (match-beginning 0)
17944 end (match-end 0)
17945 t1 (save-match-data
17946 (org-parse-time-string (substring string beg end) t))
17947 with-hm (and (nth 1 t1) (nth 2 t1))
17948 inactive (equal (substring string beg (1+ beg)) "[")
17949 tf (funcall (if with-hm 'cdr 'car)
17950 org-time-stamp-custom-formats)
17951 time (org-fix-decoded-time t1)
17952 str (format-time-string
17953 (concat
17954 (if inactive "[" "<") (substring tf 1 -1)
17955 (if inactive "]" ">"))
17956 (apply 'encode-time time))
17957 string (replace-match str t t string)
17958 start (+ start (length str)))))))
17959 string)
17961 (defun org-fix-decoded-time (time)
17962 "Set 0 instead of nil for the first 6 elements of time.
17963 Don't touch the rest."
17964 (let ((n 0))
17965 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17967 (defun org-days-to-time (timestamp-string)
17968 "Difference between TIMESTAMP-STRING and now in days."
17969 (- (time-to-days (org-time-string-to-time timestamp-string))
17970 (time-to-days (current-time))))
17972 (defun org-deadline-close (timestamp-string &optional ndays)
17973 "Is the time in TIMESTAMP-STRING close to the current date?"
17974 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17975 (and (< (org-days-to-time timestamp-string) ndays)
17976 (not (org-entry-is-done-p))))
17978 (defun org-get-wdays (ts)
17979 "Get the deadline lead time appropriate for timestring TS."
17980 (cond
17981 ((<= org-deadline-warning-days 0)
17982 ;; 0 or negative, enforce this value no matter what
17983 (- org-deadline-warning-days))
17984 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17985 ;; lead time is specified.
17986 (floor (* (string-to-number (match-string 1 ts))
17987 (cdr (assoc (match-string 2 ts)
17988 '(("d" . 1) ("w" . 7)
17989 ("m" . 30.4) ("y" . 365.25)))))))
17990 ;; go for the default.
17991 (t org-deadline-warning-days)))
17993 (defun org-calendar-select-mouse (ev)
17994 "Return to `org-read-date' with the date currently selected.
17995 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17996 (interactive "e")
17997 (mouse-set-point ev)
17998 (when (calendar-cursor-to-date)
17999 (let* ((date (calendar-cursor-to-date))
18000 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18001 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18002 (if (active-minibuffer-window) (exit-minibuffer))))
18004 (defun org-check-deadlines (ndays)
18005 "Check if there are any deadlines due or past due.
18006 A deadline is considered due if it happens within `org-deadline-warning-days'
18007 days from today's date. If the deadline appears in an entry marked DONE,
18008 it is not shown. The prefix arg NDAYS can be used to test that many
18009 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18010 (interactive "P")
18011 (let* ((org-warn-days
18012 (cond
18013 ((equal ndays '(4)) 100000)
18014 (ndays (prefix-numeric-value ndays))
18015 (t (abs org-deadline-warning-days))))
18016 (case-fold-search nil)
18017 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18018 (callback
18019 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18021 (message "%d deadlines past-due or due within %d days"
18022 (org-occur regexp nil callback)
18023 org-warn-days)))
18025 (defun org-check-before-date (date)
18026 "Check if there are deadlines or scheduled entries before DATE."
18027 (interactive (list (org-read-date)))
18028 (let ((case-fold-search nil)
18029 (regexp (concat "\\<\\(" org-deadline-string
18030 "\\|" org-scheduled-string
18031 "\\) *<\\([^>]+\\)>"))
18032 (callback
18033 (lambda () (time-less-p
18034 (org-time-string-to-time (match-string 2))
18035 (org-time-string-to-time date)))))
18036 (message "%d entries before %s"
18037 (org-occur regexp nil callback) date)))
18039 (defun org-evaluate-time-range (&optional to-buffer)
18040 "Evaluate a time range by computing the difference between start and end.
18041 Normally the result is just printed in the echo area, but with prefix arg
18042 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18043 If the time range is actually in a table, the result is inserted into the
18044 next column.
18045 For time difference computation, a year is assumed to be exactly 365
18046 days in order to avoid rounding problems."
18047 (interactive "P")
18049 (org-clock-update-time-maybe)
18050 (save-excursion
18051 (unless (org-at-date-range-p t)
18052 (goto-char (point-at-bol))
18053 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18054 (if (not (org-at-date-range-p t))
18055 (error "Not at a time-stamp range, and none found in current line")))
18056 (let* ((ts1 (match-string 1))
18057 (ts2 (match-string 2))
18058 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18059 (match-end (match-end 0))
18060 (time1 (org-time-string-to-time ts1))
18061 (time2 (org-time-string-to-time ts2))
18062 (t1 (time-to-seconds time1))
18063 (t2 (time-to-seconds time2))
18064 (diff (abs (- t2 t1)))
18065 (negative (< (- t2 t1) 0))
18066 ;; (ys (floor (* 365 24 60 60)))
18067 (ds (* 24 60 60))
18068 (hs (* 60 60))
18069 (fy "%dy %dd %02d:%02d")
18070 (fy1 "%dy %dd")
18071 (fd "%dd %02d:%02d")
18072 (fd1 "%dd")
18073 (fh "%02d:%02d")
18074 y d h m align)
18075 (if havetime
18076 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18078 d (floor (/ diff ds)) diff (mod diff ds)
18079 h (floor (/ diff hs)) diff (mod diff hs)
18080 m (floor (/ diff 60)))
18081 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18083 d (floor (+ (/ diff ds) 0.5))
18084 h 0 m 0))
18085 (if (not to-buffer)
18086 (message "%s" (org-make-tdiff-string y d h m))
18087 (if (org-at-table-p)
18088 (progn
18089 (goto-char match-end)
18090 (setq align t)
18091 (and (looking-at " *|") (goto-char (match-end 0))))
18092 (goto-char match-end))
18093 (if (looking-at
18094 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18095 (replace-match ""))
18096 (if negative (insert " -"))
18097 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18098 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18099 (insert " " (format fh h m))))
18100 (if align (org-table-align))
18101 (message "Time difference inserted")))))
18103 (defun org-make-tdiff-string (y d h m)
18104 (let ((fmt "")
18105 (l nil))
18106 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18107 l (push y l)))
18108 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18109 l (push d l)))
18110 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18111 l (push h l)))
18112 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18113 l (push m l)))
18114 (apply 'format fmt (nreverse l))))
18116 (defun org-time-string-to-time (s)
18117 (apply 'encode-time (org-parse-time-string s)))
18119 (defun org-time-string-to-absolute (s &optional daynr prefer)
18120 "Convert a time stamp to an absolute day number.
18121 If there is a specifyer for a cyclic time stamp, get the closest date to
18122 DAYNR."
18123 (cond
18124 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18125 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18126 daynr
18127 (+ daynr 1000)))
18128 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18129 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18130 (time-to-days (current-time))) (match-string 0 s)
18131 prefer))
18132 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18134 (defun org-time-from-absolute (d)
18135 "Return the time corresponding to date D.
18136 D may be an absolute day number, or a calendar-type list (month day year)."
18137 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18138 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18140 (defun org-calendar-holiday ()
18141 "List of holidays, for Diary display in Org-mode."
18142 (require 'holidays)
18143 (let ((hl (funcall
18144 (if (fboundp 'calendar-check-holidays)
18145 'calendar-check-holidays 'check-calendar-holidays) date)))
18146 (if hl (mapconcat 'identity hl "; "))))
18148 (defun org-diary-sexp-entry (sexp entry date)
18149 "Process a SEXP diary ENTRY for DATE."
18150 (require 'diary-lib)
18151 (let ((result (if calendar-debug-sexp
18152 (let ((stack-trace-on-error t))
18153 (eval (car (read-from-string sexp))))
18154 (condition-case nil
18155 (eval (car (read-from-string sexp)))
18156 (error
18157 (beep)
18158 (message "Bad sexp at line %d in %s: %s"
18159 (org-current-line)
18160 (buffer-file-name) sexp)
18161 (sleep-for 2))))))
18162 (cond ((stringp result) result)
18163 ((and (consp result)
18164 (stringp (cdr result))) (cdr result))
18165 (result entry)
18166 (t nil))))
18168 (defun org-diary-to-ical-string (frombuf)
18169 "Get iCalendar entries from diary entries in buffer FROMBUF.
18170 This uses the icalendar.el library."
18171 (let* ((tmpdir (if (featurep 'xemacs)
18172 (temp-directory)
18173 temporary-file-directory))
18174 (tmpfile (make-temp-name
18175 (expand-file-name "orgics" tmpdir)))
18176 buf rtn b e)
18177 (save-excursion
18178 (set-buffer frombuf)
18179 (icalendar-export-region (point-min) (point-max) tmpfile)
18180 (setq buf (find-buffer-visiting tmpfile))
18181 (set-buffer buf)
18182 (goto-char (point-min))
18183 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18184 (setq b (match-beginning 0)))
18185 (goto-char (point-max))
18186 (if (re-search-backward "^END:VEVENT" nil t)
18187 (setq e (match-end 0)))
18188 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18189 (kill-buffer buf)
18190 (kill-buffer frombuf)
18191 (delete-file tmpfile)
18192 rtn))
18194 (defun org-closest-date (start current change prefer)
18195 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18196 When PREFER is `past' return a date that is either CURRENT or past.
18197 When PREFER is `future', return a date that is either CURRENT or future."
18198 ;; Make the proper lists from the dates
18199 (catch 'exit
18200 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18201 dn dw sday cday n1 n2
18202 d m y y1 y2 date1 date2 nmonths nm ny m2)
18204 (setq start (org-date-to-gregorian start)
18205 current (org-date-to-gregorian
18206 (if org-agenda-repeating-timestamp-show-all
18207 current
18208 (time-to-days (current-time))))
18209 sday (calendar-absolute-from-gregorian start)
18210 cday (calendar-absolute-from-gregorian current))
18212 (if (<= cday sday) (throw 'exit sday))
18214 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18215 (setq dn (string-to-number (match-string 1 change))
18216 dw (cdr (assoc (match-string 2 change) a1)))
18217 (error "Invalid change specifyer: %s" change))
18218 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18219 (cond
18220 ((eq dw 'day)
18221 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18222 n2 (+ n1 dn)))
18223 ((eq dw 'year)
18224 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18225 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18226 (setq date1 (list m d y1)
18227 n1 (calendar-absolute-from-gregorian date1)
18228 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18229 n2 (calendar-absolute-from-gregorian date2)))
18230 ((eq dw 'month)
18231 ;; approx number of month between the tow dates
18232 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18233 ;; How often does dn fit in there?
18234 (setq d (nth 1 start) m (car start) y (nth 2 start)
18235 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18236 m (+ m nm)
18237 ny (floor (/ m 12))
18238 y (+ y ny)
18239 m (- m (* ny 12)))
18240 (while (> m 12) (setq m (- m 12) y (1+ y)))
18241 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18242 (setq m2 (+ m dn) y2 y)
18243 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18244 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18245 (while (< n2 cday)
18246 (setq n1 n2 m m2 y y2)
18247 (setq m2 (+ m dn) y2 y)
18248 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18249 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18251 (if org-agenda-repeating-timestamp-show-all
18252 (cond
18253 ((eq prefer 'past) n1)
18254 ((eq prefer 'future) (if (= cday n1) n1 n2))
18255 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18256 (cond
18257 ((eq prefer 'past) n1)
18258 ((eq prefer 'future) (if (= cday n1) n1 n2))
18259 (t (if (= cday n1) n1 n2)))))))
18261 (defun org-date-to-gregorian (date)
18262 "Turn any specification of DATE into a gregorian date for the calendar."
18263 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18264 ((and (listp date) (= (length date) 3)) date)
18265 ((stringp date)
18266 (setq date (org-parse-time-string date))
18267 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18268 ((listp date)
18269 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18271 (defun org-parse-time-string (s &optional nodefault)
18272 "Parse the standard Org-mode time string.
18273 This should be a lot faster than the normal `parse-time-string'.
18274 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18275 hour and minute fields will be nil if not given."
18276 (if (string-match org-ts-regexp0 s)
18277 (list 0
18278 (if (or (match-beginning 8) (not nodefault))
18279 (string-to-number (or (match-string 8 s) "0")))
18280 (if (or (match-beginning 7) (not nodefault))
18281 (string-to-number (or (match-string 7 s) "0")))
18282 (string-to-number (match-string 4 s))
18283 (string-to-number (match-string 3 s))
18284 (string-to-number (match-string 2 s))
18285 nil nil nil)
18286 (make-list 9 0)))
18288 (defun org-timestamp-up (&optional arg)
18289 "Increase the date item at the cursor by one.
18290 If the cursor is on the year, change the year. If it is on the month or
18291 the day, change that.
18292 With prefix ARG, change by that many units."
18293 (interactive "p")
18294 (org-timestamp-change (prefix-numeric-value arg)))
18296 (defun org-timestamp-down (&optional arg)
18297 "Decrease the date item at the cursor by one.
18298 If the cursor is on the year, change the year. If it is on the month or
18299 the day, change that.
18300 With prefix ARG, change by that many units."
18301 (interactive "p")
18302 (org-timestamp-change (- (prefix-numeric-value arg))))
18304 (defun org-timestamp-up-day (&optional arg)
18305 "Increase the date in the time stamp by one day.
18306 With prefix ARG, change that many days."
18307 (interactive "p")
18308 (if (and (not (org-at-timestamp-p t))
18309 (org-on-heading-p))
18310 (org-todo 'up)
18311 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18313 (defun org-timestamp-down-day (&optional arg)
18314 "Decrease the date in the time stamp by one day.
18315 With prefix ARG, change that many days."
18316 (interactive "p")
18317 (if (and (not (org-at-timestamp-p t))
18318 (org-on-heading-p))
18319 (org-todo 'down)
18320 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18322 (defsubst org-pos-in-match-range (pos n)
18323 (and (match-beginning n)
18324 (<= (match-beginning n) pos)
18325 (>= (match-end n) pos)))
18327 (defun org-at-timestamp-p (&optional inactive-ok)
18328 "Determine if the cursor is in or at a timestamp."
18329 (interactive)
18330 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18331 (pos (point))
18332 (ans (or (looking-at tsr)
18333 (save-excursion
18334 (skip-chars-backward "^[<\n\r\t")
18335 (if (> (point) (point-min)) (backward-char 1))
18336 (and (looking-at tsr)
18337 (> (- (match-end 0) pos) -1))))))
18338 (and ans
18339 (boundp 'org-ts-what)
18340 (setq org-ts-what
18341 (cond
18342 ((= pos (match-beginning 0)) 'bracket)
18343 ((= pos (1- (match-end 0))) 'bracket)
18344 ((org-pos-in-match-range pos 2) 'year)
18345 ((org-pos-in-match-range pos 3) 'month)
18346 ((org-pos-in-match-range pos 7) 'hour)
18347 ((org-pos-in-match-range pos 8) 'minute)
18348 ((or (org-pos-in-match-range pos 4)
18349 (org-pos-in-match-range pos 5)) 'day)
18350 ((and (> pos (or (match-end 8) (match-end 5)))
18351 (< pos (match-end 0)))
18352 (- pos (or (match-end 8) (match-end 5))))
18353 (t 'day))))
18354 ans))
18356 (defun org-toggle-timestamp-type ()
18358 (interactive)
18359 (when (org-at-timestamp-p t)
18360 (save-excursion
18361 (goto-char (match-beginning 0))
18362 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18363 (goto-char (1- (match-end 0)))
18364 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18365 (message "Timestamp is now %sactive"
18366 (if (equal (char-before) ?>) "in" ""))))
18368 (defun org-timestamp-change (n &optional what)
18369 "Change the date in the time stamp at point.
18370 The date will be changed by N times WHAT. WHAT can be `day', `month',
18371 `year', `minute', `second'. If WHAT is not given, the cursor position
18372 in the timestamp determines what will be changed."
18373 (let ((pos (point))
18374 with-hm inactive
18375 org-ts-what
18376 extra
18377 ts time time0)
18378 (if (not (org-at-timestamp-p t))
18379 (error "Not at a timestamp"))
18380 (if (and (not what) (eq org-ts-what 'bracket))
18381 (org-toggle-timestamp-type)
18382 (if (and (not what) (not (eq org-ts-what 'day))
18383 org-display-custom-times
18384 (get-text-property (point) 'display)
18385 (not (get-text-property (1- (point)) 'display)))
18386 (setq org-ts-what 'day))
18387 (setq org-ts-what (or what org-ts-what)
18388 inactive (= (char-after (match-beginning 0)) ?\[)
18389 ts (match-string 0))
18390 (replace-match "")
18391 (if (string-match
18392 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18394 (setq extra (match-string 1 ts)))
18395 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18396 (setq with-hm t))
18397 (setq time0 (org-parse-time-string ts))
18398 (setq time
18399 (encode-time (or (car time0) 0)
18400 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18401 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18402 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18403 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18404 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18405 (nthcdr 6 time0)))
18406 (when (integerp org-ts-what)
18407 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18408 (if (eq what 'calendar)
18409 (let ((cal-date (org-get-date-from-calendar)))
18410 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18411 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18412 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18413 (setcar time0 (or (car time0) 0))
18414 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18415 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18416 (setq time (apply 'encode-time time0))))
18417 (setq org-last-changed-timestamp
18418 (org-insert-time-stamp time with-hm inactive nil nil extra))
18419 (org-clock-update-time-maybe)
18420 (goto-char pos)
18421 ;; Try to recenter the calendar window, if any
18422 (if (and org-calendar-follow-timestamp-change
18423 (get-buffer-window "*Calendar*" t)
18424 (memq org-ts-what '(day month year)))
18425 (org-recenter-calendar (time-to-days time))))))
18427 ;; FIXME: does not yet work for lead times
18428 (defun org-modify-ts-extra (s pos n)
18429 "Change the different parts of the lead-time and repeat fields in timestamp."
18430 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18431 ng h m new)
18432 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18433 (cond
18434 ((or (org-pos-in-match-range pos 2)
18435 (org-pos-in-match-range pos 3))
18436 (setq m (string-to-number (match-string 3 s))
18437 h (string-to-number (match-string 2 s)))
18438 (if (org-pos-in-match-range pos 2)
18439 (setq h (+ h n))
18440 (setq m (+ m n)))
18441 (if (< m 0) (setq m (+ m 60) h (1- h)))
18442 (if (> m 59) (setq m (- m 60) h (1+ h)))
18443 (setq h (min 24 (max 0 h)))
18444 (setq ng 1 new (format "-%02d:%02d" h m)))
18445 ((org-pos-in-match-range pos 6)
18446 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18447 ((org-pos-in-match-range pos 5)
18448 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18450 (when ng
18451 (setq s (concat
18452 (substring s 0 (match-beginning ng))
18454 (substring s (match-end ng))))))
18457 (defun org-recenter-calendar (date)
18458 "If the calendar is visible, recenter it to DATE."
18459 (let* ((win (selected-window))
18460 (cwin (get-buffer-window "*Calendar*" t))
18461 (calendar-move-hook nil))
18462 (when cwin
18463 (select-window cwin)
18464 (calendar-goto-date (if (listp date) date
18465 (calendar-gregorian-from-absolute date)))
18466 (select-window win))))
18468 (defun org-goto-calendar (&optional arg)
18469 "Go to the Emacs calendar at the current date.
18470 If there is a time stamp in the current line, go to that date.
18471 A prefix ARG can be used to force the current date."
18472 (interactive "P")
18473 (let ((tsr org-ts-regexp) diff
18474 (calendar-move-hook nil)
18475 (view-calendar-holidays-initially nil)
18476 (view-diary-entries-initially nil))
18477 (if (or (org-at-timestamp-p)
18478 (save-excursion
18479 (beginning-of-line 1)
18480 (looking-at (concat ".*" tsr))))
18481 (let ((d1 (time-to-days (current-time)))
18482 (d2 (time-to-days
18483 (org-time-string-to-time (match-string 1)))))
18484 (setq diff (- d2 d1))))
18485 (calendar)
18486 (calendar-goto-today)
18487 (if (and diff (not arg)) (calendar-forward-day diff))))
18489 (defun org-get-date-from-calendar ()
18490 "Return a list (month day year) of date at point in calendar."
18491 (with-current-buffer "*Calendar*"
18492 (save-match-data
18493 (calendar-cursor-to-date))))
18495 (defun org-date-from-calendar ()
18496 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18497 If there is already a time stamp at the cursor position, update it."
18498 (interactive)
18499 (if (org-at-timestamp-p t)
18500 (org-timestamp-change 0 'calendar)
18501 (let ((cal-date (org-get-date-from-calendar)))
18502 (org-insert-time-stamp
18503 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18505 ;; Make appt aware of appointments from the agenda
18506 ;;;###autoload
18507 (defun org-agenda-to-appt (&optional filter)
18508 "Activate appointments found in `org-agenda-files'.
18509 When prefixed, prompt for a regular expression and use it as a
18510 filter: only add entries if they match this regular expression.
18512 FILTER can be a string. In this case, use this string as a
18513 regular expression to filter results.
18515 FILTER can also be an alist, with the car of each cell being
18516 either 'headline or 'category. For example:
18518 '((headline \"IMPORTANT\")
18519 (category \"Work\"))
18521 will only add headlines containing IMPORTANT or headlines
18522 belonging to the category \"Work\"."
18523 (interactive "P")
18524 (require 'calendar)
18525 (if (equal filter '(4))
18526 (setq filter (read-from-minibuffer "Regexp filter: ")))
18527 (let* ((cnt 0) ; count added events
18528 (org-agenda-new-buffers nil)
18529 (today (org-date-to-gregorian
18530 (time-to-days (current-time))))
18531 (files (org-agenda-files)) entries file)
18532 ;; Get all entries which may contain an appt
18533 (while (setq file (pop files))
18534 (setq entries
18535 (append entries
18536 (org-agenda-get-day-entries
18537 file today
18538 :timestamp :scheduled :deadline))))
18539 (setq entries (delq nil entries))
18540 ;; Map thru entries and find if they pass thru the filter
18541 (mapc
18542 (lambda(x)
18543 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18544 (cat (get-text-property 1 'org-category x))
18545 (tod (get-text-property 1 'time-of-day x))
18546 (ok (or (null filter)
18547 (and (stringp filter) (string-match filter evt))
18548 (and (listp filter)
18549 (or (string-match
18550 (cadr (assoc 'category filter)) cat)
18551 (string-match
18552 (cadr (assoc 'headline filter)) evt))))))
18553 ;; FIXME: Shall we remove text-properties for the appt text?
18554 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18555 (when (and ok tod)
18556 (setq tod (number-to-string tod)
18557 tod (when (string-match
18558 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18559 (concat (match-string 1 tod) ":"
18560 (match-string 2 tod))))
18561 (appt-add tod evt)
18562 (setq cnt (1+ cnt))))) entries)
18563 (org-release-buffers org-agenda-new-buffers)
18564 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18566 ;;; The clock for measuring work time.
18568 (defvar org-mode-line-string "")
18569 (put 'org-mode-line-string 'risky-local-variable t)
18571 (defvar org-mode-line-timer nil)
18572 (defvar org-clock-heading "")
18573 (defvar org-clock-start-time "")
18575 (defun org-update-mode-line ()
18576 (let* ((delta (- (time-to-seconds (current-time))
18577 (time-to-seconds org-clock-start-time)))
18578 (h (floor delta 3600))
18579 (m (floor (- delta (* 3600 h)) 60)))
18580 (setq org-mode-line-string
18581 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18582 'help-echo "Org-mode clock is running"))
18583 (force-mode-line-update)))
18585 (defvar org-clock-marker (make-marker)
18586 "Marker recording the last clock-in.")
18587 (defvar org-clock-mode-line-entry nil
18588 "Information for the modeline about the running clock.")
18590 (defun org-clock-in ()
18591 "Start the clock on the current item.
18592 If necessary, clock-out of the currently active clock."
18593 (interactive)
18594 (org-clock-out t)
18595 (let (ts)
18596 (save-excursion
18597 (org-back-to-heading t)
18598 (when (and org-clock-in-switch-to-state
18599 (not (looking-at (concat outline-regexp "[ \t]*"
18600 org-clock-in-switch-to-state
18601 "\\>"))))
18602 (org-todo org-clock-in-switch-to-state))
18603 (if (and org-clock-heading-function
18604 (functionp org-clock-heading-function))
18605 (setq org-clock-heading (funcall org-clock-heading-function))
18606 (if (looking-at org-complex-heading-regexp)
18607 (setq org-clock-heading (match-string 4))
18608 (setq org-clock-heading "???")))
18609 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18610 (org-clock-find-position)
18612 (insert "\n") (backward-char 1)
18613 (indent-relative)
18614 (insert org-clock-string " ")
18615 (setq org-clock-start-time (current-time))
18616 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18617 (move-marker org-clock-marker (point) (buffer-base-buffer))
18618 (or global-mode-string (setq global-mode-string '("")))
18619 (or (memq 'org-mode-line-string global-mode-string)
18620 (setq global-mode-string
18621 (append global-mode-string '(org-mode-line-string))))
18622 (org-update-mode-line)
18623 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18624 (message "Clock started at %s" ts))))
18626 (defun org-clock-find-position ()
18627 "Find the location where the next clock line should be inserted."
18628 (org-back-to-heading t)
18629 (catch 'exit
18630 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18631 (re (concat "^[ \t]*" org-clock-string))
18632 (cnt 0)
18633 first last)
18634 (goto-char beg)
18635 (when (eobp) (newline) (setq end (max (point) end)))
18636 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18637 ;; we seem to have a CLOCK drawer, so go there.
18638 (beginning-of-line 2)
18639 (throw 'exit t))
18640 ;; Lets count the CLOCK lines
18641 (goto-char beg)
18642 (while (re-search-forward re end t)
18643 (setq first (or first (match-beginning 0))
18644 last (match-beginning 0)
18645 cnt (1+ cnt)))
18646 (when (and (integerp org-clock-into-drawer)
18647 (>= (1+ cnt) org-clock-into-drawer))
18648 ;; Wrap current entries into a new drawer
18649 (goto-char last)
18650 (beginning-of-line 2)
18651 (if (org-at-item-p) (org-end-of-item))
18652 (insert ":END:\n")
18653 (beginning-of-line 0)
18654 (org-indent-line-function)
18655 (goto-char first)
18656 (insert ":CLOCK:\n")
18657 (beginning-of-line 0)
18658 (org-indent-line-function)
18659 (org-flag-drawer t)
18660 (beginning-of-line 2)
18661 (throw 'exit nil))
18663 (goto-char beg)
18664 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18665 (not (equal (match-string 1) org-clock-string)))
18666 ;; Planning info, skip to after it
18667 (beginning-of-line 2)
18668 (or (bolp) (newline)))
18669 (when (eq t org-clock-into-drawer)
18670 (insert ":CLOCK:\n:END:\n")
18671 (beginning-of-line -1)
18672 (org-indent-line-function)
18673 (org-flag-drawer t)
18674 (beginning-of-line 2)
18675 (org-indent-line-function)))))
18677 (defun org-clock-out (&optional fail-quietly)
18678 "Stop the currently running clock.
18679 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18680 (interactive)
18681 (catch 'exit
18682 (if (not (marker-buffer org-clock-marker))
18683 (if fail-quietly (throw 'exit t) (error "No active clock")))
18684 (let (ts te s h m)
18685 (save-excursion
18686 (set-buffer (marker-buffer org-clock-marker))
18687 (goto-char org-clock-marker)
18688 (beginning-of-line 1)
18689 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18690 (equal (match-string 1) org-clock-string))
18691 (setq ts (match-string 2))
18692 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18693 (goto-char (match-end 0))
18694 (delete-region (point) (point-at-eol))
18695 (insert "--")
18696 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18697 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18698 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18699 h (floor (/ s 3600))
18700 s (- s (* 3600 h))
18701 m (floor (/ s 60))
18702 s (- s (* 60 s)))
18703 (insert " => " (format "%2d:%02d" h m))
18704 (move-marker org-clock-marker nil)
18705 (when org-log-note-clock-out
18706 (org-add-log-maybe 'clock-out))
18707 (when org-mode-line-timer
18708 (cancel-timer org-mode-line-timer)
18709 (setq org-mode-line-timer nil))
18710 (setq global-mode-string
18711 (delq 'org-mode-line-string global-mode-string))
18712 (force-mode-line-update)
18713 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18715 (defun org-clock-cancel ()
18716 "Cancel the running clock be removing the start timestamp."
18717 (interactive)
18718 (if (not (marker-buffer org-clock-marker))
18719 (error "No active clock"))
18720 (save-excursion
18721 (set-buffer (marker-buffer org-clock-marker))
18722 (goto-char org-clock-marker)
18723 (delete-region (1- (point-at-bol)) (point-at-eol)))
18724 (setq global-mode-string
18725 (delq 'org-mode-line-string global-mode-string))
18726 (force-mode-line-update)
18727 (message "Clock canceled"))
18729 (defun org-clock-goto (&optional delete-windows)
18730 "Go to the currently clocked-in entry."
18731 (interactive "P")
18732 (if (not (marker-buffer org-clock-marker))
18733 (error "No active clock"))
18734 (switch-to-buffer-other-window
18735 (marker-buffer org-clock-marker))
18736 (if delete-windows (delete-other-windows))
18737 (goto-char org-clock-marker)
18738 (org-show-entry)
18739 (org-back-to-heading)
18740 (recenter))
18742 (defvar org-clock-file-total-minutes nil
18743 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18744 (make-variable-buffer-local 'org-clock-file-total-minutes)
18746 (defun org-clock-sum (&optional tstart tend)
18747 "Sum the times for each subtree.
18748 Puts the resulting times in minutes as a text property on each headline."
18749 (interactive)
18750 (let* ((bmp (buffer-modified-p))
18751 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18752 org-clock-string
18753 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18754 (lmax 30)
18755 (ltimes (make-vector lmax 0))
18756 (t1 0)
18757 (level 0)
18758 ts te dt
18759 time)
18760 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18761 (save-excursion
18762 (goto-char (point-max))
18763 (while (re-search-backward re nil t)
18764 (cond
18765 ((match-end 2)
18766 ;; Two time stamps
18767 (setq ts (match-string 2)
18768 te (match-string 3)
18769 ts (time-to-seconds
18770 (apply 'encode-time (org-parse-time-string ts)))
18771 te (time-to-seconds
18772 (apply 'encode-time (org-parse-time-string te)))
18773 ts (if tstart (max ts tstart) ts)
18774 te (if tend (min te tend) te)
18775 dt (- te ts)
18776 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18777 ((match-end 4)
18778 ;; A naket time
18779 (setq t1 (+ t1 (string-to-number (match-string 5))
18780 (* 60 (string-to-number (match-string 4))))))
18781 (t ;; A headline
18782 (setq level (- (match-end 1) (match-beginning 1)))
18783 (when (or (> t1 0) (> (aref ltimes level) 0))
18784 (loop for l from 0 to level do
18785 (aset ltimes l (+ (aref ltimes l) t1)))
18786 (setq t1 0 time (aref ltimes level))
18787 (loop for l from level to (1- lmax) do
18788 (aset ltimes l 0))
18789 (goto-char (match-beginning 0))
18790 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18791 (setq org-clock-file-total-minutes (aref ltimes 0)))
18792 (set-buffer-modified-p bmp)))
18794 (defun org-clock-display (&optional total-only)
18795 "Show subtree times in the entire buffer.
18796 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18797 in the echo area."
18798 (interactive)
18799 (org-remove-clock-overlays)
18800 (let (time h m p)
18801 (org-clock-sum)
18802 (unless total-only
18803 (save-excursion
18804 (goto-char (point-min))
18805 (while (or (and (equal (setq p (point)) (point-min))
18806 (get-text-property p :org-clock-minutes))
18807 (setq p (next-single-property-change
18808 (point) :org-clock-minutes)))
18809 (goto-char p)
18810 (when (setq time (get-text-property p :org-clock-minutes))
18811 (org-put-clock-overlay time (funcall outline-level))))
18812 (setq h (/ org-clock-file-total-minutes 60)
18813 m (- org-clock-file-total-minutes (* 60 h)))
18814 ;; Arrange to remove the overlays upon next change.
18815 (when org-remove-highlights-with-change
18816 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18817 nil 'local))))
18818 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18820 (defvar org-clock-overlays nil)
18821 (make-variable-buffer-local 'org-clock-overlays)
18823 (defun org-put-clock-overlay (time &optional level)
18824 "Put an overlays on the current line, displaying TIME.
18825 If LEVEL is given, prefix time with a corresponding number of stars.
18826 This creates a new overlay and stores it in `org-clock-overlays', so that it
18827 will be easy to remove."
18828 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18829 (l (if level (org-get-legal-level level 0) 0))
18830 (off 0)
18831 ov tx)
18832 (move-to-column c)
18833 (unless (eolp) (skip-chars-backward "^ \t"))
18834 (skip-chars-backward " \t")
18835 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18836 tx (concat (buffer-substring (1- (point)) (point))
18837 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18838 (org-add-props (format "%s %2d:%02d%s"
18839 (make-string l ?*) h m
18840 (make-string (- 10 l) ?\ ))
18841 '(face secondary-selection))
18842 ""))
18843 (if (not (featurep 'xemacs))
18844 (org-overlay-put ov 'display tx)
18845 (org-overlay-put ov 'invisible t)
18846 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18847 (push ov org-clock-overlays)))
18849 (defun org-remove-clock-overlays (&optional beg end noremove)
18850 "Remove the occur highlights from the buffer.
18851 BEG and END are ignored. If NOREMOVE is nil, remove this function
18852 from the `before-change-functions' in the current buffer."
18853 (interactive)
18854 (unless org-inhibit-highlight-removal
18855 (mapc 'org-delete-overlay org-clock-overlays)
18856 (setq org-clock-overlays nil)
18857 (unless noremove
18858 (remove-hook 'before-change-functions
18859 'org-remove-clock-overlays 'local))))
18861 (defun org-clock-out-if-current ()
18862 "Clock out if the current entry contains the running clock.
18863 This is used to stop the clock after a TODO entry is marked DONE,
18864 and is only done if the variable `org-clock-out-when-done' is not nil."
18865 (when (and org-clock-out-when-done
18866 (member state org-done-keywords)
18867 (equal (marker-buffer org-clock-marker) (current-buffer))
18868 (< (point) org-clock-marker)
18869 (> (save-excursion (outline-next-heading) (point))
18870 org-clock-marker))
18871 ;; Clock out, but don't accept a logging message for this.
18872 (let ((org-log-note-clock-out nil))
18873 (org-clock-out))))
18875 (add-hook 'org-after-todo-state-change-hook
18876 'org-clock-out-if-current)
18878 (defun org-check-running-clock ()
18879 "Check if the current buffer contains the running clock.
18880 If yes, offer to stop it and to save the buffer with the changes."
18881 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18882 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18883 (buffer-name))))
18884 (org-clock-out)
18885 (when (y-or-n-p "Save changed buffer?")
18886 (save-buffer))))
18888 (defun org-clock-report (&optional arg)
18889 "Create a table containing a report about clocked time.
18890 If the cursor is inside an existing clocktable block, then the table
18891 will be updated. If not, a new clocktable will be inserted.
18892 When called with a prefix argument, move to the first clock table in the
18893 buffer and update it."
18894 (interactive "P")
18895 (org-remove-clock-overlays)
18896 (when arg
18897 (org-find-dblock "clocktable")
18898 (org-show-entry))
18899 (if (org-in-clocktable-p)
18900 (goto-char (org-in-clocktable-p))
18901 (org-create-dblock (list :name "clocktable"
18902 :maxlevel 2 :scope 'file)))
18903 (org-update-dblock))
18905 (defun org-in-clocktable-p ()
18906 "Check if the cursor is in a clocktable."
18907 (let ((pos (point)) start)
18908 (save-excursion
18909 (end-of-line 1)
18910 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18911 (setq start (match-beginning 0))
18912 (re-search-forward "^#\\+END:.*" nil t)
18913 (>= (match-end 0) pos)
18914 start))))
18916 (defun org-clock-update-time-maybe ()
18917 "If this is a CLOCK line, update it and return t.
18918 Otherwise, return nil."
18919 (interactive)
18920 (save-excursion
18921 (beginning-of-line 1)
18922 (skip-chars-forward " \t")
18923 (when (looking-at org-clock-string)
18924 (let ((re (concat "[ \t]*" org-clock-string
18925 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18926 "\\([ \t]*=>.*\\)?"))
18927 ts te h m s)
18928 (if (not (looking-at re))
18930 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18931 (end-of-line 1)
18932 (setq ts (match-string 1)
18933 te (match-string 2))
18934 (setq s (- (time-to-seconds
18935 (apply 'encode-time (org-parse-time-string te)))
18936 (time-to-seconds
18937 (apply 'encode-time (org-parse-time-string ts))))
18938 h (floor (/ s 3600))
18939 s (- s (* 3600 h))
18940 m (floor (/ s 60))
18941 s (- s (* 60 s)))
18942 (insert " => " (format "%2d:%02d" h m))
18943 t)))))
18945 (defun org-clock-special-range (key &optional time as-strings)
18946 "Return two times bordering a special time range.
18947 Key is a symbol specifying the range and can be one of `today', `yesterday',
18948 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18949 A week starts Monday 0:00 and ends Sunday 24:00.
18950 The range is determined relative to TIME. TIME defaults to the current time.
18951 The return value is a cons cell with two internal times like the ones
18952 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18953 the returned times will be formatted strings."
18954 (let* ((tm (decode-time (or time (current-time))))
18955 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18956 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18957 (dow (nth 6 tm))
18958 s1 m1 h1 d1 month1 y1 diff ts te fm)
18959 (cond
18960 ((eq key 'today)
18961 (setq h 0 m 0 h1 24 m1 0))
18962 ((eq key 'yesterday)
18963 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18964 ((eq key 'thisweek)
18965 (setq diff (if (= dow 0) 6 (1- dow))
18966 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18967 ((eq key 'lastweek)
18968 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18969 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18970 ((eq key 'thismonth)
18971 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18972 ((eq key 'lastmonth)
18973 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18974 ((eq key 'thisyear)
18975 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18976 ((eq key 'lastyear)
18977 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18978 (t (error "No such time block %s" key)))
18979 (setq ts (encode-time s m h d month y)
18980 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18981 (or d1 d) (or month1 month) (or y1 y)))
18982 (setq fm (cdr org-time-stamp-formats))
18983 (if as-strings
18984 (cons (format-time-string fm ts) (format-time-string fm te))
18985 (cons ts te))))
18987 (defun org-dblock-write:clocktable (params)
18988 "Write the standard clocktable."
18989 (catch 'exit
18990 (let* ((hlchars '((1 . "*") (2 . "/")))
18991 (ins (make-marker))
18992 (total-time nil)
18993 (scope (plist-get params :scope))
18994 (tostring (plist-get params :tostring))
18995 (multifile (plist-get params :multifile))
18996 (header (plist-get params :header))
18997 (maxlevel (or (plist-get params :maxlevel) 3))
18998 (step (plist-get params :step))
18999 (emph (plist-get params :emphasize))
19000 (ts (plist-get params :tstart))
19001 (te (plist-get params :tend))
19002 (block (plist-get params :block))
19003 ipos time h m p level hlc hdl
19004 cc beg end pos tbl)
19005 (when step
19006 (org-clocktable-steps params)
19007 (throw 'exit nil))
19008 (when block
19009 (setq cc (org-clock-special-range block nil t)
19010 ts (car cc) te (cdr cc)))
19011 (if ts (setq ts (time-to-seconds
19012 (apply 'encode-time (org-parse-time-string ts)))))
19013 (if te (setq te (time-to-seconds
19014 (apply 'encode-time (org-parse-time-string te)))))
19015 (move-marker ins (point))
19016 (setq ipos (point))
19018 ;; Get the right scope
19019 (setq pos (point))
19020 (save-restriction
19021 (cond
19022 ((not scope))
19023 ((eq scope 'file) (widen))
19024 ((eq scope 'subtree) (org-narrow-to-subtree))
19025 ((eq scope 'tree)
19026 (while (org-up-heading-safe))
19027 (org-narrow-to-subtree))
19028 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19029 (symbol-name scope)))
19030 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19031 (catch 'exit
19032 (while (org-up-heading-safe)
19033 (looking-at outline-regexp)
19034 (if (<= (org-reduced-level (funcall outline-level)) level)
19035 (throw 'exit nil))))
19036 (org-narrow-to-subtree))
19037 ((or (listp scope) (eq scope 'agenda))
19038 (let* ((files (if (listp scope) scope (org-agenda-files)))
19039 (scope 'agenda)
19040 (p1 (copy-sequence params))
19041 file)
19042 (plist-put p1 :tostring t)
19043 (plist-put p1 :multifile t)
19044 (plist-put p1 :scope 'file)
19045 (org-prepare-agenda-buffers files)
19046 (while (setq file (pop files))
19047 (with-current-buffer (find-buffer-visiting file)
19048 (push (org-clocktable-add-file
19049 file (org-dblock-write:clocktable p1)) tbl)
19050 (setq total-time (+ (or total-time 0)
19051 org-clock-file-total-minutes)))))))
19052 (goto-char pos)
19054 (unless (eq scope 'agenda)
19055 (org-clock-sum ts te)
19056 (goto-char (point-min))
19057 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19058 (goto-char p)
19059 (when (setq time (get-text-property p :org-clock-minutes))
19060 (save-excursion
19061 (beginning-of-line 1)
19062 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19063 (setq level (org-reduced-level
19064 (- (match-end 1) (match-beginning 1))))
19065 (<= level maxlevel))
19066 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19067 hdl (match-string 2)
19068 h (/ time 60)
19069 m (- time (* 60 h)))
19070 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19071 (push (concat
19072 "| " (int-to-string level) "|" hlc hdl hlc " |"
19073 (make-string (1- level) ?|)
19074 hlc (format "%d:%02d" h m) hlc
19075 " |") tbl))))))
19076 (setq tbl (nreverse tbl))
19077 (if tostring
19078 (if tbl (mapconcat 'identity tbl "\n") nil)
19079 (goto-char ins)
19080 (insert-before-markers
19081 (or header
19082 (concat
19083 "Clock summary at ["
19084 (substring
19085 (format-time-string (cdr org-time-stamp-formats))
19086 1 -1)
19087 "]."
19088 (if block
19089 (format " Considered range is /%s/." block)
19091 "\n\n"))
19092 (if (eq scope 'agenda) "|File" "")
19093 "|L|Headline|Time|\n")
19094 (setq total-time (or total-time org-clock-file-total-minutes)
19095 h (/ total-time 60)
19096 m (- total-time (* 60 h)))
19097 (insert-before-markers
19098 "|-\n|"
19099 (if (eq scope 'agenda) "|" "")
19101 "*Total time*| "
19102 (format "*%d:%02d*" h m)
19103 "|\n|-\n")
19104 (setq tbl (delq nil tbl))
19105 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19106 (equal (substring (car tbl) 0 2) "|-"))
19107 (pop tbl))
19108 (insert-before-markers (mapconcat
19109 'identity (delq nil tbl)
19110 (if (eq scope 'agenda) "\n|-\n" "\n")))
19111 (backward-delete-char 1)
19112 (goto-char ipos)
19113 (skip-chars-forward "^|")
19114 (org-table-align))))))
19116 (defun org-clocktable-steps (params)
19117 (let* ((p1 (copy-sequence params))
19118 (ts (plist-get p1 :tstart))
19119 (te (plist-get p1 :tend))
19120 (step0 (plist-get p1 :step))
19121 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19122 (block (plist-get p1 :block))
19124 (when block
19125 (setq cc (org-clock-special-range block nil t)
19126 ts (car cc) te (cdr cc)))
19127 (if ts (setq ts (time-to-seconds
19128 (apply 'encode-time (org-parse-time-string ts)))))
19129 (if te (setq te (time-to-seconds
19130 (apply 'encode-time (org-parse-time-string te)))))
19131 (plist-put p1 :header "")
19132 (plist-put p1 :step nil)
19133 (plist-put p1 :block nil)
19134 (while (< ts te)
19135 (or (bolp) (insert "\n"))
19136 (plist-put p1 :tstart (format-time-string
19137 (car org-time-stamp-formats)
19138 (seconds-to-time ts)))
19139 (plist-put p1 :tend (format-time-string
19140 (car org-time-stamp-formats)
19141 (seconds-to-time (setq ts (+ ts step)))))
19142 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19143 (plist-get p1 :tstart) "\n")
19144 (org-dblock-write:clocktable p1)
19145 (re-search-forward "#\\+END:")
19146 (end-of-line 0))))
19149 (defun org-clocktable-add-file (file table)
19150 (if table
19151 (let ((lines (org-split-string table "\n"))
19152 (ff (file-name-nondirectory file)))
19153 (mapconcat 'identity
19154 (mapcar (lambda (x)
19155 (if (string-match org-table-dataline-regexp x)
19156 (concat "|" ff x)
19158 lines)
19159 "\n"))))
19161 ;; FIXME: I don't think anybody uses this, ask David
19162 (defun org-collect-clock-time-entries ()
19163 "Return an internal list with clocking information.
19164 This list has one entry for each CLOCK interval.
19165 FIXME: describe the elements."
19166 (interactive)
19167 (let ((re (concat "^[ \t]*" org-clock-string
19168 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19169 rtn beg end next cont level title total closedp leafp
19170 clockpos titlepos h m donep)
19171 (save-excursion
19172 (org-clock-sum)
19173 (goto-char (point-min))
19174 (while (re-search-forward re nil t)
19175 (setq clockpos (match-beginning 0)
19176 beg (match-string 1) end (match-string 2)
19177 cont (match-end 0))
19178 (setq beg (apply 'encode-time (org-parse-time-string beg))
19179 end (apply 'encode-time (org-parse-time-string end)))
19180 (org-back-to-heading t)
19181 (setq donep (org-entry-is-done-p))
19182 (setq titlepos (point)
19183 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19184 h (/ total 60) m (- total (* 60 h))
19185 total (cons h m))
19186 (looking-at "\\(\\*+\\) +\\(.*\\)")
19187 (setq level (- (match-end 1) (match-beginning 1))
19188 title (org-match-string-no-properties 2))
19189 (save-excursion (outline-next-heading) (setq next (point)))
19190 (setq closedp (re-search-forward org-closed-time-regexp next t))
19191 (goto-char next)
19192 (setq leafp (and (looking-at "^\\*+ ")
19193 (<= (- (match-end 0) (point)) level)))
19194 (push (list beg end clockpos closedp donep
19195 total title titlepos level leafp)
19196 rtn)
19197 (goto-char cont)))
19198 (nreverse rtn)))
19200 ;;;; Agenda, and Diary Integration
19202 ;;; Define the Org-agenda-mode
19204 (defvar org-agenda-mode-map (make-sparse-keymap)
19205 "Keymap for `org-agenda-mode'.")
19207 (defvar org-agenda-menu) ; defined later in this file.
19208 (defvar org-agenda-follow-mode nil)
19209 (defvar org-agenda-show-log nil)
19210 (defvar org-agenda-redo-command nil)
19211 (defvar org-agenda-mode-hook nil)
19212 (defvar org-agenda-type nil)
19213 (defvar org-agenda-force-single-file nil)
19215 (defun org-agenda-mode ()
19216 "Mode for time-sorted view on action items in Org-mode files.
19218 The following commands are available:
19220 \\{org-agenda-mode-map}"
19221 (interactive)
19222 (kill-all-local-variables)
19223 (setq org-agenda-undo-list nil
19224 org-agenda-pending-undo-list nil)
19225 (setq major-mode 'org-agenda-mode)
19226 ;; Keep global-font-lock-mode from turning on font-lock-mode
19227 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19228 (setq mode-name "Org-Agenda")
19229 (use-local-map org-agenda-mode-map)
19230 (easy-menu-add org-agenda-menu)
19231 (if org-startup-truncated (setq truncate-lines t))
19232 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19233 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19234 ;; Make sure properties are removed when copying text
19235 (when (boundp 'buffer-substring-filters)
19236 (org-set-local 'buffer-substring-filters
19237 (cons (lambda (x)
19238 (set-text-properties 0 (length x) nil x) x)
19239 buffer-substring-filters)))
19240 (unless org-agenda-keep-modes
19241 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19242 org-agenda-show-log nil))
19243 (easy-menu-change
19244 '("Agenda") "Agenda Files"
19245 (append
19246 (list
19247 (vector
19248 (if (get 'org-agenda-files 'org-restrict)
19249 "Restricted to single file"
19250 "Edit File List")
19251 '(org-edit-agenda-file-list)
19252 (not (get 'org-agenda-files 'org-restrict)))
19253 "--")
19254 (mapcar 'org-file-menu-entry (org-agenda-files))))
19255 (org-agenda-set-mode-name)
19256 (apply
19257 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19258 (list 'org-agenda-mode-hook)))
19260 (substitute-key-definition 'undo 'org-agenda-undo
19261 org-agenda-mode-map global-map)
19262 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19263 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19264 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19265 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19266 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19267 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19268 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19269 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19270 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19271 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19272 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19273 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19274 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19275 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19276 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19277 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19278 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19279 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19280 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19281 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19282 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19283 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19284 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19285 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19286 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19287 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19288 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19289 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19290 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19292 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19293 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19294 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19295 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19296 (while l (org-defkey org-agenda-mode-map
19297 (int-to-string (pop l)) 'digit-argument)))
19299 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19300 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19301 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19302 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19303 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19304 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19305 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19306 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19307 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19308 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19309 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19310 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19311 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19312 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19313 (org-defkey org-agenda-mode-map "n" 'next-line)
19314 (org-defkey org-agenda-mode-map "p" 'previous-line)
19315 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19316 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19317 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19318 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19319 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19320 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19321 (eval-after-load "calendar"
19322 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19323 'org-calendar-goto-agenda))
19324 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19325 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19326 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19327 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19328 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19329 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19330 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19331 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19332 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19333 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19334 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19335 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19336 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19337 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19338 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19339 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19340 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19341 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19342 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19343 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19344 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19345 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19347 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19348 "Local keymap for agenda entries from Org-mode.")
19350 (org-defkey org-agenda-keymap
19351 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19352 (org-defkey org-agenda-keymap
19353 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19354 (when org-agenda-mouse-1-follows-link
19355 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19356 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19357 '("Agenda"
19358 ("Agenda Files")
19359 "--"
19360 ["Show" org-agenda-show t]
19361 ["Go To (other window)" org-agenda-goto t]
19362 ["Go To (this window)" org-agenda-switch-to t]
19363 ["Follow Mode" org-agenda-follow-mode
19364 :style toggle :selected org-agenda-follow-mode :active t]
19365 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19366 "--"
19367 ["Cycle TODO" org-agenda-todo t]
19368 ["Archive subtree" org-agenda-archive t]
19369 ["Delete subtree" org-agenda-kill t]
19370 "--"
19371 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19372 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19373 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19374 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19375 "--"
19376 ("Tags and Properties"
19377 ["Show all Tags" org-agenda-show-tags t]
19378 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19379 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19380 "--"
19381 ["Column View" org-columns t])
19382 ("Date/Schedule"
19383 ["Schedule" org-agenda-schedule t]
19384 ["Set Deadline" org-agenda-deadline t]
19385 "--"
19386 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19387 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19388 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19389 ("Clock"
19390 ["Clock in" org-agenda-clock-in t]
19391 ["Clock out" org-agenda-clock-out t]
19392 ["Clock cancel" org-agenda-clock-cancel t]
19393 ["Goto running clock" org-clock-goto t])
19394 ("Priority"
19395 ["Set Priority" org-agenda-priority t]
19396 ["Increase Priority" org-agenda-priority-up t]
19397 ["Decrease Priority" org-agenda-priority-down t]
19398 ["Show Priority" org-agenda-show-priority t])
19399 ("Calendar/Diary"
19400 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19401 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19402 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19403 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19404 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19405 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19406 "--"
19407 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19408 "--"
19409 ("View"
19410 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19411 :style radio :selected (equal org-agenda-ndays 1)]
19412 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19413 :style radio :selected (equal org-agenda-ndays 7)]
19414 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19415 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19416 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19417 :style radio :selected (member org-agenda-ndays '(365 366))]
19418 "--"
19419 ["Show Logbook entries" org-agenda-log-mode
19420 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19421 ["Include Diary" org-agenda-toggle-diary
19422 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19423 ["Use Time Grid" org-agenda-toggle-time-grid
19424 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19425 ["Write view to file" org-write-agenda t]
19426 ["Rebuild buffer" org-agenda-redo t]
19427 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19428 "--"
19429 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19430 "--"
19431 ["Quit" org-agenda-quit t]
19432 ["Exit and Release Buffers" org-agenda-exit t]
19435 ;;; Agenda undo
19437 (defvar org-agenda-allow-remote-undo t
19438 "Non-nil means, allow remote undo from the agenda buffer.")
19439 (defvar org-agenda-undo-list nil
19440 "List of undoable operations in the agenda since last refresh.")
19441 (defvar org-agenda-undo-has-started-in nil
19442 "Buffers that have already seen `undo-start' in the current undo sequence.")
19443 (defvar org-agenda-pending-undo-list nil
19444 "In a series of undo commands, this is the list of remaning undo items.")
19446 (defmacro org-if-unprotected (&rest body)
19447 "Execute BODY if there is no `org-protected' text property at point."
19448 (declare (debug t))
19449 `(unless (get-text-property (point) 'org-protected)
19450 ,@body))
19452 (defmacro org-with-remote-undo (_buffer &rest _body)
19453 "Execute BODY while recording undo information in two buffers."
19454 (declare (indent 1) (debug t))
19455 `(let ((_cline (org-current-line))
19456 (_cmd this-command)
19457 (_buf1 (current-buffer))
19458 (_buf2 ,_buffer)
19459 (_undo1 buffer-undo-list)
19460 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19461 _c1 _c2)
19462 ,@_body
19463 (when org-agenda-allow-remote-undo
19464 (setq _c1 (org-verify-change-for-undo
19465 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19466 _c2 (org-verify-change-for-undo
19467 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19468 (when (or _c1 _c2)
19469 ;; make sure there are undo boundaries
19470 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19471 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19472 ;; remember which buffer to undo
19473 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19474 org-agenda-undo-list)))))
19476 (defun org-agenda-undo ()
19477 "Undo a remote editing step in the agenda.
19478 This undoes changes both in the agenda buffer and in the remote buffer
19479 that have been changed along."
19480 (interactive)
19481 (or org-agenda-allow-remote-undo
19482 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19483 (if (not (eq this-command last-command))
19484 (setq org-agenda-undo-has-started-in nil
19485 org-agenda-pending-undo-list org-agenda-undo-list))
19486 (if (not org-agenda-pending-undo-list)
19487 (error "No further undo information"))
19488 (let* ((entry (pop org-agenda-pending-undo-list))
19489 buf line cmd rembuf)
19490 (setq cmd (pop entry) line (pop entry))
19491 (setq rembuf (nth 2 entry))
19492 (org-with-remote-undo rembuf
19493 (while (bufferp (setq buf (pop entry)))
19494 (if (pop entry)
19495 (with-current-buffer buf
19496 (let ((last-undo-buffer buf)
19497 (inhibit-read-only t))
19498 (unless (memq buf org-agenda-undo-has-started-in)
19499 (push buf org-agenda-undo-has-started-in)
19500 (make-local-variable 'pending-undo-list)
19501 (undo-start))
19502 (while (and pending-undo-list
19503 (listp pending-undo-list)
19504 (not (car pending-undo-list)))
19505 (pop pending-undo-list))
19506 (undo-more 1))))))
19507 (goto-line line)
19508 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19510 (defun org-verify-change-for-undo (l1 l2)
19511 "Verify that a real change occurred between the undo lists L1 and L2."
19512 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19513 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19514 (not (eq l1 l2)))
19516 ;;; Agenda dispatch
19518 (defvar org-agenda-restrict nil)
19519 (defvar org-agenda-restrict-begin (make-marker))
19520 (defvar org-agenda-restrict-end (make-marker))
19521 (defvar org-agenda-last-dispatch-buffer nil)
19522 (defvar org-agenda-overriding-restriction nil)
19524 ;;;###autoload
19525 (defun org-agenda (arg &optional keys restriction)
19526 "Dispatch agenda commands to collect entries to the agenda buffer.
19527 Prompts for a command to execute. Any prefix arg will be passed
19528 on to the selected command. The default selections are:
19530 a Call `org-agenda-list' to display the agenda for current day or week.
19531 t Call `org-todo-list' to display the global todo list.
19532 T Call `org-todo-list' to display the global todo list, select only
19533 entries with a specific TODO keyword (the user gets a prompt).
19534 m Call `org-tags-view' to display headlines with tags matching
19535 a condition (the user is prompted for the condition).
19536 M Like `m', but select only TODO entries, no ordinary headlines.
19537 L Create a timeline for the current buffer.
19538 e Export views to associated files.
19540 More commands can be added by configuring the variable
19541 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19542 searches can be pre-defined in this way.
19544 If the current buffer is in Org-mode and visiting a file, you can also
19545 first press `<' once to indicate that the agenda should be temporarily
19546 \(until the next use of \\[org-agenda]) restricted to the current file.
19547 Pressing `<' twice means to restrict to the current subtree or region
19548 \(if active)."
19549 (interactive "P")
19550 (catch 'exit
19551 (let* ((prefix-descriptions nil)
19552 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19553 (org-agenda-custom-commands
19554 ;; normalize different versions
19555 (delq nil
19556 (mapcar
19557 (lambda (x)
19558 (cond ((stringp (cdr x))
19559 (push x prefix-descriptions)
19560 nil)
19561 ((stringp (nth 1 x)) x)
19562 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19563 (t (cons (car x) (cons "" (cdr x))))))
19564 org-agenda-custom-commands)))
19565 (buf (current-buffer))
19566 (bfn (buffer-file-name (buffer-base-buffer)))
19567 entry key type match lprops ans)
19568 ;; Turn off restriction unless there is an overriding one
19569 (unless org-agenda-overriding-restriction
19570 (put 'org-agenda-files 'org-restrict nil)
19571 (setq org-agenda-restrict nil)
19572 (move-marker org-agenda-restrict-begin nil)
19573 (move-marker org-agenda-restrict-end nil))
19574 ;; Delete old local properties
19575 (put 'org-agenda-redo-command 'org-lprops nil)
19576 ;; Remember where this call originated
19577 (setq org-agenda-last-dispatch-buffer (current-buffer))
19578 (unless keys
19579 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19580 keys (car ans)
19581 restriction (cdr ans)))
19582 ;; Estabish the restriction, if any
19583 (when (and (not org-agenda-overriding-restriction) restriction)
19584 (put 'org-agenda-files 'org-restrict (list bfn))
19585 (cond
19586 ((eq restriction 'region)
19587 (setq org-agenda-restrict t)
19588 (move-marker org-agenda-restrict-begin (region-beginning))
19589 (move-marker org-agenda-restrict-end (region-end)))
19590 ((eq restriction 'subtree)
19591 (save-excursion
19592 (setq org-agenda-restrict t)
19593 (org-back-to-heading t)
19594 (move-marker org-agenda-restrict-begin (point))
19595 (move-marker org-agenda-restrict-end
19596 (progn (org-end-of-subtree t)))))))
19598 (require 'calendar) ; FIXME: can we avoid this for some commands?
19599 ;; For example the todo list should not need it (but does...)
19600 (cond
19601 ((setq entry (assoc keys org-agenda-custom-commands))
19602 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19603 (progn
19604 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19605 (put 'org-agenda-redo-command 'org-lprops lprops)
19606 (cond
19607 ((eq type 'agenda)
19608 (org-let lprops '(org-agenda-list current-prefix-arg)))
19609 ((eq type 'alltodo)
19610 (org-let lprops '(org-todo-list current-prefix-arg)))
19611 ((eq type 'stuck)
19612 (org-let lprops '(org-agenda-list-stuck-projects
19613 current-prefix-arg)))
19614 ((eq type 'tags)
19615 (org-let lprops '(org-tags-view current-prefix-arg match)))
19616 ((eq type 'tags-todo)
19617 (org-let lprops '(org-tags-view '(4) match)))
19618 ((eq type 'todo)
19619 (org-let lprops '(org-todo-list match)))
19620 ((eq type 'tags-tree)
19621 (org-check-for-org-mode)
19622 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19623 ((eq type 'todo-tree)
19624 (org-check-for-org-mode)
19625 (org-let lprops
19626 '(org-occur (concat "^" outline-regexp "[ \t]*"
19627 (regexp-quote match) "\\>"))))
19628 ((eq type 'occur-tree)
19629 (org-check-for-org-mode)
19630 (org-let lprops '(org-occur match)))
19631 ((functionp type)
19632 (org-let lprops '(funcall type match)))
19633 ((fboundp type)
19634 (org-let lprops '(funcall type match)))
19635 (t (error "Invalid custom agenda command type %s" type))))
19636 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19637 ((equal keys "C")
19638 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19639 (customize-variable 'org-agenda-custom-commands))
19640 ((equal keys "a") (call-interactively 'org-agenda-list))
19641 ((equal keys "t") (call-interactively 'org-todo-list))
19642 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19643 ((equal keys "m") (call-interactively 'org-tags-view))
19644 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19645 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19646 ((equal keys "L")
19647 (unless (org-mode-p)
19648 (error "This is not an Org-mode file"))
19649 (unless restriction
19650 (put 'org-agenda-files 'org-restrict (list bfn))
19651 (org-call-with-arg 'org-timeline arg)))
19652 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19653 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19654 ((equal keys "!") (customize-variable 'org-stuck-projects))
19655 (t (error "Invalid agenda key"))))))
19657 (defun org-agenda-normalize-custom-commands (cmds)
19658 (delq nil
19659 (mapcar
19660 (lambda (x)
19661 (cond ((stringp (cdr x)) nil)
19662 ((stringp (nth 1 x)) x)
19663 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19664 (t (cons (car x) (cons "" (cdr x))))))
19665 cmds)))
19667 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19668 "The user interface for selecting an agenda command."
19669 (catch 'exit
19670 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19671 (restrict-ok (and bfn (org-mode-p)))
19672 (region-p (org-region-active-p))
19673 (custom org-agenda-custom-commands)
19674 (selstring "")
19675 restriction second-time
19676 c entry key type match prefixes rmheader header-end custom1 desc)
19677 (save-window-excursion
19678 (delete-other-windows)
19679 (org-switch-to-buffer-other-window " *Agenda Commands*")
19680 (erase-buffer)
19681 (insert (eval-when-compile
19682 (let ((header
19684 Press key for an agenda command: < Buffer,subtree/region restriction
19685 -------------------------------- > Remove restriction
19686 a Agenda for current week or day e Export agenda views
19687 t List of all TODO entries T Entries with special TODO kwd
19688 m Match a TAGS query M Like m, but only TODO entries
19689 L Timeline for current buffer # List stuck projects (!=configure)
19690 / Multi-occur C Configure custom agenda commands
19692 (start 0))
19693 (while (string-match
19694 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19695 header start)
19696 (setq start (match-end 0))
19697 (add-text-properties (match-beginning 2) (match-end 2)
19698 '(face bold) header))
19699 header)))
19700 (setq header-end (move-marker (make-marker) (point)))
19701 (while t
19702 (setq custom1 custom)
19703 (when (eq rmheader t)
19704 (goto-line 1)
19705 (re-search-forward ":" nil t)
19706 (delete-region (match-end 0) (point-at-eol))
19707 (forward-char 1)
19708 (looking-at "-+")
19709 (delete-region (match-end 0) (point-at-eol))
19710 (move-marker header-end (match-end 0)))
19711 (goto-char header-end)
19712 (delete-region (point) (point-max))
19713 (while (setq entry (pop custom1))
19714 (setq key (car entry) desc (nth 1 entry)
19715 type (nth 2 entry) match (nth 3 entry))
19716 (if (> (length key) 1)
19717 (add-to-list 'prefixes (string-to-char key))
19718 (insert
19719 (format
19720 "\n%-4s%-14s: %s"
19721 (org-add-props (copy-sequence key)
19722 '(face bold))
19723 (cond
19724 ((string-match "\\S-" desc) desc)
19725 ((eq type 'agenda) "Agenda for current week or day")
19726 ((eq type 'alltodo) "List of all TODO entries")
19727 ((eq type 'stuck) "List of stuck projects")
19728 ((eq type 'todo) "TODO keyword")
19729 ((eq type 'tags) "Tags query")
19730 ((eq type 'tags-todo) "Tags (TODO)")
19731 ((eq type 'tags-tree) "Tags tree")
19732 ((eq type 'todo-tree) "TODO kwd tree")
19733 ((eq type 'occur-tree) "Occur tree")
19734 ((functionp type) (if (symbolp type)
19735 (symbol-name type)
19736 "Lambda expression"))
19737 (t "???"))
19738 (cond
19739 ((stringp match)
19740 (org-add-props match nil 'face 'org-warning))
19741 (match
19742 (format "set of %d commands" (length match)))
19743 (t ""))))))
19744 (when prefixes
19745 (mapc (lambda (x)
19746 (insert
19747 (format "\n%s %s"
19748 (org-add-props (char-to-string x)
19749 nil 'face 'bold)
19750 (or (cdr (assoc (concat selstring (char-to-string x))
19751 prefix-descriptions))
19752 "Prefix key"))))
19753 prefixes))
19754 (goto-char (point-min))
19755 (when (fboundp 'fit-window-to-buffer)
19756 (if second-time
19757 (if (not (pos-visible-in-window-p (point-max)))
19758 (fit-window-to-buffer))
19759 (setq second-time t)
19760 (fit-window-to-buffer)))
19761 (message "Press key for agenda command%s:"
19762 (if (or restrict-ok org-agenda-overriding-restriction)
19763 (if org-agenda-overriding-restriction
19764 " (restriction lock active)"
19765 (if restriction
19766 (format " (restricted to %s)" restriction)
19767 " (unrestricted)"))
19768 ""))
19769 (setq c (read-char-exclusive))
19770 (message "")
19771 (cond
19772 ((assoc (char-to-string c) custom)
19773 (setq selstring (concat selstring (char-to-string c)))
19774 (throw 'exit (cons selstring restriction)))
19775 ((memq c prefixes)
19776 (setq selstring (concat selstring (char-to-string c))
19777 prefixes nil
19778 rmheader (or rmheader t)
19779 custom (delq nil (mapcar
19780 (lambda (x)
19781 (if (or (= (length (car x)) 1)
19782 (/= (string-to-char (car x)) c))
19784 (cons (substring (car x) 1) (cdr x))))
19785 custom))))
19786 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19787 (message "Restriction is only possible in Org-mode buffers")
19788 (ding) (sit-for 1))
19789 ((eq c ?1)
19790 (org-agenda-remove-restriction-lock 'noupdate)
19791 (setq restriction 'buffer))
19792 ((eq c ?0)
19793 (org-agenda-remove-restriction-lock 'noupdate)
19794 (setq restriction (if region-p 'region 'subtree)))
19795 ((eq c ?<)
19796 (org-agenda-remove-restriction-lock 'noupdate)
19797 (setq restriction
19798 (cond
19799 ((eq restriction 'buffer)
19800 (if region-p 'region 'subtree))
19801 ((memq restriction '(subtree region))
19802 nil)
19803 (t 'buffer))))
19804 ((eq c ?>)
19805 (org-agenda-remove-restriction-lock 'noupdate)
19806 (setq restriction nil))
19807 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19808 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19809 ((and (> (length selstring) 0) (eq c ?\d))
19810 (delete-window)
19811 (org-agenda-get-restriction-and-command prefix-descriptions))
19813 ((equal c ?q) (error "Abort"))
19814 (t (error "Invalid key %c" c))))))))
19816 (defun org-run-agenda-series (name series)
19817 (org-prepare-agenda name)
19818 (let* ((org-agenda-multi t)
19819 (redo (list 'org-run-agenda-series name (list 'quote series)))
19820 (cmds (car series))
19821 (gprops (nth 1 series))
19822 match ;; The byte compiler incorrectly complains about this. Keep it!
19823 cmd type lprops)
19824 (while (setq cmd (pop cmds))
19825 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19826 (cond
19827 ((eq type 'agenda)
19828 (org-let2 gprops lprops
19829 '(call-interactively 'org-agenda-list)))
19830 ((eq type 'alltodo)
19831 (org-let2 gprops lprops
19832 '(call-interactively 'org-todo-list)))
19833 ((eq type 'stuck)
19834 (org-let2 gprops lprops
19835 '(call-interactively 'org-agenda-list-stuck-projects)))
19836 ((eq type 'tags)
19837 (org-let2 gprops lprops
19838 '(org-tags-view current-prefix-arg match)))
19839 ((eq type 'tags-todo)
19840 (org-let2 gprops lprops
19841 '(org-tags-view '(4) match)))
19842 ((eq type 'todo)
19843 (org-let2 gprops lprops
19844 '(org-todo-list match)))
19845 ((fboundp type)
19846 (org-let2 gprops lprops
19847 '(funcall type match)))
19848 (t (error "Invalid type in command series"))))
19849 (widen)
19850 (setq org-agenda-redo-command redo)
19851 (goto-char (point-min)))
19852 (org-finalize-agenda))
19854 ;;;###autoload
19855 (defmacro org-batch-agenda (cmd-key &rest parameters)
19856 "Run an agenda command in batch mode and send the result to STDOUT.
19857 If CMD-KEY is a string of length 1, it is used as a key in
19858 `org-agenda-custom-commands' and triggers this command. If it is a
19859 longer string it is used as a tags/todo match string.
19860 Paramters are alternating variable names and values that will be bound
19861 before running the agenda command."
19862 (let (pars)
19863 (while parameters
19864 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19865 (if (> (length cmd-key) 2)
19866 (eval (list 'let (nreverse pars)
19867 (list 'org-tags-view nil cmd-key)))
19868 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19869 (set-buffer org-agenda-buffer-name)
19870 (princ (org-encode-for-stdout (buffer-string)))))
19872 (defun org-encode-for-stdout (string)
19873 (if (fboundp 'encode-coding-string)
19874 (encode-coding-string string buffer-file-coding-system)
19875 string))
19877 (defvar org-agenda-info nil)
19879 ;;;###autoload
19880 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19881 "Run an agenda command in batch mode and send the result to STDOUT.
19882 If CMD-KEY is a string of length 1, it is used as a key in
19883 `org-agenda-custom-commands' and triggers this command. If it is a
19884 longer string it is used as a tags/todo match string.
19885 Paramters are alternating variable names and values that will be bound
19886 before running the agenda command.
19888 The output gives a line for each selected agenda item. Each
19889 item is a list of comma-separated values, like this:
19891 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19893 category The category of the item
19894 head The headline, without TODO kwd, TAGS and PRIORITY
19895 type The type of the agenda entry, can be
19896 todo selected in TODO match
19897 tagsmatch selected in tags match
19898 diary imported from diary
19899 deadline a deadline on given date
19900 scheduled scheduled on given date
19901 timestamp entry has timestamp on given date
19902 closed entry was closed on given date
19903 upcoming-deadline warning about deadline
19904 past-scheduled forwarded scheduled item
19905 block entry has date block including g. date
19906 todo The todo keyword, if any
19907 tags All tags including inherited ones, separated by colons
19908 date The relevant date, like 2007-2-14
19909 time The time, like 15:00-16:50
19910 extra Sting with extra planning info
19911 priority-l The priority letter if any was given
19912 priority-n The computed numerical priority
19913 agenda-day The day in the agenda where this is listed"
19915 (let (pars)
19916 (while parameters
19917 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19918 (push (list 'org-agenda-remove-tags t) pars)
19919 (if (> (length cmd-key) 2)
19920 (eval (list 'let (nreverse pars)
19921 (list 'org-tags-view nil cmd-key)))
19922 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19923 (set-buffer org-agenda-buffer-name)
19924 (let* ((lines (org-split-string (buffer-string) "\n"))
19925 line)
19926 (while (setq line (pop lines))
19927 (catch 'next
19928 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19929 (setq org-agenda-info
19930 (org-fix-agenda-info (text-properties-at 0 line)))
19931 (princ
19932 (org-encode-for-stdout
19933 (mapconcat 'org-agenda-export-csv-mapper
19934 '(org-category txt type todo tags date time-of-day extra
19935 priority-letter priority agenda-day)
19936 ",")))
19937 (princ "\n"))))))
19939 (defun org-fix-agenda-info (props)
19940 "Make sure all properties on an agenda item have a canonical form,
19941 so the export commands can easily use it."
19942 (let (tmp re)
19943 (when (setq tmp (plist-get props 'tags))
19944 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19945 (when (setq tmp (plist-get props 'date))
19946 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19947 (let ((calendar-date-display-form '(year "-" month "-" day)))
19948 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19950 (setq tmp (calendar-date-string tmp)))
19951 (setq props (plist-put props 'date tmp)))
19952 (when (setq tmp (plist-get props 'day))
19953 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19954 (let ((calendar-date-display-form '(year "-" month "-" day)))
19955 (setq tmp (calendar-date-string tmp)))
19956 (setq props (plist-put props 'day tmp))
19957 (setq props (plist-put props 'agenda-day tmp)))
19958 (when (setq tmp (plist-get props 'txt))
19959 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19960 (plist-put props 'priority-letter (match-string 1 tmp))
19961 (setq tmp (replace-match "" t t tmp)))
19962 (when (and (setq re (plist-get props 'org-todo-regexp))
19963 (setq re (concat "\\`\\.*" re " ?"))
19964 (string-match re tmp))
19965 (plist-put props 'todo (match-string 1 tmp))
19966 (setq tmp (replace-match "" t t tmp)))
19967 (plist-put props 'txt tmp)))
19968 props)
19970 (defun org-agenda-export-csv-mapper (prop)
19971 (let ((res (plist-get org-agenda-info prop)))
19972 (setq res
19973 (cond
19974 ((not res) "")
19975 ((stringp res) res)
19976 (t (prin1-to-string res))))
19977 (while (string-match "," res)
19978 (setq res (replace-match ";" t t res)))
19979 (org-trim res)))
19982 ;;;###autoload
19983 (defun org-store-agenda-views (&rest parameters)
19984 (interactive)
19985 (eval (list 'org-batch-store-agenda-views)))
19987 ;; FIXME, why is this a macro?????
19988 ;;;###autoload
19989 (defmacro org-batch-store-agenda-views (&rest parameters)
19990 "Run all custom agenda commands that have a file argument."
19991 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19992 (pop-up-frames nil)
19993 (dir default-directory)
19994 pars cmd thiscmdkey files opts)
19995 (while parameters
19996 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19997 (setq pars (reverse pars))
19998 (save-window-excursion
19999 (while cmds
20000 (setq cmd (pop cmds)
20001 thiscmdkey (car cmd)
20002 opts (nth 4 cmd)
20003 files (nth 5 cmd))
20004 (if (stringp files) (setq files (list files)))
20005 (when files
20006 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20007 (list 'org-agenda nil thiscmdkey)))
20008 (set-buffer org-agenda-buffer-name)
20009 (while files
20010 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20011 (list 'org-write-agenda
20012 (expand-file-name (pop files) dir) t))))
20013 (and (get-buffer org-agenda-buffer-name)
20014 (kill-buffer org-agenda-buffer-name)))))))
20016 (defun org-write-agenda (file &optional nosettings)
20017 "Write the current buffer (an agenda view) as a file.
20018 Depending on the extension of the file name, plain text (.txt),
20019 HTML (.html or .htm) or Postscript (.ps) is produced.
20020 If NOSETTINGS is given, do not scope the settings of
20021 `org-agenda-exporter-settings' into the export commands. This is used when
20022 the settings have already been scoped and we do not wish to overrule other,
20023 higher priority settings."
20024 (interactive "FWrite agenda to file: ")
20025 (if (not (file-writable-p file))
20026 (error "Cannot write agenda to file %s" file))
20027 (cond
20028 ((string-match "\\.html?\\'" file) (require 'htmlize))
20029 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20030 (org-let (if nosettings nil org-agenda-exporter-settings)
20031 '(save-excursion
20032 (save-window-excursion
20033 (cond
20034 ((string-match "\\.html?\\'" file)
20035 (set-buffer (htmlize-buffer (current-buffer)))
20037 (when (and org-agenda-export-html-style
20038 (string-match "<style>" org-agenda-export-html-style))
20039 ;; replace <style> section with org-agenda-export-html-style
20040 (goto-char (point-min))
20041 (kill-region (- (search-forward "<style") 6)
20042 (search-forward "</style>"))
20043 (insert org-agenda-export-html-style))
20044 (write-file file)
20045 (kill-buffer (current-buffer))
20046 (message "HTML written to %s" file))
20047 ((string-match "\\.ps\\'" file)
20048 (ps-print-buffer-with-faces file)
20049 (message "Postscript written to %s" file))
20051 (let ((bs (buffer-string)))
20052 (find-file file)
20053 (insert bs)
20054 (save-buffer 0)
20055 (kill-buffer (current-buffer))
20056 (message "Plain text written to %s" file))))))
20057 (set-buffer org-agenda-buffer-name)))
20059 (defmacro org-no-read-only (&rest body)
20060 "Inhibit read-only for BODY."
20061 `(let ((inhibit-read-only t)) ,@body))
20063 (defun org-check-for-org-mode ()
20064 "Make sure current buffer is in org-mode. Error if not."
20065 (or (org-mode-p)
20066 (error "Cannot execute org-mode agenda command on buffer in %s."
20067 major-mode)))
20069 (defun org-fit-agenda-window ()
20070 "Fit the window to the buffer size."
20071 (and (memq org-agenda-window-setup '(reorganize-frame))
20072 (fboundp 'fit-window-to-buffer)
20073 (fit-window-to-buffer
20075 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20076 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20078 ;;; Agenda file list
20080 (defun org-agenda-files (&optional unrestricted)
20081 "Get the list of agenda files.
20082 Optional UNRESTRICTED means return the full list even if a restriction
20083 is currently in place."
20084 (let ((files
20085 (cond
20086 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20087 ((stringp org-agenda-files) (org-read-agenda-file-list))
20088 ((listp org-agenda-files) org-agenda-files)
20089 (t (error "Invalid value of `org-agenda-files'")))))
20090 (setq files (apply 'append
20091 (mapcar (lambda (f)
20092 (if (file-directory-p f)
20093 (directory-files f t
20094 org-agenda-file-regexp)
20095 (list f)))
20096 files)))
20097 (if org-agenda-skip-unavailable-files
20098 (delq nil
20099 (mapcar (function
20100 (lambda (file)
20101 (and (file-readable-p file) file)))
20102 files))
20103 files))) ; `org-check-agenda-file' will remove them from the list
20105 (defun org-edit-agenda-file-list ()
20106 "Edit the list of agenda files.
20107 Depending on setup, this either uses customize to edit the variable
20108 `org-agenda-files', or it visits the file that is holding the list. In the
20109 latter case, the buffer is set up in a way that saving it automatically kills
20110 the buffer and restores the previous window configuration."
20111 (interactive)
20112 (if (stringp org-agenda-files)
20113 (let ((cw (current-window-configuration)))
20114 (find-file org-agenda-files)
20115 (org-set-local 'org-window-configuration cw)
20116 (org-add-hook 'after-save-hook
20117 (lambda ()
20118 (set-window-configuration
20119 (prog1 org-window-configuration
20120 (kill-buffer (current-buffer))))
20121 (org-install-agenda-files-menu)
20122 (message "New agenda file list installed"))
20123 nil 'local)
20124 (message "%s" (substitute-command-keys
20125 "Edit list and finish with \\[save-buffer]")))
20126 (customize-variable 'org-agenda-files)))
20128 (defun org-store-new-agenda-file-list (list)
20129 "Set new value for the agenda file list and save it correcly."
20130 (if (stringp org-agenda-files)
20131 (let ((f org-agenda-files) b)
20132 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20133 (with-temp-file f
20134 (insert (mapconcat 'identity list "\n") "\n")))
20135 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20136 (setq org-agenda-files list)
20137 (customize-save-variable 'org-agenda-files org-agenda-files))))
20139 (defun org-read-agenda-file-list ()
20140 "Read the list of agenda files from a file."
20141 (when (stringp org-agenda-files)
20142 (with-temp-buffer
20143 (insert-file-contents org-agenda-files)
20144 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20147 ;;;###autoload
20148 (defun org-cycle-agenda-files ()
20149 "Cycle through the files in `org-agenda-files'.
20150 If the current buffer visits an agenda file, find the next one in the list.
20151 If the current buffer does not, find the first agenda file."
20152 (interactive)
20153 (let* ((fs (org-agenda-files t))
20154 (files (append fs (list (car fs))))
20155 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20156 file)
20157 (unless files (error "No agenda files"))
20158 (catch 'exit
20159 (while (setq file (pop files))
20160 (if (equal (file-truename file) tcf)
20161 (when (car files)
20162 (find-file (car files))
20163 (throw 'exit t))))
20164 (find-file (car fs)))
20165 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20167 (defun org-agenda-file-to-front (&optional to-end)
20168 "Move/add the current file to the top of the agenda file list.
20169 If the file is not present in the list, it is added to the front. If it is
20170 present, it is moved there. With optional argument TO-END, add/move to the
20171 end of the list."
20172 (interactive "P")
20173 (let ((org-agenda-skip-unavailable-files nil)
20174 (file-alist (mapcar (lambda (x)
20175 (cons (file-truename x) x))
20176 (org-agenda-files t)))
20177 (ctf (file-truename buffer-file-name))
20178 x had)
20179 (setq x (assoc ctf file-alist) had x)
20181 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20182 (if to-end
20183 (setq file-alist (append (delq x file-alist) (list x)))
20184 (setq file-alist (cons x (delq x file-alist))))
20185 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20186 (org-install-agenda-files-menu)
20187 (message "File %s to %s of agenda file list"
20188 (if had "moved" "added") (if to-end "end" "front"))))
20190 (defun org-remove-file (&optional file)
20191 "Remove current file from the list of files in variable `org-agenda-files'.
20192 These are the files which are being checked for agenda entries.
20193 Optional argument FILE means, use this file instead of the current."
20194 (interactive)
20195 (let* ((org-agenda-skip-unavailable-files nil)
20196 (file (or file buffer-file-name))
20197 (true-file (file-truename file))
20198 (afile (abbreviate-file-name file))
20199 (files (delq nil (mapcar
20200 (lambda (x)
20201 (if (equal true-file
20202 (file-truename x))
20203 nil x))
20204 (org-agenda-files t)))))
20205 (if (not (= (length files) (length (org-agenda-files t))))
20206 (progn
20207 (org-store-new-agenda-file-list files)
20208 (org-install-agenda-files-menu)
20209 (message "Removed file: %s" afile))
20210 (message "File was not in list: %s (not removed)" afile))))
20212 (defun org-file-menu-entry (file)
20213 (vector file (list 'find-file file) t))
20215 (defun org-check-agenda-file (file)
20216 "Make sure FILE exists. If not, ask user what to do."
20217 (when (not (file-exists-p file))
20218 (message "non-existent file %s. [R]emove from list or [A]bort?"
20219 (abbreviate-file-name file))
20220 (let ((r (downcase (read-char-exclusive))))
20221 (cond
20222 ((equal r ?r)
20223 (org-remove-file file)
20224 (throw 'nextfile t))
20225 (t (error "Abort"))))))
20227 ;;; Agenda prepare and finalize
20229 (defvar org-agenda-multi nil) ; dynammically scoped
20230 (defvar org-agenda-buffer-name "*Org Agenda*")
20231 (defvar org-pre-agenda-window-conf nil)
20232 (defvar org-agenda-name nil)
20233 (defun org-prepare-agenda (&optional name)
20234 (setq org-todo-keywords-for-agenda nil)
20235 (setq org-done-keywords-for-agenda nil)
20236 (if org-agenda-multi
20237 (progn
20238 (setq buffer-read-only nil)
20239 (goto-char (point-max))
20240 (unless (or (bobp) org-agenda-compact-blocks)
20241 (insert "\n" (make-string (window-width) ?=) "\n"))
20242 (narrow-to-region (point) (point-max)))
20243 (org-agenda-reset-markers)
20244 (org-prepare-agenda-buffers (org-agenda-files))
20245 (setq org-todo-keywords-for-agenda
20246 (org-uniquify org-todo-keywords-for-agenda))
20247 (setq org-done-keywords-for-agenda
20248 (org-uniquify org-done-keywords-for-agenda))
20249 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20250 (awin (get-buffer-window abuf)))
20251 (cond
20252 ((equal (current-buffer) abuf) nil)
20253 (awin (select-window awin))
20254 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20255 ((equal org-agenda-window-setup 'current-window)
20256 (switch-to-buffer abuf))
20257 ((equal org-agenda-window-setup 'other-window)
20258 (org-switch-to-buffer-other-window abuf))
20259 ((equal org-agenda-window-setup 'other-frame)
20260 (switch-to-buffer-other-frame abuf))
20261 ((equal org-agenda-window-setup 'reorganize-frame)
20262 (delete-other-windows)
20263 (org-switch-to-buffer-other-window abuf))))
20264 (setq buffer-read-only nil)
20265 (erase-buffer)
20266 (org-agenda-mode)
20267 (and name (not org-agenda-name)
20268 (org-set-local 'org-agenda-name name)))
20269 (setq buffer-read-only nil))
20271 (defun org-finalize-agenda ()
20272 "Finishing touch for the agenda buffer, called just before displaying it."
20273 (unless org-agenda-multi
20274 (save-excursion
20275 (let ((inhibit-read-only t))
20276 (goto-char (point-min))
20277 (while (org-activate-bracket-links (point-max))
20278 (add-text-properties (match-beginning 0) (match-end 0)
20279 '(face org-link)))
20280 (org-agenda-align-tags)
20281 (unless org-agenda-with-colors
20282 (remove-text-properties (point-min) (point-max) '(face nil))))
20283 (if (and (boundp 'org-overriding-columns-format)
20284 org-overriding-columns-format)
20285 (org-set-local 'org-overriding-columns-format
20286 org-overriding-columns-format))
20287 (if (and (boundp 'org-agenda-view-columns-initially)
20288 org-agenda-view-columns-initially)
20289 (org-agenda-columns))
20290 (when org-agenda-fontify-priorities
20291 (org-fontify-priorities))
20292 (run-hooks 'org-finalize-agenda-hook)
20293 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20296 (defun org-fontify-priorities ()
20297 "Make highest priority lines bold, and lowest italic."
20298 (interactive)
20299 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20300 (org-delete-overlay o)))
20301 (org-overlays-in (point-min) (point-max)))
20302 (save-excursion
20303 (let ((inhibit-read-only t)
20304 b e p ov h l)
20305 (goto-char (point-min))
20306 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20307 (setq h (or (get-char-property (point) 'org-highest-priority)
20308 org-highest-priority)
20309 l (or (get-char-property (point) 'org-lowest-priority)
20310 org-lowest-priority)
20311 p (string-to-char (match-string 1))
20312 b (match-beginning 0) e (point-at-eol)
20313 ov (org-make-overlay b e))
20314 (org-overlay-put
20315 ov 'face
20316 (cond ((listp org-agenda-fontify-priorities)
20317 (cdr (assoc p org-agenda-fontify-priorities)))
20318 ((equal p l) 'italic)
20319 ((equal p h) 'bold)))
20320 (org-overlay-put ov 'org-type 'org-priority)))))
20322 (defun org-prepare-agenda-buffers (files)
20323 "Create buffers for all agenda files, protect archived trees and comments."
20324 (interactive)
20325 (let ((pa '(:org-archived t))
20326 (pc '(:org-comment t))
20327 (pall '(:org-archived t :org-comment t))
20328 (inhibit-read-only t)
20329 (rea (concat ":" org-archive-tag ":"))
20330 bmp file re)
20331 (save-excursion
20332 (save-restriction
20333 (while (setq file (pop files))
20334 (if (bufferp file)
20335 (set-buffer file)
20336 (org-check-agenda-file file)
20337 (set-buffer (org-get-agenda-file-buffer file)))
20338 (widen)
20339 (setq bmp (buffer-modified-p))
20340 (org-refresh-category-properties)
20341 (setq org-todo-keywords-for-agenda
20342 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20343 (setq org-done-keywords-for-agenda
20344 (append org-done-keywords-for-agenda org-done-keywords))
20345 (save-excursion
20346 (remove-text-properties (point-min) (point-max) pall)
20347 (when org-agenda-skip-archived-trees
20348 (goto-char (point-min))
20349 (while (re-search-forward rea nil t)
20350 (if (org-on-heading-p t)
20351 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20352 (goto-char (point-min))
20353 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20354 (while (re-search-forward re nil t)
20355 (add-text-properties
20356 (match-beginning 0) (org-end-of-subtree t) pc)))
20357 (set-buffer-modified-p bmp))))))
20359 (defvar org-agenda-skip-function nil
20360 "Function to be called at each match during agenda construction.
20361 If this function returns nil, the current match should not be skipped.
20362 Otherwise, the function must return a position from where the search
20363 should be continued.
20364 This may also be a Lisp form, it will be evaluated.
20365 Never set this variable using `setq' or so, because then it will apply
20366 to all future agenda commands. Instead, bind it with `let' to scope
20367 it dynamically into the agenda-constructing command. A good way to set
20368 it is through options in org-agenda-custom-commands.")
20370 (defun org-agenda-skip ()
20371 "Throw to `:skip' in places that should be skipped.
20372 Also moves point to the end of the skipped region, so that search can
20373 continue from there."
20374 (let ((p (point-at-bol)) to fp)
20375 (and org-agenda-skip-archived-trees
20376 (get-text-property p :org-archived)
20377 (org-end-of-subtree t)
20378 (throw :skip t))
20379 (and (get-text-property p :org-comment)
20380 (org-end-of-subtree t)
20381 (throw :skip t))
20382 (if (equal (char-after p) ?#) (throw :skip t))
20383 (when (and (or (setq fp (functionp org-agenda-skip-function))
20384 (consp org-agenda-skip-function))
20385 (setq to (save-excursion
20386 (save-match-data
20387 (if fp
20388 (funcall org-agenda-skip-function)
20389 (eval org-agenda-skip-function))))))
20390 (goto-char to)
20391 (throw :skip t))))
20393 (defvar org-agenda-markers nil
20394 "List of all currently active markers created by `org-agenda'.")
20395 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20396 "Creation time of the last agenda marker.")
20398 (defun org-agenda-new-marker (&optional pos)
20399 "Return a new agenda marker.
20400 Org-mode keeps a list of these markers and resets them when they are
20401 no longer in use."
20402 (let ((m (copy-marker (or pos (point)))))
20403 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20404 (push m org-agenda-markers)
20407 (defun org-agenda-reset-markers ()
20408 "Reset markers created by `org-agenda'."
20409 (while org-agenda-markers
20410 (move-marker (pop org-agenda-markers) nil)))
20412 (defun org-get-agenda-file-buffer (file)
20413 "Get a buffer visiting FILE. If the buffer needs to be created, add
20414 it to the list of buffers which might be released later."
20415 (let ((buf (org-find-base-buffer-visiting file)))
20416 (if buf
20417 buf ; just return it
20418 ;; Make a new buffer and remember it
20419 (setq buf (find-file-noselect file))
20420 (if buf (push buf org-agenda-new-buffers))
20421 buf)))
20423 (defun org-release-buffers (blist)
20424 "Release all buffers in list, asking the user for confirmation when needed.
20425 When a buffer is unmodified, it is just killed. When modified, it is saved
20426 \(if the user agrees) and then killed."
20427 (let (buf file)
20428 (while (setq buf (pop blist))
20429 (setq file (buffer-file-name buf))
20430 (when (and (buffer-modified-p buf)
20431 file
20432 (y-or-n-p (format "Save file %s? " file)))
20433 (with-current-buffer buf (save-buffer)))
20434 (kill-buffer buf))))
20436 (defun org-get-category (&optional pos)
20437 "Get the category applying to position POS."
20438 (get-text-property (or pos (point)) 'org-category))
20440 ;;; Agenda timeline
20442 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20444 (defun org-timeline (&optional include-all)
20445 "Show a time-sorted view of the entries in the current org file.
20446 Only entries with a time stamp of today or later will be listed. With
20447 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20448 under the current date.
20449 If the buffer contains an active region, only check the region for
20450 dates."
20451 (interactive "P")
20452 (require 'calendar)
20453 (org-compile-prefix-format 'timeline)
20454 (org-set-sorting-strategy 'timeline)
20455 (let* ((dopast t)
20456 (dotodo include-all)
20457 (doclosed org-agenda-show-log)
20458 (entry buffer-file-name)
20459 (date (calendar-current-date))
20460 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20461 (end (if (org-region-active-p) (region-end) (point-max)))
20462 (day-numbers (org-get-all-dates beg end 'no-ranges
20463 t doclosed ; always include today
20464 org-timeline-show-empty-dates))
20465 (org-deadline-warning-days 0)
20466 (org-agenda-only-exact-dates t)
20467 (today (time-to-days (current-time)))
20468 (past t)
20469 args
20470 s e rtn d emptyp)
20471 (setq org-agenda-redo-command
20472 (list 'progn
20473 (list 'org-switch-to-buffer-other-window (current-buffer))
20474 (list 'org-timeline (list 'quote include-all))))
20475 (if (not dopast)
20476 ;; Remove past dates from the list of dates.
20477 (setq day-numbers (delq nil (mapcar (lambda(x)
20478 (if (>= x today) x nil))
20479 day-numbers))))
20480 (org-prepare-agenda (concat "Timeline "
20481 (file-name-nondirectory buffer-file-name)))
20482 (if doclosed (push :closed args))
20483 (push :timestamp args)
20484 (push :deadline args)
20485 (push :scheduled args)
20486 (push :sexp args)
20487 (if dotodo (push :todo args))
20488 (while (setq d (pop day-numbers))
20489 (if (and (listp d) (eq (car d) :omitted))
20490 (progn
20491 (setq s (point))
20492 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20493 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20494 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20495 (if (and (>= d today)
20496 dopast
20497 past)
20498 (progn
20499 (setq past nil)
20500 (insert (make-string 79 ?-) "\n")))
20501 (setq date (calendar-gregorian-from-absolute d))
20502 (setq s (point))
20503 (setq rtn (and (not emptyp)
20504 (apply 'org-agenda-get-day-entries entry
20505 date args)))
20506 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20507 (progn
20508 (insert
20509 (if (stringp org-agenda-format-date)
20510 (format-time-string org-agenda-format-date
20511 (org-time-from-absolute date))
20512 (funcall org-agenda-format-date date))
20513 "\n")
20514 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20515 (put-text-property s (1- (point)) 'org-date-line t)
20516 (if (equal d today)
20517 (put-text-property s (1- (point)) 'org-today t))
20518 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20519 (put-text-property s (1- (point)) 'day d)))))
20520 (goto-char (point-min))
20521 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20522 (point-min)))
20523 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20524 (org-finalize-agenda)
20525 (setq buffer-read-only t)))
20527 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20528 "Return a list of all relevant day numbers from BEG to END buffer positions.
20529 If NO-RANGES is non-nil, include only the start and end dates of a range,
20530 not every single day in the range. If FORCE-TODAY is non-nil, make
20531 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20532 inactive time stamps (those in square brackets) are included.
20533 When EMPTY is non-nil, also include days without any entries."
20534 (let ((re (concat
20535 (if pre-re pre-re "")
20536 (if inactive org-ts-regexp-both org-ts-regexp)))
20537 dates dates1 date day day1 day2 ts1 ts2)
20538 (if force-today
20539 (setq dates (list (time-to-days (current-time)))))
20540 (save-excursion
20541 (goto-char beg)
20542 (while (re-search-forward re end t)
20543 (setq day (time-to-days (org-time-string-to-time
20544 (substring (match-string 1) 0 10))))
20545 (or (memq day dates) (push day dates)))
20546 (unless no-ranges
20547 (goto-char beg)
20548 (while (re-search-forward org-tr-regexp end t)
20549 (setq ts1 (substring (match-string 1) 0 10)
20550 ts2 (substring (match-string 2) 0 10)
20551 day1 (time-to-days (org-time-string-to-time ts1))
20552 day2 (time-to-days (org-time-string-to-time ts2)))
20553 (while (< (setq day1 (1+ day1)) day2)
20554 (or (memq day1 dates) (push day1 dates)))))
20555 (setq dates (sort dates '<))
20556 (when empty
20557 (while (setq day (pop dates))
20558 (setq day2 (car dates))
20559 (push day dates1)
20560 (when (and day2 empty)
20561 (if (or (eq empty t)
20562 (and (numberp empty) (<= (- day2 day) empty)))
20563 (while (< (setq day (1+ day)) day2)
20564 (push (list day) dates1))
20565 (push (cons :omitted (- day2 day)) dates1))))
20566 (setq dates (nreverse dates1)))
20567 dates)))
20569 ;;; Agenda Daily/Weekly
20571 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20572 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20573 (defvar org-agenda-last-arguments nil
20574 "The arguments of the previous call to org-agenda")
20575 (defvar org-starting-day nil) ; local variable in the agenda buffer
20576 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20577 (defvar org-include-all-loc nil) ; local variable
20578 (defvar org-agenda-remove-date nil) ; dynamically scoped
20580 ;;;###autoload
20581 (defun org-agenda-list (&optional include-all start-day ndays)
20582 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20583 The view will be for the current day or week, but from the overview buffer
20584 you will be able to go to other days/weeks.
20586 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20587 all unfinished TODO items will also be shown, before the agenda.
20588 This feature is considered obsolete, please use the TODO list or a block
20589 agenda instead.
20591 With a numeric prefix argument in an interactive call, the agenda will
20592 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20593 the number of days. NDAYS defaults to `org-agenda-ndays'.
20595 START-DAY defaults to TODAY, or to the most recent match for the weekday
20596 given in `org-agenda-start-on-weekday'."
20597 (interactive "P")
20598 (if (and (integerp include-all) (> include-all 0))
20599 (setq ndays include-all include-all nil))
20600 (setq ndays (or ndays org-agenda-ndays)
20601 start-day (or start-day org-agenda-start-day))
20602 (if org-agenda-overriding-arguments
20603 (setq include-all (car org-agenda-overriding-arguments)
20604 start-day (nth 1 org-agenda-overriding-arguments)
20605 ndays (nth 2 org-agenda-overriding-arguments)))
20606 (if (stringp start-day)
20607 ;; Convert to an absolute day number
20608 (setq start-day (time-to-days (org-read-date nil t start-day))))
20609 (setq org-agenda-last-arguments (list include-all start-day ndays))
20610 (org-compile-prefix-format 'agenda)
20611 (org-set-sorting-strategy 'agenda)
20612 (require 'calendar)
20613 (let* ((org-agenda-start-on-weekday
20614 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20615 org-agenda-start-on-weekday nil))
20616 (thefiles (org-agenda-files))
20617 (files thefiles)
20618 (today (time-to-days
20619 (time-subtract (current-time)
20620 (list 0 (* 3600 org-extend-today-until) 0))))
20621 (sd (or start-day today))
20622 (start (if (or (null org-agenda-start-on-weekday)
20623 (< org-agenda-ndays 7))
20625 (let* ((nt (calendar-day-of-week
20626 (calendar-gregorian-from-absolute sd)))
20627 (n1 org-agenda-start-on-weekday)
20628 (d (- nt n1)))
20629 (- sd (+ (if (< d 0) 7 0) d)))))
20630 (day-numbers (list start))
20631 (day-cnt 0)
20632 (inhibit-redisplay (not debug-on-error))
20633 s e rtn rtnall file date d start-pos end-pos todayp nd)
20634 (setq org-agenda-redo-command
20635 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20636 ;; Make the list of days
20637 (setq ndays (or ndays org-agenda-ndays)
20638 nd ndays)
20639 (while (> ndays 1)
20640 (push (1+ (car day-numbers)) day-numbers)
20641 (setq ndays (1- ndays)))
20642 (setq day-numbers (nreverse day-numbers))
20643 (org-prepare-agenda "Day/Week")
20644 (org-set-local 'org-starting-day (car day-numbers))
20645 (org-set-local 'org-include-all-loc include-all)
20646 (org-set-local 'org-agenda-span
20647 (org-agenda-ndays-to-span nd))
20648 (when (and (or include-all org-agenda-include-all-todo)
20649 (member today day-numbers))
20650 (setq files thefiles
20651 rtnall nil)
20652 (while (setq file (pop files))
20653 (catch 'nextfile
20654 (org-check-agenda-file file)
20655 (setq date (calendar-gregorian-from-absolute today)
20656 rtn (org-agenda-get-day-entries
20657 file date :todo))
20658 (setq rtnall (append rtnall rtn))))
20659 (when rtnall
20660 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20661 (add-text-properties (point-min) (1- (point))
20662 (list 'face 'org-agenda-structure))
20663 (insert (org-finalize-agenda-entries rtnall) "\n")))
20664 (unless org-agenda-compact-blocks
20665 (setq s (point))
20666 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20667 "-agenda:\n")
20668 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20669 'org-date-line t)))
20670 (while (setq d (pop day-numbers))
20671 (setq date (calendar-gregorian-from-absolute d)
20672 s (point))
20673 (if (or (setq todayp (= d today))
20674 (and (not start-pos) (= d sd)))
20675 (setq start-pos (point))
20676 (if (and start-pos (not end-pos))
20677 (setq end-pos (point))))
20678 (setq files thefiles
20679 rtnall nil)
20680 (while (setq file (pop files))
20681 (catch 'nextfile
20682 (org-check-agenda-file file)
20683 (if org-agenda-show-log
20684 (setq rtn (org-agenda-get-day-entries
20685 file date
20686 :deadline :scheduled :timestamp :sexp :closed))
20687 (setq rtn (org-agenda-get-day-entries
20688 file date
20689 :deadline :scheduled :sexp :timestamp)))
20690 (setq rtnall (append rtnall rtn))))
20691 (if org-agenda-include-diary
20692 (progn
20693 (require 'diary-lib)
20694 (setq rtn (org-get-entries-from-diary date))
20695 (setq rtnall (append rtnall rtn))))
20696 (if (or rtnall org-agenda-show-all-dates)
20697 (progn
20698 (setq day-cnt (1+ day-cnt))
20699 (insert
20700 (if (stringp org-agenda-format-date)
20701 (format-time-string org-agenda-format-date
20702 (org-time-from-absolute date))
20703 (funcall org-agenda-format-date date))
20704 "\n")
20705 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20706 (put-text-property s (1- (point)) 'org-date-line t)
20707 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20708 (if todayp (put-text-property s (1- (point)) 'org-today t))
20709 (if rtnall (insert
20710 (org-finalize-agenda-entries
20711 (org-agenda-add-time-grid-maybe
20712 rtnall nd todayp))
20713 "\n"))
20714 (put-text-property s (1- (point)) 'day d)
20715 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20716 (goto-char (point-min))
20717 (org-fit-agenda-window)
20718 (unless (and (pos-visible-in-window-p (point-min))
20719 (pos-visible-in-window-p (point-max)))
20720 (goto-char (1- (point-max)))
20721 (recenter -1)
20722 (if (not (pos-visible-in-window-p (or start-pos 1)))
20723 (progn
20724 (goto-char (or start-pos 1))
20725 (recenter 1))))
20726 (goto-char (or start-pos 1))
20727 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20728 (org-finalize-agenda)
20729 (setq buffer-read-only t)
20730 (message "")))
20732 (defun org-agenda-ndays-to-span (n)
20733 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20735 ;;; Agenda TODO list
20737 (defvar org-select-this-todo-keyword nil)
20738 (defvar org-last-arg nil)
20740 ;;;###autoload
20741 (defun org-todo-list (arg)
20742 "Show all TODO entries from all agenda file in a single list.
20743 The prefix arg can be used to select a specific TODO keyword and limit
20744 the list to these. When using \\[universal-argument], you will be prompted
20745 for a keyword. A numeric prefix directly selects the Nth keyword in
20746 `org-todo-keywords-1'."
20747 (interactive "P")
20748 (require 'calendar)
20749 (org-compile-prefix-format 'todo)
20750 (org-set-sorting-strategy 'todo)
20751 (org-prepare-agenda "TODO")
20752 (let* ((today (time-to-days (current-time)))
20753 (date (calendar-gregorian-from-absolute today))
20754 (kwds org-todo-keywords-for-agenda)
20755 (completion-ignore-case t)
20756 (org-select-this-todo-keyword
20757 (if (stringp arg) arg
20758 (and arg (integerp arg) (> arg 0)
20759 (nth (1- arg) kwds))))
20760 rtn rtnall files file pos)
20761 (when (equal arg '(4))
20762 (setq org-select-this-todo-keyword
20763 (completing-read "Keyword (or KWD1|K2D2|...): "
20764 (mapcar 'list kwds) nil nil)))
20765 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20766 (org-set-local 'org-last-arg arg)
20767 (setq org-agenda-redo-command
20768 '(org-todo-list (or current-prefix-arg org-last-arg)))
20769 (setq files (org-agenda-files)
20770 rtnall nil)
20771 (while (setq file (pop files))
20772 (catch 'nextfile
20773 (org-check-agenda-file file)
20774 (setq rtn (org-agenda-get-day-entries file date :todo))
20775 (setq rtnall (append rtnall rtn))))
20776 (if org-agenda-overriding-header
20777 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20778 nil 'face 'org-agenda-structure) "\n")
20779 (insert "Global list of TODO items of type: ")
20780 (add-text-properties (point-min) (1- (point))
20781 (list 'face 'org-agenda-structure))
20782 (setq pos (point))
20783 (insert (or org-select-this-todo-keyword "ALL") "\n")
20784 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20785 (setq pos (point))
20786 (unless org-agenda-multi
20787 (insert "Available with `N r': (0)ALL")
20788 (let ((n 0) s)
20789 (mapc (lambda (x)
20790 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20791 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20792 (insert "\n "))
20793 (insert " " s))
20794 kwds))
20795 (insert "\n"))
20796 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20797 (when rtnall
20798 (insert (org-finalize-agenda-entries rtnall) "\n"))
20799 (goto-char (point-min))
20800 (org-fit-agenda-window)
20801 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20802 (org-finalize-agenda)
20803 (setq buffer-read-only t)))
20805 ;;; Agenda tags match
20807 ;;;###autoload
20808 (defun org-tags-view (&optional todo-only match)
20809 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20810 The prefix arg TODO-ONLY limits the search to TODO entries."
20811 (interactive "P")
20812 (org-compile-prefix-format 'tags)
20813 (org-set-sorting-strategy 'tags)
20814 (let* ((org-tags-match-list-sublevels
20815 (if todo-only t org-tags-match-list-sublevels))
20816 (completion-ignore-case t)
20817 rtn rtnall files file pos matcher
20818 buffer)
20819 (setq matcher (org-make-tags-matcher match)
20820 match (car matcher) matcher (cdr matcher))
20821 (org-prepare-agenda (concat "TAGS " match))
20822 (setq org-agenda-redo-command
20823 (list 'org-tags-view (list 'quote todo-only)
20824 (list 'if 'current-prefix-arg nil match)))
20825 (setq files (org-agenda-files)
20826 rtnall nil)
20827 (while (setq file (pop files))
20828 (catch 'nextfile
20829 (org-check-agenda-file file)
20830 (setq buffer (if (file-exists-p file)
20831 (org-get-agenda-file-buffer file)
20832 (error "No such file %s" file)))
20833 (if (not buffer)
20834 ;; If file does not exist, merror message to agenda
20835 (setq rtn (list
20836 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20837 rtnall (append rtnall rtn))
20838 (with-current-buffer buffer
20839 (unless (org-mode-p)
20840 (error "Agenda file %s is not in `org-mode'" file))
20841 (save-excursion
20842 (save-restriction
20843 (if org-agenda-restrict
20844 (narrow-to-region org-agenda-restrict-begin
20845 org-agenda-restrict-end)
20846 (widen))
20847 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20848 (setq rtnall (append rtnall rtn))))))))
20849 (if org-agenda-overriding-header
20850 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20851 nil 'face 'org-agenda-structure) "\n")
20852 (insert "Headlines with TAGS match: ")
20853 (add-text-properties (point-min) (1- (point))
20854 (list 'face 'org-agenda-structure))
20855 (setq pos (point))
20856 (insert match "\n")
20857 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20858 (setq pos (point))
20859 (unless org-agenda-multi
20860 (insert "Press `C-u r' to search again with new search string\n"))
20861 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20862 (when rtnall
20863 (insert (org-finalize-agenda-entries rtnall) "\n"))
20864 (goto-char (point-min))
20865 (org-fit-agenda-window)
20866 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20867 (org-finalize-agenda)
20868 (setq buffer-read-only t)))
20870 ;;; Agenda Finding stuck projects
20872 (defvar org-agenda-skip-regexp nil
20873 "Regular expression used in skipping subtrees for the agenda.
20874 This is basically a temporary global variable that can be set and then
20875 used by user-defined selections using `org-agenda-skip-function'.")
20877 (defvar org-agenda-overriding-header nil
20878 "When this is set during todo and tags searches, will replace header.")
20880 (defun org-agenda-skip-subtree-when-regexp-matches ()
20881 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20882 If yes, it returns the end position of this tree, causing agenda commands
20883 to skip this subtree. This is a function that can be put into
20884 `org-agenda-skip-function' for the duration of a command."
20885 (let ((end (save-excursion (org-end-of-subtree t)))
20886 skip)
20887 (save-excursion
20888 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20889 (and skip end)))
20891 (defun org-agenda-skip-entry-if (&rest conditions)
20892 "Skip entry if any of CONDITIONS is true.
20893 See `org-agenda-skip-if' for details."
20894 (org-agenda-skip-if nil conditions))
20896 (defun org-agenda-skip-subtree-if (&rest conditions)
20897 "Skip entry if any of CONDITIONS is true.
20898 See `org-agenda-skip-if' for details."
20899 (org-agenda-skip-if t conditions))
20901 (defun org-agenda-skip-if (subtree conditions)
20902 "Checks current entity for CONDITIONS.
20903 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20904 the entry, i.e. the text before the next heading is checked.
20906 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20907 from different tests. Valid conditions are:
20909 scheduled Check if there is a scheduled cookie
20910 notscheduled Check if there is no scheduled cookie
20911 deadline Check if there is a deadline
20912 notdeadline Check if there is no deadline
20913 regexp Check if regexp matches
20914 notregexp Check if regexp does not match.
20916 The regexp is taken from the conditions list, it must come right after
20917 the `regexp' or `notregexp' element.
20919 If any of these conditions is met, this function returns the end point of
20920 the entity, causing the search to continue from there. This is a function
20921 that can be put into `org-agenda-skip-function' for the duration of a command."
20922 (let (beg end m)
20923 (org-back-to-heading t)
20924 (setq beg (point)
20925 end (if subtree
20926 (progn (org-end-of-subtree t) (point))
20927 (progn (outline-next-heading) (1- (point)))))
20928 (goto-char beg)
20929 (and
20931 (and (memq 'scheduled conditions)
20932 (re-search-forward org-scheduled-time-regexp end t))
20933 (and (memq 'notscheduled conditions)
20934 (not (re-search-forward org-scheduled-time-regexp end t)))
20935 (and (memq 'deadline conditions)
20936 (re-search-forward org-deadline-time-regexp end t))
20937 (and (memq 'notdeadline conditions)
20938 (not (re-search-forward org-deadline-time-regexp end t)))
20939 (and (setq m (memq 'regexp conditions))
20940 (stringp (nth 1 m))
20941 (re-search-forward (nth 1 m) end t))
20942 (and (setq m (memq 'notregexp conditions))
20943 (stringp (nth 1 m))
20944 (not (re-search-forward (nth 1 m) end t))))
20945 end)))
20947 ;;;###autoload
20948 (defun org-agenda-list-stuck-projects (&rest ignore)
20949 "Create agenda view for projects that are stuck.
20950 Stuck projects are project that have no next actions. For the definitions
20951 of what a project is and how to check if it stuck, customize the variable
20952 `org-stuck-projects'.
20953 MATCH is being ignored."
20954 (interactive)
20955 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20956 ;; FIXME: we could have used org-agenda-skip-if here.
20957 (org-agenda-overriding-header "List of stuck projects: ")
20958 (matcher (nth 0 org-stuck-projects))
20959 (todo (nth 1 org-stuck-projects))
20960 (todo-wds (if (member "*" todo)
20961 (progn
20962 (org-prepare-agenda-buffers (org-agenda-files))
20963 (org-delete-all
20964 org-done-keywords-for-agenda
20965 (copy-sequence org-todo-keywords-for-agenda)))
20966 todo))
20967 (todo-re (concat "^\\*+[ \t]+\\("
20968 (mapconcat 'identity todo-wds "\\|")
20969 "\\)\\>"))
20970 (tags (nth 2 org-stuck-projects))
20971 (tags-re (if (member "*" tags)
20972 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20973 (concat "^\\*+ .*:\\("
20974 (mapconcat 'identity tags "\\|")
20975 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20976 (gen-re (nth 3 org-stuck-projects))
20977 (re-list
20978 (delq nil
20979 (list
20980 (if todo todo-re)
20981 (if tags tags-re)
20982 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20983 gen-re)))))
20984 (setq org-agenda-skip-regexp
20985 (if re-list
20986 (mapconcat 'identity re-list "\\|")
20987 (error "No information how to identify unstuck projects")))
20988 (org-tags-view nil matcher)
20989 (with-current-buffer org-agenda-buffer-name
20990 (setq org-agenda-redo-command
20991 '(org-agenda-list-stuck-projects
20992 (or current-prefix-arg org-last-arg))))))
20994 ;;; Diary integration
20996 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20998 (defun org-get-entries-from-diary (date)
20999 "Get the (Emacs Calendar) diary entries for DATE."
21000 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21001 (diary-display-hook '(fancy-diary-display))
21002 (pop-up-frames nil)
21003 (list-diary-entries-hook
21004 (cons 'org-diary-default-entry list-diary-entries-hook))
21005 (diary-file-name-prefix-function nil) ; turn this feature off
21006 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21007 entries
21008 (org-disable-agenda-to-diary t))
21009 (save-excursion
21010 (save-window-excursion
21011 (funcall (if (fboundp 'diary-list-entries)
21012 'diary-list-entries 'list-diary-entries)
21013 date 1)))
21014 (if (not (get-buffer fancy-diary-buffer))
21015 (setq entries nil)
21016 (with-current-buffer fancy-diary-buffer
21017 (setq buffer-read-only nil)
21018 (if (zerop (buffer-size))
21019 ;; No entries
21020 (setq entries nil)
21021 ;; Omit the date and other unnecessary stuff
21022 (org-agenda-cleanup-fancy-diary)
21023 ;; Add prefix to each line and extend the text properties
21024 (if (zerop (buffer-size))
21025 (setq entries nil)
21026 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21027 (set-buffer-modified-p nil)
21028 (kill-buffer fancy-diary-buffer)))
21029 (when entries
21030 (setq entries (org-split-string entries "\n"))
21031 (setq entries
21032 (mapcar
21033 (lambda (x)
21034 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21035 ;; Extend the text properties to the beginning of the line
21036 (org-add-props x (text-properties-at (1- (length x)) x)
21037 'type "diary" 'date date))
21038 entries)))))
21040 (defun org-agenda-cleanup-fancy-diary ()
21041 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21042 This gets rid of the date, the underline under the date, and
21043 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21044 date. It also removes lines that contain only whitespace."
21045 (goto-char (point-min))
21046 (if (looking-at ".*?:[ \t]*")
21047 (progn
21048 (replace-match "")
21049 (re-search-forward "\n=+$" nil t)
21050 (replace-match "")
21051 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21052 (re-search-forward "\n=+$" nil t)
21053 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21054 (goto-char (point-min))
21055 (while (re-search-forward "^ +\n" nil t)
21056 (replace-match ""))
21057 (goto-char (point-min))
21058 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21059 (replace-match "")))
21061 ;; Make sure entries from the diary have the right text properties.
21062 (eval-after-load "diary-lib"
21063 '(if (boundp 'diary-modify-entry-list-string-function)
21064 ;; We can rely on the hook, nothing to do
21066 ;; Hook not avaiable, must use advice to make this work
21067 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21068 "Make the position visible."
21069 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21070 (stringp string)
21071 buffer-file-name)
21072 (setq string (org-modify-diary-entry-string string))))))
21074 (defun org-modify-diary-entry-string (string)
21075 "Add text properties to string, allowing org-mode to act on it."
21076 (org-add-props string nil
21077 'mouse-face 'highlight
21078 'keymap org-agenda-keymap
21079 'help-echo (if buffer-file-name
21080 (format "mouse-2 or RET jump to diary file %s"
21081 (abbreviate-file-name buffer-file-name))
21083 'org-agenda-diary-link t
21084 'org-marker (org-agenda-new-marker (point-at-bol))))
21086 (defun org-diary-default-entry ()
21087 "Add a dummy entry to the diary.
21088 Needed to avoid empty dates which mess up holiday display."
21089 ;; Catch the error if dealing with the new add-to-diary-alist
21090 (when org-disable-agenda-to-diary
21091 (condition-case nil
21092 (add-to-diary-list original-date "Org-mode dummy" "")
21093 (error
21094 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21096 ;;;###autoload
21097 (defun org-diary (&rest args)
21098 "Return diary information from org-files.
21099 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21100 It accesses org files and extracts information from those files to be
21101 listed in the diary. The function accepts arguments specifying what
21102 items should be listed. The following arguments are allowed:
21104 :timestamp List the headlines of items containing a date stamp or
21105 date range matching the selected date. Deadlines will
21106 also be listed, on the expiration day.
21108 :sexp List entries resulting from diary-like sexps.
21110 :deadline List any deadlines past due, or due within
21111 `org-deadline-warning-days'. The listing occurs only
21112 in the diary for *today*, not at any other date. If
21113 an entry is marked DONE, it is no longer listed.
21115 :scheduled List all items which are scheduled for the given date.
21116 The diary for *today* also contains items which were
21117 scheduled earlier and are not yet marked DONE.
21119 :todo List all TODO items from the org-file. This may be a
21120 long list - so this is not turned on by default.
21121 Like deadlines, these entries only show up in the
21122 diary for *today*, not at any other date.
21124 The call in the diary file should look like this:
21126 &%%(org-diary) ~/path/to/some/orgfile.org
21128 Use a separate line for each org file to check. Or, if you omit the file name,
21129 all files listed in `org-agenda-files' will be checked automatically:
21131 &%%(org-diary)
21133 If you don't give any arguments (as in the example above), the default
21134 arguments (:deadline :scheduled :timestamp :sexp) are used.
21135 So the example above may also be written as
21137 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21139 The function expects the lisp variables `entry' and `date' to be provided
21140 by the caller, because this is how the calendar works. Don't use this
21141 function from a program - use `org-agenda-get-day-entries' instead."
21142 (when (> (- (time-to-seconds (current-time))
21143 org-agenda-last-marker-time)
21145 (org-agenda-reset-markers))
21146 (org-compile-prefix-format 'agenda)
21147 (org-set-sorting-strategy 'agenda)
21148 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21149 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21150 (list entry)
21151 (org-agenda-files t)))
21152 file rtn results)
21153 (org-prepare-agenda-buffers files)
21154 ;; If this is called during org-agenda, don't return any entries to
21155 ;; the calendar. Org Agenda will list these entries itself.
21156 (if org-disable-agenda-to-diary (setq files nil))
21157 (while (setq file (pop files))
21158 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21159 (setq results (append results rtn)))
21160 (if results
21161 (concat (org-finalize-agenda-entries results) "\n"))))
21163 ;;; Agenda entry finders
21165 (defun org-agenda-get-day-entries (file date &rest args)
21166 "Does the work for `org-diary' and `org-agenda'.
21167 FILE is the path to a file to be checked for entries. DATE is date like
21168 the one returned by `calendar-current-date'. ARGS are symbols indicating
21169 which kind of entries should be extracted. For details about these, see
21170 the documentation of `org-diary'."
21171 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21172 (let* ((org-startup-folded nil)
21173 (org-startup-align-all-tables nil)
21174 (buffer (if (file-exists-p file)
21175 (org-get-agenda-file-buffer file)
21176 (error "No such file %s" file)))
21177 arg results rtn)
21178 (if (not buffer)
21179 ;; If file does not exist, make sure an error message ends up in diary
21180 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21181 (with-current-buffer buffer
21182 (unless (org-mode-p)
21183 (error "Agenda file %s is not in `org-mode'" file))
21184 (let ((case-fold-search nil))
21185 (save-excursion
21186 (save-restriction
21187 (if org-agenda-restrict
21188 (narrow-to-region org-agenda-restrict-begin
21189 org-agenda-restrict-end)
21190 (widen))
21191 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21192 (while (setq arg (pop args))
21193 (cond
21194 ((and (eq arg :todo)
21195 (equal date (calendar-current-date)))
21196 (setq rtn (org-agenda-get-todos))
21197 (setq results (append results rtn)))
21198 ((eq arg :timestamp)
21199 (setq rtn (org-agenda-get-blocks))
21200 (setq results (append results rtn))
21201 (setq rtn (org-agenda-get-timestamps))
21202 (setq results (append results rtn)))
21203 ((eq arg :sexp)
21204 (setq rtn (org-agenda-get-sexps))
21205 (setq results (append results rtn)))
21206 ((eq arg :scheduled)
21207 (setq rtn (org-agenda-get-scheduled))
21208 (setq results (append results rtn)))
21209 ((eq arg :closed)
21210 (setq rtn (org-agenda-get-closed))
21211 (setq results (append results rtn)))
21212 ((eq arg :deadline)
21213 (setq rtn (org-agenda-get-deadlines))
21214 (setq results (append results rtn))))))))
21215 results))))
21217 (defun org-entry-is-todo-p ()
21218 (member (org-get-todo-state) org-not-done-keywords))
21220 (defun org-entry-is-done-p ()
21221 (member (org-get-todo-state) org-done-keywords))
21223 (defun org-get-todo-state ()
21224 (save-excursion
21225 (org-back-to-heading t)
21226 (and (looking-at org-todo-line-regexp)
21227 (match-end 2)
21228 (match-string 2))))
21230 (defun org-at-date-range-p (&optional inactive-ok)
21231 "Is the cursor inside a date range?"
21232 (interactive)
21233 (save-excursion
21234 (catch 'exit
21235 (let ((pos (point)))
21236 (skip-chars-backward "^[<\r\n")
21237 (skip-chars-backward "<[")
21238 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21239 (>= (match-end 0) pos)
21240 (throw 'exit t))
21241 (skip-chars-backward "^<[\r\n")
21242 (skip-chars-backward "<[")
21243 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21244 (>= (match-end 0) pos)
21245 (throw 'exit t)))
21246 nil)))
21248 (defun org-agenda-get-todos ()
21249 "Return the TODO information for agenda display."
21250 (let* ((props (list 'face nil
21251 'done-face 'org-done
21252 'org-not-done-regexp org-not-done-regexp
21253 'org-todo-regexp org-todo-regexp
21254 'mouse-face 'highlight
21255 'keymap org-agenda-keymap
21256 'help-echo
21257 (format "mouse-2 or RET jump to org file %s"
21258 (abbreviate-file-name buffer-file-name))))
21259 ;; FIXME: get rid of the \n at some point but watch out
21260 (regexp (concat "^\\*+[ \t]+\\("
21261 (if org-select-this-todo-keyword
21262 (if (equal org-select-this-todo-keyword "*")
21263 org-todo-regexp
21264 (concat "\\<\\("
21265 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21266 "\\)\\>"))
21267 org-not-done-regexp)
21268 "[^\n\r]*\\)"))
21269 marker priority category tags
21270 ee txt beg end)
21271 (goto-char (point-min))
21272 (while (re-search-forward regexp nil t)
21273 (catch :skip
21274 (save-match-data
21275 (beginning-of-line)
21276 (setq beg (point) end (progn (outline-next-heading) (point)))
21277 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21278 (re-search-forward org-ts-regexp end t))
21279 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21280 (re-search-forward org-scheduled-time-regexp end t))
21281 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21282 (re-search-forward org-deadline-time-regexp end t)
21283 (org-deadline-close (match-string 1))))
21284 (goto-char (1+ beg))
21285 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21286 (throw :skip nil)))
21287 (goto-char beg)
21288 (org-agenda-skip)
21289 (goto-char (match-beginning 1))
21290 (setq marker (org-agenda-new-marker (match-beginning 0))
21291 category (org-get-category)
21292 tags (org-get-tags-at (point))
21293 txt (org-format-agenda-item "" (match-string 1) category tags)
21294 priority (1+ (org-get-priority txt)))
21295 (org-add-props txt props
21296 'org-marker marker 'org-hd-marker marker
21297 'priority priority 'org-category category
21298 'type "todo")
21299 (push txt ee)
21300 (if org-agenda-todo-list-sublevels
21301 (goto-char (match-end 1))
21302 (org-end-of-subtree 'invisible))))
21303 (nreverse ee)))
21305 (defconst org-agenda-no-heading-message
21306 "No heading for this item in buffer or region.")
21308 (defun org-agenda-get-timestamps ()
21309 "Return the date stamp information for agenda display."
21310 (let* ((props (list 'face nil
21311 'org-not-done-regexp org-not-done-regexp
21312 'org-todo-regexp org-todo-regexp
21313 'mouse-face 'highlight
21314 'keymap org-agenda-keymap
21315 'help-echo
21316 (format "mouse-2 or RET jump to org file %s"
21317 (abbreviate-file-name buffer-file-name))))
21318 (d1 (calendar-absolute-from-gregorian date))
21319 (remove-re
21320 (concat
21321 (regexp-quote
21322 (format-time-string
21323 "<%Y-%m-%d"
21324 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21325 ".*?>"))
21326 (regexp
21327 (concat
21328 (regexp-quote
21329 (substring
21330 (format-time-string
21331 (car org-time-stamp-formats)
21332 (apply 'encode-time ; DATE bound by calendar
21333 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21334 0 11))
21335 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21336 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21337 marker hdmarker deadlinep scheduledp donep tmp priority category
21338 ee txt timestr tags b0 b3 e3 head)
21339 (goto-char (point-min))
21340 (while (re-search-forward regexp nil t)
21341 (setq b0 (match-beginning 0)
21342 b3 (match-beginning 3) e3 (match-end 3))
21343 (catch :skip
21344 (and (org-at-date-range-p) (throw :skip nil))
21345 (org-agenda-skip)
21346 (if (and (match-end 1)
21347 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21348 (throw :skip nil))
21349 (if (and e3
21350 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21351 (throw :skip nil))
21352 (setq marker (org-agenda-new-marker b0)
21353 category (org-get-category b0)
21354 tmp (buffer-substring (max (point-min)
21355 (- b0 org-ds-keyword-length))
21357 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21358 deadlinep (string-match org-deadline-regexp tmp)
21359 scheduledp (string-match org-scheduled-regexp tmp)
21360 donep (org-entry-is-done-p))
21361 (if (or scheduledp deadlinep) (throw :skip t))
21362 (if (string-match ">" timestr)
21363 ;; substring should only run to end of time stamp
21364 (setq timestr (substring timestr 0 (match-end 0))))
21365 (save-excursion
21366 (if (re-search-backward "^\\*+ " nil t)
21367 (progn
21368 (goto-char (match-beginning 0))
21369 (setq hdmarker (org-agenda-new-marker)
21370 tags (org-get-tags-at))
21371 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21372 (setq head (match-string 1))
21373 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21374 (setq txt (org-format-agenda-item
21375 nil head category tags timestr nil
21376 remove-re)))
21377 (setq txt org-agenda-no-heading-message))
21378 (setq priority (org-get-priority txt))
21379 (org-add-props txt props
21380 'org-marker marker 'org-hd-marker hdmarker)
21381 (org-add-props txt nil 'priority priority
21382 'org-category category 'date date
21383 'type "timestamp")
21384 (push txt ee))
21385 (outline-next-heading)))
21386 (nreverse ee)))
21388 (defun org-agenda-get-sexps ()
21389 "Return the sexp information for agenda display."
21390 (require 'diary-lib)
21391 (let* ((props (list 'face nil
21392 'mouse-face 'highlight
21393 'keymap org-agenda-keymap
21394 'help-echo
21395 (format "mouse-2 or RET jump to org file %s"
21396 (abbreviate-file-name buffer-file-name))))
21397 (regexp "^&?%%(")
21398 marker category ee txt tags entry result beg b sexp sexp-entry)
21399 (goto-char (point-min))
21400 (while (re-search-forward regexp nil t)
21401 (catch :skip
21402 (org-agenda-skip)
21403 (setq beg (match-beginning 0))
21404 (goto-char (1- (match-end 0)))
21405 (setq b (point))
21406 (forward-sexp 1)
21407 (setq sexp (buffer-substring b (point)))
21408 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21409 (org-trim (match-string 1))
21410 ""))
21411 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21412 (when result
21413 (setq marker (org-agenda-new-marker beg)
21414 category (org-get-category beg))
21416 (if (string-match "\\S-" result)
21417 (setq txt result)
21418 (setq txt "SEXP entry returned empty string"))
21420 (setq txt (org-format-agenda-item
21421 "" txt category tags 'time))
21422 (org-add-props txt props 'org-marker marker)
21423 (org-add-props txt nil
21424 'org-category category 'date date
21425 'type "sexp")
21426 (push txt ee))))
21427 (nreverse ee)))
21429 (defun org-agenda-get-closed ()
21430 "Return the logged TODO entries for agenda display."
21431 (let* ((props (list 'mouse-face 'highlight
21432 'org-not-done-regexp org-not-done-regexp
21433 'org-todo-regexp org-todo-regexp
21434 'keymap org-agenda-keymap
21435 'help-echo
21436 (format "mouse-2 or RET jump to org file %s"
21437 (abbreviate-file-name buffer-file-name))))
21438 (regexp (concat
21439 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21440 (regexp-quote
21441 (substring
21442 (format-time-string
21443 (car org-time-stamp-formats)
21444 (apply 'encode-time ; DATE bound by calendar
21445 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21446 1 11))))
21447 marker hdmarker priority category tags closedp
21448 ee txt timestr)
21449 (goto-char (point-min))
21450 (while (re-search-forward regexp nil t)
21451 (catch :skip
21452 (org-agenda-skip)
21453 (setq marker (org-agenda-new-marker (match-beginning 0))
21454 closedp (equal (match-string 1) org-closed-string)
21455 category (org-get-category (match-beginning 0))
21456 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21457 ;; donep (org-entry-is-done-p)
21459 (if (string-match "\\]" timestr)
21460 ;; substring should only run to end of time stamp
21461 (setq timestr (substring timestr 0 (match-end 0))))
21462 (save-excursion
21463 (if (re-search-backward "^\\*+ " nil t)
21464 (progn
21465 (goto-char (match-beginning 0))
21466 (setq hdmarker (org-agenda-new-marker)
21467 tags (org-get-tags-at))
21468 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21469 (setq txt (org-format-agenda-item
21470 (if closedp "Closed: " "Clocked: ")
21471 (match-string 1) category tags timestr)))
21472 (setq txt org-agenda-no-heading-message))
21473 (setq priority 100000)
21474 (org-add-props txt props
21475 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21476 'priority priority 'org-category category
21477 'type "closed" 'date date
21478 'undone-face 'org-warning 'done-face 'org-done)
21479 (push txt ee))
21480 (goto-char (point-at-eol))))
21481 (nreverse ee)))
21483 (defun org-agenda-get-deadlines ()
21484 "Return the deadline information for agenda display."
21485 (let* ((props (list 'mouse-face 'highlight
21486 'org-not-done-regexp org-not-done-regexp
21487 'org-todo-regexp org-todo-regexp
21488 'keymap org-agenda-keymap
21489 'help-echo
21490 (format "mouse-2 or RET jump to org file %s"
21491 (abbreviate-file-name buffer-file-name))))
21492 (regexp org-deadline-time-regexp)
21493 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21494 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21495 d2 diff dfrac wdays pos pos1 category tags
21496 ee txt head face s upcomingp donep timestr)
21497 (goto-char (point-min))
21498 (while (re-search-forward regexp nil t)
21499 (catch :skip
21500 (org-agenda-skip)
21501 (setq s (match-string 1)
21502 pos (1- (match-beginning 1))
21503 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21504 diff (- d2 d1)
21505 wdays (org-get-wdays s)
21506 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21507 upcomingp (and todayp (> diff 0)))
21508 ;; When to show a deadline in the calendar:
21509 ;; If the expiration is within wdays warning time.
21510 ;; Past-due deadlines are only shown on the current date
21511 (if (or (and (<= diff wdays)
21512 (and todayp (not org-agenda-only-exact-dates)))
21513 (= diff 0))
21514 (save-excursion
21515 (setq category (org-get-category))
21516 (if (re-search-backward "^\\*+[ \t]+" nil t)
21517 (progn
21518 (goto-char (match-end 0))
21519 (setq pos1 (match-beginning 0))
21520 (setq tags (org-get-tags-at pos1))
21521 (setq head (buffer-substring-no-properties
21522 (point)
21523 (progn (skip-chars-forward "^\r\n")
21524 (point))))
21525 (setq donep (string-match org-looking-at-done-regexp head))
21526 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21527 (setq timestr
21528 (concat (substring s (match-beginning 1)) " "))
21529 (setq timestr 'time))
21530 (if (and donep
21531 (or org-agenda-skip-deadline-if-done
21532 (not (= diff 0))))
21533 (setq txt nil)
21534 (setq txt (org-format-agenda-item
21535 (if (= diff 0)
21536 (car org-agenda-deadline-leaders)
21537 (format (nth 1 org-agenda-deadline-leaders)
21538 diff))
21539 head category tags timestr))))
21540 (setq txt org-agenda-no-heading-message))
21541 (when txt
21542 (setq face (org-agenda-deadline-face dfrac))
21543 (org-add-props txt props
21544 'org-marker (org-agenda-new-marker pos)
21545 'org-hd-marker (org-agenda-new-marker pos1)
21546 'priority (+ (- diff)
21547 (org-get-priority txt))
21548 'org-category category
21549 'type (if upcomingp "upcoming-deadline" "deadline")
21550 'date (if upcomingp date d2)
21551 'face (if donep 'org-done face)
21552 'undone-face face 'done-face 'org-done)
21553 (push txt ee))))))
21554 (nreverse ee)))
21556 (defun org-agenda-deadline-face (fraction)
21557 "Return the face to displaying a deadline item.
21558 FRACTION is what fraction of the head-warning time has passed."
21559 (let ((faces org-agenda-deadline-faces) f)
21560 (catch 'exit
21561 (while (setq f (pop faces))
21562 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21564 (defun org-agenda-get-scheduled ()
21565 "Return the scheduled information for agenda display."
21566 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21567 'org-todo-regexp org-todo-regexp
21568 'done-face 'org-done
21569 'mouse-face 'highlight
21570 'keymap org-agenda-keymap
21571 'help-echo
21572 (format "mouse-2 or RET jump to org file %s"
21573 (abbreviate-file-name buffer-file-name))))
21574 (regexp org-scheduled-time-regexp)
21575 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21576 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21577 d2 diff pos pos1 category tags
21578 ee txt head pastschedp donep face timestr s)
21579 (goto-char (point-min))
21580 (while (re-search-forward regexp nil t)
21581 (catch :skip
21582 (org-agenda-skip)
21583 (setq s (match-string 1)
21584 pos (1- (match-beginning 1))
21585 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21586 ;;; is this right?
21587 ;;; do we need to do this for deadleine too????
21588 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21589 diff (- d2 d1))
21590 (setq pastschedp (and todayp (< diff 0)))
21591 ;; When to show a scheduled item in the calendar:
21592 ;; If it is on or past the date.
21593 (if (or (and (< diff 0)
21594 (and todayp (not org-agenda-only-exact-dates)))
21595 (= diff 0))
21596 (save-excursion
21597 (setq category (org-get-category))
21598 (if (re-search-backward "^\\*+[ \t]+" nil t)
21599 (progn
21600 (goto-char (match-end 0))
21601 (setq pos1 (match-beginning 0))
21602 (setq tags (org-get-tags-at))
21603 (setq head (buffer-substring-no-properties
21604 (point)
21605 (progn (skip-chars-forward "^\r\n") (point))))
21606 (setq donep (string-match org-looking-at-done-regexp head))
21607 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21608 (setq timestr
21609 (concat (substring s (match-beginning 1)) " "))
21610 (setq timestr 'time))
21611 (if (and donep
21612 (or org-agenda-skip-scheduled-if-done
21613 (not (= diff 0))))
21614 (setq txt nil)
21615 (setq txt (org-format-agenda-item
21616 (if (= diff 0)
21617 (car org-agenda-scheduled-leaders)
21618 (format (nth 1 org-agenda-scheduled-leaders)
21619 (- 1 diff)))
21620 head category tags timestr))))
21621 (setq txt org-agenda-no-heading-message))
21622 (when txt
21623 (setq face (if pastschedp
21624 'org-scheduled-previously
21625 'org-scheduled-today))
21626 (org-add-props txt props
21627 'undone-face face
21628 'face (if donep 'org-done face)
21629 'org-marker (org-agenda-new-marker pos)
21630 'org-hd-marker (org-agenda-new-marker pos1)
21631 'type (if pastschedp "past-scheduled" "scheduled")
21632 'date (if pastschedp d2 date)
21633 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21634 'org-category category)
21635 (push txt ee))))))
21636 (nreverse ee)))
21638 (defun org-agenda-get-blocks ()
21639 "Return the date-range information for agenda display."
21640 (let* ((props (list 'face nil
21641 'org-not-done-regexp org-not-done-regexp
21642 'org-todo-regexp org-todo-regexp
21643 'mouse-face 'highlight
21644 'keymap org-agenda-keymap
21645 'help-echo
21646 (format "mouse-2 or RET jump to org file %s"
21647 (abbreviate-file-name buffer-file-name))))
21648 (regexp org-tr-regexp)
21649 (d0 (calendar-absolute-from-gregorian date))
21650 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21651 donep head)
21652 (goto-char (point-min))
21653 (while (re-search-forward regexp nil t)
21654 (catch :skip
21655 (org-agenda-skip)
21656 (setq pos (point))
21657 (setq timestr (match-string 0)
21658 s1 (match-string 1)
21659 s2 (match-string 2)
21660 d1 (time-to-days (org-time-string-to-time s1))
21661 d2 (time-to-days (org-time-string-to-time s2)))
21662 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21663 ;; Only allow days between the limits, because the normal
21664 ;; date stamps will catch the limits.
21665 (save-excursion
21666 (setq marker (org-agenda-new-marker (point)))
21667 (setq category (org-get-category))
21668 (if (re-search-backward "^\\*+ " nil t)
21669 (progn
21670 (goto-char (match-beginning 0))
21671 (setq hdmarker (org-agenda-new-marker (point)))
21672 (setq tags (org-get-tags-at))
21673 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21674 (setq head (match-string 1))
21675 (and org-agenda-skip-timestamp-if-done
21676 (org-entry-is-done-p)
21677 (throw :skip t))
21678 (setq txt (org-format-agenda-item
21679 (format (if (= d1 d2) "" "(%d/%d): ")
21680 (1+ (- d0 d1)) (1+ (- d2 d1)))
21681 head category tags
21682 (if (= d0 d1) timestr))))
21683 (setq txt org-agenda-no-heading-message))
21684 (org-add-props txt props
21685 'org-marker marker 'org-hd-marker hdmarker
21686 'type "block" 'date date
21687 'priority (org-get-priority txt) 'org-category category)
21688 (push txt ee)))
21689 (goto-char pos)))
21690 ;; Sort the entries by expiration date.
21691 (nreverse ee)))
21693 ;;; Agenda presentation and sorting
21695 (defconst org-plain-time-of-day-regexp
21696 (concat
21697 "\\(\\<[012]?[0-9]"
21698 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21699 "\\(--?"
21700 "\\(\\<[012]?[0-9]"
21701 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21702 "\\)?")
21703 "Regular expression to match a plain time or time range.
21704 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21705 groups carry important information:
21706 0 the full match
21707 1 the first time, range or not
21708 8 the second time, if it is a range.")
21710 (defconst org-plain-time-extension-regexp
21711 (concat
21712 "\\(\\<[012]?[0-9]"
21713 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21714 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21715 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21716 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21717 groups carry important information:
21718 0 the full match
21719 7 hours of duration
21720 9 minutes of duration")
21722 (defconst org-stamp-time-of-day-regexp
21723 (concat
21724 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21725 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21726 "\\(--?"
21727 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21728 "Regular expression to match a timestamp time or time range.
21729 After a match, the following groups carry important information:
21730 0 the full match
21731 1 date plus weekday, for backreferencing to make sure both times on same day
21732 2 the first time, range or not
21733 4 the second time, if it is a range.")
21735 (defvar org-prefix-has-time nil
21736 "A flag, set by `org-compile-prefix-format'.
21737 The flag is set if the currently compiled format contains a `%t'.")
21738 (defvar org-prefix-has-tag nil
21739 "A flag, set by `org-compile-prefix-format'.
21740 The flag is set if the currently compiled format contains a `%T'.")
21742 (defun org-format-agenda-item (extra txt &optional category tags dotime
21743 noprefix remove-re)
21744 "Format TXT to be inserted into the agenda buffer.
21745 In particular, it adds the prefix and corresponding text properties. EXTRA
21746 must be a string and replaces the `%s' specifier in the prefix format.
21747 CATEGORY (string, symbol or nil) may be used to overrule the default
21748 category taken from local variable or file name. It will replace the `%c'
21749 specifier in the format. DOTIME, when non-nil, indicates that a
21750 time-of-day should be extracted from TXT for sorting of this entry, and for
21751 the `%t' specifier in the format. When DOTIME is a string, this string is
21752 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21753 only the correctly processes TXT should be returned - this is used by
21754 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21755 Any match of REMOVE-RE will be removed from TXT."
21756 (save-match-data
21757 ;; Diary entries sometimes have extra whitespace at the beginning
21758 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21759 (let* ((category (or category
21760 org-category
21761 (if buffer-file-name
21762 (file-name-sans-extension
21763 (file-name-nondirectory buffer-file-name))
21764 "")))
21765 (tag (if tags (nth (1- (length tags)) tags) ""))
21766 time ; time and tag are needed for the eval of the prefix format
21767 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21768 (time-of-day (and dotime (org-get-time-of-day ts)))
21769 stamp plain s0 s1 s2 rtn srp)
21770 (when (and dotime time-of-day org-prefix-has-time)
21771 ;; Extract starting and ending time and move them to prefix
21772 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21773 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21774 (setq s0 (match-string 0 ts)
21775 srp (and stamp (match-end 3))
21776 s1 (match-string (if plain 1 2) ts)
21777 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21779 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21780 ;; them, we might want to remove them there to avoid duplication.
21781 ;; The user can turn this off with a variable.
21782 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21783 (string-match (concat (regexp-quote s0) " *") txt)
21784 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21785 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21786 (= (match-beginning 0) 0)
21788 (setq txt (replace-match "" nil nil txt))))
21789 ;; Normalize the time(s) to 24 hour
21790 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21791 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21793 (when (and s1 (not s2) org-agenda-default-appointment-duration
21794 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21795 (let ((m (+ (string-to-number (match-string 2 s1))
21796 (* 60 (string-to-number (match-string 1 s1)))
21797 org-agenda-default-appointment-duration))
21799 (setq h (/ m 60) m (- m (* h 60)))
21800 (setq s2 (format "%02d:%02d" h m))))
21802 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21803 txt)
21804 ;; Tags are in the string
21805 (if (or (eq org-agenda-remove-tags t)
21806 (and org-agenda-remove-tags
21807 org-prefix-has-tag))
21808 (setq txt (replace-match "" t t txt))
21809 (setq txt (replace-match
21810 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21811 (match-string 2 txt))
21812 t t txt))))
21814 (when remove-re
21815 (while (string-match remove-re txt)
21816 (setq txt (replace-match "" t t txt))))
21818 ;; Create the final string
21819 (if noprefix
21820 (setq rtn txt)
21821 ;; Prepare the variables needed in the eval of the compiled format
21822 (setq time (cond (s2 (concat s1 "-" s2))
21823 (s1 (concat s1 "......"))
21824 (t ""))
21825 extra (or extra "")
21826 category (if (symbolp category) (symbol-name category) category))
21827 ;; Evaluate the compiled format
21828 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21830 ;; And finally add the text properties
21831 (org-add-props rtn nil
21832 'org-category (downcase category) 'tags tags
21833 'org-highest-priority org-highest-priority
21834 'org-lowest-priority org-lowest-priority
21835 'prefix-length (- (length rtn) (length txt))
21836 'time-of-day time-of-day
21837 'txt txt
21838 'time time
21839 'extra extra
21840 'dotime dotime))))
21842 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21843 (defvar org-agenda-sorting-strategy-selected nil)
21845 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21846 (catch 'exit
21847 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21848 ((and todayp (member 'today (car org-agenda-time-grid))))
21849 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21850 ((member 'weekly (car org-agenda-time-grid)))
21851 (t (throw 'exit list)))
21852 (let* ((have (delq nil (mapcar
21853 (lambda (x) (get-text-property 1 'time-of-day x))
21854 list)))
21855 (string (nth 1 org-agenda-time-grid))
21856 (gridtimes (nth 2 org-agenda-time-grid))
21857 (req (car org-agenda-time-grid))
21858 (remove (member 'remove-match req))
21859 new time)
21860 (if (and (member 'require-timed req) (not have))
21861 ;; don't show empty grid
21862 (throw 'exit list))
21863 (while (setq time (pop gridtimes))
21864 (unless (and remove (member time have))
21865 (setq time (int-to-string time))
21866 (push (org-format-agenda-item
21867 nil string "" nil
21868 (concat (substring time 0 -2) ":" (substring time -2)))
21869 new)
21870 (put-text-property
21871 1 (length (car new)) 'face 'org-time-grid (car new))))
21872 (if (member 'time-up org-agenda-sorting-strategy-selected)
21873 (append new list)
21874 (append list new)))))
21876 (defun org-compile-prefix-format (key)
21877 "Compile the prefix format into a Lisp form that can be evaluated.
21878 The resulting form is returned and stored in the variable
21879 `org-prefix-format-compiled'."
21880 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21881 (let ((s (cond
21882 ((stringp org-agenda-prefix-format)
21883 org-agenda-prefix-format)
21884 ((assq key org-agenda-prefix-format)
21885 (cdr (assq key org-agenda-prefix-format)))
21886 (t " %-12:c%?-12t% s")))
21887 (start 0)
21888 varform vars var e c f opt)
21889 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21890 s start)
21891 (setq var (cdr (assoc (match-string 4 s)
21892 '(("c" . category) ("t" . time) ("s" . extra)
21893 ("T" . tag))))
21894 c (or (match-string 3 s) "")
21895 opt (match-beginning 1)
21896 start (1+ (match-beginning 0)))
21897 (if (equal var 'time) (setq org-prefix-has-time t))
21898 (if (equal var 'tag) (setq org-prefix-has-tag t))
21899 (setq f (concat "%" (match-string 2 s) "s"))
21900 (if opt
21901 (setq varform
21902 `(if (equal "" ,var)
21904 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21905 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21906 (setq s (replace-match "%s" t nil s))
21907 (push varform vars))
21908 (setq vars (nreverse vars))
21909 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21911 (defun org-set-sorting-strategy (key)
21912 (if (symbolp (car org-agenda-sorting-strategy))
21913 ;; the old format
21914 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21915 (setq org-agenda-sorting-strategy-selected
21916 (or (cdr (assq key org-agenda-sorting-strategy))
21917 (cdr (assq 'agenda org-agenda-sorting-strategy))
21918 '(time-up category-keep priority-down)))))
21920 (defun org-get-time-of-day (s &optional string mod24)
21921 "Check string S for a time of day.
21922 If found, return it as a military time number between 0 and 2400.
21923 If not found, return nil.
21924 The optional STRING argument forces conversion into a 5 character wide string
21925 HH:MM."
21926 (save-match-data
21927 (when
21928 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21929 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21930 (let* ((h (string-to-number (match-string 1 s)))
21931 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21932 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21933 (am-p (equal ampm "am"))
21934 (h1 (cond ((not ampm) h)
21935 ((= h 12) (if am-p 0 12))
21936 (t (+ h (if am-p 0 12)))))
21937 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21938 (mod h1 24) h1))
21939 (t0 (+ (* 100 h2) m))
21940 (t1 (concat (if (>= h1 24) "+" " ")
21941 (if (< t0 100) "0" "")
21942 (if (< t0 10) "0" "")
21943 (int-to-string t0))))
21944 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21946 (defun org-finalize-agenda-entries (list &optional nosort)
21947 "Sort and concatenate the agenda items."
21948 (setq list (mapcar 'org-agenda-highlight-todo list))
21949 (if nosort
21950 list
21951 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21953 (defun org-agenda-highlight-todo (x)
21954 (let (re pl)
21955 (if (eq x 'line)
21956 (save-excursion
21957 (beginning-of-line 1)
21958 (setq re (get-text-property (point) 'org-todo-regexp))
21959 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21960 (when (looking-at (concat "[ \t]*\\.*" re " +"))
21961 (add-text-properties (match-beginning 0) (match-end 0)
21962 (list 'face (org-get-todo-face 0)))
21963 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
21964 (delete-region (match-beginning 1) (1- (match-end 0)))
21965 (goto-char (match-beginning 1))
21966 (insert (format org-agenda-todo-keyword-format s)))))
21967 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21968 pl (get-text-property 0 'prefix-length x))
21969 (when (and re
21970 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
21971 x (or pl 0)) pl))
21972 (add-text-properties
21973 (or (match-end 1) (match-end 0)) (match-end 0)
21974 (list 'face (org-get-todo-face (match-string 2 x)))
21976 (setq x (concat (substring x 0 (match-end 1))
21977 (format org-agenda-todo-keyword-format
21978 (match-string 2 x))
21980 (substring x (match-end 3)))))
21981 x)))
21983 (defsubst org-cmp-priority (a b)
21984 "Compare the priorities of string A and B."
21985 (let ((pa (or (get-text-property 1 'priority a) 0))
21986 (pb (or (get-text-property 1 'priority b) 0)))
21987 (cond ((> pa pb) +1)
21988 ((< pa pb) -1)
21989 (t nil))))
21991 (defsubst org-cmp-category (a b)
21992 "Compare the string values of categories of strings A and B."
21993 (let ((ca (or (get-text-property 1 'org-category a) ""))
21994 (cb (or (get-text-property 1 'org-category b) "")))
21995 (cond ((string-lessp ca cb) -1)
21996 ((string-lessp cb ca) +1)
21997 (t nil))))
21999 (defsubst org-cmp-tag (a b)
22000 "Compare the string values of categories of strings A and B."
22001 (let ((ta (car (last (get-text-property 1 'tags a))))
22002 (tb (car (last (get-text-property 1 'tags b)))))
22003 (cond ((not ta) +1)
22004 ((not tb) -1)
22005 ((string-lessp ta tb) -1)
22006 ((string-lessp tb ta) +1)
22007 (t nil))))
22009 (defsubst org-cmp-time (a b)
22010 "Compare the time-of-day values of strings A and B."
22011 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22012 (ta (or (get-text-property 1 'time-of-day a) def))
22013 (tb (or (get-text-property 1 'time-of-day b) def)))
22014 (cond ((< ta tb) -1)
22015 ((< tb ta) +1)
22016 (t nil))))
22018 (defun org-entries-lessp (a b)
22019 "Predicate for sorting agenda entries."
22020 ;; The following variables will be used when the form is evaluated.
22021 ;; So even though the compiler complains, keep them.
22022 (let* ((time-up (org-cmp-time a b))
22023 (time-down (if time-up (- time-up) nil))
22024 (priority-up (org-cmp-priority a b))
22025 (priority-down (if priority-up (- priority-up) nil))
22026 (category-up (org-cmp-category a b))
22027 (category-down (if category-up (- category-up) nil))
22028 (category-keep (if category-up +1 nil))
22029 (tag-up (org-cmp-tag a b))
22030 (tag-down (if tag-up (- tag-up) nil)))
22031 (cdr (assoc
22032 (eval (cons 'or org-agenda-sorting-strategy-selected))
22033 '((-1 . t) (1 . nil) (nil . nil))))))
22035 ;;; Agenda restriction lock
22037 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22038 "Overlay to mark the headline to which arenda commands are restricted.")
22039 (org-overlay-put org-agenda-restriction-lock-overlay
22040 'face 'org-agenda-restriction-lock)
22041 (org-overlay-put org-agenda-restriction-lock-overlay
22042 'help-echo "Agendas are currently limited to this subtree.")
22043 (org-detach-overlay org-agenda-restriction-lock-overlay)
22044 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22045 "Overlay marking the agenda restriction line in speedbar.")
22046 (org-overlay-put org-speedbar-restriction-lock-overlay
22047 'face 'org-agenda-restriction-lock)
22048 (org-overlay-put org-speedbar-restriction-lock-overlay
22049 'help-echo "Agendas are currently limited to this item.")
22050 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22052 (defun org-agenda-set-restriction-lock (&optional type)
22053 "Set restriction lock for agenda, to current subtree or file.
22054 Restriction will be the file if TYPE is `file', or if type is the
22055 universal prefix '(4), or if the cursor is before the first headline
22056 in the file. Otherwise, restriction will be to the current subtree."
22057 (interactive "P")
22058 (and (equal type '(4)) (setq type 'file))
22059 (setq type (cond
22060 (type type)
22061 ((org-at-heading-p) 'subtree)
22062 ((condition-case nil (org-back-to-heading t) (error nil))
22063 'subtree)
22064 (t 'file)))
22065 (if (eq type 'subtree)
22066 (progn
22067 (setq org-agenda-restrict t)
22068 (setq org-agenda-overriding-restriction 'subtree)
22069 (put 'org-agenda-files 'org-restrict
22070 (list (buffer-file-name (buffer-base-buffer))))
22071 (org-back-to-heading t)
22072 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22073 (move-marker org-agenda-restrict-begin (point))
22074 (move-marker org-agenda-restrict-end
22075 (save-excursion (org-end-of-subtree t)))
22076 (message "Locking agenda restriction to subtree"))
22077 (put 'org-agenda-files 'org-restrict
22078 (list (buffer-file-name (buffer-base-buffer))))
22079 (setq org-agenda-restrict nil)
22080 (setq org-agenda-overriding-restriction 'file)
22081 (move-marker org-agenda-restrict-begin nil)
22082 (move-marker org-agenda-restrict-end nil)
22083 (message "Locking agenda restriction to file"))
22084 (setq current-prefix-arg nil)
22085 (org-agenda-maybe-redo))
22087 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22088 "Remove the agenda restriction lock."
22089 (interactive "P")
22090 (org-detach-overlay org-agenda-restriction-lock-overlay)
22091 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22092 (setq org-agenda-overriding-restriction nil)
22093 (setq org-agenda-restrict nil)
22094 (put 'org-agenda-files 'org-restrict nil)
22095 (move-marker org-agenda-restrict-begin nil)
22096 (move-marker org-agenda-restrict-end nil)
22097 (setq current-prefix-arg nil)
22098 (message "Agenda restriction lock removed")
22099 (or noupdate (org-agenda-maybe-redo)))
22101 (defun org-agenda-maybe-redo ()
22102 "If there is any window showing the agenda view, update it."
22103 (let ((w (get-buffer-window org-agenda-buffer-name t))
22104 (w0 (selected-window)))
22105 (when w
22106 (select-window w)
22107 (org-agenda-redo)
22108 (select-window w0)
22109 (if org-agenda-overriding-restriction
22110 (message "Agenda view shifted to new %s restriction"
22111 org-agenda-overriding-restriction)
22112 (message "Agenda restriction lock removed")))))
22114 ;;; Agenda commands
22116 (defun org-agenda-check-type (error &rest types)
22117 "Check if agenda buffer is of allowed type.
22118 If ERROR is non-nil, throw an error, otherwise just return nil."
22119 (if (memq org-agenda-type types)
22121 (if error
22122 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22123 nil)))
22125 (defun org-agenda-quit ()
22126 "Exit agenda by removing the window or the buffer."
22127 (interactive)
22128 (let ((buf (current-buffer)))
22129 (if (not (one-window-p)) (delete-window))
22130 (kill-buffer buf)
22131 (org-agenda-reset-markers)
22132 (org-columns-remove-overlays))
22133 ;; Maybe restore the pre-agenda window configuration.
22134 (and org-agenda-restore-windows-after-quit
22135 (not (eq org-agenda-window-setup 'other-frame))
22136 org-pre-agenda-window-conf
22137 (set-window-configuration org-pre-agenda-window-conf)))
22139 (defun org-agenda-exit ()
22140 "Exit agenda by removing the window or the buffer.
22141 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22142 Org-mode buffers visited directly by the user will not be touched."
22143 (interactive)
22144 (org-release-buffers org-agenda-new-buffers)
22145 (setq org-agenda-new-buffers nil)
22146 (org-agenda-quit))
22148 (defun org-agenda-execute (arg)
22149 "Execute another agenda command, keeping same window.\\<global-map>
22150 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22151 (interactive "P")
22152 (let ((org-agenda-window-setup 'current-window))
22153 (org-agenda arg)))
22155 (defun org-save-all-org-buffers ()
22156 "Save all Org-mode buffers without user confirmation."
22157 (interactive)
22158 (message "Saving all Org-mode buffers...")
22159 (save-some-buffers t 'org-mode-p)
22160 (message "Saving all Org-mode buffers... done"))
22162 (defun org-agenda-redo ()
22163 "Rebuild Agenda.
22164 When this is the global TODO list, a prefix argument will be interpreted."
22165 (interactive)
22166 (let* ((org-agenda-keep-modes t)
22167 (line (org-current-line))
22168 (window-line (- line (org-current-line (window-start))))
22169 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22170 (message "Rebuilding agenda buffer...")
22171 (org-let lprops '(eval org-agenda-redo-command))
22172 (setq org-agenda-undo-list nil
22173 org-agenda-pending-undo-list nil)
22174 (message "Rebuilding agenda buffer...done")
22175 (goto-line line)
22176 (recenter window-line)))
22178 (defun org-agenda-goto-date (date)
22179 "Jump to DATE in agenda."
22180 (interactive (list (org-read-date)))
22181 (org-agenda-list nil date))
22183 (defun org-agenda-goto-today ()
22184 "Go to today."
22185 (interactive)
22186 (org-agenda-check-type t 'timeline 'agenda)
22187 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22188 (cond
22189 (tdpos (goto-char tdpos))
22190 ((eq org-agenda-type 'agenda)
22191 (let* ((sd (time-to-days
22192 (time-subtract (current-time)
22193 (list 0 (* 3600 org-extend-today-until) 0))))
22194 (comp (org-agenda-compute-time-span sd org-agenda-span))
22195 (org-agenda-overriding-arguments org-agenda-last-arguments))
22196 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22197 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22198 (org-agenda-redo)
22199 (org-agenda-find-same-or-today-or-agenda)))
22200 (t (error "Cannot find today")))))
22202 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22203 (goto-char
22204 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22205 (text-property-any (point-min) (point-max) 'org-today t)
22206 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22207 (point-min))))
22209 (defun org-agenda-later (arg)
22210 "Go forward in time by thee current span.
22211 With prefix ARG, go forward that many times the current span."
22212 (interactive "p")
22213 (org-agenda-check-type t 'agenda)
22214 (let* ((span org-agenda-span)
22215 (sd org-starting-day)
22216 (greg (calendar-gregorian-from-absolute sd))
22217 (cnt (get-text-property (point) 'org-day-cnt))
22218 greg2 nd)
22219 (cond
22220 ((eq span 'day)
22221 (setq sd (+ arg sd) nd 1))
22222 ((eq span 'week)
22223 (setq sd (+ (* 7 arg) sd) nd 7))
22224 ((eq span 'month)
22225 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22226 sd (calendar-absolute-from-gregorian greg2))
22227 (setcar greg2 (1+ (car greg2)))
22228 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22229 ((eq span 'year)
22230 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22231 sd (calendar-absolute-from-gregorian greg2))
22232 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22233 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22234 (let ((org-agenda-overriding-arguments
22235 (list (car org-agenda-last-arguments) sd nd t)))
22236 (org-agenda-redo)
22237 (org-agenda-find-same-or-today-or-agenda cnt))))
22239 (defun org-agenda-earlier (arg)
22240 "Go backward in time by the current span.
22241 With prefix ARG, go backward that many times the current span."
22242 (interactive "p")
22243 (org-agenda-later (- arg)))
22245 (defun org-agenda-day-view ()
22246 "Switch to daily view for agenda."
22247 (interactive)
22248 (setq org-agenda-ndays 1)
22249 (org-agenda-change-time-span 'day))
22250 (defun org-agenda-week-view ()
22251 "Switch to daily view for agenda."
22252 (interactive)
22253 (setq org-agenda-ndays 7)
22254 (org-agenda-change-time-span 'week))
22255 (defun org-agenda-month-view ()
22256 "Switch to daily view for agenda."
22257 (interactive)
22258 (org-agenda-change-time-span 'month))
22259 (defun org-agenda-year-view ()
22260 "Switch to daily view for agenda."
22261 (interactive)
22262 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22263 (org-agenda-change-time-span 'year)
22264 (error "Abort")))
22266 (defun org-agenda-change-time-span (span)
22267 "Change the agenda view to SPAN.
22268 SPAN may be `day', `week', `month', `year'."
22269 (org-agenda-check-type t 'agenda)
22270 (if (equal org-agenda-span span)
22271 (error "Viewing span is already \"%s\"" span))
22272 (let* ((sd (or (get-text-property (point) 'day)
22273 org-starting-day))
22274 (computed (org-agenda-compute-time-span sd span))
22275 (org-agenda-overriding-arguments
22276 (list (car org-agenda-last-arguments)
22277 (car computed) (cdr computed) t)))
22278 (org-agenda-redo)
22279 (org-agenda-find-same-or-today-or-agenda))
22280 (org-agenda-set-mode-name)
22281 (message "Switched to %s view" span))
22283 (defun org-agenda-compute-time-span (sd span)
22284 "Compute starting date and number of days for agenda.
22285 SPAN may be `day', `week', `month', `year'. The return value
22286 is a cons cell with the starting date and the number of days,
22287 so that the date SD will be in that range."
22288 (let* ((greg (calendar-gregorian-from-absolute sd))
22290 (cond
22291 ((eq span 'day)
22292 (setq nd 1))
22293 ((eq span 'week)
22294 (let* ((nt (calendar-day-of-week
22295 (calendar-gregorian-from-absolute sd)))
22296 (d (if org-agenda-start-on-weekday
22297 (- nt org-agenda-start-on-weekday)
22298 0)))
22299 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22300 (setq nd 7)))
22301 ((eq span 'month)
22302 (setq sd (calendar-absolute-from-gregorian
22303 (list (car greg) 1 (nth 2 greg)))
22304 nd (- (calendar-absolute-from-gregorian
22305 (list (1+ (car greg)) 1 (nth 2 greg)))
22306 sd)))
22307 ((eq span 'year)
22308 (setq sd (calendar-absolute-from-gregorian
22309 (list 1 1 (nth 2 greg)))
22310 nd (- (calendar-absolute-from-gregorian
22311 (list 1 1 (1+ (nth 2 greg))))
22312 sd))))
22313 (cons sd nd)))
22315 ;; FIXME: does not work if user makes date format that starts with a blank
22316 (defun org-agenda-next-date-line (&optional arg)
22317 "Jump to the next line indicating a date in agenda buffer."
22318 (interactive "p")
22319 (org-agenda-check-type t 'agenda 'timeline)
22320 (beginning-of-line 1)
22321 (if (looking-at "^\\S-") (forward-char 1))
22322 (if (not (re-search-forward "^\\S-" nil t arg))
22323 (progn
22324 (backward-char 1)
22325 (error "No next date after this line in this buffer")))
22326 (goto-char (match-beginning 0)))
22328 (defun org-agenda-previous-date-line (&optional arg)
22329 "Jump to the previous line indicating a date in agenda buffer."
22330 (interactive "p")
22331 (org-agenda-check-type t 'agenda 'timeline)
22332 (beginning-of-line 1)
22333 (if (not (re-search-backward "^\\S-" nil t arg))
22334 (error "No previous date before this line in this buffer")))
22336 ;; Initialize the highlight
22337 (defvar org-hl (org-make-overlay 1 1))
22338 (org-overlay-put org-hl 'face 'highlight)
22340 (defun org-highlight (begin end &optional buffer)
22341 "Highlight a region with overlay."
22342 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22343 org-hl begin end (or buffer (current-buffer))))
22345 (defun org-unhighlight ()
22346 "Detach overlay INDEX."
22347 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22349 ;; FIXME this is currently not used.
22350 (defun org-highlight-until-next-command (beg end &optional buffer)
22351 (org-highlight beg end buffer)
22352 (add-hook 'pre-command-hook 'org-unhighlight-once))
22353 (defun org-unhighlight-once ()
22354 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22355 (org-unhighlight))
22357 (defun org-agenda-follow-mode ()
22358 "Toggle follow mode in an agenda buffer."
22359 (interactive)
22360 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22361 (org-agenda-set-mode-name)
22362 (message "Follow mode is %s"
22363 (if org-agenda-follow-mode "on" "off")))
22365 (defun org-agenda-log-mode ()
22366 "Toggle log mode in an agenda buffer."
22367 (interactive)
22368 (org-agenda-check-type t 'agenda 'timeline)
22369 (setq org-agenda-show-log (not org-agenda-show-log))
22370 (org-agenda-set-mode-name)
22371 (org-agenda-redo)
22372 (message "Log mode is %s"
22373 (if org-agenda-show-log "on" "off")))
22375 (defun org-agenda-toggle-diary ()
22376 "Toggle diary inclusion in an agenda buffer."
22377 (interactive)
22378 (org-agenda-check-type t 'agenda)
22379 (setq org-agenda-include-diary (not org-agenda-include-diary))
22380 (org-agenda-redo)
22381 (org-agenda-set-mode-name)
22382 (message "Diary inclusion turned %s"
22383 (if org-agenda-include-diary "on" "off")))
22385 (defun org-agenda-toggle-time-grid ()
22386 "Toggle time grid in an agenda buffer."
22387 (interactive)
22388 (org-agenda-check-type t 'agenda)
22389 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22390 (org-agenda-redo)
22391 (org-agenda-set-mode-name)
22392 (message "Time-grid turned %s"
22393 (if org-agenda-use-time-grid "on" "off")))
22395 (defun org-agenda-set-mode-name ()
22396 "Set the mode name to indicate all the small mode settings."
22397 (setq mode-name
22398 (concat "Org-Agenda"
22399 (if (equal org-agenda-ndays 1) " Day" "")
22400 (if (equal org-agenda-ndays 7) " Week" "")
22401 (if org-agenda-follow-mode " Follow" "")
22402 (if org-agenda-include-diary " Diary" "")
22403 (if org-agenda-use-time-grid " Grid" "")
22404 (if org-agenda-show-log " Log" "")))
22405 (force-mode-line-update))
22407 (defun org-agenda-post-command-hook ()
22408 (and (eolp) (not (bolp)) (backward-char 1))
22409 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22410 (if (and org-agenda-follow-mode
22411 (get-text-property (point) 'org-marker))
22412 (org-agenda-show)))
22414 (defun org-agenda-show-priority ()
22415 "Show the priority of the current item.
22416 This priority is composed of the main priority given with the [#A] cookies,
22417 and by additional input from the age of a schedules or deadline entry."
22418 (interactive)
22419 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22420 (message "Priority is %d" (if pri pri -1000))))
22422 (defun org-agenda-show-tags ()
22423 "Show the tags applicable to the current item."
22424 (interactive)
22425 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22426 (if tags
22427 (message "Tags are :%s:"
22428 (org-no-properties (mapconcat 'identity tags ":")))
22429 (message "No tags associated with this line"))))
22431 (defun org-agenda-goto (&optional highlight)
22432 "Go to the Org-mode file which contains the item at point."
22433 (interactive)
22434 (let* ((marker (or (get-text-property (point) 'org-marker)
22435 (org-agenda-error)))
22436 (buffer (marker-buffer marker))
22437 (pos (marker-position marker)))
22438 (switch-to-buffer-other-window buffer)
22439 (widen)
22440 (goto-char pos)
22441 (when (org-mode-p)
22442 (org-show-context 'agenda)
22443 (save-excursion
22444 (and (outline-next-heading)
22445 (org-flag-heading nil)))) ; show the next heading
22446 (recenter (/ (window-height) 2))
22447 (run-hooks 'org-agenda-after-show-hook)
22448 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22450 (defvar org-agenda-after-show-hook nil
22451 "Normal hook run after an item has been shown from the agenda.
22452 Point is in the buffer where the item originated.")
22454 (defun org-agenda-kill ()
22455 "Kill the entry or subtree belonging to the current agenda entry."
22456 (interactive)
22457 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22458 (let* ((marker (or (get-text-property (point) 'org-marker)
22459 (org-agenda-error)))
22460 (buffer (marker-buffer marker))
22461 (pos (marker-position marker))
22462 (type (get-text-property (point) 'type))
22463 dbeg dend (n 0) conf)
22464 (org-with-remote-undo buffer
22465 (with-current-buffer buffer
22466 (save-excursion
22467 (goto-char pos)
22468 (if (and (org-mode-p) (not (member type '("sexp"))))
22469 (setq dbeg (progn (org-back-to-heading t) (point))
22470 dend (org-end-of-subtree t t))
22471 (setq dbeg (point-at-bol)
22472 dend (min (point-max) (1+ (point-at-eol)))))
22473 (goto-char dbeg)
22474 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22475 (setq conf (or (eq t org-agenda-confirm-kill)
22476 (and (numberp org-agenda-confirm-kill)
22477 (> n org-agenda-confirm-kill))))
22478 (and conf
22479 (not (y-or-n-p
22480 (format "Delete entry with %d lines in buffer \"%s\"? "
22481 n (buffer-name buffer))))
22482 (error "Abort"))
22483 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22484 (with-current-buffer buffer (delete-region dbeg dend))
22485 (message "Agenda item and source killed"))))
22487 (defun org-agenda-archive ()
22488 "Kill the entry or subtree belonging to the current agenda entry."
22489 (interactive)
22490 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22491 (let* ((marker (or (get-text-property (point) 'org-marker)
22492 (org-agenda-error)))
22493 (buffer (marker-buffer marker))
22494 (pos (marker-position marker)))
22495 (org-with-remote-undo buffer
22496 (with-current-buffer buffer
22497 (if (org-mode-p)
22498 (save-excursion
22499 (goto-char pos)
22500 (org-remove-subtree-entries-from-agenda)
22501 (org-back-to-heading t)
22502 (org-archive-subtree))
22503 (error "Archiving works only in Org-mode files"))))))
22505 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22506 "Remove all lines in the agenda that correspond to a given subtree.
22507 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22508 If this information is not given, the function uses the tree at point."
22509 (let ((buf (or buf (current-buffer))) m p)
22510 (save-excursion
22511 (unless (and beg end)
22512 (org-back-to-heading t)
22513 (setq beg (point))
22514 (org-end-of-subtree t)
22515 (setq end (point)))
22516 (set-buffer (get-buffer org-agenda-buffer-name))
22517 (save-excursion
22518 (goto-char (point-max))
22519 (beginning-of-line 1)
22520 (while (not (bobp))
22521 (when (and (setq m (get-text-property (point) 'org-marker))
22522 (equal buf (marker-buffer m))
22523 (setq p (marker-position m))
22524 (>= p beg)
22525 (<= p end))
22526 (let ((inhibit-read-only t))
22527 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22528 (beginning-of-line 0))))))
22530 (defun org-agenda-open-link ()
22531 "Follow the link in the current line, if any."
22532 (interactive)
22533 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22534 (save-excursion
22535 (save-restriction
22536 (narrow-to-region (point-at-bol) (point-at-eol))
22537 (org-open-at-point))))
22539 (defun org-agenda-copy-local-variable (var)
22540 "Get a variable from a referenced buffer and install it here."
22541 (let ((m (get-text-property (point) 'org-marker)))
22542 (when (and m (buffer-live-p (marker-buffer m)))
22543 (org-set-local var (with-current-buffer (marker-buffer m)
22544 (symbol-value var))))))
22546 (defun org-agenda-switch-to (&optional delete-other-windows)
22547 "Go to the Org-mode file which contains the item at point."
22548 (interactive)
22549 (let* ((marker (or (get-text-property (point) 'org-marker)
22550 (org-agenda-error)))
22551 (buffer (marker-buffer marker))
22552 (pos (marker-position marker)))
22553 (switch-to-buffer buffer)
22554 (and delete-other-windows (delete-other-windows))
22555 (widen)
22556 (goto-char pos)
22557 (when (org-mode-p)
22558 (org-show-context 'agenda)
22559 (save-excursion
22560 (and (outline-next-heading)
22561 (org-flag-heading nil)))))) ; show the next heading
22563 (defun org-agenda-goto-mouse (ev)
22564 "Go to the Org-mode file which contains the item at the mouse click."
22565 (interactive "e")
22566 (mouse-set-point ev)
22567 (org-agenda-goto))
22569 (defun org-agenda-show ()
22570 "Display the Org-mode file which contains the item at point."
22571 (interactive)
22572 (let ((win (selected-window)))
22573 (org-agenda-goto t)
22574 (select-window win)))
22576 (defun org-agenda-recenter (arg)
22577 "Display the Org-mode file which contains the item at point and recenter."
22578 (interactive "P")
22579 (let ((win (selected-window)))
22580 (org-agenda-goto t)
22581 (recenter arg)
22582 (select-window win)))
22584 (defun org-agenda-show-mouse (ev)
22585 "Display the Org-mode file which contains the item at the mouse click."
22586 (interactive "e")
22587 (mouse-set-point ev)
22588 (org-agenda-show))
22590 (defun org-agenda-check-no-diary ()
22591 "Check if the entry is a diary link and abort if yes."
22592 (if (get-text-property (point) 'org-agenda-diary-link)
22593 (org-agenda-error)))
22595 (defun org-agenda-error ()
22596 (error "Command not allowed in this line"))
22598 (defun org-agenda-tree-to-indirect-buffer ()
22599 "Show the subtree corresponding to the current entry in an indirect buffer.
22600 This calls the command `org-tree-to-indirect-buffer' from the original
22601 Org-mode buffer.
22602 With numerical prefix arg ARG, go up to this level and then take that tree.
22603 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22604 dedicated frame)."
22605 (interactive)
22606 (org-agenda-check-no-diary)
22607 (let* ((marker (or (get-text-property (point) 'org-marker)
22608 (org-agenda-error)))
22609 (buffer (marker-buffer marker))
22610 (pos (marker-position marker)))
22611 (with-current-buffer buffer
22612 (save-excursion
22613 (goto-char pos)
22614 (call-interactively 'org-tree-to-indirect-buffer)))))
22616 (defvar org-last-heading-marker (make-marker)
22617 "Marker pointing to the headline that last changed its TODO state
22618 by a remote command from the agenda.")
22620 (defun org-agenda-todo-nextset ()
22621 "Switch TODO entry to next sequence."
22622 (interactive)
22623 (org-agenda-todo 'nextset))
22625 (defun org-agenda-todo-previousset ()
22626 "Switch TODO entry to previous sequence."
22627 (interactive)
22628 (org-agenda-todo 'previousset))
22630 (defun org-agenda-todo (&optional arg)
22631 "Cycle TODO state of line at point, also in Org-mode file.
22632 This changes the line at point, all other lines in the agenda referring to
22633 the same tree node, and the headline of the tree node in the Org-mode file."
22634 (interactive "P")
22635 (org-agenda-check-no-diary)
22636 (let* ((col (current-column))
22637 (marker (or (get-text-property (point) 'org-marker)
22638 (org-agenda-error)))
22639 (buffer (marker-buffer marker))
22640 (pos (marker-position marker))
22641 (hdmarker (get-text-property (point) 'org-hd-marker))
22642 (inhibit-read-only t)
22643 newhead)
22644 (org-with-remote-undo buffer
22645 (with-current-buffer buffer
22646 (widen)
22647 (goto-char pos)
22648 (org-show-context 'agenda)
22649 (save-excursion
22650 (and (outline-next-heading)
22651 (org-flag-heading nil))) ; show the next heading
22652 (org-todo arg)
22653 (and (bolp) (forward-char 1))
22654 (setq newhead (org-get-heading))
22655 (save-excursion
22656 (org-back-to-heading)
22657 (move-marker org-last-heading-marker (point))))
22658 (beginning-of-line 1)
22659 (save-excursion
22660 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22661 (move-to-column col))))
22663 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22664 "Change all lines in the agenda buffer which match HDMARKER.
22665 The new content of the line will be NEWHEAD (as modified by
22666 `org-format-agenda-item'). HDMARKER is checked with
22667 `equal' against all `org-hd-marker' text properties in the file.
22668 If FIXFACE is non-nil, the face of each item is modified acording to
22669 the new TODO state."
22670 (let* ((inhibit-read-only t)
22671 props m pl undone-face done-face finish new dotime cat tags)
22672 (save-excursion
22673 (goto-char (point-max))
22674 (beginning-of-line 1)
22675 (while (not finish)
22676 (setq finish (bobp))
22677 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22678 (equal m hdmarker))
22679 (setq props (text-properties-at (point))
22680 dotime (get-text-property (point) 'dotime)
22681 cat (get-text-property (point) 'org-category)
22682 tags (get-text-property (point) 'tags)
22683 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22684 pl (get-text-property (point) 'prefix-length)
22685 undone-face (get-text-property (point) 'undone-face)
22686 done-face (get-text-property (point) 'done-face))
22687 (move-to-column pl)
22688 (cond
22689 ((equal new "")
22690 (beginning-of-line 1)
22691 (and (looking-at ".*\n?") (replace-match "")))
22692 ((looking-at ".*")
22693 (replace-match new t t)
22694 (beginning-of-line 1)
22695 (add-text-properties (point-at-bol) (point-at-eol) props)
22696 (when fixface
22697 (add-text-properties
22698 (point-at-bol) (point-at-eol)
22699 (list 'face
22700 (if org-last-todo-state-is-todo
22701 undone-face done-face))))
22702 (org-agenda-highlight-todo 'line)
22703 (beginning-of-line 1))
22704 (t (error "Line update did not work"))))
22705 (beginning-of-line 0)))
22706 (org-finalize-agenda)))
22708 (defun org-agenda-align-tags (&optional line)
22709 "Align all tags in agenda items to `org-agenda-tags-column'."
22710 (let ((inhibit-read-only t) l c)
22711 (save-excursion
22712 (goto-char (if line (point-at-bol) (point-min)))
22713 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22714 (if line (point-at-eol) nil) t)
22715 (add-text-properties
22716 (match-beginning 2) (match-end 2)
22717 (list 'face (list 'org-tag (get-text-property
22718 (match-beginning 2) 'face))))
22719 (setq l (- (match-end 2) (match-beginning 2))
22720 c (if (< org-agenda-tags-column 0)
22721 (- (abs org-agenda-tags-column) l)
22722 org-agenda-tags-column))
22723 (delete-region (match-beginning 1) (match-end 1))
22724 (goto-char (match-beginning 1))
22725 (insert (org-add-props
22726 (make-string (max 1 (- c (current-column))) ?\ )
22727 (text-properties-at (point))))))))
22729 (defun org-agenda-priority-up ()
22730 "Increase the priority of line at point, also in Org-mode file."
22731 (interactive)
22732 (org-agenda-priority 'up))
22734 (defun org-agenda-priority-down ()
22735 "Decrease the priority of line at point, also in Org-mode file."
22736 (interactive)
22737 (org-agenda-priority 'down))
22739 (defun org-agenda-priority (&optional force-direction)
22740 "Set the priority of line at point, also in Org-mode file.
22741 This changes the line at point, all other lines in the agenda referring to
22742 the same tree node, and the headline of the tree node in the Org-mode file."
22743 (interactive)
22744 (org-agenda-check-no-diary)
22745 (let* ((marker (or (get-text-property (point) 'org-marker)
22746 (org-agenda-error)))
22747 (hdmarker (get-text-property (point) 'org-hd-marker))
22748 (buffer (marker-buffer hdmarker))
22749 (pos (marker-position hdmarker))
22750 (inhibit-read-only t)
22751 newhead)
22752 (org-with-remote-undo buffer
22753 (with-current-buffer buffer
22754 (widen)
22755 (goto-char pos)
22756 (org-show-context 'agenda)
22757 (save-excursion
22758 (and (outline-next-heading)
22759 (org-flag-heading nil))) ; show the next heading
22760 (funcall 'org-priority force-direction)
22761 (end-of-line 1)
22762 (setq newhead (org-get-heading)))
22763 (org-agenda-change-all-lines newhead hdmarker)
22764 (beginning-of-line 1))))
22766 (defun org-get-tags-at (&optional pos)
22767 "Get a list of all headline tags applicable at POS.
22768 POS defaults to point. If tags are inherited, the list contains
22769 the targets in the same sequence as the headlines appear, i.e.
22770 the tags of the current headline come last."
22771 (interactive)
22772 (let (tags lastpos)
22773 (save-excursion
22774 (save-restriction
22775 (widen)
22776 (goto-char (or pos (point)))
22777 (save-match-data
22778 (org-back-to-heading t)
22779 (condition-case nil
22780 (while (not (equal lastpos (point)))
22781 (setq lastpos (point))
22782 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22783 (setq tags (append (org-split-string
22784 (org-match-string-no-properties 1) ":")
22785 tags)))
22786 (or org-use-tag-inheritance (error ""))
22787 (org-up-heading-all 1))
22788 (error nil))))
22789 tags)))
22791 ;; FIXME: should fix the tags property of the agenda line.
22792 (defun org-agenda-set-tags ()
22793 "Set tags for the current headline."
22794 (interactive)
22795 (org-agenda-check-no-diary)
22796 (if (and (org-region-active-p) (interactive-p))
22797 (call-interactively 'org-change-tag-in-region)
22798 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22799 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22800 (org-agenda-error)))
22801 (buffer (marker-buffer hdmarker))
22802 (pos (marker-position hdmarker))
22803 (inhibit-read-only t)
22804 newhead)
22805 (org-with-remote-undo buffer
22806 (with-current-buffer buffer
22807 (widen)
22808 (goto-char pos)
22809 (save-excursion
22810 (org-show-context 'agenda))
22811 (save-excursion
22812 (and (outline-next-heading)
22813 (org-flag-heading nil))) ; show the next heading
22814 (goto-char pos)
22815 (call-interactively 'org-set-tags)
22816 (end-of-line 1)
22817 (setq newhead (org-get-heading)))
22818 (org-agenda-change-all-lines newhead hdmarker)
22819 (beginning-of-line 1)))))
22821 (defun org-agenda-toggle-archive-tag ()
22822 "Toggle the archive tag for the current entry."
22823 (interactive)
22824 (org-agenda-check-no-diary)
22825 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22826 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22827 (org-agenda-error)))
22828 (buffer (marker-buffer hdmarker))
22829 (pos (marker-position hdmarker))
22830 (inhibit-read-only t)
22831 newhead)
22832 (org-with-remote-undo buffer
22833 (with-current-buffer buffer
22834 (widen)
22835 (goto-char pos)
22836 (org-show-context 'agenda)
22837 (save-excursion
22838 (and (outline-next-heading)
22839 (org-flag-heading nil))) ; show the next heading
22840 (call-interactively 'org-toggle-archive-tag)
22841 (end-of-line 1)
22842 (setq newhead (org-get-heading)))
22843 (org-agenda-change-all-lines newhead hdmarker)
22844 (beginning-of-line 1))))
22846 (defun org-agenda-date-later (arg &optional what)
22847 "Change the date of this item to one day later."
22848 (interactive "p")
22849 (org-agenda-check-type t 'agenda 'timeline)
22850 (org-agenda-check-no-diary)
22851 (let* ((marker (or (get-text-property (point) 'org-marker)
22852 (org-agenda-error)))
22853 (buffer (marker-buffer marker))
22854 (pos (marker-position marker)))
22855 (org-with-remote-undo buffer
22856 (with-current-buffer buffer
22857 (widen)
22858 (goto-char pos)
22859 (if (not (org-at-timestamp-p))
22860 (error "Cannot find time stamp"))
22861 (org-timestamp-change arg (or what 'day)))
22862 (org-agenda-show-new-time marker org-last-changed-timestamp))
22863 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22865 (defun org-agenda-date-earlier (arg &optional what)
22866 "Change the date of this item to one day earlier."
22867 (interactive "p")
22868 (org-agenda-date-later (- arg) what))
22870 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22871 "Show new date stamp via text properties."
22872 ;; We use text properties to make this undoable
22873 (let ((inhibit-read-only t))
22874 (setq stamp (concat " " prefix " => " stamp))
22875 (save-excursion
22876 (goto-char (point-max))
22877 (while (not (bobp))
22878 (when (equal marker (get-text-property (point) 'org-marker))
22879 (move-to-column (- (window-width) (length stamp)) t)
22880 (if (featurep 'xemacs)
22881 ;; Use `duplicable' property to trigger undo recording
22882 (let ((ex (make-extent nil nil))
22883 (gl (make-glyph stamp)))
22884 (set-glyph-face gl 'secondary-selection)
22885 (set-extent-properties
22886 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22887 (insert-extent ex (1- (point)) (point-at-eol)))
22888 (add-text-properties
22889 (1- (point)) (point-at-eol)
22890 (list 'display (org-add-props stamp nil
22891 'face 'secondary-selection))))
22892 (beginning-of-line 1))
22893 (beginning-of-line 0)))))
22895 (defun org-agenda-date-prompt (arg)
22896 "Change the date of this item. Date is prompted for, with default today.
22897 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22898 be used to request time specification in the time stamp."
22899 (interactive "P")
22900 (org-agenda-check-type t 'agenda 'timeline)
22901 (org-agenda-check-no-diary)
22902 (let* ((marker (or (get-text-property (point) 'org-marker)
22903 (org-agenda-error)))
22904 (buffer (marker-buffer marker))
22905 (pos (marker-position marker)))
22906 (org-with-remote-undo buffer
22907 (with-current-buffer buffer
22908 (widen)
22909 (goto-char pos)
22910 (if (not (org-at-timestamp-p))
22911 (error "Cannot find time stamp"))
22912 (org-time-stamp arg)
22913 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22915 (defun org-agenda-schedule (arg)
22916 "Schedule the item at point."
22917 (interactive "P")
22918 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22919 (org-agenda-check-no-diary)
22920 (let* ((marker (or (get-text-property (point) 'org-marker)
22921 (org-agenda-error)))
22922 (buffer (marker-buffer marker))
22923 (pos (marker-position marker))
22924 (org-insert-labeled-timestamps-at-point nil)
22926 (message "%s" (marker-insertion-type marker)) (sit-for 3)
22927 (set-marker-insertion-type marker t)
22928 (org-with-remote-undo buffer
22929 (with-current-buffer buffer
22930 (widen)
22931 (goto-char pos)
22932 (setq ts (org-schedule arg)))
22933 (org-agenda-show-new-time marker ts "S"))
22934 (message "Item scheduled for %s" ts)))
22936 (defun org-agenda-deadline (arg)
22937 "Schedule the item at point."
22938 (interactive "P")
22939 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22940 (org-agenda-check-no-diary)
22941 (let* ((marker (or (get-text-property (point) 'org-marker)
22942 (org-agenda-error)))
22943 (buffer (marker-buffer marker))
22944 (pos (marker-position marker))
22945 (org-insert-labeled-timestamps-at-point nil)
22947 (org-with-remote-undo buffer
22948 (with-current-buffer buffer
22949 (widen)
22950 (goto-char pos)
22951 (setq ts (org-deadline arg)))
22952 (org-agenda-show-new-time marker ts "S"))
22953 (message "Deadline for this item set to %s" ts)))
22955 (defun org-get-heading (&optional no-tags)
22956 "Return the heading of the current entry, without the stars."
22957 (save-excursion
22958 (org-back-to-heading t)
22959 (if (looking-at
22960 (if no-tags
22961 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22962 "\\*+[ \t]+\\([^\r\n]*\\)"))
22963 (match-string 1) "")))
22965 (defun org-agenda-clock-in (&optional arg)
22966 "Start the clock on the currently selected item."
22967 (interactive "P")
22968 (org-agenda-check-no-diary)
22969 (let* ((marker (or (get-text-property (point) 'org-marker)
22970 (org-agenda-error)))
22971 (pos (marker-position marker)))
22972 (org-with-remote-undo (marker-buffer marker)
22973 (with-current-buffer (marker-buffer marker)
22974 (widen)
22975 (goto-char pos)
22976 (org-clock-in)))))
22978 (defun org-agenda-clock-out (&optional arg)
22979 "Stop the currently running clock."
22980 (interactive "P")
22981 (unless (marker-buffer org-clock-marker)
22982 (error "No running clock"))
22983 (org-with-remote-undo (marker-buffer org-clock-marker)
22984 (org-clock-out)))
22986 (defun org-agenda-clock-cancel (&optional arg)
22987 "Cancel the currently running clock."
22988 (interactive "P")
22989 (unless (marker-buffer org-clock-marker)
22990 (error "No running clock"))
22991 (org-with-remote-undo (marker-buffer org-clock-marker)
22992 (org-clock-cancel)))
22994 (defun org-agenda-diary-entry ()
22995 "Make a diary entry, like the `i' command from the calendar.
22996 All the standard commands work: block, weekly etc."
22997 (interactive)
22998 (org-agenda-check-type t 'agenda 'timeline)
22999 (require 'diary-lib)
23000 (let* ((char (progn
23001 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23002 (read-char-exclusive)))
23003 (cmd (cdr (assoc char
23004 '((?d . insert-diary-entry)
23005 (?w . insert-weekly-diary-entry)
23006 (?m . insert-monthly-diary-entry)
23007 (?y . insert-yearly-diary-entry)
23008 (?a . insert-anniversary-diary-entry)
23009 (?b . insert-block-diary-entry)
23010 (?c . insert-cyclic-diary-entry)))))
23011 (oldf (symbol-function 'calendar-cursor-to-date))
23012 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23013 (point (point))
23014 (mark (or (mark t) (point))))
23015 (unless cmd
23016 (error "No command associated with <%c>" char))
23017 (unless (and (get-text-property point 'day)
23018 (or (not (equal ?b char))
23019 (get-text-property mark 'day)))
23020 (error "Don't know which date to use for diary entry"))
23021 ;; We implement this by hacking the `calendar-cursor-to-date' function
23022 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23023 (let ((calendar-mark-ring
23024 (list (calendar-gregorian-from-absolute
23025 (or (get-text-property mark 'day)
23026 (get-text-property point 'day))))))
23027 (unwind-protect
23028 (progn
23029 (fset 'calendar-cursor-to-date
23030 (lambda (&optional error)
23031 (calendar-gregorian-from-absolute
23032 (get-text-property point 'day))))
23033 (call-interactively cmd))
23034 (fset 'calendar-cursor-to-date oldf)))))
23037 (defun org-agenda-execute-calendar-command (cmd)
23038 "Execute a calendar command from the agenda, with the date associated to
23039 the cursor position."
23040 (org-agenda-check-type t 'agenda 'timeline)
23041 (require 'diary-lib)
23042 (unless (get-text-property (point) 'day)
23043 (error "Don't know which date to use for calendar command"))
23044 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23045 (point (point))
23046 (date (calendar-gregorian-from-absolute
23047 (get-text-property point 'day)))
23048 ;; the following 3 vars are needed in the calendar
23049 (displayed-day (extract-calendar-day date))
23050 (displayed-month (extract-calendar-month date))
23051 (displayed-year (extract-calendar-year date)))
23052 (unwind-protect
23053 (progn
23054 (fset 'calendar-cursor-to-date
23055 (lambda (&optional error)
23056 (calendar-gregorian-from-absolute
23057 (get-text-property point 'day))))
23058 (call-interactively cmd))
23059 (fset 'calendar-cursor-to-date oldf))))
23061 (defun org-agenda-phases-of-moon ()
23062 "Display the phases of the moon for the 3 months around the cursor date."
23063 (interactive)
23064 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23066 (defun org-agenda-holidays ()
23067 "Display the holidays for the 3 months around the cursor date."
23068 (interactive)
23069 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23071 (defun org-agenda-sunrise-sunset (arg)
23072 "Display sunrise and sunset for the cursor date.
23073 Latitude and longitude can be specified with the variables
23074 `calendar-latitude' and `calendar-longitude'. When called with prefix
23075 argument, latitude and longitude will be prompted for."
23076 (interactive "P")
23077 (let ((calendar-longitude (if arg nil calendar-longitude))
23078 (calendar-latitude (if arg nil calendar-latitude))
23079 (calendar-location-name
23080 (if arg "the given coordinates" calendar-location-name)))
23081 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23083 (defun org-agenda-goto-calendar ()
23084 "Open the Emacs calendar with the date at the cursor."
23085 (interactive)
23086 (org-agenda-check-type t 'agenda 'timeline)
23087 (let* ((day (or (get-text-property (point) 'day)
23088 (error "Don't know which date to open in calendar")))
23089 (date (calendar-gregorian-from-absolute day))
23090 (calendar-move-hook nil)
23091 (view-calendar-holidays-initially nil)
23092 (view-diary-entries-initially nil))
23093 (calendar)
23094 (calendar-goto-date date)))
23096 (defun org-calendar-goto-agenda ()
23097 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23098 This is a command that has to be installed in `calendar-mode-map'."
23099 (interactive)
23100 (org-agenda-list nil (calendar-absolute-from-gregorian
23101 (calendar-cursor-to-date))
23102 nil))
23104 (defun org-agenda-convert-date ()
23105 (interactive)
23106 (org-agenda-check-type t 'agenda 'timeline)
23107 (let ((day (get-text-property (point) 'day))
23108 date s)
23109 (unless day
23110 (error "Don't know which date to convert"))
23111 (setq date (calendar-gregorian-from-absolute day))
23112 (setq s (concat
23113 "Gregorian: " (calendar-date-string date) "\n"
23114 "ISO: " (calendar-iso-date-string date) "\n"
23115 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23116 "Julian: " (calendar-julian-date-string date) "\n"
23117 "Astron. JD: " (calendar-astro-date-string date)
23118 " (Julian date number at noon UTC)\n"
23119 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23120 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23121 "French: " (calendar-french-date-string date) "\n"
23122 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23123 "Mayan: " (calendar-mayan-date-string date) "\n"
23124 "Coptic: " (calendar-coptic-date-string date) "\n"
23125 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23126 "Persian: " (calendar-persian-date-string date) "\n"
23127 "Chinese: " (calendar-chinese-date-string date) "\n"))
23128 (with-output-to-temp-buffer "*Dates*"
23129 (princ s))
23130 (if (fboundp 'fit-window-to-buffer)
23131 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23134 ;;;; Embedded LaTeX
23136 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23137 "Keymap for the minor `org-cdlatex-mode'.")
23139 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23140 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23141 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23142 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23143 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23145 (defvar org-cdlatex-texmathp-advice-is-done nil
23146 "Flag remembering if we have applied the advice to texmathp already.")
23148 (define-minor-mode org-cdlatex-mode
23149 "Toggle the minor `org-cdlatex-mode'.
23150 This mode supports entering LaTeX environment and math in LaTeX fragments
23151 in Org-mode.
23152 \\{org-cdlatex-mode-map}"
23153 nil " OCDL" nil
23154 (when org-cdlatex-mode (require 'cdlatex))
23155 (unless org-cdlatex-texmathp-advice-is-done
23156 (setq org-cdlatex-texmathp-advice-is-done t)
23157 (defadvice texmathp (around org-math-always-on activate)
23158 "Always return t in org-mode buffers.
23159 This is because we want to insert math symbols without dollars even outside
23160 the LaTeX math segments. If Orgmode thinks that point is actually inside
23161 en embedded LaTeX fragement, let texmathp do its job.
23162 \\[org-cdlatex-mode-map]"
23163 (interactive)
23164 (let (p)
23165 (cond
23166 ((not (org-mode-p)) ad-do-it)
23167 ((eq this-command 'cdlatex-math-symbol)
23168 (setq ad-return-value t
23169 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23171 (let ((p (org-inside-LaTeX-fragment-p)))
23172 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23173 (setq ad-return-value t
23174 texmathp-why '("Org-mode embedded math" . 0))
23175 (if p ad-do-it)))))))))
23177 (defun turn-on-org-cdlatex ()
23178 "Unconditionally turn on `org-cdlatex-mode'."
23179 (org-cdlatex-mode 1))
23181 (defun org-inside-LaTeX-fragment-p ()
23182 "Test if point is inside a LaTeX fragment.
23183 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23184 sequence appearing also before point.
23185 Even though the matchers for math are configurable, this function assumes
23186 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23187 delimiters are skipped when they have been removed by customization.
23188 The return value is nil, or a cons cell with the delimiter and
23189 and the position of this delimiter.
23191 This function does a reasonably good job, but can locally be fooled by
23192 for example currency specifications. For example it will assume being in
23193 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23194 fragments that are properly closed, but during editing, we have to live
23195 with the uncertainty caused by missing closing delimiters. This function
23196 looks only before point, not after."
23197 (catch 'exit
23198 (let ((pos (point))
23199 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23200 (lim (progn
23201 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23202 (point)))
23203 dd-on str (start 0) m re)
23204 (goto-char pos)
23205 (when dodollar
23206 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23207 re (nth 1 (assoc "$" org-latex-regexps)))
23208 (while (string-match re str start)
23209 (cond
23210 ((= (match-end 0) (length str))
23211 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23212 ((= (match-end 0) (- (length str) 5))
23213 (throw 'exit nil))
23214 (t (setq start (match-end 0))))))
23215 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23216 (goto-char pos)
23217 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23218 (and (match-beginning 2) (throw 'exit nil))
23219 ;; count $$
23220 (while (re-search-backward "\\$\\$" lim t)
23221 (setq dd-on (not dd-on)))
23222 (goto-char pos)
23223 (if dd-on (cons "$$" m))))))
23226 (defun org-try-cdlatex-tab ()
23227 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23228 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23229 - inside a LaTeX fragment, or
23230 - after the first word in a line, where an abbreviation expansion could
23231 insert a LaTeX environment."
23232 (when org-cdlatex-mode
23233 (cond
23234 ((save-excursion
23235 (skip-chars-backward "a-zA-Z0-9*")
23236 (skip-chars-backward " \t")
23237 (bolp))
23238 (cdlatex-tab) t)
23239 ((org-inside-LaTeX-fragment-p)
23240 (cdlatex-tab) t)
23241 (t nil))))
23243 (defun org-cdlatex-underscore-caret (&optional arg)
23244 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23245 Revert to the normal definition outside of these fragments."
23246 (interactive "P")
23247 (if (org-inside-LaTeX-fragment-p)
23248 (call-interactively 'cdlatex-sub-superscript)
23249 (let (org-cdlatex-mode)
23250 (call-interactively (key-binding (vector last-input-event))))))
23252 (defun org-cdlatex-math-modify (&optional arg)
23253 "Execute `cdlatex-math-modify' in LaTeX fragments.
23254 Revert to the normal definition outside of these fragments."
23255 (interactive "P")
23256 (if (org-inside-LaTeX-fragment-p)
23257 (call-interactively 'cdlatex-math-modify)
23258 (let (org-cdlatex-mode)
23259 (call-interactively (key-binding (vector last-input-event))))))
23261 (defvar org-latex-fragment-image-overlays nil
23262 "List of overlays carrying the images of latex fragments.")
23263 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23265 (defun org-remove-latex-fragment-image-overlays ()
23266 "Remove all overlays with LaTeX fragment images in current buffer."
23267 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23268 (setq org-latex-fragment-image-overlays nil))
23270 (defun org-preview-latex-fragment (&optional subtree)
23271 "Preview the LaTeX fragment at point, or all locally or globally.
23272 If the cursor is in a LaTeX fragment, create the image and overlay
23273 it over the source code. If there is no fragment at point, display
23274 all fragments in the current text, from one headline to the next. With
23275 prefix SUBTREE, display all fragments in the current subtree. With a
23276 double prefix `C-u C-u', or when the cursor is before the first headline,
23277 display all fragments in the buffer.
23278 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23279 (interactive "P")
23280 (org-remove-latex-fragment-image-overlays)
23281 (save-excursion
23282 (save-restriction
23283 (let (beg end at msg)
23284 (cond
23285 ((or (equal subtree '(16))
23286 (not (save-excursion
23287 (re-search-backward (concat "^" outline-regexp) nil t))))
23288 (setq beg (point-min) end (point-max)
23289 msg "Creating images for buffer...%s"))
23290 ((equal subtree '(4))
23291 (org-back-to-heading)
23292 (setq beg (point) end (org-end-of-subtree t)
23293 msg "Creating images for subtree...%s"))
23295 (if (setq at (org-inside-LaTeX-fragment-p))
23296 (goto-char (max (point-min) (- (cdr at) 2)))
23297 (org-back-to-heading))
23298 (setq beg (point) end (progn (outline-next-heading) (point))
23299 msg (if at "Creating image...%s"
23300 "Creating images for entry...%s"))))
23301 (message msg "")
23302 (narrow-to-region beg end)
23303 (goto-char beg)
23304 (org-format-latex
23305 (concat "ltxpng/" (file-name-sans-extension
23306 (file-name-nondirectory
23307 buffer-file-name)))
23308 default-directory 'overlays msg at 'forbuffer)
23309 (message msg "done. Use `C-c C-c' to remove images.")))))
23311 (defvar org-latex-regexps
23312 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23313 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23314 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23315 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23316 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23317 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23318 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23319 "Regular expressions for matching embedded LaTeX.")
23321 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23322 "Replace LaTeX fragments with links to an image, and produce images."
23323 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23324 (let* ((prefixnodir (file-name-nondirectory prefix))
23325 (absprefix (expand-file-name prefix dir))
23326 (todir (file-name-directory absprefix))
23327 (opt org-format-latex-options)
23328 (matchers (plist-get opt :matchers))
23329 (re-list org-latex-regexps)
23330 (cnt 0) txt link beg end re e checkdir
23331 m n block linkfile movefile ov)
23332 ;; Check if there are old images files with this prefix, and remove them
23333 (when (file-directory-p todir)
23334 (mapc 'delete-file
23335 (directory-files
23336 todir 'full
23337 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23338 ;; Check the different regular expressions
23339 (while (setq e (pop re-list))
23340 (setq m (car e) re (nth 1 e) n (nth 2 e)
23341 block (if (nth 3 e) "\n\n" ""))
23342 (when (member m matchers)
23343 (goto-char (point-min))
23344 (while (re-search-forward re nil t)
23345 (when (or (not at) (equal (cdr at) (match-beginning n)))
23346 (setq txt (match-string n)
23347 beg (match-beginning n) end (match-end n)
23348 cnt (1+ cnt)
23349 linkfile (format "%s_%04d.png" prefix cnt)
23350 movefile (format "%s_%04d.png" absprefix cnt)
23351 link (concat block "[[file:" linkfile "]]" block))
23352 (if msg (message msg cnt))
23353 (goto-char beg)
23354 (unless checkdir ; make sure the directory exists
23355 (setq checkdir t)
23356 (or (file-directory-p todir) (make-directory todir)))
23357 (org-create-formula-image
23358 txt movefile opt forbuffer)
23359 (if overlays
23360 (progn
23361 (setq ov (org-make-overlay beg end))
23362 (if (featurep 'xemacs)
23363 (progn
23364 (org-overlay-put ov 'invisible t)
23365 (org-overlay-put
23366 ov 'end-glyph
23367 (make-glyph (vector 'png :file movefile))))
23368 (org-overlay-put
23369 ov 'display
23370 (list 'image :type 'png :file movefile :ascent 'center)))
23371 (push ov org-latex-fragment-image-overlays)
23372 (goto-char end))
23373 (delete-region beg end)
23374 (insert link))))))))
23376 ;; This function borrows from Ganesh Swami's latex2png.el
23377 (defun org-create-formula-image (string tofile options buffer)
23378 (let* ((tmpdir (if (featurep 'xemacs)
23379 (temp-directory)
23380 temporary-file-directory))
23381 (texfilebase (make-temp-name
23382 (expand-file-name "orgtex" tmpdir)))
23383 (texfile (concat texfilebase ".tex"))
23384 (dvifile (concat texfilebase ".dvi"))
23385 (pngfile (concat texfilebase ".png"))
23386 (fnh (face-attribute 'default :height nil))
23387 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23388 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23389 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23390 "Black"))
23391 (bg (or (plist-get options (if buffer :background :html-background))
23392 "Transparent")))
23393 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23394 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23395 (with-temp-file texfile
23396 (insert org-format-latex-header
23397 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23398 (let ((dir default-directory))
23399 (condition-case nil
23400 (progn
23401 (cd tmpdir)
23402 (call-process "latex" nil nil nil texfile))
23403 (error nil))
23404 (cd dir))
23405 (if (not (file-exists-p dvifile))
23406 (progn (message "Failed to create dvi file from %s" texfile) nil)
23407 (call-process "dvipng" nil nil nil
23408 "-E" "-fg" fg "-bg" bg
23409 "-D" dpi
23410 ;;"-x" scale "-y" scale
23411 "-T" "tight"
23412 "-o" pngfile
23413 dvifile)
23414 (if (not (file-exists-p pngfile))
23415 (progn (message "Failed to create png file from %s" texfile) nil)
23416 ;; Use the requested file name and clean up
23417 (copy-file pngfile tofile 'replace)
23418 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23419 (delete-file (concat texfilebase e)))
23420 pngfile))))
23422 (defun org-dvipng-color (attr)
23423 "Return an rgb color specification for dvipng."
23424 (apply 'format "rgb %s %s %s"
23425 (mapcar 'org-normalize-color
23426 (color-values (face-attribute 'default attr nil)))))
23428 (defun org-normalize-color (value)
23429 "Return string to be used as color value for an RGB component."
23430 (format "%g" (/ value 65535.0)))
23432 ;;;; Exporting
23434 ;;; Variables, constants, and parameter plists
23436 (defconst org-level-max 20)
23438 (defvar org-export-html-preamble nil
23439 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23440 (defvar org-export-html-postamble nil
23441 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23442 (defvar org-export-html-auto-preamble t
23443 "Should default preamble be inserted? Set by publishing functions.")
23444 (defvar org-export-html-auto-postamble t
23445 "Should default postamble be inserted? Set by publishing functions.")
23446 (defvar org-current-export-file nil) ; dynamically scoped parameter
23447 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23450 (defconst org-export-plist-vars
23451 '((:language . org-export-default-language)
23452 (:customtime . org-display-custom-times)
23453 (:headline-levels . org-export-headline-levels)
23454 (:section-numbers . org-export-with-section-numbers)
23455 (:table-of-contents . org-export-with-toc)
23456 (:preserve-breaks . org-export-preserve-breaks)
23457 (:archived-trees . org-export-with-archived-trees)
23458 (:emphasize . org-export-with-emphasize)
23459 (:sub-superscript . org-export-with-sub-superscripts)
23460 (:special-strings . org-export-with-special-strings)
23461 (:footnotes . org-export-with-footnotes)
23462 (:drawers . org-export-with-drawers)
23463 (:tags . org-export-with-tags)
23464 (:TeX-macros . org-export-with-TeX-macros)
23465 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23466 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23467 (:fixed-width . org-export-with-fixed-width)
23468 (:timestamps . org-export-with-timestamps)
23469 (:author-info . org-export-author-info)
23470 (:time-stamp-file . org-export-time-stamp-file)
23471 (:tables . org-export-with-tables)
23472 (:table-auto-headline . org-export-highlight-first-table-line)
23473 (:style . org-export-html-style)
23474 (:agenda-style . org-agenda-export-html-style)
23475 (:convert-org-links . org-export-html-link-org-files-as-html)
23476 (:inline-images . org-export-html-inline-images)
23477 (:html-extension . org-export-html-extension)
23478 (:html-table-tag . org-export-html-table-tag)
23479 (:expand-quoted-html . org-export-html-expand)
23480 (:timestamp . org-export-html-with-timestamp)
23481 (:publishing-directory . org-export-publishing-directory)
23482 (:preamble . org-export-html-preamble)
23483 (:postamble . org-export-html-postamble)
23484 (:auto-preamble . org-export-html-auto-preamble)
23485 (:auto-postamble . org-export-html-auto-postamble)
23486 (:author . user-full-name)
23487 (:email . user-mail-address)))
23489 (defun org-default-export-plist ()
23490 "Return the property list with default settings for the export variables."
23491 (let ((l org-export-plist-vars) rtn e)
23492 (while (setq e (pop l))
23493 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23494 rtn))
23496 (defun org-infile-export-plist ()
23497 "Return the property list with file-local settings for export."
23498 (save-excursion
23499 (save-restriction
23500 (widen)
23501 (goto-char 0)
23502 (let ((re (org-make-options-regexp
23503 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23504 p key val text options)
23505 (while (re-search-forward re nil t)
23506 (setq key (org-match-string-no-properties 1)
23507 val (org-match-string-no-properties 2))
23508 (cond
23509 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23510 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23511 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23512 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23513 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23514 ((string-equal key "TEXT")
23515 (setq text (if text (concat text "\n" val) val)))
23516 ((string-equal key "OPTIONS") (setq options val))))
23517 (setq p (plist-put p :text text))
23518 (when options
23519 (let ((op '(("H" . :headline-levels)
23520 ("num" . :section-numbers)
23521 ("toc" . :table-of-contents)
23522 ("\\n" . :preserve-breaks)
23523 ("@" . :expand-quoted-html)
23524 (":" . :fixed-width)
23525 ("|" . :tables)
23526 ("^" . :sub-superscript)
23527 ("-" . :special-strings)
23528 ("f" . :footnotes)
23529 ("d" . :drawers)
23530 ("tags" . :tags)
23531 ("*" . :emphasize)
23532 ("TeX" . :TeX-macros)
23533 ("LaTeX" . :LaTeX-fragments)
23534 ("skip" . :skip-before-1st-heading)
23535 ("author" . :author-info)
23536 ("timestamp" . :time-stamp-file)))
23538 (while (setq o (pop op))
23539 (if (string-match (concat (regexp-quote (car o))
23540 ":\\([^ \t\n\r;,.]*\\)")
23541 options)
23542 (setq p (plist-put p (cdr o)
23543 (car (read-from-string
23544 (match-string 1 options)))))))))
23545 p))))
23547 (defun org-export-directory (type plist)
23548 (let* ((val (plist-get plist :publishing-directory))
23549 (dir (if (listp val)
23550 (or (cdr (assoc type val)) ".")
23551 val)))
23552 dir))
23554 (defun org-skip-comments (lines)
23555 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23556 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23557 (re2 "^\\(\\*+\\)[ \t\n\r]")
23558 (case-fold-search nil)
23559 rtn line level)
23560 (while (setq line (pop lines))
23561 (cond
23562 ((and (string-match re1 line)
23563 (setq level (- (match-end 1) (match-beginning 1))))
23564 ;; Beginning of a COMMENT subtree. Skip it.
23565 (while (and (setq line (pop lines))
23566 (or (not (string-match re2 line))
23567 (> (- (match-end 1) (match-beginning 1)) level))))
23568 (setq lines (cons line lines)))
23569 ((string-match "^#" line)
23570 ;; an ordinary comment line
23572 ((and org-export-table-remove-special-lines
23573 (string-match "^[ \t]*|" line)
23574 (or (string-match "^[ \t]*| *[!_^] *|" line)
23575 (and (string-match "| *<[0-9]+> *|" line)
23576 (not (string-match "| *[^ <|]" line)))))
23577 ;; a special table line that should be removed
23579 (t (setq rtn (cons line rtn)))))
23580 (nreverse rtn)))
23582 (defun org-export (&optional arg)
23583 (interactive)
23584 (let ((help "[t] insert the export option template
23585 \[v] limit export to visible part of outline tree
23587 \[a] export as ASCII
23589 \[h] export as HTML
23590 \[H] export as HTML to temporary buffer
23591 \[R] export region as HTML
23592 \[b] export as HTML and browse immediately
23593 \[x] export as XOXO
23595 \[l] export as LaTeX
23596 \[L] export as LaTeX to temporary buffer
23598 \[i] export current file as iCalendar file
23599 \[I] export all agenda files as iCalendar files
23600 \[c] export agenda files into combined iCalendar file
23602 \[F] publish current file
23603 \[P] publish current project
23604 \[X] publish... (project will be prompted for)
23605 \[A] publish all projects")
23606 (cmds
23607 '((?t . org-insert-export-options-template)
23608 (?v . org-export-visible)
23609 (?a . org-export-as-ascii)
23610 (?h . org-export-as-html)
23611 (?b . org-export-as-html-and-open)
23612 (?H . org-export-as-html-to-buffer)
23613 (?R . org-export-region-as-html)
23614 (?x . org-export-as-xoxo)
23615 (?l . org-export-as-latex)
23616 (?L . org-export-as-latex-to-buffer)
23617 (?i . org-export-icalendar-this-file)
23618 (?I . org-export-icalendar-all-agenda-files)
23619 (?c . org-export-icalendar-combine-agenda-files)
23620 (?F . org-publish-current-file)
23621 (?P . org-publish-current-project)
23622 (?X . org-publish)
23623 (?A . org-publish-all)))
23624 r1 r2 ass)
23625 (save-window-excursion
23626 (delete-other-windows)
23627 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23628 (princ help))
23629 (message "Select command: ")
23630 (setq r1 (read-char-exclusive)))
23631 (setq r2 (if (< r1 27) (+ r1 96) r1))
23632 (if (setq ass (assq r2 cmds))
23633 (call-interactively (cdr ass))
23634 (error "No command associated with key %c" r1))))
23636 (defconst org-html-entities
23637 '(("nbsp")
23638 ("iexcl")
23639 ("cent")
23640 ("pound")
23641 ("curren")
23642 ("yen")
23643 ("brvbar")
23644 ("vert" . "&#124;")
23645 ("sect")
23646 ("uml")
23647 ("copy")
23648 ("ordf")
23649 ("laquo")
23650 ("not")
23651 ("shy")
23652 ("reg")
23653 ("macr")
23654 ("deg")
23655 ("plusmn")
23656 ("sup2")
23657 ("sup3")
23658 ("acute")
23659 ("micro")
23660 ("para")
23661 ("middot")
23662 ("odot"."o")
23663 ("star"."*")
23664 ("cedil")
23665 ("sup1")
23666 ("ordm")
23667 ("raquo")
23668 ("frac14")
23669 ("frac12")
23670 ("frac34")
23671 ("iquest")
23672 ("Agrave")
23673 ("Aacute")
23674 ("Acirc")
23675 ("Atilde")
23676 ("Auml")
23677 ("Aring") ("AA"."&Aring;")
23678 ("AElig")
23679 ("Ccedil")
23680 ("Egrave")
23681 ("Eacute")
23682 ("Ecirc")
23683 ("Euml")
23684 ("Igrave")
23685 ("Iacute")
23686 ("Icirc")
23687 ("Iuml")
23688 ("ETH")
23689 ("Ntilde")
23690 ("Ograve")
23691 ("Oacute")
23692 ("Ocirc")
23693 ("Otilde")
23694 ("Ouml")
23695 ("times")
23696 ("Oslash")
23697 ("Ugrave")
23698 ("Uacute")
23699 ("Ucirc")
23700 ("Uuml")
23701 ("Yacute")
23702 ("THORN")
23703 ("szlig")
23704 ("agrave")
23705 ("aacute")
23706 ("acirc")
23707 ("atilde")
23708 ("auml")
23709 ("aring")
23710 ("aelig")
23711 ("ccedil")
23712 ("egrave")
23713 ("eacute")
23714 ("ecirc")
23715 ("euml")
23716 ("igrave")
23717 ("iacute")
23718 ("icirc")
23719 ("iuml")
23720 ("eth")
23721 ("ntilde")
23722 ("ograve")
23723 ("oacute")
23724 ("ocirc")
23725 ("otilde")
23726 ("ouml")
23727 ("divide")
23728 ("oslash")
23729 ("ugrave")
23730 ("uacute")
23731 ("ucirc")
23732 ("uuml")
23733 ("yacute")
23734 ("thorn")
23735 ("yuml")
23736 ("fnof")
23737 ("Alpha")
23738 ("Beta")
23739 ("Gamma")
23740 ("Delta")
23741 ("Epsilon")
23742 ("Zeta")
23743 ("Eta")
23744 ("Theta")
23745 ("Iota")
23746 ("Kappa")
23747 ("Lambda")
23748 ("Mu")
23749 ("Nu")
23750 ("Xi")
23751 ("Omicron")
23752 ("Pi")
23753 ("Rho")
23754 ("Sigma")
23755 ("Tau")
23756 ("Upsilon")
23757 ("Phi")
23758 ("Chi")
23759 ("Psi")
23760 ("Omega")
23761 ("alpha")
23762 ("beta")
23763 ("gamma")
23764 ("delta")
23765 ("epsilon")
23766 ("varepsilon"."&epsilon;")
23767 ("zeta")
23768 ("eta")
23769 ("theta")
23770 ("iota")
23771 ("kappa")
23772 ("lambda")
23773 ("mu")
23774 ("nu")
23775 ("xi")
23776 ("omicron")
23777 ("pi")
23778 ("rho")
23779 ("sigmaf") ("varsigma"."&sigmaf;")
23780 ("sigma")
23781 ("tau")
23782 ("upsilon")
23783 ("phi")
23784 ("chi")
23785 ("psi")
23786 ("omega")
23787 ("thetasym") ("vartheta"."&thetasym;")
23788 ("upsih")
23789 ("piv")
23790 ("bull") ("bullet"."&bull;")
23791 ("hellip") ("dots"."&hellip;")
23792 ("prime")
23793 ("Prime")
23794 ("oline")
23795 ("frasl")
23796 ("weierp")
23797 ("image")
23798 ("real")
23799 ("trade")
23800 ("alefsym")
23801 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23802 ("uarr") ("uparrow"."&uarr;")
23803 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23804 ("darr")("downarrow"."&darr;")
23805 ("harr") ("leftrightarrow"."&harr;")
23806 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23807 ("lArr") ("Leftarrow"."&lArr;")
23808 ("uArr") ("Uparrow"."&uArr;")
23809 ("rArr") ("Rightarrow"."&rArr;")
23810 ("dArr") ("Downarrow"."&dArr;")
23811 ("hArr") ("Leftrightarrow"."&hArr;")
23812 ("forall")
23813 ("part") ("partial"."&part;")
23814 ("exist") ("exists"."&exist;")
23815 ("empty") ("emptyset"."&empty;")
23816 ("nabla")
23817 ("isin") ("in"."&isin;")
23818 ("notin")
23819 ("ni")
23820 ("prod")
23821 ("sum")
23822 ("minus")
23823 ("lowast") ("ast"."&lowast;")
23824 ("radic")
23825 ("prop") ("proptp"."&prop;")
23826 ("infin") ("infty"."&infin;")
23827 ("ang") ("angle"."&ang;")
23828 ("and") ("wedge"."&and;")
23829 ("or") ("vee"."&or;")
23830 ("cap")
23831 ("cup")
23832 ("int")
23833 ("there4")
23834 ("sim")
23835 ("cong") ("simeq"."&cong;")
23836 ("asymp")("approx"."&asymp;")
23837 ("ne") ("neq"."&ne;")
23838 ("equiv")
23839 ("le")
23840 ("ge")
23841 ("sub") ("subset"."&sub;")
23842 ("sup") ("supset"."&sup;")
23843 ("nsub")
23844 ("sube")
23845 ("supe")
23846 ("oplus")
23847 ("otimes")
23848 ("perp")
23849 ("sdot") ("cdot"."&sdot;")
23850 ("lceil")
23851 ("rceil")
23852 ("lfloor")
23853 ("rfloor")
23854 ("lang")
23855 ("rang")
23856 ("loz") ("Diamond"."&loz;")
23857 ("spades") ("spadesuit"."&spades;")
23858 ("clubs") ("clubsuit"."&clubs;")
23859 ("hearts") ("diamondsuit"."&hearts;")
23860 ("diams") ("diamondsuit"."&diams;")
23861 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23862 ("quot")
23863 ("amp")
23864 ("lt")
23865 ("gt")
23866 ("OElig")
23867 ("oelig")
23868 ("Scaron")
23869 ("scaron")
23870 ("Yuml")
23871 ("circ")
23872 ("tilde")
23873 ("ensp")
23874 ("emsp")
23875 ("thinsp")
23876 ("zwnj")
23877 ("zwj")
23878 ("lrm")
23879 ("rlm")
23880 ("ndash")
23881 ("mdash")
23882 ("lsquo")
23883 ("rsquo")
23884 ("sbquo")
23885 ("ldquo")
23886 ("rdquo")
23887 ("bdquo")
23888 ("dagger")
23889 ("Dagger")
23890 ("permil")
23891 ("lsaquo")
23892 ("rsaquo")
23893 ("euro")
23895 ("arccos"."arccos")
23896 ("arcsin"."arcsin")
23897 ("arctan"."arctan")
23898 ("arg"."arg")
23899 ("cos"."cos")
23900 ("cosh"."cosh")
23901 ("cot"."cot")
23902 ("coth"."coth")
23903 ("csc"."csc")
23904 ("deg"."deg")
23905 ("det"."det")
23906 ("dim"."dim")
23907 ("exp"."exp")
23908 ("gcd"."gcd")
23909 ("hom"."hom")
23910 ("inf"."inf")
23911 ("ker"."ker")
23912 ("lg"."lg")
23913 ("lim"."lim")
23914 ("liminf"."liminf")
23915 ("limsup"."limsup")
23916 ("ln"."ln")
23917 ("log"."log")
23918 ("max"."max")
23919 ("min"."min")
23920 ("Pr"."Pr")
23921 ("sec"."sec")
23922 ("sin"."sin")
23923 ("sinh"."sinh")
23924 ("sup"."sup")
23925 ("tan"."tan")
23926 ("tanh"."tanh")
23928 "Entities for TeX->HTML translation.
23929 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23930 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23931 In that case, \"\\ent\" will be translated to \"&other;\".
23932 The list contains HTML entities for Latin-1, Greek and other symbols.
23933 It is supplemented by a number of commonly used TeX macros with appropriate
23934 translations. There is currently no way for users to extend this.")
23936 ;;; General functions for all backends
23938 (defun org-cleaned-string-for-export (string &rest parameters)
23939 "Cleanup a buffer STRING so that links can be created safely."
23940 (interactive)
23941 (let* ((re-radio (and org-target-link-regexp
23942 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23943 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23944 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23945 (re-archive (concat ":" org-archive-tag ":"))
23946 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23947 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23948 (htmlp (plist-get parameters :for-html))
23949 (asciip (plist-get parameters :for-ascii))
23950 (latexp (plist-get parameters :for-LaTeX))
23951 (commentsp (plist-get parameters :comments))
23952 (archived-trees (plist-get parameters :archived-trees))
23953 (inhibit-read-only t)
23954 (drawers org-drawers)
23955 (exp-drawers (plist-get parameters :drawers))
23956 (outline-regexp "\\*+ ")
23957 a b xx
23958 rtn p)
23959 (with-current-buffer (get-buffer-create " org-mode-tmp")
23960 (erase-buffer)
23961 (insert string)
23962 ;; Remove license-to-kill stuff
23963 (while (setq p (text-property-any (point-min) (point-max)
23964 :org-license-to-kill t))
23965 (delete-region p (next-single-property-change p :org-license-to-kill)))
23967 (let ((org-inhibit-startup t)) (org-mode))
23968 (untabify (point-min) (point-max))
23970 ;; Get rid of drawers
23971 (unless (eq t exp-drawers)
23972 (goto-char (point-min))
23973 (let ((re (concat "^[ \t]*:\\("
23974 (mapconcat
23975 'identity
23976 (org-delete-all exp-drawers
23977 (copy-sequence drawers))
23978 "\\|")
23979 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23980 (while (re-search-forward re nil t)
23981 (replace-match ""))))
23983 ;; Get the correct stuff before the first headline
23984 (when (plist-get parameters :skip-before-1st-heading)
23985 (goto-char (point-min))
23986 (when (re-search-forward "^\\*+[ \t]" nil t)
23987 (delete-region (point-min) (match-beginning 0))
23988 (goto-char (point-min))
23989 (insert "\n")))
23990 (when (plist-get parameters :add-text)
23991 (goto-char (point-min))
23992 (insert (plist-get parameters :add-text) "\n"))
23994 ;; Get rid of archived trees
23995 (when (not (eq archived-trees t))
23996 (goto-char (point-min))
23997 (while (re-search-forward re-archive nil t)
23998 (if (not (org-on-heading-p t))
23999 (org-end-of-subtree t)
24000 (beginning-of-line 1)
24001 (setq a (if archived-trees
24002 (1+ (point-at-eol)) (point))
24003 b (org-end-of-subtree t))
24004 (if (> b a) (delete-region a b)))))
24006 ;; Find targets in comments and move them out of comments,
24007 ;; but mark them as targets that should be invisible
24008 (goto-char (point-min))
24009 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24010 (replace-match "\\1(INVISIBLE)"))
24012 ;; Protect backend specific stuff, throw away the others.
24013 (let ((formatters
24014 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24015 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24016 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24017 fmt)
24018 (goto-char (point-min))
24019 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24020 (goto-char (match-end 0))
24021 (while (not (looking-at "#\\+END_EXAMPLE"))
24022 (insert ": ")
24023 (beginning-of-line 2)))
24024 (goto-char (point-min))
24025 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24026 (add-text-properties (match-beginning 0) (match-end 0)
24027 '(org-protected t)))
24028 (while formatters
24029 (setq fmt (pop formatters))
24030 (when (car fmt)
24031 (goto-char (point-min))
24032 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24033 ":[ \t]*\\(.*\\)") nil t)
24034 (replace-match "\\1" t)
24035 (add-text-properties
24036 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24037 '(org-protected t))))
24038 (goto-char (point-min))
24039 (while (re-search-forward
24040 (concat "^#\\+"
24041 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24042 (cadddr fmt) "\\>.*\n?") nil t)
24043 (if (car fmt)
24044 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24045 '(org-protected t))
24046 (delete-region (match-beginning 0) (match-end 0))))))
24048 ;; Protect quoted subtrees
24049 (goto-char (point-min))
24050 (while (re-search-forward re-quote nil t)
24051 (goto-char (match-beginning 0))
24052 (end-of-line 1)
24053 (add-text-properties (point) (org-end-of-subtree t)
24054 '(org-protected t)))
24056 ;; Protect verbatim elements
24057 (goto-char (point-min))
24058 (while (re-search-forward org-verbatim-re nil t)
24059 (add-text-properties (match-beginning 4) (match-end 4)
24060 '(org-protected t))
24061 (goto-char (1+ (match-end 4))))
24063 ;; Remove subtrees that are commented
24064 (goto-char (point-min))
24065 (while (re-search-forward re-commented nil t)
24066 (goto-char (match-beginning 0))
24067 (delete-region (point) (org-end-of-subtree t)))
24069 ;; Remove special table lines
24070 (when org-export-table-remove-special-lines
24071 (goto-char (point-min))
24072 (while (re-search-forward "^[ \t]*|" nil t)
24073 (beginning-of-line 1)
24074 (if (or (looking-at "[ \t]*| *[!_^] *|")
24075 (and (looking-at ".*?| *<[0-9]+> *|")
24076 (not (looking-at ".*?| *[^ <|]"))))
24077 (delete-region (max (point-min) (1- (point-at-bol)))
24078 (point-at-eol))
24079 (end-of-line 1))))
24081 ;; Specific LaTeX stuff
24082 (when latexp
24083 (require 'org-export-latex nil)
24084 (org-export-latex-cleaned-string))
24086 (when asciip
24087 (org-export-ascii-clean-string))
24089 ;; Specific HTML stuff
24090 (when htmlp
24091 ;; Convert LaTeX fragments to images
24092 (when (plist-get parameters :LaTeX-fragments)
24093 (org-format-latex
24094 (concat "ltxpng/" (file-name-sans-extension
24095 (file-name-nondirectory
24096 org-current-export-file)))
24097 org-current-export-dir nil "Creating LaTeX image %s"))
24098 (message "Exporting..."))
24100 ;; Remove or replace comments
24101 (goto-char (point-min))
24102 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24103 (if commentsp
24104 (progn (add-text-properties
24105 (match-beginning 0) (match-end 0) '(org-protected t))
24106 (replace-match (format commentsp (match-string 1)) t t))
24107 (replace-match "")))
24109 ;; Find matches for radio targets and turn them into internal links
24110 (goto-char (point-min))
24111 (when re-radio
24112 (while (re-search-forward re-radio nil t)
24113 (org-if-unprotected
24114 (replace-match "\\1[[\\2]]"))))
24116 ;; Find all links that contain a newline and put them into a single line
24117 (goto-char (point-min))
24118 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24119 (org-if-unprotected
24120 (replace-match "\\1 \\3")
24121 (goto-char (match-beginning 0))))
24124 ;; Normalize links: Convert angle and plain links into bracket links
24125 ;; Expand link abbreviations
24126 (goto-char (point-min))
24127 (while (re-search-forward re-plain-link nil t)
24128 (goto-char (1- (match-end 0)))
24129 (org-if-unprotected
24130 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24131 ":" (match-string 3) "]]")))
24132 ;; added 'org-link face to links
24133 (put-text-property 0 (length s) 'face 'org-link s)
24134 (replace-match s t t))))
24135 (goto-char (point-min))
24136 (while (re-search-forward re-angle-link nil t)
24137 (goto-char (1- (match-end 0)))
24138 (org-if-unprotected
24139 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24140 ":" (match-string 3) "]]")))
24141 (put-text-property 0 (length s) 'face 'org-link s)
24142 (replace-match s t t))))
24143 (goto-char (point-min))
24144 (while (re-search-forward org-bracket-link-regexp nil t)
24145 (org-if-unprotected
24146 (let* ((s (concat "[[" (setq xx (save-match-data
24147 (org-link-expand-abbrev (match-string 1))))
24149 (if (match-end 3)
24150 (match-string 2)
24151 (concat "[" xx "]"))
24152 "]")))
24153 (put-text-property 0 (length s) 'face 'org-link s)
24154 (replace-match s t t))))
24156 ;; Find multiline emphasis and put them into single line
24157 (when (plist-get parameters :emph-multiline)
24158 (goto-char (point-min))
24159 (while (re-search-forward org-emph-re nil t)
24160 (if (not (= (char-after (match-beginning 3))
24161 (char-after (match-beginning 4))))
24162 (org-if-unprotected
24163 (subst-char-in-region (match-beginning 0) (match-end 0)
24164 ?\n ?\ t)
24165 (goto-char (1- (match-end 0))))
24166 (goto-char (1+ (match-beginning 0))))))
24168 (setq rtn (buffer-string)))
24169 (kill-buffer " org-mode-tmp")
24170 rtn))
24172 (defun org-export-grab-title-from-buffer ()
24173 "Get a title for the current document, from looking at the buffer."
24174 (let ((inhibit-read-only t))
24175 (save-excursion
24176 (goto-char (point-min))
24177 (let ((end (save-excursion (outline-next-heading) (point))))
24178 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24179 ;; Mark the line so that it will not be exported as normal text.
24180 (org-unmodified
24181 (add-text-properties (match-beginning 0) (match-end 0)
24182 (list :org-license-to-kill t)))
24183 ;; Return the title string
24184 (org-trim (match-string 0)))))))
24186 (defun org-export-get-title-from-subtree ()
24187 "Return subtree title and exclude it from export."
24188 (let (title (m (mark)))
24189 (save-excursion
24190 (goto-char (region-beginning))
24191 (when (and (org-at-heading-p)
24192 (>= (org-end-of-subtree t t) (region-end)))
24193 ;; This is a subtree, we take the title from the first heading
24194 (goto-char (region-beginning))
24195 (looking-at org-todo-line-regexp)
24196 (setq title (match-string 3))
24197 (org-unmodified
24198 (add-text-properties (point) (1+ (point-at-eol))
24199 (list :org-license-to-kill t)))))
24200 title))
24202 (defun org-solidify-link-text (s &optional alist)
24203 "Take link text and make a safe target out of it."
24204 (save-match-data
24205 (let* ((rtn
24206 (mapconcat
24207 'identity
24208 (org-split-string s "[ \t\r\n]+") "--"))
24209 (a (assoc rtn alist)))
24210 (or (cdr a) rtn))))
24212 (defun org-get-min-level (lines)
24213 "Get the minimum level in LINES."
24214 (let ((re "^\\(\\*+\\) ") l min)
24215 (catch 'exit
24216 (while (setq l (pop lines))
24217 (if (string-match re l)
24218 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24219 1)))
24221 ;; Variable holding the vector with section numbers
24222 (defvar org-section-numbers (make-vector org-level-max 0))
24224 (defun org-init-section-numbers ()
24225 "Initialize the vector for the section numbers."
24226 (let* ((level -1)
24227 (numbers (nreverse (org-split-string "" "\\.")))
24228 (depth (1- (length org-section-numbers)))
24229 (i depth) number-string)
24230 (while (>= i 0)
24231 (if (> i level)
24232 (aset org-section-numbers i 0)
24233 (setq number-string (or (car numbers) "0"))
24234 (if (string-match "\\`[A-Z]\\'" number-string)
24235 (aset org-section-numbers i
24236 (- (string-to-char number-string) ?A -1))
24237 (aset org-section-numbers i (string-to-number number-string)))
24238 (pop numbers))
24239 (setq i (1- i)))))
24241 (defun org-section-number (&optional level)
24242 "Return a string with the current section number.
24243 When LEVEL is non-nil, increase section numbers on that level."
24244 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24245 (when level
24246 (when (> level -1)
24247 (aset org-section-numbers
24248 level (1+ (aref org-section-numbers level))))
24249 (setq idx (1+ level))
24250 (while (<= idx depth)
24251 (if (not (= idx 1))
24252 (aset org-section-numbers idx 0))
24253 (setq idx (1+ idx))))
24254 (setq idx 0)
24255 (while (<= idx depth)
24256 (setq n (aref org-section-numbers idx))
24257 (setq string (concat string (if (not (string= string "")) "." "")
24258 (int-to-string n)))
24259 (setq idx (1+ idx)))
24260 (save-match-data
24261 (if (string-match "\\`\\([@0]\\.\\)+" string)
24262 (setq string (replace-match "" t nil string)))
24263 (if (string-match "\\(\\.0\\)+\\'" string)
24264 (setq string (replace-match "" t nil string))))
24265 string))
24267 ;;; ASCII export
24269 (defvar org-last-level nil) ; dynamically scoped variable
24270 (defvar org-min-level nil) ; dynamically scoped variable
24271 (defvar org-levels-open nil) ; dynamically scoped parameter
24272 (defvar org-ascii-current-indentation nil) ; For communication
24274 (defun org-export-as-ascii (arg)
24275 "Export the outline as a pretty ASCII file.
24276 If there is an active region, export only the region.
24277 The prefix ARG specifies how many levels of the outline should become
24278 underlined headlines. The default is 3."
24279 (interactive "P")
24280 (setq-default org-todo-line-regexp org-todo-line-regexp)
24281 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24282 (org-infile-export-plist)))
24283 (region-p (org-region-active-p))
24284 (subtree-p
24285 (when region-p
24286 (save-excursion
24287 (goto-char (region-beginning))
24288 (and (org-at-heading-p)
24289 (>= (org-end-of-subtree t t) (region-end))))))
24290 (custom-times org-display-custom-times)
24291 (org-ascii-current-indentation '(0 . 0))
24292 (level 0) line txt
24293 (umax nil)
24294 (umax-toc nil)
24295 (case-fold-search nil)
24296 (filename (concat (file-name-as-directory
24297 (org-export-directory :ascii opt-plist))
24298 (file-name-sans-extension
24299 (or (and subtree-p
24300 (org-entry-get (region-beginning)
24301 "EXPORT_FILE_NAME" t))
24302 (file-name-nondirectory buffer-file-name)))
24303 ".txt"))
24304 (filename (if (equal (file-truename filename)
24305 (file-truename buffer-file-name))
24306 (concat filename ".txt")
24307 filename))
24308 (buffer (find-file-noselect filename))
24309 (org-levels-open (make-vector org-level-max nil))
24310 (odd org-odd-levels-only)
24311 (date (plist-get opt-plist :date))
24312 (author (plist-get opt-plist :author))
24313 (title (or (and subtree-p (org-export-get-title-from-subtree))
24314 (plist-get opt-plist :title)
24315 (and (not
24316 (plist-get opt-plist :skip-before-1st-heading))
24317 (org-export-grab-title-from-buffer))
24318 (file-name-sans-extension
24319 (file-name-nondirectory buffer-file-name))))
24320 (email (plist-get opt-plist :email))
24321 (language (plist-get opt-plist :language))
24322 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24323 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24324 (todo nil)
24325 (lang-words nil)
24326 (region
24327 (buffer-substring
24328 (if (org-region-active-p) (region-beginning) (point-min))
24329 (if (org-region-active-p) (region-end) (point-max))))
24330 (lines (org-split-string
24331 (org-cleaned-string-for-export
24332 region
24333 :for-ascii t
24334 :skip-before-1st-heading
24335 (plist-get opt-plist :skip-before-1st-heading)
24336 :drawers (plist-get opt-plist :drawers)
24337 :verbatim-multiline t
24338 :archived-trees
24339 (plist-get opt-plist :archived-trees)
24340 :add-text (plist-get opt-plist :text))
24341 "\n"))
24342 thetoc have-headings first-heading-pos
24343 table-open table-buffer)
24345 (let ((inhibit-read-only t))
24346 (org-unmodified
24347 (remove-text-properties (point-min) (point-max)
24348 '(:org-license-to-kill t))))
24350 (setq org-min-level (org-get-min-level lines))
24351 (setq org-last-level org-min-level)
24352 (org-init-section-numbers)
24354 (find-file-noselect filename)
24356 (setq lang-words (or (assoc language org-export-language-setup)
24357 (assoc "en" org-export-language-setup)))
24358 (switch-to-buffer-other-window buffer)
24359 (erase-buffer)
24360 (fundamental-mode)
24361 ;; create local variables for all options, to make sure all called
24362 ;; functions get the correct information
24363 (mapc (lambda (x)
24364 (set (make-local-variable (cdr x))
24365 (plist-get opt-plist (car x))))
24366 org-export-plist-vars)
24367 (org-set-local 'org-odd-levels-only odd)
24368 (setq umax (if arg (prefix-numeric-value arg)
24369 org-export-headline-levels))
24370 (setq umax-toc (if (integerp org-export-with-toc)
24371 (min org-export-with-toc umax)
24372 umax))
24374 ;; File header
24375 (if title (org-insert-centered title ?=))
24376 (insert "\n")
24377 (if (and (or author email)
24378 org-export-author-info)
24379 (insert (concat (nth 1 lang-words) ": " (or author "")
24380 (if email (concat " <" email ">") "")
24381 "\n")))
24383 (cond
24384 ((and date (string-match "%" date))
24385 (setq date (format-time-string date (current-time))))
24386 (date)
24387 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24389 (if (and date org-export-time-stamp-file)
24390 (insert (concat (nth 2 lang-words) ": " date"\n")))
24392 (insert "\n\n")
24394 (if org-export-with-toc
24395 (progn
24396 (push (concat (nth 3 lang-words) "\n") thetoc)
24397 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24398 (mapc '(lambda (line)
24399 (if (string-match org-todo-line-regexp
24400 line)
24401 ;; This is a headline
24402 (progn
24403 (setq have-headings t)
24404 (setq level (- (match-end 1) (match-beginning 1))
24405 level (org-tr-level level)
24406 txt (match-string 3 line)
24407 todo
24408 (or (and org-export-mark-todo-in-toc
24409 (match-beginning 2)
24410 (not (member (match-string 2 line)
24411 org-done-keywords)))
24412 ; TODO, not DONE
24413 (and org-export-mark-todo-in-toc
24414 (= level umax-toc)
24415 (org-search-todo-below
24416 line lines level))))
24417 (setq txt (org-html-expand-for-ascii txt))
24419 (while (string-match org-bracket-link-regexp txt)
24420 (setq txt
24421 (replace-match
24422 (match-string (if (match-end 2) 3 1) txt)
24423 t t txt)))
24425 (if (and (memq org-export-with-tags '(not-in-toc nil))
24426 (string-match
24427 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24428 txt))
24429 (setq txt (replace-match "" t t txt)))
24430 (if (string-match quote-re0 txt)
24431 (setq txt (replace-match "" t t txt)))
24433 (if org-export-with-section-numbers
24434 (setq txt (concat (org-section-number level)
24435 " " txt)))
24436 (if (<= level umax-toc)
24437 (progn
24438 (push
24439 (concat
24440 (make-string
24441 (* (max 0 (- level org-min-level)) 4) ?\ )
24442 (format (if todo "%s (*)\n" "%s\n") txt))
24443 thetoc)
24444 (setq org-last-level level))
24445 ))))
24446 lines)
24447 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24449 (org-init-section-numbers)
24450 (while (setq line (pop lines))
24451 ;; Remove the quoted HTML tags.
24452 (setq line (org-html-expand-for-ascii line))
24453 ;; Remove targets
24454 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24455 (setq line (replace-match "" t t line)))
24456 ;; Replace internal links
24457 (while (string-match org-bracket-link-regexp line)
24458 (setq line (replace-match
24459 (if (match-end 3) "[\\3]" "[\\1]")
24460 t nil line)))
24461 (when custom-times
24462 (setq line (org-translate-time line)))
24463 (cond
24464 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24465 ;; a Headline
24466 (setq first-heading-pos (or first-heading-pos (point)))
24467 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24468 txt (match-string 2 line))
24469 (org-ascii-level-start level txt umax lines))
24471 ((and org-export-with-tables
24472 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24473 (if (not table-open)
24474 ;; New table starts
24475 (setq table-open t table-buffer nil))
24476 ;; Accumulate lines
24477 (setq table-buffer (cons line table-buffer))
24478 (when (or (not lines)
24479 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24480 (car lines))))
24481 (setq table-open nil
24482 table-buffer (nreverse table-buffer))
24483 (insert (mapconcat
24484 (lambda (x)
24485 (org-fix-indentation x org-ascii-current-indentation))
24486 (org-format-table-ascii table-buffer)
24487 "\n") "\n")))
24489 (setq line (org-fix-indentation line org-ascii-current-indentation))
24490 (if (and org-export-with-fixed-width
24491 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24492 (setq line (replace-match "\\1" nil nil line)))
24493 (insert line "\n"))))
24495 (normal-mode)
24497 ;; insert the table of contents
24498 (when thetoc
24499 (goto-char (point-min))
24500 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24501 (progn
24502 (goto-char (match-beginning 0))
24503 (replace-match ""))
24504 (goto-char first-heading-pos))
24505 (mapc 'insert thetoc)
24506 (or (looking-at "[ \t]*\n[ \t]*\n")
24507 (insert "\n\n")))
24509 ;; Convert whitespace place holders
24510 (goto-char (point-min))
24511 (let (beg end)
24512 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24513 (setq end (next-single-property-change beg 'org-whitespace))
24514 (goto-char beg)
24515 (delete-region beg end)
24516 (insert (make-string (- end beg) ?\ ))))
24518 (save-buffer)
24519 ;; remove display and invisible chars
24520 (let (beg end)
24521 (goto-char (point-min))
24522 (while (setq beg (next-single-property-change (point) 'display))
24523 (setq end (next-single-property-change beg 'display))
24524 (delete-region beg end)
24525 (goto-char beg)
24526 (insert "=>"))
24527 (goto-char (point-min))
24528 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24529 (setq end (next-single-property-change beg 'org-cwidth))
24530 (delete-region beg end)
24531 (goto-char beg)))
24532 (goto-char (point-min))))
24534 (defun org-export-ascii-clean-string ()
24535 "Do extra work for ASCII export"
24536 (goto-char (point-min))
24537 (while (re-search-forward org-verbatim-re nil t)
24538 (goto-char (match-end 2))
24539 (backward-delete-char 1) (insert "'")
24540 (goto-char (match-beginning 2))
24541 (delete-char 1) (insert "`")
24542 (goto-char (match-end 2))))
24544 (defun org-search-todo-below (line lines level)
24545 "Search the subtree below LINE for any TODO entries."
24546 (let ((rest (cdr (memq line lines)))
24547 (re org-todo-line-regexp)
24548 line lv todo)
24549 (catch 'exit
24550 (while (setq line (pop rest))
24551 (if (string-match re line)
24552 (progn
24553 (setq lv (- (match-end 1) (match-beginning 1))
24554 todo (and (match-beginning 2)
24555 (not (member (match-string 2 line)
24556 org-done-keywords))))
24557 ; TODO, not DONE
24558 (if (<= lv level) (throw 'exit nil))
24559 (if todo (throw 'exit t))))))))
24561 (defun org-html-expand-for-ascii (line)
24562 "Handle quoted HTML for ASCII export."
24563 (if org-export-html-expand
24564 (while (string-match "@<[^<>\n]*>" line)
24565 ;; We just remove the tags for now.
24566 (setq line (replace-match "" nil nil line))))
24567 line)
24569 (defun org-insert-centered (s &optional underline)
24570 "Insert the string S centered and underline it with character UNDERLINE."
24571 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24572 (insert (make-string ind ?\ ) s "\n")
24573 (if underline
24574 (insert (make-string ind ?\ )
24575 (make-string (string-width s) underline)
24576 "\n"))))
24578 (defun org-ascii-level-start (level title umax &optional lines)
24579 "Insert a new level in ASCII export."
24580 (let (char (n (- level umax 1)) (ind 0))
24581 (if (> level umax)
24582 (progn
24583 (insert (make-string (* 2 n) ?\ )
24584 (char-to-string (nth (% n (length org-export-ascii-bullets))
24585 org-export-ascii-bullets))
24586 " " title "\n")
24587 ;; find the indentation of the next non-empty line
24588 (catch 'stop
24589 (while lines
24590 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24591 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24592 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24593 (pop lines)))
24594 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24595 (if (or (not (equal (char-before) ?\n))
24596 (not (equal (char-before (1- (point))) ?\n)))
24597 (insert "\n"))
24598 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24599 (unless org-export-with-tags
24600 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24601 (setq title (replace-match "" t t title))))
24602 (if org-export-with-section-numbers
24603 (setq title (concat (org-section-number level) " " title)))
24604 (insert title "\n" (make-string (string-width title) char) "\n")
24605 (setq org-ascii-current-indentation '(0 . 0)))))
24607 (defun org-export-visible (type arg)
24608 "Create a copy of the visible part of the current buffer, and export it.
24609 The copy is created in a temporary buffer and removed after use.
24610 TYPE is the final key (as a string) that also select the export command in
24611 the `C-c C-e' export dispatcher.
24612 As a special case, if the you type SPC at the prompt, the temporary
24613 org-mode file will not be removed but presented to you so that you can
24614 continue to use it. The prefix arg ARG is passed through to the exporting
24615 command."
24616 (interactive
24617 (list (progn
24618 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24619 (read-char-exclusive))
24620 current-prefix-arg))
24621 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24622 (error "Invalid export key"))
24623 (let* ((binding (cdr (assoc type
24624 '((?a . org-export-as-ascii)
24625 (?\C-a . org-export-as-ascii)
24626 (?b . org-export-as-html-and-open)
24627 (?\C-b . org-export-as-html-and-open)
24628 (?h . org-export-as-html)
24629 (?H . org-export-as-html-to-buffer)
24630 (?R . org-export-region-as-html)
24631 (?x . org-export-as-xoxo)))))
24632 (keepp (equal type ?\ ))
24633 (file buffer-file-name)
24634 (buffer (get-buffer-create "*Org Export Visible*"))
24635 s e)
24636 ;; Need to hack the drawers here.
24637 (save-excursion
24638 (goto-char (point-min))
24639 (while (re-search-forward org-drawer-regexp nil t)
24640 (goto-char (match-beginning 1))
24641 (or (org-invisible-p) (org-flag-drawer nil))))
24642 (with-current-buffer buffer (erase-buffer))
24643 (save-excursion
24644 (setq s (goto-char (point-min)))
24645 (while (not (= (point) (point-max)))
24646 (goto-char (org-find-invisible))
24647 (append-to-buffer buffer s (point))
24648 (setq s (goto-char (org-find-visible))))
24649 (org-cycle-hide-drawers 'all)
24650 (goto-char (point-min))
24651 (unless keepp
24652 ;; Copy all comment lines to the end, to make sure #+ settings are
24653 ;; still available for the second export step. Kind of a hack, but
24654 ;; does do the trick.
24655 (if (looking-at "#[^\r\n]*")
24656 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24657 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24658 (append-to-buffer buffer (1+ (match-beginning 0))
24659 (min (point-max) (1+ (match-end 0))))))
24660 (set-buffer buffer)
24661 (let ((buffer-file-name file)
24662 (org-inhibit-startup t))
24663 (org-mode)
24664 (show-all)
24665 (unless keepp (funcall binding arg))))
24666 (if (not keepp)
24667 (kill-buffer buffer)
24668 (switch-to-buffer-other-window buffer)
24669 (goto-char (point-min)))))
24671 (defun org-find-visible ()
24672 (let ((s (point)))
24673 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24674 (get-char-property s 'invisible)))
24676 (defun org-find-invisible ()
24677 (let ((s (point)))
24678 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24679 (not (get-char-property s 'invisible))))
24682 ;;; HTML export
24684 (defun org-get-current-options ()
24685 "Return a string with current options as keyword options.
24686 Does include HTML export options as well as TODO and CATEGORY stuff."
24687 (format
24688 "#+TITLE: %s
24689 #+AUTHOR: %s
24690 #+EMAIL: %s
24691 #+LANGUAGE: %s
24692 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24693 #+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
24694 #+CATEGORY: %s
24695 #+SEQ_TODO: %s
24696 #+TYP_TODO: %s
24697 #+PRIORITIES: %c %c %c
24698 #+DRAWERS: %s
24699 #+STARTUP: %s %s %s %s %s
24700 #+TAGS: %s
24701 #+ARCHIVE: %s
24702 #+LINK: %s
24704 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24705 org-export-headline-levels
24706 org-export-with-section-numbers
24707 org-export-with-toc
24708 org-export-preserve-breaks
24709 org-export-html-expand
24710 org-export-with-fixed-width
24711 org-export-with-tables
24712 org-export-with-sub-superscripts
24713 org-export-with-special-strings
24714 org-export-with-footnotes
24715 org-export-with-emphasize
24716 org-export-with-TeX-macros
24717 org-export-with-LaTeX-fragments
24718 org-export-skip-text-before-1st-heading
24719 org-export-with-drawers
24720 org-export-with-tags
24721 (file-name-nondirectory buffer-file-name)
24722 "TODO FEEDBACK VERIFY DONE"
24723 "Me Jason Marie DONE"
24724 org-highest-priority org-lowest-priority org-default-priority
24725 (mapconcat 'identity org-drawers " ")
24726 (cdr (assoc org-startup-folded
24727 '((nil . "showall") (t . "overview") (content . "content"))))
24728 (if org-odd-levels-only "odd" "oddeven")
24729 (if org-hide-leading-stars "hidestars" "showstars")
24730 (if org-startup-align-all-tables "align" "noalign")
24731 (cond ((eq org-log-done t) "logdone")
24732 ((equal org-log-done 'note) "lognotedone")
24733 ((not org-log-done) "nologdone"))
24734 (or (mapconcat (lambda (x)
24735 (cond
24736 ((equal '(:startgroup) x) "{")
24737 ((equal '(:endgroup) x) "}")
24738 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24739 (t (car x))))
24740 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24741 org-archive-location
24742 "org file:~/org/%s.org"
24745 (defun org-insert-export-options-template ()
24746 "Insert into the buffer a template with information for exporting."
24747 (interactive)
24748 (if (not (bolp)) (newline))
24749 (let ((s (org-get-current-options)))
24750 (and (string-match "#\\+CATEGORY" s)
24751 (setq s (substring s 0 (match-beginning 0))))
24752 (insert s)))
24754 (defun org-toggle-fixed-width-section (arg)
24755 "Toggle the fixed-width export.
24756 If there is no active region, the QUOTE keyword at the current headline is
24757 inserted or removed. When present, it causes the text between this headline
24758 and the next to be exported as fixed-width text, and unmodified.
24759 If there is an active region, this command adds or removes a colon as the
24760 first character of this line. If the first character of a line is a colon,
24761 this line is also exported in fixed-width font."
24762 (interactive "P")
24763 (let* ((cc 0)
24764 (regionp (org-region-active-p))
24765 (beg (if regionp (region-beginning) (point)))
24766 (end (if regionp (region-end)))
24767 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24768 (case-fold-search nil)
24769 (re "[ \t]*\\(:\\)")
24770 off)
24771 (if regionp
24772 (save-excursion
24773 (goto-char beg)
24774 (setq cc (current-column))
24775 (beginning-of-line 1)
24776 (setq off (looking-at re))
24777 (while (> nlines 0)
24778 (setq nlines (1- nlines))
24779 (beginning-of-line 1)
24780 (cond
24781 (arg
24782 (move-to-column cc t)
24783 (insert ":\n")
24784 (forward-line -1))
24785 ((and off (looking-at re))
24786 (replace-match "" t t nil 1))
24787 ((not off) (move-to-column cc t) (insert ":")))
24788 (forward-line 1)))
24789 (save-excursion
24790 (org-back-to-heading)
24791 (if (looking-at (concat outline-regexp
24792 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24793 (replace-match "" t t nil 1)
24794 (if (looking-at outline-regexp)
24795 (progn
24796 (goto-char (match-end 0))
24797 (insert org-quote-string " "))))))))
24799 (defun org-export-as-html-and-open (arg)
24800 "Export the outline as HTML and immediately open it with a browser.
24801 If there is an active region, export only the region.
24802 The prefix ARG specifies how many levels of the outline should become
24803 headlines. The default is 3. Lower levels will become bulleted lists."
24804 (interactive "P")
24805 (org-export-as-html arg 'hidden)
24806 (org-open-file buffer-file-name))
24808 (defun org-export-as-html-batch ()
24809 "Call `org-export-as-html', may be used in batch processing as
24810 emacs --batch
24811 --load=$HOME/lib/emacs/org.el
24812 --eval \"(setq org-export-headline-levels 2)\"
24813 --visit=MyFile --funcall org-export-as-html-batch"
24814 (org-export-as-html org-export-headline-levels 'hidden))
24816 (defun org-export-as-html-to-buffer (arg)
24817 "Call `org-exort-as-html` with output to a temporary buffer.
24818 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24819 (interactive "P")
24820 (org-export-as-html arg nil nil "*Org HTML Export*")
24821 (switch-to-buffer-other-window "*Org HTML Export*"))
24823 (defun org-replace-region-by-html (beg end)
24824 "Assume the current region has org-mode syntax, and convert it to HTML.
24825 This can be used in any buffer. For example, you could write an
24826 itemized list in org-mode syntax in an HTML buffer and then use this
24827 command to convert it."
24828 (interactive "r")
24829 (let (reg html buf pop-up-frames)
24830 (save-window-excursion
24831 (if (org-mode-p)
24832 (setq html (org-export-region-as-html
24833 beg end t 'string))
24834 (setq reg (buffer-substring beg end)
24835 buf (get-buffer-create "*Org tmp*"))
24836 (with-current-buffer buf
24837 (erase-buffer)
24838 (insert reg)
24839 (org-mode)
24840 (setq html (org-export-region-as-html
24841 (point-min) (point-max) t 'string)))
24842 (kill-buffer buf)))
24843 (delete-region beg end)
24844 (insert html)))
24846 (defun org-export-region-as-html (beg end &optional body-only buffer)
24847 "Convert region from BEG to END in org-mode buffer to HTML.
24848 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24849 contents, and only produce the region of converted text, useful for
24850 cut-and-paste operations.
24851 If BUFFER is a buffer or a string, use/create that buffer as a target
24852 of the converted HTML. If BUFFER is the symbol `string', return the
24853 produced HTML as a string and leave not buffer behind. For example,
24854 a Lisp program could call this function in the following way:
24856 (setq html (org-export-region-as-html beg end t 'string))
24858 When called interactively, the output buffer is selected, and shown
24859 in a window. A non-interactive call will only retunr the buffer."
24860 (interactive "r\nP")
24861 (when (interactive-p)
24862 (setq buffer "*Org HTML Export*"))
24863 (let ((transient-mark-mode t) (zmacs-regions t)
24864 rtn)
24865 (goto-char end)
24866 (set-mark (point)) ;; to activate the region
24867 (goto-char beg)
24868 (setq rtn (org-export-as-html
24869 nil nil nil
24870 buffer body-only))
24871 (if (fboundp 'deactivate-mark) (deactivate-mark))
24872 (if (and (interactive-p) (bufferp rtn))
24873 (switch-to-buffer-other-window rtn)
24874 rtn)))
24876 (defvar html-table-tag nil) ; dynamically scoped into this.
24877 (defun org-export-as-html (arg &optional hidden ext-plist
24878 to-buffer body-only)
24879 "Export the outline as a pretty HTML file.
24880 If there is an active region, export only the region. The prefix
24881 ARG specifies how many levels of the outline should become
24882 headlines. The default is 3. Lower levels will become bulleted
24883 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24884 EXT-PLIST is a property list with external parameters overriding
24885 org-mode's default settings, but still inferior to file-local
24886 settings. When TO-BUFFER is non-nil, create a buffer with that
24887 name and export to that buffer. If TO-BUFFER is the symbol `string',
24888 don't leave any buffer behind but just return the resulting HTML as
24889 a string. When BODY-ONLY is set, don't produce the file header and footer,
24890 simply return the content of <body>...</body>, without even
24891 the body tags themselves."
24892 (interactive "P")
24894 ;; Make sure we have a file name when we need it.
24895 (when (and (not (or to-buffer body-only))
24896 (not buffer-file-name))
24897 (if (buffer-base-buffer)
24898 (org-set-local 'buffer-file-name
24899 (with-current-buffer (buffer-base-buffer)
24900 buffer-file-name))
24901 (error "Need a file name to be able to export.")))
24903 (message "Exporting...")
24904 (setq-default org-todo-line-regexp org-todo-line-regexp)
24905 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24906 (setq-default org-done-keywords org-done-keywords)
24907 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24908 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24909 ext-plist
24910 (org-infile-export-plist)))
24912 (style (plist-get opt-plist :style))
24913 (html-extension (plist-get opt-plist :html-extension))
24914 (link-validate (plist-get opt-plist :link-validation-function))
24915 valid thetoc have-headings first-heading-pos
24916 (odd org-odd-levels-only)
24917 (region-p (org-region-active-p))
24918 (subtree-p
24919 (when region-p
24920 (save-excursion
24921 (goto-char (region-beginning))
24922 (and (org-at-heading-p)
24923 (>= (org-end-of-subtree t t) (region-end))))))
24924 ;; The following two are dynamically scoped into other
24925 ;; routines below.
24926 (org-current-export-dir (org-export-directory :html opt-plist))
24927 (org-current-export-file buffer-file-name)
24928 (level 0) (line "") (origline "") txt todo
24929 (umax nil)
24930 (umax-toc nil)
24931 (filename (if to-buffer nil
24932 (expand-file-name
24933 (concat
24934 (file-name-sans-extension
24935 (or (and subtree-p
24936 (org-entry-get (region-beginning)
24937 "EXPORT_FILE_NAME" t))
24938 (file-name-nondirectory buffer-file-name)))
24939 "." html-extension)
24940 (file-name-as-directory
24941 (org-export-directory :html opt-plist)))))
24942 (current-dir (if buffer-file-name
24943 (file-name-directory buffer-file-name)
24944 default-directory))
24945 (buffer (if to-buffer
24946 (cond
24947 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24948 (t (get-buffer-create to-buffer)))
24949 (find-file-noselect filename)))
24950 (org-levels-open (make-vector org-level-max nil))
24951 (date (plist-get opt-plist :date))
24952 (author (plist-get opt-plist :author))
24953 (title (or (and subtree-p (org-export-get-title-from-subtree))
24954 (plist-get opt-plist :title)
24955 (and (not
24956 (plist-get opt-plist :skip-before-1st-heading))
24957 (org-export-grab-title-from-buffer))
24958 (and buffer-file-name
24959 (file-name-sans-extension
24960 (file-name-nondirectory buffer-file-name)))
24961 "UNTITLED"))
24962 (html-table-tag (plist-get opt-plist :html-table-tag))
24963 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24964 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24965 (inquote nil)
24966 (infixed nil)
24967 (in-local-list nil)
24968 (local-list-num nil)
24969 (local-list-indent nil)
24970 (llt org-plain-list-ordered-item-terminator)
24971 (email (plist-get opt-plist :email))
24972 (language (plist-get opt-plist :language))
24973 (lang-words nil)
24974 (target-alist nil) tg
24975 (head-count 0) cnt
24976 (start 0)
24977 (coding-system (and (boundp 'buffer-file-coding-system)
24978 buffer-file-coding-system))
24979 (coding-system-for-write (or org-export-html-coding-system
24980 coding-system))
24981 (save-buffer-coding-system (or org-export-html-coding-system
24982 coding-system))
24983 (charset (and coding-system-for-write
24984 (fboundp 'coding-system-get)
24985 (coding-system-get coding-system-for-write
24986 'mime-charset)))
24987 (region
24988 (buffer-substring
24989 (if region-p (region-beginning) (point-min))
24990 (if region-p (region-end) (point-max))))
24991 (lines
24992 (org-split-string
24993 (org-cleaned-string-for-export
24994 region
24995 :emph-multiline t
24996 :for-html t
24997 :skip-before-1st-heading
24998 (plist-get opt-plist :skip-before-1st-heading)
24999 :drawers (plist-get opt-plist :drawers)
25000 :archived-trees
25001 (plist-get opt-plist :archived-trees)
25002 :add-text
25003 (plist-get opt-plist :text)
25004 :LaTeX-fragments
25005 (plist-get opt-plist :LaTeX-fragments))
25006 "[\r\n]"))
25007 table-open type
25008 table-buffer table-orig-buffer
25009 ind start-is-num starter didclose
25010 rpl path desc descp desc1 desc2 link
25013 (let ((inhibit-read-only t))
25014 (org-unmodified
25015 (remove-text-properties (point-min) (point-max)
25016 '(:org-license-to-kill t))))
25018 (message "Exporting...")
25020 (setq org-min-level (org-get-min-level lines))
25021 (setq org-last-level org-min-level)
25022 (org-init-section-numbers)
25024 (cond
25025 ((and date (string-match "%" date))
25026 (setq date (format-time-string date (current-time))))
25027 (date)
25028 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25030 ;; Get the language-dependent settings
25031 (setq lang-words (or (assoc language org-export-language-setup)
25032 (assoc "en" org-export-language-setup)))
25034 ;; Switch to the output buffer
25035 (set-buffer buffer)
25036 (let ((inhibit-read-only t)) (erase-buffer))
25037 (fundamental-mode)
25039 (and (fboundp 'set-buffer-file-coding-system)
25040 (set-buffer-file-coding-system coding-system-for-write))
25042 (let ((case-fold-search nil)
25043 (org-odd-levels-only odd))
25044 ;; create local variables for all options, to make sure all called
25045 ;; functions get the correct information
25046 (mapc (lambda (x)
25047 (set (make-local-variable (cdr x))
25048 (plist-get opt-plist (car x))))
25049 org-export-plist-vars)
25050 (setq umax (if arg (prefix-numeric-value arg)
25051 org-export-headline-levels))
25052 (setq umax-toc (if (integerp org-export-with-toc)
25053 (min org-export-with-toc umax)
25054 umax))
25055 (unless body-only
25056 ;; File header
25057 (insert (format
25058 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25059 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25060 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25061 lang=\"%s\" xml:lang=\"%s\">
25062 <head>
25063 <title>%s</title>
25064 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25065 <meta name=\"generator\" content=\"Org-mode\"/>
25066 <meta name=\"generated\" content=\"%s\"/>
25067 <meta name=\"author\" content=\"%s\"/>
25069 </head><body>
25071 language language (org-html-expand title)
25072 (or charset "iso-8859-1") date author style))
25074 (insert (or (plist-get opt-plist :preamble) ""))
25076 (when (plist-get opt-plist :auto-preamble)
25077 (if title (insert (format org-export-html-title-format
25078 (org-html-expand title))))))
25080 (if (and org-export-with-toc (not body-only))
25081 (progn
25082 (push (format "<h%d>%s</h%d>\n"
25083 org-export-html-toplevel-hlevel
25084 (nth 3 lang-words)
25085 org-export-html-toplevel-hlevel)
25086 thetoc)
25087 (push "<ul>\n<li>" thetoc)
25088 (setq lines
25089 (mapcar '(lambda (line)
25090 (if (string-match org-todo-line-regexp line)
25091 ;; This is a headline
25092 (progn
25093 (setq have-headings t)
25094 (setq level (- (match-end 1) (match-beginning 1))
25095 level (org-tr-level level)
25096 txt (save-match-data
25097 (org-html-expand
25098 (org-export-cleanup-toc-line
25099 (match-string 3 line))))
25100 todo
25101 (or (and org-export-mark-todo-in-toc
25102 (match-beginning 2)
25103 (not (member (match-string 2 line)
25104 org-done-keywords)))
25105 ; TODO, not DONE
25106 (and org-export-mark-todo-in-toc
25107 (= level umax-toc)
25108 (org-search-todo-below
25109 line lines level))))
25110 (if (string-match
25111 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25112 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25113 (if (string-match quote-re0 txt)
25114 (setq txt (replace-match "" t t txt)))
25115 (if org-export-with-section-numbers
25116 (setq txt (concat (org-section-number level)
25117 " " txt)))
25118 (if (<= level (max umax umax-toc))
25119 (setq head-count (+ head-count 1)))
25120 (if (<= level umax-toc)
25121 (progn
25122 (if (> level org-last-level)
25123 (progn
25124 (setq cnt (- level org-last-level))
25125 (while (>= (setq cnt (1- cnt)) 0)
25126 (push "\n<ul>\n<li>" thetoc))
25127 (push "\n" thetoc)))
25128 (if (< level org-last-level)
25129 (progn
25130 (setq cnt (- org-last-level level))
25131 (while (>= (setq cnt (1- cnt)) 0)
25132 (push "</li>\n</ul>" thetoc))
25133 (push "\n" thetoc)))
25134 ;; Check for targets
25135 (while (string-match org-target-regexp line)
25136 (setq tg (match-string 1 line)
25137 line (replace-match
25138 (concat "@<span class=\"target\">" tg "@</span> ")
25139 t t line))
25140 (push (cons (org-solidify-link-text tg)
25141 (format "sec-%d" head-count))
25142 target-alist))
25143 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25144 (setq txt (replace-match "" t t txt)))
25145 (push
25146 (format
25147 (if todo
25148 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25149 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25150 head-count txt) thetoc)
25152 (setq org-last-level level))
25154 line)
25155 lines))
25156 (while (> org-last-level (1- org-min-level))
25157 (setq org-last-level (1- org-last-level))
25158 (push "</li>\n</ul>\n" thetoc))
25159 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25161 (setq head-count 0)
25162 (org-init-section-numbers)
25164 (while (setq line (pop lines) origline line)
25165 (catch 'nextline
25167 ;; end of quote section?
25168 (when (and inquote (string-match "^\\*+ " line))
25169 (insert "</pre>\n")
25170 (setq inquote nil))
25171 ;; inside a quote section?
25172 (when inquote
25173 (insert (org-html-protect line) "\n")
25174 (throw 'nextline nil))
25176 ;; verbatim lines
25177 (when (and org-export-with-fixed-width
25178 (string-match "^[ \t]*:\\(.*\\)" line))
25179 (when (not infixed)
25180 (setq infixed t)
25181 (insert "<pre>\n"))
25182 (insert (org-html-protect (match-string 1 line)) "\n")
25183 (when (and lines
25184 (not (string-match "^[ \t]*\\(:.*\\)"
25185 (car lines))))
25186 (setq infixed nil)
25187 (insert "</pre>\n"))
25188 (throw 'nextline nil))
25190 ;; Protected HTML
25191 (when (get-text-property 0 'org-protected line)
25192 (let (par)
25193 (when (re-search-backward
25194 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25195 (setq par (match-string 1))
25196 (replace-match "\\2\n"))
25197 (insert line "\n")
25198 (while (and lines
25199 (or (= (length (car lines)) 0)
25200 (get-text-property 0 'org-protected (car lines))))
25201 (insert (pop lines) "\n"))
25202 (and par (insert "<p>\n")))
25203 (throw 'nextline nil))
25205 ;; Horizontal line
25206 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25207 (insert "\n<hr/>\n")
25208 (throw 'nextline nil))
25210 ;; make targets to anchors
25211 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25212 (cond
25213 ((match-end 2)
25214 (setq line (replace-match
25215 (concat "@<a name=\""
25216 (org-solidify-link-text (match-string 1 line))
25217 "\">\\nbsp@</a>")
25218 t t line)))
25219 ((and org-export-with-toc (equal (string-to-char line) ?*))
25220 (setq line (replace-match
25221 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25222 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25223 t t line)))
25225 (setq line (replace-match
25226 (concat "@<a name=\""
25227 (org-solidify-link-text (match-string 1 line))
25228 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25229 t t line)))))
25231 (setq line (org-html-handle-time-stamps line))
25233 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25234 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25235 ;; Also handle sub_superscripts and checkboxes
25236 (or (string-match org-table-hline-regexp line)
25237 (setq line (org-html-expand line)))
25239 ;; Format the links
25240 (setq start 0)
25241 (while (string-match org-bracket-link-analytic-regexp line start)
25242 (setq start (match-beginning 0))
25243 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25244 (setq path (match-string 3 line))
25245 (setq desc1 (if (match-end 5) (match-string 5 line))
25246 desc2 (if (match-end 2) (concat type ":" path) path)
25247 descp (and desc1 (not (equal desc1 desc2)))
25248 desc (or desc1 desc2))
25249 ;; Make an image out of the description if that is so wanted
25250 (when (and descp (org-file-image-p desc))
25251 (save-match-data
25252 (if (string-match "^file:" desc)
25253 (setq desc (substring desc (match-end 0)))))
25254 (setq desc (concat "<img src=\"" desc "\"/>")))
25255 ;; FIXME: do we need to unescape here somewhere?
25256 (cond
25257 ((equal type "internal")
25258 (setq rpl
25259 (concat
25260 "<a href=\"#"
25261 (org-solidify-link-text
25262 (save-match-data (org-link-unescape path)) target-alist)
25263 "\">" desc "</a>")))
25264 ((member type '("http" "https"))
25265 ;; standard URL, just check if we need to inline an image
25266 (if (and (or (eq t org-export-html-inline-images)
25267 (and org-export-html-inline-images (not descp)))
25268 (org-file-image-p path))
25269 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25270 (setq link (concat type ":" path))
25271 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25272 ((member type '("ftp" "mailto" "news"))
25273 ;; standard URL
25274 (setq link (concat type ":" path))
25275 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25276 ((string= type "file")
25277 ;; FILE link
25278 (let* ((filename path)
25279 (abs-p (file-name-absolute-p filename))
25280 thefile file-is-image-p search)
25281 (save-match-data
25282 (if (string-match "::\\(.*\\)" filename)
25283 (setq search (match-string 1 filename)
25284 filename (replace-match "" t nil filename)))
25285 (setq valid
25286 (if (functionp link-validate)
25287 (funcall link-validate filename current-dir)
25289 (setq file-is-image-p (org-file-image-p filename))
25290 (setq thefile (if abs-p (expand-file-name filename) filename))
25291 (when (and org-export-html-link-org-files-as-html
25292 (string-match "\\.org$" thefile))
25293 (setq thefile (concat (substring thefile 0
25294 (match-beginning 0))
25295 "." html-extension))
25296 (if (and search
25297 ;; make sure this is can be used as target search
25298 (not (string-match "^[0-9]*$" search))
25299 (not (string-match "^\\*" search))
25300 (not (string-match "^/.*/$" search)))
25301 (setq thefile (concat thefile "#"
25302 (org-solidify-link-text
25303 (org-link-unescape search)))))
25304 (when (string-match "^file:" desc)
25305 (setq desc (replace-match "" t t desc))
25306 (if (string-match "\\.org$" desc)
25307 (setq desc (replace-match "" t t desc))))))
25308 (setq rpl (if (and file-is-image-p
25309 (or (eq t org-export-html-inline-images)
25310 (and org-export-html-inline-images
25311 (not descp))))
25312 (concat "<img src=\"" thefile "\"/>")
25313 (concat "<a href=\"" thefile "\">" desc "</a>")))
25314 (if (not valid) (setq rpl desc))))
25315 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25316 (setq rpl (concat "<i>&lt;" type ":"
25317 (save-match-data (org-link-unescape path))
25318 "&gt;</i>"))))
25319 (setq line (replace-match rpl t t line)
25320 start (+ start (length rpl))))
25322 ;; TODO items
25323 (if (and (string-match org-todo-line-regexp line)
25324 (match-beginning 2))
25326 (setq line
25327 (concat (substring line 0 (match-beginning 2))
25328 "<span class=\""
25329 (if (member (match-string 2 line)
25330 org-done-keywords)
25331 "done" "todo")
25332 "\">" (match-string 2 line)
25333 "</span>" (substring line (match-end 2)))))
25335 ;; Does this contain a reference to a footnote?
25336 (when org-export-with-footnotes
25337 (setq start 0)
25338 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25339 (if (get-text-property (match-beginning 2) 'org-protected line)
25340 (setq start (match-end 2))
25341 (let ((n (match-string 2 line)))
25342 (setq line
25343 (replace-match
25344 (format
25345 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25346 (match-string 1 line) n n n)
25347 t t line))))))
25349 (cond
25350 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25351 ;; This is a headline
25352 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25353 txt (match-string 2 line))
25354 (if (string-match quote-re0 txt)
25355 (setq txt (replace-match "" t t txt)))
25356 (if (<= level (max umax umax-toc))
25357 (setq head-count (+ head-count 1)))
25358 (when in-local-list
25359 ;; Close any local lists before inserting a new header line
25360 (while local-list-num
25361 (org-close-li)
25362 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25363 (pop local-list-num))
25364 (setq local-list-indent nil
25365 in-local-list nil))
25366 (setq first-heading-pos (or first-heading-pos (point)))
25367 (org-html-level-start level txt umax
25368 (and org-export-with-toc (<= level umax))
25369 head-count)
25370 ;; QUOTES
25371 (when (string-match quote-re line)
25372 (insert "<pre>")
25373 (setq inquote t)))
25375 ((and org-export-with-tables
25376 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25377 (if (not table-open)
25378 ;; New table starts
25379 (setq table-open t table-buffer nil table-orig-buffer nil))
25380 ;; Accumulate lines
25381 (setq table-buffer (cons line table-buffer)
25382 table-orig-buffer (cons origline table-orig-buffer))
25383 (when (or (not lines)
25384 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25385 (car lines))))
25386 (setq table-open nil
25387 table-buffer (nreverse table-buffer)
25388 table-orig-buffer (nreverse table-orig-buffer))
25389 (org-close-par-maybe)
25390 (insert (org-format-table-html table-buffer table-orig-buffer))))
25392 ;; Normal lines
25393 (when (string-match
25394 (cond
25395 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25396 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25397 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25398 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25399 line)
25400 (setq ind (org-get-string-indentation line)
25401 start-is-num (match-beginning 4)
25402 starter (if (match-beginning 2)
25403 (substring (match-string 2 line) 0 -1))
25404 line (substring line (match-beginning 5)))
25405 (unless (string-match "[^ \t]" line)
25406 ;; empty line. Pretend indentation is large.
25407 (setq ind (if org-empty-line-terminates-plain-lists
25409 (1+ (or (car local-list-indent) 1)))))
25410 (setq didclose nil)
25411 (while (and in-local-list
25412 (or (and (= ind (car local-list-indent))
25413 (not starter))
25414 (< ind (car local-list-indent))))
25415 (setq didclose t)
25416 (org-close-li)
25417 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25418 (pop local-list-num) (pop local-list-indent)
25419 (setq in-local-list local-list-indent))
25420 (cond
25421 ((and starter
25422 (or (not in-local-list)
25423 (> ind (car local-list-indent))))
25424 ;; Start new (level of) list
25425 (org-close-par-maybe)
25426 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25427 (push start-is-num local-list-num)
25428 (push ind local-list-indent)
25429 (setq in-local-list t))
25430 (starter
25431 ;; continue current list
25432 (org-close-li)
25433 (insert "<li>\n"))
25434 (didclose
25435 ;; we did close a list, normal text follows: need <p>
25436 (org-open-par)))
25437 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25438 (setq line
25439 (replace-match
25440 (if (equal (match-string 1 line) "X")
25441 "<b>[X]</b>"
25442 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25443 t t line))))
25445 ;; Empty lines start a new paragraph. If hand-formatted lists
25446 ;; are not fully interpreted, lines starting with "-", "+", "*"
25447 ;; also start a new paragraph.
25448 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25450 ;; Is this the start of a footnote?
25451 (when org-export-with-footnotes
25452 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25453 (org-close-par-maybe)
25454 (let ((n (match-string 1 line)))
25455 (setq line (replace-match
25456 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25458 ;; Check if the line break needs to be conserved
25459 (cond
25460 ((string-match "\\\\\\\\[ \t]*$" line)
25461 (setq line (replace-match "<br/>" t t line)))
25462 (org-export-preserve-breaks
25463 (setq line (concat line "<br/>"))))
25465 (insert line "\n")))))
25467 ;; Properly close all local lists and other lists
25468 (when inquote (insert "</pre>\n"))
25469 (when in-local-list
25470 ;; Close any local lists before inserting a new header line
25471 (while local-list-num
25472 (org-close-li)
25473 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25474 (pop local-list-num))
25475 (setq local-list-indent nil
25476 in-local-list nil))
25477 (org-html-level-start 1 nil umax
25478 (and org-export-with-toc (<= level umax))
25479 head-count)
25481 (unless body-only
25482 (when (plist-get opt-plist :auto-postamble)
25483 (insert "<div id=\"postamble\">")
25484 (when (and org-export-author-info author)
25485 (insert "<p class=\"author\"> "
25486 (nth 1 lang-words) ": " author "\n")
25487 (when email
25488 (if (listp (split-string email ",+ *"))
25489 (mapc (lambda(e)
25490 (insert "<a href=\"mailto:" e "\">&lt;"
25491 e "&gt;</a>\n"))
25492 (split-string email ",+ *"))
25493 (insert "<a href=\"mailto:" email "\">&lt;"
25494 email "&gt;</a>\n")))
25495 (insert "</p>\n"))
25496 (when (and date org-export-time-stamp-file)
25497 (insert "<p class=\"date\"> "
25498 (nth 2 lang-words) ": "
25499 date "</p>\n"))
25500 (insert "</div>"))
25502 (if org-export-html-with-timestamp
25503 (insert org-export-html-html-helper-timestamp))
25504 (insert (or (plist-get opt-plist :postamble) ""))
25505 (insert "</body>\n</html>\n"))
25507 (normal-mode)
25508 (if (eq major-mode default-major-mode) (html-mode))
25510 ;; insert the table of contents
25511 (goto-char (point-min))
25512 (when thetoc
25513 (if (or (re-search-forward
25514 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25515 (re-search-forward
25516 "\\[TABLE-OF-CONTENTS\\]" nil t))
25517 (progn
25518 (goto-char (match-beginning 0))
25519 (replace-match ""))
25520 (goto-char first-heading-pos)
25521 (when (looking-at "\\s-*</p>")
25522 (goto-char (match-end 0))
25523 (insert "\n")))
25524 (insert "<div id=\"table-of-contents\">\n")
25525 (mapc 'insert thetoc)
25526 (insert "</div>\n"))
25527 ;; remove empty paragraphs and lists
25528 (goto-char (point-min))
25529 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25530 (replace-match ""))
25531 (goto-char (point-min))
25532 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25533 (replace-match ""))
25534 (goto-char (point-min))
25535 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25536 (replace-match ""))
25537 ;; Convert whitespace place holders
25538 (goto-char (point-min))
25539 (let (beg end n)
25540 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25541 (setq n (get-text-property beg 'org-whitespace)
25542 end (next-single-property-change beg 'org-whitespace))
25543 (goto-char beg)
25544 (delete-region beg end)
25545 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25546 (make-string n ?x)))))
25548 (or to-buffer (save-buffer))
25549 (goto-char (point-min))
25550 (message "Exporting... done")
25551 (if (eq to-buffer 'string)
25552 (prog1 (buffer-substring (point-min) (point-max))
25553 (kill-buffer (current-buffer)))
25554 (current-buffer)))))
25556 (defvar org-table-colgroup-info nil)
25557 (defun org-format-table-ascii (lines)
25558 "Format a table for ascii export."
25559 (if (stringp lines)
25560 (setq lines (org-split-string lines "\n")))
25561 (if (not (string-match "^[ \t]*|" (car lines)))
25562 ;; Table made by table.el - test for spanning
25563 lines
25565 ;; A normal org table
25566 ;; Get rid of hlines at beginning and end
25567 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25568 (setq lines (nreverse lines))
25569 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25570 (setq lines (nreverse lines))
25571 (when org-export-table-remove-special-lines
25572 ;; Check if the table has a marking column. If yes remove the
25573 ;; column and the special lines
25574 (setq lines (org-table-clean-before-export lines)))
25575 ;; Get rid of the vertical lines except for grouping
25576 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25577 rtn line vl1 start)
25578 (while (setq line (pop lines))
25579 (if (string-match org-table-hline-regexp line)
25580 (and (string-match "|\\(.*\\)|" line)
25581 (setq line (replace-match " \\1" t nil line)))
25582 (setq start 0 vl1 vl)
25583 (while (string-match "|" line start)
25584 (setq start (match-end 0))
25585 (or (pop vl1) (setq line (replace-match " " t t line)))))
25586 (push line rtn))
25587 (nreverse rtn))))
25589 (defun org-colgroup-info-to-vline-list (info)
25590 (let (vl new last)
25591 (while info
25592 (setq last new new (pop info))
25593 (if (or (memq last '(:end :startend))
25594 (memq new '(:start :startend)))
25595 (push t vl)
25596 (push nil vl)))
25597 (setq vl (nreverse vl))
25598 (and vl (setcar vl nil))
25599 vl))
25601 (defun org-format-table-html (lines olines)
25602 "Find out which HTML converter to use and return the HTML code."
25603 (if (stringp lines)
25604 (setq lines (org-split-string lines "\n")))
25605 (if (string-match "^[ \t]*|" (car lines))
25606 ;; A normal org table
25607 (org-format-org-table-html lines)
25608 ;; Table made by table.el - test for spanning
25609 (let* ((hlines (delq nil (mapcar
25610 (lambda (x)
25611 (if (string-match "^[ \t]*\\+-" x) x
25612 nil))
25613 lines)))
25614 (first (car hlines))
25615 (ll (and (string-match "\\S-+" first)
25616 (match-string 0 first)))
25617 (re (concat "^[ \t]*" (regexp-quote ll)))
25618 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25619 hlines))))
25620 (if (and (not spanning)
25621 (not org-export-prefer-native-exporter-for-tables))
25622 ;; We can use my own converter with HTML conversions
25623 (org-format-table-table-html lines)
25624 ;; Need to use the code generator in table.el, with the original text.
25625 (org-format-table-table-html-using-table-generate-source olines)))))
25627 (defun org-format-org-table-html (lines &optional splice)
25628 "Format a table into HTML."
25629 ;; Get rid of hlines at beginning and end
25630 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25631 (setq lines (nreverse lines))
25632 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25633 (setq lines (nreverse lines))
25634 (when org-export-table-remove-special-lines
25635 ;; Check if the table has a marking column. If yes remove the
25636 ;; column and the special lines
25637 (setq lines (org-table-clean-before-export lines)))
25639 (let ((head (and org-export-highlight-first-table-line
25640 (delq nil (mapcar
25641 (lambda (x) (string-match "^[ \t]*|-" x))
25642 (cdr lines)))))
25643 (nlines 0) fnum i
25644 tbopen line fields html gr colgropen)
25645 (if splice (setq head nil))
25646 (unless splice (push (if head "<thead>" "<tbody>") html))
25647 (setq tbopen t)
25648 (while (setq line (pop lines))
25649 (catch 'next-line
25650 (if (string-match "^[ \t]*|-" line)
25651 (progn
25652 (unless splice
25653 (push (if head "</thead>" "</tbody>") html)
25654 (if lines (push "<tbody>" html) (setq tbopen nil)))
25655 (setq head nil) ;; head ends here, first time around
25656 ;; ignore this line
25657 (throw 'next-line t)))
25658 ;; Break the line into fields
25659 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25660 (unless fnum (setq fnum (make-vector (length fields) 0)))
25661 (setq nlines (1+ nlines) i -1)
25662 (push (concat "<tr>"
25663 (mapconcat
25664 (lambda (x)
25665 (setq i (1+ i))
25666 (if (and (< i nlines)
25667 (string-match org-table-number-regexp x))
25668 (incf (aref fnum i)))
25669 (if head
25670 (concat (car org-export-table-header-tags) x
25671 (cdr org-export-table-header-tags))
25672 (concat (car org-export-table-data-tags) x
25673 (cdr org-export-table-data-tags))))
25674 fields "")
25675 "</tr>")
25676 html)))
25677 (unless splice (if tbopen (push "</tbody>" html)))
25678 (unless splice (push "</table>\n" html))
25679 (setq html (nreverse html))
25680 (unless splice
25681 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25682 (push (mapconcat
25683 (lambda (x)
25684 (setq gr (pop org-table-colgroup-info))
25685 (format "%s<col align=\"%s\"></col>%s"
25686 (if (memq gr '(:start :startend))
25687 (prog1
25688 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25689 (setq colgropen t))
25691 (if (> (/ (float x) nlines) org-table-number-fraction)
25692 "right" "left")
25693 (if (memq gr '(:end :startend))
25694 (progn (setq colgropen nil) "</colgroup>")
25695 "")))
25696 fnum "")
25697 html)
25698 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25699 (push html-table-tag html))
25700 (concat (mapconcat 'identity html "\n") "\n")))
25702 (defun org-table-clean-before-export (lines)
25703 "Check if the table has a marking column.
25704 If yes remove the column and the special lines."
25705 (setq org-table-colgroup-info nil)
25706 (if (memq nil
25707 (mapcar
25708 (lambda (x) (or (string-match "^[ \t]*|-" x)
25709 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25710 lines))
25711 (progn
25712 (setq org-table-clean-did-remove-column nil)
25713 (delq nil
25714 (mapcar
25715 (lambda (x)
25716 (cond
25717 ((string-match "^[ \t]*| */ *|" x)
25718 (setq org-table-colgroup-info
25719 (mapcar (lambda (x)
25720 (cond ((member x '("<" "&lt;")) :start)
25721 ((member x '(">" "&gt;")) :end)
25722 ((member x '("<>" "&lt;&gt;")) :startend)
25723 (t nil)))
25724 (org-split-string x "[ \t]*|[ \t]*")))
25725 nil)
25726 (t x)))
25727 lines)))
25728 (setq org-table-clean-did-remove-column t)
25729 (delq nil
25730 (mapcar
25731 (lambda (x)
25732 (cond
25733 ((string-match "^[ \t]*| */ *|" x)
25734 (setq org-table-colgroup-info
25735 (mapcar (lambda (x)
25736 (cond ((member x '("<" "&lt;")) :start)
25737 ((member x '(">" "&gt;")) :end)
25738 ((member x '("<>" "&lt;&gt;")) :startend)
25739 (t nil)))
25740 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25741 nil)
25742 ((string-match "^[ \t]*| *[!_^/] *|" x)
25743 nil) ; ignore this line
25744 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25745 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25746 ;; remove the first column
25747 (replace-match "\\1|" t nil x))))
25748 lines))))
25750 (defun org-format-table-table-html (lines)
25751 "Format a table generated by table.el into HTML.
25752 This conversion does *not* use `table-generate-source' from table.el.
25753 This has the advantage that Org-mode's HTML conversions can be used.
25754 But it has the disadvantage, that no cell- or row-spanning is allowed."
25755 (let (line field-buffer
25756 (head org-export-highlight-first-table-line)
25757 fields html empty)
25758 (setq html (concat html-table-tag "\n"))
25759 (while (setq line (pop lines))
25760 (setq empty "&nbsp;")
25761 (catch 'next-line
25762 (if (string-match "^[ \t]*\\+-" line)
25763 (progn
25764 (if field-buffer
25765 (progn
25766 (setq
25767 html
25768 (concat
25769 html
25770 "<tr>"
25771 (mapconcat
25772 (lambda (x)
25773 (if (equal x "") (setq x empty))
25774 (if head
25775 (concat (car org-export-table-header-tags) x
25776 (cdr org-export-table-header-tags))
25777 (concat (car org-export-table-data-tags) x
25778 (cdr org-export-table-data-tags))))
25779 field-buffer "\n")
25780 "</tr>\n"))
25781 (setq head nil)
25782 (setq field-buffer nil)))
25783 ;; Ignore this line
25784 (throw 'next-line t)))
25785 ;; Break the line into fields and store the fields
25786 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25787 (if field-buffer
25788 (setq field-buffer (mapcar
25789 (lambda (x)
25790 (concat x "<br/>" (pop fields)))
25791 field-buffer))
25792 (setq field-buffer fields))))
25793 (setq html (concat html "</table>\n"))
25794 html))
25796 (defun org-format-table-table-html-using-table-generate-source (lines)
25797 "Format a table into html, using `table-generate-source' from table.el.
25798 This has the advantage that cell- or row-spanning is allowed.
25799 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25800 (require 'table)
25801 (with-current-buffer (get-buffer-create " org-tmp1 ")
25802 (erase-buffer)
25803 (insert (mapconcat 'identity lines "\n"))
25804 (goto-char (point-min))
25805 (if (not (re-search-forward "|[^+]" nil t))
25806 (error "Error processing table"))
25807 (table-recognize-table)
25808 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25809 (table-generate-source 'html " org-tmp2 ")
25810 (set-buffer " org-tmp2 ")
25811 (buffer-substring (point-min) (point-max))))
25813 (defun org-html-handle-time-stamps (s)
25814 "Format time stamps in string S, or remove them."
25815 (catch 'exit
25816 (let (r b)
25817 (while (string-match org-maybe-keyword-time-regexp s)
25818 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25819 ;; never export CLOCK
25820 (throw 'exit ""))
25821 (or b (setq b (substring s 0 (match-beginning 0))))
25822 (if (not org-export-with-timestamps)
25823 (setq r (concat r (substring s 0 (match-beginning 0)))
25824 s (substring s (match-end 0)))
25825 (setq r (concat
25826 r (substring s 0 (match-beginning 0))
25827 (if (match-end 1)
25828 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25829 (match-string 1 s)))
25830 (format " @<span class=\"timestamp\">%s@</span>"
25831 (substring
25832 (org-translate-time (match-string 3 s)) 1 -1)))
25833 s (substring s (match-end 0)))))
25834 ;; Line break if line started and ended with time stamp stuff
25835 (if (not r)
25837 (setq r (concat r s))
25838 (unless (string-match "\\S-" (concat b s))
25839 (setq r (concat r "@<br/>")))
25840 r))))
25842 (defun org-html-protect (s)
25843 ;; convert & to &amp;, < to &lt; and > to &gt;
25844 (let ((start 0))
25845 (while (string-match "&" s start)
25846 (setq s (replace-match "&amp;" t t s)
25847 start (1+ (match-beginning 0))))
25848 (while (string-match "<" s)
25849 (setq s (replace-match "&lt;" t t s)))
25850 (while (string-match ">" s)
25851 (setq s (replace-match "&gt;" t t s))))
25854 (defun org-export-cleanup-toc-line (s)
25855 "Remove tags and time staps from lines going into the toc."
25856 (when (memq org-export-with-tags '(not-in-toc nil))
25857 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25858 (setq s (replace-match "" t t s))))
25859 (when org-export-remove-timestamps-from-toc
25860 (while (string-match org-maybe-keyword-time-regexp s)
25861 (setq s (replace-match "" t t s))))
25862 (while (string-match org-bracket-link-regexp s)
25863 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25864 t t s)))
25867 (defun org-html-expand (string)
25868 "Prepare STRING for HTML export. Applies all active conversions.
25869 If there are links in the string, don't modify these."
25870 (let* ((re (concat org-bracket-link-regexp "\\|"
25871 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25872 m s l res)
25873 (while (setq m (string-match re string))
25874 (setq s (substring string 0 m)
25875 l (match-string 0 string)
25876 string (substring string (match-end 0)))
25877 (push (org-html-do-expand s) res)
25878 (push l res))
25879 (push (org-html-do-expand string) res)
25880 (apply 'concat (nreverse res))))
25882 (defun org-html-do-expand (s)
25883 "Apply all active conversions to translate special ASCII to HTML."
25884 (setq s (org-html-protect s))
25885 (if org-export-html-expand
25886 (let ((start 0))
25887 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25888 (setq s (replace-match "<\\1>" t nil s)))))
25889 (if org-export-with-emphasize
25890 (setq s (org-export-html-convert-emphasize s)))
25891 (if org-export-with-special-strings
25892 (setq s (org-export-html-convert-special-strings s)))
25893 (if org-export-with-sub-superscripts
25894 (setq s (org-export-html-convert-sub-super s)))
25895 (if org-export-with-TeX-macros
25896 (let ((start 0) wd ass)
25897 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25898 (if (get-text-property (match-beginning 0) 'org-protected s)
25899 (setq start (match-end 0))
25900 (setq wd (match-string 1 s))
25901 (if (setq ass (assoc wd org-html-entities))
25902 (setq s (replace-match (or (cdr ass)
25903 (concat "&" (car ass) ";"))
25904 t t s))
25905 (setq start (+ start (length wd))))))))
25908 (defun org-create-multibrace-regexp (left right n)
25909 "Create a regular expression which will match a balanced sexp.
25910 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25911 as single character strings.
25912 The regexp returned will match the entire expression including the
25913 delimiters. It will also define a single group which contains the
25914 match except for the outermost delimiters. The maximum depth of
25915 stacked delimiters is N. Escaping delimiters is not possible."
25916 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25917 (or "\\|")
25918 (re nothing)
25919 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25920 (while (> n 1)
25921 (setq n (1- n)
25922 re (concat re or next)
25923 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25924 (concat left "\\(" re "\\)" right)))
25926 (defvar org-match-substring-regexp
25927 (concat
25928 "\\([^\\]\\)\\([_^]\\)\\("
25929 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25930 "\\|"
25931 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25932 "\\|"
25933 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25934 "The regular expression matching a sub- or superscript.")
25936 (defvar org-match-substring-with-braces-regexp
25937 (concat
25938 "\\([^\\]\\)\\([_^]\\)\\("
25939 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25940 "\\)")
25941 "The regular expression matching a sub- or superscript, forcing braces.")
25943 (defconst org-export-html-special-string-regexps
25944 '(("\\\\-" . "&shy;")
25945 ("---\\([^-]\\)" . "&mdash;\\1")
25946 ("--\\([^-]\\)" . "&ndash;\\1")
25947 ("\\.\\.\\." . "&hellip;"))
25948 "Regular expressions for special string conversion.")
25950 (defun org-export-html-convert-special-strings (string)
25951 "Convert special characters in STRING to HTML."
25952 (let ((all org-export-html-special-string-regexps)
25953 e a re rpl start)
25954 (while (setq a (pop all))
25955 (setq re (car a) rpl (cdr a) start 0)
25956 (while (string-match re string start)
25957 (if (get-text-property (match-beginning 0) 'org-protected string)
25958 (setq start (match-end 0))
25959 (setq string (replace-match rpl t nil string)))))
25960 string))
25962 (defun org-export-html-convert-sub-super (string)
25963 "Convert sub- and superscripts in STRING to HTML."
25964 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25965 (while (string-match org-match-substring-regexp string s)
25966 (cond
25967 ((and requireb (match-end 8)) (setq s (match-end 2)))
25968 ((get-text-property (match-beginning 2) 'org-protected string)
25969 (setq s (match-end 2)))
25971 (setq s (match-end 1)
25972 key (if (string= (match-string 2 string) "_") "sub" "sup")
25973 c (or (match-string 8 string)
25974 (match-string 6 string)
25975 (match-string 5 string))
25976 string (replace-match
25977 (concat (match-string 1 string)
25978 "<" key ">" c "</" key ">")
25979 t t string)))))
25980 (while (string-match "\\\\\\([_^]\\)" string)
25981 (setq string (replace-match (match-string 1 string) t t string)))
25982 string))
25984 (defun org-export-html-convert-emphasize (string)
25985 "Apply emphasis."
25986 (let ((s 0) rpl)
25987 (while (string-match org-emph-re string s)
25988 (if (not (equal
25989 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25990 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25991 (setq s (match-beginning 0)
25993 (concat
25994 (match-string 1 string)
25995 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25996 (match-string 4 string)
25997 (nth 3 (assoc (match-string 3 string)
25998 org-emphasis-alist))
25999 (match-string 5 string))
26000 string (replace-match rpl t t string)
26001 s (+ s (- (length rpl) 2)))
26002 (setq s (1+ s))))
26003 string))
26005 (defvar org-par-open nil)
26006 (defun org-open-par ()
26007 "Insert <p>, but first close previous paragraph if any."
26008 (org-close-par-maybe)
26009 (insert "\n<p>")
26010 (setq org-par-open t))
26011 (defun org-close-par-maybe ()
26012 "Close paragraph if there is one open."
26013 (when org-par-open
26014 (insert "</p>")
26015 (setq org-par-open nil)))
26016 (defun org-close-li ()
26017 "Close <li> if necessary."
26018 (org-close-par-maybe)
26019 (insert "</li>\n"))
26021 (defvar body-only) ; dynamically scoped into this.
26022 (defun org-html-level-start (level title umax with-toc head-count)
26023 "Insert a new level in HTML export.
26024 When TITLE is nil, just close all open levels."
26025 (org-close-par-maybe)
26026 (let ((l org-level-max))
26027 (while (>= l level)
26028 (if (aref org-levels-open (1- l))
26029 (progn
26030 (org-html-level-close l umax)
26031 (aset org-levels-open (1- l) nil)))
26032 (setq l (1- l)))
26033 (when title
26034 ;; If title is nil, this means this function is called to close
26035 ;; all levels, so the rest is done only if title is given
26036 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26037 (setq title (replace-match
26038 (if org-export-with-tags
26039 (save-match-data
26040 (concat
26041 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26042 (mapconcat 'identity (org-split-string
26043 (match-string 1 title) ":")
26044 "&nbsp;")
26045 "</span>"))
26047 t t title)))
26048 (if (> level umax)
26049 (progn
26050 (if (aref org-levels-open (1- level))
26051 (progn
26052 (org-close-li)
26053 (insert "<li>" title "<br/>\n"))
26054 (aset org-levels-open (1- level) t)
26055 (org-close-par-maybe)
26056 (insert "<ul>\n<li>" title "<br/>\n")))
26057 (aset org-levels-open (1- level) t)
26058 (if (and org-export-with-section-numbers (not body-only))
26059 (setq title (concat (org-section-number level) " " title)))
26060 (setq level (+ level org-export-html-toplevel-hlevel -1))
26061 (if with-toc
26062 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26063 level level head-count title level))
26064 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26065 (org-open-par)))))
26067 (defun org-html-level-close (level max-outline-level)
26068 "Terminate one level in HTML export."
26069 (if (<= level max-outline-level)
26070 (insert "</div>\n")
26071 (org-close-li)
26072 (insert "</ul>\n")))
26074 ;;; iCalendar export
26076 ;;;###autoload
26077 (defun org-export-icalendar-this-file ()
26078 "Export current file as an iCalendar file.
26079 The iCalendar file will be located in the same directory as the Org-mode
26080 file, but with extension `.ics'."
26081 (interactive)
26082 (org-export-icalendar nil buffer-file-name))
26084 ;;;###autoload
26085 (defun org-export-icalendar-all-agenda-files ()
26086 "Export all files in `org-agenda-files' to iCalendar .ics files.
26087 Each iCalendar file will be located in the same directory as the Org-mode
26088 file, but with extension `.ics'."
26089 (interactive)
26090 (apply 'org-export-icalendar nil (org-agenda-files t)))
26092 ;;;###autoload
26093 (defun org-export-icalendar-combine-agenda-files ()
26094 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26095 The file is stored under the name `org-combined-agenda-icalendar-file'."
26096 (interactive)
26097 (apply 'org-export-icalendar t (org-agenda-files t)))
26099 (defun org-export-icalendar (combine &rest files)
26100 "Create iCalendar files for all elements of FILES.
26101 If COMBINE is non-nil, combine all calendar entries into a single large
26102 file and store it under the name `org-combined-agenda-icalendar-file'."
26103 (save-excursion
26104 (org-prepare-agenda-buffers files)
26105 (let* ((dir (org-export-directory
26106 :ical (list :publishing-directory
26107 org-export-publishing-directory)))
26108 file ical-file ical-buffer category started org-agenda-new-buffers)
26110 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26111 (when combine
26112 (setq ical-file
26113 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26114 org-combined-agenda-icalendar-file
26115 (expand-file-name org-combined-agenda-icalendar-file dir))
26116 ical-buffer (org-get-agenda-file-buffer ical-file))
26117 (set-buffer ical-buffer) (erase-buffer))
26118 (while (setq file (pop files))
26119 (catch 'nextfile
26120 (org-check-agenda-file file)
26121 (set-buffer (org-get-agenda-file-buffer file))
26122 (unless combine
26123 (setq ical-file (concat (file-name-as-directory dir)
26124 (file-name-sans-extension
26125 (file-name-nondirectory buffer-file-name))
26126 ".ics"))
26127 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26128 (with-current-buffer ical-buffer (erase-buffer)))
26129 (setq category (or org-category
26130 (file-name-sans-extension
26131 (file-name-nondirectory buffer-file-name))))
26132 (if (symbolp category) (setq category (symbol-name category)))
26133 (let ((standard-output ical-buffer))
26134 (if combine
26135 (and (not started) (setq started t)
26136 (org-start-icalendar-file org-icalendar-combined-name))
26137 (org-start-icalendar-file category))
26138 (org-print-icalendar-entries combine)
26139 (when (or (and combine (not files)) (not combine))
26140 (org-finish-icalendar-file)
26141 (set-buffer ical-buffer)
26142 (save-buffer)
26143 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26144 (org-release-buffers org-agenda-new-buffers))))
26146 (defvar org-after-save-iCalendar-file-hook nil
26147 "Hook run after an iCalendar file has been saved.
26148 The iCalendar buffer is still current when this hook is run.
26149 A good way to use this is to tell a desktop calenndar application to re-read
26150 the iCalendar file.")
26152 (defun org-print-icalendar-entries (&optional combine)
26153 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26154 When COMBINE is non nil, add the category to each line."
26155 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26156 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26157 (dts (org-ical-ts-to-string
26158 (format-time-string (cdr org-time-stamp-formats) (current-time))
26159 "DTSTART"))
26160 hd ts ts2 state status (inc t) pos b sexp rrule
26161 scheduledp deadlinep tmp pri category entry location summary desc
26162 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26163 (org-refresh-category-properties)
26164 (save-excursion
26165 (goto-char (point-min))
26166 (while (re-search-forward re1 nil t)
26167 (catch :skip
26168 (org-agenda-skip)
26169 (setq pos (match-beginning 0)
26170 ts (match-string 0)
26171 inc t
26172 hd (org-get-heading)
26173 summary (org-icalendar-cleanup-string
26174 (org-entry-get nil "SUMMARY"))
26175 desc (org-icalendar-cleanup-string
26176 (or (org-entry-get nil "DESCRIPTION")
26177 (and org-icalendar-include-body (org-get-entry)))
26178 t org-icalendar-include-body)
26179 location (org-icalendar-cleanup-string
26180 (org-entry-get nil "LOCATION"))
26181 category (org-get-category))
26182 (if (looking-at re2)
26183 (progn
26184 (goto-char (match-end 0))
26185 (setq ts2 (match-string 1) inc nil))
26186 (setq tmp (buffer-substring (max (point-min)
26187 (- pos org-ds-keyword-length))
26188 pos)
26189 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26190 (progn
26191 (setq inc nil)
26192 (replace-match "\\1" t nil ts))
26194 deadlinep (string-match org-deadline-regexp tmp)
26195 scheduledp (string-match org-scheduled-regexp tmp)
26196 ;; donep (org-entry-is-done-p)
26198 (if (or (string-match org-tr-regexp hd)
26199 (string-match org-ts-regexp hd))
26200 (setq hd (replace-match "" t t hd)))
26201 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26202 (setq rrule
26203 (concat "\nRRULE:FREQ="
26204 (cdr (assoc
26205 (match-string 2 ts)
26206 '(("d" . "DAILY")("w" . "WEEKLY")
26207 ("m" . "MONTHLY")("y" . "YEARLY"))))
26208 ";INTERVAL=" (match-string 1 ts)))
26209 (setq rrule ""))
26210 (setq summary (or summary hd))
26211 (if (string-match org-bracket-link-regexp summary)
26212 (setq summary
26213 (replace-match (if (match-end 3)
26214 (match-string 3 summary)
26215 (match-string 1 summary))
26216 t t summary)))
26217 (if deadlinep (setq summary (concat "DL: " summary)))
26218 (if scheduledp (setq summary (concat "S: " summary)))
26219 (if (string-match "\\`<%%" ts)
26220 (with-current-buffer sexp-buffer
26221 (insert (substring ts 1 -1) " " summary "\n"))
26222 (princ (format "BEGIN:VEVENT
26224 %s%s
26225 SUMMARY:%s%s%s
26226 CATEGORIES:%s
26227 END:VEVENT\n"
26228 (org-ical-ts-to-string ts "DTSTART")
26229 (org-ical-ts-to-string ts2 "DTEND" inc)
26230 rrule summary
26231 (if (and desc (string-match "\\S-" desc))
26232 (concat "\nDESCRIPTION: " desc) "")
26233 (if (and location (string-match "\\S-" location))
26234 (concat "\nLOCATION: " location) "")
26235 category)))))
26237 (when (and org-icalendar-include-sexps
26238 (condition-case nil (require 'icalendar) (error nil))
26239 (fboundp 'icalendar-export-region))
26240 ;; Get all the literal sexps
26241 (goto-char (point-min))
26242 (while (re-search-forward "^&?%%(" nil t)
26243 (catch :skip
26244 (org-agenda-skip)
26245 (setq b (match-beginning 0))
26246 (goto-char (1- (match-end 0)))
26247 (forward-sexp 1)
26248 (end-of-line 1)
26249 (setq sexp (buffer-substring b (point)))
26250 (with-current-buffer sexp-buffer
26251 (insert sexp "\n"))
26252 (princ (org-diary-to-ical-string sexp-buffer)))))
26254 (when org-icalendar-include-todo
26255 (goto-char (point-min))
26256 (while (re-search-forward org-todo-line-regexp nil t)
26257 (catch :skip
26258 (org-agenda-skip)
26259 (setq state (match-string 2))
26260 (setq status (if (member state org-done-keywords)
26261 "COMPLETED" "NEEDS-ACTION"))
26262 (when (and state
26263 (or (not (member state org-done-keywords))
26264 (eq org-icalendar-include-todo 'all))
26265 (not (member org-archive-tag (org-get-tags-at)))
26267 (setq hd (match-string 3)
26268 summary (org-icalendar-cleanup-string
26269 (org-entry-get nil "SUMMARY"))
26270 desc (org-icalendar-cleanup-string
26271 (or (org-entry-get nil "DESCRIPTION")
26272 (and org-icalendar-include-body (org-get-entry)))
26273 t org-icalendar-include-body)
26274 location (org-icalendar-cleanup-string
26275 (org-entry-get nil "LOCATION")))
26276 (if (string-match org-bracket-link-regexp hd)
26277 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26278 (match-string 1 hd))
26279 t t hd)))
26280 (if (string-match org-priority-regexp hd)
26281 (setq pri (string-to-char (match-string 2 hd))
26282 hd (concat (substring hd 0 (match-beginning 1))
26283 (substring hd (match-end 1))))
26284 (setq pri org-default-priority))
26285 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26286 (- org-lowest-priority org-highest-priority))))))
26288 (princ (format "BEGIN:VTODO
26290 SUMMARY:%s%s%s
26291 CATEGORIES:%s
26292 SEQUENCE:1
26293 PRIORITY:%d
26294 STATUS:%s
26295 END:VTODO\n"
26297 (or summary hd)
26298 (if (and location (string-match "\\S-" location))
26299 (concat "\nLOCATION: " location) "")
26300 (if (and desc (string-match "\\S-" desc))
26301 (concat "\nDESCRIPTION: " desc) "")
26302 category pri status)))))))))
26304 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26305 "Take out stuff and quote what needs to be quoted.
26306 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26307 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26308 characters."
26309 (if (not s)
26311 (when is-body
26312 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26313 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26314 (while (string-match re s) (setq s (replace-match "" t t s)))
26315 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26316 (let ((start 0))
26317 (while (string-match "\\([,;\\]\\)" s start)
26318 (setq start (+ (match-beginning 0) 2)
26319 s (replace-match "\\\\\\1" nil nil s))))
26320 (when is-body
26321 (while (string-match "[ \t]*\n[ \t]*" s)
26322 (setq s (replace-match "\\n" t t s))))
26323 (setq s (org-trim s))
26324 (if is-body
26325 (if maxlength
26326 (if (and (numberp maxlength)
26327 (> (length s) maxlength))
26328 (setq s (substring s 0 maxlength)))))
26331 (defun org-get-entry ()
26332 "Clean-up description string."
26333 (save-excursion
26334 (org-back-to-heading t)
26335 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26337 (defun org-start-icalendar-file (name)
26338 "Start an iCalendar file by inserting the header."
26339 (let ((user user-full-name)
26340 (name (or name "unknown"))
26341 (timezone (cadr (current-time-zone))))
26342 (princ
26343 (format "BEGIN:VCALENDAR
26344 VERSION:2.0
26345 X-WR-CALNAME:%s
26346 PRODID:-//%s//Emacs with Org-mode//EN
26347 X-WR-TIMEZONE:%s
26348 CALSCALE:GREGORIAN\n" name user timezone))))
26350 (defun org-finish-icalendar-file ()
26351 "Finish an iCalendar file by inserting the END statement."
26352 (princ "END:VCALENDAR\n"))
26354 (defun org-ical-ts-to-string (s keyword &optional inc)
26355 "Take a time string S and convert it to iCalendar format.
26356 KEYWORD is added in front, to make a complete line like DTSTART....
26357 When INC is non-nil, increase the hour by two (if time string contains
26358 a time), or the day by one (if it does not contain a time)."
26359 (let ((t1 (org-parse-time-string s 'nodefault))
26360 t2 fmt have-time time)
26361 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26362 (setq t2 t1 have-time t)
26363 (setq t2 (org-parse-time-string s)))
26364 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26365 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26366 (when inc
26367 (if have-time
26368 (if org-agenda-default-appointment-duration
26369 (setq mi (+ org-agenda-default-appointment-duration mi))
26370 (setq h (+ 2 h)))
26371 (setq d (1+ d))))
26372 (setq time (encode-time s mi h d m y)))
26373 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26374 (concat keyword (format-time-string fmt time))))
26376 ;;; XOXO export
26378 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26379 (with-current-buffer buffer
26380 (apply 'insert output)))
26381 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26383 (defun org-export-as-xoxo (&optional buffer)
26384 "Export the org buffer as XOXO.
26385 The XOXO buffer is named *xoxo-<source buffer name>*"
26386 (interactive (list (current-buffer)))
26387 ;; A quickie abstraction
26389 ;; Output everything as XOXO
26390 (with-current-buffer (get-buffer buffer)
26391 (let* ((pos (point))
26392 (opt-plist (org-combine-plists (org-default-export-plist)
26393 (org-infile-export-plist)))
26394 (filename (concat (file-name-as-directory
26395 (org-export-directory :xoxo opt-plist))
26396 (file-name-sans-extension
26397 (file-name-nondirectory buffer-file-name))
26398 ".html"))
26399 (out (find-file-noselect filename))
26400 (last-level 1)
26401 (hanging-li nil))
26402 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26403 ;; Check the output buffer is empty.
26404 (with-current-buffer out (erase-buffer))
26405 ;; Kick off the output
26406 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26407 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26408 (let* ((hd (match-string-no-properties 1))
26409 (level (length hd))
26410 (text (concat
26411 (match-string-no-properties 2)
26412 (save-excursion
26413 (goto-char (match-end 0))
26414 (let ((str ""))
26415 (catch 'loop
26416 (while 't
26417 (forward-line)
26418 (if (looking-at "^[ \t]\\(.*\\)")
26419 (setq str (concat str (match-string-no-properties 1)))
26420 (throw 'loop str)))))))))
26422 ;; Handle level rendering
26423 (cond
26424 ((> level last-level)
26425 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26427 ((< level last-level)
26428 (dotimes (- (- last-level level) 1)
26429 (if hanging-li
26430 (org-export-as-xoxo-insert-into out "</li>\n"))
26431 (org-export-as-xoxo-insert-into out "</ol>\n"))
26432 (when hanging-li
26433 (org-export-as-xoxo-insert-into out "</li>\n")
26434 (setq hanging-li nil)))
26436 ((equal level last-level)
26437 (if hanging-li
26438 (org-export-as-xoxo-insert-into out "</li>\n")))
26441 (setq last-level level)
26443 ;; And output the new li
26444 (setq hanging-li 't)
26445 (if (equal ?+ (elt text 0))
26446 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26447 (org-export-as-xoxo-insert-into out "<li>" text))))
26449 ;; Finally finish off the ol
26450 (dotimes (- last-level 1)
26451 (if hanging-li
26452 (org-export-as-xoxo-insert-into out "</li>\n"))
26453 (org-export-as-xoxo-insert-into out "</ol>\n"))
26455 (goto-char pos)
26456 ;; Finish the buffer off and clean it up.
26457 (switch-to-buffer-other-window out)
26458 (indent-region (point-min) (point-max) nil)
26459 (save-buffer)
26460 (goto-char (point-min))
26464 ;;;; Key bindings
26466 ;; Make `C-c C-x' a prefix key
26467 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26469 ;; TAB key with modifiers
26470 (org-defkey org-mode-map "\C-i" 'org-cycle)
26471 (org-defkey org-mode-map [(tab)] 'org-cycle)
26472 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26473 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26474 (org-defkey org-mode-map "\M-\t" 'org-complete)
26475 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26476 ;; The following line is necessary under Suse GNU/Linux
26477 (unless (featurep 'xemacs)
26478 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26479 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26480 (define-key org-mode-map [backtab] 'org-shifttab)
26482 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26483 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26484 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26486 ;; Cursor keys with modifiers
26487 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26488 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26489 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26490 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26492 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26493 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26494 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26495 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26497 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26498 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26499 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26500 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26502 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26503 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26505 ;;; Extra keys for tty access.
26506 ;; We only set them when really needed because otherwise the
26507 ;; menus don't show the simple keys
26509 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26510 (not window-system))
26511 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26512 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26513 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26514 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26515 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26516 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26517 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26518 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26519 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26520 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26521 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26522 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26523 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26524 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26525 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26526 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26527 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26528 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26529 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26530 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26531 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26532 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26534 ;; All the other keys
26536 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26537 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26538 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26539 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26540 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26541 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26542 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26543 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26544 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26545 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26546 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26547 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26548 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26549 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26550 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26551 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26552 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26553 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26554 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26555 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26556 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26557 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26558 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26559 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26560 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26561 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26562 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26563 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26564 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26565 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26566 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26567 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26568 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26569 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26570 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26571 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26572 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26573 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26574 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26575 (org-defkey org-mode-map "\C-c^" 'org-sort)
26576 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26577 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26578 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26579 (org-defkey org-mode-map "\C-m" 'org-return)
26580 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26581 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26582 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26583 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26584 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26585 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26586 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26587 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26588 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26589 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26590 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26591 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26592 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26593 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26594 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26595 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26596 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26598 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26599 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26600 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26601 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26603 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26604 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26605 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26606 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26607 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26608 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26609 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26610 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26611 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26612 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26613 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26614 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26616 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26618 (when (featurep 'xemacs)
26619 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26621 (defsubst org-table-p () (org-at-table-p))
26623 (defun org-self-insert-command (N)
26624 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26625 If the cursor is in a table looking at whitespace, the whitespace is
26626 overwritten, and the table is not marked as requiring realignment."
26627 (interactive "p")
26628 (if (and (org-table-p)
26629 (progn
26630 ;; check if we blank the field, and if that triggers align
26631 (and org-table-auto-blank-field
26632 (member last-command
26633 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26634 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26635 ;; got extra space, this field does not determine column width
26636 (let (org-table-may-need-update) (org-table-blank-field))
26637 ;; no extra space, this field may determine column width
26638 (org-table-blank-field)))
26640 (eq N 1)
26641 (looking-at "[^|\n]* |"))
26642 (let (org-table-may-need-update)
26643 (goto-char (1- (match-end 0)))
26644 (delete-backward-char 1)
26645 (goto-char (match-beginning 0))
26646 (self-insert-command N))
26647 (setq org-table-may-need-update t)
26648 (self-insert-command N)
26649 (org-fix-tags-on-the-fly)))
26651 (defun org-fix-tags-on-the-fly ()
26652 (when (and (equal (char-after (point-at-bol)) ?*)
26653 (org-on-heading-p))
26654 (org-align-tags-here org-tags-column)))
26656 (defun org-delete-backward-char (N)
26657 "Like `delete-backward-char', insert whitespace at field end in tables.
26658 When deleting backwards, in tables this function will insert whitespace in
26659 front of the next \"|\" separator, to keep the table aligned. The table will
26660 still be marked for re-alignment if the field did fill the entire column,
26661 because, in this case the deletion might narrow the column."
26662 (interactive "p")
26663 (if (and (org-table-p)
26664 (eq N 1)
26665 (string-match "|" (buffer-substring (point-at-bol) (point)))
26666 (looking-at ".*?|"))
26667 (let ((pos (point))
26668 (noalign (looking-at "[^|\n\r]* |"))
26669 (c org-table-may-need-update))
26670 (backward-delete-char N)
26671 (skip-chars-forward "^|")
26672 (insert " ")
26673 (goto-char (1- pos))
26674 ;; noalign: if there were two spaces at the end, this field
26675 ;; does not determine the width of the column.
26676 (if noalign (setq org-table-may-need-update c)))
26677 (backward-delete-char N)
26678 (org-fix-tags-on-the-fly)))
26680 (defun org-delete-char (N)
26681 "Like `delete-char', but insert whitespace at field end in tables.
26682 When deleting characters, in tables this function will insert whitespace in
26683 front of the next \"|\" separator, to keep the table aligned. The table will
26684 still be marked for re-alignment if the field did fill the entire column,
26685 because, in this case the deletion might narrow the column."
26686 (interactive "p")
26687 (if (and (org-table-p)
26688 (not (bolp))
26689 (not (= (char-after) ?|))
26690 (eq N 1))
26691 (if (looking-at ".*?|")
26692 (let ((pos (point))
26693 (noalign (looking-at "[^|\n\r]* |"))
26694 (c org-table-may-need-update))
26695 (replace-match (concat
26696 (substring (match-string 0) 1 -1)
26697 " |"))
26698 (goto-char pos)
26699 ;; noalign: if there were two spaces at the end, this field
26700 ;; does not determine the width of the column.
26701 (if noalign (setq org-table-may-need-update c)))
26702 (delete-char N))
26703 (delete-char N)
26704 (org-fix-tags-on-the-fly)))
26706 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26707 (put 'org-self-insert-command 'delete-selection t)
26708 (put 'orgtbl-self-insert-command 'delete-selection t)
26709 (put 'org-delete-char 'delete-selection 'supersede)
26710 (put 'org-delete-backward-char 'delete-selection 'supersede)
26712 ;; Make `flyspell-mode' delay after some commands
26713 (put 'org-self-insert-command 'flyspell-delayed t)
26714 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26715 (put 'org-delete-char 'flyspell-delayed t)
26716 (put 'org-delete-backward-char 'flyspell-delayed t)
26718 ;; Make pabbrev-mode expand after org-mode commands
26719 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26720 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26722 ;; How to do this: Measure non-white length of current string
26723 ;; If equal to column width, we should realign.
26725 (defun org-remap (map &rest commands)
26726 "In MAP, remap the functions given in COMMANDS.
26727 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26728 (let (new old)
26729 (while commands
26730 (setq old (pop commands) new (pop commands))
26731 (if (fboundp 'command-remapping)
26732 (org-defkey map (vector 'remap old) new)
26733 (substitute-key-definition old new map global-map)))))
26735 (when (eq org-enable-table-editor 'optimized)
26736 ;; If the user wants maximum table support, we need to hijack
26737 ;; some standard editing functions
26738 (org-remap org-mode-map
26739 'self-insert-command 'org-self-insert-command
26740 'delete-char 'org-delete-char
26741 'delete-backward-char 'org-delete-backward-char)
26742 (org-defkey org-mode-map "|" 'org-force-self-insert))
26744 (defun org-shiftcursor-error ()
26745 "Throw an error because Shift-Cursor command was applied in wrong context."
26746 (error "This command is active in special context like tables, headlines or timestamps"))
26748 (defun org-shifttab (&optional arg)
26749 "Global visibility cycling or move to previous table field.
26750 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26751 on context.
26752 See the individual commands for more information."
26753 (interactive "P")
26754 (cond
26755 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26756 (arg (message "Content view to level: ")
26757 (org-content (prefix-numeric-value arg))
26758 (setq org-cycle-global-status 'overview))
26759 (t (call-interactively 'org-global-cycle))))
26761 (defun org-shiftmetaleft ()
26762 "Promote subtree or delete table column.
26763 Calls `org-promote-subtree', `org-outdent-item',
26764 or `org-table-delete-column', depending on context.
26765 See the individual commands for more information."
26766 (interactive)
26767 (cond
26768 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26769 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26770 ((org-at-item-p) (call-interactively 'org-outdent-item))
26771 (t (org-shiftcursor-error))))
26773 (defun org-shiftmetaright ()
26774 "Demote subtree or insert table column.
26775 Calls `org-demote-subtree', `org-indent-item',
26776 or `org-table-insert-column', depending on context.
26777 See the individual commands for more information."
26778 (interactive)
26779 (cond
26780 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26781 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26782 ((org-at-item-p) (call-interactively 'org-indent-item))
26783 (t (org-shiftcursor-error))))
26785 (defun org-shiftmetaup (&optional arg)
26786 "Move subtree up or kill table row.
26787 Calls `org-move-subtree-up' or `org-table-kill-row' or
26788 `org-move-item-up' depending on context. See the individual commands
26789 for more information."
26790 (interactive "P")
26791 (cond
26792 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26793 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26794 ((org-at-item-p) (call-interactively 'org-move-item-up))
26795 (t (org-shiftcursor-error))))
26796 (defun org-shiftmetadown (&optional arg)
26797 "Move subtree down or insert table row.
26798 Calls `org-move-subtree-down' or `org-table-insert-row' or
26799 `org-move-item-down', depending on context. See the individual
26800 commands for more information."
26801 (interactive "P")
26802 (cond
26803 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26804 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26805 ((org-at-item-p) (call-interactively 'org-move-item-down))
26806 (t (org-shiftcursor-error))))
26808 (defun org-metaleft (&optional arg)
26809 "Promote heading or move table column to left.
26810 Calls `org-do-promote' or `org-table-move-column', depending on context.
26811 With no specific context, calls the Emacs default `backward-word'.
26812 See the individual commands for more information."
26813 (interactive "P")
26814 (cond
26815 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26816 ((or (org-on-heading-p) (org-region-active-p))
26817 (call-interactively 'org-do-promote))
26818 ((org-at-item-p) (call-interactively 'org-outdent-item))
26819 (t (call-interactively 'backward-word))))
26821 (defun org-metaright (&optional arg)
26822 "Demote subtree or move table column to right.
26823 Calls `org-do-demote' or `org-table-move-column', depending on context.
26824 With no specific context, calls the Emacs default `forward-word'.
26825 See the individual commands for more information."
26826 (interactive "P")
26827 (cond
26828 ((org-at-table-p) (call-interactively 'org-table-move-column))
26829 ((or (org-on-heading-p) (org-region-active-p))
26830 (call-interactively 'org-do-demote))
26831 ((org-at-item-p) (call-interactively 'org-indent-item))
26832 (t (call-interactively 'forward-word))))
26834 (defun org-metaup (&optional arg)
26835 "Move subtree up or move table row up.
26836 Calls `org-move-subtree-up' or `org-table-move-row' or
26837 `org-move-item-up', depending on context. See the individual commands
26838 for more information."
26839 (interactive "P")
26840 (cond
26841 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26842 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26843 ((org-at-item-p) (call-interactively 'org-move-item-up))
26844 (t (transpose-lines 1) (beginning-of-line -1))))
26846 (defun org-metadown (&optional arg)
26847 "Move subtree down or move table row down.
26848 Calls `org-move-subtree-down' or `org-table-move-row' or
26849 `org-move-item-down', depending on context. See the individual
26850 commands for more information."
26851 (interactive "P")
26852 (cond
26853 ((org-at-table-p) (call-interactively 'org-table-move-row))
26854 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26855 ((org-at-item-p) (call-interactively 'org-move-item-down))
26856 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26858 (defun org-shiftup (&optional arg)
26859 "Increase item in timestamp or increase priority of current headline.
26860 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26861 depending on context. See the individual commands for more information."
26862 (interactive "P")
26863 (cond
26864 ((org-at-timestamp-p t)
26865 (call-interactively (if org-edit-timestamp-down-means-later
26866 'org-timestamp-down 'org-timestamp-up)))
26867 ((org-on-heading-p) (call-interactively 'org-priority-up))
26868 ((org-at-item-p) (call-interactively 'org-previous-item))
26869 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26871 (defun org-shiftdown (&optional arg)
26872 "Decrease item in timestamp or decrease priority of current headline.
26873 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26874 depending on context. See the individual commands for more information."
26875 (interactive "P")
26876 (cond
26877 ((org-at-timestamp-p t)
26878 (call-interactively (if org-edit-timestamp-down-means-later
26879 'org-timestamp-up 'org-timestamp-down)))
26880 ((org-on-heading-p) (call-interactively 'org-priority-down))
26881 (t (call-interactively 'org-next-item))))
26883 (defun org-shiftright ()
26884 "Next TODO keyword or timestamp one day later, depending on context."
26885 (interactive)
26886 (cond
26887 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26888 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26889 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26890 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26891 (t (org-shiftcursor-error))))
26893 (defun org-shiftleft ()
26894 "Previous TODO keyword or timestamp one day earlier, depending on context."
26895 (interactive)
26896 (cond
26897 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26898 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26899 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26900 ((org-at-property-p)
26901 (call-interactively 'org-property-previous-allowed-value))
26902 (t (org-shiftcursor-error))))
26904 (defun org-shiftcontrolright ()
26905 "Switch to next TODO set."
26906 (interactive)
26907 (cond
26908 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26909 (t (org-shiftcursor-error))))
26911 (defun org-shiftcontrolleft ()
26912 "Switch to previous TODO set."
26913 (interactive)
26914 (cond
26915 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26916 (t (org-shiftcursor-error))))
26918 (defun org-ctrl-c-ret ()
26919 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26920 (interactive)
26921 (cond
26922 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26923 (t (call-interactively 'org-insert-heading))))
26925 (defun org-copy-special ()
26926 "Copy region in table or copy current subtree.
26927 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26928 See the individual commands for more information."
26929 (interactive)
26930 (call-interactively
26931 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26933 (defun org-cut-special ()
26934 "Cut region in table or cut current subtree.
26935 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26936 See the individual commands for more information."
26937 (interactive)
26938 (call-interactively
26939 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26941 (defun org-paste-special (arg)
26942 "Paste rectangular region into table, or past subtree relative to level.
26943 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26944 See the individual commands for more information."
26945 (interactive "P")
26946 (if (org-at-table-p)
26947 (org-table-paste-rectangle)
26948 (org-paste-subtree arg)))
26950 (defun org-ctrl-c-ctrl-c (&optional arg)
26951 "Set tags in headline, or update according to changed information at point.
26953 This command does many different things, depending on context:
26955 - If the cursor is in a headline, prompt for tags and insert them
26956 into the current line, aligned to `org-tags-column'. When called
26957 with prefix arg, realign all tags in the current buffer.
26959 - If the cursor is in one of the special #+KEYWORD lines, this
26960 triggers scanning the buffer for these lines and updating the
26961 information.
26963 - If the cursor is inside a table, realign the table. This command
26964 works even if the automatic table editor has been turned off.
26966 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26967 the entire table.
26969 - If the cursor is a the beginning of a dynamic block, update it.
26971 - If the cursor is inside a table created by the table.el package,
26972 activate that table.
26974 - If the current buffer is a remember buffer, close note and file it.
26975 with a prefix argument, file it without further interaction to the default
26976 location.
26978 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26979 links in this buffer.
26981 - If the cursor is on a numbered item in a plain list, renumber the
26982 ordered list.
26984 - If the cursor is on a checkbox, toggle it."
26985 (interactive "P")
26986 (let ((org-enable-table-editor t))
26987 (cond
26988 ((or org-clock-overlays
26989 org-occur-highlights
26990 org-latex-fragment-image-overlays)
26991 (org-remove-clock-overlays)
26992 (org-remove-occur-highlights)
26993 (org-remove-latex-fragment-image-overlays)
26994 (message "Temporary highlights/overlays removed from current buffer"))
26995 ((and (local-variable-p 'org-finish-function (current-buffer))
26996 (fboundp org-finish-function))
26997 (funcall org-finish-function))
26998 ((org-at-property-p)
26999 (call-interactively 'org-property-action))
27000 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27001 ((org-on-heading-p) (call-interactively 'org-set-tags))
27002 ((org-at-table.el-p)
27003 (require 'table)
27004 (beginning-of-line 1)
27005 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27006 (call-interactively 'table-recognize-table))
27007 ((org-at-table-p)
27008 (org-table-maybe-eval-formula)
27009 (if arg
27010 (call-interactively 'org-table-recalculate)
27011 (org-table-maybe-recalculate-line))
27012 (call-interactively 'org-table-align))
27013 ((org-at-item-checkbox-p)
27014 (call-interactively 'org-toggle-checkbox))
27015 ((org-at-item-p)
27016 (call-interactively 'org-maybe-renumber-ordered-list))
27017 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27018 ;; Dynamic block
27019 (beginning-of-line 1)
27020 (org-update-dblock))
27021 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27022 (cond
27023 ((equal (match-string 1) "TBLFM")
27024 ;; Recalculate the table before this line
27025 (save-excursion
27026 (beginning-of-line 1)
27027 (skip-chars-backward " \r\n\t")
27028 (if (org-at-table-p)
27029 (org-call-with-arg 'org-table-recalculate t))))
27031 (call-interactively 'org-mode-restart))))
27032 (t (error "C-c C-c can do nothing useful at this location.")))))
27034 (defun org-mode-restart ()
27035 "Restart Org-mode, to scan again for special lines.
27036 Also updates the keyword regular expressions."
27037 (interactive)
27038 (let ((org-inhibit-startup t)) (org-mode))
27039 (message "Org-mode restarted to refresh keyword and special line setup"))
27041 (defun org-kill-note-or-show-branches ()
27042 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27043 (interactive)
27044 (if (not org-finish-function)
27045 (call-interactively 'show-branches)
27046 (let ((org-note-abort t))
27047 (funcall org-finish-function))))
27049 (defun org-return (&optional indent)
27050 "Goto next table row or insert a newline.
27051 Calls `org-table-next-row' or `newline', depending on context.
27052 See the individual commands for more information."
27053 (interactive)
27054 (cond
27055 ((bobp) (if indent (newline-and-indent) (newline)))
27056 ((and (org-at-heading-p)
27057 (looking-at
27058 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27059 (org-show-entry)
27060 (end-of-line 1)
27061 (newline))
27062 ((org-at-table-p)
27063 (org-table-justify-field-maybe)
27064 (call-interactively 'org-table-next-row))
27065 (t (if indent (newline-and-indent) (newline)))))
27067 (defun org-return-indent ()
27068 (interactive)
27069 "Goto next table row or insert a newline and indent.
27070 Calls `org-table-next-row' or `newline-and-indent', depending on
27071 context. See the individual commands for more information."
27072 (org-return t))
27074 (defun org-ctrl-c-minus ()
27075 "Insert separator line in table or modify bullet type in list.
27076 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
27077 depending on context."
27078 (interactive)
27079 (cond
27080 ((org-at-table-p)
27081 (call-interactively 'org-table-insert-hline))
27082 ((org-on-heading-p)
27083 ;; Convert to item
27084 (save-excursion
27085 (beginning-of-line 1)
27086 (if (looking-at "\\*+ ")
27087 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27088 ((org-in-item-p)
27089 (call-interactively 'org-cycle-list-bullet))
27090 (t (error "`C-c -' does have no function here."))))
27092 (defun org-meta-return (&optional arg)
27093 "Insert a new heading or wrap a region in a table.
27094 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27095 See the individual commands for more information."
27096 (interactive "P")
27097 (cond
27098 ((org-at-table-p)
27099 (call-interactively 'org-table-wrap-region))
27100 (t (call-interactively 'org-insert-heading))))
27102 ;;; Menu entries
27104 ;; Define the Org-mode menus
27105 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27106 '("Tbl"
27107 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27108 ["Next Field" org-cycle (org-at-table-p)]
27109 ["Previous Field" org-shifttab (org-at-table-p)]
27110 ["Next Row" org-return (org-at-table-p)]
27111 "--"
27112 ["Blank Field" org-table-blank-field (org-at-table-p)]
27113 ["Edit Field" org-table-edit-field (org-at-table-p)]
27114 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27115 "--"
27116 ("Column"
27117 ["Move Column Left" org-metaleft (org-at-table-p)]
27118 ["Move Column Right" org-metaright (org-at-table-p)]
27119 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27120 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27121 ("Row"
27122 ["Move Row Up" org-metaup (org-at-table-p)]
27123 ["Move Row Down" org-metadown (org-at-table-p)]
27124 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27125 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27126 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27127 "--"
27128 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27129 ("Rectangle"
27130 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27131 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27132 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27133 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27134 "--"
27135 ("Calculate"
27136 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27137 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27138 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27139 "--"
27140 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27141 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27142 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27143 "--"
27144 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27145 "--"
27146 ["Sum Column/Rectangle" org-table-sum
27147 (or (org-at-table-p) (org-region-active-p))]
27148 ["Which Column?" org-table-current-column (org-at-table-p)])
27149 ["Debug Formulas"
27150 org-table-toggle-formula-debugger
27151 :style toggle :selected org-table-formula-debug]
27152 ["Show Col/Row Numbers"
27153 org-table-toggle-coordinate-overlays
27154 :style toggle :selected org-table-overlay-coordinates]
27155 "--"
27156 ["Create" org-table-create (and (not (org-at-table-p))
27157 org-enable-table-editor)]
27158 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27159 ["Import from File" org-table-import (not (org-at-table-p))]
27160 ["Export to File" org-table-export (org-at-table-p)]
27161 "--"
27162 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27164 (easy-menu-define org-org-menu org-mode-map "Org menu"
27165 '("Org"
27166 ("Show/Hide"
27167 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27168 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27169 ["Sparse Tree" org-occur t]
27170 ["Reveal Context" org-reveal t]
27171 ["Show All" show-all t]
27172 "--"
27173 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27174 "--"
27175 ["New Heading" org-insert-heading t]
27176 ("Navigate Headings"
27177 ["Up" outline-up-heading t]
27178 ["Next" outline-next-visible-heading t]
27179 ["Previous" outline-previous-visible-heading t]
27180 ["Next Same Level" outline-forward-same-level t]
27181 ["Previous Same Level" outline-backward-same-level t]
27182 "--"
27183 ["Jump" org-goto t])
27184 ("Edit Structure"
27185 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27186 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27187 "--"
27188 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27189 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27190 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27191 "--"
27192 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27193 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27194 ["Demote Heading" org-metaright (not (org-at-table-p))]
27195 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27196 "--"
27197 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27198 "--"
27199 ["Convert to odd levels" org-convert-to-odd-levels t]
27200 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27201 ("Editing"
27202 ["Emphasis..." org-emphasize t])
27203 ("Archive"
27204 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27205 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27206 ; :active t :keys "C-u C-c C-x C-a"]
27207 ["Sparse trees open ARCHIVE trees"
27208 (setq org-sparse-tree-open-archived-trees
27209 (not org-sparse-tree-open-archived-trees))
27210 :style toggle :selected org-sparse-tree-open-archived-trees]
27211 ["Cycling opens ARCHIVE trees"
27212 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27213 :style toggle :selected org-cycle-open-archived-trees]
27214 ["Agenda includes ARCHIVE trees"
27215 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27216 :style toggle :selected (not org-agenda-skip-archived-trees)]
27217 "--"
27218 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27219 ; ["Check and Move Children" (org-archive-subtree '(4))
27220 ; :active t :keys "C-u C-c C-x C-s"]
27222 "--"
27223 ("TODO Lists"
27224 ["TODO/DONE/-" org-todo t]
27225 ("Select keyword"
27226 ["Next keyword" org-shiftright (org-on-heading-p)]
27227 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27228 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27229 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27230 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27231 ["Show TODO Tree" org-show-todo-tree t]
27232 ["Global TODO list" org-todo-list t]
27233 "--"
27234 ["Set Priority" org-priority t]
27235 ["Priority Up" org-shiftup t]
27236 ["Priority Down" org-shiftdown t])
27237 ("TAGS and Properties"
27238 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27239 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27240 "--"
27241 ["Set property" 'org-set-property t]
27242 ["Column view of properties" org-columns t]
27243 ["Insert Column View DBlock" org-insert-columns-dblock t])
27244 ("Dates and Scheduling"
27245 ["Timestamp" org-time-stamp t]
27246 ["Timestamp (inactive)" org-time-stamp-inactive t]
27247 ("Change Date"
27248 ["1 Day Later" org-shiftright t]
27249 ["1 Day Earlier" org-shiftleft t]
27250 ["1 ... Later" org-shiftup t]
27251 ["1 ... Earlier" org-shiftdown t])
27252 ["Compute Time Range" org-evaluate-time-range t]
27253 ["Schedule Item" org-schedule t]
27254 ["Deadline" org-deadline t]
27255 "--"
27256 ["Custom time format" org-toggle-time-stamp-overlays
27257 :style radio :selected org-display-custom-times]
27258 "--"
27259 ["Goto Calendar" org-goto-calendar t]
27260 ["Date from Calendar" org-date-from-calendar t])
27261 ("Logging work"
27262 ["Clock in" org-clock-in t]
27263 ["Clock out" org-clock-out t]
27264 ["Clock cancel" org-clock-cancel t]
27265 ["Goto running clock" org-clock-goto t]
27266 ["Display times" org-clock-display t]
27267 ["Create clock table" org-clock-report t]
27268 "--"
27269 ["Record DONE time"
27270 (progn (setq org-log-done (not org-log-done))
27271 (message "Switching to %s will %s record a timestamp"
27272 (car org-done-keywords)
27273 (if org-log-done "automatically" "not")))
27274 :style toggle :selected org-log-done])
27275 "--"
27276 ["Agenda Command..." org-agenda t]
27277 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27278 ("File List for Agenda")
27279 ("Special views current file"
27280 ["TODO Tree" org-show-todo-tree t]
27281 ["Check Deadlines" org-check-deadlines t]
27282 ["Timeline" org-timeline t]
27283 ["Tags Tree" org-tags-sparse-tree t])
27284 "--"
27285 ("Hyperlinks"
27286 ["Store Link (Global)" org-store-link t]
27287 ["Insert Link" org-insert-link t]
27288 ["Follow Link" org-open-at-point t]
27289 "--"
27290 ["Next link" org-next-link t]
27291 ["Previous link" org-previous-link t]
27292 "--"
27293 ["Descriptive Links"
27294 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27295 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27296 ["Literal Links"
27297 (progn
27298 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27299 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27300 "--"
27301 ["Export/Publish..." org-export t]
27302 ("LaTeX"
27303 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27304 :selected org-cdlatex-mode]
27305 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27306 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27307 ["Modify math symbol" org-cdlatex-math-modify
27308 (org-inside-LaTeX-fragment-p)]
27309 ["Export LaTeX fragments as images"
27310 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27311 :style toggle :selected org-export-with-LaTeX-fragments])
27312 "--"
27313 ("Documentation"
27314 ["Show Version" org-version t]
27315 ["Info Documentation" org-info t])
27316 ("Customize"
27317 ["Browse Org Group" org-customize t]
27318 "--"
27319 ["Expand This Menu" org-create-customize-menu
27320 (fboundp 'customize-menu-create)])
27321 "--"
27322 ["Refresh setup" org-mode-restart t]
27325 (defun org-info (&optional node)
27326 "Read documentation for Org-mode in the info system.
27327 With optional NODE, go directly to that node."
27328 (interactive)
27329 (require 'info)
27330 (Info-goto-node (format "(org)%s" (or node ""))))
27332 (defun org-install-agenda-files-menu ()
27333 (let ((bl (buffer-list)))
27334 (save-excursion
27335 (while bl
27336 (set-buffer (pop bl))
27337 (if (org-mode-p) (setq bl nil)))
27338 (when (org-mode-p)
27339 (easy-menu-change
27340 '("Org") "File List for Agenda"
27341 (append
27342 (list
27343 ["Edit File List" (org-edit-agenda-file-list) t]
27344 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27345 ["Remove Current File from List" org-remove-file t]
27346 ["Cycle through agenda files" org-cycle-agenda-files t]
27347 ["Occur in all agenda files" org-occur-in-agenda-files t]
27348 "--")
27349 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27351 ;;;; Documentation
27353 (defun org-customize ()
27354 "Call the customize function with org as argument."
27355 (interactive)
27356 (customize-browse 'org))
27358 (defun org-create-customize-menu ()
27359 "Create a full customization menu for Org-mode, insert it into the menu."
27360 (interactive)
27361 (if (fboundp 'customize-menu-create)
27362 (progn
27363 (easy-menu-change
27364 '("Org") "Customize"
27365 `(["Browse Org group" org-customize t]
27366 "--"
27367 ,(customize-menu-create 'org)
27368 ["Set" Custom-set t]
27369 ["Save" Custom-save t]
27370 ["Reset to Current" Custom-reset-current t]
27371 ["Reset to Saved" Custom-reset-saved t]
27372 ["Reset to Standard Settings" Custom-reset-standard t]))
27373 (message "\"Org\"-menu now contains full customization menu"))
27374 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27376 ;;;; Miscellaneous stuff
27379 ;;; Generally useful functions
27381 (defun org-context ()
27382 "Return a list of contexts of the current cursor position.
27383 If several contexts apply, all are returned.
27384 Each context entry is a list with a symbol naming the context, and
27385 two positions indicating start and end of the context. Possible
27386 contexts are:
27388 :headline anywhere in a headline
27389 :headline-stars on the leading stars in a headline
27390 :todo-keyword on a TODO keyword (including DONE) in a headline
27391 :tags on the TAGS in a headline
27392 :priority on the priority cookie in a headline
27393 :item on the first line of a plain list item
27394 :item-bullet on the bullet/number of a plain list item
27395 :checkbox on the checkbox in a plain list item
27396 :table in an org-mode table
27397 :table-special on a special filed in a table
27398 :table-table in a table.el table
27399 :link on a hyperlink
27400 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27401 :target on a <<target>>
27402 :radio-target on a <<<radio-target>>>
27403 :latex-fragment on a LaTeX fragment
27404 :latex-preview on a LaTeX fragment with overlayed preview image
27406 This function expects the position to be visible because it uses font-lock
27407 faces as a help to recognize the following contexts: :table-special, :link,
27408 and :keyword."
27409 (let* ((f (get-text-property (point) 'face))
27410 (faces (if (listp f) f (list f)))
27411 (p (point)) clist o)
27412 ;; First the large context
27413 (cond
27414 ((org-on-heading-p t)
27415 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27416 (when (progn
27417 (beginning-of-line 1)
27418 (looking-at org-todo-line-tags-regexp))
27419 (push (org-point-in-group p 1 :headline-stars) clist)
27420 (push (org-point-in-group p 2 :todo-keyword) clist)
27421 (push (org-point-in-group p 4 :tags) clist))
27422 (goto-char p)
27423 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27424 (if (looking-at "\\[#[A-Z0-9]\\]")
27425 (push (org-point-in-group p 0 :priority) clist)))
27427 ((org-at-item-p)
27428 (push (org-point-in-group p 2 :item-bullet) clist)
27429 (push (list :item (point-at-bol)
27430 (save-excursion (org-end-of-item) (point)))
27431 clist)
27432 (and (org-at-item-checkbox-p)
27433 (push (org-point-in-group p 0 :checkbox) clist)))
27435 ((org-at-table-p)
27436 (push (list :table (org-table-begin) (org-table-end)) clist)
27437 (if (memq 'org-formula faces)
27438 (push (list :table-special
27439 (previous-single-property-change p 'face)
27440 (next-single-property-change p 'face)) clist)))
27441 ((org-at-table-p 'any)
27442 (push (list :table-table) clist)))
27443 (goto-char p)
27445 ;; Now the small context
27446 (cond
27447 ((org-at-timestamp-p)
27448 (push (org-point-in-group p 0 :timestamp) clist))
27449 ((memq 'org-link faces)
27450 (push (list :link
27451 (previous-single-property-change p 'face)
27452 (next-single-property-change p 'face)) clist))
27453 ((memq 'org-special-keyword faces)
27454 (push (list :keyword
27455 (previous-single-property-change p 'face)
27456 (next-single-property-change p 'face)) clist))
27457 ((org-on-target-p)
27458 (push (org-point-in-group p 0 :target) clist)
27459 (goto-char (1- (match-beginning 0)))
27460 (if (looking-at org-radio-target-regexp)
27461 (push (org-point-in-group p 0 :radio-target) clist))
27462 (goto-char p))
27463 ((setq o (car (delq nil
27464 (mapcar
27465 (lambda (x)
27466 (if (memq x org-latex-fragment-image-overlays) x))
27467 (org-overlays-at (point))))))
27468 (push (list :latex-fragment
27469 (org-overlay-start o) (org-overlay-end o)) clist)
27470 (push (list :latex-preview
27471 (org-overlay-start o) (org-overlay-end o)) clist))
27472 ((org-inside-LaTeX-fragment-p)
27473 ;; FIXME: positions wrong.
27474 (push (list :latex-fragment (point) (point)) clist)))
27476 (setq clist (nreverse (delq nil clist)))
27477 clist))
27479 ;; FIXME: Compare with at-regexp-p Do we need both?
27480 (defun org-in-regexp (re &optional nlines visually)
27481 "Check if point is inside a match of regexp.
27482 Normally only the current line is checked, but you can include NLINES extra
27483 lines both before and after point into the search.
27484 If VISUALLY is set, require that the cursor is not after the match but
27485 really on, so that the block visually is on the match."
27486 (catch 'exit
27487 (let ((pos (point))
27488 (eol (point-at-eol (+ 1 (or nlines 0))))
27489 (inc (if visually 1 0)))
27490 (save-excursion
27491 (beginning-of-line (- 1 (or nlines 0)))
27492 (while (re-search-forward re eol t)
27493 (if (and (<= (match-beginning 0) pos)
27494 (>= (+ inc (match-end 0)) pos))
27495 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27497 (defun org-at-regexp-p (regexp)
27498 "Is point inside a match of REGEXP in the current line?"
27499 (catch 'exit
27500 (save-excursion
27501 (let ((pos (point)) (end (point-at-eol)))
27502 (beginning-of-line 1)
27503 (while (re-search-forward regexp end t)
27504 (if (and (<= (match-beginning 0) pos)
27505 (>= (match-end 0) pos))
27506 (throw 'exit t)))
27507 nil))))
27509 (defun org-occur-in-agenda-files (regexp &optional nlines)
27510 "Call `multi-occur' with buffers for all agenda files."
27511 (interactive "sOrg-files matching: \np")
27512 (let* ((files (org-agenda-files))
27513 (tnames (mapcar 'file-truename files))
27514 (extra org-agenda-multi-occur-extra-files)
27516 (while (setq f (pop extra))
27517 (unless (member (file-truename f) tnames)
27518 (add-to-list 'files f 'append)
27519 (add-to-list 'tnames (file-truename f) 'append)))
27520 (multi-occur
27521 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27522 regexp)))
27524 (if (boundp 'occur-mode-find-occurrence-hook)
27525 ;; Emacs 23
27526 (add-hook 'occur-mode-find-occurrence-hook
27527 (lambda ()
27528 (when (org-mode-p)
27529 (org-reveal))))
27530 ;; Emacs 22
27531 (defadvice occur-mode-goto-occurrence
27532 (after org-occur-reveal activate)
27533 (and (org-mode-p) (org-reveal)))
27534 (defadvice occur-mode-goto-occurrence-other-window
27535 (after org-occur-reveal activate)
27536 (and (org-mode-p) (org-reveal)))
27537 (defadvice occur-mode-display-occurrence
27538 (after org-occur-reveal activate)
27539 (when (org-mode-p)
27540 (let ((pos (occur-mode-find-occurrence)))
27541 (with-current-buffer (marker-buffer pos)
27542 (save-excursion
27543 (goto-char pos)
27544 (org-reveal)))))))
27546 (defun org-uniquify (list)
27547 "Remove duplicate elements from LIST."
27548 (let (res)
27549 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27550 res))
27552 (defun org-delete-all (elts list)
27553 "Remove all elements in ELTS from LIST."
27554 (while elts
27555 (setq list (delete (pop elts) list)))
27556 list)
27558 (defun org-back-over-empty-lines ()
27559 "Move backwards over witespace, to the beginning of the first empty line.
27560 Returns the number o empty lines passed."
27561 (let ((pos (point)))
27562 (skip-chars-backward " \t\n\r")
27563 (beginning-of-line 2)
27564 (goto-char (min (point) pos))
27565 (count-lines (point) pos)))
27567 (defun org-skip-whitespace ()
27568 (skip-chars-forward " \t\n\r"))
27570 (defun org-point-in-group (point group &optional context)
27571 "Check if POINT is in match-group GROUP.
27572 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27573 match. If the match group does ot exist or point is not inside it,
27574 return nil."
27575 (and (match-beginning group)
27576 (>= point (match-beginning group))
27577 (<= point (match-end group))
27578 (if context
27579 (list context (match-beginning group) (match-end group))
27580 t)))
27582 (defun org-switch-to-buffer-other-window (&rest args)
27583 "Switch to buffer in a second window on the current frame.
27584 In particular, do not allow pop-up frames."
27585 (let (pop-up-frames special-display-buffer-names special-display-regexps
27586 special-display-function)
27587 (apply 'switch-to-buffer-other-window args)))
27589 (defun org-combine-plists (&rest plists)
27590 "Create a single property list from all plists in PLISTS.
27591 The process starts by copying the first list, and then setting properties
27592 from the other lists. Settings in the last list are the most significant
27593 ones and overrule settings in the other lists."
27594 (let ((rtn (copy-sequence (pop plists)))
27595 p v ls)
27596 (while plists
27597 (setq ls (pop plists))
27598 (while ls
27599 (setq p (pop ls) v (pop ls))
27600 (setq rtn (plist-put rtn p v))))
27601 rtn))
27603 (defun org-move-line-down (arg)
27604 "Move the current line down. With prefix argument, move it past ARG lines."
27605 (interactive "p")
27606 (let ((col (current-column))
27607 beg end pos)
27608 (beginning-of-line 1) (setq beg (point))
27609 (beginning-of-line 2) (setq end (point))
27610 (beginning-of-line (+ 1 arg))
27611 (setq pos (move-marker (make-marker) (point)))
27612 (insert (delete-and-extract-region beg end))
27613 (goto-char pos)
27614 (move-to-column col)))
27616 (defun org-move-line-up (arg)
27617 "Move the current line up. With prefix argument, move it past ARG lines."
27618 (interactive "p")
27619 (let ((col (current-column))
27620 beg end pos)
27621 (beginning-of-line 1) (setq beg (point))
27622 (beginning-of-line 2) (setq end (point))
27623 (beginning-of-line (- arg))
27624 (setq pos (move-marker (make-marker) (point)))
27625 (insert (delete-and-extract-region beg end))
27626 (goto-char pos)
27627 (move-to-column col)))
27629 (defun org-replace-escapes (string table)
27630 "Replace %-escapes in STRING with values in TABLE.
27631 TABLE is an association list with keys like \"%a\" and string values.
27632 The sequences in STRING may contain normal field width and padding information,
27633 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27634 so values can contain further %-escapes if they are define later in TABLE."
27635 (let ((case-fold-search nil)
27636 e re rpl)
27637 (while (setq e (pop table))
27638 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27639 (while (string-match re string)
27640 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27641 (cdr e)))
27642 (setq string (replace-match rpl t t string))))
27643 string))
27646 (defun org-sublist (list start end)
27647 "Return a section of LIST, from START to END.
27648 Counting starts at 1."
27649 (let (rtn (c start))
27650 (setq list (nthcdr (1- start) list))
27651 (while (and list (<= c end))
27652 (push (pop list) rtn)
27653 (setq c (1+ c)))
27654 (nreverse rtn)))
27656 (defun org-find-base-buffer-visiting (file)
27657 "Like `find-buffer-visiting' but alway return the base buffer and
27658 not an indirect buffer"
27659 (let ((buf (find-buffer-visiting file)))
27660 (if buf
27661 (or (buffer-base-buffer buf) buf)
27662 nil)))
27664 (defun org-image-file-name-regexp ()
27665 "Return regexp matching the file names of images."
27666 (if (fboundp 'image-file-name-regexp)
27667 (image-file-name-regexp)
27668 (let ((image-file-name-extensions
27669 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27670 "xbm" "xpm" "pbm" "pgm" "ppm")))
27671 (concat "\\."
27672 (regexp-opt (nconc (mapcar 'upcase
27673 image-file-name-extensions)
27674 image-file-name-extensions)
27676 "\\'"))))
27678 (defun org-file-image-p (file)
27679 "Return non-nil if FILE is an image."
27680 (save-match-data
27681 (string-match (org-image-file-name-regexp) file)))
27683 ;;; Paragraph filling stuff.
27684 ;; We want this to be just right, so use the full arsenal.
27686 (defun org-indent-line-function ()
27687 "Indent line like previous, but further if previous was headline or item."
27688 (interactive)
27689 (let* ((pos (point))
27690 (itemp (org-at-item-p))
27691 column bpos bcol tpos tcol bullet btype bullet-type)
27692 ;; Find the previous relevant line
27693 (beginning-of-line 1)
27694 (cond
27695 ((looking-at "#") (setq column 0))
27696 ((looking-at "\\*+ ") (setq column 0))
27698 (beginning-of-line 0)
27699 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27700 (beginning-of-line 0))
27701 (cond
27702 ((looking-at "\\*+[ \t]+")
27703 (goto-char (match-end 0))
27704 (setq column (current-column)))
27705 ((org-in-item-p)
27706 (org-beginning-of-item)
27707 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27708 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27709 (setq bpos (match-beginning 1) tpos (match-end 0)
27710 bcol (progn (goto-char bpos) (current-column))
27711 tcol (progn (goto-char tpos) (current-column))
27712 bullet (match-string 1)
27713 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27714 (if (not itemp)
27715 (setq column tcol)
27716 (goto-char pos)
27717 (beginning-of-line 1)
27718 (if (looking-at "\\S-")
27719 (progn
27720 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27721 (setq bullet (match-string 1)
27722 btype (if (string-match "[0-9]" bullet) "n" bullet))
27723 (setq column (if (equal btype bullet-type) bcol tcol)))
27724 (setq column (org-get-indentation)))))
27725 (t (setq column (org-get-indentation))))))
27726 (goto-char pos)
27727 (if (<= (current-column) (current-indentation))
27728 (indent-line-to column)
27729 (save-excursion (indent-line-to column)))
27730 (setq column (current-column))
27731 (beginning-of-line 1)
27732 (if (looking-at
27733 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27734 (replace-match (concat "\\1" (format org-property-format
27735 (match-string 2) (match-string 3)))
27736 t nil))
27737 (move-to-column column)))
27739 (defun org-set-autofill-regexps ()
27740 (interactive)
27741 ;; In the paragraph separator we include headlines, because filling
27742 ;; text in a line directly attached to a headline would otherwise
27743 ;; fill the headline as well.
27744 (org-set-local 'comment-start-skip "^#+[ \t]*")
27745 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27746 ;; The paragraph starter includes hand-formatted lists.
27747 (org-set-local 'paragraph-start
27748 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27749 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27750 ;; But only if the user has not turned off tables or fixed-width regions
27751 (org-set-local
27752 'auto-fill-inhibit-regexp
27753 (concat "\\*+ \\|#\\+"
27754 "\\|[ \t]*" org-keyword-time-regexp
27755 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27756 (concat
27757 "\\|[ \t]*["
27758 (if org-enable-table-editor "|" "")
27759 (if org-enable-fixed-width-editor ":" "")
27760 "]"))))
27761 ;; We use our own fill-paragraph function, to make sure that tables
27762 ;; and fixed-width regions are not wrapped. That function will pass
27763 ;; through to `fill-paragraph' when appropriate.
27764 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27765 ; Adaptive filling: To get full control, first make sure that
27766 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27767 (org-set-local 'adaptive-fill-regexp "\000")
27768 (org-set-local 'adaptive-fill-function
27769 'org-adaptive-fill-function)
27770 (org-set-local
27771 'align-mode-rules-list
27772 '((org-in-buffer-settings
27773 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
27774 (modes . '(org-mode))))))
27776 (defun org-fill-paragraph (&optional justify)
27777 "Re-align a table, pass through to fill-paragraph if no table."
27778 (let ((table-p (org-at-table-p))
27779 (table.el-p (org-at-table.el-p)))
27780 (cond ((and (equal (char-after (point-at-bol)) ?*)
27781 (save-excursion (goto-char (point-at-bol))
27782 (looking-at outline-regexp)))
27783 t) ; skip headlines
27784 (table.el-p t) ; skip table.el tables
27785 (table-p (org-table-align) t) ; align org-mode tables
27786 (t nil)))) ; call paragraph-fill
27788 ;; For reference, this is the default value of adaptive-fill-regexp
27789 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27791 (defun org-adaptive-fill-function ()
27792 "Return a fill prefix for org-mode files.
27793 In particular, this makes sure hanging paragraphs for hand-formatted lists
27794 work correctly."
27795 (cond ((looking-at "#[ \t]+")
27796 (match-string 0))
27797 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27798 (save-excursion
27799 (goto-char (match-end 0))
27800 (make-string (current-column) ?\ )))
27801 (t nil)))
27803 ;;;; Functions extending outline functionality
27806 (defun org-beginning-of-line (&optional arg)
27807 "Go to the beginning of the current line. If that is invisible, continue
27808 to a visible line beginning. This makes the function of C-a more intuitive.
27809 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27810 first attempt, and only move to after the tags when the cursor is already
27811 beyond the end of the headline."
27812 (interactive "P")
27813 (let ((pos (point)))
27814 (beginning-of-line 1)
27815 (if (bobp)
27817 (backward-char 1)
27818 (if (org-invisible-p)
27819 (while (and (not (bobp)) (org-invisible-p))
27820 (backward-char 1)
27821 (beginning-of-line 1))
27822 (forward-char 1)))
27823 (when org-special-ctrl-a/e
27824 (cond
27825 ((and (looking-at org-todo-line-regexp)
27826 (= (char-after (match-end 1)) ?\ ))
27827 (goto-char
27828 (if (eq org-special-ctrl-a/e t)
27829 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27830 ((= pos (point)) (match-beginning 3))
27831 (t (point)))
27832 (cond ((> pos (point)) (point))
27833 ((not (eq last-command this-command)) (point))
27834 (t (match-beginning 3))))))
27835 ((org-at-item-p)
27836 (goto-char
27837 (if (eq org-special-ctrl-a/e t)
27838 (cond ((> pos (match-end 4)) (match-end 4))
27839 ((= pos (point)) (match-end 4))
27840 (t (point)))
27841 (cond ((> pos (point)) (point))
27842 ((not (eq last-command this-command)) (point))
27843 (t (match-end 4))))))))))
27845 (defun org-end-of-line (&optional arg)
27846 "Go to the end of the line.
27847 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27848 first attempt, and only move to after the tags when the cursor is already
27849 beyond the end of the headline."
27850 (interactive "P")
27851 (if (or (not org-special-ctrl-a/e)
27852 (not (org-on-heading-p)))
27853 (end-of-line arg)
27854 (let ((pos (point)))
27855 (beginning-of-line 1)
27856 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27857 (if (eq org-special-ctrl-a/e t)
27858 (if (or (< pos (match-beginning 1))
27859 (= pos (match-end 0)))
27860 (goto-char (match-beginning 1))
27861 (goto-char (match-end 0)))
27862 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27863 (goto-char (match-end 0))
27864 (goto-char (match-beginning 1))))
27865 (end-of-line arg)))))
27867 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27868 (define-key org-mode-map "\C-e" 'org-end-of-line)
27870 (defun org-kill-line (&optional arg)
27871 "Kill line, to tags or end of line."
27872 (interactive "P")
27873 (cond
27874 ((or (not org-special-ctrl-k)
27875 (bolp)
27876 (not (org-on-heading-p)))
27877 (call-interactively 'kill-line))
27878 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
27879 (kill-region (point) (match-beginning 1))
27880 (org-set-tags nil t))
27881 (t (kill-region (point) (point-at-eol)))))
27883 (define-key org-mode-map "\C-k" 'org-kill-line)
27885 (defun org-invisible-p ()
27886 "Check if point is at a character currently not visible."
27887 ;; Early versions of noutline don't have `outline-invisible-p'.
27888 (if (fboundp 'outline-invisible-p)
27889 (outline-invisible-p)
27890 (get-char-property (point) 'invisible)))
27892 (defun org-invisible-p2 ()
27893 "Check if point is at a character currently not visible."
27894 (save-excursion
27895 (if (and (eolp) (not (bobp))) (backward-char 1))
27896 ;; Early versions of noutline don't have `outline-invisible-p'.
27897 (if (fboundp 'outline-invisible-p)
27898 (outline-invisible-p)
27899 (get-char-property (point) 'invisible))))
27901 (defalias 'org-back-to-heading 'outline-back-to-heading)
27902 (defalias 'org-on-heading-p 'outline-on-heading-p)
27903 (defalias 'org-at-heading-p 'outline-on-heading-p)
27904 (defun org-at-heading-or-item-p ()
27905 (or (org-on-heading-p) (org-at-item-p)))
27907 (defun org-on-target-p ()
27908 (or (org-in-regexp org-radio-target-regexp)
27909 (org-in-regexp org-target-regexp)))
27911 (defun org-up-heading-all (arg)
27912 "Move to the heading line of which the present line is a subheading.
27913 This function considers both visible and invisible heading lines.
27914 With argument, move up ARG levels."
27915 (if (fboundp 'outline-up-heading-all)
27916 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27917 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27919 (defun org-up-heading-safe ()
27920 "Move to the heading line of which the present line is a subheading.
27921 This version will not throw an error. It will return the level of the
27922 headline found, or nil if no higher level is found."
27923 (let ((pos (point)) start-level level
27924 (re (concat "^" outline-regexp)))
27925 (catch 'exit
27926 (outline-back-to-heading t)
27927 (setq start-level (funcall outline-level))
27928 (if (equal start-level 1) (throw 'exit nil))
27929 (while (re-search-backward re nil t)
27930 (setq level (funcall outline-level))
27931 (if (< level start-level) (throw 'exit level)))
27932 nil)))
27934 (defun org-first-sibling-p ()
27935 "Is this heading the first child of its parents?"
27936 (interactive)
27937 (let ((re (concat "^" outline-regexp))
27938 level l)
27939 (unless (org-at-heading-p t)
27940 (error "Not at a heading"))
27941 (setq level (funcall outline-level))
27942 (save-excursion
27943 (if (not (re-search-backward re nil t))
27945 (setq l (funcall outline-level))
27946 (< l level)))))
27948 (defun org-goto-sibling (&optional previous)
27949 "Goto the next sibling, even if it is invisible.
27950 When PREVIOUS is set, go to the previous sibling instead. Returns t
27951 when a sibling was found. When none is found, return nil and don't
27952 move point."
27953 (let ((fun (if previous 're-search-backward 're-search-forward))
27954 (pos (point))
27955 (re (concat "^" outline-regexp))
27956 level l)
27957 (when (condition-case nil (org-back-to-heading t) (error nil))
27958 (setq level (funcall outline-level))
27959 (catch 'exit
27960 (or previous (forward-char 1))
27961 (while (funcall fun re nil t)
27962 (setq l (funcall outline-level))
27963 (when (< l level) (goto-char pos) (throw 'exit nil))
27964 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27965 (goto-char pos)
27966 nil))))
27968 (defun org-show-siblings ()
27969 "Show all siblings of the current headline."
27970 (save-excursion
27971 (while (org-goto-sibling) (org-flag-heading nil)))
27972 (save-excursion
27973 (while (org-goto-sibling 'previous)
27974 (org-flag-heading nil))))
27976 (defun org-show-hidden-entry ()
27977 "Show an entry where even the heading is hidden."
27978 (save-excursion
27979 (org-show-entry)))
27981 (defun org-flag-heading (flag &optional entry)
27982 "Flag the current heading. FLAG non-nil means make invisible.
27983 When ENTRY is non-nil, show the entire entry."
27984 (save-excursion
27985 (org-back-to-heading t)
27986 ;; Check if we should show the entire entry
27987 (if entry
27988 (progn
27989 (org-show-entry)
27990 (save-excursion
27991 (and (outline-next-heading)
27992 (org-flag-heading nil))))
27993 (outline-flag-region (max (point-min) (1- (point)))
27994 (save-excursion (outline-end-of-heading) (point))
27995 flag))))
27997 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27998 ;; This is an exact copy of the original function, but it uses
27999 ;; `org-back-to-heading', to make it work also in invisible
28000 ;; trees. And is uses an invisible-OK argument.
28001 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28002 (org-back-to-heading invisible-OK)
28003 (let ((first t)
28004 (level (funcall outline-level)))
28005 (while (and (not (eobp))
28006 (or first (> (funcall outline-level) level)))
28007 (setq first nil)
28008 (outline-next-heading))
28009 (unless to-heading
28010 (if (memq (preceding-char) '(?\n ?\^M))
28011 (progn
28012 ;; Go to end of line before heading
28013 (forward-char -1)
28014 (if (memq (preceding-char) '(?\n ?\^M))
28015 ;; leave blank line before heading
28016 (forward-char -1))))))
28017 (point))
28019 (defun org-show-subtree ()
28020 "Show everything after this heading at deeper levels."
28021 (outline-flag-region
28022 (point)
28023 (save-excursion
28024 (outline-end-of-subtree) (outline-next-heading) (point))
28025 nil))
28027 (defun org-show-entry ()
28028 "Show the body directly following this heading.
28029 Show the heading too, if it is currently invisible."
28030 (interactive)
28031 (save-excursion
28032 (condition-case nil
28033 (progn
28034 (org-back-to-heading t)
28035 (outline-flag-region
28036 (max (point-min) (1- (point)))
28037 (save-excursion
28038 (re-search-forward
28039 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28040 (or (match-beginning 1) (point-max)))
28041 nil))
28042 (error nil))))
28044 (defun org-make-options-regexp (kwds)
28045 "Make a regular expression for keyword lines."
28046 (concat
28048 "#?[ \t]*\\+\\("
28049 (mapconcat 'regexp-quote kwds "\\|")
28050 "\\):[ \t]*"
28051 "\\(.+\\)"))
28053 ;; Make isearch reveal the necessary context
28054 (defun org-isearch-end ()
28055 "Reveal context after isearch exits."
28056 (when isearch-success ; only if search was successful
28057 (if (featurep 'xemacs)
28058 ;; Under XEmacs, the hook is run in the correct place,
28059 ;; we directly show the context.
28060 (org-show-context 'isearch)
28061 ;; In Emacs the hook runs *before* restoring the overlays.
28062 ;; So we have to use a one-time post-command-hook to do this.
28063 ;; (Emacs 22 has a special variable, see function `org-mode')
28064 (unless (and (boundp 'isearch-mode-end-hook-quit)
28065 isearch-mode-end-hook-quit)
28066 ;; Only when the isearch was not quitted.
28067 (org-add-hook 'post-command-hook 'org-isearch-post-command
28068 'append 'local)))))
28070 (defun org-isearch-post-command ()
28071 "Remove self from hook, and show context."
28072 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28073 (org-show-context 'isearch))
28076 ;;;; Integration with and fixes for other packages
28078 ;;; Imenu support
28080 (defvar org-imenu-markers nil
28081 "All markers currently used by Imenu.")
28082 (make-variable-buffer-local 'org-imenu-markers)
28084 (defun org-imenu-new-marker (&optional pos)
28085 "Return a new marker for use by Imenu, and remember the marker."
28086 (let ((m (make-marker)))
28087 (move-marker m (or pos (point)))
28088 (push m org-imenu-markers)
28091 (defun org-imenu-get-tree ()
28092 "Produce the index for Imenu."
28093 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28094 (setq org-imenu-markers nil)
28095 (let* ((n org-imenu-depth)
28096 (re (concat "^" outline-regexp))
28097 (subs (make-vector (1+ n) nil))
28098 (last-level 0)
28099 m tree level head)
28100 (save-excursion
28101 (save-restriction
28102 (widen)
28103 (goto-char (point-max))
28104 (while (re-search-backward re nil t)
28105 (setq level (org-reduced-level (funcall outline-level)))
28106 (when (<= level n)
28107 (looking-at org-complex-heading-regexp)
28108 (setq head (org-match-string-no-properties 4)
28109 m (org-imenu-new-marker))
28110 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28111 (if (>= level last-level)
28112 (push (cons head m) (aref subs level))
28113 (push (cons head (aref subs (1+ level))) (aref subs level))
28114 (loop for i from (1+ level) to n do (aset subs i nil)))
28115 (setq last-level level)))))
28116 (aref subs 1)))
28118 (eval-after-load "imenu"
28119 '(progn
28120 (add-hook 'imenu-after-jump-hook
28121 (lambda () (org-show-context 'org-goto)))))
28123 ;; Speedbar support
28125 (defun org-speedbar-set-agenda-restriction ()
28126 "Restrict future agenda commands to the location at point in speedbar.
28127 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28128 (interactive)
28129 (let (p m tp np dir txt w)
28130 (cond
28131 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28132 'org-imenu t))
28133 (setq m (get-text-property p 'org-imenu-marker))
28134 (save-excursion
28135 (save-restriction
28136 (set-buffer (marker-buffer m))
28137 (goto-char m)
28138 (org-agenda-set-restriction-lock 'subtree))))
28139 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28140 'speedbar-function 'speedbar-find-file))
28141 (setq tp (previous-single-property-change
28142 (1+ p) 'speedbar-function)
28143 np (next-single-property-change
28144 tp 'speedbar-function)
28145 dir (speedbar-line-directory)
28146 txt (buffer-substring-no-properties (or tp (point-min))
28147 (or np (point-max))))
28148 (save-excursion
28149 (save-restriction
28150 (set-buffer (find-file-noselect
28151 (let ((default-directory dir))
28152 (expand-file-name txt))))
28153 (unless (org-mode-p)
28154 (error "Cannot restrict to non-Org-mode file"))
28155 (org-agenda-set-restriction-lock 'file))))
28156 (t (error "Don't know how to restrict Org-mode's agenda")))
28157 (org-move-overlay org-speedbar-restriction-lock-overlay
28158 (point-at-bol) (point-at-eol))
28159 (setq current-prefix-arg nil)
28160 (org-agenda-maybe-redo)))
28162 (eval-after-load "speedbar"
28163 '(progn
28164 (speedbar-add-supported-extension ".org")
28165 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28166 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28167 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28168 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28169 (add-hook 'speedbar-visiting-tag-hook
28170 (lambda () (org-show-context 'org-goto)))))
28173 ;;; Fixes and Hacks
28175 ;; Make flyspell not check words in links, to not mess up our keymap
28176 (defun org-mode-flyspell-verify ()
28177 "Don't let flyspell put overlays at active buttons."
28178 (not (get-text-property (point) 'keymap)))
28180 ;; Make `bookmark-jump' show the jump location if it was hidden.
28181 (eval-after-load "bookmark"
28182 '(if (boundp 'bookmark-after-jump-hook)
28183 ;; We can use the hook
28184 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28185 ;; Hook not available, use advice
28186 (defadvice bookmark-jump (after org-make-visible activate)
28187 "Make the position visible."
28188 (org-bookmark-jump-unhide))))
28190 (defun org-bookmark-jump-unhide ()
28191 "Unhide the current position, to show the bookmark location."
28192 (and (org-mode-p)
28193 (or (org-invisible-p)
28194 (save-excursion (goto-char (max (point-min) (1- (point))))
28195 (org-invisible-p)))
28196 (org-show-context 'bookmark-jump)))
28198 ;; Fix a bug in htmlize where there are text properties (face nil)
28199 (eval-after-load "htmlize"
28200 '(progn
28201 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28202 "Make sure there are no nil faces"
28203 (setq ad-return-value (delq nil ad-return-value)))))
28205 ;; Make session.el ignore our circular variable
28206 (eval-after-load "session"
28207 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28209 ;;;; Experimental code
28211 (defun org-closed-in-range ()
28212 "Sparse tree of items closed in a certain time range.
28213 Still experimental, may disappear in the future."
28214 (interactive)
28215 ;; Get the time interval from the user.
28216 (let* ((time1 (time-to-seconds
28217 (org-read-date nil 'to-time nil "Starting date: ")))
28218 (time2 (time-to-seconds
28219 (org-read-date nil 'to-time nil "End date:")))
28220 ;; callback function
28221 (callback (lambda ()
28222 (let ((time
28223 (time-to-seconds
28224 (apply 'encode-time
28225 (org-parse-time-string
28226 (match-string 1))))))
28227 ;; check if time in interval
28228 (and (>= time time1) (<= time time2))))))
28229 ;; make tree, check each match with the callback
28230 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28232 ;;;; Finish up
28234 (provide 'org)
28236 (run-hooks 'org-load-hook)
28238 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28239 ;;; org.el ends here