(Limitations and Known Bugs): State that the number of parens/brackets in
[emacs.git] / lisp / textmodes / org.el
blob71d8dee75f3c0873e3f4a191382140544450a37a
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.19a
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.19a"
88 "The version number of the file org.el.")
89 (defun org-version ()
90 (interactive)
91 (message "Org-mode version %s" org-version))
93 ;;; Compatibility constants
94 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
95 (defconst org-format-transports-properties-p
96 (let ((x "a"))
97 (add-text-properties 0 1 '(test t) x)
98 (get-text-property 0 'test (format "%s" x)))
99 "Does format transport text properties?")
101 (defmacro org-bound-and-true-p (var)
102 "Return the value of symbol VAR if it is bound, else nil."
103 `(and (boundp (quote ,var)) ,var))
105 (defmacro org-unmodified (&rest body)
106 "Execute body without changing `buffer-modified-p'."
107 `(set-buffer-modified-p
108 (prog1 (buffer-modified-p) ,@body)))
110 (defmacro org-re (s)
111 "Replace posix classes in regular expression."
112 (if (featurep 'xemacs)
113 (let ((ss s))
114 (save-match-data
115 (while (string-match "\\[:alnum:\\]" ss)
116 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
117 (while (string-match "\\[:alpha:\\]" ss)
118 (setq ss (replace-match "a-zA-Z" t t ss)))
119 ss))
122 (defmacro org-preserve-lc (&rest body)
123 `(let ((_line (org-current-line))
124 (_col (current-column)))
125 (unwind-protect
126 (progn ,@body)
127 (goto-line _line)
128 (move-to-column _col))))
130 (defmacro org-without-partial-completion (&rest body)
131 `(let ((pc-mode (and (boundp 'partial-completion-mode)
132 partial-completion-mode)))
133 (unwind-protect
134 (progn
135 (if pc-mode (partial-completion-mode -1))
136 ,@body)
137 (if pc-mode (partial-completion-mode 1)))))
139 ;;; The custom variables
141 (defgroup org nil
142 "Outline-based notes management and organizer."
143 :tag "Org"
144 :group 'outlines
145 :group 'hypermedia
146 :group 'calendar)
148 ;; FIXME: Needs a separate group...
149 (defcustom org-completion-fallback-command 'hippie-expand
150 "The expansion command called by \\[org-complete] in normal context.
151 Normal means, no org-mode-specific context."
152 :group 'org
153 :type 'function)
155 (defgroup org-startup nil
156 "Options concerning startup of Org-mode."
157 :tag "Org Startup"
158 :group 'org)
160 (defcustom org-startup-folded t
161 "Non-nil means, entering Org-mode will switch to OVERVIEW.
162 This can also be configured on a per-file basis by adding one of
163 the following lines anywhere in the buffer:
165 #+STARTUP: fold
166 #+STARTUP: nofold
167 #+STARTUP: content"
168 :group 'org-startup
169 :type '(choice
170 (const :tag "nofold: show all" nil)
171 (const :tag "fold: overview" t)
172 (const :tag "content: all headlines" content)))
174 (defcustom org-startup-truncated t
175 "Non-nil means, entering Org-mode will set `truncate-lines'.
176 This is useful since some lines containing links can be very long and
177 uninteresting. Also tables look terrible when wrapped."
178 :group 'org-startup
179 :type 'boolean)
181 (defcustom org-startup-align-all-tables nil
182 "Non-nil means, align all tables when visiting a file.
183 This is useful when the column width in tables is forced with <N> cookies
184 in table fields. Such tables will look correct only after the first re-align.
185 This can also be configured on a per-file basis by adding one of
186 the following lines anywhere in the buffer:
187 #+STARTUP: align
188 #+STARTUP: noalign"
189 :group 'org-startup
190 :type 'boolean)
192 (defcustom org-insert-mode-line-in-empty-file nil
193 "Non-nil means insert the first line setting Org-mode in empty files.
194 When the function `org-mode' is called interactively in an empty file, this
195 normally means that the file name does not automatically trigger Org-mode.
196 To ensure that the file will always be in Org-mode in the future, a
197 line enforcing Org-mode will be inserted into the buffer, if this option
198 has been set."
199 :group 'org-startup
200 :type 'boolean)
202 (defcustom org-replace-disputed-keys nil
203 "Non-nil means use alternative key bindings for some keys.
204 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
205 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
206 If you want to use Org-mode together with one of these other modes,
207 or more generally if you would like to move some Org-mode commands to
208 other keys, set this variable and configure the keys with the variable
209 `org-disputed-keys'.
211 This option is only relevant at load-time of Org-mode, and must be set
212 *before* org.el is loaded. Changing it requires a restart of Emacs to
213 become effective."
214 :group 'org-startup
215 :type 'boolean)
217 (if (fboundp 'defvaralias)
218 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
220 (defcustom org-disputed-keys
221 '(([(shift up)] . [(meta p)])
222 ([(shift down)] . [(meta n)])
223 ([(shift left)] . [(meta -)])
224 ([(shift right)] . [(meta +)])
225 ([(control shift right)] . [(meta shift +)])
226 ([(control shift left)] . [(meta shift -)]))
227 "Keys for which Org-mode and other modes compete.
228 This is an alist, cars are the default keys, second element specifies
229 the alternative to use when `org-replace-disputed-keys' is t.
231 Keys can be specified in any syntax supported by `define-key'.
232 The value of this option takes effect only at Org-mode's startup,
233 therefore you'll have to restart Emacs to apply it after changing."
234 :group 'org-startup
235 :type 'alist)
237 (defun org-key (key)
238 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
239 Or return the original if not disputed."
240 (if org-replace-disputed-keys
241 (let* ((nkey (key-description key))
242 (x (org-find-if (lambda (x)
243 (equal (key-description (car x)) nkey))
244 org-disputed-keys)))
245 (if x (cdr x) key))
246 key))
248 (defun org-find-if (predicate seq)
249 (catch 'exit
250 (while seq
251 (if (funcall predicate (car seq))
252 (throw 'exit (car seq))
253 (pop seq)))))
255 (defun org-defkey (keymap key def)
256 "Define a key, possibly translated, as returned by `org-key'."
257 (define-key keymap (org-key key) def))
259 (defcustom org-ellipsis nil
260 "The ellipsis to use in the Org-mode outline.
261 When nil, just use the standard three dots. When a string, use that instead,
262 When a face, use the standart 3 dots, but with the specified face.
263 The change affects only Org-mode (which will then use its own display table).
264 Changing this requires executing `M-x org-mode' in a buffer to become
265 effective."
266 :group 'org-startup
267 :type '(choice (const :tag "Default" nil)
268 (face :tag "Face" :value org-warning)
269 (string :tag "String" :value "...#")))
271 (defvar org-display-table nil
272 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
274 (defgroup org-keywords nil
275 "Keywords in Org-mode."
276 :tag "Org Keywords"
277 :group 'org)
279 (defcustom org-deadline-string "DEADLINE:"
280 "String to mark deadline entries.
281 A deadline is this string, followed by a time stamp. Should be a word,
282 terminated by a colon. You can insert a schedule keyword and
283 a timestamp with \\[org-deadline].
284 Changes become only effective after restarting Emacs."
285 :group 'org-keywords
286 :type 'string)
288 (defcustom org-scheduled-string "SCHEDULED:"
289 "String to mark scheduled TODO entries.
290 A schedule is this string, followed by a time stamp. Should be a word,
291 terminated by a colon. You can insert a schedule keyword and
292 a timestamp with \\[org-schedule].
293 Changes become only effective after restarting Emacs."
294 :group 'org-keywords
295 :type 'string)
297 (defcustom org-closed-string "CLOSED:"
298 "String used as the prefix for timestamps logging closing a TODO entry."
299 :group 'org-keywords
300 :type 'string)
302 (defcustom org-clock-string "CLOCK:"
303 "String used as prefix for timestamps clocking work hours on an item."
304 :group 'org-keywords
305 :type 'string)
307 (defcustom org-comment-string "COMMENT"
308 "Entries starting with this keyword will never be exported.
309 An entry can be toggled between COMMENT and normal with
310 \\[org-toggle-comment].
311 Changes become only effective after restarting Emacs."
312 :group 'org-keywords
313 :type 'string)
315 (defcustom org-quote-string "QUOTE"
316 "Entries starting with this keyword will be exported in fixed-width font.
317 Quoting applies only to the text in the entry following the headline, and does
318 not extend beyond the next headline, even if that is lower level.
319 An entry can be toggled between QUOTE and normal with
320 \\[org-toggle-fixed-width-section]."
321 :group 'org-keywords
322 :type 'string)
324 (defconst org-repeat-re
325 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
326 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
327 "Regular expression for specifying repeated events.
328 After a match, group 1 contains the repeat expression.")
330 (defgroup org-structure nil
331 "Options concerning the general structure of Org-mode files."
332 :tag "Org Structure"
333 :group 'org)
335 (defgroup org-reveal-location nil
336 "Options about how to make context of a location visible."
337 :tag "Org Reveal Location"
338 :group 'org-structure)
340 (defconst org-context-choice
341 '(choice
342 (const :tag "Always" t)
343 (const :tag "Never" nil)
344 (repeat :greedy t :tag "Individual contexts"
345 (cons
346 (choice :tag "Context"
347 (const agenda)
348 (const org-goto)
349 (const occur-tree)
350 (const tags-tree)
351 (const link-search)
352 (const mark-goto)
353 (const bookmark-jump)
354 (const isearch)
355 (const default))
356 (boolean))))
357 "Contexts for the reveal options.")
359 (defcustom org-show-hierarchy-above '((default . t))
360 "Non-nil means, show full hierarchy when revealing a location.
361 Org-mode often shows locations in an org-mode file which might have
362 been invisible before. When this is set, the hierarchy of headings
363 above the exposed location is shown.
364 Turning this off for example for sparse trees makes them very compact.
365 Instead of t, this can also be an alist specifying this option for different
366 contexts. Valid contexts are
367 agenda when exposing an entry from the agenda
368 org-goto when using the command `org-goto' on key C-c C-j
369 occur-tree when using the command `org-occur' on key C-c /
370 tags-tree when constructing a sparse tree based on tags matches
371 link-search when exposing search matches associated with a link
372 mark-goto when exposing the jump goal of a mark
373 bookmark-jump when exposing a bookmark location
374 isearch when exiting from an incremental search
375 default default for all contexts not set explicitly"
376 :group 'org-reveal-location
377 :type org-context-choice)
379 (defcustom org-show-following-heading '((default . nil))
380 "Non-nil means, show following heading when revealing a location.
381 Org-mode often shows locations in an org-mode file which might have
382 been invisible before. When this is set, the heading following the
383 match is shown.
384 Turning this off for example for sparse trees makes them very compact,
385 but makes it harder to edit the location of the match. In such a case,
386 use the command \\[org-reveal] to show more context.
387 Instead of t, this can also be an alist specifying this option for different
388 contexts. See `org-show-hierarchy-above' for valid contexts."
389 :group 'org-reveal-location
390 :type org-context-choice)
392 (defcustom org-show-siblings '((default . nil) (isearch t))
393 "Non-nil means, show all sibling heading when revealing a location.
394 Org-mode often shows locations in an org-mode file which might have
395 been invisible before. When this is set, the sibling of the current entry
396 heading are all made visible. If `org-show-hierarchy-above' is t,
397 the same happens on each level of the hierarchy above the current entry.
399 By default this is on for the isearch context, off for all other contexts.
400 Turning this off for example for sparse trees makes them very compact,
401 but makes it harder to edit the location of the match. In such a case,
402 use the command \\[org-reveal] to show more context.
403 Instead of t, this can also be an alist specifying this option for different
404 contexts. See `org-show-hierarchy-above' for valid contexts."
405 :group 'org-reveal-location
406 :type org-context-choice)
408 (defcustom org-show-entry-below '((default . nil))
409 "Non-nil means, show the entry below a headline when revealing a location.
410 Org-mode often shows locations in an org-mode file which might have
411 been invisible before. When this is set, the text below the headline that is
412 exposed is also shown.
414 By default this is off for all contexts.
415 Instead of t, this can also be an alist specifying this option for different
416 contexts. See `org-show-hierarchy-above' for valid contexts."
417 :group 'org-reveal-location
418 :type org-context-choice)
420 (defgroup org-cycle nil
421 "Options concerning visibility cycling in Org-mode."
422 :tag "Org Cycle"
423 :group 'org-structure)
425 (defcustom org-drawers '("PROPERTIES" "CLOCK")
426 "Names of drawers. Drawers are not opened by cycling on the headline above.
427 Drawers only open with a TAB on the drawer line itself. A drawer looks like
428 this:
429 :DRAWERNAME:
430 .....
431 :END:
432 The drawer \"PROPERTIES\" is special for capturing properties through
433 the property API.
435 Drawers can be defined on the per-file basis with a line like:
437 #+DRAWERS: HIDDEN STATE PROPERTIES"
438 :group 'org-structure
439 :type '(repeat (string :tag "Drawer Name")))
441 (defcustom org-cycle-global-at-bob nil
442 "Cycle globally if cursor is at beginning of buffer and not at a headline.
443 This makes it possible to do global cycling without having to use S-TAB or
444 C-u TAB. For this special case to work, the first line of the buffer
445 must not be a headline - it may be empty ot some other text. When used in
446 this way, `org-cycle-hook' is disables temporarily, to make sure the
447 cursor stays at the beginning of the buffer.
448 When this option is nil, don't do anything special at the beginning
449 of the buffer."
450 :group 'org-cycle
451 :type 'boolean)
453 (defcustom org-cycle-emulate-tab t
454 "Where should `org-cycle' emulate TAB.
455 nil Never
456 white Only in completely white lines
457 whitestart Only at the beginning of lines, before the first non-white char
458 t Everywhere except in headlines
459 exc-hl-bol Everywhere except at the start of a headline
460 If TAB is used in a place where it does not emulate TAB, the current subtree
461 visibility is cycled."
462 :group 'org-cycle
463 :type '(choice (const :tag "Never" nil)
464 (const :tag "Only in completely white lines" white)
465 (const :tag "Before first char in a line" whitestart)
466 (const :tag "Everywhere except in headlines" t)
467 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
470 (defcustom org-cycle-separator-lines 2
471 "Number of empty lines needed to keep an empty line between collapsed trees.
472 If you leave an empty line between the end of a subtree and the following
473 headline, this empty line is hidden when the subtree is folded.
474 Org-mode will leave (exactly) one empty line visible if the number of
475 empty lines is equal or larger to the number given in this variable.
476 So the default 2 means, at least 2 empty lines after the end of a subtree
477 are needed to produce free space between a collapsed subtree and the
478 following headline.
480 Special case: when 0, never leave empty lines in collapsed view."
481 :group 'org-cycle
482 :type 'integer)
484 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
485 org-cycle-hide-drawers
486 org-cycle-show-empty-lines
487 org-optimize-window-after-visibility-change)
488 "Hook that is run after `org-cycle' has changed the buffer visibility.
489 The function(s) in this hook must accept a single argument which indicates
490 the new state that was set by the most recent `org-cycle' command. The
491 argument is a symbol. After a global state change, it can have the values
492 `overview', `content', or `all'. After a local state change, it can have
493 the values `folded', `children', or `subtree'."
494 :group 'org-cycle
495 :type 'hook)
497 (defgroup org-edit-structure nil
498 "Options concerning structure editing in Org-mode."
499 :tag "Org Edit Structure"
500 :group 'org-structure)
502 (defcustom org-special-ctrl-a/e nil
503 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
504 When t, `C-a' will bring back the cursor to the beginning of the
505 headline text, i.e. after the stars and after a possible TODO keyword.
506 In an item, this will be the position after the bullet.
507 When the cursor is already at that position, another `C-a' will bring
508 it to the beginning of the line.
509 `C-e' will jump to the end of the headline, ignoring the presence of tags
510 in the headline. A second `C-e' will then jump to the true end of the
511 line, after any tags.
512 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
513 and only a directly following, identical keypress will bring the cursor
514 to the special positions."
515 :group 'org-edit-structure
516 :type '(choice
517 (const :tag "off" nil)
518 (const :tag "after bullet first" t)
519 (const :tag "border first" reversed)))
521 (if (fboundp 'defvaralias)
522 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
524 (defcustom org-odd-levels-only nil
525 "Non-nil means, skip even levels and only use odd levels for the outline.
526 This has the effect that two stars are being added/taken away in
527 promotion/demotion commands. It also influences how levels are
528 handled by the exporters.
529 Changing it requires restart of `font-lock-mode' to become effective
530 for fontification also in regions already fontified.
531 You may also set this on a per-file basis by adding one of the following
532 lines to the buffer:
534 #+STARTUP: odd
535 #+STARTUP: oddeven"
536 :group 'org-edit-structure
537 :group 'org-font-lock
538 :type 'boolean)
540 (defcustom org-adapt-indentation t
541 "Non-nil means, adapt indentation when promoting and demoting.
542 When this is set and the *entire* text in an entry is indented, the
543 indentation is increased by one space in a demotion command, and
544 decreased by one in a promotion command. If any line in the entry
545 body starts at column 0, indentation is not changed at all."
546 :group 'org-edit-structure
547 :type 'boolean)
549 (defcustom org-blank-before-new-entry '((heading . nil)
550 (plain-list-item . nil))
551 "Should `org-insert-heading' leave a blank line before new heading/item?
552 The value is an alist, with `heading' and `plain-list-item' as car,
553 and a boolean flag as cdr."
554 :group 'org-edit-structure
555 :type '(list
556 (cons (const heading) (boolean))
557 (cons (const plain-list-item) (boolean))))
559 (defcustom org-insert-heading-hook nil
560 "Hook being run after inserting a new heading."
561 :group 'org-edit-structure
562 :type 'hook)
564 (defcustom org-enable-fixed-width-editor t
565 "Non-nil means, lines starting with \":\" are treated as fixed-width.
566 This currently only means, they are never auto-wrapped.
567 When nil, such lines will be treated like ordinary lines.
568 See also the QUOTE keyword."
569 :group 'org-edit-structure
570 :type 'boolean)
572 (defgroup org-sparse-trees nil
573 "Options concerning sparse trees in Org-mode."
574 :tag "Org Sparse Trees"
575 :group 'org-structure)
577 (defcustom org-highlight-sparse-tree-matches t
578 "Non-nil means, highlight all matches that define a sparse tree.
579 The highlights will automatically disappear the next time the buffer is
580 changed by an edit command."
581 :group 'org-sparse-trees
582 :type 'boolean)
584 (defcustom org-remove-highlights-with-change t
585 "Non-nil means, any change to the buffer will remove temporary highlights.
586 Such highlights are created by `org-occur' and `org-clock-display'.
587 When nil, `C-c C-c needs to be used to get rid of the highlights.
588 The highlights created by `org-preview-latex-fragment' always need
589 `C-c C-c' to be removed."
590 :group 'org-sparse-trees
591 :group 'org-time
592 :type 'boolean)
595 (defcustom org-occur-hook '(org-first-headline-recenter)
596 "Hook that is run after `org-occur' has constructed a sparse tree.
597 This can be used to recenter the window to show as much of the structure
598 as possible."
599 :group 'org-sparse-trees
600 :type 'hook)
602 (defgroup org-plain-lists nil
603 "Options concerning plain lists in Org-mode."
604 :tag "Org Plain lists"
605 :group 'org-structure)
607 (defcustom org-cycle-include-plain-lists nil
608 "Non-nil means, include plain lists into visibility cycling.
609 This means that during cycling, plain list items will *temporarily* be
610 interpreted as outline headlines with a level given by 1000+i where i is the
611 indentation of the bullet. In all other operations, plain list items are
612 not seen as headlines. For example, you cannot assign a TODO keyword to
613 such an item."
614 :group 'org-plain-lists
615 :type 'boolean)
617 (defcustom org-plain-list-ordered-item-terminator t
618 "The character that makes a line with leading number an ordered list item.
619 Valid values are ?. and ?\). To get both terminators, use t. While
620 ?. may look nicer, it creates the danger that a line with leading
621 number may be incorrectly interpreted as an item. ?\) therefore is
622 the safe choice."
623 :group 'org-plain-lists
624 :type '(choice (const :tag "dot like in \"2.\"" ?.)
625 (const :tag "paren like in \"2)\"" ?\))
626 (const :tab "both" t)))
628 (defcustom org-auto-renumber-ordered-lists t
629 "Non-nil means, automatically renumber ordered plain lists.
630 Renumbering happens when the sequence have been changed with
631 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
632 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
633 :group 'org-plain-lists
634 :type 'boolean)
636 (defcustom org-provide-checkbox-statistics t
637 "Non-nil means, update checkbox statistics after insert and toggle.
638 When this is set, checkbox statistics is updated each time you either insert
639 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
640 with \\[org-ctrl-c-ctrl-c\\]."
641 :group 'org-plain-lists
642 :type 'boolean)
644 (defgroup org-archive nil
645 "Options concerning archiving in Org-mode."
646 :tag "Org Archive"
647 :group 'org-structure)
649 (defcustom org-archive-tag "ARCHIVE"
650 "The tag that marks a subtree as archived.
651 An archived subtree does not open during visibility cycling, and does
652 not contribute to the agenda listings.
653 After changing this, font-lock must be restarted in the relevant buffers to
654 get the proper fontification."
655 :group 'org-archive
656 :group 'org-keywords
657 :type 'string)
659 (defcustom org-agenda-skip-archived-trees t
660 "Non-nil means, the agenda will skip any items located in archived trees.
661 An archived tree is a tree marked with the tag ARCHIVE."
662 :group 'org-archive
663 :group 'org-agenda-skip
664 :type 'boolean)
666 (defcustom org-cycle-open-archived-trees nil
667 "Non-nil means, `org-cycle' will open archived trees.
668 An archived tree is a tree marked with the tag ARCHIVE.
669 When nil, archived trees will stay folded. You can still open them with
670 normal outline commands like `show-all', but not with the cycling commands."
671 :group 'org-archive
672 :group 'org-cycle
673 :type 'boolean)
675 (defcustom org-sparse-tree-open-archived-trees nil
676 "Non-nil means sparse tree construction shows matches in archived trees.
677 When nil, matches in these trees are highlighted, but the trees are kept in
678 collapsed state."
679 :group 'org-archive
680 :group 'org-sparse-trees
681 :type 'boolean)
683 (defcustom org-archive-location "%s_archive::"
684 "The location where subtrees should be archived.
685 This string consists of two parts, separated by a double-colon.
687 The first part is a file name - when omitted, archiving happens in the same
688 file. %s will be replaced by the current file name (without directory part).
689 Archiving to a different file is useful to keep archived entries from
690 contributing to the Org-mode Agenda.
692 The part after the double colon is a headline. The archived entries will be
693 filed under that headline. When omitted, the subtrees are simply filed away
694 at the end of the file, as top-level entries.
696 Here are a few examples:
697 \"%s_archive::\"
698 If the current file is Projects.org, archive in file
699 Projects.org_archive, as top-level trees. This is the default.
701 \"::* Archived Tasks\"
702 Archive in the current file, under the top-level headline
703 \"* Archived Tasks\".
705 \"~/org/archive.org::\"
706 Archive in file ~/org/archive.org (absolute path), as top-level trees.
708 \"basement::** Finished Tasks\"
709 Archive in file ./basement (relative path), as level 3 trees
710 below the level 2 heading \"** Finished Tasks\".
712 You may set this option on a per-file basis by adding to the buffer a
713 line like
715 #+ARCHIVE: basement::** Finished Tasks"
716 :group 'org-archive
717 :type 'string)
719 (defcustom org-archive-mark-done t
720 "Non-nil means, mark entries as DONE when they are moved to the archive file.
721 This can be a string to set the keyword to use. When t, Org-mode will
722 use the first keyword in its list that means done."
723 :group 'org-archive
724 :type '(choice
725 (const :tag "No" nil)
726 (const :tag "Yes" t)
727 (string :tag "Use this keyword")))
729 (defcustom org-archive-stamp-time t
730 "Non-nil means, add a time stamp to entries moved to an archive file.
731 This variable is obsolete and has no effect anymore, instead add ot remove
732 `time' from the variablle `org-archive-save-context-info'."
733 :group 'org-archive
734 :type 'boolean)
736 (defcustom org-archive-save-context-info '(time file category todo itags)
737 "Parts of context info that should be stored as properties when archiving.
738 When a subtree is moved to an archive file, it looses information given by
739 context, like inherited tags, the category, and possibly also the TODO
740 state (depending on the variable `org-archive-mark-done').
741 This variable can be a list of any of the following symbols:
743 time The time of archiving.
744 file The file where the entry originates.
745 itags The local tags, in the headline of the subtree.
746 ltags The tags the subtree inherits from further up the hierarchy.
747 todo The pre-archive TODO state.
748 category The category, taken from file name or #+CATEGORY lines.
750 For each symbol present in the list, a property will be created in
751 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
752 information."
753 :group 'org-archive
754 :type '(set :greedy t
755 (const :tag "Time" time)
756 (const :tag "File" file)
757 (const :tag "Category" category)
758 (const :tag "TODO state" todo)
759 (const :tag "TODO state" priority)
760 (const :tag "Inherited tags" itags)
761 (const :tag "Local tags" ltags)))
763 (defgroup org-imenu-and-speedbar nil
764 "Options concerning imenu and speedbar in Org-mode."
765 :tag "Org Imenu and Speedbar"
766 :group 'org-structure)
768 (defcustom org-imenu-depth 2
769 "The maximum level for Imenu access to Org-mode headlines.
770 This also applied for speedbar access."
771 :group 'org-imenu-and-speedbar
772 :type 'number)
774 (defgroup org-table nil
775 "Options concerning tables in Org-mode."
776 :tag "Org Table"
777 :group 'org)
779 (defcustom org-enable-table-editor 'optimized
780 "Non-nil means, lines starting with \"|\" are handled by the table editor.
781 When nil, such lines will be treated like ordinary lines.
783 When equal to the symbol `optimized', the table editor will be optimized to
784 do the following:
785 - Automatic overwrite mode in front of whitespace in table fields.
786 This makes the structure of the table stay in tact as long as the edited
787 field does not exceed the column width.
788 - Minimize the number of realigns. Normally, the table is aligned each time
789 TAB or RET are pressed to move to another field. With optimization this
790 happens only if changes to a field might have changed the column width.
791 Optimization requires replacing the functions `self-insert-command',
792 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
793 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
794 very good at guessing when a re-align will be necessary, but you can always
795 force one with \\[org-ctrl-c-ctrl-c].
797 If you would like to use the optimized version in Org-mode, but the
798 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
800 This variable can be used to turn on and off the table editor during a session,
801 but in order to toggle optimization, a restart is required.
803 See also the variable `org-table-auto-blank-field'."
804 :group 'org-table
805 :type '(choice
806 (const :tag "off" nil)
807 (const :tag "on" t)
808 (const :tag "on, optimized" optimized)))
810 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
811 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
812 In the optimized version, the table editor takes over all simple keys that
813 normally just insert a character. In tables, the characters are inserted
814 in a way to minimize disturbing the table structure (i.e. in overwrite mode
815 for empty fields). Outside tables, the correct binding of the keys is
816 restored.
818 The default for this option is t if the optimized version is also used in
819 Org-mode. See the variable `org-enable-table-editor' for details. Changing
820 this variable requires a restart of Emacs to become effective."
821 :group 'org-table
822 :type 'boolean)
824 (defcustom orgtbl-radio-table-templates
825 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
826 % END RECEIVE ORGTBL %n
827 \\begin{comment}
828 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
829 | | |
830 \\end{comment}\n")
831 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
832 @c END RECEIVE ORGTBL %n
833 @ignore
834 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
835 | | |
836 @end ignore\n")
837 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
838 <!-- END RECEIVE ORGTBL %n -->
839 <!--
840 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
841 | | |
842 -->\n"))
843 "Templates for radio tables in different major modes.
844 All occurrences of %n in a template will be replaced with the name of the
845 table, obtained by prompting the user."
846 :group 'org-table
847 :type '(repeat
848 (list (symbol :tag "Major mode")
849 (string :tag "Format"))))
851 (defgroup org-table-settings nil
852 "Settings for tables in Org-mode."
853 :tag "Org Table Settings"
854 :group 'org-table)
856 (defcustom org-table-default-size "5x2"
857 "The default size for newly created tables, Columns x Rows."
858 :group 'org-table-settings
859 :type 'string)
861 (defcustom org-table-number-regexp
862 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
863 "Regular expression for recognizing numbers in table columns.
864 If a table column contains mostly numbers, it will be aligned to the
865 right. If not, it will be aligned to the left.
867 The default value of this option is a regular expression which allows
868 anything which looks remotely like a number as used in scientific
869 context. For example, all of the following will be considered a
870 number:
871 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
873 Other options offered by the customize interface are more restrictive."
874 :group 'org-table-settings
875 :type '(choice
876 (const :tag "Positive Integers"
877 "^[0-9]+$")
878 (const :tag "Integers"
879 "^[-+]?[0-9]+$")
880 (const :tag "Floating Point Numbers"
881 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
882 (const :tag "Floating Point Number or Integer"
883 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
884 (const :tag "Exponential, Floating point, Integer"
885 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
886 (const :tag "Very General Number-Like, including hex"
887 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
888 (string :tag "Regexp:")))
890 (defcustom org-table-number-fraction 0.5
891 "Fraction of numbers in a column required to make the column align right.
892 In a column all non-white fields are considered. If at least this
893 fraction of fields is matched by `org-table-number-fraction',
894 alignment to the right border applies."
895 :group 'org-table-settings
896 :type 'number)
898 (defgroup org-table-editing nil
899 "Behavior of tables during editing in Org-mode."
900 :tag "Org Table Editing"
901 :group 'org-table)
903 (defcustom org-table-automatic-realign t
904 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
905 When nil, aligning is only done with \\[org-table-align], or after column
906 removal/insertion."
907 :group 'org-table-editing
908 :type 'boolean)
910 (defcustom org-table-auto-blank-field t
911 "Non-nil means, automatically blank table field when starting to type into it.
912 This only happens when typing immediately after a field motion
913 command (TAB, S-TAB or RET).
914 Only relevant when `org-enable-table-editor' is equal to `optimized'."
915 :group 'org-table-editing
916 :type 'boolean)
918 (defcustom org-table-tab-jumps-over-hlines t
919 "Non-nil means, tab in the last column of a table with jump over a hline.
920 If a horizontal separator line is following the current line,
921 `org-table-next-field' can either create a new row before that line, or jump
922 over the line. When this option is nil, a new line will be created before
923 this line."
924 :group 'org-table-editing
925 :type 'boolean)
927 (defcustom org-table-tab-recognizes-table.el t
928 "Non-nil means, TAB will automatically notice a table.el table.
929 When it sees such a table, it moves point into it and - if necessary -
930 calls `table-recognize-table'."
931 :group 'org-table-editing
932 :type 'boolean)
934 (defgroup org-table-calculation nil
935 "Options concerning tables in Org-mode."
936 :tag "Org Table Calculation"
937 :group 'org-table)
939 (defcustom org-table-use-standard-references t
940 "Should org-mode work with table refrences like B3 instead of @3$2?
941 Possible values are:
942 nil never use them
943 from accept as input, do not present for editing
944 t: accept as input and present for editing"
945 :group 'org-table-calculation
946 :type '(choice
947 (const :tag "Never, don't even check unser input for them" nil)
948 (const :tag "Always, both as user input, and when editing" t)
949 (const :tag "Convert user input, don't offer during editing" 'from)))
951 (defcustom org-table-copy-increment t
952 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
953 :group 'org-table-calculation
954 :type 'boolean)
956 (defcustom org-calc-default-modes
957 '(calc-internal-prec 12
958 calc-float-format (float 5)
959 calc-angle-mode deg
960 calc-prefer-frac nil
961 calc-symbolic-mode nil
962 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
963 calc-display-working-message t
965 "List with Calc mode settings for use in calc-eval for table formulas.
966 The list must contain alternating symbols (Calc modes variables and values).
967 Don't remove any of the default settings, just change the values. Org-mode
968 relies on the variables to be present in the list."
969 :group 'org-table-calculation
970 :type 'plist)
972 (defcustom org-table-formula-evaluate-inline t
973 "Non-nil means, TAB and RET evaluate a formula in current table field.
974 If the current field starts with an equal sign, it is assumed to be a formula
975 which should be evaluated as described in the manual and in the documentation
976 string of the command `org-table-eval-formula'. This feature requires the
977 Emacs calc package.
978 When this variable is nil, formula calculation is only available through
979 the command \\[org-table-eval-formula]."
980 :group 'org-table-calculation
981 :type 'boolean)
983 (defcustom org-table-formula-use-constants t
984 "Non-nil means, interpret constants in formulas in tables.
985 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
986 by the value given in `org-table-formula-constants', or by a value obtained
987 from the `constants.el' package."
988 :group 'org-table-calculation
989 :type 'boolean)
991 (defcustom org-table-formula-constants nil
992 "Alist with constant names and values, for use in table formulas.
993 The car of each element is a name of a constant, without the `$' before it.
994 The cdr is the value as a string. For example, if you'd like to use the
995 speed of light in a formula, you would configure
997 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
999 and then use it in an equation like `$1*$c'.
1001 Constants can also be defined on a per-file basis using a line like
1003 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1004 :group 'org-table-calculation
1005 :type '(repeat
1006 (cons (string :tag "name")
1007 (string :tag "value"))))
1009 (defvar org-table-formula-constants-local nil
1010 "Local version of `org-table-formula-constants'.")
1011 (make-variable-buffer-local 'org-table-formula-constants-local)
1013 (defcustom org-table-allow-automatic-line-recalculation t
1014 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1015 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1016 :group 'org-table-calculation
1017 :type 'boolean)
1019 (defgroup org-link nil
1020 "Options concerning links in Org-mode."
1021 :tag "Org Link"
1022 :group 'org)
1024 (defvar org-link-abbrev-alist-local nil
1025 "Buffer-local version of `org-link-abbrev-alist', which see.
1026 The value of this is taken from the #+LINK lines.")
1027 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1029 (defcustom org-link-abbrev-alist nil
1030 "Alist of link abbreviations.
1031 The car of each element is a string, to be replaced at the start of a link.
1032 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1033 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1035 [[linkkey:tag][description]]
1037 If REPLACE is a string, the tag will simply be appended to create the link.
1038 If the string contains \"%s\", the tag will be inserted there.
1040 REPLACE may also be a function that will be called with the tag as the
1041 only argument to create the link, which should be returned as a string.
1043 See the manual for examples."
1044 :group 'org-link
1045 :type 'alist)
1047 (defcustom org-descriptive-links t
1048 "Non-nil means, hide link part and only show description of bracket links.
1049 Bracket links are like [[link][descritpion]]. This variable sets the initial
1050 state in new org-mode buffers. The setting can then be toggled on a
1051 per-buffer basis from the Org->Hyperlinks menu."
1052 :group 'org-link
1053 :type 'boolean)
1055 (defcustom org-link-file-path-type 'adaptive
1056 "How the path name in file links should be stored.
1057 Valid values are:
1059 relative Relative to the current directory, i.e. the directory of the file
1060 into which the link is being inserted.
1061 absolute Absolute path, if possible with ~ for home directory.
1062 noabbrev Absolute path, no abbreviation of home directory.
1063 adaptive Use relative path for files in the current directory and sub-
1064 directories of it. For other files, use an absolute path."
1065 :group 'org-link
1066 :type '(choice
1067 (const relative)
1068 (const absolute)
1069 (const noabbrev)
1070 (const adaptive)))
1072 (defcustom org-activate-links '(bracket angle plain radio tag date)
1073 "Types of links that should be activated in Org-mode files.
1074 This is a list of symbols, each leading to the activation of a certain link
1075 type. In principle, it does not hurt to turn on most link types - there may
1076 be a small gain when turning off unused link types. The types are:
1078 bracket The recommended [[link][description]] or [[link]] links with hiding.
1079 angular Links in angular brackes that may contain whitespace like
1080 <bbdb:Carsten Dominik>.
1081 plain Plain links in normal text, no whitespace, like http://google.com.
1082 radio Text that is matched by a radio target, see manual for details.
1083 tag Tag settings in a headline (link to tag search).
1084 date Time stamps (link to calendar).
1086 Changing this variable requires a restart of Emacs to become effective."
1087 :group 'org-link
1088 :type '(set (const :tag "Double bracket links (new style)" bracket)
1089 (const :tag "Angular bracket links (old style)" angular)
1090 (const :tag "plain text links" plain)
1091 (const :tag "Radio target matches" radio)
1092 (const :tag "Tags" tag)
1093 (const :tag "Tags" target)
1094 (const :tag "Timestamps" date)))
1096 (defgroup org-link-store nil
1097 "Options concerning storing links in Org-mode"
1098 :tag "Org Store Link"
1099 :group 'org-link)
1101 (defcustom org-email-link-description-format "Email %c: %.30s"
1102 "Format of the description part of a link to an email or usenet message.
1103 The following %-excapes will be replaced by corresponding information:
1105 %F full \"From\" field
1106 %f name, taken from \"From\" field, address if no name
1107 %T full \"To\" field
1108 %t first name in \"To\" field, address if no name
1109 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1110 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1111 %s subject
1112 %m message-id.
1114 You may use normal field width specification between the % and the letter.
1115 This is for example useful to limit the length of the subject.
1117 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1118 :group 'org-link-store
1119 :type 'string)
1121 (defcustom org-from-is-user-regexp
1122 (let (r1 r2)
1123 (when (and user-mail-address (not (string= user-mail-address "")))
1124 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1125 (when (and user-full-name (not (string= user-full-name "")))
1126 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1127 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1128 "Regexp mached against the \"From:\" header of an email or usenet message.
1129 It should match if the message is from the user him/herself."
1130 :group 'org-link-store
1131 :type 'regexp)
1133 (defcustom org-context-in-file-links t
1134 "Non-nil means, file links from `org-store-link' contain context.
1135 A search string will be added to the file name with :: as separator and
1136 used to find the context when the link is activated by the command
1137 `org-open-at-point'.
1138 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1139 negates this setting for the duration of the command."
1140 :group 'org-link-store
1141 :type 'boolean)
1143 (defcustom org-keep-stored-link-after-insertion nil
1144 "Non-nil means, keep link in list for entire session.
1146 The command `org-store-link' adds a link pointing to the current
1147 location to an internal list. These links accumulate during a session.
1148 The command `org-insert-link' can be used to insert links into any
1149 Org-mode file (offering completion for all stored links). When this
1150 option is nil, every link which has been inserted once using \\[org-insert-link]
1151 will be removed from the list, to make completing the unused links
1152 more efficient."
1153 :group 'org-link-store
1154 :type 'boolean)
1156 (defcustom org-usenet-links-prefer-google nil
1157 "Non-nil means, `org-store-link' will create web links to Google groups.
1158 When nil, Gnus will be used for such links.
1159 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1160 negates this setting for the duration of the command."
1161 :group 'org-link-store
1162 :type 'boolean)
1164 (defgroup org-link-follow nil
1165 "Options concerning following links in Org-mode"
1166 :tag "Org Follow Link"
1167 :group 'org-link)
1169 (defcustom org-tab-follows-link nil
1170 "Non-nil means, on links TAB will follow the link.
1171 Needs to be set before org.el is loaded."
1172 :group 'org-link-follow
1173 :type 'boolean)
1175 (defcustom org-return-follows-link nil
1176 "Non-nil means, on links RET will follow the link.
1177 Needs to be set before org.el is loaded."
1178 :group 'org-link-follow
1179 :type 'boolean)
1181 (defcustom org-mouse-1-follows-link t
1182 "Non-nil means, mouse-1 on a link will follow the link.
1183 A longer mouse click will still set point. Does not wortk on XEmacs.
1184 Needs to be set before org.el is loaded."
1185 :group 'org-link-follow
1186 :type 'boolean)
1188 (defcustom org-mark-ring-length 4
1189 "Number of different positions to be recorded in the ring
1190 Changing this requires a restart of Emacs to work correctly."
1191 :group 'org-link-follow
1192 :type 'interger)
1194 (defcustom org-link-frame-setup
1195 '((vm . vm-visit-folder-other-frame)
1196 (gnus . gnus-other-frame)
1197 (file . find-file-other-window))
1198 "Setup the frame configuration for following links.
1199 When following a link with Emacs, it may often be useful to display
1200 this link in another window or frame. This variable can be used to
1201 set this up for the different types of links.
1202 For VM, use any of
1203 `vm-visit-folder'
1204 `vm-visit-folder-other-frame'
1205 For Gnus, use any of
1206 `gnus'
1207 `gnus-other-frame'
1208 For FILE, use any of
1209 `find-file'
1210 `find-file-other-window'
1211 `find-file-other-frame'
1212 For the calendar, use the variable `calendar-setup'.
1213 For BBDB, it is currently only possible to display the matches in
1214 another window."
1215 :group 'org-link-follow
1216 :type '(list
1217 (cons (const vm)
1218 (choice
1219 (const vm-visit-folder)
1220 (const vm-visit-folder-other-window)
1221 (const vm-visit-folder-other-frame)))
1222 (cons (const gnus)
1223 (choice
1224 (const gnus)
1225 (const gnus-other-frame)))
1226 (cons (const file)
1227 (choice
1228 (const find-file)
1229 (const find-file-other-window)
1230 (const find-file-other-frame)))))
1232 (defcustom org-display-internal-link-with-indirect-buffer nil
1233 "Non-nil means, use indirect buffer to display infile links.
1234 Activating internal links (from one location in a file to another location
1235 in the same file) normally just jumps to the location. When the link is
1236 activated with a C-u prefix (or with mouse-3), the link is displayed in
1237 another window. When this option is set, the other window actually displays
1238 an indirect buffer clone of the current buffer, to avoid any visibility
1239 changes to the current buffer."
1240 :group 'org-link-follow
1241 :type 'boolean)
1243 (defcustom org-open-non-existing-files nil
1244 "Non-nil means, `org-open-file' will open non-existing files.
1245 When nil, an error will be generated."
1246 :group 'org-link-follow
1247 :type 'boolean)
1249 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1250 "Function and arguments to call for following mailto links.
1251 This is a list with the first element being a lisp function, and the
1252 remaining elements being arguments to the function. In string arguments,
1253 %a will be replaced by the address, and %s will be replaced by the subject
1254 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1255 :group 'org-link-follow
1256 :type '(choice
1257 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1258 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1259 (const :tag "message-mail" (message-mail "%a" "%s"))
1260 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1262 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1263 "Non-nil means, ask for confirmation before executing shell links.
1264 Shell links can be dangerous: just think about a link
1266 [[shell:rm -rf ~/*][Google Search]]
1268 This link would show up in your Org-mode document as \"Google Search\",
1269 but really it would remove your entire home directory.
1270 Therefore we advise against setting this variable to nil.
1271 Just change it to `y-or-n-p' of you want to confirm with a
1272 single keystroke rather than having to type \"yes\"."
1273 :group 'org-link-follow
1274 :type '(choice
1275 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1276 (const :tag "with y-or-n (faster)" y-or-n-p)
1277 (const :tag "no confirmation (dangerous)" nil)))
1279 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1280 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1281 Elisp links can be dangerous: just think about a link
1283 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1285 This link would show up in your Org-mode document as \"Google Search\",
1286 but really it would remove your entire home directory.
1287 Therefore we advise against setting this variable to nil.
1288 Just change it to `y-or-n-p' of you want to confirm with a
1289 single keystroke rather than having to type \"yes\"."
1290 :group 'org-link-follow
1291 :type '(choice
1292 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1293 (const :tag "with y-or-n (faster)" y-or-n-p)
1294 (const :tag "no confirmation (dangerous)" nil)))
1296 (defconst org-file-apps-defaults-gnu
1297 '((remote . emacs)
1298 (t . mailcap))
1299 "Default file applications on a UNIX or GNU/Linux system.
1300 See `org-file-apps'.")
1302 (defconst org-file-apps-defaults-macosx
1303 '((remote . emacs)
1304 (t . "open %s")
1305 ("ps" . "gv %s")
1306 ("ps.gz" . "gv %s")
1307 ("eps" . "gv %s")
1308 ("eps.gz" . "gv %s")
1309 ("dvi" . "xdvi %s")
1310 ("fig" . "xfig %s"))
1311 "Default file applications on a MacOS X system.
1312 The system \"open\" is known as a default, but we use X11 applications
1313 for some files for which the OS does not have a good default.
1314 See `org-file-apps'.")
1316 (defconst org-file-apps-defaults-windowsnt
1317 (list
1318 '(remote . emacs)
1319 (cons t
1320 (list (if (featurep 'xemacs)
1321 'mswindows-shell-execute
1322 'w32-shell-execute)
1323 "open" 'file)))
1324 "Default file applications on a Windows NT system.
1325 The system \"open\" is used for most files.
1326 See `org-file-apps'.")
1328 (defcustom org-file-apps
1330 ("txt" . emacs)
1331 ("tex" . emacs)
1332 ("ltx" . emacs)
1333 ("org" . emacs)
1334 ("el" . emacs)
1335 ("bib" . emacs)
1337 "External applications for opening `file:path' items in a document.
1338 Org-mode uses system defaults for different file types, but
1339 you can use this variable to set the application for a given file
1340 extension. The entries in this list are cons cells where the car identifies
1341 files and the cdr the corresponding command. Possible values for the
1342 file identifier are
1343 \"ext\" A string identifying an extension
1344 `directory' Matches a directory
1345 `remote' Matches a remote file, accessible through tramp or efs.
1346 Remote files most likely should be visited through Emacs
1347 because external applications cannot handle such paths.
1348 t Default for all remaining files
1350 Possible values for the command are:
1351 `emacs' The file will be visited by the current Emacs process.
1352 `default' Use the default application for this file type.
1353 string A command to be executed by a shell; %s will be replaced
1354 by the path to the file.
1355 sexp A Lisp form which will be evaluated. The file path will
1356 be available in the Lisp variable `file'.
1357 For more examples, see the system specific constants
1358 `org-file-apps-defaults-macosx'
1359 `org-file-apps-defaults-windowsnt'
1360 `org-file-apps-defaults-gnu'."
1361 :group 'org-link-follow
1362 :type '(repeat
1363 (cons (choice :value ""
1364 (string :tag "Extension")
1365 (const :tag "Default for unrecognized files" t)
1366 (const :tag "Remote file" remote)
1367 (const :tag "Links to a directory" directory))
1368 (choice :value ""
1369 (const :tag "Visit with Emacs" emacs)
1370 (const :tag "Use system default" default)
1371 (string :tag "Command")
1372 (sexp :tag "Lisp form")))))
1374 (defcustom org-mhe-search-all-folders nil
1375 "Non-nil means, that the search for the mh-message will be extended to
1376 all folders if the message cannot be found in the folder given in the link.
1377 Searching all folders is very efficient with one of the search engines
1378 supported by MH-E, but will be slow with pick."
1379 :group 'org-link-follow
1380 :type 'boolean)
1382 (defgroup org-remember nil
1383 "Options concerning interaction with remember.el."
1384 :tag "Org Remember"
1385 :group 'org)
1387 (defcustom org-directory "~/org"
1388 "Directory with org files.
1389 This directory will be used as default to prompt for org files.
1390 Used by the hooks for remember.el."
1391 :group 'org-remember
1392 :type 'directory)
1394 (defcustom org-default-notes-file "~/.notes"
1395 "Default target for storing notes.
1396 Used by the hooks for remember.el. This can be a string, or nil to mean
1397 the value of `remember-data-file'.
1398 You can set this on a per-template basis with the variable
1399 `org-remember-templates'."
1400 :group 'org-remember
1401 :type '(choice
1402 (const :tag "Default from remember-data-file" nil)
1403 file))
1405 (defcustom org-remember-store-without-prompt t
1406 "Non-nil means, `C-c C-c' stores remember note without further promts.
1407 In this case, you need `C-u C-c C-c' to get the prompts for
1408 note file and headline.
1409 When this variable is nil, `C-c C-c' give you the prompts, and
1410 `C-u C-c C-c' trigger the fasttrack."
1411 :group 'org-remember
1412 :type 'boolean)
1414 (defcustom org-remember-use-refile-when-interactive t
1415 "Non-nil means, use refile to file a remember note.
1416 This is only used when the interactive mode for selecting a filing
1417 location is used (see the variable `org-remember-store-without-prompt').
1418 When nil, the `org-goto' interface is used."
1419 :group 'org-remember
1420 :type 'boolean)
1422 (defcustom org-remember-default-headline ""
1423 "The headline that should be the default location in the notes file.
1424 When filing remember notes, the cursor will start at that position.
1425 You can set this on a per-template basis with the variable
1426 `org-remember-templates'."
1427 :group 'org-remember
1428 :type 'string)
1430 (defcustom org-remember-templates nil
1431 "Templates for the creation of remember buffers.
1432 When nil, just let remember make the buffer.
1433 When not nil, this is a list of 5-element lists. In each entry, the first
1434 element is the name of the template, which should be a single short word.
1435 The second element is a character, a unique key to select this template.
1436 The third element is the template. The fourth element is optional and can
1437 specify a destination file for remember items created with this template.
1438 The default file is given by `org-default-notes-file'. An optional fifth
1439 element can specify the headline in that file that should be offered
1440 first when the user is asked to file the entry. The default headline is
1441 given in the variable `org-remember-default-headline'.
1443 The template specifies the structure of the remember buffer. It should have
1444 a first line starting with a star, to act as the org-mode headline.
1445 Furthermore, the following %-escapes will be replaced with content:
1447 %^{prompt} Prompt the user for a string and replace this sequence with it.
1448 A default value and a completion table ca be specified like this:
1449 %^{prompt|default|completion2|completion3|...}
1450 %t time stamp, date only
1451 %T time stamp with date and time
1452 %u, %U like the above, but inactive time stamps
1453 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1454 You may define a prompt like %^{Please specify birthday}t
1455 %n user name (taken from `user-full-name')
1456 %a annotation, normally the link created with org-store-link
1457 %i initial content, the region when remember is called with C-u.
1458 If %i is indented, the entire inserted text will be indented
1459 as well.
1460 %c content of the clipboard, or current kill ring head
1461 %^g prompt for tags, with completion on tags in target file
1462 %^G prompt for tags, with completion all tags in all agenda files
1463 %:keyword specific information for certain link types, see below
1464 %[pathname] insert the contents of the file given by `pathname'
1465 %(sexp) evaluate elisp `(sexp)' and replace with the result
1466 %! Store this note immediately after filling the template
1468 %? After completing the template, position cursor here.
1470 Apart from these general escapes, you can access information specific to the
1471 link type that is created. For example, calling `remember' in emails or gnus
1472 will record the author and the subject of the message, which you can access
1473 with %:author and %:subject, respectively. Here is a complete list of what
1474 is recorded for each link type.
1476 Link type | Available information
1477 -------------------+------------------------------------------------------
1478 bbdb | %:type %:name %:company
1479 vm, wl, mh, rmail | %:type %:subject %:message-id
1480 | %:from %:fromname %:fromaddress
1481 | %:to %:toname %:toaddress
1482 | %:fromto (either \"to NAME\" or \"from NAME\")
1483 gnus | %:group, for messages also all email fields
1484 w3, w3m | %:type %:url
1485 info | %:type %:file %:node
1486 calendar | %:type %:date"
1487 :group 'org-remember
1488 :get (lambda (var) ; Make sure all entries have 5 elements
1489 (mapcar (lambda (x)
1490 (if (not (stringp (car x))) (setq x (cons "" x)))
1491 (cond ((= (length x) 4) (append x '("")))
1492 ((= (length x) 3) (append x '("" "")))
1493 (t x)))
1494 (default-value var)))
1495 :type '(repeat
1496 :tag "enabled"
1497 (list :value ("" ?a "\n" nil nil)
1498 (string :tag "Name")
1499 (character :tag "Selection Key")
1500 (string :tag "Template")
1501 (choice
1502 (file :tag "Destination file")
1503 (const :tag "Prompt for file" nil))
1504 (choice
1505 (string :tag "Destination headline")
1506 (const :tag "Selection interface for heading")))))
1508 (defcustom org-reverse-note-order nil
1509 "Non-nil means, store new notes at the beginning of a file or entry.
1510 When nil, new notes will be filed to the end of a file or entry.
1511 This can also be a list with cons cells of regular expressions that
1512 are matched against file names, and values."
1513 :group 'org-remember
1514 :type '(choice
1515 (const :tag "Reverse always" t)
1516 (const :tag "Reverse never" nil)
1517 (repeat :tag "By file name regexp"
1518 (cons regexp boolean))))
1520 (defcustom org-refile-targets nil
1521 "Targets for refiling entries with \\[org-refile].
1522 This is list of cons cells. Each cell contains:
1523 - a specification of the files to be considered, either a list of files,
1524 or a symbol whose function or value fields will be used to retrieve
1525 a file name or a list of file names. Nil means, refile to a different
1526 heading in the current buffer.
1527 - A specification of how to find candidate refile targets. This may be
1528 any of
1529 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1530 This tag has to be present in all target headlines, inheritance will
1531 not be considered.
1532 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1533 todo keyword.
1534 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1535 headlines that are refiling targets.
1536 - a cons cell (:level . N). Any headline of level N is considered a target.
1537 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1538 ;; FIXME: what if there are a var and func with same name???
1539 :group 'org-remember
1540 :type '(repeat
1541 (cons
1542 (choice :value org-agenda-files
1543 (const :tag "All agenda files" org-agenda-files)
1544 (const :tag "Current buffer" nil)
1545 (function) (variable) (file))
1546 (choice :tag "Identify target headline by"
1547 (cons :tag "Specific tag" (const :tag) (string))
1548 (cons :tag "TODO keyword" (const :todo) (string))
1549 (cons :tag "Regular expression" (const :regexp) (regexp))
1550 (cons :tag "Level number" (const :level) (integer))
1551 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1553 (defcustom org-refile-use-outline-path nil
1554 "Non-nil means, provide refile targets as paths.
1555 So a level 3 headline will be available as level1/level2/level3.
1556 When the value is `file', also include the file name (without directory)
1557 into the path. When `full-file-path', include the full file path."
1558 :group 'org-remember
1559 :type '(choice
1560 (const :tag "Not" nil)
1561 (const :tag "Yes" t)
1562 (const :tag "Start with file name" file)
1563 (const :tag "Start with full file path" full-file-path)))
1565 (defgroup org-todo nil
1566 "Options concerning TODO items in Org-mode."
1567 :tag "Org TODO"
1568 :group 'org)
1570 (defgroup org-progress nil
1571 "Options concerning Progress logging in Org-mode."
1572 :tag "Org Progress"
1573 :group 'org-time)
1575 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1576 "List of TODO entry keyword sequences and their interpretation.
1577 \\<org-mode-map>This is a list of sequences.
1579 Each sequence starts with a symbol, either `sequence' or `type',
1580 indicating if the keywords should be interpreted as a sequence of
1581 action steps, or as different types of TODO items. The first
1582 keywords are states requiring action - these states will select a headline
1583 for inclusion into the global TODO list Org-mode produces. If one of
1584 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1585 signify that no further action is necessary. If \"|\" is not found,
1586 the last keyword is treated as the only DONE state of the sequence.
1588 The command \\[org-todo] cycles an entry through these states, and one
1589 additional state where no keyword is present. For details about this
1590 cycling, see the manual.
1592 TODO keywords and interpretation can also be set on a per-file basis with
1593 the special #+SEQ_TODO and #+TYP_TODO lines.
1595 For backward compatibility, this variable may also be just a list
1596 of keywords - in this case the interptetation (sequence or type) will be
1597 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1598 :group 'org-todo
1599 :group 'org-keywords
1600 :type '(choice
1601 (repeat :tag "Old syntax, just keywords"
1602 (string :tag "Keyword"))
1603 (repeat :tag "New syntax"
1604 (cons
1605 (choice
1606 :tag "Interpretation"
1607 (const :tag "Sequence (cycling hits every state)" sequence)
1608 (const :tag "Type (cycling directly to DONE)" type))
1609 (repeat
1610 (string :tag "Keyword"))))))
1612 (defvar org-todo-keywords-1 nil)
1613 (make-variable-buffer-local 'org-todo-keywords-1)
1614 (defvar org-todo-keywords-for-agenda nil)
1615 (defvar org-done-keywords-for-agenda nil)
1616 (defvar org-not-done-keywords nil)
1617 (make-variable-buffer-local 'org-not-done-keywords)
1618 (defvar org-done-keywords nil)
1619 (make-variable-buffer-local 'org-done-keywords)
1620 (defvar org-todo-heads nil)
1621 (make-variable-buffer-local 'org-todo-heads)
1622 (defvar org-todo-sets nil)
1623 (make-variable-buffer-local 'org-todo-sets)
1624 (defvar org-todo-log-states nil)
1625 (make-variable-buffer-local 'org-todo-log-states)
1626 (defvar org-todo-kwd-alist nil)
1627 (make-variable-buffer-local 'org-todo-kwd-alist)
1628 (defvar org-todo-key-alist nil)
1629 (make-variable-buffer-local 'org-todo-key-alist)
1630 (defvar org-todo-key-trigger nil)
1631 (make-variable-buffer-local 'org-todo-key-trigger)
1633 (defcustom org-todo-interpretation 'sequence
1634 "Controls how TODO keywords are interpreted.
1635 This variable is in principle obsolete and is only used for
1636 backward compatibility, if the interpretation of todo keywords is
1637 not given already in `org-todo-keywords'. See that variable for
1638 more information."
1639 :group 'org-todo
1640 :group 'org-keywords
1641 :type '(choice (const sequence)
1642 (const type)))
1644 (defcustom org-use-fast-todo-selection 'prefix
1645 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1646 This variable describes if and under what circumstances the cycling
1647 mechanism for TODO keywords will be replaced by a single-key, direct
1648 selection scheme.
1650 When nil, fast selection is never used.
1652 When the symbol `prefix', it will be used when `org-todo' is called with
1653 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1654 in an agenda buffer.
1656 When t, fast selection is used by default. In this case, the prefix
1657 argument forces cycling instead.
1659 In all cases, the special interface is only used if access keys have actually
1660 been assigned by the user, i.e. if keywords in the configuration are followed
1661 by a letter in parenthesis, like TODO(t)."
1662 :group 'org-todo
1663 :type '(choice
1664 (const :tag "Never" nil)
1665 (const :tag "By default" t)
1666 (const :tag "Only with C-u C-c C-t" prefix)))
1668 (defcustom org-after-todo-state-change-hook nil
1669 "Hook which is run after the state of a TODO item was changed.
1670 The new state (a string with a TODO keyword, or nil) is available in the
1671 Lisp variable `state'."
1672 :group 'org-todo
1673 :type 'hook)
1675 (defcustom org-log-done nil
1676 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1677 When the state of an entry is changed from nothing or a DONE state to
1678 a not-done TODO state, remove a previous closing date.
1680 This can also be a list of symbols indicating under which conditions
1681 the time stamp recording the action should be annotated with a short note.
1682 Valid members of this list are
1684 done Offer to record a note when marking entries done
1685 state Offer to record a note whenever changing the TODO state
1686 of an item. This is only relevant if TODO keywords are
1687 interpreted as sequence, see variable `org-todo-interpretation'.
1688 When `state' is set, this includes tracking `done'.
1689 clock-out Offer to record a note when clocking out of an item.
1691 A separate window will then pop up and allow you to type a note.
1692 After finishing with C-c C-c, the note will be added directly after the
1693 timestamp, as a plain list item. See also the variable
1694 `org-log-note-headings'.
1696 Logging can also be configured on a per-file basis by adding one of
1697 the following lines anywhere in the buffer:
1699 #+STARTUP: logdone
1700 #+STARTUP: nologging
1701 #+STARTUP: lognotedone
1702 #+STARTUP: lognotestate
1703 #+STARTUP: lognoteclock-out
1705 You can have local logging settings for a subtree by setting the LOGGING
1706 property to one or more of these keywords."
1707 :group 'org-todo
1708 :group 'org-progress
1709 :type '(choice
1710 (const :tag "off" nil)
1711 (const :tag "on" t)
1712 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1713 (const :tag "when item is marked DONE" done)
1714 (const :tag "when TODO state changes" state)
1715 (const :tag "when clocking out" clock-out))))
1717 (defcustom org-log-done-with-time t
1718 "Non-nil means, the CLOSED time stamp will contain date and time.
1719 When nil, only the date will be recorded."
1720 :group 'org-progress
1721 :type 'boolean)
1723 (defcustom org-log-note-headings
1724 '((done . "CLOSING NOTE %t")
1725 (state . "State %-12s %t")
1726 (clock-out . ""))
1727 "Headings for notes added when clocking out or closing TODO items.
1728 The value is an alist, with the car being a symbol indicating the note
1729 context, and the cdr is the heading to be used. The heading may also be the
1730 empty string.
1731 %t in the heading will be replaced by a time stamp.
1732 %s will be replaced by the new TODO state, in double quotes.
1733 %u will be replaced by the user name.
1734 %U will be replaced by the full user name."
1735 :group 'org-todo
1736 :group 'org-progress
1737 :type '(list :greedy t
1738 (cons (const :tag "Heading when closing an item" done) string)
1739 (cons (const :tag
1740 "Heading when changing todo state (todo sequence only)"
1741 state) string)
1742 (cons (const :tag "Heading when clocking out" clock-out) string)))
1744 (defcustom org-log-states-order-reversed t
1745 "Non-nil means, the latest state change note will be directly after heading.
1746 When nil, the notes will be orderer according to time."
1747 :group 'org-todo
1748 :group 'org-progress
1749 :type 'boolean)
1751 (defcustom org-log-repeat t
1752 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1753 When nil, no note will be taken.
1754 This option can also be set with on a per-file-basis with
1756 #+STARTUP: logrepeat
1757 #+STARTUP: nologrepeat
1759 You can have local logging settings for a subtree by setting the LOGGING
1760 property to one or more of these keywords."
1761 :group 'org-todo
1762 :group 'org-progress
1763 :type 'boolean)
1765 (defcustom org-clock-into-drawer 2
1766 "Should clocking info be wrapped into a drawer?
1767 When t, clocking info will always be inserted into a :CLOCK: drawer.
1768 If necessary, the drawer will be created.
1769 When nil, the drawer will not be created, but used when present.
1770 When an integer and the number of clocking entries in an item
1771 reaches or exceeds this number, a drawer will be created."
1772 :group 'org-todo
1773 :group 'org-progress
1774 :type '(choice
1775 (const :tag "Always" t)
1776 (const :tag "Only when drawer exists" nil)
1777 (integer :tag "When at least N clock entries")))
1779 (defcustom org-clock-out-when-done t
1780 "When t, the clock will be stopped when the relevant entry is marked DONE.
1781 Nil means, clock will keep running until stopped explicitly with
1782 `C-c C-x C-o', or until the clock is started in a different item."
1783 :group 'org-progress
1784 :type 'boolean)
1786 (defcustom org-clock-in-switch-to-state nil
1787 "Set task to a special todo state while clocking it.
1788 The value should be the state to which the entry should be switched."
1789 :group 'org-progress
1790 :group 'org-todo
1791 :type '(choice
1792 (const :tag "Don't force a state" nil)
1793 (string :tag "State")))
1795 (defgroup org-priorities nil
1796 "Priorities in Org-mode."
1797 :tag "Org Priorities"
1798 :group 'org-todo)
1800 (defcustom org-highest-priority ?A
1801 "The highest priority of TODO items. A character like ?A, ?B etc.
1802 Must have a smaller ASCII number than `org-lowest-priority'."
1803 :group 'org-priorities
1804 :type 'character)
1806 (defcustom org-lowest-priority ?C
1807 "The lowest priority of TODO items. A character like ?A, ?B etc.
1808 Must have a larger ASCII number than `org-highest-priority'."
1809 :group 'org-priorities
1810 :type 'character)
1812 (defcustom org-default-priority ?B
1813 "The default priority of TODO items.
1814 This is the priority an item get if no explicit priority is given."
1815 :group 'org-priorities
1816 :type 'character)
1818 (defcustom org-priority-start-cycle-with-default t
1819 "Non-nil means, start with default priority when starting to cycle.
1820 When this is nil, the first step in the cycle will be (depending on the
1821 command used) one higher or lower that the default priority."
1822 :group 'org-priorities
1823 :type 'boolean)
1825 (defgroup org-time nil
1826 "Options concerning time stamps and deadlines in Org-mode."
1827 :tag "Org Time"
1828 :group 'org)
1830 (defcustom org-insert-labeled-timestamps-at-point nil
1831 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1832 When nil, these labeled time stamps are forces into the second line of an
1833 entry, just after the headline. When scheduling from the global TODO list,
1834 the time stamp will always be forced into the second line."
1835 :group 'org-time
1836 :type 'boolean)
1838 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1839 "Formats for `format-time-string' which are used for time stamps.
1840 It is not recommended to change this constant.")
1842 (defcustom org-time-stamp-rounding-minutes 0
1843 "Number of minutes to round time stamps to upon insertion.
1844 When zero, insert the time unmodified. Useful rounding numbers
1845 should be factors of 60, so for example 5, 10, 15.
1846 When this is not zero, you can still force an exact time-stamp by using
1847 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1848 :group 'org-time
1849 :type 'integer)
1851 (defcustom org-display-custom-times nil
1852 "Non-nil means, overlay custom formats over all time stamps.
1853 The formats are defined through the variable `org-time-stamp-custom-formats'.
1854 To turn this on on a per-file basis, insert anywhere in the file:
1855 #+STARTUP: customtime"
1856 :group 'org-time
1857 :set 'set-default
1858 :type 'sexp)
1859 (make-variable-buffer-local 'org-display-custom-times)
1861 (defcustom org-time-stamp-custom-formats
1862 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1863 "Custom formats for time stamps. See `format-time-string' for the syntax.
1864 These are overlayed over the default ISO format if the variable
1865 `org-display-custom-times' is set. Time like %H:%M should be at the
1866 end of the second format."
1867 :group 'org-time
1868 :type 'sexp)
1870 (defun org-time-stamp-format (&optional long inactive)
1871 "Get the right format for a time string."
1872 (let ((f (if long (cdr org-time-stamp-formats)
1873 (car org-time-stamp-formats))))
1874 (if inactive
1875 (concat "[" (substring f 1 -1) "]")
1876 f)))
1878 (defcustom org-read-date-prefer-future t
1879 "Non-nil means, assume future for incomplete date input from user.
1880 This affects the following situations:
1881 1. The user gives a day, but no month.
1882 For example, if today is the 15th, and you enter \"3\", Org-mode will
1883 read this as the third of *next* month. However, if you enter \"17\",
1884 it will be considered as *this* month.
1885 2. The user gives a month but not a year.
1886 For example, if it is april and you enter \"feb 2\", this will be read
1887 as feb 2, *next* year. \"May 5\", however, will be this year.
1889 When this option is nil, the current month and year will always be used
1890 as defaults."
1891 :group 'org-time
1892 :type 'boolean)
1894 (defcustom org-read-date-display-live t
1895 "Non-nil means, display current interpretation of date prompt live.
1896 This display will be in an overlay, in the minibuffer."
1897 :group 'org-time
1898 :type 'boolean)
1900 (defcustom org-read-date-popup-calendar t
1901 "Non-nil means, pop up a calendar when prompting for a date.
1902 In the calendar, the date can be selected with mouse-1. However, the
1903 minibuffer will also be active, and you can simply enter the date as well.
1904 When nil, only the minibuffer will be available."
1905 :group 'org-time
1906 :type 'boolean)
1907 (if (fboundp 'defvaralias)
1908 (defvaralias 'org-popup-calendar-for-date-prompt
1909 'org-read-date-popup-calendar))
1911 (defcustom org-extend-today-until 0
1912 "The hour when your day really ends.
1913 This has influence for the following applications:
1914 - When switching the agenda to \"today\". It it is still earlier than
1915 the time given here, the day recognized as TODAY is actually yesterday.
1916 - When a date is read from the user and it is still before the time given
1917 here, the current date and time will be assumed to be yesterday, 23:59.
1919 FIXME:
1920 IMPORTANT: This is still a very experimental feature, it may disappear
1921 again or it may be extended to mean more things."
1922 :group 'org-time
1923 :type 'number)
1925 (defcustom org-edit-timestamp-down-means-later nil
1926 "Non-nil means, S-down will increase the time in a time stamp.
1927 When nil, S-up will increase."
1928 :group 'org-time
1929 :type 'boolean)
1931 (defcustom org-calendar-follow-timestamp-change t
1932 "Non-nil means, make the calendar window follow timestamp changes.
1933 When a timestamp is modified and the calendar window is visible, it will be
1934 moved to the new date."
1935 :group 'org-time
1936 :type 'boolean)
1938 (defcustom org-clock-heading-function nil
1939 "When non-nil, should be a function to create `org-clock-heading'.
1940 This is the string shown in the mode line when a clock is running.
1941 The function is called with point at the beginning of the headline."
1942 :group 'org-time ; FIXME: Should we have a separate group????
1943 :type 'function)
1945 (defgroup org-tags nil
1946 "Options concerning tags in Org-mode."
1947 :tag "Org Tags"
1948 :group 'org)
1950 (defcustom org-tag-alist nil
1951 "List of tags allowed in Org-mode files.
1952 When this list is nil, Org-mode will base TAG input on what is already in the
1953 buffer.
1954 The value of this variable is an alist, the car of each entry must be a
1955 keyword as a string, the cdr may be a character that is used to select
1956 that tag through the fast-tag-selection interface.
1957 See the manual for details."
1958 :group 'org-tags
1959 :type '(repeat
1960 (choice
1961 (cons (string :tag "Tag name")
1962 (character :tag "Access char"))
1963 (const :tag "Start radio group" (:startgroup))
1964 (const :tag "End radio group" (:endgroup)))))
1966 (defcustom org-use-fast-tag-selection 'auto
1967 "Non-nil means, use fast tag selection scheme.
1968 This is a special interface to select and deselect tags with single keys.
1969 When nil, fast selection is never used.
1970 When the symbol `auto', fast selection is used if and only if selection
1971 characters for tags have been configured, either through the variable
1972 `org-tag-alist' or through a #+TAGS line in the buffer.
1973 When t, fast selection is always used and selection keys are assigned
1974 automatically if necessary."
1975 :group 'org-tags
1976 :type '(choice
1977 (const :tag "Always" t)
1978 (const :tag "Never" nil)
1979 (const :tag "When selection characters are configured" 'auto)))
1981 (defcustom org-fast-tag-selection-single-key nil
1982 "Non-nil means, fast tag selection exits after first change.
1983 When nil, you have to press RET to exit it.
1984 During fast tag selection, you can toggle this flag with `C-c'.
1985 This variable can also have the value `expert'. In this case, the window
1986 displaying the tags menu is not even shown, until you press C-c again."
1987 :group 'org-tags
1988 :type '(choice
1989 (const :tag "No" nil)
1990 (const :tag "Yes" t)
1991 (const :tag "Expert" expert)))
1993 (defvar org-fast-tag-selection-include-todo nil
1994 "Non-nil means, fast tags selection interface will also offer TODO states.
1995 This is an undocumented feature, you should not rely on it.")
1997 (defcustom org-tags-column -80
1998 "The column to which tags should be indented in a headline.
1999 If this number is positive, it specifies the column. If it is negative,
2000 it means that the tags should be flushright to that column. For example,
2001 -80 works well for a normal 80 character screen."
2002 :group 'org-tags
2003 :type 'integer)
2005 (defcustom org-auto-align-tags t
2006 "Non-nil means, realign tags after pro/demotion of TODO state change.
2007 These operations change the length of a headline and therefore shift
2008 the tags around. With this options turned on, after each such operation
2009 the tags are again aligned to `org-tags-column'."
2010 :group 'org-tags
2011 :type 'boolean)
2013 (defcustom org-use-tag-inheritance t
2014 "Non-nil means, tags in levels apply also for sublevels.
2015 When nil, only the tags directly given in a specific line apply there.
2016 If you turn off this option, you very likely want to turn on the
2017 companion option `org-tags-match-list-sublevels'."
2018 :group 'org-tags
2019 :type 'boolean)
2021 (defcustom org-tags-match-list-sublevels nil
2022 "Non-nil means list also sublevels of headlines matching tag search.
2023 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2024 the sublevels of a headline matching a tag search often also match
2025 the same search. Listing all of them can create very long lists.
2026 Setting this variable to nil causes subtrees of a match to be skipped.
2027 This option is off by default, because inheritance in on. If you turn
2028 inheritance off, you very likely want to turn this option on.
2030 As a special case, if the tag search is restricted to TODO items, the
2031 value of this variable is ignored and sublevels are always checked, to
2032 make sure all corresponding TODO items find their way into the list."
2033 :group 'org-tags
2034 :type 'boolean)
2036 (defvar org-tags-history nil
2037 "History of minibuffer reads for tags.")
2038 (defvar org-last-tags-completion-table nil
2039 "The last used completion table for tags.")
2040 (defvar org-after-tags-change-hook nil
2041 "Hook that is run after the tags in a line have changed.")
2043 (defgroup org-properties nil
2044 "Options concerning properties in Org-mode."
2045 :tag "Org Properties"
2046 :group 'org)
2048 (defcustom org-property-format "%-10s %s"
2049 "How property key/value pairs should be formatted by `indent-line'.
2050 When `indent-line' hits a property definition, it will format the line
2051 according to this format, mainly to make sure that the values are
2052 lined-up with respect to each other."
2053 :group 'org-properties
2054 :type 'string)
2056 (defcustom org-use-property-inheritance nil
2057 "Non-nil means, properties apply also for sublevels.
2058 This setting is only relevant during property searches, not when querying
2059 an entry with `org-entry-get'. To retrieve a property with inheritance,
2060 you need to call `org-entry-get' with the inheritance flag.
2061 Turning this on can cause significant overhead when doing a search, so
2062 this is turned off by default.
2063 When nil, only the properties directly given in the current entry count.
2064 The value may also be a list of properties that shouldhave inheritance.
2066 However, note that some special properties use inheritance under special
2067 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2068 and the properties ending in \"_ALL\" when they are used as descriptor
2069 for valid values of a property."
2070 :group 'org-properties
2071 :type '(choice
2072 (const :tag "Not" nil)
2073 (const :tag "Always" nil)
2074 (repeat :tag "Specific properties" (string :tag "Property"))))
2076 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2077 "The default column format, if no other format has been defined.
2078 This variable can be set on the per-file basis by inserting a line
2080 #+COLUMNS: %25ITEM ....."
2081 :group 'org-properties
2082 :type 'string)
2084 (defcustom org-global-properties nil
2085 "List of property/value pairs that can be inherited by any entry.
2086 You can set buffer-local values for this by adding lines like
2088 #+PROPERTY: NAME VALUE"
2089 :group 'org-properties
2090 :type '(repeat
2091 (cons (string :tag "Property")
2092 (string :tag "Value"))))
2094 (defvar org-local-properties nil
2095 "List of property/value pairs that can be inherited by any entry.
2096 Valid for the current buffer.
2097 This variable is populated from #+PROPERTY lines.")
2099 (defgroup org-agenda nil
2100 "Options concerning agenda views in Org-mode."
2101 :tag "Org Agenda"
2102 :group 'org)
2104 (defvar org-category nil
2105 "Variable used by org files to set a category for agenda display.
2106 Such files should use a file variable to set it, for example
2108 # -*- mode: org; org-category: \"ELisp\"
2110 or contain a special line
2112 #+CATEGORY: ELisp
2114 If the file does not specify a category, then file's base name
2115 is used instead.")
2116 (make-variable-buffer-local 'org-category)
2118 (defcustom org-agenda-files nil
2119 "The files to be used for agenda display.
2120 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2121 \\[org-remove-file]. You can also use customize to edit the list.
2123 If an entry is a directory, all files in that directory that are matched by
2124 `org-agenda-file-regexp' will be part of the file list.
2126 If the value of the variable is not a list but a single file name, then
2127 the list of agenda files is actually stored and maintained in that file, one
2128 agenda file per line."
2129 :group 'org-agenda
2130 :type '(choice
2131 (repeat :tag "List of files and directories" file)
2132 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2134 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2135 "Regular expression to match files for `org-agenda-files'.
2136 If any element in the list in that variable contains a directory instead
2137 of a normal file, all files in that directory that are matched by this
2138 regular expression will be included."
2139 :group 'org-agenda
2140 :type 'regexp)
2142 (defcustom org-agenda-skip-unavailable-files nil
2143 "t means to just skip non-reachable files in `org-agenda-files'.
2144 Nil means to remove them, after a query, from the list."
2145 :group 'org-agenda
2146 :type 'boolean)
2148 (defcustom org-agenda-multi-occur-extra-files nil
2149 "List of extra files to be searched by `org-occur-in-agenda-files'.
2150 The files in `org-agenda-files' are always searched."
2151 :group 'org-agenda
2152 :type '(repeat file))
2154 (defcustom org-agenda-confirm-kill 1
2155 "When set, remote killing from the agenda buffer needs confirmation.
2156 When t, a confirmation is always needed. When a number N, confirmation is
2157 only needed when the text to be killed contains more than N non-white lines."
2158 :group 'org-agenda
2159 :type '(choice
2160 (const :tag "Never" nil)
2161 (const :tag "Always" t)
2162 (number :tag "When more than N lines")))
2164 (defcustom org-calendar-to-agenda-key [?c]
2165 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2166 The command `org-calendar-goto-agenda' will be bound to this key. The
2167 default is the character `c' because then `c' can be used to switch back and
2168 forth between agenda and calendar."
2169 :group 'org-agenda
2170 :type 'sexp)
2172 (defcustom org-agenda-compact-blocks nil
2173 "Non-nil means, make the block agenda more compact.
2174 This is done by leaving out unnecessary lines."
2175 :group 'org-agenda
2176 :type nil)
2178 (defgroup org-agenda-export nil
2179 "Options concerning exporting agenda views in Org-mode."
2180 :tag "Org Agenda Export"
2181 :group 'org-agenda)
2183 (defcustom org-agenda-with-colors t
2184 "Non-nil means, use colors in agenda views."
2185 :group 'org-agenda-export
2186 :type 'boolean)
2188 (defcustom org-agenda-exporter-settings nil
2189 "Alist of variable/value pairs that should be active during agenda export.
2190 This is a good place to set uptions for ps-print and for htmlize."
2191 :group 'org-agenda-export
2192 :type '(repeat
2193 (list
2194 (variable)
2195 (sexp :tag "Value"))))
2197 (defcustom org-agenda-export-html-style ""
2198 "The style specification for exported HTML Agenda files.
2199 If this variable contains a string, it will replace the default <style>
2200 section as produced by `htmlize'.
2201 Since there are different ways of setting style information, this variable
2202 needs to contain the full HTML structure to provide a style, including the
2203 surrounding HTML tags. The style specifications should include definitions
2204 the fonts used by the agenda, here is an example:
2206 <style type=\"text/css\">
2207 p { font-weight: normal; color: gray; }
2208 .org-agenda-structure {
2209 font-size: 110%;
2210 color: #003399;
2211 font-weight: 600;
2213 .org-todo {
2214 color: #cc6666;Week-agenda:
2215 font-weight: bold;
2217 .org-done {
2218 color: #339933;
2220 .title { text-align: center; }
2221 .todo, .deadline { color: red; }
2222 .done { color: green; }
2223 </style>
2225 or, if you want to keep the style in a file,
2227 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2229 As the value of this option simply gets inserted into the HTML <head> header,
2230 you can \"misuse\" it to also add other text to the header. However,
2231 <style>...</style> is required, if not present the variable will be ignored."
2232 :group 'org-agenda-export
2233 :group 'org-export-html
2234 :type 'string)
2236 (defgroup org-agenda-custom-commands nil
2237 "Options concerning agenda views in Org-mode."
2238 :tag "Org Agenda Custom Commands"
2239 :group 'org-agenda)
2241 (defcustom org-agenda-custom-commands nil
2242 "Custom commands for the agenda.
2243 These commands will be offered on the splash screen displayed by the
2244 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2246 (key desc type match options files)
2248 key The key (one or more characters as a string) to be associated
2249 with the command.
2250 desc A description of the commend, when omitted or nil, a default
2251 description is built using MATCH.
2252 type The command type, any of the following symbols:
2253 todo Entries with a specific TODO keyword, in all agenda files.
2254 tags Tags match in all agenda files.
2255 tags-todo Tags match in all agenda files, TODO entries only.
2256 todo-tree Sparse tree of specific TODO keyword in *current* file.
2257 tags-tree Sparse tree with all tags matches in *current* file.
2258 occur-tree Occur sparse tree for *current* file.
2259 ... A user-defined function.
2260 match What to search for:
2261 - a single keyword for TODO keyword searches
2262 - a tags match expression for tags searches
2263 - a regular expression for occur searches
2264 options A list of option settings, similar to that in a let form, so like
2265 this: ((opt1 val1) (opt2 val2) ...)
2266 files A list of files file to write the produced agenda buffer to
2267 with the command `org-store-agenda-views'.
2268 If a file name ends in \".html\", an HTML version of the buffer
2269 is written out. If it ends in \".ps\", a postscript version is
2270 produced. Otherwide, only the plain text is written to the file.
2272 You can also define a set of commands, to create a composite agenda buffer.
2273 In this case, an entry looks like this:
2275 (key desc (cmd1 cmd2 ...) general-options file)
2277 where
2279 desc A description string to be displayed in the dispatcher menu.
2280 cmd An agenda command, similar to the above. However, tree commands
2281 are no allowed, but instead you can get agenda and global todo list.
2282 So valid commands for a set are:
2283 (agenda)
2284 (alltodo)
2285 (stuck)
2286 (todo \"match\" options files)
2287 (tags \"match\" options files)
2288 (tags-todo \"match\" options files)
2290 Each command can carry a list of options, and another set of options can be
2291 given for the whole set of commands. Individual command options take
2292 precedence over the general options.
2294 When using several characters as key to a command, the first characters
2295 are prefix commands. For the dispatcher to display useful information, you
2296 should provide a description for the prefix, like
2298 (setq org-agenda-custom-commands
2299 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2300 (\"hl\" tags \"+HOME+Lisa\")
2301 (\"hp\" tags \"+HOME+Peter\")
2302 (\"hk\" tags \"+HOME+Kim\")))"
2303 :group 'org-agenda-custom-commands
2304 :type '(repeat
2305 (choice :value ("a" "" tags "" nil)
2306 (list :tag "Single command"
2307 (string :tag "Access Key(s) ")
2308 (option (string :tag "Description"))
2309 (choice
2310 (const :tag "Agenda" agenda)
2311 (const :tag "TODO list" alltodo)
2312 (const :tag "Stuck projects" stuck)
2313 (const :tag "Tags search (all agenda files)" tags)
2314 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2315 (const :tag "TODO keyword search (all agenda files)" todo)
2316 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2317 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2318 (const :tag "Occur tree (current buffer)" occur-tree)
2319 (sexp :tag "Other, user-defined function"))
2320 (string :tag "Match")
2321 (repeat :tag "Local options"
2322 (list (variable :tag "Option") (sexp :tag "Value")))
2323 (option (repeat :tag "Export" (file :tag "Export to"))))
2324 (list :tag "Command series, all agenda files"
2325 (string :tag "Access Key(s)")
2326 (string :tag "Description ")
2327 (repeat
2328 (choice
2329 (const :tag "Agenda" (agenda))
2330 (const :tag "TODO list" (alltodo))
2331 (const :tag "Stuck projects" (stuck))
2332 (list :tag "Tags search"
2333 (const :format "" tags)
2334 (string :tag "Match")
2335 (repeat :tag "Local options"
2336 (list (variable :tag "Option")
2337 (sexp :tag "Value"))))
2339 (list :tag "Tags search, TODO entries only"
2340 (const :format "" tags-todo)
2341 (string :tag "Match")
2342 (repeat :tag "Local options"
2343 (list (variable :tag "Option")
2344 (sexp :tag "Value"))))
2346 (list :tag "TODO keyword search"
2347 (const :format "" todo)
2348 (string :tag "Match")
2349 (repeat :tag "Local options"
2350 (list (variable :tag "Option")
2351 (sexp :tag "Value"))))
2353 (list :tag "Other, user-defined function"
2354 (symbol :tag "function")
2355 (string :tag "Match")
2356 (repeat :tag "Local options"
2357 (list (variable :tag "Option")
2358 (sexp :tag "Value"))))))
2360 (repeat :tag "General options"
2361 (list (variable :tag "Option")
2362 (sexp :tag "Value")))
2363 (option (repeat :tag "Export" (file :tag "Export to"))))
2364 (cons :tag "Prefix key documentation"
2365 (string :tag "Access Key(s)")
2366 (string :tag "Description ")))))
2368 (defcustom org-stuck-projects
2369 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2370 "How to identify stuck projects.
2371 This is a list of four items:
2372 1. A tags/todo matcher string that is used to identify a project.
2373 The entire tree below a headline matched by this is considered one project.
2374 2. A list of TODO keywords identifying non-stuck projects.
2375 If the project subtree contains any headline with one of these todo
2376 keywords, the project is considered to be not stuck. If you specify
2377 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2378 3. A list of tags identifying non-stuck projects.
2379 If the project subtree contains any headline with one of these tags,
2380 the project is considered to be not stuck. If you specify \"*\" as
2381 a tag, any tag will mark the project unstuck.
2382 4. An arbitrary regular expression matching non-stuck projects.
2384 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2385 or `C-c a #' to produce the list."
2386 :group 'org-agenda-custom-commands
2387 :type '(list
2388 (string :tag "Tags/TODO match to identify a project")
2389 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2390 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2391 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2394 (defgroup org-agenda-skip nil
2395 "Options concerning skipping parts of agenda files."
2396 :tag "Org Agenda Skip"
2397 :group 'org-agenda)
2399 (defcustom org-agenda-todo-list-sublevels t
2400 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2401 When nil, the sublevels of a TODO entry are not checked, resulting in
2402 potentially much shorter TODO lists."
2403 :group 'org-agenda-skip
2404 :group 'org-todo
2405 :type 'boolean)
2407 (defcustom org-agenda-todo-ignore-with-date nil
2408 "Non-nil means, don't show entries with a date in the global todo list.
2409 You can use this if you prefer to mark mere appointments with a TODO keyword,
2410 but don't want them to show up in the TODO list.
2411 When this is set, it also covers deadlines and scheduled items, the settings
2412 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2413 will be ignored."
2414 :group 'org-agenda-skip
2415 :group 'org-todo
2416 :type 'boolean)
2418 (defcustom org-agenda-todo-ignore-scheduled nil
2419 "Non-nil means, don't show scheduled entries in the global todo list.
2420 The idea behind this is that by scheduling it, you have already taken care
2421 of this item.
2422 See also `org-agenda-todo-ignore-with-date'."
2423 :group 'org-agenda-skip
2424 :group 'org-todo
2425 :type 'boolean)
2427 (defcustom org-agenda-todo-ignore-deadlines nil
2428 "Non-nil means, don't show near deadline entries in the global todo list.
2429 Near means closer than `org-deadline-warning-days' days.
2430 The idea behind this is that such items will appear in the agenda anyway.
2431 See also `org-agenda-todo-ignore-with-date'."
2432 :group 'org-agenda-skip
2433 :group 'org-todo
2434 :type 'boolean)
2436 (defcustom org-agenda-skip-scheduled-if-done nil
2437 "Non-nil means don't show scheduled items in agenda when they are done.
2438 This is relevant for the daily/weekly agenda, not for the TODO list. And
2439 it applies only to the actual date of the scheduling. Warnings about
2440 an item with a past scheduling dates are always turned off when the item
2441 is DONE."
2442 :group 'org-agenda-skip
2443 :type 'boolean)
2445 (defcustom org-agenda-skip-deadline-if-done nil
2446 "Non-nil means don't show deadines when the corresponding item is done.
2447 When nil, the deadline is still shown and should give you a happy feeling.
2448 This is relevant for the daily/weekly agenda. And it applied only to the
2449 actualy date of the deadline. Warnings about approching and past-due
2450 deadlines are always turned off when the item is DONE."
2451 :group 'org-agenda-skip
2452 :type 'boolean)
2454 (defcustom org-agenda-skip-timestamp-if-done nil
2455 "Non-nil means don't select item by timestamp or -range if it is DONE."
2456 :group 'org-agenda-skip
2457 :type 'boolean)
2459 (defcustom org-timeline-show-empty-dates 3
2460 "Non-nil means, `org-timeline' also shows dates without an entry.
2461 When nil, only the days which actually have entries are shown.
2462 When t, all days between the first and the last date are shown.
2463 When an integer, show also empty dates, but if there is a gap of more than
2464 N days, just insert a special line indicating the size of the gap."
2465 :group 'org-agenda-skip
2466 :type '(choice
2467 (const :tag "None" nil)
2468 (const :tag "All" t)
2469 (number :tag "at most")))
2472 (defgroup org-agenda-startup nil
2473 "Options concerning initial settings in the Agenda in Org Mode."
2474 :tag "Org Agenda Startup"
2475 :group 'org-agenda)
2477 (defcustom org-finalize-agenda-hook nil
2478 "Hook run just before displaying an agenda buffer."
2479 :group 'org-agenda-startup
2480 :type 'hook)
2482 (defcustom org-agenda-mouse-1-follows-link nil
2483 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2484 A longer mouse click will still set point. Does not wortk on XEmacs.
2485 Needs to be set before org.el is loaded."
2486 :group 'org-agenda-startup
2487 :type 'boolean)
2489 (defcustom org-agenda-start-with-follow-mode nil
2490 "The initial value of follow-mode in a newly created agenda window."
2491 :group 'org-agenda-startup
2492 :type 'boolean)
2494 (defgroup org-agenda-windows nil
2495 "Options concerning the windows used by the Agenda in Org Mode."
2496 :tag "Org Agenda Windows"
2497 :group 'org-agenda)
2499 (defcustom org-agenda-window-setup 'reorganize-frame
2500 "How the agenda buffer should be displayed.
2501 Possible values for this option are:
2503 current-window Show agenda in the current window, keeping all other windows.
2504 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2505 other-window Use `switch-to-buffer-other-window' to display agenda.
2506 reorganize-frame Show only two windows on the current frame, the current
2507 window and the agenda.
2508 See also the variable `org-agenda-restore-windows-after-quit'."
2509 :group 'org-agenda-windows
2510 :type '(choice
2511 (const current-window)
2512 (const other-frame)
2513 (const other-window)
2514 (const reorganize-frame)))
2516 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2517 "The min and max height of the agenda window as a fraction of frame height.
2518 The value of the variable is a cons cell with two numbers between 0 and 1.
2519 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2520 :group 'org-agenda-windows
2521 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2523 (defcustom org-agenda-restore-windows-after-quit nil
2524 "Non-nil means, restore window configuration open exiting agenda.
2525 Before the window configuration is changed for displaying the agenda,
2526 the current status is recorded. When the agenda is exited with
2527 `q' or `x' and this option is set, the old state is restored. If
2528 `org-agenda-window-setup' is `other-frame', the value of this
2529 option will be ignored.."
2530 :group 'org-agenda-windows
2531 :type 'boolean)
2533 (defcustom org-indirect-buffer-display 'other-window
2534 "How should indirect tree buffers be displayed?
2535 This applies to indirect buffers created with the commands
2536 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2537 Valid values are:
2538 current-window Display in the current window
2539 other-window Just display in another window.
2540 dedicated-frame Create one new frame, and re-use it each time.
2541 new-frame Make a new frame each time. Note that in this case
2542 previously-made indirect buffers are kept, and you need to
2543 kill these buffers yourself."
2544 :group 'org-structure
2545 :group 'org-agenda-windows
2546 :type '(choice
2547 (const :tag "In current window" current-window)
2548 (const :tag "In current frame, other window" other-window)
2549 (const :tag "Each time a new frame" new-frame)
2550 (const :tag "One dedicated frame" dedicated-frame)))
2552 (defgroup org-agenda-daily/weekly nil
2553 "Options concerning the daily/weekly agenda."
2554 :tag "Org Agenda Daily/Weekly"
2555 :group 'org-agenda)
2557 (defcustom org-agenda-ndays 7
2558 "Number of days to include in overview display.
2559 Should be 1 or 7."
2560 :group 'org-agenda-daily/weekly
2561 :type 'number)
2563 (defcustom org-agenda-start-on-weekday 1
2564 "Non-nil means, start the overview always on the specified weekday.
2565 0 denotes Sunday, 1 denotes Monday etc.
2566 When nil, always start on the current day."
2567 :group 'org-agenda-daily/weekly
2568 :type '(choice (const :tag "Today" nil)
2569 (number :tag "Weekday No.")))
2571 (defcustom org-agenda-show-all-dates t
2572 "Non-nil means, `org-agenda' shows every day in the selected range.
2573 When nil, only the days which actually have entries are shown."
2574 :group 'org-agenda-daily/weekly
2575 :type 'boolean)
2577 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2578 "Format string for displaying dates in the agenda.
2579 Used by the daily/weekly agenda and by the timeline. This should be
2580 a format string understood by `format-time-string', or a function returning
2581 the formatted date as a string. The function must take a single argument,
2582 a calendar-style date list like (month day year)."
2583 :group 'org-agenda-daily/weekly
2584 :type '(choice
2585 (string :tag "Format string")
2586 (function :tag "Function")))
2588 (defun org-agenda-format-date-aligned (date)
2589 "Format a date string for display in the daily/weekly agenda, or timeline.
2590 This function makes sure that dates are aligned for easy reading."
2591 (format "%-9s %2d %s %4d"
2592 (calendar-day-name date)
2593 (extract-calendar-day date)
2594 (calendar-month-name (extract-calendar-month date))
2595 (extract-calendar-year date)))
2597 (defcustom org-agenda-include-diary nil
2598 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2599 :group 'org-agenda-daily/weekly
2600 :type 'boolean)
2602 (defcustom org-agenda-include-all-todo nil
2603 "Set means weekly/daily agenda will always contain all TODO entries.
2604 The TODO entries will be listed at the top of the agenda, before
2605 the entries for specific days."
2606 :group 'org-agenda-daily/weekly
2607 :type 'boolean)
2609 (defcustom org-agenda-repeating-timestamp-show-all t
2610 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2611 When nil, only one occurence is shown, either today or the
2612 nearest into the future."
2613 :group 'org-agenda-daily/weekly
2614 :type 'boolean)
2616 (defcustom org-deadline-warning-days 14
2617 "No. of days before expiration during which a deadline becomes active.
2618 This variable governs the display in sparse trees and in the agenda.
2619 When negative, it means use this number (the absolute value of it)
2620 even if a deadline has a different individual lead time specified."
2621 :group 'org-time
2622 :group 'org-agenda-daily/weekly
2623 :type 'number)
2625 (defcustom org-scheduled-past-days 10000
2626 "No. of days to continue listing scheduled items that are not marked DONE.
2627 When an item is scheduled on a date, it shows up in the agenda on this
2628 day and will be listed until it is marked done for the number of days
2629 given here."
2630 :group 'org-agenda-daily/weekly
2631 :type 'number)
2633 (defgroup org-agenda-time-grid nil
2634 "Options concerning the time grid in the Org-mode Agenda."
2635 :tag "Org Agenda Time Grid"
2636 :group 'org-agenda)
2638 (defcustom org-agenda-use-time-grid t
2639 "Non-nil means, show a time grid in the agenda schedule.
2640 A time grid is a set of lines for specific times (like every two hours between
2641 8:00 and 20:00). The items scheduled for a day at specific times are
2642 sorted in between these lines.
2643 For details about when the grid will be shown, and what it will look like, see
2644 the variable `org-agenda-time-grid'."
2645 :group 'org-agenda-time-grid
2646 :type 'boolean)
2648 (defcustom org-agenda-time-grid
2649 '((daily today require-timed)
2650 "----------------"
2651 (800 1000 1200 1400 1600 1800 2000))
2653 "The settings for time grid for agenda display.
2654 This is a list of three items. The first item is again a list. It contains
2655 symbols specifying conditions when the grid should be displayed:
2657 daily if the agenda shows a single day
2658 weekly if the agenda shows an entire week
2659 today show grid on current date, independent of daily/weekly display
2660 require-timed show grid only if at least one item has a time specification
2662 The second item is a string which will be places behing the grid time.
2664 The third item is a list of integers, indicating the times that should have
2665 a grid line."
2666 :group 'org-agenda-time-grid
2667 :type
2668 '(list
2669 (set :greedy t :tag "Grid Display Options"
2670 (const :tag "Show grid in single day agenda display" daily)
2671 (const :tag "Show grid in weekly agenda display" weekly)
2672 (const :tag "Always show grid for today" today)
2673 (const :tag "Show grid only if any timed entries are present"
2674 require-timed)
2675 (const :tag "Skip grid times already present in an entry"
2676 remove-match))
2677 (string :tag "Grid String")
2678 (repeat :tag "Grid Times" (integer :tag "Time"))))
2680 (defgroup org-agenda-sorting nil
2681 "Options concerning sorting in the Org-mode Agenda."
2682 :tag "Org Agenda Sorting"
2683 :group 'org-agenda)
2685 (defconst org-sorting-choice
2686 '(choice
2687 (const time-up) (const time-down)
2688 (const category-keep) (const category-up) (const category-down)
2689 (const tag-down) (const tag-up)
2690 (const priority-up) (const priority-down))
2691 "Sorting choices.")
2693 (defcustom org-agenda-sorting-strategy
2694 '((agenda time-up category-keep priority-down)
2695 (todo category-keep priority-down)
2696 (tags category-keep priority-down))
2697 "Sorting structure for the agenda items of a single day.
2698 This is a list of symbols which will be used in sequence to determine
2699 if an entry should be listed before another entry. The following
2700 symbols are recognized:
2702 time-up Put entries with time-of-day indications first, early first
2703 time-down Put entries with time-of-day indications first, late first
2704 category-keep Keep the default order of categories, corresponding to the
2705 sequence in `org-agenda-files'.
2706 category-up Sort alphabetically by category, A-Z.
2707 category-down Sort alphabetically by category, Z-A.
2708 tag-up Sort alphabetically by last tag, A-Z.
2709 tag-down Sort alphabetically by last tag, Z-A.
2710 priority-up Sort numerically by priority, high priority last.
2711 priority-down Sort numerically by priority, high priority first.
2713 The different possibilities will be tried in sequence, and testing stops
2714 if one comparison returns a \"not-equal\". For example, the default
2715 '(time-up category-keep priority-down)
2716 means: Pull out all entries having a specified time of day and sort them,
2717 in order to make a time schedule for the current day the first thing in the
2718 agenda listing for the day. Of the entries without a time indication, keep
2719 the grouped in categories, don't sort the categories, but keep them in
2720 the sequence given in `org-agenda-files'. Within each category sort by
2721 priority.
2723 Leaving out `category-keep' would mean that items will be sorted across
2724 categories by priority.
2726 Instead of a single list, this can also be a set of list for specific
2727 contents, with a context symbol in the car of the list, any of
2728 `agenda', `todo', `tags' for the corresponding agenda views."
2729 :group 'org-agenda-sorting
2730 :type `(choice
2731 (repeat :tag "General" ,org-sorting-choice)
2732 (list :tag "Individually"
2733 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2734 (repeat ,org-sorting-choice))
2735 (cons (const :tag "Strategy for TODO lists" todo)
2736 (repeat ,org-sorting-choice))
2737 (cons (const :tag "Strategy for Tags matches" tags)
2738 (repeat ,org-sorting-choice)))))
2740 (defcustom org-sort-agenda-notime-is-late t
2741 "Non-nil means, items without time are considered late.
2742 This is only relevant for sorting. When t, items which have no explicit
2743 time like 15:30 will be considered as 99:01, i.e. later than any items which
2744 do have a time. When nil, the default time is before 0:00. You can use this
2745 option to decide if the schedule for today should come before or after timeless
2746 agenda entries."
2747 :group 'org-agenda-sorting
2748 :type 'boolean)
2750 (defgroup org-agenda-line-format nil
2751 "Options concerning the entry prefix in the Org-mode agenda display."
2752 :tag "Org Agenda Line Format"
2753 :group 'org-agenda)
2755 (defcustom org-agenda-prefix-format
2756 '((agenda . " %-12:c%?-12t% s")
2757 (timeline . " % s")
2758 (todo . " %-12:c")
2759 (tags . " %-12:c"))
2760 "Format specifications for the prefix of items in the agenda views.
2761 An alist with four entries, for the different agenda types. The keys to the
2762 sublists are `agenda', `timeline', `todo', and `tags'. The values
2763 are format strings.
2764 This format works similar to a printf format, with the following meaning:
2766 %c the category of the item, \"Diary\" for entries from the diary, or
2767 as given by the CATEGORY keyword or derived from the file name.
2768 %T the *last* tag of the item. Last because inherited tags come
2769 first in the list.
2770 %t the time-of-day specification if one applies to the entry, in the
2771 format HH:MM
2772 %s Scheduling/Deadline information, a short string
2774 All specifiers work basically like the standard `%s' of printf, but may
2775 contain two additional characters: A question mark just after the `%' and
2776 a whitespace/punctuation character just before the final letter.
2778 If the first character after `%' is a question mark, the entire field
2779 will only be included if the corresponding value applies to the
2780 current entry. This is useful for fields which should have fixed
2781 width when present, but zero width when absent. For example,
2782 \"%?-12t\" will result in a 12 character time field if a time of the
2783 day is specified, but will completely disappear in entries which do
2784 not contain a time.
2786 If there is punctuation or whitespace character just before the final
2787 format letter, this character will be appended to the field value if
2788 the value is not empty. For example, the format \"%-12:c\" leads to
2789 \"Diary: \" if the category is \"Diary\". If the category were be
2790 empty, no additional colon would be interted.
2792 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2793 - Indent the line with two space characters
2794 - Give the category in a 12 chars wide field, padded with whitespace on
2795 the right (because of `-'). Append a colon if there is a category
2796 (because of `:').
2797 - If there is a time-of-day, put it into a 12 chars wide field. If no
2798 time, don't put in an empty field, just skip it (because of '?').
2799 - Finally, put the scheduling information and append a whitespace.
2801 As another example, if you don't want the time-of-day of entries in
2802 the prefix, you could use:
2804 (setq org-agenda-prefix-format \" %-11:c% s\")
2806 See also the variables `org-agenda-remove-times-when-in-prefix' and
2807 `org-agenda-remove-tags'."
2808 :type '(choice
2809 (string :tag "General format")
2810 (list :greedy t :tag "View dependent"
2811 (cons (const agenda) (string :tag "Format"))
2812 (cons (const timeline) (string :tag "Format"))
2813 (cons (const todo) (string :tag "Format"))
2814 (cons (const tags) (string :tag "Format"))))
2815 :group 'org-agenda-line-format)
2817 (defvar org-prefix-format-compiled nil
2818 "The compiled version of the most recently used prefix format.
2819 See the variable `org-agenda-prefix-format'.")
2821 (defcustom org-agenda-todo-keyword-format "%-1s"
2822 "Format for the TODO keyword in agenda lines.
2823 Set this to something like \"%-12s\" if you want all TODO keywords
2824 to occupy a fixed space in the agenda display."
2825 :group 'org-agenda-line-format
2826 :type 'string)
2828 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2829 "Text preceeding scheduled items in the agenda view.
2830 This is a list with two strings. The first applies when the item is
2831 scheduled on the current day. The second applies when it has been scheduled
2832 previously, it may contain a %d to capture how many days ago the item was
2833 scheduled."
2834 :group 'org-agenda-line-format
2835 :type '(list
2836 (string :tag "Scheduled today ")
2837 (string :tag "Scheduled previously")))
2839 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2840 "Text preceeding deadline items in the agenda view.
2841 This is a list with two strings. The first applies when the item has its
2842 deadline on the current day. The second applies when it is in the past or
2843 in the future, it may contain %d to capture how many days away the deadline
2844 is (was)."
2845 :group 'org-agenda-line-format
2846 :type '(list
2847 (string :tag "Deadline today ")
2848 (string :tag "Deadline relative")))
2850 (defcustom org-agenda-remove-times-when-in-prefix t
2851 "Non-nil means, remove duplicate time specifications in agenda items.
2852 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2853 time-of-day specification in a headline or diary entry is extracted and
2854 placed into the prefix. If this option is non-nil, the original specification
2855 \(a timestamp or -range, or just a plain time(range) specification like
2856 11:30-4pm) will be removed for agenda display. This makes the agenda less
2857 cluttered.
2858 The option can be t or nil. It may also be the symbol `beg', indicating
2859 that the time should only be removed what it is located at the beginning of
2860 the headline/diary entry."
2861 :group 'org-agenda-line-format
2862 :type '(choice
2863 (const :tag "Always" t)
2864 (const :tag "Never" nil)
2865 (const :tag "When at beginning of entry" beg)))
2868 (defcustom org-agenda-default-appointment-duration nil
2869 "Default duration for appointments that only have a starting time.
2870 When nil, no duration is specified in such cases.
2871 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2872 :group 'org-agenda-line-format
2873 :type '(choice
2874 (integer :tag "Minutes")
2875 (const :tag "No default duration")))
2878 (defcustom org-agenda-remove-tags nil
2879 "Non-nil means, remove the tags from the headline copy in the agenda.
2880 When this is the symbol `prefix', only remove tags when
2881 `org-agenda-prefix-format' contains a `%T' specifier."
2882 :group 'org-agenda-line-format
2883 :type '(choice
2884 (const :tag "Always" t)
2885 (const :tag "Never" nil)
2886 (const :tag "When prefix format contains %T" prefix)))
2888 (if (fboundp 'defvaralias)
2889 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2890 'org-agenda-remove-tags))
2892 (defcustom org-agenda-tags-column -80
2893 "Shift tags in agenda items to this column.
2894 If this number is positive, it specifies the column. If it is negative,
2895 it means that the tags should be flushright to that column. For example,
2896 -80 works well for a normal 80 character screen."
2897 :group 'org-agenda-line-format
2898 :type 'integer)
2900 (if (fboundp 'defvaralias)
2901 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2903 (defcustom org-agenda-fontify-priorities t
2904 "Non-nil means, highlight low and high priorities in agenda.
2905 When t, the highest priority entries are bold, lowest priority italic.
2906 This may also be an association list of priority faces. The face may be
2907 a names face, or a list like `(:background \"Red\")'."
2908 :group 'org-agenda-line-format
2909 :type '(choice
2910 (const :tag "Never" nil)
2911 (const :tag "Defaults" t)
2912 (repeat :tag "Specify"
2913 (list (character :tag "Priority" :value ?A)
2914 (sexp :tag "face")))))
2916 (defgroup org-latex nil
2917 "Options for embedding LaTeX code into Org-mode"
2918 :tag "Org LaTeX"
2919 :group 'org)
2921 (defcustom org-format-latex-options
2922 '(:foreground default :background default :scale 1.0
2923 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2924 :matchers ("begin" "$" "$$" "\\(" "\\["))
2925 "Options for creating images from LaTeX fragments.
2926 This is a property list with the following properties:
2927 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2928 `default' means use the forground of the default face.
2929 :background the background color, or \"Transparent\".
2930 `default' means use the background of the default face.
2931 :scale a scaling factor for the size of the images
2932 :html-foreground, :html-background, :html-scale
2933 The same numbers for HTML export.
2934 :matchers a list indicating which matchers should be used to
2935 find LaTeX fragments. Valid members of this list are:
2936 \"begin\" find environments
2937 \"$\" find math expressions surrounded by $...$
2938 \"$$\" find math expressions surrounded by $$....$$
2939 \"\\(\" find math expressions surrounded by \\(...\\)
2940 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2941 :group 'org-latex
2942 :type 'plist)
2944 (defcustom org-format-latex-header "\\documentclass{article}
2945 \\usepackage{fullpage} % do not remove
2946 \\usepackage{amssymb}
2947 \\usepackage[usenames]{color}
2948 \\usepackage{amsmath}
2949 \\usepackage{latexsym}
2950 \\usepackage[mathscr]{eucal}
2951 \\pagestyle{empty} % do not remove"
2952 "The document header used for processing LaTeX fragments."
2953 :group 'org-latex
2954 :type 'string)
2956 (defgroup org-export nil
2957 "Options for exporting org-listings."
2958 :tag "Org Export"
2959 :group 'org)
2961 (defgroup org-export-general nil
2962 "General options for exporting Org-mode files."
2963 :tag "Org Export General"
2964 :group 'org-export)
2966 ;; FIXME
2967 (defvar org-export-publishing-directory nil)
2969 (defcustom org-export-with-special-strings t
2970 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
2971 When this option is turned on, these strings will be exported as:
2973 Org HTML LaTeX
2974 -----+----------+--------
2975 \\- &shy; \\-
2976 -- &ndash; --
2977 --- &mdash; ---
2978 ... &hellip; \ldots
2980 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
2981 :group 'org-export-translation
2982 :type 'boolean)
2984 (defcustom org-export-language-setup
2985 '(("en" "Author" "Date" "Table of Contents")
2986 ("cs" "Autor" "Datum" "Obsah")
2987 ("da" "Ophavsmand" "Dato" "Indhold")
2988 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2989 ("es" "Autor" "Fecha" "\xcdndice")
2990 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2991 ("it" "Autore" "Data" "Indice")
2992 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2993 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2994 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2995 "Terms used in export text, translated to different languages.
2996 Use the variable `org-export-default-language' to set the language,
2997 or use the +OPTION lines for a per-file setting."
2998 :group 'org-export-general
2999 :type '(repeat
3000 (list
3001 (string :tag "HTML language tag")
3002 (string :tag "Author")
3003 (string :tag "Date")
3004 (string :tag "Table of Contents"))))
3006 (defcustom org-export-default-language "en"
3007 "The default language of HTML export, as a string.
3008 This should have an association in `org-export-language-setup'."
3009 :group 'org-export-general
3010 :type 'string)
3012 (defcustom org-export-skip-text-before-1st-heading t
3013 "Non-nil means, skip all text before the first headline when exporting.
3014 When nil, that text is exported as well."
3015 :group 'org-export-general
3016 :type 'boolean)
3018 (defcustom org-export-headline-levels 3
3019 "The last level which is still exported as a headline.
3020 Inferior levels will produce itemize lists when exported.
3021 Note that a numeric prefix argument to an exporter function overrides
3022 this setting.
3024 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3025 :group 'org-export-general
3026 :type 'number)
3028 (defcustom org-export-with-section-numbers t
3029 "Non-nil means, add section numbers to headlines when exporting.
3031 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3032 :group 'org-export-general
3033 :type 'boolean)
3035 (defcustom org-export-with-toc t
3036 "Non-nil means, create a table of contents in exported files.
3037 The TOC contains headlines with levels up to`org-export-headline-levels'.
3038 When an integer, include levels up to N in the toc, this may then be
3039 different from `org-export-headline-levels', but it will not be allowed
3040 to be larger than the number of headline levels.
3041 When nil, no table of contents is made.
3043 Headlines which contain any TODO items will be marked with \"(*)\" in
3044 ASCII export, and with red color in HTML output, if the option
3045 `org-export-mark-todo-in-toc' is set.
3047 In HTML output, the TOC will be clickable.
3049 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3050 or \"toc:3\"."
3051 :group 'org-export-general
3052 :type '(choice
3053 (const :tag "No Table of Contents" nil)
3054 (const :tag "Full Table of Contents" t)
3055 (integer :tag "TOC to level")))
3057 (defcustom org-export-mark-todo-in-toc nil
3058 "Non-nil means, mark TOC lines that contain any open TODO items."
3059 :group 'org-export-general
3060 :type 'boolean)
3062 (defcustom org-export-preserve-breaks nil
3063 "Non-nil means, preserve all line breaks when exporting.
3064 Normally, in HTML output paragraphs will be reformatted. In ASCII
3065 export, line breaks will always be preserved, regardless of this variable.
3067 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3068 :group 'org-export-general
3069 :type 'boolean)
3071 (defcustom org-export-with-archived-trees 'headline
3072 "Whether subtrees with the ARCHIVE tag should be exported.
3073 This can have three different values
3074 nil Do not export, pretend this tree is not present
3075 t Do export the entire tree
3076 headline Only export the headline, but skip the tree below it."
3077 :group 'org-export-general
3078 :group 'org-archive
3079 :type '(choice
3080 (const :tag "not at all" nil)
3081 (const :tag "headline only" 'headline)
3082 (const :tag "entirely" t)))
3084 (defcustom org-export-author-info t
3085 "Non-nil means, insert author name and email into the exported file.
3087 This option can also be set with the +OPTIONS line,
3088 e.g. \"author-info:nil\"."
3089 :group 'org-export-general
3090 :type 'boolean)
3092 (defcustom org-export-time-stamp-file t
3093 "Non-nil means, insert a time stamp into the exported file.
3094 The time stamp shows when the file was created.
3096 This option can also be set with the +OPTIONS line,
3097 e.g. \"timestamp:nil\"."
3098 :group 'org-export-general
3099 :type 'boolean)
3101 (defcustom org-export-with-timestamps t
3102 "If nil, do not export time stamps and associated keywords."
3103 :group 'org-export-general
3104 :type 'boolean)
3106 (defcustom org-export-remove-timestamps-from-toc t
3107 "If nil, remove timestamps from the table of contents entries."
3108 :group 'org-export-general
3109 :type 'boolean)
3111 (defcustom org-export-with-tags 'not-in-toc
3112 "If nil, do not export tags, just remove them from headlines.
3113 If this is the symbol `not-in-toc', tags will be removed from table of
3114 contents entries, but still be shown in the headlines of the document.
3116 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3117 :group 'org-export-general
3118 :type '(choice
3119 (const :tag "Off" nil)
3120 (const :tag "Not in TOC" not-in-toc)
3121 (const :tag "On" t)))
3123 (defcustom org-export-with-drawers nil
3124 "Non-nil means, export with drawers like the property drawer.
3125 When t, all drawers are exported. This may also be a list of
3126 drawer names to export."
3127 :group 'org-export-general
3128 :type '(choice
3129 (const :tag "All drawers" t)
3130 (const :tag "None" nil)
3131 (repeat :tag "Selected drawers"
3132 (string :tag "Drawer name"))))
3134 (defgroup org-export-translation nil
3135 "Options for translating special ascii sequences for the export backends."
3136 :tag "Org Export Translation"
3137 :group 'org-export)
3139 (defcustom org-export-with-emphasize t
3140 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3141 If the export target supports emphasizing text, the word will be
3142 typeset in bold, italic, or underlined, respectively. Works only for
3143 single words, but you can say: I *really* *mean* *this*.
3144 Not all export backends support this.
3146 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3147 :group 'org-export-translation
3148 :type 'boolean)
3150 (defcustom org-export-with-footnotes t
3151 "If nil, export [1] as a footnote marker.
3152 Lines starting with [1] will be formatted as footnotes.
3154 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3155 :group 'org-export-translation
3156 :type 'boolean)
3158 (defcustom org-export-with-sub-superscripts t
3159 "Non-nil means, interpret \"_\" and \"^\" for export.
3160 When this option is turned on, you can use TeX-like syntax for sub- and
3161 superscripts. Several characters after \"_\" or \"^\" will be
3162 considered as a single item - so grouping with {} is normally not
3163 needed. For example, the following things will be parsed as single
3164 sub- or superscripts.
3166 10^24 or 10^tau several digits will be considered 1 item.
3167 10^-12 or 10^-tau a leading sign with digits or a word
3168 x^2-y^3 will be read as x^2 - y^3, because items are
3169 terminated by almost any nonword/nondigit char.
3170 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3172 Still, ambiguity is possible - so when in doubt use {} to enclose the
3173 sub/superscript. If you set this variable to the symbol `{}',
3174 the braces are *required* in order to trigger interpretations as
3175 sub/superscript. This can be helpful in documents that need \"_\"
3176 frequently in plain text.
3178 Not all export backends support this, but HTML does.
3180 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3181 :group 'org-export-translation
3182 :type '(choice
3183 (const :tag "Always interpret" t)
3184 (const :tag "Only with braces" {})
3185 (const :tag "Never interpret" nil)))
3187 (defcustom org-export-with-special-strings t
3188 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3189 When this option is turned on, these strings will be exported as:
3191 \\- : &shy;
3192 -- : &ndash;
3193 --- : &mdash;
3195 Not all export backends support this, but HTML does.
3197 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3198 :group 'org-export-translation
3199 :type 'boolean)
3201 (defcustom org-export-with-TeX-macros t
3202 "Non-nil means, interpret simple TeX-like macros when exporting.
3203 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3204 No only real TeX macros will work here, but the standard HTML entities
3205 for math can be used as macro names as well. For a list of supported
3206 names in HTML export, see the constant `org-html-entities'.
3207 Not all export backends support this.
3209 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3210 :group 'org-export-translation
3211 :group 'org-export-latex
3212 :type 'boolean)
3214 (defcustom org-export-with-LaTeX-fragments nil
3215 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3216 When set, the exporter will find LaTeX environments if the \\begin line is
3217 the first non-white thing on a line. It will also find the math delimiters
3218 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3219 display math.
3221 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3222 :group 'org-export-translation
3223 :group 'org-export-latex
3224 :type 'boolean)
3226 (defcustom org-export-with-fixed-width t
3227 "Non-nil means, lines starting with \":\" will be in fixed width font.
3228 This can be used to have pre-formatted text, fragments of code etc. For
3229 example:
3230 : ;; Some Lisp examples
3231 : (while (defc cnt)
3232 : (ding))
3233 will be looking just like this in also HTML. See also the QUOTE keyword.
3234 Not all export backends support this.
3236 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3237 :group 'org-export-translation
3238 :type 'boolean)
3240 (defcustom org-match-sexp-depth 3
3241 "Number of stacked braces for sub/superscript matching.
3242 This has to be set before loading org.el to be effective."
3243 :group 'org-export-translation
3244 :type 'integer)
3246 (defgroup org-export-tables nil
3247 "Options for exporting tables in Org-mode."
3248 :tag "Org Export Tables"
3249 :group 'org-export)
3251 (defcustom org-export-with-tables t
3252 "If non-nil, lines starting with \"|\" define a table.
3253 For example:
3255 | Name | Address | Birthday |
3256 |-------------+----------+-----------|
3257 | Arthur Dent | England | 29.2.2100 |
3259 Not all export backends support this.
3261 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3262 :group 'org-export-tables
3263 :type 'boolean)
3265 (defcustom org-export-highlight-first-table-line t
3266 "Non-nil means, highlight the first table line.
3267 In HTML export, this means use <th> instead of <td>.
3268 In tables created with table.el, this applies to the first table line.
3269 In Org-mode tables, all lines before the first horizontal separator
3270 line will be formatted with <th> tags."
3271 :group 'org-export-tables
3272 :type 'boolean)
3274 (defcustom org-export-table-remove-special-lines t
3275 "Remove special lines and marking characters in calculating tables.
3276 This removes the special marking character column from tables that are set
3277 up for spreadsheet calculations. It also removes the entire lines
3278 marked with `!', `_', or `^'. The lines with `$' are kept, because
3279 the values of constants may be useful to have."
3280 :group 'org-export-tables
3281 :type 'boolean)
3283 (defcustom org-export-prefer-native-exporter-for-tables nil
3284 "Non-nil means, always export tables created with table.el natively.
3285 Natively means, use the HTML code generator in table.el.
3286 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3287 the table does not use row- or column-spanning). This has the
3288 advantage, that the automatic HTML conversions for math symbols and
3289 sub/superscripts can be applied. Org-mode's HTML generator is also
3290 much faster."
3291 :group 'org-export-tables
3292 :type 'boolean)
3294 (defgroup org-export-ascii nil
3295 "Options specific for ASCII export of Org-mode files."
3296 :tag "Org Export ASCII"
3297 :group 'org-export)
3299 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3300 "Characters for underlining headings in ASCII export.
3301 In the given sequence, these characters will be used for level 1, 2, ..."
3302 :group 'org-export-ascii
3303 :type '(repeat character))
3305 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3306 "Bullet characters for headlines converted to lists in ASCII export.
3307 The first character is used for the first lest level generated in this
3308 way, and so on. If there are more levels than characters given here,
3309 the list will be repeated.
3310 Note that plain lists will keep the same bullets as the have in the
3311 Org-mode file."
3312 :group 'org-export-ascii
3313 :type '(repeat character))
3315 (defgroup org-export-xml nil
3316 "Options specific for XML export of Org-mode files."
3317 :tag "Org Export XML"
3318 :group 'org-export)
3320 (defgroup org-export-html nil
3321 "Options specific for HTML export of Org-mode files."
3322 :tag "Org Export HTML"
3323 :group 'org-export)
3325 (defcustom org-export-html-coding-system nil
3327 :group 'org-export-html
3328 :type 'coding-system)
3330 (defcustom org-export-html-extension "html"
3331 "The extension for exported HTML files."
3332 :group 'org-export-html
3333 :type 'string)
3335 (defcustom org-export-html-style
3336 "<style type=\"text/css\">
3337 html {
3338 font-family: Times, serif;
3339 font-size: 12pt;
3341 .title { text-align: center; }
3342 .todo { color: red; }
3343 .done { color: green; }
3344 .timestamp { color: grey }
3345 .timestamp-kwd { color: CadetBlue }
3346 .tag { background-color:lightblue; font-weight:normal }
3347 .target { background-color: lavender; }
3348 pre {
3349 border: 1pt solid #AEBDCC;
3350 background-color: #F3F5F7;
3351 padding: 5pt;
3352 font-family: courier, monospace;
3354 table { border-collapse: collapse; }
3355 td, th {
3356 vertical-align: top;
3357 <!--border: 1pt solid #ADB9CC;-->
3359 </style>"
3360 "The default style specification for exported HTML files.
3361 Since there are different ways of setting style information, this variable
3362 needs to contain the full HTML structure to provide a style, including the
3363 surrounding HTML tags. The style specifications should include definitions
3364 for new classes todo, done, title, and deadline. For example, valid values
3365 would be:
3367 <style type=\"text/css\">
3368 p { font-weight: normal; color: gray; }
3369 h1 { color: black; }
3370 .title { text-align: center; }
3371 .todo, .deadline { color: red; }
3372 .done { color: green; }
3373 </style>
3375 or, if you want to keep the style in a file,
3377 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3379 As the value of this option simply gets inserted into the HTML <head> header,
3380 you can \"misuse\" it to add arbitrary text to the header."
3381 :group 'org-export-html
3382 :type 'string)
3385 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3386 "Format for typesetting the document title in HTML export."
3387 :group 'org-export-html
3388 :type 'string)
3390 (defcustom org-export-html-toplevel-hlevel 2
3391 "The <H> level for level 1 headings in HTML export."
3392 :group 'org-export-html
3393 :type 'string)
3395 (defcustom org-export-html-link-org-files-as-html t
3396 "Non-nil means, make file links to `file.org' point to `file.html'.
3397 When org-mode is exporting an org-mode file to HTML, links to
3398 non-html files are directly put into a href tag in HTML.
3399 However, links to other Org-mode files (recognized by the
3400 extension `.org.) should become links to the corresponding html
3401 file, assuming that the linked org-mode file will also be
3402 converted to HTML.
3403 When nil, the links still point to the plain `.org' file."
3404 :group 'org-export-html
3405 :type 'boolean)
3407 (defcustom org-export-html-inline-images 'maybe
3408 "Non-nil means, inline images into exported HTML pages.
3409 This is done using an <img> tag. When nil, an anchor with href is used to
3410 link to the image. If this option is `maybe', then images in links with
3411 an empty description will be inlined, while images with a description will
3412 be linked only."
3413 :group 'org-export-html
3414 :type '(choice (const :tag "Never" nil)
3415 (const :tag "Always" t)
3416 (const :tag "When there is no description" maybe)))
3418 ;; FIXME: rename
3419 (defcustom org-export-html-expand t
3420 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3421 When nil, these tags will be exported as plain text and therefore
3422 not be interpreted by a browser.
3424 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3425 :group 'org-export-html
3426 :type 'boolean)
3428 (defcustom org-export-html-table-tag
3429 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3430 "The HTML tag that is used to start a table.
3431 This must be a <table> tag, but you may change the options like
3432 borders and spacing."
3433 :group 'org-export-html
3434 :type 'string)
3436 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3437 "The opening tag for table header fields.
3438 This is customizable so that alignment options can be specified."
3439 :group 'org-export-tables
3440 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3442 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3443 "The opening tag for table data fields.
3444 This is customizable so that alignment options can be specified."
3445 :group 'org-export-tables
3446 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3448 (defcustom org-export-html-with-timestamp nil
3449 "If non-nil, write `org-export-html-html-helper-timestamp'
3450 into the exported HTML text. Otherwise, the buffer will just be saved
3451 to a file."
3452 :group 'org-export-html
3453 :type 'boolean)
3455 (defcustom org-export-html-html-helper-timestamp
3456 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3457 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3458 :group 'org-export-html
3459 :type 'string)
3461 (defgroup org-export-icalendar nil
3462 "Options specific for iCalendar export of Org-mode files."
3463 :tag "Org Export iCalendar"
3464 :group 'org-export)
3466 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3467 "The file name for the iCalendar file covering all agenda files.
3468 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3469 The file name should be absolute, the file will be overwritten without warning."
3470 :group 'org-export-icalendar
3471 :type 'file)
3473 (defcustom org-icalendar-include-todo nil
3474 "Non-nil means, export to iCalendar files should also cover TODO items."
3475 :group 'org-export-icalendar
3476 :type '(choice
3477 (const :tag "None" nil)
3478 (const :tag "Unfinished" t)
3479 (const :tag "All" all)))
3481 (defcustom org-icalendar-include-sexps t
3482 "Non-nil means, export to iCalendar files should also cover sexp entries.
3483 These are entries like in the diary, but directly in an Org-mode file."
3484 :group 'org-export-icalendar
3485 :type 'boolean)
3487 (defcustom org-icalendar-include-body 100
3488 "Amount of text below headline to be included in iCalendar export.
3489 This is a number of characters that should maximally be included.
3490 Properties, scheduling and clocking lines will always be removed.
3491 The text will be inserted into the DESCRIPTION field."
3492 :group 'org-export-icalendar
3493 :type '(choice
3494 (const :tag "Nothing" nil)
3495 (const :tag "Everything" t)
3496 (integer :tag "Max characters")))
3498 (defcustom org-icalendar-combined-name "OrgMode"
3499 "Calendar name for the combined iCalendar representing all agenda files."
3500 :group 'org-export-icalendar
3501 :type 'string)
3503 (defgroup org-font-lock nil
3504 "Font-lock settings for highlighting in Org-mode."
3505 :tag "Org Font Lock"
3506 :group 'org)
3508 (defcustom org-level-color-stars-only nil
3509 "Non-nil means fontify only the stars in each headline.
3510 When nil, the entire headline is fontified.
3511 Changing it requires restart of `font-lock-mode' to become effective
3512 also in regions already fontified."
3513 :group 'org-font-lock
3514 :type 'boolean)
3516 (defcustom org-hide-leading-stars nil
3517 "Non-nil means, hide the first N-1 stars in a headline.
3518 This works by using the face `org-hide' for these stars. This
3519 face is white for a light background, and black for a dark
3520 background. You may have to customize the face `org-hide' to
3521 make this work.
3522 Changing it requires restart of `font-lock-mode' to become effective
3523 also in regions already fontified.
3524 You may also set this on a per-file basis by adding one of the following
3525 lines to the buffer:
3527 #+STARTUP: hidestars
3528 #+STARTUP: showstars"
3529 :group 'org-font-lock
3530 :type 'boolean)
3532 (defcustom org-fontify-done-headline nil
3533 "Non-nil means, change the face of a headline if it is marked DONE.
3534 Normally, only the TODO/DONE keyword indicates the state of a headline.
3535 When this is non-nil, the headline after the keyword is set to the
3536 `org-headline-done' as an additional indication."
3537 :group 'org-font-lock
3538 :type 'boolean)
3540 (defcustom org-fontify-emphasized-text t
3541 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3542 Changing this variable requires a restart of Emacs to take effect."
3543 :group 'org-font-lock
3544 :type 'boolean)
3546 (defcustom org-highlight-latex-fragments-and-specials nil
3547 "Non-nil means, fontify what is treated specially by the exporters."
3548 :group 'org-font-lock
3549 :type 'boolean)
3551 (defcustom org-hide-emphasis-markers nil
3552 "Non-nil mean font-lock should hide the emphasis marker characters."
3553 :group 'org-font-lock
3554 :type 'boolean)
3556 (defvar org-emph-re nil
3557 "Regular expression for matching emphasis.")
3558 (defvar org-verbatim-re nil
3559 "Regular expression for matching verbatim text.")
3560 (defvar org-emphasis-regexp-components) ; defined just below
3561 (defvar org-emphasis-alist) ; defined just below
3562 (defun org-set-emph-re (var val)
3563 "Set variable and compute the emphasis regular expression."
3564 (set var val)
3565 (when (and (boundp 'org-emphasis-alist)
3566 (boundp 'org-emphasis-regexp-components)
3567 org-emphasis-alist org-emphasis-regexp-components)
3568 (let* ((e org-emphasis-regexp-components)
3569 (pre (car e))
3570 (post (nth 1 e))
3571 (border (nth 2 e))
3572 (body (nth 3 e))
3573 (nl (nth 4 e))
3574 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3575 (body1 (concat body "*?"))
3576 (markers (mapconcat 'car org-emphasis-alist ""))
3577 (vmarkers (mapconcat
3578 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3579 org-emphasis-alist "")))
3580 ;; make sure special characters appear at the right position in the class
3581 (if (string-match "\\^" markers)
3582 (setq markers (concat (replace-match "" t t markers) "^")))
3583 (if (string-match "-" markers)
3584 (setq markers (concat (replace-match "" t t markers) "-")))
3585 (if (string-match "\\^" vmarkers)
3586 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3587 (if (string-match "-" vmarkers)
3588 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3589 (if (> nl 0)
3590 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3591 (int-to-string nl) "\\}")))
3592 ;; Make the regexp
3593 (setq org-emph-re
3594 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3595 "\\("
3596 "\\([" markers "]\\)"
3597 "\\("
3598 "[^" border "]\\|"
3599 "[^" border (if (and nil stacked) markers) "]"
3600 body1
3601 "[^" border (if (and nil stacked) markers) "]"
3602 "\\)"
3603 "\\3\\)"
3604 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3605 (setq org-verbatim-re
3606 (concat "\\([" pre "]\\|^\\)"
3607 "\\("
3608 "\\([" vmarkers "]\\)"
3609 "\\("
3610 "[^" border "]\\|"
3611 "[^" border "]"
3612 body1
3613 "[^" border "]"
3614 "\\)"
3615 "\\3\\)"
3616 "\\([" post "]\\|$\\)")))))
3618 (defcustom org-emphasis-regexp-components
3619 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3620 "Components used to build the regular expression for emphasis.
3621 This is a list with 6 entries. Terminology: In an emphasis string
3622 like \" *strong word* \", we call the initial space PREMATCH, the final
3623 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3624 and \"trong wor\" is the body. The different components in this variable
3625 specify what is allowed/forbidden in each part:
3627 pre Chars allowed as prematch. Beginning of line will be allowed too.
3628 post Chars allowed as postmatch. End of line will be allowed too.
3629 border The chars *forbidden* as border characters.
3630 body-regexp A regexp like \".\" to match a body character. Don't use
3631 non-shy groups here, and don't allow newline here.
3632 newline The maximum number of newlines allowed in an emphasis exp.
3634 Use customize to modify this, or restart Emacs after changing it."
3635 :group 'org-font-lock
3636 :set 'org-set-emph-re
3637 :type '(list
3638 (sexp :tag "Allowed chars in pre ")
3639 (sexp :tag "Allowed chars in post ")
3640 (sexp :tag "Forbidden chars in border ")
3641 (sexp :tag "Regexp for body ")
3642 (integer :tag "number of newlines allowed")
3643 (option (boolean :tag "Stacking (DISABLED) "))))
3645 (defcustom org-emphasis-alist
3646 '(("*" bold "<b>" "</b>")
3647 ("/" italic "<i>" "</i>")
3648 ("_" underline "<u>" "</u>")
3649 ("=" org-code "<code>" "</code>" verbatim)
3650 ("~" org-verbatim "" "" verbatim)
3651 ("+" (:strike-through t) "<del>" "</del>")
3653 "Special syntax for emphasized text.
3654 Text starting and ending with a special character will be emphasized, for
3655 example *bold*, _underlined_ and /italic/. This variable sets the marker
3656 characters, the face to be used by font-lock for highlighting in Org-mode
3657 Emacs buffers, and the HTML tags to be used for this.
3658 Use customize to modify this, or restart Emacs after changing it."
3659 :group 'org-font-lock
3660 :set 'org-set-emph-re
3661 :type '(repeat
3662 (list
3663 (string :tag "Marker character")
3664 (choice
3665 (face :tag "Font-lock-face")
3666 (plist :tag "Face property list"))
3667 (string :tag "HTML start tag")
3668 (string :tag "HTML end tag")
3669 (option (const verbatim)))))
3671 ;;; The faces
3673 (defgroup org-faces nil
3674 "Faces in Org-mode."
3675 :tag "Org Faces"
3676 :group 'org-font-lock)
3678 (defun org-compatible-face (inherits specs)
3679 "Make a compatible face specification.
3680 If INHERITS is an existing face and if the Emacs version supports it,
3681 just inherit the face. If not, use SPECS to define the face.
3682 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3683 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3684 to the top of the list. The `min-colors' attribute will be removed from
3685 any other entries, and any resulting duplicates will be removed entirely."
3686 (cond
3687 ((and inherits (facep inherits)
3688 (not (featurep 'xemacs)) (> emacs-major-version 22))
3689 ;; In Emacs 23, we use inheritance where possible.
3690 ;; We only do this in Emacs 23, because only there the outline
3691 ;; faces have been changed to the original org-mode-level-faces.
3692 (list (list t :inherit inherits)))
3693 ((or (featurep 'xemacs) (< emacs-major-version 22))
3694 ;; These do not understand the `min-colors' attribute.
3695 (let (r e a)
3696 (while (setq e (pop specs))
3697 (cond
3698 ((memq (car e) '(t default)) (push e r))
3699 ((setq a (member '(min-colors 8) (car e)))
3700 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3701 (cdr e)))))
3702 ((setq a (assq 'min-colors (car e)))
3703 (setq e (cons (delq a (car e)) (cdr e)))
3704 (or (assoc (car e) r) (push e r)))
3705 (t (or (assoc (car e) r) (push e r)))))
3706 (nreverse r)))
3707 (t specs)))
3708 (put 'org-compatible-face 'lisp-indent-function 1)
3710 (defface org-hide
3711 '((((background light)) (:foreground "white"))
3712 (((background dark)) (:foreground "black")))
3713 "Face used to hide leading stars in headlines.
3714 The forground color of this face should be equal to the background
3715 color of the frame."
3716 :group 'org-faces)
3718 (defface org-level-1 ;; font-lock-function-name-face
3719 (org-compatible-face 'outline-1
3720 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3721 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3722 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3723 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3724 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3725 (t (:bold t))))
3726 "Face used for level 1 headlines."
3727 :group 'org-faces)
3729 (defface org-level-2 ;; font-lock-variable-name-face
3730 (org-compatible-face 'outline-2
3731 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3732 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3733 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3734 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3735 (t (:bold t))))
3736 "Face used for level 2 headlines."
3737 :group 'org-faces)
3739 (defface org-level-3 ;; font-lock-keyword-face
3740 (org-compatible-face 'outline-3
3741 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3742 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3743 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3744 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3745 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3746 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3747 (t (:bold t))))
3748 "Face used for level 3 headlines."
3749 :group 'org-faces)
3751 (defface org-level-4 ;; font-lock-comment-face
3752 (org-compatible-face 'outline-4
3753 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3754 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3755 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3756 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3757 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3758 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3759 (t (:bold t))))
3760 "Face used for level 4 headlines."
3761 :group 'org-faces)
3763 (defface org-level-5 ;; font-lock-type-face
3764 (org-compatible-face 'outline-5
3765 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3766 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3767 (((class color) (min-colors 8)) (:foreground "green"))))
3768 "Face used for level 5 headlines."
3769 :group 'org-faces)
3771 (defface org-level-6 ;; font-lock-constant-face
3772 (org-compatible-face 'outline-6
3773 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3774 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3775 (((class color) (min-colors 8)) (:foreground "magenta"))))
3776 "Face used for level 6 headlines."
3777 :group 'org-faces)
3779 (defface org-level-7 ;; font-lock-builtin-face
3780 (org-compatible-face 'outline-7
3781 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3782 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3783 (((class color) (min-colors 8)) (:foreground "blue"))))
3784 "Face used for level 7 headlines."
3785 :group 'org-faces)
3787 (defface org-level-8 ;; font-lock-string-face
3788 (org-compatible-face 'outline-8
3789 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3790 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3791 (((class color) (min-colors 8)) (:foreground "green"))))
3792 "Face used for level 8 headlines."
3793 :group 'org-faces)
3795 (defface org-special-keyword ;; font-lock-string-face
3796 (org-compatible-face nil
3797 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3798 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3799 (t (:italic t))))
3800 "Face used for special keywords."
3801 :group 'org-faces)
3803 (defface org-drawer ;; font-lock-function-name-face
3804 (org-compatible-face nil
3805 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3806 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3807 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3808 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3809 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3810 (t (:bold t))))
3811 "Face used for drawers."
3812 :group 'org-faces)
3814 (defface org-property-value nil
3815 "Face used for the value of a property."
3816 :group 'org-faces)
3818 (defface org-column
3819 (org-compatible-face nil
3820 '((((class color) (min-colors 16) (background light))
3821 (:background "grey90"))
3822 (((class color) (min-colors 16) (background dark))
3823 (:background "grey30"))
3824 (((class color) (min-colors 8))
3825 (:background "cyan" :foreground "black"))
3826 (t (:inverse-video t))))
3827 "Face for column display of entry properties."
3828 :group 'org-faces)
3830 (when (fboundp 'set-face-attribute)
3831 ;; Make sure that a fixed-width face is used when we have a column table.
3832 (set-face-attribute 'org-column nil
3833 :height (face-attribute 'default :height)
3834 :family (face-attribute 'default :family)))
3836 (defface org-warning
3837 (org-compatible-face 'font-lock-warning-face
3838 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3839 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3840 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3841 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3842 (t (:bold t))))
3843 "Face for deadlines and TODO keywords."
3844 :group 'org-faces)
3846 (defface org-archived ; similar to shadow
3847 (org-compatible-face 'shadow
3848 '((((class color grayscale) (min-colors 88) (background light))
3849 (:foreground "grey50"))
3850 (((class color grayscale) (min-colors 88) (background dark))
3851 (:foreground "grey70"))
3852 (((class color) (min-colors 8) (background light))
3853 (:foreground "green"))
3854 (((class color) (min-colors 8) (background dark))
3855 (:foreground "yellow"))))
3856 "Face for headline with the ARCHIVE tag."
3857 :group 'org-faces)
3859 (defface org-link
3860 '((((class color) (background light)) (:foreground "Purple" :underline t))
3861 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3862 (t (:underline t)))
3863 "Face for links."
3864 :group 'org-faces)
3866 (defface org-ellipsis
3867 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3868 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3869 (t (:strike-through t)))
3870 "Face for the ellipsis in folded text."
3871 :group 'org-faces)
3873 (defface org-target
3874 '((((class color) (background light)) (:underline t))
3875 (((class color) (background dark)) (:underline t))
3876 (t (:underline t)))
3877 "Face for links."
3878 :group 'org-faces)
3880 (defface org-date
3881 '((((class color) (background light)) (:foreground "Purple" :underline t))
3882 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3883 (t (:underline t)))
3884 "Face for links."
3885 :group 'org-faces)
3887 (defface org-sexp-date
3888 '((((class color) (background light)) (:foreground "Purple"))
3889 (((class color) (background dark)) (:foreground "Cyan"))
3890 (t (:underline t)))
3891 "Face for links."
3892 :group 'org-faces)
3894 (defface org-tag
3895 '((t (:bold t)))
3896 "Face for tags."
3897 :group 'org-faces)
3899 (defface org-todo ; font-lock-warning-face
3900 (org-compatible-face nil
3901 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3902 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3903 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3904 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3905 (t (:inverse-video t :bold t))))
3906 "Face for TODO keywords."
3907 :group 'org-faces)
3909 (defface org-done ;; font-lock-type-face
3910 (org-compatible-face nil
3911 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3912 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3913 (((class color) (min-colors 8)) (:foreground "green"))
3914 (t (:bold t))))
3915 "Face used for todo keywords that indicate DONE items."
3916 :group 'org-faces)
3918 (defface org-headline-done ;; font-lock-string-face
3919 (org-compatible-face nil
3920 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3921 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3922 (((class color) (min-colors 8) (background light)) (:bold nil))))
3923 "Face used to indicate that a headline is DONE.
3924 This face is only used if `org-fontify-done-headline' is set. If applies
3925 to the part of the headline after the DONE keyword."
3926 :group 'org-faces)
3928 (defcustom org-todo-keyword-faces nil
3929 "Faces for specific TODO keywords.
3930 This is a list of cons cells, with TODO keywords in the car
3931 and faces in the cdr. The face can be a symbol, or a property
3932 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3933 :group 'org-faces
3934 :group 'org-todo
3935 :type '(repeat
3936 (cons
3937 (string :tag "keyword")
3938 (sexp :tag "face"))))
3940 (defface org-table ;; font-lock-function-name-face
3941 (org-compatible-face nil
3942 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3943 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3944 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3945 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3946 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3947 (((class color) (min-colors 8) (background dark)))))
3948 "Face used for tables."
3949 :group 'org-faces)
3951 (defface org-formula
3952 (org-compatible-face nil
3953 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3954 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3955 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3956 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3957 (t (:bold t :italic t))))
3958 "Face for formulas."
3959 :group 'org-faces)
3961 (defface org-code
3962 (org-compatible-face nil
3963 '((((class color grayscale) (min-colors 88) (background light))
3964 (:foreground "grey50"))
3965 (((class color grayscale) (min-colors 88) (background dark))
3966 (:foreground "grey70"))
3967 (((class color) (min-colors 8) (background light))
3968 (:foreground "green"))
3969 (((class color) (min-colors 8) (background dark))
3970 (:foreground "yellow"))))
3971 "Face for fixed-with text like code snippets."
3972 :group 'org-faces
3973 :version "22.1")
3975 (defface org-verbatim
3976 (org-compatible-face nil
3977 '((((class color grayscale) (min-colors 88) (background light))
3978 (:foreground "grey50" :underline t))
3979 (((class color grayscale) (min-colors 88) (background dark))
3980 (:foreground "grey70" :underline t))
3981 (((class color) (min-colors 8) (background light))
3982 (:foreground "green" :underline t))
3983 (((class color) (min-colors 8) (background dark))
3984 (:foreground "yellow" :underline t))))
3985 "Face for fixed-with text like code snippets."
3986 :group 'org-faces
3987 :version "22.1")
3989 (defface org-agenda-structure ;; font-lock-function-name-face
3990 (org-compatible-face nil
3991 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3992 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3993 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3994 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3995 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3996 (t (:bold t))))
3997 "Face used in agenda for captions and dates."
3998 :group 'org-faces)
4000 (defface org-scheduled-today
4001 (org-compatible-face nil
4002 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4003 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4004 (((class color) (min-colors 8)) (:foreground "green"))
4005 (t (:bold t :italic t))))
4006 "Face for items scheduled for a certain day."
4007 :group 'org-faces)
4009 (defface org-scheduled-previously
4010 (org-compatible-face nil
4011 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4012 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4013 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4014 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4015 (t (:bold t))))
4016 "Face for items scheduled previously, and not yet done."
4017 :group 'org-faces)
4019 (defface org-upcoming-deadline
4020 (org-compatible-face nil
4021 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4022 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4023 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4024 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4025 (t (:bold t))))
4026 "Face for items scheduled previously, and not yet done."
4027 :group 'org-faces)
4029 (defcustom org-agenda-deadline-faces
4030 '((1.0 . org-warning)
4031 (0.5 . org-upcoming-deadline)
4032 (0.0 . default))
4033 "Faces for showing deadlines in the agenda.
4034 This is a list of cons cells. The cdr of each cell is a face to be used,
4035 and it can also just be like '(:foreground \"yellow\").
4036 Each car is a fraction of the head-warning time that must have passed for
4037 this the face in the cdr to be used for display. The numbers must be
4038 given in descending order. The head-warning time is normally taken
4039 from `org-deadline-warning-days', but can also be specified in the deadline
4040 timestamp itself, like this:
4042 DEADLINE: <2007-08-13 Mon -8d>
4044 You may use d for days, w for weeks, m for months and y for years. Months
4045 and years will only be treated in an approximate fashion (30.4 days for a
4046 month and 365.24 days for a year)."
4047 :group 'org-faces
4048 :group 'org-agenda-daily/weekly
4049 :type '(repeat
4050 (cons
4051 (number :tag "Fraction of head-warning time passed")
4052 (sexp :tag "Face"))))
4054 ;; FIXME: this is not a good face yet.
4055 (defface org-agenda-restriction-lock
4056 (org-compatible-face nil
4057 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4058 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4059 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4060 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4061 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4062 (t (:inverse-video t))))
4063 "Face for showing the agenda restriction lock."
4064 :group 'org-faces)
4066 (defface org-time-grid ;; font-lock-variable-name-face
4067 (org-compatible-face nil
4068 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4069 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4070 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4071 "Face used for time grids."
4072 :group 'org-faces)
4074 (defconst org-level-faces
4075 '(org-level-1 org-level-2 org-level-3 org-level-4
4076 org-level-5 org-level-6 org-level-7 org-level-8
4079 (defcustom org-n-level-faces (length org-level-faces)
4080 "The number different faces to be used for headlines.
4081 Org-mode defines 8 different headline faces, so this can be at most 8.
4082 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4083 :type 'number
4084 :group 'org-faces)
4086 ;;; Functions and variables from ther packages
4087 ;; Declared here to avoid compiler warnings
4089 (eval-and-compile
4090 (unless (fboundp 'declare-function)
4091 (defmacro declare-function (fn file &optional arglist fileonly))))
4093 ;; XEmacs only
4094 (defvar outline-mode-menu-heading)
4095 (defvar outline-mode-menu-show)
4096 (defvar outline-mode-menu-hide)
4097 (defvar zmacs-regions) ; XEmacs regions
4099 ;; Emacs only
4100 (defvar mark-active)
4102 ;; Various packages
4103 ;; FIXME: get the argument lists for the UNKNOWN stuff
4104 (declare-function add-to-diary-list "diary-lib"
4105 (date string specifier &optional marker globcolor literal))
4106 (declare-function table--at-cell-p "table" (position &optional object at-column))
4107 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4108 (declare-function bbdb "ext:bbdb-com" (string elidep))
4109 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4110 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4111 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4112 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4113 (declare-function bbdb-record-name "ext:bbdb" (record))
4114 (declare-function bibtex-beginning-of-entry "bibtex" ())
4115 (declare-function bibtex-generate-autokey "bibtex" ())
4116 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4117 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4118 (defvar calc-embedded-close-formula)
4119 (defvar calc-embedded-open-formula)
4120 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4121 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4122 (declare-function calendar-check-holidays "holidays" (date))
4123 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4124 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4125 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4126 (declare-function calendar-forward-day "cal-move" (arg))
4127 (declare-function calendar-french-date-string "cal-french" (&optional date))
4128 (declare-function calendar-goto-date "cal-move" (date))
4129 (declare-function calendar-goto-today "cal-move" ())
4130 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4131 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4132 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4133 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4134 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4135 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4136 (defvar calendar-mode-map)
4137 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4138 (declare-function cdlatex-tab "ext:cdlatex" ())
4139 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4140 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4141 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4142 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4143 ;; backward compatibility to old version of elmo
4144 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4145 (defvar font-lock-unfontify-region-function)
4146 (declare-function gnus-article-show-summary "gnus-art" ())
4147 (declare-function gnus-summary-last-subject "gnus-sum" ())
4148 (defvar gnus-other-frame-object)
4149 (defvar gnus-group-name)
4150 (defvar gnus-article-current)
4151 (defvar Info-current-file)
4152 (defvar Info-current-node)
4153 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4154 (declare-function mh-find-path "mh-utils" ())
4155 (declare-function mh-get-header-field "mh-utils" (field))
4156 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4157 (declare-function mh-header-display "mh-show" ())
4158 (declare-function mh-index-previous-folder "mh-search" ())
4159 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4160 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4161 (declare-function mh-search-choose "mh-search" (&optional searcher))
4162 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4163 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4164 (declare-function mh-show-header-display "mh-show" t t)
4165 (declare-function mh-show-msg "mh-show" (msg))
4166 (declare-function mh-show-show "mh-show" t t)
4167 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4168 (defvar mh-progs)
4169 (defvar mh-current-folder)
4170 (defvar mh-show-folder-buffer)
4171 (defvar mh-index-folder)
4172 (defvar mh-searcher)
4173 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4174 (declare-function parse-time-string "parse-time" (string))
4175 (declare-function remember "remember" (&optional initial))
4176 (declare-function remember-buffer-desc "remember" ())
4177 (defvar remember-save-after-remembering)
4178 (defvar remember-data-file)
4179 (defvar remember-register)
4180 (defvar remember-buffer)
4181 (defvar remember-handler-functions)
4182 (defvar remember-annotation-functions)
4183 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4184 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4185 (declare-function rmail-what-message "rmail" ())
4186 (defvar texmathp-why)
4187 (declare-function vm-beginning-of-message "ext:vm-page" ())
4188 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4189 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4190 (declare-function vm-isearch-narrow "ext:vm-search" ())
4191 (declare-function vm-isearch-update "ext:vm-search" ())
4192 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4193 (declare-function vm-su-message-id "ext:vm-summary" (m))
4194 (declare-function vm-su-subject "ext:vm-summary" (m))
4195 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4196 (defvar vm-message-pointer)
4197 (defvar vm-folder-directory)
4198 (defvar w3m-current-url)
4199 (defvar w3m-current-title)
4200 ;; backward compatibility to old version of wl
4201 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4202 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4203 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4204 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4205 (declare-function wl-summary-line-from "ext:wl-summary" ())
4206 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4207 (declare-function wl-summary-message-number "ext:wl-summary" ())
4208 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4209 (defvar wl-summary-buffer-elmo-folder)
4210 (defvar wl-summary-buffer-folder-name)
4211 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4213 (defvar org-latex-regexps)
4214 (defvar constants-unit-system)
4216 ;;; Variables for pre-computed regular expressions, all buffer local
4218 (defvar org-drawer-regexp nil
4219 "Matches first line of a hidden block.")
4220 (make-variable-buffer-local 'org-drawer-regexp)
4221 (defvar org-todo-regexp nil
4222 "Matches any of the TODO state keywords.")
4223 (make-variable-buffer-local 'org-todo-regexp)
4224 (defvar org-not-done-regexp nil
4225 "Matches any of the TODO state keywords except the last one.")
4226 (make-variable-buffer-local 'org-not-done-regexp)
4227 (defvar org-todo-line-regexp nil
4228 "Matches a headline and puts TODO state into group 2 if present.")
4229 (make-variable-buffer-local 'org-todo-line-regexp)
4230 (defvar org-complex-heading-regexp nil
4231 "Matches a headline and puts everything into groups:
4232 group 1: the stars
4233 group 2: The todo keyword, maybe
4234 group 3: Priority cookie
4235 group 4: True headline
4236 group 5: Tags")
4237 (make-variable-buffer-local 'org-complex-heading-regexp)
4238 (defvar org-todo-line-tags-regexp nil
4239 "Matches a headline and puts TODO state into group 2 if present.
4240 Also put tags into group 4 if tags are present.")
4241 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4242 (defvar org-nl-done-regexp nil
4243 "Matches newline followed by a headline with the DONE keyword.")
4244 (make-variable-buffer-local 'org-nl-done-regexp)
4245 (defvar org-looking-at-done-regexp nil
4246 "Matches the DONE keyword a point.")
4247 (make-variable-buffer-local 'org-looking-at-done-regexp)
4248 (defvar org-ds-keyword-length 12
4249 "Maximum length of the Deadline and SCHEDULED keywords.")
4250 (make-variable-buffer-local 'org-ds-keyword-length)
4251 (defvar org-deadline-regexp nil
4252 "Matches the DEADLINE keyword.")
4253 (make-variable-buffer-local 'org-deadline-regexp)
4254 (defvar org-deadline-time-regexp nil
4255 "Matches the DEADLINE keyword together with a time stamp.")
4256 (make-variable-buffer-local 'org-deadline-time-regexp)
4257 (defvar org-deadline-line-regexp nil
4258 "Matches the DEADLINE keyword and the rest of the line.")
4259 (make-variable-buffer-local 'org-deadline-line-regexp)
4260 (defvar org-scheduled-regexp nil
4261 "Matches the SCHEDULED keyword.")
4262 (make-variable-buffer-local 'org-scheduled-regexp)
4263 (defvar org-scheduled-time-regexp nil
4264 "Matches the SCHEDULED keyword together with a time stamp.")
4265 (make-variable-buffer-local 'org-scheduled-time-regexp)
4266 (defvar org-closed-time-regexp nil
4267 "Matches the CLOSED keyword together with a time stamp.")
4268 (make-variable-buffer-local 'org-closed-time-regexp)
4270 (defvar org-keyword-time-regexp nil
4271 "Matches any of the 4 keywords, together with the time stamp.")
4272 (make-variable-buffer-local 'org-keyword-time-regexp)
4273 (defvar org-keyword-time-not-clock-regexp nil
4274 "Matches any of the 3 keywords, together with the time stamp.")
4275 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4276 (defvar org-maybe-keyword-time-regexp nil
4277 "Matches a timestamp, possibly preceeded by a keyword.")
4278 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4279 (defvar org-planning-or-clock-line-re nil
4280 "Matches a line with planning or clock info.")
4281 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4283 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4284 rear-nonsticky t mouse-map t fontified t)
4285 "Properties to remove when a string without properties is wanted.")
4287 (defsubst org-match-string-no-properties (num &optional string)
4288 (if (featurep 'xemacs)
4289 (let ((s (match-string num string)))
4290 (remove-text-properties 0 (length s) org-rm-props s)
4292 (match-string-no-properties num string)))
4294 (defsubst org-no-properties (s)
4295 (if (fboundp 'set-text-properties)
4296 (set-text-properties 0 (length s) nil s)
4297 (remove-text-properties 0 (length s) org-rm-props s))
4300 (defsubst org-get-alist-option (option key)
4301 (cond ((eq key t) t)
4302 ((eq option t) t)
4303 ((assoc key option) (cdr (assoc key option)))
4304 (t (cdr (assq 'default option)))))
4306 (defsubst org-inhibit-invisibility ()
4307 "Modified `buffer-invisibility-spec' for Emacs 21.
4308 Some ops with invisible text do not work correctly on Emacs 21. For these
4309 we turn off invisibility temporarily. Use this in a `let' form."
4310 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4312 (defsubst org-set-local (var value)
4313 "Make VAR local in current buffer and set it to VALUE."
4314 (set (make-variable-buffer-local var) value))
4316 (defsubst org-mode-p ()
4317 "Check if the current buffer is in Org-mode."
4318 (eq major-mode 'org-mode))
4320 (defsubst org-last (list)
4321 "Return the last element of LIST."
4322 (car (last list)))
4324 (defun org-let (list &rest body)
4325 (eval (cons 'let (cons list body))))
4326 (put 'org-let 'lisp-indent-function 1)
4328 (defun org-let2 (list1 list2 &rest body)
4329 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4330 (put 'org-let2 'lisp-indent-function 2)
4331 (defconst org-startup-options
4332 '(("fold" org-startup-folded t)
4333 ("overview" org-startup-folded t)
4334 ("nofold" org-startup-folded nil)
4335 ("showall" org-startup-folded nil)
4336 ("content" org-startup-folded content)
4337 ("hidestars" org-hide-leading-stars t)
4338 ("showstars" org-hide-leading-stars nil)
4339 ("odd" org-odd-levels-only t)
4340 ("oddeven" org-odd-levels-only nil)
4341 ("align" org-startup-align-all-tables t)
4342 ("noalign" org-startup-align-all-tables nil)
4343 ("customtime" org-display-custom-times t)
4344 ("logging" org-log-done t)
4345 ("logdone" org-log-done t)
4346 ("nologging" org-log-done nil)
4347 ("lognotedone" org-log-done done push)
4348 ("lognotestate" org-log-done state push)
4349 ("lognoteclock-out" org-log-done clock-out push)
4350 ("logrepeat" org-log-repeat t)
4351 ("nologrepeat" org-log-repeat nil)
4352 ("constcgs" constants-unit-system cgs)
4353 ("constSI" constants-unit-system SI))
4354 "Variable associated with STARTUP options for org-mode.
4355 Each element is a list of three items: The startup options as written
4356 in the #+STARTUP line, the corresponding variable, and the value to
4357 set this variable to if the option is found. An optional forth element PUSH
4358 means to push this value onto the list in the variable.")
4360 (defun org-set-regexps-and-options ()
4361 "Precompute regular expressions for current buffer."
4362 (when (org-mode-p)
4363 (org-set-local 'org-todo-kwd-alist nil)
4364 (org-set-local 'org-todo-key-alist nil)
4365 (org-set-local 'org-todo-key-trigger nil)
4366 (org-set-local 'org-todo-keywords-1 nil)
4367 (org-set-local 'org-done-keywords nil)
4368 (org-set-local 'org-todo-heads nil)
4369 (org-set-local 'org-todo-sets nil)
4370 (org-set-local 'org-todo-log-states nil)
4371 (let ((re (org-make-options-regexp
4372 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4373 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4374 "CONSTANTS" "PROPERTY" "DRAWERS")))
4375 (splitre "[ \t]+")
4376 kwds kws0 kwsa key value cat arch tags const links hw dws
4377 tail sep kws1 prio props drawers
4378 ex log)
4379 (save-excursion
4380 (save-restriction
4381 (widen)
4382 (goto-char (point-min))
4383 (while (re-search-forward re nil t)
4384 (setq key (match-string 1) value (org-match-string-no-properties 2))
4385 (cond
4386 ((equal key "CATEGORY")
4387 (if (string-match "[ \t]+$" value)
4388 (setq value (replace-match "" t t value)))
4389 (setq cat value))
4390 ((member key '("SEQ_TODO" "TODO"))
4391 (push (cons 'sequence (org-split-string value splitre)) kwds))
4392 ((equal key "TYP_TODO")
4393 (push (cons 'type (org-split-string value splitre)) kwds))
4394 ((equal key "TAGS")
4395 (setq tags (append tags (org-split-string value splitre))))
4396 ((equal key "COLUMNS")
4397 (org-set-local 'org-columns-default-format value))
4398 ((equal key "LINK")
4399 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4400 (push (cons (match-string 1 value)
4401 (org-trim (match-string 2 value)))
4402 links)))
4403 ((equal key "PRIORITIES")
4404 (setq prio (org-split-string value " +")))
4405 ((equal key "PROPERTY")
4406 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4407 (push (cons (match-string 1 value) (match-string 2 value))
4408 props)))
4409 ((equal key "DRAWERS")
4410 (setq drawers (org-split-string value splitre)))
4411 ((equal key "CONSTANTS")
4412 (setq const (append const (org-split-string value splitre))))
4413 ((equal key "STARTUP")
4414 (let ((opts (org-split-string value splitre))
4415 l var val)
4416 (while (setq l (pop opts))
4417 (when (setq l (assoc l org-startup-options))
4418 (setq var (nth 1 l) val (nth 2 l))
4419 (if (not (nth 3 l))
4420 (set (make-local-variable var) val)
4421 (if (not (listp (symbol-value var)))
4422 (set (make-local-variable var) nil))
4423 (set (make-local-variable var) (symbol-value var))
4424 (add-to-list var val))))))
4425 ((equal key "ARCHIVE")
4426 (string-match " *$" value)
4427 (setq arch (replace-match "" t t value))
4428 (remove-text-properties 0 (length arch)
4429 '(face t fontified t) arch)))
4431 (when cat
4432 (org-set-local 'org-category (intern cat))
4433 (push (cons "CATEGORY" cat) props))
4434 (when prio
4435 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4436 (setq prio (mapcar 'string-to-char prio))
4437 (org-set-local 'org-highest-priority (nth 0 prio))
4438 (org-set-local 'org-lowest-priority (nth 1 prio))
4439 (org-set-local 'org-default-priority (nth 2 prio)))
4440 (and props (org-set-local 'org-local-properties (nreverse props)))
4441 (and drawers (org-set-local 'org-drawers drawers))
4442 (and arch (org-set-local 'org-archive-location arch))
4443 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4444 ;; Process the TODO keywords
4445 (unless kwds
4446 ;; Use the global values as if they had been given locally.
4447 (setq kwds (default-value 'org-todo-keywords))
4448 (if (stringp (car kwds))
4449 (setq kwds (list (cons org-todo-interpretation
4450 (default-value 'org-todo-keywords)))))
4451 (setq kwds (reverse kwds)))
4452 (setq kwds (nreverse kwds))
4453 (let (inter kws kw)
4454 (while (setq kws (pop kwds))
4455 (setq inter (pop kws) sep (member "|" kws)
4456 kws0 (delete "|" (copy-sequence kws))
4457 kwsa nil
4458 kws1 (mapcar
4459 (lambda (x)
4460 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4461 (progn
4462 (setq kw (match-string 1 x)
4463 ex (and (match-end 2) (match-string 2 x))
4464 log (and ex (string-match "@" ex))
4465 key (and ex (substring ex 0 1)))
4466 (if (equal key "@") (setq key nil))
4467 (push (cons kw (and key (string-to-char key))) kwsa)
4468 (and log (push kw org-todo-log-states))
4470 (error "Invalid TODO keyword %s" x)))
4471 kws0)
4472 kwsa (if kwsa (append '((:startgroup))
4473 (nreverse kwsa)
4474 '((:endgroup))))
4475 hw (car kws1)
4476 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4477 tail (list inter hw (car dws) (org-last dws)))
4478 (add-to-list 'org-todo-heads hw 'append)
4479 (push kws1 org-todo-sets)
4480 (setq org-done-keywords (append org-done-keywords dws nil))
4481 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4482 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4483 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4484 (setq org-todo-sets (nreverse org-todo-sets)
4485 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4486 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4487 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4488 ;; Process the constants
4489 (when const
4490 (let (e cst)
4491 (while (setq e (pop const))
4492 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4493 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4494 (setq org-table-formula-constants-local cst)))
4496 ;; Process the tags.
4497 (when tags
4498 (let (e tgs)
4499 (while (setq e (pop tags))
4500 (cond
4501 ((equal e "{") (push '(:startgroup) tgs))
4502 ((equal e "}") (push '(:endgroup) tgs))
4503 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4504 (push (cons (match-string 1 e)
4505 (string-to-char (match-string 2 e)))
4506 tgs))
4507 (t (push (list e) tgs))))
4508 (org-set-local 'org-tag-alist nil)
4509 (while (setq e (pop tgs))
4510 (or (and (stringp (car e))
4511 (assoc (car e) org-tag-alist))
4512 (push e org-tag-alist))))))
4514 ;; Compute the regular expressions and other local variables
4515 (if (not org-done-keywords)
4516 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4517 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4518 (length org-scheduled-string)))
4519 org-drawer-regexp
4520 (concat "^[ \t]*:\\("
4521 (mapconcat 'regexp-quote org-drawers "\\|")
4522 "\\):[ \t]*$")
4523 org-not-done-keywords
4524 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4525 org-todo-regexp
4526 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4527 "\\|") "\\)\\>")
4528 org-not-done-regexp
4529 (concat "\\<\\("
4530 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4531 "\\)\\>")
4532 org-todo-line-regexp
4533 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4534 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4535 "\\)\\>\\)?[ \t]*\\(.*\\)")
4536 org-complex-heading-regexp
4537 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4538 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4539 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4540 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4541 org-nl-done-regexp
4542 (concat "\n\\*+[ \t]+"
4543 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4544 "\\)" "\\>")
4545 org-todo-line-tags-regexp
4546 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4547 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4548 (org-re
4549 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4550 org-looking-at-done-regexp
4551 (concat "^" "\\(?:"
4552 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4553 "\\>")
4554 org-deadline-regexp (concat "\\<" org-deadline-string)
4555 org-deadline-time-regexp
4556 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4557 org-deadline-line-regexp
4558 (concat "\\<\\(" org-deadline-string "\\).*")
4559 org-scheduled-regexp
4560 (concat "\\<" org-scheduled-string)
4561 org-scheduled-time-regexp
4562 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4563 org-closed-time-regexp
4564 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4565 org-keyword-time-regexp
4566 (concat "\\<\\(" org-scheduled-string
4567 "\\|" org-deadline-string
4568 "\\|" org-closed-string
4569 "\\|" org-clock-string "\\)"
4570 " *[[<]\\([^]>]+\\)[]>]")
4571 org-keyword-time-not-clock-regexp
4572 (concat "\\<\\(" org-scheduled-string
4573 "\\|" org-deadline-string
4574 "\\|" org-closed-string
4575 "\\)"
4576 " *[[<]\\([^]>]+\\)[]>]")
4577 org-maybe-keyword-time-regexp
4578 (concat "\\(\\<\\(" org-scheduled-string
4579 "\\|" org-deadline-string
4580 "\\|" org-closed-string
4581 "\\|" org-clock-string "\\)\\)?"
4582 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4583 org-planning-or-clock-line-re
4584 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4585 "\\|" org-deadline-string
4586 "\\|" org-closed-string "\\|" org-clock-string
4587 "\\)\\>\\)")
4589 (org-compute-latex-and-specials-regexp)
4590 (org-set-font-lock-defaults)))
4592 (defun org-remove-keyword-keys (list)
4593 (mapcar (lambda (x)
4594 (if (string-match "(..?)$" x)
4595 (substring x 0 (match-beginning 0))
4597 list))
4599 ;; FIXME: this could be done much better, using second characters etc.
4600 (defun org-assign-fast-keys (alist)
4601 "Assign fast keys to a keyword-key alist.
4602 Respect keys that are already there."
4603 (let (new e k c c1 c2 (char ?a))
4604 (while (setq e (pop alist))
4605 (cond
4606 ((equal e '(:startgroup)) (push e new))
4607 ((equal e '(:endgroup)) (push e new))
4609 (setq k (car e) c2 nil)
4610 (if (cdr e)
4611 (setq c (cdr e))
4612 ;; automatically assign a character.
4613 (setq c1 (string-to-char
4614 (downcase (substring
4615 k (if (= (string-to-char k) ?@) 1 0)))))
4616 (if (or (rassoc c1 new) (rassoc c1 alist))
4617 (while (or (rassoc char new) (rassoc char alist))
4618 (setq char (1+ char)))
4619 (setq c2 c1))
4620 (setq c (or c2 char)))
4621 (push (cons k c) new))))
4622 (nreverse new)))
4624 ;;; Some variables ujsed in various places
4626 (defvar org-window-configuration nil
4627 "Used in various places to store a window configuration.")
4628 (defvar org-finish-function nil
4629 "Function to be called when `C-c C-c' is used.
4630 This is for getting out of special buffers like remember.")
4633 ;; FIXME: Occasionally check by commenting these, to make sure
4634 ;; no other functions uses these, forgetting to let-bind them.
4635 (defvar entry)
4636 (defvar state)
4637 (defvar last-state)
4638 (defvar date)
4639 (defvar description)
4641 ;; Defined somewhere in this file, but used before definition.
4642 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4643 (defvar org-agenda-buffer-name)
4644 (defvar org-agenda-undo-list)
4645 (defvar org-agenda-pending-undo-list)
4646 (defvar org-agenda-overriding-header)
4647 (defvar orgtbl-mode)
4648 (defvar org-html-entities)
4649 (defvar org-struct-menu)
4650 (defvar org-org-menu)
4651 (defvar org-tbl-menu)
4652 (defvar org-agenda-keymap)
4654 ;;;; Emacs/XEmacs compatibility
4656 ;; Overlay compatibility functions
4657 (defun org-make-overlay (beg end &optional buffer)
4658 (if (featurep 'xemacs)
4659 (make-extent beg end buffer)
4660 (make-overlay beg end buffer)))
4661 (defun org-delete-overlay (ovl)
4662 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4663 (defun org-detach-overlay (ovl)
4664 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4665 (defun org-move-overlay (ovl beg end &optional buffer)
4666 (if (featurep 'xemacs)
4667 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4668 (move-overlay ovl beg end buffer)))
4669 (defun org-overlay-put (ovl prop value)
4670 (if (featurep 'xemacs)
4671 (set-extent-property ovl prop value)
4672 (overlay-put ovl prop value)))
4673 (defun org-overlay-display (ovl text &optional face evap)
4674 "Make overlay OVL display TEXT with face FACE."
4675 (if (featurep 'xemacs)
4676 (let ((gl (make-glyph text)))
4677 (and face (set-glyph-face gl face))
4678 (set-extent-property ovl 'invisible t)
4679 (set-extent-property ovl 'end-glyph gl))
4680 (overlay-put ovl 'display text)
4681 (if face (overlay-put ovl 'face face))
4682 (if evap (overlay-put ovl 'evaporate t))))
4683 (defun org-overlay-before-string (ovl text &optional face evap)
4684 "Make overlay OVL display TEXT with face FACE."
4685 (if (featurep 'xemacs)
4686 (let ((gl (make-glyph text)))
4687 (and face (set-glyph-face gl face))
4688 (set-extent-property ovl 'begin-glyph gl))
4689 (if face (org-add-props text nil 'face face))
4690 (overlay-put ovl 'before-string text)
4691 (if evap (overlay-put ovl 'evaporate t))))
4692 (defun org-overlay-get (ovl prop)
4693 (if (featurep 'xemacs)
4694 (extent-property ovl prop)
4695 (overlay-get ovl prop)))
4696 (defun org-overlays-at (pos)
4697 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4698 (defun org-overlays-in (&optional start end)
4699 (if (featurep 'xemacs)
4700 (extent-list nil start end)
4701 (overlays-in start end)))
4702 (defun org-overlay-start (o)
4703 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4704 (defun org-overlay-end (o)
4705 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4706 (defun org-find-overlays (prop &optional pos delete)
4707 "Find all overlays specifying PROP at POS or point.
4708 If DELETE is non-nil, delete all those overlays."
4709 (let ((overlays (org-overlays-at (or pos (point))))
4710 ov found)
4711 (while (setq ov (pop overlays))
4712 (if (org-overlay-get ov prop)
4713 (if delete (org-delete-overlay ov) (push ov found))))
4714 found))
4716 ;; Region compatibility
4718 (defun org-add-hook (hook function &optional append local)
4719 "Add-hook, compatible with both Emacsen."
4720 (if (and local (featurep 'xemacs))
4721 (add-local-hook hook function append)
4722 (add-hook hook function append local)))
4724 (defvar org-ignore-region nil
4725 "To temporarily disable the active region.")
4727 (defun org-region-active-p ()
4728 "Is `transient-mark-mode' on and the region active?
4729 Works on both Emacs and XEmacs."
4730 (if org-ignore-region
4732 (if (featurep 'xemacs)
4733 (and zmacs-regions (region-active-p))
4734 (if (fboundp 'use-region-p)
4735 (use-region-p)
4736 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4738 ;; Invisibility compatibility
4740 (defun org-add-to-invisibility-spec (arg)
4741 "Add elements to `buffer-invisibility-spec'.
4742 See documentation for `buffer-invisibility-spec' for the kind of elements
4743 that can be added."
4744 (cond
4745 ((fboundp 'add-to-invisibility-spec)
4746 (add-to-invisibility-spec arg))
4747 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4748 (setq buffer-invisibility-spec (list arg)))
4750 (setq buffer-invisibility-spec
4751 (cons arg buffer-invisibility-spec)))))
4753 (defun org-remove-from-invisibility-spec (arg)
4754 "Remove elements from `buffer-invisibility-spec'."
4755 (if (fboundp 'remove-from-invisibility-spec)
4756 (remove-from-invisibility-spec arg)
4757 (if (consp buffer-invisibility-spec)
4758 (setq buffer-invisibility-spec
4759 (delete arg buffer-invisibility-spec)))))
4761 (defun org-in-invisibility-spec-p (arg)
4762 "Is ARG a member of `buffer-invisibility-spec'?"
4763 (if (consp buffer-invisibility-spec)
4764 (member arg buffer-invisibility-spec)
4765 nil))
4767 ;;;; Define the Org-mode
4769 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4770 (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."))
4773 ;; We use a before-change function to check if a table might need
4774 ;; an update.
4775 (defvar org-table-may-need-update t
4776 "Indicates that a table might need an update.
4777 This variable is set by `org-before-change-function'.
4778 `org-table-align' sets it back to nil.")
4779 (defvar org-mode-map)
4780 (defvar org-mode-hook nil)
4781 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4782 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4783 (defvar org-table-buffer-is-an nil)
4784 (defconst org-outline-regexp "\\*+ ")
4786 ;;;###autoload
4787 (define-derived-mode org-mode outline-mode "Org"
4788 "Outline-based notes management and organizer, alias
4789 \"Carsten's outline-mode for keeping track of everything.\"
4791 Org-mode develops organizational tasks around a NOTES file which
4792 contains information about projects as plain text. Org-mode is
4793 implemented on top of outline-mode, which is ideal to keep the content
4794 of large files well structured. It supports ToDo items, deadlines and
4795 time stamps, which magically appear in the diary listing of the Emacs
4796 calendar. Tables are easily created with a built-in table editor.
4797 Plain text URL-like links connect to websites, emails (VM), Usenet
4798 messages (Gnus), BBDB entries, and any files related to the project.
4799 For printing and sharing of notes, an Org-mode file (or a part of it)
4800 can be exported as a structured ASCII or HTML file.
4802 The following commands are available:
4804 \\{org-mode-map}"
4806 ;; Get rid of Outline menus, they are not needed
4807 ;; Need to do this here because define-derived-mode sets up
4808 ;; the keymap so late. Still, it is a waste to call this each time
4809 ;; we switch another buffer into org-mode.
4810 (if (featurep 'xemacs)
4811 (when (boundp 'outline-mode-menu-heading)
4812 ;; Assume this is Greg's port, it used easymenu
4813 (easy-menu-remove outline-mode-menu-heading)
4814 (easy-menu-remove outline-mode-menu-show)
4815 (easy-menu-remove outline-mode-menu-hide))
4816 (define-key org-mode-map [menu-bar headings] 'undefined)
4817 (define-key org-mode-map [menu-bar hide] 'undefined)
4818 (define-key org-mode-map [menu-bar show] 'undefined))
4820 (easy-menu-add org-org-menu)
4821 (easy-menu-add org-tbl-menu)
4822 (org-install-agenda-files-menu)
4823 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4824 (org-add-to-invisibility-spec '(org-cwidth))
4825 (when (featurep 'xemacs)
4826 (org-set-local 'line-move-ignore-invisible t))
4827 (org-set-local 'outline-regexp org-outline-regexp)
4828 (org-set-local 'outline-level 'org-outline-level)
4829 (when (and org-ellipsis
4830 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4831 (fboundp 'make-glyph-code))
4832 (unless org-display-table
4833 (setq org-display-table (make-display-table)))
4834 (set-display-table-slot
4835 org-display-table 4
4836 (vconcat (mapcar
4837 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4838 org-ellipsis)))
4839 (if (stringp org-ellipsis) org-ellipsis "..."))))
4840 (setq buffer-display-table org-display-table))
4841 (org-set-regexps-and-options)
4842 ;; Calc embedded
4843 (org-set-local 'calc-embedded-open-mode "# ")
4844 (modify-syntax-entry ?# "<")
4845 (modify-syntax-entry ?@ "w")
4846 (if org-startup-truncated (setq truncate-lines t))
4847 (org-set-local 'font-lock-unfontify-region-function
4848 'org-unfontify-region)
4849 ;; Activate before-change-function
4850 (org-set-local 'org-table-may-need-update t)
4851 (org-add-hook 'before-change-functions 'org-before-change-function nil
4852 'local)
4853 ;; Check for running clock before killing a buffer
4854 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4855 ;; Paragraphs and auto-filling
4856 (org-set-autofill-regexps)
4857 (setq indent-line-function 'org-indent-line-function)
4858 (org-update-radio-target-regexp)
4860 ;; Comment characters
4861 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4862 (org-set-local 'comment-padding " ")
4864 ;; Imenu
4865 (org-set-local 'imenu-create-index-function
4866 'org-imenu-get-tree)
4868 ;; Make isearch reveal context
4869 (if (or (featurep 'xemacs)
4870 (not (boundp 'outline-isearch-open-invisible-function)))
4871 ;; Emacs 21 and XEmacs make use of the hook
4872 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4873 ;; Emacs 22 deals with this through a special variable
4874 (org-set-local 'outline-isearch-open-invisible-function
4875 (lambda (&rest ignore) (org-show-context 'isearch))))
4877 ;; If empty file that did not turn on org-mode automatically, make it to.
4878 (if (and org-insert-mode-line-in-empty-file
4879 (interactive-p)
4880 (= (point-min) (point-max)))
4881 (insert "# -*- mode: org -*-\n\n"))
4883 (unless org-inhibit-startup
4884 (when org-startup-align-all-tables
4885 (let ((bmp (buffer-modified-p)))
4886 (org-table-map-tables 'org-table-align)
4887 (set-buffer-modified-p bmp)))
4888 (org-cycle-hide-drawers 'all)
4889 (cond
4890 ((eq org-startup-folded t)
4891 (org-cycle '(4)))
4892 ((eq org-startup-folded 'content)
4893 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4894 (org-cycle '(4)) (org-cycle '(4)))))))
4896 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4898 (defsubst org-call-with-arg (command arg)
4899 "Call COMMAND interactively, but pretend prefix are was ARG."
4900 (let ((current-prefix-arg arg)) (call-interactively command)))
4902 (defsubst org-current-line (&optional pos)
4903 (save-excursion
4904 (and pos (goto-char pos))
4905 ;; works also in narrowed buffer, because we start at 1, not point-min
4906 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4908 (defun org-current-time ()
4909 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4910 (if (> org-time-stamp-rounding-minutes 0)
4911 (let ((r org-time-stamp-rounding-minutes)
4912 (time (decode-time)))
4913 (apply 'encode-time
4914 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4915 (nthcdr 2 time))))
4916 (current-time)))
4918 (defun org-add-props (string plist &rest props)
4919 "Add text properties to entire string, from beginning to end.
4920 PLIST may be a list of properties, PROPS are individual properties and values
4921 that will be added to PLIST. Returns the string that was modified."
4922 (add-text-properties
4923 0 (length string) (if props (append plist props) plist) string)
4924 string)
4925 (put 'org-add-props 'lisp-indent-function 2)
4928 ;;;; Font-Lock stuff, including the activators
4930 (defvar org-mouse-map (make-sparse-keymap))
4931 (org-defkey org-mouse-map
4932 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4933 (org-defkey org-mouse-map
4934 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4935 (when org-mouse-1-follows-link
4936 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4937 (when org-tab-follows-link
4938 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4939 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4940 (when org-return-follows-link
4941 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4942 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4944 (require 'font-lock)
4946 (defconst org-non-link-chars "]\t\n\r<>")
4947 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4948 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
4949 (defvar org-link-re-with-space nil
4950 "Matches a link with spaces, optional angular brackets around it.")
4951 (defvar org-link-re-with-space2 nil
4952 "Matches a link with spaces, optional angular brackets around it.")
4953 (defvar org-angle-link-re nil
4954 "Matches link with angular brackets, spaces are allowed.")
4955 (defvar org-plain-link-re nil
4956 "Matches plain link, without spaces.")
4957 (defvar org-bracket-link-regexp nil
4958 "Matches a link in double brackets.")
4959 (defvar org-bracket-link-analytic-regexp nil
4960 "Regular expression used to analyze links.
4961 Here is what the match groups contain after a match:
4962 1: http:
4963 2: http
4964 3: path
4965 4: [desc]
4966 5: desc")
4967 (defvar org-any-link-re nil
4968 "Regular expression matching any link.")
4970 (defun org-make-link-regexps ()
4971 "Update the link regular expressions.
4972 This should be called after the variable `org-link-types' has changed."
4973 (setq org-link-re-with-space
4974 (concat
4975 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4976 "\\([^" org-non-link-chars " ]"
4977 "[^" org-non-link-chars "]*"
4978 "[^" org-non-link-chars " ]\\)>?")
4979 org-link-re-with-space2
4980 (concat
4981 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4982 "\\([^" org-non-link-chars " ]"
4983 "[^]\t\n\r]*"
4984 "[^" org-non-link-chars " ]\\)>?")
4985 org-angle-link-re
4986 (concat
4987 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4988 "\\([^" org-non-link-chars " ]"
4989 "[^" org-non-link-chars "]*"
4990 "\\)>")
4991 org-plain-link-re
4992 (concat
4993 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4994 "\\([^]\t\n\r<>,;() ]+\\)")
4995 org-bracket-link-regexp
4996 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4997 org-bracket-link-analytic-regexp
4998 (concat
4999 "\\[\\["
5000 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5001 "\\([^]]+\\)"
5002 "\\]"
5003 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5004 "\\]")
5005 org-any-link-re
5006 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5007 org-angle-link-re "\\)\\|\\("
5008 org-plain-link-re "\\)")))
5010 (org-make-link-regexps)
5012 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5013 "Regular expression for fast time stamp matching.")
5014 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5015 "Regular expression for fast time stamp matching.")
5016 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5017 "Regular expression matching time strings for analysis.
5018 This one does not require the space after the date.")
5019 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5020 "Regular expression matching time strings for analysis.")
5021 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5022 "Regular expression matching time stamps, with groups.")
5023 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5024 "Regular expression matching time stamps (also [..]), with groups.")
5025 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5026 "Regular expression matching a time stamp range.")
5027 (defconst org-tr-regexp-both
5028 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5029 "Regular expression matching a time stamp range.")
5030 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5031 org-ts-regexp "\\)?")
5032 "Regular expression matching a time stamp or time stamp range.")
5033 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5034 org-ts-regexp-both "\\)?")
5035 "Regular expression matching a time stamp or time stamp range.
5036 The time stamps may be either active or inactive.")
5038 (defvar org-emph-face nil)
5040 (defun org-do-emphasis-faces (limit)
5041 "Run through the buffer and add overlays to links."
5042 (let (rtn)
5043 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5044 (if (not (= (char-after (match-beginning 3))
5045 (char-after (match-beginning 4))))
5046 (progn
5047 (setq rtn t)
5048 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5049 'face
5050 (nth 1 (assoc (match-string 3)
5051 org-emphasis-alist)))
5052 (add-text-properties (match-beginning 2) (match-end 2)
5053 '(font-lock-multiline t))
5054 (when org-hide-emphasis-markers
5055 (add-text-properties (match-end 4) (match-beginning 5)
5056 '(invisible org-link))
5057 (add-text-properties (match-beginning 3) (match-end 3)
5058 '(invisible org-link)))))
5059 (backward-char 1))
5060 rtn))
5062 (defun org-emphasize (&optional char)
5063 "Insert or change an emphasis, i.e. a font like bold or italic.
5064 If there is an active region, change that region to a new emphasis.
5065 If there is no region, just insert the marker characters and position
5066 the cursor between them.
5067 CHAR should be either the marker character, or the first character of the
5068 HTML tag associated with that emphasis. If CHAR is a space, the means
5069 to remove the emphasis of the selected region.
5070 If char is not given (for example in an interactive call) it
5071 will be prompted for."
5072 (interactive)
5073 (let ((eal org-emphasis-alist) e det
5074 (erc org-emphasis-regexp-components)
5075 (prompt "")
5076 (string "") beg end move tag c s)
5077 (if (org-region-active-p)
5078 (setq beg (region-beginning) end (region-end)
5079 string (buffer-substring beg end))
5080 (setq move t))
5082 (while (setq e (pop eal))
5083 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5084 c (aref tag 0))
5085 (push (cons c (string-to-char (car e))) det)
5086 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5087 (substring tag 1)))))
5088 (unless char
5089 (message "%s" (concat "Emphasis marker or tag:" prompt))
5090 (setq char (read-char-exclusive)))
5091 (setq char (or (cdr (assoc char det)) char))
5092 (if (equal char ?\ )
5093 (setq s "" move nil)
5094 (unless (assoc (char-to-string char) org-emphasis-alist)
5095 (error "No such emphasis marker: \"%c\"" char))
5096 (setq s (char-to-string char)))
5097 (while (and (> (length string) 1)
5098 (equal (substring string 0 1) (substring string -1))
5099 (assoc (substring string 0 1) org-emphasis-alist))
5100 (setq string (substring string 1 -1)))
5101 (setq string (concat s string s))
5102 (if beg (delete-region beg end))
5103 (unless (or (bolp)
5104 (string-match (concat "[" (nth 0 erc) "\n]")
5105 (char-to-string (char-before (point)))))
5106 (insert " "))
5107 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5108 (char-to-string (char-after (point))))
5109 (insert " ") (backward-char 1))
5110 (insert string)
5111 (and move (backward-char 1))))
5113 (defconst org-nonsticky-props
5114 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5117 (defun org-activate-plain-links (limit)
5118 "Run through the buffer and add overlays to links."
5119 (catch 'exit
5120 (let (f)
5121 (while (re-search-forward org-plain-link-re limit t)
5122 (setq f (get-text-property (match-beginning 0) 'face))
5123 (if (or (eq f 'org-tag)
5124 (and (listp f) (memq 'org-tag f)))
5126 (add-text-properties (match-beginning 0) (match-end 0)
5127 (list 'mouse-face 'highlight
5128 'rear-nonsticky org-nonsticky-props
5129 'keymap org-mouse-map
5131 (throw 'exit t))))))
5133 (defun org-activate-code (limit)
5134 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5135 (unless (get-text-property (match-beginning 1) 'face)
5136 (remove-text-properties (match-beginning 0) (match-end 0)
5137 '(display t invisible t intangible t))
5138 t)))
5140 (defun org-activate-angle-links (limit)
5141 "Run through the buffer and add overlays to links."
5142 (if (re-search-forward org-angle-link-re limit t)
5143 (progn
5144 (add-text-properties (match-beginning 0) (match-end 0)
5145 (list 'mouse-face 'highlight
5146 'rear-nonsticky org-nonsticky-props
5147 'keymap org-mouse-map
5149 t)))
5151 (defmacro org-maybe-intangible (props)
5152 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5153 In emacs 21, invisible text is not avoided by the command loop, so the
5154 intangible property is needed to make sure point skips this text.
5155 In Emacs 22, this is not necessary. The intangible text property has
5156 led to problems with flyspell. These problems are fixed in flyspell.el,
5157 but we still avoid setting the property in Emacs 22 and later.
5158 We use a macro so that the test can happen at compilation time."
5159 (if (< emacs-major-version 22)
5160 `(append '(intangible t) ,props)
5161 props))
5163 (defun org-activate-bracket-links (limit)
5164 "Run through the buffer and add overlays to bracketed links."
5165 (if (re-search-forward org-bracket-link-regexp limit t)
5166 (let* ((help (concat "LINK: "
5167 (org-match-string-no-properties 1)))
5168 ;; FIXME: above we should remove the escapes.
5169 ;; but that requires another match, protecting match data,
5170 ;; a lot of overhead for font-lock.
5171 (ip (org-maybe-intangible
5172 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5173 'keymap org-mouse-map 'mouse-face 'highlight
5174 'font-lock-multiline t 'help-echo help)))
5175 (vp (list 'rear-nonsticky org-nonsticky-props
5176 'keymap org-mouse-map 'mouse-face 'highlight
5177 ' font-lock-multiline t 'help-echo help)))
5178 ;; We need to remove the invisible property here. Table narrowing
5179 ;; may have made some of this invisible.
5180 (remove-text-properties (match-beginning 0) (match-end 0)
5181 '(invisible nil))
5182 (if (match-end 3)
5183 (progn
5184 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5185 (add-text-properties (match-beginning 3) (match-end 3) vp)
5186 (add-text-properties (match-end 3) (match-end 0) ip))
5187 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5188 (add-text-properties (match-beginning 1) (match-end 1) vp)
5189 (add-text-properties (match-end 1) (match-end 0) ip))
5190 t)))
5192 (defun org-activate-dates (limit)
5193 "Run through the buffer and add overlays to dates."
5194 (if (re-search-forward org-tsr-regexp-both limit t)
5195 (progn
5196 (add-text-properties (match-beginning 0) (match-end 0)
5197 (list 'mouse-face 'highlight
5198 'rear-nonsticky org-nonsticky-props
5199 'keymap org-mouse-map))
5200 (when org-display-custom-times
5201 (if (match-end 3)
5202 (org-display-custom-time (match-beginning 3) (match-end 3)))
5203 (org-display-custom-time (match-beginning 1) (match-end 1)))
5204 t)))
5206 (defvar org-target-link-regexp nil
5207 "Regular expression matching radio targets in plain text.")
5208 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5209 "Regular expression matching a link target.")
5210 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5211 "Regular expression matching a radio target.")
5212 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5213 "Regular expression matching any target.")
5215 (defun org-activate-target-links (limit)
5216 "Run through the buffer and add overlays to target matches."
5217 (when org-target-link-regexp
5218 (let ((case-fold-search t))
5219 (if (re-search-forward org-target-link-regexp limit t)
5220 (progn
5221 (add-text-properties (match-beginning 0) (match-end 0)
5222 (list 'mouse-face 'highlight
5223 'rear-nonsticky org-nonsticky-props
5224 'keymap org-mouse-map
5225 'help-echo "Radio target link"
5226 'org-linked-text t))
5227 t)))))
5229 (defun org-update-radio-target-regexp ()
5230 "Find all radio targets in this file and update the regular expression."
5231 (interactive)
5232 (when (memq 'radio org-activate-links)
5233 (setq org-target-link-regexp
5234 (org-make-target-link-regexp (org-all-targets 'radio)))
5235 (org-restart-font-lock)))
5237 (defun org-hide-wide-columns (limit)
5238 (let (s e)
5239 (setq s (text-property-any (point) (or limit (point-max))
5240 'org-cwidth t))
5241 (when s
5242 (setq e (next-single-property-change s 'org-cwidth))
5243 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5244 (goto-char e)
5245 t)))
5247 (defvar org-latex-and-specials-regexp nil
5248 "Regular expression for highlighting export special stuff.")
5249 (defvar org-match-substring-regexp)
5250 (defvar org-match-substring-with-braces-regexp)
5251 (defvar org-export-html-special-string-regexps)
5253 (defun org-compute-latex-and-specials-regexp ()
5254 "Compute regular expression for stuff treated specially by exporters."
5255 (if (not org-highlight-latex-fragments-and-specials)
5256 (org-set-local 'org-latex-and-specials-regexp nil)
5257 (let*
5258 ((matchers (plist-get org-format-latex-options :matchers))
5259 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5260 org-latex-regexps)))
5261 (options (org-combine-plists (org-default-export-plist)
5262 (org-infile-export-plist)))
5263 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5264 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5265 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5266 (org-export-html-expand (plist-get options :expand-quoted-html))
5267 (org-export-with-special-strings (plist-get options :special-strings))
5268 (re-sub
5269 (cond
5270 ((equal org-export-with-sub-superscripts '{})
5271 (list org-match-substring-with-braces-regexp))
5272 (org-export-with-sub-superscripts
5273 (list org-match-substring-regexp))
5274 (t nil)))
5275 (re-latex
5276 (if org-export-with-LaTeX-fragments
5277 (mapcar (lambda (x) (nth 1 x)) latexs)))
5278 (re-macros
5279 (if org-export-with-TeX-macros
5280 (list (concat "\\\\"
5281 (regexp-opt
5282 (append (mapcar 'car org-html-entities)
5283 (if (boundp 'org-latex-entities)
5284 org-latex-entities nil))
5285 'words))) ; FIXME
5287 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5288 (re-special (if org-export-with-special-strings
5289 (mapcar (lambda (x) (car x))
5290 org-export-html-special-string-regexps)))
5291 (re-rest
5292 (delq nil
5293 (list
5294 (if org-export-html-expand "@<[^>\n]+>")
5295 ))))
5296 (org-set-local
5297 'org-latex-and-specials-regexp
5298 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5299 re-rest) "\\|")))))
5301 (defface org-latex-and-export-specials
5302 (let ((font (cond ((assq :inherit custom-face-attributes)
5303 '(:inherit underline))
5304 (t '(:underline t)))))
5305 `((((class grayscale) (background light))
5306 (:foreground "DimGray" ,@font))
5307 (((class grayscale) (background dark))
5308 (:foreground "LightGray" ,@font))
5309 (((class color) (background light))
5310 (:foreground "SaddleBrown"))
5311 (((class color) (background dark))
5312 (:foreground "burlywood"))
5313 (t (,@font))))
5314 "Face used to highlight math latex and other special exporter stuff."
5315 :group 'org-faces)
5317 (defun org-do-latex-and-special-faces (limit)
5318 "Run through the buffer and add overlays to links."
5319 (when org-latex-and-specials-regexp
5320 (let (rtn d)
5321 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5322 limit t))
5323 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5324 'face))
5325 '(org-code org-verbatim underline)))
5326 (progn
5327 (setq rtn t
5328 d (cond ((member (char-after (1+ (match-beginning 0)))
5329 '(?_ ?^)) 1)
5330 (t 0)))
5331 (font-lock-prepend-text-property
5332 (+ d (match-beginning 0)) (match-end 0)
5333 'face 'org-latex-and-export-specials)
5334 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5335 '(font-lock-multiline t)))))
5336 rtn)))
5338 (defun org-restart-font-lock ()
5339 "Restart font-lock-mode, to force refontification."
5340 (when (and (boundp 'font-lock-mode) font-lock-mode)
5341 (font-lock-mode -1)
5342 (font-lock-mode 1)))
5344 (defun org-all-targets (&optional radio)
5345 "Return a list of all targets in this file.
5346 With optional argument RADIO, only find radio targets."
5347 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5348 rtn)
5349 (save-excursion
5350 (goto-char (point-min))
5351 (while (re-search-forward re nil t)
5352 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5353 rtn)))
5355 (defun org-make-target-link-regexp (targets)
5356 "Make regular expression matching all strings in TARGETS.
5357 The regular expression finds the targets also if there is a line break
5358 between words."
5359 (and targets
5360 (concat
5361 "\\<\\("
5362 (mapconcat
5363 (lambda (x)
5364 (while (string-match " +" x)
5365 (setq x (replace-match "\\s-+" t t x)))
5367 targets
5368 "\\|")
5369 "\\)\\>")))
5371 (defun org-activate-tags (limit)
5372 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5373 (progn
5374 (add-text-properties (match-beginning 1) (match-end 1)
5375 (list 'mouse-face 'highlight
5376 'rear-nonsticky org-nonsticky-props
5377 'keymap org-mouse-map))
5378 t)))
5380 (defun org-outline-level ()
5381 (save-excursion
5382 (looking-at outline-regexp)
5383 (if (match-beginning 1)
5384 (+ (org-get-string-indentation (match-string 1)) 1000)
5385 (1- (- (match-end 0) (match-beginning 0))))))
5387 (defvar org-font-lock-keywords nil)
5389 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5390 "Regular expression matching a property line.")
5392 (defun org-set-font-lock-defaults ()
5393 (let* ((em org-fontify-emphasized-text)
5394 (lk org-activate-links)
5395 (org-font-lock-extra-keywords
5396 (list
5397 ;; Headlines
5398 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5399 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5400 ;; Table lines
5401 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5402 (1 'org-table t))
5403 ;; Table internals
5404 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5405 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5406 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5407 ;; Drawers
5408 (list org-drawer-regexp '(0 'org-special-keyword t))
5409 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5410 ;; Properties
5411 (list org-property-re
5412 '(1 'org-special-keyword t)
5413 '(3 'org-property-value t))
5414 (if org-format-transports-properties-p
5415 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5416 ;; Links
5417 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5418 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5419 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5420 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5421 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5422 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5423 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5424 '(org-hide-wide-columns (0 nil append))
5425 ;; TODO lines
5426 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5427 '(1 (org-get-todo-face 1) t))
5428 ;; DONE
5429 (if org-fontify-done-headline
5430 (list (concat "^[*]+ +\\<\\("
5431 (mapconcat 'regexp-quote org-done-keywords "\\|")
5432 "\\)\\(.*\\)")
5433 '(2 'org-headline-done t))
5434 nil)
5435 ;; Priorities
5436 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5437 ;; Special keywords
5438 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5439 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5440 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5441 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5442 ;; Emphasis
5443 (if em
5444 (if (featurep 'xemacs)
5445 '(org-do-emphasis-faces (0 nil append))
5446 '(org-do-emphasis-faces)))
5447 ;; Checkboxes
5448 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5449 2 'bold prepend)
5450 (if org-provide-checkbox-statistics
5451 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5452 (0 (org-get-checkbox-statistics-face) t)))
5453 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5454 '(1 'org-archived prepend))
5455 ;; Specials
5456 '(org-do-latex-and-special-faces)
5457 ;; Code
5458 '(org-activate-code (1 'org-code t))
5459 ;; COMMENT
5460 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5461 "\\|" org-quote-string "\\)\\>")
5462 '(1 'org-special-keyword t))
5463 '("^#.*" (0 'font-lock-comment-face t))
5465 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5466 ;; Now set the full font-lock-keywords
5467 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5468 (org-set-local 'font-lock-defaults
5469 '(org-font-lock-keywords t nil nil backward-paragraph))
5470 (kill-local-variable 'font-lock-keywords) nil))
5472 (defvar org-m nil)
5473 (defvar org-l nil)
5474 (defvar org-f nil)
5475 (defun org-get-level-face (n)
5476 "Get the right face for match N in font-lock matching of healdines."
5477 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5478 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5479 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5480 (cond
5481 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5482 ((eq n 2) org-f)
5483 (t (if org-level-color-stars-only nil org-f))))
5485 (defun org-get-todo-face (kwd)
5486 "Get the right face for a TODO keyword KWD.
5487 If KWD is a number, get the corresponding match group."
5488 (if (numberp kwd) (setq kwd (match-string kwd)))
5489 (or (cdr (assoc kwd org-todo-keyword-faces))
5490 (and (member kwd org-done-keywords) 'org-done)
5491 'org-todo))
5493 (defun org-unfontify-region (beg end &optional maybe_loudly)
5494 "Remove fontification and activation overlays from links."
5495 (font-lock-default-unfontify-region beg end)
5496 (let* ((buffer-undo-list t)
5497 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5498 (inhibit-modification-hooks t)
5499 deactivate-mark buffer-file-name buffer-file-truename)
5500 (remove-text-properties beg end
5501 '(mouse-face t keymap t org-linked-text t
5502 invisible t intangible t))))
5504 ;;;; Visibility cycling, including org-goto and indirect buffer
5506 ;;; Cycling
5508 (defvar org-cycle-global-status nil)
5509 (make-variable-buffer-local 'org-cycle-global-status)
5510 (defvar org-cycle-subtree-status nil)
5511 (make-variable-buffer-local 'org-cycle-subtree-status)
5513 ;;;###autoload
5514 (defun org-cycle (&optional arg)
5515 "Visibility cycling for Org-mode.
5517 - When this function is called with a prefix argument, rotate the entire
5518 buffer through 3 states (global cycling)
5519 1. OVERVIEW: Show only top-level headlines.
5520 2. CONTENTS: Show all headlines of all levels, but no body text.
5521 3. SHOW ALL: Show everything.
5523 - When point is at the beginning of a headline, rotate the subtree started
5524 by this line through 3 different states (local cycling)
5525 1. FOLDED: Only the main headline is shown.
5526 2. CHILDREN: The main headline and the direct children are shown.
5527 From this state, you can move to one of the children
5528 and zoom in further.
5529 3. SUBTREE: Show the entire subtree, including body text.
5531 - When there is a numeric prefix, go up to a heading with level ARG, do
5532 a `show-subtree' and return to the previous cursor position. If ARG
5533 is negative, go up that many levels.
5535 - When point is not at the beginning of a headline, execute
5536 `indent-relative', like TAB normally does. See the option
5537 `org-cycle-emulate-tab' for details.
5539 - Special case: if point is at the beginning of the buffer and there is
5540 no headline in line 1, this function will act as if called with prefix arg.
5541 But only if also the variable `org-cycle-global-at-bob' is t."
5542 (interactive "P")
5543 (let* ((outline-regexp
5544 (if (and (org-mode-p) org-cycle-include-plain-lists)
5545 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5546 outline-regexp))
5547 (bob-special (and org-cycle-global-at-bob (bobp)
5548 (not (looking-at outline-regexp))))
5549 (org-cycle-hook
5550 (if bob-special
5551 (delq 'org-optimize-window-after-visibility-change
5552 (copy-sequence org-cycle-hook))
5553 org-cycle-hook))
5554 (pos (point)))
5556 (if (or bob-special (equal arg '(4)))
5557 ;; special case: use global cycling
5558 (setq arg t))
5560 (cond
5562 ((org-at-table-p 'any)
5563 ;; Enter the table or move to the next field in the table
5564 (or (org-table-recognize-table.el)
5565 (progn
5566 (if arg (org-table-edit-field t)
5567 (org-table-justify-field-maybe)
5568 (call-interactively 'org-table-next-field)))))
5570 ((eq arg t) ;; Global cycling
5572 (cond
5573 ((and (eq last-command this-command)
5574 (eq org-cycle-global-status 'overview))
5575 ;; We just created the overview - now do table of contents
5576 ;; This can be slow in very large buffers, so indicate action
5577 (message "CONTENTS...")
5578 (org-content)
5579 (message "CONTENTS...done")
5580 (setq org-cycle-global-status 'contents)
5581 (run-hook-with-args 'org-cycle-hook 'contents))
5583 ((and (eq last-command this-command)
5584 (eq org-cycle-global-status 'contents))
5585 ;; We just showed the table of contents - now show everything
5586 (show-all)
5587 (message "SHOW ALL")
5588 (setq org-cycle-global-status 'all)
5589 (run-hook-with-args 'org-cycle-hook 'all))
5592 ;; Default action: go to overview
5593 (org-overview)
5594 (message "OVERVIEW")
5595 (setq org-cycle-global-status 'overview)
5596 (run-hook-with-args 'org-cycle-hook 'overview))))
5598 ((and org-drawers org-drawer-regexp
5599 (save-excursion
5600 (beginning-of-line 1)
5601 (looking-at org-drawer-regexp)))
5602 ;; Toggle block visibility
5603 (org-flag-drawer
5604 (not (get-char-property (match-end 0) 'invisible))))
5606 ((integerp arg)
5607 ;; Show-subtree, ARG levels up from here.
5608 (save-excursion
5609 (org-back-to-heading)
5610 (outline-up-heading (if (< arg 0) (- arg)
5611 (- (funcall outline-level) arg)))
5612 (org-show-subtree)))
5614 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5615 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5616 ;; At a heading: rotate between three different views
5617 (org-back-to-heading)
5618 (let ((goal-column 0) eoh eol eos)
5619 ;; First, some boundaries
5620 (save-excursion
5621 (org-back-to-heading)
5622 (save-excursion
5623 (beginning-of-line 2)
5624 (while (and (not (eobp)) ;; this is like `next-line'
5625 (get-char-property (1- (point)) 'invisible))
5626 (beginning-of-line 2)) (setq eol (point)))
5627 (outline-end-of-heading) (setq eoh (point))
5628 (org-end-of-subtree t)
5629 (unless (eobp)
5630 (skip-chars-forward " \t\n")
5631 (beginning-of-line 1) ; in case this is an item
5633 (setq eos (1- (point))))
5634 ;; Find out what to do next and set `this-command'
5635 (cond
5636 ((= eos eoh)
5637 ;; Nothing is hidden behind this heading
5638 (message "EMPTY ENTRY")
5639 (setq org-cycle-subtree-status nil)
5640 (save-excursion
5641 (goto-char eos)
5642 (outline-next-heading)
5643 (if (org-invisible-p) (org-flag-heading nil))))
5644 ((or (>= eol eos)
5645 (not (string-match "\\S-" (buffer-substring eol eos))))
5646 ;; Entire subtree is hidden in one line: open it
5647 (org-show-entry)
5648 (show-children)
5649 (message "CHILDREN")
5650 (save-excursion
5651 (goto-char eos)
5652 (outline-next-heading)
5653 (if (org-invisible-p) (org-flag-heading nil)))
5654 (setq org-cycle-subtree-status 'children)
5655 (run-hook-with-args 'org-cycle-hook 'children))
5656 ((and (eq last-command this-command)
5657 (eq org-cycle-subtree-status 'children))
5658 ;; We just showed the children, now show everything.
5659 (org-show-subtree)
5660 (message "SUBTREE")
5661 (setq org-cycle-subtree-status 'subtree)
5662 (run-hook-with-args 'org-cycle-hook 'subtree))
5664 ;; Default action: hide the subtree.
5665 (hide-subtree)
5666 (message "FOLDED")
5667 (setq org-cycle-subtree-status 'folded)
5668 (run-hook-with-args 'org-cycle-hook 'folded)))))
5670 ;; TAB emulation
5671 (buffer-read-only (org-back-to-heading))
5673 ((org-try-cdlatex-tab))
5675 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5676 (or (not (bolp))
5677 (not (looking-at outline-regexp))))
5678 (call-interactively (global-key-binding "\t")))
5680 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5681 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5682 (or (and (eq org-cycle-emulate-tab 'white)
5683 (= (match-end 0) (point-at-eol)))
5684 (and (eq org-cycle-emulate-tab 'whitestart)
5685 (>= (match-end 0) pos))))
5687 (eq org-cycle-emulate-tab t))
5688 ; (if (and (looking-at "[ \n\r\t]")
5689 ; (string-match "^[ \t]*$" (buffer-substring
5690 ; (point-at-bol) (point))))
5691 ; (progn
5692 ; (beginning-of-line 1)
5693 ; (and (looking-at "[ \t]+") (replace-match ""))))
5694 (call-interactively (global-key-binding "\t")))
5696 (t (save-excursion
5697 (org-back-to-heading)
5698 (org-cycle))))))
5700 ;;;###autoload
5701 (defun org-global-cycle (&optional arg)
5702 "Cycle the global visibility. For details see `org-cycle'."
5703 (interactive "P")
5704 (let ((org-cycle-include-plain-lists
5705 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5706 (if (integerp arg)
5707 (progn
5708 (show-all)
5709 (hide-sublevels arg)
5710 (setq org-cycle-global-status 'contents))
5711 (org-cycle '(4)))))
5713 (defun org-overview ()
5714 "Switch to overview mode, shoing only top-level headlines.
5715 Really, this shows all headlines with level equal or greater than the level
5716 of the first headline in the buffer. This is important, because if the
5717 first headline is not level one, then (hide-sublevels 1) gives confusing
5718 results."
5719 (interactive)
5720 (let ((level (save-excursion
5721 (goto-char (point-min))
5722 (if (re-search-forward (concat "^" outline-regexp) nil t)
5723 (progn
5724 (goto-char (match-beginning 0))
5725 (funcall outline-level))))))
5726 (and level (hide-sublevels level))))
5728 (defun org-content (&optional arg)
5729 "Show all headlines in the buffer, like a table of contents.
5730 With numerical argument N, show content up to level N."
5731 (interactive "P")
5732 (save-excursion
5733 ;; Visit all headings and show their offspring
5734 (and (integerp arg) (org-overview))
5735 (goto-char (point-max))
5736 (catch 'exit
5737 (while (and (progn (condition-case nil
5738 (outline-previous-visible-heading 1)
5739 (error (goto-char (point-min))))
5741 (looking-at outline-regexp))
5742 (if (integerp arg)
5743 (show-children (1- arg))
5744 (show-branches))
5745 (if (bobp) (throw 'exit nil))))))
5748 (defun org-optimize-window-after-visibility-change (state)
5749 "Adjust the window after a change in outline visibility.
5750 This function is the default value of the hook `org-cycle-hook'."
5751 (when (get-buffer-window (current-buffer))
5752 (cond
5753 ; ((eq state 'overview) (org-first-headline-recenter 1))
5754 ; ((eq state 'overview) (org-beginning-of-line))
5755 ((eq state 'content) nil)
5756 ((eq state 'all) nil)
5757 ((eq state 'folded) nil)
5758 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5759 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5761 (defun org-compact-display-after-subtree-move ()
5762 (let (beg end)
5763 (save-excursion
5764 (if (org-up-heading-safe)
5765 (progn
5766 (hide-subtree)
5767 (show-entry)
5768 (show-children)
5769 (org-cycle-show-empty-lines 'children)
5770 (org-cycle-hide-drawers 'children))
5771 (org-overview)))))
5773 (defun org-cycle-show-empty-lines (state)
5774 "Show empty lines above all visible headlines.
5775 The region to be covered depends on STATE when called through
5776 `org-cycle-hook'. Lisp program can use t for STATE to get the
5777 entire buffer covered. Note that an empty line is only shown if there
5778 are at least `org-cycle-separator-lines' empty lines before the headeline."
5779 (when (> org-cycle-separator-lines 0)
5780 (save-excursion
5781 (let* ((n org-cycle-separator-lines)
5782 (re (cond
5783 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5784 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5785 (t (let ((ns (number-to-string (- n 2))))
5786 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5787 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5788 beg end)
5789 (cond
5790 ((memq state '(overview contents t))
5791 (setq beg (point-min) end (point-max)))
5792 ((memq state '(children folded))
5793 (setq beg (point) end (progn (org-end-of-subtree t t)
5794 (beginning-of-line 2)
5795 (point)))))
5796 (when beg
5797 (goto-char beg)
5798 (while (re-search-forward re end t)
5799 (if (not (get-char-property (match-end 1) 'invisible))
5800 (outline-flag-region
5801 (match-beginning 1) (match-end 1) nil)))))))
5802 ;; Never hide empty lines at the end of the file.
5803 (save-excursion
5804 (goto-char (point-max))
5805 (outline-previous-heading)
5806 (outline-end-of-heading)
5807 (if (and (looking-at "[ \t\n]+")
5808 (= (match-end 0) (point-max)))
5809 (outline-flag-region (point) (match-end 0) nil))))
5811 (defun org-subtree-end-visible-p ()
5812 "Is the end of the current subtree visible?"
5813 (pos-visible-in-window-p
5814 (save-excursion (org-end-of-subtree t) (point))))
5816 (defun org-first-headline-recenter (&optional N)
5817 "Move cursor to the first headline and recenter the headline.
5818 Optional argument N means, put the headline into the Nth line of the window."
5819 (goto-char (point-min))
5820 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5821 (beginning-of-line)
5822 (recenter (prefix-numeric-value N))))
5824 ;;; Org-goto
5826 (defvar org-goto-window-configuration nil)
5827 (defvar org-goto-marker nil)
5828 (defvar org-goto-map
5829 (let ((map (make-sparse-keymap)))
5830 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5831 (while (setq cmd (pop cmds))
5832 (substitute-key-definition cmd cmd map global-map)))
5833 (suppress-keymap map)
5834 (org-defkey map "\C-m" 'org-goto-ret)
5835 (org-defkey map [(left)] 'org-goto-left)
5836 (org-defkey map [(right)] 'org-goto-right)
5837 (org-defkey map [(?q)] 'org-goto-quit)
5838 (org-defkey map [(control ?g)] 'org-goto-quit)
5839 (org-defkey map "\C-i" 'org-cycle)
5840 (org-defkey map [(tab)] 'org-cycle)
5841 (org-defkey map [(down)] 'outline-next-visible-heading)
5842 (org-defkey map [(up)] 'outline-previous-visible-heading)
5843 (org-defkey map "n" 'outline-next-visible-heading)
5844 (org-defkey map "p" 'outline-previous-visible-heading)
5845 (org-defkey map "f" 'outline-forward-same-level)
5846 (org-defkey map "b" 'outline-backward-same-level)
5847 (org-defkey map "u" 'outline-up-heading)
5848 (org-defkey map "/" 'org-occur)
5849 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5850 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5851 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5852 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5853 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5854 map))
5856 (defconst org-goto-help
5857 "Browse copy of buffer to find location or copy text.
5858 RET=jump to location [Q]uit and return to previous location
5859 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5862 (defvar org-goto-start-pos) ; dynamically scoped parameter
5864 (defun org-goto ()
5865 "Look up a different location in the current file, keeping current visibility.
5867 When you want look-up or go to a different location in a document, the
5868 fastest way is often to fold the entire buffer and then dive into the tree.
5869 This method has the disadvantage, that the previous location will be folded,
5870 which may not be what you want.
5872 This command works around this by showing a copy of the current buffer
5873 in an indirect buffer, in overview mode. You can dive into the tree in
5874 that copy, use org-occur and incremental search to find a location.
5875 When pressing RET or `Q', the command returns to the original buffer in
5876 which the visibility is still unchanged. After RET is will also jump to
5877 the location selected in the indirect buffer and expose the
5878 the headline hierarchy above."
5879 (interactive)
5880 (let* ((org-goto-start-pos (point))
5881 (selected-point
5882 (car (org-get-location (current-buffer) org-goto-help))))
5883 (if selected-point
5884 (progn
5885 (org-mark-ring-push org-goto-start-pos)
5886 (goto-char selected-point)
5887 (if (or (org-invisible-p) (org-invisible-p2))
5888 (org-show-context 'org-goto)))
5889 (message "Quit"))))
5891 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5892 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5894 (defun org-get-location (buf help)
5895 "Let the user select a location in the Org-mode buffer BUF.
5896 This function uses a recursive edit. It returns the selected position
5897 or nil."
5898 (let (org-goto-selected-point org-goto-exit-command)
5899 (save-excursion
5900 (save-window-excursion
5901 (delete-other-windows)
5902 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5903 (switch-to-buffer
5904 (condition-case nil
5905 (make-indirect-buffer (current-buffer) "*org-goto*")
5906 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5907 (with-output-to-temp-buffer "*Help*"
5908 (princ help))
5909 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5910 (setq buffer-read-only nil)
5911 (let ((org-startup-truncated t)
5912 (org-startup-folded nil)
5913 (org-startup-align-all-tables nil))
5914 (org-mode)
5915 (org-overview))
5916 (setq buffer-read-only t)
5917 (if (and (boundp 'org-goto-start-pos)
5918 (integer-or-marker-p org-goto-start-pos))
5919 (let ((org-show-hierarchy-above t)
5920 (org-show-siblings t)
5921 (org-show-following-heading t))
5922 (goto-char org-goto-start-pos)
5923 (and (org-invisible-p) (org-show-context)))
5924 (goto-char (point-min)))
5925 (org-beginning-of-line)
5926 (message "Select location and press RET")
5927 ;; now we make sure that during selection, ony very few keys work
5928 ;; and that it is impossible to switch to another window.
5929 ; (let ((gm (current-global-map))
5930 ; (overriding-local-map org-goto-map))
5931 ; (unwind-protect
5932 ; (progn
5933 ; (use-global-map org-goto-map)
5934 ; (recursive-edit))
5935 ; (use-global-map gm)))
5936 (use-local-map org-goto-map)
5937 (recursive-edit)
5939 (kill-buffer "*org-goto*")
5940 (cons org-goto-selected-point org-goto-exit-command)))
5942 (defun org-goto-ret (&optional arg)
5943 "Finish `org-goto' by going to the new location."
5944 (interactive "P")
5945 (setq org-goto-selected-point (point)
5946 org-goto-exit-command 'return)
5947 (throw 'exit nil))
5949 (defun org-goto-left ()
5950 "Finish `org-goto' by going to the new location."
5951 (interactive)
5952 (if (org-on-heading-p)
5953 (progn
5954 (beginning-of-line 1)
5955 (setq org-goto-selected-point (point)
5956 org-goto-exit-command 'left)
5957 (throw 'exit nil))
5958 (error "Not on a heading")))
5960 (defun org-goto-right ()
5961 "Finish `org-goto' by going to the new location."
5962 (interactive)
5963 (if (org-on-heading-p)
5964 (progn
5965 (setq org-goto-selected-point (point)
5966 org-goto-exit-command 'right)
5967 (throw 'exit nil))
5968 (error "Not on a heading")))
5970 (defun org-goto-quit ()
5971 "Finish `org-goto' without cursor motion."
5972 (interactive)
5973 (setq org-goto-selected-point nil)
5974 (setq org-goto-exit-command 'quit)
5975 (throw 'exit nil))
5977 ;;; Indirect buffer display of subtrees
5979 (defvar org-indirect-dedicated-frame nil
5980 "This is the frame being used for indirect tree display.")
5981 (defvar org-last-indirect-buffer nil)
5983 (defun org-tree-to-indirect-buffer (&optional arg)
5984 "Create indirect buffer and narrow it to current subtree.
5985 With numerical prefix ARG, go up to this level and then take that tree.
5986 If ARG is negative, go up that many levels.
5987 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5988 indirect buffer previously made with this command, to avoid proliferation of
5989 indirect buffers. However, when you call the command with a `C-u' prefix, or
5990 when `org-indirect-buffer-display' is `new-frame', the last buffer
5991 is kept so that you can work with several indirect buffers at the same time.
5992 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5993 requests that a new frame be made for the new buffer, so that the dedicated
5994 frame is not changed."
5995 (interactive "P")
5996 (let ((cbuf (current-buffer))
5997 (cwin (selected-window))
5998 (pos (point))
5999 beg end level heading ibuf)
6000 (save-excursion
6001 (org-back-to-heading t)
6002 (when (numberp arg)
6003 (setq level (org-outline-level))
6004 (if (< arg 0) (setq arg (+ level arg)))
6005 (while (> (setq level (org-outline-level)) arg)
6006 (outline-up-heading 1 t)))
6007 (setq beg (point)
6008 heading (org-get-heading))
6009 (org-end-of-subtree t) (setq end (point)))
6010 (if (and (buffer-live-p org-last-indirect-buffer)
6011 (not (eq org-indirect-buffer-display 'new-frame))
6012 (not arg))
6013 (kill-buffer org-last-indirect-buffer))
6014 (setq ibuf (org-get-indirect-buffer cbuf)
6015 org-last-indirect-buffer ibuf)
6016 (cond
6017 ((or (eq org-indirect-buffer-display 'new-frame)
6018 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6019 (select-frame (make-frame))
6020 (delete-other-windows)
6021 (switch-to-buffer ibuf)
6022 (org-set-frame-title heading))
6023 ((eq org-indirect-buffer-display 'dedicated-frame)
6024 (raise-frame
6025 (select-frame (or (and org-indirect-dedicated-frame
6026 (frame-live-p org-indirect-dedicated-frame)
6027 org-indirect-dedicated-frame)
6028 (setq org-indirect-dedicated-frame (make-frame)))))
6029 (delete-other-windows)
6030 (switch-to-buffer ibuf)
6031 (org-set-frame-title (concat "Indirect: " heading)))
6032 ((eq org-indirect-buffer-display 'current-window)
6033 (switch-to-buffer ibuf))
6034 ((eq org-indirect-buffer-display 'other-window)
6035 (pop-to-buffer ibuf))
6036 (t (error "Invalid value.")))
6037 (if (featurep 'xemacs)
6038 (save-excursion (org-mode) (turn-on-font-lock)))
6039 (narrow-to-region beg end)
6040 (show-all)
6041 (goto-char pos)
6042 (and (window-live-p cwin) (select-window cwin))))
6044 (defun org-get-indirect-buffer (&optional buffer)
6045 (setq buffer (or buffer (current-buffer)))
6046 (let ((n 1) (base (buffer-name buffer)) bname)
6047 (while (buffer-live-p
6048 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6049 (setq n (1+ n)))
6050 (condition-case nil
6051 (make-indirect-buffer buffer bname 'clone)
6052 (error (make-indirect-buffer buffer bname)))))
6054 (defun org-set-frame-title (title)
6055 "Set the title of the current frame to the string TITLE."
6056 ;; FIXME: how to name a single frame in XEmacs???
6057 (unless (featurep 'xemacs)
6058 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6060 ;;;; Structure editing
6062 ;;; Inserting headlines
6064 (defun org-insert-heading (&optional force-heading)
6065 "Insert a new heading or item with same depth at point.
6066 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6067 If point is at the beginning of a headline, insert a sibling before the
6068 current headline. If point is in the middle of a headline, split the headline
6069 at that position and make the rest of the headline part of the sibling below
6070 the current headline."
6071 (interactive "P")
6072 (if (= (buffer-size) 0)
6073 (insert "\n* ")
6074 (when (or force-heading (not (org-insert-item)))
6075 (let* ((head (save-excursion
6076 (condition-case nil
6077 (progn
6078 (org-back-to-heading)
6079 (match-string 0))
6080 (error "*"))))
6081 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6082 pos)
6083 (cond
6084 ((and (org-on-heading-p) (bolp)
6085 (or (bobp)
6086 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6087 (open-line (if blank 2 1)))
6088 ((and (bolp)
6089 (or (bobp)
6090 (save-excursion
6091 (backward-char 1) (not (org-invisible-p)))))
6092 nil)
6093 (t (newline (if blank 2 1))))
6094 (insert head) (just-one-space)
6095 (setq pos (point))
6096 (end-of-line 1)
6097 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6098 (run-hooks 'org-insert-heading-hook)))))
6100 (defun org-insert-heading-after-current ()
6101 "Insert a new heading with same level as current, after current subtree."
6102 (interactive)
6103 (org-back-to-heading)
6104 (org-insert-heading)
6105 (org-move-subtree-down)
6106 (end-of-line 1))
6108 (defun org-insert-todo-heading (arg)
6109 "Insert a new heading with the same level and TODO state as current heading.
6110 If the heading has no TODO state, or if the state is DONE, use the first
6111 state (TODO by default). Also with prefix arg, force first state."
6112 (interactive "P")
6113 (when (not (org-insert-item 'checkbox))
6114 (org-insert-heading)
6115 (save-excursion
6116 (org-back-to-heading)
6117 (outline-previous-heading)
6118 (looking-at org-todo-line-regexp))
6119 (if (or arg
6120 (not (match-beginning 2))
6121 (member (match-string 2) org-done-keywords))
6122 (insert (car org-todo-keywords-1) " ")
6123 (insert (match-string 2) " "))))
6125 (defun org-insert-subheading (arg)
6126 "Insert a new subheading and demote it.
6127 Works for outline headings and for plain lists alike."
6128 (interactive "P")
6129 (org-insert-heading arg)
6130 (cond
6131 ((org-on-heading-p) (org-do-demote))
6132 ((org-at-item-p) (org-indent-item 1))))
6134 (defun org-insert-todo-subheading (arg)
6135 "Insert a new subheading with TODO keyword or checkbox and demote it.
6136 Works for outline headings and for plain lists alike."
6137 (interactive "P")
6138 (org-insert-todo-heading arg)
6139 (cond
6140 ((org-on-heading-p) (org-do-demote))
6141 ((org-at-item-p) (org-indent-item 1))))
6143 ;;; Promotion and Demotion
6145 (defun org-promote-subtree ()
6146 "Promote the entire subtree.
6147 See also `org-promote'."
6148 (interactive)
6149 (save-excursion
6150 (org-map-tree 'org-promote))
6151 (org-fix-position-after-promote))
6153 (defun org-demote-subtree ()
6154 "Demote the entire subtree. See `org-demote'.
6155 See also `org-promote'."
6156 (interactive)
6157 (save-excursion
6158 (org-map-tree 'org-demote))
6159 (org-fix-position-after-promote))
6162 (defun org-do-promote ()
6163 "Promote the current heading higher up the tree.
6164 If the region is active in `transient-mark-mode', promote all headings
6165 in the region."
6166 (interactive)
6167 (save-excursion
6168 (if (org-region-active-p)
6169 (org-map-region 'org-promote (region-beginning) (region-end))
6170 (org-promote)))
6171 (org-fix-position-after-promote))
6173 (defun org-do-demote ()
6174 "Demote the current heading lower down the tree.
6175 If the region is active in `transient-mark-mode', demote all headings
6176 in the region."
6177 (interactive)
6178 (save-excursion
6179 (if (org-region-active-p)
6180 (org-map-region 'org-demote (region-beginning) (region-end))
6181 (org-demote)))
6182 (org-fix-position-after-promote))
6184 (defun org-fix-position-after-promote ()
6185 "Make sure that after pro/demotion cursor position is right."
6186 (let ((pos (point)))
6187 (when (save-excursion
6188 (beginning-of-line 1)
6189 (looking-at org-todo-line-regexp)
6190 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6191 (cond ((eobp) (insert " "))
6192 ((eolp) (insert " "))
6193 ((equal (char-after) ?\ ) (forward-char 1))))))
6195 (defun org-reduced-level (l)
6196 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6198 (defun org-get-valid-level (level &optional change)
6199 "Rectify a level change under the influence of `org-odd-levels-only'
6200 LEVEL is a current level, CHANGE is by how much the level should be
6201 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6202 even level numbers will become the next higher odd number."
6203 (if org-odd-levels-only
6204 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6205 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6206 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6207 (max 1 (+ level change))))
6209 (define-obsolete-function-alias 'org-get-legal-level
6210 'org-get-valid-level "23.1")
6212 (defun org-promote ()
6213 "Promote the current heading higher up the tree.
6214 If the region is active in `transient-mark-mode', promote all headings
6215 in the region."
6216 (org-back-to-heading t)
6217 (let* ((level (save-match-data (funcall outline-level)))
6218 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6219 (diff (abs (- level (length up-head) -1))))
6220 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6221 (replace-match up-head nil t)
6222 ;; Fixup tag positioning
6223 (and org-auto-align-tags (org-set-tags nil t))
6224 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6226 (defun org-demote ()
6227 "Demote the current heading lower down the tree.
6228 If the region is active in `transient-mark-mode', demote all headings
6229 in the region."
6230 (org-back-to-heading t)
6231 (let* ((level (save-match-data (funcall outline-level)))
6232 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6233 (diff (abs (- level (length down-head) -1))))
6234 (replace-match down-head nil t)
6235 ;; Fixup tag positioning
6236 (and org-auto-align-tags (org-set-tags nil t))
6237 (if org-adapt-indentation (org-fixup-indentation diff))))
6239 (defun org-map-tree (fun)
6240 "Call FUN for every heading underneath the current one."
6241 (org-back-to-heading)
6242 (let ((level (funcall outline-level)))
6243 (save-excursion
6244 (funcall fun)
6245 (while (and (progn
6246 (outline-next-heading)
6247 (> (funcall outline-level) level))
6248 (not (eobp)))
6249 (funcall fun)))))
6251 (defun org-map-region (fun beg end)
6252 "Call FUN for every heading between BEG and END."
6253 (let ((org-ignore-region t))
6254 (save-excursion
6255 (setq end (copy-marker end))
6256 (goto-char beg)
6257 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6258 (< (point) end))
6259 (funcall fun))
6260 (while (and (progn
6261 (outline-next-heading)
6262 (< (point) end))
6263 (not (eobp)))
6264 (funcall fun)))))
6266 (defun org-fixup-indentation (diff)
6267 "Change the indentation in the current entry by DIFF
6268 However, if any line in the current entry has no indentation, or if it
6269 would end up with no indentation after the change, nothing at all is done."
6270 (save-excursion
6271 (let ((end (save-excursion (outline-next-heading)
6272 (point-marker)))
6273 (prohibit (if (> diff 0)
6274 "^\\S-"
6275 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6276 col)
6277 (unless (save-excursion (end-of-line 1)
6278 (re-search-forward prohibit end t))
6279 (while (and (< (point) end)
6280 (re-search-forward "^[ \t]+" end t))
6281 (goto-char (match-end 0))
6282 (setq col (current-column))
6283 (if (< diff 0) (replace-match ""))
6284 (indent-to (+ diff col))))
6285 (move-marker end nil))))
6287 (defun org-convert-to-odd-levels ()
6288 "Convert an org-mode file with all levels allowed to one with odd levels.
6289 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6290 level 5 etc."
6291 (interactive)
6292 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6293 (let ((org-odd-levels-only nil) n)
6294 (save-excursion
6295 (goto-char (point-min))
6296 (while (re-search-forward "^\\*\\*+ " nil t)
6297 (setq n (- (length (match-string 0)) 2))
6298 (while (>= (setq n (1- n)) 0)
6299 (org-demote))
6300 (end-of-line 1))))))
6303 (defun org-convert-to-oddeven-levels ()
6304 "Convert an org-mode file with only odd levels to one with odd and even levels.
6305 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6306 section with an even level, conversion would destroy the structure of the file. An error
6307 is signaled in this case."
6308 (interactive)
6309 (goto-char (point-min))
6310 ;; First check if there are no even levels
6311 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6312 (org-show-context t)
6313 (error "Not all levels are odd in this file. Conversion not possible."))
6314 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6315 (let ((org-odd-levels-only nil) n)
6316 (save-excursion
6317 (goto-char (point-min))
6318 (while (re-search-forward "^\\*\\*+ " nil t)
6319 (setq n (/ (1- (length (match-string 0))) 2))
6320 (while (>= (setq n (1- n)) 0)
6321 (org-promote))
6322 (end-of-line 1))))))
6324 (defun org-tr-level (n)
6325 "Make N odd if required."
6326 (if org-odd-levels-only (1+ (/ n 2)) n))
6328 ;;; Vertical tree motion, cutting and pasting of subtrees
6330 (defun org-move-subtree-up (&optional arg)
6331 "Move the current subtree up past ARG headlines of the same level."
6332 (interactive "p")
6333 (org-move-subtree-down (- (prefix-numeric-value arg))))
6335 (defun org-move-subtree-down (&optional arg)
6336 "Move the current subtree down past ARG headlines of the same level."
6337 (interactive "p")
6338 (setq arg (prefix-numeric-value arg))
6339 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6340 'outline-get-last-sibling))
6341 (ins-point (make-marker))
6342 (cnt (abs arg))
6343 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6344 ;; Select the tree
6345 (org-back-to-heading)
6346 (setq beg0 (point))
6347 (save-excursion
6348 (setq ne-beg (org-back-over-empty-lines))
6349 (setq beg (point)))
6350 (save-match-data
6351 (save-excursion (outline-end-of-heading)
6352 (setq folded (org-invisible-p)))
6353 (outline-end-of-subtree))
6354 (outline-next-heading)
6355 (setq ne-end (org-back-over-empty-lines))
6356 (setq end (point))
6357 (goto-char beg0)
6358 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6359 ;; include less whitespace
6360 (save-excursion
6361 (goto-char beg)
6362 (forward-line (- ne-beg ne-end))
6363 (setq beg (point))))
6364 ;; Find insertion point, with error handling
6365 (while (> cnt 0)
6366 (or (and (funcall movfunc) (looking-at outline-regexp))
6367 (progn (goto-char beg0)
6368 (error "Cannot move past superior level or buffer limit")))
6369 (setq cnt (1- cnt)))
6370 (if (> arg 0)
6371 ;; Moving forward - still need to move over subtree
6372 (progn (org-end-of-subtree t t)
6373 (save-excursion
6374 (org-back-over-empty-lines)
6375 (or (bolp) (newline)))))
6376 (setq ne-ins (org-back-over-empty-lines))
6377 (move-marker ins-point (point))
6378 (setq txt (buffer-substring beg end))
6379 (delete-region beg end)
6380 (outline-flag-region (1- beg) beg nil)
6381 (outline-flag-region (1- (point)) (point) nil)
6382 (insert txt)
6383 (or (bolp) (insert "\n"))
6384 (setq ins-end (point))
6385 (goto-char ins-point)
6386 (org-skip-whitespace)
6387 (when (and (< arg 0)
6388 (org-first-sibling-p)
6389 (> ne-ins ne-beg))
6390 ;; Move whitespace back to beginning
6391 (save-excursion
6392 (goto-char ins-end)
6393 (let ((kill-whole-line t))
6394 (kill-line (- ne-ins ne-beg)) (point)))
6395 (insert (make-string (- ne-ins ne-beg) ?\n)))
6396 (move-marker ins-point nil)
6397 (org-compact-display-after-subtree-move)
6398 (unless folded
6399 (org-show-entry)
6400 (show-children)
6401 (org-cycle-hide-drawers 'children))))
6403 (defvar org-subtree-clip ""
6404 "Clipboard for cut and paste of subtrees.
6405 This is actually only a copy of the kill, because we use the normal kill
6406 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6408 (defvar org-subtree-clip-folded nil
6409 "Was the last copied subtree folded?
6410 This is used to fold the tree back after pasting.")
6412 (defun org-cut-subtree (&optional n)
6413 "Cut the current subtree into the clipboard.
6414 With prefix arg N, cut this many sequential subtrees.
6415 This is a short-hand for marking the subtree and then cutting it."
6416 (interactive "p")
6417 (org-copy-subtree n 'cut))
6419 (defun org-copy-subtree (&optional n cut)
6420 "Cut the current subtree into the clipboard.
6421 With prefix arg N, cut this many sequential subtrees.
6422 This is a short-hand for marking the subtree and then copying it.
6423 If CUT is non-nil, actually cut the subtree."
6424 (interactive "p")
6425 (let (beg end folded (beg0 (point)))
6426 (if (interactive-p)
6427 (org-back-to-heading nil) ; take what looks like a subtree
6428 (org-back-to-heading t)) ; take what is really there
6429 (org-back-over-empty-lines)
6430 (setq beg (point))
6431 (skip-chars-forward " \t\r\n")
6432 (save-match-data
6433 (save-excursion (outline-end-of-heading)
6434 (setq folded (org-invisible-p)))
6435 (condition-case nil
6436 (outline-forward-same-level (1- n))
6437 (error nil))
6438 (org-end-of-subtree t t))
6439 (org-back-over-empty-lines)
6440 (setq end (point))
6441 (goto-char beg0)
6442 (when (> end beg)
6443 (setq org-subtree-clip-folded folded)
6444 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6445 (setq org-subtree-clip (current-kill 0))
6446 (message "%s: Subtree(s) with %d characters"
6447 (if cut "Cut" "Copied")
6448 (length org-subtree-clip)))))
6450 (defun org-paste-subtree (&optional level tree)
6451 "Paste the clipboard as a subtree, with modification of headline level.
6452 The entire subtree is promoted or demoted in order to match a new headline
6453 level. By default, the new level is derived from the visible headings
6454 before and after the insertion point, and taken to be the inferior headline
6455 level of the two. So if the previous visible heading is level 3 and the
6456 next is level 4 (or vice versa), level 4 will be used for insertion.
6457 This makes sure that the subtree remains an independent subtree and does
6458 not swallow low level entries.
6460 You can also force a different level, either by using a numeric prefix
6461 argument, or by inserting the heading marker by hand. For example, if the
6462 cursor is after \"*****\", then the tree will be shifted to level 5.
6464 If you want to insert the tree as is, just use \\[yank].
6466 If optional TREE is given, use this text instead of the kill ring."
6467 (interactive "P")
6468 (unless (org-kill-is-subtree-p tree)
6469 (error "%s"
6470 (substitute-command-keys
6471 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6472 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6473 (^re (concat "^\\(" outline-regexp "\\)"))
6474 (re (concat "\\(" outline-regexp "\\)"))
6475 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6477 (old-level (if (string-match ^re txt)
6478 (- (match-end 0) (match-beginning 0) 1)
6479 -1))
6480 (force-level (cond (level (prefix-numeric-value level))
6481 ((string-match
6482 ^re_ (buffer-substring (point-at-bol) (point)))
6483 (- (match-end 1) (match-beginning 1)))
6484 (t nil)))
6485 (previous-level (save-excursion
6486 (condition-case nil
6487 (progn
6488 (outline-previous-visible-heading 1)
6489 (if (looking-at re)
6490 (- (match-end 0) (match-beginning 0) 1)
6492 (error 1))))
6493 (next-level (save-excursion
6494 (condition-case nil
6495 (progn
6496 (or (looking-at outline-regexp)
6497 (outline-next-visible-heading 1))
6498 (if (looking-at re)
6499 (- (match-end 0) (match-beginning 0) 1)
6501 (error 1))))
6502 (new-level (or force-level (max previous-level next-level)))
6503 (shift (if (or (= old-level -1)
6504 (= new-level -1)
6505 (= old-level new-level))
6507 (- new-level old-level)))
6508 (delta (if (> shift 0) -1 1))
6509 (func (if (> shift 0) 'org-demote 'org-promote))
6510 (org-odd-levels-only nil)
6511 beg end)
6512 ;; Remove the forced level indicator
6513 (if force-level
6514 (delete-region (point-at-bol) (point)))
6515 ;; Paste
6516 (beginning-of-line 1)
6517 (org-back-over-empty-lines) ;; FIXME: correct fix????
6518 (setq beg (point))
6519 (insert-before-markers txt) ;; FIXME: correct fix????
6520 (unless (string-match "\n\\'" txt) (insert "\n"))
6521 (setq end (point))
6522 (goto-char beg)
6523 (skip-chars-forward " \t\n\r")
6524 (setq beg (point))
6525 ;; Shift if necessary
6526 (unless (= shift 0)
6527 (save-restriction
6528 (narrow-to-region beg end)
6529 (while (not (= shift 0))
6530 (org-map-region func (point-min) (point-max))
6531 (setq shift (+ delta shift)))
6532 (goto-char (point-min))))
6533 (when (interactive-p)
6534 (message "Clipboard pasted as level %d subtree" new-level))
6535 (if (and kill-ring
6536 (eq org-subtree-clip (current-kill 0))
6537 org-subtree-clip-folded)
6538 ;; The tree was folded before it was killed/copied
6539 (hide-subtree))))
6541 (defun org-kill-is-subtree-p (&optional txt)
6542 "Check if the current kill is an outline subtree, or a set of trees.
6543 Returns nil if kill does not start with a headline, or if the first
6544 headline level is not the largest headline level in the tree.
6545 So this will actually accept several entries of equal levels as well,
6546 which is OK for `org-paste-subtree'.
6547 If optional TXT is given, check this string instead of the current kill."
6548 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6549 (start-level (and kill
6550 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6551 org-outline-regexp "\\)")
6552 kill)
6553 (- (match-end 2) (match-beginning 2) 1)))
6554 (re (concat "^" org-outline-regexp))
6555 (start (1+ (match-beginning 2))))
6556 (if (not start-level)
6557 (progn
6558 nil) ;; does not even start with a heading
6559 (catch 'exit
6560 (while (setq start (string-match re kill (1+ start)))
6561 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6562 (throw 'exit nil)))
6563 t))))
6565 (defun org-narrow-to-subtree ()
6566 "Narrow buffer to the current subtree."
6567 (interactive)
6568 (save-excursion
6569 (narrow-to-region
6570 (progn (org-back-to-heading) (point))
6571 (progn (org-end-of-subtree t t) (point)))))
6574 ;;; Outline Sorting
6576 (defun org-sort (with-case)
6577 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6578 Optional argument WITH-CASE means sort case-sensitively."
6579 (interactive "P")
6580 (if (org-at-table-p)
6581 (org-call-with-arg 'org-table-sort-lines with-case)
6582 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6584 (defvar org-priority-regexp) ; defined later in the file
6586 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6587 "Sort entries on a certain level of an outline tree.
6588 If there is an active region, the entries in the region are sorted.
6589 Else, if the cursor is before the first entry, sort the top-level items.
6590 Else, the children of the entry at point are sorted.
6592 Sorting can be alphabetically, numerically, and by date/time as given by
6593 the first time stamp in the entry. The command prompts for the sorting
6594 type unless it has been given to the function through the SORTING-TYPE
6595 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6596 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6597 called with point at the beginning of the record. It must return either
6598 a string or a number that should serve as the sorting key for that record.
6600 Comparing entries ignores case by default. However, with an optional argument
6601 WITH-CASE, the sorting considers case as well."
6602 (interactive "P")
6603 (let ((case-func (if with-case 'identity 'downcase))
6604 start beg end stars re re2
6605 txt what tmp plain-list-p)
6606 ;; Find beginning and end of region to sort
6607 (cond
6608 ((org-region-active-p)
6609 ;; we will sort the region
6610 (setq end (region-end)
6611 what "region")
6612 (goto-char (region-beginning))
6613 (if (not (org-on-heading-p)) (outline-next-heading))
6614 (setq start (point)))
6615 ((org-at-item-p)
6616 ;; we will sort this plain list
6617 (org-beginning-of-item-list) (setq start (point))
6618 (org-end-of-item-list) (setq end (point))
6619 (goto-char start)
6620 (setq plain-list-p t
6621 what "plain list"))
6622 ((or (org-on-heading-p)
6623 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6624 ;; we will sort the children of the current headline
6625 (org-back-to-heading)
6626 (setq start (point)
6627 end (progn (org-end-of-subtree t t)
6628 (org-back-over-empty-lines)
6629 (point))
6630 what "children")
6631 (goto-char start)
6632 (show-subtree)
6633 (outline-next-heading))
6635 ;; we will sort the top-level entries in this file
6636 (goto-char (point-min))
6637 (or (org-on-heading-p) (outline-next-heading))
6638 (setq start (point) end (point-max) what "top-level")
6639 (goto-char start)
6640 (show-all)))
6642 (setq beg (point))
6643 (if (>= beg end) (error "Nothing to sort"))
6645 (unless plain-list-p
6646 (looking-at "\\(\\*+\\)")
6647 (setq stars (match-string 1)
6648 re (concat "^" (regexp-quote stars) " +")
6649 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6650 txt (buffer-substring beg end))
6651 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6652 (if (and (not (equal stars "*")) (string-match re2 txt))
6653 (error "Region to sort contains a level above the first entry")))
6655 (unless sorting-type
6656 (message
6657 (if plain-list-p
6658 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6659 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6660 what)
6661 (setq sorting-type (read-char-exclusive))
6663 (and (= (downcase sorting-type) ?f)
6664 (setq getkey-func
6665 (completing-read "Sort using function: "
6666 obarray 'fboundp t nil nil))
6667 (setq getkey-func (intern getkey-func)))
6669 (and (= (downcase sorting-type) ?r)
6670 (setq property
6671 (completing-read "Property: "
6672 (mapcar 'list (org-buffer-property-keys t))
6673 nil t))))
6675 (message "Sorting entries...")
6677 (save-restriction
6678 (narrow-to-region start end)
6680 (let ((dcst (downcase sorting-type))
6681 (now (current-time)))
6682 (sort-subr
6683 (/= dcst sorting-type)
6684 ;; This function moves to the beginning character of the "record" to
6685 ;; be sorted.
6686 (if plain-list-p
6687 (lambda nil
6688 (if (org-at-item-p) t (goto-char (point-max))))
6689 (lambda nil
6690 (if (re-search-forward re nil t)
6691 (goto-char (match-beginning 0))
6692 (goto-char (point-max)))))
6693 ;; This function moves to the last character of the "record" being
6694 ;; sorted.
6695 (if plain-list-p
6696 'org-end-of-item
6697 (lambda nil
6698 (save-match-data
6699 (condition-case nil
6700 (outline-forward-same-level 1)
6701 (error
6702 (goto-char (point-max)))))))
6704 ;; This function returns the value that gets sorted against.
6705 (if plain-list-p
6706 (lambda nil
6707 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6708 (cond
6709 ((= dcst ?n)
6710 (string-to-number (buffer-substring (match-end 0)
6711 (point-at-eol))))
6712 ((= dcst ?a)
6713 (buffer-substring (match-end 0) (point-at-eol)))
6714 ((= dcst ?t)
6715 (if (re-search-forward org-ts-regexp
6716 (point-at-eol) t)
6717 (org-time-string-to-time (match-string 0))
6718 now))
6719 ((= dcst ?f)
6720 (if getkey-func
6721 (progn
6722 (setq tmp (funcall getkey-func))
6723 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6724 tmp)
6725 (error "Invalid key function `%s'" getkey-func)))
6726 (t (error "Invalid sorting type `%c'" sorting-type)))))
6727 (lambda nil
6728 (cond
6729 ((= dcst ?n)
6730 (if (looking-at outline-regexp)
6731 (string-to-number (buffer-substring (match-end 0)
6732 (point-at-eol)))
6733 nil))
6734 ((= dcst ?a)
6735 (funcall case-func (buffer-substring (point-at-bol)
6736 (point-at-eol))))
6737 ((= dcst ?t)
6738 (if (re-search-forward org-ts-regexp
6739 (save-excursion
6740 (forward-line 2)
6741 (point)) t)
6742 (org-time-string-to-time (match-string 0))
6743 now))
6744 ((= dcst ?p)
6745 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6746 (string-to-char (match-string 2))
6747 org-default-priority))
6748 ((= dcst ?r)
6749 (or (org-entry-get nil property) ""))
6750 ((= dcst ?f)
6751 (if getkey-func
6752 (progn
6753 (setq tmp (funcall getkey-func))
6754 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6755 tmp)
6756 (error "Invalid key function `%s'" getkey-func)))
6757 (t (error "Invalid sorting type `%c'" sorting-type)))))
6759 (cond
6760 ((= dcst ?a) 'string<)
6761 ((= dcst ?t) 'time-less-p)
6762 (t nil)))))
6763 (message "Sorting entries...done")))
6765 (defun org-do-sort (table what &optional with-case sorting-type)
6766 "Sort TABLE of WHAT according to SORTING-TYPE.
6767 The user will be prompted for the SORTING-TYPE if the call to this
6768 function does not specify it. WHAT is only for the prompt, to indicate
6769 what is being sorted. The sorting key will be extracted from
6770 the car of the elements of the table.
6771 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6772 (unless sorting-type
6773 (message
6774 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6775 what)
6776 (setq sorting-type (read-char-exclusive)))
6777 (let ((dcst (downcase sorting-type))
6778 extractfun comparefun)
6779 ;; Define the appropriate functions
6780 (cond
6781 ((= dcst ?n)
6782 (setq extractfun 'string-to-number
6783 comparefun (if (= dcst sorting-type) '< '>)))
6784 ((= dcst ?a)
6785 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6786 (lambda(x) (downcase (org-sort-remove-invisible x))))
6787 comparefun (if (= dcst sorting-type)
6788 'string<
6789 (lambda (a b) (and (not (string< a b))
6790 (not (string= a b)))))))
6791 ((= dcst ?t)
6792 (setq extractfun
6793 (lambda (x)
6794 (if (string-match org-ts-regexp x)
6795 (time-to-seconds
6796 (org-time-string-to-time (match-string 0 x)))
6798 comparefun (if (= dcst sorting-type) '< '>)))
6799 (t (error "Invalid sorting type `%c'" sorting-type)))
6801 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6802 table)
6803 (lambda (a b) (funcall comparefun (car a) (car b))))))
6805 ;;;; Plain list items, including checkboxes
6807 ;;; Plain list items
6809 (defun org-at-item-p ()
6810 "Is point in a line starting a hand-formatted item?"
6811 (let ((llt org-plain-list-ordered-item-terminator))
6812 (save-excursion
6813 (goto-char (point-at-bol))
6814 (looking-at
6815 (cond
6816 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6817 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6818 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6819 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6821 (defun org-in-item-p ()
6822 "It the cursor inside a plain list item.
6823 Does not have to be the first line."
6824 (save-excursion
6825 (condition-case nil
6826 (progn
6827 (org-beginning-of-item)
6828 (org-at-item-p)
6830 (error nil))))
6832 (defun org-insert-item (&optional checkbox)
6833 "Insert a new item at the current level.
6834 Return t when things worked, nil when we are not in an item."
6835 (when (save-excursion
6836 (condition-case nil
6837 (progn
6838 (org-beginning-of-item)
6839 (org-at-item-p)
6840 (if (org-invisible-p) (error "Invisible item"))
6842 (error nil)))
6843 (let* ((bul (match-string 0))
6844 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6845 (match-end 0)))
6846 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6847 pos)
6848 (cond
6849 ((and (org-at-item-p) (<= (point) eow))
6850 ;; before the bullet
6851 (beginning-of-line 1)
6852 (open-line (if blank 2 1)))
6853 ((<= (point) eow)
6854 (beginning-of-line 1))
6855 (t (newline (if blank 2 1))))
6856 (insert bul (if checkbox "[ ]" ""))
6857 (just-one-space)
6858 (setq pos (point))
6859 (end-of-line 1)
6860 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6861 (org-maybe-renumber-ordered-list)
6862 (and checkbox (org-update-checkbox-count-maybe))
6865 ;;; Checkboxes
6867 (defun org-at-item-checkbox-p ()
6868 "Is point at a line starting a plain-list item with a checklet?"
6869 (and (org-at-item-p)
6870 (save-excursion
6871 (goto-char (match-end 0))
6872 (skip-chars-forward " \t")
6873 (looking-at "\\[[- X]\\]"))))
6875 (defun org-toggle-checkbox (&optional arg)
6876 "Toggle the checkbox in the current line."
6877 (interactive "P")
6878 (catch 'exit
6879 (let (beg end status (firstnew 'unknown))
6880 (cond
6881 ((org-region-active-p)
6882 (setq beg (region-beginning) end (region-end)))
6883 ((org-on-heading-p)
6884 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6885 ((org-at-item-checkbox-p)
6886 (let ((pos (point)))
6887 (replace-match
6888 (cond (arg "[-]")
6889 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6890 (t "[ ]"))
6891 t t)
6892 (goto-char pos))
6893 (throw 'exit t))
6894 (t (error "Not at a checkbox or heading, and no active region")))
6895 (save-excursion
6896 (goto-char beg)
6897 (while (< (point) end)
6898 (when (org-at-item-checkbox-p)
6899 (setq status (equal (match-string 0) "[X]"))
6900 (when (eq firstnew 'unknown)
6901 (setq firstnew (not status)))
6902 (replace-match
6903 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6904 (beginning-of-line 2)))))
6905 (org-update-checkbox-count-maybe))
6907 (defun org-update-checkbox-count-maybe ()
6908 "Update checkbox statistics unless turned off by user."
6909 (when org-provide-checkbox-statistics
6910 (org-update-checkbox-count)))
6912 (defun org-update-checkbox-count (&optional all)
6913 "Update the checkbox statistics in the current section.
6914 This will find all statistic cookies like [57%] and [6/12] and update them
6915 with the current numbers. With optional prefix argument ALL, do this for
6916 the whole buffer."
6917 (interactive "P")
6918 (save-excursion
6919 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6920 (beg (condition-case nil
6921 (progn (outline-back-to-heading) (point))
6922 (error (point-min))))
6923 (end (move-marker (make-marker)
6924 (progn (outline-next-heading) (point))))
6925 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6926 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6927 b1 e1 f1 c-on c-off lim (cstat 0))
6928 (when all
6929 (goto-char (point-min))
6930 (outline-next-heading)
6931 (setq beg (point) end (point-max)))
6932 (goto-char beg)
6933 (while (re-search-forward re end t)
6934 (setq cstat (1+ cstat)
6935 b1 (match-beginning 0)
6936 e1 (match-end 0)
6937 f1 (match-beginning 1)
6938 lim (cond
6939 ((org-on-heading-p) (outline-next-heading) (point))
6940 ((org-at-item-p) (org-end-of-item) (point))
6941 (t nil))
6942 c-on 0 c-off 0)
6943 (goto-char e1)
6944 (when lim
6945 (while (re-search-forward re-box lim t)
6946 (if (member (match-string 2) '("[ ]" "[-]"))
6947 (setq c-off (1+ c-off))
6948 (setq c-on (1+ c-on))))
6949 ; (delete-region b1 e1)
6950 (goto-char b1)
6951 (insert (if f1
6952 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6953 (format "[%d/%d]" c-on (+ c-on c-off))))
6954 (and (looking-at "\\[.*?\\]")
6955 (replace-match ""))))
6956 (when (interactive-p)
6957 (message "Checkbox satistics updated %s (%d places)"
6958 (if all "in entire file" "in current outline entry") cstat)))))
6960 (defun org-get-checkbox-statistics-face ()
6961 "Select the face for checkbox statistics.
6962 The face will be `org-done' when all relevant boxes are checked. Otherwise
6963 it will be `org-todo'."
6964 (if (match-end 1)
6965 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6966 (if (and (> (match-end 2) (match-beginning 2))
6967 (equal (match-string 2) (match-string 3)))
6968 'org-done
6969 'org-todo)))
6971 (defun org-get-indentation (&optional line)
6972 "Get the indentation of the current line, interpreting tabs.
6973 When LINE is given, assume it represents a line and compute its indentation."
6974 (if line
6975 (if (string-match "^ *" (org-remove-tabs line))
6976 (match-end 0))
6977 (save-excursion
6978 (beginning-of-line 1)
6979 (skip-chars-forward " \t")
6980 (current-column))))
6982 (defun org-remove-tabs (s &optional width)
6983 "Replace tabulators in S with spaces.
6984 Assumes that s is a single line, starting in column 0."
6985 (setq width (or width tab-width))
6986 (while (string-match "\t" s)
6987 (setq s (replace-match
6988 (make-string
6989 (- (* width (/ (+ (match-beginning 0) width) width))
6990 (match-beginning 0)) ?\ )
6991 t t s)))
6994 (defun org-fix-indentation (line ind)
6995 "Fix indentation in LINE.
6996 IND is a cons cell with target and minimum indentation.
6997 If the current indenation in LINE is smaller than the minimum,
6998 leave it alone. If it is larger than ind, set it to the target."
6999 (let* ((l (org-remove-tabs line))
7000 (i (org-get-indentation l))
7001 (i1 (car ind)) (i2 (cdr ind)))
7002 (if (>= i i2) (setq l (substring line i2)))
7003 (if (> i1 0)
7004 (concat (make-string i1 ?\ ) l)
7005 l)))
7007 (defcustom org-empty-line-terminates-plain-lists nil
7008 "Non-nil means, an empty line ends all plain list levels.
7009 When nil, empty lines are part of the preceeding item."
7010 :group 'org-plain-lists
7011 :type 'boolean)
7013 (defun org-beginning-of-item ()
7014 "Go to the beginning of the current hand-formatted item.
7015 If the cursor is not in an item, throw an error."
7016 (interactive)
7017 (let ((pos (point))
7018 (limit (save-excursion
7019 (condition-case nil
7020 (progn
7021 (org-back-to-heading)
7022 (beginning-of-line 2) (point))
7023 (error (point-min)))))
7024 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7025 ind ind1)
7026 (if (org-at-item-p)
7027 (beginning-of-line 1)
7028 (beginning-of-line 1)
7029 (skip-chars-forward " \t")
7030 (setq ind (current-column))
7031 (if (catch 'exit
7032 (while t
7033 (beginning-of-line 0)
7034 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7036 (if (looking-at "[ \t]*$")
7037 (setq ind1 ind-empty)
7038 (skip-chars-forward " \t")
7039 (setq ind1 (current-column)))
7040 (if (< ind1 ind)
7041 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7043 (goto-char pos)
7044 (error "Not in an item")))))
7046 (defun org-end-of-item ()
7047 "Go to the end of the current hand-formatted item.
7048 If the cursor is not in an item, throw an error."
7049 (interactive)
7050 (let* ((pos (point))
7051 ind1
7052 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7053 (limit (save-excursion (outline-next-heading) (point)))
7054 (ind (save-excursion
7055 (org-beginning-of-item)
7056 (skip-chars-forward " \t")
7057 (current-column)))
7058 (end (catch 'exit
7059 (while t
7060 (beginning-of-line 2)
7061 (if (eobp) (throw 'exit (point)))
7062 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7063 (if (looking-at "[ \t]*$")
7064 (setq ind1 ind-empty)
7065 (skip-chars-forward " \t")
7066 (setq ind1 (current-column)))
7067 (if (<= ind1 ind)
7068 (throw 'exit (point-at-bol)))))))
7069 (if end
7070 (goto-char end)
7071 (goto-char pos)
7072 (error "Not in an item"))))
7074 (defun org-next-item ()
7075 "Move to the beginning of the next item in the current plain list.
7076 Error if not at a plain list, or if this is the last item in the list."
7077 (interactive)
7078 (let (ind ind1 (pos (point)))
7079 (org-beginning-of-item)
7080 (setq ind (org-get-indentation))
7081 (org-end-of-item)
7082 (setq ind1 (org-get-indentation))
7083 (unless (and (org-at-item-p) (= ind ind1))
7084 (goto-char pos)
7085 (error "On last item"))))
7087 (defun org-previous-item ()
7088 "Move to the beginning of the previous item in the current plain list.
7089 Error if not at a plain list, or if this is the first item in the list."
7090 (interactive)
7091 (let (beg ind ind1 (pos (point)))
7092 (org-beginning-of-item)
7093 (setq beg (point))
7094 (setq ind (org-get-indentation))
7095 (goto-char beg)
7096 (catch 'exit
7097 (while t
7098 (beginning-of-line 0)
7099 (if (looking-at "[ \t]*$")
7101 (if (<= (setq ind1 (org-get-indentation)) ind)
7102 (throw 'exit t)))))
7103 (condition-case nil
7104 (if (or (not (org-at-item-p))
7105 (< ind1 (1- ind)))
7106 (error "")
7107 (org-beginning-of-item))
7108 (error (goto-char pos)
7109 (error "On first item")))))
7111 (defun org-first-list-item-p ()
7112 "Is this heading the item in a plain list?"
7113 (unless (org-at-item-p)
7114 (error "Not at a plain list item"))
7115 (org-beginning-of-item)
7116 (= (point) (save-excursion (org-beginning-of-item-list))))
7118 (defun org-move-item-down ()
7119 "Move the plain list item at point down, i.e. swap with following item.
7120 Subitems (items with larger indentation) are considered part of the item,
7121 so this really moves item trees."
7122 (interactive)
7123 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7124 (org-beginning-of-item)
7125 (setq beg0 (point))
7126 (save-excursion
7127 (setq ne-beg (org-back-over-empty-lines))
7128 (setq beg (point)))
7129 (goto-char beg0)
7130 (setq ind (org-get-indentation))
7131 (org-end-of-item)
7132 (setq end0 (point))
7133 (setq ind1 (org-get-indentation))
7134 (setq ne-end (org-back-over-empty-lines))
7135 (setq end (point))
7136 (goto-char beg0)
7137 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7138 ;; include less whitespace
7139 (save-excursion
7140 (goto-char beg)
7141 (forward-line (- ne-beg ne-end))
7142 (setq beg (point))))
7143 (goto-char end0)
7144 (if (and (org-at-item-p) (= ind ind1))
7145 (progn
7146 (org-end-of-item)
7147 (org-back-over-empty-lines)
7148 (setq txt (buffer-substring beg end))
7149 (save-excursion
7150 (delete-region beg end))
7151 (setq pos (point))
7152 (insert txt)
7153 (goto-char pos) (org-skip-whitespace)
7154 (org-maybe-renumber-ordered-list))
7155 (goto-char pos)
7156 (error "Cannot move this item further down"))))
7158 (defun org-move-item-up (arg)
7159 "Move the plain list item at point up, i.e. swap with previous item.
7160 Subitems (items with larger indentation) are considered part of the item,
7161 so this really moves item trees."
7162 (interactive "p")
7163 (let (beg beg0 end end0 ind ind1 (pos (point)) txt
7164 ne-beg ne-end ne-ins ins-end)
7165 (org-beginning-of-item)
7166 (setq beg0 (point))
7167 (setq ind (org-get-indentation))
7168 (save-excursion
7169 (setq ne-beg (org-back-over-empty-lines))
7170 (setq beg (point)))
7171 (goto-char beg0)
7172 (org-end-of-item)
7173 (setq ne-end (org-back-over-empty-lines))
7174 (setq end (point))
7175 (goto-char beg0)
7176 (catch 'exit
7177 (while t
7178 (beginning-of-line 0)
7179 (if (looking-at "[ \t]*$")
7180 (if org-empty-line-terminates-plain-lists
7181 (progn
7182 (goto-char pos)
7183 (error "Cannot move this item further up"))
7184 nil)
7185 (if (<= (setq ind1 (org-get-indentation)) ind)
7186 (throw 'exit t)))))
7187 (condition-case nil
7188 (org-beginning-of-item)
7189 (error (goto-char beg)
7190 (error "Cannot move this item further up")))
7191 (setq ind1 (org-get-indentation))
7192 (if (and (org-at-item-p) (= ind ind1))
7193 (progn
7194 (setq ne-ins (org-back-over-empty-lines))
7195 (setq txt (buffer-substring beg end))
7196 (save-excursion
7197 (delete-region beg end))
7198 (setq pos (point))
7199 (insert txt)
7200 (setq ins-end (point))
7201 (goto-char pos) (org-skip-whitespace)
7203 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7204 ;; Move whitespace back to beginning
7205 (save-excursion
7206 (goto-char ins-end)
7207 (let ((kill-whole-line t))
7208 (kill-line (- ne-ins ne-beg)) (point)))
7209 (insert (make-string (- ne-ins ne-beg) ?\n)))
7211 (org-maybe-renumber-ordered-list))
7212 (goto-char pos)
7213 (error "Cannot move this item further up"))))
7215 (defun org-maybe-renumber-ordered-list ()
7216 "Renumber the ordered list at point if setup allows it.
7217 This tests the user option `org-auto-renumber-ordered-lists' before
7218 doing the renumbering."
7219 (interactive)
7220 (when (and org-auto-renumber-ordered-lists
7221 (org-at-item-p))
7222 (if (match-beginning 3)
7223 (org-renumber-ordered-list 1)
7224 (org-fix-bullet-type))))
7226 (defun org-maybe-renumber-ordered-list-safe ()
7227 (condition-case nil
7228 (save-excursion
7229 (org-maybe-renumber-ordered-list))
7230 (error nil)))
7232 (defun org-cycle-list-bullet (&optional which)
7233 "Cycle through the different itemize/enumerate bullets.
7234 This cycle the entire list level through the sequence:
7236 `-' -> `+' -> `*' -> `1.' -> `1)'
7238 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7239 0 meand `-', 1 means `+' etc."
7240 (interactive "P")
7241 (org-preserve-lc
7242 (org-beginning-of-item-list)
7243 (org-at-item-p)
7244 (beginning-of-line 1)
7245 (let ((current (match-string 0))
7246 (prevp (eq which 'previous))
7247 new)
7248 (setq new (cond
7249 ((and (numberp which)
7250 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7251 ((string-match "-" current) (if prevp "1)" "+"))
7252 ((string-match "\\+" current)
7253 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7254 ((string-match "\\*" current) (if prevp "+" "1."))
7255 ((string-match "\\." current) (if prevp "*" "1)"))
7256 ((string-match ")" current) (if prevp "1." "-"))
7257 (t (error "This should not happen"))))
7258 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7259 (org-fix-bullet-type)
7260 (org-maybe-renumber-ordered-list))))
7262 (defun org-get-string-indentation (s)
7263 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7264 (let ((n -1) (i 0) (w tab-width) c)
7265 (catch 'exit
7266 (while (< (setq n (1+ n)) (length s))
7267 (setq c (aref s n))
7268 (cond ((= c ?\ ) (setq i (1+ i)))
7269 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7270 (t (throw 'exit t)))))
7273 (defun org-renumber-ordered-list (arg)
7274 "Renumber an ordered plain list.
7275 Cursor needs to be in the first line of an item, the line that starts
7276 with something like \"1.\" or \"2)\"."
7277 (interactive "p")
7278 (unless (and (org-at-item-p)
7279 (match-beginning 3))
7280 (error "This is not an ordered list"))
7281 (let ((line (org-current-line))
7282 (col (current-column))
7283 (ind (org-get-string-indentation
7284 (buffer-substring (point-at-bol) (match-beginning 3))))
7285 ;; (term (substring (match-string 3) -1))
7286 ind1 (n (1- arg))
7287 fmt)
7288 ;; find where this list begins
7289 (org-beginning-of-item-list)
7290 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7291 (setq fmt (concat "%d" (match-string 1)))
7292 (beginning-of-line 0)
7293 ;; walk forward and replace these numbers
7294 (catch 'exit
7295 (while t
7296 (catch 'next
7297 (beginning-of-line 2)
7298 (if (eobp) (throw 'exit nil))
7299 (if (looking-at "[ \t]*$") (throw 'next nil))
7300 (skip-chars-forward " \t") (setq ind1 (current-column))
7301 (if (> ind1 ind) (throw 'next t))
7302 (if (< ind1 ind) (throw 'exit t))
7303 (if (not (org-at-item-p)) (throw 'exit nil))
7304 (delete-region (match-beginning 2) (match-end 2))
7305 (goto-char (match-beginning 2))
7306 (insert (format fmt (setq n (1+ n)))))))
7307 (goto-line line)
7308 (move-to-column col)))
7310 (defun org-fix-bullet-type ()
7311 "Make sure all items in this list have the same bullet as the firsst item."
7312 (interactive)
7313 (unless (org-at-item-p) (error "This is not a list"))
7314 (let ((line (org-current-line))
7315 (col (current-column))
7316 (ind (current-indentation))
7317 ind1 bullet)
7318 ;; find where this list begins
7319 (org-beginning-of-item-list)
7320 (beginning-of-line 1)
7321 ;; find out what the bullet type is
7322 (looking-at "[ \t]*\\(\\S-+\\)")
7323 (setq bullet (match-string 1))
7324 ;; walk forward and replace these numbers
7325 (beginning-of-line 0)
7326 (catch 'exit
7327 (while t
7328 (catch 'next
7329 (beginning-of-line 2)
7330 (if (eobp) (throw 'exit nil))
7331 (if (looking-at "[ \t]*$") (throw 'next nil))
7332 (skip-chars-forward " \t") (setq ind1 (current-column))
7333 (if (> ind1 ind) (throw 'next t))
7334 (if (< ind1 ind) (throw 'exit t))
7335 (if (not (org-at-item-p)) (throw 'exit nil))
7336 (skip-chars-forward " \t")
7337 (looking-at "\\S-+")
7338 (replace-match bullet))))
7339 (goto-line line)
7340 (move-to-column col)
7341 (if (string-match "[0-9]" bullet)
7342 (org-renumber-ordered-list 1))))
7344 (defun org-beginning-of-item-list ()
7345 "Go to the beginning of the current item list.
7346 I.e. to the first item in this list."
7347 (interactive)
7348 (org-beginning-of-item)
7349 (let ((pos (point-at-bol))
7350 (ind (org-get-indentation))
7351 ind1)
7352 ;; find where this list begins
7353 (catch 'exit
7354 (while t
7355 (catch 'next
7356 (beginning-of-line 0)
7357 (if (looking-at "[ \t]*$")
7358 (throw (if (bobp) 'exit 'next) t))
7359 (skip-chars-forward " \t") (setq ind1 (current-column))
7360 (if (or (< ind1 ind)
7361 (and (= ind1 ind)
7362 (not (org-at-item-p)))
7363 (bobp))
7364 (throw 'exit t)
7365 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7366 (goto-char pos)))
7369 (defun org-end-of-item-list ()
7370 "Go to the end of the current item list.
7371 I.e. to the text after the last item."
7372 (interactive)
7373 (org-beginning-of-item)
7374 (let ((pos (point-at-bol))
7375 (ind (org-get-indentation))
7376 ind1)
7377 ;; find where this list begins
7378 (catch 'exit
7379 (while t
7380 (catch 'next
7381 (beginning-of-line 2)
7382 (if (looking-at "[ \t]*$")
7383 (throw (if (eobp) 'exit 'next) t))
7384 (skip-chars-forward " \t") (setq ind1 (current-column))
7385 (if (or (< ind1 ind)
7386 (and (= ind1 ind)
7387 (not (org-at-item-p)))
7388 (eobp))
7389 (progn
7390 (setq pos (point-at-bol))
7391 (throw 'exit t))))))
7392 (goto-char pos)))
7395 (defvar org-last-indent-begin-marker (make-marker))
7396 (defvar org-last-indent-end-marker (make-marker))
7398 (defun org-outdent-item (arg)
7399 "Outdent a local list item."
7400 (interactive "p")
7401 (org-indent-item (- arg)))
7403 (defun org-indent-item (arg)
7404 "Indent a local list item."
7405 (interactive "p")
7406 (unless (org-at-item-p)
7407 (error "Not on an item"))
7408 (save-excursion
7409 (let (beg end ind ind1 tmp delta ind-down ind-up)
7410 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7411 (setq beg org-last-indent-begin-marker
7412 end org-last-indent-end-marker)
7413 (org-beginning-of-item)
7414 (setq beg (move-marker org-last-indent-begin-marker (point)))
7415 (org-end-of-item)
7416 (setq end (move-marker org-last-indent-end-marker (point))))
7417 (goto-char beg)
7418 (setq tmp (org-item-indent-positions)
7419 ind (car tmp)
7420 ind-down (nth 2 tmp)
7421 ind-up (nth 1 tmp)
7422 delta (if (> arg 0)
7423 (if ind-down (- ind-down ind) 2)
7424 (if ind-up (- ind-up ind) -2)))
7425 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7426 (while (< (point) end)
7427 (beginning-of-line 1)
7428 (skip-chars-forward " \t") (setq ind1 (current-column))
7429 (delete-region (point-at-bol) (point))
7430 (or (eolp) (indent-to-column (+ ind1 delta)))
7431 (beginning-of-line 2))))
7432 (org-fix-bullet-type)
7433 (org-maybe-renumber-ordered-list-safe)
7434 (save-excursion
7435 (beginning-of-line 0)
7436 (condition-case nil (org-beginning-of-item) (error nil))
7437 (org-maybe-renumber-ordered-list-safe)))
7439 (defun org-item-indent-positions ()
7440 "Return indentation for plain list items.
7441 This returns a list with three values: The current indentation, the
7442 parent indentation and the indentation a child should habe.
7443 Assumes cursor in item line."
7444 (let* ((bolpos (point-at-bol))
7445 (ind (org-get-indentation))
7446 ind-down ind-up pos)
7447 (save-excursion
7448 (org-beginning-of-item-list)
7449 (skip-chars-backward "\n\r \t")
7450 (when (org-in-item-p)
7451 (org-beginning-of-item)
7452 (setq ind-up (org-get-indentation))))
7453 (setq pos (point))
7454 (save-excursion
7455 (cond
7456 ((and (condition-case nil (progn (org-previous-item) t)
7457 (error nil))
7458 (or (forward-char 1) t)
7459 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7460 (setq ind-down (org-get-indentation)))
7461 ((and (goto-char pos)
7462 (org-at-item-p))
7463 (goto-char (match-end 0))
7464 (skip-chars-forward " \t")
7465 (setq ind-down (current-column)))))
7466 (list ind ind-up ind-down)))
7468 ;;; The orgstruct minor mode
7470 ;; Define a minor mode which can be used in other modes in order to
7471 ;; integrate the org-mode structure editing commands.
7473 ;; This is really a hack, because the org-mode structure commands use
7474 ;; keys which normally belong to the major mode. Here is how it
7475 ;; works: The minor mode defines all the keys necessary to operate the
7476 ;; structure commands, but wraps the commands into a function which
7477 ;; tests if the cursor is currently at a headline or a plain list
7478 ;; item. If that is the case, the structure command is used,
7479 ;; temporarily setting many Org-mode variables like regular
7480 ;; expressions for filling etc. However, when any of those keys is
7481 ;; used at a different location, function uses `key-binding' to look
7482 ;; up if the key has an associated command in another currently active
7483 ;; keymap (minor modes, major mode, global), and executes that
7484 ;; command. There might be problems if any of the keys is otherwise
7485 ;; used as a prefix key.
7487 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7488 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7489 ;; addresses this by checking explicitly for both bindings.
7491 (defvar orgstruct-mode-map (make-sparse-keymap)
7492 "Keymap for the minor `orgstruct-mode'.")
7494 (defvar org-local-vars nil
7495 "List of local variables, for use by `orgstruct-mode'")
7497 ;;;###autoload
7498 (define-minor-mode orgstruct-mode
7499 "Toggle the minor more `orgstruct-mode'.
7500 This mode is for using Org-mode structure commands in other modes.
7501 The following key behave as if Org-mode was active, if the cursor
7502 is on a headline, or on a plain list item (both in the definition
7503 of Org-mode).
7505 M-up Move entry/item up
7506 M-down Move entry/item down
7507 M-left Promote
7508 M-right Demote
7509 M-S-up Move entry/item up
7510 M-S-down Move entry/item down
7511 M-S-left Promote subtree
7512 M-S-right Demote subtree
7513 M-q Fill paragraph and items like in Org-mode
7514 C-c ^ Sort entries
7515 C-c - Cycle list bullet
7516 TAB Cycle item visibility
7517 M-RET Insert new heading/item
7518 S-M-RET Insert new TODO heading / Chekbox item
7519 C-c C-c Set tags / toggle checkbox"
7520 nil " OrgStruct" nil
7521 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7523 ;;;###autoload
7524 (defun turn-on-orgstruct ()
7525 "Unconditionally turn on `orgstruct-mode'."
7526 (orgstruct-mode 1))
7528 ;;;###autoload
7529 (defun turn-on-orgstruct++ ()
7530 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7531 In addition to setting orgstruct-mode, this also exports all indentation and
7532 autofilling variables from org-mode into the buffer. Note that turning
7533 off orgstruct-mode will *not* remove these additional settings."
7534 (orgstruct-mode 1)
7535 (let (var val)
7536 (mapc
7537 (lambda (x)
7538 (when (string-match
7539 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7540 (symbol-name (car x)))
7541 (setq var (car x) val (nth 1 x))
7542 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7543 org-local-vars)))
7545 (defun orgstruct-error ()
7546 "Error when there is no default binding for a structure key."
7547 (interactive)
7548 (error "This key has no function outside structure elements"))
7550 (defun orgstruct-setup ()
7551 "Setup orgstruct keymaps."
7552 (let ((nfunc 0)
7553 (bindings
7554 (list
7555 '([(meta up)] org-metaup)
7556 '([(meta down)] org-metadown)
7557 '([(meta left)] org-metaleft)
7558 '([(meta right)] org-metaright)
7559 '([(meta shift up)] org-shiftmetaup)
7560 '([(meta shift down)] org-shiftmetadown)
7561 '([(meta shift left)] org-shiftmetaleft)
7562 '([(meta shift right)] org-shiftmetaright)
7563 '([(shift up)] org-shiftup)
7564 '([(shift down)] org-shiftdown)
7565 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7566 '("\M-q" fill-paragraph)
7567 '("\C-c^" org-sort)
7568 '("\C-c-" org-cycle-list-bullet)))
7569 elt key fun cmd)
7570 (while (setq elt (pop bindings))
7571 (setq nfunc (1+ nfunc))
7572 (setq key (org-key (car elt))
7573 fun (nth 1 elt)
7574 cmd (orgstruct-make-binding fun nfunc key))
7575 (org-defkey orgstruct-mode-map key cmd))
7577 ;; Special treatment needed for TAB and RET
7578 (org-defkey orgstruct-mode-map [(tab)]
7579 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7580 (org-defkey orgstruct-mode-map "\C-i"
7581 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7583 (org-defkey orgstruct-mode-map "\M-\C-m"
7584 (orgstruct-make-binding 'org-insert-heading 105
7585 "\M-\C-m" [(meta return)]))
7586 (org-defkey orgstruct-mode-map [(meta return)]
7587 (orgstruct-make-binding 'org-insert-heading 106
7588 [(meta return)] "\M-\C-m"))
7590 (org-defkey orgstruct-mode-map [(shift meta return)]
7591 (orgstruct-make-binding 'org-insert-todo-heading 107
7592 [(meta return)] "\M-\C-m"))
7594 (unless org-local-vars
7595 (setq org-local-vars (org-get-local-variables)))
7599 (defun orgstruct-make-binding (fun n &rest keys)
7600 "Create a function for binding in the structure minor mode.
7601 FUN is the command to call inside a table. N is used to create a unique
7602 command name. KEYS are keys that should be checked in for a command
7603 to execute outside of tables."
7604 (eval
7605 (list 'defun
7606 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7607 '(arg)
7608 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7609 "Outside of structure, run the binding of `"
7610 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7611 "'.")
7612 '(interactive "p")
7613 (list 'if
7614 '(org-context-p 'headline 'item)
7615 (list 'org-run-like-in-org-mode (list 'quote fun))
7616 (list 'let '(orgstruct-mode)
7617 (list 'call-interactively
7618 (append '(or)
7619 (mapcar (lambda (k)
7620 (list 'key-binding k))
7621 keys)
7622 '('orgstruct-error))))))))
7624 (defun org-context-p (&rest contexts)
7625 "Check if local context is and of CONTEXTS.
7626 Possible values in the list of contexts are `table', `headline', and `item'."
7627 (let ((pos (point)))
7628 (goto-char (point-at-bol))
7629 (prog1 (or (and (memq 'table contexts)
7630 (looking-at "[ \t]*|"))
7631 (and (memq 'headline contexts)
7632 (looking-at "\\*+"))
7633 (and (memq 'item contexts)
7634 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7635 (goto-char pos))))
7637 (defun org-get-local-variables ()
7638 "Return a list of all local variables in an org-mode buffer."
7639 (let (varlist)
7640 (with-current-buffer (get-buffer-create "*Org tmp*")
7641 (erase-buffer)
7642 (org-mode)
7643 (setq varlist (buffer-local-variables)))
7644 (kill-buffer "*Org tmp*")
7645 (delq nil
7646 (mapcar
7647 (lambda (x)
7648 (setq x
7649 (if (symbolp x)
7650 (list x)
7651 (list (car x) (list 'quote (cdr x)))))
7652 (if (string-match
7653 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7654 (symbol-name (car x)))
7655 x nil))
7656 varlist))))
7658 ;;;###autoload
7659 (defun org-run-like-in-org-mode (cmd)
7660 (unless org-local-vars
7661 (setq org-local-vars (org-get-local-variables)))
7662 (eval (list 'let org-local-vars
7663 (list 'call-interactively (list 'quote cmd)))))
7665 ;;;; Archiving
7667 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7669 (defun org-archive-subtree (&optional find-done)
7670 "Move the current subtree to the archive.
7671 The archive can be a certain top-level heading in the current file, or in
7672 a different file. The tree will be moved to that location, the subtree
7673 heading be marked DONE, and the current time will be added.
7675 When called with prefix argument FIND-DONE, find whole trees without any
7676 open TODO items and archive them (after getting confirmation from the user).
7677 If the cursor is not at a headline when this comand is called, try all level
7678 1 trees. If the cursor is on a headline, only try the direct children of
7679 this heading."
7680 (interactive "P")
7681 (if find-done
7682 (org-archive-all-done)
7683 ;; Save all relevant TODO keyword-relatex variables
7685 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7686 (tr-org-todo-keywords-1 org-todo-keywords-1)
7687 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7688 (tr-org-done-keywords org-done-keywords)
7689 (tr-org-todo-regexp org-todo-regexp)
7690 (tr-org-todo-line-regexp org-todo-line-regexp)
7691 (tr-org-odd-levels-only org-odd-levels-only)
7692 (this-buffer (current-buffer))
7693 (org-archive-location org-archive-location)
7694 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7695 ;; start of variables that will be used for saving context
7696 ;; The compiler complains about them - keep them anyway!
7697 (file (abbreviate-file-name (buffer-file-name)))
7698 (time (format-time-string
7699 (substring (cdr org-time-stamp-formats) 1 -1)
7700 (current-time)))
7701 afile heading buffer level newfile-p
7702 category todo priority
7703 ;; start of variables that will be used for savind context
7704 ltags itags prop)
7706 ;; Try to find a local archive location
7707 (save-excursion
7708 (save-restriction
7709 (widen)
7710 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7711 (if (and prop (string-match "\\S-" prop))
7712 (setq org-archive-location prop)
7713 (if (or (re-search-backward re nil t)
7714 (re-search-forward re nil t))
7715 (setq org-archive-location (match-string 1))))))
7717 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7718 (progn
7719 (setq afile (format (match-string 1 org-archive-location)
7720 (file-name-nondirectory buffer-file-name))
7721 heading (match-string 2 org-archive-location)))
7722 (error "Invalid `org-archive-location'"))
7723 (if (> (length afile) 0)
7724 (setq newfile-p (not (file-exists-p afile))
7725 buffer (find-file-noselect afile))
7726 (setq buffer (current-buffer)))
7727 (unless buffer
7728 (error "Cannot access file \"%s\"" afile))
7729 (if (and (> (length heading) 0)
7730 (string-match "^\\*+" heading))
7731 (setq level (match-end 0))
7732 (setq heading nil level 0))
7733 (save-excursion
7734 (org-back-to-heading t)
7735 ;; Get context information that will be lost by moving the tree
7736 (org-refresh-category-properties)
7737 (setq category (org-get-category)
7738 todo (and (looking-at org-todo-line-regexp)
7739 (match-string 2))
7740 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7741 ltags (org-get-tags)
7742 itags (org-delete-all ltags (org-get-tags-at)))
7743 (setq ltags (mapconcat 'identity ltags " ")
7744 itags (mapconcat 'identity itags " "))
7745 ;; We first only copy, in case something goes wrong
7746 ;; we need to protect this-command, to avoid kill-region sets it,
7747 ;; which would lead to duplication of subtrees
7748 (let (this-command) (org-copy-subtree))
7749 (set-buffer buffer)
7750 ;; Enforce org-mode for the archive buffer
7751 (if (not (org-mode-p))
7752 ;; Force the mode for future visits.
7753 (let ((org-insert-mode-line-in-empty-file t)
7754 (org-inhibit-startup t))
7755 (call-interactively 'org-mode)))
7756 (when newfile-p
7757 (goto-char (point-max))
7758 (insert (format "\nArchived entries from file %s\n\n"
7759 (buffer-file-name this-buffer))))
7760 ;; Force the TODO keywords of the original buffer
7761 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7762 (org-todo-keywords-1 tr-org-todo-keywords-1)
7763 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7764 (org-done-keywords tr-org-done-keywords)
7765 (org-todo-regexp tr-org-todo-regexp)
7766 (org-todo-line-regexp tr-org-todo-line-regexp)
7767 (org-odd-levels-only
7768 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7769 org-odd-levels-only
7770 tr-org-odd-levels-only)))
7771 (goto-char (point-min))
7772 (if heading
7773 (progn
7774 (if (re-search-forward
7775 (concat "^" (regexp-quote heading)
7776 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7777 nil t)
7778 (goto-char (match-end 0))
7779 ;; Heading not found, just insert it at the end
7780 (goto-char (point-max))
7781 (or (bolp) (insert "\n"))
7782 (insert "\n" heading "\n")
7783 (end-of-line 0))
7784 ;; Make the subtree visible
7785 (show-subtree)
7786 (org-end-of-subtree t)
7787 (skip-chars-backward " \t\r\n")
7788 (and (looking-at "[ \t\r\n]*")
7789 (replace-match "\n\n")))
7790 ;; No specific heading, just go to end of file.
7791 (goto-char (point-max)) (insert "\n"))
7792 ;; Paste
7793 (org-paste-subtree (org-get-valid-level level 1))
7795 ;; Mark the entry as done
7796 (when (and org-archive-mark-done
7797 (looking-at org-todo-line-regexp)
7798 (or (not (match-end 2))
7799 (not (member (match-string 2) org-done-keywords))))
7800 (let (org-log-done)
7801 (org-todo
7802 (car (or (member org-archive-mark-done org-done-keywords)
7803 org-done-keywords)))))
7805 ;; Add the context info
7806 (when org-archive-save-context-info
7807 (let ((l org-archive-save-context-info) e n v)
7808 (while (setq e (pop l))
7809 (when (and (setq v (symbol-value e))
7810 (stringp v) (string-match "\\S-" v))
7811 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7812 (org-entry-put (point) n v)))))
7814 ;; Save the buffer, if it is not the same buffer.
7815 (if (not (eq this-buffer buffer)) (save-buffer))))
7816 ;; Here we are back in the original buffer. Everything seems to have
7817 ;; worked. So now cut the tree and finish up.
7818 (let (this-command) (org-cut-subtree))
7819 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7820 (message "Subtree archived %s"
7821 (if (eq this-buffer buffer)
7822 (concat "under heading: " heading)
7823 (concat "in file: " (abbreviate-file-name afile)))))))
7825 (defun org-refresh-category-properties ()
7826 "Refresh category text properties in teh buffer."
7827 (let ((def-cat (cond
7828 ((null org-category)
7829 (if buffer-file-name
7830 (file-name-sans-extension
7831 (file-name-nondirectory buffer-file-name))
7832 "???"))
7833 ((symbolp org-category) (symbol-name org-category))
7834 (t org-category)))
7835 beg end cat pos optionp)
7836 (org-unmodified
7837 (save-excursion
7838 (save-restriction
7839 (widen)
7840 (goto-char (point-min))
7841 (put-text-property (point) (point-max) 'org-category def-cat)
7842 (while (re-search-forward
7843 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7844 (setq pos (match-end 0)
7845 optionp (equal (char-after (match-beginning 0)) ?#)
7846 cat (org-trim (match-string 2)))
7847 (if optionp
7848 (setq beg (point-at-bol) end (point-max))
7849 (org-back-to-heading t)
7850 (setq beg (point) end (org-end-of-subtree t t)))
7851 (put-text-property beg end 'org-category cat)
7852 (goto-char pos)))))))
7854 (defun org-archive-all-done (&optional tag)
7855 "Archive sublevels of the current tree without open TODO items.
7856 If the cursor is not on a headline, try all level 1 trees. If
7857 it is on a headline, try all direct children.
7858 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7859 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7860 (rea (concat ".*:" org-archive-tag ":"))
7861 (begm (make-marker))
7862 (endm (make-marker))
7863 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7864 "Move subtree to archive (no open TODO items)? "))
7865 beg end (cntarch 0))
7866 (if (org-on-heading-p)
7867 (progn
7868 (setq re1 (concat "^" (regexp-quote
7869 (make-string
7870 (1+ (- (match-end 0) (match-beginning 0)))
7871 ?*))
7872 " "))
7873 (move-marker begm (point))
7874 (move-marker endm (org-end-of-subtree t)))
7875 (setq re1 "^* ")
7876 (move-marker begm (point-min))
7877 (move-marker endm (point-max)))
7878 (save-excursion
7879 (goto-char begm)
7880 (while (re-search-forward re1 endm t)
7881 (setq beg (match-beginning 0)
7882 end (save-excursion (org-end-of-subtree t) (point)))
7883 (goto-char beg)
7884 (if (re-search-forward re end t)
7885 (goto-char end)
7886 (goto-char beg)
7887 (if (and (or (not tag) (not (looking-at rea)))
7888 (y-or-n-p question))
7889 (progn
7890 (if tag
7891 (org-toggle-tag org-archive-tag 'on)
7892 (org-archive-subtree))
7893 (setq cntarch (1+ cntarch)))
7894 (goto-char end)))))
7895 (message "%d trees archived" cntarch)))
7897 (defun org-cycle-hide-drawers (state)
7898 "Re-hide all drawers after a visibility state change."
7899 (when (and (org-mode-p)
7900 (not (memq state '(overview folded))))
7901 (save-excursion
7902 (let* ((globalp (memq state '(contents all)))
7903 (beg (if globalp (point-min) (point)))
7904 (end (if globalp (point-max) (org-end-of-subtree t))))
7905 (goto-char beg)
7906 (while (re-search-forward org-drawer-regexp end t)
7907 (org-flag-drawer t))))))
7909 (defun org-flag-drawer (flag)
7910 (save-excursion
7911 (beginning-of-line 1)
7912 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7913 (let ((b (match-end 0))
7914 (outline-regexp org-outline-regexp))
7915 (if (re-search-forward
7916 "^[ \t]*:END:"
7917 (save-excursion (outline-next-heading) (point)) t)
7918 (outline-flag-region b (point-at-eol) flag)
7919 (error ":END: line missing"))))))
7921 (defun org-cycle-hide-archived-subtrees (state)
7922 "Re-hide all archived subtrees after a visibility state change."
7923 (when (and (not org-cycle-open-archived-trees)
7924 (not (memq state '(overview folded))))
7925 (save-excursion
7926 (let* ((globalp (memq state '(contents all)))
7927 (beg (if globalp (point-min) (point)))
7928 (end (if globalp (point-max) (org-end-of-subtree t))))
7929 (org-hide-archived-subtrees beg end)
7930 (goto-char beg)
7931 (if (looking-at (concat ".*:" org-archive-tag ":"))
7932 (message "%s" (substitute-command-keys
7933 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7935 (defun org-force-cycle-archived ()
7936 "Cycle subtree even if it is archived."
7937 (interactive)
7938 (setq this-command 'org-cycle)
7939 (let ((org-cycle-open-archived-trees t))
7940 (call-interactively 'org-cycle)))
7942 (defun org-hide-archived-subtrees (beg end)
7943 "Re-hide all archived subtrees after a visibility state change."
7944 (save-excursion
7945 (let* ((re (concat ":" org-archive-tag ":")))
7946 (goto-char beg)
7947 (while (re-search-forward re end t)
7948 (and (org-on-heading-p) (hide-subtree))
7949 (org-end-of-subtree t)))))
7951 (defun org-toggle-tag (tag &optional onoff)
7952 "Toggle the tag TAG for the current line.
7953 If ONOFF is `on' or `off', don't toggle but set to this state."
7954 (unless (org-on-heading-p t) (error "Not on headling"))
7955 (let (res current)
7956 (save-excursion
7957 (beginning-of-line)
7958 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7959 (point-at-eol) t)
7960 (progn
7961 (setq current (match-string 1))
7962 (replace-match ""))
7963 (setq current ""))
7964 (setq current (nreverse (org-split-string current ":")))
7965 (cond
7966 ((eq onoff 'on)
7967 (setq res t)
7968 (or (member tag current) (push tag current)))
7969 ((eq onoff 'off)
7970 (or (not (member tag current)) (setq current (delete tag current))))
7971 (t (if (member tag current)
7972 (setq current (delete tag current))
7973 (setq res t)
7974 (push tag current))))
7975 (end-of-line 1)
7976 (if current
7977 (progn
7978 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7979 (org-set-tags nil t))
7980 (delete-horizontal-space))
7981 (run-hooks 'org-after-tags-change-hook))
7982 res))
7984 (defun org-toggle-archive-tag (&optional arg)
7985 "Toggle the archive tag for the current headline.
7986 With prefix ARG, check all children of current headline and offer tagging
7987 the children that do not contain any open TODO items."
7988 (interactive "P")
7989 (if arg
7990 (org-archive-all-done 'tag)
7991 (let (set)
7992 (save-excursion
7993 (org-back-to-heading t)
7994 (setq set (org-toggle-tag org-archive-tag))
7995 (when set (hide-subtree)))
7996 (and set (beginning-of-line 1))
7997 (message "Subtree %s" (if set "archived" "unarchived")))))
8000 ;;;; Tables
8002 ;;; The table editor
8004 ;; Watch out: Here we are talking about two different kind of tables.
8005 ;; Most of the code is for the tables created with the Org-mode table editor.
8006 ;; Sometimes, we talk about tables created and edited with the table.el
8007 ;; Emacs package. We call the former org-type tables, and the latter
8008 ;; table.el-type tables.
8010 (defun org-before-change-function (beg end)
8011 "Every change indicates that a table might need an update."
8012 (setq org-table-may-need-update t))
8014 (defconst org-table-line-regexp "^[ \t]*|"
8015 "Detects an org-type table line.")
8016 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8017 "Detects an org-type table line.")
8018 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8019 "Detects a table line marked for automatic recalculation.")
8020 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8021 "Detects a table line marked for automatic recalculation.")
8022 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8023 "Detects a table line marked for automatic recalculation.")
8024 (defconst org-table-hline-regexp "^[ \t]*|-"
8025 "Detects an org-type table hline.")
8026 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8027 "Detects a table-type table hline.")
8028 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8029 "Detects an org-type or table-type table.")
8030 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8031 "Searching from within a table (any type) this finds the first line
8032 outside the table.")
8033 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8034 "Searching from within a table (any type) this finds the first line
8035 outside the table.")
8037 (defvar org-table-last-highlighted-reference nil)
8038 (defvar org-table-formula-history nil)
8040 (defvar org-table-column-names nil
8041 "Alist with column names, derived from the `!' line.")
8042 (defvar org-table-column-name-regexp nil
8043 "Regular expression matching the current column names.")
8044 (defvar org-table-local-parameters nil
8045 "Alist with parameter names, derived from the `$' line.")
8046 (defvar org-table-named-field-locations nil
8047 "Alist with locations of named fields.")
8049 (defvar org-table-current-line-types nil
8050 "Table row types, non-nil only for the duration of a comand.")
8051 (defvar org-table-current-begin-line nil
8052 "Table begin line, non-nil only for the duration of a comand.")
8053 (defvar org-table-current-begin-pos nil
8054 "Table begin position, non-nil only for the duration of a comand.")
8055 (defvar org-table-dlines nil
8056 "Vector of data line line numbers in the current table.")
8057 (defvar org-table-hlines nil
8058 "Vector of hline line numbers in the current table.")
8060 (defconst org-table-range-regexp
8061 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8062 ;; 1 2 3 4 5
8063 "Regular expression for matching ranges in formulas.")
8065 (defconst org-table-range-regexp2
8066 (concat
8067 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8068 "\\.\\."
8069 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8070 "Match a range for reference display.")
8072 (defconst org-table-translate-regexp
8073 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8074 "Match a reference that needs translation, for reference display.")
8076 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8078 (defun org-table-create-with-table.el ()
8079 "Use the table.el package to insert a new table.
8080 If there is already a table at point, convert between Org-mode tables
8081 and table.el tables."
8082 (interactive)
8083 (require 'table)
8084 (cond
8085 ((org-at-table.el-p)
8086 (if (y-or-n-p "Convert table to Org-mode table? ")
8087 (org-table-convert)))
8088 ((org-at-table-p)
8089 (if (y-or-n-p "Convert table to table.el table? ")
8090 (org-table-convert)))
8091 (t (call-interactively 'table-insert))))
8093 (defun org-table-create-or-convert-from-region (arg)
8094 "Convert region to table, or create an empty table.
8095 If there is an active region, convert it to a table, using the function
8096 `org-table-convert-region'. See the documentation of that function
8097 to learn how the prefix argument is interpreted to determine the field
8098 separator.
8099 If there is no such region, create an empty table with `org-table-create'."
8100 (interactive "P")
8101 (if (org-region-active-p)
8102 (org-table-convert-region (region-beginning) (region-end) arg)
8103 (org-table-create arg)))
8105 (defun org-table-create (&optional size)
8106 "Query for a size and insert a table skeleton.
8107 SIZE is a string Columns x Rows like for example \"3x2\"."
8108 (interactive "P")
8109 (unless size
8110 (setq size (read-string
8111 (concat "Table size Columns x Rows [e.g. "
8112 org-table-default-size "]: ")
8113 "" nil org-table-default-size)))
8115 (let* ((pos (point))
8116 (indent (make-string (current-column) ?\ ))
8117 (split (org-split-string size " *x *"))
8118 (rows (string-to-number (nth 1 split)))
8119 (columns (string-to-number (car split)))
8120 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8121 "\n")))
8122 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8123 (point-at-bol) (point)))
8124 (beginning-of-line 1)
8125 (newline))
8126 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8127 (dotimes (i rows) (insert line))
8128 (goto-char pos)
8129 (if (> rows 1)
8130 ;; Insert a hline after the first row.
8131 (progn
8132 (end-of-line 1)
8133 (insert "\n|-")
8134 (goto-char pos)))
8135 (org-table-align)))
8137 (defun org-table-convert-region (beg0 end0 &optional separator)
8138 "Convert region to a table.
8139 The region goes from BEG0 to END0, but these borders will be moved
8140 slightly, to make sure a beginning of line in the first line is included.
8142 SEPARATOR specifies the field separator in the lines. It can have the
8143 following values:
8145 '(4) Use the comma as a field separator
8146 '(16) Use a TAB as field separator
8147 integer When a number, use that many spaces as field separator
8148 nil When nil, the command tries to be smart and figure out the
8149 separator in the following way:
8150 - when each line contains a TAB, assume TAB-separated material
8151 - when each line contains a comme, assume CSV material
8152 - else, assume one or more SPACE charcters as separator."
8153 (interactive "rP")
8154 (let* ((beg (min beg0 end0))
8155 (end (max beg0 end0))
8157 (goto-char beg)
8158 (beginning-of-line 1)
8159 (setq beg (move-marker (make-marker) (point)))
8160 (goto-char end)
8161 (if (bolp) (backward-char 1) (end-of-line 1))
8162 (setq end (move-marker (make-marker) (point)))
8163 ;; Get the right field separator
8164 (unless separator
8165 (goto-char beg)
8166 (setq separator
8167 (cond
8168 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8169 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8170 (t 1))))
8171 (setq re (cond
8172 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8173 ((equal separator '(16)) "^\\|\t")
8174 ((integerp separator)
8175 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8176 (t (error "This should not happen"))))
8177 (goto-char beg)
8178 (while (re-search-forward re end t)
8179 (replace-match "| " t t))
8180 (goto-char beg)
8181 (insert " ")
8182 (org-table-align)))
8184 (defun org-table-import (file arg)
8185 "Import FILE as a table.
8186 The file is assumed to be tab-separated. Such files can be produced by most
8187 spreadsheet and database applications. If no tabs (at least one per line)
8188 are found, lines will be split on whitespace into fields."
8189 (interactive "f\nP")
8190 (or (bolp) (newline))
8191 (let ((beg (point))
8192 (pm (point-max)))
8193 (insert-file-contents file)
8194 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8196 (defun org-table-export ()
8197 "Export table as a tab-separated file.
8198 Such a file can be imported into a spreadsheet program like Excel."
8199 (interactive)
8200 (let* ((beg (org-table-begin))
8201 (end (org-table-end))
8202 (table (buffer-substring beg end))
8203 (file (read-file-name "Export table to: "))
8204 buf)
8205 (unless (or (not (file-exists-p file))
8206 (y-or-n-p (format "Overwrite file %s? " file)))
8207 (error "Abort"))
8208 (with-current-buffer (find-file-noselect file)
8209 (setq buf (current-buffer))
8210 (erase-buffer)
8211 (fundamental-mode)
8212 (insert table)
8213 (goto-char (point-min))
8214 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8215 (replace-match "" t t)
8216 (end-of-line 1))
8217 (goto-char (point-min))
8218 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8219 (replace-match "" t t)
8220 (goto-char (min (1+ (point)) (point-max))))
8221 (goto-char (point-min))
8222 (while (re-search-forward "^-[-+]*$" nil t)
8223 (replace-match "")
8224 (if (looking-at "\n")
8225 (delete-char 1)))
8226 (goto-char (point-min))
8227 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8228 (replace-match "\t" t t))
8229 (save-buffer))
8230 (kill-buffer buf)))
8232 (defvar org-table-aligned-begin-marker (make-marker)
8233 "Marker at the beginning of the table last aligned.
8234 Used to check if cursor still is in that table, to minimize realignment.")
8235 (defvar org-table-aligned-end-marker (make-marker)
8236 "Marker at the end of the table last aligned.
8237 Used to check if cursor still is in that table, to minimize realignment.")
8238 (defvar org-table-last-alignment nil
8239 "List of flags for flushright alignment, from the last re-alignment.
8240 This is being used to correctly align a single field after TAB or RET.")
8241 (defvar org-table-last-column-widths nil
8242 "List of max width of fields in each column.
8243 This is being used to correctly align a single field after TAB or RET.")
8244 (defvar org-table-overlay-coordinates nil
8245 "Overlay coordinates after each align of a table.")
8246 (make-variable-buffer-local 'org-table-overlay-coordinates)
8248 (defvar org-last-recalc-line nil)
8249 (defconst org-narrow-column-arrow "=>"
8250 "Used as display property in narrowed table columns.")
8252 (defun org-table-align ()
8253 "Align the table at point by aligning all vertical bars."
8254 (interactive)
8255 (let* (
8256 ;; Limits of table
8257 (beg (org-table-begin))
8258 (end (org-table-end))
8259 ;; Current cursor position
8260 (linepos (org-current-line))
8261 (colpos (org-table-current-column))
8262 (winstart (window-start))
8263 (winstartline (org-current-line (min winstart (1- (point-max)))))
8264 lines (new "") lengths l typenums ty fields maxfields i
8265 column
8266 (indent "") cnt frac
8267 rfmt hfmt
8268 (spaces '(1 . 1))
8269 (sp1 (car spaces))
8270 (sp2 (cdr spaces))
8271 (rfmt1 (concat
8272 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8273 (hfmt1 (concat
8274 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8275 emptystrings links dates emph narrow fmax f1 len c e)
8276 (untabify beg end)
8277 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8278 ;; Check if we have links or dates
8279 (goto-char beg)
8280 (setq links (re-search-forward org-bracket-link-regexp end t))
8281 (goto-char beg)
8282 (setq emph (and org-hide-emphasis-markers
8283 (re-search-forward org-emph-re end t)))
8284 (goto-char beg)
8285 (setq dates (and org-display-custom-times
8286 (re-search-forward org-ts-regexp-both end t)))
8287 ;; Make sure the link properties are right
8288 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8289 ;; Make sure the date properties are right
8290 (when dates (goto-char beg) (while (org-activate-dates end)))
8291 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8293 ;; Check if we are narrowing any columns
8294 (goto-char beg)
8295 (setq narrow (and org-format-transports-properties-p
8296 (re-search-forward "<[0-9]+>" end t)))
8297 ;; Get the rows
8298 (setq lines (org-split-string
8299 (buffer-substring beg end) "\n"))
8300 ;; Store the indentation of the first line
8301 (if (string-match "^ *" (car lines))
8302 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8303 ;; Mark the hlines by setting the corresponding element to nil
8304 ;; At the same time, we remove trailing space.
8305 (setq lines (mapcar (lambda (l)
8306 (if (string-match "^ *|-" l)
8308 (if (string-match "[ \t]+$" l)
8309 (substring l 0 (match-beginning 0))
8310 l)))
8311 lines))
8312 ;; Get the data fields by splitting the lines.
8313 (setq fields (mapcar
8314 (lambda (l)
8315 (org-split-string l " *| *"))
8316 (delq nil (copy-sequence lines))))
8317 ;; How many fields in the longest line?
8318 (condition-case nil
8319 (setq maxfields (apply 'max (mapcar 'length fields)))
8320 (error
8321 (kill-region beg end)
8322 (org-table-create org-table-default-size)
8323 (error "Empty table - created default table")))
8324 ;; A list of empty strings to fill any short rows on output
8325 (setq emptystrings (make-list maxfields ""))
8326 ;; Check for special formatting.
8327 (setq i -1)
8328 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8329 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8330 ;; Check if there is an explicit width specified
8331 (when narrow
8332 (setq c column fmax nil)
8333 (while c
8334 (setq e (pop c))
8335 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8336 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8337 ;; Find fields that are wider than fmax, and shorten them
8338 (when fmax
8339 (loop for xx in column do
8340 (when (and (stringp xx)
8341 (> (org-string-width xx) fmax))
8342 (org-add-props xx nil
8343 'help-echo
8344 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8345 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8346 (unless (> f1 1)
8347 (error "Cannot narrow field starting with wide link \"%s\""
8348 (match-string 0 xx)))
8349 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8350 (add-text-properties (- f1 2) f1
8351 (list 'display org-narrow-column-arrow)
8352 xx)))))
8353 ;; Get the maximum width for each column
8354 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8355 ;; Get the fraction of numbers, to decide about alignment of the column
8356 (setq cnt 0 frac 0.0)
8357 (loop for x in column do
8358 (if (equal x "")
8360 (setq frac ( / (+ (* frac cnt)
8361 (if (string-match org-table-number-regexp x) 1 0))
8362 (setq cnt (1+ cnt))))))
8363 (push (>= frac org-table-number-fraction) typenums))
8364 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8366 ;; Store the alignment of this table, for later editing of single fields
8367 (setq org-table-last-alignment typenums
8368 org-table-last-column-widths lengths)
8370 ;; With invisible characters, `format' does not get the field width right
8371 ;; So we need to make these fields wide by hand.
8372 (when (or links emph)
8373 (loop for i from 0 upto (1- maxfields) do
8374 (setq len (nth i lengths))
8375 (loop for j from 0 upto (1- (length fields)) do
8376 (setq c (nthcdr i (car (nthcdr j fields))))
8377 (if (and (stringp (car c))
8378 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8379 ; (string-match org-bracket-link-regexp (car c))
8380 (< (org-string-width (car c)) len))
8381 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8383 ;; Compute the formats needed for output of the table
8384 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8385 (while (setq l (pop lengths))
8386 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8387 (setq rfmt (concat rfmt (format rfmt1 ty l))
8388 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8389 (setq rfmt (concat rfmt "\n")
8390 hfmt (concat (substring hfmt 0 -1) "|\n"))
8392 (setq new (mapconcat
8393 (lambda (l)
8394 (if l (apply 'format rfmt
8395 (append (pop fields) emptystrings))
8396 hfmt))
8397 lines ""))
8398 ;; Replace the old one
8399 (delete-region beg end)
8400 (move-marker end nil)
8401 (move-marker org-table-aligned-begin-marker (point))
8402 (insert new)
8403 (move-marker org-table-aligned-end-marker (point))
8404 (when (and orgtbl-mode (not (org-mode-p)))
8405 (goto-char org-table-aligned-begin-marker)
8406 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8407 ;; Try to move to the old location
8408 (goto-line winstartline)
8409 (setq winstart (point-at-bol))
8410 (goto-line linepos)
8411 (set-window-start (selected-window) winstart 'noforce)
8412 (org-table-goto-column colpos)
8413 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8414 (setq org-table-may-need-update nil)
8417 (defun org-string-width (s)
8418 "Compute width of string, ignoring invisible characters.
8419 This ignores character with invisibility property `org-link', and also
8420 characters with property `org-cwidth', because these will become invisible
8421 upon the next fontification round."
8422 (let (b l)
8423 (when (or (eq t buffer-invisibility-spec)
8424 (assq 'org-link buffer-invisibility-spec))
8425 (while (setq b (text-property-any 0 (length s)
8426 'invisible 'org-link s))
8427 (setq s (concat (substring s 0 b)
8428 (substring s (or (next-single-property-change
8429 b 'invisible s) (length s)))))))
8430 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8431 (setq s (concat (substring s 0 b)
8432 (substring s (or (next-single-property-change
8433 b 'org-cwidth s) (length s))))))
8434 (setq l (string-width s) b -1)
8435 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8436 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8439 (defun org-table-begin (&optional table-type)
8440 "Find the beginning of the table and return its position.
8441 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8442 (save-excursion
8443 (if (not (re-search-backward
8444 (if table-type org-table-any-border-regexp
8445 org-table-border-regexp)
8446 nil t))
8447 (progn (goto-char (point-min)) (point))
8448 (goto-char (match-beginning 0))
8449 (beginning-of-line 2)
8450 (point))))
8452 (defun org-table-end (&optional table-type)
8453 "Find the end of the table and return its position.
8454 With argument TABLE-TYPE, go to the end of a table.el-type table."
8455 (save-excursion
8456 (if (not (re-search-forward
8457 (if table-type org-table-any-border-regexp
8458 org-table-border-regexp)
8459 nil t))
8460 (goto-char (point-max))
8461 (goto-char (match-beginning 0)))
8462 (point-marker)))
8464 (defun org-table-justify-field-maybe (&optional new)
8465 "Justify the current field, text to left, number to right.
8466 Optional argument NEW may specify text to replace the current field content."
8467 (cond
8468 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8469 ((org-at-table-hline-p))
8470 ((and (not new)
8471 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8472 (current-buffer)))
8473 (< (point) org-table-aligned-begin-marker)
8474 (>= (point) org-table-aligned-end-marker)))
8475 ;; This is not the same table, force a full re-align
8476 (setq org-table-may-need-update t))
8477 (t ;; realign the current field, based on previous full realign
8478 (let* ((pos (point)) s
8479 (col (org-table-current-column))
8480 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8481 l f n o e)
8482 (when (> col 0)
8483 (skip-chars-backward "^|\n")
8484 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8485 (progn
8486 (setq s (match-string 1)
8487 o (match-string 0)
8488 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8489 e (not (= (match-beginning 2) (match-end 2))))
8490 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8491 l (if e "|" (setq org-table-may-need-update t) ""))
8492 n (format f s))
8493 (if new
8494 (if (<= (length new) l) ;; FIXME: length -> str-width?
8495 (setq n (format f new))
8496 (setq n (concat new "|") org-table-may-need-update t)))
8497 (or (equal n o)
8498 (let (org-table-may-need-update)
8499 (replace-match n t t))))
8500 (setq org-table-may-need-update t))
8501 (goto-char pos))))))
8503 (defun org-table-next-field ()
8504 "Go to the next field in the current table, creating new lines as needed.
8505 Before doing so, re-align the table if necessary."
8506 (interactive)
8507 (org-table-maybe-eval-formula)
8508 (org-table-maybe-recalculate-line)
8509 (if (and org-table-automatic-realign
8510 org-table-may-need-update)
8511 (org-table-align))
8512 (let ((end (org-table-end)))
8513 (if (org-at-table-hline-p)
8514 (end-of-line 1))
8515 (condition-case nil
8516 (progn
8517 (re-search-forward "|" end)
8518 (if (looking-at "[ \t]*$")
8519 (re-search-forward "|" end))
8520 (if (and (looking-at "-")
8521 org-table-tab-jumps-over-hlines
8522 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8523 (goto-char (match-beginning 1)))
8524 (if (looking-at "-")
8525 (progn
8526 (beginning-of-line 0)
8527 (org-table-insert-row 'below))
8528 (if (looking-at " ") (forward-char 1))))
8529 (error
8530 (org-table-insert-row 'below)))))
8532 (defun org-table-previous-field ()
8533 "Go to the previous field in the table.
8534 Before doing so, re-align the table if necessary."
8535 (interactive)
8536 (org-table-justify-field-maybe)
8537 (org-table-maybe-recalculate-line)
8538 (if (and org-table-automatic-realign
8539 org-table-may-need-update)
8540 (org-table-align))
8541 (if (org-at-table-hline-p)
8542 (end-of-line 1))
8543 (re-search-backward "|" (org-table-begin))
8544 (re-search-backward "|" (org-table-begin))
8545 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8546 (re-search-backward "|" (org-table-begin)))
8547 (if (looking-at "| ?")
8548 (goto-char (match-end 0))))
8550 (defun org-table-next-row ()
8551 "Go to the next row (same column) in the current table.
8552 Before doing so, re-align the table if necessary."
8553 (interactive)
8554 (org-table-maybe-eval-formula)
8555 (org-table-maybe-recalculate-line)
8556 (if (or (looking-at "[ \t]*$")
8557 (save-excursion (skip-chars-backward " \t") (bolp)))
8558 (newline)
8559 (if (and org-table-automatic-realign
8560 org-table-may-need-update)
8561 (org-table-align))
8562 (let ((col (org-table-current-column)))
8563 (beginning-of-line 2)
8564 (if (or (not (org-at-table-p))
8565 (org-at-table-hline-p))
8566 (progn
8567 (beginning-of-line 0)
8568 (org-table-insert-row 'below)))
8569 (org-table-goto-column col)
8570 (skip-chars-backward "^|\n\r")
8571 (if (looking-at " ") (forward-char 1)))))
8573 (defun org-table-copy-down (n)
8574 "Copy a field down in the current column.
8575 If the field at the cursor is empty, copy into it the content of the nearest
8576 non-empty field above. With argument N, use the Nth non-empty field.
8577 If the current field is not empty, it is copied down to the next row, and
8578 the cursor is moved with it. Therefore, repeating this command causes the
8579 column to be filled row-by-row.
8580 If the variable `org-table-copy-increment' is non-nil and the field is an
8581 integer or a timestamp, it will be incremented while copying. In the case of
8582 a timestamp, if the cursor is on the year, change the year. If it is on the
8583 month or the day, change that. Point will stay on the current date field
8584 in order to easily repeat the interval."
8585 (interactive "p")
8586 (let* ((colpos (org-table-current-column))
8587 (col (current-column))
8588 (field (org-table-get-field))
8589 (non-empty (string-match "[^ \t]" field))
8590 (beg (org-table-begin))
8591 txt)
8592 (org-table-check-inside-data-field)
8593 (if non-empty
8594 (progn
8595 (setq txt (org-trim field))
8596 (org-table-next-row)
8597 (org-table-blank-field))
8598 (save-excursion
8599 (setq txt
8600 (catch 'exit
8601 (while (progn (beginning-of-line 1)
8602 (re-search-backward org-table-dataline-regexp
8603 beg t))
8604 (org-table-goto-column colpos t)
8605 (if (and (looking-at
8606 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8607 (= (setq n (1- n)) 0))
8608 (throw 'exit (match-string 1))))))))
8609 (if txt
8610 (progn
8611 (if (and org-table-copy-increment
8612 (string-match "^[0-9]+$" txt))
8613 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8614 (insert txt)
8615 (move-to-column col)
8616 (if (and org-table-copy-increment (org-at-timestamp-p t))
8617 (org-timestamp-up 1)
8618 (org-table-maybe-recalculate-line))
8619 (org-table-align)
8620 (move-to-column col))
8621 (error "No non-empty field found"))))
8623 (defun org-table-check-inside-data-field ()
8624 "Is point inside a table data field?
8625 I.e. not on a hline or before the first or after the last column?
8626 This actually throws an error, so it aborts the current command."
8627 (if (or (not (org-at-table-p))
8628 (= (org-table-current-column) 0)
8629 (org-at-table-hline-p)
8630 (looking-at "[ \t]*$"))
8631 (error "Not in table data field")))
8633 (defvar org-table-clip nil
8634 "Clipboard for table regions.")
8636 (defun org-table-blank-field ()
8637 "Blank the current table field or active region."
8638 (interactive)
8639 (org-table-check-inside-data-field)
8640 (if (and (interactive-p) (org-region-active-p))
8641 (let (org-table-clip)
8642 (org-table-cut-region (region-beginning) (region-end)))
8643 (skip-chars-backward "^|")
8644 (backward-char 1)
8645 (if (looking-at "|[^|\n]+")
8646 (let* ((pos (match-beginning 0))
8647 (match (match-string 0))
8648 (len (org-string-width match)))
8649 (replace-match (concat "|" (make-string (1- len) ?\ )))
8650 (goto-char (+ 2 pos))
8651 (substring match 1)))))
8653 (defun org-table-get-field (&optional n replace)
8654 "Return the value of the field in column N of current row.
8655 N defaults to current field.
8656 If REPLACE is a string, replace field with this value. The return value
8657 is always the old value."
8658 (and n (org-table-goto-column n))
8659 (skip-chars-backward "^|\n")
8660 (backward-char 1)
8661 (if (looking-at "|[^|\r\n]*")
8662 (let* ((pos (match-beginning 0))
8663 (val (buffer-substring (1+ pos) (match-end 0))))
8664 (if replace
8665 (replace-match (concat "|" replace) t t))
8666 (goto-char (min (point-at-eol) (+ 2 pos)))
8667 val)
8668 (forward-char 1) ""))
8670 (defun org-table-field-info (arg)
8671 "Show info about the current field, and highlight any reference at point."
8672 (interactive "P")
8673 (org-table-get-specials)
8674 (save-excursion
8675 (let* ((pos (point))
8676 (col (org-table-current-column))
8677 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8678 (name (car (rassoc (list (org-current-line) col)
8679 org-table-named-field-locations)))
8680 (eql (org-table-get-stored-formulas))
8681 (dline (org-table-current-dline))
8682 (ref (format "@%d$%d" dline col))
8683 (ref1 (org-table-convert-refs-to-an ref))
8684 (fequation (or (assoc name eql) (assoc ref eql)))
8685 (cequation (assoc (int-to-string col) eql))
8686 (eqn (or fequation cequation)))
8687 (goto-char pos)
8688 (condition-case nil
8689 (org-table-show-reference 'local)
8690 (error nil))
8691 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8692 dline col
8693 (if cname (concat " or $" cname) "")
8694 dline col ref1
8695 (if name (concat " or $" name) "")
8696 ;; FIXME: formula info not correct if special table line
8697 (if eqn
8698 (concat ", formula: "
8699 (org-table-formula-to-user
8700 (concat
8701 (if (string-match "^[$@]"(car eqn)) "" "$")
8702 (car eqn) "=" (cdr eqn))))
8703 "")))))
8705 (defun org-table-current-column ()
8706 "Find out which column we are in.
8707 When called interactively, column is also displayed in echo area."
8708 (interactive)
8709 (if (interactive-p) (org-table-check-inside-data-field))
8710 (save-excursion
8711 (let ((cnt 0) (pos (point)))
8712 (beginning-of-line 1)
8713 (while (search-forward "|" pos t)
8714 (setq cnt (1+ cnt)))
8715 (if (interactive-p) (message "This is table column %d" cnt))
8716 cnt)))
8718 (defun org-table-current-dline ()
8719 "Find out what table data line we are in.
8720 Only datalins count for this."
8721 (interactive)
8722 (if (interactive-p) (org-table-check-inside-data-field))
8723 (save-excursion
8724 (let ((cnt 0) (pos (point)))
8725 (goto-char (org-table-begin))
8726 (while (<= (point) pos)
8727 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8728 (beginning-of-line 2))
8729 (if (interactive-p) (message "This is table line %d" cnt))
8730 cnt)))
8732 (defun org-table-goto-column (n &optional on-delim force)
8733 "Move the cursor to the Nth column in the current table line.
8734 With optional argument ON-DELIM, stop with point before the left delimiter
8735 of the field.
8736 If there are less than N fields, just go to after the last delimiter.
8737 However, when FORCE is non-nil, create new columns if necessary."
8738 (interactive "p")
8739 (let ((pos (point-at-eol)))
8740 (beginning-of-line 1)
8741 (when (> n 0)
8742 (while (and (> (setq n (1- n)) -1)
8743 (or (search-forward "|" pos t)
8744 (and force
8745 (progn (end-of-line 1)
8746 (skip-chars-backward "^|")
8747 (insert " | "))))))
8748 ; (backward-char 2) t)))))
8749 (when (and force (not (looking-at ".*|")))
8750 (save-excursion (end-of-line 1) (insert " | ")))
8751 (if on-delim
8752 (backward-char 1)
8753 (if (looking-at " ") (forward-char 1))))))
8755 (defun org-at-table-p (&optional table-type)
8756 "Return t if the cursor is inside an org-type table.
8757 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8758 (if org-enable-table-editor
8759 (save-excursion
8760 (beginning-of-line 1)
8761 (looking-at (if table-type org-table-any-line-regexp
8762 org-table-line-regexp)))
8763 nil))
8765 (defun org-at-table.el-p ()
8766 "Return t if and only if we are at a table.el table."
8767 (and (org-at-table-p 'any)
8768 (save-excursion
8769 (goto-char (org-table-begin 'any))
8770 (looking-at org-table1-hline-regexp))))
8772 (defun org-table-recognize-table.el ()
8773 "If there is a table.el table nearby, recognize it and move into it."
8774 (if org-table-tab-recognizes-table.el
8775 (if (org-at-table.el-p)
8776 (progn
8777 (beginning-of-line 1)
8778 (if (looking-at org-table-dataline-regexp)
8780 (if (looking-at org-table1-hline-regexp)
8781 (progn
8782 (beginning-of-line 2)
8783 (if (looking-at org-table-any-border-regexp)
8784 (beginning-of-line -1)))))
8785 (if (re-search-forward "|" (org-table-end t) t)
8786 (progn
8787 (require 'table)
8788 (if (table--at-cell-p (point))
8790 (message "recognizing table.el table...")
8791 (table-recognize-table)
8792 (message "recognizing table.el table...done")))
8793 (error "This should not happen..."))
8795 nil)
8796 nil))
8798 (defun org-at-table-hline-p ()
8799 "Return t if the cursor is inside a hline in a table."
8800 (if org-enable-table-editor
8801 (save-excursion
8802 (beginning-of-line 1)
8803 (looking-at org-table-hline-regexp))
8804 nil))
8806 (defun org-table-insert-column ()
8807 "Insert a new column into the table."
8808 (interactive)
8809 (if (not (org-at-table-p))
8810 (error "Not at a table"))
8811 (org-table-find-dataline)
8812 (let* ((col (max 1 (org-table-current-column)))
8813 (beg (org-table-begin))
8814 (end (org-table-end))
8815 ;; Current cursor position
8816 (linepos (org-current-line))
8817 (colpos col))
8818 (goto-char beg)
8819 (while (< (point) end)
8820 (if (org-at-table-hline-p)
8822 (org-table-goto-column col t)
8823 (insert "| "))
8824 (beginning-of-line 2))
8825 (move-marker end nil)
8826 (goto-line linepos)
8827 (org-table-goto-column colpos)
8828 (org-table-align)
8829 (org-table-fix-formulas "$" nil (1- col) 1)))
8831 (defun org-table-find-dataline ()
8832 "Find a dataline in the current table, which is needed for column commands."
8833 (if (and (org-at-table-p)
8834 (not (org-at-table-hline-p)))
8836 (let ((col (current-column))
8837 (end (org-table-end)))
8838 (move-to-column col)
8839 (while (and (< (point) end)
8840 (or (not (= (current-column) col))
8841 (org-at-table-hline-p)))
8842 (beginning-of-line 2)
8843 (move-to-column col))
8844 (if (and (org-at-table-p)
8845 (not (org-at-table-hline-p)))
8847 (error
8848 "Please position cursor in a data line for column operations")))))
8850 (defun org-table-delete-column ()
8851 "Delete a column from the table."
8852 (interactive)
8853 (if (not (org-at-table-p))
8854 (error "Not at a table"))
8855 (org-table-find-dataline)
8856 (org-table-check-inside-data-field)
8857 (let* ((col (org-table-current-column))
8858 (beg (org-table-begin))
8859 (end (org-table-end))
8860 ;; Current cursor position
8861 (linepos (org-current-line))
8862 (colpos col))
8863 (goto-char beg)
8864 (while (< (point) end)
8865 (if (org-at-table-hline-p)
8867 (org-table-goto-column col t)
8868 (and (looking-at "|[^|\n]+|")
8869 (replace-match "|")))
8870 (beginning-of-line 2))
8871 (move-marker end nil)
8872 (goto-line linepos)
8873 (org-table-goto-column colpos)
8874 (org-table-align)
8875 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8876 col -1 col)))
8878 (defun org-table-move-column-right ()
8879 "Move column to the right."
8880 (interactive)
8881 (org-table-move-column nil))
8882 (defun org-table-move-column-left ()
8883 "Move column to the left."
8884 (interactive)
8885 (org-table-move-column 'left))
8887 (defun org-table-move-column (&optional left)
8888 "Move the current column to the right. With arg LEFT, move to the left."
8889 (interactive "P")
8890 (if (not (org-at-table-p))
8891 (error "Not at a table"))
8892 (org-table-find-dataline)
8893 (org-table-check-inside-data-field)
8894 (let* ((col (org-table-current-column))
8895 (col1 (if left (1- col) col))
8896 (beg (org-table-begin))
8897 (end (org-table-end))
8898 ;; Current cursor position
8899 (linepos (org-current-line))
8900 (colpos (if left (1- col) (1+ col))))
8901 (if (and left (= col 1))
8902 (error "Cannot move column further left"))
8903 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8904 (error "Cannot move column further right"))
8905 (goto-char beg)
8906 (while (< (point) end)
8907 (if (org-at-table-hline-p)
8909 (org-table-goto-column col1 t)
8910 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8911 (replace-match "|\\2|\\1|")))
8912 (beginning-of-line 2))
8913 (move-marker end nil)
8914 (goto-line linepos)
8915 (org-table-goto-column colpos)
8916 (org-table-align)
8917 (org-table-fix-formulas
8918 "$" (list (cons (number-to-string col) (number-to-string colpos))
8919 (cons (number-to-string colpos) (number-to-string col))))))
8921 (defun org-table-move-row-down ()
8922 "Move table row down."
8923 (interactive)
8924 (org-table-move-row nil))
8925 (defun org-table-move-row-up ()
8926 "Move table row up."
8927 (interactive)
8928 (org-table-move-row 'up))
8930 (defun org-table-move-row (&optional up)
8931 "Move the current table line down. With arg UP, move it up."
8932 (interactive "P")
8933 (let* ((col (current-column))
8934 (pos (point))
8935 (hline1p (save-excursion (beginning-of-line 1)
8936 (looking-at org-table-hline-regexp)))
8937 (dline1 (org-table-current-dline))
8938 (dline2 (+ dline1 (if up -1 1)))
8939 (tonew (if up 0 2))
8940 txt hline2p)
8941 (beginning-of-line tonew)
8942 (unless (org-at-table-p)
8943 (goto-char pos)
8944 (error "Cannot move row further"))
8945 (setq hline2p (looking-at org-table-hline-regexp))
8946 (goto-char pos)
8947 (beginning-of-line 1)
8948 (setq pos (point))
8949 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8950 (delete-region (point) (1+ (point-at-eol)))
8951 (beginning-of-line tonew)
8952 (insert txt)
8953 (beginning-of-line 0)
8954 (move-to-column col)
8955 (unless (or hline1p hline2p)
8956 (org-table-fix-formulas
8957 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8958 (cons (number-to-string dline2) (number-to-string dline1)))))))
8960 (defun org-table-insert-row (&optional arg)
8961 "Insert a new row above the current line into the table.
8962 With prefix ARG, insert below the current line."
8963 (interactive "P")
8964 (if (not (org-at-table-p))
8965 (error "Not at a table"))
8966 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8967 (new (org-table-clean-line line)))
8968 ;; Fix the first field if necessary
8969 (if (string-match "^[ \t]*| *[#$] *|" line)
8970 (setq new (replace-match (match-string 0 line) t t new)))
8971 (beginning-of-line (if arg 2 1))
8972 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8973 (beginning-of-line 0)
8974 (re-search-forward "| ?" (point-at-eol) t)
8975 (and (or org-table-may-need-update org-table-overlay-coordinates)
8976 (org-table-align))
8977 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8979 (defun org-table-insert-hline (&optional above)
8980 "Insert a horizontal-line below the current line into the table.
8981 With prefix ABOVE, insert above the current line."
8982 (interactive "P")
8983 (if (not (org-at-table-p))
8984 (error "Not at a table"))
8985 (let ((line (org-table-clean-line
8986 (buffer-substring (point-at-bol) (point-at-eol))))
8987 (col (current-column)))
8988 (while (string-match "|\\( +\\)|" line)
8989 (setq line (replace-match
8990 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8991 ?-) "|") t t line)))
8992 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8993 (beginning-of-line (if above 1 2))
8994 (insert line "\n")
8995 (beginning-of-line (if above 1 -1))
8996 (move-to-column col)
8997 (and org-table-overlay-coordinates (org-table-align))))
8999 (defun org-table-hline-and-move (&optional same-column)
9000 "Insert a hline and move to the row below that line."
9001 (interactive "P")
9002 (let ((col (org-table-current-column)))
9003 (org-table-maybe-eval-formula)
9004 (org-table-maybe-recalculate-line)
9005 (org-table-insert-hline)
9006 (end-of-line 2)
9007 (if (looking-at "\n[ \t]*|-")
9008 (progn (insert "\n|") (org-table-align))
9009 (org-table-next-field))
9010 (if same-column (org-table-goto-column col))))
9012 (defun org-table-clean-line (s)
9013 "Convert a table line S into a string with only \"|\" and space.
9014 In particular, this does handle wide and invisible characters."
9015 (if (string-match "^[ \t]*|-" s)
9016 ;; It's a hline, just map the characters
9017 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9018 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9019 (setq s (replace-match
9020 (concat "|" (make-string (org-string-width (match-string 1 s))
9021 ?\ ) "|")
9022 t t s)))
9025 (defun org-table-kill-row ()
9026 "Delete the current row or horizontal line from the table."
9027 (interactive)
9028 (if (not (org-at-table-p))
9029 (error "Not at a table"))
9030 (let ((col (current-column))
9031 (dline (org-table-current-dline)))
9032 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9033 (if (not (org-at-table-p)) (beginning-of-line 0))
9034 (move-to-column col)
9035 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9036 dline -1 dline)))
9038 (defun org-table-sort-lines (with-case &optional sorting-type)
9039 "Sort table lines according to the column at point.
9041 The position of point indicates the column to be used for
9042 sorting, and the range of lines is the range between the nearest
9043 horizontal separator lines, or the entire table of no such lines
9044 exist. If point is before the first column, you will be prompted
9045 for the sorting column. If there is an active region, the mark
9046 specifies the first line and the sorting column, while point
9047 should be in the last line to be included into the sorting.
9049 The command then prompts for the sorting type which can be
9050 alphabetically, numerically, or by time (as given in a time stamp
9051 in the field). Sorting in reverse order is also possible.
9053 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9055 If SORTING-TYPE is specified when this function is called from a Lisp
9056 program, no prompting will take place. SORTING-TYPE must be a character,
9057 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9058 should be done in reverse order."
9059 (interactive "P")
9060 (let* ((thisline (org-current-line))
9061 (thiscol (org-table-current-column))
9062 beg end bcol ecol tend tbeg column lns pos)
9063 (when (equal thiscol 0)
9064 (if (interactive-p)
9065 (setq thiscol
9066 (string-to-number
9067 (read-string "Use column N for sorting: ")))
9068 (setq thiscol 1))
9069 (org-table-goto-column thiscol))
9070 (org-table-check-inside-data-field)
9071 (if (org-region-active-p)
9072 (progn
9073 (setq beg (region-beginning) end (region-end))
9074 (goto-char beg)
9075 (setq column (org-table-current-column)
9076 beg (point-at-bol))
9077 (goto-char end)
9078 (setq end (point-at-bol 2)))
9079 (setq column (org-table-current-column)
9080 pos (point)
9081 tbeg (org-table-begin)
9082 tend (org-table-end))
9083 (if (re-search-backward org-table-hline-regexp tbeg t)
9084 (setq beg (point-at-bol 2))
9085 (goto-char tbeg)
9086 (setq beg (point-at-bol 1)))
9087 (goto-char pos)
9088 (if (re-search-forward org-table-hline-regexp tend t)
9089 (setq end (point-at-bol 1))
9090 (goto-char tend)
9091 (setq end (point-at-bol))))
9092 (setq beg (move-marker (make-marker) beg)
9093 end (move-marker (make-marker) end))
9094 (untabify beg end)
9095 (goto-char beg)
9096 (org-table-goto-column column)
9097 (skip-chars-backward "^|")
9098 (setq bcol (current-column))
9099 (org-table-goto-column (1+ column))
9100 (skip-chars-backward "^|")
9101 (setq ecol (1- (current-column)))
9102 (org-table-goto-column column)
9103 (setq lns (mapcar (lambda(x) (cons
9104 (org-sort-remove-invisible
9105 (nth (1- column)
9106 (org-split-string x "[ \t]*|[ \t]*")))
9108 (org-split-string (buffer-substring beg end) "\n")))
9109 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9110 (delete-region beg end)
9111 (move-marker beg nil)
9112 (move-marker end nil)
9113 (insert (mapconcat 'cdr lns "\n") "\n")
9114 (goto-line thisline)
9115 (org-table-goto-column thiscol)
9116 (message "%d lines sorted, based on column %d" (length lns) column)))
9118 ;; FIXME: maybe we will not need this? Table sorting is broken....
9119 (defun org-sort-remove-invisible (s)
9120 (remove-text-properties 0 (length s) org-rm-props s)
9121 (while (string-match org-bracket-link-regexp s)
9122 (setq s (replace-match (if (match-end 2)
9123 (match-string 3 s)
9124 (match-string 1 s)) t t s)))
9127 (defun org-table-cut-region (beg end)
9128 "Copy region in table to the clipboard and blank all relevant fields."
9129 (interactive "r")
9130 (org-table-copy-region beg end 'cut))
9132 (defun org-table-copy-region (beg end &optional cut)
9133 "Copy rectangular region in table to clipboard.
9134 A special clipboard is used which can only be accessed
9135 with `org-table-paste-rectangle'."
9136 (interactive "rP")
9137 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9138 region cols
9139 (rpl (if cut " " nil)))
9140 (goto-char beg)
9141 (org-table-check-inside-data-field)
9142 (setq l01 (org-current-line)
9143 c01 (org-table-current-column))
9144 (goto-char end)
9145 (org-table-check-inside-data-field)
9146 (setq l02 (org-current-line)
9147 c02 (org-table-current-column))
9148 (setq l1 (min l01 l02) l2 (max l01 l02)
9149 c1 (min c01 c02) c2 (max c01 c02))
9150 (catch 'exit
9151 (while t
9152 (catch 'nextline
9153 (if (> l1 l2) (throw 'exit t))
9154 (goto-line l1)
9155 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9156 (setq cols nil ic1 c1 ic2 c2)
9157 (while (< ic1 (1+ ic2))
9158 (push (org-table-get-field ic1 rpl) cols)
9159 (setq ic1 (1+ ic1)))
9160 (push (nreverse cols) region)
9161 (setq l1 (1+ l1)))))
9162 (setq org-table-clip (nreverse region))
9163 (if cut (org-table-align))
9164 org-table-clip))
9166 (defun org-table-paste-rectangle ()
9167 "Paste a rectangular region into a table.
9168 The upper right corner ends up in the current field. All involved fields
9169 will be overwritten. If the rectangle does not fit into the present table,
9170 the table is enlarged as needed. The process ignores horizontal separator
9171 lines."
9172 (interactive)
9173 (unless (and org-table-clip (listp org-table-clip))
9174 (error "First cut/copy a region to paste!"))
9175 (org-table-check-inside-data-field)
9176 (let* ((clip org-table-clip)
9177 (line (org-current-line))
9178 (col (org-table-current-column))
9179 (org-enable-table-editor t)
9180 (org-table-automatic-realign nil)
9181 c cols field)
9182 (while (setq cols (pop clip))
9183 (while (org-at-table-hline-p) (beginning-of-line 2))
9184 (if (not (org-at-table-p))
9185 (progn (end-of-line 0) (org-table-next-field)))
9186 (setq c col)
9187 (while (setq field (pop cols))
9188 (org-table-goto-column c nil 'force)
9189 (org-table-get-field nil field)
9190 (setq c (1+ c)))
9191 (beginning-of-line 2))
9192 (goto-line line)
9193 (org-table-goto-column col)
9194 (org-table-align)))
9196 (defun org-table-convert ()
9197 "Convert from `org-mode' table to table.el and back.
9198 Obviously, this only works within limits. When an Org-mode table is
9199 converted to table.el, all horizontal separator lines get lost, because
9200 table.el uses these as cell boundaries and has no notion of horizontal lines.
9201 A table.el table can be converted to an Org-mode table only if it does not
9202 do row or column spanning. Multiline cells will become multiple cells.
9203 Beware, Org-mode does not test if the table can be successfully converted - it
9204 blindly applies a recipe that works for simple tables."
9205 (interactive)
9206 (require 'table)
9207 (if (org-at-table.el-p)
9208 ;; convert to Org-mode table
9209 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9210 (end (move-marker (make-marker) (org-table-end t))))
9211 (table-unrecognize-region beg end)
9212 (goto-char beg)
9213 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9214 (replace-match ""))
9215 (goto-char beg))
9216 (if (org-at-table-p)
9217 ;; convert to table.el table
9218 (let ((beg (move-marker (make-marker) (org-table-begin)))
9219 (end (move-marker (make-marker) (org-table-end))))
9220 ;; first, get rid of all horizontal lines
9221 (goto-char beg)
9222 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9223 (replace-match ""))
9224 ;; insert a hline before first
9225 (goto-char beg)
9226 (org-table-insert-hline 'above)
9227 (beginning-of-line -1)
9228 ;; insert a hline after each line
9229 (while (progn (beginning-of-line 3) (< (point) end))
9230 (org-table-insert-hline))
9231 (goto-char beg)
9232 (setq end (move-marker end (org-table-end)))
9233 ;; replace "+" at beginning and ending of hlines
9234 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9235 (replace-match "\\1+-"))
9236 (goto-char beg)
9237 (while (re-search-forward "-|[ \t]*$" end t)
9238 (replace-match "-+"))
9239 (goto-char beg)))))
9241 (defun org-table-wrap-region (arg)
9242 "Wrap several fields in a column like a paragraph.
9243 This is useful if you'd like to spread the contents of a field over several
9244 lines, in order to keep the table compact.
9246 If there is an active region, and both point and mark are in the same column,
9247 the text in the column is wrapped to minimum width for the given number of
9248 lines. Generally, this makes the table more compact. A prefix ARG may be
9249 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9250 formats the selected text to two lines. If the region was longer than two
9251 lines, the remaining lines remain empty. A negative prefix argument reduces
9252 the current number of lines by that amount. The wrapped text is pasted back
9253 into the table. If you formatted it to more lines than it was before, fields
9254 further down in the table get overwritten - so you might need to make space in
9255 the table first.
9257 If there is no region, the current field is split at the cursor position and
9258 the text fragment to the right of the cursor is prepended to the field one
9259 line down.
9261 If there is no region, but you specify a prefix ARG, the current field gets
9262 blank, and the content is appended to the field above."
9263 (interactive "P")
9264 (org-table-check-inside-data-field)
9265 (if (org-region-active-p)
9266 ;; There is a region: fill as a paragraph
9267 (let* ((beg (region-beginning))
9268 (cline (save-excursion (goto-char beg) (org-current-line)))
9269 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9270 nlines)
9271 (org-table-cut-region (region-beginning) (region-end))
9272 (if (> (length (car org-table-clip)) 1)
9273 (error "Region must be limited to single column"))
9274 (setq nlines (if arg
9275 (if (< arg 1)
9276 (+ (length org-table-clip) arg)
9277 arg)
9278 (length org-table-clip)))
9279 (setq org-table-clip
9280 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9281 nil nlines)))
9282 (goto-line cline)
9283 (org-table-goto-column ccol)
9284 (org-table-paste-rectangle))
9285 ;; No region, split the current field at point
9286 (if arg
9287 ;; combine with field above
9288 (let ((s (org-table-blank-field))
9289 (col (org-table-current-column)))
9290 (beginning-of-line 0)
9291 (while (org-at-table-hline-p) (beginning-of-line 0))
9292 (org-table-goto-column col)
9293 (skip-chars-forward "^|")
9294 (skip-chars-backward " ")
9295 (insert " " (org-trim s))
9296 (org-table-align))
9297 ;; split field
9298 (when (looking-at "\\([^|]+\\)+|")
9299 (let ((s (match-string 1)))
9300 (replace-match " |")
9301 (goto-char (match-beginning 0))
9302 (org-table-next-row)
9303 (insert (org-trim s) " ")
9304 (org-table-align))))))
9306 (defvar org-field-marker nil)
9308 (defun org-table-edit-field (arg)
9309 "Edit table field in a different window.
9310 This is mainly useful for fields that contain hidden parts.
9311 When called with a \\[universal-argument] prefix, just make the full field visible so that
9312 it can be edited in place."
9313 (interactive "P")
9314 (if arg
9315 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9316 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9317 (remove-text-properties b e '(org-cwidth t invisible t
9318 display t intangible t))
9319 (if (and (boundp 'font-lock-mode) font-lock-mode)
9320 (font-lock-fontify-block)))
9321 (let ((pos (move-marker (make-marker) (point)))
9322 (field (org-table-get-field))
9323 (cw (current-window-configuration))
9325 (org-switch-to-buffer-other-window "*Org tmp*")
9326 (erase-buffer)
9327 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9328 (let ((org-inhibit-startup t)) (org-mode))
9329 (goto-char (setq p (point-max)))
9330 (insert (org-trim field))
9331 (remove-text-properties p (point-max)
9332 '(invisible t org-cwidth t display t
9333 intangible t))
9334 (goto-char p)
9335 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9336 (org-set-local 'org-window-configuration cw)
9337 (org-set-local 'org-field-marker pos)
9338 (message "Edit and finish with C-c C-c"))))
9340 (defun org-table-finish-edit-field ()
9341 "Finish editing a table data field.
9342 Remove all newline characters, insert the result into the table, realign
9343 the table and kill the editing buffer."
9344 (let ((pos org-field-marker)
9345 (cw org-window-configuration)
9346 (cb (current-buffer))
9347 text)
9348 (goto-char (point-min))
9349 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9350 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9351 (replace-match " "))
9352 (setq text (org-trim (buffer-string)))
9353 (set-window-configuration cw)
9354 (kill-buffer cb)
9355 (select-window (get-buffer-window (marker-buffer pos)))
9356 (goto-char pos)
9357 (move-marker pos nil)
9358 (org-table-check-inside-data-field)
9359 (org-table-get-field nil text)
9360 (org-table-align)
9361 (message "New field value inserted")))
9363 (defun org-trim (s)
9364 "Remove whitespace at beginning and end of string."
9365 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9366 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9369 (defun org-wrap (string &optional width lines)
9370 "Wrap string to either a number of lines, or a width in characters.
9371 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9372 that costs. If there is a word longer than WIDTH, the text is actually
9373 wrapped to the length of that word.
9374 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9375 many lines, whatever width that takes.
9376 The return value is a list of lines, without newlines at the end."
9377 (let* ((words (org-split-string string "[ \t\n]+"))
9378 (maxword (apply 'max (mapcar 'org-string-width words)))
9379 w ll)
9380 (cond (width
9381 (org-do-wrap words (max maxword width)))
9382 (lines
9383 (setq w maxword)
9384 (setq ll (org-do-wrap words maxword))
9385 (if (<= (length ll) lines)
9387 (setq ll words)
9388 (while (> (length ll) lines)
9389 (setq w (1+ w))
9390 (setq ll (org-do-wrap words w)))
9391 ll))
9392 (t (error "Cannot wrap this")))))
9395 (defun org-do-wrap (words width)
9396 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9397 (let (lines line)
9398 (while words
9399 (setq line (pop words))
9400 (while (and words (< (+ (length line) (length (car words))) width))
9401 (setq line (concat line " " (pop words))))
9402 (setq lines (push line lines)))
9403 (nreverse lines)))
9405 (defun org-split-string (string &optional separators)
9406 "Splits STRING into substrings at SEPARATORS.
9407 No empty strings are returned if there are matches at the beginning
9408 and end of string."
9409 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9410 (start 0)
9411 notfirst
9412 (list nil))
9413 (while (and (string-match rexp string
9414 (if (and notfirst
9415 (= start (match-beginning 0))
9416 (< start (length string)))
9417 (1+ start) start))
9418 (< (match-beginning 0) (length string)))
9419 (setq notfirst t)
9420 (or (eq (match-beginning 0) 0)
9421 (and (eq (match-beginning 0) (match-end 0))
9422 (eq (match-beginning 0) start))
9423 (setq list
9424 (cons (substring string start (match-beginning 0))
9425 list)))
9426 (setq start (match-end 0)))
9427 (or (eq start (length string))
9428 (setq list
9429 (cons (substring string start)
9430 list)))
9431 (nreverse list)))
9433 (defun org-table-map-tables (function)
9434 "Apply FUNCTION to the start of all tables in the buffer."
9435 (save-excursion
9436 (save-restriction
9437 (widen)
9438 (goto-char (point-min))
9439 (while (re-search-forward org-table-any-line-regexp nil t)
9440 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9441 (beginning-of-line 1)
9442 (if (looking-at org-table-line-regexp)
9443 (save-excursion (funcall function)))
9444 (re-search-forward org-table-any-border-regexp nil 1))))
9445 (message "Mapping tables: done"))
9447 (defvar org-timecnt) ; dynamically scoped parameter
9449 (defun org-table-sum (&optional beg end nlast)
9450 "Sum numbers in region of current table column.
9451 The result will be displayed in the echo area, and will be available
9452 as kill to be inserted with \\[yank].
9454 If there is an active region, it is interpreted as a rectangle and all
9455 numbers in that rectangle will be summed. If there is no active
9456 region and point is located in a table column, sum all numbers in that
9457 column.
9459 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9460 numbers are assumed to be times as well (in decimal hours) and the
9461 numbers are added as such.
9463 If NLAST is a number, only the NLAST fields will actually be summed."
9464 (interactive)
9465 (save-excursion
9466 (let (col (org-timecnt 0) diff h m s org-table-clip)
9467 (cond
9468 ((and beg end)) ; beg and end given explicitly
9469 ((org-region-active-p)
9470 (setq beg (region-beginning) end (region-end)))
9472 (setq col (org-table-current-column))
9473 (goto-char (org-table-begin))
9474 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9475 (error "No table data"))
9476 (org-table-goto-column col)
9477 (setq beg (point))
9478 (goto-char (org-table-end))
9479 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9480 (error "No table data"))
9481 (org-table-goto-column col)
9482 (setq end (point))))
9483 (let* ((items (apply 'append (org-table-copy-region beg end)))
9484 (items1 (cond ((not nlast) items)
9485 ((>= nlast (length items)) items)
9486 (t (setq items (reverse items))
9487 (setcdr (nthcdr (1- nlast) items) nil)
9488 (nreverse items))))
9489 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9490 items1)))
9491 (res (apply '+ numbers))
9492 (sres (if (= org-timecnt 0)
9493 (format "%g" res)
9494 (setq diff (* 3600 res)
9495 h (floor (/ diff 3600)) diff (mod diff 3600)
9496 m (floor (/ diff 60)) diff (mod diff 60)
9497 s diff)
9498 (format "%d:%02d:%02d" h m s))))
9499 (kill-new sres)
9500 (if (interactive-p)
9501 (message "%s"
9502 (substitute-command-keys
9503 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9504 (length numbers) sres))))
9505 sres))))
9507 (defun org-table-get-number-for-summing (s)
9508 (let (n)
9509 (if (string-match "^ *|? *" s)
9510 (setq s (replace-match "" nil nil s)))
9511 (if (string-match " *|? *$" s)
9512 (setq s (replace-match "" nil nil s)))
9513 (setq n (string-to-number s))
9514 (cond
9515 ((and (string-match "0" s)
9516 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9517 ((string-match "\\`[ \t]+\\'" s) nil)
9518 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9519 (let ((h (string-to-number (or (match-string 1 s) "0")))
9520 (m (string-to-number (or (match-string 2 s) "0")))
9521 (s (string-to-number (or (match-string 4 s) "0"))))
9522 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9523 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9524 ((equal n 0) nil)
9525 (t n))))
9527 (defun org-table-current-field-formula (&optional key noerror)
9528 "Return the formula active for the current field.
9529 Assumes that specials are in place.
9530 If KEY is given, return the key to this formula.
9531 Otherwise return the formula preceeded with \"=\" or \":=\"."
9532 (let* ((name (car (rassoc (list (org-current-line)
9533 (org-table-current-column))
9534 org-table-named-field-locations)))
9535 (col (org-table-current-column))
9536 (scol (int-to-string col))
9537 (ref (format "@%d$%d" (org-table-current-dline) col))
9538 (stored-list (org-table-get-stored-formulas noerror))
9539 (ass (or (assoc name stored-list)
9540 (assoc ref stored-list)
9541 (assoc scol stored-list))))
9542 (if key
9543 (car ass)
9544 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9545 (cdr ass))))))
9547 (defun org-table-get-formula (&optional equation named)
9548 "Read a formula from the minibuffer, offer stored formula as default.
9549 When NAMED is non-nil, look for a named equation."
9550 (let* ((stored-list (org-table-get-stored-formulas))
9551 (name (car (rassoc (list (org-current-line)
9552 (org-table-current-column))
9553 org-table-named-field-locations)))
9554 (ref (format "@%d$%d" (org-table-current-dline)
9555 (org-table-current-column)))
9556 (refass (assoc ref stored-list))
9557 (scol (if named
9558 (if name name ref)
9559 (int-to-string (org-table-current-column))))
9560 (dummy (and (or name refass) (not named)
9561 (not (y-or-n-p "Replace field formula with column formula? " ))
9562 (error "Abort")))
9563 (name (or name ref))
9564 (org-table-may-need-update nil)
9565 (stored (cdr (assoc scol stored-list)))
9566 (eq (cond
9567 ((and stored equation (string-match "^ *=? *$" equation))
9568 stored)
9569 ((stringp equation)
9570 equation)
9571 (t (org-table-formula-from-user
9572 (read-string
9573 (org-table-formula-to-user
9574 (format "%s formula %s%s="
9575 (if named "Field" "Column")
9576 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9577 scol))
9578 (if stored (org-table-formula-to-user stored) "")
9579 'org-table-formula-history
9580 )))))
9581 mustsave)
9582 (when (not (string-match "\\S-" eq))
9583 ;; remove formula
9584 (setq stored-list (delq (assoc scol stored-list) stored-list))
9585 (org-table-store-formulas stored-list)
9586 (error "Formula removed"))
9587 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9588 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9589 (if (and name (not named))
9590 ;; We set the column equation, delete the named one.
9591 (setq stored-list (delq (assoc name stored-list) stored-list)
9592 mustsave t))
9593 (if stored
9594 (setcdr (assoc scol stored-list) eq)
9595 (setq stored-list (cons (cons scol eq) stored-list)))
9596 (if (or mustsave (not (equal stored eq)))
9597 (org-table-store-formulas stored-list))
9598 eq))
9600 (defun org-table-store-formulas (alist)
9601 "Store the list of formulas below the current table."
9602 (setq alist (sort alist 'org-table-formula-less-p))
9603 (save-excursion
9604 (goto-char (org-table-end))
9605 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9606 (progn
9607 ;; don't overwrite TBLFM, we might use text properties to store stuff
9608 (goto-char (match-beginning 2))
9609 (delete-region (match-beginning 2) (match-end 0)))
9610 (insert "#+TBLFM:"))
9611 (insert " "
9612 (mapconcat (lambda (x)
9613 (concat
9614 (if (equal (string-to-char (car x)) ?@) "" "$")
9615 (car x) "=" (cdr x)))
9616 alist "::")
9617 "\n")))
9619 (defsubst org-table-formula-make-cmp-string (a)
9620 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9621 (concat
9622 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9623 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9624 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9626 (defun org-table-formula-less-p (a b)
9627 "Compare two formulas for sorting."
9628 (let ((as (org-table-formula-make-cmp-string (car a)))
9629 (bs (org-table-formula-make-cmp-string (car b))))
9630 (and as bs (string< as bs))))
9632 (defun org-table-get-stored-formulas (&optional noerror)
9633 "Return an alist with the stored formulas directly after current table."
9634 (interactive)
9635 (let (scol eq eq-alist strings string seen)
9636 (save-excursion
9637 (goto-char (org-table-end))
9638 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9639 (setq strings (org-split-string (match-string 2) " *:: *"))
9640 (while (setq string (pop strings))
9641 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9642 (setq scol (if (match-end 2)
9643 (match-string 2 string)
9644 (match-string 1 string))
9645 eq (match-string 3 string)
9646 eq-alist (cons (cons scol eq) eq-alist))
9647 (if (member scol seen)
9648 (if noerror
9649 (progn
9650 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9651 (ding)
9652 (sit-for 2))
9653 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9654 (push scol seen))))))
9655 (nreverse eq-alist)))
9657 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9658 "Modify the equations after the table structure has been edited.
9659 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9660 For all numbers larger than LIMIT, shift them by DELTA."
9661 (save-excursion
9662 (goto-char (org-table-end))
9663 (when (looking-at "#\\+TBLFM:")
9664 (let ((re (concat key "\\([0-9]+\\)"))
9665 (re2
9666 (when remove
9667 (if (equal key "$")
9668 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9669 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9670 s n a)
9671 (when remove
9672 (while (re-search-forward re2 (point-at-eol) t)
9673 (replace-match "")))
9674 (while (re-search-forward re (point-at-eol) t)
9675 (setq s (match-string 1) n (string-to-number s))
9676 (cond
9677 ((setq a (assoc s replace))
9678 (replace-match (concat key (cdr a)) t t))
9679 ((and limit (> n limit))
9680 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9682 (defun org-table-get-specials ()
9683 "Get the column names and local parameters for this table."
9684 (save-excursion
9685 (let ((beg (org-table-begin)) (end (org-table-end))
9686 names name fields fields1 field cnt
9687 c v l line col types dlines hlines)
9688 (setq org-table-column-names nil
9689 org-table-local-parameters nil
9690 org-table-named-field-locations nil
9691 org-table-current-begin-line nil
9692 org-table-current-begin-pos nil
9693 org-table-current-line-types nil)
9694 (goto-char beg)
9695 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9696 (setq names (org-split-string (match-string 1) " *| *")
9697 cnt 1)
9698 (while (setq name (pop names))
9699 (setq cnt (1+ cnt))
9700 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9701 (push (cons name (int-to-string cnt)) org-table-column-names))))
9702 (setq org-table-column-names (nreverse org-table-column-names))
9703 (setq org-table-column-name-regexp
9704 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9705 (goto-char beg)
9706 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9707 (setq fields (org-split-string (match-string 1) " *| *"))
9708 (while (setq field (pop fields))
9709 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9710 (push (cons (match-string 1 field) (match-string 2 field))
9711 org-table-local-parameters))))
9712 (goto-char beg)
9713 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9714 (setq c (match-string 1)
9715 fields (org-split-string (match-string 2) " *| *"))
9716 (save-excursion
9717 (beginning-of-line (if (equal c "_") 2 0))
9718 (setq line (org-current-line) col 1)
9719 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9720 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9721 (while (and fields1 (setq field (pop fields)))
9722 (setq v (pop fields1) col (1+ col))
9723 (when (and (stringp field) (stringp v)
9724 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9725 (push (cons field v) org-table-local-parameters)
9726 (push (list field line col) org-table-named-field-locations))))
9727 ;; Analyse the line types
9728 (goto-char beg)
9729 (setq org-table-current-begin-line (org-current-line)
9730 org-table-current-begin-pos (point)
9731 l org-table-current-begin-line)
9732 (while (looking-at "[ \t]*|\\(-\\)?")
9733 (push (if (match-end 1) 'hline 'dline) types)
9734 (if (match-end 1) (push l hlines) (push l dlines))
9735 (beginning-of-line 2)
9736 (setq l (1+ l)))
9737 (setq org-table-current-line-types (apply 'vector (nreverse types))
9738 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9739 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9741 (defun org-table-maybe-eval-formula ()
9742 "Check if the current field starts with \"=\" or \":=\".
9743 If yes, store the formula and apply it."
9744 ;; We already know we are in a table. Get field will only return a formula
9745 ;; when appropriate. It might return a separator line, but no problem.
9746 (when org-table-formula-evaluate-inline
9747 (let* ((field (org-trim (or (org-table-get-field) "")))
9748 named eq)
9749 (when (string-match "^:?=\\(.*\\)" field)
9750 (setq named (equal (string-to-char field) ?:)
9751 eq (match-string 1 field))
9752 (if (or (fboundp 'calc-eval)
9753 (equal (substring eq 0 (min 2 (length eq))) "'("))
9754 (org-table-eval-formula (if named '(4) nil)
9755 (org-table-formula-from-user eq))
9756 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9758 (defvar org-recalc-commands nil
9759 "List of commands triggering the recalculation of a line.
9760 Will be filled automatically during use.")
9762 (defvar org-recalc-marks
9763 '((" " . "Unmarked: no special line, no automatic recalculation")
9764 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9765 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9766 ("!" . "Column name definition line. Reference in formula as $name.")
9767 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9768 ("_" . "Names for values in row below this one.")
9769 ("^" . "Names for values in row above this one.")))
9771 (defun org-table-rotate-recalc-marks (&optional newchar)
9772 "Rotate the recalculation mark in the first column.
9773 If in any row, the first field is not consistent with a mark,
9774 insert a new column for the markers.
9775 When there is an active region, change all the lines in the region,
9776 after prompting for the marking character.
9777 After each change, a message will be displayed indicating the meaning
9778 of the new mark."
9779 (interactive)
9780 (unless (org-at-table-p) (error "Not at a table"))
9781 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9782 (beg (org-table-begin))
9783 (end (org-table-end))
9784 (l (org-current-line))
9785 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9786 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9787 (have-col
9788 (save-excursion
9789 (goto-char beg)
9790 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9791 (col (org-table-current-column))
9792 (forcenew (car (assoc newchar org-recalc-marks)))
9793 epos new)
9794 (when l1
9795 (message "Change region to what mark? Type # * ! $ or SPC: ")
9796 (setq newchar (char-to-string (read-char-exclusive))
9797 forcenew (car (assoc newchar org-recalc-marks))))
9798 (if (and newchar (not forcenew))
9799 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9800 newchar))
9801 (if l1 (goto-line l1))
9802 (save-excursion
9803 (beginning-of-line 1)
9804 (unless (looking-at org-table-dataline-regexp)
9805 (error "Not at a table data line")))
9806 (unless have-col
9807 (org-table-goto-column 1)
9808 (org-table-insert-column)
9809 (org-table-goto-column (1+ col)))
9810 (setq epos (point-at-eol))
9811 (save-excursion
9812 (beginning-of-line 1)
9813 (org-table-get-field
9814 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9815 (concat " "
9816 (setq new (or forcenew
9817 (cadr (member (match-string 1) marks))))
9818 " ")
9819 " # ")))
9820 (if (and l1 l2)
9821 (progn
9822 (goto-line l1)
9823 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9824 (and (looking-at org-table-dataline-regexp)
9825 (org-table-get-field 1 (concat " " new " "))))
9826 (goto-line l1)))
9827 (if (not (= epos (point-at-eol))) (org-table-align))
9828 (goto-line l)
9829 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
9831 (defun org-table-maybe-recalculate-line ()
9832 "Recompute the current line if marked for it, and if we haven't just done it."
9833 (interactive)
9834 (and org-table-allow-automatic-line-recalculation
9835 (not (and (memq last-command org-recalc-commands)
9836 (equal org-last-recalc-line (org-current-line))))
9837 (save-excursion (beginning-of-line 1)
9838 (looking-at org-table-auto-recalculate-regexp))
9839 (org-table-recalculate) t))
9841 (defvar org-table-formula-debug nil
9842 "Non-nil means, debug table formulas.
9843 When nil, simply write \"#ERROR\" in corrupted fields.")
9844 (make-variable-buffer-local 'org-table-formula-debug)
9846 (defvar modes)
9847 (defsubst org-set-calc-mode (var &optional value)
9848 (if (stringp var)
9849 (setq var (assoc var '(("D" calc-angle-mode deg)
9850 ("R" calc-angle-mode rad)
9851 ("F" calc-prefer-frac t)
9852 ("S" calc-symbolic-mode t)))
9853 value (nth 2 var) var (nth 1 var)))
9854 (if (memq var modes)
9855 (setcar (cdr (memq var modes)) value)
9856 (cons var (cons value modes)))
9857 modes)
9859 (defun org-table-eval-formula (&optional arg equation
9860 suppress-align suppress-const
9861 suppress-store suppress-analysis)
9862 "Replace the table field value at the cursor by the result of a calculation.
9864 This function makes use of Dave Gillespie's Calc package, in my view the
9865 most exciting program ever written for GNU Emacs. So you need to have Calc
9866 installed in order to use this function.
9868 In a table, this command replaces the value in the current field with the
9869 result of a formula. It also installs the formula as the \"current\" column
9870 formula, by storing it in a special line below the table. When called
9871 with a `C-u' prefix, the current field must ba a named field, and the
9872 formula is installed as valid in only this specific field.
9874 When called with two `C-u' prefixes, insert the active equation
9875 for the field back into the current field, so that it can be
9876 edited there. This is useful in order to use \\[org-table-show-reference]
9877 to check the referenced fields.
9879 When called, the command first prompts for a formula, which is read in
9880 the minibuffer. Previously entered formulas are available through the
9881 history list, and the last used formula is offered as a default.
9882 These stored formulas are adapted correctly when moving, inserting, or
9883 deleting columns with the corresponding commands.
9885 The formula can be any algebraic expression understood by the Calc package.
9886 For details, see the Org-mode manual.
9888 This function can also be called from Lisp programs and offers
9889 additional arguments: EQUATION can be the formula to apply. If this
9890 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9891 used to speed-up recursive calls by by-passing unnecessary aligns.
9892 SUPPRESS-CONST suppresses the interpretation of constants in the
9893 formula, assuming that this has been done already outside the function.
9894 SUPPRESS-STORE means the formula should not be stored, either because
9895 it is already stored, or because it is a modified equation that should
9896 not overwrite the stored one."
9897 (interactive "P")
9898 (org-table-check-inside-data-field)
9899 (or suppress-analysis (org-table-get-specials))
9900 (if (equal arg '(16))
9901 (let ((eq (org-table-current-field-formula)))
9902 (or eq (error "No equation active for current field"))
9903 (org-table-get-field nil eq)
9904 (org-table-align)
9905 (setq org-table-may-need-update t))
9906 (let* (fields
9907 (ndown (if (integerp arg) arg 1))
9908 (org-table-automatic-realign nil)
9909 (case-fold-search nil)
9910 (down (> ndown 1))
9911 (formula (if (and equation suppress-store)
9912 equation
9913 (org-table-get-formula equation (equal arg '(4)))))
9914 (n0 (org-table-current-column))
9915 (modes (copy-sequence org-calc-default-modes))
9916 (numbers nil) ; was a variable, now fixed default
9917 (keep-empty nil)
9918 n form form0 bw fmt x ev orig c lispp literal)
9919 ;; Parse the format string. Since we have a lot of modes, this is
9920 ;; a lot of work. However, I think calc still uses most of the time.
9921 (if (string-match ";" formula)
9922 (let ((tmp (org-split-string formula ";")))
9923 (setq formula (car tmp)
9924 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9925 (nth 1 tmp)))
9926 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9927 (setq c (string-to-char (match-string 1 fmt))
9928 n (string-to-number (match-string 2 fmt)))
9929 (if (= c ?p)
9930 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9931 (setq modes (org-set-calc-mode
9932 'calc-float-format
9933 (list (cdr (assoc c '((?n . float) (?f . fix)
9934 (?s . sci) (?e . eng))))
9935 n))))
9936 (setq fmt (replace-match "" t t fmt)))
9937 (if (string-match "[NT]" fmt)
9938 (setq numbers (equal (match-string 0 fmt) "N")
9939 fmt (replace-match "" t t fmt)))
9940 (if (string-match "L" fmt)
9941 (setq literal t
9942 fmt (replace-match "" t t fmt)))
9943 (if (string-match "E" fmt)
9944 (setq keep-empty t
9945 fmt (replace-match "" t t fmt)))
9946 (while (string-match "[DRFS]" fmt)
9947 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9948 (setq fmt (replace-match "" t t fmt)))
9949 (unless (string-match "\\S-" fmt)
9950 (setq fmt nil))))
9951 (if (and (not suppress-const) org-table-formula-use-constants)
9952 (setq formula (org-table-formula-substitute-names formula)))
9953 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9954 (while (> ndown 0)
9955 (setq fields (org-split-string
9956 (org-no-properties
9957 (buffer-substring (point-at-bol) (point-at-eol)))
9958 " *| *"))
9959 (if (eq numbers t)
9960 (setq fields (mapcar
9961 (lambda (x) (number-to-string (string-to-number x)))
9962 fields)))
9963 (setq ndown (1- ndown))
9964 (setq form (copy-sequence formula)
9965 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9966 (if (and lispp literal) (setq lispp 'literal))
9967 ;; Check for old vertical references
9968 (setq form (org-rewrite-old-row-references form))
9969 ;; Insert complex ranges
9970 (while (string-match org-table-range-regexp form)
9971 (setq form
9972 (replace-match
9973 (save-match-data
9974 (org-table-make-reference
9975 (org-table-get-range (match-string 0 form) nil n0)
9976 keep-empty numbers lispp))
9977 t t form)))
9978 ;; Insert simple ranges
9979 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9980 (setq form
9981 (replace-match
9982 (save-match-data
9983 (org-table-make-reference
9984 (org-sublist
9985 fields (string-to-number (match-string 1 form))
9986 (string-to-number (match-string 2 form)))
9987 keep-empty numbers lispp))
9988 t t form)))
9989 (setq form0 form)
9990 ;; Insert the references to fields in same row
9991 (while (string-match "\\$\\([0-9]+\\)" form)
9992 (setq n (string-to-number (match-string 1 form))
9993 x (nth (1- (if (= n 0) n0 n)) fields))
9994 (unless x (error "Invalid field specifier \"%s\""
9995 (match-string 0 form)))
9996 (setq form (replace-match
9997 (save-match-data
9998 (org-table-make-reference x nil numbers lispp))
9999 t t form)))
10001 (if lispp
10002 (setq ev (condition-case nil
10003 (eval (eval (read form)))
10004 (error "#ERROR"))
10005 ev (if (numberp ev) (number-to-string ev) ev))
10006 (or (fboundp 'calc-eval)
10007 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10008 (setq ev (calc-eval (cons form modes)
10009 (if numbers 'num))))
10011 (when org-table-formula-debug
10012 (with-output-to-temp-buffer "*Substitution History*"
10013 (princ (format "Substitution history of formula
10014 Orig: %s
10015 $xyz-> %s
10016 @r$c-> %s
10017 $1-> %s\n" orig formula form0 form))
10018 (if (listp ev)
10019 (princ (format " %s^\nError: %s"
10020 (make-string (car ev) ?\-) (nth 1 ev)))
10021 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10022 ev (or fmt "NONE")
10023 (if fmt (format fmt (string-to-number ev)) ev)))))
10024 (setq bw (get-buffer-window "*Substitution History*"))
10025 (shrink-window-if-larger-than-buffer bw)
10026 (unless (and (interactive-p) (not ndown))
10027 (unless (let (inhibit-redisplay)
10028 (y-or-n-p "Debugging Formula. Continue to next? "))
10029 (org-table-align)
10030 (error "Abort"))
10031 (delete-window bw)
10032 (message "")))
10033 (if (listp ev) (setq fmt nil ev "#ERROR"))
10034 (org-table-justify-field-maybe
10035 (if fmt (format fmt (string-to-number ev)) ev))
10036 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10037 (call-interactively 'org-return)
10038 (setq ndown 0)))
10039 (and down (org-table-maybe-recalculate-line))
10040 (or suppress-align (and org-table-may-need-update
10041 (org-table-align))))))
10043 (defun org-table-put-field-property (prop value)
10044 (save-excursion
10045 (put-text-property (progn (skip-chars-backward "^|") (point))
10046 (progn (skip-chars-forward "^|") (point))
10047 prop value)))
10049 (defun org-table-get-range (desc &optional tbeg col highlight)
10050 "Get a calc vector from a column, accorting to descriptor DESC.
10051 Optional arguments TBEG and COL can give the beginning of the table and
10052 the current column, to avoid unnecessary parsing.
10053 HIGHLIGHT means, just highlight the range."
10054 (if (not (equal (string-to-char desc) ?@))
10055 (setq desc (concat "@" desc)))
10056 (save-excursion
10057 (or tbeg (setq tbeg (org-table-begin)))
10058 (or col (setq col (org-table-current-column)))
10059 (let ((thisline (org-current-line))
10060 beg end c1 c2 r1 r2 rangep tmp)
10061 (unless (string-match org-table-range-regexp desc)
10062 (error "Invalid table range specifier `%s'" desc))
10063 (setq rangep (match-end 3)
10064 r1 (and (match-end 1) (match-string 1 desc))
10065 r2 (and (match-end 4) (match-string 4 desc))
10066 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10067 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10069 (and c1 (setq c1 (+ (string-to-number c1)
10070 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10071 (and c2 (setq c2 (+ (string-to-number c2)
10072 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10073 (if (equal r1 "") (setq r1 nil))
10074 (if (equal r2 "") (setq r2 nil))
10075 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10076 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10077 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10078 (if (not r1) (setq r1 thisline))
10079 (if (not r2) (setq r2 thisline))
10080 (if (not c1) (setq c1 col))
10081 (if (not c2) (setq c2 col))
10082 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10083 ;; just one field
10084 (progn
10085 (goto-line r1)
10086 (while (not (looking-at org-table-dataline-regexp))
10087 (beginning-of-line 2))
10088 (prog1 (org-trim (org-table-get-field c1))
10089 (if highlight (org-table-highlight-rectangle (point) (point)))))
10090 ;; A range, return a vector
10091 ;; First sort the numbers to get a regular ractangle
10092 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10093 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10094 (goto-line r1)
10095 (while (not (looking-at org-table-dataline-regexp))
10096 (beginning-of-line 2))
10097 (org-table-goto-column c1)
10098 (setq beg (point))
10099 (goto-line r2)
10100 (while (not (looking-at org-table-dataline-regexp))
10101 (beginning-of-line 0))
10102 (org-table-goto-column c2)
10103 (setq end (point))
10104 (if highlight
10105 (org-table-highlight-rectangle
10106 beg (progn (skip-chars-forward "^|\n") (point))))
10107 ;; return string representation of calc vector
10108 (mapcar 'org-trim
10109 (apply 'append (org-table-copy-region beg end)))))))
10111 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10112 "Analyze descriptor DESC and retrieve the corresponding line number.
10113 The cursor is currently in line CLINE, the table begins in line BLINE,
10114 and TABLE is a vector with line types."
10115 (if (string-match "^[0-9]+$" desc)
10116 (aref org-table-dlines (string-to-number desc))
10117 (setq cline (or cline (org-current-line))
10118 bline (or bline org-table-current-begin-line)
10119 table (or table org-table-current-line-types))
10120 (if (or
10121 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10122 ;; 1 2 3 4 5 6
10123 (and (not (match-end 3)) (not (match-end 6)))
10124 (and (match-end 3) (match-end 6) (not (match-end 5))))
10125 (error "invalid row descriptor `%s'" desc))
10126 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10127 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10128 (odir (and (match-end 5) (match-string 5 desc)))
10129 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10130 (i (- cline bline))
10131 (rel (and (match-end 6)
10132 (or (and (match-end 1) (not (match-end 3)))
10133 (match-end 5)))))
10134 (if (and hn (not hdir))
10135 (progn
10136 (setq i 0 hdir "+")
10137 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10138 (if (and (not hn) on (not odir))
10139 (error "should never happen");;(aref org-table-dlines on)
10140 (if (and hn (> hn 0))
10141 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10142 (if on
10143 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10144 (+ bline i)))))
10146 (defun org-find-row-type (table i type backwards relative n)
10147 (let ((l (length table)))
10148 (while (> n 0)
10149 (while (and (setq i (+ i (if backwards -1 1)))
10150 (>= i 0) (< i l)
10151 (not (eq (aref table i) type))
10152 (if (and relative (eq (aref table i) 'hline))
10153 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10154 t)))
10155 (setq n (1- n)))
10156 (if (or (< i 0) (>= i l))
10157 (error "Row descriptior leads outside table")
10158 i)))
10160 (defun org-rewrite-old-row-references (s)
10161 (if (string-match "&[-+0-9I]" s)
10162 (error "Formula contains old &row reference, please rewrite using @-syntax")
10165 (defun org-table-make-reference (elements keep-empty numbers lispp)
10166 "Convert list ELEMENTS to something appropriate to insert into formula.
10167 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10168 NUMBERS indicates that everything should be converted to numbers.
10169 LISPP means to return something appropriate for a Lisp list."
10170 (if (stringp elements) ; just a single val
10171 (if lispp
10172 (if (eq lispp 'literal)
10173 elements
10174 (prin1-to-string (if numbers (string-to-number elements) elements)))
10175 (if (equal elements "") (setq elements "0"))
10176 (if numbers (number-to-string (string-to-number elements)) elements))
10177 (unless keep-empty
10178 (setq elements
10179 (delq nil
10180 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10181 elements))))
10182 (setq elements (or elements '("0")))
10183 (if lispp
10184 (mapconcat
10185 (lambda (x)
10186 (if (eq lispp 'literal)
10188 (prin1-to-string (if numbers (string-to-number x) x))))
10189 elements " ")
10190 (concat "[" (mapconcat
10191 (lambda (x)
10192 (if numbers (number-to-string (string-to-number x)) x))
10193 elements
10194 ",") "]"))))
10196 (defun org-table-recalculate (&optional all noalign)
10197 "Recalculate the current table line by applying all stored formulas.
10198 With prefix arg ALL, do this for all lines in the table."
10199 (interactive "P")
10200 (or (memq this-command org-recalc-commands)
10201 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10202 (unless (org-at-table-p) (error "Not at a table"))
10203 (if (equal all '(16))
10204 (org-table-iterate)
10205 (org-table-get-specials)
10206 (let* ((eqlist (sort (org-table-get-stored-formulas)
10207 (lambda (a b) (string< (car a) (car b)))))
10208 (inhibit-redisplay (not debug-on-error))
10209 (line-re org-table-dataline-regexp)
10210 (thisline (org-current-line))
10211 (thiscol (org-table-current-column))
10212 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10213 ;; Insert constants in all formulas
10214 (setq eqlist
10215 (mapcar (lambda (x)
10216 (setcdr x (org-table-formula-substitute-names (cdr x)))
10218 eqlist))
10219 ;; Split the equation list
10220 (while (setq eq (pop eqlist))
10221 (if (<= (string-to-char (car eq)) ?9)
10222 (push eq eqlnum)
10223 (push eq eqlname)))
10224 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10225 (if all
10226 (progn
10227 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10228 (goto-char (setq beg (org-table-begin)))
10229 (if (re-search-forward org-table-calculate-mark-regexp end t)
10230 ;; This is a table with marked lines, compute selected lines
10231 (setq line-re org-table-recalculate-regexp)
10232 ;; Move forward to the first non-header line
10233 (if (and (re-search-forward org-table-dataline-regexp end t)
10234 (re-search-forward org-table-hline-regexp end t)
10235 (re-search-forward org-table-dataline-regexp end t))
10236 (setq beg (match-beginning 0))
10237 nil))) ;; just leave beg where it is
10238 (setq beg (point-at-bol)
10239 end (move-marker (make-marker) (1+ (point-at-eol)))))
10240 (goto-char beg)
10241 (and all (message "Re-applying formulas to full table..."))
10243 ;; First find the named fields, and mark them untouchanble
10244 (remove-text-properties beg end '(org-untouchable t))
10245 (while (setq eq (pop eqlname))
10246 (setq name (car eq)
10247 a (assoc name org-table-named-field-locations))
10248 (and (not a)
10249 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10250 (setq a (list name
10251 (aref org-table-dlines
10252 (string-to-number (match-string 1 name)))
10253 (string-to-number (match-string 2 name)))))
10254 (when (and a (or all (equal (nth 1 a) thisline)))
10255 (message "Re-applying formula to field: %s" name)
10256 (goto-line (nth 1 a))
10257 (org-table-goto-column (nth 2 a))
10258 (push (append a (list (cdr eq))) eqlname1)
10259 (org-table-put-field-property :org-untouchable t)))
10261 ;; Now evauluate the column formulas, but skip fields covered by
10262 ;; field formulas
10263 (goto-char beg)
10264 (while (re-search-forward line-re end t)
10265 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10266 ;; Unprotected line, recalculate
10267 (and all (message "Re-applying formulas to full table...(line %d)"
10268 (setq cnt (1+ cnt))))
10269 (setq org-last-recalc-line (org-current-line))
10270 (setq eql eqlnum)
10271 (while (setq entry (pop eql))
10272 (goto-line org-last-recalc-line)
10273 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10274 (unless (get-text-property (point) :org-untouchable)
10275 (org-table-eval-formula nil (cdr entry)
10276 'noalign 'nocst 'nostore 'noanalysis)))))
10278 ;; Now evaluate the field formulas
10279 (while (setq eq (pop eqlname1))
10280 (message "Re-applying formula to field: %s" (car eq))
10281 (goto-line (nth 1 eq))
10282 (org-table-goto-column (nth 2 eq))
10283 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10284 'nostore 'noanalysis))
10286 (goto-line thisline)
10287 (org-table-goto-column thiscol)
10288 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10289 (or noalign (and org-table-may-need-update (org-table-align))
10290 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10292 ;; back to initial position
10293 (message "Re-applying formulas...done")
10294 (goto-line thisline)
10295 (org-table-goto-column thiscol)
10296 (or noalign (and org-table-may-need-update (org-table-align))
10297 (and all (message "Re-applying formulas...done"))))))
10299 (defun org-table-iterate (&optional arg)
10300 "Recalculate the table until it does not change anymore."
10301 (interactive "P")
10302 (let ((imax (if arg (prefix-numeric-value arg) 10))
10303 (i 0)
10304 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10305 thistbl)
10306 (catch 'exit
10307 (while (< i imax)
10308 (setq i (1+ i))
10309 (org-table-recalculate 'all)
10310 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10311 (if (not (string= lasttbl thistbl))
10312 (setq lasttbl thistbl)
10313 (if (> i 1)
10314 (message "Convergence after %d iterations" i)
10315 (message "Table was already stable"))
10316 (throw 'exit t)))
10317 (error "No convergence after %d iterations" i))))
10319 (defun org-table-formula-substitute-names (f)
10320 "Replace $const with values in string F."
10321 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10322 ;; First, check for column names
10323 (while (setq start (string-match org-table-column-name-regexp f start))
10324 (setq start (1+ start))
10325 (setq a (assoc (match-string 1 f) org-table-column-names))
10326 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10327 ;; Parameters and constants
10328 (setq start 0)
10329 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10330 (setq start (1+ start))
10331 (if (setq a (save-match-data
10332 (org-table-get-constant (match-string 1 f))))
10333 (setq f (replace-match
10334 (concat (if pp "(") a (if pp ")")) t t f))))
10335 (if org-table-formula-debug
10336 (put-text-property 0 (length f) :orig-formula f1 f))
10339 (defun org-table-get-constant (const)
10340 "Find the value for a parameter or constant in a formula.
10341 Parameters get priority."
10342 (or (cdr (assoc const org-table-local-parameters))
10343 (cdr (assoc const org-table-formula-constants-local))
10344 (cdr (assoc const org-table-formula-constants))
10345 (and (fboundp 'constants-get) (constants-get const))
10346 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10347 (org-entry-get nil (substring const 5) 'inherit))
10348 "#UNDEFINED_NAME"))
10350 (defvar org-table-fedit-map
10351 (let ((map (make-sparse-keymap)))
10352 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10353 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10354 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10355 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10356 (org-defkey map "\C-c?" 'org-table-show-reference)
10357 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10358 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10359 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10360 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10361 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10362 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10363 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10364 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10365 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10366 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10367 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10368 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10369 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10370 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10371 map))
10373 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10374 '("Edit-Formulas"
10375 ["Finish and Install" org-table-fedit-finish t]
10376 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10377 ["Abort" org-table-fedit-abort t]
10378 "--"
10379 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10380 ["Complete Lisp Symbol" lisp-complete-symbol t]
10381 "--"
10382 "Shift Reference at Point"
10383 ["Up" org-table-fedit-ref-up t]
10384 ["Down" org-table-fedit-ref-down t]
10385 ["Left" org-table-fedit-ref-left t]
10386 ["Right" org-table-fedit-ref-right t]
10388 "Change Test Row for Column Formulas"
10389 ["Up" org-table-fedit-line-up t]
10390 ["Down" org-table-fedit-line-down t]
10391 "--"
10392 ["Scroll Table Window" org-table-fedit-scroll t]
10393 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10394 ["Show Table Grid" org-table-fedit-toggle-coordinates
10395 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10396 org-table-overlay-coordinates)]
10397 "--"
10398 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10399 :style toggle :selected org-table-buffer-is-an]))
10401 (defvar org-pos)
10403 (defun org-table-edit-formulas ()
10404 "Edit the formulas of the current table in a separate buffer."
10405 (interactive)
10406 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10407 (beginning-of-line 0))
10408 (unless (org-at-table-p) (error "Not at a table"))
10409 (org-table-get-specials)
10410 (let ((key (org-table-current-field-formula 'key 'noerror))
10411 (eql (sort (org-table-get-stored-formulas 'noerror)
10412 'org-table-formula-less-p))
10413 (pos (move-marker (make-marker) (point)))
10414 (startline 1)
10415 (wc (current-window-configuration))
10416 (titles '((column . "# Column Formulas\n")
10417 (field . "# Field Formulas\n")
10418 (named . "# Named Field Formulas\n")))
10419 entry s type title)
10420 (org-switch-to-buffer-other-window "*Edit Formulas*")
10421 (erase-buffer)
10422 ;; Keep global-font-lock-mode from turning on font-lock-mode
10423 (let ((font-lock-global-modes '(not fundamental-mode)))
10424 (fundamental-mode))
10425 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10426 (org-set-local 'org-pos pos)
10427 (org-set-local 'org-window-configuration wc)
10428 (use-local-map org-table-fedit-map)
10429 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10430 (easy-menu-add org-table-fedit-menu)
10431 (setq startline (org-current-line))
10432 (while (setq entry (pop eql))
10433 (setq type (cond
10434 ((equal (string-to-char (car entry)) ?@) 'field)
10435 ((string-match "^[0-9]" (car entry)) 'column)
10436 (t 'named)))
10437 (when (setq title (assq type titles))
10438 (or (bobp) (insert "\n"))
10439 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10440 (setq titles (delq title titles)))
10441 (if (equal key (car entry)) (setq startline (org-current-line)))
10442 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10443 (car entry) " = " (cdr entry) "\n"))
10444 (remove-text-properties 0 (length s) '(face nil) s)
10445 (insert s))
10446 (if (eq org-table-use-standard-references t)
10447 (org-table-fedit-toggle-ref-type))
10448 (goto-line startline)
10449 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10451 (defun org-table-fedit-post-command ()
10452 (when (not (memq this-command '(lisp-complete-symbol)))
10453 (let ((win (selected-window)))
10454 (save-excursion
10455 (condition-case nil
10456 (org-table-show-reference)
10457 (error nil))
10458 (select-window win)))))
10460 (defun org-table-formula-to-user (s)
10461 "Convert a formula from internal to user representation."
10462 (if (eq org-table-use-standard-references t)
10463 (org-table-convert-refs-to-an s)
10466 (defun org-table-formula-from-user (s)
10467 "Convert a formula from user to internal representation."
10468 (if org-table-use-standard-references
10469 (org-table-convert-refs-to-rc s)
10472 (defun org-table-convert-refs-to-rc (s)
10473 "Convert spreadsheet references from AB7 to @7$28.
10474 Works for single references, but also for entire formulas and even the
10475 full TBLFM line."
10476 (let ((start 0))
10477 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10478 (cond
10479 ((match-end 3)
10480 ;; format match, just advance
10481 (setq start (match-end 0)))
10482 ((and (> (match-beginning 0) 0)
10483 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10484 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10485 ;; 3.e5 or something like this.
10486 (setq start (match-end 0)))
10488 (setq start (match-beginning 0)
10489 s (replace-match
10490 (if (equal (match-string 2 s) "&")
10491 (format "$%d" (org-letters-to-number (match-string 1 s)))
10492 (format "@%d$%d"
10493 (string-to-number (match-string 2 s))
10494 (org-letters-to-number (match-string 1 s))))
10495 t t s)))))
10498 (defun org-table-convert-refs-to-an (s)
10499 "Convert spreadsheet references from to @7$28 to AB7.
10500 Works for single references, but also for entire formulas and even the
10501 full TBLFM line."
10502 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10503 (setq s (replace-match
10504 (format "%s%d"
10505 (org-number-to-letters
10506 (string-to-number (match-string 2 s)))
10507 (string-to-number (match-string 1 s)))
10508 t t s)))
10509 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10510 (setq s (replace-match (concat "\\1"
10511 (org-number-to-letters
10512 (string-to-number (match-string 2 s))) "&")
10513 t nil s)))
10516 (defun org-letters-to-number (s)
10517 "Convert a base 26 number represented by letters into an integer.
10518 For example: AB -> 28."
10519 (let ((n 0))
10520 (setq s (upcase s))
10521 (while (> (length s) 0)
10522 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10523 s (substring s 1)))
10526 (defun org-number-to-letters (n)
10527 "Convert an integer into a base 26 number represented by letters.
10528 For example: 28 -> AB."
10529 (let ((s ""))
10530 (while (> n 0)
10531 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10532 n (/ (1- n) 26)))
10535 (defun org-table-fedit-convert-buffer (function)
10536 "Convert all references in this buffer, using FUNTION."
10537 (let ((line (org-current-line)))
10538 (goto-char (point-min))
10539 (while (not (eobp))
10540 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10541 (delete-region (point) (point-at-eol))
10542 (or (eobp) (forward-char 1)))
10543 (goto-line line)))
10545 (defun org-table-fedit-toggle-ref-type ()
10546 "Convert all references in the buffer from B3 to @3$2 and back."
10547 (interactive)
10548 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10549 (org-table-fedit-convert-buffer
10550 (if org-table-buffer-is-an
10551 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10552 (message "Reference type switched to %s"
10553 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10555 (defun org-table-fedit-ref-up ()
10556 "Shift the reference at point one row/hline up."
10557 (interactive)
10558 (org-table-fedit-shift-reference 'up))
10559 (defun org-table-fedit-ref-down ()
10560 "Shift the reference at point one row/hline down."
10561 (interactive)
10562 (org-table-fedit-shift-reference 'down))
10563 (defun org-table-fedit-ref-left ()
10564 "Shift the reference at point one field to the left."
10565 (interactive)
10566 (org-table-fedit-shift-reference 'left))
10567 (defun org-table-fedit-ref-right ()
10568 "Shift the reference at point one field to the right."
10569 (interactive)
10570 (org-table-fedit-shift-reference 'right))
10572 (defun org-table-fedit-shift-reference (dir)
10573 (cond
10574 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10575 (if (memq dir '(left right))
10576 (org-rematch-and-replace 1 (eq dir 'left))
10577 (error "Cannot shift reference in this direction")))
10578 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10579 ;; A B3-like reference
10580 (if (memq dir '(up down))
10581 (org-rematch-and-replace 2 (eq dir 'up))
10582 (org-rematch-and-replace 1 (eq dir 'left))))
10583 ((org-at-regexp-p
10584 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10585 ;; An internal reference
10586 (if (memq dir '(up down))
10587 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10588 (org-rematch-and-replace 5 (eq dir 'left))))))
10590 (defun org-rematch-and-replace (n &optional decr hline)
10591 "Re-match the group N, and replace it with the shifted refrence."
10592 (or (match-end n) (error "Cannot shift reference in this direction"))
10593 (goto-char (match-beginning n))
10594 (and (looking-at (regexp-quote (match-string n)))
10595 (replace-match (org-shift-refpart (match-string 0) decr hline)
10596 t t)))
10598 (defun org-shift-refpart (ref &optional decr hline)
10599 "Shift a refrence part REF.
10600 If DECR is set, decrease the references row/column, else increase.
10601 If HLINE is set, this may be a hline reference, it certainly is not
10602 a translation reference."
10603 (save-match-data
10604 (let* ((sign (string-match "^[-+]" ref)) n)
10606 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10607 (cond
10608 ((and hline (string-match "^I+" ref))
10609 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10610 (setq n (+ n (if decr -1 1)))
10611 (if (= n 0) (setq n (+ n (if decr -1 1))))
10612 (if sign
10613 (setq sign (if (< n 0) "-" "+") n (abs n))
10614 (setq n (max 1 n)))
10615 (concat sign (make-string n ?I)))
10617 ((string-match "^[0-9]+" ref)
10618 (setq n (string-to-number (concat sign ref)))
10619 (setq n (+ n (if decr -1 1)))
10620 (if sign
10621 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10622 (number-to-string (max 1 n))))
10624 ((string-match "^[a-zA-Z]+" ref)
10625 (org-number-to-letters
10626 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10628 (t (error "Cannot shift reference"))))))
10630 (defun org-table-fedit-toggle-coordinates ()
10631 "Toggle the display of coordinates in the refrenced table."
10632 (interactive)
10633 (let ((pos (marker-position org-pos)))
10634 (with-current-buffer (marker-buffer org-pos)
10635 (save-excursion
10636 (goto-char pos)
10637 (org-table-toggle-coordinate-overlays)))))
10639 (defun org-table-fedit-finish (&optional arg)
10640 "Parse the buffer for formula definitions and install them.
10641 With prefix ARG, apply the new formulas to the table."
10642 (interactive "P")
10643 (org-table-remove-rectangle-highlight)
10644 (if org-table-use-standard-references
10645 (progn
10646 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10647 (setq org-table-buffer-is-an nil)))
10648 (let ((pos org-pos) eql var form)
10649 (goto-char (point-min))
10650 (while (re-search-forward
10651 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10652 nil t)
10653 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10654 form (match-string 3))
10655 (setq form (org-trim form))
10656 (when (not (equal form ""))
10657 (while (string-match "[ \t]*\n[ \t]*" form)
10658 (setq form (replace-match " " t t form)))
10659 (when (assoc var eql)
10660 (error "Double formulas for %s" var))
10661 (push (cons var form) eql)))
10662 (setq org-pos nil)
10663 (set-window-configuration org-window-configuration)
10664 (select-window (get-buffer-window (marker-buffer pos)))
10665 (goto-char pos)
10666 (unless (org-at-table-p)
10667 (error "Lost table position - cannot install formulae"))
10668 (org-table-store-formulas eql)
10669 (move-marker pos nil)
10670 (kill-buffer "*Edit Formulas*")
10671 (if arg
10672 (org-table-recalculate 'all)
10673 (message "New formulas installed - press C-u C-c C-c to apply."))))
10675 (defun org-table-fedit-abort ()
10676 "Abort editing formulas, without installing the changes."
10677 (interactive)
10678 (org-table-remove-rectangle-highlight)
10679 (let ((pos org-pos))
10680 (set-window-configuration org-window-configuration)
10681 (select-window (get-buffer-window (marker-buffer pos)))
10682 (goto-char pos)
10683 (move-marker pos nil)
10684 (message "Formula editing aborted without installing changes")))
10686 (defun org-table-fedit-lisp-indent ()
10687 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10688 (interactive)
10689 (let ((pos (point)) beg end ind)
10690 (beginning-of-line 1)
10691 (cond
10692 ((looking-at "[ \t]")
10693 (goto-char pos)
10694 (call-interactively 'lisp-indent-line))
10695 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10696 ((not (fboundp 'pp-buffer))
10697 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10698 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10699 (goto-char (- (match-end 0) 2))
10700 (setq beg (point))
10701 (setq ind (make-string (current-column) ?\ ))
10702 (condition-case nil (forward-sexp 1)
10703 (error
10704 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10705 (setq end (point))
10706 (save-restriction
10707 (narrow-to-region beg end)
10708 (if (eq last-command this-command)
10709 (progn
10710 (goto-char (point-min))
10711 (setq this-command nil)
10712 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10713 (replace-match " ")))
10714 (pp-buffer)
10715 (untabify (point-min) (point-max))
10716 (goto-char (1+ (point-min)))
10717 (while (re-search-forward "^." nil t)
10718 (beginning-of-line 1)
10719 (insert ind))
10720 (goto-char (point-max))
10721 (backward-delete-char 1)))
10722 (goto-char beg))
10723 (t nil))))
10725 (defvar org-show-positions nil)
10727 (defun org-table-show-reference (&optional local)
10728 "Show the location/value of the $ expression at point."
10729 (interactive)
10730 (org-table-remove-rectangle-highlight)
10731 (catch 'exit
10732 (let ((pos (if local (point) org-pos))
10733 (face2 'highlight)
10734 (org-inhibit-highlight-removal t)
10735 (win (selected-window))
10736 (org-show-positions nil)
10737 var name e what match dest)
10738 (if local (org-table-get-specials))
10739 (setq what (cond
10740 ((or (org-at-regexp-p org-table-range-regexp2)
10741 (org-at-regexp-p org-table-translate-regexp)
10742 (org-at-regexp-p org-table-range-regexp))
10743 (setq match
10744 (save-match-data
10745 (org-table-convert-refs-to-rc (match-string 0))))
10746 'range)
10747 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10748 ((org-at-regexp-p "\\$[0-9]+") 'column)
10749 ((not local) nil)
10750 (t (error "No reference at point")))
10751 match (and what (or match (match-string 0))))
10752 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10753 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10754 'secondary-selection))
10755 (org-add-hook 'before-change-functions
10756 'org-table-remove-rectangle-highlight)
10757 (if (eq what 'name) (setq var (substring match 1)))
10758 (when (eq what 'range)
10759 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10760 (setq match (org-table-formula-substitute-names match)))
10761 (unless local
10762 (save-excursion
10763 (end-of-line 1)
10764 (re-search-backward "^\\S-" nil t)
10765 (beginning-of-line 1)
10766 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10767 (setq dest
10768 (save-match-data
10769 (org-table-convert-refs-to-rc (match-string 1))))
10770 (org-table-add-rectangle-overlay
10771 (match-beginning 1) (match-end 1) face2))))
10772 (if (and (markerp pos) (marker-buffer pos))
10773 (if (get-buffer-window (marker-buffer pos))
10774 (select-window (get-buffer-window (marker-buffer pos)))
10775 (org-switch-to-buffer-other-window (get-buffer-window
10776 (marker-buffer pos)))))
10777 (goto-char pos)
10778 (org-table-force-dataline)
10779 (when dest
10780 (setq name (substring dest 1))
10781 (cond
10782 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10783 (setq e (assoc name org-table-named-field-locations))
10784 (goto-line (nth 1 e))
10785 (org-table-goto-column (nth 2 e)))
10786 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10787 (let ((l (string-to-number (match-string 1 dest)))
10788 (c (string-to-number (match-string 2 dest))))
10789 (goto-line (aref org-table-dlines l))
10790 (org-table-goto-column c)))
10791 (t (org-table-goto-column (string-to-number name))))
10792 (move-marker pos (point))
10793 (org-table-highlight-rectangle nil nil face2))
10794 (cond
10795 ((equal dest match))
10796 ((not match))
10797 ((eq what 'range)
10798 (condition-case nil
10799 (save-excursion
10800 (org-table-get-range match nil nil 'highlight))
10801 (error nil)))
10802 ((setq e (assoc var org-table-named-field-locations))
10803 (goto-line (nth 1 e))
10804 (org-table-goto-column (nth 2 e))
10805 (org-table-highlight-rectangle (point) (point))
10806 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10807 ((setq e (assoc var org-table-column-names))
10808 (org-table-goto-column (string-to-number (cdr e)))
10809 (org-table-highlight-rectangle (point) (point))
10810 (goto-char (org-table-begin))
10811 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10812 (org-table-end) t)
10813 (progn
10814 (goto-char (match-beginning 1))
10815 (org-table-highlight-rectangle)
10816 (message "Named column (column %s)" (cdr e)))
10817 (error "Column name not found")))
10818 ((eq what 'column)
10819 ;; column number
10820 (org-table-goto-column (string-to-number (substring match 1)))
10821 (org-table-highlight-rectangle (point) (point))
10822 (message "Column %s" (substring match 1)))
10823 ((setq e (assoc var org-table-local-parameters))
10824 (goto-char (org-table-begin))
10825 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10826 (progn
10827 (goto-char (match-beginning 1))
10828 (org-table-highlight-rectangle)
10829 (message "Local parameter."))
10830 (error "Parameter not found")))
10832 (cond
10833 ((not var) (error "No reference at point"))
10834 ((setq e (assoc var org-table-formula-constants-local))
10835 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10836 var (cdr e)))
10837 ((setq e (assoc var org-table-formula-constants))
10838 (message "Constant: $%s=%s in `org-table-formula-constants'."
10839 var (cdr e)))
10840 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10841 (message "Constant: $%s=%s, from `constants.el'%s."
10842 var e (format " (%s units)" constants-unit-system)))
10843 (t (error "Undefined name $%s" var)))))
10844 (goto-char pos)
10845 (when (and org-show-positions
10846 (not (memq this-command '(org-table-fedit-scroll
10847 org-table-fedit-scroll-down))))
10848 (push pos org-show-positions)
10849 (push org-table-current-begin-pos org-show-positions)
10850 (let ((min (apply 'min org-show-positions))
10851 (max (apply 'max org-show-positions)))
10852 (goto-char min) (recenter 0)
10853 (goto-char max)
10854 (or (pos-visible-in-window-p max) (recenter -1))))
10855 (select-window win))))
10857 (defun org-table-force-dataline ()
10858 "Make sure the cursor is in a dataline in a table."
10859 (unless (save-excursion
10860 (beginning-of-line 1)
10861 (looking-at org-table-dataline-regexp))
10862 (let* ((re org-table-dataline-regexp)
10863 (p1 (save-excursion (re-search-forward re nil 'move)))
10864 (p2 (save-excursion (re-search-backward re nil 'move))))
10865 (cond ((and p1 p2)
10866 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10867 p1 p2)))
10868 ((or p1 p2) (goto-char (or p1 p2)))
10869 (t (error "No table dataline around here"))))))
10871 (defun org-table-fedit-line-up ()
10872 "Move cursor one line up in the window showing the table."
10873 (interactive)
10874 (org-table-fedit-move 'previous-line))
10876 (defun org-table-fedit-line-down ()
10877 "Move cursor one line down in the window showing the table."
10878 (interactive)
10879 (org-table-fedit-move 'next-line))
10881 (defun org-table-fedit-move (command)
10882 "Move the cursor in the window shoinw the table.
10883 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10884 (let ((org-table-allow-automatic-line-recalculation nil)
10885 (pos org-pos) (win (selected-window)) p)
10886 (select-window (get-buffer-window (marker-buffer org-pos)))
10887 (setq p (point))
10888 (call-interactively command)
10889 (while (and (org-at-table-p)
10890 (org-at-table-hline-p))
10891 (call-interactively command))
10892 (or (org-at-table-p) (goto-char p))
10893 (move-marker pos (point))
10894 (select-window win)))
10896 (defun org-table-fedit-scroll (N)
10897 (interactive "p")
10898 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10899 (scroll-other-window N)))
10901 (defun org-table-fedit-scroll-down (N)
10902 (interactive "p")
10903 (org-table-fedit-scroll (- N)))
10905 (defvar org-table-rectangle-overlays nil)
10907 (defun org-table-add-rectangle-overlay (beg end &optional face)
10908 "Add a new overlay."
10909 (let ((ov (org-make-overlay beg end)))
10910 (org-overlay-put ov 'face (or face 'secondary-selection))
10911 (push ov org-table-rectangle-overlays)))
10913 (defun org-table-highlight-rectangle (&optional beg end face)
10914 "Highlight rectangular region in a table."
10915 (setq beg (or beg (point)) end (or end (point)))
10916 (let ((b (min beg end))
10917 (e (max beg end))
10918 l1 c1 l2 c2 tmp)
10919 (and (boundp 'org-show-positions)
10920 (setq org-show-positions (cons b (cons e org-show-positions))))
10921 (goto-char (min beg end))
10922 (setq l1 (org-current-line)
10923 c1 (org-table-current-column))
10924 (goto-char (max beg end))
10925 (setq l2 (org-current-line)
10926 c2 (org-table-current-column))
10927 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10928 (goto-line l1)
10929 (beginning-of-line 1)
10930 (loop for line from l1 to l2 do
10931 (when (looking-at org-table-dataline-regexp)
10932 (org-table-goto-column c1)
10933 (skip-chars-backward "^|\n") (setq beg (point))
10934 (org-table-goto-column c2)
10935 (skip-chars-forward "^|\n") (setq end (point))
10936 (org-table-add-rectangle-overlay beg end face))
10937 (beginning-of-line 2))
10938 (goto-char b))
10939 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10941 (defun org-table-remove-rectangle-highlight (&rest ignore)
10942 "Remove the rectangle overlays."
10943 (unless org-inhibit-highlight-removal
10944 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10945 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10946 (setq org-table-rectangle-overlays nil)))
10948 (defvar org-table-coordinate-overlays nil
10949 "Collects the cooordinate grid overlays, so that they can be removed.")
10950 (make-variable-buffer-local 'org-table-coordinate-overlays)
10952 (defun org-table-overlay-coordinates ()
10953 "Add overlays to the table at point, to show row/column coordinates."
10954 (interactive)
10955 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10956 (setq org-table-coordinate-overlays nil)
10957 (save-excursion
10958 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10959 (goto-char (org-table-begin))
10960 (while (org-at-table-p)
10961 (setq eol (point-at-eol))
10962 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10963 (push ov org-table-coordinate-overlays)
10964 (setq hline (looking-at org-table-hline-regexp))
10965 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10966 (format "%4d" (setq id (1+ id)))))
10967 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10968 (when hline
10969 (setq ic 0)
10970 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10971 (setq beg (1+ (match-beginning 0))
10972 ic (1+ ic)
10973 s1 (concat "$" (int-to-string ic))
10974 s2 (org-number-to-letters ic)
10975 str (if (eq org-table-use-standard-references t) s2 s1))
10976 (setq ov (org-make-overlay beg (+ beg (length str))))
10977 (push ov org-table-coordinate-overlays)
10978 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10979 (beginning-of-line 2)))))
10981 (defun org-table-toggle-coordinate-overlays ()
10982 "Toggle the display of Row/Column numbers in tables."
10983 (interactive)
10984 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10985 (message "Row/Column number display turned %s"
10986 (if org-table-overlay-coordinates "on" "off"))
10987 (if (and (org-at-table-p) org-table-overlay-coordinates)
10988 (org-table-align))
10989 (unless org-table-overlay-coordinates
10990 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10991 (setq org-table-coordinate-overlays nil)))
10993 (defun org-table-toggle-formula-debugger ()
10994 "Toggle the formula debugger in tables."
10995 (interactive)
10996 (setq org-table-formula-debug (not org-table-formula-debug))
10997 (message "Formula debugging has been turned %s"
10998 (if org-table-formula-debug "on" "off")))
11000 ;;; The orgtbl minor mode
11002 ;; Define a minor mode which can be used in other modes in order to
11003 ;; integrate the org-mode table editor.
11005 ;; This is really a hack, because the org-mode table editor uses several
11006 ;; keys which normally belong to the major mode, for example the TAB and
11007 ;; RET keys. Here is how it works: The minor mode defines all the keys
11008 ;; necessary to operate the table editor, but wraps the commands into a
11009 ;; function which tests if the cursor is currently inside a table. If that
11010 ;; is the case, the table editor command is executed. However, when any of
11011 ;; those keys is used outside a table, the function uses `key-binding' to
11012 ;; look up if the key has an associated command in another currently active
11013 ;; keymap (minor modes, major mode, global), and executes that command.
11014 ;; There might be problems if any of the keys used by the table editor is
11015 ;; otherwise used as a prefix key.
11017 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11018 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11019 ;; addresses this by checking explicitly for both bindings.
11021 ;; The optimized version (see variable `orgtbl-optimized') takes over
11022 ;; all keys which are bound to `self-insert-command' in the *global map*.
11023 ;; Some modes bind other commands to simple characters, for example
11024 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11025 ;; active, this binding is ignored inside tables and replaced with a
11026 ;; modified self-insert.
11028 (defvar orgtbl-mode nil
11029 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11030 table editor in arbitrary modes.")
11031 (make-variable-buffer-local 'orgtbl-mode)
11033 (defvar orgtbl-mode-map (make-keymap)
11034 "Keymap for `orgtbl-mode'.")
11036 ;;;###autoload
11037 (defun turn-on-orgtbl ()
11038 "Unconditionally turn on `orgtbl-mode'."
11039 (orgtbl-mode 1))
11041 (defvar org-old-auto-fill-inhibit-regexp nil
11042 "Local variable used by `orgtbl-mode'")
11044 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11045 "Matches a line belonging to an orgtbl.")
11047 (defconst orgtbl-extra-font-lock-keywords
11048 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11049 0 (quote 'org-table) 'prepend))
11050 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11052 ;;;###autoload
11053 (defun orgtbl-mode (&optional arg)
11054 "The `org-mode' table editor as a minor mode for use in other modes."
11055 (interactive)
11056 (if (org-mode-p)
11057 ;; Exit without error, in case some hook functions calls this
11058 ;; by accident in org-mode.
11059 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11060 (setq orgtbl-mode
11061 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11062 (if orgtbl-mode
11063 (progn
11064 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11065 ;; Make sure we are first in minor-mode-map-alist
11066 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11067 (and c (setq minor-mode-map-alist
11068 (cons c (delq c minor-mode-map-alist)))))
11069 (org-set-local (quote org-table-may-need-update) t)
11070 (org-add-hook 'before-change-functions 'org-before-change-function
11071 nil 'local)
11072 (org-set-local 'org-old-auto-fill-inhibit-regexp
11073 auto-fill-inhibit-regexp)
11074 (org-set-local 'auto-fill-inhibit-regexp
11075 (if auto-fill-inhibit-regexp
11076 (concat orgtbl-line-start-regexp "\\|"
11077 auto-fill-inhibit-regexp)
11078 orgtbl-line-start-regexp))
11079 (org-add-to-invisibility-spec '(org-cwidth))
11080 (when (fboundp 'font-lock-add-keywords)
11081 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11082 (org-restart-font-lock))
11083 (easy-menu-add orgtbl-mode-menu)
11084 (run-hooks 'orgtbl-mode-hook))
11085 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11086 (org-cleanup-narrow-column-properties)
11087 (org-remove-from-invisibility-spec '(org-cwidth))
11088 (remove-hook 'before-change-functions 'org-before-change-function t)
11089 (when (fboundp 'font-lock-remove-keywords)
11090 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11091 (org-restart-font-lock))
11092 (easy-menu-remove orgtbl-mode-menu)
11093 (force-mode-line-update 'all))))
11095 (defun org-cleanup-narrow-column-properties ()
11096 "Remove all properties related to narrow-column invisibility."
11097 (let ((s 1))
11098 (while (setq s (text-property-any s (point-max)
11099 'display org-narrow-column-arrow))
11100 (remove-text-properties s (1+ s) '(display t)))
11101 (setq s 1)
11102 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11103 (remove-text-properties s (1+ s) '(org-cwidth t)))
11104 (setq s 1)
11105 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11106 (remove-text-properties s (1+ s) '(invisible t)))))
11108 ;; Install it as a minor mode.
11109 (put 'orgtbl-mode :included t)
11110 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11111 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11113 (defun orgtbl-make-binding (fun n &rest keys)
11114 "Create a function for binding in the table minor mode.
11115 FUN is the command to call inside a table. N is used to create a unique
11116 command name. KEYS are keys that should be checked in for a command
11117 to execute outside of tables."
11118 (eval
11119 (list 'defun
11120 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11121 '(arg)
11122 (concat "In tables, run `" (symbol-name fun) "'.\n"
11123 "Outside of tables, run the binding of `"
11124 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11125 "'.")
11126 '(interactive "p")
11127 (list 'if
11128 '(org-at-table-p)
11129 (list 'call-interactively (list 'quote fun))
11130 (list 'let '(orgtbl-mode)
11131 (list 'call-interactively
11132 (append '(or)
11133 (mapcar (lambda (k)
11134 (list 'key-binding k))
11135 keys)
11136 '('orgtbl-error))))))))
11138 (defun orgtbl-error ()
11139 "Error when there is no default binding for a table key."
11140 (interactive)
11141 (error "This key has no function outside tables"))
11143 (defun orgtbl-setup ()
11144 "Setup orgtbl keymaps."
11145 (let ((nfunc 0)
11146 (bindings
11147 (list
11148 '([(meta shift left)] org-table-delete-column)
11149 '([(meta left)] org-table-move-column-left)
11150 '([(meta right)] org-table-move-column-right)
11151 '([(meta shift right)] org-table-insert-column)
11152 '([(meta shift up)] org-table-kill-row)
11153 '([(meta shift down)] org-table-insert-row)
11154 '([(meta up)] org-table-move-row-up)
11155 '([(meta down)] org-table-move-row-down)
11156 '("\C-c\C-w" org-table-cut-region)
11157 '("\C-c\M-w" org-table-copy-region)
11158 '("\C-c\C-y" org-table-paste-rectangle)
11159 '("\C-c-" org-table-insert-hline)
11160 '("\C-c}" org-table-toggle-coordinate-overlays)
11161 '("\C-c{" org-table-toggle-formula-debugger)
11162 '("\C-m" org-table-next-row)
11163 '([(shift return)] org-table-copy-down)
11164 '("\C-c\C-q" org-table-wrap-region)
11165 '("\C-c?" org-table-field-info)
11166 '("\C-c " org-table-blank-field)
11167 '("\C-c+" org-table-sum)
11168 '("\C-c=" org-table-eval-formula)
11169 '("\C-c'" org-table-edit-formulas)
11170 '("\C-c`" org-table-edit-field)
11171 '("\C-c*" org-table-recalculate)
11172 '("\C-c|" org-table-create-or-convert-from-region)
11173 '("\C-c^" org-table-sort-lines)
11174 '([(control ?#)] org-table-rotate-recalc-marks)))
11175 elt key fun cmd)
11176 (while (setq elt (pop bindings))
11177 (setq nfunc (1+ nfunc))
11178 (setq key (org-key (car elt))
11179 fun (nth 1 elt)
11180 cmd (orgtbl-make-binding fun nfunc key))
11181 (org-defkey orgtbl-mode-map key cmd))
11183 ;; Special treatment needed for TAB and RET
11184 (org-defkey orgtbl-mode-map [(return)]
11185 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11186 (org-defkey orgtbl-mode-map "\C-m"
11187 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11189 (org-defkey orgtbl-mode-map [(tab)]
11190 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11191 (org-defkey orgtbl-mode-map "\C-i"
11192 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11194 (org-defkey orgtbl-mode-map [(shift tab)]
11195 (orgtbl-make-binding 'org-table-previous-field 104
11196 [(shift tab)] [(tab)] "\C-i"))
11198 (org-defkey orgtbl-mode-map "\M-\C-m"
11199 (orgtbl-make-binding 'org-table-wrap-region 105
11200 "\M-\C-m" [(meta return)]))
11201 (org-defkey orgtbl-mode-map [(meta return)]
11202 (orgtbl-make-binding 'org-table-wrap-region 106
11203 [(meta return)] "\M-\C-m"))
11205 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11206 (when orgtbl-optimized
11207 ;; If the user wants maximum table support, we need to hijack
11208 ;; some standard editing functions
11209 (org-remap orgtbl-mode-map
11210 'self-insert-command 'orgtbl-self-insert-command
11211 'delete-char 'org-delete-char
11212 'delete-backward-char 'org-delete-backward-char)
11213 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11214 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11215 '("OrgTbl"
11216 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11217 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11218 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11219 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11220 "--"
11221 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11222 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11223 ["Copy Field from Above"
11224 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11225 "--"
11226 ("Column"
11227 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11228 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11229 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11230 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11231 ("Row"
11232 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11233 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11234 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11235 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11236 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11237 "--"
11238 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11239 ("Rectangle"
11240 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11241 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11242 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11243 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11244 "--"
11245 ("Radio tables"
11246 ["Insert table template" orgtbl-insert-radio-table
11247 (assq major-mode orgtbl-radio-table-templates)]
11248 ["Comment/uncomment table" orgtbl-toggle-comment t])
11249 "--"
11250 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11251 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11252 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11253 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11254 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11255 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11256 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11257 ["Sum Column/Rectangle" org-table-sum
11258 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11259 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11260 ["Debug Formulas"
11261 org-table-toggle-formula-debugger :active (org-at-table-p)
11262 :keys "C-c {"
11263 :style toggle :selected org-table-formula-debug]
11264 ["Show Col/Row Numbers"
11265 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11266 :keys "C-c }"
11267 :style toggle :selected org-table-overlay-coordinates]
11271 (defun orgtbl-ctrl-c-ctrl-c (arg)
11272 "If the cursor is inside a table, realign the table.
11273 It it is a table to be sent away to a receiver, do it.
11274 With prefix arg, also recompute table."
11275 (interactive "P")
11276 (let ((pos (point)) action)
11277 (save-excursion
11278 (beginning-of-line 1)
11279 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11280 ((looking-at "[ \t]*|") pos)
11281 ((looking-at "#\\+TBLFM:") 'recalc))))
11282 (cond
11283 ((integerp action)
11284 (goto-char action)
11285 (org-table-maybe-eval-formula)
11286 (if arg
11287 (call-interactively 'org-table-recalculate)
11288 (org-table-maybe-recalculate-line))
11289 (call-interactively 'org-table-align)
11290 (orgtbl-send-table 'maybe))
11291 ((eq action 'recalc)
11292 (save-excursion
11293 (beginning-of-line 1)
11294 (skip-chars-backward " \r\n\t")
11295 (if (org-at-table-p)
11296 (org-call-with-arg 'org-table-recalculate t))))
11297 (t (let (orgtbl-mode)
11298 (call-interactively (key-binding "\C-c\C-c")))))))
11300 (defun orgtbl-tab (arg)
11301 "Justification and field motion for `orgtbl-mode'."
11302 (interactive "P")
11303 (if arg (org-table-edit-field t)
11304 (org-table-justify-field-maybe)
11305 (org-table-next-field)))
11307 (defun orgtbl-ret ()
11308 "Justification and field motion for `orgtbl-mode'."
11309 (interactive)
11310 (org-table-justify-field-maybe)
11311 (org-table-next-row))
11313 (defun orgtbl-self-insert-command (N)
11314 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11315 If the cursor is in a table looking at whitespace, the whitespace is
11316 overwritten, and the table is not marked as requiring realignment."
11317 (interactive "p")
11318 (if (and (org-at-table-p)
11320 (and org-table-auto-blank-field
11321 (member last-command
11322 '(orgtbl-hijacker-command-100
11323 orgtbl-hijacker-command-101
11324 orgtbl-hijacker-command-102
11325 orgtbl-hijacker-command-103
11326 orgtbl-hijacker-command-104
11327 orgtbl-hijacker-command-105))
11328 (org-table-blank-field))
11330 (eq N 1)
11331 (looking-at "[^|\n]* +|"))
11332 (let (org-table-may-need-update)
11333 (goto-char (1- (match-end 0)))
11334 (delete-backward-char 1)
11335 (goto-char (match-beginning 0))
11336 (self-insert-command N))
11337 (setq org-table-may-need-update t)
11338 (let (orgtbl-mode)
11339 (call-interactively (key-binding (vector last-input-event))))))
11341 (defun org-force-self-insert (N)
11342 "Needed to enforce self-insert under remapping."
11343 (interactive "p")
11344 (self-insert-command N))
11346 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11347 "Regula expression matching exponentials as produced by calc.")
11349 (defvar org-table-clean-did-remove-column nil)
11351 (defun orgtbl-export (table target)
11352 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11353 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11354 org-table-last-alignment org-table-last-column-widths
11355 maxcol column)
11356 (if (not (fboundp func))
11357 (error "Cannot export orgtbl table to %s" target))
11358 (setq lines (org-table-clean-before-export lines))
11359 (setq table
11360 (mapcar
11361 (lambda (x)
11362 (if (string-match org-table-hline-regexp x)
11363 'hline
11364 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11365 lines))
11366 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11367 table)))
11368 (loop for i from (1- maxcol) downto 0 do
11369 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11370 (setq column (delq nil column))
11371 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11372 (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))
11373 (funcall func table nil)))
11375 (defun orgtbl-send-table (&optional maybe)
11376 "Send a tranformed version of this table to the receiver position.
11377 With argument MAYBE, fail quietly if no transformation is defined for
11378 this table."
11379 (interactive)
11380 (catch 'exit
11381 (unless (org-at-table-p) (error "Not at a table"))
11382 ;; when non-interactive, we assume align has just happened.
11383 (when (interactive-p) (org-table-align))
11384 (save-excursion
11385 (goto-char (org-table-begin))
11386 (beginning-of-line 0)
11387 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11388 (if maybe
11389 (throw 'exit nil)
11390 (error "Don't know how to transform this table."))))
11391 (let* ((name (match-string 1))
11393 (transform (intern (match-string 2)))
11394 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11395 (skip (plist-get params :skip))
11396 (skipcols (plist-get params :skipcols))
11397 (txt (buffer-substring-no-properties
11398 (org-table-begin) (org-table-end)))
11399 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11400 (lines (org-table-clean-before-export lines))
11401 (i0 (if org-table-clean-did-remove-column 2 1))
11402 (table (mapcar
11403 (lambda (x)
11404 (if (string-match org-table-hline-regexp x)
11405 'hline
11406 (org-remove-by-index
11407 (org-split-string (org-trim x) "\\s-*|\\s-*")
11408 skipcols i0)))
11409 lines))
11410 (fun (if (= i0 2) 'cdr 'identity))
11411 (org-table-last-alignment
11412 (org-remove-by-index (funcall fun org-table-last-alignment)
11413 skipcols i0))
11414 (org-table-last-column-widths
11415 (org-remove-by-index (funcall fun org-table-last-column-widths)
11416 skipcols i0)))
11418 (unless (fboundp transform)
11419 (error "No such transformation function %s" transform))
11420 (setq txt (funcall transform table params))
11421 ;; Find the insertion place
11422 (save-excursion
11423 (goto-char (point-min))
11424 (unless (re-search-forward
11425 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11426 (error "Don't know where to insert translated table"))
11427 (goto-char (match-beginning 0))
11428 (beginning-of-line 2)
11429 (setq beg (point))
11430 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11431 (error "Cannot find end of insertion region"))
11432 (beginning-of-line 1)
11433 (delete-region beg (point))
11434 (goto-char beg)
11435 (insert txt "\n"))
11436 (message "Table converted and installed at receiver location"))))
11438 (defun org-remove-by-index (list indices &optional i0)
11439 "Remove the elements in LIST with indices in INDICES.
11440 First element has index 0, or I0 if given."
11441 (if (not indices)
11442 list
11443 (if (integerp indices) (setq indices (list indices)))
11444 (setq i0 (1- (or i0 0)))
11445 (delq :rm (mapcar (lambda (x)
11446 (setq i0 (1+ i0))
11447 (if (memq i0 indices) :rm x))
11448 list))))
11450 (defun orgtbl-toggle-comment ()
11451 "Comment or uncomment the orgtbl at point."
11452 (interactive)
11453 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11454 (re2 (concat "^" orgtbl-line-start-regexp))
11455 (commented (save-excursion (beginning-of-line 1)
11456 (cond ((looking-at re1) t)
11457 ((looking-at re2) nil)
11458 (t (error "Not at an org table")))))
11459 (re (if commented re1 re2))
11460 beg end)
11461 (save-excursion
11462 (beginning-of-line 1)
11463 (while (looking-at re) (beginning-of-line 0))
11464 (beginning-of-line 2)
11465 (setq beg (point))
11466 (while (looking-at re) (beginning-of-line 2))
11467 (setq end (point)))
11468 (comment-region beg end (if commented '(4) nil))))
11470 (defun orgtbl-insert-radio-table ()
11471 "Insert a radio table template appropriate for this major mode."
11472 (interactive)
11473 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11474 (txt (nth 1 e))
11475 name pos)
11476 (unless e (error "No radio table setup defined for %s" major-mode))
11477 (setq name (read-string "Table name: "))
11478 (while (string-match "%n" txt)
11479 (setq txt (replace-match name t t txt)))
11480 (or (bolp) (insert "\n"))
11481 (setq pos (point))
11482 (insert txt)
11483 (goto-char pos)))
11485 (defun org-get-param (params header i sym &optional hsym)
11486 "Get parameter value for symbol SYM.
11487 If this is a header line, actually get the value for the symbol with an
11488 additional \"h\" inserted after the colon.
11489 If the value is a protperty list, get the element for the current column.
11490 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11491 (let ((val (plist-get params sym)))
11492 (and hsym header (setq val (or (plist-get params hsym) val)))
11493 (if (consp val) (plist-get val i) val)))
11495 (defun orgtbl-to-generic (table params)
11496 "Convert the orgtbl-mode TABLE to some other format.
11497 This generic routine can be used for many standard cases.
11498 TABLE is a list, each entry either the symbol `hline' for a horizontal
11499 separator line, or a list of fields for that line.
11500 PARAMS is a property list of parameters that can influence the conversion.
11501 For the generic converter, some parameters are obligatory: You need to
11502 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11503 :splice, you must have :tstart and :tend.
11505 Valid parameters are
11507 :tstart String to start the table. Ignored when :splice is t.
11508 :tend String to end the table. Ignored when :splice is t.
11510 :splice When set to t, return only table body lines, don't wrap
11511 them into :tstart and :tend. Default is nil.
11513 :hline String to be inserted on horizontal separation lines.
11514 May be nil to ignore hlines.
11516 :lstart String to start a new table line.
11517 :lend String to end a table line
11518 :sep Separator between two fields
11519 :lfmt Format for entire line, with enough %s to capture all fields.
11520 If this is present, :lstart, :lend, and :sep are ignored.
11521 :fmt A format to be used to wrap the field, should contain
11522 %s for the original field value. For example, to wrap
11523 everything in dollars, you could use :fmt \"$%s$\".
11524 This may also be a property list with column numbers and
11525 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11527 :hlstart :hlend :hlsep :hlfmt :hfmt
11528 Same as above, specific for the header lines in the table.
11529 All lines before the first hline are treated as header.
11530 If any of these is not present, the data line value is used.
11532 :efmt Use this format to print numbers with exponentials.
11533 The format should have %s twice for inserting mantissa
11534 and exponent, for example \"%s\\\\times10^{%s}\". This
11535 may also be a property list with column numbers and
11536 formats. :fmt will still be applied after :efmt.
11538 In addition to this, the parameters :skip and :skipcols are always handled
11539 directly by `orgtbl-send-table'. See manual."
11540 (interactive)
11541 (let* ((p params)
11542 (splicep (plist-get p :splice))
11543 (hline (plist-get p :hline))
11544 rtn line i fm efm lfmt h)
11546 ;; Do we have a header?
11547 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11548 (setq h t))
11550 ;; Put header
11551 (unless splicep
11552 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11554 ;; Now loop over all lines
11555 (while (setq line (pop table))
11556 (if (eq line 'hline)
11557 ;; A horizontal separator line
11558 (progn (if hline (push hline rtn))
11559 (setq h nil)) ; no longer in header
11560 ;; A normal line. Convert the fields, push line onto the result list
11561 (setq i 0)
11562 (setq line
11563 (mapcar
11564 (lambda (f)
11565 (setq i (1+ i)
11566 fm (org-get-param p h i :fmt :hfmt)
11567 efm (org-get-param p h i :efmt))
11568 (if (and efm (string-match orgtbl-exp-regexp f))
11569 (setq f (format
11570 efm (match-string 1 f) (match-string 2 f))))
11571 (if fm (setq f (format fm f)))
11573 line))
11574 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11575 (push (apply 'format lfmt line) rtn)
11576 (push (concat
11577 (org-get-param p h i :lstart :hlstart)
11578 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11579 (org-get-param p h i :lend :hlend))
11580 rtn))))
11582 (unless splicep
11583 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11585 (mapconcat 'identity (nreverse rtn) "\n")))
11587 (defun orgtbl-to-latex (table params)
11588 "Convert the orgtbl-mode TABLE to LaTeX.
11589 TABLE is a list, each entry either the symbol `hline' for a horizontal
11590 separator line, or a list of fields for that line.
11591 PARAMS is a property list of parameters that can influence the conversion.
11592 Supports all parameters from `orgtbl-to-generic'. Most important for
11593 LaTeX are:
11595 :splice When set to t, return only table body lines, don't wrap
11596 them into a tabular environment. Default is nil.
11598 :fmt A format to be used to wrap the field, should contain %s for the
11599 original field value. For example, to wrap everything in dollars,
11600 use :fmt \"$%s$\". This may also be a property list with column
11601 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11603 :efmt Format for transforming numbers with exponentials. The format
11604 should have %s twice for inserting mantissa and exponent, for
11605 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11606 This may also be a property list with column numbers and formats.
11608 The general parameters :skip and :skipcols have already been applied when
11609 this function is called."
11610 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11611 org-table-last-alignment ""))
11612 (params2
11613 (list
11614 :tstart (concat "\\begin{tabular}{" alignment "}")
11615 :tend "\\end{tabular}"
11616 :lstart "" :lend " \\\\" :sep " & "
11617 :efmt "%s\\,(%s)" :hline "\\hline")))
11618 (orgtbl-to-generic table (org-combine-plists params2 params))))
11620 (defun orgtbl-to-html (table params)
11621 "Convert the orgtbl-mode TABLE to LaTeX.
11622 TABLE is a list, each entry either the symbol `hline' for a horizontal
11623 separator line, or a list of fields for that line.
11624 PARAMS is a property list of parameters that can influence the conversion.
11625 Currently this function recognizes the following parameters:
11627 :splice When set to t, return only table body lines, don't wrap
11628 them into a <table> environment. Default is nil.
11630 The general parameters :skip and :skipcols have already been applied when
11631 this function is called. The function does *not* use `orgtbl-to-generic',
11632 so you cannot specify parameters for it."
11633 (let* ((splicep (plist-get params :splice))
11634 html)
11635 ;; Just call the formatter we already have
11636 ;; We need to make text lines for it, so put the fields back together.
11637 (setq html (org-format-org-table-html
11638 (mapcar
11639 (lambda (x)
11640 (if (eq x 'hline)
11641 "|----+----|"
11642 (concat "| " (mapconcat 'identity x " | ") " |")))
11643 table)
11644 splicep))
11645 (if (string-match "\n+\\'" html)
11646 (setq html (replace-match "" t t html)))
11647 html))
11649 (defun orgtbl-to-texinfo (table params)
11650 "Convert the orgtbl-mode TABLE to TeXInfo.
11651 TABLE is a list, each entry either the symbol `hline' for a horizontal
11652 separator line, or a list of fields for that line.
11653 PARAMS is a property list of parameters that can influence the conversion.
11654 Supports all parameters from `orgtbl-to-generic'. Most important for
11655 TeXInfo are:
11657 :splice nil/t When set to t, return only table body lines, don't wrap
11658 them into a multitable environment. Default is nil.
11660 :fmt fmt A format to be used to wrap the field, should contain
11661 %s for the original field value. For example, to wrap
11662 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11663 This may also be a property list with column numbers and
11664 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11666 :cf \"f1 f2..\" The column fractions for the table. By default these
11667 are computed automatically from the width of the columns
11668 under org-mode.
11670 The general parameters :skip and :skipcols have already been applied when
11671 this function is called."
11672 (let* ((total (float (apply '+ org-table-last-column-widths)))
11673 (colfrac (or (plist-get params :cf)
11674 (mapconcat
11675 (lambda (x) (format "%.3f" (/ (float x) total)))
11676 org-table-last-column-widths " ")))
11677 (params2
11678 (list
11679 :tstart (concat "@multitable @columnfractions " colfrac)
11680 :tend "@end multitable"
11681 :lstart "@item " :lend "" :sep " @tab "
11682 :hlstart "@headitem ")))
11683 (orgtbl-to-generic table (org-combine-plists params2 params))))
11685 ;;;; Link Stuff
11687 ;;; Link abbreviations
11689 (defun org-link-expand-abbrev (link)
11690 "Apply replacements as defined in `org-link-abbrev-alist."
11691 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11692 (let* ((key (match-string 1 link))
11693 (as (or (assoc key org-link-abbrev-alist-local)
11694 (assoc key org-link-abbrev-alist)))
11695 (tag (and (match-end 2) (match-string 3 link)))
11696 rpl)
11697 (if (not as)
11698 link
11699 (setq rpl (cdr as))
11700 (cond
11701 ((symbolp rpl) (funcall rpl tag))
11702 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11703 (t (concat rpl tag)))))
11704 link))
11706 ;;; Storing and inserting links
11708 (defvar org-insert-link-history nil
11709 "Minibuffer history for links inserted with `org-insert-link'.")
11711 (defvar org-stored-links nil
11712 "Contains the links stored with `org-store-link'.")
11714 (defvar org-store-link-plist nil
11715 "Plist with info about the most recently link created with `org-store-link'.")
11717 (defvar org-link-protocols nil
11718 "Link protocols added to Org-mode using `org-add-link-type'.")
11720 (defvar org-store-link-functions nil
11721 "List of functions that are called to create and store a link.
11722 Each function will be called in turn until one returns a non-nil
11723 value. Each function should check if it is responsible for creating
11724 this link (for example by looking at the major mode).
11725 If not, it must exit and return nil.
11726 If yes, it should return a non-nil value after a calling
11727 `org-store-link-props' with a list of properties and values.
11728 Special properties are:
11730 :type The link prefix. like \"http\". This must be given.
11731 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11732 This is obligatory as well.
11733 :description Optional default description for the second pair
11734 of brackets in an Org-mode link. The user can still change
11735 this when inserting this link into an Org-mode buffer.
11737 In addition to these, any additional properties can be specified
11738 and then used in remember templates.")
11740 (defun org-add-link-type (type &optional follow publish)
11741 "Add TYPE to the list of `org-link-types'.
11742 Re-compute all regular expressions depending on `org-link-types'
11743 FOLLOW and PUBLISH are two functions. Both take the link path as
11744 an argument.
11745 FOLLOW should do whatever is necessary to follow the link, for example
11746 to find a file or display a mail message.
11748 PUBLISH takes the path and retuns the string that should be used when
11749 this document is published. FIMXE: This is actually not yet implemented."
11750 (add-to-list 'org-link-types type t)
11751 (org-make-link-regexps)
11752 (add-to-list 'org-link-protocols
11753 (list type follow publish)))
11755 (defun org-add-agenda-custom-command (entry)
11756 "Replace or add a command in `org-agenda-custom-commands'.
11757 This is mostly for hacking and trying a new command - once the command
11758 works you probably want to add it to `org-agenda-custom-commands' for good."
11759 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11760 (if ass
11761 (setcdr ass (cdr entry))
11762 (push entry org-agenda-custom-commands))))
11764 ;;;###autoload
11765 (defun org-store-link (arg)
11766 "\\<org-mode-map>Store an org-link to the current location.
11767 This link can later be inserted into an org-buffer with
11768 \\[org-insert-link].
11769 For some link types, a prefix arg is interpreted:
11770 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11771 For file links, arg negates `org-context-in-file-links'."
11772 (interactive "P")
11773 (setq org-store-link-plist nil) ; reset
11774 (let (link cpltxt desc description search txt)
11775 (cond
11777 ((run-hook-with-args-until-success 'org-store-link-functions)
11778 (setq link (plist-get org-store-link-plist :link)
11779 desc (or (plist-get org-store-link-plist :description) link)))
11781 ((eq major-mode 'bbdb-mode)
11782 (let ((name (bbdb-record-name (bbdb-current-record)))
11783 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11784 (setq cpltxt (concat "bbdb:" (or name company))
11785 link (org-make-link cpltxt))
11786 (org-store-link-props :type "bbdb" :name name :company company)))
11788 ((eq major-mode 'Info-mode)
11789 (setq link (org-make-link "info:"
11790 (file-name-nondirectory Info-current-file)
11791 ":" Info-current-node))
11792 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11793 ":" Info-current-node))
11794 (org-store-link-props :type "info" :file Info-current-file
11795 :node Info-current-node))
11797 ((eq major-mode 'calendar-mode)
11798 (let ((cd (calendar-cursor-to-date)))
11799 (setq link
11800 (format-time-string
11801 (car org-time-stamp-formats)
11802 (apply 'encode-time
11803 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11804 nil nil nil))))
11805 (org-store-link-props :type "calendar" :date cd)))
11807 ((or (eq major-mode 'vm-summary-mode)
11808 (eq major-mode 'vm-presentation-mode))
11809 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11810 (vm-follow-summary-cursor)
11811 (save-excursion
11812 (vm-select-folder-buffer)
11813 (let* ((message (car vm-message-pointer))
11814 (folder buffer-file-name)
11815 (subject (vm-su-subject message))
11816 (to (vm-get-header-contents message "To"))
11817 (from (vm-get-header-contents message "From"))
11818 (message-id (vm-su-message-id message)))
11819 (org-store-link-props :type "vm" :from from :to to :subject subject
11820 :message-id message-id)
11821 (setq message-id (org-remove-angle-brackets message-id))
11822 (setq folder (abbreviate-file-name folder))
11823 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11824 folder)
11825 (setq folder (replace-match "" t t folder)))
11826 (setq cpltxt (org-email-link-description))
11827 (setq link (org-make-link "vm:" folder "#" message-id)))))
11829 ((eq major-mode 'wl-summary-mode)
11830 (let* ((msgnum (wl-summary-message-number))
11831 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11832 msgnum 'message-id))
11833 (wl-message-entity
11834 (if (fboundp 'elmo-message-entity)
11835 (elmo-message-entity
11836 wl-summary-buffer-elmo-folder msgnum)
11837 (elmo-msgdb-overview-get-entity
11838 msgnum (wl-summary-buffer-msgdb))))
11839 (from (wl-summary-line-from))
11840 (to (car (elmo-message-entity-field wl-message-entity 'to)))
11841 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11842 (wl-summary-line-subject))))
11843 (org-store-link-props :type "wl" :from from :to to
11844 :subject subject :message-id message-id)
11845 (setq message-id (org-remove-angle-brackets message-id))
11846 (setq cpltxt (org-email-link-description))
11847 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11848 "#" message-id))))
11850 ((or (equal major-mode 'mh-folder-mode)
11851 (equal major-mode 'mh-show-mode))
11852 (let ((from (org-mhe-get-header "From:"))
11853 (to (org-mhe-get-header "To:"))
11854 (message-id (org-mhe-get-header "Message-Id:"))
11855 (subject (org-mhe-get-header "Subject:")))
11856 (org-store-link-props :type "mh" :from from :to to
11857 :subject subject :message-id message-id)
11858 (setq cpltxt (org-email-link-description))
11859 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11860 (org-remove-angle-brackets message-id)))))
11862 ((eq major-mode 'rmail-mode)
11863 (save-excursion
11864 (save-restriction
11865 (rmail-narrow-to-non-pruned-header)
11866 (let ((folder buffer-file-name)
11867 (message-id (mail-fetch-field "message-id"))
11868 (from (mail-fetch-field "from"))
11869 (to (mail-fetch-field "to"))
11870 (subject (mail-fetch-field "subject")))
11871 (org-store-link-props
11872 :type "rmail" :from from :to to
11873 :subject subject :message-id message-id)
11874 (setq message-id (org-remove-angle-brackets message-id))
11875 (setq cpltxt (org-email-link-description))
11876 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11878 ((eq major-mode 'gnus-group-mode)
11879 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11880 (gnus-group-group-name)) ; version
11881 ((fboundp 'gnus-group-name)
11882 (gnus-group-name))
11883 (t "???"))))
11884 (unless group (error "Not on a group"))
11885 (org-store-link-props :type "gnus" :group group)
11886 (setq cpltxt (concat
11887 (if (org-xor arg org-usenet-links-prefer-google)
11888 "http://groups.google.com/groups?group="
11889 "gnus:")
11890 group)
11891 link (org-make-link cpltxt))))
11893 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11894 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11895 (let* ((group gnus-newsgroup-name)
11896 (article (gnus-summary-article-number))
11897 (header (gnus-summary-article-header article))
11898 (from (mail-header-from header))
11899 (message-id (mail-header-id header))
11900 (date (mail-header-date header))
11901 (subject (gnus-summary-subject-string)))
11902 (org-store-link-props :type "gnus" :from from :subject subject
11903 :message-id message-id :group group)
11904 (setq cpltxt (org-email-link-description))
11905 (if (org-xor arg org-usenet-links-prefer-google)
11906 (setq link
11907 (concat
11908 cpltxt "\n "
11909 (format "http://groups.google.com/groups?as_umsgid=%s"
11910 (org-fixup-message-id-for-http message-id))))
11911 (setq link (org-make-link "gnus:" group
11912 "#" (number-to-string article))))))
11914 ((eq major-mode 'w3-mode)
11915 (setq cpltxt (url-view-url t)
11916 link (org-make-link cpltxt))
11917 (org-store-link-props :type "w3" :url (url-view-url t)))
11919 ((eq major-mode 'w3m-mode)
11920 (setq cpltxt (or w3m-current-title w3m-current-url)
11921 link (org-make-link w3m-current-url))
11922 (org-store-link-props :type "w3m" :url (url-view-url t)))
11924 ((setq search (run-hook-with-args-until-success
11925 'org-create-file-search-functions))
11926 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11927 "::" search))
11928 (setq cpltxt (or description link)))
11930 ((eq major-mode 'image-mode)
11931 (setq cpltxt (concat "file:"
11932 (abbreviate-file-name buffer-file-name))
11933 link (org-make-link cpltxt))
11934 (org-store-link-props :type "image" :file buffer-file-name))
11936 ((eq major-mode 'dired-mode)
11937 ;; link to the file in the current line
11938 (setq cpltxt (concat "file:"
11939 (abbreviate-file-name
11940 (expand-file-name
11941 (dired-get-filename nil t))))
11942 link (org-make-link cpltxt)))
11944 ((and buffer-file-name (org-mode-p))
11945 ;; Just link to current headline
11946 (setq cpltxt (concat "file:"
11947 (abbreviate-file-name buffer-file-name)))
11948 ;; Add a context search string
11949 (when (org-xor org-context-in-file-links arg)
11950 ;; Check if we are on a target
11951 (if (org-in-regexp "<<\\(.*?\\)>>")
11952 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11953 (setq txt (cond
11954 ((org-on-heading-p) nil)
11955 ((org-region-active-p)
11956 (buffer-substring (region-beginning) (region-end)))
11957 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11958 (when (or (null txt) (string-match "\\S-" txt))
11959 (setq cpltxt
11960 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11961 desc "NONE"))))
11962 (if (string-match "::\\'" cpltxt)
11963 (setq cpltxt (substring cpltxt 0 -2)))
11964 (setq link (org-make-link cpltxt)))
11966 ((buffer-file-name (buffer-base-buffer))
11967 ;; Just link to this file here.
11968 (setq cpltxt (concat "file:"
11969 (abbreviate-file-name
11970 (buffer-file-name (buffer-base-buffer)))))
11971 ;; Add a context string
11972 (when (org-xor org-context-in-file-links arg)
11973 (setq txt (if (org-region-active-p)
11974 (buffer-substring (region-beginning) (region-end))
11975 (buffer-substring (point-at-bol) (point-at-eol))))
11976 ;; Only use search option if there is some text.
11977 (when (string-match "\\S-" txt)
11978 (setq cpltxt
11979 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11980 desc "NONE")))
11981 (setq link (org-make-link cpltxt)))
11983 ((interactive-p)
11984 (error "Cannot link to a buffer which is not visiting a file"))
11986 (t (setq link nil)))
11988 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11989 (setq link (or link cpltxt)
11990 desc (or desc cpltxt))
11991 (if (equal desc "NONE") (setq desc nil))
11993 (if (and (interactive-p) link)
11994 (progn
11995 (setq org-stored-links
11996 (cons (list link desc) org-stored-links))
11997 (message "Stored: %s" (or desc link)))
11998 (and link (org-make-link-string link desc)))))
12000 (defun org-store-link-props (&rest plist)
12001 "Store link properties, extract names and addresses."
12002 (let (x adr)
12003 (when (setq x (plist-get plist :from))
12004 (setq adr (mail-extract-address-components x))
12005 (plist-put plist :fromname (car adr))
12006 (plist-put plist :fromaddress (nth 1 adr)))
12007 (when (setq x (plist-get plist :to))
12008 (setq adr (mail-extract-address-components x))
12009 (plist-put plist :toname (car adr))
12010 (plist-put plist :toaddress (nth 1 adr))))
12011 (let ((from (plist-get plist :from))
12012 (to (plist-get plist :to)))
12013 (when (and from to org-from-is-user-regexp)
12014 (plist-put plist :fromto
12015 (if (string-match org-from-is-user-regexp from)
12016 (concat "to %t")
12017 (concat "from %f")))))
12018 (setq org-store-link-plist plist))
12020 (defun org-email-link-description (&optional fmt)
12021 "Return the description part of an email link.
12022 This takes information from `org-store-link-plist' and formats it
12023 according to FMT (default from `org-email-link-description-format')."
12024 (setq fmt (or fmt org-email-link-description-format))
12025 (let* ((p org-store-link-plist)
12026 (to (plist-get p :toaddress))
12027 (from (plist-get p :fromaddress))
12028 (table
12029 (list
12030 (cons "%c" (plist-get p :fromto))
12031 (cons "%F" (plist-get p :from))
12032 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12033 (cons "%T" (plist-get p :to))
12034 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12035 (cons "%s" (plist-get p :subject))
12036 (cons "%m" (plist-get p :message-id)))))
12037 (when (string-match "%c" fmt)
12038 ;; Check if the user wrote this message
12039 (if (and org-from-is-user-regexp from to
12040 (save-match-data (string-match org-from-is-user-regexp from)))
12041 (setq fmt (replace-match "to %t" t t fmt))
12042 (setq fmt (replace-match "from %f" t t fmt))))
12043 (org-replace-escapes fmt table)))
12045 (defun org-make-org-heading-search-string (&optional string heading)
12046 "Make search string for STRING or current headline."
12047 (interactive)
12048 (let ((s (or string (org-get-heading))))
12049 (unless (and string (not heading))
12050 ;; We are using a headline, clean up garbage in there.
12051 (if (string-match org-todo-regexp s)
12052 (setq s (replace-match "" t t s)))
12053 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12054 (setq s (replace-match "" t t s)))
12055 (setq s (org-trim s))
12056 (if (string-match (concat "^\\(" org-quote-string "\\|"
12057 org-comment-string "\\)") s)
12058 (setq s (replace-match "" t t s)))
12059 (while (string-match org-ts-regexp s)
12060 (setq s (replace-match "" t t s))))
12061 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12062 (setq s (replace-match " " t t s)))
12063 (or string (setq s (concat "*" s))) ; Add * for headlines
12064 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12066 (defun org-make-link (&rest strings)
12067 "Concatenate STRINGS."
12068 (apply 'concat strings))
12070 (defun org-make-link-string (link &optional description)
12071 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12072 (unless (string-match "\\S-" link)
12073 (error "Empty link"))
12074 (when (stringp description)
12075 ;; Remove brackets from the description, they are fatal.
12076 (while (string-match "\\[" description)
12077 (setq description (replace-match "{" t t description)))
12078 (while (string-match "\\]" description)
12079 (setq description (replace-match "}" t t description))))
12080 (when (equal (org-link-escape link) description)
12081 ;; No description needed, it is identical
12082 (setq description nil))
12083 (when (and (not description)
12084 (not (equal link (org-link-escape link))))
12085 (setq description link))
12086 (concat "[[" (org-link-escape link) "]"
12087 (if description (concat "[" description "]") "")
12088 "]"))
12090 (defconst org-link-escape-chars
12091 '((?\ . "%20")
12092 (?\[ . "%5B")
12093 (?\] . "%5D")
12094 (?\340 . "%E0") ; `a
12095 (?\342 . "%E2") ; ^a
12096 (?\347 . "%E7") ; ,c
12097 (?\350 . "%E8") ; `e
12098 (?\351 . "%E9") ; 'e
12099 (?\352 . "%EA") ; ^e
12100 (?\356 . "%EE") ; ^i
12101 (?\364 . "%F4") ; ^o
12102 (?\371 . "%F9") ; `u
12103 (?\373 . "%FB") ; ^u
12104 (?\; . "%3B")
12105 (?? . "%3F")
12106 (?= . "%3D")
12107 (?+ . "%2B")
12109 "Association list of escapes for some characters problematic in links.
12110 This is the list that is used for internal purposes.")
12112 (defconst org-link-escape-chars-browser
12113 '((?\ . "%20")) ; 32 for the SPC char
12114 "Association list of escapes for some characters problematic in links.
12115 This is the list that is used before handing over to the browser.")
12117 (defun org-link-escape (text &optional table)
12118 "Escape charaters in TEXT that are problematic for links."
12119 (setq table (or table org-link-escape-chars))
12120 (when text
12121 (let ((re (mapconcat (lambda (x) (regexp-quote
12122 (char-to-string (car x))))
12123 table "\\|")))
12124 (while (string-match re text)
12125 (setq text
12126 (replace-match
12127 (cdr (assoc (string-to-char (match-string 0 text))
12128 table))
12129 t t text)))
12130 text)))
12132 (defun org-link-unescape (text &optional table)
12133 "Reverse the action of `org-link-escape'."
12134 (setq table (or table org-link-escape-chars))
12135 (when text
12136 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12137 table "\\|")))
12138 (while (string-match re text)
12139 (setq text
12140 (replace-match
12141 (char-to-string (car (rassoc (match-string 0 text) table)))
12142 t t text)))
12143 text)))
12145 (defun org-xor (a b)
12146 "Exclusive or."
12147 (if a (not b) b))
12149 (defun org-get-header (header)
12150 "Find a header field in the current buffer."
12151 (save-excursion
12152 (goto-char (point-min))
12153 (let ((case-fold-search t) s)
12154 (cond
12155 ((eq header 'from)
12156 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12157 (setq s (match-string 1)))
12158 (while (string-match "\"" s)
12159 (setq s (replace-match "" t t s)))
12160 (if (string-match "[<(].*" s)
12161 (setq s (replace-match "" t t s))))
12162 ((eq header 'message-id)
12163 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12164 (setq s (match-string 1))))
12165 ((eq header 'subject)
12166 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12167 (setq s (match-string 1)))))
12168 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12169 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12170 s)))
12173 (defun org-fixup-message-id-for-http (s)
12174 "Replace special characters in a message id, so it can be used in an http query."
12175 (while (string-match "<" s)
12176 (setq s (replace-match "%3C" t t s)))
12177 (while (string-match ">" s)
12178 (setq s (replace-match "%3E" t t s)))
12179 (while (string-match "@" s)
12180 (setq s (replace-match "%40" t t s)))
12183 ;;;###autoload
12184 (defun org-insert-link-global ()
12185 "Insert a link like Org-mode does.
12186 This command can be called in any mode to insert a link in Org-mode syntax."
12187 (interactive)
12188 (org-run-like-in-org-mode 'org-insert-link))
12190 (defun org-insert-link (&optional complete-file)
12191 "Insert a link. At the prompt, enter the link.
12193 Completion can be used to select a link previously stored with
12194 `org-store-link'. When the empty string is entered (i.e. if you just
12195 press RET at the prompt), the link defaults to the most recently
12196 stored link. As SPC triggers completion in the minibuffer, you need to
12197 use M-SPC or C-q SPC to force the insertion of a space character.
12199 You will also be prompted for a description, and if one is given, it will
12200 be displayed in the buffer instead of the link.
12202 If there is already a link at point, this command will allow you to edit link
12203 and description parts.
12205 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12206 selected using completion. The path to the file will be relative to
12207 the current directory if the file is in the current directory or a
12208 subdirectory. Otherwise, the link will be the absolute path as
12209 completed in the minibuffer (i.e. normally ~/path/to/file).
12211 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12212 is in the current directory or below.
12213 With three \\[universal-argument] prefixes, negate the meaning of
12214 `org-keep-stored-link-after-insertion'."
12215 (interactive "P")
12216 (let* ((wcf (current-window-configuration))
12217 (region (if (org-region-active-p)
12218 (buffer-substring (region-beginning) (region-end))))
12219 (remove (and region (list (region-beginning) (region-end))))
12220 (desc region)
12221 tmphist ; byte-compile incorrectly complains about this
12222 link entry file)
12223 (cond
12224 ((org-in-regexp org-bracket-link-regexp 1)
12225 ;; We do have a link at point, and we are going to edit it.
12226 (setq remove (list (match-beginning 0) (match-end 0)))
12227 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12228 (setq link (read-string "Link: "
12229 (org-link-unescape
12230 (org-match-string-no-properties 1)))))
12231 ((or (org-in-regexp org-angle-link-re)
12232 (org-in-regexp org-plain-link-re))
12233 ;; Convert to bracket link
12234 (setq remove (list (match-beginning 0) (match-end 0))
12235 link (read-string "Link: "
12236 (org-remove-angle-brackets (match-string 0)))))
12237 ((equal complete-file '(4))
12238 ;; Completing read for file names.
12239 (setq file (read-file-name "File: "))
12240 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12241 (pwd1 (file-name-as-directory (abbreviate-file-name
12242 (expand-file-name ".")))))
12243 (cond
12244 ((equal complete-file '(16))
12245 (setq link (org-make-link
12246 "file:"
12247 (abbreviate-file-name (expand-file-name file)))))
12248 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12249 (setq link (org-make-link "file:" (match-string 1 file))))
12250 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12251 (expand-file-name file))
12252 (setq link (org-make-link
12253 "file:" (match-string 1 (expand-file-name file)))))
12254 (t (setq link (org-make-link "file:" file))))))
12256 ;; Read link, with completion for stored links.
12257 (with-output-to-temp-buffer "*Org Links*"
12258 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12259 (when org-stored-links
12260 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12261 (princ (mapconcat
12262 (lambda (x)
12263 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12264 (reverse org-stored-links) "\n"))))
12265 (let ((cw (selected-window)))
12266 (select-window (get-buffer-window "*Org Links*"))
12267 (shrink-window-if-larger-than-buffer)
12268 (setq truncate-lines t)
12269 (select-window cw))
12270 ;; Fake a link history, containing the stored links.
12271 (setq tmphist (append (mapcar 'car org-stored-links)
12272 org-insert-link-history))
12273 (unwind-protect
12274 (setq link (org-completing-read
12275 "Link: "
12276 (append
12277 (mapcar (lambda (x) (list (concat (car x) ":")))
12278 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12279 (mapcar (lambda (x) (list (concat x ":")))
12280 org-link-types))
12281 nil nil nil
12282 'tmphist
12283 (or (car (car org-stored-links)))))
12284 (set-window-configuration wcf)
12285 (kill-buffer "*Org Links*"))
12286 (setq entry (assoc link org-stored-links))
12287 (or entry (push link org-insert-link-history))
12288 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12289 (not org-keep-stored-link-after-insertion))
12290 (setq org-stored-links (delq (assoc link org-stored-links)
12291 org-stored-links)))
12292 (setq desc (or desc (nth 1 entry)))))
12294 (if (string-match org-plain-link-re link)
12295 ;; URL-like link, normalize the use of angular brackets.
12296 (setq link (org-make-link (org-remove-angle-brackets link))))
12298 ;; Check if we are linking to the current file with a search option
12299 ;; If yes, simplify the link by using only the search option.
12300 (when (and buffer-file-name
12301 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12302 (let* ((path (match-string 1 link))
12303 (case-fold-search nil)
12304 (search (match-string 2 link)))
12305 (save-match-data
12306 (if (equal (file-truename buffer-file-name) (file-truename path))
12307 ;; We are linking to this same file, with a search option
12308 (setq link search)))))
12310 ;; Check if we can/should use a relative path. If yes, simplify the link
12311 (when (string-match "\\<file:\\(.*\\)" link)
12312 (let* ((path (match-string 1 link))
12313 (origpath path)
12314 (desc-is-link (equal link desc))
12315 (case-fold-search nil))
12316 (cond
12317 ((eq org-link-file-path-type 'absolute)
12318 (setq path (abbreviate-file-name (expand-file-name path))))
12319 ((eq org-link-file-path-type 'noabbrev)
12320 (setq path (expand-file-name path)))
12321 ((eq org-link-file-path-type 'relative)
12322 (setq path (file-relative-name path)))
12324 (save-match-data
12325 (if (string-match (concat "^" (regexp-quote
12326 (file-name-as-directory
12327 (expand-file-name "."))))
12328 (expand-file-name path))
12329 ;; We are linking a file with relative path name.
12330 (setq path (substring (expand-file-name path)
12331 (match-end 0)))))))
12332 (setq link (concat "file:" path))
12333 (if (equal desc origpath)
12334 (setq desc path))))
12336 (setq desc (read-string "Description: " desc))
12337 (unless (string-match "\\S-" desc) (setq desc nil))
12338 (if remove (apply 'delete-region remove))
12339 (insert (org-make-link-string link desc))))
12341 (defun org-completing-read (&rest args)
12342 (let ((minibuffer-local-completion-map
12343 (copy-keymap minibuffer-local-completion-map)))
12344 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12345 (apply 'completing-read args)))
12347 ;;; Opening/following a link
12348 (defvar org-link-search-failed nil)
12350 (defun org-next-link ()
12351 "Move forward to the next link.
12352 If the link is in hidden text, expose it."
12353 (interactive)
12354 (when (and org-link-search-failed (eq this-command last-command))
12355 (goto-char (point-min))
12356 (message "Link search wrapped back to beginning of buffer"))
12357 (setq org-link-search-failed nil)
12358 (let* ((pos (point))
12359 (ct (org-context))
12360 (a (assoc :link ct)))
12361 (if a (goto-char (nth 2 a)))
12362 (if (re-search-forward org-any-link-re nil t)
12363 (progn
12364 (goto-char (match-beginning 0))
12365 (if (org-invisible-p) (org-show-context)))
12366 (goto-char pos)
12367 (setq org-link-search-failed t)
12368 (error "No further link found"))))
12370 (defun org-previous-link ()
12371 "Move backward to the previous link.
12372 If the link is in hidden text, expose it."
12373 (interactive)
12374 (when (and org-link-search-failed (eq this-command last-command))
12375 (goto-char (point-max))
12376 (message "Link search wrapped back to end of buffer"))
12377 (setq org-link-search-failed nil)
12378 (let* ((pos (point))
12379 (ct (org-context))
12380 (a (assoc :link ct)))
12381 (if a (goto-char (nth 1 a)))
12382 (if (re-search-backward org-any-link-re nil t)
12383 (progn
12384 (goto-char (match-beginning 0))
12385 (if (org-invisible-p) (org-show-context)))
12386 (goto-char pos)
12387 (setq org-link-search-failed t)
12388 (error "No further link found"))))
12390 (defun org-find-file-at-mouse (ev)
12391 "Open file link or URL at mouse."
12392 (interactive "e")
12393 (mouse-set-point ev)
12394 (org-open-at-point 'in-emacs))
12396 (defun org-open-at-mouse (ev)
12397 "Open file link or URL at mouse."
12398 (interactive "e")
12399 (mouse-set-point ev)
12400 (org-open-at-point))
12402 (defvar org-window-config-before-follow-link nil
12403 "The window configuration before following a link.
12404 This is saved in case the need arises to restore it.")
12406 (defvar org-open-link-marker (make-marker)
12407 "Marker pointing to the location where `org-open-at-point; was called.")
12409 ;;;###autoload
12410 (defun org-open-at-point-global ()
12411 "Follow a link like Org-mode does.
12412 This command can be called in any mode to follow a link that has
12413 Org-mode syntax."
12414 (interactive)
12415 (org-run-like-in-org-mode 'org-open-at-point))
12417 (defun org-open-at-point (&optional in-emacs)
12418 "Open link at or after point.
12419 If there is no link at point, this function will search forward up to
12420 the end of the current subtree.
12421 Normally, files will be opened by an appropriate application. If the
12422 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12423 (interactive "P")
12424 (catch 'abort
12425 (move-marker org-open-link-marker (point))
12426 (setq org-window-config-before-follow-link (current-window-configuration))
12427 (org-remove-occur-highlights nil nil t)
12428 (if (org-at-timestamp-p t)
12429 (org-follow-timestamp-link)
12430 (let (type path link line search (pos (point)))
12431 (catch 'match
12432 (save-excursion
12433 (skip-chars-forward "^]\n\r")
12434 (when (org-in-regexp org-bracket-link-regexp)
12435 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12436 (while (string-match " *\n *" link)
12437 (setq link (replace-match " " t t link)))
12438 (setq link (org-link-expand-abbrev link))
12439 (if (string-match org-link-re-with-space2 link)
12440 (setq type (match-string 1 link) path (match-string 2 link))
12441 (setq type "thisfile" path link))
12442 (throw 'match t)))
12444 (when (get-text-property (point) 'org-linked-text)
12445 (setq type "thisfile"
12446 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12447 (1+ (point)) (point))
12448 path (buffer-substring
12449 (previous-single-property-change pos 'org-linked-text)
12450 (next-single-property-change pos 'org-linked-text)))
12451 (throw 'match t))
12453 (save-excursion
12454 (when (or (org-in-regexp org-angle-link-re)
12455 (org-in-regexp org-plain-link-re))
12456 (setq type (match-string 1) path (match-string 2))
12457 (throw 'match t)))
12458 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12459 (setq type "tree-match"
12460 path (match-string 1))
12461 (throw 'match t))
12462 (save-excursion
12463 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12464 (setq type "tags"
12465 path (match-string 1))
12466 (while (string-match ":" path)
12467 (setq path (replace-match "+" t t path)))
12468 (throw 'match t))))
12469 (unless path
12470 (error "No link found"))
12471 ;; Remove any trailing spaces in path
12472 (if (string-match " +\\'" path)
12473 (setq path (replace-match "" t t path)))
12475 (cond
12477 ((assoc type org-link-protocols)
12478 (funcall (nth 1 (assoc type org-link-protocols)) path))
12480 ((equal type "mailto")
12481 (let ((cmd (car org-link-mailto-program))
12482 (args (cdr org-link-mailto-program)) args1
12483 (address path) (subject "") a)
12484 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12485 (setq address (match-string 1 path)
12486 subject (org-link-escape (match-string 2 path))))
12487 (while args
12488 (cond
12489 ((not (stringp (car args))) (push (pop args) args1))
12490 (t (setq a (pop args))
12491 (if (string-match "%a" a)
12492 (setq a (replace-match address t t a)))
12493 (if (string-match "%s" a)
12494 (setq a (replace-match subject t t a)))
12495 (push a args1))))
12496 (apply cmd (nreverse args1))))
12498 ((member type '("http" "https" "ftp" "news"))
12499 (browse-url (concat type ":" (org-link-escape
12500 path org-link-escape-chars-browser))))
12502 ((member type '("message"))
12503 (browse-url (concat type ":" path)))
12505 ((string= type "tags")
12506 (org-tags-view in-emacs path))
12507 ((string= type "thisfile")
12508 (if in-emacs
12509 (switch-to-buffer-other-window
12510 (org-get-buffer-for-internal-link (current-buffer)))
12511 (org-mark-ring-push))
12512 (let ((cmd `(org-link-search
12513 ,path
12514 ,(cond ((equal in-emacs '(4)) 'occur)
12515 ((equal in-emacs '(16)) 'org-occur)
12516 (t nil))
12517 ,pos)))
12518 (condition-case nil (eval cmd)
12519 (error (progn (widen) (eval cmd))))))
12521 ((string= type "tree-match")
12522 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12524 ((string= type "file")
12525 (if (string-match "::\\([0-9]+\\)\\'" path)
12526 (setq line (string-to-number (match-string 1 path))
12527 path (substring path 0 (match-beginning 0)))
12528 (if (string-match "::\\(.+\\)\\'" path)
12529 (setq search (match-string 1 path)
12530 path (substring path 0 (match-beginning 0)))))
12531 (if (string-match "[*?{]" (file-name-nondirectory path))
12532 (dired path)
12533 (org-open-file path in-emacs line search)))
12535 ((string= type "news")
12536 (org-follow-gnus-link path))
12538 ((string= type "bbdb")
12539 (org-follow-bbdb-link path))
12541 ((string= type "info")
12542 (org-follow-info-link path))
12544 ((string= type "gnus")
12545 (let (group article)
12546 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12547 (error "Error in Gnus link"))
12548 (setq group (match-string 1 path)
12549 article (match-string 3 path))
12550 (org-follow-gnus-link group article)))
12552 ((string= type "vm")
12553 (let (folder article)
12554 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12555 (error "Error in VM link"))
12556 (setq folder (match-string 1 path)
12557 article (match-string 3 path))
12558 ;; in-emacs is the prefix arg, will be interpreted as read-only
12559 (org-follow-vm-link folder article in-emacs)))
12561 ((string= type "wl")
12562 (let (folder article)
12563 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12564 (error "Error in Wanderlust link"))
12565 (setq folder (match-string 1 path)
12566 article (match-string 3 path))
12567 (org-follow-wl-link folder article)))
12569 ((string= type "mhe")
12570 (let (folder article)
12571 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12572 (error "Error in MHE link"))
12573 (setq folder (match-string 1 path)
12574 article (match-string 3 path))
12575 (org-follow-mhe-link folder article)))
12577 ((string= type "rmail")
12578 (let (folder article)
12579 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12580 (error "Error in RMAIL link"))
12581 (setq folder (match-string 1 path)
12582 article (match-string 3 path))
12583 (org-follow-rmail-link folder article)))
12585 ((string= type "shell")
12586 (let ((cmd path))
12587 (if (or (not org-confirm-shell-link-function)
12588 (funcall org-confirm-shell-link-function
12589 (format "Execute \"%s\" in shell? "
12590 (org-add-props cmd nil
12591 'face 'org-warning))))
12592 (progn
12593 (message "Executing %s" cmd)
12594 (shell-command cmd))
12595 (error "Abort"))))
12597 ((string= type "elisp")
12598 (let ((cmd path))
12599 (if (or (not org-confirm-elisp-link-function)
12600 (funcall org-confirm-elisp-link-function
12601 (format "Execute \"%s\" as elisp? "
12602 (org-add-props cmd nil
12603 'face 'org-warning))))
12604 (message "%s => %s" cmd (eval (read cmd)))
12605 (error "Abort"))))
12608 (browse-url-at-point)))))
12609 (move-marker org-open-link-marker nil)))
12611 ;;; File search
12613 (defvar org-create-file-search-functions nil
12614 "List of functions to construct the right search string for a file link.
12615 These functions are called in turn with point at the location to
12616 which the link should point.
12618 A function in the hook should first test if it would like to
12619 handle this file type, for example by checking the major-mode or
12620 the file extension. If it decides not to handle this file, it
12621 should just return nil to give other functions a chance. If it
12622 does handle the file, it must return the search string to be used
12623 when following the link. The search string will be part of the
12624 file link, given after a double colon, and `org-open-at-point'
12625 will automatically search for it. If special measures must be
12626 taken to make the search successful, another function should be
12627 added to the companion hook `org-execute-file-search-functions',
12628 which see.
12630 A function in this hook may also use `setq' to set the variable
12631 `description' to provide a suggestion for the descriptive text to
12632 be used for this link when it gets inserted into an Org-mode
12633 buffer with \\[org-insert-link].")
12635 (defvar org-execute-file-search-functions nil
12636 "List of functions to execute a file search triggered by a link.
12638 Functions added to this hook must accept a single argument, the
12639 search string that was part of the file link, the part after the
12640 double colon. The function must first check if it would like to
12641 handle this search, for example by checking the major-mode or the
12642 file extension. If it decides not to handle this search, it
12643 should just return nil to give other functions a chance. If it
12644 does handle the search, it must return a non-nil value to keep
12645 other functions from trying.
12647 Each function can access the current prefix argument through the
12648 variable `current-prefix-argument'. Note that a single prefix is
12649 used to force opening a link in Emacs, so it may be good to only
12650 use a numeric or double prefix to guide the search function.
12652 In case this is needed, a function in this hook can also restore
12653 the window configuration before `org-open-at-point' was called using:
12655 (set-window-configuration org-window-config-before-follow-link)")
12657 (defun org-link-search (s &optional type avoid-pos)
12658 "Search for a link search option.
12659 If S is surrounded by forward slashes, it is interpreted as a
12660 regular expression. In org-mode files, this will create an `org-occur'
12661 sparse tree. In ordinary files, `occur' will be used to list matches.
12662 If the current buffer is in `dired-mode', grep will be used to search
12663 in all files. If AVOID-POS is given, ignore matches near that position."
12664 (let ((case-fold-search t)
12665 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12666 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12667 (append '(("") (" ") ("\t") ("\n"))
12668 org-emphasis-alist)
12669 "\\|") "\\)"))
12670 (pos (point))
12671 (pre "") (post "")
12672 words re0 re1 re2 re3 re4 re5 re2a reall)
12673 (cond
12674 ;; First check if there are any special
12675 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12676 ;; Now try the builtin stuff
12677 ((save-excursion
12678 (goto-char (point-min))
12679 (and
12680 (re-search-forward
12681 (concat "<<" (regexp-quote s0) ">>") nil t)
12682 (setq pos (match-beginning 0))))
12683 ;; There is an exact target for this
12684 (goto-char pos))
12685 ((string-match "^/\\(.*\\)/$" s)
12686 ;; A regular expression
12687 (cond
12688 ((org-mode-p)
12689 (org-occur (match-string 1 s)))
12690 ;;((eq major-mode 'dired-mode)
12691 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12692 (t (org-do-occur (match-string 1 s)))))
12694 ;; A normal search strings
12695 (when (equal (string-to-char s) ?*)
12696 ;; Anchor on headlines, post may include tags.
12697 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12698 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12699 s (substring s 1)))
12700 (remove-text-properties
12701 0 (length s)
12702 '(face nil mouse-face nil keymap nil fontified nil) s)
12703 ;; Make a series of regular expressions to find a match
12704 (setq words (org-split-string s "[ \n\r\t]+")
12705 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12706 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12707 "\\)" markers)
12708 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12709 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12710 re1 (concat pre re2 post)
12711 re3 (concat pre re4 post)
12712 re5 (concat pre ".*" re4)
12713 re2 (concat pre re2)
12714 re2a (concat pre re2a)
12715 re4 (concat pre re4)
12716 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12717 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12718 re5 "\\)"
12720 (cond
12721 ((eq type 'org-occur) (org-occur reall))
12722 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12723 (t (goto-char (point-min))
12724 (if (or (org-search-not-self 1 re0 nil t)
12725 (org-search-not-self 1 re1 nil t)
12726 (org-search-not-self 1 re2 nil t)
12727 (org-search-not-self 1 re2a nil t)
12728 (org-search-not-self 1 re3 nil t)
12729 (org-search-not-self 1 re4 nil t)
12730 (org-search-not-self 1 re5 nil t)
12732 (goto-char (match-beginning 1))
12733 (goto-char pos)
12734 (error "No match")))))
12736 ;; Normal string-search
12737 (goto-char (point-min))
12738 (if (search-forward s nil t)
12739 (goto-char (match-beginning 0))
12740 (error "No match"))))
12741 (and (org-mode-p) (org-show-context 'link-search))))
12743 (defun org-search-not-self (group &rest args)
12744 "Execute `re-search-forward', but only accept matches that do not
12745 enclose the position of `org-open-link-marker'."
12746 (let ((m org-open-link-marker))
12747 (catch 'exit
12748 (while (apply 're-search-forward args)
12749 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12750 (goto-char (match-end group))
12751 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12752 (> (match-beginning 0) (marker-position m))
12753 (< (match-end 0) (marker-position m)))
12754 (save-match-data
12755 (or (not (org-in-regexp
12756 org-bracket-link-analytic-regexp 1))
12757 (not (match-end 4)) ; no description
12758 (and (<= (match-beginning 4) (point))
12759 (>= (match-end 4) (point))))))
12760 (throw 'exit (point))))))))
12762 (defun org-get-buffer-for-internal-link (buffer)
12763 "Return a buffer to be used for displaying the link target of internal links."
12764 (cond
12765 ((not org-display-internal-link-with-indirect-buffer)
12766 buffer)
12767 ((string-match "(Clone)$" (buffer-name buffer))
12768 (message "Buffer is already a clone, not making another one")
12769 ;; we also do not modify visibility in this case
12770 buffer)
12771 (t ; make a new indirect buffer for displaying the link
12772 (let* ((bn (buffer-name buffer))
12773 (ibn (concat bn "(Clone)"))
12774 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12775 (with-current-buffer ib (org-overview))
12776 ib))))
12778 (defun org-do-occur (regexp &optional cleanup)
12779 "Call the Emacs command `occur'.
12780 If CLEANUP is non-nil, remove the printout of the regular expression
12781 in the *Occur* buffer. This is useful if the regex is long and not useful
12782 to read."
12783 (occur regexp)
12784 (when cleanup
12785 (let ((cwin (selected-window)) win beg end)
12786 (when (setq win (get-buffer-window "*Occur*"))
12787 (select-window win))
12788 (goto-char (point-min))
12789 (when (re-search-forward "match[a-z]+" nil t)
12790 (setq beg (match-end 0))
12791 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12792 (setq end (1- (match-beginning 0)))))
12793 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12794 (goto-char (point-min))
12795 (select-window cwin))))
12797 ;;; The mark ring for links jumps
12799 (defvar org-mark-ring nil
12800 "Mark ring for positions before jumps in Org-mode.")
12801 (defvar org-mark-ring-last-goto nil
12802 "Last position in the mark ring used to go back.")
12803 ;; Fill and close the ring
12804 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12805 (loop for i from 1 to org-mark-ring-length do
12806 (push (make-marker) org-mark-ring))
12807 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12808 org-mark-ring)
12810 (defun org-mark-ring-push (&optional pos buffer)
12811 "Put the current position or POS into the mark ring and rotate it."
12812 (interactive)
12813 (setq pos (or pos (point)))
12814 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12815 (move-marker (car org-mark-ring)
12816 (or pos (point))
12817 (or buffer (current-buffer)))
12818 (message "%s"
12819 (substitute-command-keys
12820 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12822 (defun org-mark-ring-goto (&optional n)
12823 "Jump to the previous position in the mark ring.
12824 With prefix arg N, jump back that many stored positions. When
12825 called several times in succession, walk through the entire ring.
12826 Org-mode commands jumping to a different position in the current file,
12827 or to another Org-mode file, automatically push the old position
12828 onto the ring."
12829 (interactive "p")
12830 (let (p m)
12831 (if (eq last-command this-command)
12832 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12833 (setq p org-mark-ring))
12834 (setq org-mark-ring-last-goto p)
12835 (setq m (car p))
12836 (switch-to-buffer (marker-buffer m))
12837 (goto-char m)
12838 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12840 (defun org-remove-angle-brackets (s)
12841 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12842 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12844 (defun org-add-angle-brackets (s)
12845 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12846 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12849 ;;; Following specific links
12851 (defun org-follow-timestamp-link ()
12852 (cond
12853 ((org-at-date-range-p t)
12854 (let ((org-agenda-start-on-weekday)
12855 (t1 (match-string 1))
12856 (t2 (match-string 2)))
12857 (setq t1 (time-to-days (org-time-string-to-time t1))
12858 t2 (time-to-days (org-time-string-to-time t2)))
12859 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12860 ((org-at-timestamp-p t)
12861 (org-agenda-list nil (time-to-days (org-time-string-to-time
12862 (substring (match-string 1) 0 10)))
12864 (t (error "This should not happen"))))
12867 (defun org-follow-bbdb-link (name)
12868 "Follow a BBDB link to NAME."
12869 (require 'bbdb)
12870 (let ((inhibit-redisplay (not debug-on-error))
12871 (bbdb-electric-p nil))
12872 (catch 'exit
12873 ;; Exact match on name
12874 (bbdb-name (concat "\\`" name "\\'") nil)
12875 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12876 ;; Exact match on name
12877 (bbdb-company (concat "\\`" name "\\'") nil)
12878 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12879 ;; Partial match on name
12880 (bbdb-name name nil)
12881 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12882 ;; Partial match on company
12883 (bbdb-company name nil)
12884 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12885 ;; General match including network address and notes
12886 (bbdb name nil)
12887 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12888 (delete-window (get-buffer-window "*BBDB*"))
12889 (error "No matching BBDB record")))))
12891 (defun org-follow-info-link (name)
12892 "Follow an info file & node link to NAME."
12893 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12894 (string-match "\\(.*\\)" name))
12895 (progn
12896 (require 'info)
12897 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12898 (Info-find-node (match-string 1 name) (match-string 2 name))
12899 (Info-find-node (match-string 1 name) "Top")))
12900 (message "Could not open: %s" name)))
12902 (defun org-follow-gnus-link (&optional group article)
12903 "Follow a Gnus link to GROUP and ARTICLE."
12904 (require 'gnus)
12905 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12906 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12907 (cond ((and group article)
12908 (gnus-group-read-group 1 nil group)
12909 (gnus-summary-goto-article (string-to-number article) nil t))
12910 (group (gnus-group-jump-to-group group))))
12912 (defun org-follow-vm-link (&optional folder article readonly)
12913 "Follow a VM link to FOLDER and ARTICLE."
12914 (require 'vm)
12915 (setq article (org-add-angle-brackets article))
12916 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12917 ;; ange-ftp or efs or tramp access
12918 (let ((user (or (match-string 1 folder) (user-login-name)))
12919 (host (match-string 2 folder))
12920 (file (match-string 3 folder)))
12921 (cond
12922 ((featurep 'tramp)
12923 ;; use tramp to access the file
12924 (if (featurep 'xemacs)
12925 (setq folder (format "[%s@%s]%s" user host file))
12926 (setq folder (format "/%s@%s:%s" user host file))))
12928 ;; use ange-ftp or efs
12929 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12930 (setq folder (format "/%s@%s:%s" user host file))))))
12931 (when folder
12932 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12933 (sit-for 0.1)
12934 (when article
12935 (vm-select-folder-buffer)
12936 (widen)
12937 (let ((case-fold-search t))
12938 (goto-char (point-min))
12939 (if (not (re-search-forward
12940 (concat "^" "message-id: *" (regexp-quote article))))
12941 (error "Could not find the specified message in this folder"))
12942 (vm-isearch-update)
12943 (vm-isearch-narrow)
12944 (vm-beginning-of-message)
12945 (vm-summarize)))))
12947 (defun org-follow-wl-link (folder article)
12948 "Follow a Wanderlust link to FOLDER and ARTICLE."
12949 (if (and (string= folder "%")
12950 article
12951 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12952 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12953 ;; Thus, we recompose folder and article ids.
12954 (setq folder (format "%s#%s" folder (match-string 1 article))
12955 article (match-string 3 article)))
12956 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12957 (error "No such folder: %s" folder))
12958 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12959 (and article
12960 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12961 (wl-summary-redisplay)))
12963 (defun org-follow-rmail-link (folder article)
12964 "Follow an RMAIL link to FOLDER and ARTICLE."
12965 (setq article (org-add-angle-brackets article))
12966 (let (message-number)
12967 (save-excursion
12968 (save-window-excursion
12969 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12970 (setq message-number
12971 (save-restriction
12972 (widen)
12973 (goto-char (point-max))
12974 (if (re-search-backward
12975 (concat "^Message-ID:\\s-+" (regexp-quote
12976 (or article "")))
12977 nil t)
12978 (rmail-what-message))))))
12979 (if message-number
12980 (progn
12981 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12982 (rmail-show-message message-number)
12983 message-number)
12984 (error "Message not found"))))
12986 ;;; mh-e integration based on planner-mode
12987 (defun org-mhe-get-message-real-folder ()
12988 "Return the name of the current message real folder, so if you use
12989 sequences, it will now work."
12990 (save-excursion
12991 (let* ((folder
12992 (if (equal major-mode 'mh-folder-mode)
12993 mh-current-folder
12994 ;; Refer to the show buffer
12995 mh-show-folder-buffer))
12996 (end-index
12997 (if (boundp 'mh-index-folder)
12998 (min (length mh-index-folder) (length folder))))
13000 ;; a simple test on mh-index-data does not work, because
13001 ;; mh-index-data is always nil in a show buffer.
13002 (if (and (boundp 'mh-index-folder)
13003 (string= mh-index-folder (substring folder 0 end-index)))
13004 (if (equal major-mode 'mh-show-mode)
13005 (save-window-excursion
13006 (let (pop-up-frames)
13007 (when (buffer-live-p (get-buffer folder))
13008 (progn
13009 (pop-to-buffer folder)
13010 (org-mhe-get-message-folder-from-index)
13013 (org-mhe-get-message-folder-from-index)
13015 folder
13019 (defun org-mhe-get-message-folder-from-index ()
13020 "Returns the name of the message folder in a index folder buffer."
13021 (save-excursion
13022 (mh-index-previous-folder)
13023 (re-search-forward "^\\(+.*\\)$" nil t)
13024 (message "%s" (match-string 1))))
13026 (defun org-mhe-get-message-folder ()
13027 "Return the name of the current message folder. Be careful if you
13028 use sequences."
13029 (save-excursion
13030 (if (equal major-mode 'mh-folder-mode)
13031 mh-current-folder
13032 ;; Refer to the show buffer
13033 mh-show-folder-buffer)))
13035 (defun org-mhe-get-message-num ()
13036 "Return the number of the current message. Be careful if you
13037 use sequences."
13038 (save-excursion
13039 (if (equal major-mode 'mh-folder-mode)
13040 (mh-get-msg-num nil)
13041 ;; Refer to the show buffer
13042 (mh-show-buffer-message-number))))
13044 (defun org-mhe-get-header (header)
13045 "Return a header of the message in folder mode. This will create a
13046 show buffer for the corresponding message. If you have a more clever
13047 idea..."
13048 (let* ((folder (org-mhe-get-message-folder))
13049 (num (org-mhe-get-message-num))
13050 (buffer (get-buffer-create (concat "show-" folder)))
13051 (header-field))
13052 (with-current-buffer buffer
13053 (mh-display-msg num folder)
13054 (if (equal major-mode 'mh-folder-mode)
13055 (mh-header-display)
13056 (mh-show-header-display))
13057 (set-buffer buffer)
13058 (setq header-field (mh-get-header-field header))
13059 (if (equal major-mode 'mh-folder-mode)
13060 (mh-show)
13061 (mh-show-show))
13062 header-field)))
13064 (defun org-follow-mhe-link (folder article)
13065 "Follow an MHE link to FOLDER and ARTICLE.
13066 If ARTICLE is nil FOLDER is shown. If the configuration variable
13067 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13068 ARTICLE is searched in all folders. Indexed searches (swish++,
13069 namazu, and others supported by MH-E) will always search in all
13070 folders."
13071 (require 'mh-e)
13072 (require 'mh-search)
13073 (require 'mh-utils)
13074 (mh-find-path)
13075 (if (not article)
13076 (mh-visit-folder (mh-normalize-folder-name folder))
13077 (setq article (org-add-angle-brackets article))
13078 (mh-search-choose)
13079 (if (equal mh-searcher 'pick)
13080 (progn
13081 (mh-search folder (list "--message-id" article))
13082 (when (and org-mhe-search-all-folders
13083 (not (org-mhe-get-message-real-folder)))
13084 (kill-this-buffer)
13085 (mh-search "+" (list "--message-id" article))))
13086 (mh-search "+" article))
13087 (if (org-mhe-get-message-real-folder)
13088 (mh-show-msg 1)
13089 (kill-this-buffer)
13090 (error "Message not found"))))
13092 ;;; BibTeX links
13094 ;; Use the custom search meachnism to construct and use search strings for
13095 ;; file links to BibTeX database entries.
13097 (defun org-create-file-search-in-bibtex ()
13098 "Create the search string and description for a BibTeX database entry."
13099 (when (eq major-mode 'bibtex-mode)
13100 ;; yes, we want to construct this search string.
13101 ;; Make a good description for this entry, using names, year and the title
13102 ;; Put it into the `description' variable which is dynamically scoped.
13103 (let ((bibtex-autokey-names 1)
13104 (bibtex-autokey-names-stretch 1)
13105 (bibtex-autokey-name-case-convert-function 'identity)
13106 (bibtex-autokey-name-separator " & ")
13107 (bibtex-autokey-additional-names " et al.")
13108 (bibtex-autokey-year-length 4)
13109 (bibtex-autokey-name-year-separator " ")
13110 (bibtex-autokey-titlewords 3)
13111 (bibtex-autokey-titleword-separator " ")
13112 (bibtex-autokey-titleword-case-convert-function 'identity)
13113 (bibtex-autokey-titleword-length 'infty)
13114 (bibtex-autokey-year-title-separator ": "))
13115 (setq description (bibtex-generate-autokey)))
13116 ;; Now parse the entry, get the key and return it.
13117 (save-excursion
13118 (bibtex-beginning-of-entry)
13119 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13121 (defun org-execute-file-search-in-bibtex (s)
13122 "Find the link search string S as a key for a database entry."
13123 (when (eq major-mode 'bibtex-mode)
13124 ;; Yes, we want to do the search in this file.
13125 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13126 (goto-char (point-min))
13127 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13128 (regexp-quote s) "[ \t\n]*,") nil t)
13129 (goto-char (match-beginning 0)))
13130 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13131 ;; Use double prefix to indicate that any web link should be browsed
13132 (let ((b (current-buffer)) (p (point)))
13133 ;; Restore the window configuration because we just use the web link
13134 (set-window-configuration org-window-config-before-follow-link)
13135 (save-excursion (set-buffer b) (goto-char p)
13136 (bibtex-url)))
13137 (recenter 0)) ; Move entry start to beginning of window
13138 ;; return t to indicate that the search is done.
13141 ;; Finally add the functions to the right hooks.
13142 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13143 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13145 ;; end of Bibtex link setup
13147 ;;; Following file links
13149 (defun org-open-file (path &optional in-emacs line search)
13150 "Open the file at PATH.
13151 First, this expands any special file name abbreviations. Then the
13152 configuration variable `org-file-apps' is checked if it contains an
13153 entry for this file type, and if yes, the corresponding command is launched.
13154 If no application is found, Emacs simply visits the file.
13155 With optional argument IN-EMACS, Emacs will visit the file.
13156 Optional LINE specifies a line to go to, optional SEARCH a string to
13157 search for. If LINE or SEARCH is given, the file will always be
13158 opened in Emacs.
13159 If the file does not exist, an error is thrown."
13160 (setq in-emacs (or in-emacs line search))
13161 (let* ((file (if (equal path "")
13162 buffer-file-name
13163 (substitute-in-file-name (expand-file-name path))))
13164 (apps (append org-file-apps (org-default-apps)))
13165 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13166 (dirp (if remp nil (file-directory-p file)))
13167 (dfile (downcase file))
13168 (old-buffer (current-buffer))
13169 (old-pos (point))
13170 (old-mode major-mode)
13171 ext cmd)
13172 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13173 (setq ext (match-string 1 dfile))
13174 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13175 (setq ext (match-string 1 dfile))))
13176 (if in-emacs
13177 (setq cmd 'emacs)
13178 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13179 (and dirp (cdr (assoc 'directory apps)))
13180 (cdr (assoc ext apps))
13181 (cdr (assoc t apps)))))
13182 (when (eq cmd 'mailcap)
13183 (require 'mailcap)
13184 (mailcap-parse-mailcaps)
13185 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13186 (command (mailcap-mime-info mime-type)))
13187 (if (stringp command)
13188 (setq cmd command)
13189 (setq cmd 'emacs))))
13190 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13191 (not (file-exists-p file))
13192 (not org-open-non-existing-files))
13193 (error "No such file: %s" file))
13194 (cond
13195 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13196 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13197 (while (string-match "['\"]%s['\"]" cmd)
13198 (setq cmd (replace-match "%s" t t cmd)))
13199 (while (string-match "%s" cmd)
13200 (setq cmd (replace-match (shell-quote-argument file) t t cmd)))
13201 (save-window-excursion
13202 (start-process-shell-command cmd nil cmd)))
13203 ((or (stringp cmd)
13204 (eq cmd 'emacs))
13205 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13206 (widen)
13207 (if line (goto-line line)
13208 (if search (org-link-search search))))
13209 ((consp cmd)
13210 (eval cmd))
13211 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13212 (and (org-mode-p) (eq old-mode 'org-mode)
13213 (or (not (equal old-buffer (current-buffer)))
13214 (not (equal old-pos (point))))
13215 (org-mark-ring-push old-pos old-buffer))))
13217 (defun org-default-apps ()
13218 "Return the default applications for this operating system."
13219 (cond
13220 ((eq system-type 'darwin)
13221 org-file-apps-defaults-macosx)
13222 ((eq system-type 'windows-nt)
13223 org-file-apps-defaults-windowsnt)
13224 (t org-file-apps-defaults-gnu)))
13226 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13227 (defun org-file-remote-p (file)
13228 "Test whether FILE specifies a location on a remote system.
13229 Return non-nil if the location is indeed remote.
13231 For example, the filename \"/user@host:/foo\" specifies a location
13232 on the system \"/user@host:\"."
13233 (cond ((fboundp 'file-remote-p)
13234 (file-remote-p file))
13235 ((fboundp 'tramp-handle-file-remote-p)
13236 (tramp-handle-file-remote-p file))
13237 ((and (boundp 'ange-ftp-name-format)
13238 (string-match (car ange-ftp-name-format) file))
13240 (t nil)))
13243 ;;;; Hooks for remember.el, and refiling
13245 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13246 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13248 ;;;###autoload
13249 (defun org-remember-insinuate ()
13250 "Setup remember.el for use wiht Org-mode."
13251 (require 'remember)
13252 (setq remember-annotation-functions '(org-remember-annotation))
13253 (setq remember-handler-functions '(org-remember-handler))
13254 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13256 ;;;###autoload
13257 (defun org-remember-annotation ()
13258 "Return a link to the current location as an annotation for remember.el.
13259 If you are using Org-mode files as target for data storage with
13260 remember.el, then the annotations should include a link compatible with the
13261 conventions in Org-mode. This function returns such a link."
13262 (org-store-link nil))
13264 (defconst org-remember-help
13265 "Select a destination location for the note.
13266 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13267 RET on headline -> Store as sublevel entry to current headline
13268 RET at beg-of-buf -> Append to file as level 2 headline
13269 <left>/<right> -> before/after current headline, same headings level")
13271 (defvar org-remember-previous-location nil)
13272 (defvar org-force-remember-template-char) ;; dynamically scoped
13274 (defun org-select-remember-template (&optional use-char)
13275 (when org-remember-templates
13276 (let* ((templates (mapcar (lambda (x)
13277 (if (stringp (car x))
13278 (append (list (nth 1 x) (car x)) (cddr x))
13279 (append (list (car x) "") (cdr x))))
13280 org-remember-templates))
13281 (char (or use-char
13282 (cond
13283 ((= (length templates) 1)
13284 (caar templates))
13285 ((and (boundp 'org-force-remember-template-char)
13286 org-force-remember-template-char)
13287 (if (stringp org-force-remember-template-char)
13288 (string-to-char org-force-remember-template-char)
13289 org-force-remember-template-char))
13291 (message "Select template: %s"
13292 (mapconcat
13293 (lambda (x)
13294 (cond
13295 ((not (string-match "\\S-" (nth 1 x)))
13296 (format "[%c]" (car x)))
13297 ((equal (downcase (car x))
13298 (downcase (aref (nth 1 x) 0)))
13299 (format "[%c]%s" (car x)
13300 (substring (nth 1 x) 1)))
13301 (t (format "[%c]%s" (car x) (nth 1 x)))))
13302 templates " "))
13303 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13304 (when (equal char0 ?\C-g)
13305 (jump-to-register remember-register)
13306 (kill-buffer remember-buffer))
13307 char0))))))
13308 (cddr (assoc char templates)))))
13310 (defvar x-last-selected-text)
13311 (defvar x-last-selected-text-primary)
13313 ;;;###autoload
13314 (defun org-remember-apply-template (&optional use-char skip-interactive)
13315 "Initialize *remember* buffer with template, invoke `org-mode'.
13316 This function should be placed into `remember-mode-hook' and in fact requires
13317 to be run from that hook to function properly."
13318 (unless (fboundp 'remember-finalize)
13319 (defalias 'remember-finalize 'remember-buffer))
13320 (if org-remember-templates
13321 (let* ((entry (org-select-remember-template use-char))
13322 (tpl (car entry))
13323 (plist-p (if org-store-link-plist t nil))
13324 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13325 (string-match "\\S-" (nth 1 entry)))
13326 (nth 1 entry)
13327 org-default-notes-file))
13328 (headline (nth 2 entry))
13329 (v-c (or (and (eq window-system 'x)
13330 (fboundp 'x-cut-buffer-or-selection-value)
13331 (x-cut-buffer-or-selection-value))
13332 (org-bound-and-true-p x-last-selected-text)
13333 (org-bound-and-true-p x-last-selected-text-primary)
13334 (and (> (length kill-ring) 0) (current-kill 0))))
13335 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13336 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13337 (v-u (concat "[" (substring v-t 1 -1) "]"))
13338 (v-U (concat "[" (substring v-T 1 -1) "]"))
13339 ;; `initial' and `annotation' are bound in `remember'
13340 (v-i (if (boundp 'initial) initial))
13341 (v-a (if (and (boundp 'annotation) annotation)
13342 (if (equal annotation "[[]]") "" annotation)
13343 ""))
13344 (v-A (if (and v-a
13345 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13346 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13347 v-a))
13348 (v-n user-full-name)
13349 (org-startup-folded nil)
13350 org-time-was-given org-end-time-was-given x
13351 prompt completions char time pos default histvar)
13352 (setq org-store-link-plist
13353 (append (list :annotation v-a :initial v-i)
13354 org-store-link-plist))
13355 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13356 (erase-buffer)
13357 (insert (substitute-command-keys
13358 (format
13359 "## Filing location: Select interactively, default, or last used:
13360 ## %s to select file and header location interactively.
13361 ## %s \"%s\" -> \"* %s\"
13362 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13363 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13364 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13365 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13366 (abbreviate-file-name (or file org-default-notes-file))
13367 (or headline "")
13368 (or (car org-remember-previous-location) "???")
13369 (or (cdr org-remember-previous-location) "???"))))
13370 (insert tpl) (goto-char (point-min))
13371 ;; Simple %-escapes
13372 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13373 (when (and initial (equal (match-string 0) "%i"))
13374 (save-match-data
13375 (let* ((lead (buffer-substring
13376 (point-at-bol) (match-beginning 0))))
13377 (setq v-i (mapconcat 'identity
13378 (org-split-string initial "\n")
13379 (concat "\n" lead))))))
13380 (replace-match
13381 (or (eval (intern (concat "v-" (match-string 1)))) "")
13382 t t))
13384 ;; %[] Insert contents of a file.
13385 (goto-char (point-min))
13386 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13387 (let ((start (match-beginning 0))
13388 (end (match-end 0))
13389 (filename (expand-file-name (match-string 1))))
13390 (goto-char start)
13391 (delete-region start end)
13392 (condition-case error
13393 (insert-file-contents filename)
13394 (error (insert (format "%%![Couldn't insert %s: %s]"
13395 filename error))))))
13396 ;; %() embedded elisp
13397 (goto-char (point-min))
13398 (while (re-search-forward "%\\((.+)\\)" nil t)
13399 (goto-char (match-beginning 0))
13400 (let ((template-start (point)))
13401 (forward-char 1)
13402 (let ((result
13403 (condition-case error
13404 (eval (read (current-buffer)))
13405 (error (format "%%![Error: %s]" error)))))
13406 (delete-region template-start (point))
13407 (insert result))))
13409 ;; From the property list
13410 (when plist-p
13411 (goto-char (point-min))
13412 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13413 (and (setq x (or (plist-get org-store-link-plist
13414 (intern (match-string 1))) ""))
13415 (replace-match x t t))))
13417 ;; Turn on org-mode in the remember buffer, set local variables
13418 (org-mode)
13419 (org-set-local 'org-finish-function 'remember-finalize)
13420 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13421 (org-set-local 'org-default-notes-file file))
13422 (if (and headline (stringp headline) (string-match "\\S-" headline))
13423 (org-set-local 'org-remember-default-headline headline))
13424 ;; Interactive template entries
13425 (goto-char (point-min))
13426 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
13427 (setq char (if (match-end 3) (match-string 3))
13428 prompt (if (match-end 2) (match-string 2)))
13429 (goto-char (match-beginning 0))
13430 (replace-match "")
13431 (setq completions nil default nil)
13432 (when prompt
13433 (setq completions (org-split-string prompt "|")
13434 prompt (pop completions)
13435 default (car completions)
13436 histvar (intern (concat
13437 "org-remember-template-prompt-history::"
13438 (or prompt "")))
13439 completions (mapcar 'list completions)))
13440 (cond
13441 ((member char '("G" "g"))
13442 (let* ((org-last-tags-completion-table
13443 (org-global-tags-completion-table
13444 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13445 (org-add-colon-after-tag-completion t)
13446 (ins (completing-read
13447 (if prompt (concat prompt ": ") "Tags: ")
13448 'org-tags-completion-function nil nil nil
13449 'org-tags-history)))
13450 (setq ins (mapconcat 'identity
13451 (org-split-string ins (org-re "[^[:alnum:]]+"))
13452 ":"))
13453 (when (string-match "\\S-" ins)
13454 (or (equal (char-before) ?:) (insert ":"))
13455 (insert ins)
13456 (or (equal (char-after) ?:) (insert ":")))))
13457 (char
13458 (setq org-time-was-given (equal (upcase char) char))
13459 (setq time (org-read-date (equal (upcase char) "U") t nil
13460 prompt))
13461 (org-insert-time-stamp time org-time-was-given
13462 (member char '("u" "U"))
13463 nil nil (list org-end-time-was-given)))
13465 (insert (org-completing-read
13466 (concat (if prompt prompt "Enter string")
13467 (if default (concat " [" default "]"))
13468 ": ")
13469 completions nil nil nil histvar default)))))
13470 (goto-char (point-min))
13471 (if (re-search-forward "%\\?" nil t)
13472 (replace-match "")
13473 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13474 (org-mode)
13475 (org-set-local 'org-finish-function 'remember-finalize))
13476 (when (save-excursion
13477 (goto-char (point-min))
13478 (re-search-forward "%!" nil t))
13479 (replace-match "")
13480 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13482 (defun org-remember-finish-immediately ()
13483 "File remember note immediately.
13484 This should be run in `post-command-hook' and will remove itself
13485 from that hook."
13486 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13487 (when org-finish-function
13488 (funcall org-finish-function)))
13491 ;;;###autoload
13492 (defun org-remember (&optional goto org-force-remember-template-char)
13493 "Call `remember'. If this is already a remember buffer, re-apply template.
13494 If there is an active region, make sure remember uses it as initial content
13495 of the remember buffer.
13497 When called interactively with a `C-u' prefix argument GOTO, don't remember
13498 anything, just go to the file/headline where the selected template usually
13499 stores its notes. With a double prefix arg `C-u C-u', go to the last
13500 note stored by remember.
13502 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13503 associated with a template in `org-remember-templates'."
13504 (interactive "P")
13505 (cond
13506 ((equal goto '(4)) (org-go-to-remember-target))
13507 ((equal goto '(16)) (org-remember-goto-last-stored))
13509 (if (memq org-finish-function '(remember-buffer remember-finalize))
13510 (progn
13511 (when (< (length org-remember-templates) 2)
13512 (error "No other template available"))
13513 (erase-buffer)
13514 (let ((annotation (plist-get org-store-link-plist :annotation))
13515 (initial (plist-get org-store-link-plist :initial)))
13516 (org-remember-apply-template))
13517 (message "Press C-c C-c to remember data"))
13518 (if (org-region-active-p)
13519 (remember (buffer-substring (point) (mark)))
13520 (call-interactively 'remember))))))
13522 (defun org-remember-goto-last-stored ()
13523 "Go to the location where the last remember note was stored."
13524 (interactive)
13525 (bookmark-jump "org-remember-last-stored")
13526 (message "This is the last note stored by remember"))
13528 (defun org-go-to-remember-target (&optional template-key)
13529 "Go to the target location of a remember template.
13530 The user is queried for the template."
13531 (interactive)
13532 (let* ((entry (org-select-remember-template template-key))
13533 (file (nth 1 entry))
13534 (heading (nth 2 entry))
13535 visiting)
13536 (unless (and file (stringp file) (string-match "\\S-" file))
13537 (setq file org-default-notes-file))
13538 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13539 (setq heading org-remember-default-headline))
13540 (setq visiting (org-find-base-buffer-visiting file))
13541 (if (not visiting) (find-file-noselect file))
13542 (switch-to-buffer (or visiting (get-file-buffer file)))
13543 (widen)
13544 (goto-char (point-min))
13545 (if (re-search-forward
13546 (concat "^\\*+[ \t]+" (regexp-quote heading)
13547 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13548 nil t)
13549 (goto-char (match-beginning 0))
13550 (error "Target headline not found: %s" heading))))
13552 (defvar org-note-abort nil) ; dynamically scoped
13554 ;;;###autoload
13555 (defun org-remember-handler ()
13556 "Store stuff from remember.el into an org file.
13557 First prompts for an org file. If the user just presses return, the value
13558 of `org-default-notes-file' is used.
13559 Then the command offers the headings tree of the selected file in order to
13560 file the text at a specific location.
13561 You can either immediately press RET to get the note appended to the
13562 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13563 find a better place. Then press RET or <left> or <right> in insert the note.
13565 Key Cursor position Note gets inserted
13566 -----------------------------------------------------------------------------
13567 RET buffer-start as level 1 heading at end of file
13568 RET on headline as sublevel of the heading at cursor
13569 RET no heading at cursor position, level taken from context.
13570 Or use prefix arg to specify level manually.
13571 <left> on headline as same level, before current heading
13572 <right> on headline as same level, after current heading
13574 So the fastest way to store the note is to press RET RET to append it to
13575 the default file. This way your current train of thought is not
13576 interrupted, in accordance with the principles of remember.el.
13577 You can also get the fast execution without prompting by using
13578 C-u C-c C-c to exit the remember buffer. See also the variable
13579 `org-remember-store-without-prompt'.
13581 Before being stored away, the function ensures that the text has a
13582 headline, i.e. a first line that starts with a \"*\". If not, a headline
13583 is constructed from the current date and some additional data.
13585 If the variable `org-adapt-indentation' is non-nil, the entire text is
13586 also indented so that it starts in the same column as the headline
13587 \(i.e. after the stars).
13589 See also the variable `org-reverse-note-order'."
13590 (goto-char (point-min))
13591 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13592 (replace-match ""))
13593 (goto-char (point-max))
13594 (beginning-of-line 1)
13595 (while (looking-at "[ \t]*$\\|##.*")
13596 (delete-region (1- (point)) (point-max))
13597 (beginning-of-line 1))
13598 (catch 'quit
13599 (if org-note-abort (throw 'quit nil))
13600 (let* ((txt (buffer-substring (point-min) (point-max)))
13601 (fastp (org-xor (equal current-prefix-arg '(4))
13602 org-remember-store-without-prompt))
13603 (file (cond
13604 (fastp org-default-notes-file)
13605 ((and org-remember-use-refile-when-interactive
13606 org-refile-targets)
13607 org-default-notes-file)
13608 (t (org-get-org-file))))
13609 (heading org-remember-default-headline)
13610 (visiting (and file (org-find-base-buffer-visiting file)))
13611 (org-startup-folded nil)
13612 (org-startup-align-all-tables nil)
13613 (org-goto-start-pos 1)
13614 spos exitcmd level indent reversed)
13615 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13616 (setq file (car org-remember-previous-location)
13617 heading (cdr org-remember-previous-location)
13618 fastp t))
13619 (setq current-prefix-arg nil)
13620 (if (string-match "[ \t\n]+\\'" txt)
13621 (setq txt (replace-match "" t t txt)))
13622 ;; Modify text so that it becomes a nice subtree which can be inserted
13623 ;; into an org tree.
13624 (let* ((lines (split-string txt "\n"))
13625 first)
13626 (setq first (car lines) lines (cdr lines))
13627 (if (string-match "^\\*+ " first)
13628 ;; Is already a headline
13629 (setq indent nil)
13630 ;; We need to add a headline: Use time and first buffer line
13631 (setq lines (cons first lines)
13632 first (concat "* " (current-time-string)
13633 " (" (remember-buffer-desc) ")")
13634 indent " "))
13635 (if (and org-adapt-indentation indent)
13636 (setq lines (mapcar
13637 (lambda (x)
13638 (if (string-match "\\S-" x)
13639 (concat indent x) x))
13640 lines)))
13641 (setq txt (concat first "\n"
13642 (mapconcat 'identity lines "\n"))))
13643 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13644 (setq txt (replace-match "\n\n" t t txt))
13645 (if (string-match "[ \t\n]*\\'" txt)
13646 (setq txt (replace-match "\n" t t txt))))
13647 ;; Put the modified text back into the remember buffer, for refile.
13648 (erase-buffer)
13649 (insert txt)
13650 (goto-char (point-min))
13651 (when (and org-remember-use-refile-when-interactive
13652 (not fastp))
13653 (org-refile nil (or visiting (find-file-noselect file)))
13654 (throw 'quit t))
13655 ;; Find the file
13656 (if (not visiting) (find-file-noselect file))
13657 (with-current-buffer (or visiting (get-file-buffer file))
13658 (unless (org-mode-p)
13659 (error "Target files for remember notes must be in Org-mode"))
13660 (save-excursion
13661 (save-restriction
13662 (widen)
13663 (and (goto-char (point-min))
13664 (not (re-search-forward "^\\* " nil t))
13665 (insert "\n* " (or heading "Notes") "\n"))
13666 (setq reversed (org-notes-order-reversed-p))
13668 ;; Find the default location
13669 (when (and heading (stringp heading) (string-match "\\S-" heading))
13670 (goto-char (point-min))
13671 (if (re-search-forward
13672 (concat "^\\*+[ \t]+" (regexp-quote heading)
13673 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13674 nil t)
13675 (setq org-goto-start-pos (match-beginning 0))
13676 (when fastp
13677 (goto-char (point-max))
13678 (unless (bolp) (newline))
13679 (insert "* " heading "\n")
13680 (setq org-goto-start-pos (point-at-bol 0)))))
13682 ;; Ask the User for a location
13683 (if fastp
13684 (setq spos org-goto-start-pos
13685 exitcmd 'return)
13686 (setq spos (org-get-location (current-buffer) org-remember-help)
13687 exitcmd (cdr spos)
13688 spos (car spos)))
13689 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13690 ; not handle this note
13691 (goto-char spos)
13692 (cond ((org-on-heading-p t)
13693 (org-back-to-heading t)
13694 (setq level (funcall outline-level))
13695 (cond
13696 ((eq exitcmd 'return)
13697 ;; sublevel of current
13698 (setq org-remember-previous-location
13699 (cons (abbreviate-file-name file)
13700 (org-get-heading 'notags)))
13701 (if reversed
13702 (outline-next-heading)
13703 (org-end-of-subtree t)
13704 (if (not (bolp))
13705 (if (looking-at "[ \t]*\n")
13706 (beginning-of-line 2)
13707 (end-of-line 1)
13708 (insert "\n"))))
13709 (bookmark-set "org-remember-last-stored")
13710 (org-paste-subtree (org-get-valid-level level 1) txt))
13711 ((eq exitcmd 'left)
13712 ;; before current
13713 (bookmark-set "org-remember-last-stored")
13714 (org-paste-subtree level txt))
13715 ((eq exitcmd 'right)
13716 ;; after current
13717 (org-end-of-subtree t)
13718 (bookmark-set "org-remember-last-stored")
13719 (org-paste-subtree level txt))
13720 (t (error "This should not happen"))))
13722 ((and (bobp) (not reversed))
13723 ;; Put it at the end, one level below level 1
13724 (save-restriction
13725 (widen)
13726 (goto-char (point-max))
13727 (if (not (bolp)) (newline))
13728 (bookmark-set "org-remember-last-stored")
13729 (org-paste-subtree (org-get-valid-level 1 1) txt)))
13731 ((and (bobp) reversed)
13732 ;; Put it at the start, as level 1
13733 (save-restriction
13734 (widen)
13735 (goto-char (point-min))
13736 (re-search-forward "^\\*+ " nil t)
13737 (beginning-of-line 1)
13738 (bookmark-set "org-remember-last-stored")
13739 (org-paste-subtree 1 txt)))
13741 ;; Put it right there, with automatic level determined by
13742 ;; org-paste-subtree or from prefix arg
13743 (bookmark-set "org-remember-last-stored")
13744 (org-paste-subtree
13745 (if (numberp current-prefix-arg) current-prefix-arg)
13746 txt)))
13747 (when remember-save-after-remembering
13748 (save-buffer)
13749 (if (not visiting) (kill-buffer (current-buffer)))))))))
13751 t) ;; return t to indicate that we took care of this note.
13753 (defun org-get-org-file ()
13754 "Read a filename, with default directory `org-directory'."
13755 (let ((default (or org-default-notes-file remember-data-file)))
13756 (read-file-name (format "File name [%s]: " default)
13757 (file-name-as-directory org-directory)
13758 default)))
13760 (defun org-notes-order-reversed-p ()
13761 "Check if the current file should receive notes in reversed order."
13762 (cond
13763 ((not org-reverse-note-order) nil)
13764 ((eq t org-reverse-note-order) t)
13765 ((not (listp org-reverse-note-order)) nil)
13766 (t (catch 'exit
13767 (let ((all org-reverse-note-order)
13768 entry)
13769 (while (setq entry (pop all))
13770 (if (string-match (car entry) buffer-file-name)
13771 (throw 'exit (cdr entry))))
13772 nil)))))
13774 ;;; Refiling
13776 (defvar org-refile-target-table nil
13777 "The list of refile targets, created by `org-refile'.")
13779 (defvar org-agenda-new-buffers nil
13780 "Buffers created to visit agenda files.")
13782 (defun org-get-refile-targets (&optional default-buffer)
13783 "Produce a table with refile targets."
13784 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13785 org-agenda-new-buffers targets txt re files f desc descre)
13786 (with-current-buffer (or default-buffer (current-buffer))
13787 (while (setq entry (pop entries))
13788 (setq files (car entry) desc (cdr entry))
13789 (cond
13790 ((null files) (setq files (list (current-buffer))))
13791 ((eq files 'org-agenda-files)
13792 (setq files (org-agenda-files 'unrestricted)))
13793 ((and (symbolp files) (fboundp files))
13794 (setq files (funcall files)))
13795 ((and (symbolp files) (boundp files))
13796 (setq files (symbol-value files))))
13797 (if (stringp files) (setq files (list files)))
13798 (cond
13799 ((eq (car desc) :tag)
13800 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13801 ((eq (car desc) :todo)
13802 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13803 ((eq (car desc) :regexp)
13804 (setq descre (cdr desc)))
13805 ((eq (car desc) :level)
13806 (setq descre (concat "^\\*\\{" (number-to-string
13807 (if org-odd-levels-only
13808 (1- (* 2 (cdr desc)))
13809 (cdr desc)))
13810 "\\}[ \t]")))
13811 ((eq (car desc) :maxlevel)
13812 (setq descre (concat "^\\*\\{1," (number-to-string
13813 (if org-odd-levels-only
13814 (1- (* 2 (cdr desc)))
13815 (cdr desc)))
13816 "\\}[ \t]")))
13817 (t (error "Bad refiling target description %s" desc)))
13818 (while (setq f (pop files))
13819 (save-excursion
13820 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13821 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13822 (save-excursion
13823 (save-restriction
13824 (widen)
13825 (goto-char (point-min))
13826 (while (re-search-forward descre nil t)
13827 (goto-char (point-at-bol))
13828 (when (looking-at org-complex-heading-regexp)
13829 (setq txt (match-string 4)
13830 re (concat "^" (regexp-quote
13831 (buffer-substring (match-beginning 1)
13832 (match-end 4)))))
13833 (if (match-end 5) (setq re (concat re "[ \t]+"
13834 (regexp-quote
13835 (match-string 5)))))
13836 (setq re (concat re "[ \t]*$"))
13837 (when org-refile-use-outline-path
13838 (setq txt (mapconcat 'identity
13839 (append
13840 (if (eq org-refile-use-outline-path 'file)
13841 (list (file-name-nondirectory
13842 (buffer-file-name (buffer-base-buffer))))
13843 (if (eq org-refile-use-outline-path 'full-file-path)
13844 (list (buffer-file-name (buffer-base-buffer)))))
13845 (org-get-outline-path)
13846 (list txt))
13847 "/")))
13848 (push (list txt f re (point)) targets))
13849 (goto-char (point-at-eol))))))))
13850 (org-release-buffers org-agenda-new-buffers)
13851 (nreverse targets))))
13853 (defun org-get-outline-path ()
13854 (let (rtn)
13855 (save-excursion
13856 (while (org-up-heading-safe)
13857 (when (looking-at org-complex-heading-regexp)
13858 (push (org-match-string-no-properties 4) rtn)))
13859 rtn)))
13861 (defvar org-refile-history nil
13862 "History for refiling operations.")
13864 (defun org-refile (&optional reversed-or-update default-buffer)
13865 "Move the entry at point to another heading.
13866 The list of target headings is compiled using the information in
13867 `org-refile-targets', which see. This list is created upon first use, and
13868 you can update it by calling this command with a double prefix (`C-u C-u').
13869 FIXME: Can we find a better way of updating?
13871 At the target location, the entry is filed as a subitem of the target heading.
13872 Depending on `org-reverse-note-order', the new subitem will either be the
13873 first of the last subitem. A single C-u prefix will toggle the value of this
13874 variable for the duration of the command."
13875 (interactive "P")
13876 (if (equal reversed-or-update '(16))
13877 (progn
13878 (setq org-refile-target-table (org-get-refile-targets default-buffer))
13879 (message "Refile targets updated (%d targets)"
13880 (length org-refile-target-table)))
13881 (when (or (not org-refile-target-table)
13882 (assq nil org-refile-targets))
13883 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
13884 (unless org-refile-target-table
13885 (error "No refile targets"))
13886 (let* ((cbuf (current-buffer))
13887 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13888 (fname (and filename (file-truename filename)))
13889 (tbl (mapcar
13890 (lambda (x)
13891 (if (not (equal fname (file-truename (nth 1 x))))
13892 (cons (concat (car x) " (" (file-name-nondirectory
13893 (nth 1 x)) ")")
13894 (cdr x))
13896 org-refile-target-table))
13897 (completion-ignore-case t)
13898 pos it nbuf file re level reversed)
13899 (when (setq it (completing-read "Refile to: " tbl
13900 nil t nil 'org-refile-history))
13901 (setq it (assoc it tbl)
13902 file (nth 1 it)
13903 re (nth 2 it))
13904 (org-copy-special)
13905 (save-excursion
13906 (set-buffer (setq nbuf (or (find-buffer-visiting file)
13907 (find-file-noselect file))))
13908 (setq reversed (org-notes-order-reversed-p))
13909 (if (equal reversed-or-update '(16)) (setq reversed (not reversed)))
13910 (save-excursion
13911 (save-restriction
13912 (widen)
13913 (goto-char (point-min))
13914 (unless (re-search-forward re nil t)
13915 (error "Cannot find target location - try again with `C-u' prefix."))
13916 (goto-char (match-beginning 0))
13917 (looking-at outline-regexp)
13918 (setq level (org-get-valid-level (funcall outline-level) 1))
13919 (goto-char (or (save-excursion
13920 (if reversed
13921 (outline-next-heading)
13922 (outline-get-next-sibling)))
13923 (point-max)))
13924 (org-paste-subtree level))))
13925 (org-cut-special)
13926 (message "Entry refiled to \"%s\"" (car it))))))
13928 ;;;; Dynamic blocks
13930 (defun org-find-dblock (name)
13931 "Find the first dynamic block with name NAME in the buffer.
13932 If not found, stay at current position and return nil."
13933 (let (pos)
13934 (save-excursion
13935 (goto-char (point-min))
13936 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13937 nil t)
13938 (match-beginning 0))))
13939 (if pos (goto-char pos))
13940 pos))
13942 (defconst org-dblock-start-re
13943 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13944 "Matches the startline of a dynamic block, with parameters.")
13946 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13947 "Matches the end of a dyhamic block.")
13949 (defun org-create-dblock (plist)
13950 "Create a dynamic block section, with parameters taken from PLIST.
13951 PLIST must containe a :name entry which is used as name of the block."
13952 (unless (bolp) (newline))
13953 (let ((name (plist-get plist :name)))
13954 (insert "#+BEGIN: " name)
13955 (while plist
13956 (if (eq (car plist) :name)
13957 (setq plist (cddr plist))
13958 (insert " " (prin1-to-string (pop plist)))))
13959 (insert "\n\n#+END:\n")
13960 (beginning-of-line -2)))
13962 (defun org-prepare-dblock ()
13963 "Prepare dynamic block for refresh.
13964 This empties the block, puts the cursor at the insert position and returns
13965 the property list including an extra property :name with the block name."
13966 (unless (looking-at org-dblock-start-re)
13967 (error "Not at a dynamic block"))
13968 (let* ((begdel (1+ (match-end 0)))
13969 (name (org-no-properties (match-string 1)))
13970 (params (append (list :name name)
13971 (read (concat "(" (match-string 3) ")")))))
13972 (unless (re-search-forward org-dblock-end-re nil t)
13973 (error "Dynamic block not terminated"))
13974 (delete-region begdel (match-beginning 0))
13975 (goto-char begdel)
13976 (open-line 1)
13977 params))
13979 (defun org-map-dblocks (&optional command)
13980 "Apply COMMAND to all dynamic blocks in the current buffer.
13981 If COMMAND is not given, use `org-update-dblock'."
13982 (let ((cmd (or command 'org-update-dblock))
13983 pos)
13984 (save-excursion
13985 (goto-char (point-min))
13986 (while (re-search-forward org-dblock-start-re nil t)
13987 (goto-char (setq pos (match-beginning 0)))
13988 (condition-case nil
13989 (funcall cmd)
13990 (error (message "Error during update of dynamic block")))
13991 (goto-char pos)
13992 (unless (re-search-forward org-dblock-end-re nil t)
13993 (error "Dynamic block not terminated"))))))
13995 (defun org-dblock-update (&optional arg)
13996 "User command for updating dynamic blocks.
13997 Update the dynamic block at point. With prefix ARG, update all dynamic
13998 blocks in the buffer."
13999 (interactive "P")
14000 (if arg
14001 (org-update-all-dblocks)
14002 (or (looking-at org-dblock-start-re)
14003 (org-beginning-of-dblock))
14004 (org-update-dblock)))
14006 (defun org-update-dblock ()
14007 "Update the dynamic block at point
14008 This means to empty the block, parse for parameters and then call
14009 the correct writing function."
14010 (save-window-excursion
14011 (let* ((pos (point))
14012 (line (org-current-line))
14013 (params (org-prepare-dblock))
14014 (name (plist-get params :name))
14015 (cmd (intern (concat "org-dblock-write:" name))))
14016 (message "Updating dynamic block `%s' at line %d..." name line)
14017 (funcall cmd params)
14018 (message "Updating dynamic block `%s' at line %d...done" name line)
14019 (goto-char pos))))
14021 (defun org-beginning-of-dblock ()
14022 "Find the beginning of the dynamic block at point.
14023 Error if there is no scuh block at point."
14024 (let ((pos (point))
14025 beg)
14026 (end-of-line 1)
14027 (if (and (re-search-backward org-dblock-start-re nil t)
14028 (setq beg (match-beginning 0))
14029 (re-search-forward org-dblock-end-re nil t)
14030 (> (match-end 0) pos))
14031 (goto-char beg)
14032 (goto-char pos)
14033 (error "Not in a dynamic block"))))
14035 (defun org-update-all-dblocks ()
14036 "Update all dynamic blocks in the buffer.
14037 This function can be used in a hook."
14038 (when (org-mode-p)
14039 (org-map-dblocks 'org-update-dblock)))
14042 ;;;; Completion
14044 (defconst org-additional-option-like-keywords
14045 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14046 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14047 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14049 (defun org-complete (&optional arg)
14050 "Perform completion on word at point.
14051 At the beginning of a headline, this completes TODO keywords as given in
14052 `org-todo-keywords'.
14053 If the current word is preceded by a backslash, completes the TeX symbols
14054 that are supported for HTML support.
14055 If the current word is preceded by \"#+\", completes special words for
14056 setting file options.
14057 In the line after \"#+STARTUP:, complete valid keywords.\"
14058 At all other locations, this simply calls the value of
14059 `org-completion-fallback-command'."
14060 (interactive "P")
14061 (org-without-partial-completion
14062 (catch 'exit
14063 (let* ((end (point))
14064 (beg1 (save-excursion
14065 (skip-chars-backward (org-re "[:alnum:]_@"))
14066 (point)))
14067 (beg (save-excursion
14068 (skip-chars-backward "a-zA-Z0-9_:$")
14069 (point)))
14070 (confirm (lambda (x) (stringp (car x))))
14071 (searchhead (equal (char-before beg) ?*))
14072 (tag (and (equal (char-before beg1) ?:)
14073 (equal (char-after (point-at-bol)) ?*)))
14074 (prop (and (equal (char-before beg1) ?:)
14075 (not (equal (char-after (point-at-bol)) ?*))))
14076 (texp (equal (char-before beg) ?\\))
14077 (link (equal (char-before beg) ?\[))
14078 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14079 beg)
14080 "#+"))
14081 (startup (string-match "^#\\+STARTUP:.*"
14082 (buffer-substring (point-at-bol) (point))))
14083 (completion-ignore-case opt)
14084 (type nil)
14085 (tbl nil)
14086 (table (cond
14087 (opt
14088 (setq type :opt)
14089 (append
14090 (mapcar
14091 (lambda (x)
14092 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14093 (cons (match-string 2 x) (match-string 1 x)))
14094 (org-split-string (org-get-current-options) "\n"))
14095 (mapcar 'list org-additional-option-like-keywords)))
14096 (startup
14097 (setq type :startup)
14098 org-startup-options)
14099 (link (append org-link-abbrev-alist-local
14100 org-link-abbrev-alist))
14101 (texp
14102 (setq type :tex)
14103 org-html-entities)
14104 ((string-match "\\`\\*+[ \t]+\\'"
14105 (buffer-substring (point-at-bol) beg))
14106 (setq type :todo)
14107 (mapcar 'list org-todo-keywords-1))
14108 (searchhead
14109 (setq type :searchhead)
14110 (save-excursion
14111 (goto-char (point-min))
14112 (while (re-search-forward org-todo-line-regexp nil t)
14113 (push (list
14114 (org-make-org-heading-search-string
14115 (match-string 3) t))
14116 tbl)))
14117 tbl)
14118 (tag (setq type :tag beg beg1)
14119 (or org-tag-alist (org-get-buffer-tags)))
14120 (prop (setq type :prop beg beg1)
14121 (mapcar 'list (org-buffer-property-keys)))
14122 (t (progn
14123 (call-interactively org-completion-fallback-command)
14124 (throw 'exit nil)))))
14125 (pattern (buffer-substring-no-properties beg end))
14126 (completion (try-completion pattern table confirm)))
14127 (cond ((eq completion t)
14128 (if (not (assoc (upcase pattern) table))
14129 (message "Already complete")
14130 (if (equal type :opt)
14131 (insert (substring (cdr (assoc (upcase pattern) table))
14132 (length pattern)))
14133 (if (memq type '(:tag :prop)) (insert ":")))))
14134 ((null completion)
14135 (message "Can't find completion for \"%s\"" pattern)
14136 (ding))
14137 ((not (string= pattern completion))
14138 (delete-region beg end)
14139 (if (string-match " +$" completion)
14140 (setq completion (replace-match "" t t completion)))
14141 (insert completion)
14142 (if (get-buffer-window "*Completions*")
14143 (delete-window (get-buffer-window "*Completions*")))
14144 (if (assoc completion table)
14145 (if (eq type :todo) (insert " ")
14146 (if (memq type '(:tag :prop)) (insert ":"))))
14147 (if (and (equal type :opt) (assoc completion table))
14148 (message "%s" (substitute-command-keys
14149 "Press \\[org-complete] again to insert example settings"))))
14151 (message "Making completion list...")
14152 (let ((list (sort (all-completions pattern table confirm)
14153 'string<)))
14154 (with-output-to-temp-buffer "*Completions*"
14155 (condition-case nil
14156 ;; Protection needed for XEmacs and emacs 21
14157 (display-completion-list list pattern)
14158 (error (display-completion-list list)))))
14159 (message "Making completion list...%s" "done")))))))
14161 ;;;; TODO, DEADLINE, Comments
14163 (defun org-toggle-comment ()
14164 "Change the COMMENT state of an entry."
14165 (interactive)
14166 (save-excursion
14167 (org-back-to-heading)
14168 (let (case-fold-search)
14169 (if (looking-at (concat outline-regexp
14170 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14171 (replace-match "" t t nil 1)
14172 (if (looking-at outline-regexp)
14173 (progn
14174 (goto-char (match-end 0))
14175 (insert org-comment-string " ")))))))
14177 (defvar org-last-todo-state-is-todo nil
14178 "This is non-nil when the last TODO state change led to a TODO state.
14179 If the last change removed the TODO tag or switched to DONE, then
14180 this is nil.")
14182 (defvar org-setting-tags nil) ; dynamically skiped
14184 ;; FIXME: better place
14185 (defun org-property-or-variable-value (var &optional inherit)
14186 "Check if there is a property fixing the value of VAR.
14187 If yes, return this value. If not, return the current value of the variable."
14188 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14189 (if (and prop (stringp prop) (string-match "\\S-" prop))
14190 (read prop)
14191 (symbol-value var))))
14193 (defun org-parse-local-options (string var)
14194 "Parse STRING for startup setting relevant for variable VAR."
14195 (let ((rtn (symbol-value var))
14196 e opts)
14197 (save-match-data
14198 (if (or (not string) (not (string-match "\\S-" string)))
14200 (setq opts (delq nil (mapcar (lambda (x)
14201 (setq e (assoc x org-startup-options))
14202 (if (eq (nth 1 e) var) e nil))
14203 (org-split-string string "[ \t]+"))))
14204 (if (not opts)
14206 (setq rtn nil)
14207 (while (setq e (pop opts))
14208 (if (not (nth 3 e))
14209 (setq rtn (nth 2 e))
14210 (if (not (listp rtn)) (setq rtn nil))
14211 (push (nth 2 e) rtn)))
14212 rtn)))))
14214 (defvar org-blocker-hook nil
14215 "Hook for functions that are allowed to block a state change.
14217 Each function gets as its single argument a property list, see
14218 `org-trigger-hook' for more information about this list.
14220 If any of the functions in this hook returns nil, the state change
14221 is blocked.")
14223 (defvar org-trigger-hook nil
14224 "Hook for functions that are triggered by a state change.
14226 Each function gets as its single argument a property list with at least
14227 the following elements:
14229 (:type type-of-change :position pos-at-entry-start
14230 :from old-state :to new-state)
14232 Depending on the type, more properties may be present.
14234 This mechanism is currently implemented for:
14236 TODO state changes
14237 ------------------
14238 :type todo-state-change
14239 :from previous state (keyword as a string), or nil
14240 :to new state (keyword as a string), or nil")
14243 (defun org-todo (&optional arg)
14244 "Change the TODO state of an item.
14245 The state of an item is given by a keyword at the start of the heading,
14246 like
14247 *** TODO Write paper
14248 *** DONE Call mom
14250 The different keywords are specified in the variable `org-todo-keywords'.
14251 By default the available states are \"TODO\" and \"DONE\".
14252 So for this example: when the item starts with TODO, it is changed to DONE.
14253 When it starts with DONE, the DONE is removed. And when neither TODO nor
14254 DONE are present, add TODO at the beginning of the heading.
14256 With C-u prefix arg, use completion to determine the new state.
14257 With numeric prefix arg, switch to that state.
14259 For calling through lisp, arg is also interpreted in the following way:
14260 'none -> empty state
14261 \"\"(empty string) -> switch to empty state
14262 'done -> switch to DONE
14263 'nextset -> switch to the next set of keywords
14264 'previousset -> switch to the previous set of keywords
14265 \"WAITING\" -> switch to the specified keyword, but only if it
14266 really is a member of `org-todo-keywords'."
14267 (interactive "P")
14268 (save-excursion
14269 (catch 'exit
14270 (org-back-to-heading)
14271 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14272 (or (looking-at (concat " +" org-todo-regexp " *"))
14273 (looking-at " *"))
14274 (let* ((match-data (match-data))
14275 (startpos (point-at-bol))
14276 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14277 (org-log-done (org-parse-local-options logging 'org-log-done))
14278 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
14279 (this (match-string 1))
14280 (hl-pos (match-beginning 0))
14281 (head (org-get-todo-sequence-head this))
14282 (ass (assoc head org-todo-kwd-alist))
14283 (interpret (nth 1 ass))
14284 (done-word (nth 3 ass))
14285 (final-done-word (nth 4 ass))
14286 (last-state (or this ""))
14287 (completion-ignore-case t)
14288 (member (member this org-todo-keywords-1))
14289 (tail (cdr member))
14290 (state (cond
14291 ((and org-todo-key-trigger
14292 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14293 (and (not arg) org-use-fast-todo-selection
14294 (not (eq org-use-fast-todo-selection 'prefix)))))
14295 ;; Use fast selection
14296 (org-fast-todo-selection))
14297 ((and (equal arg '(4))
14298 (or (not org-use-fast-todo-selection)
14299 (not org-todo-key-trigger)))
14300 ;; Read a state with completion
14301 (completing-read "State: " (mapcar (lambda(x) (list x))
14302 org-todo-keywords-1)
14303 nil t))
14304 ((eq arg 'right)
14305 (if this
14306 (if tail (car tail) nil)
14307 (car org-todo-keywords-1)))
14308 ((eq arg 'left)
14309 (if (equal member org-todo-keywords-1)
14311 (if this
14312 (nth (- (length org-todo-keywords-1) (length tail) 2)
14313 org-todo-keywords-1)
14314 (org-last org-todo-keywords-1))))
14315 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14316 (setq arg nil))) ; hack to fall back to cycling
14317 (arg
14318 ;; user or caller requests a specific state
14319 (cond
14320 ((equal arg "") nil)
14321 ((eq arg 'none) nil)
14322 ((eq arg 'done) (or done-word (car org-done-keywords)))
14323 ((eq arg 'nextset)
14324 (or (car (cdr (member head org-todo-heads)))
14325 (car org-todo-heads)))
14326 ((eq arg 'previousset)
14327 (let ((org-todo-heads (reverse org-todo-heads)))
14328 (or (car (cdr (member head org-todo-heads)))
14329 (car org-todo-heads))))
14330 ((car (member arg org-todo-keywords-1)))
14331 ((nth (1- (prefix-numeric-value arg))
14332 org-todo-keywords-1))))
14333 ((null member) (or head (car org-todo-keywords-1)))
14334 ((equal this final-done-word) nil) ;; -> make empty
14335 ((null tail) nil) ;; -> first entry
14336 ((eq interpret 'sequence)
14337 (car tail))
14338 ((memq interpret '(type priority))
14339 (if (eq this-command last-command)
14340 (car tail)
14341 (if (> (length tail) 0)
14342 (or done-word (car org-done-keywords))
14343 nil)))
14344 (t nil)))
14345 (next (if state (concat " " state " ") " "))
14346 (change-plist (list :type 'todo-state-change :from this :to state
14347 :position startpos))
14348 dostates)
14349 (when org-blocker-hook
14350 (unless (save-excursion
14351 (save-match-data
14352 (run-hook-with-args-until-failure
14353 'org-blocker-hook change-plist)))
14354 (if (interactive-p)
14355 (error "TODO state change from %s to %s blocked" this state)
14356 ;; fail silently
14357 (message "TODO state change from %s to %s blocked" this state)
14358 (throw 'exit nil))))
14359 (store-match-data match-data)
14360 (replace-match next t t)
14361 (unless (pos-visible-in-window-p hl-pos)
14362 (message "TODO state changed to %s" (org-trim next)))
14363 (unless head
14364 (setq head (org-get-todo-sequence-head state)
14365 ass (assoc head org-todo-kwd-alist)
14366 interpret (nth 1 ass)
14367 done-word (nth 3 ass)
14368 final-done-word (nth 4 ass)))
14369 (when (memq arg '(nextset previousset))
14370 (message "Keyword-Set %d/%d: %s"
14371 (- (length org-todo-sets) -1
14372 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14373 (length org-todo-sets)
14374 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14375 (setq org-last-todo-state-is-todo
14376 (not (member state org-done-keywords)))
14377 (when (and org-log-done (not (memq arg '(nextset previousset))))
14378 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14379 (or (not org-todo-log-states)
14380 (member state org-todo-log-states))))
14382 (cond
14383 ((and state (member state org-not-done-keywords)
14384 (not (member this org-not-done-keywords)))
14385 ;; This is now a todo state and was not one before
14386 ;; Remove any CLOSED timestamp, and possibly log the state change
14387 (org-add-planning-info nil nil 'closed)
14388 (and dostates (org-add-log-maybe 'state state 'findpos)))
14389 ((and state dostates)
14390 ;; This is a non-nil state, and we need to log it
14391 (org-add-log-maybe 'state state 'findpos))
14392 ((and (member state org-done-keywords)
14393 (not (member this org-done-keywords)))
14394 ;; It is now done, and it was not done before
14395 (org-add-planning-info 'closed (org-current-time))
14396 (org-add-log-maybe 'done state 'findpos))))
14397 ;; Fixup tag positioning
14398 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14399 (run-hooks 'org-after-todo-state-change-hook)
14400 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14401 (if (and arg (not (member state org-done-keywords)))
14402 (setq head (org-get-todo-sequence-head state)))
14403 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14404 ;; Fixup cursor location if close to the keyword
14405 (if (and (outline-on-heading-p)
14406 (not (bolp))
14407 (save-excursion (beginning-of-line 1)
14408 (looking-at org-todo-line-regexp))
14409 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14410 (progn
14411 (goto-char (or (match-end 2) (match-end 1)))
14412 (just-one-space)))
14413 (when org-trigger-hook
14414 (save-excursion
14415 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14417 (defun org-get-todo-sequence-head (kwd)
14418 "Return the head of the TODO sequence to which KWD belongs.
14419 If KWD is not set, check if there is a text property remembering the
14420 right sequence."
14421 (let (p)
14422 (cond
14423 ((not kwd)
14424 (or (get-text-property (point-at-bol) 'org-todo-head)
14425 (progn
14426 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14427 nil (point-at-eol)))
14428 (get-text-property p 'org-todo-head))))
14429 ((not (member kwd org-todo-keywords-1))
14430 (car org-todo-keywords-1))
14431 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14433 (defun org-fast-todo-selection ()
14434 "Fast TODO keyword selection with single keys.
14435 Returns the new TODO keyword, or nil if no state change should occur."
14436 (let* ((fulltable org-todo-key-alist)
14437 (done-keywords org-done-keywords) ;; needed for the faces.
14438 (maxlen (apply 'max (mapcar
14439 (lambda (x)
14440 (if (stringp (car x)) (string-width (car x)) 0))
14441 fulltable)))
14442 (expert nil)
14443 (fwidth (+ maxlen 3 1 3))
14444 (ncol (/ (- (window-width) 4) fwidth))
14445 tg cnt e c tbl
14446 groups ingroup)
14447 (save-window-excursion
14448 (if expert
14449 (set-buffer (get-buffer-create " *Org todo*"))
14450 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14451 (erase-buffer)
14452 (org-set-local 'org-done-keywords done-keywords)
14453 (setq tbl fulltable cnt 0)
14454 (while (setq e (pop tbl))
14455 (cond
14456 ((equal e '(:startgroup))
14457 (push '() groups) (setq ingroup t)
14458 (when (not (= cnt 0))
14459 (setq cnt 0)
14460 (insert "\n"))
14461 (insert "{ "))
14462 ((equal e '(:endgroup))
14463 (setq ingroup nil cnt 0)
14464 (insert "}\n"))
14466 (setq tg (car e) c (cdr e))
14467 (if ingroup (push tg (car groups)))
14468 (setq tg (org-add-props tg nil 'face
14469 (org-get-todo-face tg)))
14470 (if (and (= cnt 0) (not ingroup)) (insert " "))
14471 (insert "[" c "] " tg (make-string
14472 (- fwidth 4 (length tg)) ?\ ))
14473 (when (= (setq cnt (1+ cnt)) ncol)
14474 (insert "\n")
14475 (if ingroup (insert " "))
14476 (setq cnt 0)))))
14477 (insert "\n")
14478 (goto-char (point-min))
14479 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14480 (fit-window-to-buffer))
14481 (message "[a-z..]:Set [SPC]:clear")
14482 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14483 (cond
14484 ((or (= c ?\C-g)
14485 (and (= c ?q) (not (rassoc c fulltable))))
14486 (setq quit-flag t))
14487 ((= c ?\ ) nil)
14488 ((setq e (rassoc c fulltable) tg (car e))
14490 (t (setq quit-flag t))))))
14492 (defun org-get-repeat ()
14493 "Check if tere is a deadline/schedule with repeater in this entry."
14494 (save-match-data
14495 (save-excursion
14496 (org-back-to-heading t)
14497 (if (re-search-forward
14498 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14499 (match-string 1)))))
14501 (defvar org-last-changed-timestamp)
14502 (defvar org-log-post-message)
14503 (defun org-auto-repeat-maybe ()
14504 "Check if the current headline contains a repeated deadline/schedule.
14505 If yes, set TODO state back to what it was and change the base date
14506 of repeating deadline/scheduled time stamps to new date.
14507 This function should be run in the `org-after-todo-state-change-hook'."
14508 ;; last-state is dynamically scoped into this function
14509 (let* ((repeat (org-get-repeat))
14510 (aa (assoc last-state org-todo-kwd-alist))
14511 (interpret (nth 1 aa))
14512 (head (nth 2 aa))
14513 (done-word (nth 3 aa))
14514 (whata '(("d" . day) ("m" . month) ("y" . year)))
14515 (msg "Entry repeats: ")
14516 (org-log-done)
14517 re type n what ts)
14518 (when repeat
14519 (org-todo (if (eq interpret 'type) last-state head))
14520 (when (and org-log-repeat
14521 (not (memq 'org-add-log-note
14522 (default-value 'post-command-hook))))
14523 ;; Make sure a note is taken
14524 (let ((org-log-done '(done)))
14525 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14526 'findpos)))
14527 (org-back-to-heading t)
14528 (org-add-planning-info nil nil 'closed)
14529 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14530 org-deadline-time-regexp "\\)"))
14531 (while (re-search-forward
14532 re (save-excursion (outline-next-heading) (point)) t)
14533 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
14534 ts (match-string (if (match-end 2) 2 4)))
14535 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14536 (setq n (string-to-number (match-string 1 ts))
14537 what (match-string 2 ts))
14538 (if (equal what "w") (setq n (* n 7) what "d"))
14539 (org-timestamp-change n (cdr (assoc what whata))))
14540 (setq msg (concat msg type org-last-changed-timestamp " ")))
14541 (setq org-log-post-message msg)
14542 (message "%s" msg))))
14544 (defun org-show-todo-tree (arg)
14545 "Make a compact tree which shows all headlines marked with TODO.
14546 The tree will show the lines where the regexp matches, and all higher
14547 headlines above the match.
14548 With \\[universal-argument] prefix, also show the DONE entries.
14549 With a numeric prefix N, construct a sparse tree for the Nth element
14550 of `org-todo-keywords-1'."
14551 (interactive "P")
14552 (let ((case-fold-search nil)
14553 (kwd-re
14554 (cond ((null arg) org-not-done-regexp)
14555 ((equal arg '(4))
14556 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14557 (mapcar 'list org-todo-keywords-1))))
14558 (concat "\\("
14559 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14560 "\\)\\>")))
14561 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14562 (regexp-quote (nth (1- (prefix-numeric-value arg))
14563 org-todo-keywords-1)))
14564 (t (error "Invalid prefix argument: %s" arg)))))
14565 (message "%d TODO entries found"
14566 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14568 (defun org-deadline (&optional remove)
14569 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14570 With argument REMOVE, remove any deadline from the item."
14571 (interactive "P")
14572 (if remove
14573 (progn
14574 (org-add-planning-info nil nil 'deadline)
14575 (message "Item no longer has a deadline."))
14576 (org-add-planning-info 'deadline nil 'closed)))
14578 (defun org-schedule (&optional remove)
14579 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14580 With argument REMOVE, remove any scheduling date from the item."
14581 (interactive "P")
14582 (if remove
14583 (progn
14584 (org-add-planning-info nil nil 'scheduled)
14585 (message "Item is no longer scheduled."))
14586 (org-add-planning-info 'scheduled nil 'closed)))
14588 (defun org-add-planning-info (what &optional time &rest remove)
14589 "Insert new timestamp with keyword in the line directly after the headline.
14590 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14591 If non is given, the user is prompted for a date.
14592 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14593 be removed."
14594 (interactive)
14595 (let (org-time-was-given org-end-time-was-given)
14596 (when what (setq time (or time (org-read-date nil 'to-time))))
14597 (when (and org-insert-labeled-timestamps-at-point
14598 (member what '(scheduled deadline)))
14599 (insert
14600 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14601 (org-insert-time-stamp time org-time-was-given
14602 nil nil nil (list org-end-time-was-given))
14603 (setq what nil))
14604 (save-excursion
14605 (save-restriction
14606 (let (col list elt ts buffer-invisibility-spec)
14607 (org-back-to-heading t)
14608 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14609 (goto-char (match-end 1))
14610 (setq col (current-column))
14611 (goto-char (match-end 0))
14612 (if (eobp) (insert "\n") (forward-char 1))
14613 (if (and (not (looking-at outline-regexp))
14614 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14615 "[^\r\n]*"))
14616 (not (equal (match-string 1) org-clock-string)))
14617 (narrow-to-region (match-beginning 0) (match-end 0))
14618 (insert-before-markers "\n")
14619 (backward-char 1)
14620 (narrow-to-region (point) (point))
14621 (indent-to-column col))
14622 ;; Check if we have to remove something.
14623 (setq list (cons what remove))
14624 (while list
14625 (setq elt (pop list))
14626 (goto-char (point-min))
14627 (when (or (and (eq elt 'scheduled)
14628 (re-search-forward org-scheduled-time-regexp nil t))
14629 (and (eq elt 'deadline)
14630 (re-search-forward org-deadline-time-regexp nil t))
14631 (and (eq elt 'closed)
14632 (re-search-forward org-closed-time-regexp nil t)))
14633 (replace-match "")
14634 (if (looking-at "--+<[^>]+>") (replace-match ""))
14635 (if (looking-at " +") (replace-match ""))))
14636 (goto-char (point-max))
14637 (when what
14638 (insert
14639 (if (not (equal (char-before) ?\ )) " " "")
14640 (cond ((eq what 'scheduled) org-scheduled-string)
14641 ((eq what 'deadline) org-deadline-string)
14642 ((eq what 'closed) org-closed-string))
14643 " ")
14644 (setq ts (org-insert-time-stamp
14645 time
14646 (or org-time-was-given
14647 (and (eq what 'closed) org-log-done-with-time))
14648 (eq what 'closed)
14649 nil nil (list org-end-time-was-given)))
14650 (end-of-line 1))
14651 (goto-char (point-min))
14652 (widen)
14653 (if (looking-at "[ \t]+\r?\n")
14654 (replace-match ""))
14655 ts)))))
14657 (defvar org-log-note-marker (make-marker))
14658 (defvar org-log-note-purpose nil)
14659 (defvar org-log-note-state nil)
14660 (defvar org-log-note-window-configuration nil)
14661 (defvar org-log-note-return-to (make-marker))
14662 (defvar org-log-post-message nil
14663 "Message to be displayed after a log note has been stored.
14664 The auto-repeater uses this.")
14666 (defun org-add-log-maybe (&optional purpose state findpos)
14667 "Set up the post command hook to take a note."
14668 (save-excursion
14669 (when (and (listp org-log-done)
14670 (memq purpose org-log-done))
14671 (when findpos
14672 (org-back-to-heading t)
14673 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14674 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14675 "[^\r\n]*\\)?"))
14676 (goto-char (match-end 0))
14677 (unless org-log-states-order-reversed
14678 (and (= (char-after) ?\n) (forward-char 1))
14679 (org-skip-over-state-notes)
14680 (skip-chars-backward " \t\n\r")))
14681 (move-marker org-log-note-marker (point))
14682 (setq org-log-note-purpose purpose)
14683 (setq org-log-note-state state)
14684 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14686 (defun org-skip-over-state-notes ()
14687 "Skip past the list of State notes in an entry."
14688 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14689 (while (looking-at "[ \t]*- State")
14690 (condition-case nil
14691 (org-next-item)
14692 (error (org-end-of-item)))))
14694 (defun org-add-log-note (&optional purpose)
14695 "Pop up a window for taking a note, and add this note later at point."
14696 (remove-hook 'post-command-hook 'org-add-log-note)
14697 (setq org-log-note-window-configuration (current-window-configuration))
14698 (delete-other-windows)
14699 (move-marker org-log-note-return-to (point))
14700 (switch-to-buffer (marker-buffer org-log-note-marker))
14701 (goto-char org-log-note-marker)
14702 (org-switch-to-buffer-other-window "*Org Note*")
14703 (erase-buffer)
14704 (let ((org-inhibit-startup t)) (org-mode))
14705 (insert (format "# Insert note for %s.
14706 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14707 (cond
14708 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14709 ((eq org-log-note-purpose 'done) "closed todo item")
14710 ((eq org-log-note-purpose 'state)
14711 (format "state change to \"%s\"" org-log-note-state))
14712 (t (error "This should not happen")))))
14713 (org-set-local 'org-finish-function 'org-store-log-note))
14715 (defun org-store-log-note ()
14716 "Finish taking a log note, and insert it to where it belongs."
14717 (let ((txt (buffer-string))
14718 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14719 lines ind)
14720 (kill-buffer (current-buffer))
14721 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14722 (setq txt (replace-match "" t t txt)))
14723 (if (string-match "\\s-+\\'" txt)
14724 (setq txt (replace-match "" t t txt)))
14725 (setq lines (org-split-string txt "\n"))
14726 (when (and note (string-match "\\S-" note))
14727 (setq note
14728 (org-replace-escapes
14729 note
14730 (list (cons "%u" (user-login-name))
14731 (cons "%U" user-full-name)
14732 (cons "%t" (format-time-string
14733 (org-time-stamp-format 'long 'inactive)
14734 (current-time)))
14735 (cons "%s" (if org-log-note-state
14736 (concat "\"" org-log-note-state "\"")
14737 "")))))
14738 (if lines (setq note (concat note " \\\\")))
14739 (push note lines))
14740 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14741 (when lines
14742 (save-excursion
14743 (set-buffer (marker-buffer org-log-note-marker))
14744 (save-excursion
14745 (goto-char org-log-note-marker)
14746 (move-marker org-log-note-marker nil)
14747 (end-of-line 1)
14748 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14749 (indent-relative nil)
14750 (insert "- " (pop lines))
14751 (org-indent-line-function)
14752 (beginning-of-line 1)
14753 (looking-at "[ \t]*")
14754 (setq ind (concat (match-string 0) " "))
14755 (end-of-line 1)
14756 (while lines (insert "\n" ind (pop lines)))))))
14757 (set-window-configuration org-log-note-window-configuration)
14758 (with-current-buffer (marker-buffer org-log-note-return-to)
14759 (goto-char org-log-note-return-to))
14760 (move-marker org-log-note-return-to nil)
14761 (and org-log-post-message (message "%s" org-log-post-message)))
14763 ;; FIXME: what else would be useful?
14764 ;; - priority
14765 ;; - date
14767 (defun org-sparse-tree (&optional arg)
14768 "Create a sparse tree, prompt for the details.
14769 This command can create sparse trees. You first need to select the type
14770 of match used to create the tree:
14772 t Show entries with a specific TODO keyword.
14773 T Show entries selected by a tags match.
14774 p Enter a property name and its value (both with completion on existing
14775 names/values) and show entries with that property.
14776 r Show entries matching a regular expression
14777 d Show deadlines due within `org-deadline-warning-days'."
14778 (interactive "P")
14779 (let (ans kwd value)
14780 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14781 (setq ans (read-char-exclusive))
14782 (cond
14783 ((equal ans ?d)
14784 (call-interactively 'org-check-deadlines))
14785 ((equal ans ?b)
14786 (call-interactively 'org-check-before-date))
14787 ((equal ans ?t)
14788 (org-show-todo-tree '(4)))
14789 ((equal ans ?T)
14790 (call-interactively 'org-tags-sparse-tree))
14791 ((member ans '(?p ?P))
14792 (setq kwd (completing-read "Property: "
14793 (mapcar 'list (org-buffer-property-keys))))
14794 (setq value (completing-read "Value: "
14795 (mapcar 'list (org-property-values kwd))))
14796 (unless (string-match "\\`{.*}\\'" value)
14797 (setq value (concat "\"" value "\"")))
14798 (org-tags-sparse-tree arg (concat kwd "=" value)))
14799 ((member ans '(?r ?R ?/))
14800 (call-interactively 'org-occur))
14801 (t (error "No such sparse tree command \"%c\"" ans)))))
14803 (defvar org-occur-highlights nil)
14804 (make-variable-buffer-local 'org-occur-highlights)
14806 (defun org-occur (regexp &optional keep-previous callback)
14807 "Make a compact tree which shows all matches of REGEXP.
14808 The tree will show the lines where the regexp matches, and all higher
14809 headlines above the match. It will also show the heading after the match,
14810 to make sure editing the matching entry is easy.
14811 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14812 call to `org-occur' will be kept, to allow stacking of calls to this
14813 command.
14814 If CALLBACK is non-nil, it is a function which is called to confirm
14815 that the match should indeed be shown."
14816 (interactive "sRegexp: \nP")
14817 (or keep-previous (org-remove-occur-highlights nil nil t))
14818 (let ((cnt 0))
14819 (save-excursion
14820 (goto-char (point-min))
14821 (if (or (not keep-previous) ; do not want to keep
14822 (not org-occur-highlights)) ; no previous matches
14823 ;; hide everything
14824 (org-overview))
14825 (while (re-search-forward regexp nil t)
14826 (when (or (not callback)
14827 (save-match-data (funcall callback)))
14828 (setq cnt (1+ cnt))
14829 (when org-highlight-sparse-tree-matches
14830 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14831 (org-show-context 'occur-tree))))
14832 (when org-remove-highlights-with-change
14833 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14834 nil 'local))
14835 (unless org-sparse-tree-open-archived-trees
14836 (org-hide-archived-subtrees (point-min) (point-max)))
14837 (run-hooks 'org-occur-hook)
14838 (if (interactive-p)
14839 (message "%d match(es) for regexp %s" cnt regexp))
14840 cnt))
14842 (defun org-show-context (&optional key)
14843 "Make sure point and context and visible.
14844 How much context is shown depends upon the variables
14845 `org-show-hierarchy-above', `org-show-following-heading'. and
14846 `org-show-siblings'."
14847 (let ((heading-p (org-on-heading-p t))
14848 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14849 (following-p (org-get-alist-option org-show-following-heading key))
14850 (entry-p (org-get-alist-option org-show-entry-below key))
14851 (siblings-p (org-get-alist-option org-show-siblings key)))
14852 (catch 'exit
14853 ;; Show heading or entry text
14854 (if (and heading-p (not entry-p))
14855 (org-flag-heading nil) ; only show the heading
14856 (and (or entry-p (org-invisible-p) (org-invisible-p2))
14857 (org-show-hidden-entry))) ; show entire entry
14858 (when following-p
14859 ;; Show next sibling, or heading below text
14860 (save-excursion
14861 (and (if heading-p (org-goto-sibling) (outline-next-heading))
14862 (org-flag-heading nil))))
14863 (when siblings-p (org-show-siblings))
14864 (when hierarchy-p
14865 ;; show all higher headings, possibly with siblings
14866 (save-excursion
14867 (while (and (condition-case nil
14868 (progn (org-up-heading-all 1) t)
14869 (error nil))
14870 (not (bobp)))
14871 (org-flag-heading nil)
14872 (when siblings-p (org-show-siblings))))))))
14874 (defun org-reveal (&optional siblings)
14875 "Show current entry, hierarchy above it, and the following headline.
14876 This can be used to show a consistent set of context around locations
14877 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14878 not t for the search context.
14880 With optional argument SIBLINGS, on each level of the hierarchy all
14881 siblings are shown. This repairs the tree structure to what it would
14882 look like when opened with hierarchical calls to `org-cycle'."
14883 (interactive "P")
14884 (let ((org-show-hierarchy-above t)
14885 (org-show-following-heading t)
14886 (org-show-siblings (if siblings t org-show-siblings)))
14887 (org-show-context nil)))
14889 (defun org-highlight-new-match (beg end)
14890 "Highlight from BEG to END and mark the highlight is an occur headline."
14891 (let ((ov (org-make-overlay beg end)))
14892 (org-overlay-put ov 'face 'secondary-selection)
14893 (push ov org-occur-highlights)))
14895 (defun org-remove-occur-highlights (&optional beg end noremove)
14896 "Remove the occur highlights from the buffer.
14897 BEG and END are ignored. If NOREMOVE is nil, remove this function
14898 from the `before-change-functions' in the current buffer."
14899 (interactive)
14900 (unless org-inhibit-highlight-removal
14901 (mapc 'org-delete-overlay org-occur-highlights)
14902 (setq org-occur-highlights nil)
14903 (unless noremove
14904 (remove-hook 'before-change-functions
14905 'org-remove-occur-highlights 'local))))
14907 ;;;; Priorities
14909 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14910 "Regular expression matching the priority indicator.")
14912 (defvar org-remove-priority-next-time nil)
14914 (defun org-priority-up ()
14915 "Increase the priority of the current item."
14916 (interactive)
14917 (org-priority 'up))
14919 (defun org-priority-down ()
14920 "Decrease the priority of the current item."
14921 (interactive)
14922 (org-priority 'down))
14924 (defun org-priority (&optional action)
14925 "Change the priority of an item by ARG.
14926 ACTION can be `set', `up', `down', or a character."
14927 (interactive)
14928 (setq action (or action 'set))
14929 (let (current new news have remove)
14930 (save-excursion
14931 (org-back-to-heading)
14932 (if (looking-at org-priority-regexp)
14933 (setq current (string-to-char (match-string 2))
14934 have t)
14935 (setq current org-default-priority))
14936 (cond
14937 ((or (eq action 'set) (integerp action))
14938 (if (integerp action)
14939 (setq new action)
14940 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14941 (setq new (read-char-exclusive)))
14942 (if (and (= (upcase org-highest-priority) org-highest-priority)
14943 (= (upcase org-lowest-priority) org-lowest-priority))
14944 (setq new (upcase new)))
14945 (cond ((equal new ?\ ) (setq remove t))
14946 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14947 (error "Priority must be between `%c' and `%c'"
14948 org-highest-priority org-lowest-priority))))
14949 ((eq action 'up)
14950 (if (and (not have) (eq last-command this-command))
14951 (setq new org-lowest-priority)
14952 (setq new (if (and org-priority-start-cycle-with-default (not have))
14953 org-default-priority (1- current)))))
14954 ((eq action 'down)
14955 (if (and (not have) (eq last-command this-command))
14956 (setq new org-highest-priority)
14957 (setq new (if (and org-priority-start-cycle-with-default (not have))
14958 org-default-priority (1+ current)))))
14959 (t (error "Invalid action")))
14960 (if (or (< (upcase new) org-highest-priority)
14961 (> (upcase new) org-lowest-priority))
14962 (setq remove t))
14963 (setq news (format "%c" new))
14964 (if have
14965 (if remove
14966 (replace-match "" t t nil 1)
14967 (replace-match news t t nil 2))
14968 (if remove
14969 (error "No priority cookie found in line")
14970 (looking-at org-todo-line-regexp)
14971 (if (match-end 2)
14972 (progn
14973 (goto-char (match-end 2))
14974 (insert " [#" news "]"))
14975 (goto-char (match-beginning 3))
14976 (insert "[#" news "] ")))))
14977 (org-preserve-lc (org-set-tags nil 'align))
14978 (if remove
14979 (message "Priority removed")
14980 (message "Priority of current item set to %s" news))))
14983 (defun org-get-priority (s)
14984 "Find priority cookie and return priority."
14985 (save-match-data
14986 (if (not (string-match org-priority-regexp s))
14987 (* 1000 (- org-lowest-priority org-default-priority))
14988 (* 1000 (- org-lowest-priority
14989 (string-to-char (match-string 2 s)))))))
14991 ;;;; Tags
14993 (defun org-scan-tags (action matcher &optional todo-only)
14994 "Scan headline tags with inheritance and produce output ACTION.
14995 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
14996 evaluated, testing if a given set of tags qualifies a headline for
14997 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
14998 are included in the output."
14999 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15000 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15001 (org-re
15002 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15003 (props (list 'face nil
15004 'done-face 'org-done
15005 'undone-face nil
15006 'mouse-face 'highlight
15007 'org-not-done-regexp org-not-done-regexp
15008 'org-todo-regexp org-todo-regexp
15009 'keymap org-agenda-keymap
15010 'help-echo
15011 (format "mouse-2 or RET jump to org file %s"
15012 (abbreviate-file-name
15013 (or (buffer-file-name (buffer-base-buffer))
15014 (buffer-name (buffer-base-buffer)))))))
15015 (case-fold-search nil)
15016 lspos
15017 tags tags-list tags-alist (llast 0) rtn level category i txt
15018 todo marker entry priority)
15019 (save-excursion
15020 (goto-char (point-min))
15021 (when (eq action 'sparse-tree)
15022 (org-overview)
15023 (org-remove-occur-highlights))
15024 (while (re-search-forward re nil t)
15025 (catch :skip
15026 (setq todo (if (match-end 1) (match-string 2))
15027 tags (if (match-end 4) (match-string 4)))
15028 (goto-char (setq lspos (1+ (match-beginning 0))))
15029 (setq level (org-reduced-level (funcall outline-level))
15030 category (org-get-category))
15031 (setq i llast llast level)
15032 ;; remove tag lists from same and sublevels
15033 (while (>= i level)
15034 (when (setq entry (assoc i tags-alist))
15035 (setq tags-alist (delete entry tags-alist)))
15036 (setq i (1- i)))
15037 ;; add the nex tags
15038 (when tags
15039 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15040 tags-alist
15041 (cons (cons level tags) tags-alist)))
15042 ;; compile tags for current headline
15043 (setq tags-list
15044 (if org-use-tag-inheritance
15045 (apply 'append (mapcar 'cdr tags-alist))
15046 tags))
15047 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15048 (eval matcher)
15049 (or (not org-agenda-skip-archived-trees)
15050 (not (member org-archive-tag tags-list))))
15051 (and (eq action 'agenda) (org-agenda-skip))
15052 ;; list this headline
15054 (if (eq action 'sparse-tree)
15055 (progn
15056 (and org-highlight-sparse-tree-matches
15057 (org-get-heading) (match-end 0)
15058 (org-highlight-new-match
15059 (match-beginning 0) (match-beginning 1)))
15060 (org-show-context 'tags-tree))
15061 (setq txt (org-format-agenda-item
15063 (concat
15064 (if org-tags-match-list-sublevels
15065 (make-string (1- level) ?.) "")
15066 (org-get-heading))
15067 category tags-list)
15068 priority (org-get-priority txt))
15069 (goto-char lspos)
15070 (setq marker (org-agenda-new-marker))
15071 (org-add-props txt props
15072 'org-marker marker 'org-hd-marker marker 'org-category category
15073 'priority priority 'type "tagsmatch")
15074 (push txt rtn))
15075 ;; if we are to skip sublevels, jump to end of subtree
15076 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15077 (when (and (eq action 'sparse-tree)
15078 (not org-sparse-tree-open-archived-trees))
15079 (org-hide-archived-subtrees (point-min) (point-max)))
15080 (nreverse rtn)))
15082 (defvar todo-only) ;; dynamically scoped
15084 (defun org-tags-sparse-tree (&optional todo-only match)
15085 "Create a sparse tree according to tags string MATCH.
15086 MATCH can contain positive and negative selection of tags, like
15087 \"+WORK+URGENT-WITHBOSS\".
15088 If optional argument TODO_ONLY is non-nil, only select lines that are
15089 also TODO lines."
15090 (interactive "P")
15091 (org-prepare-agenda-buffers (list (current-buffer)))
15092 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15094 (defvar org-cached-props nil)
15095 (defun org-cached-entry-get (pom property)
15096 (if (or (eq t org-use-property-inheritance)
15097 (member property org-use-property-inheritance))
15098 ;; Caching is not possible, check it directly
15099 (org-entry-get pom property 'inherit)
15100 ;; Get all properties, so that we can do complicated checks easily
15101 (cdr (assoc property (or org-cached-props
15102 (setq org-cached-props
15103 (org-entry-properties pom)))))))
15105 (defun org-global-tags-completion-table (&optional files)
15106 "Return the list of all tags in all agenda buffer/files."
15107 (save-excursion
15108 (org-uniquify
15109 (apply 'append
15110 (mapcar
15111 (lambda (file)
15112 (set-buffer (find-file-noselect file))
15113 (org-get-buffer-tags))
15114 (if (and files (car files))
15115 files
15116 (org-agenda-files)))))))
15118 (defun org-make-tags-matcher (match)
15119 "Create the TAGS//TODO matcher form for the selection string MATCH."
15120 ;; todo-only is scoped dynamically into this function, and the function
15121 ;; may change it it the matcher asksk for it.
15122 (unless match
15123 ;; Get a new match request, with completion
15124 (let ((org-last-tags-completion-table
15125 (org-global-tags-completion-table)))
15126 (setq match (completing-read
15127 "Match: " 'org-tags-completion-function nil nil nil
15128 'org-tags-history))))
15130 ;; Parse the string and create a lisp form
15131 (let ((match0 match)
15132 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
15133 minus tag mm
15134 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15135 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15136 (if (string-match "/+" match)
15137 ;; match contains also a todo-matching request
15138 (progn
15139 (setq tagsmatch (substring match 0 (match-beginning 0))
15140 todomatch (substring match (match-end 0)))
15141 (if (string-match "^!" todomatch)
15142 (setq todo-only t todomatch (substring todomatch 1)))
15143 (if (string-match "^\\s-*$" todomatch)
15144 (setq todomatch nil)))
15145 ;; only matching tags
15146 (setq tagsmatch match todomatch nil))
15148 ;; Make the tags matcher
15149 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15150 (setq tagsmatcher t)
15151 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15152 (while (setq term (pop orterms))
15153 (while (and (equal (substring term -1) "\\") orterms)
15154 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15155 (while (string-match re term)
15156 (setq minus (and (match-end 1)
15157 (equal (match-string 1 term) "-"))
15158 tag (match-string 2 term)
15159 re-p (equal (string-to-char tag) ?{)
15160 level-p (match-end 3)
15161 prop-p (match-end 4)
15162 mm (cond
15163 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15164 (level-p `(= level ,(string-to-number
15165 (match-string 3 term))))
15166 (prop-p
15167 (setq pn (match-string 4 term)
15168 pv (match-string 5 term)
15169 cat-p (equal pn "CATEGORY")
15170 re-p (equal (string-to-char pv) ?{)
15171 pv (substring pv 1 -1))
15172 (if (equal pn "CATEGORY")
15173 (setq gv '(get-text-property (point) 'org-category))
15174 (setq gv `(org-cached-entry-get nil ,pn)))
15175 (if re-p
15176 `(string-match ,pv (or ,gv ""))
15177 `(equal ,pv ,gv)))
15178 (t `(member ,(downcase tag) tags-list)))
15179 mm (if minus (list 'not mm) mm)
15180 term (substring term (match-end 0)))
15181 (push mm tagsmatcher))
15182 (push (if (> (length tagsmatcher) 1)
15183 (cons 'and tagsmatcher)
15184 (car tagsmatcher))
15185 orlist)
15186 (setq tagsmatcher nil))
15187 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15188 (setq tagsmatcher
15189 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15191 ;; Make the todo matcher
15192 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15193 (setq todomatcher t)
15194 (setq orterms (org-split-string todomatch "|") orlist nil)
15195 (while (setq term (pop orterms))
15196 (while (string-match re term)
15197 (setq minus (and (match-end 1)
15198 (equal (match-string 1 term) "-"))
15199 kwd (match-string 2 term)
15200 re-p (equal (string-to-char kwd) ?{)
15201 term (substring term (match-end 0))
15202 mm (if re-p
15203 `(string-match ,(substring kwd 1 -1) todo)
15204 (list 'equal 'todo kwd))
15205 mm (if minus (list 'not mm) mm))
15206 (push mm todomatcher))
15207 (push (if (> (length todomatcher) 1)
15208 (cons 'and todomatcher)
15209 (car todomatcher))
15210 orlist)
15211 (setq todomatcher nil))
15212 (setq todomatcher (if (> (length orlist) 1)
15213 (cons 'or orlist) (car orlist))))
15215 ;; Return the string and lisp forms of the matcher
15216 (setq matcher (if todomatcher
15217 (list 'and tagsmatcher todomatcher)
15218 tagsmatcher))
15219 (cons match0 matcher)))
15221 (defun org-match-any-p (re list)
15222 "Does re match any element of list?"
15223 (setq list (mapcar (lambda (x) (string-match re x)) list))
15224 (delq nil list))
15226 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15227 (defvar org-tags-overlay (org-make-overlay 1 1))
15228 (org-detach-overlay org-tags-overlay)
15230 (defun org-align-tags-here (to-col)
15231 ;; Assumes that this is a headline
15232 (let ((pos (point)) (col (current-column)) tags)
15233 (beginning-of-line 1)
15234 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15235 (< pos (match-beginning 2)))
15236 (progn
15237 (setq tags (match-string 2))
15238 (goto-char (match-beginning 1))
15239 (insert " ")
15240 (delete-region (point) (1+ (match-end 0)))
15241 (backward-char 1)
15242 (move-to-column
15243 (max (1+ (current-column))
15244 (1+ col)
15245 (if (> to-col 0)
15246 to-col
15247 (- (abs to-col) (length tags))))
15249 (insert tags)
15250 (move-to-column (min (current-column) col) t))
15251 (goto-char pos))))
15253 (defun org-set-tags (&optional arg just-align)
15254 "Set the tags for the current headline.
15255 With prefix ARG, realign all tags in headings in the current buffer."
15256 (interactive "P")
15257 (let* ((re (concat "^" outline-regexp))
15258 (current (org-get-tags-string))
15259 (col (current-column))
15260 (org-setting-tags t)
15261 table current-tags inherited-tags ; computed below when needed
15262 tags p0 c0 c1 rpl)
15263 (if arg
15264 (save-excursion
15265 (goto-char (point-min))
15266 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15267 (while (re-search-forward re nil t)
15268 (org-set-tags nil t)
15269 (end-of-line 1)))
15270 (message "All tags realigned to column %d" org-tags-column))
15271 (if just-align
15272 (setq tags current)
15273 ;; Get a new set of tags from the user
15274 (save-excursion
15275 (setq table (or org-tag-alist (org-get-buffer-tags))
15276 org-last-tags-completion-table table
15277 current-tags (org-split-string current ":")
15278 inherited-tags (nreverse
15279 (nthcdr (length current-tags)
15280 (nreverse (org-get-tags-at))))
15281 tags
15282 (if (or (eq t org-use-fast-tag-selection)
15283 (and org-use-fast-tag-selection
15284 (delq nil (mapcar 'cdr table))))
15285 (org-fast-tag-selection
15286 current-tags inherited-tags table
15287 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15288 (let ((org-add-colon-after-tag-completion t))
15289 (org-trim
15290 (org-without-partial-completion
15291 (completing-read "Tags: " 'org-tags-completion-function
15292 nil nil current 'org-tags-history)))))))
15293 (while (string-match "[-+&]+" tags)
15294 ;; No boolean logic, just a list
15295 (setq tags (replace-match ":" t t tags))))
15297 (if (string-match "\\`[\t ]*\\'" tags)
15298 (setq tags "")
15299 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15300 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15302 ;; Insert new tags at the correct column
15303 (beginning-of-line 1)
15304 (cond
15305 ((and (equal current "") (equal tags "")))
15306 ((re-search-forward
15307 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15308 (point-at-eol) t)
15309 (if (equal tags "")
15310 (setq rpl "")
15311 (goto-char (match-beginning 0))
15312 (setq c0 (current-column) p0 (point)
15313 c1 (max (1+ c0) (if (> org-tags-column 0)
15314 org-tags-column
15315 (- (- org-tags-column) (length tags))))
15316 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15317 (replace-match rpl t t)
15318 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
15319 tags)
15320 (t (error "Tags alignment failed")))
15321 (move-to-column col)
15322 (unless just-align
15323 (run-hooks 'org-after-tags-change-hook)))))
15325 (defun org-change-tag-in-region (beg end tag off)
15326 "Add or remove TAG for each entry in the region.
15327 This works in the agenda, and also in an org-mode buffer."
15328 (interactive
15329 (list (region-beginning) (region-end)
15330 (let ((org-last-tags-completion-table
15331 (if (org-mode-p)
15332 (org-get-buffer-tags)
15333 (org-global-tags-completion-table))))
15334 (completing-read
15335 "Tag: " 'org-tags-completion-function nil nil nil
15336 'org-tags-history))
15337 (progn
15338 (message "[s]et or [r]emove? ")
15339 (equal (read-char-exclusive) ?r))))
15340 (if (fboundp 'deactivate-mark) (deactivate-mark))
15341 (let ((agendap (equal major-mode 'org-agenda-mode))
15342 l1 l2 m buf pos newhead (cnt 0))
15343 (goto-char end)
15344 (setq l2 (1- (org-current-line)))
15345 (goto-char beg)
15346 (setq l1 (org-current-line))
15347 (loop for l from l1 to l2 do
15348 (goto-line l)
15349 (setq m (get-text-property (point) 'org-hd-marker))
15350 (when (or (and (org-mode-p) (org-on-heading-p))
15351 (and agendap m))
15352 (setq buf (if agendap (marker-buffer m) (current-buffer))
15353 pos (if agendap m (point)))
15354 (with-current-buffer buf
15355 (save-excursion
15356 (save-restriction
15357 (goto-char pos)
15358 (setq cnt (1+ cnt))
15359 (org-toggle-tag tag (if off 'off 'on))
15360 (setq newhead (org-get-heading)))))
15361 (and agendap (org-agenda-change-all-lines newhead m))))
15362 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15364 (defun org-tags-completion-function (string predicate &optional flag)
15365 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15366 (confirm (lambda (x) (stringp (car x)))))
15367 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15368 (setq s1 (match-string 1 string)
15369 s2 (match-string 2 string))
15370 (setq s1 "" s2 string))
15371 (cond
15372 ((eq flag nil)
15373 ;; try completion
15374 (setq rtn (try-completion s2 ctable confirm))
15375 (if (stringp rtn)
15376 (setq rtn
15377 (concat s1 s2 (substring rtn (length s2))
15378 (if (and org-add-colon-after-tag-completion
15379 (assoc rtn ctable))
15380 ":" ""))))
15381 rtn)
15382 ((eq flag t)
15383 ;; all-completions
15384 (all-completions s2 ctable confirm)
15386 ((eq flag 'lambda)
15387 ;; exact match?
15388 (assoc s2 ctable)))
15391 (defun org-fast-tag-insert (kwd tags face &optional end)
15392 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15393 (insert (format "%-12s" (concat kwd ":"))
15394 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15395 (or end "")))
15397 (defun org-fast-tag-show-exit (flag)
15398 (save-excursion
15399 (goto-line 3)
15400 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15401 (replace-match ""))
15402 (when flag
15403 (end-of-line 1)
15404 (move-to-column (- (window-width) 19) t)
15405 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15407 (defun org-set-current-tags-overlay (current prefix)
15408 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15409 (if (featurep 'xemacs)
15410 (org-overlay-display org-tags-overlay (concat prefix s)
15411 'secondary-selection)
15412 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15413 (org-overlay-display org-tags-overlay (concat prefix s)))))
15415 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15416 "Fast tag selection with single keys.
15417 CURRENT is the current list of tags in the headline, INHERITED is the
15418 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15419 possibly with grouping information. TODO-TABLE is a similar table with
15420 TODO keywords, should these have keys assigned to them.
15421 If the keys are nil, a-z are automatically assigned.
15422 Returns the new tags string, or nil to not change the current settings."
15423 (let* ((fulltable (append table todo-table))
15424 (maxlen (apply 'max (mapcar
15425 (lambda (x)
15426 (if (stringp (car x)) (string-width (car x)) 0))
15427 fulltable)))
15428 (buf (current-buffer))
15429 (expert (eq org-fast-tag-selection-single-key 'expert))
15430 (buffer-tags nil)
15431 (fwidth (+ maxlen 3 1 3))
15432 (ncol (/ (- (window-width) 4) fwidth))
15433 (i-face 'org-done)
15434 (c-face 'org-todo)
15435 tg cnt e c char c1 c2 ntable tbl rtn
15436 ov-start ov-end ov-prefix
15437 (exit-after-next org-fast-tag-selection-single-key)
15438 (done-keywords org-done-keywords)
15439 groups ingroup)
15440 (save-excursion
15441 (beginning-of-line 1)
15442 (if (looking-at
15443 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15444 (setq ov-start (match-beginning 1)
15445 ov-end (match-end 1)
15446 ov-prefix "")
15447 (setq ov-start (1- (point-at-eol))
15448 ov-end (1+ ov-start))
15449 (skip-chars-forward "^\n\r")
15450 (setq ov-prefix
15451 (concat
15452 (buffer-substring (1- (point)) (point))
15453 (if (> (current-column) org-tags-column)
15455 (make-string (- org-tags-column (current-column)) ?\ ))))))
15456 (org-move-overlay org-tags-overlay ov-start ov-end)
15457 (save-window-excursion
15458 (if expert
15459 (set-buffer (get-buffer-create " *Org tags*"))
15460 (delete-other-windows)
15461 (split-window-vertically)
15462 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15463 (erase-buffer)
15464 (org-set-local 'org-done-keywords done-keywords)
15465 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15466 (org-fast-tag-insert "Current" current c-face "\n\n")
15467 (org-fast-tag-show-exit exit-after-next)
15468 (org-set-current-tags-overlay current ov-prefix)
15469 (setq tbl fulltable char ?a cnt 0)
15470 (while (setq e (pop tbl))
15471 (cond
15472 ((equal e '(:startgroup))
15473 (push '() groups) (setq ingroup t)
15474 (when (not (= cnt 0))
15475 (setq cnt 0)
15476 (insert "\n"))
15477 (insert "{ "))
15478 ((equal e '(:endgroup))
15479 (setq ingroup nil cnt 0)
15480 (insert "}\n"))
15482 (setq tg (car e) c2 nil)
15483 (if (cdr e)
15484 (setq c (cdr e))
15485 ;; automatically assign a character.
15486 (setq c1 (string-to-char
15487 (downcase (substring
15488 tg (if (= (string-to-char tg) ?@) 1 0)))))
15489 (if (or (rassoc c1 ntable) (rassoc c1 table))
15490 (while (or (rassoc char ntable) (rassoc char table))
15491 (setq char (1+ char)))
15492 (setq c2 c1))
15493 (setq c (or c2 char)))
15494 (if ingroup (push tg (car groups)))
15495 (setq tg (org-add-props tg nil 'face
15496 (cond
15497 ((not (assoc tg table))
15498 (org-get-todo-face tg))
15499 ((member tg current) c-face)
15500 ((member tg inherited) i-face)
15501 (t nil))))
15502 (if (and (= cnt 0) (not ingroup)) (insert " "))
15503 (insert "[" c "] " tg (make-string
15504 (- fwidth 4 (length tg)) ?\ ))
15505 (push (cons tg c) ntable)
15506 (when (= (setq cnt (1+ cnt)) ncol)
15507 (insert "\n")
15508 (if ingroup (insert " "))
15509 (setq cnt 0)))))
15510 (setq ntable (nreverse ntable))
15511 (insert "\n")
15512 (goto-char (point-min))
15513 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15514 (fit-window-to-buffer))
15515 (setq rtn
15516 (catch 'exit
15517 (while t
15518 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15519 (if groups " [!] no groups" " [!]groups")
15520 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15521 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15522 (cond
15523 ((= c ?\r) (throw 'exit t))
15524 ((= c ?!)
15525 (setq groups (not groups))
15526 (goto-char (point-min))
15527 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15528 ((= c ?\C-c)
15529 (if (not expert)
15530 (org-fast-tag-show-exit
15531 (setq exit-after-next (not exit-after-next)))
15532 (setq expert nil)
15533 (delete-other-windows)
15534 (split-window-vertically)
15535 (org-switch-to-buffer-other-window " *Org tags*")
15536 (and (fboundp 'fit-window-to-buffer)
15537 (fit-window-to-buffer))))
15538 ((or (= c ?\C-g)
15539 (and (= c ?q) (not (rassoc c ntable))))
15540 (org-detach-overlay org-tags-overlay)
15541 (setq quit-flag t))
15542 ((= c ?\ )
15543 (setq current nil)
15544 (if exit-after-next (setq exit-after-next 'now)))
15545 ((= c ?\t)
15546 (condition-case nil
15547 (setq tg (completing-read
15548 "Tag: "
15549 (or buffer-tags
15550 (with-current-buffer buf
15551 (org-get-buffer-tags)))))
15552 (quit (setq tg "")))
15553 (when (string-match "\\S-" tg)
15554 (add-to-list 'buffer-tags (list tg))
15555 (if (member tg current)
15556 (setq current (delete tg current))
15557 (push tg current)))
15558 (if exit-after-next (setq exit-after-next 'now)))
15559 ((setq e (rassoc c todo-table) tg (car e))
15560 (with-current-buffer buf
15561 (save-excursion (org-todo tg)))
15562 (if exit-after-next (setq exit-after-next 'now)))
15563 ((setq e (rassoc c ntable) tg (car e))
15564 (if (member tg current)
15565 (setq current (delete tg current))
15566 (loop for g in groups do
15567 (if (member tg g)
15568 (mapc (lambda (x)
15569 (setq current (delete x current)))
15570 g)))
15571 (push tg current))
15572 (if exit-after-next (setq exit-after-next 'now))))
15574 ;; Create a sorted list
15575 (setq current
15576 (sort current
15577 (lambda (a b)
15578 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15579 (if (eq exit-after-next 'now) (throw 'exit t))
15580 (goto-char (point-min))
15581 (beginning-of-line 2)
15582 (delete-region (point) (point-at-eol))
15583 (org-fast-tag-insert "Current" current c-face)
15584 (org-set-current-tags-overlay current ov-prefix)
15585 (while (re-search-forward
15586 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15587 (setq tg (match-string 1))
15588 (add-text-properties
15589 (match-beginning 1) (match-end 1)
15590 (list 'face
15591 (cond
15592 ((member tg current) c-face)
15593 ((member tg inherited) i-face)
15594 (t (get-text-property (match-beginning 1) 'face))))))
15595 (goto-char (point-min)))))
15596 (org-detach-overlay org-tags-overlay)
15597 (if rtn
15598 (mapconcat 'identity current ":")
15599 nil))))
15601 (defun org-get-tags-string ()
15602 "Get the TAGS string in the current headline."
15603 (unless (org-on-heading-p t)
15604 (error "Not on a heading"))
15605 (save-excursion
15606 (beginning-of-line 1)
15607 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15608 (org-match-string-no-properties 1)
15609 "")))
15611 (defun org-get-tags ()
15612 "Get the list of tags specified in the current headline."
15613 (org-split-string (org-get-tags-string) ":"))
15615 (defun org-get-buffer-tags ()
15616 "Get a table of all tags used in the buffer, for completion."
15617 (let (tags)
15618 (save-excursion
15619 (goto-char (point-min))
15620 (while (re-search-forward
15621 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15622 (when (equal (char-after (point-at-bol 0)) ?*)
15623 (mapc (lambda (x) (add-to-list 'tags x))
15624 (org-split-string (org-match-string-no-properties 1) ":")))))
15625 (mapcar 'list tags)))
15628 ;;;; Properties
15630 ;;; Setting and retrieving properties
15632 (defconst org-special-properties
15633 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15634 "TIMESTAMP" "TIMESTAMP_IA")
15635 "The special properties valid in Org-mode.
15637 These are properties that are not defined in the property drawer,
15638 but in some other way.")
15640 (defconst org-default-properties
15641 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15642 "LOCATION" "LOGGING" "COLUMNS")
15643 "Some properties that are used by Org-mode for various purposes.
15644 Being in this list makes sure that they are offered for completion.")
15646 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15647 "Regular expression matching the first line of a property drawer.")
15649 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15650 "Regular expression matching the first line of a property drawer.")
15652 (defun org-property-action ()
15653 "Do an action on properties."
15654 (interactive)
15655 (let (c)
15656 (org-at-property-p)
15657 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15658 (setq c (read-char-exclusive))
15659 (cond
15660 ((equal c ?s)
15661 (call-interactively 'org-set-property))
15662 ((equal c ?d)
15663 (call-interactively 'org-delete-property))
15664 ((equal c ?D)
15665 (call-interactively 'org-delete-property-globally))
15666 ((equal c ?c)
15667 (call-interactively 'org-compute-property-at-point))
15668 (t (error "No such property action %c" c)))))
15670 (defun org-at-property-p ()
15671 "Is the cursor in a property line?"
15672 ;; FIXME: Does not check if we are actually in the drawer.
15673 ;; FIXME: also returns true on any drawers.....
15674 ;; This is used by C-c C-c for property action.
15675 (save-excursion
15676 (beginning-of-line 1)
15677 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15679 (defmacro org-with-point-at (pom &rest body)
15680 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15681 (declare (indent 1) (debug t))
15682 `(save-excursion
15683 (if (markerp pom) (set-buffer (marker-buffer pom)))
15684 (save-excursion
15685 (goto-char (or pom (point)))
15686 ,@body)))
15688 (defun org-get-property-block (&optional beg end force)
15689 "Return the (beg . end) range of the body of the property drawer.
15690 BEG and END can be beginning and end of subtree, if not given
15691 they will be found.
15692 If the drawer does not exist and FORCE is non-nil, create the drawer."
15693 (catch 'exit
15694 (save-excursion
15695 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15696 (end (or end (progn (outline-next-heading) (point)))))
15697 (goto-char beg)
15698 (if (re-search-forward org-property-start-re end t)
15699 (setq beg (1+ (match-end 0)))
15700 (if force
15701 (save-excursion
15702 (org-insert-property-drawer)
15703 (setq end (progn (outline-next-heading) (point))))
15704 (throw 'exit nil))
15705 (goto-char beg)
15706 (if (re-search-forward org-property-start-re end t)
15707 (setq beg (1+ (match-end 0)))))
15708 (if (re-search-forward org-property-end-re end t)
15709 (setq end (match-beginning 0))
15710 (or force (throw 'exit nil))
15711 (goto-char beg)
15712 (setq end beg)
15713 (org-indent-line-function)
15714 (insert ":END:\n"))
15715 (cons beg end)))))
15717 (defun org-entry-properties (&optional pom which)
15718 "Get all properties of the entry at point-or-marker POM.
15719 This includes the TODO keyword, the tags, time strings for deadline,
15720 scheduled, and clocking, and any additional properties defined in the
15721 entry. The return value is an alist, keys may occur multiple times
15722 if the property key was used several times.
15723 POM may also be nil, in which case the current entry is used.
15724 If WHICH is nil or `all', get all properties. If WHICH is
15725 `special' or `standard', only get that subclass."
15726 (setq which (or which 'all))
15727 (org-with-point-at pom
15728 (let ((clockstr (substring org-clock-string 0 -1))
15729 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15730 beg end range props sum-props key value string clocksum)
15731 (save-excursion
15732 (when (condition-case nil (org-back-to-heading t) (error nil))
15733 (setq beg (point))
15734 (setq sum-props (get-text-property (point) 'org-summaries))
15735 (setq clocksum (get-text-property (point) :org-clock-minutes))
15736 (outline-next-heading)
15737 (setq end (point))
15738 (when (memq which '(all special))
15739 ;; Get the special properties, like TODO and tags
15740 (goto-char beg)
15741 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15742 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15743 (when (looking-at org-priority-regexp)
15744 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15745 (when (and (setq value (org-get-tags-string))
15746 (string-match "\\S-" value))
15747 (push (cons "TAGS" value) props))
15748 (when (setq value (org-get-tags-at))
15749 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15750 props))
15751 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15752 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15753 string (if (equal key clockstr)
15754 (org-no-properties
15755 (org-trim
15756 (buffer-substring
15757 (match-beginning 3) (goto-char (point-at-eol)))))
15758 (substring (org-match-string-no-properties 3) 1 -1)))
15759 (unless key
15760 (if (= (char-after (match-beginning 3)) ?\[)
15761 (setq key "TIMESTAMP_IA")
15762 (setq key "TIMESTAMP")))
15763 (when (or (equal key clockstr) (not (assoc key props)))
15764 (push (cons key string) props)))
15768 (when (memq which '(all standard))
15769 ;; Get the standard properties, like :PORP: ...
15770 (setq range (org-get-property-block beg end))
15771 (when range
15772 (goto-char (car range))
15773 (while (re-search-forward
15774 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15775 (cdr range) t)
15776 (setq key (org-match-string-no-properties 1)
15777 value (org-trim (or (org-match-string-no-properties 2) "")))
15778 (unless (member key excluded)
15779 (push (cons key (or value "")) props)))))
15780 (if clocksum
15781 (push (cons "CLOCKSUM"
15782 (org-column-number-to-string (/ (float clocksum) 60.)
15783 'add_times))
15784 props))
15785 (append sum-props (nreverse props)))))))
15787 (defun org-entry-get (pom property &optional inherit)
15788 "Get value of PROPERTY for entry at point-or-marker POM.
15789 If INHERIT is non-nil and the entry does not have the property,
15790 then also check higher levels of the hierarchy.
15791 If the property is present but empty, the return value is the empty string.
15792 If the property is not present at all, nil is returned."
15793 (org-with-point-at pom
15794 (if inherit
15795 (org-entry-get-with-inheritance property)
15796 (if (member property org-special-properties)
15797 ;; We need a special property. Use brute force, get all properties.
15798 (cdr (assoc property (org-entry-properties nil 'special)))
15799 (let ((range (org-get-property-block)))
15800 (if (and range
15801 (goto-char (car range))
15802 (re-search-forward
15803 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15804 (cdr range) t))
15805 ;; Found the property, return it.
15806 (if (match-end 1)
15807 (org-match-string-no-properties 1)
15808 "")))))))
15810 (defun org-entry-delete (pom property)
15811 "Delete the property PROPERTY from entry at point-or-marker POM."
15812 (org-with-point-at pom
15813 (if (member property org-special-properties)
15814 nil ; cannot delete these properties.
15815 (let ((range (org-get-property-block)))
15816 (if (and range
15817 (goto-char (car range))
15818 (re-search-forward
15819 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
15820 (cdr range) t))
15821 (progn
15822 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15824 nil)))))
15826 ;; Multi-values properties are properties that contain multiple values
15827 ;; These values are assumed to be single words, separated by whitespace.
15828 (defun org-entry-add-to-multivalued-property (pom property value)
15829 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15830 (let* ((old (org-entry-get pom property))
15831 (values (and old (org-split-string old "[ \t]"))))
15832 (unless (member value values)
15833 (setq values (cons value values))
15834 (org-entry-put pom property
15835 (mapconcat 'identity values " ")))))
15837 (defun org-entry-remove-from-multivalued-property (pom property value)
15838 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15839 (let* ((old (org-entry-get pom property))
15840 (values (and old (org-split-string old "[ \t]"))))
15841 (when (member value values)
15842 (setq values (delete value values))
15843 (org-entry-put pom property
15844 (mapconcat 'identity values " ")))))
15846 (defun org-entry-member-in-multivalued-property (pom property value)
15847 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15848 (let* ((old (org-entry-get pom property))
15849 (values (and old (org-split-string old "[ \t]"))))
15850 (member value values)))
15852 (defvar org-entry-property-inherited-from (make-marker))
15854 (defun org-entry-get-with-inheritance (property)
15855 "Get entry property, and search higher levels if not present."
15856 (let (tmp)
15857 (save-excursion
15858 (save-restriction
15859 (widen)
15860 (catch 'ex
15861 (while t
15862 (when (setq tmp (org-entry-get nil property))
15863 (org-back-to-heading t)
15864 (move-marker org-entry-property-inherited-from (point))
15865 (throw 'ex tmp))
15866 (or (org-up-heading-safe) (throw 'ex nil)))))
15867 (or tmp (cdr (assoc property org-local-properties))
15868 (cdr (assoc property org-global-properties))))))
15870 (defun org-entry-put (pom property value)
15871 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15872 (org-with-point-at pom
15873 (org-back-to-heading t)
15874 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15875 range)
15876 (cond
15877 ((equal property "TODO")
15878 (when (and (stringp value) (string-match "\\S-" value)
15879 (not (member value org-todo-keywords-1)))
15880 (error "\"%s\" is not a valid TODO state" value))
15881 (if (or (not value)
15882 (not (string-match "\\S-" value)))
15883 (setq value 'none))
15884 (org-todo value)
15885 (org-set-tags nil 'align))
15886 ((equal property "PRIORITY")
15887 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15888 (string-to-char value) ?\ ))
15889 (org-set-tags nil 'align))
15890 ((equal property "SCHEDULED")
15891 (if (re-search-forward org-scheduled-time-regexp end t)
15892 (cond
15893 ((eq value 'earlier) (org-timestamp-change -1 'day))
15894 ((eq value 'later) (org-timestamp-change 1 'day))
15895 (t (call-interactively 'org-schedule)))
15896 (call-interactively 'org-schedule)))
15897 ((equal property "DEADLINE")
15898 (if (re-search-forward org-deadline-time-regexp end t)
15899 (cond
15900 ((eq value 'earlier) (org-timestamp-change -1 'day))
15901 ((eq value 'later) (org-timestamp-change 1 'day))
15902 (t (call-interactively 'org-deadline)))
15903 (call-interactively 'org-deadline)))
15904 ((member property org-special-properties)
15905 (error "The %s property can not yet be set with `org-entry-put'"
15906 property))
15907 (t ; a non-special property
15908 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15909 (setq range (org-get-property-block beg end 'force))
15910 (goto-char (car range))
15911 (if (re-search-forward
15912 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15913 (progn
15914 (delete-region (match-beginning 1) (match-end 1))
15915 (goto-char (match-beginning 1)))
15916 (goto-char (cdr range))
15917 (insert "\n")
15918 (backward-char 1)
15919 (org-indent-line-function)
15920 (insert ":" property ":"))
15921 (and value (insert " " value))
15922 (org-indent-line-function)))))))
15924 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15925 "Get all property keys in the current buffer.
15926 With INCLUDE-SPECIALS, also list the special properties that relect things
15927 like tags and TODO state.
15928 With INCLUDE-DEFAULTS, also include properties that has special meaning
15929 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15930 (let (rtn range)
15931 (save-excursion
15932 (save-restriction
15933 (widen)
15934 (goto-char (point-min))
15935 (while (re-search-forward org-property-start-re nil t)
15936 (setq range (org-get-property-block))
15937 (goto-char (car range))
15938 (while (re-search-forward
15939 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15940 (cdr range) t)
15941 (add-to-list 'rtn (org-match-string-no-properties 1)))
15942 (outline-next-heading))))
15944 (when include-specials
15945 (setq rtn (append org-special-properties rtn)))
15947 (when include-defaults
15948 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15950 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15952 (defun org-property-values (key)
15953 "Return a list of all values of property KEY."
15954 (save-excursion
15955 (save-restriction
15956 (widen)
15957 (goto-char (point-min))
15958 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15959 values)
15960 (while (re-search-forward re nil t)
15961 (add-to-list 'values (org-trim (match-string 1))))
15962 (delete "" values)))))
15964 (defun org-insert-property-drawer ()
15965 "Insert a property drawer into the current entry."
15966 (interactive)
15967 (org-back-to-heading t)
15968 (looking-at outline-regexp)
15969 (let ((indent (- (match-end 0)(match-beginning 0)))
15970 (beg (point))
15971 (re (concat "^[ \t]*" org-keyword-time-regexp))
15972 end hiddenp)
15973 (outline-next-heading)
15974 (setq end (point))
15975 (goto-char beg)
15976 (while (re-search-forward re end t))
15977 (setq hiddenp (org-invisible-p))
15978 (end-of-line 1)
15979 (and (equal (char-after) ?\n) (forward-char 1))
15980 (org-skip-over-state-notes)
15981 (skip-chars-backward " \t\n\r")
15982 (if (eq (char-before) ?*) (forward-char 1))
15983 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15984 (beginning-of-line 0)
15985 (indent-to-column indent)
15986 (beginning-of-line 2)
15987 (indent-to-column indent)
15988 (beginning-of-line 0)
15989 (if hiddenp
15990 (save-excursion
15991 (org-back-to-heading t)
15992 (hide-entry))
15993 (org-flag-drawer t))))
15995 (defun org-set-property (property value)
15996 "In the current entry, set PROPERTY to VALUE.
15997 When called interactively, this will prompt for a property name, offering
15998 completion on existing and default properties. And then it will prompt
15999 for a value, offering competion either on allowed values (via an inherited
16000 xxx_ALL property) or on existing values in other instances of this property
16001 in the current file."
16002 (interactive
16003 (let* ((prop (completing-read
16004 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
16005 (cur (org-entry-get nil prop))
16006 (allowed (org-property-get-allowed-values nil prop 'table))
16007 (existing (mapcar 'list (org-property-values prop)))
16008 (val (if allowed
16009 (completing-read "Value: " allowed nil 'req-match)
16010 (completing-read
16011 (concat "Value" (if (and cur (string-match "\\S-" cur))
16012 (concat "[" cur "]") "")
16013 ": ")
16014 existing nil nil "" nil cur))))
16015 (list prop (if (equal val "") cur val))))
16016 (unless (equal (org-entry-get nil property) value)
16017 (org-entry-put nil property value)))
16019 (defun org-delete-property (property)
16020 "In the current entry, delete PROPERTY."
16021 (interactive
16022 (let* ((prop (completing-read
16023 "Property: " (org-entry-properties nil 'standard))))
16024 (list prop)))
16025 (message "Property %s %s" property
16026 (if (org-entry-delete nil property)
16027 "deleted"
16028 "was not present in the entry")))
16030 (defun org-delete-property-globally (property)
16031 "Remove PROPERTY globally, from all entries."
16032 (interactive
16033 (let* ((prop (completing-read
16034 "Globally remove property: "
16035 (mapcar 'list (org-buffer-property-keys)))))
16036 (list prop)))
16037 (save-excursion
16038 (save-restriction
16039 (widen)
16040 (goto-char (point-min))
16041 (let ((cnt 0))
16042 (while (re-search-forward
16043 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16044 nil t)
16045 (setq cnt (1+ cnt))
16046 (replace-match ""))
16047 (message "Property \"%s\" removed from %d entries" property cnt)))))
16049 (defvar org-columns-current-fmt-compiled) ; defined below
16051 (defun org-compute-property-at-point ()
16052 "Compute the property at point.
16053 This looks for an enclosing column format, extracts the operator and
16054 then applies it to the proerty in the column format's scope."
16055 (interactive)
16056 (unless (org-at-property-p)
16057 (error "Not at a property"))
16058 (let ((prop (org-match-string-no-properties 2)))
16059 (org-columns-get-format-and-top-level)
16060 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16061 (error "No operator defined for property %s" prop))
16062 (org-columns-compute prop)))
16064 (defun org-property-get-allowed-values (pom property &optional table)
16065 "Get allowed values for the property PROPERTY.
16066 When TABLE is non-nil, return an alist that can directly be used for
16067 completion."
16068 (let (vals)
16069 (cond
16070 ((equal property "TODO")
16071 (setq vals (org-with-point-at pom
16072 (append org-todo-keywords-1 '("")))))
16073 ((equal property "PRIORITY")
16074 (let ((n org-lowest-priority))
16075 (while (>= n org-highest-priority)
16076 (push (char-to-string n) vals)
16077 (setq n (1- n)))))
16078 ((member property org-special-properties))
16080 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16082 (when (and vals (string-match "\\S-" vals))
16083 (setq vals (car (read-from-string (concat "(" vals ")"))))
16084 (setq vals (mapcar (lambda (x)
16085 (cond ((stringp x) x)
16086 ((numberp x) (number-to-string x))
16087 ((symbolp x) (symbol-name x))
16088 (t "???")))
16089 vals)))))
16090 (if table (mapcar 'list vals) vals)))
16092 (defun org-property-previous-allowed-value (&optional previous)
16093 "Switch to the next allowed value for this property."
16094 (interactive)
16095 (org-property-next-allowed-value t))
16097 (defun org-property-next-allowed-value (&optional previous)
16098 "Switch to the next allowed value for this property."
16099 (interactive)
16100 (unless (org-at-property-p)
16101 (error "Not at a property"))
16102 (let* ((key (match-string 2))
16103 (value (match-string 3))
16104 (allowed (or (org-property-get-allowed-values (point) key)
16105 (and (member value '("[ ]" "[-]" "[X]"))
16106 '("[ ]" "[X]"))))
16107 nval)
16108 (unless allowed
16109 (error "Allowed values for this property have not been defined"))
16110 (if previous (setq allowed (reverse allowed)))
16111 (if (member value allowed)
16112 (setq nval (car (cdr (member value allowed)))))
16113 (setq nval (or nval (car allowed)))
16114 (if (equal nval value)
16115 (error "Only one allowed value for this property"))
16116 (org-at-property-p)
16117 (replace-match (concat " :" key ": " nval) t t)
16118 (org-indent-line-function)
16119 (beginning-of-line 1)
16120 (skip-chars-forward " \t")))
16122 (defun org-find-entry-with-id (ident)
16123 "Locate the entry that contains the ID property with exact value IDENT.
16124 IDENT can be a string, a symbol or a number, this function will search for
16125 the string representation of it.
16126 Return the position where this entry starts, or nil if there is no such entry."
16127 (let ((id (cond
16128 ((stringp ident) ident)
16129 ((symbol-name ident) (symbol-name ident))
16130 ((numberp ident) (number-to-string ident))
16131 (t (error "IDENT %s must be a string, symbol or number" ident))))
16132 (case-fold-search nil))
16133 (save-excursion
16134 (save-restriction
16135 (goto-char (point-min))
16136 (when (re-search-forward
16137 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16138 nil t)
16139 (org-back-to-heading)
16140 (point))))))
16142 ;;; Column View
16144 (defvar org-columns-overlays nil
16145 "Holds the list of current column overlays.")
16147 (defvar org-columns-current-fmt nil
16148 "Local variable, holds the currently active column format.")
16149 (defvar org-columns-current-fmt-compiled nil
16150 "Local variable, holds the currently active column format.
16151 This is the compiled version of the format.")
16152 (defvar org-columns-current-widths nil
16153 "Loval variable, holds the currently widths of fields.")
16154 (defvar org-columns-current-maxwidths nil
16155 "Loval variable, holds the currently active maximum column widths.")
16156 (defvar org-columns-begin-marker (make-marker)
16157 "Points to the position where last a column creation command was called.")
16158 (defvar org-columns-top-level-marker (make-marker)
16159 "Points to the position where current columns region starts.")
16161 (defvar org-columns-map (make-sparse-keymap)
16162 "The keymap valid in column display.")
16164 (defun org-columns-content ()
16165 "Switch to contents view while in columns view."
16166 (interactive)
16167 (org-overview)
16168 (org-content))
16170 (org-defkey org-columns-map "c" 'org-columns-content)
16171 (org-defkey org-columns-map "o" 'org-overview)
16172 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16173 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16174 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16175 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16176 (org-defkey org-columns-map "v" 'org-columns-show-value)
16177 (org-defkey org-columns-map "q" 'org-columns-quit)
16178 (org-defkey org-columns-map "r" 'org-columns-redo)
16179 (org-defkey org-columns-map [left] 'backward-char)
16180 (org-defkey org-columns-map "\M-b" 'backward-char)
16181 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16182 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16183 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16184 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16185 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16186 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16187 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16188 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16189 (org-defkey org-columns-map "<" 'org-columns-narrow)
16190 (org-defkey org-columns-map ">" 'org-columns-widen)
16191 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16192 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16193 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16194 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16196 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16197 '("Column"
16198 ["Edit property" org-columns-edit-value t]
16199 ["Next allowed value" org-columns-next-allowed-value t]
16200 ["Previous allowed value" org-columns-previous-allowed-value t]
16201 ["Show full value" org-columns-show-value t]
16202 ["Edit allowed values" org-columns-edit-allowed t]
16203 "--"
16204 ["Edit column attributes" org-columns-edit-attributes t]
16205 ["Increase column width" org-columns-widen t]
16206 ["Decrease column width" org-columns-narrow t]
16207 "--"
16208 ["Move column right" org-columns-move-right t]
16209 ["Move column left" org-columns-move-left t]
16210 ["Add column" org-columns-new t]
16211 ["Delete column" org-columns-delete t]
16212 "--"
16213 ["CONTENTS" org-columns-content t]
16214 ["OVERVIEW" org-overview t]
16215 ["Refresh columns display" org-columns-redo t]
16216 "--"
16217 ["Open link" org-columns-open-link t]
16218 "--"
16219 ["Quit" org-columns-quit t]))
16221 (defun org-columns-new-overlay (beg end &optional string face)
16222 "Create a new column overlay and add it to the list."
16223 (let ((ov (org-make-overlay beg end)))
16224 (org-overlay-put ov 'face (or face 'secondary-selection))
16225 (org-overlay-display ov string face)
16226 (push ov org-columns-overlays)
16227 ov))
16229 (defun org-columns-display-here (&optional props)
16230 "Overlay the current line with column display."
16231 (interactive)
16232 (let* ((fmt org-columns-current-fmt-compiled)
16233 (beg (point-at-bol))
16234 (level-face (save-excursion
16235 (beginning-of-line 1)
16236 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16237 (org-get-level-face 2))))
16238 (color (list :foreground
16239 (face-attribute (or level-face 'default) :foreground)))
16240 props pom property ass width f string ov column val modval)
16241 ;; Check if the entry is in another buffer.
16242 (unless props
16243 (if (eq major-mode 'org-agenda-mode)
16244 (setq pom (or (get-text-property (point) 'org-hd-marker)
16245 (get-text-property (point) 'org-marker))
16246 props (if pom (org-entry-properties pom) nil))
16247 (setq props (org-entry-properties nil))))
16248 ;; Walk the format
16249 (while (setq column (pop fmt))
16250 (setq property (car column)
16251 ass (if (equal property "ITEM")
16252 (cons "ITEM"
16253 (save-match-data
16254 (org-no-properties
16255 (org-remove-tabs
16256 (buffer-substring-no-properties
16257 (point-at-bol) (point-at-eol))))))
16258 (assoc property props))
16259 width (or (cdr (assoc property org-columns-current-maxwidths))
16260 (nth 2 column)
16261 (length property))
16262 f (format "%%-%d.%ds | " width width)
16263 val (or (cdr ass) "")
16264 modval (if (equal property "ITEM")
16265 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16266 string (format f (or modval val)))
16267 ;; Create the overlay
16268 (org-unmodified
16269 (setq ov (org-columns-new-overlay
16270 beg (setq beg (1+ beg)) string
16271 (list color 'org-column)))
16272 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16273 (org-overlay-put ov 'keymap org-columns-map)
16274 (org-overlay-put ov 'org-columns-key property)
16275 (org-overlay-put ov 'org-columns-value (cdr ass))
16276 (org-overlay-put ov 'org-columns-value-modified modval)
16277 (org-overlay-put ov 'org-columns-pom pom)
16278 (org-overlay-put ov 'org-columns-format f))
16279 (if (or (not (char-after beg))
16280 (equal (char-after beg) ?\n))
16281 (let ((inhibit-read-only t))
16282 (save-excursion
16283 (goto-char beg)
16284 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16285 ;; Make the rest of the line disappear.
16286 (org-unmodified
16287 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16288 (org-overlay-put ov 'invisible t)
16289 (org-overlay-put ov 'keymap org-columns-map)
16290 (org-overlay-put ov 'intangible t)
16291 (push ov org-columns-overlays)
16292 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16293 (org-overlay-put ov 'keymap org-columns-map)
16294 (push ov org-columns-overlays)
16295 (let ((inhibit-read-only t))
16296 (put-text-property (max (point-min) (1- (point-at-bol)))
16297 (min (point-max) (1+ (point-at-eol)))
16298 'read-only "Type `e' to edit property")))))
16300 (defvar org-previous-header-line-format nil
16301 "The header line format before column view was turned on.")
16302 (defvar org-columns-inhibit-recalculation nil
16303 "Inhibit recomputing of columns on column view startup.")
16306 (defvar header-line-format)
16307 (defun org-columns-display-here-title ()
16308 "Overlay the newline before the current line with the table title."
16309 (interactive)
16310 (let ((fmt org-columns-current-fmt-compiled)
16311 string (title "")
16312 property width f column str widths)
16313 (while (setq column (pop fmt))
16314 (setq property (car column)
16315 str (or (nth 1 column) property)
16316 width (or (cdr (assoc property org-columns-current-maxwidths))
16317 (nth 2 column)
16318 (length str))
16319 widths (push width widths)
16320 f (format "%%-%d.%ds | " width width)
16321 string (format f str)
16322 title (concat title string)))
16323 (setq title (concat
16324 (org-add-props " " nil 'display '(space :align-to 0))
16325 (org-add-props title nil 'face '(:weight bold :underline t))))
16326 (org-set-local 'org-previous-header-line-format header-line-format)
16327 (org-set-local 'org-columns-current-widths (nreverse widths))
16328 (setq header-line-format title)))
16330 (defun org-columns-remove-overlays ()
16331 "Remove all currently active column overlays."
16332 (interactive)
16333 (when (marker-buffer org-columns-begin-marker)
16334 (with-current-buffer (marker-buffer org-columns-begin-marker)
16335 (when (local-variable-p 'org-previous-header-line-format)
16336 (setq header-line-format org-previous-header-line-format)
16337 (kill-local-variable 'org-previous-header-line-format))
16338 (move-marker org-columns-begin-marker nil)
16339 (move-marker org-columns-top-level-marker nil)
16340 (org-unmodified
16341 (mapc 'org-delete-overlay org-columns-overlays)
16342 (setq org-columns-overlays nil)
16343 (let ((inhibit-read-only t))
16344 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16346 (defun org-columns-cleanup-item (item fmt)
16347 "Remove from ITEM what is a column in the format FMT."
16348 (if (not org-complex-heading-regexp)
16349 item
16350 (when (string-match org-complex-heading-regexp item)
16351 (concat
16352 (org-add-props (concat (match-string 1 item) " ") nil
16353 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16354 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16355 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16356 " " (match-string 4 item)
16357 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16359 (defun org-columns-show-value ()
16360 "Show the full value of the property."
16361 (interactive)
16362 (let ((value (get-char-property (point) 'org-columns-value)))
16363 (message "Value is: %s" (or value ""))))
16365 (defun org-columns-quit ()
16366 "Remove the column overlays and in this way exit column editing."
16367 (interactive)
16368 (org-unmodified
16369 (org-columns-remove-overlays)
16370 (let ((inhibit-read-only t))
16371 (remove-text-properties (point-min) (point-max) '(read-only t))))
16372 (when (eq major-mode 'org-agenda-mode)
16373 (message
16374 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16376 (defun org-columns-check-computed ()
16377 "Check if this column value is computed.
16378 If yes, throw an error indicating that changing it does not make sense."
16379 (let ((val (get-char-property (point) 'org-columns-value)))
16380 (when (and (stringp val)
16381 (get-char-property 0 'org-computed val))
16382 (error "This value is computed from the entry's children"))))
16384 (defun org-columns-todo (&optional arg)
16385 "Change the TODO state during column view."
16386 (interactive "P")
16387 (org-columns-edit-value "TODO"))
16389 (defun org-columns-set-tags-or-toggle (&optional arg)
16390 "Toggle checkbox at point, or set tags for current headline."
16391 (interactive "P")
16392 (if (string-match "\\`\\[[ xX-]\\]\\'"
16393 (get-char-property (point) 'org-columns-value))
16394 (org-columns-next-allowed-value)
16395 (org-columns-edit-value "TAGS")))
16397 (defun org-columns-edit-value (&optional key)
16398 "Edit the value of the property at point in column view.
16399 Where possible, use the standard interface for changing this line."
16400 (interactive)
16401 (org-columns-check-computed)
16402 (let* ((external-key key)
16403 (col (current-column))
16404 (key (or key (get-char-property (point) 'org-columns-key)))
16405 (value (get-char-property (point) 'org-columns-value))
16406 (bol (point-at-bol)) (eol (point-at-eol))
16407 (pom (or (get-text-property bol 'org-hd-marker)
16408 (point))) ; keep despite of compiler waring
16409 (line-overlays
16410 (delq nil (mapcar (lambda (x)
16411 (and (eq (overlay-buffer x) (current-buffer))
16412 (>= (overlay-start x) bol)
16413 (<= (overlay-start x) eol)
16415 org-columns-overlays)))
16416 nval eval allowed)
16417 (cond
16418 ((equal key "CLOCKSUM")
16419 (error "This special column cannot be edited"))
16420 ((equal key "ITEM")
16421 (setq eval '(org-with-point-at pom
16422 (org-edit-headline))))
16423 ((equal key "TODO")
16424 (setq eval '(org-with-point-at pom
16425 (let ((current-prefix-arg
16426 (if external-key current-prefix-arg '(4))))
16427 (call-interactively 'org-todo)))))
16428 ((equal key "PRIORITY")
16429 (setq eval '(org-with-point-at pom
16430 (call-interactively 'org-priority))))
16431 ((equal key "TAGS")
16432 (setq eval '(org-with-point-at pom
16433 (let ((org-fast-tag-selection-single-key
16434 (if (eq org-fast-tag-selection-single-key 'expert)
16435 t org-fast-tag-selection-single-key)))
16436 (call-interactively 'org-set-tags)))))
16437 ((equal key "DEADLINE")
16438 (setq eval '(org-with-point-at pom
16439 (call-interactively 'org-deadline))))
16440 ((equal key "SCHEDULED")
16441 (setq eval '(org-with-point-at pom
16442 (call-interactively 'org-schedule))))
16444 (setq allowed (org-property-get-allowed-values pom key 'table))
16445 (if allowed
16446 (setq nval (completing-read "Value: " allowed nil t))
16447 (setq nval (read-string "Edit: " value)))
16448 (setq nval (org-trim nval))
16449 (when (not (equal nval value))
16450 (setq eval '(org-entry-put pom key nval)))))
16451 (when eval
16452 (let ((inhibit-read-only t))
16453 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16454 (unwind-protect
16455 (progn
16456 (setq org-columns-overlays
16457 (org-delete-all line-overlays org-columns-overlays))
16458 (mapc 'org-delete-overlay line-overlays)
16459 (org-columns-eval eval))
16460 (org-columns-display-here))))
16461 (move-to-column col)
16462 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16463 (org-columns-update key))))
16465 (defun org-edit-headline () ; FIXME: this is not columns specific
16466 "Edit the current headline, the part without TODO keyword, TAGS."
16467 (org-back-to-heading)
16468 (when (looking-at org-todo-line-regexp)
16469 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16470 (txt (match-string 3))
16471 (post "")
16472 txt2)
16473 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16474 (setq post (match-string 0 txt)
16475 txt (substring txt 0 (match-beginning 0))))
16476 (setq txt2 (read-string "Edit: " txt))
16477 (when (not (equal txt txt2))
16478 (beginning-of-line 1)
16479 (insert pre txt2 post)
16480 (delete-region (point) (point-at-eol))
16481 (org-set-tags nil t)))))
16483 (defun org-columns-edit-allowed ()
16484 "Edit the list of allowed values for the current property."
16485 (interactive)
16486 (let* ((key (get-char-property (point) 'org-columns-key))
16487 (key1 (concat key "_ALL"))
16488 (allowed (org-entry-get (point) key1 t))
16489 nval)
16490 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16491 (setq nval (read-string "Allowed: " allowed))
16492 (org-entry-put
16493 (cond ((marker-position org-entry-property-inherited-from)
16494 org-entry-property-inherited-from)
16495 ((marker-position org-columns-top-level-marker)
16496 org-columns-top-level-marker))
16497 key1 nval)))
16499 (defmacro org-no-warnings (&rest body)
16500 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16502 (defun org-columns-eval (form)
16503 (let (hidep)
16504 (save-excursion
16505 (beginning-of-line 1)
16506 ;; `next-line' is needed here, because it skips invisible line.
16507 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16508 (setq hidep (org-on-heading-p 1)))
16509 (eval form)
16510 (and hidep (hide-entry))))
16512 (defun org-columns-previous-allowed-value ()
16513 "Switch to the previous allowed value for this column."
16514 (interactive)
16515 (org-columns-next-allowed-value t))
16517 (defun org-columns-next-allowed-value (&optional previous)
16518 "Switch to the next allowed value for this column."
16519 (interactive)
16520 (org-columns-check-computed)
16521 (let* ((col (current-column))
16522 (key (get-char-property (point) 'org-columns-key))
16523 (value (get-char-property (point) 'org-columns-value))
16524 (bol (point-at-bol)) (eol (point-at-eol))
16525 (pom (or (get-text-property bol 'org-hd-marker)
16526 (point))) ; keep despite of compiler waring
16527 (line-overlays
16528 (delq nil (mapcar (lambda (x)
16529 (and (eq (overlay-buffer x) (current-buffer))
16530 (>= (overlay-start x) bol)
16531 (<= (overlay-start x) eol)
16533 org-columns-overlays)))
16534 (allowed (or (org-property-get-allowed-values pom key)
16535 (and (equal
16536 (nth 4 (assoc key org-columns-current-fmt-compiled))
16537 'checkbox) '("[ ]" "[X]"))))
16538 nval)
16539 (when (equal key "ITEM")
16540 (error "Cannot edit item headline from here"))
16541 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16542 (error "Allowed values for this property have not been defined"))
16543 (if (member key '("SCHEDULED" "DEADLINE"))
16544 (setq nval (if previous 'earlier 'later))
16545 (if previous (setq allowed (reverse allowed)))
16546 (if (member value allowed)
16547 (setq nval (car (cdr (member value allowed)))))
16548 (setq nval (or nval (car allowed)))
16549 (if (equal nval value)
16550 (error "Only one allowed value for this property")))
16551 (let ((inhibit-read-only t))
16552 (remove-text-properties (1- bol) eol '(read-only t))
16553 (unwind-protect
16554 (progn
16555 (setq org-columns-overlays
16556 (org-delete-all line-overlays org-columns-overlays))
16557 (mapc 'org-delete-overlay line-overlays)
16558 (org-columns-eval '(org-entry-put pom key nval)))
16559 (org-columns-display-here)))
16560 (move-to-column col)
16561 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16562 (org-columns-update key))))
16564 (defun org-verify-version (task)
16565 (cond
16566 ((eq task 'columns)
16567 (if (or (featurep 'xemacs)
16568 (< emacs-major-version 22))
16569 (error "Emacs 22 is required for the columns feature")))))
16571 (defun org-columns-open-link (&optional arg)
16572 (interactive "P")
16573 (let ((key (get-char-property (point) 'org-columns-key))
16574 (value (get-char-property (point) 'org-columns-value)))
16575 (org-open-link-from-string arg)))
16577 (defun org-open-link-from-string (s &optional arg)
16578 "Open a link in the string S, as if it was in Org-mode."
16579 (interactive)
16580 (with-temp-buffer
16581 (let ((org-inhibit-startup t))
16582 (org-mode)
16583 (insert s)
16584 (goto-char (point-min))
16585 (org-open-at-point arg))))
16587 (defun org-columns-get-format-and-top-level ()
16588 (let (fmt)
16589 (when (condition-case nil (org-back-to-heading) (error nil))
16590 (move-marker org-entry-property-inherited-from nil)
16591 (setq fmt (org-entry-get nil "COLUMNS" t)))
16592 (setq fmt (or fmt org-columns-default-format))
16593 (org-set-local 'org-columns-current-fmt fmt)
16594 (org-columns-compile-format fmt)
16595 (if (marker-position org-entry-property-inherited-from)
16596 (move-marker org-columns-top-level-marker
16597 org-entry-property-inherited-from)
16598 (move-marker org-columns-top-level-marker (point)))
16599 fmt))
16601 (defun org-columns ()
16602 "Turn on column view on an org-mode file."
16603 (interactive)
16604 (org-verify-version 'columns)
16605 (org-columns-remove-overlays)
16606 (move-marker org-columns-begin-marker (point))
16607 (let (beg end fmt cache maxwidths clocksump)
16608 (setq fmt (org-columns-get-format-and-top-level))
16609 (save-excursion
16610 (goto-char org-columns-top-level-marker)
16611 (setq beg (point))
16612 (unless org-columns-inhibit-recalculation
16613 (org-columns-compute-all))
16614 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16615 (point-max)))
16616 ;; Get and cache the properties
16617 (goto-char beg)
16618 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16619 (setq clocksump t)
16620 (save-excursion
16621 (save-restriction
16622 (narrow-to-region beg end)
16623 (org-clock-sum))))
16624 (while (re-search-forward (concat "^" outline-regexp) end t)
16625 (push (cons (org-current-line) (org-entry-properties)) cache))
16626 (when cache
16627 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16628 (org-set-local 'org-columns-current-maxwidths maxwidths)
16629 (org-columns-display-here-title)
16630 (mapc (lambda (x)
16631 (goto-line (car x))
16632 (org-columns-display-here (cdr x)))
16633 cache)))))
16635 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16636 "Insert a new column, to the leeft o the current column."
16637 (interactive)
16638 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16639 cell)
16640 (setq prop (completing-read
16641 "Property: " (mapcar 'list (org-buffer-property-keys t))
16642 nil nil prop))
16643 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16644 (setq width (read-string "Column width: " (if width (number-to-string width))))
16645 (if (string-match "\\S-" width)
16646 (setq width (string-to-number width))
16647 (setq width nil))
16648 (setq fmt (completing-read "Summary [none]: "
16649 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16650 nil t))
16651 (if (string-match "\\S-" fmt)
16652 (setq fmt (intern fmt))
16653 (setq fmt nil))
16654 (if (eq fmt 'none) (setq fmt nil))
16655 (if editp
16656 (progn
16657 (setcar editp prop)
16658 (setcdr editp (list title width nil fmt)))
16659 (setq cell (nthcdr (1- (current-column))
16660 org-columns-current-fmt-compiled))
16661 (setcdr cell (cons (list prop title width nil fmt)
16662 (cdr cell))))
16663 (org-columns-store-format)
16664 (org-columns-redo)))
16666 (defun org-columns-delete ()
16667 "Delete the column at point from columns view."
16668 (interactive)
16669 (let* ((n (current-column))
16670 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16671 (when (y-or-n-p
16672 (format "Are you sure you want to remove column \"%s\"? " title))
16673 (setq org-columns-current-fmt-compiled
16674 (delq (nth n org-columns-current-fmt-compiled)
16675 org-columns-current-fmt-compiled))
16676 (org-columns-store-format)
16677 (org-columns-redo)
16678 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16679 (backward-char 1)))))
16681 (defun org-columns-edit-attributes ()
16682 "Edit the attributes of the current column."
16683 (interactive)
16684 (let* ((n (current-column))
16685 (info (nth n org-columns-current-fmt-compiled)))
16686 (apply 'org-columns-new info)))
16688 (defun org-columns-widen (arg)
16689 "Make the column wider by ARG characters."
16690 (interactive "p")
16691 (let* ((n (current-column))
16692 (entry (nth n org-columns-current-fmt-compiled))
16693 (width (or (nth 2 entry)
16694 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16695 (setq width (max 1 (+ width arg)))
16696 (setcar (nthcdr 2 entry) width)
16697 (org-columns-store-format)
16698 (org-columns-redo)))
16700 (defun org-columns-narrow (arg)
16701 "Make the column nrrower by ARG characters."
16702 (interactive "p")
16703 (org-columns-widen (- arg)))
16705 (defun org-columns-move-right ()
16706 "Swap this column with the one to the right."
16707 (interactive)
16708 (let* ((n (current-column))
16709 (cell (nthcdr n org-columns-current-fmt-compiled))
16711 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16712 (error "Cannot shift this column further to the right"))
16713 (setq e (car cell))
16714 (setcar cell (car (cdr cell)))
16715 (setcdr cell (cons e (cdr (cdr cell))))
16716 (org-columns-store-format)
16717 (org-columns-redo)
16718 (forward-char 1)))
16720 (defun org-columns-move-left ()
16721 "Swap this column with the one to the left."
16722 (interactive)
16723 (let* ((n (current-column)))
16724 (when (= n 0)
16725 (error "Cannot shift this column further to the left"))
16726 (backward-char 1)
16727 (org-columns-move-right)
16728 (backward-char 1)))
16730 (defun org-columns-store-format ()
16731 "Store the text version of the current columns format in appropriate place.
16732 This is either in the COLUMNS property of the node starting the current column
16733 display, or in the #+COLUMNS line of the current buffer."
16734 (let (fmt (cnt 0))
16735 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16736 (org-set-local 'org-columns-current-fmt fmt)
16737 (if (marker-position org-columns-top-level-marker)
16738 (save-excursion
16739 (goto-char org-columns-top-level-marker)
16740 (if (and (org-at-heading-p)
16741 (org-entry-get nil "COLUMNS"))
16742 (org-entry-put nil "COLUMNS" fmt)
16743 (goto-char (point-min))
16744 ;; Overwrite all #+COLUMNS lines....
16745 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16746 (setq cnt (1+ cnt))
16747 (replace-match (concat "#+COLUMNS: " fmt) t t))
16748 (unless (> cnt 0)
16749 (goto-char (point-min))
16750 (or (org-on-heading-p t) (outline-next-heading))
16751 (let ((inhibit-read-only t))
16752 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16753 (org-set-local 'org-columns-default-format fmt))))))
16755 (defvar org-overriding-columns-format nil
16756 "When set, overrides any other definition.")
16757 (defvar org-agenda-view-columns-initially nil
16758 "When set, switch to columns view immediately after creating the agenda.")
16760 (defun org-agenda-columns ()
16761 "Turn on column view in the agenda."
16762 (interactive)
16763 (org-verify-version 'columns)
16764 (org-columns-remove-overlays)
16765 (move-marker org-columns-begin-marker (point))
16766 (let (fmt cache maxwidths m)
16767 (cond
16768 ((and (local-variable-p 'org-overriding-columns-format)
16769 org-overriding-columns-format)
16770 (setq fmt org-overriding-columns-format))
16771 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16772 (setq fmt (org-entry-get m "COLUMNS" t)))
16773 ((and (boundp 'org-columns-current-fmt)
16774 (local-variable-p 'org-columns-current-fmt)
16775 org-columns-current-fmt)
16776 (setq fmt org-columns-current-fmt))
16777 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16778 (setq m (get-text-property m 'org-hd-marker))
16779 (setq fmt (org-entry-get m "COLUMNS" t))))
16780 (setq fmt (or fmt org-columns-default-format))
16781 (org-set-local 'org-columns-current-fmt fmt)
16782 (org-columns-compile-format fmt)
16783 (save-excursion
16784 ;; Get and cache the properties
16785 (goto-char (point-min))
16786 (while (not (eobp))
16787 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16788 (get-text-property (point) 'org-marker)))
16789 (push (cons (org-current-line) (org-entry-properties m)) cache))
16790 (beginning-of-line 2))
16791 (when cache
16792 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16793 (org-set-local 'org-columns-current-maxwidths maxwidths)
16794 (org-columns-display-here-title)
16795 (mapc (lambda (x)
16796 (goto-line (car x))
16797 (org-columns-display-here (cdr x)))
16798 cache)))))
16800 (defun org-columns-get-autowidth-alist (s cache)
16801 "Derive the maximum column widths from the format and the cache."
16802 (let ((start 0) rtn)
16803 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
16804 (push (cons (match-string 1 s) 1) rtn)
16805 (setq start (match-end 0)))
16806 (mapc (lambda (x)
16807 (setcdr x (apply 'max
16808 (mapcar
16809 (lambda (y)
16810 (length (or (cdr (assoc (car x) (cdr y))) " ")))
16811 cache))))
16812 rtn)
16813 rtn))
16815 (defun org-columns-compute-all ()
16816 "Compute all columns that have operators defined."
16817 (org-unmodified
16818 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
16819 (let ((columns org-columns-current-fmt-compiled) col)
16820 (while (setq col (pop columns))
16821 (when (nth 3 col)
16822 (save-excursion
16823 (org-columns-compute (car col)))))))
16825 (defun org-columns-update (property)
16826 "Recompute PROPERTY, and update the columns display for it."
16827 (org-columns-compute property)
16828 (let (fmt val pos)
16829 (save-excursion
16830 (mapc (lambda (ov)
16831 (when (equal (org-overlay-get ov 'org-columns-key) property)
16832 (setq pos (org-overlay-start ov))
16833 (goto-char pos)
16834 (when (setq val (cdr (assoc property
16835 (get-text-property
16836 (point-at-bol) 'org-summaries))))
16837 (setq fmt (org-overlay-get ov 'org-columns-format))
16838 (org-overlay-put ov 'org-columns-value val)
16839 (org-overlay-put ov 'display (format fmt val)))))
16840 org-columns-overlays))))
16842 (defun org-columns-compute (property)
16843 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16844 (interactive)
16845 (let* ((re (concat "^" outline-regexp))
16846 (lmax 30) ; Does anyone use deeper levels???
16847 (lsum (make-vector lmax 0))
16848 (lflag (make-vector lmax nil))
16849 (level 0)
16850 (ass (assoc property org-columns-current-fmt-compiled))
16851 (format (nth 4 ass))
16852 (printf (nth 5 ass))
16853 (beg org-columns-top-level-marker)
16854 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
16855 (save-excursion
16856 ;; Find the region to compute
16857 (goto-char beg)
16858 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
16859 (goto-char end)
16860 ;; Walk the tree from the back and do the computations
16861 (while (re-search-backward re beg t)
16862 (setq sumpos (match-beginning 0)
16863 last-level level
16864 level (org-outline-level)
16865 val (org-entry-get nil property)
16866 valflag (and val (string-match "\\S-" val)))
16867 (cond
16868 ((< level last-level)
16869 ;; put the sum of lower levels here as a property
16870 (setq sum (aref lsum last-level) ; current sum
16871 flag (aref lflag last-level) ; any valid entries from children?
16872 str (org-column-number-to-string sum format printf)
16873 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
16874 useval (if flag str1 (if valflag val ""))
16875 sum-alist (get-text-property sumpos 'org-summaries))
16876 (if (assoc property sum-alist)
16877 (setcdr (assoc property sum-alist) useval)
16878 (push (cons property useval) sum-alist)
16879 (org-unmodified
16880 (add-text-properties sumpos (1+ sumpos)
16881 (list 'org-summaries sum-alist))))
16882 (when val
16883 (org-entry-put nil property (if flag str val)))
16884 ;; add current to current level accumulator
16885 (when (or flag valflag)
16886 (aset lsum level (+ (aref lsum level)
16887 (if flag sum (org-column-string-to-number
16888 (if flag str val) format))))
16889 (aset lflag level t))
16890 ;; clear accumulators for deeper levels
16891 (loop for l from (1+ level) to (1- lmax) do
16892 (aset lsum l 0)
16893 (aset lflag l nil)))
16894 ((>= level last-level)
16895 ;; add what we have here to the accumulator for this level
16896 (aset lsum level (+ (aref lsum level)
16897 (org-column-string-to-number (or val "0") format)))
16898 (and valflag (aset lflag level t)))
16899 (t (error "This should not happen")))))))
16901 (defun org-columns-redo ()
16902 "Construct the column display again."
16903 (interactive)
16904 (message "Recomputing columns...")
16905 (save-excursion
16906 (if (marker-position org-columns-begin-marker)
16907 (goto-char org-columns-begin-marker))
16908 (org-columns-remove-overlays)
16909 (if (org-mode-p)
16910 (call-interactively 'org-columns)
16911 (call-interactively 'org-agenda-columns)))
16912 (message "Recomputing columns...done"))
16914 (defun org-columns-not-in-agenda ()
16915 (if (eq major-mode 'org-agenda-mode)
16916 (error "This command is only allowed in Org-mode buffers")))
16919 (defun org-string-to-number (s)
16920 "Convert string to number, and interpret hh:mm:ss."
16921 (if (not (string-match ":" s))
16922 (string-to-number s)
16923 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16924 (while l
16925 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16926 sum)))
16928 (defun org-column-number-to-string (n fmt &optional printf)
16929 "Convert a computed column number to a string value, according to FMT."
16930 (cond
16931 ((eq fmt 'add_times)
16932 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16933 (format "%d:%02d" h m)))
16934 ((eq fmt 'checkbox)
16935 (cond ((= n (floor n)) "[X]")
16936 ((> n 1.) "[-]")
16937 (t "[ ]")))
16938 (printf (format printf n))
16939 ((eq fmt 'currency)
16940 (format "%.2f" n))
16941 (t (number-to-string n))))
16943 (defun org-column-string-to-number (s fmt)
16944 "Convert a column value to a number that can be used for column computing."
16945 (cond
16946 ((string-match ":" s)
16947 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16948 (while l
16949 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16950 sum))
16951 ((eq fmt 'checkbox)
16952 (if (equal s "[X]") 1. 0.000001))
16953 (t (string-to-number s))))
16955 (defun org-columns-uncompile-format (cfmt)
16956 "Turn the compiled columns format back into a string representation."
16957 (let ((rtn "") e s prop title op width fmt printf)
16958 (while (setq e (pop cfmt))
16959 (setq prop (car e)
16960 title (nth 1 e)
16961 width (nth 2 e)
16962 op (nth 3 e)
16963 fmt (nth 4 e)
16964 printf (nth 5 e))
16965 (cond
16966 ((eq fmt 'add_times) (setq op ":"))
16967 ((eq fmt 'checkbox) (setq op "X"))
16968 ((eq fmt 'add_numbers) (setq op "+"))
16969 ((eq fmt 'currency) (setq op "$")))
16970 (if (and op printf) (setq op (concat op ";" printf)))
16971 (if (equal title prop) (setq title nil))
16972 (setq s (concat "%" (if width (number-to-string width))
16973 prop
16974 (if title (concat "(" title ")"))
16975 (if op (concat "{" op "}"))))
16976 (setq rtn (concat rtn " " s)))
16977 (org-trim rtn)))
16979 (defun org-columns-compile-format (fmt)
16980 "Turn a column format string into an alist of specifications.
16981 The alist has one entry for each column in the format. The elements of
16982 that list are:
16983 property the property
16984 title the title field for the columns
16985 width the column width in characters, can be nil for automatic
16986 operator the operator if any
16987 format the output format for computed results, derived from operator
16988 printf a printf format for computed values"
16989 (let ((start 0) width prop title op f printf)
16990 (setq org-columns-current-fmt-compiled nil)
16991 (while (string-match
16992 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16993 fmt start)
16994 (setq start (match-end 0)
16995 width (match-string 1 fmt)
16996 prop (match-string 2 fmt)
16997 title (or (match-string 3 fmt) prop)
16998 op (match-string 4 fmt)
16999 f nil
17000 printf nil)
17001 (if width (setq width (string-to-number width)))
17002 (when (and op (string-match ";" op))
17003 (setq printf (substring op (match-end 0))
17004 op (substring op 0 (match-beginning 0))))
17005 (cond
17006 ((equal op "+") (setq f 'add_numbers))
17007 ((equal op "$") (setq f 'currency))
17008 ((equal op ":") (setq f 'add_times))
17009 ((equal op "X") (setq f 'checkbox)))
17010 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17011 (setq org-columns-current-fmt-compiled
17012 (nreverse org-columns-current-fmt-compiled))))
17015 ;;; Dynamic block for Column view
17017 (defun org-columns-capture-view ()
17018 "Get the column view of the current buffer and return it as a list.
17019 The list will contains the title row and all other rows. Each row is
17020 a list of fields."
17021 (save-excursion
17022 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17023 (n (length title)) row tbl)
17024 (goto-char (point-min))
17025 (while (re-search-forward "^\\*+ " nil t)
17026 (when (get-char-property (match-beginning 0) 'org-columns-key)
17027 (setq row nil)
17028 (loop for i from 0 to (1- n) do
17029 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17030 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17032 row))
17033 (setq row (nreverse row))
17034 (push row tbl)))
17035 (append (list title 'hline) (nreverse tbl)))))
17037 (defun org-dblock-write:columnview (params)
17038 "Write the column view table.
17039 PARAMS is a property list of parameters:
17041 :width enforce same column widths with <N> specifiers.
17042 :id the :ID: property of the entry where the columns view
17043 should be built, as a string. When `local', call locally.
17044 When `global' call column view with the cursor at the beginning
17045 of the buffer (usually this means that the whole buffer switches
17046 to column view).
17047 :hlines When t, insert a hline before each item. When a number, insert
17048 a hline before each level <= that number.
17049 :vlines When t, make each column a colgroup to enforce vertical lines."
17050 (let ((pos (move-marker (make-marker) (point)))
17051 (hlines (plist-get params :hlines))
17052 (vlines (plist-get params :vlines))
17053 tbl id idpos nfields tmp)
17054 (save-excursion
17055 (save-restriction
17056 (when (setq id (plist-get params :id))
17057 (cond ((not id) nil)
17058 ((eq id 'global) (goto-char (point-min)))
17059 ((eq id 'local) nil)
17060 ((setq idpos (org-find-entry-with-id id))
17061 (goto-char idpos))
17062 (t (error "Cannot find entry with :ID: %s" id))))
17063 (org-columns)
17064 (setq tbl (org-columns-capture-view))
17065 (setq nfields (length (car tbl)))
17066 (org-columns-quit)))
17067 (goto-char pos)
17068 (move-marker pos nil)
17069 (when tbl
17070 (when (plist-get params :hlines)
17071 (setq tmp nil)
17072 (while tbl
17073 (if (eq (car tbl) 'hline)
17074 (push (pop tbl) tmp)
17075 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17076 (if (and (not (eq (car tmp) 'hline))
17077 (or (eq hlines t)
17078 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17079 (push 'hline tmp)))
17080 (push (pop tbl) tmp)))
17081 (setq tbl (nreverse tmp)))
17082 (when vlines
17083 (setq tbl (mapcar (lambda (x)
17084 (if (eq 'hline x) x (cons "" x)))
17085 tbl))
17086 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17087 (setq pos (point))
17088 (insert (org-listtable-to-string tbl))
17089 (when (plist-get params :width)
17090 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17091 org-columns-current-widths "|")))
17092 (goto-char pos)
17093 (org-table-align))))
17095 (defun org-listtable-to-string (tbl)
17096 "Convert a listtable TBL to a string that contains the Org-mode table.
17097 The table still need to be alligned. The resulting string has no leading
17098 and tailing newline characters."
17099 (mapconcat
17100 (lambda (x)
17101 (cond
17102 ((listp x)
17103 (concat "|" (mapconcat 'identity x "|") "|"))
17104 ((eq x 'hline) "|-|")
17105 (t (error "Garbage in listtable: %s" x))))
17106 tbl "\n"))
17108 (defun org-insert-columns-dblock ()
17109 "Create a dynamic block capturing a column view table."
17110 (interactive)
17111 (let ((defaults '(:name "columnview" :hlines 1))
17112 (id (completing-read
17113 "Capture columns (local, global, entry with :ID: property) [local]: "
17114 (append '(("global") ("local"))
17115 (mapcar 'list (org-property-values "ID"))))))
17116 (if (equal id "") (setq id 'local))
17117 (if (equal id "global") (setq id 'global))
17118 (setq defaults (append defaults (list :id id)))
17119 (org-create-dblock defaults)
17120 (org-update-dblock)))
17122 ;;;; Timestamps
17124 (defvar org-last-changed-timestamp nil)
17125 (defvar org-time-was-given) ; dynamically scoped parameter
17126 (defvar org-end-time-was-given) ; dynamically scoped parameter
17127 (defvar org-ts-what) ; dynamically scoped parameter
17129 (defun org-time-stamp (arg)
17130 "Prompt for a date/time and insert a time stamp.
17131 If the user specifies a time like HH:MM, or if this command is called
17132 with a prefix argument, the time stamp will contain date and time.
17133 Otherwise, only the date will be included. All parts of a date not
17134 specified by the user will be filled in from the current date/time.
17135 So if you press just return without typing anything, the time stamp
17136 will represent the current date/time. If there is already a timestamp
17137 at the cursor, it will be modified."
17138 (interactive "P")
17139 (let* ((ts nil)
17140 (default-time
17141 ;; Default time is either today, or, when entering a range,
17142 ;; the range start.
17143 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17144 (save-excursion
17145 (re-search-backward
17146 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17147 (- (point) 20) t)))
17148 (apply 'encode-time (org-parse-time-string (match-string 1)))
17149 (current-time)))
17150 (default-input (and ts (org-get-compact-tod ts)))
17151 org-time-was-given org-end-time-was-given time)
17152 (cond
17153 ((and (org-at-timestamp-p)
17154 (eq last-command 'org-time-stamp)
17155 (eq this-command 'org-time-stamp))
17156 (insert "--")
17157 (setq time (let ((this-command this-command))
17158 (org-read-date arg 'totime nil nil default-time default-input)))
17159 (org-insert-time-stamp time (or org-time-was-given arg)))
17160 ((org-at-timestamp-p)
17161 (setq time (let ((this-command this-command))
17162 (org-read-date arg 'totime nil nil default-time default-input)))
17163 (when (org-at-timestamp-p) ; just to get the match data
17164 (replace-match "")
17165 (setq org-last-changed-timestamp
17166 (org-insert-time-stamp
17167 time (or org-time-was-given arg)
17168 nil nil nil (list org-end-time-was-given))))
17169 (message "Timestamp updated"))
17171 (setq time (let ((this-command this-command))
17172 (org-read-date arg 'totime nil nil default-time default-input)))
17173 (org-insert-time-stamp time (or org-time-was-given arg)
17174 nil nil nil (list org-end-time-was-given))))))
17176 ;; FIXME: can we use this for something else????
17177 ;; like computing time differences?????
17178 (defun org-get-compact-tod (s)
17179 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17180 (let* ((t1 (match-string 1 s))
17181 (h1 (string-to-number (match-string 2 s)))
17182 (m1 (string-to-number (match-string 3 s)))
17183 (t2 (and (match-end 4) (match-string 5 s)))
17184 (h2 (and t2 (string-to-number (match-string 6 s))))
17185 (m2 (and t2 (string-to-number (match-string 7 s))))
17186 dh dm)
17187 (if (not t2)
17189 (setq dh (- h2 h1) dm (- m2 m1))
17190 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17191 (concat t1 "+" (number-to-string dh)
17192 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17194 (defun org-time-stamp-inactive (&optional arg)
17195 "Insert an inactive time stamp.
17196 An inactive time stamp is enclosed in square brackets instead of angle
17197 brackets. It is inactive in the sense that it does not trigger agenda entries,
17198 does not link to the calendar and cannot be changed with the S-cursor keys.
17199 So these are more for recording a certain time/date."
17200 (interactive "P")
17201 (let (org-time-was-given org-end-time-was-given time)
17202 (setq time (org-read-date arg 'totime))
17203 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17204 nil nil (list org-end-time-was-given))))
17206 (defvar org-date-ovl (org-make-overlay 1 1))
17207 (org-overlay-put org-date-ovl 'face 'org-warning)
17208 (org-detach-overlay org-date-ovl)
17210 (defvar org-ans1) ; dynamically scoped parameter
17211 (defvar org-ans2) ; dynamically scoped parameter
17213 (defvar org-plain-time-of-day-regexp) ; defined below
17215 (defvar org-read-date-overlay nil)
17216 (defvar org-dcst nil) ; dynamically scoped
17218 (defun org-read-date (&optional with-time to-time from-string prompt
17219 default-time default-input)
17220 "Read a date, possibly a time, and make things smooth for the user.
17221 The prompt will suggest to enter an ISO date, but you can also enter anything
17222 which will at least partially be understood by `parse-time-string'.
17223 Unrecognized parts of the date will default to the current day, month, year,
17224 hour and minute. If this command is called to replace a timestamp at point,
17225 of to enter the second timestamp of a range, the default time is taken from the
17226 existing stamp. For example,
17227 3-2-5 --> 2003-02-05
17228 feb 15 --> currentyear-02-15
17229 sep 12 9 --> 2009-09-12
17230 12:45 --> today 12:45
17231 22 sept 0:34 --> currentyear-09-22 0:34
17232 12 --> currentyear-currentmonth-12
17233 Fri --> nearest Friday (today or later)
17234 etc.
17236 Furthermore you can specify a relative date by giving, as the *first* thing
17237 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17238 change in days weeks, months, years.
17239 With a single plus or minus, the date is relative to today. With a double
17240 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17241 +4d --> four days from today
17242 +4 --> same as above
17243 +2w --> two weeks from today
17244 ++5 --> five days from default date
17246 The function understands only English month and weekday abbreviations,
17247 but this can be configured with the variables `parse-time-months' and
17248 `parse-time-weekdays'.
17250 While prompting, a calendar is popped up - you can also select the
17251 date with the mouse (button 1). The calendar shows a period of three
17252 months. To scroll it to other months, use the keys `>' and `<'.
17253 If you don't like the calendar, turn it off with
17254 \(setq org-read-date-popup-calendar nil)
17256 With optional argument TO-TIME, the date will immediately be converted
17257 to an internal time.
17258 With an optional argument WITH-TIME, the prompt will suggest to also
17259 insert a time. Note that when WITH-TIME is not set, you can still
17260 enter a time, and this function will inform the calling routine about
17261 this change. The calling routine may then choose to change the format
17262 used to insert the time stamp into the buffer to include the time.
17263 With optional argument FROM-STRING, read from this string instead from
17264 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17265 the time/date that is used for everything that is not specified by the
17266 user."
17267 (require 'parse-time)
17268 (let* ((org-time-stamp-rounding-minutes
17269 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17270 (org-dcst org-display-custom-times)
17271 (ct (org-current-time))
17272 (def (or default-time ct))
17273 (defdecode (decode-time def))
17274 (dummy (progn
17275 (when (< (nth 2 defdecode) org-extend-today-until)
17276 (setcar (nthcdr 2 defdecode) -1)
17277 (setcar (nthcdr 1 defdecode) 59)
17278 (setq def (apply 'encode-time defdecode)
17279 defdecode (decode-time def)))))
17280 (calendar-move-hook nil)
17281 (view-diary-entries-initially nil)
17282 (view-calendar-holidays-initially nil)
17283 (timestr (format-time-string
17284 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17285 (prompt (concat (if prompt (concat prompt " ") "")
17286 (format "Date+time [%s]: " timestr)))
17287 ans (org-ans0 "") org-ans1 org-ans2 final)
17289 (cond
17290 (from-string (setq ans from-string))
17291 (org-read-date-popup-calendar
17292 (save-excursion
17293 (save-window-excursion
17294 (calendar)
17295 (calendar-forward-day (- (time-to-days def)
17296 (calendar-absolute-from-gregorian
17297 (calendar-current-date))))
17298 (org-eval-in-calendar nil t)
17299 (let* ((old-map (current-local-map))
17300 (map (copy-keymap calendar-mode-map))
17301 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17302 (org-defkey map (kbd "RET") 'org-calendar-select)
17303 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17304 'org-calendar-select-mouse)
17305 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17306 'org-calendar-select-mouse)
17307 (org-defkey minibuffer-local-map [(meta shift left)]
17308 (lambda () (interactive)
17309 (org-eval-in-calendar '(calendar-backward-month 1))))
17310 (org-defkey minibuffer-local-map [(meta shift right)]
17311 (lambda () (interactive)
17312 (org-eval-in-calendar '(calendar-forward-month 1))))
17313 (org-defkey minibuffer-local-map [(meta shift up)]
17314 (lambda () (interactive)
17315 (org-eval-in-calendar '(calendar-backward-year 1))))
17316 (org-defkey minibuffer-local-map [(meta shift down)]
17317 (lambda () (interactive)
17318 (org-eval-in-calendar '(calendar-forward-year 1))))
17319 (org-defkey minibuffer-local-map [(shift up)]
17320 (lambda () (interactive)
17321 (org-eval-in-calendar '(calendar-backward-week 1))))
17322 (org-defkey minibuffer-local-map [(shift down)]
17323 (lambda () (interactive)
17324 (org-eval-in-calendar '(calendar-forward-week 1))))
17325 (org-defkey minibuffer-local-map [(shift left)]
17326 (lambda () (interactive)
17327 (org-eval-in-calendar '(calendar-backward-day 1))))
17328 (org-defkey minibuffer-local-map [(shift right)]
17329 (lambda () (interactive)
17330 (org-eval-in-calendar '(calendar-forward-day 1))))
17331 (org-defkey minibuffer-local-map ">"
17332 (lambda () (interactive)
17333 (org-eval-in-calendar '(scroll-calendar-left 1))))
17334 (org-defkey minibuffer-local-map "<"
17335 (lambda () (interactive)
17336 (org-eval-in-calendar '(scroll-calendar-right 1))))
17337 (unwind-protect
17338 (progn
17339 (use-local-map map)
17340 (add-hook 'post-command-hook 'org-read-date-display)
17341 (setq org-ans0 (read-string prompt default-input nil nil))
17342 ;; org-ans0: from prompt
17343 ;; org-ans1: from mouse click
17344 ;; org-ans2: from calendar motion
17345 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17346 (remove-hook 'post-command-hook 'org-read-date-display)
17347 (use-local-map old-map)
17348 (when org-read-date-overlay
17349 (org-delete-overlay org-read-date-overlay)
17350 (setq org-read-date-overlay nil)))))))
17352 (t ; Naked prompt only
17353 (unwind-protect
17354 (setq ans (read-string prompt default-input nil timestr))
17355 (when org-read-date-overlay
17356 (org-delete-overlay org-read-date-overlay)
17357 (setq org-read-date-overlay nil)))))
17359 (setq final (org-read-date-analyze ans def defdecode))
17361 (if to-time
17362 (apply 'encode-time final)
17363 (if (and (boundp 'org-time-was-given) org-time-was-given)
17364 (format "%04d-%02d-%02d %02d:%02d"
17365 (nth 5 final) (nth 4 final) (nth 3 final)
17366 (nth 2 final) (nth 1 final))
17367 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17368 (defvar def)
17369 (defvar defdecode)
17370 (defvar with-time)
17371 (defun org-read-date-display ()
17372 "Display the currrent date prompt interpretation in the minibuffer."
17373 (when org-read-date-display-live
17374 (when org-read-date-overlay
17375 (org-delete-overlay org-read-date-overlay))
17376 (let ((p (point)))
17377 (end-of-line 1)
17378 (while (not (equal (buffer-substring
17379 (max (point-min) (- (point) 4)) (point))
17380 " "))
17381 (insert " "))
17382 (goto-char p))
17383 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17384 " " (or org-ans1 org-ans2)))
17385 (org-end-time-was-given nil)
17386 (f (org-read-date-analyze ans def defdecode))
17387 (fmts (if org-dcst
17388 org-time-stamp-custom-formats
17389 org-time-stamp-formats))
17390 (fmt (if (or with-time
17391 (and (boundp 'org-time-was-given) org-time-was-given))
17392 (cdr fmts)
17393 (car fmts)))
17394 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17395 (when (and org-end-time-was-given
17396 (string-match org-plain-time-of-day-regexp txt))
17397 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17398 org-end-time-was-given
17399 (substring txt (match-end 0)))))
17400 (setq org-read-date-overlay
17401 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17402 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17404 (defun org-read-date-analyze (ans def defdecode)
17405 "Analyze the combined answer of the date prompt."
17406 ;; FIXME: cleanup and comment
17407 (let (delta deltan deltaw deltadef year month day
17408 hour minute second wday pm h2 m2 tl wday1)
17410 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17411 (setq ans (replace-match "" t t ans)
17412 deltan (car delta)
17413 deltaw (nth 1 delta)
17414 deltadef (nth 2 delta)))
17416 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17417 (when (string-match
17418 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17419 (setq year (if (match-end 2)
17420 (string-to-number (match-string 2 ans))
17421 (string-to-number (format-time-string "%Y")))
17422 month (string-to-number (match-string 3 ans))
17423 day (string-to-number (match-string 4 ans)))
17424 (if (< year 100) (setq year (+ 2000 year)))
17425 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17426 t nil ans)))
17427 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17428 ;; If there is a time with am/pm, and *no* time without it, we convert
17429 ;; so that matching will be successful.
17430 (loop for i from 1 to 2 do ; twice, for end time as well
17431 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17432 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17433 (setq hour (string-to-number (match-string 1 ans))
17434 minute (if (match-end 3)
17435 (string-to-number (match-string 3 ans))
17437 pm (equal ?p
17438 (string-to-char (downcase (match-string 4 ans)))))
17439 (if (and (= hour 12) (not pm))
17440 (setq hour 0)
17441 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17442 (setq ans (replace-match (format "%02d:%02d" hour minute)
17443 t t ans))))
17445 ;; Check if a time range is given as a duration
17446 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17447 (setq hour (string-to-number (match-string 1 ans))
17448 h2 (+ hour (string-to-number (match-string 3 ans)))
17449 minute (string-to-number (match-string 2 ans))
17450 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17451 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17452 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17454 ;; Check if there is a time range
17455 (when (boundp 'org-end-time-was-given)
17456 (setq org-time-was-given nil)
17457 (when (and (string-match org-plain-time-of-day-regexp ans)
17458 (match-end 8))
17459 (setq org-end-time-was-given (match-string 8 ans))
17460 (setq ans (concat (substring ans 0 (match-beginning 7))
17461 (substring ans (match-end 7))))))
17463 (setq tl (parse-time-string ans)
17464 day (or (nth 3 tl) (nth 3 defdecode))
17465 month (or (nth 4 tl)
17466 (if (and org-read-date-prefer-future
17467 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17468 (1+ (nth 4 defdecode))
17469 (nth 4 defdecode)))
17470 year (or (nth 5 tl)
17471 (if (and org-read-date-prefer-future
17472 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17473 (1+ (nth 5 defdecode))
17474 (nth 5 defdecode)))
17475 hour (or (nth 2 tl) (nth 2 defdecode))
17476 minute (or (nth 1 tl) (nth 1 defdecode))
17477 second (or (nth 0 tl) 0)
17478 wday (nth 6 tl))
17479 (when deltan
17480 (unless deltadef
17481 (let ((now (decode-time (current-time))))
17482 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17483 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17484 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17485 ((equal deltaw "m") (setq month (+ month deltan)))
17486 ((equal deltaw "y") (setq year (+ year deltan)))))
17487 (when (and wday (not (nth 3 tl)))
17488 ;; Weekday was given, but no day, so pick that day in the week
17489 ;; on or after the derived date.
17490 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17491 (unless (equal wday wday1)
17492 (setq day (+ day (% (- wday wday1 -7) 7)))))
17493 (if (and (boundp 'org-time-was-given)
17494 (nth 2 tl))
17495 (setq org-time-was-given t))
17496 (if (< year 100) (setq year (+ 2000 year)))
17497 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17498 (list second minute hour day month year)))
17500 (defvar parse-time-weekdays)
17502 (defun org-read-date-get-relative (s today default)
17503 "Check string S for special relative date string.
17504 TODAY and DEFAULT are internal times, for today and for a default.
17505 Return shift list (N what def-flag)
17506 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17507 N is the number of WHATs to shift.
17508 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17509 the DEFAULT date rather than TODAY."
17510 (when (string-match
17511 (concat
17512 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17513 "\\([0-9]+\\)?"
17514 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17515 "\\([ \t]\\|$\\)") s)
17516 (let* ((dir (if (match-end 1)
17517 (string-to-char (substring (match-string 1 s) -1))
17518 ?+))
17519 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17520 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17521 (what (if (match-end 3) (match-string 3 s) "d"))
17522 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17523 (date (if rel default today))
17524 (wday (nth 6 (decode-time date)))
17525 delta)
17526 (if wday1
17527 (progn
17528 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17529 (if (= dir ?-) (setq delta (- delta 7)))
17530 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17531 (list delta "d" rel))
17532 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17534 (defun org-eval-in-calendar (form &optional keepdate)
17535 "Eval FORM in the calendar window and return to current window.
17536 Also, store the cursor date in variable org-ans2."
17537 (let ((sw (selected-window)))
17538 (select-window (get-buffer-window "*Calendar*"))
17539 (eval form)
17540 (when (and (not keepdate) (calendar-cursor-to-date))
17541 (let* ((date (calendar-cursor-to-date))
17542 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17543 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17544 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17545 (select-window sw)))
17547 ; ;; Update the prompt to show new default date
17548 ; (save-excursion
17549 ; (goto-char (point-min))
17550 ; (when (and org-ans2
17551 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17552 ; (get-text-property (match-end 0) 'field))
17553 ; (let ((inhibit-read-only t))
17554 ; (replace-match (concat "[" org-ans2 "]") t t)
17555 ; (add-text-properties (point-min) (1+ (match-end 0))
17556 ; (text-properties-at (1+ (point-min)))))))))
17558 (defun org-calendar-select ()
17559 "Return to `org-read-date' with the date currently selected.
17560 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17561 (interactive)
17562 (when (calendar-cursor-to-date)
17563 (let* ((date (calendar-cursor-to-date))
17564 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17565 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17566 (if (active-minibuffer-window) (exit-minibuffer))))
17568 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17569 "Insert a date stamp for the date given by the internal TIME.
17570 WITH-HM means, use the stamp format that includes the time of the day.
17571 INACTIVE means use square brackets instead of angular ones, so that the
17572 stamp will not contribute to the agenda.
17573 PRE and POST are optional strings to be inserted before and after the
17574 stamp.
17575 The command returns the inserted time stamp."
17576 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17577 stamp)
17578 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17579 (insert-before-markers (or pre ""))
17580 (insert-before-markers (setq stamp (format-time-string fmt time)))
17581 (when (listp extra)
17582 (setq extra (car extra))
17583 (if (and (stringp extra)
17584 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17585 (setq extra (format "-%02d:%02d"
17586 (string-to-number (match-string 1 extra))
17587 (string-to-number (match-string 2 extra))))
17588 (setq extra nil)))
17589 (when extra
17590 (backward-char 1)
17591 (insert-before-markers extra)
17592 (forward-char 1))
17593 (insert-before-markers (or post ""))
17594 stamp))
17596 (defun org-toggle-time-stamp-overlays ()
17597 "Toggle the use of custom time stamp formats."
17598 (interactive)
17599 (setq org-display-custom-times (not org-display-custom-times))
17600 (unless org-display-custom-times
17601 (let ((p (point-min)) (bmp (buffer-modified-p)))
17602 (while (setq p (next-single-property-change p 'display))
17603 (if (and (get-text-property p 'display)
17604 (eq (get-text-property p 'face) 'org-date))
17605 (remove-text-properties
17606 p (setq p (next-single-property-change p 'display))
17607 '(display t))))
17608 (set-buffer-modified-p bmp)))
17609 (if (featurep 'xemacs)
17610 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17611 (org-restart-font-lock)
17612 (setq org-table-may-need-update t)
17613 (if org-display-custom-times
17614 (message "Time stamps are overlayed with custom format")
17615 (message "Time stamp overlays removed")))
17617 (defun org-display-custom-time (beg end)
17618 "Overlay modified time stamp format over timestamp between BED and END."
17619 (let* ((ts (buffer-substring beg end))
17620 t1 w1 with-hm tf time str w2 (off 0))
17621 (save-match-data
17622 (setq t1 (org-parse-time-string ts t))
17623 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17624 (setq off (- (match-end 0) (match-beginning 0)))))
17625 (setq end (- end off))
17626 (setq w1 (- end beg)
17627 with-hm (and (nth 1 t1) (nth 2 t1))
17628 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17629 time (org-fix-decoded-time t1)
17630 str (org-add-props
17631 (format-time-string
17632 (substring tf 1 -1) (apply 'encode-time time))
17633 nil 'mouse-face 'highlight)
17634 w2 (length str))
17635 (if (not (= w2 w1))
17636 (add-text-properties (1+ beg) (+ 2 beg)
17637 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17638 (if (featurep 'xemacs)
17639 (progn
17640 (put-text-property beg end 'invisible t)
17641 (put-text-property beg end 'end-glyph (make-glyph str)))
17642 (put-text-property beg end 'display str))))
17644 (defun org-translate-time (string)
17645 "Translate all timestamps in STRING to custom format.
17646 But do this only if the variable `org-display-custom-times' is set."
17647 (when org-display-custom-times
17648 (save-match-data
17649 (let* ((start 0)
17650 (re org-ts-regexp-both)
17651 t1 with-hm inactive tf time str beg end)
17652 (while (setq start (string-match re string start))
17653 (setq beg (match-beginning 0)
17654 end (match-end 0)
17655 t1 (save-match-data
17656 (org-parse-time-string (substring string beg end) t))
17657 with-hm (and (nth 1 t1) (nth 2 t1))
17658 inactive (equal (substring string beg (1+ beg)) "[")
17659 tf (funcall (if with-hm 'cdr 'car)
17660 org-time-stamp-custom-formats)
17661 time (org-fix-decoded-time t1)
17662 str (format-time-string
17663 (concat
17664 (if inactive "[" "<") (substring tf 1 -1)
17665 (if inactive "]" ">"))
17666 (apply 'encode-time time))
17667 string (replace-match str t t string)
17668 start (+ start (length str)))))))
17669 string)
17671 (defun org-fix-decoded-time (time)
17672 "Set 0 instead of nil for the first 6 elements of time.
17673 Don't touch the rest."
17674 (let ((n 0))
17675 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17677 (defun org-days-to-time (timestamp-string)
17678 "Difference between TIMESTAMP-STRING and now in days."
17679 (- (time-to-days (org-time-string-to-time timestamp-string))
17680 (time-to-days (current-time))))
17682 (defun org-deadline-close (timestamp-string &optional ndays)
17683 "Is the time in TIMESTAMP-STRING close to the current date?"
17684 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17685 (and (< (org-days-to-time timestamp-string) ndays)
17686 (not (org-entry-is-done-p))))
17688 (defun org-get-wdays (ts)
17689 "Get the deadline lead time appropriate for timestring TS."
17690 (cond
17691 ((<= org-deadline-warning-days 0)
17692 ;; 0 or negative, enforce this value no matter what
17693 (- org-deadline-warning-days))
17694 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17695 ;; lead time is specified.
17696 (floor (* (string-to-number (match-string 1 ts))
17697 (cdr (assoc (match-string 2 ts)
17698 '(("d" . 1) ("w" . 7)
17699 ("m" . 30.4) ("y" . 365.25)))))))
17700 ;; go for the default.
17701 (t org-deadline-warning-days)))
17703 (defun org-calendar-select-mouse (ev)
17704 "Return to `org-read-date' with the date currently selected.
17705 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17706 (interactive "e")
17707 (mouse-set-point ev)
17708 (when (calendar-cursor-to-date)
17709 (let* ((date (calendar-cursor-to-date))
17710 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17711 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17712 (if (active-minibuffer-window) (exit-minibuffer))))
17714 (defun org-check-deadlines (ndays)
17715 "Check if there are any deadlines due or past due.
17716 A deadline is considered due if it happens within `org-deadline-warning-days'
17717 days from today's date. If the deadline appears in an entry marked DONE,
17718 it is not shown. The prefix arg NDAYS can be used to test that many
17719 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17720 (interactive "P")
17721 (let* ((org-warn-days
17722 (cond
17723 ((equal ndays '(4)) 100000)
17724 (ndays (prefix-numeric-value ndays))
17725 (t (abs org-deadline-warning-days))))
17726 (case-fold-search nil)
17727 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17728 (callback
17729 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17731 (message "%d deadlines past-due or due within %d days"
17732 (org-occur regexp nil callback)
17733 org-warn-days)))
17735 (defun org-check-before-date (date)
17736 "Check if there are deadlines or scheduled entries before DATE."
17737 (interactive (list (org-read-date)))
17738 (let ((case-fold-search nil)
17739 (regexp (concat "\\<\\(" org-deadline-string
17740 "\\|" org-scheduled-string
17741 "\\) *<\\([^>]+\\)>"))
17742 (callback
17743 (lambda () (time-less-p
17744 (org-time-string-to-time (match-string 2))
17745 (org-time-string-to-time date)))))
17746 (message "%d entries before %s"
17747 (org-occur regexp nil callback) date)))
17749 (defun org-evaluate-time-range (&optional to-buffer)
17750 "Evaluate a time range by computing the difference between start and end.
17751 Normally the result is just printed in the echo area, but with prefix arg
17752 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17753 If the time range is actually in a table, the result is inserted into the
17754 next column.
17755 For time difference computation, a year is assumed to be exactly 365
17756 days in order to avoid rounding problems."
17757 (interactive "P")
17759 (org-clock-update-time-maybe)
17760 (save-excursion
17761 (unless (org-at-date-range-p t)
17762 (goto-char (point-at-bol))
17763 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17764 (if (not (org-at-date-range-p t))
17765 (error "Not at a time-stamp range, and none found in current line")))
17766 (let* ((ts1 (match-string 1))
17767 (ts2 (match-string 2))
17768 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17769 (match-end (match-end 0))
17770 (time1 (org-time-string-to-time ts1))
17771 (time2 (org-time-string-to-time ts2))
17772 (t1 (time-to-seconds time1))
17773 (t2 (time-to-seconds time2))
17774 (diff (abs (- t2 t1)))
17775 (negative (< (- t2 t1) 0))
17776 ;; (ys (floor (* 365 24 60 60)))
17777 (ds (* 24 60 60))
17778 (hs (* 60 60))
17779 (fy "%dy %dd %02d:%02d")
17780 (fy1 "%dy %dd")
17781 (fd "%dd %02d:%02d")
17782 (fd1 "%dd")
17783 (fh "%02d:%02d")
17784 y d h m align)
17785 (if havetime
17786 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17788 d (floor (/ diff ds)) diff (mod diff ds)
17789 h (floor (/ diff hs)) diff (mod diff hs)
17790 m (floor (/ diff 60)))
17791 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17793 d (floor (+ (/ diff ds) 0.5))
17794 h 0 m 0))
17795 (if (not to-buffer)
17796 (message "%s" (org-make-tdiff-string y d h m))
17797 (if (org-at-table-p)
17798 (progn
17799 (goto-char match-end)
17800 (setq align t)
17801 (and (looking-at " *|") (goto-char (match-end 0))))
17802 (goto-char match-end))
17803 (if (looking-at
17804 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17805 (replace-match ""))
17806 (if negative (insert " -"))
17807 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17808 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17809 (insert " " (format fh h m))))
17810 (if align (org-table-align))
17811 (message "Time difference inserted")))))
17813 (defun org-make-tdiff-string (y d h m)
17814 (let ((fmt "")
17815 (l nil))
17816 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17817 l (push y l)))
17818 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17819 l (push d l)))
17820 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17821 l (push h l)))
17822 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17823 l (push m l)))
17824 (apply 'format fmt (nreverse l))))
17826 (defun org-time-string-to-time (s)
17827 (apply 'encode-time (org-parse-time-string s)))
17829 (defun org-time-string-to-absolute (s &optional daynr)
17830 "Convert a time stamp to an absolute day number.
17831 If there is a specifyer for a cyclic time stamp, get the closest date to
17832 DAYNR."
17833 (cond
17834 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17835 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17836 daynr
17837 (+ daynr 1000)))
17838 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
17839 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17840 (time-to-days (current-time))) (match-string 0 s)))
17841 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
17843 (defun org-time-from-absolute (d)
17844 "Return the time corresponding to date D.
17845 D may be an absolute day number, or a calendar-type list (month day year)."
17846 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17847 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17849 (defun org-calendar-holiday ()
17850 "List of holidays, for Diary display in Org-mode."
17851 (require 'holidays)
17852 (let ((hl (funcall
17853 (if (fboundp 'calendar-check-holidays)
17854 'calendar-check-holidays 'check-calendar-holidays) date)))
17855 (if hl (mapconcat 'identity hl "; "))))
17857 (defun org-diary-sexp-entry (sexp entry date)
17858 "Process a SEXP diary ENTRY for DATE."
17859 (require 'diary-lib)
17860 (let ((result (if calendar-debug-sexp
17861 (let ((stack-trace-on-error t))
17862 (eval (car (read-from-string sexp))))
17863 (condition-case nil
17864 (eval (car (read-from-string sexp)))
17865 (error
17866 (beep)
17867 (message "Bad sexp at line %d in %s: %s"
17868 (org-current-line)
17869 (buffer-file-name) sexp)
17870 (sleep-for 2))))))
17871 (cond ((stringp result) result)
17872 ((and (consp result)
17873 (stringp (cdr result))) (cdr result))
17874 (result entry)
17875 (t nil))))
17877 (defun org-diary-to-ical-string (frombuf)
17878 "Get iCalendar entries from diary entries in buffer FROMBUF.
17879 This uses the icalendar.el library."
17880 (let* ((tmpdir (if (featurep 'xemacs)
17881 (temp-directory)
17882 temporary-file-directory))
17883 (tmpfile (make-temp-name
17884 (expand-file-name "orgics" tmpdir)))
17885 buf rtn b e)
17886 (save-excursion
17887 (set-buffer frombuf)
17888 (icalendar-export-region (point-min) (point-max) tmpfile)
17889 (setq buf (find-buffer-visiting tmpfile))
17890 (set-buffer buf)
17891 (goto-char (point-min))
17892 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17893 (setq b (match-beginning 0)))
17894 (goto-char (point-max))
17895 (if (re-search-backward "^END:VEVENT" nil t)
17896 (setq e (match-end 0)))
17897 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17898 (kill-buffer buf)
17899 (kill-buffer frombuf)
17900 (delete-file tmpfile)
17901 rtn))
17903 (defun org-closest-date (start current change)
17904 "Find the date closest to CURRENT that is consistent with START and CHANGE."
17905 ;; Make the proper lists from the dates
17906 (catch 'exit
17907 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
17908 dn dw sday cday n1 n2
17909 d m y y1 y2 date1 date2 nmonths nm ny m2)
17911 (setq start (org-date-to-gregorian start)
17912 current (org-date-to-gregorian
17913 (if org-agenda-repeating-timestamp-show-all
17914 current
17915 (time-to-days (current-time))))
17916 sday (calendar-absolute-from-gregorian start)
17917 cday (calendar-absolute-from-gregorian current))
17919 (if (<= cday sday) (throw 'exit sday))
17921 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
17922 (setq dn (string-to-number (match-string 1 change))
17923 dw (cdr (assoc (match-string 2 change) a1)))
17924 (error "Invalid change specifyer: %s" change))
17925 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17926 (cond
17927 ((eq dw 'day)
17928 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17929 n2 (+ n1 dn)))
17930 ((eq dw 'year)
17931 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17932 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17933 (setq date1 (list m d y1)
17934 n1 (calendar-absolute-from-gregorian date1)
17935 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17936 n2 (calendar-absolute-from-gregorian date2)))
17937 ((eq dw 'month)
17938 ;; approx number of month between the tow dates
17939 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17940 ;; How often does dn fit in there?
17941 (setq d (nth 1 start) m (car start) y (nth 2 start)
17942 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17943 m (+ m nm)
17944 ny (floor (/ m 12))
17945 y (+ y ny)
17946 m (- m (* ny 12)))
17947 (while (> m 12) (setq m (- m 12) y (1+ y)))
17948 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17949 (setq m2 (+ m dn) y2 y)
17950 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17951 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17952 (while (< n2 cday)
17953 (setq n1 n2 m m2 y y2)
17954 (setq m2 (+ m dn) y2 y)
17955 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17956 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17958 (if org-agenda-repeating-timestamp-show-all
17959 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
17960 (if (= cday n1) n1 n2)))))
17962 (defun org-date-to-gregorian (date)
17963 "Turn any specification of DATE into a gregorian date for the calendar."
17964 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17965 ((and (listp date) (= (length date) 3)) date)
17966 ((stringp date)
17967 (setq date (org-parse-time-string date))
17968 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17969 ((listp date)
17970 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17972 (defun org-parse-time-string (s &optional nodefault)
17973 "Parse the standard Org-mode time string.
17974 This should be a lot faster than the normal `parse-time-string'.
17975 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17976 hour and minute fields will be nil if not given."
17977 (if (string-match org-ts-regexp0 s)
17978 (list 0
17979 (if (or (match-beginning 8) (not nodefault))
17980 (string-to-number (or (match-string 8 s) "0")))
17981 (if (or (match-beginning 7) (not nodefault))
17982 (string-to-number (or (match-string 7 s) "0")))
17983 (string-to-number (match-string 4 s))
17984 (string-to-number (match-string 3 s))
17985 (string-to-number (match-string 2 s))
17986 nil nil nil)
17987 (make-list 9 0)))
17989 (defun org-timestamp-up (&optional arg)
17990 "Increase the date item at the cursor by one.
17991 If the cursor is on the year, change the year. If it is on the month or
17992 the day, change that.
17993 With prefix ARG, change by that many units."
17994 (interactive "p")
17995 (org-timestamp-change (prefix-numeric-value arg)))
17997 (defun org-timestamp-down (&optional arg)
17998 "Decrease the date item at the cursor by one.
17999 If the cursor is on the year, change the year. If it is on the month or
18000 the day, change that.
18001 With prefix ARG, change by that many units."
18002 (interactive "p")
18003 (org-timestamp-change (- (prefix-numeric-value arg))))
18005 (defun org-timestamp-up-day (&optional arg)
18006 "Increase the date in the time stamp by one day.
18007 With prefix ARG, change that many days."
18008 (interactive "p")
18009 (if (and (not (org-at-timestamp-p t))
18010 (org-on-heading-p))
18011 (org-todo 'up)
18012 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18014 (defun org-timestamp-down-day (&optional arg)
18015 "Decrease the date in the time stamp by one day.
18016 With prefix ARG, change that many days."
18017 (interactive "p")
18018 (if (and (not (org-at-timestamp-p t))
18019 (org-on-heading-p))
18020 (org-todo 'down)
18021 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18023 (defsubst org-pos-in-match-range (pos n)
18024 (and (match-beginning n)
18025 (<= (match-beginning n) pos)
18026 (>= (match-end n) pos)))
18028 (defun org-at-timestamp-p (&optional inactive-ok)
18029 "Determine if the cursor is in or at a timestamp."
18030 (interactive)
18031 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18032 (pos (point))
18033 (ans (or (looking-at tsr)
18034 (save-excursion
18035 (skip-chars-backward "^[<\n\r\t")
18036 (if (> (point) (point-min)) (backward-char 1))
18037 (and (looking-at tsr)
18038 (> (- (match-end 0) pos) -1))))))
18039 (and ans
18040 (boundp 'org-ts-what)
18041 (setq org-ts-what
18042 (cond
18043 ((= pos (match-beginning 0)) 'bracket)
18044 ((= pos (1- (match-end 0))) 'bracket)
18045 ((org-pos-in-match-range pos 2) 'year)
18046 ((org-pos-in-match-range pos 3) 'month)
18047 ((org-pos-in-match-range pos 7) 'hour)
18048 ((org-pos-in-match-range pos 8) 'minute)
18049 ((or (org-pos-in-match-range pos 4)
18050 (org-pos-in-match-range pos 5)) 'day)
18051 ((and (> pos (or (match-end 8) (match-end 5)))
18052 (< pos (match-end 0)))
18053 (- pos (or (match-end 8) (match-end 5))))
18054 (t 'day))))
18055 ans))
18057 (defun org-toggle-timestamp-type ()
18059 (interactive)
18060 (when (org-at-timestamp-p t)
18061 (save-excursion
18062 (goto-char (match-beginning 0))
18063 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18064 (goto-char (1- (match-end 0)))
18065 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18066 (message "Timestamp is now %sactive"
18067 (if (equal (char-before) ?>) "in" ""))))
18069 (defun org-timestamp-change (n &optional what)
18070 "Change the date in the time stamp at point.
18071 The date will be changed by N times WHAT. WHAT can be `day', `month',
18072 `year', `minute', `second'. If WHAT is not given, the cursor position
18073 in the timestamp determines what will be changed."
18074 (let ((pos (point))
18075 with-hm inactive
18076 org-ts-what
18077 extra
18078 ts time time0)
18079 (if (not (org-at-timestamp-p t))
18080 (error "Not at a timestamp"))
18081 (if (and (not what) (eq org-ts-what 'bracket))
18082 (org-toggle-timestamp-type)
18083 (if (and (not what) (not (eq org-ts-what 'day))
18084 org-display-custom-times
18085 (get-text-property (point) 'display)
18086 (not (get-text-property (1- (point)) 'display)))
18087 (setq org-ts-what 'day))
18088 (setq org-ts-what (or what org-ts-what)
18089 inactive (= (char-after (match-beginning 0)) ?\[)
18090 ts (match-string 0))
18091 (replace-match "")
18092 (if (string-match
18093 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18095 (setq extra (match-string 1 ts)))
18096 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18097 (setq with-hm t))
18098 (setq time0 (org-parse-time-string ts))
18099 (setq time
18100 (encode-time (or (car time0) 0)
18101 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18102 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18103 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18104 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18105 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18106 (nthcdr 6 time0)))
18107 (when (integerp org-ts-what)
18108 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18109 (if (eq what 'calendar)
18110 (let ((cal-date (org-get-date-from-calendar)))
18111 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18112 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18113 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18114 (setcar time0 (or (car time0) 0))
18115 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18116 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18117 (setq time (apply 'encode-time time0))))
18118 (setq org-last-changed-timestamp
18119 (org-insert-time-stamp time with-hm inactive nil nil extra))
18120 (org-clock-update-time-maybe)
18121 (goto-char pos)
18122 ;; Try to recenter the calendar window, if any
18123 (if (and org-calendar-follow-timestamp-change
18124 (get-buffer-window "*Calendar*" t)
18125 (memq org-ts-what '(day month year)))
18126 (org-recenter-calendar (time-to-days time))))))
18128 ;; FIXME: does not yet work for lead times
18129 (defun org-modify-ts-extra (s pos n)
18130 "Change the different parts of the lead-time and repeat fields in timestamp."
18131 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18132 ng h m new)
18133 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18134 (cond
18135 ((or (org-pos-in-match-range pos 2)
18136 (org-pos-in-match-range pos 3))
18137 (setq m (string-to-number (match-string 3 s))
18138 h (string-to-number (match-string 2 s)))
18139 (if (org-pos-in-match-range pos 2)
18140 (setq h (+ h n))
18141 (setq m (+ m n)))
18142 (if (< m 0) (setq m (+ m 60) h (1- h)))
18143 (if (> m 59) (setq m (- m 60) h (1+ h)))
18144 (setq h (min 24 (max 0 h)))
18145 (setq ng 1 new (format "-%02d:%02d" h m)))
18146 ((org-pos-in-match-range pos 6)
18147 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18148 ((org-pos-in-match-range pos 5)
18149 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18151 (when ng
18152 (setq s (concat
18153 (substring s 0 (match-beginning ng))
18155 (substring s (match-end ng))))))
18158 (defun org-recenter-calendar (date)
18159 "If the calendar is visible, recenter it to DATE."
18160 (let* ((win (selected-window))
18161 (cwin (get-buffer-window "*Calendar*" t))
18162 (calendar-move-hook nil))
18163 (when cwin
18164 (select-window cwin)
18165 (calendar-goto-date (if (listp date) date
18166 (calendar-gregorian-from-absolute date)))
18167 (select-window win))))
18169 (defun org-goto-calendar (&optional arg)
18170 "Go to the Emacs calendar at the current date.
18171 If there is a time stamp in the current line, go to that date.
18172 A prefix ARG can be used to force the current date."
18173 (interactive "P")
18174 (let ((tsr org-ts-regexp) diff
18175 (calendar-move-hook nil)
18176 (view-calendar-holidays-initially nil)
18177 (view-diary-entries-initially nil))
18178 (if (or (org-at-timestamp-p)
18179 (save-excursion
18180 (beginning-of-line 1)
18181 (looking-at (concat ".*" tsr))))
18182 (let ((d1 (time-to-days (current-time)))
18183 (d2 (time-to-days
18184 (org-time-string-to-time (match-string 1)))))
18185 (setq diff (- d2 d1))))
18186 (calendar)
18187 (calendar-goto-today)
18188 (if (and diff (not arg)) (calendar-forward-day diff))))
18190 (defun org-get-date-from-calendar ()
18191 "Return a list (month day year) of date at point in calendar."
18192 (with-current-buffer "*Calendar*"
18193 (save-match-data
18194 (calendar-cursor-to-date))))
18196 (defun org-date-from-calendar ()
18197 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18198 If there is already a time stamp at the cursor position, update it."
18199 (interactive)
18200 (if (org-at-timestamp-p t)
18201 (org-timestamp-change 0 'calendar)
18202 (let ((cal-date (org-get-date-from-calendar)))
18203 (org-insert-time-stamp
18204 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18206 ;; Make appt aware of appointments from the agenda
18207 ;;;###autoload
18208 (defun org-agenda-to-appt (&optional filter)
18209 "Activate appointments found in `org-agenda-files'.
18210 When prefixed, prompt for a regular expression and use it as a
18211 filter: only add entries if they match this regular expression.
18213 FILTER can be a string. In this case, use this string as a
18214 regular expression to filter results.
18216 FILTER can also be an alist, with the car of each cell being
18217 either 'headline or 'category. For example:
18219 '((headline \"IMPORTANT\")
18220 (category \"Work\"))
18222 will only add headlines containing IMPORTANT or headlines
18223 belonging to the category \"Work\"."
18224 (interactive "P")
18225 (require 'calendar)
18226 (if (equal filter '(4))
18227 (setq filter (read-from-minibuffer "Regexp filter: ")))
18228 (let* ((cnt 0) ; count added events
18229 (org-agenda-new-buffers nil)
18230 (today (org-date-to-gregorian
18231 (time-to-days (current-time))))
18232 (files (org-agenda-files)) entries file)
18233 ;; Get all entries which may contain an appt
18234 (while (setq file (pop files))
18235 (setq entries
18236 (append entries
18237 (org-agenda-get-day-entries
18238 file today
18239 :timestamp :scheduled :deadline))))
18240 (setq entries (delq nil entries))
18241 ;; Map thru entries and find if they pass thru the filter
18242 (mapc
18243 (lambda(x)
18244 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18245 (cat (get-text-property 1 'org-category x))
18246 (tod (get-text-property 1 'time-of-day x))
18247 (ok (or (null filter)
18248 (and (stringp filter) (string-match filter evt))
18249 (and (listp filter)
18250 (or (string-match
18251 (cadr (assoc 'category filter)) cat)
18252 (string-match
18253 (cadr (assoc 'headline filter)) evt))))))
18254 ;; FIXME: Shall we remove text-properties for the appt text?
18255 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18256 (when (and ok tod)
18257 (setq tod (number-to-string tod)
18258 tod (when (string-match
18259 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18260 (concat (match-string 1 tod) ":"
18261 (match-string 2 tod))))
18262 (appt-add tod evt)
18263 (setq cnt (1+ cnt))))) entries)
18264 (org-release-buffers org-agenda-new-buffers)
18265 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18267 ;;; The clock for measuring work time.
18269 (defvar org-mode-line-string "")
18270 (put 'org-mode-line-string 'risky-local-variable t)
18272 (defvar org-mode-line-timer nil)
18273 (defvar org-clock-heading "")
18274 (defvar org-clock-start-time "")
18276 (defun org-update-mode-line ()
18277 (let* ((delta (- (time-to-seconds (current-time))
18278 (time-to-seconds org-clock-start-time)))
18279 (h (floor delta 3600))
18280 (m (floor (- delta (* 3600 h)) 60)))
18281 (setq org-mode-line-string
18282 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18283 'help-echo "Org-mode clock is running"))
18284 (force-mode-line-update)))
18286 (defvar org-clock-marker (make-marker)
18287 "Marker recording the last clock-in.")
18288 (defvar org-clock-mode-line-entry nil
18289 "Information for the modeline about the running clock.")
18291 (defun org-clock-in ()
18292 "Start the clock on the current item.
18293 If necessary, clock-out of the currently active clock."
18294 (interactive)
18295 (org-clock-out t)
18296 (let (ts)
18297 (save-excursion
18298 (org-back-to-heading t)
18299 (when (and org-clock-in-switch-to-state
18300 (not (looking-at (concat outline-regexp "[ \t]*"
18301 org-clock-in-switch-to-state
18302 "\\>"))))
18303 (org-todo org-clock-in-switch-to-state))
18304 (if (and org-clock-heading-function
18305 (functionp org-clock-heading-function))
18306 (setq org-clock-heading (funcall org-clock-heading-function))
18307 (if (looking-at org-complex-heading-regexp)
18308 (setq org-clock-heading (match-string 4))
18309 (setq org-clock-heading "???")))
18310 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18311 (org-clock-find-position)
18313 (insert "\n") (backward-char 1)
18314 (indent-relative)
18315 (insert org-clock-string " ")
18316 (setq org-clock-start-time (current-time))
18317 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18318 (move-marker org-clock-marker (point) (buffer-base-buffer))
18319 (or global-mode-string (setq global-mode-string '("")))
18320 (or (memq 'org-mode-line-string global-mode-string)
18321 (setq global-mode-string
18322 (append global-mode-string '(org-mode-line-string))))
18323 (org-update-mode-line)
18324 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18325 (message "Clock started at %s" ts))))
18327 (defun org-clock-find-position ()
18328 "Find the location where the next clock line should be inserted."
18329 (org-back-to-heading t)
18330 (catch 'exit
18331 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18332 (re (concat "^[ \t]*" org-clock-string))
18333 (cnt 0)
18334 first last)
18335 (goto-char beg)
18336 (when (eobp) (newline) (setq end (max (point) end)))
18337 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18338 ;; we seem to have a CLOCK drawer, so go there.
18339 (beginning-of-line 2)
18340 (throw 'exit t))
18341 ;; Lets count the CLOCK lines
18342 (goto-char beg)
18343 (while (re-search-forward re end t)
18344 (setq first (or first (match-beginning 0))
18345 last (match-beginning 0)
18346 cnt (1+ cnt)))
18347 (when (and (integerp org-clock-into-drawer)
18348 (>= (1+ cnt) org-clock-into-drawer))
18349 ;; Wrap current entries into a new drawer
18350 (goto-char last)
18351 (beginning-of-line 2)
18352 (if (org-at-item-p) (org-end-of-item))
18353 (insert ":END:\n")
18354 (beginning-of-line 0)
18355 (org-indent-line-function)
18356 (goto-char first)
18357 (insert ":CLOCK:\n")
18358 (beginning-of-line 0)
18359 (org-indent-line-function)
18360 (org-flag-drawer t)
18361 (beginning-of-line 2)
18362 (throw 'exit nil))
18364 (goto-char beg)
18365 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18366 (not (equal (match-string 1) org-clock-string)))
18367 ;; Planning info, skip to after it
18368 (beginning-of-line 2)
18369 (or (bolp) (newline)))
18370 (when (eq t org-clock-into-drawer)
18371 (insert ":CLOCK:\n:END:\n")
18372 (beginning-of-line -1)
18373 (org-indent-line-function)
18374 (org-flag-drawer t)
18375 (beginning-of-line 2)
18376 (org-indent-line-function)))))
18378 (defun org-clock-out (&optional fail-quietly)
18379 "Stop the currently running clock.
18380 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18381 (interactive)
18382 (catch 'exit
18383 (if (not (marker-buffer org-clock-marker))
18384 (if fail-quietly (throw 'exit t) (error "No active clock")))
18385 (let (ts te s h m)
18386 (save-excursion
18387 (set-buffer (marker-buffer org-clock-marker))
18388 (goto-char org-clock-marker)
18389 (beginning-of-line 1)
18390 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18391 (equal (match-string 1) org-clock-string))
18392 (setq ts (match-string 2))
18393 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18394 (goto-char (match-end 0))
18395 (delete-region (point) (point-at-eol))
18396 (insert "--")
18397 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18398 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18399 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18400 h (floor (/ s 3600))
18401 s (- s (* 3600 h))
18402 m (floor (/ s 60))
18403 s (- s (* 60 s)))
18404 (insert " => " (format "%2d:%02d" h m))
18405 (move-marker org-clock-marker nil)
18406 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18407 (org-log-done (org-parse-local-options logging 'org-log-done))
18408 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18409 (org-add-log-maybe 'clock-out))
18410 (when org-mode-line-timer
18411 (cancel-timer org-mode-line-timer)
18412 (setq org-mode-line-timer nil))
18413 (setq global-mode-string
18414 (delq 'org-mode-line-string global-mode-string))
18415 (force-mode-line-update)
18416 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18418 (defun org-clock-cancel ()
18419 "Cancel the running clock be removing the start timestamp."
18420 (interactive)
18421 (if (not (marker-buffer org-clock-marker))
18422 (error "No active clock"))
18423 (save-excursion
18424 (set-buffer (marker-buffer org-clock-marker))
18425 (goto-char org-clock-marker)
18426 (delete-region (1- (point-at-bol)) (point-at-eol)))
18427 (setq global-mode-string
18428 (delq 'org-mode-line-string global-mode-string))
18429 (force-mode-line-update)
18430 (message "Clock canceled"))
18432 (defun org-clock-goto (&optional delete-windows)
18433 "Go to the currently clocked-in entry."
18434 (interactive "P")
18435 (if (not (marker-buffer org-clock-marker))
18436 (error "No active clock"))
18437 (switch-to-buffer-other-window
18438 (marker-buffer org-clock-marker))
18439 (if delete-windows (delete-other-windows))
18440 (goto-char org-clock-marker)
18441 (org-show-entry)
18442 (org-back-to-heading)
18443 (recenter))
18445 (defvar org-clock-file-total-minutes nil
18446 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18447 (make-variable-buffer-local 'org-clock-file-total-minutes)
18449 (defun org-clock-sum (&optional tstart tend)
18450 "Sum the times for each subtree.
18451 Puts the resulting times in minutes as a text property on each headline."
18452 (interactive)
18453 (let* ((bmp (buffer-modified-p))
18454 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18455 org-clock-string
18456 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18457 (lmax 30)
18458 (ltimes (make-vector lmax 0))
18459 (t1 0)
18460 (level 0)
18461 ts te dt
18462 time)
18463 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18464 (save-excursion
18465 (goto-char (point-max))
18466 (while (re-search-backward re nil t)
18467 (cond
18468 ((match-end 2)
18469 ;; Two time stamps
18470 (setq ts (match-string 2)
18471 te (match-string 3)
18472 ts (time-to-seconds
18473 (apply 'encode-time (org-parse-time-string ts)))
18474 te (time-to-seconds
18475 (apply 'encode-time (org-parse-time-string te)))
18476 ts (if tstart (max ts tstart) ts)
18477 te (if tend (min te tend) te)
18478 dt (- te ts)
18479 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18480 ((match-end 4)
18481 ;; A naket time
18482 (setq t1 (+ t1 (string-to-number (match-string 5))
18483 (* 60 (string-to-number (match-string 4))))))
18484 (t ;; A headline
18485 (setq level (- (match-end 1) (match-beginning 1)))
18486 (when (or (> t1 0) (> (aref ltimes level) 0))
18487 (loop for l from 0 to level do
18488 (aset ltimes l (+ (aref ltimes l) t1)))
18489 (setq t1 0 time (aref ltimes level))
18490 (loop for l from level to (1- lmax) do
18491 (aset ltimes l 0))
18492 (goto-char (match-beginning 0))
18493 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18494 (setq org-clock-file-total-minutes (aref ltimes 0)))
18495 (set-buffer-modified-p bmp)))
18497 (defun org-clock-display (&optional total-only)
18498 "Show subtree times in the entire buffer.
18499 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18500 in the echo area."
18501 (interactive)
18502 (org-remove-clock-overlays)
18503 (let (time h m p)
18504 (org-clock-sum)
18505 (unless total-only
18506 (save-excursion
18507 (goto-char (point-min))
18508 (while (or (and (equal (setq p (point)) (point-min))
18509 (get-text-property p :org-clock-minutes))
18510 (setq p (next-single-property-change
18511 (point) :org-clock-minutes)))
18512 (goto-char p)
18513 (when (setq time (get-text-property p :org-clock-minutes))
18514 (org-put-clock-overlay time (funcall outline-level))))
18515 (setq h (/ org-clock-file-total-minutes 60)
18516 m (- org-clock-file-total-minutes (* 60 h)))
18517 ;; Arrange to remove the overlays upon next change.
18518 (when org-remove-highlights-with-change
18519 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18520 nil 'local))))
18521 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18523 (defvar org-clock-overlays nil)
18524 (make-variable-buffer-local 'org-clock-overlays)
18526 (defun org-put-clock-overlay (time &optional level)
18527 "Put an overlays on the current line, displaying TIME.
18528 If LEVEL is given, prefix time with a corresponding number of stars.
18529 This creates a new overlay and stores it in `org-clock-overlays', so that it
18530 will be easy to remove."
18531 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18532 (l (if level (org-get-valid-level level 0) 0))
18533 (off 0)
18534 ov tx)
18535 (move-to-column c)
18536 (unless (eolp) (skip-chars-backward "^ \t"))
18537 (skip-chars-backward " \t")
18538 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18539 tx (concat (buffer-substring (1- (point)) (point))
18540 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18541 (org-add-props (format "%s %2d:%02d%s"
18542 (make-string l ?*) h m
18543 (make-string (- 10 l) ?\ ))
18544 '(face secondary-selection))
18545 ""))
18546 (if (not (featurep 'xemacs))
18547 (org-overlay-put ov 'display tx)
18548 (org-overlay-put ov 'invisible t)
18549 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18550 (push ov org-clock-overlays)))
18552 (defun org-remove-clock-overlays (&optional beg end noremove)
18553 "Remove the occur highlights from the buffer.
18554 BEG and END are ignored. If NOREMOVE is nil, remove this function
18555 from the `before-change-functions' in the current buffer."
18556 (interactive)
18557 (unless org-inhibit-highlight-removal
18558 (mapc 'org-delete-overlay org-clock-overlays)
18559 (setq org-clock-overlays nil)
18560 (unless noremove
18561 (remove-hook 'before-change-functions
18562 'org-remove-clock-overlays 'local))))
18564 (defun org-clock-out-if-current ()
18565 "Clock out if the current entry contains the running clock.
18566 This is used to stop the clock after a TODO entry is marked DONE,
18567 and is only done if the variable `org-clock-out-when-done' is not nil."
18568 (when (and org-clock-out-when-done
18569 (member state org-done-keywords)
18570 (equal (marker-buffer org-clock-marker) (current-buffer))
18571 (< (point) org-clock-marker)
18572 (> (save-excursion (outline-next-heading) (point))
18573 org-clock-marker))
18574 ;; Clock out, but don't accept a logging message for this.
18575 (let ((org-log-done (if (and (listp org-log-done)
18576 (member 'clock-out org-log-done))
18577 '(done)
18578 org-log-done)))
18579 (org-clock-out))))
18581 (add-hook 'org-after-todo-state-change-hook
18582 'org-clock-out-if-current)
18584 (defun org-check-running-clock ()
18585 "Check if the current buffer contains the running clock.
18586 If yes, offer to stop it and to save the buffer with the changes."
18587 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18588 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18589 (buffer-name))))
18590 (org-clock-out)
18591 (when (y-or-n-p "Save changed buffer?")
18592 (save-buffer))))
18594 (defun org-clock-report (&optional arg)
18595 "Create a table containing a report about clocked time.
18596 If the cursor is inside an existing clocktable block, then the table
18597 will be updated. If not, a new clocktable will be inserted.
18598 When called with a prefix argument, move to the first clock table in the
18599 buffer and update it."
18600 (interactive "P")
18601 (org-remove-clock-overlays)
18602 (when arg (org-find-dblock "clocktable"))
18603 (if (org-in-clocktable-p)
18604 (goto-char (org-in-clocktable-p))
18605 (org-create-dblock (list :name "clocktable"
18606 :maxlevel 2 :scope 'file)))
18607 (org-update-dblock))
18609 (defun org-in-clocktable-p ()
18610 "Check if the cursor is in a clocktable."
18611 (let ((pos (point)) start)
18612 (save-excursion
18613 (end-of-line 1)
18614 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18615 (setq start (match-beginning 0))
18616 (re-search-forward "^#\\+END:.*" nil t)
18617 (>= (match-end 0) pos)
18618 start))))
18620 (defun org-clock-update-time-maybe ()
18621 "If this is a CLOCK line, update it and return t.
18622 Otherwise, return nil."
18623 (interactive)
18624 (save-excursion
18625 (beginning-of-line 1)
18626 (skip-chars-forward " \t")
18627 (when (looking-at org-clock-string)
18628 (let ((re (concat "[ \t]*" org-clock-string
18629 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18630 "\\([ \t]*=>.*\\)?"))
18631 ts te h m s)
18632 (if (not (looking-at re))
18634 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18635 (end-of-line 1)
18636 (setq ts (match-string 1)
18637 te (match-string 2))
18638 (setq s (- (time-to-seconds
18639 (apply 'encode-time (org-parse-time-string te)))
18640 (time-to-seconds
18641 (apply 'encode-time (org-parse-time-string ts))))
18642 h (floor (/ s 3600))
18643 s (- s (* 3600 h))
18644 m (floor (/ s 60))
18645 s (- s (* 60 s)))
18646 (insert " => " (format "%2d:%02d" h m))
18647 t)))))
18649 (defun org-clock-special-range (key &optional time as-strings)
18650 "Return two times bordering a special time range.
18651 Key is a symbol specifying the range and can be one of `today', `yesterday',
18652 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18653 A week starts Monday 0:00 and ends Sunday 24:00.
18654 The range is determined relative to TIME. TIME defaults to the current time.
18655 The return value is a cons cell with two internal times like the ones
18656 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18657 the returned times will be formatted strings."
18658 (let* ((tm (decode-time (or time (current-time))))
18659 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18660 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18661 (dow (nth 6 tm))
18662 s1 m1 h1 d1 month1 y1 diff ts te fm)
18663 (cond
18664 ((eq key 'today)
18665 (setq h 0 m 0 h1 24 m1 0))
18666 ((eq key 'yesterday)
18667 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18668 ((eq key 'thisweek)
18669 (setq diff (if (= dow 0) 6 (1- dow))
18670 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18671 ((eq key 'lastweek)
18672 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18673 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18674 ((eq key 'thismonth)
18675 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18676 ((eq key 'lastmonth)
18677 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18678 ((eq key 'thisyear)
18679 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18680 ((eq key 'lastyear)
18681 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18682 (t (error "No such time block %s" key)))
18683 (setq ts (encode-time s m h d month y)
18684 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18685 (or d1 d) (or month1 month) (or y1 y)))
18686 (setq fm (cdr org-time-stamp-formats))
18687 (if as-strings
18688 (cons (format-time-string fm ts) (format-time-string fm te))
18689 (cons ts te))))
18691 (defun org-dblock-write:clocktable (params)
18692 "Write the standard clocktable."
18693 (let ((hlchars '((1 . "*") (2 . "/")))
18694 (emph nil)
18695 (ins (make-marker))
18696 (total-time nil)
18697 ipos time h m p level hlc hdl maxlevel
18698 ts te cc block beg end pos scope tbl tostring multifile)
18699 (setq scope (plist-get params :scope)
18700 tostring (plist-get params :tostring)
18701 multifile (plist-get params :multifile)
18702 maxlevel (or (plist-get params :maxlevel) 3)
18703 emph (plist-get params :emphasize)
18704 ts (plist-get params :tstart)
18705 te (plist-get params :tend)
18706 block (plist-get params :block))
18707 (when block
18708 (setq cc (org-clock-special-range block nil t)
18709 ts (car cc) te (cdr cc)))
18710 (if ts (setq ts (time-to-seconds
18711 (apply 'encode-time (org-parse-time-string ts)))))
18712 (if te (setq te (time-to-seconds
18713 (apply 'encode-time (org-parse-time-string te)))))
18714 (move-marker ins (point))
18715 (setq ipos (point))
18717 ;; Get the right scope
18718 (setq pos (point))
18719 (save-restriction
18720 (cond
18721 ((not scope))
18722 ((eq scope 'file) (widen))
18723 ((eq scope 'subtree) (org-narrow-to-subtree))
18724 ((eq scope 'tree)
18725 (while (org-up-heading-safe))
18726 (org-narrow-to-subtree))
18727 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18728 (symbol-name scope)))
18729 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18730 (catch 'exit
18731 (while (org-up-heading-safe)
18732 (looking-at outline-regexp)
18733 (if (<= (org-reduced-level (funcall outline-level)) level)
18734 (throw 'exit nil))))
18735 (org-narrow-to-subtree))
18736 ((or (listp scope) (eq scope 'agenda))
18737 (let* ((files (if (listp scope) scope (org-agenda-files)))
18738 (scope 'agenda)
18739 (p1 (copy-sequence params))
18740 file)
18741 (plist-put p1 :tostring t)
18742 (plist-put p1 :multifile t)
18743 (plist-put p1 :scope 'file)
18744 (org-prepare-agenda-buffers files)
18745 (while (setq file (pop files))
18746 (with-current-buffer (find-buffer-visiting file)
18747 (push (org-clocktable-add-file
18748 file (org-dblock-write:clocktable p1)) tbl)
18749 (setq total-time (+ (or total-time 0)
18750 org-clock-file-total-minutes)))))))
18751 (goto-char pos)
18753 (unless (eq scope 'agenda)
18754 (org-clock-sum ts te)
18755 (goto-char (point-min))
18756 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18757 (goto-char p)
18758 (when (setq time (get-text-property p :org-clock-minutes))
18759 (save-excursion
18760 (beginning-of-line 1)
18761 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18762 (setq level (org-reduced-level
18763 (- (match-end 1) (match-beginning 1))))
18764 (<= level maxlevel))
18765 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18766 hdl (match-string 2)
18767 h (/ time 60)
18768 m (- time (* 60 h)))
18769 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18770 (push (concat
18771 "| " (int-to-string level) "|" hlc hdl hlc " |"
18772 (make-string (1- level) ?|)
18773 hlc (format "%d:%02d" h m) hlc
18774 " |") tbl))))))
18775 (setq tbl (nreverse tbl))
18776 (if tostring
18777 (if tbl (mapconcat 'identity tbl "\n") nil)
18778 (goto-char ins)
18779 (insert-before-markers
18780 "Clock summary at ["
18781 (substring
18782 (format-time-string (cdr org-time-stamp-formats))
18783 1 -1)
18784 "]."
18785 (if block
18786 (format " Considered range is /%s/." block)
18788 "\n\n"
18789 (if (eq scope 'agenda) "|File" "")
18790 "|L|Headline|Time|\n")
18791 (setq total-time (or total-time org-clock-file-total-minutes)
18792 h (/ total-time 60)
18793 m (- total-time (* 60 h)))
18794 (insert-before-markers
18795 "|-\n|"
18796 (if (eq scope 'agenda) "|" "")
18798 "*Total time*| "
18799 (format "*%d:%02d*" h m)
18800 "|\n|-\n")
18801 (setq tbl (delq nil tbl))
18802 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
18803 (equal (substring (car tbl) 0 2) "|-"))
18804 (pop tbl))
18805 (insert-before-markers (mapconcat
18806 'identity (delq nil tbl)
18807 (if (eq scope 'agenda) "\n|-\n" "\n")))
18808 (backward-delete-char 1)
18809 (goto-char ipos)
18810 (skip-chars-forward "^|")
18811 (org-table-align)))))
18813 (defun org-clocktable-add-file (file table)
18814 (if table
18815 (let ((lines (org-split-string table "\n"))
18816 (ff (file-name-nondirectory file)))
18817 (mapconcat 'identity
18818 (mapcar (lambda (x)
18819 (if (string-match org-table-dataline-regexp x)
18820 (concat "|" ff x)
18822 lines)
18823 "\n"))))
18825 ;; FIXME: I don't think anybody uses this, ask David
18826 (defun org-collect-clock-time-entries ()
18827 "Return an internal list with clocking information.
18828 This list has one entry for each CLOCK interval.
18829 FIXME: describe the elements."
18830 (interactive)
18831 (let ((re (concat "^[ \t]*" org-clock-string
18832 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
18833 rtn beg end next cont level title total closedp leafp
18834 clockpos titlepos h m donep)
18835 (save-excursion
18836 (org-clock-sum)
18837 (goto-char (point-min))
18838 (while (re-search-forward re nil t)
18839 (setq clockpos (match-beginning 0)
18840 beg (match-string 1) end (match-string 2)
18841 cont (match-end 0))
18842 (setq beg (apply 'encode-time (org-parse-time-string beg))
18843 end (apply 'encode-time (org-parse-time-string end)))
18844 (org-back-to-heading t)
18845 (setq donep (org-entry-is-done-p))
18846 (setq titlepos (point)
18847 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
18848 h (/ total 60) m (- total (* 60 h))
18849 total (cons h m))
18850 (looking-at "\\(\\*+\\) +\\(.*\\)")
18851 (setq level (- (match-end 1) (match-beginning 1))
18852 title (org-match-string-no-properties 2))
18853 (save-excursion (outline-next-heading) (setq next (point)))
18854 (setq closedp (re-search-forward org-closed-time-regexp next t))
18855 (goto-char next)
18856 (setq leafp (and (looking-at "^\\*+ ")
18857 (<= (- (match-end 0) (point)) level)))
18858 (push (list beg end clockpos closedp donep
18859 total title titlepos level leafp)
18860 rtn)
18861 (goto-char cont)))
18862 (nreverse rtn)))
18864 ;;;; Agenda, and Diary Integration
18866 ;;; Define the Org-agenda-mode
18868 (defvar org-agenda-mode-map (make-sparse-keymap)
18869 "Keymap for `org-agenda-mode'.")
18871 (defvar org-agenda-menu) ; defined later in this file.
18872 (defvar org-agenda-follow-mode nil)
18873 (defvar org-agenda-show-log nil)
18874 (defvar org-agenda-redo-command nil)
18875 (defvar org-agenda-mode-hook nil)
18876 (defvar org-agenda-type nil)
18877 (defvar org-agenda-force-single-file nil)
18879 (defun org-agenda-mode ()
18880 "Mode for time-sorted view on action items in Org-mode files.
18882 The following commands are available:
18884 \\{org-agenda-mode-map}"
18885 (interactive)
18886 (kill-all-local-variables)
18887 (setq org-agenda-undo-list nil
18888 org-agenda-pending-undo-list nil)
18889 (setq major-mode 'org-agenda-mode)
18890 ;; Keep global-font-lock-mode from turning on font-lock-mode
18891 (org-set-local 'font-lock-global-modes (list 'not major-mode))
18892 (setq mode-name "Org-Agenda")
18893 (use-local-map org-agenda-mode-map)
18894 (easy-menu-add org-agenda-menu)
18895 (if org-startup-truncated (setq truncate-lines t))
18896 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
18897 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
18898 ;; Make sure properties are removed when copying text
18899 (when (boundp 'buffer-substring-filters)
18900 (org-set-local 'buffer-substring-filters
18901 (cons (lambda (x)
18902 (set-text-properties 0 (length x) nil x) x)
18903 buffer-substring-filters)))
18904 (unless org-agenda-keep-modes
18905 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
18906 org-agenda-show-log nil))
18907 (easy-menu-change
18908 '("Agenda") "Agenda Files"
18909 (append
18910 (list
18911 (vector
18912 (if (get 'org-agenda-files 'org-restrict)
18913 "Restricted to single file"
18914 "Edit File List")
18915 '(org-edit-agenda-file-list)
18916 (not (get 'org-agenda-files 'org-restrict)))
18917 "--")
18918 (mapcar 'org-file-menu-entry (org-agenda-files))))
18919 (org-agenda-set-mode-name)
18920 (apply
18921 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
18922 (list 'org-agenda-mode-hook)))
18924 (substitute-key-definition 'undo 'org-agenda-undo
18925 org-agenda-mode-map global-map)
18926 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
18927 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
18928 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
18929 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
18930 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
18931 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
18932 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
18933 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
18934 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
18935 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
18936 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
18937 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
18938 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
18939 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
18940 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
18941 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
18942 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
18943 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
18944 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
18945 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
18946 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
18947 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
18948 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
18949 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
18950 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
18951 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
18952 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
18953 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
18954 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
18956 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
18957 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
18958 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
18959 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
18960 (while l (org-defkey org-agenda-mode-map
18961 (int-to-string (pop l)) 'digit-argument)))
18963 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
18964 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
18965 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
18966 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
18967 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
18968 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
18969 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
18970 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
18971 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
18972 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
18973 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
18974 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
18975 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
18976 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
18977 (org-defkey org-agenda-mode-map "n" 'next-line)
18978 (org-defkey org-agenda-mode-map "p" 'previous-line)
18979 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
18980 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
18981 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
18982 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
18983 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
18984 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
18985 (eval-after-load "calendar"
18986 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
18987 'org-calendar-goto-agenda))
18988 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
18989 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
18990 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
18991 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
18992 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
18993 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
18994 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
18995 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
18996 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
18997 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
18998 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
18999 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19000 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19001 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19002 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19003 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19004 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19005 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19006 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19007 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19008 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19009 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19011 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19012 "Local keymap for agenda entries from Org-mode.")
19014 (org-defkey org-agenda-keymap
19015 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19016 (org-defkey org-agenda-keymap
19017 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19018 (when org-agenda-mouse-1-follows-link
19019 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19020 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19021 '("Agenda"
19022 ("Agenda Files")
19023 "--"
19024 ["Show" org-agenda-show t]
19025 ["Go To (other window)" org-agenda-goto t]
19026 ["Go To (this window)" org-agenda-switch-to t]
19027 ["Follow Mode" org-agenda-follow-mode
19028 :style toggle :selected org-agenda-follow-mode :active t]
19029 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19030 "--"
19031 ["Cycle TODO" org-agenda-todo t]
19032 ["Archive subtree" org-agenda-archive t]
19033 ["Delete subtree" org-agenda-kill t]
19034 "--"
19035 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19036 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19037 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19038 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19039 "--"
19040 ("Tags and Properties"
19041 ["Show all Tags" org-agenda-show-tags t]
19042 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19043 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19044 "--"
19045 ["Column View" org-columns t])
19046 ("Date/Schedule"
19047 ["Schedule" org-agenda-schedule t]
19048 ["Set Deadline" org-agenda-deadline t]
19049 "--"
19050 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19051 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19052 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19053 ("Clock"
19054 ["Clock in" org-agenda-clock-in t]
19055 ["Clock out" org-agenda-clock-out t]
19056 ["Clock cancel" org-agenda-clock-cancel t]
19057 ["Goto running clock" org-clock-goto t])
19058 ("Priority"
19059 ["Set Priority" org-agenda-priority t]
19060 ["Increase Priority" org-agenda-priority-up t]
19061 ["Decrease Priority" org-agenda-priority-down t]
19062 ["Show Priority" org-agenda-show-priority t])
19063 ("Calendar/Diary"
19064 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19065 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19066 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19067 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19068 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19069 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19070 "--"
19071 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19072 "--"
19073 ("View"
19074 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19075 :style radio :selected (equal org-agenda-ndays 1)]
19076 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19077 :style radio :selected (equal org-agenda-ndays 7)]
19078 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19079 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19080 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19081 :style radio :selected (member org-agenda-ndays '(365 366))]
19082 "--"
19083 ["Show Logbook entries" org-agenda-log-mode
19084 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19085 ["Include Diary" org-agenda-toggle-diary
19086 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19087 ["Use Time Grid" org-agenda-toggle-time-grid
19088 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19089 ["Write view to file" org-write-agenda t]
19090 ["Rebuild buffer" org-agenda-redo t]
19091 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19092 "--"
19093 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19094 "--"
19095 ["Quit" org-agenda-quit t]
19096 ["Exit and Release Buffers" org-agenda-exit t]
19099 ;;; Agenda undo
19101 (defvar org-agenda-allow-remote-undo t
19102 "Non-nil means, allow remote undo from the agenda buffer.")
19103 (defvar org-agenda-undo-list nil
19104 "List of undoable operations in the agenda since last refresh.")
19105 (defvar org-agenda-undo-has-started-in nil
19106 "Buffers that have already seen `undo-start' in the current undo sequence.")
19107 (defvar org-agenda-pending-undo-list nil
19108 "In a series of undo commands, this is the list of remaning undo items.")
19110 (defmacro org-if-unprotected (&rest body)
19111 "Execute BODY if there is no `org-protected' text property at point."
19112 (declare (debug t))
19113 `(unless (get-text-property (point) 'org-protected)
19114 ,@body))
19116 (defmacro org-with-remote-undo (_buffer &rest _body)
19117 "Execute BODY while recording undo information in two buffers."
19118 (declare (indent 1) (debug t))
19119 `(let ((_cline (org-current-line))
19120 (_cmd this-command)
19121 (_buf1 (current-buffer))
19122 (_buf2 ,_buffer)
19123 (_undo1 buffer-undo-list)
19124 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19125 _c1 _c2)
19126 ,@_body
19127 (when org-agenda-allow-remote-undo
19128 (setq _c1 (org-verify-change-for-undo
19129 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19130 _c2 (org-verify-change-for-undo
19131 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19132 (when (or _c1 _c2)
19133 ;; make sure there are undo boundaries
19134 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19135 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19136 ;; remember which buffer to undo
19137 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19138 org-agenda-undo-list)))))
19140 (defun org-agenda-undo ()
19141 "Undo a remote editing step in the agenda.
19142 This undoes changes both in the agenda buffer and in the remote buffer
19143 that have been changed along."
19144 (interactive)
19145 (or org-agenda-allow-remote-undo
19146 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19147 (if (not (eq this-command last-command))
19148 (setq org-agenda-undo-has-started-in nil
19149 org-agenda-pending-undo-list org-agenda-undo-list))
19150 (if (not org-agenda-pending-undo-list)
19151 (error "No further undo information"))
19152 (let* ((entry (pop org-agenda-pending-undo-list))
19153 buf line cmd rembuf)
19154 (setq cmd (pop entry) line (pop entry))
19155 (setq rembuf (nth 2 entry))
19156 (org-with-remote-undo rembuf
19157 (while (bufferp (setq buf (pop entry)))
19158 (if (pop entry)
19159 (with-current-buffer buf
19160 (let ((last-undo-buffer buf)
19161 (inhibit-read-only t))
19162 (unless (memq buf org-agenda-undo-has-started-in)
19163 (push buf org-agenda-undo-has-started-in)
19164 (make-local-variable 'pending-undo-list)
19165 (undo-start))
19166 (while (and pending-undo-list
19167 (listp pending-undo-list)
19168 (not (car pending-undo-list)))
19169 (pop pending-undo-list))
19170 (undo-more 1))))))
19171 (goto-line line)
19172 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19174 (defun org-verify-change-for-undo (l1 l2)
19175 "Verify that a real change occurred between the undo lists L1 and L2."
19176 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19177 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19178 (not (eq l1 l2)))
19180 ;;; Agenda dispatch
19182 (defvar org-agenda-restrict nil)
19183 (defvar org-agenda-restrict-begin (make-marker))
19184 (defvar org-agenda-restrict-end (make-marker))
19185 (defvar org-agenda-last-dispatch-buffer nil)
19186 (defvar org-agenda-overriding-restriction nil)
19188 ;;;###autoload
19189 (defun org-agenda (arg &optional keys restriction)
19190 "Dispatch agenda commands to collect entries to the agenda buffer.
19191 Prompts for a command to execute. Any prefix arg will be passed
19192 on to the selected command. The default selections are:
19194 a Call `org-agenda-list' to display the agenda for current day or week.
19195 t Call `org-todo-list' to display the global todo list.
19196 T Call `org-todo-list' to display the global todo list, select only
19197 entries with a specific TODO keyword (the user gets a prompt).
19198 m Call `org-tags-view' to display headlines with tags matching
19199 a condition (the user is prompted for the condition).
19200 M Like `m', but select only TODO entries, no ordinary headlines.
19201 L Create a timeline for the current buffer.
19202 e Export views to associated files.
19204 More commands can be added by configuring the variable
19205 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19206 searches can be pre-defined in this way.
19208 If the current buffer is in Org-mode and visiting a file, you can also
19209 first press `<' once to indicate that the agenda should be temporarily
19210 \(until the next use of \\[org-agenda]) restricted to the current file.
19211 Pressing `<' twice means to restrict to the current subtree or region
19212 \(if active)."
19213 (interactive "P")
19214 (catch 'exit
19215 (let* ((prefix-descriptions nil)
19216 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19217 (org-agenda-custom-commands
19218 ;; normalize different versions
19219 (delq nil
19220 (mapcar
19221 (lambda (x)
19222 (cond ((stringp (cdr x))
19223 (push x prefix-descriptions)
19224 nil)
19225 ((stringp (nth 1 x)) x)
19226 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19227 (t (cons (car x) (cons "" (cdr x))))))
19228 org-agenda-custom-commands)))
19229 (buf (current-buffer))
19230 (bfn (buffer-file-name (buffer-base-buffer)))
19231 entry key type match lprops ans)
19232 ;; Turn off restriction unless there is an overriding one
19233 (unless org-agenda-overriding-restriction
19234 (put 'org-agenda-files 'org-restrict nil)
19235 (setq org-agenda-restrict nil)
19236 (move-marker org-agenda-restrict-begin nil)
19237 (move-marker org-agenda-restrict-end nil))
19238 ;; Delete old local properties
19239 (put 'org-agenda-redo-command 'org-lprops nil)
19240 ;; Remember where this call originated
19241 (setq org-agenda-last-dispatch-buffer (current-buffer))
19242 (unless keys
19243 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19244 keys (car ans)
19245 restriction (cdr ans)))
19246 ;; Estabish the restriction, if any
19247 (when (and (not org-agenda-overriding-restriction) restriction)
19248 (put 'org-agenda-files 'org-restrict (list bfn))
19249 (cond
19250 ((eq restriction 'region)
19251 (setq org-agenda-restrict t)
19252 (move-marker org-agenda-restrict-begin (region-beginning))
19253 (move-marker org-agenda-restrict-end (region-end)))
19254 ((eq restriction 'subtree)
19255 (save-excursion
19256 (setq org-agenda-restrict t)
19257 (org-back-to-heading t)
19258 (move-marker org-agenda-restrict-begin (point))
19259 (move-marker org-agenda-restrict-end
19260 (progn (org-end-of-subtree t)))))))
19262 (require 'calendar) ; FIXME: can we avoid this for some commands?
19263 ;; For example the todo list should not need it (but does...)
19264 (cond
19265 ((setq entry (assoc keys org-agenda-custom-commands))
19266 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19267 (progn
19268 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19269 (put 'org-agenda-redo-command 'org-lprops lprops)
19270 (cond
19271 ((eq type 'agenda)
19272 (org-let lprops '(org-agenda-list current-prefix-arg)))
19273 ((eq type 'alltodo)
19274 (org-let lprops '(org-todo-list current-prefix-arg)))
19275 ((eq type 'stuck)
19276 (org-let lprops '(org-agenda-list-stuck-projects
19277 current-prefix-arg)))
19278 ((eq type 'tags)
19279 (org-let lprops '(org-tags-view current-prefix-arg match)))
19280 ((eq type 'tags-todo)
19281 (org-let lprops '(org-tags-view '(4) match)))
19282 ((eq type 'todo)
19283 (org-let lprops '(org-todo-list match)))
19284 ((eq type 'tags-tree)
19285 (org-check-for-org-mode)
19286 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19287 ((eq type 'todo-tree)
19288 (org-check-for-org-mode)
19289 (org-let lprops
19290 '(org-occur (concat "^" outline-regexp "[ \t]*"
19291 (regexp-quote match) "\\>"))))
19292 ((eq type 'occur-tree)
19293 (org-check-for-org-mode)
19294 (org-let lprops '(org-occur match)))
19295 ((functionp type)
19296 (org-let lprops '(funcall type match)))
19297 ((fboundp type)
19298 (org-let lprops '(funcall type match)))
19299 (t (error "Invalid custom agenda command type %s" type))))
19300 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19301 ((equal keys "C")
19302 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19303 (customize-variable 'org-agenda-custom-commands))
19304 ((equal keys "a") (call-interactively 'org-agenda-list))
19305 ((equal keys "t") (call-interactively 'org-todo-list))
19306 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19307 ((equal keys "m") (call-interactively 'org-tags-view))
19308 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19309 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19310 ((equal keys "L")
19311 (unless (org-mode-p)
19312 (error "This is not an Org-mode file"))
19313 (unless restriction
19314 (put 'org-agenda-files 'org-restrict (list bfn))
19315 (org-call-with-arg 'org-timeline arg)))
19316 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19317 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19318 ((equal keys "!") (customize-variable 'org-stuck-projects))
19319 (t (error "Invalid agenda key"))))))
19321 (defun org-agenda-normalize-custom-commands (cmds)
19322 (delq nil
19323 (mapcar
19324 (lambda (x)
19325 (cond ((stringp (cdr x)) nil)
19326 ((stringp (nth 1 x)) x)
19327 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19328 (t (cons (car x) (cons "" (cdr x))))))
19329 cmds)))
19331 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19332 "The user interface for selecting an agenda command."
19333 (catch 'exit
19334 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19335 (restrict-ok (and bfn (org-mode-p)))
19336 (region-p (org-region-active-p))
19337 (custom org-agenda-custom-commands)
19338 (selstring "")
19339 restriction second-time
19340 c entry key type match prefixes rmheader header-end custom1 desc)
19341 (save-window-excursion
19342 (delete-other-windows)
19343 (org-switch-to-buffer-other-window " *Agenda Commands*")
19344 (erase-buffer)
19345 (insert (eval-when-compile
19346 (let ((header
19348 Press key for an agenda command: < Buffer,subtree/region restriction
19349 -------------------------------- > Remove restriction
19350 a Agenda for current week or day e Export agenda views
19351 t List of all TODO entries T Entries with special TODO kwd
19352 m Match a TAGS query M Like m, but only TODO entries
19353 L Timeline for current buffer # List stuck projects (!=configure)
19354 / Multi-occur C Configure custom agenda commands
19356 (start 0))
19357 (while (string-match
19358 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19359 header start)
19360 (setq start (match-end 0))
19361 (add-text-properties (match-beginning 2) (match-end 2)
19362 '(face bold) header))
19363 header)))
19364 (setq header-end (move-marker (make-marker) (point)))
19365 (while t
19366 (setq custom1 custom)
19367 (when (eq rmheader t)
19368 (goto-line 1)
19369 (re-search-forward ":" nil t)
19370 (delete-region (match-end 0) (point-at-eol))
19371 (forward-char 1)
19372 (looking-at "-+")
19373 (delete-region (match-end 0) (point-at-eol))
19374 (move-marker header-end (match-end 0)))
19375 (goto-char header-end)
19376 (delete-region (point) (point-max))
19377 (while (setq entry (pop custom1))
19378 (setq key (car entry) desc (nth 1 entry)
19379 type (nth 2 entry) match (nth 3 entry))
19380 (if (> (length key) 1)
19381 (add-to-list 'prefixes (string-to-char key))
19382 (insert
19383 (format
19384 "\n%-4s%-14s: %s"
19385 (org-add-props (copy-sequence key)
19386 '(face bold))
19387 (cond
19388 ((string-match "\\S-" desc) desc)
19389 ((eq type 'agenda) "Agenda for current week or day")
19390 ((eq type 'alltodo) "List of all TODO entries")
19391 ((eq type 'stuck) "List of stuck projects")
19392 ((eq type 'todo) "TODO keyword")
19393 ((eq type 'tags) "Tags query")
19394 ((eq type 'tags-todo) "Tags (TODO)")
19395 ((eq type 'tags-tree) "Tags tree")
19396 ((eq type 'todo-tree) "TODO kwd tree")
19397 ((eq type 'occur-tree) "Occur tree")
19398 ((functionp type) (if (symbolp type)
19399 (symbol-name type)
19400 "Lambda expression"))
19401 (t "???"))
19402 (cond
19403 ((stringp match)
19404 (org-add-props match nil 'face 'org-warning))
19405 (match
19406 (format "set of %d commands" (length match)))
19407 (t ""))))))
19408 (when prefixes
19409 (mapc (lambda (x)
19410 (insert
19411 (format "\n%s %s"
19412 (org-add-props (char-to-string x)
19413 nil 'face 'bold)
19414 (or (cdr (assoc (concat selstring (char-to-string x))
19415 prefix-descriptions))
19416 "Prefix key"))))
19417 prefixes))
19418 (goto-char (point-min))
19419 (when (fboundp 'fit-window-to-buffer)
19420 (if second-time
19421 (if (not (pos-visible-in-window-p (point-max)))
19422 (fit-window-to-buffer))
19423 (setq second-time t)
19424 (fit-window-to-buffer)))
19425 (message "Press key for agenda command%s:"
19426 (if (or restrict-ok org-agenda-overriding-restriction)
19427 (if org-agenda-overriding-restriction
19428 " (restriction lock active)"
19429 (if restriction
19430 (format " (restricted to %s)" restriction)
19431 " (unrestricted)"))
19432 ""))
19433 (setq c (read-char-exclusive))
19434 (message "")
19435 (cond
19436 ((assoc (char-to-string c) custom)
19437 (setq selstring (concat selstring (char-to-string c)))
19438 (throw 'exit (cons selstring restriction)))
19439 ((memq c prefixes)
19440 (setq selstring (concat selstring (char-to-string c))
19441 prefixes nil
19442 rmheader (or rmheader t)
19443 custom (delq nil (mapcar
19444 (lambda (x)
19445 (if (or (= (length (car x)) 1)
19446 (/= (string-to-char (car x)) c))
19448 (cons (substring (car x) 1) (cdr x))))
19449 custom))))
19450 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19451 (message "Restriction is only possible in Org-mode buffers")
19452 (ding) (sit-for 1))
19453 ((eq c ?1)
19454 (org-agenda-remove-restriction-lock 'noupdate)
19455 (setq restriction 'buffer))
19456 ((eq c ?0)
19457 (org-agenda-remove-restriction-lock 'noupdate)
19458 (setq restriction (if region-p 'region 'subtree)))
19459 ((eq c ?<)
19460 (org-agenda-remove-restriction-lock 'noupdate)
19461 (setq restriction
19462 (cond
19463 ((eq restriction 'buffer)
19464 (if region-p 'region 'subtree))
19465 ((memq restriction '(subtree region))
19466 nil)
19467 (t 'buffer))))
19468 ((eq c ?>)
19469 (org-agenda-remove-restriction-lock 'noupdate)
19470 (setq restriction nil))
19471 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19472 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19473 ((and (> (length selstring) 0) (eq c ?\d))
19474 (delete-window)
19475 (org-agenda-get-restriction-and-command prefix-descriptions))
19477 ((equal c ?q) (error "Abort"))
19478 (t (error "Invalid key %c" c))))))))
19480 (defun org-run-agenda-series (name series)
19481 (org-prepare-agenda name)
19482 (let* ((org-agenda-multi t)
19483 (redo (list 'org-run-agenda-series name (list 'quote series)))
19484 (cmds (car series))
19485 (gprops (nth 1 series))
19486 match ;; The byte compiler incorrectly complains about this. Keep it!
19487 cmd type lprops)
19488 (while (setq cmd (pop cmds))
19489 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19490 (cond
19491 ((eq type 'agenda)
19492 (org-let2 gprops lprops
19493 '(call-interactively 'org-agenda-list)))
19494 ((eq type 'alltodo)
19495 (org-let2 gprops lprops
19496 '(call-interactively 'org-todo-list)))
19497 ((eq type 'stuck)
19498 (org-let2 gprops lprops
19499 '(call-interactively 'org-agenda-list-stuck-projects)))
19500 ((eq type 'tags)
19501 (org-let2 gprops lprops
19502 '(org-tags-view current-prefix-arg match)))
19503 ((eq type 'tags-todo)
19504 (org-let2 gprops lprops
19505 '(org-tags-view '(4) match)))
19506 ((eq type 'todo)
19507 (org-let2 gprops lprops
19508 '(org-todo-list match)))
19509 ((fboundp type)
19510 (org-let2 gprops lprops
19511 '(funcall type match)))
19512 (t (error "Invalid type in command series"))))
19513 (widen)
19514 (setq org-agenda-redo-command redo)
19515 (goto-char (point-min)))
19516 (org-finalize-agenda))
19518 ;;;###autoload
19519 (defmacro org-batch-agenda (cmd-key &rest parameters)
19520 "Run an agenda command in batch mode and send the result to STDOUT.
19521 If CMD-KEY is a string of length 1, it is used as a key in
19522 `org-agenda-custom-commands' and triggers this command. If it is a
19523 longer string it is used as a tags/todo match string.
19524 Paramters are alternating variable names and values that will be bound
19525 before running the agenda command."
19526 (let (pars)
19527 (while parameters
19528 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19529 (if (> (length cmd-key) 2)
19530 (eval (list 'let (nreverse pars)
19531 (list 'org-tags-view nil cmd-key)))
19532 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19533 (set-buffer org-agenda-buffer-name)
19534 (princ (org-encode-for-stdout (buffer-string)))))
19536 (defun org-encode-for-stdout (string)
19537 (if (fboundp 'encode-coding-string)
19538 (encode-coding-string string buffer-file-coding-system)
19539 string))
19541 (defvar org-agenda-info nil)
19543 ;;;###autoload
19544 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19545 "Run an agenda command in batch mode and send the result to STDOUT.
19546 If CMD-KEY is a string of length 1, it is used as a key in
19547 `org-agenda-custom-commands' and triggers this command. If it is a
19548 longer string it is used as a tags/todo match string.
19549 Paramters are alternating variable names and values that will be bound
19550 before running the agenda command.
19552 The output gives a line for each selected agenda item. Each
19553 item is a list of comma-separated values, like this:
19555 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19557 category The category of the item
19558 head The headline, without TODO kwd, TAGS and PRIORITY
19559 type The type of the agenda entry, can be
19560 todo selected in TODO match
19561 tagsmatch selected in tags match
19562 diary imported from diary
19563 deadline a deadline on given date
19564 scheduled scheduled on given date
19565 timestamp entry has timestamp on given date
19566 closed entry was closed on given date
19567 upcoming-deadline warning about deadline
19568 past-scheduled forwarded scheduled item
19569 block entry has date block including g. date
19570 todo The todo keyword, if any
19571 tags All tags including inherited ones, separated by colons
19572 date The relevant date, like 2007-2-14
19573 time The time, like 15:00-16:50
19574 extra Sting with extra planning info
19575 priority-l The priority letter if any was given
19576 priority-n The computed numerical priority
19577 agenda-day The day in the agenda where this is listed"
19579 (let (pars)
19580 (while parameters
19581 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19582 (push (list 'org-agenda-remove-tags t) pars)
19583 (if (> (length cmd-key) 2)
19584 (eval (list 'let (nreverse pars)
19585 (list 'org-tags-view nil cmd-key)))
19586 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19587 (set-buffer org-agenda-buffer-name)
19588 (let* ((lines (org-split-string (buffer-string) "\n"))
19589 line)
19590 (while (setq line (pop lines))
19591 (catch 'next
19592 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19593 (setq org-agenda-info
19594 (org-fix-agenda-info (text-properties-at 0 line)))
19595 (princ
19596 (org-encode-for-stdout
19597 (mapconcat 'org-agenda-export-csv-mapper
19598 '(org-category txt type todo tags date time-of-day extra
19599 priority-letter priority agenda-day)
19600 ",")))
19601 (princ "\n"))))))
19603 (defun org-fix-agenda-info (props)
19604 "Make sure all properties on an agenda item have a canonical form,
19605 so the export commands can easily use it."
19606 (let (tmp re)
19607 (when (setq tmp (plist-get props 'tags))
19608 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19609 (when (setq tmp (plist-get props 'date))
19610 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19611 (let ((calendar-date-display-form '(year "-" month "-" day)))
19612 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19614 (setq tmp (calendar-date-string tmp)))
19615 (setq props (plist-put props 'date tmp)))
19616 (when (setq tmp (plist-get props 'day))
19617 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19618 (let ((calendar-date-display-form '(year "-" month "-" day)))
19619 (setq tmp (calendar-date-string tmp)))
19620 (setq props (plist-put props 'day tmp))
19621 (setq props (plist-put props 'agenda-day tmp)))
19622 (when (setq tmp (plist-get props 'txt))
19623 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19624 (plist-put props 'priority-letter (match-string 1 tmp))
19625 (setq tmp (replace-match "" t t tmp)))
19626 (when (and (setq re (plist-get props 'org-todo-regexp))
19627 (setq re (concat "\\`\\.*" re " ?"))
19628 (string-match re tmp))
19629 (plist-put props 'todo (match-string 1 tmp))
19630 (setq tmp (replace-match "" t t tmp)))
19631 (plist-put props 'txt tmp)))
19632 props)
19634 (defun org-agenda-export-csv-mapper (prop)
19635 (let ((res (plist-get org-agenda-info prop)))
19636 (setq res
19637 (cond
19638 ((not res) "")
19639 ((stringp res) res)
19640 (t (prin1-to-string res))))
19641 (while (string-match "," res)
19642 (setq res (replace-match ";" t t res)))
19643 (org-trim res)))
19646 ;;;###autoload
19647 (defun org-store-agenda-views (&rest parameters)
19648 (interactive)
19649 (eval (list 'org-batch-store-agenda-views)))
19651 ;; FIXME, why is this a macro?????
19652 ;;;###autoload
19653 (defmacro org-batch-store-agenda-views (&rest parameters)
19654 "Run all custom agenda commands that have a file argument."
19655 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19656 (pop-up-frames nil)
19657 (dir default-directory)
19658 pars cmd thiscmdkey files opts)
19659 (while parameters
19660 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19661 (setq pars (reverse pars))
19662 (save-window-excursion
19663 (while cmds
19664 (setq cmd (pop cmds)
19665 thiscmdkey (car cmd)
19666 opts (nth 4 cmd)
19667 files (nth 5 cmd))
19668 (if (stringp files) (setq files (list files)))
19669 (when files
19670 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19671 (list 'org-agenda nil thiscmdkey)))
19672 (set-buffer org-agenda-buffer-name)
19673 (while files
19674 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19675 (list 'org-write-agenda
19676 (expand-file-name (pop files) dir) t))))
19677 (and (get-buffer org-agenda-buffer-name)
19678 (kill-buffer org-agenda-buffer-name)))))))
19680 (defun org-write-agenda (file &optional nosettings)
19681 "Write the current buffer (an agenda view) as a file.
19682 Depending on the extension of the file name, plain text (.txt),
19683 HTML (.html or .htm) or Postscript (.ps) is produced.
19684 If NOSETTINGS is given, do not scope the settings of
19685 `org-agenda-exporter-settings' into the export commands. This is used when
19686 the settings have already been scoped and we do not wish to overrule other,
19687 higher priority settings."
19688 (interactive "FWrite agenda to file: ")
19689 (if (not (file-writable-p file))
19690 (error "Cannot write agenda to file %s" file))
19691 (cond
19692 ((string-match "\\.html?\\'" file) (require 'htmlize))
19693 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19694 (org-let (if nosettings nil org-agenda-exporter-settings)
19695 '(save-excursion
19696 (save-window-excursion
19697 (cond
19698 ((string-match "\\.html?\\'" file)
19699 (set-buffer (htmlize-buffer (current-buffer)))
19701 (when (and org-agenda-export-html-style
19702 (string-match "<style>" org-agenda-export-html-style))
19703 ;; replace <style> section with org-agenda-export-html-style
19704 (goto-char (point-min))
19705 (kill-region (- (search-forward "<style") 6)
19706 (search-forward "</style>"))
19707 (insert org-agenda-export-html-style))
19708 (write-file file)
19709 (kill-buffer (current-buffer))
19710 (message "HTML written to %s" file))
19711 ((string-match "\\.ps\\'" file)
19712 (ps-print-buffer-with-faces file)
19713 (message "Postscript written to %s" file))
19715 (let ((bs (buffer-string)))
19716 (find-file file)
19717 (insert bs)
19718 (save-buffer 0)
19719 (kill-buffer (current-buffer))
19720 (message "Plain text written to %s" file))))))
19721 (set-buffer org-agenda-buffer-name)))
19723 (defmacro org-no-read-only (&rest body)
19724 "Inhibit read-only for BODY."
19725 `(let ((inhibit-read-only t)) ,@body))
19727 (defun org-check-for-org-mode ()
19728 "Make sure current buffer is in org-mode. Error if not."
19729 (or (org-mode-p)
19730 (error "Cannot execute org-mode agenda command on buffer in %s."
19731 major-mode)))
19733 (defun org-fit-agenda-window ()
19734 "Fit the window to the buffer size."
19735 (and (memq org-agenda-window-setup '(reorganize-frame))
19736 (fboundp 'fit-window-to-buffer)
19737 (fit-window-to-buffer
19739 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19740 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19742 ;;; Agenda file list
19744 (defun org-agenda-files (&optional unrestricted)
19745 "Get the list of agenda files.
19746 Optional UNRESTRICTED means return the full list even if a restriction
19747 is currently in place."
19748 (let ((files
19749 (cond
19750 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19751 ((stringp org-agenda-files) (org-read-agenda-file-list))
19752 ((listp org-agenda-files) org-agenda-files)
19753 (t (error "Invalid value of `org-agenda-files'")))))
19754 (setq files (apply 'append
19755 (mapcar (lambda (f)
19756 (if (file-directory-p f)
19757 (directory-files f t
19758 org-agenda-file-regexp)
19759 (list f)))
19760 files)))
19761 (if org-agenda-skip-unavailable-files
19762 (delq nil
19763 (mapcar (function
19764 (lambda (file)
19765 (and (file-readable-p file) file)))
19766 files))
19767 files))) ; `org-check-agenda-file' will remove them from the list
19769 (defun org-edit-agenda-file-list ()
19770 "Edit the list of agenda files.
19771 Depending on setup, this either uses customize to edit the variable
19772 `org-agenda-files', or it visits the file that is holding the list. In the
19773 latter case, the buffer is set up in a way that saving it automatically kills
19774 the buffer and restores the previous window configuration."
19775 (interactive)
19776 (if (stringp org-agenda-files)
19777 (let ((cw (current-window-configuration)))
19778 (find-file org-agenda-files)
19779 (org-set-local 'org-window-configuration cw)
19780 (org-add-hook 'after-save-hook
19781 (lambda ()
19782 (set-window-configuration
19783 (prog1 org-window-configuration
19784 (kill-buffer (current-buffer))))
19785 (org-install-agenda-files-menu)
19786 (message "New agenda file list installed"))
19787 nil 'local)
19788 (message "%s" (substitute-command-keys
19789 "Edit list and finish with \\[save-buffer]")))
19790 (customize-variable 'org-agenda-files)))
19792 (defun org-store-new-agenda-file-list (list)
19793 "Set new value for the agenda file list and save it correcly."
19794 (if (stringp org-agenda-files)
19795 (let ((f org-agenda-files) b)
19796 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
19797 (with-temp-file f
19798 (insert (mapconcat 'identity list "\n") "\n")))
19799 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
19800 (setq org-agenda-files list)
19801 (customize-save-variable 'org-agenda-files org-agenda-files))))
19803 (defun org-read-agenda-file-list ()
19804 "Read the list of agenda files from a file."
19805 (when (stringp org-agenda-files)
19806 (with-temp-buffer
19807 (insert-file-contents org-agenda-files)
19808 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
19811 ;;;###autoload
19812 (defun org-cycle-agenda-files ()
19813 "Cycle through the files in `org-agenda-files'.
19814 If the current buffer visits an agenda file, find the next one in the list.
19815 If the current buffer does not, find the first agenda file."
19816 (interactive)
19817 (let* ((fs (org-agenda-files t))
19818 (files (append fs (list (car fs))))
19819 (tcf (if buffer-file-name (file-truename buffer-file-name)))
19820 file)
19821 (unless files (error "No agenda files"))
19822 (catch 'exit
19823 (while (setq file (pop files))
19824 (if (equal (file-truename file) tcf)
19825 (when (car files)
19826 (find-file (car files))
19827 (throw 'exit t))))
19828 (find-file (car fs)))
19829 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
19831 (defun org-agenda-file-to-front (&optional to-end)
19832 "Move/add the current file to the top of the agenda file list.
19833 If the file is not present in the list, it is added to the front. If it is
19834 present, it is moved there. With optional argument TO-END, add/move to the
19835 end of the list."
19836 (interactive "P")
19837 (let ((org-agenda-skip-unavailable-files nil)
19838 (file-alist (mapcar (lambda (x)
19839 (cons (file-truename x) x))
19840 (org-agenda-files t)))
19841 (ctf (file-truename buffer-file-name))
19842 x had)
19843 (setq x (assoc ctf file-alist) had x)
19845 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
19846 (if to-end
19847 (setq file-alist (append (delq x file-alist) (list x)))
19848 (setq file-alist (cons x (delq x file-alist))))
19849 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
19850 (org-install-agenda-files-menu)
19851 (message "File %s to %s of agenda file list"
19852 (if had "moved" "added") (if to-end "end" "front"))))
19854 (defun org-remove-file (&optional file)
19855 "Remove current file from the list of files in variable `org-agenda-files'.
19856 These are the files which are being checked for agenda entries.
19857 Optional argument FILE means, use this file instead of the current."
19858 (interactive)
19859 (let* ((org-agenda-skip-unavailable-files nil)
19860 (file (or file buffer-file-name))
19861 (true-file (file-truename file))
19862 (afile (abbreviate-file-name file))
19863 (files (delq nil (mapcar
19864 (lambda (x)
19865 (if (equal true-file
19866 (file-truename x))
19867 nil x))
19868 (org-agenda-files t)))))
19869 (if (not (= (length files) (length (org-agenda-files t))))
19870 (progn
19871 (org-store-new-agenda-file-list files)
19872 (org-install-agenda-files-menu)
19873 (message "Removed file: %s" afile))
19874 (message "File was not in list: %s (not removed)" afile))))
19876 (defun org-file-menu-entry (file)
19877 (vector file (list 'find-file file) t))
19879 (defun org-check-agenda-file (file)
19880 "Make sure FILE exists. If not, ask user what to do."
19881 (when (not (file-exists-p file))
19882 (message "non-existent file %s. [R]emove from list or [A]bort?"
19883 (abbreviate-file-name file))
19884 (let ((r (downcase (read-char-exclusive))))
19885 (cond
19886 ((equal r ?r)
19887 (org-remove-file file)
19888 (throw 'nextfile t))
19889 (t (error "Abort"))))))
19891 ;;; Agenda prepare and finalize
19893 (defvar org-agenda-multi nil) ; dynammically scoped
19894 (defvar org-agenda-buffer-name "*Org Agenda*")
19895 (defvar org-pre-agenda-window-conf nil)
19896 (defvar org-agenda-name nil)
19897 (defun org-prepare-agenda (&optional name)
19898 (setq org-todo-keywords-for-agenda nil)
19899 (setq org-done-keywords-for-agenda nil)
19900 (if org-agenda-multi
19901 (progn
19902 (setq buffer-read-only nil)
19903 (goto-char (point-max))
19904 (unless (or (bobp) org-agenda-compact-blocks)
19905 (insert "\n" (make-string (window-width) ?=) "\n"))
19906 (narrow-to-region (point) (point-max)))
19907 (org-agenda-maybe-reset-markers 'force)
19908 (org-prepare-agenda-buffers (org-agenda-files))
19909 (setq org-todo-keywords-for-agenda
19910 (org-uniquify org-todo-keywords-for-agenda))
19911 (setq org-done-keywords-for-agenda
19912 (org-uniquify org-done-keywords-for-agenda))
19913 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
19914 (awin (get-buffer-window abuf)))
19915 (cond
19916 ((equal (current-buffer) abuf) nil)
19917 (awin (select-window awin))
19918 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
19919 ((equal org-agenda-window-setup 'current-window)
19920 (switch-to-buffer abuf))
19921 ((equal org-agenda-window-setup 'other-window)
19922 (org-switch-to-buffer-other-window abuf))
19923 ((equal org-agenda-window-setup 'other-frame)
19924 (switch-to-buffer-other-frame abuf))
19925 ((equal org-agenda-window-setup 'reorganize-frame)
19926 (delete-other-windows)
19927 (org-switch-to-buffer-other-window abuf))))
19928 (setq buffer-read-only nil)
19929 (erase-buffer)
19930 (org-agenda-mode)
19931 (and name (not org-agenda-name)
19932 (org-set-local 'org-agenda-name name)))
19933 (setq buffer-read-only nil))
19935 (defun org-finalize-agenda ()
19936 "Finishing touch for the agenda buffer, called just before displaying it."
19937 (unless org-agenda-multi
19938 (save-excursion
19939 (let ((inhibit-read-only t))
19940 (goto-char (point-min))
19941 (while (org-activate-bracket-links (point-max))
19942 (add-text-properties (match-beginning 0) (match-end 0)
19943 '(face org-link)))
19944 (org-agenda-align-tags)
19945 (unless org-agenda-with-colors
19946 (remove-text-properties (point-min) (point-max) '(face nil))))
19947 (if (and (boundp 'org-overriding-columns-format)
19948 org-overriding-columns-format)
19949 (org-set-local 'org-overriding-columns-format
19950 org-overriding-columns-format))
19951 (if (and (boundp 'org-agenda-view-columns-initially)
19952 org-agenda-view-columns-initially)
19953 (org-agenda-columns))
19954 (when org-agenda-fontify-priorities
19955 (org-fontify-priorities))
19956 (run-hooks 'org-finalize-agenda-hook))))
19958 (defun org-fontify-priorities ()
19959 "Make highest priority lines bold, and lowest italic."
19960 (interactive)
19961 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
19962 (org-delete-overlay o)))
19963 (org-overlays-in (point-min) (point-max)))
19964 (save-excursion
19965 (let ((inhibit-read-only t)
19966 b e p ov h l)
19967 (goto-char (point-min))
19968 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
19969 (setq h (or (get-char-property (point) 'org-highest-priority)
19970 org-highest-priority)
19971 l (or (get-char-property (point) 'org-lowest-priority)
19972 org-lowest-priority)
19973 p (string-to-char (match-string 1))
19974 b (match-beginning 0) e (point-at-eol)
19975 ov (org-make-overlay b e))
19976 (org-overlay-put
19977 ov 'face
19978 (cond ((listp org-agenda-fontify-priorities)
19979 (cdr (assoc p org-agenda-fontify-priorities)))
19980 ((equal p l) 'italic)
19981 ((equal p h) 'bold)))
19982 (org-overlay-put ov 'org-type 'org-priority)))))
19984 (defun org-prepare-agenda-buffers (files)
19985 "Create buffers for all agenda files, protect archived trees and comments."
19986 (interactive)
19987 (let ((pa '(:org-archived t))
19988 (pc '(:org-comment t))
19989 (pall '(:org-archived t :org-comment t))
19990 (inhibit-read-only t)
19991 (rea (concat ":" org-archive-tag ":"))
19992 bmp file re)
19993 (save-excursion
19994 (save-restriction
19995 (while (setq file (pop files))
19996 (if (bufferp file)
19997 (set-buffer file)
19998 (org-check-agenda-file file)
19999 (set-buffer (org-get-agenda-file-buffer file)))
20000 (widen)
20001 (setq bmp (buffer-modified-p))
20002 (org-refresh-category-properties)
20003 (setq org-todo-keywords-for-agenda
20004 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20005 (setq org-done-keywords-for-agenda
20006 (append org-done-keywords-for-agenda org-done-keywords))
20007 (save-excursion
20008 (remove-text-properties (point-min) (point-max) pall)
20009 (when org-agenda-skip-archived-trees
20010 (goto-char (point-min))
20011 (while (re-search-forward rea nil t)
20012 (if (org-on-heading-p t)
20013 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20014 (goto-char (point-min))
20015 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20016 (while (re-search-forward re nil t)
20017 (add-text-properties
20018 (match-beginning 0) (org-end-of-subtree t) pc)))
20019 (set-buffer-modified-p bmp))))))
20021 (defvar org-agenda-skip-function nil
20022 "Function to be called at each match during agenda construction.
20023 If this function returns nil, the current match should not be skipped.
20024 Otherwise, the function must return a position from where the search
20025 should be continued.
20026 This may also be a Lisp form, it will be evaluated.
20027 Never set this variable using `setq' or so, because then it will apply
20028 to all future agenda commands. Instead, bind it with `let' to scope
20029 it dynamically into the agenda-constructing command. A good way to set
20030 it is through options in org-agenda-custom-commands.")
20032 (defun org-agenda-skip ()
20033 "Throw to `:skip' in places that should be skipped.
20034 Also moves point to the end of the skipped region, so that search can
20035 continue from there."
20036 (let ((p (point-at-bol)) to fp)
20037 (and org-agenda-skip-archived-trees
20038 (get-text-property p :org-archived)
20039 (org-end-of-subtree t)
20040 (throw :skip t))
20041 (and (get-text-property p :org-comment)
20042 (org-end-of-subtree t)
20043 (throw :skip t))
20044 (if (equal (char-after p) ?#) (throw :skip t))
20045 (when (and (or (setq fp (functionp org-agenda-skip-function))
20046 (consp org-agenda-skip-function))
20047 (setq to (save-excursion
20048 (save-match-data
20049 (if fp
20050 (funcall org-agenda-skip-function)
20051 (eval org-agenda-skip-function))))))
20052 (goto-char to)
20053 (throw :skip t))))
20055 (defvar org-agenda-markers nil
20056 "List of all currently active markers created by `org-agenda'.")
20057 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20058 "Creation time of the last agenda marker.")
20060 (defun org-agenda-new-marker (&optional pos)
20061 "Return a new agenda marker.
20062 Org-mode keeps a list of these markers and resets them when they are
20063 no longer in use."
20064 (let ((m (copy-marker (or pos (point)))))
20065 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20066 (push m org-agenda-markers)
20069 (defun org-agenda-maybe-reset-markers (&optional force)
20070 "Reset markers created by `org-agenda'. But only if they are old enough."
20071 (if (or (and force (not org-agenda-multi))
20072 (> (- (time-to-seconds (current-time))
20073 org-agenda-last-marker-time)
20075 (while org-agenda-markers
20076 (move-marker (pop org-agenda-markers) nil))))
20078 (defun org-get-agenda-file-buffer (file)
20079 "Get a buffer visiting FILE. If the buffer needs to be created, add
20080 it to the list of buffers which might be released later."
20081 (let ((buf (org-find-base-buffer-visiting file)))
20082 (if buf
20083 buf ; just return it
20084 ;; Make a new buffer and remember it
20085 (setq buf (find-file-noselect file))
20086 (if buf (push buf org-agenda-new-buffers))
20087 buf)))
20089 (defun org-release-buffers (blist)
20090 "Release all buffers in list, asking the user for confirmation when needed.
20091 When a buffer is unmodified, it is just killed. When modified, it is saved
20092 \(if the user agrees) and then killed."
20093 (let (buf file)
20094 (while (setq buf (pop blist))
20095 (setq file (buffer-file-name buf))
20096 (when (and (buffer-modified-p buf)
20097 file
20098 (y-or-n-p (format "Save file %s? " file)))
20099 (with-current-buffer buf (save-buffer)))
20100 (kill-buffer buf))))
20102 (defun org-get-category (&optional pos)
20103 "Get the category applying to position POS."
20104 (get-text-property (or pos (point)) 'org-category))
20106 ;;; Agenda timeline
20108 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20110 (defun org-timeline (&optional include-all)
20111 "Show a time-sorted view of the entries in the current org file.
20112 Only entries with a time stamp of today or later will be listed. With
20113 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20114 under the current date.
20115 If the buffer contains an active region, only check the region for
20116 dates."
20117 (interactive "P")
20118 (require 'calendar)
20119 (org-compile-prefix-format 'timeline)
20120 (org-set-sorting-strategy 'timeline)
20121 (let* ((dopast t)
20122 (dotodo include-all)
20123 (doclosed org-agenda-show-log)
20124 (entry buffer-file-name)
20125 (date (calendar-current-date))
20126 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20127 (end (if (org-region-active-p) (region-end) (point-max)))
20128 (day-numbers (org-get-all-dates beg end 'no-ranges
20129 t doclosed ; always include today
20130 org-timeline-show-empty-dates))
20131 (org-deadline-warning-days 0)
20132 (org-agenda-only-exact-dates t)
20133 (today (time-to-days (current-time)))
20134 (past t)
20135 args
20136 s e rtn d emptyp)
20137 (setq org-agenda-redo-command
20138 (list 'progn
20139 (list 'org-switch-to-buffer-other-window (current-buffer))
20140 (list 'org-timeline (list 'quote include-all))))
20141 (if (not dopast)
20142 ;; Remove past dates from the list of dates.
20143 (setq day-numbers (delq nil (mapcar (lambda(x)
20144 (if (>= x today) x nil))
20145 day-numbers))))
20146 (org-prepare-agenda (concat "Timeline "
20147 (file-name-nondirectory buffer-file-name)))
20148 (if doclosed (push :closed args))
20149 (push :timestamp args)
20150 (push :deadline args)
20151 (push :scheduled args)
20152 (push :sexp args)
20153 (if dotodo (push :todo args))
20154 (while (setq d (pop day-numbers))
20155 (if (and (listp d) (eq (car d) :omitted))
20156 (progn
20157 (setq s (point))
20158 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20159 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20160 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20161 (if (and (>= d today)
20162 dopast
20163 past)
20164 (progn
20165 (setq past nil)
20166 (insert (make-string 79 ?-) "\n")))
20167 (setq date (calendar-gregorian-from-absolute d))
20168 (setq s (point))
20169 (setq rtn (and (not emptyp)
20170 (apply 'org-agenda-get-day-entries entry
20171 date args)))
20172 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20173 (progn
20174 (insert
20175 (if (stringp org-agenda-format-date)
20176 (format-time-string org-agenda-format-date
20177 (org-time-from-absolute date))
20178 (funcall org-agenda-format-date date))
20179 "\n")
20180 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20181 (put-text-property s (1- (point)) 'org-date-line t)
20182 (if (equal d today)
20183 (put-text-property s (1- (point)) 'org-today t))
20184 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20185 (put-text-property s (1- (point)) 'day d)))))
20186 (goto-char (point-min))
20187 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20188 (point-min)))
20189 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20190 (org-finalize-agenda)
20191 (setq buffer-read-only t)))
20193 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
20194 "Return a list of all relevant day numbers from BEG to END buffer positions.
20195 If NO-RANGES is non-nil, include only the start and end dates of a range,
20196 not every single day in the range. If FORCE-TODAY is non-nil, make
20197 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20198 inactive time stamps (those in square brackets) are included.
20199 When EMPTY is non-nil, also include days without any entries."
20200 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
20201 dates dates1 date day day1 day2 ts1 ts2)
20202 (if force-today
20203 (setq dates (list (time-to-days (current-time)))))
20204 (save-excursion
20205 (goto-char beg)
20206 (while (re-search-forward re end t)
20207 (setq day (time-to-days (org-time-string-to-time
20208 (substring (match-string 1) 0 10))))
20209 (or (memq day dates) (push day dates)))
20210 (unless no-ranges
20211 (goto-char beg)
20212 (while (re-search-forward org-tr-regexp end t)
20213 (setq ts1 (substring (match-string 1) 0 10)
20214 ts2 (substring (match-string 2) 0 10)
20215 day1 (time-to-days (org-time-string-to-time ts1))
20216 day2 (time-to-days (org-time-string-to-time ts2)))
20217 (while (< (setq day1 (1+ day1)) day2)
20218 (or (memq day1 dates) (push day1 dates)))))
20219 (setq dates (sort dates '<))
20220 (when empty
20221 (while (setq day (pop dates))
20222 (setq day2 (car dates))
20223 (push day dates1)
20224 (when (and day2 empty)
20225 (if (or (eq empty t)
20226 (and (numberp empty) (<= (- day2 day) empty)))
20227 (while (< (setq day (1+ day)) day2)
20228 (push (list day) dates1))
20229 (push (cons :omitted (- day2 day)) dates1))))
20230 (setq dates (nreverse dates1)))
20231 dates)))
20233 ;;; Agenda Daily/Weekly
20235 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20236 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20237 (defvar org-agenda-last-arguments nil
20238 "The arguments of the previous call to org-agenda")
20239 (defvar org-starting-day nil) ; local variable in the agenda buffer
20240 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20241 (defvar org-include-all-loc nil) ; local variable
20242 (defvar org-agenda-remove-date nil) ; dynamically scoped
20244 ;;;###autoload
20245 (defun org-agenda-list (&optional include-all start-day ndays)
20246 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20247 The view will be for the current day or week, but from the overview buffer
20248 you will be able to go to other days/weeks.
20250 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20251 all unfinished TODO items will also be shown, before the agenda.
20252 This feature is considered obsolete, please use the TODO list or a block
20253 agenda instead.
20255 With a numeric prefix argument in an interactive call, the agenda will
20256 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20257 the number of days. NDAYS defaults to `org-agenda-ndays'.
20259 START-DAY defaults to TODAY, or to the most recent match for the weekday
20260 given in `org-agenda-start-on-weekday'."
20261 (interactive "P")
20262 (if (and (integerp include-all) (> include-all 0))
20263 (setq ndays include-all include-all nil))
20264 (setq ndays (or ndays org-agenda-ndays)
20265 start-day (or start-day org-agenda-start-day))
20266 (if org-agenda-overriding-arguments
20267 (setq include-all (car org-agenda-overriding-arguments)
20268 start-day (nth 1 org-agenda-overriding-arguments)
20269 ndays (nth 2 org-agenda-overriding-arguments)))
20270 (if (stringp start-day)
20271 ;; Convert to an absolute day number
20272 (setq start-day (time-to-days (org-read-date nil t start-day))))
20273 (setq org-agenda-last-arguments (list include-all start-day ndays))
20274 (org-compile-prefix-format 'agenda)
20275 (org-set-sorting-strategy 'agenda)
20276 (require 'calendar)
20277 (let* ((org-agenda-start-on-weekday
20278 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20279 org-agenda-start-on-weekday nil))
20280 (thefiles (org-agenda-files))
20281 (files thefiles)
20282 (today (time-to-days
20283 (time-subtract (current-time)
20284 (list 0 (* 3600 org-extend-today-until) 0))))
20285 (sd (or start-day today))
20286 (start (if (or (null org-agenda-start-on-weekday)
20287 (< org-agenda-ndays 7))
20289 (let* ((nt (calendar-day-of-week
20290 (calendar-gregorian-from-absolute sd)))
20291 (n1 org-agenda-start-on-weekday)
20292 (d (- nt n1)))
20293 (- sd (+ (if (< d 0) 7 0) d)))))
20294 (day-numbers (list start))
20295 (day-cnt 0)
20296 (inhibit-redisplay (not debug-on-error))
20297 s e rtn rtnall file date d start-pos end-pos todayp nd)
20298 (setq org-agenda-redo-command
20299 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20300 ;; Make the list of days
20301 (setq ndays (or ndays org-agenda-ndays)
20302 nd ndays)
20303 (while (> ndays 1)
20304 (push (1+ (car day-numbers)) day-numbers)
20305 (setq ndays (1- ndays)))
20306 (setq day-numbers (nreverse day-numbers))
20307 (org-prepare-agenda "Day/Week")
20308 (org-set-local 'org-starting-day (car day-numbers))
20309 (org-set-local 'org-include-all-loc include-all)
20310 (org-set-local 'org-agenda-span
20311 (org-agenda-ndays-to-span nd))
20312 (when (and (or include-all org-agenda-include-all-todo)
20313 (member today day-numbers))
20314 (setq files thefiles
20315 rtnall nil)
20316 (while (setq file (pop files))
20317 (catch 'nextfile
20318 (org-check-agenda-file file)
20319 (setq date (calendar-gregorian-from-absolute today)
20320 rtn (org-agenda-get-day-entries
20321 file date :todo))
20322 (setq rtnall (append rtnall rtn))))
20323 (when rtnall
20324 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20325 (add-text-properties (point-min) (1- (point))
20326 (list 'face 'org-agenda-structure))
20327 (insert (org-finalize-agenda-entries rtnall) "\n")))
20328 (unless org-agenda-compact-blocks
20329 (setq s (point))
20330 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20331 "-agenda:\n")
20332 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20333 'org-date-line t)))
20334 (while (setq d (pop day-numbers))
20335 (setq date (calendar-gregorian-from-absolute d)
20336 s (point))
20337 (if (or (setq todayp (= d today))
20338 (and (not start-pos) (= d sd)))
20339 (setq start-pos (point))
20340 (if (and start-pos (not end-pos))
20341 (setq end-pos (point))))
20342 (setq files thefiles
20343 rtnall nil)
20344 (while (setq file (pop files))
20345 (catch 'nextfile
20346 (org-check-agenda-file file)
20347 (if org-agenda-show-log
20348 (setq rtn (org-agenda-get-day-entries
20349 file date
20350 :deadline :scheduled :timestamp :sexp :closed))
20351 (setq rtn (org-agenda-get-day-entries
20352 file date
20353 :deadline :scheduled :sexp :timestamp)))
20354 (setq rtnall (append rtnall rtn))))
20355 (if org-agenda-include-diary
20356 (progn
20357 (require 'diary-lib)
20358 (setq rtn (org-get-entries-from-diary date))
20359 (setq rtnall (append rtnall rtn))))
20360 (if (or rtnall org-agenda-show-all-dates)
20361 (progn
20362 (setq day-cnt (1+ day-cnt))
20363 (insert
20364 (if (stringp org-agenda-format-date)
20365 (format-time-string org-agenda-format-date
20366 (org-time-from-absolute date))
20367 (funcall org-agenda-format-date date))
20368 "\n")
20369 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20370 (put-text-property s (1- (point)) 'org-date-line t)
20371 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20372 (if todayp (put-text-property s (1- (point)) 'org-today t))
20373 (if rtnall (insert
20374 (org-finalize-agenda-entries
20375 (org-agenda-add-time-grid-maybe
20376 rtnall nd todayp))
20377 "\n"))
20378 (put-text-property s (1- (point)) 'day d)
20379 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20380 (goto-char (point-min))
20381 (org-fit-agenda-window)
20382 (unless (and (pos-visible-in-window-p (point-min))
20383 (pos-visible-in-window-p (point-max)))
20384 (goto-char (1- (point-max)))
20385 (recenter -1)
20386 (if (not (pos-visible-in-window-p (or start-pos 1)))
20387 (progn
20388 (goto-char (or start-pos 1))
20389 (recenter 1))))
20390 (goto-char (or start-pos 1))
20391 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20392 (org-finalize-agenda)
20393 (setq buffer-read-only t)
20394 (message "")))
20396 (defun org-agenda-ndays-to-span (n)
20397 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20399 ;;; Agenda TODO list
20401 (defvar org-select-this-todo-keyword nil)
20402 (defvar org-last-arg nil)
20404 ;;;###autoload
20405 (defun org-todo-list (arg)
20406 "Show all TODO entries from all agenda file in a single list.
20407 The prefix arg can be used to select a specific TODO keyword and limit
20408 the list to these. When using \\[universal-argument], you will be prompted
20409 for a keyword. A numeric prefix directly selects the Nth keyword in
20410 `org-todo-keywords-1'."
20411 (interactive "P")
20412 (require 'calendar)
20413 (org-compile-prefix-format 'todo)
20414 (org-set-sorting-strategy 'todo)
20415 (org-prepare-agenda "TODO")
20416 (let* ((today (time-to-days (current-time)))
20417 (date (calendar-gregorian-from-absolute today))
20418 (kwds org-todo-keywords-for-agenda)
20419 (completion-ignore-case t)
20420 (org-select-this-todo-keyword
20421 (if (stringp arg) arg
20422 (and arg (integerp arg) (> arg 0)
20423 (nth (1- arg) kwds))))
20424 rtn rtnall files file pos)
20425 (when (equal arg '(4))
20426 (setq org-select-this-todo-keyword
20427 (completing-read "Keyword (or KWD1|K2D2|...): "
20428 (mapcar 'list kwds) nil nil)))
20429 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20430 (org-set-local 'org-last-arg arg)
20431 (setq org-agenda-redo-command
20432 '(org-todo-list (or current-prefix-arg org-last-arg)))
20433 (setq files (org-agenda-files)
20434 rtnall nil)
20435 (while (setq file (pop files))
20436 (catch 'nextfile
20437 (org-check-agenda-file file)
20438 (setq rtn (org-agenda-get-day-entries file date :todo))
20439 (setq rtnall (append rtnall rtn))))
20440 (if org-agenda-overriding-header
20441 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20442 nil 'face 'org-agenda-structure) "\n")
20443 (insert "Global list of TODO items of type: ")
20444 (add-text-properties (point-min) (1- (point))
20445 (list 'face 'org-agenda-structure))
20446 (setq pos (point))
20447 (insert (or org-select-this-todo-keyword "ALL") "\n")
20448 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20449 (setq pos (point))
20450 (unless org-agenda-multi
20451 (insert "Available with `N r': (0)ALL")
20452 (let ((n 0) s)
20453 (mapc (lambda (x)
20454 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20455 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20456 (insert "\n "))
20457 (insert " " s))
20458 kwds))
20459 (insert "\n"))
20460 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20461 (when rtnall
20462 (insert (org-finalize-agenda-entries rtnall) "\n"))
20463 (goto-char (point-min))
20464 (org-fit-agenda-window)
20465 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20466 (org-finalize-agenda)
20467 (setq buffer-read-only t)))
20469 ;;; Agenda tags match
20471 ;;;###autoload
20472 (defun org-tags-view (&optional todo-only match)
20473 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20474 The prefix arg TODO-ONLY limits the search to TODO entries."
20475 (interactive "P")
20476 (org-compile-prefix-format 'tags)
20477 (org-set-sorting-strategy 'tags)
20478 (let* ((org-tags-match-list-sublevels
20479 (if todo-only t org-tags-match-list-sublevels))
20480 (completion-ignore-case t)
20481 rtn rtnall files file pos matcher
20482 buffer)
20483 (setq matcher (org-make-tags-matcher match)
20484 match (car matcher) matcher (cdr matcher))
20485 (org-prepare-agenda (concat "TAGS " match))
20486 (setq org-agenda-redo-command
20487 (list 'org-tags-view (list 'quote todo-only)
20488 (list 'if 'current-prefix-arg nil match)))
20489 (setq files (org-agenda-files)
20490 rtnall nil)
20491 (while (setq file (pop files))
20492 (catch 'nextfile
20493 (org-check-agenda-file file)
20494 (setq buffer (if (file-exists-p file)
20495 (org-get-agenda-file-buffer file)
20496 (error "No such file %s" file)))
20497 (if (not buffer)
20498 ;; If file does not exist, merror message to agenda
20499 (setq rtn (list
20500 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20501 rtnall (append rtnall rtn))
20502 (with-current-buffer buffer
20503 (unless (org-mode-p)
20504 (error "Agenda file %s is not in `org-mode'" file))
20505 (save-excursion
20506 (save-restriction
20507 (if org-agenda-restrict
20508 (narrow-to-region org-agenda-restrict-begin
20509 org-agenda-restrict-end)
20510 (widen))
20511 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20512 (setq rtnall (append rtnall rtn))))))))
20513 (if org-agenda-overriding-header
20514 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20515 nil 'face 'org-agenda-structure) "\n")
20516 (insert "Headlines with TAGS match: ")
20517 (add-text-properties (point-min) (1- (point))
20518 (list 'face 'org-agenda-structure))
20519 (setq pos (point))
20520 (insert match "\n")
20521 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20522 (setq pos (point))
20523 (unless org-agenda-multi
20524 (insert "Press `C-u r' to search again with new search string\n"))
20525 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20526 (when rtnall
20527 (insert (org-finalize-agenda-entries rtnall) "\n"))
20528 (goto-char (point-min))
20529 (org-fit-agenda-window)
20530 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20531 (org-finalize-agenda)
20532 (setq buffer-read-only t)))
20534 ;;; Agenda Finding stuck projects
20536 (defvar org-agenda-skip-regexp nil
20537 "Regular expression used in skipping subtrees for the agenda.
20538 This is basically a temporary global variable that can be set and then
20539 used by user-defined selections using `org-agenda-skip-function'.")
20541 (defvar org-agenda-overriding-header nil
20542 "When this is set during todo and tags searches, will replace header.")
20544 (defun org-agenda-skip-subtree-when-regexp-matches ()
20545 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20546 If yes, it returns the end position of this tree, causing agenda commands
20547 to skip this subtree. This is a function that can be put into
20548 `org-agenda-skip-function' for the duration of a command."
20549 (let ((end (save-excursion (org-end-of-subtree t)))
20550 skip)
20551 (save-excursion
20552 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20553 (and skip end)))
20555 (defun org-agenda-skip-entry-if (&rest conditions)
20556 "Skip entry if any of CONDITIONS is true.
20557 See `org-agenda-skip-if' for details."
20558 (org-agenda-skip-if nil conditions))
20560 (defun org-agenda-skip-subtree-if (&rest conditions)
20561 "Skip entry if any of CONDITIONS is true.
20562 See `org-agenda-skip-if' for details."
20563 (org-agenda-skip-if t conditions))
20565 (defun org-agenda-skip-if (subtree conditions)
20566 "Checks current entity for CONDITIONS.
20567 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20568 the entry, i.e. the text before the next heading is checked.
20570 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20571 from different tests. Valid conditions are:
20573 scheduled Check if there is a scheduled cookie
20574 notscheduled Check if there is no scheduled cookie
20575 deadline Check if there is a deadline
20576 notdeadline Check if there is no deadline
20577 regexp Check if regexp matches
20578 notregexp Check if regexp does not match.
20580 The regexp is taken from the conditions list, it must come right after
20581 the `regexp' or `notregexp' element.
20583 If any of these conditions is met, this function returns the end point of
20584 the entity, causing the search to continue from there. This is a function
20585 that can be put into `org-agenda-skip-function' for the duration of a command."
20586 (let (beg end m)
20587 (org-back-to-heading t)
20588 (setq beg (point)
20589 end (if subtree
20590 (progn (org-end-of-subtree t) (point))
20591 (progn (outline-next-heading) (1- (point)))))
20592 (goto-char beg)
20593 (and
20595 (and (memq 'scheduled conditions)
20596 (re-search-forward org-scheduled-time-regexp end t))
20597 (and (memq 'notscheduled conditions)
20598 (not (re-search-forward org-scheduled-time-regexp end t)))
20599 (and (memq 'deadline conditions)
20600 (re-search-forward org-deadline-time-regexp end t))
20601 (and (memq 'notdeadline conditions)
20602 (not (re-search-forward org-deadline-time-regexp end t)))
20603 (and (setq m (memq 'regexp conditions))
20604 (stringp (nth 1 m))
20605 (re-search-forward (nth 1 m) end t))
20606 (and (setq m (memq 'notregexp conditions))
20607 (stringp (nth 1 m))
20608 (not (re-search-forward (nth 1 m) end t))))
20609 end)))
20611 ;;;###autoload
20612 (defun org-agenda-list-stuck-projects (&rest ignore)
20613 "Create agenda view for projects that are stuck.
20614 Stuck projects are project that have no next actions. For the definitions
20615 of what a project is and how to check if it stuck, customize the variable
20616 `org-stuck-projects'.
20617 MATCH is being ignored."
20618 (interactive)
20619 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20620 ;; FIXME: we could have used org-agenda-skip-if here.
20621 (org-agenda-overriding-header "List of stuck projects: ")
20622 (matcher (nth 0 org-stuck-projects))
20623 (todo (nth 1 org-stuck-projects))
20624 (todo-wds (if (member "*" todo)
20625 (progn
20626 (org-prepare-agenda-buffers (org-agenda-files))
20627 (org-delete-all
20628 org-done-keywords-for-agenda
20629 (copy-sequence org-todo-keywords-for-agenda)))
20630 todo))
20631 (todo-re (concat "^\\*+[ \t]+\\("
20632 (mapconcat 'identity todo-wds "\\|")
20633 "\\)\\>"))
20634 (tags (nth 2 org-stuck-projects))
20635 (tags-re (if (member "*" tags)
20636 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20637 (concat "^\\*+ .*:\\("
20638 (mapconcat 'identity tags "\\|")
20639 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20640 (gen-re (nth 3 org-stuck-projects))
20641 (re-list
20642 (delq nil
20643 (list
20644 (if todo todo-re)
20645 (if tags tags-re)
20646 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20647 gen-re)))))
20648 (setq org-agenda-skip-regexp
20649 (if re-list
20650 (mapconcat 'identity re-list "\\|")
20651 (error "No information how to identify unstuck projects")))
20652 (org-tags-view nil matcher)
20653 (with-current-buffer org-agenda-buffer-name
20654 (setq org-agenda-redo-command
20655 '(org-agenda-list-stuck-projects
20656 (or current-prefix-arg org-last-arg))))))
20658 ;;; Diary integration
20660 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20662 (defun org-get-entries-from-diary (date)
20663 "Get the (Emacs Calendar) diary entries for DATE."
20664 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20665 (diary-display-hook '(fancy-diary-display))
20666 (pop-up-frames nil)
20667 (list-diary-entries-hook
20668 (cons 'org-diary-default-entry list-diary-entries-hook))
20669 (diary-file-name-prefix-function nil) ; turn this feature off
20670 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20671 entries
20672 (org-disable-agenda-to-diary t))
20673 (save-excursion
20674 (save-window-excursion
20675 (funcall (if (fboundp 'diary-list-entries)
20676 'diary-list-entries 'list-diary-entries)
20677 date 1)))
20678 (if (not (get-buffer fancy-diary-buffer))
20679 (setq entries nil)
20680 (with-current-buffer fancy-diary-buffer
20681 (setq buffer-read-only nil)
20682 (if (zerop (buffer-size))
20683 ;; No entries
20684 (setq entries nil)
20685 ;; Omit the date and other unnecessary stuff
20686 (org-agenda-cleanup-fancy-diary)
20687 ;; Add prefix to each line and extend the text properties
20688 (if (zerop (buffer-size))
20689 (setq entries nil)
20690 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20691 (set-buffer-modified-p nil)
20692 (kill-buffer fancy-diary-buffer)))
20693 (when entries
20694 (setq entries (org-split-string entries "\n"))
20695 (setq entries
20696 (mapcar
20697 (lambda (x)
20698 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20699 ;; Extend the text properties to the beginning of the line
20700 (org-add-props x (text-properties-at (1- (length x)) x)
20701 'type "diary" 'date date))
20702 entries)))))
20704 (defun org-agenda-cleanup-fancy-diary ()
20705 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20706 This gets rid of the date, the underline under the date, and
20707 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20708 date. It also removes lines that contain only whitespace."
20709 (goto-char (point-min))
20710 (if (looking-at ".*?:[ \t]*")
20711 (progn
20712 (replace-match "")
20713 (re-search-forward "\n=+$" nil t)
20714 (replace-match "")
20715 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20716 (re-search-forward "\n=+$" nil t)
20717 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20718 (goto-char (point-min))
20719 (while (re-search-forward "^ +\n" nil t)
20720 (replace-match ""))
20721 (goto-char (point-min))
20722 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20723 (replace-match "")))
20725 ;; Make sure entries from the diary have the right text properties.
20726 (eval-after-load "diary-lib"
20727 '(if (boundp 'diary-modify-entry-list-string-function)
20728 ;; We can rely on the hook, nothing to do
20730 ;; Hook not avaiable, must use advice to make this work
20731 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20732 "Make the position visible."
20733 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20734 (stringp string)
20735 buffer-file-name)
20736 (setq string (org-modify-diary-entry-string string))))))
20738 (defun org-modify-diary-entry-string (string)
20739 "Add text properties to string, allowing org-mode to act on it."
20740 (org-add-props string nil
20741 'mouse-face 'highlight
20742 'keymap org-agenda-keymap
20743 'help-echo (if buffer-file-name
20744 (format "mouse-2 or RET jump to diary file %s"
20745 (abbreviate-file-name buffer-file-name))
20747 'org-agenda-diary-link t
20748 'org-marker (org-agenda-new-marker (point-at-bol))))
20750 (defun org-diary-default-entry ()
20751 "Add a dummy entry to the diary.
20752 Needed to avoid empty dates which mess up holiday display."
20753 ;; Catch the error if dealing with the new add-to-diary-alist
20754 (when org-disable-agenda-to-diary
20755 (condition-case nil
20756 (add-to-diary-list original-date "Org-mode dummy" "")
20757 (error
20758 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
20760 ;;;###autoload
20761 (defun org-diary (&rest args)
20762 "Return diary information from org-files.
20763 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
20764 It accesses org files and extracts information from those files to be
20765 listed in the diary. The function accepts arguments specifying what
20766 items should be listed. The following arguments are allowed:
20768 :timestamp List the headlines of items containing a date stamp or
20769 date range matching the selected date. Deadlines will
20770 also be listed, on the expiration day.
20772 :sexp List entries resulting from diary-like sexps.
20774 :deadline List any deadlines past due, or due within
20775 `org-deadline-warning-days'. The listing occurs only
20776 in the diary for *today*, not at any other date. If
20777 an entry is marked DONE, it is no longer listed.
20779 :scheduled List all items which are scheduled for the given date.
20780 The diary for *today* also contains items which were
20781 scheduled earlier and are not yet marked DONE.
20783 :todo List all TODO items from the org-file. This may be a
20784 long list - so this is not turned on by default.
20785 Like deadlines, these entries only show up in the
20786 diary for *today*, not at any other date.
20788 The call in the diary file should look like this:
20790 &%%(org-diary) ~/path/to/some/orgfile.org
20792 Use a separate line for each org file to check. Or, if you omit the file name,
20793 all files listed in `org-agenda-files' will be checked automatically:
20795 &%%(org-diary)
20797 If you don't give any arguments (as in the example above), the default
20798 arguments (:deadline :scheduled :timestamp :sexp) are used.
20799 So the example above may also be written as
20801 &%%(org-diary :deadline :timestamp :sexp :scheduled)
20803 The function expects the lisp variables `entry' and `date' to be provided
20804 by the caller, because this is how the calendar works. Don't use this
20805 function from a program - use `org-agenda-get-day-entries' instead."
20806 (org-agenda-maybe-reset-markers)
20807 (org-compile-prefix-format 'agenda)
20808 (org-set-sorting-strategy 'agenda)
20809 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20810 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
20811 (list entry)
20812 (org-agenda-files t)))
20813 file rtn results)
20814 (org-prepare-agenda-buffers files)
20815 ;; If this is called during org-agenda, don't return any entries to
20816 ;; the calendar. Org Agenda will list these entries itself.
20817 (if org-disable-agenda-to-diary (setq files nil))
20818 (while (setq file (pop files))
20819 (setq rtn (apply 'org-agenda-get-day-entries file date args))
20820 (setq results (append results rtn)))
20821 (if results
20822 (concat (org-finalize-agenda-entries results) "\n"))))
20824 ;;; Agenda entry finders
20826 (defun org-agenda-get-day-entries (file date &rest args)
20827 "Does the work for `org-diary' and `org-agenda'.
20828 FILE is the path to a file to be checked for entries. DATE is date like
20829 the one returned by `calendar-current-date'. ARGS are symbols indicating
20830 which kind of entries should be extracted. For details about these, see
20831 the documentation of `org-diary'."
20832 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20833 (let* ((org-startup-folded nil)
20834 (org-startup-align-all-tables nil)
20835 (buffer (if (file-exists-p file)
20836 (org-get-agenda-file-buffer file)
20837 (error "No such file %s" file)))
20838 arg results rtn)
20839 (if (not buffer)
20840 ;; If file does not exist, make sure an error message ends up in diary
20841 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20842 (with-current-buffer buffer
20843 (unless (org-mode-p)
20844 (error "Agenda file %s is not in `org-mode'" file))
20845 (let ((case-fold-search nil))
20846 (save-excursion
20847 (save-restriction
20848 (if org-agenda-restrict
20849 (narrow-to-region org-agenda-restrict-begin
20850 org-agenda-restrict-end)
20851 (widen))
20852 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
20853 (while (setq arg (pop args))
20854 (cond
20855 ((and (eq arg :todo)
20856 (equal date (calendar-current-date)))
20857 (setq rtn (org-agenda-get-todos))
20858 (setq results (append results rtn)))
20859 ((eq arg :timestamp)
20860 (setq rtn (org-agenda-get-blocks))
20861 (setq results (append results rtn))
20862 (setq rtn (org-agenda-get-timestamps))
20863 (setq results (append results rtn)))
20864 ((eq arg :sexp)
20865 (setq rtn (org-agenda-get-sexps))
20866 (setq results (append results rtn)))
20867 ((eq arg :scheduled)
20868 (setq rtn (org-agenda-get-scheduled))
20869 (setq results (append results rtn)))
20870 ((eq arg :closed)
20871 (setq rtn (org-agenda-get-closed))
20872 (setq results (append results rtn)))
20873 ((eq arg :deadline)
20874 (setq rtn (org-agenda-get-deadlines))
20875 (setq results (append results rtn))))))))
20876 results))))
20878 (defun org-entry-is-todo-p ()
20879 (member (org-get-todo-state) org-not-done-keywords))
20881 (defun org-entry-is-done-p ()
20882 (member (org-get-todo-state) org-done-keywords))
20884 (defun org-get-todo-state ()
20885 (save-excursion
20886 (org-back-to-heading t)
20887 (and (looking-at org-todo-line-regexp)
20888 (match-end 2)
20889 (match-string 2))))
20891 (defun org-at-date-range-p (&optional inactive-ok)
20892 "Is the cursor inside a date range?"
20893 (interactive)
20894 (save-excursion
20895 (catch 'exit
20896 (let ((pos (point)))
20897 (skip-chars-backward "^[<\r\n")
20898 (skip-chars-backward "<[")
20899 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20900 (>= (match-end 0) pos)
20901 (throw 'exit t))
20902 (skip-chars-backward "^<[\r\n")
20903 (skip-chars-backward "<[")
20904 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20905 (>= (match-end 0) pos)
20906 (throw 'exit t)))
20907 nil)))
20909 (defun org-agenda-get-todos ()
20910 "Return the TODO information for agenda display."
20911 (let* ((props (list 'face nil
20912 'done-face 'org-done
20913 'org-not-done-regexp org-not-done-regexp
20914 'org-todo-regexp org-todo-regexp
20915 'mouse-face 'highlight
20916 'keymap org-agenda-keymap
20917 'help-echo
20918 (format "mouse-2 or RET jump to org file %s"
20919 (abbreviate-file-name buffer-file-name))))
20920 ;; FIXME: get rid of the \n at some point but watch out
20921 (regexp (concat "^\\*+[ \t]+\\("
20922 (if org-select-this-todo-keyword
20923 (if (equal org-select-this-todo-keyword "*")
20924 org-todo-regexp
20925 (concat "\\<\\("
20926 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
20927 "\\)\\>"))
20928 org-not-done-regexp)
20929 "[^\n\r]*\\)"))
20930 marker priority category tags
20931 ee txt beg end)
20932 (goto-char (point-min))
20933 (while (re-search-forward regexp nil t)
20934 (catch :skip
20935 (save-match-data
20936 (beginning-of-line)
20937 (setq beg (point) end (progn (outline-next-heading) (point)))
20938 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
20939 (re-search-forward org-ts-regexp end t))
20940 (and org-agenda-todo-ignore-scheduled (goto-char beg)
20941 (re-search-forward org-scheduled-time-regexp end t))
20942 (and org-agenda-todo-ignore-deadlines (goto-char beg)
20943 (re-search-forward org-deadline-time-regexp end t)
20944 (org-deadline-close (match-string 1))))
20945 (goto-char (1+ beg))
20946 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
20947 (throw :skip nil)))
20948 (goto-char beg)
20949 (org-agenda-skip)
20950 (goto-char (match-beginning 1))
20951 (setq marker (org-agenda-new-marker (match-beginning 0))
20952 category (org-get-category)
20953 tags (org-get-tags-at (point))
20954 txt (org-format-agenda-item "" (match-string 1) category tags)
20955 priority (1+ (org-get-priority txt)))
20956 (org-add-props txt props
20957 'org-marker marker 'org-hd-marker marker
20958 'priority priority 'org-category category
20959 'type "todo")
20960 (push txt ee)
20961 (if org-agenda-todo-list-sublevels
20962 (goto-char (match-end 1))
20963 (org-end-of-subtree 'invisible))))
20964 (nreverse ee)))
20966 (defconst org-agenda-no-heading-message
20967 "No heading for this item in buffer or region.")
20969 (defun org-agenda-get-timestamps ()
20970 "Return the date stamp information for agenda display."
20971 (let* ((props (list 'face nil
20972 'org-not-done-regexp org-not-done-regexp
20973 'org-todo-regexp org-todo-regexp
20974 'mouse-face 'highlight
20975 'keymap org-agenda-keymap
20976 'help-echo
20977 (format "mouse-2 or RET jump to org file %s"
20978 (abbreviate-file-name buffer-file-name))))
20979 (d1 (calendar-absolute-from-gregorian date))
20980 (remove-re
20981 (concat
20982 (regexp-quote
20983 (format-time-string
20984 "<%Y-%m-%d"
20985 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20986 ".*?>"))
20987 (regexp
20988 (concat
20989 (regexp-quote
20990 (substring
20991 (format-time-string
20992 (car org-time-stamp-formats)
20993 (apply 'encode-time ; DATE bound by calendar
20994 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20995 0 11))
20996 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
20997 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
20998 marker hdmarker deadlinep scheduledp donep tmp priority category
20999 ee txt timestr tags b0 b3 e3 head)
21000 (goto-char (point-min))
21001 (while (re-search-forward regexp nil t)
21002 (setq b0 (match-beginning 0)
21003 b3 (match-beginning 3) e3 (match-end 3))
21004 (catch :skip
21005 (and (org-at-date-range-p) (throw :skip nil))
21006 (org-agenda-skip)
21007 (if (and (match-end 1)
21008 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21009 (throw :skip nil))
21010 (if (and e3
21011 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21012 (throw :skip nil))
21013 (setq marker (org-agenda-new-marker b0)
21014 category (org-get-category b0)
21015 tmp (buffer-substring (max (point-min)
21016 (- b0 org-ds-keyword-length))
21018 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21019 deadlinep (string-match org-deadline-regexp tmp)
21020 scheduledp (string-match org-scheduled-regexp tmp)
21021 donep (org-entry-is-done-p))
21022 (if (or scheduledp deadlinep) (throw :skip t))
21023 (if (string-match ">" timestr)
21024 ;; substring should only run to end of time stamp
21025 (setq timestr (substring timestr 0 (match-end 0))))
21026 (save-excursion
21027 (if (re-search-backward "^\\*+ " nil t)
21028 (progn
21029 (goto-char (match-beginning 0))
21030 (setq hdmarker (org-agenda-new-marker)
21031 tags (org-get-tags-at))
21032 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21033 (setq head (match-string 1))
21034 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21035 (setq txt (org-format-agenda-item
21036 nil head category tags timestr nil
21037 remove-re)))
21038 (setq txt org-agenda-no-heading-message))
21039 (setq priority (org-get-priority txt))
21040 (org-add-props txt props
21041 'org-marker marker 'org-hd-marker hdmarker)
21042 (org-add-props txt nil 'priority priority
21043 'org-category category 'date date
21044 'type "timestamp")
21045 (push txt ee))
21046 (outline-next-heading)))
21047 (nreverse ee)))
21049 (defun org-agenda-get-sexps ()
21050 "Return the sexp information for agenda display."
21051 (require 'diary-lib)
21052 (let* ((props (list 'face nil
21053 'mouse-face 'highlight
21054 'keymap org-agenda-keymap
21055 'help-echo
21056 (format "mouse-2 or RET jump to org file %s"
21057 (abbreviate-file-name buffer-file-name))))
21058 (regexp "^&?%%(")
21059 marker category ee txt tags entry result beg b sexp sexp-entry)
21060 (goto-char (point-min))
21061 (while (re-search-forward regexp nil t)
21062 (catch :skip
21063 (org-agenda-skip)
21064 (setq beg (match-beginning 0))
21065 (goto-char (1- (match-end 0)))
21066 (setq b (point))
21067 (forward-sexp 1)
21068 (setq sexp (buffer-substring b (point)))
21069 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21070 (org-trim (match-string 1))
21071 ""))
21072 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21073 (when result
21074 (setq marker (org-agenda-new-marker beg)
21075 category (org-get-category beg))
21077 (if (string-match "\\S-" result)
21078 (setq txt result)
21079 (setq txt "SEXP entry returned empty string"))
21081 (setq txt (org-format-agenda-item
21082 "" txt category tags 'time))
21083 (org-add-props txt props 'org-marker marker)
21084 (org-add-props txt nil
21085 'org-category category 'date date
21086 'type "sexp")
21087 (push txt ee))))
21088 (nreverse ee)))
21090 (defun org-agenda-get-closed ()
21091 "Return the logged TODO entries for agenda display."
21092 (let* ((props (list 'mouse-face 'highlight
21093 'org-not-done-regexp org-not-done-regexp
21094 'org-todo-regexp org-todo-regexp
21095 'keymap org-agenda-keymap
21096 'help-echo
21097 (format "mouse-2 or RET jump to org file %s"
21098 (abbreviate-file-name buffer-file-name))))
21099 (regexp (concat
21100 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21101 (regexp-quote
21102 (substring
21103 (format-time-string
21104 (car org-time-stamp-formats)
21105 (apply 'encode-time ; DATE bound by calendar
21106 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21107 1 11))))
21108 marker hdmarker priority category tags closedp
21109 ee txt timestr)
21110 (goto-char (point-min))
21111 (while (re-search-forward regexp nil t)
21112 (catch :skip
21113 (org-agenda-skip)
21114 (setq marker (org-agenda-new-marker (match-beginning 0))
21115 closedp (equal (match-string 1) org-closed-string)
21116 category (org-get-category (match-beginning 0))
21117 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21118 ;; donep (org-entry-is-done-p)
21120 (if (string-match "\\]" timestr)
21121 ;; substring should only run to end of time stamp
21122 (setq timestr (substring timestr 0 (match-end 0))))
21123 (save-excursion
21124 (if (re-search-backward "^\\*+ " nil t)
21125 (progn
21126 (goto-char (match-beginning 0))
21127 (setq hdmarker (org-agenda-new-marker)
21128 tags (org-get-tags-at))
21129 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21130 (setq txt (org-format-agenda-item
21131 (if closedp "Closed: " "Clocked: ")
21132 (match-string 1) category tags timestr)))
21133 (setq txt org-agenda-no-heading-message))
21134 (setq priority 100000)
21135 (org-add-props txt props
21136 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21137 'priority priority 'org-category category
21138 'type "closed" 'date date
21139 'undone-face 'org-warning 'done-face 'org-done)
21140 (push txt ee))
21141 (outline-next-heading)))
21142 (nreverse ee)))
21144 (defun org-agenda-get-deadlines ()
21145 "Return the deadline information for agenda display."
21146 (let* ((props (list 'mouse-face 'highlight
21147 'org-not-done-regexp org-not-done-regexp
21148 'org-todo-regexp org-todo-regexp
21149 'keymap org-agenda-keymap
21150 'help-echo
21151 (format "mouse-2 or RET jump to org file %s"
21152 (abbreviate-file-name buffer-file-name))))
21153 (regexp org-deadline-time-regexp)
21154 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21155 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21156 d2 diff dfrac wdays pos pos1 category tags
21157 ee txt head face s upcomingp donep timestr)
21158 (goto-char (point-min))
21159 (while (re-search-forward regexp nil t)
21160 (catch :skip
21161 (org-agenda-skip)
21162 (setq s (match-string 1)
21163 pos (1- (match-beginning 1))
21164 d2 (org-time-string-to-absolute (match-string 1) d1)
21165 diff (- d2 d1)
21166 wdays (org-get-wdays s)
21167 dfrac (/ (* 1.0 (- wdays diff)) wdays)
21168 upcomingp (and todayp (> diff 0)))
21169 ;; When to show a deadline in the calendar:
21170 ;; If the expiration is within wdays warning time.
21171 ;; Past-due deadlines are only shown on the current date
21172 (if (or (and (<= diff wdays)
21173 (and todayp (not org-agenda-only-exact-dates)))
21174 (= diff 0))
21175 (save-excursion
21176 (setq category (org-get-category))
21177 (if (re-search-backward "^\\*+[ \t]+" nil t)
21178 (progn
21179 (goto-char (match-end 0))
21180 (setq pos1 (match-beginning 0))
21181 (setq tags (org-get-tags-at pos1))
21182 (setq head (buffer-substring-no-properties
21183 (point)
21184 (progn (skip-chars-forward "^\r\n")
21185 (point))))
21186 (setq donep (string-match org-looking-at-done-regexp head))
21187 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21188 (setq timestr
21189 (concat (substring s (match-beginning 1)) " "))
21190 (setq timestr 'time))
21191 (if (and donep
21192 (or org-agenda-skip-deadline-if-done
21193 (not (= diff 0))))
21194 (setq txt nil)
21195 (setq txt (org-format-agenda-item
21196 (if (= diff 0)
21197 (car org-agenda-deadline-leaders)
21198 (format (nth 1 org-agenda-deadline-leaders)
21199 diff))
21200 head category tags timestr))))
21201 (setq txt org-agenda-no-heading-message))
21202 (when txt
21203 (setq face (org-agenda-deadline-face dfrac))
21204 (org-add-props txt props
21205 'org-marker (org-agenda-new-marker pos)
21206 'org-hd-marker (org-agenda-new-marker pos1)
21207 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
21208 (org-get-priority txt))
21209 'org-category category
21210 'type (if upcomingp "upcoming-deadline" "deadline")
21211 'date (if upcomingp date d2)
21212 'face (if donep 'org-done face)
21213 'undone-face face 'done-face 'org-done)
21214 (push txt ee))))))
21215 (nreverse ee)))
21217 (defun org-agenda-deadline-face (fraction)
21218 "Return the face to displaying a deadline item.
21219 FRACTION is what fraction of the head-warning time has passed."
21220 (let ((faces org-agenda-deadline-faces) f)
21221 (catch 'exit
21222 (while (setq f (pop faces))
21223 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21225 (defun org-agenda-get-scheduled ()
21226 "Return the scheduled information for agenda display."
21227 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21228 'org-todo-regexp org-todo-regexp
21229 'done-face 'org-done
21230 'mouse-face 'highlight
21231 'keymap org-agenda-keymap
21232 'help-echo
21233 (format "mouse-2 or RET jump to org file %s"
21234 (abbreviate-file-name buffer-file-name))))
21235 (regexp org-scheduled-time-regexp)
21236 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21237 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21238 d2 diff pos pos1 category tags
21239 ee txt head pastschedp donep face timestr s)
21240 (goto-char (point-min))
21241 (while (re-search-forward regexp nil t)
21242 (catch :skip
21243 (org-agenda-skip)
21244 (setq s (match-string 1)
21245 pos (1- (match-beginning 1))
21246 d2 (org-time-string-to-absolute (match-string 1) d1)
21247 diff (- d2 d1))
21248 (setq pastschedp (and todayp (< diff 0)))
21249 ;; When to show a scheduled item in the calendar:
21250 ;; If it is on or past the date.
21251 (if (or (and (< diff 0)
21252 (and todayp (not org-agenda-only-exact-dates)))
21253 (= diff 0))
21254 (save-excursion
21255 (setq category (org-get-category))
21256 (if (re-search-backward "^\\*+[ \t]+" nil t)
21257 (progn
21258 (goto-char (match-end 0))
21259 (setq pos1 (match-beginning 0))
21260 (setq tags (org-get-tags-at))
21261 (setq head (buffer-substring-no-properties
21262 (point)
21263 (progn (skip-chars-forward "^\r\n") (point))))
21264 (setq donep (string-match org-looking-at-done-regexp head))
21265 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21266 (setq timestr
21267 (concat (substring s (match-beginning 1)) " "))
21268 (setq timestr 'time))
21269 (if (and donep
21270 (or org-agenda-skip-scheduled-if-done
21271 (not (= diff 0))))
21272 (setq txt nil)
21273 (setq txt (org-format-agenda-item
21274 (if (= diff 0)
21275 (car org-agenda-scheduled-leaders)
21276 (format (nth 1 org-agenda-scheduled-leaders)
21277 (- 1 diff)))
21278 head category tags timestr))))
21279 (setq txt org-agenda-no-heading-message))
21280 (when txt
21281 (setq face (if pastschedp
21282 'org-scheduled-previously
21283 'org-scheduled-today))
21284 (org-add-props txt props
21285 'undone-face face
21286 'face (if donep 'org-done face)
21287 'org-marker (org-agenda-new-marker pos)
21288 'org-hd-marker (org-agenda-new-marker pos1)
21289 'type (if pastschedp "past-scheduled" "scheduled")
21290 'date (if pastschedp d2 date)
21291 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21292 'org-category category)
21293 (push txt ee))))))
21294 (nreverse ee)))
21296 (defun org-agenda-get-blocks ()
21297 "Return the date-range information for agenda display."
21298 (let* ((props (list 'face nil
21299 'org-not-done-regexp org-not-done-regexp
21300 'org-todo-regexp org-todo-regexp
21301 'mouse-face 'highlight
21302 'keymap org-agenda-keymap
21303 'help-echo
21304 (format "mouse-2 or RET jump to org file %s"
21305 (abbreviate-file-name buffer-file-name))))
21306 (regexp org-tr-regexp)
21307 (d0 (calendar-absolute-from-gregorian date))
21308 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21309 donep head)
21310 (goto-char (point-min))
21311 (while (re-search-forward regexp nil t)
21312 (catch :skip
21313 (org-agenda-skip)
21314 (setq pos (point))
21315 (setq timestr (match-string 0)
21316 s1 (match-string 1)
21317 s2 (match-string 2)
21318 d1 (time-to-days (org-time-string-to-time s1))
21319 d2 (time-to-days (org-time-string-to-time s2)))
21320 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21321 ;; Only allow days between the limits, because the normal
21322 ;; date stamps will catch the limits.
21323 (save-excursion
21324 (setq marker (org-agenda-new-marker (point)))
21325 (setq category (org-get-category))
21326 (if (re-search-backward "^\\*+ " nil t)
21327 (progn
21328 (goto-char (match-beginning 0))
21329 (setq hdmarker (org-agenda-new-marker (point)))
21330 (setq tags (org-get-tags-at))
21331 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21332 (setq head (match-string 1))
21333 (and org-agenda-skip-timestamp-if-done
21334 (org-entry-is-done-p)
21335 (throw :skip t))
21336 (setq txt (org-format-agenda-item
21337 (format (if (= d1 d2) "" "(%d/%d): ")
21338 (1+ (- d0 d1)) (1+ (- d2 d1)))
21339 head category tags
21340 (if (= d0 d1) timestr))))
21341 (setq txt org-agenda-no-heading-message))
21342 (org-add-props txt props
21343 'org-marker marker 'org-hd-marker hdmarker
21344 'type "block" 'date date
21345 'priority (org-get-priority txt) 'org-category category)
21346 (push txt ee)))
21347 (goto-char pos)))
21348 ;; Sort the entries by expiration date.
21349 (nreverse ee)))
21351 ;;; Agenda presentation and sorting
21353 (defconst org-plain-time-of-day-regexp
21354 (concat
21355 "\\(\\<[012]?[0-9]"
21356 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21357 "\\(--?"
21358 "\\(\\<[012]?[0-9]"
21359 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21360 "\\)?")
21361 "Regular expression to match a plain time or time range.
21362 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21363 groups carry important information:
21364 0 the full match
21365 1 the first time, range or not
21366 8 the second time, if it is a range.")
21368 (defconst org-plain-time-extension-regexp
21369 (concat
21370 "\\(\\<[012]?[0-9]"
21371 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21372 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21373 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21374 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21375 groups carry important information:
21376 0 the full match
21377 7 hours of duration
21378 9 minutes of duration")
21380 (defconst org-stamp-time-of-day-regexp
21381 (concat
21382 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21383 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21384 "\\(--?"
21385 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21386 "Regular expression to match a timestamp time or time range.
21387 After a match, the following groups carry important information:
21388 0 the full match
21389 1 date plus weekday, for backreferencing to make sure both times on same day
21390 2 the first time, range or not
21391 4 the second time, if it is a range.")
21393 (defvar org-prefix-has-time nil
21394 "A flag, set by `org-compile-prefix-format'.
21395 The flag is set if the currently compiled format contains a `%t'.")
21396 (defvar org-prefix-has-tag nil
21397 "A flag, set by `org-compile-prefix-format'.
21398 The flag is set if the currently compiled format contains a `%T'.")
21400 (defun org-format-agenda-item (extra txt &optional category tags dotime
21401 noprefix remove-re)
21402 "Format TXT to be inserted into the agenda buffer.
21403 In particular, it adds the prefix and corresponding text properties. EXTRA
21404 must be a string and replaces the `%s' specifier in the prefix format.
21405 CATEGORY (string, symbol or nil) may be used to overrule the default
21406 category taken from local variable or file name. It will replace the `%c'
21407 specifier in the format. DOTIME, when non-nil, indicates that a
21408 time-of-day should be extracted from TXT for sorting of this entry, and for
21409 the `%t' specifier in the format. When DOTIME is a string, this string is
21410 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21411 only the correctly processes TXT should be returned - this is used by
21412 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21413 Any match of REMOVE-RE will be removed from TXT."
21414 (save-match-data
21415 ;; Diary entries sometimes have extra whitespace at the beginning
21416 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21417 (let* ((category (or category
21418 org-category
21419 (if buffer-file-name
21420 (file-name-sans-extension
21421 (file-name-nondirectory buffer-file-name))
21422 "")))
21423 (tag (if tags (nth (1- (length tags)) tags) ""))
21424 time ; time and tag are needed for the eval of the prefix format
21425 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21426 (time-of-day (and dotime (org-get-time-of-day ts)))
21427 stamp plain s0 s1 s2 rtn srp)
21428 (when (and dotime time-of-day org-prefix-has-time)
21429 ;; Extract starting and ending time and move them to prefix
21430 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21431 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21432 (setq s0 (match-string 0 ts)
21433 srp (and stamp (match-end 3))
21434 s1 (match-string (if plain 1 2) ts)
21435 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21437 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21438 ;; them, we might want to remove them there to avoid duplication.
21439 ;; The user can turn this off with a variable.
21440 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21441 (string-match (concat (regexp-quote s0) " *") txt)
21442 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21443 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21444 (= (match-beginning 0) 0)
21446 (setq txt (replace-match "" nil nil txt))))
21447 ;; Normalize the time(s) to 24 hour
21448 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21449 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21451 (when (and s1 (not s2) org-agenda-default-appointment-duration
21452 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21453 (let ((m (+ (string-to-number (match-string 2 s1))
21454 (* 60 (string-to-number (match-string 1 s1)))
21455 org-agenda-default-appointment-duration))
21457 (setq h (/ m 60) m (- m (* h 60)))
21458 (setq s2 (format "%02d:%02d" h m))))
21460 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21461 txt)
21462 ;; Tags are in the string
21463 (if (or (eq org-agenda-remove-tags t)
21464 (and org-agenda-remove-tags
21465 org-prefix-has-tag))
21466 (setq txt (replace-match "" t t txt))
21467 (setq txt (replace-match
21468 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21469 (match-string 2 txt))
21470 t t txt))))
21472 (when remove-re
21473 (while (string-match remove-re txt)
21474 (setq txt (replace-match "" t t txt))))
21476 ;; Create the final string
21477 (if noprefix
21478 (setq rtn txt)
21479 ;; Prepare the variables needed in the eval of the compiled format
21480 (setq time (cond (s2 (concat s1 "-" s2))
21481 (s1 (concat s1 "......"))
21482 (t ""))
21483 extra (or extra "")
21484 category (if (symbolp category) (symbol-name category) category))
21485 ;; Evaluate the compiled format
21486 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21488 ;; And finally add the text properties
21489 (org-add-props rtn nil
21490 'org-category (downcase category) 'tags tags
21491 'org-highest-priority org-highest-priority
21492 'org-lowest-priority org-lowest-priority
21493 'prefix-length (- (length rtn) (length txt))
21494 'time-of-day time-of-day
21495 'txt txt
21496 'time time
21497 'extra extra
21498 'dotime dotime))))
21500 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21501 (defvar org-agenda-sorting-strategy-selected nil)
21503 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21504 (catch 'exit
21505 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21506 ((and todayp (member 'today (car org-agenda-time-grid))))
21507 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21508 ((member 'weekly (car org-agenda-time-grid)))
21509 (t (throw 'exit list)))
21510 (let* ((have (delq nil (mapcar
21511 (lambda (x) (get-text-property 1 'time-of-day x))
21512 list)))
21513 (string (nth 1 org-agenda-time-grid))
21514 (gridtimes (nth 2 org-agenda-time-grid))
21515 (req (car org-agenda-time-grid))
21516 (remove (member 'remove-match req))
21517 new time)
21518 (if (and (member 'require-timed req) (not have))
21519 ;; don't show empty grid
21520 (throw 'exit list))
21521 (while (setq time (pop gridtimes))
21522 (unless (and remove (member time have))
21523 (setq time (int-to-string time))
21524 (push (org-format-agenda-item
21525 nil string "" nil
21526 (concat (substring time 0 -2) ":" (substring time -2)))
21527 new)
21528 (put-text-property
21529 1 (length (car new)) 'face 'org-time-grid (car new))))
21530 (if (member 'time-up org-agenda-sorting-strategy-selected)
21531 (append new list)
21532 (append list new)))))
21534 (defun org-compile-prefix-format (key)
21535 "Compile the prefix format into a Lisp form that can be evaluated.
21536 The resulting form is returned and stored in the variable
21537 `org-prefix-format-compiled'."
21538 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21539 (let ((s (cond
21540 ((stringp org-agenda-prefix-format)
21541 org-agenda-prefix-format)
21542 ((assq key org-agenda-prefix-format)
21543 (cdr (assq key org-agenda-prefix-format)))
21544 (t " %-12:c%?-12t% s")))
21545 (start 0)
21546 varform vars var e c f opt)
21547 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21548 s start)
21549 (setq var (cdr (assoc (match-string 4 s)
21550 '(("c" . category) ("t" . time) ("s" . extra)
21551 ("T" . tag))))
21552 c (or (match-string 3 s) "")
21553 opt (match-beginning 1)
21554 start (1+ (match-beginning 0)))
21555 (if (equal var 'time) (setq org-prefix-has-time t))
21556 (if (equal var 'tag) (setq org-prefix-has-tag t))
21557 (setq f (concat "%" (match-string 2 s) "s"))
21558 (if opt
21559 (setq varform
21560 `(if (equal "" ,var)
21562 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21563 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21564 (setq s (replace-match "%s" t nil s))
21565 (push varform vars))
21566 (setq vars (nreverse vars))
21567 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21569 (defun org-set-sorting-strategy (key)
21570 (if (symbolp (car org-agenda-sorting-strategy))
21571 ;; the old format
21572 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21573 (setq org-agenda-sorting-strategy-selected
21574 (or (cdr (assq key org-agenda-sorting-strategy))
21575 (cdr (assq 'agenda org-agenda-sorting-strategy))
21576 '(time-up category-keep priority-down)))))
21578 (defun org-get-time-of-day (s &optional string mod24)
21579 "Check string S for a time of day.
21580 If found, return it as a military time number between 0 and 2400.
21581 If not found, return nil.
21582 The optional STRING argument forces conversion into a 5 character wide string
21583 HH:MM."
21584 (save-match-data
21585 (when
21586 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21587 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21588 (let* ((h (string-to-number (match-string 1 s)))
21589 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21590 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21591 (am-p (equal ampm "am"))
21592 (h1 (cond ((not ampm) h)
21593 ((= h 12) (if am-p 0 12))
21594 (t (+ h (if am-p 0 12)))))
21595 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21596 (mod h1 24) h1))
21597 (t0 (+ (* 100 h2) m))
21598 (t1 (concat (if (>= h1 24) "+" " ")
21599 (if (< t0 100) "0" "")
21600 (if (< t0 10) "0" "")
21601 (int-to-string t0))))
21602 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21604 (defun org-finalize-agenda-entries (list &optional nosort)
21605 "Sort and concatenate the agenda items."
21606 (setq list (mapcar 'org-agenda-highlight-todo list))
21607 (if nosort
21608 list
21609 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21611 (defun org-agenda-highlight-todo (x)
21612 (let (re pl)
21613 (if (eq x 'line)
21614 (save-excursion
21615 (beginning-of-line 1)
21616 (setq re (get-text-property (point) 'org-todo-regexp))
21617 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21618 (when (looking-at (concat "[ \t]*\\.*" re " +"))
21619 (add-text-properties (match-beginning 0) (match-end 0)
21620 (list 'face (org-get-todo-face 0)))
21621 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
21622 (delete-region (match-beginning 1) (1- (match-end 0)))
21623 (goto-char (match-beginning 1))
21624 (insert (format org-agenda-todo-keyword-format s)))))
21625 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21626 pl (get-text-property 0 'prefix-length x))
21627 ; (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21628 ; (add-text-properties
21629 ; (or (match-end 1) (match-end 0)) (match-end 0)
21630 ; (list 'face (org-get-todo-face (match-string 2 x)))
21631 ; x))
21632 (when (and re
21633 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
21634 x (or pl 0)) pl))
21635 (add-text-properties
21636 (or (match-end 1) (match-end 0)) (match-end 0)
21637 (list 'face (org-get-todo-face (match-string 2 x)))
21639 (setq x (concat (substring x 0 (match-end 1))
21640 (format org-agenda-todo-keyword-format
21641 (match-string 2 x))
21643 (substring x (match-end 3)))))
21644 x)))
21646 (defsubst org-cmp-priority (a b)
21647 "Compare the priorities of string A and B."
21648 (let ((pa (or (get-text-property 1 'priority a) 0))
21649 (pb (or (get-text-property 1 'priority b) 0)))
21650 (cond ((> pa pb) +1)
21651 ((< pa pb) -1)
21652 (t nil))))
21654 (defsubst org-cmp-category (a b)
21655 "Compare the string values of categories of strings A and B."
21656 (let ((ca (or (get-text-property 1 'org-category a) ""))
21657 (cb (or (get-text-property 1 'org-category b) "")))
21658 (cond ((string-lessp ca cb) -1)
21659 ((string-lessp cb ca) +1)
21660 (t nil))))
21662 (defsubst org-cmp-tag (a b)
21663 "Compare the string values of categories of strings A and B."
21664 (let ((ta (car (last (get-text-property 1 'tags a))))
21665 (tb (car (last (get-text-property 1 'tags b)))))
21666 (cond ((not ta) +1)
21667 ((not tb) -1)
21668 ((string-lessp ta tb) -1)
21669 ((string-lessp tb ta) +1)
21670 (t nil))))
21672 (defsubst org-cmp-time (a b)
21673 "Compare the time-of-day values of strings A and B."
21674 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21675 (ta (or (get-text-property 1 'time-of-day a) def))
21676 (tb (or (get-text-property 1 'time-of-day b) def)))
21677 (cond ((< ta tb) -1)
21678 ((< tb ta) +1)
21679 (t nil))))
21681 (defun org-entries-lessp (a b)
21682 "Predicate for sorting agenda entries."
21683 ;; The following variables will be used when the form is evaluated.
21684 ;; So even though the compiler complains, keep them.
21685 (let* ((time-up (org-cmp-time a b))
21686 (time-down (if time-up (- time-up) nil))
21687 (priority-up (org-cmp-priority a b))
21688 (priority-down (if priority-up (- priority-up) nil))
21689 (category-up (org-cmp-category a b))
21690 (category-down (if category-up (- category-up) nil))
21691 (category-keep (if category-up +1 nil))
21692 (tag-up (org-cmp-tag a b))
21693 (tag-down (if tag-up (- tag-up) nil)))
21694 (cdr (assoc
21695 (eval (cons 'or org-agenda-sorting-strategy-selected))
21696 '((-1 . t) (1 . nil) (nil . nil))))))
21698 ;;; Agenda restriction lock
21700 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21701 "Overlay to mark the headline to which arenda commands are restricted.")
21702 (org-overlay-put org-agenda-restriction-lock-overlay
21703 'face 'org-agenda-restriction-lock)
21704 (org-overlay-put org-agenda-restriction-lock-overlay
21705 'help-echo "Agendas are currently limited to this subtree.")
21706 (org-detach-overlay org-agenda-restriction-lock-overlay)
21707 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21708 "Overlay marking the agenda restriction line in speedbar.")
21709 (org-overlay-put org-speedbar-restriction-lock-overlay
21710 'face 'org-agenda-restriction-lock)
21711 (org-overlay-put org-speedbar-restriction-lock-overlay
21712 'help-echo "Agendas are currently limited to this item.")
21713 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21715 (defun org-agenda-set-restriction-lock (&optional type)
21716 "Set restriction lock for agenda, to current subtree or file.
21717 Restriction will be the file if TYPE is `file', or if type is the
21718 universal prefix '(4), or if the cursor is before the first headline
21719 in the file. Otherwise, restriction will be to the current subtree."
21720 (interactive "P")
21721 (and (equal type '(4)) (setq type 'file))
21722 (setq type (cond
21723 (type type)
21724 ((org-at-heading-p) 'subtree)
21725 ((condition-case nil (org-back-to-heading t) (error nil))
21726 'subtree)
21727 (t 'file)))
21728 (if (eq type 'subtree)
21729 (progn
21730 (setq org-agenda-restrict t)
21731 (setq org-agenda-overriding-restriction 'subtree)
21732 (put 'org-agenda-files 'org-restrict
21733 (list (buffer-file-name (buffer-base-buffer))))
21734 (org-back-to-heading t)
21735 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21736 (move-marker org-agenda-restrict-begin (point))
21737 (move-marker org-agenda-restrict-end
21738 (save-excursion (org-end-of-subtree t)))
21739 (message "Locking agenda restriction to subtree"))
21740 (put 'org-agenda-files 'org-restrict
21741 (list (buffer-file-name (buffer-base-buffer))))
21742 (setq org-agenda-restrict nil)
21743 (setq org-agenda-overriding-restriction 'file)
21744 (move-marker org-agenda-restrict-begin nil)
21745 (move-marker org-agenda-restrict-end nil)
21746 (message "Locking agenda restriction to file"))
21747 (setq current-prefix-arg nil)
21748 (org-agenda-maybe-redo))
21750 (defun org-agenda-remove-restriction-lock (&optional noupdate)
21751 "Remove the agenda restriction lock."
21752 (interactive "P")
21753 (org-detach-overlay org-agenda-restriction-lock-overlay)
21754 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21755 (setq org-agenda-overriding-restriction nil)
21756 (setq org-agenda-restrict nil)
21757 (put 'org-agenda-files 'org-restrict nil)
21758 (move-marker org-agenda-restrict-begin nil)
21759 (move-marker org-agenda-restrict-end nil)
21760 (setq current-prefix-arg nil)
21761 (message "Agenda restriction lock removed")
21762 (or noupdate (org-agenda-maybe-redo)))
21764 (defun org-agenda-maybe-redo ()
21765 "If there is any window showing the agenda view, update it."
21766 (let ((w (get-buffer-window org-agenda-buffer-name t))
21767 (w0 (selected-window)))
21768 (when w
21769 (select-window w)
21770 (org-agenda-redo)
21771 (select-window w0)
21772 (if org-agenda-overriding-restriction
21773 (message "Agenda view shifted to new %s restriction"
21774 org-agenda-overriding-restriction)
21775 (message "Agenda restriction lock removed")))))
21777 ;;; Agenda commands
21779 (defun org-agenda-check-type (error &rest types)
21780 "Check if agenda buffer is of allowed type.
21781 If ERROR is non-nil, throw an error, otherwise just return nil."
21782 (if (memq org-agenda-type types)
21784 (if error
21785 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
21786 nil)))
21788 (defun org-agenda-quit ()
21789 "Exit agenda by removing the window or the buffer."
21790 (interactive)
21791 (let ((buf (current-buffer)))
21792 (if (not (one-window-p)) (delete-window))
21793 (kill-buffer buf)
21794 (org-agenda-maybe-reset-markers 'force)
21795 (org-columns-remove-overlays))
21796 ;; Maybe restore the pre-agenda window configuration.
21797 (and org-agenda-restore-windows-after-quit
21798 (not (eq org-agenda-window-setup 'other-frame))
21799 org-pre-agenda-window-conf
21800 (set-window-configuration org-pre-agenda-window-conf)))
21802 (defun org-agenda-exit ()
21803 "Exit agenda by removing the window or the buffer.
21804 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
21805 Org-mode buffers visited directly by the user will not be touched."
21806 (interactive)
21807 (org-release-buffers org-agenda-new-buffers)
21808 (setq org-agenda-new-buffers nil)
21809 (org-agenda-quit))
21811 (defun org-agenda-execute (arg)
21812 "Execute another agenda command, keeping same window.\\<global-map>
21813 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
21814 (interactive "P")
21815 (let ((org-agenda-window-setup 'current-window))
21816 (org-agenda arg)))
21818 (defun org-save-all-org-buffers ()
21819 "Save all Org-mode buffers without user confirmation."
21820 (interactive)
21821 (message "Saving all Org-mode buffers...")
21822 (save-some-buffers t 'org-mode-p)
21823 (message "Saving all Org-mode buffers... done"))
21825 (defun org-agenda-redo ()
21826 "Rebuild Agenda.
21827 When this is the global TODO list, a prefix argument will be interpreted."
21828 (interactive)
21829 (let* ((org-agenda-keep-modes t)
21830 (line (org-current-line))
21831 (window-line (- line (org-current-line (window-start))))
21832 (lprops (get 'org-agenda-redo-command 'org-lprops)))
21833 (message "Rebuilding agenda buffer...")
21834 (org-let lprops '(eval org-agenda-redo-command))
21835 (setq org-agenda-undo-list nil
21836 org-agenda-pending-undo-list nil)
21837 (message "Rebuilding agenda buffer...done")
21838 (goto-line line)
21839 (recenter window-line)))
21841 (defun org-agenda-goto-date (date)
21842 "Jump to DATE in agenda."
21843 (interactive (list (org-read-date)))
21844 (org-agenda-list nil date))
21846 (defun org-agenda-goto-today ()
21847 "Go to today."
21848 (interactive)
21849 (org-agenda-check-type t 'timeline 'agenda)
21850 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
21851 (cond
21852 (tdpos (goto-char tdpos))
21853 ((eq org-agenda-type 'agenda)
21854 (let* ((sd (time-to-days
21855 (time-subtract (current-time)
21856 (list 0 (* 3600 org-extend-today-until) 0))))
21857 (comp (org-agenda-compute-time-span sd org-agenda-span))
21858 (org-agenda-overriding-arguments org-agenda-last-arguments))
21859 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
21860 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
21861 (org-agenda-redo)
21862 (org-agenda-find-same-or-today-or-agenda)))
21863 (t (error "Cannot find today")))))
21865 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
21866 (goto-char
21867 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
21868 (text-property-any (point-min) (point-max) 'org-today t)
21869 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
21870 (point-min))))
21872 (defun org-agenda-later (arg)
21873 "Go forward in time by thee current span.
21874 With prefix ARG, go forward that many times the current span."
21875 (interactive "p")
21876 (org-agenda-check-type t 'agenda)
21877 (let* ((span org-agenda-span)
21878 (sd org-starting-day)
21879 (greg (calendar-gregorian-from-absolute sd))
21880 (cnt (get-text-property (point) 'org-day-cnt))
21881 greg2 nd)
21882 (cond
21883 ((eq span 'day)
21884 (setq sd (+ arg sd) nd 1))
21885 ((eq span 'week)
21886 (setq sd (+ (* 7 arg) sd) nd 7))
21887 ((eq span 'month)
21888 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
21889 sd (calendar-absolute-from-gregorian greg2))
21890 (setcar greg2 (1+ (car greg2)))
21891 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
21892 ((eq span 'year)
21893 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
21894 sd (calendar-absolute-from-gregorian greg2))
21895 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
21896 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
21897 (let ((org-agenda-overriding-arguments
21898 (list (car org-agenda-last-arguments) sd nd t)))
21899 (org-agenda-redo)
21900 (org-agenda-find-same-or-today-or-agenda cnt))))
21902 (defun org-agenda-earlier (arg)
21903 "Go backward in time by the current span.
21904 With prefix ARG, go backward that many times the current span."
21905 (interactive "p")
21906 (org-agenda-later (- arg)))
21908 (defun org-agenda-day-view ()
21909 "Switch to daily view for agenda."
21910 (interactive)
21911 (setq org-agenda-ndays 1)
21912 (org-agenda-change-time-span 'day))
21913 (defun org-agenda-week-view ()
21914 "Switch to daily view for agenda."
21915 (interactive)
21916 (setq org-agenda-ndays 7)
21917 (org-agenda-change-time-span 'week))
21918 (defun org-agenda-month-view ()
21919 "Switch to daily view for agenda."
21920 (interactive)
21921 (org-agenda-change-time-span 'month))
21922 (defun org-agenda-year-view ()
21923 "Switch to daily view for agenda."
21924 (interactive)
21925 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
21926 (org-agenda-change-time-span 'year)
21927 (error "Abort")))
21929 (defun org-agenda-change-time-span (span)
21930 "Change the agenda view to SPAN.
21931 SPAN may be `day', `week', `month', `year'."
21932 (org-agenda-check-type t 'agenda)
21933 (if (equal org-agenda-span span)
21934 (error "Viewing span is already \"%s\"" span))
21935 (let* ((sd (or (get-text-property (point) 'day)
21936 org-starting-day))
21937 (computed (org-agenda-compute-time-span sd span))
21938 (org-agenda-overriding-arguments
21939 (list (car org-agenda-last-arguments)
21940 (car computed) (cdr computed) t)))
21941 (org-agenda-redo)
21942 (org-agenda-find-same-or-today-or-agenda))
21943 (org-agenda-set-mode-name)
21944 (message "Switched to %s view" span))
21946 (defun org-agenda-compute-time-span (sd span)
21947 "Compute starting date and number of days for agenda.
21948 SPAN may be `day', `week', `month', `year'. The return value
21949 is a cons cell with the starting date and the number of days,
21950 so that the date SD will be in that range."
21951 (let* ((greg (calendar-gregorian-from-absolute sd))
21953 (cond
21954 ((eq span 'day)
21955 (setq nd 1))
21956 ((eq span 'week)
21957 (let* ((nt (calendar-day-of-week
21958 (calendar-gregorian-from-absolute sd)))
21959 (d (if org-agenda-start-on-weekday
21960 (- nt org-agenda-start-on-weekday)
21961 0)))
21962 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
21963 (setq nd 7)))
21964 ((eq span 'month)
21965 (setq sd (calendar-absolute-from-gregorian
21966 (list (car greg) 1 (nth 2 greg)))
21967 nd (- (calendar-absolute-from-gregorian
21968 (list (1+ (car greg)) 1 (nth 2 greg)))
21969 sd)))
21970 ((eq span 'year)
21971 (setq sd (calendar-absolute-from-gregorian
21972 (list 1 1 (nth 2 greg)))
21973 nd (- (calendar-absolute-from-gregorian
21974 (list 1 1 (1+ (nth 2 greg))))
21975 sd))))
21976 (cons sd nd)))
21978 ;; FIXME: does not work if user makes date format that starts with a blank
21979 (defun org-agenda-next-date-line (&optional arg)
21980 "Jump to the next line indicating a date in agenda buffer."
21981 (interactive "p")
21982 (org-agenda-check-type t 'agenda 'timeline)
21983 (beginning-of-line 1)
21984 (if (looking-at "^\\S-") (forward-char 1))
21985 (if (not (re-search-forward "^\\S-" nil t arg))
21986 (progn
21987 (backward-char 1)
21988 (error "No next date after this line in this buffer")))
21989 (goto-char (match-beginning 0)))
21991 (defun org-agenda-previous-date-line (&optional arg)
21992 "Jump to the previous line indicating a date in agenda buffer."
21993 (interactive "p")
21994 (org-agenda-check-type t 'agenda 'timeline)
21995 (beginning-of-line 1)
21996 (if (not (re-search-backward "^\\S-" nil t arg))
21997 (error "No previous date before this line in this buffer")))
21999 ;; Initialize the highlight
22000 (defvar org-hl (org-make-overlay 1 1))
22001 (org-overlay-put org-hl 'face 'highlight)
22003 (defun org-highlight (begin end &optional buffer)
22004 "Highlight a region with overlay."
22005 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22006 org-hl begin end (or buffer (current-buffer))))
22008 (defun org-unhighlight ()
22009 "Detach overlay INDEX."
22010 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22012 ;; FIXME this is currently not used.
22013 (defun org-highlight-until-next-command (beg end &optional buffer)
22014 (org-highlight beg end buffer)
22015 (add-hook 'pre-command-hook 'org-unhighlight-once))
22016 (defun org-unhighlight-once ()
22017 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22018 (org-unhighlight))
22020 (defun org-agenda-follow-mode ()
22021 "Toggle follow mode in an agenda buffer."
22022 (interactive)
22023 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22024 (org-agenda-set-mode-name)
22025 (message "Follow mode is %s"
22026 (if org-agenda-follow-mode "on" "off")))
22028 (defun org-agenda-log-mode ()
22029 "Toggle log mode in an agenda buffer."
22030 (interactive)
22031 (org-agenda-check-type t 'agenda 'timeline)
22032 (setq org-agenda-show-log (not org-agenda-show-log))
22033 (org-agenda-set-mode-name)
22034 (org-agenda-redo)
22035 (message "Log mode is %s"
22036 (if org-agenda-show-log "on" "off")))
22038 (defun org-agenda-toggle-diary ()
22039 "Toggle diary inclusion in an agenda buffer."
22040 (interactive)
22041 (org-agenda-check-type t 'agenda)
22042 (setq org-agenda-include-diary (not org-agenda-include-diary))
22043 (org-agenda-redo)
22044 (org-agenda-set-mode-name)
22045 (message "Diary inclusion turned %s"
22046 (if org-agenda-include-diary "on" "off")))
22048 (defun org-agenda-toggle-time-grid ()
22049 "Toggle time grid in an agenda buffer."
22050 (interactive)
22051 (org-agenda-check-type t 'agenda)
22052 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22053 (org-agenda-redo)
22054 (org-agenda-set-mode-name)
22055 (message "Time-grid turned %s"
22056 (if org-agenda-use-time-grid "on" "off")))
22058 (defun org-agenda-set-mode-name ()
22059 "Set the mode name to indicate all the small mode settings."
22060 (setq mode-name
22061 (concat "Org-Agenda"
22062 (if (equal org-agenda-ndays 1) " Day" "")
22063 (if (equal org-agenda-ndays 7) " Week" "")
22064 (if org-agenda-follow-mode " Follow" "")
22065 (if org-agenda-include-diary " Diary" "")
22066 (if org-agenda-use-time-grid " Grid" "")
22067 (if org-agenda-show-log " Log" "")))
22068 (force-mode-line-update))
22070 (defun org-agenda-post-command-hook ()
22071 (and (eolp) (not (bolp)) (backward-char 1))
22072 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22073 (if (and org-agenda-follow-mode
22074 (get-text-property (point) 'org-marker))
22075 (org-agenda-show)))
22077 (defun org-agenda-show-priority ()
22078 "Show the priority of the current item.
22079 This priority is composed of the main priority given with the [#A] cookies,
22080 and by additional input from the age of a schedules or deadline entry."
22081 (interactive)
22082 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22083 (message "Priority is %d" (if pri pri -1000))))
22085 (defun org-agenda-show-tags ()
22086 "Show the tags applicable to the current item."
22087 (interactive)
22088 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22089 (if tags
22090 (message "Tags are :%s:"
22091 (org-no-properties (mapconcat 'identity tags ":")))
22092 (message "No tags associated with this line"))))
22094 (defun org-agenda-goto (&optional highlight)
22095 "Go to the Org-mode file which contains the item at point."
22096 (interactive)
22097 (let* ((marker (or (get-text-property (point) 'org-marker)
22098 (org-agenda-error)))
22099 (buffer (marker-buffer marker))
22100 (pos (marker-position marker)))
22101 (switch-to-buffer-other-window buffer)
22102 (widen)
22103 (goto-char pos)
22104 (when (org-mode-p)
22105 (org-show-context 'agenda)
22106 (save-excursion
22107 (and (outline-next-heading)
22108 (org-flag-heading nil)))) ; show the next heading
22109 (run-hooks 'org-agenda-after-show-hook)
22110 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22112 (defvar org-agenda-after-show-hook nil
22113 "Normal hook run after an item has been shown from the agenda.
22114 Point is in the buffer where the item originated.")
22116 (defun org-agenda-kill ()
22117 "Kill the entry or subtree belonging to the current agenda entry."
22118 (interactive)
22119 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22120 (let* ((marker (or (get-text-property (point) 'org-marker)
22121 (org-agenda-error)))
22122 (buffer (marker-buffer marker))
22123 (pos (marker-position marker))
22124 (type (get-text-property (point) 'type))
22125 dbeg dend (n 0) conf)
22126 (org-with-remote-undo buffer
22127 (with-current-buffer buffer
22128 (save-excursion
22129 (goto-char pos)
22130 (if (and (org-mode-p) (not (member type '("sexp"))))
22131 (setq dbeg (progn (org-back-to-heading t) (point))
22132 dend (org-end-of-subtree t t))
22133 (setq dbeg (point-at-bol)
22134 dend (min (point-max) (1+ (point-at-eol)))))
22135 (goto-char dbeg)
22136 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22137 (setq conf (or (eq t org-agenda-confirm-kill)
22138 (and (numberp org-agenda-confirm-kill)
22139 (> n org-agenda-confirm-kill))))
22140 (and conf
22141 (not (y-or-n-p
22142 (format "Delete entry with %d lines in buffer \"%s\"? "
22143 n (buffer-name buffer))))
22144 (error "Abort"))
22145 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22146 (with-current-buffer buffer (delete-region dbeg dend))
22147 (message "Agenda item and source killed"))))
22149 (defun org-agenda-archive ()
22150 "Kill the entry or subtree belonging to the current agenda entry."
22151 (interactive)
22152 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22153 (let* ((marker (or (get-text-property (point) 'org-marker)
22154 (org-agenda-error)))
22155 (buffer (marker-buffer marker))
22156 (pos (marker-position marker)))
22157 (org-with-remote-undo buffer
22158 (with-current-buffer buffer
22159 (if (org-mode-p)
22160 (save-excursion
22161 (goto-char pos)
22162 (org-remove-subtree-entries-from-agenda)
22163 (org-back-to-heading t)
22164 (org-archive-subtree))
22165 (error "Archiving works only in Org-mode files"))))))
22167 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22168 "Remove all lines in the agenda that correspond to a given subtree.
22169 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22170 If this information is not given, the function uses the tree at point."
22171 (let ((buf (or buf (current-buffer))) m p)
22172 (save-excursion
22173 (unless (and beg end)
22174 (org-back-to-heading t)
22175 (setq beg (point))
22176 (org-end-of-subtree t)
22177 (setq end (point)))
22178 (set-buffer (get-buffer org-agenda-buffer-name))
22179 (save-excursion
22180 (goto-char (point-max))
22181 (beginning-of-line 1)
22182 (while (not (bobp))
22183 (when (and (setq m (get-text-property (point) 'org-marker))
22184 (equal buf (marker-buffer m))
22185 (setq p (marker-position m))
22186 (>= p beg)
22187 (<= p end))
22188 (let ((inhibit-read-only t))
22189 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22190 (beginning-of-line 0))))))
22192 (defun org-agenda-open-link ()
22193 "Follow the link in the current line, if any."
22194 (interactive)
22195 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22196 (save-excursion
22197 (save-restriction
22198 (narrow-to-region (point-at-bol) (point-at-eol))
22199 (org-open-at-point))))
22201 (defun org-agenda-copy-local-variable (var)
22202 "Get a variable from a referenced buffer and install it here."
22203 (let ((m (get-text-property (point) 'org-marker)))
22204 (when (and m (buffer-live-p (marker-buffer m)))
22205 (org-set-local var (with-current-buffer (marker-buffer m)
22206 (symbol-value var))))))
22208 (defun org-agenda-switch-to (&optional delete-other-windows)
22209 "Go to the Org-mode file which contains the item at point."
22210 (interactive)
22211 (let* ((marker (or (get-text-property (point) 'org-marker)
22212 (org-agenda-error)))
22213 (buffer (marker-buffer marker))
22214 (pos (marker-position marker)))
22215 (switch-to-buffer buffer)
22216 (and delete-other-windows (delete-other-windows))
22217 (widen)
22218 (goto-char pos)
22219 (when (org-mode-p)
22220 (org-show-context 'agenda)
22221 (save-excursion
22222 (and (outline-next-heading)
22223 (org-flag-heading nil)))))) ; show the next heading
22225 (defun org-agenda-goto-mouse (ev)
22226 "Go to the Org-mode file which contains the item at the mouse click."
22227 (interactive "e")
22228 (mouse-set-point ev)
22229 (org-agenda-goto))
22231 (defun org-agenda-show ()
22232 "Display the Org-mode file which contains the item at point."
22233 (interactive)
22234 (let ((win (selected-window)))
22235 (org-agenda-goto t)
22236 (select-window win)))
22238 (defun org-agenda-recenter (arg)
22239 "Display the Org-mode file which contains the item at point and recenter."
22240 (interactive "P")
22241 (let ((win (selected-window)))
22242 (org-agenda-goto t)
22243 (recenter arg)
22244 (select-window win)))
22246 (defun org-agenda-show-mouse (ev)
22247 "Display the Org-mode file which contains the item at the mouse click."
22248 (interactive "e")
22249 (mouse-set-point ev)
22250 (org-agenda-show))
22252 (defun org-agenda-check-no-diary ()
22253 "Check if the entry is a diary link and abort if yes."
22254 (if (get-text-property (point) 'org-agenda-diary-link)
22255 (org-agenda-error)))
22257 (defun org-agenda-error ()
22258 (error "Command not allowed in this line"))
22260 (defun org-agenda-tree-to-indirect-buffer ()
22261 "Show the subtree corresponding to the current entry in an indirect buffer.
22262 This calls the command `org-tree-to-indirect-buffer' from the original
22263 Org-mode buffer.
22264 With numerical prefix arg ARG, go up to this level and then take that tree.
22265 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22266 dedicated frame)."
22267 (interactive)
22268 (org-agenda-check-no-diary)
22269 (let* ((marker (or (get-text-property (point) 'org-marker)
22270 (org-agenda-error)))
22271 (buffer (marker-buffer marker))
22272 (pos (marker-position marker)))
22273 (with-current-buffer buffer
22274 (save-excursion
22275 (goto-char pos)
22276 (call-interactively 'org-tree-to-indirect-buffer)))))
22278 (defvar org-last-heading-marker (make-marker)
22279 "Marker pointing to the headline that last changed its TODO state
22280 by a remote command from the agenda.")
22282 (defun org-agenda-todo-nextset ()
22283 "Switch TODO entry to next sequence."
22284 (interactive)
22285 (org-agenda-todo 'nextset))
22287 (defun org-agenda-todo-previousset ()
22288 "Switch TODO entry to previous sequence."
22289 (interactive)
22290 (org-agenda-todo 'previousset))
22292 (defun org-agenda-todo (&optional arg)
22293 "Cycle TODO state of line at point, also in Org-mode file.
22294 This changes the line at point, all other lines in the agenda referring to
22295 the same tree node, and the headline of the tree node in the Org-mode file."
22296 (interactive "P")
22297 (org-agenda-check-no-diary)
22298 (let* ((col (current-column))
22299 (marker (or (get-text-property (point) 'org-marker)
22300 (org-agenda-error)))
22301 (buffer (marker-buffer marker))
22302 (pos (marker-position marker))
22303 (hdmarker (get-text-property (point) 'org-hd-marker))
22304 (inhibit-read-only t)
22305 newhead)
22306 (org-with-remote-undo buffer
22307 (with-current-buffer buffer
22308 (widen)
22309 (goto-char pos)
22310 (org-show-context 'agenda)
22311 (save-excursion
22312 (and (outline-next-heading)
22313 (org-flag-heading nil))) ; show the next heading
22314 (org-todo arg)
22315 (and (bolp) (forward-char 1))
22316 (setq newhead (org-get-heading))
22317 (save-excursion
22318 (org-back-to-heading)
22319 (move-marker org-last-heading-marker (point))))
22320 (beginning-of-line 1)
22321 (save-excursion
22322 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22323 (move-to-column col))))
22325 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22326 "Change all lines in the agenda buffer which match HDMARKER.
22327 The new content of the line will be NEWHEAD (as modified by
22328 `org-format-agenda-item'). HDMARKER is checked with
22329 `equal' against all `org-hd-marker' text properties in the file.
22330 If FIXFACE is non-nil, the face of each item is modified acording to
22331 the new TODO state."
22332 (let* ((inhibit-read-only t)
22333 props m pl undone-face done-face finish new dotime cat tags)
22334 (save-excursion
22335 (goto-char (point-max))
22336 (beginning-of-line 1)
22337 (while (not finish)
22338 (setq finish (bobp))
22339 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22340 (equal m hdmarker))
22341 (setq props (text-properties-at (point))
22342 dotime (get-text-property (point) 'dotime)
22343 cat (get-text-property (point) 'org-category)
22344 tags (get-text-property (point) 'tags)
22345 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22346 pl (get-text-property (point) 'prefix-length)
22347 undone-face (get-text-property (point) 'undone-face)
22348 done-face (get-text-property (point) 'done-face))
22349 (move-to-column pl)
22350 (cond
22351 ((equal new "")
22352 (beginning-of-line 1)
22353 (and (looking-at ".*\n?") (replace-match "")))
22354 ((looking-at ".*")
22355 (replace-match new t t)
22356 (beginning-of-line 1)
22357 (add-text-properties (point-at-bol) (point-at-eol) props)
22358 (when fixface
22359 (add-text-properties
22360 (point-at-bol) (point-at-eol)
22361 (list 'face
22362 (if org-last-todo-state-is-todo
22363 undone-face done-face))))
22364 (org-agenda-highlight-todo 'line)
22365 (beginning-of-line 1))
22366 (t (error "Line update did not work"))))
22367 (beginning-of-line 0)))
22368 (org-finalize-agenda)))
22370 (defun org-agenda-align-tags (&optional line)
22371 "Align all tags in agenda items to `org-agenda-tags-column'."
22372 (let ((inhibit-read-only t) l c)
22373 (save-excursion
22374 (goto-char (if line (point-at-bol) (point-min)))
22375 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22376 (if line (point-at-eol) nil) t)
22377 (add-text-properties
22378 (match-beginning 2) (match-end 2)
22379 (list 'face (list 'org-tag (get-text-property
22380 (match-beginning 2) 'face))))
22381 (setq l (- (match-end 2) (match-beginning 2))
22382 c (if (< org-agenda-tags-column 0)
22383 (- (abs org-agenda-tags-column) l)
22384 org-agenda-tags-column))
22385 (delete-region (match-beginning 1) (match-end 1))
22386 (goto-char (match-beginning 1))
22387 (insert (org-add-props
22388 (make-string (max 1 (- c (current-column))) ?\ )
22389 (text-properties-at (point))))))))
22391 (defun org-agenda-priority-up ()
22392 "Increase the priority of line at point, also in Org-mode file."
22393 (interactive)
22394 (org-agenda-priority 'up))
22396 (defun org-agenda-priority-down ()
22397 "Decrease the priority of line at point, also in Org-mode file."
22398 (interactive)
22399 (org-agenda-priority 'down))
22401 (defun org-agenda-priority (&optional force-direction)
22402 "Set the priority of line at point, also in Org-mode file.
22403 This changes the line at point, all other lines in the agenda referring to
22404 the same tree node, and the headline of the tree node in the Org-mode file."
22405 (interactive)
22406 (org-agenda-check-no-diary)
22407 (let* ((marker (or (get-text-property (point) 'org-marker)
22408 (org-agenda-error)))
22409 (hdmarker (get-text-property (point) 'org-hd-marker))
22410 (buffer (marker-buffer hdmarker))
22411 (pos (marker-position hdmarker))
22412 (inhibit-read-only t)
22413 newhead)
22414 (org-with-remote-undo buffer
22415 (with-current-buffer buffer
22416 (widen)
22417 (goto-char pos)
22418 (org-show-context 'agenda)
22419 (save-excursion
22420 (and (outline-next-heading)
22421 (org-flag-heading nil))) ; show the next heading
22422 (funcall 'org-priority force-direction)
22423 (end-of-line 1)
22424 (setq newhead (org-get-heading)))
22425 (org-agenda-change-all-lines newhead hdmarker)
22426 (beginning-of-line 1))))
22428 (defun org-get-tags-at (&optional pos)
22429 "Get a list of all headline tags applicable at POS.
22430 POS defaults to point. If tags are inherited, the list contains
22431 the targets in the same sequence as the headlines appear, i.e.
22432 the tags of the current headline come last."
22433 (interactive)
22434 (let (tags lastpos)
22435 (save-excursion
22436 (save-restriction
22437 (widen)
22438 (goto-char (or pos (point)))
22439 (save-match-data
22440 (org-back-to-heading t)
22441 (condition-case nil
22442 (while (not (equal lastpos (point)))
22443 (setq lastpos (point))
22444 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22445 (setq tags (append (org-split-string
22446 (org-match-string-no-properties 1) ":")
22447 tags)))
22448 (or org-use-tag-inheritance (error ""))
22449 (org-up-heading-all 1))
22450 (error nil))))
22451 tags)))
22453 ;; FIXME: should fix the tags property of the agenda line.
22454 (defun org-agenda-set-tags ()
22455 "Set tags for the current headline."
22456 (interactive)
22457 (org-agenda-check-no-diary)
22458 (if (and (org-region-active-p) (interactive-p))
22459 (call-interactively 'org-change-tag-in-region)
22460 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22461 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22462 (org-agenda-error)))
22463 (buffer (marker-buffer hdmarker))
22464 (pos (marker-position hdmarker))
22465 (inhibit-read-only t)
22466 newhead)
22467 (org-with-remote-undo buffer
22468 (with-current-buffer buffer
22469 (widen)
22470 (goto-char pos)
22471 (save-excursion
22472 (org-show-context 'agenda))
22473 (save-excursion
22474 (and (outline-next-heading)
22475 (org-flag-heading nil))) ; show the next heading
22476 (goto-char pos)
22477 (call-interactively 'org-set-tags)
22478 (end-of-line 1)
22479 (setq newhead (org-get-heading)))
22480 (org-agenda-change-all-lines newhead hdmarker)
22481 (beginning-of-line 1)))))
22483 (defun org-agenda-toggle-archive-tag ()
22484 "Toggle the archive tag for the current entry."
22485 (interactive)
22486 (org-agenda-check-no-diary)
22487 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22488 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22489 (org-agenda-error)))
22490 (buffer (marker-buffer hdmarker))
22491 (pos (marker-position hdmarker))
22492 (inhibit-read-only t)
22493 newhead)
22494 (org-with-remote-undo buffer
22495 (with-current-buffer buffer
22496 (widen)
22497 (goto-char pos)
22498 (org-show-context 'agenda)
22499 (save-excursion
22500 (and (outline-next-heading)
22501 (org-flag-heading nil))) ; show the next heading
22502 (call-interactively 'org-toggle-archive-tag)
22503 (end-of-line 1)
22504 (setq newhead (org-get-heading)))
22505 (org-agenda-change-all-lines newhead hdmarker)
22506 (beginning-of-line 1))))
22508 (defun org-agenda-date-later (arg &optional what)
22509 "Change the date of this item to one day later."
22510 (interactive "p")
22511 (org-agenda-check-type t 'agenda 'timeline)
22512 (org-agenda-check-no-diary)
22513 (let* ((marker (or (get-text-property (point) 'org-marker)
22514 (org-agenda-error)))
22515 (buffer (marker-buffer marker))
22516 (pos (marker-position marker)))
22517 (org-with-remote-undo buffer
22518 (with-current-buffer buffer
22519 (widen)
22520 (goto-char pos)
22521 (if (not (org-at-timestamp-p))
22522 (error "Cannot find time stamp"))
22523 (org-timestamp-change arg (or what 'day)))
22524 (org-agenda-show-new-time marker org-last-changed-timestamp))
22525 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22527 (defun org-agenda-date-earlier (arg &optional what)
22528 "Change the date of this item to one day earlier."
22529 (interactive "p")
22530 (org-agenda-date-later (- arg) what))
22532 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22533 "Show new date stamp via text properties."
22534 ;; We use text properties to make this undoable
22535 (let ((inhibit-read-only t))
22536 (setq stamp (concat " " prefix " => " stamp))
22537 (save-excursion
22538 (goto-char (point-max))
22539 (while (not (bobp))
22540 (when (equal marker (get-text-property (point) 'org-marker))
22541 (move-to-column (- (window-width) (length stamp)) t)
22542 (if (featurep 'xemacs)
22543 ;; Use `duplicable' property to trigger undo recording
22544 (let ((ex (make-extent nil nil))
22545 (gl (make-glyph stamp)))
22546 (set-glyph-face gl 'secondary-selection)
22547 (set-extent-properties
22548 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22549 (insert-extent ex (1- (point)) (point-at-eol)))
22550 (add-text-properties
22551 (1- (point)) (point-at-eol)
22552 (list 'display (org-add-props stamp nil
22553 'face 'secondary-selection))))
22554 (beginning-of-line 1))
22555 (beginning-of-line 0)))))
22557 (defun org-agenda-date-prompt (arg)
22558 "Change the date of this item. Date is prompted for, with default today.
22559 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22560 be used to request time specification in the time stamp."
22561 (interactive "P")
22562 (org-agenda-check-type t 'agenda 'timeline)
22563 (org-agenda-check-no-diary)
22564 (let* ((marker (or (get-text-property (point) 'org-marker)
22565 (org-agenda-error)))
22566 (buffer (marker-buffer marker))
22567 (pos (marker-position marker)))
22568 (org-with-remote-undo buffer
22569 (with-current-buffer buffer
22570 (widen)
22571 (goto-char pos)
22572 (if (not (org-at-timestamp-p))
22573 (error "Cannot find time stamp"))
22574 (org-time-stamp arg)
22575 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22577 (defun org-agenda-schedule (arg)
22578 "Schedule the item at point."
22579 (interactive "P")
22580 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22581 (org-agenda-check-no-diary)
22582 (let* ((marker (or (get-text-property (point) 'org-marker)
22583 (org-agenda-error)))
22584 (buffer (marker-buffer marker))
22585 (pos (marker-position marker))
22586 (org-insert-labeled-timestamps-at-point nil)
22588 (org-with-remote-undo buffer
22589 (with-current-buffer buffer
22590 (widen)
22591 (goto-char pos)
22592 (setq ts (org-schedule arg)))
22593 (org-agenda-show-new-time marker ts "S"))
22594 (message "Item scheduled for %s" ts)))
22596 (defun org-agenda-deadline (arg)
22597 "Schedule the item at point."
22598 (interactive "P")
22599 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22600 (org-agenda-check-no-diary)
22601 (let* ((marker (or (get-text-property (point) 'org-marker)
22602 (org-agenda-error)))
22603 (buffer (marker-buffer marker))
22604 (pos (marker-position marker))
22605 (org-insert-labeled-timestamps-at-point nil)
22607 (org-with-remote-undo buffer
22608 (with-current-buffer buffer
22609 (widen)
22610 (goto-char pos)
22611 (setq ts (org-deadline arg)))
22612 (org-agenda-show-new-time marker ts "S"))
22613 (message "Deadline for this item set to %s" ts)))
22615 (defun org-get-heading (&optional no-tags)
22616 "Return the heading of the current entry, without the stars."
22617 (save-excursion
22618 (org-back-to-heading t)
22619 (if (looking-at
22620 (if no-tags
22621 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22622 "\\*+[ \t]+\\([^\r\n]*\\)"))
22623 (match-string 1) "")))
22625 (defun org-agenda-clock-in (&optional arg)
22626 "Start the clock on the currently selected item."
22627 (interactive "P")
22628 (org-agenda-check-no-diary)
22629 (let* ((marker (or (get-text-property (point) 'org-marker)
22630 (org-agenda-error)))
22631 (pos (marker-position marker)))
22632 (org-with-remote-undo (marker-buffer marker)
22633 (with-current-buffer (marker-buffer marker)
22634 (widen)
22635 (goto-char pos)
22636 (org-clock-in)))))
22638 (defun org-agenda-clock-out (&optional arg)
22639 "Stop the currently running clock."
22640 (interactive "P")
22641 (unless (marker-buffer org-clock-marker)
22642 (error "No running clock"))
22643 (org-with-remote-undo (marker-buffer org-clock-marker)
22644 (org-clock-out)))
22646 (defun org-agenda-clock-cancel (&optional arg)
22647 "Cancel the currently running clock."
22648 (interactive "P")
22649 (unless (marker-buffer org-clock-marker)
22650 (error "No running clock"))
22651 (org-with-remote-undo (marker-buffer org-clock-marker)
22652 (org-clock-cancel)))
22654 (defun org-agenda-diary-entry ()
22655 "Make a diary entry, like the `i' command from the calendar.
22656 All the standard commands work: block, weekly etc."
22657 (interactive)
22658 (org-agenda-check-type t 'agenda 'timeline)
22659 (require 'diary-lib)
22660 (let* ((char (progn
22661 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22662 (read-char-exclusive)))
22663 (cmd (cdr (assoc char
22664 '((?d . insert-diary-entry)
22665 (?w . insert-weekly-diary-entry)
22666 (?m . insert-monthly-diary-entry)
22667 (?y . insert-yearly-diary-entry)
22668 (?a . insert-anniversary-diary-entry)
22669 (?b . insert-block-diary-entry)
22670 (?c . insert-cyclic-diary-entry)))))
22671 (oldf (symbol-function 'calendar-cursor-to-date))
22672 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22673 (point (point))
22674 (mark (or (mark t) (point))))
22675 (unless cmd
22676 (error "No command associated with <%c>" char))
22677 (unless (and (get-text-property point 'day)
22678 (or (not (equal ?b char))
22679 (get-text-property mark 'day)))
22680 (error "Don't know which date to use for diary entry"))
22681 ;; We implement this by hacking the `calendar-cursor-to-date' function
22682 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22683 (let ((calendar-mark-ring
22684 (list (calendar-gregorian-from-absolute
22685 (or (get-text-property mark 'day)
22686 (get-text-property point 'day))))))
22687 (unwind-protect
22688 (progn
22689 (fset 'calendar-cursor-to-date
22690 (lambda (&optional error)
22691 (calendar-gregorian-from-absolute
22692 (get-text-property point 'day))))
22693 (call-interactively cmd))
22694 (fset 'calendar-cursor-to-date oldf)))))
22697 (defun org-agenda-execute-calendar-command (cmd)
22698 "Execute a calendar command from the agenda, with the date associated to
22699 the cursor position."
22700 (org-agenda-check-type t 'agenda 'timeline)
22701 (require 'diary-lib)
22702 (unless (get-text-property (point) 'day)
22703 (error "Don't know which date to use for calendar command"))
22704 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22705 (point (point))
22706 (date (calendar-gregorian-from-absolute
22707 (get-text-property point 'day)))
22708 ;; the following 3 vars are needed in the calendar
22709 (displayed-day (extract-calendar-day date))
22710 (displayed-month (extract-calendar-month date))
22711 (displayed-year (extract-calendar-year date)))
22712 (unwind-protect
22713 (progn
22714 (fset 'calendar-cursor-to-date
22715 (lambda (&optional error)
22716 (calendar-gregorian-from-absolute
22717 (get-text-property point 'day))))
22718 (call-interactively cmd))
22719 (fset 'calendar-cursor-to-date oldf))))
22721 (defun org-agenda-phases-of-moon ()
22722 "Display the phases of the moon for the 3 months around the cursor date."
22723 (interactive)
22724 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22726 (defun org-agenda-holidays ()
22727 "Display the holidays for the 3 months around the cursor date."
22728 (interactive)
22729 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22731 (defvar calendar-longitude)
22732 (defvar calendar-latitude)
22733 (defvar calendar-location-name)
22735 (defun org-agenda-sunrise-sunset (arg)
22736 "Display sunrise and sunset for the cursor date.
22737 Latitude and longitude can be specified with the variables
22738 `calendar-latitude' and `calendar-longitude'. When called with prefix
22739 argument, latitude and longitude will be prompted for."
22740 (interactive "P")
22741 (require 'solar)
22742 (let ((calendar-longitude (if arg nil calendar-longitude))
22743 (calendar-latitude (if arg nil calendar-latitude))
22744 (calendar-location-name
22745 (if arg "the given coordinates" calendar-location-name)))
22746 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22748 (defun org-agenda-goto-calendar ()
22749 "Open the Emacs calendar with the date at the cursor."
22750 (interactive)
22751 (org-agenda-check-type t 'agenda 'timeline)
22752 (let* ((day (or (get-text-property (point) 'day)
22753 (error "Don't know which date to open in calendar")))
22754 (date (calendar-gregorian-from-absolute day))
22755 (calendar-move-hook nil)
22756 (view-calendar-holidays-initially nil)
22757 (view-diary-entries-initially nil))
22758 (calendar)
22759 (calendar-goto-date date)))
22761 (defun org-calendar-goto-agenda ()
22762 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
22763 This is a command that has to be installed in `calendar-mode-map'."
22764 (interactive)
22765 (org-agenda-list nil (calendar-absolute-from-gregorian
22766 (calendar-cursor-to-date))
22767 nil))
22769 (defun org-agenda-convert-date ()
22770 (interactive)
22771 (org-agenda-check-type t 'agenda 'timeline)
22772 (let ((day (get-text-property (point) 'day))
22773 date s)
22774 (unless day
22775 (error "Don't know which date to convert"))
22776 (setq date (calendar-gregorian-from-absolute day))
22777 (setq s (concat
22778 "Gregorian: " (calendar-date-string date) "\n"
22779 "ISO: " (calendar-iso-date-string date) "\n"
22780 "Day of Yr: " (calendar-day-of-year-string date) "\n"
22781 "Julian: " (calendar-julian-date-string date) "\n"
22782 "Astron. JD: " (calendar-astro-date-string date)
22783 " (Julian date number at noon UTC)\n"
22784 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
22785 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
22786 "French: " (calendar-french-date-string date) "\n"
22787 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
22788 "Mayan: " (calendar-mayan-date-string date) "\n"
22789 "Coptic: " (calendar-coptic-date-string date) "\n"
22790 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
22791 "Persian: " (calendar-persian-date-string date) "\n"
22792 "Chinese: " (calendar-chinese-date-string date) "\n"))
22793 (with-output-to-temp-buffer "*Dates*"
22794 (princ s))
22795 (if (fboundp 'fit-window-to-buffer)
22796 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
22799 ;;;; Embedded LaTeX
22801 (defvar org-cdlatex-mode-map (make-sparse-keymap)
22802 "Keymap for the minor `org-cdlatex-mode'.")
22804 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
22805 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
22806 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
22807 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
22808 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
22810 (defvar org-cdlatex-texmathp-advice-is-done nil
22811 "Flag remembering if we have applied the advice to texmathp already.")
22813 (define-minor-mode org-cdlatex-mode
22814 "Toggle the minor `org-cdlatex-mode'.
22815 This mode supports entering LaTeX environment and math in LaTeX fragments
22816 in Org-mode.
22817 \\{org-cdlatex-mode-map}"
22818 nil " OCDL" nil
22819 (when org-cdlatex-mode (require 'cdlatex))
22820 (unless org-cdlatex-texmathp-advice-is-done
22821 (setq org-cdlatex-texmathp-advice-is-done t)
22822 (defadvice texmathp (around org-math-always-on activate)
22823 "Always return t in org-mode buffers.
22824 This is because we want to insert math symbols without dollars even outside
22825 the LaTeX math segments. If Orgmode thinks that point is actually inside
22826 en embedded LaTeX fragement, let texmathp do its job.
22827 \\[org-cdlatex-mode-map]"
22828 (interactive)
22829 (let (p)
22830 (cond
22831 ((not (org-mode-p)) ad-do-it)
22832 ((eq this-command 'cdlatex-math-symbol)
22833 (setq ad-return-value t
22834 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
22836 (let ((p (org-inside-LaTeX-fragment-p)))
22837 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
22838 (setq ad-return-value t
22839 texmathp-why '("Org-mode embedded math" . 0))
22840 (if p ad-do-it)))))))))
22842 (defun turn-on-org-cdlatex ()
22843 "Unconditionally turn on `org-cdlatex-mode'."
22844 (org-cdlatex-mode 1))
22846 (defun org-inside-LaTeX-fragment-p ()
22847 "Test if point is inside a LaTeX fragment.
22848 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
22849 sequence appearing also before point.
22850 Even though the matchers for math are configurable, this function assumes
22851 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
22852 delimiters are skipped when they have been removed by customization.
22853 The return value is nil, or a cons cell with the delimiter and
22854 and the position of this delimiter.
22856 This function does a reasonably good job, but can locally be fooled by
22857 for example currency specifications. For example it will assume being in
22858 inline math after \"$22.34\". The LaTeX fragment formatter will only format
22859 fragments that are properly closed, but during editing, we have to live
22860 with the uncertainty caused by missing closing delimiters. This function
22861 looks only before point, not after."
22862 (catch 'exit
22863 (let ((pos (point))
22864 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
22865 (lim (progn
22866 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
22867 (point)))
22868 dd-on str (start 0) m re)
22869 (goto-char pos)
22870 (when dodollar
22871 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
22872 re (nth 1 (assoc "$" org-latex-regexps)))
22873 (while (string-match re str start)
22874 (cond
22875 ((= (match-end 0) (length str))
22876 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
22877 ((= (match-end 0) (- (length str) 5))
22878 (throw 'exit nil))
22879 (t (setq start (match-end 0))))))
22880 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
22881 (goto-char pos)
22882 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
22883 (and (match-beginning 2) (throw 'exit nil))
22884 ;; count $$
22885 (while (re-search-backward "\\$\\$" lim t)
22886 (setq dd-on (not dd-on)))
22887 (goto-char pos)
22888 (if dd-on (cons "$$" m))))))
22891 (defun org-try-cdlatex-tab ()
22892 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
22893 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
22894 - inside a LaTeX fragment, or
22895 - after the first word in a line, where an abbreviation expansion could
22896 insert a LaTeX environment."
22897 (when org-cdlatex-mode
22898 (cond
22899 ((save-excursion
22900 (skip-chars-backward "a-zA-Z0-9*")
22901 (skip-chars-backward " \t")
22902 (bolp))
22903 (cdlatex-tab) t)
22904 ((org-inside-LaTeX-fragment-p)
22905 (cdlatex-tab) t)
22906 (t nil))))
22908 (defun org-cdlatex-underscore-caret (&optional arg)
22909 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
22910 Revert to the normal definition outside of these fragments."
22911 (interactive "P")
22912 (if (org-inside-LaTeX-fragment-p)
22913 (call-interactively 'cdlatex-sub-superscript)
22914 (let (org-cdlatex-mode)
22915 (call-interactively (key-binding (vector last-input-event))))))
22917 (defun org-cdlatex-math-modify (&optional arg)
22918 "Execute `cdlatex-math-modify' in LaTeX fragments.
22919 Revert to the normal definition outside of these fragments."
22920 (interactive "P")
22921 (if (org-inside-LaTeX-fragment-p)
22922 (call-interactively 'cdlatex-math-modify)
22923 (let (org-cdlatex-mode)
22924 (call-interactively (key-binding (vector last-input-event))))))
22926 (defvar org-latex-fragment-image-overlays nil
22927 "List of overlays carrying the images of latex fragments.")
22928 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
22930 (defun org-remove-latex-fragment-image-overlays ()
22931 "Remove all overlays with LaTeX fragment images in current buffer."
22932 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
22933 (setq org-latex-fragment-image-overlays nil))
22935 (defun org-preview-latex-fragment (&optional subtree)
22936 "Preview the LaTeX fragment at point, or all locally or globally.
22937 If the cursor is in a LaTeX fragment, create the image and overlay
22938 it over the source code. If there is no fragment at point, display
22939 all fragments in the current text, from one headline to the next. With
22940 prefix SUBTREE, display all fragments in the current subtree. With a
22941 double prefix `C-u C-u', or when the cursor is before the first headline,
22942 display all fragments in the buffer.
22943 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
22944 (interactive "P")
22945 (org-remove-latex-fragment-image-overlays)
22946 (save-excursion
22947 (save-restriction
22948 (let (beg end at msg)
22949 (cond
22950 ((or (equal subtree '(16))
22951 (not (save-excursion
22952 (re-search-backward (concat "^" outline-regexp) nil t))))
22953 (setq beg (point-min) end (point-max)
22954 msg "Creating images for buffer...%s"))
22955 ((equal subtree '(4))
22956 (org-back-to-heading)
22957 (setq beg (point) end (org-end-of-subtree t)
22958 msg "Creating images for subtree...%s"))
22960 (if (setq at (org-inside-LaTeX-fragment-p))
22961 (goto-char (max (point-min) (- (cdr at) 2)))
22962 (org-back-to-heading))
22963 (setq beg (point) end (progn (outline-next-heading) (point))
22964 msg (if at "Creating image...%s"
22965 "Creating images for entry...%s"))))
22966 (message msg "")
22967 (narrow-to-region beg end)
22968 (goto-char beg)
22969 (org-format-latex
22970 (concat "ltxpng/" (file-name-sans-extension
22971 (file-name-nondirectory
22972 buffer-file-name)))
22973 default-directory 'overlays msg at 'forbuffer)
22974 (message msg "done. Use `C-c C-c' to remove images.")))))
22976 (defvar org-latex-regexps
22977 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
22978 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
22979 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
22980 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
22981 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
22982 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
22983 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
22984 "Regular expressions for matching embedded LaTeX.")
22986 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
22987 "Replace LaTeX fragments with links to an image, and produce images."
22988 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
22989 (let* ((prefixnodir (file-name-nondirectory prefix))
22990 (absprefix (expand-file-name prefix dir))
22991 (todir (file-name-directory absprefix))
22992 (opt org-format-latex-options)
22993 (matchers (plist-get opt :matchers))
22994 (re-list org-latex-regexps)
22995 (cnt 0) txt link beg end re e checkdir
22996 m n block linkfile movefile ov)
22997 ;; Check if there are old images files with this prefix, and remove them
22998 (when (file-directory-p todir)
22999 (mapc 'delete-file
23000 (directory-files
23001 todir 'full
23002 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23003 ;; Check the different regular expressions
23004 (while (setq e (pop re-list))
23005 (setq m (car e) re (nth 1 e) n (nth 2 e)
23006 block (if (nth 3 e) "\n\n" ""))
23007 (when (member m matchers)
23008 (goto-char (point-min))
23009 (while (re-search-forward re nil t)
23010 (when (or (not at) (equal (cdr at) (match-beginning n)))
23011 (setq txt (match-string n)
23012 beg (match-beginning n) end (match-end n)
23013 cnt (1+ cnt)
23014 linkfile (format "%s_%04d.png" prefix cnt)
23015 movefile (format "%s_%04d.png" absprefix cnt)
23016 link (concat block "[[file:" linkfile "]]" block))
23017 (if msg (message msg cnt))
23018 (goto-char beg)
23019 (unless checkdir ; make sure the directory exists
23020 (setq checkdir t)
23021 (or (file-directory-p todir) (make-directory todir)))
23022 (org-create-formula-image
23023 txt movefile opt forbuffer)
23024 (if overlays
23025 (progn
23026 (setq ov (org-make-overlay beg end))
23027 (if (featurep 'xemacs)
23028 (progn
23029 (org-overlay-put ov 'invisible t)
23030 (org-overlay-put
23031 ov 'end-glyph
23032 (make-glyph (vector 'png :file movefile))))
23033 (org-overlay-put
23034 ov 'display
23035 (list 'image :type 'png :file movefile :ascent 'center)))
23036 (push ov org-latex-fragment-image-overlays)
23037 (goto-char end))
23038 (delete-region beg end)
23039 (insert link))))))))
23041 ;; This function borrows from Ganesh Swami's latex2png.el
23042 (defun org-create-formula-image (string tofile options buffer)
23043 (let* ((tmpdir (if (featurep 'xemacs)
23044 (temp-directory)
23045 temporary-file-directory))
23046 (texfilebase (make-temp-name
23047 (expand-file-name "orgtex" tmpdir)))
23048 (texfile (concat texfilebase ".tex"))
23049 (dvifile (concat texfilebase ".dvi"))
23050 (pngfile (concat texfilebase ".png"))
23051 (fnh (face-attribute 'default :height nil))
23052 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23053 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23054 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23055 "Black"))
23056 (bg (or (plist-get options (if buffer :background :html-background))
23057 "Transparent")))
23058 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23059 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23060 (with-temp-file texfile
23061 (insert org-format-latex-header
23062 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23063 (let ((dir default-directory))
23064 (condition-case nil
23065 (progn
23066 (cd tmpdir)
23067 (call-process "latex" nil nil nil texfile))
23068 (error nil))
23069 (cd dir))
23070 (if (not (file-exists-p dvifile))
23071 (progn (message "Failed to create dvi file from %s" texfile) nil)
23072 (call-process "dvipng" nil nil nil
23073 "-E" "-fg" fg "-bg" bg
23074 "-D" dpi
23075 ;;"-x" scale "-y" scale
23076 "-T" "tight"
23077 "-o" pngfile
23078 dvifile)
23079 (if (not (file-exists-p pngfile))
23080 (progn (message "Failed to create png file from %s" texfile) nil)
23081 ;; Use the requested file name and clean up
23082 (copy-file pngfile tofile 'replace)
23083 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23084 (delete-file (concat texfilebase e)))
23085 pngfile))))
23087 (defun org-dvipng-color (attr)
23088 "Return an rgb color specification for dvipng."
23089 (apply 'format "rgb %s %s %s"
23090 (mapcar 'org-normalize-color
23091 (color-values (face-attribute 'default attr nil)))))
23093 (defun org-normalize-color (value)
23094 "Return string to be used as color value for an RGB component."
23095 (format "%g" (/ value 65535.0)))
23097 ;;;; Exporting
23099 ;;; Variables, constants, and parameter plists
23101 (defconst org-level-max 20)
23103 (defvar org-export-html-preamble nil
23104 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23105 (defvar org-export-html-postamble nil
23106 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23107 (defvar org-export-html-auto-preamble t
23108 "Should default preamble be inserted? Set by publishing functions.")
23109 (defvar org-export-html-auto-postamble t
23110 "Should default postamble be inserted? Set by publishing functions.")
23111 (defvar org-current-export-file nil) ; dynamically scoped parameter
23112 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23115 (defconst org-export-plist-vars
23116 '((:language . org-export-default-language)
23117 (:customtime . org-display-custom-times)
23118 (:headline-levels . org-export-headline-levels)
23119 (:section-numbers . org-export-with-section-numbers)
23120 (:table-of-contents . org-export-with-toc)
23121 (:preserve-breaks . org-export-preserve-breaks)
23122 (:archived-trees . org-export-with-archived-trees)
23123 (:emphasize . org-export-with-emphasize)
23124 (:sub-superscript . org-export-with-sub-superscripts)
23125 (:special-strings . org-export-with-special-strings)
23126 (:footnotes . org-export-with-footnotes)
23127 (:drawers . org-export-with-drawers)
23128 (:tags . org-export-with-tags)
23129 (:TeX-macros . org-export-with-TeX-macros)
23130 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23131 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23132 (:fixed-width . org-export-with-fixed-width)
23133 (:timestamps . org-export-with-timestamps)
23134 (:author-info . org-export-author-info)
23135 (:time-stamp-file . org-export-time-stamp-file)
23136 (:tables . org-export-with-tables)
23137 (:table-auto-headline . org-export-highlight-first-table-line)
23138 (:style . org-export-html-style)
23139 (:agenda-style . org-agenda-export-html-style)
23140 (:convert-org-links . org-export-html-link-org-files-as-html)
23141 (:inline-images . org-export-html-inline-images)
23142 (:html-extension . org-export-html-extension)
23143 (:html-table-tag . org-export-html-table-tag)
23144 (:expand-quoted-html . org-export-html-expand)
23145 (:timestamp . org-export-html-with-timestamp)
23146 (:publishing-directory . org-export-publishing-directory)
23147 (:preamble . org-export-html-preamble)
23148 (:postamble . org-export-html-postamble)
23149 (:auto-preamble . org-export-html-auto-preamble)
23150 (:auto-postamble . org-export-html-auto-postamble)
23151 (:author . user-full-name)
23152 (:email . user-mail-address)))
23154 (defun org-default-export-plist ()
23155 "Return the property list with default settings for the export variables."
23156 (let ((l org-export-plist-vars) rtn e)
23157 (while (setq e (pop l))
23158 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23159 rtn))
23161 (defun org-infile-export-plist ()
23162 "Return the property list with file-local settings for export."
23163 (save-excursion
23164 (save-restriction
23165 (widen)
23166 (goto-char 0)
23167 (let ((re (org-make-options-regexp
23168 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23169 p key val text options)
23170 (while (re-search-forward re nil t)
23171 (setq key (org-match-string-no-properties 1)
23172 val (org-match-string-no-properties 2))
23173 (cond
23174 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23175 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23176 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23177 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23178 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23179 ((string-equal key "TEXT")
23180 (setq text (if text (concat text "\n" val) val)))
23181 ((string-equal key "OPTIONS") (setq options val))))
23182 (setq p (plist-put p :text text))
23183 (when options
23184 (let ((op '(("H" . :headline-levels)
23185 ("num" . :section-numbers)
23186 ("toc" . :table-of-contents)
23187 ("\\n" . :preserve-breaks)
23188 ("@" . :expand-quoted-html)
23189 (":" . :fixed-width)
23190 ("|" . :tables)
23191 ("^" . :sub-superscript)
23192 ("-" . :special-strings)
23193 ("f" . :footnotes)
23194 ("d" . :drawers)
23195 ("tags" . :tags)
23196 ("*" . :emphasize)
23197 ("TeX" . :TeX-macros)
23198 ("LaTeX" . :LaTeX-fragments)
23199 ("skip" . :skip-before-1st-heading)
23200 ("author" . :author-info)
23201 ("timestamp" . :time-stamp-file)))
23203 (while (setq o (pop op))
23204 (if (string-match (concat (regexp-quote (car o))
23205 ":\\([^ \t\n\r;,.]*\\)")
23206 options)
23207 (setq p (plist-put p (cdr o)
23208 (car (read-from-string
23209 (match-string 1 options)))))))))
23210 p))))
23212 (defun org-export-directory (type plist)
23213 (let* ((val (plist-get plist :publishing-directory))
23214 (dir (if (listp val)
23215 (or (cdr (assoc type val)) ".")
23216 val)))
23217 dir))
23219 (defun org-skip-comments (lines)
23220 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23221 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23222 (re2 "^\\(\\*+\\)[ \t\n\r]")
23223 (case-fold-search nil)
23224 rtn line level)
23225 (while (setq line (pop lines))
23226 (cond
23227 ((and (string-match re1 line)
23228 (setq level (- (match-end 1) (match-beginning 1))))
23229 ;; Beginning of a COMMENT subtree. Skip it.
23230 (while (and (setq line (pop lines))
23231 (or (not (string-match re2 line))
23232 (> (- (match-end 1) (match-beginning 1)) level))))
23233 (setq lines (cons line lines)))
23234 ((string-match "^#" line)
23235 ;; an ordinary comment line
23237 ((and org-export-table-remove-special-lines
23238 (string-match "^[ \t]*|" line)
23239 (or (string-match "^[ \t]*| *[!_^] *|" line)
23240 (and (string-match "| *<[0-9]+> *|" line)
23241 (not (string-match "| *[^ <|]" line)))))
23242 ;; a special table line that should be removed
23244 (t (setq rtn (cons line rtn)))))
23245 (nreverse rtn)))
23247 (defun org-export (&optional arg)
23248 (interactive)
23249 (let ((help "[t] insert the export option template
23250 \[v] limit export to visible part of outline tree
23252 \[a] export as ASCII
23254 \[h] export as HTML
23255 \[H] export as HTML to temporary buffer
23256 \[R] export region as HTML
23257 \[b] export as HTML and browse immediately
23258 \[x] export as XOXO
23260 \[l] export as LaTeX
23261 \[L] export as LaTeX to temporary buffer
23263 \[i] export current file as iCalendar file
23264 \[I] export all agenda files as iCalendar files
23265 \[c] export agenda files into combined iCalendar file
23267 \[F] publish current file
23268 \[P] publish current project
23269 \[X] publish... (project will be prompted for)
23270 \[A] publish all projects")
23271 (cmds
23272 '((?t . org-insert-export-options-template)
23273 (?v . org-export-visible)
23274 (?a . org-export-as-ascii)
23275 (?h . org-export-as-html)
23276 (?b . org-export-as-html-and-open)
23277 (?H . org-export-as-html-to-buffer)
23278 (?R . org-export-region-as-html)
23279 (?x . org-export-as-xoxo)
23280 (?l . org-export-as-latex)
23281 (?L . org-export-as-latex-to-buffer)
23282 (?i . org-export-icalendar-this-file)
23283 (?I . org-export-icalendar-all-agenda-files)
23284 (?c . org-export-icalendar-combine-agenda-files)
23285 (?F . org-publish-current-file)
23286 (?P . org-publish-current-project)
23287 (?X . org-publish)
23288 (?A . org-publish-all)))
23289 r1 r2 ass)
23290 (save-window-excursion
23291 (delete-other-windows)
23292 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23293 (princ help))
23294 (message "Select command: ")
23295 (setq r1 (read-char-exclusive)))
23296 (setq r2 (if (< r1 27) (+ r1 96) r1))
23297 (if (setq ass (assq r2 cmds))
23298 (call-interactively (cdr ass))
23299 (error "No command associated with key %c" r1))))
23301 (defconst org-html-entities
23302 '(("nbsp")
23303 ("iexcl")
23304 ("cent")
23305 ("pound")
23306 ("curren")
23307 ("yen")
23308 ("brvbar")
23309 ("vert" . "&#124;")
23310 ("sect")
23311 ("uml")
23312 ("copy")
23313 ("ordf")
23314 ("laquo")
23315 ("not")
23316 ("shy")
23317 ("reg")
23318 ("macr")
23319 ("deg")
23320 ("plusmn")
23321 ("sup2")
23322 ("sup3")
23323 ("acute")
23324 ("micro")
23325 ("para")
23326 ("middot")
23327 ("odot"."o")
23328 ("star"."*")
23329 ("cedil")
23330 ("sup1")
23331 ("ordm")
23332 ("raquo")
23333 ("frac14")
23334 ("frac12")
23335 ("frac34")
23336 ("iquest")
23337 ("Agrave")
23338 ("Aacute")
23339 ("Acirc")
23340 ("Atilde")
23341 ("Auml")
23342 ("Aring") ("AA"."&Aring;")
23343 ("AElig")
23344 ("Ccedil")
23345 ("Egrave")
23346 ("Eacute")
23347 ("Ecirc")
23348 ("Euml")
23349 ("Igrave")
23350 ("Iacute")
23351 ("Icirc")
23352 ("Iuml")
23353 ("ETH")
23354 ("Ntilde")
23355 ("Ograve")
23356 ("Oacute")
23357 ("Ocirc")
23358 ("Otilde")
23359 ("Ouml")
23360 ("times")
23361 ("Oslash")
23362 ("Ugrave")
23363 ("Uacute")
23364 ("Ucirc")
23365 ("Uuml")
23366 ("Yacute")
23367 ("THORN")
23368 ("szlig")
23369 ("agrave")
23370 ("aacute")
23371 ("acirc")
23372 ("atilde")
23373 ("auml")
23374 ("aring")
23375 ("aelig")
23376 ("ccedil")
23377 ("egrave")
23378 ("eacute")
23379 ("ecirc")
23380 ("euml")
23381 ("igrave")
23382 ("iacute")
23383 ("icirc")
23384 ("iuml")
23385 ("eth")
23386 ("ntilde")
23387 ("ograve")
23388 ("oacute")
23389 ("ocirc")
23390 ("otilde")
23391 ("ouml")
23392 ("divide")
23393 ("oslash")
23394 ("ugrave")
23395 ("uacute")
23396 ("ucirc")
23397 ("uuml")
23398 ("yacute")
23399 ("thorn")
23400 ("yuml")
23401 ("fnof")
23402 ("Alpha")
23403 ("Beta")
23404 ("Gamma")
23405 ("Delta")
23406 ("Epsilon")
23407 ("Zeta")
23408 ("Eta")
23409 ("Theta")
23410 ("Iota")
23411 ("Kappa")
23412 ("Lambda")
23413 ("Mu")
23414 ("Nu")
23415 ("Xi")
23416 ("Omicron")
23417 ("Pi")
23418 ("Rho")
23419 ("Sigma")
23420 ("Tau")
23421 ("Upsilon")
23422 ("Phi")
23423 ("Chi")
23424 ("Psi")
23425 ("Omega")
23426 ("alpha")
23427 ("beta")
23428 ("gamma")
23429 ("delta")
23430 ("epsilon")
23431 ("varepsilon"."&epsilon;")
23432 ("zeta")
23433 ("eta")
23434 ("theta")
23435 ("iota")
23436 ("kappa")
23437 ("lambda")
23438 ("mu")
23439 ("nu")
23440 ("xi")
23441 ("omicron")
23442 ("pi")
23443 ("rho")
23444 ("sigmaf") ("varsigma"."&sigmaf;")
23445 ("sigma")
23446 ("tau")
23447 ("upsilon")
23448 ("phi")
23449 ("chi")
23450 ("psi")
23451 ("omega")
23452 ("thetasym") ("vartheta"."&thetasym;")
23453 ("upsih")
23454 ("piv")
23455 ("bull") ("bullet"."&bull;")
23456 ("hellip") ("dots"."&hellip;")
23457 ("prime")
23458 ("Prime")
23459 ("oline")
23460 ("frasl")
23461 ("weierp")
23462 ("image")
23463 ("real")
23464 ("trade")
23465 ("alefsym")
23466 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23467 ("uarr") ("uparrow"."&uarr;")
23468 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23469 ("darr")("downarrow"."&darr;")
23470 ("harr") ("leftrightarrow"."&harr;")
23471 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23472 ("lArr") ("Leftarrow"."&lArr;")
23473 ("uArr") ("Uparrow"."&uArr;")
23474 ("rArr") ("Rightarrow"."&rArr;")
23475 ("dArr") ("Downarrow"."&dArr;")
23476 ("hArr") ("Leftrightarrow"."&hArr;")
23477 ("forall")
23478 ("part") ("partial"."&part;")
23479 ("exist") ("exists"."&exist;")
23480 ("empty") ("emptyset"."&empty;")
23481 ("nabla")
23482 ("isin") ("in"."&isin;")
23483 ("notin")
23484 ("ni")
23485 ("prod")
23486 ("sum")
23487 ("minus")
23488 ("lowast") ("ast"."&lowast;")
23489 ("radic")
23490 ("prop") ("proptp"."&prop;")
23491 ("infin") ("infty"."&infin;")
23492 ("ang") ("angle"."&ang;")
23493 ("and") ("wedge"."&and;")
23494 ("or") ("vee"."&or;")
23495 ("cap")
23496 ("cup")
23497 ("int")
23498 ("there4")
23499 ("sim")
23500 ("cong") ("simeq"."&cong;")
23501 ("asymp")("approx"."&asymp;")
23502 ("ne") ("neq"."&ne;")
23503 ("equiv")
23504 ("le")
23505 ("ge")
23506 ("sub") ("subset"."&sub;")
23507 ("sup") ("supset"."&sup;")
23508 ("nsub")
23509 ("sube")
23510 ("supe")
23511 ("oplus")
23512 ("otimes")
23513 ("perp")
23514 ("sdot") ("cdot"."&sdot;")
23515 ("lceil")
23516 ("rceil")
23517 ("lfloor")
23518 ("rfloor")
23519 ("lang")
23520 ("rang")
23521 ("loz") ("Diamond"."&loz;")
23522 ("spades") ("spadesuit"."&spades;")
23523 ("clubs") ("clubsuit"."&clubs;")
23524 ("hearts") ("diamondsuit"."&hearts;")
23525 ("diams") ("diamondsuit"."&diams;")
23526 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23527 ("quot")
23528 ("amp")
23529 ("lt")
23530 ("gt")
23531 ("OElig")
23532 ("oelig")
23533 ("Scaron")
23534 ("scaron")
23535 ("Yuml")
23536 ("circ")
23537 ("tilde")
23538 ("ensp")
23539 ("emsp")
23540 ("thinsp")
23541 ("zwnj")
23542 ("zwj")
23543 ("lrm")
23544 ("rlm")
23545 ("ndash")
23546 ("mdash")
23547 ("lsquo")
23548 ("rsquo")
23549 ("sbquo")
23550 ("ldquo")
23551 ("rdquo")
23552 ("bdquo")
23553 ("dagger")
23554 ("Dagger")
23555 ("permil")
23556 ("lsaquo")
23557 ("rsaquo")
23558 ("euro")
23560 ("arccos"."arccos")
23561 ("arcsin"."arcsin")
23562 ("arctan"."arctan")
23563 ("arg"."arg")
23564 ("cos"."cos")
23565 ("cosh"."cosh")
23566 ("cot"."cot")
23567 ("coth"."coth")
23568 ("csc"."csc")
23569 ("deg"."deg")
23570 ("det"."det")
23571 ("dim"."dim")
23572 ("exp"."exp")
23573 ("gcd"."gcd")
23574 ("hom"."hom")
23575 ("inf"."inf")
23576 ("ker"."ker")
23577 ("lg"."lg")
23578 ("lim"."lim")
23579 ("liminf"."liminf")
23580 ("limsup"."limsup")
23581 ("ln"."ln")
23582 ("log"."log")
23583 ("max"."max")
23584 ("min"."min")
23585 ("Pr"."Pr")
23586 ("sec"."sec")
23587 ("sin"."sin")
23588 ("sinh"."sinh")
23589 ("sup"."sup")
23590 ("tan"."tan")
23591 ("tanh"."tanh")
23593 "Entities for TeX->HTML translation.
23594 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23595 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23596 In that case, \"\\ent\" will be translated to \"&other;\".
23597 The list contains HTML entities for Latin-1, Greek and other symbols.
23598 It is supplemented by a number of commonly used TeX macros with appropriate
23599 translations. There is currently no way for users to extend this.")
23601 ;;; General functions for all backends
23603 (defun org-cleaned-string-for-export (string &rest parameters)
23604 "Cleanup a buffer STRING so that links can be created safely."
23605 (interactive)
23606 (let* ((re-radio (and org-target-link-regexp
23607 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23608 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23609 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23610 (re-archive (concat ":" org-archive-tag ":"))
23611 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23612 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23613 (htmlp (plist-get parameters :for-html))
23614 (asciip (plist-get parameters :for-ascii))
23615 (latexp (plist-get parameters :for-LaTeX))
23616 (commentsp (plist-get parameters :comments))
23617 (archived-trees (plist-get parameters :archived-trees))
23618 (inhibit-read-only t)
23619 (drawers org-drawers)
23620 (exp-drawers (plist-get parameters :drawers))
23621 (outline-regexp "\\*+ ")
23622 a b xx
23623 rtn p)
23624 (with-current-buffer (get-buffer-create " org-mode-tmp")
23625 (erase-buffer)
23626 (insert string)
23627 ;; Remove license-to-kill stuff
23628 (while (setq p (text-property-any (point-min) (point-max)
23629 :org-license-to-kill t))
23630 (delete-region p (next-single-property-change p :org-license-to-kill)))
23632 (let ((org-inhibit-startup t)) (org-mode))
23633 (untabify (point-min) (point-max))
23635 ;; Get the correct stuff before the first headline
23636 (when (plist-get parameters :skip-before-1st-heading)
23637 (goto-char (point-min))
23638 (when (re-search-forward "^\\*+[ \t]" nil t)
23639 (delete-region (point-min) (match-beginning 0))
23640 (goto-char (point-min))
23641 (insert "\n")))
23642 (when (plist-get parameters :add-text)
23643 (goto-char (point-min))
23644 (insert (plist-get parameters :add-text) "\n"))
23646 ;; Get rid of archived trees
23647 (when (not (eq archived-trees t))
23648 (goto-char (point-min))
23649 (while (re-search-forward re-archive nil t)
23650 (if (not (org-on-heading-p t))
23651 (org-end-of-subtree t)
23652 (beginning-of-line 1)
23653 (setq a (if archived-trees
23654 (1+ (point-at-eol)) (point))
23655 b (org-end-of-subtree t))
23656 (if (> b a) (delete-region a b)))))
23658 ;; Get rid of drawers
23659 (unless (eq t exp-drawers)
23660 (goto-char (point-min))
23661 (let ((re (concat "^[ \t]*:\\("
23662 (mapconcat
23663 'identity
23664 (org-delete-all exp-drawers
23665 (copy-sequence drawers))
23666 "\\|")
23667 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23668 (while (re-search-forward re nil t)
23669 (replace-match ""))))
23671 ;; Find targets in comments and move them out of comments,
23672 ;; but mark them as targets that should be invisible
23673 (goto-char (point-min))
23674 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23675 (replace-match "\\1(INVISIBLE)"))
23677 ;; Protect backend specific stuff, throw away the others.
23678 (let ((formatters
23679 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23680 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23681 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23682 fmt)
23683 (goto-char (point-min))
23684 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23685 (goto-char (match-end 0))
23686 (while (not (looking-at "#\\+END_EXAMPLE"))
23687 (insert ": ")
23688 (beginning-of-line 2)))
23689 (goto-char (point-min))
23690 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23691 (add-text-properties (match-beginning 0) (match-end 0)
23692 '(org-protected t)))
23693 (while formatters
23694 (setq fmt (pop formatters))
23695 (when (car fmt)
23696 (goto-char (point-min))
23697 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23698 ":[ \t]*\\(.*\\)") nil t)
23699 (replace-match "\\1" t)
23700 (add-text-properties
23701 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23702 '(org-protected t))))
23703 (goto-char (point-min))
23704 (while (re-search-forward
23705 (concat "^#\\+"
23706 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23707 (cadddr fmt) "\\>.*\n?") nil t)
23708 (if (car fmt)
23709 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23710 '(org-protected t))
23711 (delete-region (match-beginning 0) (match-end 0))))))
23713 ;; Protect quoted subtrees
23714 (goto-char (point-min))
23715 (while (re-search-forward re-quote nil t)
23716 (goto-char (match-beginning 0))
23717 (end-of-line 1)
23718 (add-text-properties (point) (org-end-of-subtree t)
23719 '(org-protected t)))
23721 ;; Protect verbatim elements
23722 (goto-char (point-min))
23723 (while (re-search-forward org-verbatim-re nil t)
23724 (add-text-properties (match-beginning 4) (match-end 4)
23725 '(org-protected t))
23726 (goto-char (1+ (match-end 4))))
23728 ;; Remove subtrees that are commented
23729 (goto-char (point-min))
23730 (while (re-search-forward re-commented nil t)
23731 (goto-char (match-beginning 0))
23732 (delete-region (point) (org-end-of-subtree t)))
23734 ;; Remove special table lines
23735 (when org-export-table-remove-special-lines
23736 (goto-char (point-min))
23737 (while (re-search-forward "^[ \t]*|" nil t)
23738 (beginning-of-line 1)
23739 (if (or (looking-at "[ \t]*| *[!_^] *|")
23740 (and (looking-at ".*?| *<[0-9]+> *|")
23741 (not (looking-at ".*?| *[^ <|]"))))
23742 (delete-region (max (point-min) (1- (point-at-bol)))
23743 (point-at-eol))
23744 (end-of-line 1))))
23746 ;; Specific LaTeX stuff
23747 (when latexp
23748 (require 'org-export-latex nil)
23749 (org-export-latex-cleaned-string))
23751 (when asciip
23752 (org-export-ascii-clean-string))
23754 ;; Specific HTML stuff
23755 (when htmlp
23756 ;; Convert LaTeX fragments to images
23757 (when (plist-get parameters :LaTeX-fragments)
23758 (org-format-latex
23759 (concat "ltxpng/" (file-name-sans-extension
23760 (file-name-nondirectory
23761 org-current-export-file)))
23762 org-current-export-dir nil "Creating LaTeX image %s"))
23763 (message "Exporting..."))
23765 ;; Remove or replace comments
23766 (goto-char (point-min))
23767 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
23768 (if commentsp
23769 (progn (add-text-properties
23770 (match-beginning 0) (match-end 0) '(org-protected t))
23771 (replace-match (format commentsp (match-string 1)) t t))
23772 (replace-match "")))
23774 ;; Find matches for radio targets and turn them into internal links
23775 (goto-char (point-min))
23776 (when re-radio
23777 (while (re-search-forward re-radio nil t)
23778 (org-if-unprotected
23779 (replace-match "\\1[[\\2]]"))))
23781 ;; Find all links that contain a newline and put them into a single line
23782 (goto-char (point-min))
23783 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
23784 (org-if-unprotected
23785 (replace-match "\\1 \\3")
23786 (goto-char (match-beginning 0))))
23789 ;; Normalize links: Convert angle and plain links into bracket links
23790 ;; Expand link abbreviations
23791 (goto-char (point-min))
23792 (while (re-search-forward re-plain-link nil t)
23793 (goto-char (1- (match-end 0)))
23794 (org-if-unprotected
23795 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23796 ":" (match-string 3) "]]")))
23797 ;; added 'org-link face to links
23798 (put-text-property 0 (length s) 'face 'org-link s)
23799 (replace-match s t t))))
23800 (goto-char (point-min))
23801 (while (re-search-forward re-angle-link nil t)
23802 (goto-char (1- (match-end 0)))
23803 (org-if-unprotected
23804 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23805 ":" (match-string 3) "]]")))
23806 (put-text-property 0 (length s) 'face 'org-link s)
23807 (replace-match s t t))))
23808 (goto-char (point-min))
23809 (while (re-search-forward org-bracket-link-regexp nil t)
23810 (org-if-unprotected
23811 (let* ((s (concat "[[" (setq xx (save-match-data
23812 (org-link-expand-abbrev (match-string 1))))
23814 (if (match-end 3)
23815 (match-string 2)
23816 (concat "[" xx "]"))
23817 "]")))
23818 (put-text-property 0 (length s) 'face 'org-link s)
23819 (replace-match s t t))))
23821 ;; Find multiline emphasis and put them into single line
23822 (when (plist-get parameters :emph-multiline)
23823 (goto-char (point-min))
23824 (while (re-search-forward org-emph-re nil t)
23825 (if (not (= (char-after (match-beginning 3))
23826 (char-after (match-beginning 4))))
23827 (org-if-unprotected
23828 (subst-char-in-region (match-beginning 0) (match-end 0)
23829 ?\n ?\ t)
23830 (goto-char (1- (match-end 0))))
23831 (goto-char (1+ (match-beginning 0))))))
23833 (setq rtn (buffer-string)))
23834 (kill-buffer " org-mode-tmp")
23835 rtn))
23837 (defun org-export-grab-title-from-buffer ()
23838 "Get a title for the current document, from looking at the buffer."
23839 (let ((inhibit-read-only t))
23840 (save-excursion
23841 (goto-char (point-min))
23842 (let ((end (save-excursion (outline-next-heading) (point))))
23843 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
23844 ;; Mark the line so that it will not be exported as normal text.
23845 (org-unmodified
23846 (add-text-properties (match-beginning 0) (match-end 0)
23847 (list :org-license-to-kill t)))
23848 ;; Return the title string
23849 (org-trim (match-string 0)))))))
23851 (defun org-export-get-title-from-subtree ()
23852 "Return subtree title and exclude it from export."
23853 (let (title (m (mark)))
23854 (save-excursion
23855 (goto-char (region-beginning))
23856 (when (and (org-at-heading-p)
23857 (>= (org-end-of-subtree t t) (region-end)))
23858 ;; This is a subtree, we take the title from the first heading
23859 (goto-char (region-beginning))
23860 (looking-at org-todo-line-regexp)
23861 (setq title (match-string 3))
23862 (org-unmodified
23863 (add-text-properties (point) (1+ (point-at-eol))
23864 (list :org-license-to-kill t)))))
23865 title))
23867 (defun org-solidify-link-text (s &optional alist)
23868 "Take link text and make a safe target out of it."
23869 (save-match-data
23870 (let* ((rtn
23871 (mapconcat
23872 'identity
23873 (org-split-string s "[ \t\r\n]+") "--"))
23874 (a (assoc rtn alist)))
23875 (or (cdr a) rtn))))
23877 (defun org-get-min-level (lines)
23878 "Get the minimum level in LINES."
23879 (let ((re "^\\(\\*+\\) ") l min)
23880 (catch 'exit
23881 (while (setq l (pop lines))
23882 (if (string-match re l)
23883 (throw 'exit (org-tr-level (length (match-string 1 l))))))
23884 1)))
23886 ;; Variable holding the vector with section numbers
23887 (defvar org-section-numbers (make-vector org-level-max 0))
23889 (defun org-init-section-numbers ()
23890 "Initialize the vector for the section numbers."
23891 (let* ((level -1)
23892 (numbers (nreverse (org-split-string "" "\\.")))
23893 (depth (1- (length org-section-numbers)))
23894 (i depth) number-string)
23895 (while (>= i 0)
23896 (if (> i level)
23897 (aset org-section-numbers i 0)
23898 (setq number-string (or (car numbers) "0"))
23899 (if (string-match "\\`[A-Z]\\'" number-string)
23900 (aset org-section-numbers i
23901 (- (string-to-char number-string) ?A -1))
23902 (aset org-section-numbers i (string-to-number number-string)))
23903 (pop numbers))
23904 (setq i (1- i)))))
23906 (defun org-section-number (&optional level)
23907 "Return a string with the current section number.
23908 When LEVEL is non-nil, increase section numbers on that level."
23909 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
23910 (when level
23911 (when (> level -1)
23912 (aset org-section-numbers
23913 level (1+ (aref org-section-numbers level))))
23914 (setq idx (1+ level))
23915 (while (<= idx depth)
23916 (if (not (= idx 1))
23917 (aset org-section-numbers idx 0))
23918 (setq idx (1+ idx))))
23919 (setq idx 0)
23920 (while (<= idx depth)
23921 (setq n (aref org-section-numbers idx))
23922 (setq string (concat string (if (not (string= string "")) "." "")
23923 (int-to-string n)))
23924 (setq idx (1+ idx)))
23925 (save-match-data
23926 (if (string-match "\\`\\([@0]\\.\\)+" string)
23927 (setq string (replace-match "" t nil string)))
23928 (if (string-match "\\(\\.0\\)+\\'" string)
23929 (setq string (replace-match "" t nil string))))
23930 string))
23932 ;;; ASCII export
23934 (defvar org-last-level nil) ; dynamically scoped variable
23935 (defvar org-min-level nil) ; dynamically scoped variable
23936 (defvar org-levels-open nil) ; dynamically scoped parameter
23937 (defvar org-ascii-current-indentation nil) ; For communication
23939 (defun org-export-as-ascii (arg)
23940 "Export the outline as a pretty ASCII file.
23941 If there is an active region, export only the region.
23942 The prefix ARG specifies how many levels of the outline should become
23943 underlined headlines. The default is 3."
23944 (interactive "P")
23945 (setq-default org-todo-line-regexp org-todo-line-regexp)
23946 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23947 (org-infile-export-plist)))
23948 (region-p (org-region-active-p))
23949 (subtree-p
23950 (when region-p
23951 (save-excursion
23952 (goto-char (region-beginning))
23953 (and (org-at-heading-p)
23954 (>= (org-end-of-subtree t t) (region-end))))))
23955 (custom-times org-display-custom-times)
23956 (org-ascii-current-indentation '(0 . 0))
23957 (level 0) line txt
23958 (umax nil)
23959 (umax-toc nil)
23960 (case-fold-search nil)
23961 (filename (concat (file-name-as-directory
23962 (org-export-directory :ascii opt-plist))
23963 (file-name-sans-extension
23964 (or (and subtree-p
23965 (org-entry-get (region-beginning)
23966 "EXPORT_FILE_NAME" t))
23967 (file-name-nondirectory buffer-file-name)))
23968 ".txt"))
23969 (filename (if (equal (file-truename filename)
23970 (file-truename buffer-file-name))
23971 (concat filename ".txt")
23972 filename))
23973 (buffer (find-file-noselect filename))
23974 (org-levels-open (make-vector org-level-max nil))
23975 (odd org-odd-levels-only)
23976 (date (plist-get opt-plist :date))
23977 (author (plist-get opt-plist :author))
23978 (title (or (and subtree-p (org-export-get-title-from-subtree))
23979 (plist-get opt-plist :title)
23980 (and (not
23981 (plist-get opt-plist :skip-before-1st-heading))
23982 (org-export-grab-title-from-buffer))
23983 (file-name-sans-extension
23984 (file-name-nondirectory buffer-file-name))))
23985 (email (plist-get opt-plist :email))
23986 (language (plist-get opt-plist :language))
23987 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23988 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
23989 (todo nil)
23990 (lang-words nil)
23991 (region
23992 (buffer-substring
23993 (if (org-region-active-p) (region-beginning) (point-min))
23994 (if (org-region-active-p) (region-end) (point-max))))
23995 (lines (org-split-string
23996 (org-cleaned-string-for-export
23997 region
23998 :for-ascii t
23999 :skip-before-1st-heading
24000 (plist-get opt-plist :skip-before-1st-heading)
24001 :drawers (plist-get opt-plist :drawers)
24002 :verbatim-multiline t
24003 :archived-trees
24004 (plist-get opt-plist :archived-trees)
24005 :add-text (plist-get opt-plist :text))
24006 "\n"))
24007 thetoc have-headings first-heading-pos
24008 table-open table-buffer)
24010 (let ((inhibit-read-only t))
24011 (org-unmodified
24012 (remove-text-properties (point-min) (point-max)
24013 '(:org-license-to-kill t))))
24015 (setq org-min-level (org-get-min-level lines))
24016 (setq org-last-level org-min-level)
24017 (org-init-section-numbers)
24019 (find-file-noselect filename)
24021 (setq lang-words (or (assoc language org-export-language-setup)
24022 (assoc "en" org-export-language-setup)))
24023 (switch-to-buffer-other-window buffer)
24024 (erase-buffer)
24025 (fundamental-mode)
24026 ;; create local variables for all options, to make sure all called
24027 ;; functions get the correct information
24028 (mapc (lambda (x)
24029 (set (make-local-variable (cdr x))
24030 (plist-get opt-plist (car x))))
24031 org-export-plist-vars)
24032 (org-set-local 'org-odd-levels-only odd)
24033 (setq umax (if arg (prefix-numeric-value arg)
24034 org-export-headline-levels))
24035 (setq umax-toc (if (integerp org-export-with-toc)
24036 (min org-export-with-toc umax)
24037 umax))
24039 ;; File header
24040 (if title (org-insert-centered title ?=))
24041 (insert "\n")
24042 (if (and (or author email)
24043 org-export-author-info)
24044 (insert (concat (nth 1 lang-words) ": " (or author "")
24045 (if email (concat " <" email ">") "")
24046 "\n")))
24048 (cond
24049 ((and date (string-match "%" date))
24050 (setq date (format-time-string date (current-time))))
24051 (date)
24052 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24054 (if (and date org-export-time-stamp-file)
24055 (insert (concat (nth 2 lang-words) ": " date"\n")))
24057 (insert "\n\n")
24059 (if org-export-with-toc
24060 (progn
24061 (push (concat (nth 3 lang-words) "\n") thetoc)
24062 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24063 (mapc '(lambda (line)
24064 (if (string-match org-todo-line-regexp
24065 line)
24066 ;; This is a headline
24067 (progn
24068 (setq have-headings t)
24069 (setq level (- (match-end 1) (match-beginning 1))
24070 level (org-tr-level level)
24071 txt (match-string 3 line)
24072 todo
24073 (or (and org-export-mark-todo-in-toc
24074 (match-beginning 2)
24075 (not (member (match-string 2 line)
24076 org-done-keywords)))
24077 ; TODO, not DONE
24078 (and org-export-mark-todo-in-toc
24079 (= level umax-toc)
24080 (org-search-todo-below
24081 line lines level))))
24082 (setq txt (org-html-expand-for-ascii txt))
24084 (while (string-match org-bracket-link-regexp txt)
24085 (setq txt
24086 (replace-match
24087 (match-string (if (match-end 2) 3 1) txt)
24088 t t txt)))
24090 (if (and (memq org-export-with-tags '(not-in-toc nil))
24091 (string-match
24092 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24093 txt))
24094 (setq txt (replace-match "" t t txt)))
24095 (if (string-match quote-re0 txt)
24096 (setq txt (replace-match "" t t txt)))
24098 (if org-export-with-section-numbers
24099 (setq txt (concat (org-section-number level)
24100 " " txt)))
24101 (if (<= level umax-toc)
24102 (progn
24103 (push
24104 (concat
24105 (make-string
24106 (* (max 0 (- level org-min-level)) 4) ?\ )
24107 (format (if todo "%s (*)\n" "%s\n") txt))
24108 thetoc)
24109 (setq org-last-level level))
24110 ))))
24111 lines)
24112 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24114 (org-init-section-numbers)
24115 (while (setq line (pop lines))
24116 ;; Remove the quoted HTML tags.
24117 (setq line (org-html-expand-for-ascii line))
24118 ;; Remove targets
24119 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24120 (setq line (replace-match "" t t line)))
24121 ;; Replace internal links
24122 (while (string-match org-bracket-link-regexp line)
24123 (setq line (replace-match
24124 (if (match-end 3) "[\\3]" "[\\1]")
24125 t nil line)))
24126 (when custom-times
24127 (setq line (org-translate-time line)))
24128 (cond
24129 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24130 ;; a Headline
24131 (setq first-heading-pos (or first-heading-pos (point)))
24132 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24133 txt (match-string 2 line))
24134 (org-ascii-level-start level txt umax lines))
24136 ((and org-export-with-tables
24137 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24138 (if (not table-open)
24139 ;; New table starts
24140 (setq table-open t table-buffer nil))
24141 ;; Accumulate lines
24142 (setq table-buffer (cons line table-buffer))
24143 (when (or (not lines)
24144 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24145 (car lines))))
24146 (setq table-open nil
24147 table-buffer (nreverse table-buffer))
24148 (insert (mapconcat
24149 (lambda (x)
24150 (org-fix-indentation x org-ascii-current-indentation))
24151 (org-format-table-ascii table-buffer)
24152 "\n") "\n")))
24154 (setq line (org-fix-indentation line org-ascii-current-indentation))
24155 (if (and org-export-with-fixed-width
24156 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24157 (setq line (replace-match "\\1" nil nil line)))
24158 (insert line "\n"))))
24160 (normal-mode)
24162 ;; insert the table of contents
24163 (when thetoc
24164 (goto-char (point-min))
24165 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24166 (progn
24167 (goto-char (match-beginning 0))
24168 (replace-match ""))
24169 (goto-char first-heading-pos))
24170 (mapc 'insert thetoc)
24171 (or (looking-at "[ \t]*\n[ \t]*\n")
24172 (insert "\n\n")))
24174 ;; Convert whitespace place holders
24175 (goto-char (point-min))
24176 (let (beg end)
24177 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24178 (setq end (next-single-property-change beg 'org-whitespace))
24179 (goto-char beg)
24180 (delete-region beg end)
24181 (insert (make-string (- end beg) ?\ ))))
24183 (save-buffer)
24184 ;; remove display and invisible chars
24185 (let (beg end)
24186 (goto-char (point-min))
24187 (while (setq beg (next-single-property-change (point) 'display))
24188 (setq end (next-single-property-change beg 'display))
24189 (delete-region beg end)
24190 (goto-char beg)
24191 (insert "=>"))
24192 (goto-char (point-min))
24193 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24194 (setq end (next-single-property-change beg 'org-cwidth))
24195 (delete-region beg end)
24196 (goto-char beg)))
24197 (goto-char (point-min))))
24199 (defun org-export-ascii-clean-string ()
24200 "Do extra work for ASCII export"
24201 (goto-char (point-min))
24202 (while (re-search-forward org-verbatim-re nil t)
24203 (goto-char (match-end 2))
24204 (backward-delete-char 1) (insert "'")
24205 (goto-char (match-beginning 2))
24206 (delete-char 1) (insert "`")
24207 (goto-char (match-end 2))))
24209 (defun org-search-todo-below (line lines level)
24210 "Search the subtree below LINE for any TODO entries."
24211 (let ((rest (cdr (memq line lines)))
24212 (re org-todo-line-regexp)
24213 line lv todo)
24214 (catch 'exit
24215 (while (setq line (pop rest))
24216 (if (string-match re line)
24217 (progn
24218 (setq lv (- (match-end 1) (match-beginning 1))
24219 todo (and (match-beginning 2)
24220 (not (member (match-string 2 line)
24221 org-done-keywords))))
24222 ; TODO, not DONE
24223 (if (<= lv level) (throw 'exit nil))
24224 (if todo (throw 'exit t))))))))
24226 (defun org-html-expand-for-ascii (line)
24227 "Handle quoted HTML for ASCII export."
24228 (if org-export-html-expand
24229 (while (string-match "@<[^<>\n]*>" line)
24230 ;; We just remove the tags for now.
24231 (setq line (replace-match "" nil nil line))))
24232 line)
24234 (defun org-insert-centered (s &optional underline)
24235 "Insert the string S centered and underline it with character UNDERLINE."
24236 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24237 (insert (make-string ind ?\ ) s "\n")
24238 (if underline
24239 (insert (make-string ind ?\ )
24240 (make-string (string-width s) underline)
24241 "\n"))))
24243 (defun org-ascii-level-start (level title umax &optional lines)
24244 "Insert a new level in ASCII export."
24245 (let (char (n (- level umax 1)) (ind 0))
24246 (if (> level umax)
24247 (progn
24248 (insert (make-string (* 2 n) ?\ )
24249 (char-to-string (nth (% n (length org-export-ascii-bullets))
24250 org-export-ascii-bullets))
24251 " " title "\n")
24252 ;; find the indentation of the next non-empty line
24253 (catch 'stop
24254 (while lines
24255 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24256 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24257 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24258 (pop lines)))
24259 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24260 (if (or (not (equal (char-before) ?\n))
24261 (not (equal (char-before (1- (point))) ?\n)))
24262 (insert "\n"))
24263 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24264 (unless org-export-with-tags
24265 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24266 (setq title (replace-match "" t t title))))
24267 (if org-export-with-section-numbers
24268 (setq title (concat (org-section-number level) " " title)))
24269 (insert title "\n" (make-string (string-width title) char) "\n")
24270 (setq org-ascii-current-indentation '(0 . 0)))))
24272 (defun org-export-visible (type arg)
24273 "Create a copy of the visible part of the current buffer, and export it.
24274 The copy is created in a temporary buffer and removed after use.
24275 TYPE is the final key (as a string) that also select the export command in
24276 the `C-c C-e' export dispatcher.
24277 As a special case, if the you type SPC at the prompt, the temporary
24278 org-mode file will not be removed but presented to you so that you can
24279 continue to use it. The prefix arg ARG is passed through to the exporting
24280 command."
24281 (interactive
24282 (list (progn
24283 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24284 (read-char-exclusive))
24285 current-prefix-arg))
24286 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24287 (error "Invalid export key"))
24288 (let* ((binding (cdr (assoc type
24289 '((?a . org-export-as-ascii)
24290 (?\C-a . org-export-as-ascii)
24291 (?b . org-export-as-html-and-open)
24292 (?\C-b . org-export-as-html-and-open)
24293 (?h . org-export-as-html)
24294 (?H . org-export-as-html-to-buffer)
24295 (?R . org-export-region-as-html)
24296 (?x . org-export-as-xoxo)))))
24297 (keepp (equal type ?\ ))
24298 (file buffer-file-name)
24299 (buffer (get-buffer-create "*Org Export Visible*"))
24300 s e)
24301 ;; Need to hack the drawers here.
24302 (save-excursion
24303 (goto-char (point-min))
24304 (while (re-search-forward org-drawer-regexp nil t)
24305 (goto-char (match-beginning 1))
24306 (or (org-invisible-p) (org-flag-drawer nil))))
24307 (with-current-buffer buffer (erase-buffer))
24308 (save-excursion
24309 (setq s (goto-char (point-min)))
24310 (while (not (= (point) (point-max)))
24311 (goto-char (org-find-invisible))
24312 (append-to-buffer buffer s (point))
24313 (setq s (goto-char (org-find-visible))))
24314 (org-cycle-hide-drawers 'all)
24315 (goto-char (point-min))
24316 (unless keepp
24317 ;; Copy all comment lines to the end, to make sure #+ settings are
24318 ;; still available for the second export step. Kind of a hack, but
24319 ;; does do the trick.
24320 (if (looking-at "#[^\r\n]*")
24321 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24322 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24323 (append-to-buffer buffer (1+ (match-beginning 0))
24324 (min (point-max) (1+ (match-end 0))))))
24325 (set-buffer buffer)
24326 (let ((buffer-file-name file)
24327 (org-inhibit-startup t))
24328 (org-mode)
24329 (show-all)
24330 (unless keepp (funcall binding arg))))
24331 (if (not keepp)
24332 (kill-buffer buffer)
24333 (switch-to-buffer-other-window buffer)
24334 (goto-char (point-min)))))
24336 (defun org-find-visible ()
24337 (let ((s (point)))
24338 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24339 (get-char-property s 'invisible)))
24341 (defun org-find-invisible ()
24342 (let ((s (point)))
24343 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24344 (not (get-char-property s 'invisible))))
24347 ;;; HTML export
24349 (defun org-get-current-options ()
24350 "Return a string with current options as keyword options.
24351 Does include HTML export options as well as TODO and CATEGORY stuff."
24352 (format
24353 "#+TITLE: %s
24354 #+AUTHOR: %s
24355 #+EMAIL: %s
24356 #+LANGUAGE: %s
24357 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24358 #+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
24359 #+CATEGORY: %s
24360 #+SEQ_TODO: %s
24361 #+TYP_TODO: %s
24362 #+PRIORITIES: %c %c %c
24363 #+DRAWERS: %s
24364 #+STARTUP: %s %s %s %s %s
24365 #+TAGS: %s
24366 #+ARCHIVE: %s
24367 #+LINK: %s
24369 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24370 org-export-headline-levels
24371 org-export-with-section-numbers
24372 org-export-with-toc
24373 org-export-preserve-breaks
24374 org-export-html-expand
24375 org-export-with-fixed-width
24376 org-export-with-tables
24377 org-export-with-sub-superscripts
24378 org-export-with-special-strings
24379 org-export-with-footnotes
24380 org-export-with-emphasize
24381 org-export-with-TeX-macros
24382 org-export-with-LaTeX-fragments
24383 org-export-skip-text-before-1st-heading
24384 org-export-with-drawers
24385 org-export-with-tags
24386 (file-name-nondirectory buffer-file-name)
24387 "TODO FEEDBACK VERIFY DONE"
24388 "Me Jason Marie DONE"
24389 org-highest-priority org-lowest-priority org-default-priority
24390 (mapconcat 'identity org-drawers " ")
24391 (cdr (assoc org-startup-folded
24392 '((nil . "showall") (t . "overview") (content . "content"))))
24393 (if org-odd-levels-only "odd" "oddeven")
24394 (if org-hide-leading-stars "hidestars" "showstars")
24395 (if org-startup-align-all-tables "align" "noalign")
24396 (cond ((eq t org-log-done) "logdone")
24397 ((not org-log-done) "nologging")
24398 ((listp org-log-done)
24399 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
24400 org-log-done " ")))
24401 (or (mapconcat (lambda (x)
24402 (cond
24403 ((equal '(:startgroup) x) "{")
24404 ((equal '(:endgroup) x) "}")
24405 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24406 (t (car x))))
24407 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24408 org-archive-location
24409 "org file:~/org/%s.org"
24412 (defun org-insert-export-options-template ()
24413 "Insert into the buffer a template with information for exporting."
24414 (interactive)
24415 (if (not (bolp)) (newline))
24416 (let ((s (org-get-current-options)))
24417 (and (string-match "#\\+CATEGORY" s)
24418 (setq s (substring s 0 (match-beginning 0))))
24419 (insert s)))
24421 (defun org-toggle-fixed-width-section (arg)
24422 "Toggle the fixed-width export.
24423 If there is no active region, the QUOTE keyword at the current headline is
24424 inserted or removed. When present, it causes the text between this headline
24425 and the next to be exported as fixed-width text, and unmodified.
24426 If there is an active region, this command adds or removes a colon as the
24427 first character of this line. If the first character of a line is a colon,
24428 this line is also exported in fixed-width font."
24429 (interactive "P")
24430 (let* ((cc 0)
24431 (regionp (org-region-active-p))
24432 (beg (if regionp (region-beginning) (point)))
24433 (end (if regionp (region-end)))
24434 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24435 (case-fold-search nil)
24436 (re "[ \t]*\\(:\\)")
24437 off)
24438 (if regionp
24439 (save-excursion
24440 (goto-char beg)
24441 (setq cc (current-column))
24442 (beginning-of-line 1)
24443 (setq off (looking-at re))
24444 (while (> nlines 0)
24445 (setq nlines (1- nlines))
24446 (beginning-of-line 1)
24447 (cond
24448 (arg
24449 (move-to-column cc t)
24450 (insert ":\n")
24451 (forward-line -1))
24452 ((and off (looking-at re))
24453 (replace-match "" t t nil 1))
24454 ((not off) (move-to-column cc t) (insert ":")))
24455 (forward-line 1)))
24456 (save-excursion
24457 (org-back-to-heading)
24458 (if (looking-at (concat outline-regexp
24459 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24460 (replace-match "" t t nil 1)
24461 (if (looking-at outline-regexp)
24462 (progn
24463 (goto-char (match-end 0))
24464 (insert org-quote-string " "))))))))
24466 (defun org-export-as-html-and-open (arg)
24467 "Export the outline as HTML and immediately open it with a browser.
24468 If there is an active region, export only the region.
24469 The prefix ARG specifies how many levels of the outline should become
24470 headlines. The default is 3. Lower levels will become bulleted lists."
24471 (interactive "P")
24472 (org-export-as-html arg 'hidden)
24473 (org-open-file buffer-file-name))
24475 (defun org-export-as-html-batch ()
24476 "Call `org-export-as-html', may be used in batch processing as
24477 emacs --batch
24478 --load=$HOME/lib/emacs/org.el
24479 --eval \"(setq org-export-headline-levels 2)\"
24480 --visit=MyFile --funcall org-export-as-html-batch"
24481 (org-export-as-html org-export-headline-levels 'hidden))
24483 (defun org-export-as-html-to-buffer (arg)
24484 "Call `org-exort-as-html` with output to a temporary buffer.
24485 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24486 (interactive "P")
24487 (org-export-as-html arg nil nil "*Org HTML Export*")
24488 (switch-to-buffer-other-window "*Org HTML Export*"))
24490 (defun org-replace-region-by-html (beg end)
24491 "Assume the current region has org-mode syntax, and convert it to HTML.
24492 This can be used in any buffer. For example, you could write an
24493 itemized list in org-mode syntax in an HTML buffer and then use this
24494 command to convert it."
24495 (interactive "r")
24496 (let (reg html buf pop-up-frames)
24497 (save-window-excursion
24498 (if (org-mode-p)
24499 (setq html (org-export-region-as-html
24500 beg end t 'string))
24501 (setq reg (buffer-substring beg end)
24502 buf (get-buffer-create "*Org tmp*"))
24503 (with-current-buffer buf
24504 (erase-buffer)
24505 (insert reg)
24506 (org-mode)
24507 (setq html (org-export-region-as-html
24508 (point-min) (point-max) t 'string)))
24509 (kill-buffer buf)))
24510 (delete-region beg end)
24511 (insert html)))
24513 (defun org-export-region-as-html (beg end &optional body-only buffer)
24514 "Convert region from BEG to END in org-mode buffer to HTML.
24515 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24516 contents, and only produce the region of converted text, useful for
24517 cut-and-paste operations.
24518 If BUFFER is a buffer or a string, use/create that buffer as a target
24519 of the converted HTML. If BUFFER is the symbol `string', return the
24520 produced HTML as a string and leave not buffer behind. For example,
24521 a Lisp program could call this function in the following way:
24523 (setq html (org-export-region-as-html beg end t 'string))
24525 When called interactively, the output buffer is selected, and shown
24526 in a window. A non-interactive call will only retunr the buffer."
24527 (interactive "r\nP")
24528 (when (interactive-p)
24529 (setq buffer "*Org HTML Export*"))
24530 (let ((transient-mark-mode t) (zmacs-regions t)
24531 rtn)
24532 (goto-char end)
24533 (set-mark (point)) ;; to activate the region
24534 (goto-char beg)
24535 (setq rtn (org-export-as-html
24536 nil nil nil
24537 buffer body-only))
24538 (if (fboundp 'deactivate-mark) (deactivate-mark))
24539 (if (and (interactive-p) (bufferp rtn))
24540 (switch-to-buffer-other-window rtn)
24541 rtn)))
24543 (defvar html-table-tag nil) ; dynamically scoped into this.
24544 (defun org-export-as-html (arg &optional hidden ext-plist
24545 to-buffer body-only)
24546 "Export the outline as a pretty HTML file.
24547 If there is an active region, export only the region. The prefix
24548 ARG specifies how many levels of the outline should become
24549 headlines. The default is 3. Lower levels will become bulleted
24550 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24551 EXT-PLIST is a property list with external parameters overriding
24552 org-mode's default settings, but still inferior to file-local
24553 settings. When TO-BUFFER is non-nil, create a buffer with that
24554 name and export to that buffer. If TO-BUFFER is the symbol `string',
24555 don't leave any buffer behind but just return the resulting HTML as
24556 a string. When BODY-ONLY is set, don't produce the file header and footer,
24557 simply return the content of <body>...</body>, without even
24558 the body tags themselves."
24559 (interactive "P")
24561 ;; Make sure we have a file name when we need it.
24562 (when (and (not (or to-buffer body-only))
24563 (not buffer-file-name))
24564 (if (buffer-base-buffer)
24565 (org-set-local 'buffer-file-name
24566 (with-current-buffer (buffer-base-buffer)
24567 buffer-file-name))
24568 (error "Need a file name to be able to export.")))
24570 (message "Exporting...")
24571 (setq-default org-todo-line-regexp org-todo-line-regexp)
24572 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24573 (setq-default org-done-keywords org-done-keywords)
24574 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24575 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24576 ext-plist
24577 (org-infile-export-plist)))
24579 (style (plist-get opt-plist :style))
24580 (link-validate (plist-get opt-plist :link-validation-function))
24581 valid thetoc have-headings first-heading-pos
24582 (odd org-odd-levels-only)
24583 (region-p (org-region-active-p))
24584 (subtree-p
24585 (when region-p
24586 (save-excursion
24587 (goto-char (region-beginning))
24588 (and (org-at-heading-p)
24589 (>= (org-end-of-subtree t t) (region-end))))))
24590 ;; The following two are dynamically scoped into other
24591 ;; routines below.
24592 (org-current-export-dir (org-export-directory :html opt-plist))
24593 (org-current-export-file buffer-file-name)
24594 (level 0) (line "") (origline "") txt todo
24595 (umax nil)
24596 (umax-toc nil)
24597 (filename (if to-buffer nil
24598 (expand-file-name
24599 (concat
24600 (file-name-sans-extension
24601 (or (and subtree-p
24602 (org-entry-get (region-beginning)
24603 "EXPORT_FILE_NAME" t))
24604 (file-name-nondirectory buffer-file-name)))
24605 "." org-export-html-extension)
24606 (file-name-as-directory
24607 (org-export-directory :html opt-plist)))))
24608 (current-dir (if buffer-file-name
24609 (file-name-directory buffer-file-name)
24610 default-directory))
24611 (buffer (if to-buffer
24612 (cond
24613 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24614 (t (get-buffer-create to-buffer)))
24615 (find-file-noselect filename)))
24616 (org-levels-open (make-vector org-level-max nil))
24617 (date (plist-get opt-plist :date))
24618 (author (plist-get opt-plist :author))
24619 (title (or (and subtree-p (org-export-get-title-from-subtree))
24620 (plist-get opt-plist :title)
24621 (and (not
24622 (plist-get opt-plist :skip-before-1st-heading))
24623 (org-export-grab-title-from-buffer))
24624 (and buffer-file-name
24625 (file-name-sans-extension
24626 (file-name-nondirectory buffer-file-name)))
24627 "UNTITLED"))
24628 (html-table-tag (plist-get opt-plist :html-table-tag))
24629 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24630 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24631 (inquote nil)
24632 (infixed nil)
24633 (in-local-list nil)
24634 (local-list-num nil)
24635 (local-list-indent nil)
24636 (llt org-plain-list-ordered-item-terminator)
24637 (email (plist-get opt-plist :email))
24638 (language (plist-get opt-plist :language))
24639 (lang-words nil)
24640 (target-alist nil) tg
24641 (head-count 0) cnt
24642 (start 0)
24643 (coding-system (and (boundp 'buffer-file-coding-system)
24644 buffer-file-coding-system))
24645 (coding-system-for-write (or org-export-html-coding-system
24646 coding-system))
24647 (save-buffer-coding-system (or org-export-html-coding-system
24648 coding-system))
24649 (charset (and coding-system-for-write
24650 (fboundp 'coding-system-get)
24651 (coding-system-get coding-system-for-write
24652 'mime-charset)))
24653 (region
24654 (buffer-substring
24655 (if region-p (region-beginning) (point-min))
24656 (if region-p (region-end) (point-max))))
24657 (lines
24658 (org-split-string
24659 (org-cleaned-string-for-export
24660 region
24661 :emph-multiline t
24662 :for-html t
24663 :skip-before-1st-heading
24664 (plist-get opt-plist :skip-before-1st-heading)
24665 :drawers (plist-get opt-plist :drawers)
24666 :archived-trees
24667 (plist-get opt-plist :archived-trees)
24668 :add-text
24669 (plist-get opt-plist :text)
24670 :LaTeX-fragments
24671 (plist-get opt-plist :LaTeX-fragments))
24672 "[\r\n]"))
24673 table-open type
24674 table-buffer table-orig-buffer
24675 ind start-is-num starter didclose
24676 rpl path desc descp desc1 desc2 link
24679 (let ((inhibit-read-only t))
24680 (org-unmodified
24681 (remove-text-properties (point-min) (point-max)
24682 '(:org-license-to-kill t))))
24684 (message "Exporting...")
24686 (setq org-min-level (org-get-min-level lines))
24687 (setq org-last-level org-min-level)
24688 (org-init-section-numbers)
24690 (cond
24691 ((and date (string-match "%" date))
24692 (setq date (format-time-string date (current-time))))
24693 (date)
24694 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24696 ;; Get the language-dependent settings
24697 (setq lang-words (or (assoc language org-export-language-setup)
24698 (assoc "en" org-export-language-setup)))
24700 ;; Switch to the output buffer
24701 (set-buffer buffer)
24702 (let ((inhibit-read-only t)) (erase-buffer))
24703 (fundamental-mode)
24705 (and (fboundp 'set-buffer-file-coding-system)
24706 (set-buffer-file-coding-system coding-system-for-write))
24708 (let ((case-fold-search nil)
24709 (org-odd-levels-only odd))
24710 ;; create local variables for all options, to make sure all called
24711 ;; functions get the correct information
24712 (mapc (lambda (x)
24713 (set (make-local-variable (cdr x))
24714 (plist-get opt-plist (car x))))
24715 org-export-plist-vars)
24716 (setq umax (if arg (prefix-numeric-value arg)
24717 org-export-headline-levels))
24718 (setq umax-toc (if (integerp org-export-with-toc)
24719 (min org-export-with-toc umax)
24720 umax))
24721 (unless body-only
24722 ;; File header
24723 (insert (format
24724 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24725 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24726 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24727 lang=\"%s\" xml:lang=\"%s\">
24728 <head>
24729 <title>%s</title>
24730 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24731 <meta name=\"generator\" content=\"Org-mode\"/>
24732 <meta name=\"generated\" content=\"%s\"/>
24733 <meta name=\"author\" content=\"%s\"/>
24735 </head><body>
24737 language language (org-html-expand title)
24738 (or charset "iso-8859-1") date author style))
24740 (insert (or (plist-get opt-plist :preamble) ""))
24742 (when (plist-get opt-plist :auto-preamble)
24743 (if title (insert (format org-export-html-title-format
24744 (org-html-expand title))))))
24746 (if (and org-export-with-toc (not body-only))
24747 (progn
24748 (push (format "<h%d>%s</h%d>\n"
24749 org-export-html-toplevel-hlevel
24750 (nth 3 lang-words)
24751 org-export-html-toplevel-hlevel)
24752 thetoc)
24753 (push "<ul>\n<li>" thetoc)
24754 (setq lines
24755 (mapcar '(lambda (line)
24756 (if (string-match org-todo-line-regexp line)
24757 ;; This is a headline
24758 (progn
24759 (setq have-headings t)
24760 (setq level (- (match-end 1) (match-beginning 1))
24761 level (org-tr-level level)
24762 txt (save-match-data
24763 (org-html-expand
24764 (org-export-cleanup-toc-line
24765 (match-string 3 line))))
24766 todo
24767 (or (and org-export-mark-todo-in-toc
24768 (match-beginning 2)
24769 (not (member (match-string 2 line)
24770 org-done-keywords)))
24771 ; TODO, not DONE
24772 (and org-export-mark-todo-in-toc
24773 (= level umax-toc)
24774 (org-search-todo-below
24775 line lines level))))
24776 (if (string-match
24777 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
24778 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
24779 (if (string-match quote-re0 txt)
24780 (setq txt (replace-match "" t t txt)))
24781 (if org-export-with-section-numbers
24782 (setq txt (concat (org-section-number level)
24783 " " txt)))
24784 (if (<= level (max umax umax-toc))
24785 (setq head-count (+ head-count 1)))
24786 (if (<= level umax-toc)
24787 (progn
24788 (if (> level org-last-level)
24789 (progn
24790 (setq cnt (- level org-last-level))
24791 (while (>= (setq cnt (1- cnt)) 0)
24792 (push "\n<ul>\n<li>" thetoc))
24793 (push "\n" thetoc)))
24794 (if (< level org-last-level)
24795 (progn
24796 (setq cnt (- org-last-level level))
24797 (while (>= (setq cnt (1- cnt)) 0)
24798 (push "</li>\n</ul>" thetoc))
24799 (push "\n" thetoc)))
24800 ;; Check for targets
24801 (while (string-match org-target-regexp line)
24802 (setq tg (match-string 1 line)
24803 line (replace-match
24804 (concat "@<span class=\"target\">" tg "@</span> ")
24805 t t line))
24806 (push (cons (org-solidify-link-text tg)
24807 (format "sec-%d" head-count))
24808 target-alist))
24809 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
24810 (setq txt (replace-match "" t t txt)))
24811 (push
24812 (format
24813 (if todo
24814 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
24815 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
24816 head-count txt) thetoc)
24818 (setq org-last-level level))
24820 line)
24821 lines))
24822 (while (> org-last-level (1- org-min-level))
24823 (setq org-last-level (1- org-last-level))
24824 (push "</li>\n</ul>\n" thetoc))
24825 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24827 (setq head-count 0)
24828 (org-init-section-numbers)
24830 (while (setq line (pop lines) origline line)
24831 (catch 'nextline
24833 ;; end of quote section?
24834 (when (and inquote (string-match "^\\*+ " line))
24835 (insert "</pre>\n")
24836 (setq inquote nil))
24837 ;; inside a quote section?
24838 (when inquote
24839 (insert (org-html-protect line) "\n")
24840 (throw 'nextline nil))
24842 ;; verbatim lines
24843 (when (and org-export-with-fixed-width
24844 (string-match "^[ \t]*:\\(.*\\)" line))
24845 (when (not infixed)
24846 (setq infixed t)
24847 (insert "<pre>\n"))
24848 (insert (org-html-protect (match-string 1 line)) "\n")
24849 (when (and lines
24850 (not (string-match "^[ \t]*\\(:.*\\)"
24851 (car lines))))
24852 (setq infixed nil)
24853 (insert "</pre>\n"))
24854 (throw 'nextline nil))
24856 ;; Protected HTML
24857 (when (get-text-property 0 'org-protected line)
24858 (let (par)
24859 (when (re-search-backward
24860 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
24861 (setq par (match-string 1))
24862 (replace-match "\\2\n"))
24863 (insert line "\n")
24864 (while (and lines
24865 (or (= (length (car lines)) 0)
24866 (get-text-property 0 'org-protected (car lines))))
24867 (insert (pop lines) "\n"))
24868 (and par (insert "<p>\n")))
24869 (throw 'nextline nil))
24871 ;; Horizontal line
24872 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
24873 (insert "\n<hr/>\n")
24874 (throw 'nextline nil))
24876 ;; make targets to anchors
24877 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
24878 (cond
24879 ((match-end 2)
24880 (setq line (replace-match
24881 (concat "@<a name=\""
24882 (org-solidify-link-text (match-string 1 line))
24883 "\">\\nbsp@</a>")
24884 t t line)))
24885 ((and org-export-with-toc (equal (string-to-char line) ?*))
24886 (setq line (replace-match
24887 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
24888 ; (concat "@<i>" (match-string 1 line) "@</i> ")
24889 t t line)))
24891 (setq line (replace-match
24892 (concat "@<a name=\""
24893 (org-solidify-link-text (match-string 1 line))
24894 "\" class=\"target\">" (match-string 1 line) "@</a> ")
24895 t t line)))))
24897 (setq line (org-html-handle-time-stamps line))
24899 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
24900 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
24901 ;; Also handle sub_superscripts and checkboxes
24902 (or (string-match org-table-hline-regexp line)
24903 (setq line (org-html-expand line)))
24905 ;; Format the links
24906 (setq start 0)
24907 (while (string-match org-bracket-link-analytic-regexp line start)
24908 (setq start (match-beginning 0))
24909 (setq type (if (match-end 2) (match-string 2 line) "internal"))
24910 (setq path (match-string 3 line))
24911 (setq desc1 (if (match-end 5) (match-string 5 line))
24912 desc2 (if (match-end 2) (concat type ":" path) path)
24913 descp (and desc1 (not (equal desc1 desc2)))
24914 desc (or desc1 desc2))
24915 ;; Make an image out of the description if that is so wanted
24916 (when (and descp (org-file-image-p desc))
24917 (save-match-data
24918 (if (string-match "^file:" desc)
24919 (setq desc (substring desc (match-end 0)))))
24920 (setq desc (concat "<img src=\"" desc "\"/>")))
24921 ;; FIXME: do we need to unescape here somewhere?
24922 (cond
24923 ((equal type "internal")
24924 (setq rpl
24925 (concat
24926 "<a href=\"#"
24927 (org-solidify-link-text
24928 (save-match-data (org-link-unescape path)) target-alist)
24929 "\">" desc "</a>")))
24930 ((member type '("http" "https"))
24931 ;; standard URL, just check if we need to inline an image
24932 (if (and (or (eq t org-export-html-inline-images)
24933 (and org-export-html-inline-images (not descp)))
24934 (org-file-image-p path))
24935 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
24936 (setq link (concat type ":" path))
24937 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
24938 ((member type '("ftp" "mailto" "news"))
24939 ;; standard URL
24940 (setq link (concat type ":" path))
24941 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
24942 ((string= type "file")
24943 ;; FILE link
24944 (let* ((filename path)
24945 (abs-p (file-name-absolute-p filename))
24946 thefile file-is-image-p search)
24947 (save-match-data
24948 (if (string-match "::\\(.*\\)" filename)
24949 (setq search (match-string 1 filename)
24950 filename (replace-match "" t nil filename)))
24951 (setq valid
24952 (if (functionp link-validate)
24953 (funcall link-validate filename current-dir)
24955 (setq file-is-image-p (org-file-image-p filename))
24956 (setq thefile (if abs-p (expand-file-name filename) filename))
24957 (when (and org-export-html-link-org-files-as-html
24958 (string-match "\\.org$" thefile))
24959 (setq thefile (concat (substring thefile 0
24960 (match-beginning 0))
24961 "." org-export-html-extension))
24962 (if (and search
24963 ;; make sure this is can be used as target search
24964 (not (string-match "^[0-9]*$" search))
24965 (not (string-match "^\\*" search))
24966 (not (string-match "^/.*/$" search)))
24967 (setq thefile (concat thefile "#"
24968 (org-solidify-link-text
24969 (org-link-unescape search)))))
24970 (when (string-match "^file:" desc)
24971 (setq desc (replace-match "" t t desc))
24972 (if (string-match "\\.org$" desc)
24973 (setq desc (replace-match "" t t desc))))))
24974 (setq rpl (if (and file-is-image-p
24975 (or (eq t org-export-html-inline-images)
24976 (and org-export-html-inline-images
24977 (not descp))))
24978 (concat "<img src=\"" thefile "\"/>")
24979 (concat "<a href=\"" thefile "\">" desc "</a>")))
24980 (if (not valid) (setq rpl desc))))
24981 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
24982 (setq rpl (concat "<i>&lt;" type ":"
24983 (save-match-data (org-link-unescape path))
24984 "&gt;</i>"))))
24985 (setq line (replace-match rpl t t line)
24986 start (+ start (length rpl))))
24988 ;; TODO items
24989 (if (and (string-match org-todo-line-regexp line)
24990 (match-beginning 2))
24992 (setq line
24993 (concat (substring line 0 (match-beginning 2))
24994 "<span class=\""
24995 (if (member (match-string 2 line)
24996 org-done-keywords)
24997 "done" "todo")
24998 "\">" (match-string 2 line)
24999 "</span>" (substring line (match-end 2)))))
25001 ;; Does this contain a reference to a footnote?
25002 (when org-export-with-footnotes
25003 (setq start 0)
25004 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25005 (if (get-text-property (match-beginning 2) 'org-protected line)
25006 (setq start (match-end 2))
25007 (let ((n (match-string 2 line)))
25008 (setq line
25009 (replace-match
25010 (format
25011 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25012 (match-string 1 line) n n n)
25013 t t line))))))
25015 (cond
25016 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25017 ;; This is a headline
25018 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25019 txt (match-string 2 line))
25020 (if (string-match quote-re0 txt)
25021 (setq txt (replace-match "" t t txt)))
25022 (if (<= level (max umax umax-toc))
25023 (setq head-count (+ head-count 1)))
25024 (when in-local-list
25025 ;; Close any local lists before inserting a new header line
25026 (while local-list-num
25027 (org-close-li)
25028 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25029 (pop local-list-num))
25030 (setq local-list-indent nil
25031 in-local-list nil))
25032 (setq first-heading-pos (or first-heading-pos (point)))
25033 (org-html-level-start level txt umax
25034 (and org-export-with-toc (<= level umax))
25035 head-count)
25036 ;; QUOTES
25037 (when (string-match quote-re line)
25038 (insert "<pre>")
25039 (setq inquote t)))
25041 ((and org-export-with-tables
25042 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25043 (if (not table-open)
25044 ;; New table starts
25045 (setq table-open t table-buffer nil table-orig-buffer nil))
25046 ;; Accumulate lines
25047 (setq table-buffer (cons line table-buffer)
25048 table-orig-buffer (cons origline table-orig-buffer))
25049 (when (or (not lines)
25050 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25051 (car lines))))
25052 (setq table-open nil
25053 table-buffer (nreverse table-buffer)
25054 table-orig-buffer (nreverse table-orig-buffer))
25055 (org-close-par-maybe)
25056 (insert (org-format-table-html table-buffer table-orig-buffer))))
25058 ;; Normal lines
25059 (when (string-match
25060 (cond
25061 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25062 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25063 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25064 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25065 line)
25066 (setq ind (org-get-string-indentation line)
25067 start-is-num (match-beginning 4)
25068 starter (if (match-beginning 2)
25069 (substring (match-string 2 line) 0 -1))
25070 line (substring line (match-beginning 5)))
25071 (unless (string-match "[^ \t]" line)
25072 ;; empty line. Pretend indentation is large.
25073 (setq ind (if org-empty-line-terminates-plain-lists
25075 (1+ (or (car local-list-indent) 1)))))
25076 (setq didclose nil)
25077 (while (and in-local-list
25078 (or (and (= ind (car local-list-indent))
25079 (not starter))
25080 (< ind (car local-list-indent))))
25081 (setq didclose t)
25082 (org-close-li)
25083 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25084 (pop local-list-num) (pop local-list-indent)
25085 (setq in-local-list local-list-indent))
25086 (cond
25087 ((and starter
25088 (or (not in-local-list)
25089 (> ind (car local-list-indent))))
25090 ;; Start new (level of) list
25091 (org-close-par-maybe)
25092 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25093 (push start-is-num local-list-num)
25094 (push ind local-list-indent)
25095 (setq in-local-list t))
25096 (starter
25097 ;; continue current list
25098 (org-close-li)
25099 (insert "<li>\n"))
25100 (didclose
25101 ;; we did close a list, normal text follows: need <p>
25102 (org-open-par)))
25103 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25104 (setq line
25105 (replace-match
25106 (if (equal (match-string 1 line) "X")
25107 "<b>[X]</b>"
25108 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25109 t t line))))
25111 ;; Empty lines start a new paragraph. If hand-formatted lists
25112 ;; are not fully interpreted, lines starting with "-", "+", "*"
25113 ;; also start a new paragraph.
25114 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25116 ;; Is this the start of a footnote?
25117 (when org-export-with-footnotes
25118 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25119 (org-close-par-maybe)
25120 (let ((n (match-string 1 line)))
25121 (setq line (replace-match
25122 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25124 ;; Check if the line break needs to be conserved
25125 (cond
25126 ((string-match "\\\\\\\\[ \t]*$" line)
25127 (setq line (replace-match "<br/>" t t line)))
25128 (org-export-preserve-breaks
25129 (setq line (concat line "<br/>"))))
25131 (insert line "\n")))))
25133 ;; Properly close all local lists and other lists
25134 (when inquote (insert "</pre>\n"))
25135 (when in-local-list
25136 ;; Close any local lists before inserting a new header line
25137 (while local-list-num
25138 (org-close-li)
25139 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25140 (pop local-list-num))
25141 (setq local-list-indent nil
25142 in-local-list nil))
25143 (org-html-level-start 1 nil umax
25144 (and org-export-with-toc (<= level umax))
25145 head-count)
25147 (unless body-only
25148 (when (plist-get opt-plist :auto-postamble)
25149 (insert "<div id=\"postamble\">")
25150 (when (and org-export-author-info author)
25151 (insert "<p class=\"author\"> "
25152 (nth 1 lang-words) ": " author "\n")
25153 (when email
25154 (if (listp (split-string email ",+ *"))
25155 (mapc (lambda(e)
25156 (insert "<a href=\"mailto:" e "\">&lt;"
25157 e "&gt;</a>\n"))
25158 (split-string email ",+ *"))
25159 (insert "<a href=\"mailto:" email "\">&lt;"
25160 email "&gt;</a>\n")))
25161 (insert "</p>\n"))
25162 (when (and date org-export-time-stamp-file)
25163 (insert "<p class=\"date\"> "
25164 (nth 2 lang-words) ": "
25165 date "</p>\n"))
25166 (insert "</div>"))
25168 (if org-export-html-with-timestamp
25169 (insert org-export-html-html-helper-timestamp))
25170 (insert (or (plist-get opt-plist :postamble) ""))
25171 (insert "</body>\n</html>\n"))
25173 (normal-mode)
25174 (if (eq major-mode default-major-mode) (html-mode))
25176 ;; insert the table of contents
25177 (goto-char (point-min))
25178 (when thetoc
25179 (if (or (re-search-forward
25180 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25181 (re-search-forward
25182 "\\[TABLE-OF-CONTENTS\\]" nil t))
25183 (progn
25184 (goto-char (match-beginning 0))
25185 (replace-match ""))
25186 (goto-char first-heading-pos)
25187 (when (looking-at "\\s-*</p>")
25188 (goto-char (match-end 0))
25189 (insert "\n")))
25190 (insert "<div id=\"table-of-contents\">\n")
25191 (mapc 'insert thetoc)
25192 (insert "</div>\n"))
25193 ;; remove empty paragraphs and lists
25194 (goto-char (point-min))
25195 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25196 (replace-match ""))
25197 (goto-char (point-min))
25198 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25199 (replace-match ""))
25200 ;; Convert whitespace place holders
25201 (goto-char (point-min))
25202 (let (beg end n)
25203 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25204 (setq n (get-text-property beg 'org-whitespace)
25205 end (next-single-property-change beg 'org-whitespace))
25206 (goto-char beg)
25207 (delete-region beg end)
25208 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25209 (make-string n ?x)))))
25211 (or to-buffer (save-buffer))
25212 (goto-char (point-min))
25213 (message "Exporting... done")
25214 (if (eq to-buffer 'string)
25215 (prog1 (buffer-substring (point-min) (point-max))
25216 (kill-buffer (current-buffer)))
25217 (current-buffer)))))
25219 (defvar org-table-colgroup-info nil)
25220 (defun org-format-table-ascii (lines)
25221 "Format a table for ascii export."
25222 (if (stringp lines)
25223 (setq lines (org-split-string lines "\n")))
25224 (if (not (string-match "^[ \t]*|" (car lines)))
25225 ;; Table made by table.el - test for spanning
25226 lines
25228 ;; A normal org table
25229 ;; Get rid of hlines at beginning and end
25230 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25231 (setq lines (nreverse lines))
25232 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25233 (setq lines (nreverse lines))
25234 (when org-export-table-remove-special-lines
25235 ;; Check if the table has a marking column. If yes remove the
25236 ;; column and the special lines
25237 (setq lines (org-table-clean-before-export lines)))
25238 ;; Get rid of the vertical lines except for grouping
25239 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25240 rtn line vl1 start)
25241 (while (setq line (pop lines))
25242 (if (string-match org-table-hline-regexp line)
25243 (and (string-match "|\\(.*\\)|" line)
25244 (setq line (replace-match " \\1" t nil line)))
25245 (setq start 0 vl1 vl)
25246 (while (string-match "|" line start)
25247 (setq start (match-end 0))
25248 (or (pop vl1) (setq line (replace-match " " t t line)))))
25249 (push line rtn))
25250 (nreverse rtn))))
25252 (defun org-colgroup-info-to-vline-list (info)
25253 (let (vl new last)
25254 (while info
25255 (setq last new new (pop info))
25256 (if (or (memq last '(:end :startend))
25257 (memq new '(:start :startend)))
25258 (push t vl)
25259 (push nil vl)))
25260 (setq vl (nreverse vl))
25261 (and vl (setcar vl nil))
25262 vl))
25264 (defun org-format-table-html (lines olines)
25265 "Find out which HTML converter to use and return the HTML code."
25266 (if (stringp lines)
25267 (setq lines (org-split-string lines "\n")))
25268 (if (string-match "^[ \t]*|" (car lines))
25269 ;; A normal org table
25270 (org-format-org-table-html lines)
25271 ;; Table made by table.el - test for spanning
25272 (let* ((hlines (delq nil (mapcar
25273 (lambda (x)
25274 (if (string-match "^[ \t]*\\+-" x) x
25275 nil))
25276 lines)))
25277 (first (car hlines))
25278 (ll (and (string-match "\\S-+" first)
25279 (match-string 0 first)))
25280 (re (concat "^[ \t]*" (regexp-quote ll)))
25281 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25282 hlines))))
25283 (if (and (not spanning)
25284 (not org-export-prefer-native-exporter-for-tables))
25285 ;; We can use my own converter with HTML conversions
25286 (org-format-table-table-html lines)
25287 ;; Need to use the code generator in table.el, with the original text.
25288 (org-format-table-table-html-using-table-generate-source olines)))))
25290 (defun org-format-org-table-html (lines &optional splice)
25291 "Format a table into HTML."
25292 ;; Get rid of hlines at beginning and end
25293 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25294 (setq lines (nreverse lines))
25295 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25296 (setq lines (nreverse lines))
25297 (when org-export-table-remove-special-lines
25298 ;; Check if the table has a marking column. If yes remove the
25299 ;; column and the special lines
25300 (setq lines (org-table-clean-before-export lines)))
25302 (let ((head (and org-export-highlight-first-table-line
25303 (delq nil (mapcar
25304 (lambda (x) (string-match "^[ \t]*|-" x))
25305 (cdr lines)))))
25306 (nlines 0) fnum i
25307 tbopen line fields html gr colgropen)
25308 (if splice (setq head nil))
25309 (unless splice (push (if head "<thead>" "<tbody>") html))
25310 (setq tbopen t)
25311 (while (setq line (pop lines))
25312 (catch 'next-line
25313 (if (string-match "^[ \t]*|-" line)
25314 (progn
25315 (unless splice
25316 (push (if head "</thead>" "</tbody>") html)
25317 (if lines (push "<tbody>" html) (setq tbopen nil)))
25318 (setq head nil) ;; head ends here, first time around
25319 ;; ignore this line
25320 (throw 'next-line t)))
25321 ;; Break the line into fields
25322 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25323 (unless fnum (setq fnum (make-vector (length fields) 0)))
25324 (setq nlines (1+ nlines) i -1)
25325 (push (concat "<tr>"
25326 (mapconcat
25327 (lambda (x)
25328 (setq i (1+ i))
25329 (if (and (< i nlines)
25330 (string-match org-table-number-regexp x))
25331 (incf (aref fnum i)))
25332 (if head
25333 (concat (car org-export-table-header-tags) x
25334 (cdr org-export-table-header-tags))
25335 (concat (car org-export-table-data-tags) x
25336 (cdr org-export-table-data-tags))))
25337 fields "")
25338 "</tr>")
25339 html)))
25340 (unless splice (if tbopen (push "</tbody>" html)))
25341 (unless splice (push "</table>\n" html))
25342 (setq html (nreverse html))
25343 (unless splice
25344 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25345 (push (mapconcat
25346 (lambda (x)
25347 (setq gr (pop org-table-colgroup-info))
25348 (format "%s<col align=\"%s\"></col>%s"
25349 (if (memq gr '(:start :startend))
25350 (prog1
25351 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25352 (setq colgropen t))
25354 (if (> (/ (float x) nlines) org-table-number-fraction)
25355 "right" "left")
25356 (if (memq gr '(:end :startend))
25357 (progn (setq colgropen nil) "</colgroup>")
25358 "")))
25359 fnum "")
25360 html)
25361 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25362 (push html-table-tag html))
25363 (concat (mapconcat 'identity html "\n") "\n")))
25365 (defun org-table-clean-before-export (lines)
25366 "Check if the table has a marking column.
25367 If yes remove the column and the special lines."
25368 (setq org-table-colgroup-info nil)
25369 (if (memq nil
25370 (mapcar
25371 (lambda (x) (or (string-match "^[ \t]*|-" x)
25372 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25373 lines))
25374 (progn
25375 (setq org-table-clean-did-remove-column nil)
25376 (delq nil
25377 (mapcar
25378 (lambda (x)
25379 (cond
25380 ((string-match "^[ \t]*| */ *|" x)
25381 (setq org-table-colgroup-info
25382 (mapcar (lambda (x)
25383 (cond ((member x '("<" "&lt;")) :start)
25384 ((member x '(">" "&gt;")) :end)
25385 ((member x '("<>" "&lt;&gt;")) :startend)
25386 (t nil)))
25387 (org-split-string x "[ \t]*|[ \t]*")))
25388 nil)
25389 (t x)))
25390 lines)))
25391 (setq org-table-clean-did-remove-column t)
25392 (delq nil
25393 (mapcar
25394 (lambda (x)
25395 (cond
25396 ((string-match "^[ \t]*| */ *|" x)
25397 (setq org-table-colgroup-info
25398 (mapcar (lambda (x)
25399 (cond ((member x '("<" "&lt;")) :start)
25400 ((member x '(">" "&gt;")) :end)
25401 ((member x '("<>" "&lt;&gt;")) :startend)
25402 (t nil)))
25403 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25404 nil)
25405 ((string-match "^[ \t]*| *[!_^/] *|" x)
25406 nil) ; ignore this line
25407 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25408 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25409 ;; remove the first column
25410 (replace-match "\\1|" t nil x))))
25411 lines))))
25413 (defun org-format-table-table-html (lines)
25414 "Format a table generated by table.el into HTML.
25415 This conversion does *not* use `table-generate-source' from table.el.
25416 This has the advantage that Org-mode's HTML conversions can be used.
25417 But it has the disadvantage, that no cell- or row-spanning is allowed."
25418 (let (line field-buffer
25419 (head org-export-highlight-first-table-line)
25420 fields html empty)
25421 (setq html (concat html-table-tag "\n"))
25422 (while (setq line (pop lines))
25423 (setq empty "&nbsp;")
25424 (catch 'next-line
25425 (if (string-match "^[ \t]*\\+-" line)
25426 (progn
25427 (if field-buffer
25428 (progn
25429 (setq
25430 html
25431 (concat
25432 html
25433 "<tr>"
25434 (mapconcat
25435 (lambda (x)
25436 (if (equal x "") (setq x empty))
25437 (if head
25438 (concat (car org-export-table-header-tags) x
25439 (cdr org-export-table-header-tags))
25440 (concat (car org-export-table-data-tags) x
25441 (cdr org-export-table-data-tags))))
25442 field-buffer "\n")
25443 "</tr>\n"))
25444 (setq head nil)
25445 (setq field-buffer nil)))
25446 ;; Ignore this line
25447 (throw 'next-line t)))
25448 ;; Break the line into fields and store the fields
25449 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25450 (if field-buffer
25451 (setq field-buffer (mapcar
25452 (lambda (x)
25453 (concat x "<br/>" (pop fields)))
25454 field-buffer))
25455 (setq field-buffer fields))))
25456 (setq html (concat html "</table>\n"))
25457 html))
25459 (defun org-format-table-table-html-using-table-generate-source (lines)
25460 "Format a table into html, using `table-generate-source' from table.el.
25461 This has the advantage that cell- or row-spanning is allowed.
25462 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25463 (require 'table)
25464 (with-current-buffer (get-buffer-create " org-tmp1 ")
25465 (erase-buffer)
25466 (insert (mapconcat 'identity lines "\n"))
25467 (goto-char (point-min))
25468 (if (not (re-search-forward "|[^+]" nil t))
25469 (error "Error processing table"))
25470 (table-recognize-table)
25471 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25472 (table-generate-source 'html " org-tmp2 ")
25473 (set-buffer " org-tmp2 ")
25474 (buffer-substring (point-min) (point-max))))
25476 (defun org-html-handle-time-stamps (s)
25477 "Format time stamps in string S, or remove them."
25478 (catch 'exit
25479 (let (r b)
25480 (while (string-match org-maybe-keyword-time-regexp s)
25481 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25482 ;; never export CLOCK
25483 (throw 'exit ""))
25484 (or b (setq b (substring s 0 (match-beginning 0))))
25485 (if (not org-export-with-timestamps)
25486 (setq r (concat r (substring s 0 (match-beginning 0)))
25487 s (substring s (match-end 0)))
25488 (setq r (concat
25489 r (substring s 0 (match-beginning 0))
25490 (if (match-end 1)
25491 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25492 (match-string 1 s)))
25493 (format " @<span class=\"timestamp\">%s@</span>"
25494 (substring
25495 (org-translate-time (match-string 3 s)) 1 -1)))
25496 s (substring s (match-end 0)))))
25497 ;; Line break if line started and ended with time stamp stuff
25498 (if (not r)
25500 (setq r (concat r s))
25501 (unless (string-match "\\S-" (concat b s))
25502 (setq r (concat r "@<br/>")))
25503 r))))
25505 (defun org-html-protect (s)
25506 ;; convert & to &amp;, < to &lt; and > to &gt;
25507 (let ((start 0))
25508 (while (string-match "&" s start)
25509 (setq s (replace-match "&amp;" t t s)
25510 start (1+ (match-beginning 0))))
25511 (while (string-match "<" s)
25512 (setq s (replace-match "&lt;" t t s)))
25513 (while (string-match ">" s)
25514 (setq s (replace-match "&gt;" t t s))))
25517 (defun org-export-cleanup-toc-line (s)
25518 "Remove tags and time staps from lines going into the toc."
25519 (when (memq org-export-with-tags '(not-in-toc nil))
25520 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25521 (setq s (replace-match "" t t s))))
25522 (when org-export-remove-timestamps-from-toc
25523 (while (string-match org-maybe-keyword-time-regexp s)
25524 (setq s (replace-match "" t t s))))
25525 (while (string-match org-bracket-link-regexp s)
25526 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25527 t t s)))
25530 (defun org-html-expand (string)
25531 "Prepare STRING for HTML export. Applies all active conversions.
25532 If there are links in the string, don't modify these."
25533 (let* ((re (concat org-bracket-link-regexp "\\|"
25534 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25535 m s l res)
25536 (while (setq m (string-match re string))
25537 (setq s (substring string 0 m)
25538 l (match-string 0 string)
25539 string (substring string (match-end 0)))
25540 (push (org-html-do-expand s) res)
25541 (push l res))
25542 (push (org-html-do-expand string) res)
25543 (apply 'concat (nreverse res))))
25545 (defun org-html-do-expand (s)
25546 "Apply all active conversions to translate special ASCII to HTML."
25547 (setq s (org-html-protect s))
25548 (if org-export-html-expand
25549 (let ((start 0))
25550 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25551 (setq s (replace-match "<\\1>" t nil s)))))
25552 (if org-export-with-emphasize
25553 (setq s (org-export-html-convert-emphasize s)))
25554 (if org-export-with-special-strings
25555 (setq s (org-export-html-convert-special-strings s)))
25556 (if org-export-with-sub-superscripts
25557 (setq s (org-export-html-convert-sub-super s)))
25558 (if org-export-with-TeX-macros
25559 (let ((start 0) wd ass)
25560 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25561 (if (get-text-property (match-beginning 0) 'org-protected s)
25562 (setq start (match-end 0))
25563 (setq wd (match-string 1 s))
25564 (if (setq ass (assoc wd org-html-entities))
25565 (setq s (replace-match (or (cdr ass)
25566 (concat "&" (car ass) ";"))
25567 t t s))
25568 (setq start (+ start (length wd))))))))
25571 (defun org-create-multibrace-regexp (left right n)
25572 "Create a regular expression which will match a balanced sexp.
25573 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25574 as single character strings.
25575 The regexp returned will match the entire expression including the
25576 delimiters. It will also define a single group which contains the
25577 match except for the outermost delimiters. The maximum depth of
25578 stacked delimiters is N. Escaping delimiters is not possible."
25579 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25580 (or "\\|")
25581 (re nothing)
25582 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25583 (while (> n 1)
25584 (setq n (1- n)
25585 re (concat re or next)
25586 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25587 (concat left "\\(" re "\\)" right)))
25589 (defvar org-match-substring-regexp
25590 (concat
25591 "\\([^\\]\\)\\([_^]\\)\\("
25592 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25593 "\\|"
25594 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25595 "\\|"
25596 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25597 "The regular expression matching a sub- or superscript.")
25599 (defvar org-match-substring-with-braces-regexp
25600 (concat
25601 "\\([^\\]\\)\\([_^]\\)\\("
25602 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25603 "\\)")
25604 "The regular expression matching a sub- or superscript, forcing braces.")
25606 (defconst org-export-html-special-string-regexps
25607 '(("\\\\-" . "&shy;")
25608 ("---\\([^-]\\)" . "&mdash;\\1")
25609 ("--\\([^-]\\)" . "&ndash;\\1")
25610 ("\\.\\.\\." . "&hellip;"))
25611 "Regular expressions for special string conversion.")
25613 (defun org-export-html-convert-special-strings (string)
25614 "Convert special characters in STRING to HTML."
25615 (let ((all org-export-html-special-string-regexps)
25616 e a re rpl start)
25617 (while (setq a (pop all))
25618 (setq re (car a) rpl (cdr a) start 0)
25619 (while (string-match re string start)
25620 (if (get-text-property (match-beginning 0) 'org-protected string)
25621 (setq start (match-end 0))
25622 (setq string (replace-match rpl t nil string)))))
25623 string))
25625 (defun org-export-html-convert-sub-super (string)
25626 "Convert sub- and superscripts in STRING to HTML."
25627 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25628 (while (string-match org-match-substring-regexp string s)
25629 (cond
25630 ((and requireb (match-end 8)) (setq s (match-end 2)))
25631 ((get-text-property (match-beginning 2) 'org-protected string)
25632 (setq s (match-end 2)))
25634 (setq s (match-end 1)
25635 key (if (string= (match-string 2 string) "_") "sub" "sup")
25636 c (or (match-string 8 string)
25637 (match-string 6 string)
25638 (match-string 5 string))
25639 string (replace-match
25640 (concat (match-string 1 string)
25641 "<" key ">" c "</" key ">")
25642 t t string)))))
25643 (while (string-match "\\\\\\([_^]\\)" string)
25644 (setq string (replace-match (match-string 1 string) t t string)))
25645 string))
25647 (defun org-export-html-convert-emphasize (string)
25648 "Apply emphasis."
25649 (let ((s 0) rpl)
25650 (while (string-match org-emph-re string s)
25651 (if (not (equal
25652 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25653 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25654 (setq s (match-beginning 0)
25656 (concat
25657 (match-string 1 string)
25658 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25659 (match-string 4 string)
25660 (nth 3 (assoc (match-string 3 string)
25661 org-emphasis-alist))
25662 (match-string 5 string))
25663 string (replace-match rpl t t string)
25664 s (+ s (- (length rpl) 2)))
25665 (setq s (1+ s))))
25666 string))
25668 (defvar org-par-open nil)
25669 (defun org-open-par ()
25670 "Insert <p>, but first close previous paragraph if any."
25671 (org-close-par-maybe)
25672 (insert "\n<p>")
25673 (setq org-par-open t))
25674 (defun org-close-par-maybe ()
25675 "Close paragraph if there is one open."
25676 (when org-par-open
25677 (insert "</p>")
25678 (setq org-par-open nil)))
25679 (defun org-close-li ()
25680 "Close <li> if necessary."
25681 (org-close-par-maybe)
25682 (insert "</li>\n"))
25684 (defvar body-only) ; dynamically scoped into this.
25685 (defun org-html-level-start (level title umax with-toc head-count)
25686 "Insert a new level in HTML export.
25687 When TITLE is nil, just close all open levels."
25688 (org-close-par-maybe)
25689 (let ((l org-level-max))
25690 (while (>= l level)
25691 (if (aref org-levels-open (1- l))
25692 (progn
25693 (org-html-level-close l umax)
25694 (aset org-levels-open (1- l) nil)))
25695 (setq l (1- l)))
25696 (when title
25697 ;; If title is nil, this means this function is called to close
25698 ;; all levels, so the rest is done only if title is given
25699 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25700 (setq title (replace-match
25701 (if org-export-with-tags
25702 (save-match-data
25703 (concat
25704 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25705 (mapconcat 'identity (org-split-string
25706 (match-string 1 title) ":")
25707 "&nbsp;")
25708 "</span>"))
25710 t t title)))
25711 (if (> level umax)
25712 (progn
25713 (if (aref org-levels-open (1- level))
25714 (progn
25715 (org-close-li)
25716 (insert "<li>" title "<br/>\n"))
25717 (aset org-levels-open (1- level) t)
25718 (org-close-par-maybe)
25719 (insert "<ul>\n<li>" title "<br/>\n")))
25720 (aset org-levels-open (1- level) t)
25721 (if (and org-export-with-section-numbers (not body-only))
25722 (setq title (concat (org-section-number level) " " title)))
25723 (setq level (+ level org-export-html-toplevel-hlevel -1))
25724 (if with-toc
25725 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25726 level level head-count title level))
25727 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25728 (org-open-par)))))
25730 (defun org-html-level-close (level max-outline-level)
25731 "Terminate one level in HTML export."
25732 (if (<= level max-outline-level)
25733 (insert "</div>\n")
25734 (org-close-li)
25735 (insert "</ul>\n")))
25737 ;;; iCalendar export
25739 ;;;###autoload
25740 (defun org-export-icalendar-this-file ()
25741 "Export current file as an iCalendar file.
25742 The iCalendar file will be located in the same directory as the Org-mode
25743 file, but with extension `.ics'."
25744 (interactive)
25745 (org-export-icalendar nil buffer-file-name))
25747 ;;;###autoload
25748 (defun org-export-icalendar-all-agenda-files ()
25749 "Export all files in `org-agenda-files' to iCalendar .ics files.
25750 Each iCalendar file will be located in the same directory as the Org-mode
25751 file, but with extension `.ics'."
25752 (interactive)
25753 (apply 'org-export-icalendar nil (org-agenda-files t)))
25755 ;;;###autoload
25756 (defun org-export-icalendar-combine-agenda-files ()
25757 "Export all files in `org-agenda-files' to a single combined iCalendar file.
25758 The file is stored under the name `org-combined-agenda-icalendar-file'."
25759 (interactive)
25760 (apply 'org-export-icalendar t (org-agenda-files t)))
25762 (defun org-export-icalendar (combine &rest files)
25763 "Create iCalendar files for all elements of FILES.
25764 If COMBINE is non-nil, combine all calendar entries into a single large
25765 file and store it under the name `org-combined-agenda-icalendar-file'."
25766 (save-excursion
25767 (org-prepare-agenda-buffers files)
25768 (let* ((dir (org-export-directory
25769 :ical (list :publishing-directory
25770 org-export-publishing-directory)))
25771 file ical-file ical-buffer category started org-agenda-new-buffers)
25773 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
25774 (when combine
25775 (setq ical-file
25776 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
25777 org-combined-agenda-icalendar-file
25778 (expand-file-name org-combined-agenda-icalendar-file dir))
25779 ical-buffer (org-get-agenda-file-buffer ical-file))
25780 (set-buffer ical-buffer) (erase-buffer))
25781 (while (setq file (pop files))
25782 (catch 'nextfile
25783 (org-check-agenda-file file)
25784 (set-buffer (org-get-agenda-file-buffer file))
25785 (unless combine
25786 (setq ical-file (concat (file-name-as-directory dir)
25787 (file-name-sans-extension
25788 (file-name-nondirectory buffer-file-name))
25789 ".ics"))
25790 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
25791 (with-current-buffer ical-buffer (erase-buffer)))
25792 (setq category (or org-category
25793 (file-name-sans-extension
25794 (file-name-nondirectory buffer-file-name))))
25795 (if (symbolp category) (setq category (symbol-name category)))
25796 (let ((standard-output ical-buffer))
25797 (if combine
25798 (and (not started) (setq started t)
25799 (org-start-icalendar-file org-icalendar-combined-name))
25800 (org-start-icalendar-file category))
25801 (org-print-icalendar-entries combine)
25802 (when (or (and combine (not files)) (not combine))
25803 (org-finish-icalendar-file)
25804 (set-buffer ical-buffer)
25805 (save-buffer)
25806 (run-hooks 'org-after-save-iCalendar-file-hook)))))
25807 (org-release-buffers org-agenda-new-buffers))))
25809 (defvar org-after-save-iCalendar-file-hook nil
25810 "Hook run after an iCalendar file has been saved.
25811 The iCalendar buffer is still current when this hook is run.
25812 A good way to use this is to tell a desktop calenndar application to re-read
25813 the iCalendar file.")
25815 (defun org-print-icalendar-entries (&optional combine)
25816 "Print iCalendar entries for the current Org-mode file to `standard-output'.
25817 When COMBINE is non nil, add the category to each line."
25818 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
25819 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
25820 (dts (org-ical-ts-to-string
25821 (format-time-string (cdr org-time-stamp-formats) (current-time))
25822 "DTSTART"))
25823 hd ts ts2 state status (inc t) pos b sexp rrule
25824 scheduledp deadlinep tmp pri category entry location summary desc
25825 (sexp-buffer (get-buffer-create "*ical-tmp*")))
25826 (org-refresh-category-properties)
25827 (save-excursion
25828 (goto-char (point-min))
25829 (while (re-search-forward re1 nil t)
25830 (catch :skip
25831 (org-agenda-skip)
25832 (setq pos (match-beginning 0)
25833 ts (match-string 0)
25834 inc t
25835 hd (org-get-heading)
25836 summary (org-icalendar-cleanup-string
25837 (org-entry-get nil "SUMMARY"))
25838 desc (org-icalendar-cleanup-string
25839 (or (org-entry-get nil "DESCRIPTION")
25840 (and org-icalendar-include-body (org-get-entry)))
25841 t org-icalendar-include-body)
25842 location (org-icalendar-cleanup-string
25843 (org-entry-get nil "LOCATION"))
25844 category (org-get-category))
25845 (if (looking-at re2)
25846 (progn
25847 (goto-char (match-end 0))
25848 (setq ts2 (match-string 1) inc nil))
25849 (setq tmp (buffer-substring (max (point-min)
25850 (- pos org-ds-keyword-length))
25851 pos)
25852 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
25853 (progn
25854 (setq inc nil)
25855 (replace-match "\\1" t nil ts))
25857 deadlinep (string-match org-deadline-regexp tmp)
25858 scheduledp (string-match org-scheduled-regexp tmp)
25859 ;; donep (org-entry-is-done-p)
25861 (if (or (string-match org-tr-regexp hd)
25862 (string-match org-ts-regexp hd))
25863 (setq hd (replace-match "" t t hd)))
25864 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
25865 (setq rrule
25866 (concat "\nRRULE:FREQ="
25867 (cdr (assoc
25868 (match-string 2 ts)
25869 '(("d" . "DAILY")("w" . "WEEKLY")
25870 ("m" . "MONTHLY")("y" . "YEARLY"))))
25871 ";INTERVAL=" (match-string 1 ts)))
25872 (setq rrule ""))
25873 (setq summary (or summary hd))
25874 (if (string-match org-bracket-link-regexp summary)
25875 (setq summary
25876 (replace-match (if (match-end 3)
25877 (match-string 3 summary)
25878 (match-string 1 summary))
25879 t t summary)))
25880 (if deadlinep (setq summary (concat "DL: " summary)))
25881 (if scheduledp (setq summary (concat "S: " summary)))
25882 (if (string-match "\\`<%%" ts)
25883 (with-current-buffer sexp-buffer
25884 (insert (substring ts 1 -1) " " summary "\n"))
25885 (princ (format "BEGIN:VEVENT
25887 %s%s
25888 SUMMARY:%s%s%s
25889 CATEGORIES:%s
25890 END:VEVENT\n"
25891 (org-ical-ts-to-string ts "DTSTART")
25892 (org-ical-ts-to-string ts2 "DTEND" inc)
25893 rrule summary
25894 (if (and desc (string-match "\\S-" desc))
25895 (concat "\nDESCRIPTION: " desc) "")
25896 (if (and location (string-match "\\S-" location))
25897 (concat "\nLOCATION: " location) "")
25898 category)))))
25900 (when (and org-icalendar-include-sexps
25901 (condition-case nil (require 'icalendar) (error nil))
25902 (fboundp 'icalendar-export-region))
25903 ;; Get all the literal sexps
25904 (goto-char (point-min))
25905 (while (re-search-forward "^&?%%(" nil t)
25906 (catch :skip
25907 (org-agenda-skip)
25908 (setq b (match-beginning 0))
25909 (goto-char (1- (match-end 0)))
25910 (forward-sexp 1)
25911 (end-of-line 1)
25912 (setq sexp (buffer-substring b (point)))
25913 (with-current-buffer sexp-buffer
25914 (insert sexp "\n"))
25915 (princ (org-diary-to-ical-string sexp-buffer)))))
25917 (when org-icalendar-include-todo
25918 (goto-char (point-min))
25919 (while (re-search-forward org-todo-line-regexp nil t)
25920 (catch :skip
25921 (org-agenda-skip)
25922 (setq state (match-string 2))
25923 (setq status (if (member state org-done-keywords)
25924 "COMPLETED" "NEEDS-ACTION"))
25925 (when (and state
25926 (or (not (member state org-done-keywords))
25927 (eq org-icalendar-include-todo 'all))
25928 (not (member org-archive-tag (org-get-tags-at)))
25930 (setq hd (match-string 3)
25931 summary (org-icalendar-cleanup-string
25932 (org-entry-get nil "SUMMARY"))
25933 desc (org-icalendar-cleanup-string
25934 (or (org-entry-get nil "DESCRIPTION")
25935 (and org-icalendar-include-body (org-get-entry)))
25936 t org-icalendar-include-body)
25937 location (org-icalendar-cleanup-string
25938 (org-entry-get nil "LOCATION")))
25939 (if (string-match org-bracket-link-regexp hd)
25940 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
25941 (match-string 1 hd))
25942 t t hd)))
25943 (if (string-match org-priority-regexp hd)
25944 (setq pri (string-to-char (match-string 2 hd))
25945 hd (concat (substring hd 0 (match-beginning 1))
25946 (substring hd (match-end 1))))
25947 (setq pri org-default-priority))
25948 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
25949 (- org-lowest-priority org-highest-priority))))))
25951 (princ (format "BEGIN:VTODO
25953 SUMMARY:%s%s%s
25954 CATEGORIES:%s
25955 SEQUENCE:1
25956 PRIORITY:%d
25957 STATUS:%s
25958 END:VTODO\n"
25960 (or summary hd)
25961 (if (and location (string-match "\\S-" location))
25962 (concat "\nLOCATION: " location) "")
25963 (if (and desc (string-match "\\S-" desc))
25964 (concat "\nDESCRIPTION: " desc) "")
25965 category pri status)))))))))
25967 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
25968 "Take out stuff and quote what needs to be quoted.
25969 When IS-BODY is non-nil, assume that this is the body of an item, clean up
25970 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
25971 characters."
25972 (if (not s)
25974 (when is-body
25975 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
25976 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
25977 (while (string-match re s) (setq s (replace-match "" t t s)))
25978 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
25979 (let ((start 0))
25980 (while (string-match "\\([,;\\]\\)" s start)
25981 (setq start (+ (match-beginning 0) 2)
25982 s (replace-match "\\\\\\1" nil nil s))))
25983 (when is-body
25984 (while (string-match "[ \t]*\n[ \t]*" s)
25985 (setq s (replace-match "\\n" t t s))))
25986 (setq s (org-trim s))
25987 (if is-body
25988 (if maxlength
25989 (if (and (numberp maxlength)
25990 (> (length s) maxlength))
25991 (setq s (substring s 0 maxlength)))))
25994 (defun org-get-entry ()
25995 "Clean-up description string."
25996 (save-excursion
25997 (org-back-to-heading t)
25998 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26000 (defun org-start-icalendar-file (name)
26001 "Start an iCalendar file by inserting the header."
26002 (let ((user user-full-name)
26003 (name (or name "unknown"))
26004 (timezone (cadr (current-time-zone))))
26005 (princ
26006 (format "BEGIN:VCALENDAR
26007 VERSION:2.0
26008 X-WR-CALNAME:%s
26009 PRODID:-//%s//Emacs with Org-mode//EN
26010 X-WR-TIMEZONE:%s
26011 CALSCALE:GREGORIAN\n" name user timezone))))
26013 (defun org-finish-icalendar-file ()
26014 "Finish an iCalendar file by inserting the END statement."
26015 (princ "END:VCALENDAR\n"))
26017 (defun org-ical-ts-to-string (s keyword &optional inc)
26018 "Take a time string S and convert it to iCalendar format.
26019 KEYWORD is added in front, to make a complete line like DTSTART....
26020 When INC is non-nil, increase the hour by two (if time string contains
26021 a time), or the day by one (if it does not contain a time)."
26022 (let ((t1 (org-parse-time-string s 'nodefault))
26023 t2 fmt have-time time)
26024 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26025 (setq t2 t1 have-time t)
26026 (setq t2 (org-parse-time-string s)))
26027 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26028 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26029 (when inc
26030 (if have-time
26031 (if org-agenda-default-appointment-duration
26032 (setq mi (+ org-agenda-default-appointment-duration mi))
26033 (setq h (+ 2 h)))
26034 (setq d (1+ d))))
26035 (setq time (encode-time s mi h d m y)))
26036 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26037 (concat keyword (format-time-string fmt time))))
26039 ;;; XOXO export
26041 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26042 (with-current-buffer buffer
26043 (apply 'insert output)))
26044 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26046 (defun org-export-as-xoxo (&optional buffer)
26047 "Export the org buffer as XOXO.
26048 The XOXO buffer is named *xoxo-<source buffer name>*"
26049 (interactive (list (current-buffer)))
26050 ;; A quickie abstraction
26052 ;; Output everything as XOXO
26053 (with-current-buffer (get-buffer buffer)
26054 (let* ((pos (point))
26055 (opt-plist (org-combine-plists (org-default-export-plist)
26056 (org-infile-export-plist)))
26057 (filename (concat (file-name-as-directory
26058 (org-export-directory :xoxo opt-plist))
26059 (file-name-sans-extension
26060 (file-name-nondirectory buffer-file-name))
26061 ".html"))
26062 (out (find-file-noselect filename))
26063 (last-level 1)
26064 (hanging-li nil))
26065 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26066 ;; Check the output buffer is empty.
26067 (with-current-buffer out (erase-buffer))
26068 ;; Kick off the output
26069 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26070 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26071 (let* ((hd (match-string-no-properties 1))
26072 (level (length hd))
26073 (text (concat
26074 (match-string-no-properties 2)
26075 (save-excursion
26076 (goto-char (match-end 0))
26077 (let ((str ""))
26078 (catch 'loop
26079 (while 't
26080 (forward-line)
26081 (if (looking-at "^[ \t]\\(.*\\)")
26082 (setq str (concat str (match-string-no-properties 1)))
26083 (throw 'loop str)))))))))
26085 ;; Handle level rendering
26086 (cond
26087 ((> level last-level)
26088 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26090 ((< level last-level)
26091 (dotimes (- (- last-level level) 1)
26092 (if hanging-li
26093 (org-export-as-xoxo-insert-into out "</li>\n"))
26094 (org-export-as-xoxo-insert-into out "</ol>\n"))
26095 (when hanging-li
26096 (org-export-as-xoxo-insert-into out "</li>\n")
26097 (setq hanging-li nil)))
26099 ((equal level last-level)
26100 (if hanging-li
26101 (org-export-as-xoxo-insert-into out "</li>\n")))
26104 (setq last-level level)
26106 ;; And output the new li
26107 (setq hanging-li 't)
26108 (if (equal ?+ (elt text 0))
26109 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26110 (org-export-as-xoxo-insert-into out "<li>" text))))
26112 ;; Finally finish off the ol
26113 (dotimes (- last-level 1)
26114 (if hanging-li
26115 (org-export-as-xoxo-insert-into out "</li>\n"))
26116 (org-export-as-xoxo-insert-into out "</ol>\n"))
26118 (goto-char pos)
26119 ;; Finish the buffer off and clean it up.
26120 (switch-to-buffer-other-window out)
26121 (indent-region (point-min) (point-max) nil)
26122 (save-buffer)
26123 (goto-char (point-min))
26127 ;;;; Key bindings
26129 ;; Make `C-c C-x' a prefix key
26130 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26132 ;; TAB key with modifiers
26133 (org-defkey org-mode-map "\C-i" 'org-cycle)
26134 (org-defkey org-mode-map [(tab)] 'org-cycle)
26135 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26136 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26137 (org-defkey org-mode-map "\M-\t" 'org-complete)
26138 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26139 ;; The following line is necessary under Suse GNU/Linux
26140 (unless (featurep 'xemacs)
26141 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26142 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26143 (define-key org-mode-map [backtab] 'org-shifttab)
26145 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26146 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26147 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26149 ;; Cursor keys with modifiers
26150 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26151 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26152 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26153 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26155 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26156 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26157 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26158 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26160 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26161 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26162 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26163 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26165 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26166 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26168 ;;; Extra keys for tty access.
26169 ;; We only set them when really needed because otherwise the
26170 ;; menus don't show the simple keys
26172 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26173 (not window-system))
26174 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26175 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26176 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26177 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26178 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26179 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26180 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26181 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26182 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26183 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26184 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26185 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26186 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26187 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26188 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26189 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26190 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26191 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26192 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26193 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26194 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26195 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26197 ;; All the other keys
26199 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26200 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26201 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26202 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26203 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26204 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26205 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26206 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26207 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26208 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26209 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26210 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26211 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26212 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26213 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26214 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26215 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26216 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26217 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26218 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26219 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26220 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26221 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26222 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26223 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26224 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26225 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26226 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26227 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26228 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26229 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26230 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26231 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26232 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26233 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26234 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26235 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26236 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26237 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26238 (org-defkey org-mode-map "\C-c^" 'org-sort)
26239 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26240 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26241 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26242 (org-defkey org-mode-map "\C-m" 'org-return)
26243 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26244 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26245 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26246 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26247 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26248 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26249 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26250 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26251 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26252 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26253 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26254 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26255 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26256 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26257 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26258 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26259 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26261 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26262 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26263 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26264 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26266 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26267 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26268 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26269 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26270 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26271 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26272 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26273 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26274 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26275 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26276 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26277 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26279 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26281 (when (featurep 'xemacs)
26282 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26284 (defsubst org-table-p () (org-at-table-p))
26286 (defun org-self-insert-command (N)
26287 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26288 If the cursor is in a table looking at whitespace, the whitespace is
26289 overwritten, and the table is not marked as requiring realignment."
26290 (interactive "p")
26291 (if (and (org-table-p)
26292 (progn
26293 ;; check if we blank the field, and if that triggers align
26294 (and org-table-auto-blank-field
26295 (member last-command
26296 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26297 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26298 ;; got extra space, this field does not determine column width
26299 (let (org-table-may-need-update) (org-table-blank-field))
26300 ;; no extra space, this field may determine column width
26301 (org-table-blank-field)))
26303 (eq N 1)
26304 (looking-at "[^|\n]* |"))
26305 (let (org-table-may-need-update)
26306 (goto-char (1- (match-end 0)))
26307 (delete-backward-char 1)
26308 (goto-char (match-beginning 0))
26309 (self-insert-command N))
26310 (setq org-table-may-need-update t)
26311 (self-insert-command N)
26312 (org-fix-tags-on-the-fly)))
26314 (defun org-fix-tags-on-the-fly ()
26315 (when (and (equal (char-after (point-at-bol)) ?*)
26316 (org-on-heading-p))
26317 (org-align-tags-here org-tags-column)))
26319 (defun org-delete-backward-char (N)
26320 "Like `delete-backward-char', insert whitespace at field end in tables.
26321 When deleting backwards, in tables this function will insert whitespace in
26322 front of the next \"|\" separator, to keep the table aligned. The table will
26323 still be marked for re-alignment if the field did fill the entire column,
26324 because, in this case the deletion might narrow the column."
26325 (interactive "p")
26326 (if (and (org-table-p)
26327 (eq N 1)
26328 (string-match "|" (buffer-substring (point-at-bol) (point)))
26329 (looking-at ".*?|"))
26330 (let ((pos (point))
26331 (noalign (looking-at "[^|\n\r]* |"))
26332 (c org-table-may-need-update))
26333 (backward-delete-char N)
26334 (skip-chars-forward "^|")
26335 (insert " ")
26336 (goto-char (1- pos))
26337 ;; noalign: if there were two spaces at the end, this field
26338 ;; does not determine the width of the column.
26339 (if noalign (setq org-table-may-need-update c)))
26340 (backward-delete-char N)
26341 (org-fix-tags-on-the-fly)))
26343 (defun org-delete-char (N)
26344 "Like `delete-char', but insert whitespace at field end in tables.
26345 When deleting characters, in tables this function will insert whitespace in
26346 front of the next \"|\" separator, to keep the table aligned. The table will
26347 still be marked for re-alignment if the field did fill the entire column,
26348 because, in this case the deletion might narrow the column."
26349 (interactive "p")
26350 (if (and (org-table-p)
26351 (not (bolp))
26352 (not (= (char-after) ?|))
26353 (eq N 1))
26354 (if (looking-at ".*?|")
26355 (let ((pos (point))
26356 (noalign (looking-at "[^|\n\r]* |"))
26357 (c org-table-may-need-update))
26358 (replace-match (concat
26359 (substring (match-string 0) 1 -1)
26360 " |"))
26361 (goto-char pos)
26362 ;; noalign: if there were two spaces at the end, this field
26363 ;; does not determine the width of the column.
26364 (if noalign (setq org-table-may-need-update c)))
26365 (delete-char N))
26366 (delete-char N)
26367 (org-fix-tags-on-the-fly)))
26369 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26370 (put 'org-self-insert-command 'delete-selection t)
26371 (put 'orgtbl-self-insert-command 'delete-selection t)
26372 (put 'org-delete-char 'delete-selection 'supersede)
26373 (put 'org-delete-backward-char 'delete-selection 'supersede)
26375 ;; Make `flyspell-mode' delay after some commands
26376 (put 'org-self-insert-command 'flyspell-delayed t)
26377 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26378 (put 'org-delete-char 'flyspell-delayed t)
26379 (put 'org-delete-backward-char 'flyspell-delayed t)
26381 ;; Make pabbrev-mode expand after org-mode commands
26382 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26383 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26385 ;; How to do this: Measure non-white length of current string
26386 ;; If equal to column width, we should realign.
26388 (defun org-remap (map &rest commands)
26389 "In MAP, remap the functions given in COMMANDS.
26390 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26391 (let (new old)
26392 (while commands
26393 (setq old (pop commands) new (pop commands))
26394 (if (fboundp 'command-remapping)
26395 (org-defkey map (vector 'remap old) new)
26396 (substitute-key-definition old new map global-map)))))
26398 (when (eq org-enable-table-editor 'optimized)
26399 ;; If the user wants maximum table support, we need to hijack
26400 ;; some standard editing functions
26401 (org-remap org-mode-map
26402 'self-insert-command 'org-self-insert-command
26403 'delete-char 'org-delete-char
26404 'delete-backward-char 'org-delete-backward-char)
26405 (org-defkey org-mode-map "|" 'org-force-self-insert))
26407 (defun org-shiftcursor-error ()
26408 "Throw an error because Shift-Cursor command was applied in wrong context."
26409 (error "This command is active in special context like tables, headlines or timestamps"))
26411 (defun org-shifttab (&optional arg)
26412 "Global visibility cycling or move to previous table field.
26413 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26414 on context.
26415 See the individual commands for more information."
26416 (interactive "P")
26417 (cond
26418 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26419 (arg (message "Content view to level: ")
26420 (org-content (prefix-numeric-value arg))
26421 (setq org-cycle-global-status 'overview))
26422 (t (call-interactively 'org-global-cycle))))
26424 (defun org-shiftmetaleft ()
26425 "Promote subtree or delete table column.
26426 Calls `org-promote-subtree', `org-outdent-item',
26427 or `org-table-delete-column', depending on context.
26428 See the individual commands for more information."
26429 (interactive)
26430 (cond
26431 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26432 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26433 ((org-at-item-p) (call-interactively 'org-outdent-item))
26434 (t (org-shiftcursor-error))))
26436 (defun org-shiftmetaright ()
26437 "Demote subtree or insert table column.
26438 Calls `org-demote-subtree', `org-indent-item',
26439 or `org-table-insert-column', depending on context.
26440 See the individual commands for more information."
26441 (interactive)
26442 (cond
26443 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26444 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26445 ((org-at-item-p) (call-interactively 'org-indent-item))
26446 (t (org-shiftcursor-error))))
26448 (defun org-shiftmetaup (&optional arg)
26449 "Move subtree up or kill table row.
26450 Calls `org-move-subtree-up' or `org-table-kill-row' or
26451 `org-move-item-up' depending on context. See the individual commands
26452 for more information."
26453 (interactive "P")
26454 (cond
26455 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26456 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26457 ((org-at-item-p) (call-interactively 'org-move-item-up))
26458 (t (org-shiftcursor-error))))
26459 (defun org-shiftmetadown (&optional arg)
26460 "Move subtree down or insert table row.
26461 Calls `org-move-subtree-down' or `org-table-insert-row' or
26462 `org-move-item-down', depending on context. See the individual
26463 commands for more information."
26464 (interactive "P")
26465 (cond
26466 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26467 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26468 ((org-at-item-p) (call-interactively 'org-move-item-down))
26469 (t (org-shiftcursor-error))))
26471 (defun org-metaleft (&optional arg)
26472 "Promote heading or move table column to left.
26473 Calls `org-do-promote' or `org-table-move-column', depending on context.
26474 With no specific context, calls the Emacs default `backward-word'.
26475 See the individual commands for more information."
26476 (interactive "P")
26477 (cond
26478 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26479 ((or (org-on-heading-p) (org-region-active-p))
26480 (call-interactively 'org-do-promote))
26481 ((org-at-item-p) (call-interactively 'org-outdent-item))
26482 (t (call-interactively 'backward-word))))
26484 (defun org-metaright (&optional arg)
26485 "Demote subtree or move table column to right.
26486 Calls `org-do-demote' or `org-table-move-column', depending on context.
26487 With no specific context, calls the Emacs default `forward-word'.
26488 See the individual commands for more information."
26489 (interactive "P")
26490 (cond
26491 ((org-at-table-p) (call-interactively 'org-table-move-column))
26492 ((or (org-on-heading-p) (org-region-active-p))
26493 (call-interactively 'org-do-demote))
26494 ((org-at-item-p) (call-interactively 'org-indent-item))
26495 (t (call-interactively 'forward-word))))
26497 (defun org-metaup (&optional arg)
26498 "Move subtree up or move table row up.
26499 Calls `org-move-subtree-up' or `org-table-move-row' or
26500 `org-move-item-up', depending on context. See the individual commands
26501 for more information."
26502 (interactive "P")
26503 (cond
26504 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26505 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26506 ((org-at-item-p) (call-interactively 'org-move-item-up))
26507 (t (transpose-lines 1) (beginning-of-line -1))))
26509 (defun org-metadown (&optional arg)
26510 "Move subtree down or move table row down.
26511 Calls `org-move-subtree-down' or `org-table-move-row' or
26512 `org-move-item-down', depending on context. See the individual
26513 commands for more information."
26514 (interactive "P")
26515 (cond
26516 ((org-at-table-p) (call-interactively 'org-table-move-row))
26517 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26518 ((org-at-item-p) (call-interactively 'org-move-item-down))
26519 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26521 (defun org-shiftup (&optional arg)
26522 "Increase item in timestamp or increase priority of current headline.
26523 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26524 depending on context. See the individual commands for more information."
26525 (interactive "P")
26526 (cond
26527 ((org-at-timestamp-p t)
26528 (call-interactively (if org-edit-timestamp-down-means-later
26529 'org-timestamp-down 'org-timestamp-up)))
26530 ((org-on-heading-p) (call-interactively 'org-priority-up))
26531 ((org-at-item-p) (call-interactively 'org-previous-item))
26532 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26534 (defun org-shiftdown (&optional arg)
26535 "Decrease item in timestamp or decrease priority of current headline.
26536 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26537 depending on context. See the individual commands for more information."
26538 (interactive "P")
26539 (cond
26540 ((org-at-timestamp-p t)
26541 (call-interactively (if org-edit-timestamp-down-means-later
26542 'org-timestamp-up 'org-timestamp-down)))
26543 ((org-on-heading-p) (call-interactively 'org-priority-down))
26544 (t (call-interactively 'org-next-item))))
26546 (defun org-shiftright ()
26547 "Next TODO keyword or timestamp one day later, depending on context."
26548 (interactive)
26549 (cond
26550 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26551 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26552 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26553 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26554 (t (org-shiftcursor-error))))
26556 (defun org-shiftleft ()
26557 "Previous TODO keyword or timestamp one day earlier, depending on context."
26558 (interactive)
26559 (cond
26560 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26561 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26562 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26563 ((org-at-property-p)
26564 (call-interactively 'org-property-previous-allowed-value))
26565 (t (org-shiftcursor-error))))
26567 (defun org-shiftcontrolright ()
26568 "Switch to next TODO set."
26569 (interactive)
26570 (cond
26571 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26572 (t (org-shiftcursor-error))))
26574 (defun org-shiftcontrolleft ()
26575 "Switch to previous TODO set."
26576 (interactive)
26577 (cond
26578 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26579 (t (org-shiftcursor-error))))
26581 (defun org-ctrl-c-ret ()
26582 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26583 (interactive)
26584 (cond
26585 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26586 (t (call-interactively 'org-insert-heading))))
26588 (defun org-copy-special ()
26589 "Copy region in table or copy current subtree.
26590 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26591 See the individual commands for more information."
26592 (interactive)
26593 (call-interactively
26594 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26596 (defun org-cut-special ()
26597 "Cut region in table or cut current subtree.
26598 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26599 See the individual commands for more information."
26600 (interactive)
26601 (call-interactively
26602 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26604 (defun org-paste-special (arg)
26605 "Paste rectangular region into table, or past subtree relative to level.
26606 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26607 See the individual commands for more information."
26608 (interactive "P")
26609 (if (org-at-table-p)
26610 (org-table-paste-rectangle)
26611 (org-paste-subtree arg)))
26613 (defun org-ctrl-c-ctrl-c (&optional arg)
26614 "Set tags in headline, or update according to changed information at point.
26616 This command does many different things, depending on context:
26618 - If the cursor is in a headline, prompt for tags and insert them
26619 into the current line, aligned to `org-tags-column'. When called
26620 with prefix arg, realign all tags in the current buffer.
26622 - If the cursor is in one of the special #+KEYWORD lines, this
26623 triggers scanning the buffer for these lines and updating the
26624 information.
26626 - If the cursor is inside a table, realign the table. This command
26627 works even if the automatic table editor has been turned off.
26629 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26630 the entire table.
26632 - If the cursor is a the beginning of a dynamic block, update it.
26634 - If the cursor is inside a table created by the table.el package,
26635 activate that table.
26637 - If the current buffer is a remember buffer, close note and file it.
26638 with a prefix argument, file it without further interaction to the default
26639 location.
26641 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26642 links in this buffer.
26644 - If the cursor is on a numbered item in a plain list, renumber the
26645 ordered list.
26647 - If the cursor is on a checkbox, toggle it."
26648 (interactive "P")
26649 (let ((org-enable-table-editor t))
26650 (cond
26651 ((or org-clock-overlays
26652 org-occur-highlights
26653 org-latex-fragment-image-overlays)
26654 (org-remove-clock-overlays)
26655 (org-remove-occur-highlights)
26656 (org-remove-latex-fragment-image-overlays)
26657 (message "Temporary highlights/overlays removed from current buffer"))
26658 ((and (local-variable-p 'org-finish-function (current-buffer))
26659 (fboundp org-finish-function))
26660 (funcall org-finish-function))
26661 ((org-at-property-p)
26662 (call-interactively 'org-property-action))
26663 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26664 ((org-on-heading-p) (call-interactively 'org-set-tags))
26665 ((org-at-table.el-p)
26666 (require 'table)
26667 (beginning-of-line 1)
26668 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26669 (call-interactively 'table-recognize-table))
26670 ((org-at-table-p)
26671 (org-table-maybe-eval-formula)
26672 (if arg
26673 (call-interactively 'org-table-recalculate)
26674 (org-table-maybe-recalculate-line))
26675 (call-interactively 'org-table-align))
26676 ((org-at-item-checkbox-p)
26677 (call-interactively 'org-toggle-checkbox))
26678 ((org-at-item-p)
26679 (call-interactively 'org-maybe-renumber-ordered-list))
26680 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26681 ;; Dynamic block
26682 (beginning-of-line 1)
26683 (org-update-dblock))
26684 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26685 (cond
26686 ((equal (match-string 1) "TBLFM")
26687 ;; Recalculate the table before this line
26688 (save-excursion
26689 (beginning-of-line 1)
26690 (skip-chars-backward " \r\n\t")
26691 (if (org-at-table-p)
26692 (org-call-with-arg 'org-table-recalculate t))))
26694 (call-interactively 'org-mode-restart))))
26695 (t (error "C-c C-c can do nothing useful at this location.")))))
26697 (defun org-mode-restart ()
26698 "Restart Org-mode, to scan again for special lines.
26699 Also updates the keyword regular expressions."
26700 (interactive)
26701 (let ((org-inhibit-startup t)) (org-mode))
26702 (message "Org-mode restarted to refresh keyword and special line setup"))
26704 (defun org-kill-note-or-show-branches ()
26705 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26706 (interactive)
26707 (if (not org-finish-function)
26708 (call-interactively 'show-branches)
26709 (let ((org-note-abort t))
26710 (funcall org-finish-function))))
26712 (defun org-return (&optional indent)
26713 "Goto next table row or insert a newline.
26714 Calls `org-table-next-row' or `newline', depending on context.
26715 See the individual commands for more information."
26716 (interactive)
26717 (cond
26718 ((bobp) (if indent (newline-and-indent) (newline)))
26719 ((org-at-table-p)
26720 (org-table-justify-field-maybe)
26721 (call-interactively 'org-table-next-row))
26722 (t (if indent (newline-and-indent) (newline)))))
26724 (defun org-return-indent ()
26725 (interactive)
26726 "Goto next table row or insert a newline and indent.
26727 Calls `org-table-next-row' or `newline-and-indent', depending on
26728 context. See the individual commands for more information."
26729 (org-return t))
26731 (defun org-ctrl-c-minus ()
26732 "Insert separator line in table or modify bullet type in list.
26733 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26734 depending on context."
26735 (interactive)
26736 (cond
26737 ((org-at-table-p)
26738 (call-interactively 'org-table-insert-hline))
26739 ((org-on-heading-p)
26740 ;; Convert to item
26741 (save-excursion
26742 (beginning-of-line 1)
26743 (if (looking-at "\\*+ ")
26744 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26745 ((org-in-item-p)
26746 (call-interactively 'org-cycle-list-bullet))
26747 (t (error "`C-c -' does have no function here."))))
26749 (defun org-meta-return (&optional arg)
26750 "Insert a new heading or wrap a region in a table.
26751 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
26752 See the individual commands for more information."
26753 (interactive "P")
26754 (cond
26755 ((org-at-table-p)
26756 (call-interactively 'org-table-wrap-region))
26757 (t (call-interactively 'org-insert-heading))))
26759 ;;; Menu entries
26761 ;; Define the Org-mode menus
26762 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
26763 '("Tbl"
26764 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
26765 ["Next Field" org-cycle (org-at-table-p)]
26766 ["Previous Field" org-shifttab (org-at-table-p)]
26767 ["Next Row" org-return (org-at-table-p)]
26768 "--"
26769 ["Blank Field" org-table-blank-field (org-at-table-p)]
26770 ["Edit Field" org-table-edit-field (org-at-table-p)]
26771 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
26772 "--"
26773 ("Column"
26774 ["Move Column Left" org-metaleft (org-at-table-p)]
26775 ["Move Column Right" org-metaright (org-at-table-p)]
26776 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
26777 ["Insert Column" org-shiftmetaright (org-at-table-p)])
26778 ("Row"
26779 ["Move Row Up" org-metaup (org-at-table-p)]
26780 ["Move Row Down" org-metadown (org-at-table-p)]
26781 ["Delete Row" org-shiftmetaup (org-at-table-p)]
26782 ["Insert Row" org-shiftmetadown (org-at-table-p)]
26783 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
26784 "--"
26785 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
26786 ("Rectangle"
26787 ["Copy Rectangle" org-copy-special (org-at-table-p)]
26788 ["Cut Rectangle" org-cut-special (org-at-table-p)]
26789 ["Paste Rectangle" org-paste-special (org-at-table-p)]
26790 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
26791 "--"
26792 ("Calculate"
26793 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
26794 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
26795 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
26796 "--"
26797 ["Recalculate line" org-table-recalculate (org-at-table-p)]
26798 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
26799 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
26800 "--"
26801 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
26802 "--"
26803 ["Sum Column/Rectangle" org-table-sum
26804 (or (org-at-table-p) (org-region-active-p))]
26805 ["Which Column?" org-table-current-column (org-at-table-p)])
26806 ["Debug Formulas"
26807 org-table-toggle-formula-debugger
26808 :style toggle :selected org-table-formula-debug]
26809 ["Show Col/Row Numbers"
26810 org-table-toggle-coordinate-overlays
26811 :style toggle :selected org-table-overlay-coordinates]
26812 "--"
26813 ["Create" org-table-create (and (not (org-at-table-p))
26814 org-enable-table-editor)]
26815 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
26816 ["Import from File" org-table-import (not (org-at-table-p))]
26817 ["Export to File" org-table-export (org-at-table-p)]
26818 "--"
26819 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
26821 (easy-menu-define org-org-menu org-mode-map "Org menu"
26822 '("Org"
26823 ("Show/Hide"
26824 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
26825 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
26826 ["Sparse Tree" org-occur t]
26827 ["Reveal Context" org-reveal t]
26828 ["Show All" show-all t]
26829 "--"
26830 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
26831 "--"
26832 ["New Heading" org-insert-heading t]
26833 ("Navigate Headings"
26834 ["Up" outline-up-heading t]
26835 ["Next" outline-next-visible-heading t]
26836 ["Previous" outline-previous-visible-heading t]
26837 ["Next Same Level" outline-forward-same-level t]
26838 ["Previous Same Level" outline-backward-same-level t]
26839 "--"
26840 ["Jump" org-goto t])
26841 ("Edit Structure"
26842 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
26843 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
26844 "--"
26845 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
26846 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
26847 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
26848 "--"
26849 ["Promote Heading" org-metaleft (not (org-at-table-p))]
26850 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
26851 ["Demote Heading" org-metaright (not (org-at-table-p))]
26852 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
26853 "--"
26854 ["Sort Region/Children" org-sort (not (org-at-table-p))]
26855 "--"
26856 ["Convert to odd levels" org-convert-to-odd-levels t]
26857 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
26858 ("Editing"
26859 ["Emphasis..." org-emphasize t])
26860 ("Archive"
26861 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
26862 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
26863 ; :active t :keys "C-u C-c C-x C-a"]
26864 ["Sparse trees open ARCHIVE trees"
26865 (setq org-sparse-tree-open-archived-trees
26866 (not org-sparse-tree-open-archived-trees))
26867 :style toggle :selected org-sparse-tree-open-archived-trees]
26868 ["Cycling opens ARCHIVE trees"
26869 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
26870 :style toggle :selected org-cycle-open-archived-trees]
26871 ["Agenda includes ARCHIVE trees"
26872 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
26873 :style toggle :selected (not org-agenda-skip-archived-trees)]
26874 "--"
26875 ["Move Subtree to Archive" org-advertized-archive-subtree t]
26876 ; ["Check and Move Children" (org-archive-subtree '(4))
26877 ; :active t :keys "C-u C-c C-x C-s"]
26879 "--"
26880 ("TODO Lists"
26881 ["TODO/DONE/-" org-todo t]
26882 ("Select keyword"
26883 ["Next keyword" org-shiftright (org-on-heading-p)]
26884 ["Previous keyword" org-shiftleft (org-on-heading-p)]
26885 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
26886 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
26887 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
26888 ["Show TODO Tree" org-show-todo-tree t]
26889 ["Global TODO list" org-todo-list t]
26890 "--"
26891 ["Set Priority" org-priority t]
26892 ["Priority Up" org-shiftup t]
26893 ["Priority Down" org-shiftdown t])
26894 ("TAGS and Properties"
26895 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
26896 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
26897 "--"
26898 ["Set property" 'org-set-property t]
26899 ["Column view of properties" org-columns t]
26900 ["Insert Column View DBlock" org-insert-columns-dblock t])
26901 ("Dates and Scheduling"
26902 ["Timestamp" org-time-stamp t]
26903 ["Timestamp (inactive)" org-time-stamp-inactive t]
26904 ("Change Date"
26905 ["1 Day Later" org-shiftright t]
26906 ["1 Day Earlier" org-shiftleft t]
26907 ["1 ... Later" org-shiftup t]
26908 ["1 ... Earlier" org-shiftdown t])
26909 ["Compute Time Range" org-evaluate-time-range t]
26910 ["Schedule Item" org-schedule t]
26911 ["Deadline" org-deadline t]
26912 "--"
26913 ["Custom time format" org-toggle-time-stamp-overlays
26914 :style radio :selected org-display-custom-times]
26915 "--"
26916 ["Goto Calendar" org-goto-calendar t]
26917 ["Date from Calendar" org-date-from-calendar t])
26918 ("Logging work"
26919 ["Clock in" org-clock-in t]
26920 ["Clock out" org-clock-out t]
26921 ["Clock cancel" org-clock-cancel t]
26922 ["Goto running clock" org-clock-goto t]
26923 ["Display times" org-clock-display t]
26924 ["Create clock table" org-clock-report t]
26925 "--"
26926 ["Record DONE time"
26927 (progn (setq org-log-done (not org-log-done))
26928 (message "Switching to %s will %s record a timestamp"
26929 (car org-done-keywords)
26930 (if org-log-done "automatically" "not")))
26931 :style toggle :selected org-log-done])
26932 "--"
26933 ["Agenda Command..." org-agenda t]
26934 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
26935 ("File List for Agenda")
26936 ("Special views current file"
26937 ["TODO Tree" org-show-todo-tree t]
26938 ["Check Deadlines" org-check-deadlines t]
26939 ["Timeline" org-timeline t]
26940 ["Tags Tree" org-tags-sparse-tree t])
26941 "--"
26942 ("Hyperlinks"
26943 ["Store Link (Global)" org-store-link t]
26944 ["Insert Link" org-insert-link t]
26945 ["Follow Link" org-open-at-point t]
26946 "--"
26947 ["Next link" org-next-link t]
26948 ["Previous link" org-previous-link t]
26949 "--"
26950 ["Descriptive Links"
26951 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
26952 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
26953 ["Literal Links"
26954 (progn
26955 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
26956 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
26957 "--"
26958 ["Export/Publish..." org-export t]
26959 ("LaTeX"
26960 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
26961 :selected org-cdlatex-mode]
26962 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
26963 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
26964 ["Modify math symbol" org-cdlatex-math-modify
26965 (org-inside-LaTeX-fragment-p)]
26966 ["Export LaTeX fragments as images"
26967 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
26968 :style toggle :selected org-export-with-LaTeX-fragments])
26969 "--"
26970 ("Documentation"
26971 ["Show Version" org-version t]
26972 ["Info Documentation" org-info t])
26973 ("Customize"
26974 ["Browse Org Group" org-customize t]
26975 "--"
26976 ["Expand This Menu" org-create-customize-menu
26977 (fboundp 'customize-menu-create)])
26978 "--"
26979 ["Refresh setup" org-mode-restart t]
26982 (defun org-info (&optional node)
26983 "Read documentation for Org-mode in the info system.
26984 With optional NODE, go directly to that node."
26985 (interactive)
26986 (info (format "(org)%s" (or node ""))))
26988 (defun org-install-agenda-files-menu ()
26989 (let ((bl (buffer-list)))
26990 (save-excursion
26991 (while bl
26992 (set-buffer (pop bl))
26993 (if (org-mode-p) (setq bl nil)))
26994 (when (org-mode-p)
26995 (easy-menu-change
26996 '("Org") "File List for Agenda"
26997 (append
26998 (list
26999 ["Edit File List" (org-edit-agenda-file-list) t]
27000 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27001 ["Remove Current File from List" org-remove-file t]
27002 ["Cycle through agenda files" org-cycle-agenda-files t]
27003 ["Occur in all agenda files" org-occur-in-agenda-files t]
27004 "--")
27005 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27007 ;;;; Documentation
27009 (defun org-customize ()
27010 "Call the customize function with org as argument."
27011 (interactive)
27012 (customize-browse 'org))
27014 (defun org-create-customize-menu ()
27015 "Create a full customization menu for Org-mode, insert it into the menu."
27016 (interactive)
27017 (if (fboundp 'customize-menu-create)
27018 (progn
27019 (easy-menu-change
27020 '("Org") "Customize"
27021 `(["Browse Org group" org-customize t]
27022 "--"
27023 ,(customize-menu-create 'org)
27024 ["Set" Custom-set t]
27025 ["Save" Custom-save t]
27026 ["Reset to Current" Custom-reset-current t]
27027 ["Reset to Saved" Custom-reset-saved t]
27028 ["Reset to Standard Settings" Custom-reset-standard t]))
27029 (message "\"Org\"-menu now contains full customization menu"))
27030 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27032 ;;;; Miscellaneous stuff
27035 ;;; Generally useful functions
27037 (defun org-context ()
27038 "Return a list of contexts of the current cursor position.
27039 If several contexts apply, all are returned.
27040 Each context entry is a list with a symbol naming the context, and
27041 two positions indicating start and end of the context. Possible
27042 contexts are:
27044 :headline anywhere in a headline
27045 :headline-stars on the leading stars in a headline
27046 :todo-keyword on a TODO keyword (including DONE) in a headline
27047 :tags on the TAGS in a headline
27048 :priority on the priority cookie in a headline
27049 :item on the first line of a plain list item
27050 :item-bullet on the bullet/number of a plain list item
27051 :checkbox on the checkbox in a plain list item
27052 :table in an org-mode table
27053 :table-special on a special filed in a table
27054 :table-table in a table.el table
27055 :link on a hyperlink
27056 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27057 :target on a <<target>>
27058 :radio-target on a <<<radio-target>>>
27059 :latex-fragment on a LaTeX fragment
27060 :latex-preview on a LaTeX fragment with overlayed preview image
27062 This function expects the position to be visible because it uses font-lock
27063 faces as a help to recognize the following contexts: :table-special, :link,
27064 and :keyword."
27065 (let* ((f (get-text-property (point) 'face))
27066 (faces (if (listp f) f (list f)))
27067 (p (point)) clist o)
27068 ;; First the large context
27069 (cond
27070 ((org-on-heading-p t)
27071 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27072 (when (progn
27073 (beginning-of-line 1)
27074 (looking-at org-todo-line-tags-regexp))
27075 (push (org-point-in-group p 1 :headline-stars) clist)
27076 (push (org-point-in-group p 2 :todo-keyword) clist)
27077 (push (org-point-in-group p 4 :tags) clist))
27078 (goto-char p)
27079 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27080 (if (looking-at "\\[#[A-Z0-9]\\]")
27081 (push (org-point-in-group p 0 :priority) clist)))
27083 ((org-at-item-p)
27084 (push (org-point-in-group p 2 :item-bullet) clist)
27085 (push (list :item (point-at-bol)
27086 (save-excursion (org-end-of-item) (point)))
27087 clist)
27088 (and (org-at-item-checkbox-p)
27089 (push (org-point-in-group p 0 :checkbox) clist)))
27091 ((org-at-table-p)
27092 (push (list :table (org-table-begin) (org-table-end)) clist)
27093 (if (memq 'org-formula faces)
27094 (push (list :table-special
27095 (previous-single-property-change p 'face)
27096 (next-single-property-change p 'face)) clist)))
27097 ((org-at-table-p 'any)
27098 (push (list :table-table) clist)))
27099 (goto-char p)
27101 ;; Now the small context
27102 (cond
27103 ((org-at-timestamp-p)
27104 (push (org-point-in-group p 0 :timestamp) clist))
27105 ((memq 'org-link faces)
27106 (push (list :link
27107 (previous-single-property-change p 'face)
27108 (next-single-property-change p 'face)) clist))
27109 ((memq 'org-special-keyword faces)
27110 (push (list :keyword
27111 (previous-single-property-change p 'face)
27112 (next-single-property-change p 'face)) clist))
27113 ((org-on-target-p)
27114 (push (org-point-in-group p 0 :target) clist)
27115 (goto-char (1- (match-beginning 0)))
27116 (if (looking-at org-radio-target-regexp)
27117 (push (org-point-in-group p 0 :radio-target) clist))
27118 (goto-char p))
27119 ((setq o (car (delq nil
27120 (mapcar
27121 (lambda (x)
27122 (if (memq x org-latex-fragment-image-overlays) x))
27123 (org-overlays-at (point))))))
27124 (push (list :latex-fragment
27125 (org-overlay-start o) (org-overlay-end o)) clist)
27126 (push (list :latex-preview
27127 (org-overlay-start o) (org-overlay-end o)) clist))
27128 ((org-inside-LaTeX-fragment-p)
27129 ;; FIXME: positions wrong.
27130 (push (list :latex-fragment (point) (point)) clist)))
27132 (setq clist (nreverse (delq nil clist)))
27133 clist))
27135 ;; FIXME: Compare with at-regexp-p Do we need both?
27136 (defun org-in-regexp (re &optional nlines visually)
27137 "Check if point is inside a match of regexp.
27138 Normally only the current line is checked, but you can include NLINES extra
27139 lines both before and after point into the search.
27140 If VISUALLY is set, require that the cursor is not after the match but
27141 really on, so that the block visually is on the match."
27142 (catch 'exit
27143 (let ((pos (point))
27144 (eol (point-at-eol (+ 1 (or nlines 0))))
27145 (inc (if visually 1 0)))
27146 (save-excursion
27147 (beginning-of-line (- 1 (or nlines 0)))
27148 (while (re-search-forward re eol t)
27149 (if (and (<= (match-beginning 0) pos)
27150 (>= (+ inc (match-end 0)) pos))
27151 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27153 (defun org-at-regexp-p (regexp)
27154 "Is point inside a match of REGEXP in the current line?"
27155 (catch 'exit
27156 (save-excursion
27157 (let ((pos (point)) (end (point-at-eol)))
27158 (beginning-of-line 1)
27159 (while (re-search-forward regexp end t)
27160 (if (and (<= (match-beginning 0) pos)
27161 (>= (match-end 0) pos))
27162 (throw 'exit t)))
27163 nil))))
27165 (defun org-occur-in-agenda-files (regexp &optional nlines)
27166 "Call `multi-occur' with buffers for all agenda files."
27167 (interactive "sOrg-files matching: \np")
27168 (let* ((files (org-agenda-files))
27169 (tnames (mapcar 'file-truename files))
27170 (extra org-agenda-multi-occur-extra-files)
27172 (while (setq f (pop extra))
27173 (unless (member (file-truename f) tnames)
27174 (add-to-list 'files f 'append)
27175 (add-to-list 'tnames (file-truename f) 'append)))
27176 (multi-occur
27177 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27178 regexp)))
27180 (defun org-uniquify (list)
27181 "Remove duplicate elements from LIST."
27182 (let (res)
27183 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27184 res))
27186 (defun org-delete-all (elts list)
27187 "Remove all elements in ELTS from LIST."
27188 (while elts
27189 (setq list (delete (pop elts) list)))
27190 list)
27192 (defun org-back-over-empty-lines ()
27193 "Move backwards over witespace, to the beginning of the first empty line.
27194 Returns the number o empty lines passed."
27195 (let ((pos (point)))
27196 (skip-chars-backward " \t\n\r")
27197 (beginning-of-line 2)
27198 (goto-char (min (point) pos))
27199 (count-lines (point) pos)))
27201 (defun org-skip-whitespace ()
27202 (skip-chars-forward " \t\n\r"))
27204 (defun org-point-in-group (point group &optional context)
27205 "Check if POINT is in match-group GROUP.
27206 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27207 match. If the match group does ot exist or point is not inside it,
27208 return nil."
27209 (and (match-beginning group)
27210 (>= point (match-beginning group))
27211 (<= point (match-end group))
27212 (if context
27213 (list context (match-beginning group) (match-end group))
27214 t)))
27216 (defun org-switch-to-buffer-other-window (&rest args)
27217 "Switch to buffer in a second window on the current frame.
27218 In particular, do not allow pop-up frames."
27219 (let (pop-up-frames special-display-buffer-names special-display-regexps
27220 special-display-function)
27221 (apply 'switch-to-buffer-other-window args)))
27223 (defun org-combine-plists (&rest plists)
27224 "Create a single property list from all plists in PLISTS.
27225 The process starts by copying the first list, and then setting properties
27226 from the other lists. Settings in the last list are the most significant
27227 ones and overrule settings in the other lists."
27228 (let ((rtn (copy-sequence (pop plists)))
27229 p v ls)
27230 (while plists
27231 (setq ls (pop plists))
27232 (while ls
27233 (setq p (pop ls) v (pop ls))
27234 (setq rtn (plist-put rtn p v))))
27235 rtn))
27237 (defun org-move-line-down (arg)
27238 "Move the current line down. With prefix argument, move it past ARG lines."
27239 (interactive "p")
27240 (let ((col (current-column))
27241 beg end pos)
27242 (beginning-of-line 1) (setq beg (point))
27243 (beginning-of-line 2) (setq end (point))
27244 (beginning-of-line (+ 1 arg))
27245 (setq pos (move-marker (make-marker) (point)))
27246 (insert (delete-and-extract-region beg end))
27247 (goto-char pos)
27248 (move-to-column col)))
27250 (defun org-move-line-up (arg)
27251 "Move the current line up. With prefix argument, move it past ARG lines."
27252 (interactive "p")
27253 (let ((col (current-column))
27254 beg end pos)
27255 (beginning-of-line 1) (setq beg (point))
27256 (beginning-of-line 2) (setq end (point))
27257 (beginning-of-line (- arg))
27258 (setq pos (move-marker (make-marker) (point)))
27259 (insert (delete-and-extract-region beg end))
27260 (goto-char pos)
27261 (move-to-column col)))
27263 (defun org-replace-escapes (string table)
27264 "Replace %-escapes in STRING with values in TABLE.
27265 TABLE is an association list with keys like \"%a\" and string values.
27266 The sequences in STRING may contain normal field width and padding information,
27267 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27268 so values can contain further %-escapes if they are define later in TABLE."
27269 (let ((case-fold-search nil)
27270 e re rpl)
27271 (while (setq e (pop table))
27272 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27273 (while (string-match re string)
27274 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27275 (cdr e)))
27276 (setq string (replace-match rpl t t string))))
27277 string))
27280 (defun org-sublist (list start end)
27281 "Return a section of LIST, from START to END.
27282 Counting starts at 1."
27283 (let (rtn (c start))
27284 (setq list (nthcdr (1- start) list))
27285 (while (and list (<= c end))
27286 (push (pop list) rtn)
27287 (setq c (1+ c)))
27288 (nreverse rtn)))
27290 (defun org-find-base-buffer-visiting (file)
27291 "Like `find-buffer-visiting' but alway return the base buffer and
27292 not an indirect buffer"
27293 (let ((buf (find-buffer-visiting file)))
27294 (if buf
27295 (or (buffer-base-buffer buf) buf)
27296 nil)))
27298 (defun org-image-file-name-regexp ()
27299 "Return regexp matching the file names of images."
27300 (if (fboundp 'image-file-name-regexp)
27301 (image-file-name-regexp)
27302 (let ((image-file-name-extensions
27303 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27304 "xbm" "xpm" "pbm" "pgm" "ppm")))
27305 (concat "\\."
27306 (regexp-opt (nconc (mapcar 'upcase
27307 image-file-name-extensions)
27308 image-file-name-extensions)
27310 "\\'"))))
27312 (defun org-file-image-p (file)
27313 "Return non-nil if FILE is an image."
27314 (save-match-data
27315 (string-match (org-image-file-name-regexp) file)))
27317 ;;; Paragraph filling stuff.
27318 ;; We want this to be just right, so use the full arsenal.
27320 (defun org-indent-line-function ()
27321 "Indent line like previous, but further if previous was headline or item."
27322 (interactive)
27323 (let* ((pos (point))
27324 (itemp (org-at-item-p))
27325 column bpos bcol tpos tcol bullet btype bullet-type)
27326 ;; Find the previous relevant line
27327 (beginning-of-line 1)
27328 (cond
27329 ((looking-at "#") (setq column 0))
27330 ((looking-at "\\*+ ") (setq column 0))
27332 (beginning-of-line 0)
27333 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27334 (beginning-of-line 0))
27335 (cond
27336 ((looking-at "\\*+[ \t]+")
27337 (goto-char (match-end 0))
27338 (setq column (current-column)))
27339 ((org-in-item-p)
27340 (org-beginning-of-item)
27341 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27342 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27343 (setq bpos (match-beginning 1) tpos (match-end 0)
27344 bcol (progn (goto-char bpos) (current-column))
27345 tcol (progn (goto-char tpos) (current-column))
27346 bullet (match-string 1)
27347 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27348 (if (not itemp)
27349 (setq column tcol)
27350 (goto-char pos)
27351 (beginning-of-line 1)
27352 (if (looking-at "\\S-")
27353 (progn
27354 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27355 (setq bullet (match-string 1)
27356 btype (if (string-match "[0-9]" bullet) "n" bullet))
27357 (setq column (if (equal btype bullet-type) bcol tcol)))
27358 (setq column (org-get-indentation)))))
27359 (t (setq column (org-get-indentation))))))
27360 (goto-char pos)
27361 (if (<= (current-column) (current-indentation))
27362 (indent-line-to column)
27363 (save-excursion (indent-line-to column)))
27364 (setq column (current-column))
27365 (beginning-of-line 1)
27366 (if (looking-at
27367 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27368 (replace-match (concat "\\1" (format org-property-format
27369 (match-string 2) (match-string 3)))
27370 t nil))
27371 (move-to-column column)))
27373 (defun org-set-autofill-regexps ()
27374 (interactive)
27375 ;; In the paragraph separator we include headlines, because filling
27376 ;; text in a line directly attached to a headline would otherwise
27377 ;; fill the headline as well.
27378 (org-set-local 'comment-start-skip "^#+[ \t]*")
27379 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27380 ;; The paragraph starter includes hand-formatted lists.
27381 (org-set-local 'paragraph-start
27382 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27383 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27384 ;; But only if the user has not turned off tables or fixed-width regions
27385 (org-set-local
27386 'auto-fill-inhibit-regexp
27387 (concat "\\*+ \\|#\\+"
27388 "\\|[ \t]*" org-keyword-time-regexp
27389 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27390 (concat
27391 "\\|[ \t]*["
27392 (if org-enable-table-editor "|" "")
27393 (if org-enable-fixed-width-editor ":" "")
27394 "]"))))
27395 ;; We use our own fill-paragraph function, to make sure that tables
27396 ;; and fixed-width regions are not wrapped. That function will pass
27397 ;; through to `fill-paragraph' when appropriate.
27398 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27399 ; Adaptive filling: To get full control, first make sure that
27400 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27401 (org-set-local 'adaptive-fill-regexp "\000")
27402 (org-set-local 'adaptive-fill-function
27403 'org-adaptive-fill-function))
27405 (defun org-fill-paragraph (&optional justify)
27406 "Re-align a table, pass through to fill-paragraph if no table."
27407 (let ((table-p (org-at-table-p))
27408 (table.el-p (org-at-table.el-p)))
27409 (cond ((and (equal (char-after (point-at-bol)) ?*)
27410 (save-excursion (goto-char (point-at-bol))
27411 (looking-at outline-regexp)))
27412 t) ; skip headlines
27413 (table.el-p t) ; skip table.el tables
27414 (table-p (org-table-align) t) ; align org-mode tables
27415 (t nil)))) ; call paragraph-fill
27417 ;; For reference, this is the default value of adaptive-fill-regexp
27418 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27420 (defun org-adaptive-fill-function ()
27421 "Return a fill prefix for org-mode files.
27422 In particular, this makes sure hanging paragraphs for hand-formatted lists
27423 work correctly."
27424 (cond ((looking-at "#[ \t]+")
27425 (match-string 0))
27426 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27427 (save-excursion
27428 (goto-char (match-end 0))
27429 (make-string (current-column) ?\ )))
27430 (t nil)))
27432 ;;;; Functions extending outline functionality
27434 (defun org-beginning-of-line (&optional arg)
27435 "Go to the beginning of the current line. If that is invisible, continue
27436 to a visible line beginning. This makes the function of C-a more intuitive.
27437 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27438 first attempt, and only move to after the tags when the cursor is already
27439 beyond the end of the headline."
27440 (interactive "P")
27441 (let ((pos (point)))
27442 (beginning-of-line 1)
27443 (if (bobp)
27445 (backward-char 1)
27446 (if (org-invisible-p)
27447 (while (and (not (bobp)) (org-invisible-p))
27448 (backward-char 1)
27449 (beginning-of-line 1))
27450 (forward-char 1)))
27451 (when org-special-ctrl-a/e
27452 (cond
27453 ((and (looking-at org-todo-line-regexp)
27454 (= (char-after (match-end 1)) ?\ ))
27455 (goto-char
27456 (if (eq org-special-ctrl-a/e t)
27457 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27458 ((= pos (point)) (match-beginning 3))
27459 (t (point)))
27460 (cond ((> pos (point)) (point))
27461 ((not (eq last-command this-command)) (point))
27462 (t (match-beginning 3))))))
27463 ((org-at-item-p)
27464 (goto-char
27465 (if (eq org-special-ctrl-a/e t)
27466 (cond ((> pos (match-end 4)) (match-end 4))
27467 ((= pos (point)) (match-end 4))
27468 (t (point)))
27469 (cond ((> pos (point)) (point))
27470 ((not (eq last-command this-command)) (point))
27471 (t (match-end 4))))))))))
27473 (defun org-end-of-line (&optional arg)
27474 "Go to the end of the line.
27475 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27476 first attempt, and only move to after the tags when the cursor is already
27477 beyond the end of the headline."
27478 (interactive "P")
27479 (if (or (not org-special-ctrl-a/e)
27480 (not (org-on-heading-p)))
27481 (end-of-line arg)
27482 (let ((pos (point)))
27483 (beginning-of-line 1)
27484 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27485 (if (eq org-special-ctrl-a/e t)
27486 (if (or (< pos (match-beginning 1))
27487 (= pos (match-end 0)))
27488 (goto-char (match-beginning 1))
27489 (goto-char (match-end 0)))
27490 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27491 (goto-char (match-end 0))
27492 (goto-char (match-beginning 1))))
27493 (end-of-line arg)))))
27495 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27496 (define-key org-mode-map "\C-e" 'org-end-of-line)
27498 (defun org-invisible-p ()
27499 "Check if point is at a character currently not visible."
27500 ;; Early versions of noutline don't have `outline-invisible-p'.
27501 (if (fboundp 'outline-invisible-p)
27502 (outline-invisible-p)
27503 (get-char-property (point) 'invisible)))
27505 (defun org-invisible-p2 ()
27506 "Check if point is at a character currently not visible."
27507 (save-excursion
27508 (if (and (eolp) (not (bobp))) (backward-char 1))
27509 ;; Early versions of noutline don't have `outline-invisible-p'.
27510 (if (fboundp 'outline-invisible-p)
27511 (outline-invisible-p)
27512 (get-char-property (point) 'invisible))))
27514 (defalias 'org-back-to-heading 'outline-back-to-heading)
27515 (defalias 'org-on-heading-p 'outline-on-heading-p)
27516 (defalias 'org-at-heading-p 'outline-on-heading-p)
27517 (defun org-at-heading-or-item-p ()
27518 (or (org-on-heading-p) (org-at-item-p)))
27520 (defun org-on-target-p ()
27521 (or (org-in-regexp org-radio-target-regexp)
27522 (org-in-regexp org-target-regexp)))
27524 (defun org-up-heading-all (arg)
27525 "Move to the heading line of which the present line is a subheading.
27526 This function considers both visible and invisible heading lines.
27527 With argument, move up ARG levels."
27528 (if (fboundp 'outline-up-heading-all)
27529 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27530 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27532 (defun org-up-heading-safe ()
27533 "Move to the heading line of which the present line is a subheading.
27534 This version will not throw an error. It will return the level of the
27535 headline found, or nil if no higher level is found."
27536 (let ((pos (point)) start-level level
27537 (re (concat "^" outline-regexp)))
27538 (catch 'exit
27539 (outline-back-to-heading t)
27540 (setq start-level (funcall outline-level))
27541 (if (equal start-level 1) (throw 'exit nil))
27542 (while (re-search-backward re nil t)
27543 (setq level (funcall outline-level))
27544 (if (< level start-level) (throw 'exit level)))
27545 nil)))
27547 (defun org-first-sibling-p ()
27548 "Is this heading the first child of its parents?"
27549 (interactive)
27550 (let ((re (concat "^" outline-regexp))
27551 level l)
27552 (unless (org-at-heading-p t)
27553 (error "Not at a heading"))
27554 (setq level (funcall outline-level))
27555 (save-excursion
27556 (if (not (re-search-backward re nil t))
27558 (setq l (funcall outline-level))
27559 (< l level)))))
27561 (defun org-goto-sibling (&optional previous)
27562 "Goto the next sibling, even if it is invisible.
27563 When PREVIOUS is set, go to the previous sibling instead. Returns t
27564 when a sibling was found. When none is found, return nil and don't
27565 move point."
27566 (let ((fun (if previous 're-search-backward 're-search-forward))
27567 (pos (point))
27568 (re (concat "^" outline-regexp))
27569 level l)
27570 (when (condition-case nil (org-back-to-heading t) (error nil))
27571 (setq level (funcall outline-level))
27572 (catch 'exit
27573 (or previous (forward-char 1))
27574 (while (funcall fun re nil t)
27575 (setq l (funcall outline-level))
27576 (when (< l level) (goto-char pos) (throw 'exit nil))
27577 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27578 (goto-char pos)
27579 nil))))
27581 (defun org-show-siblings ()
27582 "Show all siblings of the current headline."
27583 (save-excursion
27584 (while (org-goto-sibling) (org-flag-heading nil)))
27585 (save-excursion
27586 (while (org-goto-sibling 'previous)
27587 (org-flag-heading nil))))
27589 (defun org-show-hidden-entry ()
27590 "Show an entry where even the heading is hidden."
27591 (save-excursion
27592 (org-show-entry)))
27594 (defun org-flag-heading (flag &optional entry)
27595 "Flag the current heading. FLAG non-nil means make invisible.
27596 When ENTRY is non-nil, show the entire entry."
27597 (save-excursion
27598 (org-back-to-heading t)
27599 ;; Check if we should show the entire entry
27600 (if entry
27601 (progn
27602 (org-show-entry)
27603 (save-excursion
27604 (and (outline-next-heading)
27605 (org-flag-heading nil))))
27606 (outline-flag-region (max (point-min) (1- (point)))
27607 (save-excursion (outline-end-of-heading) (point))
27608 flag))))
27610 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27611 ;; This is an exact copy of the original function, but it uses
27612 ;; `org-back-to-heading', to make it work also in invisible
27613 ;; trees. And is uses an invisible-OK argument.
27614 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27615 (org-back-to-heading invisible-OK)
27616 (let ((first t)
27617 (level (funcall outline-level)))
27618 (while (and (not (eobp))
27619 (or first (> (funcall outline-level) level)))
27620 (setq first nil)
27621 (outline-next-heading))
27622 (unless to-heading
27623 (if (memq (preceding-char) '(?\n ?\^M))
27624 (progn
27625 ;; Go to end of line before heading
27626 (forward-char -1)
27627 (if (memq (preceding-char) '(?\n ?\^M))
27628 ;; leave blank line before heading
27629 (forward-char -1))))))
27630 (point))
27632 (defun org-show-subtree ()
27633 "Show everything after this heading at deeper levels."
27634 (outline-flag-region
27635 (point)
27636 (save-excursion
27637 (outline-end-of-subtree) (outline-next-heading) (point))
27638 nil))
27640 (defun org-show-entry ()
27641 "Show the body directly following this heading.
27642 Show the heading too, if it is currently invisible."
27643 (interactive)
27644 (save-excursion
27645 (condition-case nil
27646 (progn
27647 (org-back-to-heading t)
27648 (outline-flag-region
27649 (max (point-min) (1- (point)))
27650 (save-excursion
27651 (re-search-forward
27652 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27653 (or (match-beginning 1) (point-max)))
27654 nil))
27655 (error nil))))
27657 (defun org-make-options-regexp (kwds)
27658 "Make a regular expression for keyword lines."
27659 (concat
27661 "#?[ \t]*\\+\\("
27662 (mapconcat 'regexp-quote kwds "\\|")
27663 "\\):[ \t]*"
27664 "\\(.+\\)"))
27666 ;; Make isearch reveal the necessary context
27667 (defun org-isearch-end ()
27668 "Reveal context after isearch exits."
27669 (when isearch-success ; only if search was successful
27670 (if (featurep 'xemacs)
27671 ;; Under XEmacs, the hook is run in the correct place,
27672 ;; we directly show the context.
27673 (org-show-context 'isearch)
27674 ;; In Emacs the hook runs *before* restoring the overlays.
27675 ;; So we have to use a one-time post-command-hook to do this.
27676 ;; (Emacs 22 has a special variable, see function `org-mode')
27677 (unless (and (boundp 'isearch-mode-end-hook-quit)
27678 isearch-mode-end-hook-quit)
27679 ;; Only when the isearch was not quitted.
27680 (org-add-hook 'post-command-hook 'org-isearch-post-command
27681 'append 'local)))))
27683 (defun org-isearch-post-command ()
27684 "Remove self from hook, and show context."
27685 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27686 (org-show-context 'isearch))
27689 ;;;; Integration with and fixes for other packages
27691 ;;; Imenu support
27693 (defvar org-imenu-markers nil
27694 "All markers currently used by Imenu.")
27695 (make-variable-buffer-local 'org-imenu-markers)
27697 (defun org-imenu-new-marker (&optional pos)
27698 "Return a new marker for use by Imenu, and remember the marker."
27699 (let ((m (make-marker)))
27700 (move-marker m (or pos (point)))
27701 (push m org-imenu-markers)
27704 (defun org-imenu-get-tree ()
27705 "Produce the index for Imenu."
27706 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
27707 (setq org-imenu-markers nil)
27708 (let* ((n org-imenu-depth)
27709 (re (concat "^" outline-regexp))
27710 (subs (make-vector (1+ n) nil))
27711 (last-level 0)
27712 m tree level head)
27713 (save-excursion
27714 (save-restriction
27715 (widen)
27716 (goto-char (point-max))
27717 (while (re-search-backward re nil t)
27718 (setq level (org-reduced-level (funcall outline-level)))
27719 (when (<= level n)
27720 (looking-at org-complex-heading-regexp)
27721 (setq head (org-match-string-no-properties 4)
27722 m (org-imenu-new-marker))
27723 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
27724 (if (>= level last-level)
27725 (push (cons head m) (aref subs level))
27726 (push (cons head (aref subs (1+ level))) (aref subs level))
27727 (loop for i from (1+ level) to n do (aset subs i nil)))
27728 (setq last-level level)))))
27729 (aref subs 1)))
27731 (eval-after-load "imenu"
27732 '(progn
27733 (add-hook 'imenu-after-jump-hook
27734 (lambda () (org-show-context 'org-goto)))))
27736 ;; Speedbar support
27738 (defun org-speedbar-set-agenda-restriction ()
27739 "Restrict future agenda commands to the location at point in speedbar.
27740 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
27741 (interactive)
27742 (let (p m tp np dir txt w)
27743 (cond
27744 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27745 'org-imenu t))
27746 (setq m (get-text-property p 'org-imenu-marker))
27747 (save-excursion
27748 (save-restriction
27749 (set-buffer (marker-buffer m))
27750 (goto-char m)
27751 (org-agenda-set-restriction-lock 'subtree))))
27752 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27753 'speedbar-function 'speedbar-find-file))
27754 (setq tp (previous-single-property-change
27755 (1+ p) 'speedbar-function)
27756 np (next-single-property-change
27757 tp 'speedbar-function)
27758 dir (speedbar-line-directory)
27759 txt (buffer-substring-no-properties (or tp (point-min))
27760 (or np (point-max))))
27761 (save-excursion
27762 (save-restriction
27763 (set-buffer (find-file-noselect
27764 (let ((default-directory dir))
27765 (expand-file-name txt))))
27766 (unless (org-mode-p)
27767 (error "Cannot restrict to non-Org-mode file"))
27768 (org-agenda-set-restriction-lock 'file))))
27769 (t (error "Don't know how to restrict Org-mode's agenda")))
27770 (org-move-overlay org-speedbar-restriction-lock-overlay
27771 (point-at-bol) (point-at-eol))
27772 (setq current-prefix-arg nil)
27773 (org-agenda-maybe-redo)))
27775 (eval-after-load "speedbar"
27776 '(progn
27777 (speedbar-add-supported-extension ".org")
27778 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
27779 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
27780 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
27781 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27782 (add-hook 'speedbar-visiting-tag-hook
27783 (lambda () (org-show-context 'org-goto)))))
27786 ;;; Fixes and Hacks
27788 ;; Make flyspell not check words in links, to not mess up our keymap
27789 (defun org-mode-flyspell-verify ()
27790 "Don't let flyspell put overlays at active buttons."
27791 (not (get-text-property (point) 'keymap)))
27793 ;; Make `bookmark-jump' show the jump location if it was hidden.
27794 (eval-after-load "bookmark"
27795 '(if (boundp 'bookmark-after-jump-hook)
27796 ;; We can use the hook
27797 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
27798 ;; Hook not available, use advice
27799 (defadvice bookmark-jump (after org-make-visible activate)
27800 "Make the position visible."
27801 (org-bookmark-jump-unhide))))
27803 (defun org-bookmark-jump-unhide ()
27804 "Unhide the current position, to show the bookmark location."
27805 (and (org-mode-p)
27806 (or (org-invisible-p)
27807 (save-excursion (goto-char (max (point-min) (1- (point))))
27808 (org-invisible-p)))
27809 (org-show-context 'bookmark-jump)))
27811 ;; Fix a bug in htmlize where there are text properties (face nil)
27812 (eval-after-load "htmlize"
27813 '(progn
27814 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
27815 "Make sure there are no nil faces"
27816 (setq ad-return-value (delq nil ad-return-value)))))
27818 ;; Make session.el ignore our circular variable
27819 (eval-after-load "session"
27820 '(add-to-list 'session-globals-exclude 'org-mark-ring))
27822 ;;;; Experimental code
27824 (defun org-closed-in-range ()
27825 "Sparse tree of items closed in a certain time range.
27826 Still experimental, may disappear in the future."
27827 (interactive)
27828 ;; Get the time interval from the user.
27829 (let* ((time1 (time-to-seconds
27830 (org-read-date nil 'to-time nil "Starting date: ")))
27831 (time2 (time-to-seconds
27832 (org-read-date nil 'to-time nil "End date:")))
27833 ;; callback function
27834 (callback (lambda ()
27835 (let ((time
27836 (time-to-seconds
27837 (apply 'encode-time
27838 (org-parse-time-string
27839 (match-string 1))))))
27840 ;; check if time in interval
27841 (and (>= time time1) (<= time time2))))))
27842 ;; make tree, check each match with the callback
27843 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
27845 ;;;; Finish up
27847 (provide 'org)
27849 (run-hooks 'org-load-hook)
27851 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
27852 ;;; org.el ends here