Release 5.19a
[org-mode.git] / org.el
blob83f24b3f683a99f253671c5b4445a385bf8e1c6a
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 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 targes 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 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 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, legal 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 cess is a face to be used,
4035 and it can also just be a like 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 Info-goto-node "info" (nodename &optional fork))
4109 (declare-function bbdb "ext:bbdb-com" (string elidep))
4110 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4111 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4112 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4113 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4114 (declare-function bbdb-record-name "ext:bbdb" (record))
4115 (declare-function bibtex-beginning-of-entry "bibtex" ())
4116 (declare-function bibtex-generate-autokey "bibtex" ())
4117 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4118 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4119 (defvar calc-embedded-close-formula)
4120 (defvar calc-embedded-open-formula)
4121 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4122 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4123 (declare-function calendar-check-holidays "holidays" (date))
4124 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4125 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4126 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4127 (declare-function calendar-forward-day "cal-move" (arg))
4128 (declare-function calendar-french-date-string "cal-french" (&optional date))
4129 (declare-function calendar-goto-date "cal-move" (date))
4130 (declare-function calendar-goto-today "cal-move" ())
4131 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4132 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4133 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4134 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4135 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4136 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4137 (defvar calendar-mode-map)
4138 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4139 (declare-function cdlatex-tab "ext:cdlatex" ())
4140 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4141 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4142 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4143 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
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" (&optional commentsp))
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-legal-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 (defun org-promote ()
6210 "Promote the current heading higher up the tree.
6211 If the region is active in `transient-mark-mode', promote all headings
6212 in the region."
6213 (org-back-to-heading t)
6214 (let* ((level (save-match-data (funcall outline-level)))
6215 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6216 (diff (abs (- level (length up-head) -1))))
6217 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6218 (replace-match up-head nil t)
6219 ;; Fixup tag positioning
6220 (and org-auto-align-tags (org-set-tags nil t))
6221 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6223 (defun org-demote ()
6224 "Demote the current heading lower down the tree.
6225 If the region is active in `transient-mark-mode', demote all headings
6226 in the region."
6227 (org-back-to-heading t)
6228 (let* ((level (save-match-data (funcall outline-level)))
6229 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6230 (diff (abs (- level (length down-head) -1))))
6231 (replace-match down-head nil t)
6232 ;; Fixup tag positioning
6233 (and org-auto-align-tags (org-set-tags nil t))
6234 (if org-adapt-indentation (org-fixup-indentation diff))))
6236 (defun org-map-tree (fun)
6237 "Call FUN for every heading underneath the current one."
6238 (org-back-to-heading)
6239 (let ((level (funcall outline-level)))
6240 (save-excursion
6241 (funcall fun)
6242 (while (and (progn
6243 (outline-next-heading)
6244 (> (funcall outline-level) level))
6245 (not (eobp)))
6246 (funcall fun)))))
6248 (defun org-map-region (fun beg end)
6249 "Call FUN for every heading between BEG and END."
6250 (let ((org-ignore-region t))
6251 (save-excursion
6252 (setq end (copy-marker end))
6253 (goto-char beg)
6254 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6255 (< (point) end))
6256 (funcall fun))
6257 (while (and (progn
6258 (outline-next-heading)
6259 (< (point) end))
6260 (not (eobp)))
6261 (funcall fun)))))
6263 (defun org-fixup-indentation (diff)
6264 "Change the indentation in the current entry by DIFF
6265 However, if any line in the current entry has no indentation, or if it
6266 would end up with no indentation after the change, nothing at all is done."
6267 (save-excursion
6268 (let ((end (save-excursion (outline-next-heading)
6269 (point-marker)))
6270 (prohibit (if (> diff 0)
6271 "^\\S-"
6272 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6273 col)
6274 (unless (save-excursion (end-of-line 1)
6275 (re-search-forward prohibit end t))
6276 (while (and (< (point) end)
6277 (re-search-forward "^[ \t]+" end t))
6278 (goto-char (match-end 0))
6279 (setq col (current-column))
6280 (if (< diff 0) (replace-match ""))
6281 (indent-to (+ diff col))))
6282 (move-marker end nil))))
6284 (defun org-convert-to-odd-levels ()
6285 "Convert an org-mode file with all levels allowed to one with odd levels.
6286 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6287 level 5 etc."
6288 (interactive)
6289 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6290 (let ((org-odd-levels-only nil) n)
6291 (save-excursion
6292 (goto-char (point-min))
6293 (while (re-search-forward "^\\*\\*+ " nil t)
6294 (setq n (- (length (match-string 0)) 2))
6295 (while (>= (setq n (1- n)) 0)
6296 (org-demote))
6297 (end-of-line 1))))))
6300 (defun org-convert-to-oddeven-levels ()
6301 "Convert an org-mode file with only odd levels to one with odd and even levels.
6302 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6303 section with an even level, conversion would destroy the structure of the file. An error
6304 is signaled in this case."
6305 (interactive)
6306 (goto-char (point-min))
6307 ;; First check if there are no even levels
6308 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6309 (org-show-context t)
6310 (error "Not all levels are odd in this file. Conversion not possible."))
6311 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6312 (let ((org-odd-levels-only nil) n)
6313 (save-excursion
6314 (goto-char (point-min))
6315 (while (re-search-forward "^\\*\\*+ " nil t)
6316 (setq n (/ (1- (length (match-string 0))) 2))
6317 (while (>= (setq n (1- n)) 0)
6318 (org-promote))
6319 (end-of-line 1))))))
6321 (defun org-tr-level (n)
6322 "Make N odd if required."
6323 (if org-odd-levels-only (1+ (/ n 2)) n))
6325 ;;; Vertical tree motion, cutting and pasting of subtrees
6327 (defun org-move-subtree-up (&optional arg)
6328 "Move the current subtree up past ARG headlines of the same level."
6329 (interactive "p")
6330 (org-move-subtree-down (- (prefix-numeric-value arg))))
6332 (defun org-move-subtree-down (&optional arg)
6333 "Move the current subtree down past ARG headlines of the same level."
6334 (interactive "p")
6335 (setq arg (prefix-numeric-value arg))
6336 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6337 'outline-get-last-sibling))
6338 (ins-point (make-marker))
6339 (cnt (abs arg))
6340 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6341 ;; Select the tree
6342 (org-back-to-heading)
6343 (setq beg0 (point))
6344 (save-excursion
6345 (setq ne-beg (org-back-over-empty-lines))
6346 (setq beg (point)))
6347 (save-match-data
6348 (save-excursion (outline-end-of-heading)
6349 (setq folded (org-invisible-p)))
6350 (outline-end-of-subtree))
6351 (outline-next-heading)
6352 (setq ne-end (org-back-over-empty-lines))
6353 (setq end (point))
6354 (goto-char beg0)
6355 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6356 ;; include less whitespace
6357 (save-excursion
6358 (goto-char beg)
6359 (forward-line (- ne-beg ne-end))
6360 (setq beg (point))))
6361 ;; Find insertion point, with error handling
6362 (while (> cnt 0)
6363 (or (and (funcall movfunc) (looking-at outline-regexp))
6364 (progn (goto-char beg0)
6365 (error "Cannot move past superior level or buffer limit")))
6366 (setq cnt (1- cnt)))
6367 (if (> arg 0)
6368 ;; Moving forward - still need to move over subtree
6369 (progn (org-end-of-subtree t t)
6370 (save-excursion
6371 (org-back-over-empty-lines)
6372 (or (bolp) (newline)))))
6373 (setq ne-ins (org-back-over-empty-lines))
6374 (move-marker ins-point (point))
6375 (setq txt (buffer-substring beg end))
6376 (delete-region beg end)
6377 (outline-flag-region (1- beg) beg nil)
6378 (outline-flag-region (1- (point)) (point) nil)
6379 (insert txt)
6380 (or (bolp) (insert "\n"))
6381 (setq ins-end (point))
6382 (goto-char ins-point)
6383 (org-skip-whitespace)
6384 (when (and (< arg 0)
6385 (org-first-sibling-p)
6386 (> ne-ins ne-beg))
6387 ;; Move whitespace back to beginning
6388 (save-excursion
6389 (goto-char ins-end)
6390 (let ((kill-whole-line t))
6391 (kill-line (- ne-ins ne-beg)) (point)))
6392 (insert (make-string (- ne-ins ne-beg) ?\n)))
6393 (move-marker ins-point nil)
6394 (org-compact-display-after-subtree-move)
6395 (unless folded
6396 (org-show-entry)
6397 (show-children)
6398 (org-cycle-hide-drawers 'children))))
6400 (defvar org-subtree-clip ""
6401 "Clipboard for cut and paste of subtrees.
6402 This is actually only a copy of the kill, because we use the normal kill
6403 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6405 (defvar org-subtree-clip-folded nil
6406 "Was the last copied subtree folded?
6407 This is used to fold the tree back after pasting.")
6409 (defun org-cut-subtree (&optional n)
6410 "Cut the current subtree into the clipboard.
6411 With prefix arg N, cut this many sequential subtrees.
6412 This is a short-hand for marking the subtree and then cutting it."
6413 (interactive "p")
6414 (org-copy-subtree n 'cut))
6416 (defun org-copy-subtree (&optional n cut)
6417 "Cut the current subtree into the clipboard.
6418 With prefix arg N, cut this many sequential subtrees.
6419 This is a short-hand for marking the subtree and then copying it.
6420 If CUT is non-nil, actually cut the subtree."
6421 (interactive "p")
6422 (let (beg end folded (beg0 (point)))
6423 (if (interactive-p)
6424 (org-back-to-heading nil) ; take what looks like a subtree
6425 (org-back-to-heading t)) ; take what is really there
6426 (org-back-over-empty-lines)
6427 (setq beg (point))
6428 (skip-chars-forward " \t\r\n")
6429 (save-match-data
6430 (save-excursion (outline-end-of-heading)
6431 (setq folded (org-invisible-p)))
6432 (condition-case nil
6433 (outline-forward-same-level (1- n))
6434 (error nil))
6435 (org-end-of-subtree t t))
6436 (org-back-over-empty-lines)
6437 (setq end (point))
6438 (goto-char beg0)
6439 (when (> end beg)
6440 (setq org-subtree-clip-folded folded)
6441 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6442 (setq org-subtree-clip (current-kill 0))
6443 (message "%s: Subtree(s) with %d characters"
6444 (if cut "Cut" "Copied")
6445 (length org-subtree-clip)))))
6447 (defun org-paste-subtree (&optional level tree)
6448 "Paste the clipboard as a subtree, with modification of headline level.
6449 The entire subtree is promoted or demoted in order to match a new headline
6450 level. By default, the new level is derived from the visible headings
6451 before and after the insertion point, and taken to be the inferior headline
6452 level of the two. So if the previous visible heading is level 3 and the
6453 next is level 4 (or vice versa), level 4 will be used for insertion.
6454 This makes sure that the subtree remains an independent subtree and does
6455 not swallow low level entries.
6457 You can also force a different level, either by using a numeric prefix
6458 argument, or by inserting the heading marker by hand. For example, if the
6459 cursor is after \"*****\", then the tree will be shifted to level 5.
6461 If you want to insert the tree as is, just use \\[yank].
6463 If optional TREE is given, use this text instead of the kill ring."
6464 (interactive "P")
6465 (unless (org-kill-is-subtree-p tree)
6466 (error "%s"
6467 (substitute-command-keys
6468 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6469 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6470 (^re (concat "^\\(" outline-regexp "\\)"))
6471 (re (concat "\\(" outline-regexp "\\)"))
6472 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6474 (old-level (if (string-match ^re txt)
6475 (- (match-end 0) (match-beginning 0) 1)
6476 -1))
6477 (force-level (cond (level (prefix-numeric-value level))
6478 ((string-match
6479 ^re_ (buffer-substring (point-at-bol) (point)))
6480 (- (match-end 1) (match-beginning 1)))
6481 (t nil)))
6482 (previous-level (save-excursion
6483 (condition-case nil
6484 (progn
6485 (outline-previous-visible-heading 1)
6486 (if (looking-at re)
6487 (- (match-end 0) (match-beginning 0) 1)
6489 (error 1))))
6490 (next-level (save-excursion
6491 (condition-case nil
6492 (progn
6493 (or (looking-at outline-regexp)
6494 (outline-next-visible-heading 1))
6495 (if (looking-at re)
6496 (- (match-end 0) (match-beginning 0) 1)
6498 (error 1))))
6499 (new-level (or force-level (max previous-level next-level)))
6500 (shift (if (or (= old-level -1)
6501 (= new-level -1)
6502 (= old-level new-level))
6504 (- new-level old-level)))
6505 (delta (if (> shift 0) -1 1))
6506 (func (if (> shift 0) 'org-demote 'org-promote))
6507 (org-odd-levels-only nil)
6508 beg end)
6509 ;; Remove the forced level indicator
6510 (if force-level
6511 (delete-region (point-at-bol) (point)))
6512 ;; Paste
6513 (beginning-of-line 1)
6514 (org-back-over-empty-lines) ;; FIXME: correct fix????
6515 (setq beg (point))
6516 (insert-before-markers txt) ;; FIXME: correct fix????
6517 (unless (string-match "\n\\'" txt) (insert "\n"))
6518 (setq end (point))
6519 (goto-char beg)
6520 (skip-chars-forward " \t\n\r")
6521 (setq beg (point))
6522 ;; Shift if necessary
6523 (unless (= shift 0)
6524 (save-restriction
6525 (narrow-to-region beg end)
6526 (while (not (= shift 0))
6527 (org-map-region func (point-min) (point-max))
6528 (setq shift (+ delta shift)))
6529 (goto-char (point-min))))
6530 (when (interactive-p)
6531 (message "Clipboard pasted as level %d subtree" new-level))
6532 (if (and kill-ring
6533 (eq org-subtree-clip (current-kill 0))
6534 org-subtree-clip-folded)
6535 ;; The tree was folded before it was killed/copied
6536 (hide-subtree))))
6538 (defun org-kill-is-subtree-p (&optional txt)
6539 "Check if the current kill is an outline subtree, or a set of trees.
6540 Returns nil if kill does not start with a headline, or if the first
6541 headline level is not the largest headline level in the tree.
6542 So this will actually accept several entries of equal levels as well,
6543 which is OK for `org-paste-subtree'.
6544 If optional TXT is given, check this string instead of the current kill."
6545 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6546 (start-level (and kill
6547 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6548 org-outline-regexp "\\)")
6549 kill)
6550 (- (match-end 2) (match-beginning 2) 1)))
6551 (re (concat "^" org-outline-regexp))
6552 (start (1+ (match-beginning 2))))
6553 (if (not start-level)
6554 (progn
6555 nil) ;; does not even start with a heading
6556 (catch 'exit
6557 (while (setq start (string-match re kill (1+ start)))
6558 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6559 (throw 'exit nil)))
6560 t))))
6562 (defun org-narrow-to-subtree ()
6563 "Narrow buffer to the current subtree."
6564 (interactive)
6565 (save-excursion
6566 (narrow-to-region
6567 (progn (org-back-to-heading) (point))
6568 (progn (org-end-of-subtree t t) (point)))))
6571 ;;; Outline Sorting
6573 (defun org-sort (with-case)
6574 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6575 Optional argument WITH-CASE means sort case-sensitively."
6576 (interactive "P")
6577 (if (org-at-table-p)
6578 (org-call-with-arg 'org-table-sort-lines with-case)
6579 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6581 (defvar org-priority-regexp) ; defined later in the file
6583 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6584 "Sort entries on a certain level of an outline tree.
6585 If there is an active region, the entries in the region are sorted.
6586 Else, if the cursor is before the first entry, sort the top-level items.
6587 Else, the children of the entry at point are sorted.
6589 Sorting can be alphabetically, numerically, and by date/time as given by
6590 the first time stamp in the entry. The command prompts for the sorting
6591 type unless it has been given to the function through the SORTING-TYPE
6592 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6593 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6594 called with point at the beginning of the record. It must return either
6595 a string or a number that should serve as the sorting key for that record.
6597 Comparing entries ignores case by default. However, with an optional argument
6598 WITH-CASE, the sorting considers case as well."
6599 (interactive "P")
6600 (let ((case-func (if with-case 'identity 'downcase))
6601 start beg end stars re re2
6602 txt what tmp plain-list-p)
6603 ;; Find beginning and end of region to sort
6604 (cond
6605 ((org-region-active-p)
6606 ;; we will sort the region
6607 (setq end (region-end)
6608 what "region")
6609 (goto-char (region-beginning))
6610 (if (not (org-on-heading-p)) (outline-next-heading))
6611 (setq start (point)))
6612 ((org-at-item-p)
6613 ;; we will sort this plain list
6614 (org-beginning-of-item-list) (setq start (point))
6615 (org-end-of-item-list) (setq end (point))
6616 (goto-char start)
6617 (setq plain-list-p t
6618 what "plain list"))
6619 ((or (org-on-heading-p)
6620 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6621 ;; we will sort the children of the current headline
6622 (org-back-to-heading)
6623 (setq start (point)
6624 end (progn (org-end-of-subtree t t)
6625 (org-back-over-empty-lines)
6626 (point))
6627 what "children")
6628 (goto-char start)
6629 (show-subtree)
6630 (outline-next-heading))
6632 ;; we will sort the top-level entries in this file
6633 (goto-char (point-min))
6634 (or (org-on-heading-p) (outline-next-heading))
6635 (setq start (point) end (point-max) what "top-level")
6636 (goto-char start)
6637 (show-all)))
6639 (setq beg (point))
6640 (if (>= beg end) (error "Nothing to sort"))
6642 (unless plain-list-p
6643 (looking-at "\\(\\*+\\)")
6644 (setq stars (match-string 1)
6645 re (concat "^" (regexp-quote stars) " +")
6646 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6647 txt (buffer-substring beg end))
6648 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6649 (if (and (not (equal stars "*")) (string-match re2 txt))
6650 (error "Region to sort contains a level above the first entry")))
6652 (unless sorting-type
6653 (message
6654 (if plain-list-p
6655 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6656 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6657 what)
6658 (setq sorting-type (read-char-exclusive))
6660 (and (= (downcase sorting-type) ?f)
6661 (setq getkey-func
6662 (completing-read "Sort using function: "
6663 obarray 'fboundp t nil nil))
6664 (setq getkey-func (intern getkey-func)))
6666 (and (= (downcase sorting-type) ?r)
6667 (setq property
6668 (completing-read "Property: "
6669 (mapcar 'list (org-buffer-property-keys t))
6670 nil t))))
6672 (message "Sorting entries...")
6674 (save-restriction
6675 (narrow-to-region start end)
6677 (let ((dcst (downcase sorting-type))
6678 (now (current-time)))
6679 (sort-subr
6680 (/= dcst sorting-type)
6681 ;; This function moves to the beginning character of the "record" to
6682 ;; be sorted.
6683 (if plain-list-p
6684 (lambda nil
6685 (if (org-at-item-p) t (goto-char (point-max))))
6686 (lambda nil
6687 (if (re-search-forward re nil t)
6688 (goto-char (match-beginning 0))
6689 (goto-char (point-max)))))
6690 ;; This function moves to the last character of the "record" being
6691 ;; sorted.
6692 (if plain-list-p
6693 'org-end-of-item
6694 (lambda nil
6695 (save-match-data
6696 (condition-case nil
6697 (outline-forward-same-level 1)
6698 (error
6699 (goto-char (point-max)))))))
6701 ;; This function returns the value that gets sorted against.
6702 (if plain-list-p
6703 (lambda nil
6704 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6705 (cond
6706 ((= dcst ?n)
6707 (string-to-number (buffer-substring (match-end 0)
6708 (point-at-eol))))
6709 ((= dcst ?a)
6710 (buffer-substring (match-end 0) (point-at-eol)))
6711 ((= dcst ?t)
6712 (if (re-search-forward org-ts-regexp
6713 (point-at-eol) t)
6714 (org-time-string-to-time (match-string 0))
6715 now))
6716 ((= dcst ?f)
6717 (if getkey-func
6718 (progn
6719 (setq tmp (funcall getkey-func))
6720 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6721 tmp)
6722 (error "Invalid key function `%s'" getkey-func)))
6723 (t (error "Invalid sorting type `%c'" sorting-type)))))
6724 (lambda nil
6725 (cond
6726 ((= dcst ?n)
6727 (if (looking-at outline-regexp)
6728 (string-to-number (buffer-substring (match-end 0)
6729 (point-at-eol)))
6730 nil))
6731 ((= dcst ?a)
6732 (funcall case-func (buffer-substring (point-at-bol)
6733 (point-at-eol))))
6734 ((= dcst ?t)
6735 (if (re-search-forward org-ts-regexp
6736 (save-excursion
6737 (forward-line 2)
6738 (point)) t)
6739 (org-time-string-to-time (match-string 0))
6740 now))
6741 ((= dcst ?p)
6742 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6743 (string-to-char (match-string 2))
6744 org-default-priority))
6745 ((= dcst ?r)
6746 (or (org-entry-get nil property) ""))
6747 ((= dcst ?f)
6748 (if getkey-func
6749 (progn
6750 (setq tmp (funcall getkey-func))
6751 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6752 tmp)
6753 (error "Invalid key function `%s'" getkey-func)))
6754 (t (error "Invalid sorting type `%c'" sorting-type)))))
6756 (cond
6757 ((= dcst ?a) 'string<)
6758 ((= dcst ?t) 'time-less-p)
6759 (t nil)))))
6760 (message "Sorting entries...done")))
6762 (defun org-do-sort (table what &optional with-case sorting-type)
6763 "Sort TABLE of WHAT according to SORTING-TYPE.
6764 The user will be prompted for the SORTING-TYPE if the call to this
6765 function does not specify it. WHAT is only for the prompt, to indicate
6766 what is being sorted. The sorting key will be extracted from
6767 the car of the elements of the table.
6768 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6769 (unless sorting-type
6770 (message
6771 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6772 what)
6773 (setq sorting-type (read-char-exclusive)))
6774 (let ((dcst (downcase sorting-type))
6775 extractfun comparefun)
6776 ;; Define the appropriate functions
6777 (cond
6778 ((= dcst ?n)
6779 (setq extractfun 'string-to-number
6780 comparefun (if (= dcst sorting-type) '< '>)))
6781 ((= dcst ?a)
6782 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6783 (lambda(x) (downcase (org-sort-remove-invisible x))))
6784 comparefun (if (= dcst sorting-type)
6785 'string<
6786 (lambda (a b) (and (not (string< a b))
6787 (not (string= a b)))))))
6788 ((= dcst ?t)
6789 (setq extractfun
6790 (lambda (x)
6791 (if (string-match org-ts-regexp x)
6792 (time-to-seconds
6793 (org-time-string-to-time (match-string 0 x)))
6795 comparefun (if (= dcst sorting-type) '< '>)))
6796 (t (error "Invalid sorting type `%c'" sorting-type)))
6798 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6799 table)
6800 (lambda (a b) (funcall comparefun (car a) (car b))))))
6802 ;;;; Plain list items, including checkboxes
6804 ;;; Plain list items
6806 (defun org-at-item-p ()
6807 "Is point in a line starting a hand-formatted item?"
6808 (let ((llt org-plain-list-ordered-item-terminator))
6809 (save-excursion
6810 (goto-char (point-at-bol))
6811 (looking-at
6812 (cond
6813 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6814 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6815 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6816 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6818 (defun org-in-item-p ()
6819 "It the cursor inside a plain list item.
6820 Does not have to be the first line."
6821 (save-excursion
6822 (condition-case nil
6823 (progn
6824 (org-beginning-of-item)
6825 (org-at-item-p)
6827 (error nil))))
6829 (defun org-insert-item (&optional checkbox)
6830 "Insert a new item at the current level.
6831 Return t when things worked, nil when we are not in an item."
6832 (when (save-excursion
6833 (condition-case nil
6834 (progn
6835 (org-beginning-of-item)
6836 (org-at-item-p)
6837 (if (org-invisible-p) (error "Invisible item"))
6839 (error nil)))
6840 (let* ((bul (match-string 0))
6841 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6842 (match-end 0)))
6843 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6844 pos)
6845 (cond
6846 ((and (org-at-item-p) (<= (point) eow))
6847 ;; before the bullet
6848 (beginning-of-line 1)
6849 (open-line (if blank 2 1)))
6850 ((<= (point) eow)
6851 (beginning-of-line 1))
6852 (t (newline (if blank 2 1))))
6853 (insert bul (if checkbox "[ ]" ""))
6854 (just-one-space)
6855 (setq pos (point))
6856 (end-of-line 1)
6857 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6858 (org-maybe-renumber-ordered-list)
6859 (and checkbox (org-update-checkbox-count-maybe))
6862 ;;; Checkboxes
6864 (defun org-at-item-checkbox-p ()
6865 "Is point at a line starting a plain-list item with a checklet?"
6866 (and (org-at-item-p)
6867 (save-excursion
6868 (goto-char (match-end 0))
6869 (skip-chars-forward " \t")
6870 (looking-at "\\[[- X]\\]"))))
6872 (defun org-toggle-checkbox (&optional arg)
6873 "Toggle the checkbox in the current line."
6874 (interactive "P")
6875 (catch 'exit
6876 (let (beg end status (firstnew 'unknown))
6877 (cond
6878 ((org-region-active-p)
6879 (setq beg (region-beginning) end (region-end)))
6880 ((org-on-heading-p)
6881 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6882 ((org-at-item-checkbox-p)
6883 (let ((pos (point)))
6884 (replace-match
6885 (cond (arg "[-]")
6886 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6887 (t "[ ]"))
6888 t t)
6889 (goto-char pos))
6890 (throw 'exit t))
6891 (t (error "Not at a checkbox or heading, and no active region")))
6892 (save-excursion
6893 (goto-char beg)
6894 (while (< (point) end)
6895 (when (org-at-item-checkbox-p)
6896 (setq status (equal (match-string 0) "[X]"))
6897 (when (eq firstnew 'unknown)
6898 (setq firstnew (not status)))
6899 (replace-match
6900 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6901 (beginning-of-line 2)))))
6902 (org-update-checkbox-count-maybe))
6904 (defun org-update-checkbox-count-maybe ()
6905 "Update checkbox statistics unless turned off by user."
6906 (when org-provide-checkbox-statistics
6907 (org-update-checkbox-count)))
6909 (defun org-update-checkbox-count (&optional all)
6910 "Update the checkbox statistics in the current section.
6911 This will find all statistic cookies like [57%] and [6/12] and update them
6912 with the current numbers. With optional prefix argument ALL, do this for
6913 the whole buffer."
6914 (interactive "P")
6915 (save-excursion
6916 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6917 (beg (condition-case nil
6918 (progn (outline-back-to-heading) (point))
6919 (error (point-min))))
6920 (end (move-marker (make-marker)
6921 (progn (outline-next-heading) (point))))
6922 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6923 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6924 b1 e1 f1 c-on c-off lim (cstat 0))
6925 (when all
6926 (goto-char (point-min))
6927 (outline-next-heading)
6928 (setq beg (point) end (point-max)))
6929 (goto-char beg)
6930 (while (re-search-forward re end t)
6931 (setq cstat (1+ cstat)
6932 b1 (match-beginning 0)
6933 e1 (match-end 0)
6934 f1 (match-beginning 1)
6935 lim (cond
6936 ((org-on-heading-p) (outline-next-heading) (point))
6937 ((org-at-item-p) (org-end-of-item) (point))
6938 (t nil))
6939 c-on 0 c-off 0)
6940 (goto-char e1)
6941 (when lim
6942 (while (re-search-forward re-box lim t)
6943 (if (member (match-string 2) '("[ ]" "[-]"))
6944 (setq c-off (1+ c-off))
6945 (setq c-on (1+ c-on))))
6946 ; (delete-region b1 e1)
6947 (goto-char b1)
6948 (insert (if f1
6949 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6950 (format "[%d/%d]" c-on (+ c-on c-off))))
6951 (and (looking-at "\\[.*?\\]")
6952 (replace-match ""))))
6953 (when (interactive-p)
6954 (message "Checkbox satistics updated %s (%d places)"
6955 (if all "in entire file" "in current outline entry") cstat)))))
6957 (defun org-get-checkbox-statistics-face ()
6958 "Select the face for checkbox statistics.
6959 The face will be `org-done' when all relevant boxes are checked. Otherwise
6960 it will be `org-todo'."
6961 (if (match-end 1)
6962 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6963 (if (and (> (match-end 2) (match-beginning 2))
6964 (equal (match-string 2) (match-string 3)))
6965 'org-done
6966 'org-todo)))
6968 (defun org-get-indentation (&optional line)
6969 "Get the indentation of the current line, interpreting tabs.
6970 When LINE is given, assume it represents a line and compute its indentation."
6971 (if line
6972 (if (string-match "^ *" (org-remove-tabs line))
6973 (match-end 0))
6974 (save-excursion
6975 (beginning-of-line 1)
6976 (skip-chars-forward " \t")
6977 (current-column))))
6979 (defun org-remove-tabs (s &optional width)
6980 "Replace tabulators in S with spaces.
6981 Assumes that s is a single line, starting in column 0."
6982 (setq width (or width tab-width))
6983 (while (string-match "\t" s)
6984 (setq s (replace-match
6985 (make-string
6986 (- (* width (/ (+ (match-beginning 0) width) width))
6987 (match-beginning 0)) ?\ )
6988 t t s)))
6991 (defun org-fix-indentation (line ind)
6992 "Fix indentation in LINE.
6993 IND is a cons cell with target and minimum indentation.
6994 If the current indenation in LINE is smaller than the minimum,
6995 leave it alone. If it is larger than ind, set it to the target."
6996 (let* ((l (org-remove-tabs line))
6997 (i (org-get-indentation l))
6998 (i1 (car ind)) (i2 (cdr ind)))
6999 (if (>= i i2) (setq l (substring line i2)))
7000 (if (> i1 0)
7001 (concat (make-string i1 ?\ ) l)
7002 l)))
7004 (defcustom org-empty-line-terminates-plain-lists nil
7005 "Non-nil means, an empty line ends all plain list levels.
7006 When nil, empty lines are part of the preceeding item."
7007 :group 'org-plain-lists
7008 :type 'boolean)
7010 (defun org-beginning-of-item ()
7011 "Go to the beginning of the current hand-formatted item.
7012 If the cursor is not in an item, throw an error."
7013 (interactive)
7014 (let ((pos (point))
7015 (limit (save-excursion
7016 (condition-case nil
7017 (progn
7018 (org-back-to-heading)
7019 (beginning-of-line 2) (point))
7020 (error (point-min)))))
7021 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7022 ind ind1)
7023 (if (org-at-item-p)
7024 (beginning-of-line 1)
7025 (beginning-of-line 1)
7026 (skip-chars-forward " \t")
7027 (setq ind (current-column))
7028 (if (catch 'exit
7029 (while t
7030 (beginning-of-line 0)
7031 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7033 (if (looking-at "[ \t]*$")
7034 (setq ind1 ind-empty)
7035 (skip-chars-forward " \t")
7036 (setq ind1 (current-column)))
7037 (if (< ind1 ind)
7038 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7040 (goto-char pos)
7041 (error "Not in an item")))))
7043 (defun org-end-of-item ()
7044 "Go to the end of the current hand-formatted item.
7045 If the cursor is not in an item, throw an error."
7046 (interactive)
7047 (let* ((pos (point))
7048 ind1
7049 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7050 (limit (save-excursion (outline-next-heading) (point)))
7051 (ind (save-excursion
7052 (org-beginning-of-item)
7053 (skip-chars-forward " \t")
7054 (current-column)))
7055 (end (catch 'exit
7056 (while t
7057 (beginning-of-line 2)
7058 (if (eobp) (throw 'exit (point)))
7059 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7060 (if (looking-at "[ \t]*$")
7061 (setq ind1 ind-empty)
7062 (skip-chars-forward " \t")
7063 (setq ind1 (current-column)))
7064 (if (<= ind1 ind)
7065 (throw 'exit (point-at-bol)))))))
7066 (if end
7067 (goto-char end)
7068 (goto-char pos)
7069 (error "Not in an item"))))
7071 (defun org-next-item ()
7072 "Move to the beginning of the next item in the current plain list.
7073 Error if not at a plain list, or if this is the last item in the list."
7074 (interactive)
7075 (let (ind ind1 (pos (point)))
7076 (org-beginning-of-item)
7077 (setq ind (org-get-indentation))
7078 (org-end-of-item)
7079 (setq ind1 (org-get-indentation))
7080 (unless (and (org-at-item-p) (= ind ind1))
7081 (goto-char pos)
7082 (error "On last item"))))
7084 (defun org-previous-item ()
7085 "Move to the beginning of the previous item in the current plain list.
7086 Error if not at a plain list, or if this is the first item in the list."
7087 (interactive)
7088 (let (beg ind ind1 (pos (point)))
7089 (org-beginning-of-item)
7090 (setq beg (point))
7091 (setq ind (org-get-indentation))
7092 (goto-char beg)
7093 (catch 'exit
7094 (while t
7095 (beginning-of-line 0)
7096 (if (looking-at "[ \t]*$")
7098 (if (<= (setq ind1 (org-get-indentation)) ind)
7099 (throw 'exit t)))))
7100 (condition-case nil
7101 (if (or (not (org-at-item-p))
7102 (< ind1 (1- ind)))
7103 (error "")
7104 (org-beginning-of-item))
7105 (error (goto-char pos)
7106 (error "On first item")))))
7108 (defun org-first-list-item-p ()
7109 "Is this heading the item in a plain list?"
7110 (unless (org-at-item-p)
7111 (error "Not at a plain list item"))
7112 (org-beginning-of-item)
7113 (= (point) (save-excursion (org-beginning-of-item-list))))
7115 (defun org-move-item-down ()
7116 "Move the plain list item at point down, i.e. swap with following item.
7117 Subitems (items with larger indentation) are considered part of the item,
7118 so this really moves item trees."
7119 (interactive)
7120 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7121 (org-beginning-of-item)
7122 (setq beg0 (point))
7123 (save-excursion
7124 (setq ne-beg (org-back-over-empty-lines))
7125 (setq beg (point)))
7126 (goto-char beg0)
7127 (setq ind (org-get-indentation))
7128 (org-end-of-item)
7129 (setq end0 (point))
7130 (setq ind1 (org-get-indentation))
7131 (setq ne-end (org-back-over-empty-lines))
7132 (setq end (point))
7133 (goto-char beg0)
7134 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7135 ;; include less whitespace
7136 (save-excursion
7137 (goto-char beg)
7138 (forward-line (- ne-beg ne-end))
7139 (setq beg (point))))
7140 (goto-char end0)
7141 (if (and (org-at-item-p) (= ind ind1))
7142 (progn
7143 (org-end-of-item)
7144 (org-back-over-empty-lines)
7145 (setq txt (buffer-substring beg end))
7146 (save-excursion
7147 (delete-region beg end))
7148 (setq pos (point))
7149 (insert txt)
7150 (goto-char pos) (org-skip-whitespace)
7151 (org-maybe-renumber-ordered-list))
7152 (goto-char pos)
7153 (error "Cannot move this item further down"))))
7155 (defun org-move-item-up (arg)
7156 "Move the plain list item at point up, i.e. swap with previous item.
7157 Subitems (items with larger indentation) are considered part of the item,
7158 so this really moves item trees."
7159 (interactive "p")
7160 (let (beg beg0 end end0 ind ind1 (pos (point)) txt
7161 ne-beg ne-end ne-ins ins-end)
7162 (org-beginning-of-item)
7163 (setq beg0 (point))
7164 (setq ind (org-get-indentation))
7165 (save-excursion
7166 (setq ne-beg (org-back-over-empty-lines))
7167 (setq beg (point)))
7168 (goto-char beg0)
7169 (org-end-of-item)
7170 (setq ne-end (org-back-over-empty-lines))
7171 (setq end (point))
7172 (goto-char beg0)
7173 (catch 'exit
7174 (while t
7175 (beginning-of-line 0)
7176 (if (looking-at "[ \t]*$")
7177 (if org-empty-line-terminates-plain-lists
7178 (progn
7179 (goto-char pos)
7180 (error "Cannot move this item further up"))
7181 nil)
7182 (if (<= (setq ind1 (org-get-indentation)) ind)
7183 (throw 'exit t)))))
7184 (condition-case nil
7185 (org-beginning-of-item)
7186 (error (goto-char beg)
7187 (error "Cannot move this item further up")))
7188 (setq ind1 (org-get-indentation))
7189 (if (and (org-at-item-p) (= ind ind1))
7190 (progn
7191 (setq ne-ins (org-back-over-empty-lines))
7192 (setq txt (buffer-substring beg end))
7193 (save-excursion
7194 (delete-region beg end))
7195 (setq pos (point))
7196 (insert txt)
7197 (setq ins-end (point))
7198 (goto-char pos) (org-skip-whitespace)
7200 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7201 ;; Move whitespace back to beginning
7202 (save-excursion
7203 (goto-char ins-end)
7204 (let ((kill-whole-line t))
7205 (kill-line (- ne-ins ne-beg)) (point)))
7206 (insert (make-string (- ne-ins ne-beg) ?\n)))
7208 (org-maybe-renumber-ordered-list))
7209 (goto-char pos)
7210 (error "Cannot move this item further up"))))
7212 (defun org-maybe-renumber-ordered-list ()
7213 "Renumber the ordered list at point if setup allows it.
7214 This tests the user option `org-auto-renumber-ordered-lists' before
7215 doing the renumbering."
7216 (interactive)
7217 (when (and org-auto-renumber-ordered-lists
7218 (org-at-item-p))
7219 (if (match-beginning 3)
7220 (org-renumber-ordered-list 1)
7221 (org-fix-bullet-type))))
7223 (defun org-maybe-renumber-ordered-list-safe ()
7224 (condition-case nil
7225 (save-excursion
7226 (org-maybe-renumber-ordered-list))
7227 (error nil)))
7229 (defun org-cycle-list-bullet (&optional which)
7230 "Cycle through the different itemize/enumerate bullets.
7231 This cycle the entire list level through the sequence:
7233 `-' -> `+' -> `*' -> `1.' -> `1)'
7235 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7236 0 meand `-', 1 means `+' etc."
7237 (interactive "P")
7238 (org-preserve-lc
7239 (org-beginning-of-item-list)
7240 (org-at-item-p)
7241 (beginning-of-line 1)
7242 (let ((current (match-string 0))
7243 (prevp (eq which 'previous))
7244 new)
7245 (setq new (cond
7246 ((and (numberp which)
7247 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7248 ((string-match "-" current) (if prevp "1)" "+"))
7249 ((string-match "\\+" current)
7250 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7251 ((string-match "\\*" current) (if prevp "+" "1."))
7252 ((string-match "\\." current) (if prevp "*" "1)"))
7253 ((string-match ")" current) (if prevp "1." "-"))
7254 (t (error "This should not happen"))))
7255 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7256 (org-fix-bullet-type)
7257 (org-maybe-renumber-ordered-list))))
7259 (defun org-get-string-indentation (s)
7260 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7261 (let ((n -1) (i 0) (w tab-width) c)
7262 (catch 'exit
7263 (while (< (setq n (1+ n)) (length s))
7264 (setq c (aref s n))
7265 (cond ((= c ?\ ) (setq i (1+ i)))
7266 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7267 (t (throw 'exit t)))))
7270 (defun org-renumber-ordered-list (arg)
7271 "Renumber an ordered plain list.
7272 Cursor needs to be in the first line of an item, the line that starts
7273 with something like \"1.\" or \"2)\"."
7274 (interactive "p")
7275 (unless (and (org-at-item-p)
7276 (match-beginning 3))
7277 (error "This is not an ordered list"))
7278 (let ((line (org-current-line))
7279 (col (current-column))
7280 (ind (org-get-string-indentation
7281 (buffer-substring (point-at-bol) (match-beginning 3))))
7282 ;; (term (substring (match-string 3) -1))
7283 ind1 (n (1- arg))
7284 fmt)
7285 ;; find where this list begins
7286 (org-beginning-of-item-list)
7287 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7288 (setq fmt (concat "%d" (match-string 1)))
7289 (beginning-of-line 0)
7290 ;; walk forward and replace these numbers
7291 (catch 'exit
7292 (while t
7293 (catch 'next
7294 (beginning-of-line 2)
7295 (if (eobp) (throw 'exit nil))
7296 (if (looking-at "[ \t]*$") (throw 'next nil))
7297 (skip-chars-forward " \t") (setq ind1 (current-column))
7298 (if (> ind1 ind) (throw 'next t))
7299 (if (< ind1 ind) (throw 'exit t))
7300 (if (not (org-at-item-p)) (throw 'exit nil))
7301 (delete-region (match-beginning 2) (match-end 2))
7302 (goto-char (match-beginning 2))
7303 (insert (format fmt (setq n (1+ n)))))))
7304 (goto-line line)
7305 (move-to-column col)))
7307 (defun org-fix-bullet-type ()
7308 "Make sure all items in this list have the same bullet as the firsst item."
7309 (interactive)
7310 (unless (org-at-item-p) (error "This is not a list"))
7311 (let ((line (org-current-line))
7312 (col (current-column))
7313 (ind (current-indentation))
7314 ind1 bullet)
7315 ;; find where this list begins
7316 (org-beginning-of-item-list)
7317 (beginning-of-line 1)
7318 ;; find out what the bullet type is
7319 (looking-at "[ \t]*\\(\\S-+\\)")
7320 (setq bullet (match-string 1))
7321 ;; walk forward and replace these numbers
7322 (beginning-of-line 0)
7323 (catch 'exit
7324 (while t
7325 (catch 'next
7326 (beginning-of-line 2)
7327 (if (eobp) (throw 'exit nil))
7328 (if (looking-at "[ \t]*$") (throw 'next nil))
7329 (skip-chars-forward " \t") (setq ind1 (current-column))
7330 (if (> ind1 ind) (throw 'next t))
7331 (if (< ind1 ind) (throw 'exit t))
7332 (if (not (org-at-item-p)) (throw 'exit nil))
7333 (skip-chars-forward " \t")
7334 (looking-at "\\S-+")
7335 (replace-match bullet))))
7336 (goto-line line)
7337 (move-to-column col)
7338 (if (string-match "[0-9]" bullet)
7339 (org-renumber-ordered-list 1))))
7341 (defun org-beginning-of-item-list ()
7342 "Go to the beginning of the current item list.
7343 I.e. to the first item in this list."
7344 (interactive)
7345 (org-beginning-of-item)
7346 (let ((pos (point-at-bol))
7347 (ind (org-get-indentation))
7348 ind1)
7349 ;; find where this list begins
7350 (catch 'exit
7351 (while t
7352 (catch 'next
7353 (beginning-of-line 0)
7354 (if (looking-at "[ \t]*$")
7355 (throw (if (bobp) 'exit 'next) t))
7356 (skip-chars-forward " \t") (setq ind1 (current-column))
7357 (if (or (< ind1 ind)
7358 (and (= ind1 ind)
7359 (not (org-at-item-p)))
7360 (bobp))
7361 (throw 'exit t)
7362 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7363 (goto-char pos)))
7366 (defun org-end-of-item-list ()
7367 "Go to the end of the current item list.
7368 I.e. to the text after the last item."
7369 (interactive)
7370 (org-beginning-of-item)
7371 (let ((pos (point-at-bol))
7372 (ind (org-get-indentation))
7373 ind1)
7374 ;; find where this list begins
7375 (catch 'exit
7376 (while t
7377 (catch 'next
7378 (beginning-of-line 2)
7379 (if (looking-at "[ \t]*$")
7380 (throw (if (eobp) 'exit 'next) t))
7381 (skip-chars-forward " \t") (setq ind1 (current-column))
7382 (if (or (< ind1 ind)
7383 (and (= ind1 ind)
7384 (not (org-at-item-p)))
7385 (eobp))
7386 (progn
7387 (setq pos (point-at-bol))
7388 (throw 'exit t))))))
7389 (goto-char pos)))
7392 (defvar org-last-indent-begin-marker (make-marker))
7393 (defvar org-last-indent-end-marker (make-marker))
7395 (defun org-outdent-item (arg)
7396 "Outdent a local list item."
7397 (interactive "p")
7398 (org-indent-item (- arg)))
7400 (defun org-indent-item (arg)
7401 "Indent a local list item."
7402 (interactive "p")
7403 (unless (org-at-item-p)
7404 (error "Not on an item"))
7405 (save-excursion
7406 (let (beg end ind ind1 tmp delta ind-down ind-up)
7407 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7408 (setq beg org-last-indent-begin-marker
7409 end org-last-indent-end-marker)
7410 (org-beginning-of-item)
7411 (setq beg (move-marker org-last-indent-begin-marker (point)))
7412 (org-end-of-item)
7413 (setq end (move-marker org-last-indent-end-marker (point))))
7414 (goto-char beg)
7415 (setq tmp (org-item-indent-positions)
7416 ind (car tmp)
7417 ind-down (nth 2 tmp)
7418 ind-up (nth 1 tmp)
7419 delta (if (> arg 0)
7420 (if ind-down (- ind-down ind) 2)
7421 (if ind-up (- ind-up ind) -2)))
7422 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7423 (while (< (point) end)
7424 (beginning-of-line 1)
7425 (skip-chars-forward " \t") (setq ind1 (current-column))
7426 (delete-region (point-at-bol) (point))
7427 (or (eolp) (indent-to-column (+ ind1 delta)))
7428 (beginning-of-line 2))))
7429 (org-fix-bullet-type)
7430 (org-maybe-renumber-ordered-list-safe)
7431 (save-excursion
7432 (beginning-of-line 0)
7433 (condition-case nil (org-beginning-of-item) (error nil))
7434 (org-maybe-renumber-ordered-list-safe)))
7436 (defun org-item-indent-positions ()
7437 "Return indentation for plain list items.
7438 This returns a list with three values: The current indentation, the
7439 parent indentation and the indentation a child should habe.
7440 Assumes cursor in item line."
7441 (let* ((bolpos (point-at-bol))
7442 (ind (org-get-indentation))
7443 ind-down ind-up pos)
7444 (save-excursion
7445 (org-beginning-of-item-list)
7446 (skip-chars-backward "\n\r \t")
7447 (when (org-in-item-p)
7448 (org-beginning-of-item)
7449 (setq ind-up (org-get-indentation))))
7450 (setq pos (point))
7451 (save-excursion
7452 (cond
7453 ((and (condition-case nil (progn (org-previous-item) t)
7454 (error nil))
7455 (or (forward-char 1) t)
7456 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7457 (setq ind-down (org-get-indentation)))
7458 ((and (goto-char pos)
7459 (org-at-item-p))
7460 (goto-char (match-end 0))
7461 (skip-chars-forward " \t")
7462 (setq ind-down (current-column)))))
7463 (list ind ind-up ind-down)))
7465 ;;; The orgstruct minor mode
7467 ;; Define a minor mode which can be used in other modes in order to
7468 ;; integrate the org-mode structure editing commands.
7470 ;; This is really a hack, because the org-mode structure commands use
7471 ;; keys which normally belong to the major mode. Here is how it
7472 ;; works: The minor mode defines all the keys necessary to operate the
7473 ;; structure commands, but wraps the commands into a function which
7474 ;; tests if the cursor is currently at a headline or a plain list
7475 ;; item. If that is the case, the structure command is used,
7476 ;; temporarily setting many Org-mode variables like regular
7477 ;; expressions for filling etc. However, when any of those keys is
7478 ;; used at a different location, function uses `key-binding' to look
7479 ;; up if the key has an associated command in another currently active
7480 ;; keymap (minor modes, major mode, global), and executes that
7481 ;; command. There might be problems if any of the keys is otherwise
7482 ;; used as a prefix key.
7484 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7485 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7486 ;; addresses this by checking explicitly for both bindings.
7488 (defvar orgstruct-mode-map (make-sparse-keymap)
7489 "Keymap for the minor `orgstruct-mode'.")
7491 (defvar org-local-vars nil
7492 "List of local variables, for use by `orgstruct-mode'")
7494 ;;;###autoload
7495 (define-minor-mode orgstruct-mode
7496 "Toggle the minor more `orgstruct-mode'.
7497 This mode is for using Org-mode structure commands in other modes.
7498 The following key behave as if Org-mode was active, if the cursor
7499 is on a headline, or on a plain list item (both in the definition
7500 of Org-mode).
7502 M-up Move entry/item up
7503 M-down Move entry/item down
7504 M-left Promote
7505 M-right Demote
7506 M-S-up Move entry/item up
7507 M-S-down Move entry/item down
7508 M-S-left Promote subtree
7509 M-S-right Demote subtree
7510 M-q Fill paragraph and items like in Org-mode
7511 C-c ^ Sort entries
7512 C-c - Cycle list bullet
7513 TAB Cycle item visibility
7514 M-RET Insert new heading/item
7515 S-M-RET Insert new TODO heading / Chekbox item
7516 C-c C-c Set tags / toggle checkbox"
7517 nil " OrgStruct" nil
7518 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7520 ;;;###autoload
7521 (defun turn-on-orgstruct ()
7522 "Unconditionally turn on `orgstruct-mode'."
7523 (orgstruct-mode 1))
7525 ;;;###autoload
7526 (defun turn-on-orgstruct++ ()
7527 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7528 In addition to setting orgstruct-mode, this also exports all indentation and
7529 autofilling variables from org-mode into the buffer. Note that turning
7530 off orgstruct-mode will *not* remove these additonal settings."
7531 (orgstruct-mode 1)
7532 (let (var val)
7533 (mapc
7534 (lambda (x)
7535 (when (string-match
7536 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7537 (symbol-name (car x)))
7538 (setq var (car x) val (nth 1 x))
7539 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7540 org-local-vars)))
7542 (defun orgstruct-error ()
7543 "Error when there is no default binding for a structure key."
7544 (interactive)
7545 (error "This key has no function outside structure elements"))
7547 (defun orgstruct-setup ()
7548 "Setup orgstruct keymaps."
7549 (let ((nfunc 0)
7550 (bindings
7551 (list
7552 '([(meta up)] org-metaup)
7553 '([(meta down)] org-metadown)
7554 '([(meta left)] org-metaleft)
7555 '([(meta right)] org-metaright)
7556 '([(meta shift up)] org-shiftmetaup)
7557 '([(meta shift down)] org-shiftmetadown)
7558 '([(meta shift left)] org-shiftmetaleft)
7559 '([(meta shift right)] org-shiftmetaright)
7560 '([(shift up)] org-shiftup)
7561 '([(shift down)] org-shiftdown)
7562 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7563 '("\M-q" fill-paragraph)
7564 '("\C-c^" org-sort)
7565 '("\C-c-" org-cycle-list-bullet)))
7566 elt key fun cmd)
7567 (while (setq elt (pop bindings))
7568 (setq nfunc (1+ nfunc))
7569 (setq key (org-key (car elt))
7570 fun (nth 1 elt)
7571 cmd (orgstruct-make-binding fun nfunc key))
7572 (org-defkey orgstruct-mode-map key cmd))
7574 ;; Special treatment needed for TAB and RET
7575 (org-defkey orgstruct-mode-map [(tab)]
7576 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7577 (org-defkey orgstruct-mode-map "\C-i"
7578 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7580 (org-defkey orgstruct-mode-map "\M-\C-m"
7581 (orgstruct-make-binding 'org-insert-heading 105
7582 "\M-\C-m" [(meta return)]))
7583 (org-defkey orgstruct-mode-map [(meta return)]
7584 (orgstruct-make-binding 'org-insert-heading 106
7585 [(meta return)] "\M-\C-m"))
7587 (org-defkey orgstruct-mode-map [(shift meta return)]
7588 (orgstruct-make-binding 'org-insert-todo-heading 107
7589 [(meta return)] "\M-\C-m"))
7591 (unless org-local-vars
7592 (setq org-local-vars (org-get-local-variables)))
7596 (defun orgstruct-make-binding (fun n &rest keys)
7597 "Create a function for binding in the structure minor mode.
7598 FUN is the command to call inside a table. N is used to create a unique
7599 command name. KEYS are keys that should be checked in for a command
7600 to execute outside of tables."
7601 (eval
7602 (list 'defun
7603 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7604 '(arg)
7605 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7606 "Outside of structure, run the binding of `"
7607 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7608 "'.")
7609 '(interactive "p")
7610 (list 'if
7611 '(org-context-p 'headline 'item)
7612 (list 'org-run-like-in-org-mode (list 'quote fun))
7613 (list 'let '(orgstruct-mode)
7614 (list 'call-interactively
7615 (append '(or)
7616 (mapcar (lambda (k)
7617 (list 'key-binding k))
7618 keys)
7619 '('orgstruct-error))))))))
7621 (defun org-context-p (&rest contexts)
7622 "Check if local context is and of CONTEXTS.
7623 Possible values in the list of contexts are `table', `headline', and `item'."
7624 (let ((pos (point)))
7625 (goto-char (point-at-bol))
7626 (prog1 (or (and (memq 'table contexts)
7627 (looking-at "[ \t]*|"))
7628 (and (memq 'headline contexts)
7629 (looking-at "\\*+"))
7630 (and (memq 'item contexts)
7631 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7632 (goto-char pos))))
7634 (defun org-get-local-variables ()
7635 "Return a list of all local variables in an org-mode buffer."
7636 (let (varlist)
7637 (with-current-buffer (get-buffer-create "*Org tmp*")
7638 (erase-buffer)
7639 (org-mode)
7640 (setq varlist (buffer-local-variables)))
7641 (kill-buffer "*Org tmp*")
7642 (delq nil
7643 (mapcar
7644 (lambda (x)
7645 (setq x
7646 (if (symbolp x)
7647 (list x)
7648 (list (car x) (list 'quote (cdr x)))))
7649 (if (string-match
7650 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7651 (symbol-name (car x)))
7652 x nil))
7653 varlist))))
7655 ;;;###autoload
7656 (defun org-run-like-in-org-mode (cmd)
7657 (unless org-local-vars
7658 (setq org-local-vars (org-get-local-variables)))
7659 (eval (list 'let org-local-vars
7660 (list 'call-interactively (list 'quote cmd)))))
7662 ;;;; Archiving
7664 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7666 (defun org-archive-subtree (&optional find-done)
7667 "Move the current subtree to the archive.
7668 The archive can be a certain top-level heading in the current file, or in
7669 a different file. The tree will be moved to that location, the subtree
7670 heading be marked DONE, and the current time will be added.
7672 When called with prefix argument FIND-DONE, find whole trees without any
7673 open TODO items and archive them (after getting confirmation from the user).
7674 If the cursor is not at a headline when this comand is called, try all level
7675 1 trees. If the cursor is on a headline, only try the direct children of
7676 this heading."
7677 (interactive "P")
7678 (if find-done
7679 (org-archive-all-done)
7680 ;; Save all relevant TODO keyword-relatex variables
7682 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7683 (tr-org-todo-keywords-1 org-todo-keywords-1)
7684 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7685 (tr-org-done-keywords org-done-keywords)
7686 (tr-org-todo-regexp org-todo-regexp)
7687 (tr-org-todo-line-regexp org-todo-line-regexp)
7688 (tr-org-odd-levels-only org-odd-levels-only)
7689 (this-buffer (current-buffer))
7690 (org-archive-location org-archive-location)
7691 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7692 ;; start of variables that will be used for saving context
7693 ;; The compiler complains about them - keep them anyway!
7694 (file (abbreviate-file-name (buffer-file-name)))
7695 (time (format-time-string
7696 (substring (cdr org-time-stamp-formats) 1 -1)
7697 (current-time)))
7698 afile heading buffer level newfile-p
7699 category todo priority
7700 ;; start of variables that will be used for savind context
7701 ltags itags prop)
7703 ;; Try to find a local archive location
7704 (save-excursion
7705 (save-restriction
7706 (widen)
7707 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7708 (if (and prop (string-match "\\S-" prop))
7709 (setq org-archive-location prop)
7710 (if (or (re-search-backward re nil t)
7711 (re-search-forward re nil t))
7712 (setq org-archive-location (match-string 1))))))
7714 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7715 (progn
7716 (setq afile (format (match-string 1 org-archive-location)
7717 (file-name-nondirectory buffer-file-name))
7718 heading (match-string 2 org-archive-location)))
7719 (error "Invalid `org-archive-location'"))
7720 (if (> (length afile) 0)
7721 (setq newfile-p (not (file-exists-p afile))
7722 buffer (find-file-noselect afile))
7723 (setq buffer (current-buffer)))
7724 (unless buffer
7725 (error "Cannot access file \"%s\"" afile))
7726 (if (and (> (length heading) 0)
7727 (string-match "^\\*+" heading))
7728 (setq level (match-end 0))
7729 (setq heading nil level 0))
7730 (save-excursion
7731 (org-back-to-heading t)
7732 ;; Get context information that will be lost by moving the tree
7733 (org-refresh-category-properties)
7734 (setq category (org-get-category)
7735 todo (and (looking-at org-todo-line-regexp)
7736 (match-string 2))
7737 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7738 ltags (org-get-tags)
7739 itags (org-delete-all ltags (org-get-tags-at)))
7740 (setq ltags (mapconcat 'identity ltags " ")
7741 itags (mapconcat 'identity itags " "))
7742 ;; We first only copy, in case something goes wrong
7743 ;; we need to protect this-command, to avoid kill-region sets it,
7744 ;; which would lead to duplication of subtrees
7745 (let (this-command) (org-copy-subtree))
7746 (set-buffer buffer)
7747 ;; Enforce org-mode for the archive buffer
7748 (if (not (org-mode-p))
7749 ;; Force the mode for future visits.
7750 (let ((org-insert-mode-line-in-empty-file t)
7751 (org-inhibit-startup t))
7752 (call-interactively 'org-mode)))
7753 (when newfile-p
7754 (goto-char (point-max))
7755 (insert (format "\nArchived entries from file %s\n\n"
7756 (buffer-file-name this-buffer))))
7757 ;; Force the TODO keywords of the original buffer
7758 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7759 (org-todo-keywords-1 tr-org-todo-keywords-1)
7760 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7761 (org-done-keywords tr-org-done-keywords)
7762 (org-todo-regexp tr-org-todo-regexp)
7763 (org-todo-line-regexp tr-org-todo-line-regexp)
7764 (org-odd-levels-only
7765 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7766 org-odd-levels-only
7767 tr-org-odd-levels-only)))
7768 (goto-char (point-min))
7769 (if heading
7770 (progn
7771 (if (re-search-forward
7772 (concat "^" (regexp-quote heading)
7773 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7774 nil t)
7775 (goto-char (match-end 0))
7776 ;; Heading not found, just insert it at the end
7777 (goto-char (point-max))
7778 (or (bolp) (insert "\n"))
7779 (insert "\n" heading "\n")
7780 (end-of-line 0))
7781 ;; Make the subtree visible
7782 (show-subtree)
7783 (org-end-of-subtree t)
7784 (skip-chars-backward " \t\r\n")
7785 (and (looking-at "[ \t\r\n]*")
7786 (replace-match "\n\n")))
7787 ;; No specific heading, just go to end of file.
7788 (goto-char (point-max)) (insert "\n"))
7789 ;; Paste
7790 (org-paste-subtree (org-get-legal-level level 1))
7792 ;; Mark the entry as done
7793 (when (and org-archive-mark-done
7794 (looking-at org-todo-line-regexp)
7795 (or (not (match-end 2))
7796 (not (member (match-string 2) org-done-keywords))))
7797 (let (org-log-done)
7798 (org-todo
7799 (car (or (member org-archive-mark-done org-done-keywords)
7800 org-done-keywords)))))
7802 ;; Add the context info
7803 (when org-archive-save-context-info
7804 (let ((l org-archive-save-context-info) e n v)
7805 (while (setq e (pop l))
7806 (when (and (setq v (symbol-value e))
7807 (stringp v) (string-match "\\S-" v))
7808 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7809 (org-entry-put (point) n v)))))
7811 ;; Save the buffer, if it is not the same buffer.
7812 (if (not (eq this-buffer buffer)) (save-buffer))))
7813 ;; Here we are back in the original buffer. Everything seems to have
7814 ;; worked. So now cut the tree and finish up.
7815 (let (this-command) (org-cut-subtree))
7816 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7817 (message "Subtree archived %s"
7818 (if (eq this-buffer buffer)
7819 (concat "under heading: " heading)
7820 (concat "in file: " (abbreviate-file-name afile)))))))
7822 (defun org-refresh-category-properties ()
7823 "Refresh category text properties in teh buffer."
7824 (let ((def-cat (cond
7825 ((null org-category)
7826 (if buffer-file-name
7827 (file-name-sans-extension
7828 (file-name-nondirectory buffer-file-name))
7829 "???"))
7830 ((symbolp org-category) (symbol-name org-category))
7831 (t org-category)))
7832 beg end cat pos optionp)
7833 (org-unmodified
7834 (save-excursion
7835 (save-restriction
7836 (widen)
7837 (goto-char (point-min))
7838 (put-text-property (point) (point-max) 'org-category def-cat)
7839 (while (re-search-forward
7840 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7841 (setq pos (match-end 0)
7842 optionp (equal (char-after (match-beginning 0)) ?#)
7843 cat (org-trim (match-string 2)))
7844 (if optionp
7845 (setq beg (point-at-bol) end (point-max))
7846 (org-back-to-heading t)
7847 (setq beg (point) end (org-end-of-subtree t t)))
7848 (put-text-property beg end 'org-category cat)
7849 (goto-char pos)))))))
7851 (defun org-archive-all-done (&optional tag)
7852 "Archive sublevels of the current tree without open TODO items.
7853 If the cursor is not on a headline, try all level 1 trees. If
7854 it is on a headline, try all direct children.
7855 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7856 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7857 (rea (concat ".*:" org-archive-tag ":"))
7858 (begm (make-marker))
7859 (endm (make-marker))
7860 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7861 "Move subtree to archive (no open TODO items)? "))
7862 beg end (cntarch 0))
7863 (if (org-on-heading-p)
7864 (progn
7865 (setq re1 (concat "^" (regexp-quote
7866 (make-string
7867 (1+ (- (match-end 0) (match-beginning 0)))
7868 ?*))
7869 " "))
7870 (move-marker begm (point))
7871 (move-marker endm (org-end-of-subtree t)))
7872 (setq re1 "^* ")
7873 (move-marker begm (point-min))
7874 (move-marker endm (point-max)))
7875 (save-excursion
7876 (goto-char begm)
7877 (while (re-search-forward re1 endm t)
7878 (setq beg (match-beginning 0)
7879 end (save-excursion (org-end-of-subtree t) (point)))
7880 (goto-char beg)
7881 (if (re-search-forward re end t)
7882 (goto-char end)
7883 (goto-char beg)
7884 (if (and (or (not tag) (not (looking-at rea)))
7885 (y-or-n-p question))
7886 (progn
7887 (if tag
7888 (org-toggle-tag org-archive-tag 'on)
7889 (org-archive-subtree))
7890 (setq cntarch (1+ cntarch)))
7891 (goto-char end)))))
7892 (message "%d trees archived" cntarch)))
7894 (defun org-cycle-hide-drawers (state)
7895 "Re-hide all drawers after a visibility state change."
7896 (when (and (org-mode-p)
7897 (not (memq state '(overview folded))))
7898 (save-excursion
7899 (let* ((globalp (memq state '(contents all)))
7900 (beg (if globalp (point-min) (point)))
7901 (end (if globalp (point-max) (org-end-of-subtree t))))
7902 (goto-char beg)
7903 (while (re-search-forward org-drawer-regexp end t)
7904 (org-flag-drawer t))))))
7906 (defun org-flag-drawer (flag)
7907 (save-excursion
7908 (beginning-of-line 1)
7909 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7910 (let ((b (match-end 0))
7911 (outline-regexp org-outline-regexp))
7912 (if (re-search-forward
7913 "^[ \t]*:END:"
7914 (save-excursion (outline-next-heading) (point)) t)
7915 (outline-flag-region b (point-at-eol) flag)
7916 (error ":END: line missing"))))))
7918 (defun org-cycle-hide-archived-subtrees (state)
7919 "Re-hide all archived subtrees after a visibility state change."
7920 (when (and (not org-cycle-open-archived-trees)
7921 (not (memq state '(overview folded))))
7922 (save-excursion
7923 (let* ((globalp (memq state '(contents all)))
7924 (beg (if globalp (point-min) (point)))
7925 (end (if globalp (point-max) (org-end-of-subtree t))))
7926 (org-hide-archived-subtrees beg end)
7927 (goto-char beg)
7928 (if (looking-at (concat ".*:" org-archive-tag ":"))
7929 (message "%s" (substitute-command-keys
7930 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7932 (defun org-force-cycle-archived ()
7933 "Cycle subtree even if it is archived."
7934 (interactive)
7935 (setq this-command 'org-cycle)
7936 (let ((org-cycle-open-archived-trees t))
7937 (call-interactively 'org-cycle)))
7939 (defun org-hide-archived-subtrees (beg end)
7940 "Re-hide all archived subtrees after a visibility state change."
7941 (save-excursion
7942 (let* ((re (concat ":" org-archive-tag ":")))
7943 (goto-char beg)
7944 (while (re-search-forward re end t)
7945 (and (org-on-heading-p) (hide-subtree))
7946 (org-end-of-subtree t)))))
7948 (defun org-toggle-tag (tag &optional onoff)
7949 "Toggle the tag TAG for the current line.
7950 If ONOFF is `on' or `off', don't toggle but set to this state."
7951 (unless (org-on-heading-p t) (error "Not on headling"))
7952 (let (res current)
7953 (save-excursion
7954 (beginning-of-line)
7955 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7956 (point-at-eol) t)
7957 (progn
7958 (setq current (match-string 1))
7959 (replace-match ""))
7960 (setq current ""))
7961 (setq current (nreverse (org-split-string current ":")))
7962 (cond
7963 ((eq onoff 'on)
7964 (setq res t)
7965 (or (member tag current) (push tag current)))
7966 ((eq onoff 'off)
7967 (or (not (member tag current)) (setq current (delete tag current))))
7968 (t (if (member tag current)
7969 (setq current (delete tag current))
7970 (setq res t)
7971 (push tag current))))
7972 (end-of-line 1)
7973 (if current
7974 (progn
7975 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7976 (org-set-tags nil t))
7977 (delete-horizontal-space))
7978 (run-hooks 'org-after-tags-change-hook))
7979 res))
7981 (defun org-toggle-archive-tag (&optional arg)
7982 "Toggle the archive tag for the current headline.
7983 With prefix ARG, check all children of current headline and offer tagging
7984 the children that do not contain any open TODO items."
7985 (interactive "P")
7986 (if arg
7987 (org-archive-all-done 'tag)
7988 (let (set)
7989 (save-excursion
7990 (org-back-to-heading t)
7991 (setq set (org-toggle-tag org-archive-tag))
7992 (when set (hide-subtree)))
7993 (and set (beginning-of-line 1))
7994 (message "Subtree %s" (if set "archived" "unarchived")))))
7997 ;;;; Tables
7999 ;;; The table editor
8001 ;; Watch out: Here we are talking about two different kind of tables.
8002 ;; Most of the code is for the tables created with the Org-mode table editor.
8003 ;; Sometimes, we talk about tables created and edited with the table.el
8004 ;; Emacs package. We call the former org-type tables, and the latter
8005 ;; table.el-type tables.
8007 (defun org-before-change-function (beg end)
8008 "Every change indicates that a table might need an update."
8009 (setq org-table-may-need-update t))
8011 (defconst org-table-line-regexp "^[ \t]*|"
8012 "Detects an org-type table line.")
8013 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8014 "Detects an org-type table line.")
8015 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8016 "Detects a table line marked for automatic recalculation.")
8017 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8018 "Detects a table line marked for automatic recalculation.")
8019 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8020 "Detects a table line marked for automatic recalculation.")
8021 (defconst org-table-hline-regexp "^[ \t]*|-"
8022 "Detects an org-type table hline.")
8023 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8024 "Detects a table-type table hline.")
8025 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8026 "Detects an org-type or table-type table.")
8027 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8028 "Searching from within a table (any type) this finds the first line
8029 outside the table.")
8030 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8031 "Searching from within a table (any type) this finds the first line
8032 outside the table.")
8034 (defvar org-table-last-highlighted-reference nil)
8035 (defvar org-table-formula-history nil)
8037 (defvar org-table-column-names nil
8038 "Alist with column names, derived from the `!' line.")
8039 (defvar org-table-column-name-regexp nil
8040 "Regular expression matching the current column names.")
8041 (defvar org-table-local-parameters nil
8042 "Alist with parameter names, derived from the `$' line.")
8043 (defvar org-table-named-field-locations nil
8044 "Alist with locations of named fields.")
8046 (defvar org-table-current-line-types nil
8047 "Table row types, non-nil only for the duration of a comand.")
8048 (defvar org-table-current-begin-line nil
8049 "Table begin line, non-nil only for the duration of a comand.")
8050 (defvar org-table-current-begin-pos nil
8051 "Table begin position, non-nil only for the duration of a comand.")
8052 (defvar org-table-dlines nil
8053 "Vector of data line line numbers in the current table.")
8054 (defvar org-table-hlines nil
8055 "Vector of hline line numbers in the current table.")
8057 (defconst org-table-range-regexp
8058 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8059 ;; 1 2 3 4 5
8060 "Regular expression for matching ranges in formulas.")
8062 (defconst org-table-range-regexp2
8063 (concat
8064 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8065 "\\.\\."
8066 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8067 "Match a range for reference display.")
8069 (defconst org-table-translate-regexp
8070 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8071 "Match a reference that needs translation, for reference display.")
8073 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8075 (defun org-table-create-with-table.el ()
8076 "Use the table.el package to insert a new table.
8077 If there is already a table at point, convert between Org-mode tables
8078 and table.el tables."
8079 (interactive)
8080 (require 'table)
8081 (cond
8082 ((org-at-table.el-p)
8083 (if (y-or-n-p "Convert table to Org-mode table? ")
8084 (org-table-convert)))
8085 ((org-at-table-p)
8086 (if (y-or-n-p "Convert table to table.el table? ")
8087 (org-table-convert)))
8088 (t (call-interactively 'table-insert))))
8090 (defun org-table-create-or-convert-from-region (arg)
8091 "Convert region to table, or create an empty table.
8092 If there is an active region, convert it to a table, using the function
8093 `org-table-convert-region'. See the documentation of that function
8094 to learn how the prefix argument is interpreted to determine the field
8095 separator.
8096 If there is no such region, create an empty table with `org-table-create'."
8097 (interactive "P")
8098 (if (org-region-active-p)
8099 (org-table-convert-region (region-beginning) (region-end) arg)
8100 (org-table-create arg)))
8102 (defun org-table-create (&optional size)
8103 "Query for a size and insert a table skeleton.
8104 SIZE is a string Columns x Rows like for example \"3x2\"."
8105 (interactive "P")
8106 (unless size
8107 (setq size (read-string
8108 (concat "Table size Columns x Rows [e.g. "
8109 org-table-default-size "]: ")
8110 "" nil org-table-default-size)))
8112 (let* ((pos (point))
8113 (indent (make-string (current-column) ?\ ))
8114 (split (org-split-string size " *x *"))
8115 (rows (string-to-number (nth 1 split)))
8116 (columns (string-to-number (car split)))
8117 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8118 "\n")))
8119 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8120 (point-at-bol) (point)))
8121 (beginning-of-line 1)
8122 (newline))
8123 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8124 (dotimes (i rows) (insert line))
8125 (goto-char pos)
8126 (if (> rows 1)
8127 ;; Insert a hline after the first row.
8128 (progn
8129 (end-of-line 1)
8130 (insert "\n|-")
8131 (goto-char pos)))
8132 (org-table-align)))
8134 (defun org-table-convert-region (beg0 end0 &optional separator)
8135 "Convert region to a table.
8136 The region goes from BEG0 to END0, but these borders will be moved
8137 slightly, to make sure a beginning of line in the first line is included.
8139 SEPARATOR specifies the field separator in the lines. It can have the
8140 following values:
8142 '(4) Use the comma as a field separator
8143 '(16) Use a TAB as field separator
8144 integer When a number, use that many spaces as field separator
8145 nil When nil, the command tries to be smart and figure out the
8146 separator in the following way:
8147 - when each line contains a TAB, assume TAB-separated material
8148 - when each line contains a comme, assume CSV material
8149 - else, assume one or more SPACE charcters as separator."
8150 (interactive "rP")
8151 (let* ((beg (min beg0 end0))
8152 (end (max beg0 end0))
8154 (goto-char beg)
8155 (beginning-of-line 1)
8156 (setq beg (move-marker (make-marker) (point)))
8157 (goto-char end)
8158 (if (bolp) (backward-char 1) (end-of-line 1))
8159 (setq end (move-marker (make-marker) (point)))
8160 ;; Get the right field separator
8161 (unless separator
8162 (goto-char beg)
8163 (setq separator
8164 (cond
8165 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8166 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8167 (t 1))))
8168 (setq re (cond
8169 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8170 ((equal separator '(16)) "^\\|\t")
8171 ((integerp separator)
8172 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8173 (t (error "This should not happen"))))
8174 (goto-char beg)
8175 (while (re-search-forward re end t)
8176 (replace-match "| " t t))
8177 (goto-char beg)
8178 (insert " ")
8179 (org-table-align)))
8181 (defun org-table-import (file arg)
8182 "Import FILE as a table.
8183 The file is assumed to be tab-separated. Such files can be produced by most
8184 spreadsheet and database applications. If no tabs (at least one per line)
8185 are found, lines will be split on whitespace into fields."
8186 (interactive "f\nP")
8187 (or (bolp) (newline))
8188 (let ((beg (point))
8189 (pm (point-max)))
8190 (insert-file-contents file)
8191 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8193 (defun org-table-export ()
8194 "Export table as a tab-separated file.
8195 Such a file can be imported into a spreadsheet program like Excel."
8196 (interactive)
8197 (let* ((beg (org-table-begin))
8198 (end (org-table-end))
8199 (table (buffer-substring beg end))
8200 (file (read-file-name "Export table to: "))
8201 buf)
8202 (unless (or (not (file-exists-p file))
8203 (y-or-n-p (format "Overwrite file %s? " file)))
8204 (error "Abort"))
8205 (with-current-buffer (find-file-noselect file)
8206 (setq buf (current-buffer))
8207 (erase-buffer)
8208 (fundamental-mode)
8209 (insert table)
8210 (goto-char (point-min))
8211 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8212 (replace-match "" t t)
8213 (end-of-line 1))
8214 (goto-char (point-min))
8215 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8216 (replace-match "" t t)
8217 (goto-char (min (1+ (point)) (point-max))))
8218 (goto-char (point-min))
8219 (while (re-search-forward "^-[-+]*$" nil t)
8220 (replace-match "")
8221 (if (looking-at "\n")
8222 (delete-char 1)))
8223 (goto-char (point-min))
8224 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8225 (replace-match "\t" t t))
8226 (save-buffer))
8227 (kill-buffer buf)))
8229 (defvar org-table-aligned-begin-marker (make-marker)
8230 "Marker at the beginning of the table last aligned.
8231 Used to check if cursor still is in that table, to minimize realignment.")
8232 (defvar org-table-aligned-end-marker (make-marker)
8233 "Marker at the end of the table last aligned.
8234 Used to check if cursor still is in that table, to minimize realignment.")
8235 (defvar org-table-last-alignment nil
8236 "List of flags for flushright alignment, from the last re-alignment.
8237 This is being used to correctly align a single field after TAB or RET.")
8238 (defvar org-table-last-column-widths nil
8239 "List of max width of fields in each column.
8240 This is being used to correctly align a single field after TAB or RET.")
8241 (defvar org-table-overlay-coordinates nil
8242 "Overlay coordinates after each align of a table.")
8243 (make-variable-buffer-local 'org-table-overlay-coordinates)
8245 (defvar org-last-recalc-line nil)
8246 (defconst org-narrow-column-arrow "=>"
8247 "Used as display property in narrowed table columns.")
8249 (defun org-table-align ()
8250 "Align the table at point by aligning all vertical bars."
8251 (interactive)
8252 (let* (
8253 ;; Limits of table
8254 (beg (org-table-begin))
8255 (end (org-table-end))
8256 ;; Current cursor position
8257 (linepos (org-current-line))
8258 (colpos (org-table-current-column))
8259 (winstart (window-start))
8260 (winstartline (org-current-line (min winstart (1- (point-max)))))
8261 lines (new "") lengths l typenums ty fields maxfields i
8262 column
8263 (indent "") cnt frac
8264 rfmt hfmt
8265 (spaces '(1 . 1))
8266 (sp1 (car spaces))
8267 (sp2 (cdr spaces))
8268 (rfmt1 (concat
8269 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8270 (hfmt1 (concat
8271 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8272 emptystrings links dates emph narrow fmax f1 len c e)
8273 (untabify beg end)
8274 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8275 ;; Check if we have links or dates
8276 (goto-char beg)
8277 (setq links (re-search-forward org-bracket-link-regexp end t))
8278 (goto-char beg)
8279 (setq emph (and org-hide-emphasis-markers
8280 (re-search-forward org-emph-re end t)))
8281 (goto-char beg)
8282 (setq dates (and org-display-custom-times
8283 (re-search-forward org-ts-regexp-both end t)))
8284 ;; Make sure the link properties are right
8285 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8286 ;; Make sure the date properties are right
8287 (when dates (goto-char beg) (while (org-activate-dates end)))
8288 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8290 ;; Check if we are narrowing any columns
8291 (goto-char beg)
8292 (setq narrow (and org-format-transports-properties-p
8293 (re-search-forward "<[0-9]+>" end t)))
8294 ;; Get the rows
8295 (setq lines (org-split-string
8296 (buffer-substring beg end) "\n"))
8297 ;; Store the indentation of the first line
8298 (if (string-match "^ *" (car lines))
8299 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8300 ;; Mark the hlines by setting the corresponding element to nil
8301 ;; At the same time, we remove trailing space.
8302 (setq lines (mapcar (lambda (l)
8303 (if (string-match "^ *|-" l)
8305 (if (string-match "[ \t]+$" l)
8306 (substring l 0 (match-beginning 0))
8307 l)))
8308 lines))
8309 ;; Get the data fields by splitting the lines.
8310 (setq fields (mapcar
8311 (lambda (l)
8312 (org-split-string l " *| *"))
8313 (delq nil (copy-sequence lines))))
8314 ;; How many fields in the longest line?
8315 (condition-case nil
8316 (setq maxfields (apply 'max (mapcar 'length fields)))
8317 (error
8318 (kill-region beg end)
8319 (org-table-create org-table-default-size)
8320 (error "Empty table - created default table")))
8321 ;; A list of empty strings to fill any short rows on output
8322 (setq emptystrings (make-list maxfields ""))
8323 ;; Check for special formatting.
8324 (setq i -1)
8325 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8326 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8327 ;; Check if there is an explicit width specified
8328 (when narrow
8329 (setq c column fmax nil)
8330 (while c
8331 (setq e (pop c))
8332 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8333 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8334 ;; Find fields that are wider than fmax, and shorten them
8335 (when fmax
8336 (loop for xx in column do
8337 (when (and (stringp xx)
8338 (> (org-string-width xx) fmax))
8339 (org-add-props xx nil
8340 'help-echo
8341 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8342 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8343 (unless (> f1 1)
8344 (error "Cannot narrow field starting with wide link \"%s\""
8345 (match-string 0 xx)))
8346 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8347 (add-text-properties (- f1 2) f1
8348 (list 'display org-narrow-column-arrow)
8349 xx)))))
8350 ;; Get the maximum width for each column
8351 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8352 ;; Get the fraction of numbers, to decide about alignment of the column
8353 (setq cnt 0 frac 0.0)
8354 (loop for x in column do
8355 (if (equal x "")
8357 (setq frac ( / (+ (* frac cnt)
8358 (if (string-match org-table-number-regexp x) 1 0))
8359 (setq cnt (1+ cnt))))))
8360 (push (>= frac org-table-number-fraction) typenums))
8361 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8363 ;; Store the alignment of this table, for later editing of single fields
8364 (setq org-table-last-alignment typenums
8365 org-table-last-column-widths lengths)
8367 ;; With invisible characters, `format' does not get the field width right
8368 ;; So we need to make these fields wide by hand.
8369 (when (or links emph)
8370 (loop for i from 0 upto (1- maxfields) do
8371 (setq len (nth i lengths))
8372 (loop for j from 0 upto (1- (length fields)) do
8373 (setq c (nthcdr i (car (nthcdr j fields))))
8374 (if (and (stringp (car c))
8375 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8376 ; (string-match org-bracket-link-regexp (car c))
8377 (< (org-string-width (car c)) len))
8378 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8380 ;; Compute the formats needed for output of the table
8381 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8382 (while (setq l (pop lengths))
8383 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8384 (setq rfmt (concat rfmt (format rfmt1 ty l))
8385 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8386 (setq rfmt (concat rfmt "\n")
8387 hfmt (concat (substring hfmt 0 -1) "|\n"))
8389 (setq new (mapconcat
8390 (lambda (l)
8391 (if l (apply 'format rfmt
8392 (append (pop fields) emptystrings))
8393 hfmt))
8394 lines ""))
8395 ;; Replace the old one
8396 (delete-region beg end)
8397 (move-marker end nil)
8398 (move-marker org-table-aligned-begin-marker (point))
8399 (insert new)
8400 (move-marker org-table-aligned-end-marker (point))
8401 (when (and orgtbl-mode (not (org-mode-p)))
8402 (goto-char org-table-aligned-begin-marker)
8403 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8404 ;; Try to move to the old location
8405 (goto-line winstartline)
8406 (setq winstart (point-at-bol))
8407 (goto-line linepos)
8408 (set-window-start (selected-window) winstart 'noforce)
8409 (org-table-goto-column colpos)
8410 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8411 (setq org-table-may-need-update nil)
8414 (defun org-string-width (s)
8415 "Compute width of string, ignoring invisible characters.
8416 This ignores character with invisibility property `org-link', and also
8417 characters with property `org-cwidth', because these will become invisible
8418 upon the next fontification round."
8419 (let (b l)
8420 (when (or (eq t buffer-invisibility-spec)
8421 (assq 'org-link buffer-invisibility-spec))
8422 (while (setq b (text-property-any 0 (length s)
8423 'invisible 'org-link s))
8424 (setq s (concat (substring s 0 b)
8425 (substring s (or (next-single-property-change
8426 b 'invisible s) (length s)))))))
8427 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8428 (setq s (concat (substring s 0 b)
8429 (substring s (or (next-single-property-change
8430 b 'org-cwidth s) (length s))))))
8431 (setq l (string-width s) b -1)
8432 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8433 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8436 (defun org-table-begin (&optional table-type)
8437 "Find the beginning of the table and return its position.
8438 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8439 (save-excursion
8440 (if (not (re-search-backward
8441 (if table-type org-table-any-border-regexp
8442 org-table-border-regexp)
8443 nil t))
8444 (progn (goto-char (point-min)) (point))
8445 (goto-char (match-beginning 0))
8446 (beginning-of-line 2)
8447 (point))))
8449 (defun org-table-end (&optional table-type)
8450 "Find the end of the table and return its position.
8451 With argument TABLE-TYPE, go to the end of a table.el-type table."
8452 (save-excursion
8453 (if (not (re-search-forward
8454 (if table-type org-table-any-border-regexp
8455 org-table-border-regexp)
8456 nil t))
8457 (goto-char (point-max))
8458 (goto-char (match-beginning 0)))
8459 (point-marker)))
8461 (defun org-table-justify-field-maybe (&optional new)
8462 "Justify the current field, text to left, number to right.
8463 Optional argument NEW may specify text to replace the current field content."
8464 (cond
8465 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8466 ((org-at-table-hline-p))
8467 ((and (not new)
8468 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8469 (current-buffer)))
8470 (< (point) org-table-aligned-begin-marker)
8471 (>= (point) org-table-aligned-end-marker)))
8472 ;; This is not the same table, force a full re-align
8473 (setq org-table-may-need-update t))
8474 (t ;; realign the current field, based on previous full realign
8475 (let* ((pos (point)) s
8476 (col (org-table-current-column))
8477 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8478 l f n o e)
8479 (when (> col 0)
8480 (skip-chars-backward "^|\n")
8481 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8482 (progn
8483 (setq s (match-string 1)
8484 o (match-string 0)
8485 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8486 e (not (= (match-beginning 2) (match-end 2))))
8487 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8488 l (if e "|" (setq org-table-may-need-update t) ""))
8489 n (format f s))
8490 (if new
8491 (if (<= (length new) l) ;; FIXME: length -> str-width?
8492 (setq n (format f new))
8493 (setq n (concat new "|") org-table-may-need-update t)))
8494 (or (equal n o)
8495 (let (org-table-may-need-update)
8496 (replace-match n t t))))
8497 (setq org-table-may-need-update t))
8498 (goto-char pos))))))
8500 (defun org-table-next-field ()
8501 "Go to the next field in the current table, creating new lines as needed.
8502 Before doing so, re-align the table if necessary."
8503 (interactive)
8504 (org-table-maybe-eval-formula)
8505 (org-table-maybe-recalculate-line)
8506 (if (and org-table-automatic-realign
8507 org-table-may-need-update)
8508 (org-table-align))
8509 (let ((end (org-table-end)))
8510 (if (org-at-table-hline-p)
8511 (end-of-line 1))
8512 (condition-case nil
8513 (progn
8514 (re-search-forward "|" end)
8515 (if (looking-at "[ \t]*$")
8516 (re-search-forward "|" end))
8517 (if (and (looking-at "-")
8518 org-table-tab-jumps-over-hlines
8519 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8520 (goto-char (match-beginning 1)))
8521 (if (looking-at "-")
8522 (progn
8523 (beginning-of-line 0)
8524 (org-table-insert-row 'below))
8525 (if (looking-at " ") (forward-char 1))))
8526 (error
8527 (org-table-insert-row 'below)))))
8529 (defun org-table-previous-field ()
8530 "Go to the previous field in the table.
8531 Before doing so, re-align the table if necessary."
8532 (interactive)
8533 (org-table-justify-field-maybe)
8534 (org-table-maybe-recalculate-line)
8535 (if (and org-table-automatic-realign
8536 org-table-may-need-update)
8537 (org-table-align))
8538 (if (org-at-table-hline-p)
8539 (end-of-line 1))
8540 (re-search-backward "|" (org-table-begin))
8541 (re-search-backward "|" (org-table-begin))
8542 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8543 (re-search-backward "|" (org-table-begin)))
8544 (if (looking-at "| ?")
8545 (goto-char (match-end 0))))
8547 (defun org-table-next-row ()
8548 "Go to the next row (same column) in the current table.
8549 Before doing so, re-align the table if necessary."
8550 (interactive)
8551 (org-table-maybe-eval-formula)
8552 (org-table-maybe-recalculate-line)
8553 (if (or (looking-at "[ \t]*$")
8554 (save-excursion (skip-chars-backward " \t") (bolp)))
8555 (newline)
8556 (if (and org-table-automatic-realign
8557 org-table-may-need-update)
8558 (org-table-align))
8559 (let ((col (org-table-current-column)))
8560 (beginning-of-line 2)
8561 (if (or (not (org-at-table-p))
8562 (org-at-table-hline-p))
8563 (progn
8564 (beginning-of-line 0)
8565 (org-table-insert-row 'below)))
8566 (org-table-goto-column col)
8567 (skip-chars-backward "^|\n\r")
8568 (if (looking-at " ") (forward-char 1)))))
8570 (defun org-table-copy-down (n)
8571 "Copy a field down in the current column.
8572 If the field at the cursor is empty, copy into it the content of the nearest
8573 non-empty field above. With argument N, use the Nth non-empty field.
8574 If the current field is not empty, it is copied down to the next row, and
8575 the cursor is moved with it. Therefore, repeating this command causes the
8576 column to be filled row-by-row.
8577 If the variable `org-table-copy-increment' is non-nil and the field is an
8578 integer or a timestamp, it will be incremented while copying. In the case of
8579 a timestamp, if the cursor is on the year, change the year. If it is on the
8580 month or the day, change that. Point will stay on the current date field
8581 in order to easily repeat the interval."
8582 (interactive "p")
8583 (let* ((colpos (org-table-current-column))
8584 (col (current-column))
8585 (field (org-table-get-field))
8586 (non-empty (string-match "[^ \t]" field))
8587 (beg (org-table-begin))
8588 txt)
8589 (org-table-check-inside-data-field)
8590 (if non-empty
8591 (progn
8592 (setq txt (org-trim field))
8593 (org-table-next-row)
8594 (org-table-blank-field))
8595 (save-excursion
8596 (setq txt
8597 (catch 'exit
8598 (while (progn (beginning-of-line 1)
8599 (re-search-backward org-table-dataline-regexp
8600 beg t))
8601 (org-table-goto-column colpos t)
8602 (if (and (looking-at
8603 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8604 (= (setq n (1- n)) 0))
8605 (throw 'exit (match-string 1))))))))
8606 (if txt
8607 (progn
8608 (if (and org-table-copy-increment
8609 (string-match "^[0-9]+$" txt))
8610 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8611 (insert txt)
8612 (move-to-column col)
8613 (if (and org-table-copy-increment (org-at-timestamp-p t))
8614 (org-timestamp-up 1)
8615 (org-table-maybe-recalculate-line))
8616 (org-table-align)
8617 (move-to-column col))
8618 (error "No non-empty field found"))))
8620 (defun org-table-check-inside-data-field ()
8621 "Is point inside a table data field?
8622 I.e. not on a hline or before the first or after the last column?
8623 This actually throws an error, so it aborts the current command."
8624 (if (or (not (org-at-table-p))
8625 (= (org-table-current-column) 0)
8626 (org-at-table-hline-p)
8627 (looking-at "[ \t]*$"))
8628 (error "Not in table data field")))
8630 (defvar org-table-clip nil
8631 "Clipboard for table regions.")
8633 (defun org-table-blank-field ()
8634 "Blank the current table field or active region."
8635 (interactive)
8636 (org-table-check-inside-data-field)
8637 (if (and (interactive-p) (org-region-active-p))
8638 (let (org-table-clip)
8639 (org-table-cut-region (region-beginning) (region-end)))
8640 (skip-chars-backward "^|")
8641 (backward-char 1)
8642 (if (looking-at "|[^|\n]+")
8643 (let* ((pos (match-beginning 0))
8644 (match (match-string 0))
8645 (len (org-string-width match)))
8646 (replace-match (concat "|" (make-string (1- len) ?\ )))
8647 (goto-char (+ 2 pos))
8648 (substring match 1)))))
8650 (defun org-table-get-field (&optional n replace)
8651 "Return the value of the field in column N of current row.
8652 N defaults to current field.
8653 If REPLACE is a string, replace field with this value. The return value
8654 is always the old value."
8655 (and n (org-table-goto-column n))
8656 (skip-chars-backward "^|\n")
8657 (backward-char 1)
8658 (if (looking-at "|[^|\r\n]*")
8659 (let* ((pos (match-beginning 0))
8660 (val (buffer-substring (1+ pos) (match-end 0))))
8661 (if replace
8662 (replace-match (concat "|" replace) t t))
8663 (goto-char (min (point-at-eol) (+ 2 pos)))
8664 val)
8665 (forward-char 1) ""))
8667 (defun org-table-field-info (arg)
8668 "Show info about the current field, and highlight any reference at point."
8669 (interactive "P")
8670 (org-table-get-specials)
8671 (save-excursion
8672 (let* ((pos (point))
8673 (col (org-table-current-column))
8674 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8675 (name (car (rassoc (list (org-current-line) col)
8676 org-table-named-field-locations)))
8677 (eql (org-table-get-stored-formulas))
8678 (dline (org-table-current-dline))
8679 (ref (format "@%d$%d" dline col))
8680 (ref1 (org-table-convert-refs-to-an ref))
8681 (fequation (or (assoc name eql) (assoc ref eql)))
8682 (cequation (assoc (int-to-string col) eql))
8683 (eqn (or fequation cequation)))
8684 (goto-char pos)
8685 (condition-case nil
8686 (org-table-show-reference 'local)
8687 (error nil))
8688 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8689 dline col
8690 (if cname (concat " or $" cname) "")
8691 dline col ref1
8692 (if name (concat " or $" name) "")
8693 ;; FIXME: formula info not correct if special table line
8694 (if eqn
8695 (concat ", formula: "
8696 (org-table-formula-to-user
8697 (concat
8698 (if (string-match "^[$@]"(car eqn)) "" "$")
8699 (car eqn) "=" (cdr eqn))))
8700 "")))))
8702 (defun org-table-current-column ()
8703 "Find out which column we are in.
8704 When called interactively, column is also displayed in echo area."
8705 (interactive)
8706 (if (interactive-p) (org-table-check-inside-data-field))
8707 (save-excursion
8708 (let ((cnt 0) (pos (point)))
8709 (beginning-of-line 1)
8710 (while (search-forward "|" pos t)
8711 (setq cnt (1+ cnt)))
8712 (if (interactive-p) (message "This is table column %d" cnt))
8713 cnt)))
8715 (defun org-table-current-dline ()
8716 "Find out what table data line we are in.
8717 Only datalins count for this."
8718 (interactive)
8719 (if (interactive-p) (org-table-check-inside-data-field))
8720 (save-excursion
8721 (let ((cnt 0) (pos (point)))
8722 (goto-char (org-table-begin))
8723 (while (<= (point) pos)
8724 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8725 (beginning-of-line 2))
8726 (if (interactive-p) (message "This is table line %d" cnt))
8727 cnt)))
8729 (defun org-table-goto-column (n &optional on-delim force)
8730 "Move the cursor to the Nth column in the current table line.
8731 With optional argument ON-DELIM, stop with point before the left delimiter
8732 of the field.
8733 If there are less than N fields, just go to after the last delimiter.
8734 However, when FORCE is non-nil, create new columns if necessary."
8735 (interactive "p")
8736 (let ((pos (point-at-eol)))
8737 (beginning-of-line 1)
8738 (when (> n 0)
8739 (while (and (> (setq n (1- n)) -1)
8740 (or (search-forward "|" pos t)
8741 (and force
8742 (progn (end-of-line 1)
8743 (skip-chars-backward "^|")
8744 (insert " | "))))))
8745 ; (backward-char 2) t)))))
8746 (when (and force (not (looking-at ".*|")))
8747 (save-excursion (end-of-line 1) (insert " | ")))
8748 (if on-delim
8749 (backward-char 1)
8750 (if (looking-at " ") (forward-char 1))))))
8752 (defun org-at-table-p (&optional table-type)
8753 "Return t if the cursor is inside an org-type table.
8754 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8755 (if org-enable-table-editor
8756 (save-excursion
8757 (beginning-of-line 1)
8758 (looking-at (if table-type org-table-any-line-regexp
8759 org-table-line-regexp)))
8760 nil))
8762 (defun org-at-table.el-p ()
8763 "Return t if and only if we are at a table.el table."
8764 (and (org-at-table-p 'any)
8765 (save-excursion
8766 (goto-char (org-table-begin 'any))
8767 (looking-at org-table1-hline-regexp))))
8769 (defun org-table-recognize-table.el ()
8770 "If there is a table.el table nearby, recognize it and move into it."
8771 (if org-table-tab-recognizes-table.el
8772 (if (org-at-table.el-p)
8773 (progn
8774 (beginning-of-line 1)
8775 (if (looking-at org-table-dataline-regexp)
8777 (if (looking-at org-table1-hline-regexp)
8778 (progn
8779 (beginning-of-line 2)
8780 (if (looking-at org-table-any-border-regexp)
8781 (beginning-of-line -1)))))
8782 (if (re-search-forward "|" (org-table-end t) t)
8783 (progn
8784 (require 'table)
8785 (if (table--at-cell-p (point))
8787 (message "recognizing table.el table...")
8788 (table-recognize-table)
8789 (message "recognizing table.el table...done")))
8790 (error "This should not happen..."))
8792 nil)
8793 nil))
8795 (defun org-at-table-hline-p ()
8796 "Return t if the cursor is inside a hline in a table."
8797 (if org-enable-table-editor
8798 (save-excursion
8799 (beginning-of-line 1)
8800 (looking-at org-table-hline-regexp))
8801 nil))
8803 (defun org-table-insert-column ()
8804 "Insert a new column into the table."
8805 (interactive)
8806 (if (not (org-at-table-p))
8807 (error "Not at a table"))
8808 (org-table-find-dataline)
8809 (let* ((col (max 1 (org-table-current-column)))
8810 (beg (org-table-begin))
8811 (end (org-table-end))
8812 ;; Current cursor position
8813 (linepos (org-current-line))
8814 (colpos col))
8815 (goto-char beg)
8816 (while (< (point) end)
8817 (if (org-at-table-hline-p)
8819 (org-table-goto-column col t)
8820 (insert "| "))
8821 (beginning-of-line 2))
8822 (move-marker end nil)
8823 (goto-line linepos)
8824 (org-table-goto-column colpos)
8825 (org-table-align)
8826 (org-table-fix-formulas "$" nil (1- col) 1)))
8828 (defun org-table-find-dataline ()
8829 "Find a dataline in the current table, which is needed for column commands."
8830 (if (and (org-at-table-p)
8831 (not (org-at-table-hline-p)))
8833 (let ((col (current-column))
8834 (end (org-table-end)))
8835 (move-to-column col)
8836 (while (and (< (point) end)
8837 (or (not (= (current-column) col))
8838 (org-at-table-hline-p)))
8839 (beginning-of-line 2)
8840 (move-to-column col))
8841 (if (and (org-at-table-p)
8842 (not (org-at-table-hline-p)))
8844 (error
8845 "Please position cursor in a data line for column operations")))))
8847 (defun org-table-delete-column ()
8848 "Delete a column from the table."
8849 (interactive)
8850 (if (not (org-at-table-p))
8851 (error "Not at a table"))
8852 (org-table-find-dataline)
8853 (org-table-check-inside-data-field)
8854 (let* ((col (org-table-current-column))
8855 (beg (org-table-begin))
8856 (end (org-table-end))
8857 ;; Current cursor position
8858 (linepos (org-current-line))
8859 (colpos col))
8860 (goto-char beg)
8861 (while (< (point) end)
8862 (if (org-at-table-hline-p)
8864 (org-table-goto-column col t)
8865 (and (looking-at "|[^|\n]+|")
8866 (replace-match "|")))
8867 (beginning-of-line 2))
8868 (move-marker end nil)
8869 (goto-line linepos)
8870 (org-table-goto-column colpos)
8871 (org-table-align)
8872 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8873 col -1 col)))
8875 (defun org-table-move-column-right ()
8876 "Move column to the right."
8877 (interactive)
8878 (org-table-move-column nil))
8879 (defun org-table-move-column-left ()
8880 "Move column to the left."
8881 (interactive)
8882 (org-table-move-column 'left))
8884 (defun org-table-move-column (&optional left)
8885 "Move the current column to the right. With arg LEFT, move to the left."
8886 (interactive "P")
8887 (if (not (org-at-table-p))
8888 (error "Not at a table"))
8889 (org-table-find-dataline)
8890 (org-table-check-inside-data-field)
8891 (let* ((col (org-table-current-column))
8892 (col1 (if left (1- col) col))
8893 (beg (org-table-begin))
8894 (end (org-table-end))
8895 ;; Current cursor position
8896 (linepos (org-current-line))
8897 (colpos (if left (1- col) (1+ col))))
8898 (if (and left (= col 1))
8899 (error "Cannot move column further left"))
8900 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8901 (error "Cannot move column further right"))
8902 (goto-char beg)
8903 (while (< (point) end)
8904 (if (org-at-table-hline-p)
8906 (org-table-goto-column col1 t)
8907 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8908 (replace-match "|\\2|\\1|")))
8909 (beginning-of-line 2))
8910 (move-marker end nil)
8911 (goto-line linepos)
8912 (org-table-goto-column colpos)
8913 (org-table-align)
8914 (org-table-fix-formulas
8915 "$" (list (cons (number-to-string col) (number-to-string colpos))
8916 (cons (number-to-string colpos) (number-to-string col))))))
8918 (defun org-table-move-row-down ()
8919 "Move table row down."
8920 (interactive)
8921 (org-table-move-row nil))
8922 (defun org-table-move-row-up ()
8923 "Move table row up."
8924 (interactive)
8925 (org-table-move-row 'up))
8927 (defun org-table-move-row (&optional up)
8928 "Move the current table line down. With arg UP, move it up."
8929 (interactive "P")
8930 (let* ((col (current-column))
8931 (pos (point))
8932 (hline1p (save-excursion (beginning-of-line 1)
8933 (looking-at org-table-hline-regexp)))
8934 (dline1 (org-table-current-dline))
8935 (dline2 (+ dline1 (if up -1 1)))
8936 (tonew (if up 0 2))
8937 txt hline2p)
8938 (beginning-of-line tonew)
8939 (unless (org-at-table-p)
8940 (goto-char pos)
8941 (error "Cannot move row further"))
8942 (setq hline2p (looking-at org-table-hline-regexp))
8943 (goto-char pos)
8944 (beginning-of-line 1)
8945 (setq pos (point))
8946 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8947 (delete-region (point) (1+ (point-at-eol)))
8948 (beginning-of-line tonew)
8949 (insert txt)
8950 (beginning-of-line 0)
8951 (move-to-column col)
8952 (unless (or hline1p hline2p)
8953 (org-table-fix-formulas
8954 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8955 (cons (number-to-string dline2) (number-to-string dline1)))))))
8957 (defun org-table-insert-row (&optional arg)
8958 "Insert a new row above the current line into the table.
8959 With prefix ARG, insert below the current line."
8960 (interactive "P")
8961 (if (not (org-at-table-p))
8962 (error "Not at a table"))
8963 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8964 (new (org-table-clean-line line)))
8965 ;; Fix the first field if necessary
8966 (if (string-match "^[ \t]*| *[#$] *|" line)
8967 (setq new (replace-match (match-string 0 line) t t new)))
8968 (beginning-of-line (if arg 2 1))
8969 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8970 (beginning-of-line 0)
8971 (re-search-forward "| ?" (point-at-eol) t)
8972 (and (or org-table-may-need-update org-table-overlay-coordinates)
8973 (org-table-align))
8974 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8976 (defun org-table-insert-hline (&optional above)
8977 "Insert a horizontal-line below the current line into the table.
8978 With prefix ABOVE, insert above the current line."
8979 (interactive "P")
8980 (if (not (org-at-table-p))
8981 (error "Not at a table"))
8982 (let ((line (org-table-clean-line
8983 (buffer-substring (point-at-bol) (point-at-eol))))
8984 (col (current-column)))
8985 (while (string-match "|\\( +\\)|" line)
8986 (setq line (replace-match
8987 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8988 ?-) "|") t t line)))
8989 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8990 (beginning-of-line (if above 1 2))
8991 (insert line "\n")
8992 (beginning-of-line (if above 1 -1))
8993 (move-to-column col)
8994 (and org-table-overlay-coordinates (org-table-align))))
8996 (defun org-table-hline-and-move (&optional same-column)
8997 "Insert a hline and move to the row below that line."
8998 (interactive "P")
8999 (let ((col (org-table-current-column)))
9000 (org-table-maybe-eval-formula)
9001 (org-table-maybe-recalculate-line)
9002 (org-table-insert-hline)
9003 (end-of-line 2)
9004 (if (looking-at "\n[ \t]*|-")
9005 (progn (insert "\n|") (org-table-align))
9006 (org-table-next-field))
9007 (if same-column (org-table-goto-column col))))
9009 (defun org-table-clean-line (s)
9010 "Convert a table line S into a string with only \"|\" and space.
9011 In particular, this does handle wide and invisible characters."
9012 (if (string-match "^[ \t]*|-" s)
9013 ;; It's a hline, just map the characters
9014 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9015 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9016 (setq s (replace-match
9017 (concat "|" (make-string (org-string-width (match-string 1 s))
9018 ?\ ) "|")
9019 t t s)))
9022 (defun org-table-kill-row ()
9023 "Delete the current row or horizontal line from the table."
9024 (interactive)
9025 (if (not (org-at-table-p))
9026 (error "Not at a table"))
9027 (let ((col (current-column))
9028 (dline (org-table-current-dline)))
9029 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9030 (if (not (org-at-table-p)) (beginning-of-line 0))
9031 (move-to-column col)
9032 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9033 dline -1 dline)))
9035 (defun org-table-sort-lines (with-case &optional sorting-type)
9036 "Sort table lines according to the column at point.
9038 The position of point indicates the column to be used for
9039 sorting, and the range of lines is the range between the nearest
9040 horizontal separator lines, or the entire table of no such lines
9041 exist. If point is before the first column, you will be prompted
9042 for the sorting column. If there is an active region, the mark
9043 specifies the first line and the sorting column, while point
9044 should be in the last line to be included into the sorting.
9046 The command then prompts for the sorting type which can be
9047 alphabetically, numerically, or by time (as given in a time stamp
9048 in the field). Sorting in reverse order is also possible.
9050 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9052 If SORTING-TYPE is specified when this function is called from a Lisp
9053 program, no prompting will take place. SORTING-TYPE must be a character,
9054 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9055 should be done in reverse order."
9056 (interactive "P")
9057 (let* ((thisline (org-current-line))
9058 (thiscol (org-table-current-column))
9059 beg end bcol ecol tend tbeg column lns pos)
9060 (when (equal thiscol 0)
9061 (if (interactive-p)
9062 (setq thiscol
9063 (string-to-number
9064 (read-string "Use column N for sorting: ")))
9065 (setq thiscol 1))
9066 (org-table-goto-column thiscol))
9067 (org-table-check-inside-data-field)
9068 (if (org-region-active-p)
9069 (progn
9070 (setq beg (region-beginning) end (region-end))
9071 (goto-char beg)
9072 (setq column (org-table-current-column)
9073 beg (point-at-bol))
9074 (goto-char end)
9075 (setq end (point-at-bol 2)))
9076 (setq column (org-table-current-column)
9077 pos (point)
9078 tbeg (org-table-begin)
9079 tend (org-table-end))
9080 (if (re-search-backward org-table-hline-regexp tbeg t)
9081 (setq beg (point-at-bol 2))
9082 (goto-char tbeg)
9083 (setq beg (point-at-bol 1)))
9084 (goto-char pos)
9085 (if (re-search-forward org-table-hline-regexp tend t)
9086 (setq end (point-at-bol 1))
9087 (goto-char tend)
9088 (setq end (point-at-bol))))
9089 (setq beg (move-marker (make-marker) beg)
9090 end (move-marker (make-marker) end))
9091 (untabify beg end)
9092 (goto-char beg)
9093 (org-table-goto-column column)
9094 (skip-chars-backward "^|")
9095 (setq bcol (current-column))
9096 (org-table-goto-column (1+ column))
9097 (skip-chars-backward "^|")
9098 (setq ecol (1- (current-column)))
9099 (org-table-goto-column column)
9100 (setq lns (mapcar (lambda(x) (cons
9101 (org-sort-remove-invisible
9102 (nth (1- column)
9103 (org-split-string x "[ \t]*|[ \t]*")))
9105 (org-split-string (buffer-substring beg end) "\n")))
9106 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9107 (delete-region beg end)
9108 (move-marker beg nil)
9109 (move-marker end nil)
9110 (insert (mapconcat 'cdr lns "\n") "\n")
9111 (goto-line thisline)
9112 (org-table-goto-column thiscol)
9113 (message "%d lines sorted, based on column %d" (length lns) column)))
9115 ;; FIXME: maybe we will not need this? Table sorting is broken....
9116 (defun org-sort-remove-invisible (s)
9117 (remove-text-properties 0 (length s) org-rm-props s)
9118 (while (string-match org-bracket-link-regexp s)
9119 (setq s (replace-match (if (match-end 2)
9120 (match-string 3 s)
9121 (match-string 1 s)) t t s)))
9124 (defun org-table-cut-region (beg end)
9125 "Copy region in table to the clipboard and blank all relevant fields."
9126 (interactive "r")
9127 (org-table-copy-region beg end 'cut))
9129 (defun org-table-copy-region (beg end &optional cut)
9130 "Copy rectangular region in table to clipboard.
9131 A special clipboard is used which can only be accessed
9132 with `org-table-paste-rectangle'."
9133 (interactive "rP")
9134 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9135 region cols
9136 (rpl (if cut " " nil)))
9137 (goto-char beg)
9138 (org-table-check-inside-data-field)
9139 (setq l01 (org-current-line)
9140 c01 (org-table-current-column))
9141 (goto-char end)
9142 (org-table-check-inside-data-field)
9143 (setq l02 (org-current-line)
9144 c02 (org-table-current-column))
9145 (setq l1 (min l01 l02) l2 (max l01 l02)
9146 c1 (min c01 c02) c2 (max c01 c02))
9147 (catch 'exit
9148 (while t
9149 (catch 'nextline
9150 (if (> l1 l2) (throw 'exit t))
9151 (goto-line l1)
9152 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9153 (setq cols nil ic1 c1 ic2 c2)
9154 (while (< ic1 (1+ ic2))
9155 (push (org-table-get-field ic1 rpl) cols)
9156 (setq ic1 (1+ ic1)))
9157 (push (nreverse cols) region)
9158 (setq l1 (1+ l1)))))
9159 (setq org-table-clip (nreverse region))
9160 (if cut (org-table-align))
9161 org-table-clip))
9163 (defun org-table-paste-rectangle ()
9164 "Paste a rectangular region into a table.
9165 The upper right corner ends up in the current field. All involved fields
9166 will be overwritten. If the rectangle does not fit into the present table,
9167 the table is enlarged as needed. The process ignores horizontal separator
9168 lines."
9169 (interactive)
9170 (unless (and org-table-clip (listp org-table-clip))
9171 (error "First cut/copy a region to paste!"))
9172 (org-table-check-inside-data-field)
9173 (let* ((clip org-table-clip)
9174 (line (org-current-line))
9175 (col (org-table-current-column))
9176 (org-enable-table-editor t)
9177 (org-table-automatic-realign nil)
9178 c cols field)
9179 (while (setq cols (pop clip))
9180 (while (org-at-table-hline-p) (beginning-of-line 2))
9181 (if (not (org-at-table-p))
9182 (progn (end-of-line 0) (org-table-next-field)))
9183 (setq c col)
9184 (while (setq field (pop cols))
9185 (org-table-goto-column c nil 'force)
9186 (org-table-get-field nil field)
9187 (setq c (1+ c)))
9188 (beginning-of-line 2))
9189 (goto-line line)
9190 (org-table-goto-column col)
9191 (org-table-align)))
9193 (defun org-table-convert ()
9194 "Convert from `org-mode' table to table.el and back.
9195 Obviously, this only works within limits. When an Org-mode table is
9196 converted to table.el, all horizontal separator lines get lost, because
9197 table.el uses these as cell boundaries and has no notion of horizontal lines.
9198 A table.el table can be converted to an Org-mode table only if it does not
9199 do row or column spanning. Multiline cells will become multiple cells.
9200 Beware, Org-mode does not test if the table can be successfully converted - it
9201 blindly applies a recipe that works for simple tables."
9202 (interactive)
9203 (require 'table)
9204 (if (org-at-table.el-p)
9205 ;; convert to Org-mode table
9206 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9207 (end (move-marker (make-marker) (org-table-end t))))
9208 (table-unrecognize-region beg end)
9209 (goto-char beg)
9210 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9211 (replace-match ""))
9212 (goto-char beg))
9213 (if (org-at-table-p)
9214 ;; convert to table.el table
9215 (let ((beg (move-marker (make-marker) (org-table-begin)))
9216 (end (move-marker (make-marker) (org-table-end))))
9217 ;; first, get rid of all horizontal lines
9218 (goto-char beg)
9219 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9220 (replace-match ""))
9221 ;; insert a hline before first
9222 (goto-char beg)
9223 (org-table-insert-hline 'above)
9224 (beginning-of-line -1)
9225 ;; insert a hline after each line
9226 (while (progn (beginning-of-line 3) (< (point) end))
9227 (org-table-insert-hline))
9228 (goto-char beg)
9229 (setq end (move-marker end (org-table-end)))
9230 ;; replace "+" at beginning and ending of hlines
9231 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9232 (replace-match "\\1+-"))
9233 (goto-char beg)
9234 (while (re-search-forward "-|[ \t]*$" end t)
9235 (replace-match "-+"))
9236 (goto-char beg)))))
9238 (defun org-table-wrap-region (arg)
9239 "Wrap several fields in a column like a paragraph.
9240 This is useful if you'd like to spread the contents of a field over several
9241 lines, in order to keep the table compact.
9243 If there is an active region, and both point and mark are in the same column,
9244 the text in the column is wrapped to minimum width for the given number of
9245 lines. Generally, this makes the table more compact. A prefix ARG may be
9246 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9247 formats the selected text to two lines. If the region was longer than two
9248 lines, the remaining lines remain empty. A negative prefix argument reduces
9249 the current number of lines by that amount. The wrapped text is pasted back
9250 into the table. If you formatted it to more lines than it was before, fields
9251 further down in the table get overwritten - so you might need to make space in
9252 the table first.
9254 If there is no region, the current field is split at the cursor position and
9255 the text fragment to the right of the cursor is prepended to the field one
9256 line down.
9258 If there is no region, but you specify a prefix ARG, the current field gets
9259 blank, and the content is appended to the field above."
9260 (interactive "P")
9261 (org-table-check-inside-data-field)
9262 (if (org-region-active-p)
9263 ;; There is a region: fill as a paragraph
9264 (let* ((beg (region-beginning))
9265 (cline (save-excursion (goto-char beg) (org-current-line)))
9266 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9267 nlines)
9268 (org-table-cut-region (region-beginning) (region-end))
9269 (if (> (length (car org-table-clip)) 1)
9270 (error "Region must be limited to single column"))
9271 (setq nlines (if arg
9272 (if (< arg 1)
9273 (+ (length org-table-clip) arg)
9274 arg)
9275 (length org-table-clip)))
9276 (setq org-table-clip
9277 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9278 nil nlines)))
9279 (goto-line cline)
9280 (org-table-goto-column ccol)
9281 (org-table-paste-rectangle))
9282 ;; No region, split the current field at point
9283 (if arg
9284 ;; combine with field above
9285 (let ((s (org-table-blank-field))
9286 (col (org-table-current-column)))
9287 (beginning-of-line 0)
9288 (while (org-at-table-hline-p) (beginning-of-line 0))
9289 (org-table-goto-column col)
9290 (skip-chars-forward "^|")
9291 (skip-chars-backward " ")
9292 (insert " " (org-trim s))
9293 (org-table-align))
9294 ;; split field
9295 (when (looking-at "\\([^|]+\\)+|")
9296 (let ((s (match-string 1)))
9297 (replace-match " |")
9298 (goto-char (match-beginning 0))
9299 (org-table-next-row)
9300 (insert (org-trim s) " ")
9301 (org-table-align))))))
9303 (defvar org-field-marker nil)
9305 (defun org-table-edit-field (arg)
9306 "Edit table field in a different window.
9307 This is mainly useful for fields that contain hidden parts.
9308 When called with a \\[universal-argument] prefix, just make the full field visible so that
9309 it can be edited in place."
9310 (interactive "P")
9311 (if arg
9312 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9313 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9314 (remove-text-properties b e '(org-cwidth t invisible t
9315 display t intangible t))
9316 (if (and (boundp 'font-lock-mode) font-lock-mode)
9317 (font-lock-fontify-block)))
9318 (let ((pos (move-marker (make-marker) (point)))
9319 (field (org-table-get-field))
9320 (cw (current-window-configuration))
9322 (org-switch-to-buffer-other-window "*Org tmp*")
9323 (erase-buffer)
9324 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9325 (let ((org-inhibit-startup t)) (org-mode))
9326 (goto-char (setq p (point-max)))
9327 (insert (org-trim field))
9328 (remove-text-properties p (point-max)
9329 '(invisible t org-cwidth t display t
9330 intangible t))
9331 (goto-char p)
9332 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9333 (org-set-local 'org-window-configuration cw)
9334 (org-set-local 'org-field-marker pos)
9335 (message "Edit and finish with C-c C-c"))))
9337 (defun org-table-finish-edit-field ()
9338 "Finish editing a table data field.
9339 Remove all newline characters, insert the result into the table, realign
9340 the table and kill the editing buffer."
9341 (let ((pos org-field-marker)
9342 (cw org-window-configuration)
9343 (cb (current-buffer))
9344 text)
9345 (goto-char (point-min))
9346 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9347 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9348 (replace-match " "))
9349 (setq text (org-trim (buffer-string)))
9350 (set-window-configuration cw)
9351 (kill-buffer cb)
9352 (select-window (get-buffer-window (marker-buffer pos)))
9353 (goto-char pos)
9354 (move-marker pos nil)
9355 (org-table-check-inside-data-field)
9356 (org-table-get-field nil text)
9357 (org-table-align)
9358 (message "New field value inserted")))
9360 (defun org-trim (s)
9361 "Remove whitespace at beginning and end of string."
9362 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9363 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9366 (defun org-wrap (string &optional width lines)
9367 "Wrap string to either a number of lines, or a width in characters.
9368 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9369 that costs. If there is a word longer than WIDTH, the text is actually
9370 wrapped to the length of that word.
9371 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9372 many lines, whatever width that takes.
9373 The return value is a list of lines, without newlines at the end."
9374 (let* ((words (org-split-string string "[ \t\n]+"))
9375 (maxword (apply 'max (mapcar 'org-string-width words)))
9376 w ll)
9377 (cond (width
9378 (org-do-wrap words (max maxword width)))
9379 (lines
9380 (setq w maxword)
9381 (setq ll (org-do-wrap words maxword))
9382 (if (<= (length ll) lines)
9384 (setq ll words)
9385 (while (> (length ll) lines)
9386 (setq w (1+ w))
9387 (setq ll (org-do-wrap words w)))
9388 ll))
9389 (t (error "Cannot wrap this")))))
9392 (defun org-do-wrap (words width)
9393 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9394 (let (lines line)
9395 (while words
9396 (setq line (pop words))
9397 (while (and words (< (+ (length line) (length (car words))) width))
9398 (setq line (concat line " " (pop words))))
9399 (setq lines (push line lines)))
9400 (nreverse lines)))
9402 (defun org-split-string (string &optional separators)
9403 "Splits STRING into substrings at SEPARATORS.
9404 No empty strings are returned if there are matches at the beginning
9405 and end of string."
9406 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9407 (start 0)
9408 notfirst
9409 (list nil))
9410 (while (and (string-match rexp string
9411 (if (and notfirst
9412 (= start (match-beginning 0))
9413 (< start (length string)))
9414 (1+ start) start))
9415 (< (match-beginning 0) (length string)))
9416 (setq notfirst t)
9417 (or (eq (match-beginning 0) 0)
9418 (and (eq (match-beginning 0) (match-end 0))
9419 (eq (match-beginning 0) start))
9420 (setq list
9421 (cons (substring string start (match-beginning 0))
9422 list)))
9423 (setq start (match-end 0)))
9424 (or (eq start (length string))
9425 (setq list
9426 (cons (substring string start)
9427 list)))
9428 (nreverse list)))
9430 (defun org-table-map-tables (function)
9431 "Apply FUNCTION to the start of all tables in the buffer."
9432 (save-excursion
9433 (save-restriction
9434 (widen)
9435 (goto-char (point-min))
9436 (while (re-search-forward org-table-any-line-regexp nil t)
9437 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9438 (beginning-of-line 1)
9439 (if (looking-at org-table-line-regexp)
9440 (save-excursion (funcall function)))
9441 (re-search-forward org-table-any-border-regexp nil 1))))
9442 (message "Mapping tables: done"))
9444 (defvar org-timecnt) ; dynamically scoped parameter
9446 (defun org-table-sum (&optional beg end nlast)
9447 "Sum numbers in region of current table column.
9448 The result will be displayed in the echo area, and will be available
9449 as kill to be inserted with \\[yank].
9451 If there is an active region, it is interpreted as a rectangle and all
9452 numbers in that rectangle will be summed. If there is no active
9453 region and point is located in a table column, sum all numbers in that
9454 column.
9456 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9457 numbers are assumed to be times as well (in decimal hours) and the
9458 numbers are added as such.
9460 If NLAST is a number, only the NLAST fields will actually be summed."
9461 (interactive)
9462 (save-excursion
9463 (let (col (org-timecnt 0) diff h m s org-table-clip)
9464 (cond
9465 ((and beg end)) ; beg and end given explicitly
9466 ((org-region-active-p)
9467 (setq beg (region-beginning) end (region-end)))
9469 (setq col (org-table-current-column))
9470 (goto-char (org-table-begin))
9471 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9472 (error "No table data"))
9473 (org-table-goto-column col)
9474 (setq beg (point))
9475 (goto-char (org-table-end))
9476 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9477 (error "No table data"))
9478 (org-table-goto-column col)
9479 (setq end (point))))
9480 (let* ((items (apply 'append (org-table-copy-region beg end)))
9481 (items1 (cond ((not nlast) items)
9482 ((>= nlast (length items)) items)
9483 (t (setq items (reverse items))
9484 (setcdr (nthcdr (1- nlast) items) nil)
9485 (nreverse items))))
9486 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9487 items1)))
9488 (res (apply '+ numbers))
9489 (sres (if (= org-timecnt 0)
9490 (format "%g" res)
9491 (setq diff (* 3600 res)
9492 h (floor (/ diff 3600)) diff (mod diff 3600)
9493 m (floor (/ diff 60)) diff (mod diff 60)
9494 s diff)
9495 (format "%d:%02d:%02d" h m s))))
9496 (kill-new sres)
9497 (if (interactive-p)
9498 (message "%s"
9499 (substitute-command-keys
9500 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9501 (length numbers) sres))))
9502 sres))))
9504 (defun org-table-get-number-for-summing (s)
9505 (let (n)
9506 (if (string-match "^ *|? *" s)
9507 (setq s (replace-match "" nil nil s)))
9508 (if (string-match " *|? *$" s)
9509 (setq s (replace-match "" nil nil s)))
9510 (setq n (string-to-number s))
9511 (cond
9512 ((and (string-match "0" s)
9513 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9514 ((string-match "\\`[ \t]+\\'" s) nil)
9515 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9516 (let ((h (string-to-number (or (match-string 1 s) "0")))
9517 (m (string-to-number (or (match-string 2 s) "0")))
9518 (s (string-to-number (or (match-string 4 s) "0"))))
9519 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9520 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9521 ((equal n 0) nil)
9522 (t n))))
9524 (defun org-table-current-field-formula (&optional key noerror)
9525 "Return the formula active for the current field.
9526 Assumes that specials are in place.
9527 If KEY is given, return the key to this formula.
9528 Otherwise return the formula preceeded with \"=\" or \":=\"."
9529 (let* ((name (car (rassoc (list (org-current-line)
9530 (org-table-current-column))
9531 org-table-named-field-locations)))
9532 (col (org-table-current-column))
9533 (scol (int-to-string col))
9534 (ref (format "@%d$%d" (org-table-current-dline) col))
9535 (stored-list (org-table-get-stored-formulas noerror))
9536 (ass (or (assoc name stored-list)
9537 (assoc ref stored-list)
9538 (assoc scol stored-list))))
9539 (if key
9540 (car ass)
9541 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9542 (cdr ass))))))
9544 (defun org-table-get-formula (&optional equation named)
9545 "Read a formula from the minibuffer, offer stored formula as default.
9546 When NAMED is non-nil, look for a named equation."
9547 (let* ((stored-list (org-table-get-stored-formulas))
9548 (name (car (rassoc (list (org-current-line)
9549 (org-table-current-column))
9550 org-table-named-field-locations)))
9551 (ref (format "@%d$%d" (org-table-current-dline)
9552 (org-table-current-column)))
9553 (refass (assoc ref stored-list))
9554 (scol (if named
9555 (if name name ref)
9556 (int-to-string (org-table-current-column))))
9557 (dummy (and (or name refass) (not named)
9558 (not (y-or-n-p "Replace field formula with column formula? " ))
9559 (error "Abort")))
9560 (name (or name ref))
9561 (org-table-may-need-update nil)
9562 (stored (cdr (assoc scol stored-list)))
9563 (eq (cond
9564 ((and stored equation (string-match "^ *=? *$" equation))
9565 stored)
9566 ((stringp equation)
9567 equation)
9568 (t (org-table-formula-from-user
9569 (read-string
9570 (org-table-formula-to-user
9571 (format "%s formula %s%s="
9572 (if named "Field" "Column")
9573 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9574 scol))
9575 (if stored (org-table-formula-to-user stored) "")
9576 'org-table-formula-history
9577 )))))
9578 mustsave)
9579 (when (not (string-match "\\S-" eq))
9580 ;; remove formula
9581 (setq stored-list (delq (assoc scol stored-list) stored-list))
9582 (org-table-store-formulas stored-list)
9583 (error "Formula removed"))
9584 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9585 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9586 (if (and name (not named))
9587 ;; We set the column equation, delete the named one.
9588 (setq stored-list (delq (assoc name stored-list) stored-list)
9589 mustsave t))
9590 (if stored
9591 (setcdr (assoc scol stored-list) eq)
9592 (setq stored-list (cons (cons scol eq) stored-list)))
9593 (if (or mustsave (not (equal stored eq)))
9594 (org-table-store-formulas stored-list))
9595 eq))
9597 (defun org-table-store-formulas (alist)
9598 "Store the list of formulas below the current table."
9599 (setq alist (sort alist 'org-table-formula-less-p))
9600 (save-excursion
9601 (goto-char (org-table-end))
9602 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9603 (progn
9604 ;; don't overwrite TBLFM, we might use text properties to store stuff
9605 (goto-char (match-beginning 2))
9606 (delete-region (match-beginning 2) (match-end 0)))
9607 (insert "#+TBLFM:"))
9608 (insert " "
9609 (mapconcat (lambda (x)
9610 (concat
9611 (if (equal (string-to-char (car x)) ?@) "" "$")
9612 (car x) "=" (cdr x)))
9613 alist "::")
9614 "\n")))
9616 (defsubst org-table-formula-make-cmp-string (a)
9617 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9618 (concat
9619 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9620 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9621 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9623 (defun org-table-formula-less-p (a b)
9624 "Compare two formulas for sorting."
9625 (let ((as (org-table-formula-make-cmp-string (car a)))
9626 (bs (org-table-formula-make-cmp-string (car b))))
9627 (and as bs (string< as bs))))
9629 (defun org-table-get-stored-formulas (&optional noerror)
9630 "Return an alist with the stored formulas directly after current table."
9631 (interactive)
9632 (let (scol eq eq-alist strings string seen)
9633 (save-excursion
9634 (goto-char (org-table-end))
9635 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9636 (setq strings (org-split-string (match-string 2) " *:: *"))
9637 (while (setq string (pop strings))
9638 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9639 (setq scol (if (match-end 2)
9640 (match-string 2 string)
9641 (match-string 1 string))
9642 eq (match-string 3 string)
9643 eq-alist (cons (cons scol eq) eq-alist))
9644 (if (member scol seen)
9645 (if noerror
9646 (progn
9647 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9648 (ding)
9649 (sit-for 2))
9650 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9651 (push scol seen))))))
9652 (nreverse eq-alist)))
9654 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9655 "Modify the equations after the table structure has been edited.
9656 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9657 For all numbers larger than LIMIT, shift them by DELTA."
9658 (save-excursion
9659 (goto-char (org-table-end))
9660 (when (looking-at "#\\+TBLFM:")
9661 (let ((re (concat key "\\([0-9]+\\)"))
9662 (re2
9663 (when remove
9664 (if (equal key "$")
9665 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9666 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9667 s n a)
9668 (when remove
9669 (while (re-search-forward re2 (point-at-eol) t)
9670 (replace-match "")))
9671 (while (re-search-forward re (point-at-eol) t)
9672 (setq s (match-string 1) n (string-to-number s))
9673 (cond
9674 ((setq a (assoc s replace))
9675 (replace-match (concat key (cdr a)) t t))
9676 ((and limit (> n limit))
9677 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9679 (defun org-table-get-specials ()
9680 "Get the column names and local parameters for this table."
9681 (save-excursion
9682 (let ((beg (org-table-begin)) (end (org-table-end))
9683 names name fields fields1 field cnt
9684 c v l line col types dlines hlines)
9685 (setq org-table-column-names nil
9686 org-table-local-parameters nil
9687 org-table-named-field-locations nil
9688 org-table-current-begin-line nil
9689 org-table-current-begin-pos nil
9690 org-table-current-line-types nil)
9691 (goto-char beg)
9692 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9693 (setq names (org-split-string (match-string 1) " *| *")
9694 cnt 1)
9695 (while (setq name (pop names))
9696 (setq cnt (1+ cnt))
9697 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9698 (push (cons name (int-to-string cnt)) org-table-column-names))))
9699 (setq org-table-column-names (nreverse org-table-column-names))
9700 (setq org-table-column-name-regexp
9701 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9702 (goto-char beg)
9703 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9704 (setq fields (org-split-string (match-string 1) " *| *"))
9705 (while (setq field (pop fields))
9706 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9707 (push (cons (match-string 1 field) (match-string 2 field))
9708 org-table-local-parameters))))
9709 (goto-char beg)
9710 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9711 (setq c (match-string 1)
9712 fields (org-split-string (match-string 2) " *| *"))
9713 (save-excursion
9714 (beginning-of-line (if (equal c "_") 2 0))
9715 (setq line (org-current-line) col 1)
9716 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9717 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9718 (while (and fields1 (setq field (pop fields)))
9719 (setq v (pop fields1) col (1+ col))
9720 (when (and (stringp field) (stringp v)
9721 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9722 (push (cons field v) org-table-local-parameters)
9723 (push (list field line col) org-table-named-field-locations))))
9724 ;; Analyse the line types
9725 (goto-char beg)
9726 (setq org-table-current-begin-line (org-current-line)
9727 org-table-current-begin-pos (point)
9728 l org-table-current-begin-line)
9729 (while (looking-at "[ \t]*|\\(-\\)?")
9730 (push (if (match-end 1) 'hline 'dline) types)
9731 (if (match-end 1) (push l hlines) (push l dlines))
9732 (beginning-of-line 2)
9733 (setq l (1+ l)))
9734 (setq org-table-current-line-types (apply 'vector (nreverse types))
9735 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9736 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9738 (defun org-table-maybe-eval-formula ()
9739 "Check if the current field starts with \"=\" or \":=\".
9740 If yes, store the formula and apply it."
9741 ;; We already know we are in a table. Get field will only return a formula
9742 ;; when appropriate. It might return a separator line, but no problem.
9743 (when org-table-formula-evaluate-inline
9744 (let* ((field (org-trim (or (org-table-get-field) "")))
9745 named eq)
9746 (when (string-match "^:?=\\(.*\\)" field)
9747 (setq named (equal (string-to-char field) ?:)
9748 eq (match-string 1 field))
9749 (if (or (fboundp 'calc-eval)
9750 (equal (substring eq 0 (min 2 (length eq))) "'("))
9751 (org-table-eval-formula (if named '(4) nil)
9752 (org-table-formula-from-user eq))
9753 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9755 (defvar org-recalc-commands nil
9756 "List of commands triggering the recalculation of a line.
9757 Will be filled automatically during use.")
9759 (defvar org-recalc-marks
9760 '((" " . "Unmarked: no special line, no automatic recalculation")
9761 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9762 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9763 ("!" . "Column name definition line. Reference in formula as $name.")
9764 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9765 ("_" . "Names for values in row below this one.")
9766 ("^" . "Names for values in row above this one.")))
9768 (defun org-table-rotate-recalc-marks (&optional newchar)
9769 "Rotate the recalculation mark in the first column.
9770 If in any row, the first field is not consistent with a mark,
9771 insert a new column for the markers.
9772 When there is an active region, change all the lines in the region,
9773 after prompting for the marking character.
9774 After each change, a message will be displayed indicating the meaning
9775 of the new mark."
9776 (interactive)
9777 (unless (org-at-table-p) (error "Not at a table"))
9778 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9779 (beg (org-table-begin))
9780 (end (org-table-end))
9781 (l (org-current-line))
9782 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9783 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9784 (have-col
9785 (save-excursion
9786 (goto-char beg)
9787 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9788 (col (org-table-current-column))
9789 (forcenew (car (assoc newchar org-recalc-marks)))
9790 epos new)
9791 (when l1
9792 (message "Change region to what mark? Type # * ! $ or SPC: ")
9793 (setq newchar (char-to-string (read-char-exclusive))
9794 forcenew (car (assoc newchar org-recalc-marks))))
9795 (if (and newchar (not forcenew))
9796 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9797 newchar))
9798 (if l1 (goto-line l1))
9799 (save-excursion
9800 (beginning-of-line 1)
9801 (unless (looking-at org-table-dataline-regexp)
9802 (error "Not at a table data line")))
9803 (unless have-col
9804 (org-table-goto-column 1)
9805 (org-table-insert-column)
9806 (org-table-goto-column (1+ col)))
9807 (setq epos (point-at-eol))
9808 (save-excursion
9809 (beginning-of-line 1)
9810 (org-table-get-field
9811 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9812 (concat " "
9813 (setq new (or forcenew
9814 (cadr (member (match-string 1) marks))))
9815 " ")
9816 " # ")))
9817 (if (and l1 l2)
9818 (progn
9819 (goto-line l1)
9820 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9821 (and (looking-at org-table-dataline-regexp)
9822 (org-table-get-field 1 (concat " " new " "))))
9823 (goto-line l1)))
9824 (if (not (= epos (point-at-eol))) (org-table-align))
9825 (goto-line l)
9826 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
9828 (defun org-table-maybe-recalculate-line ()
9829 "Recompute the current line if marked for it, and if we haven't just done it."
9830 (interactive)
9831 (and org-table-allow-automatic-line-recalculation
9832 (not (and (memq last-command org-recalc-commands)
9833 (equal org-last-recalc-line (org-current-line))))
9834 (save-excursion (beginning-of-line 1)
9835 (looking-at org-table-auto-recalculate-regexp))
9836 (org-table-recalculate) t))
9838 (defvar org-table-formula-debug nil
9839 "Non-nil means, debug table formulas.
9840 When nil, simply write \"#ERROR\" in corrupted fields.")
9841 (make-variable-buffer-local 'org-table-formula-debug)
9843 (defvar modes)
9844 (defsubst org-set-calc-mode (var &optional value)
9845 (if (stringp var)
9846 (setq var (assoc var '(("D" calc-angle-mode deg)
9847 ("R" calc-angle-mode rad)
9848 ("F" calc-prefer-frac t)
9849 ("S" calc-symbolic-mode t)))
9850 value (nth 2 var) var (nth 1 var)))
9851 (if (memq var modes)
9852 (setcar (cdr (memq var modes)) value)
9853 (cons var (cons value modes)))
9854 modes)
9856 (defun org-table-eval-formula (&optional arg equation
9857 suppress-align suppress-const
9858 suppress-store suppress-analysis)
9859 "Replace the table field value at the cursor by the result of a calculation.
9861 This function makes use of Dave Gillespie's Calc package, in my view the
9862 most exciting program ever written for GNU Emacs. So you need to have Calc
9863 installed in order to use this function.
9865 In a table, this command replaces the value in the current field with the
9866 result of a formula. It also installs the formula as the \"current\" column
9867 formula, by storing it in a special line below the table. When called
9868 with a `C-u' prefix, the current field must ba a named field, and the
9869 formula is installed as valid in only this specific field.
9871 When called with two `C-u' prefixes, insert the active equation
9872 for the field back into the current field, so that it can be
9873 edited there. This is useful in order to use \\[org-table-show-reference]
9874 to check the referenced fields.
9876 When called, the command first prompts for a formula, which is read in
9877 the minibuffer. Previously entered formulas are available through the
9878 history list, and the last used formula is offered as a default.
9879 These stored formulas are adapted correctly when moving, inserting, or
9880 deleting columns with the corresponding commands.
9882 The formula can be any algebraic expression understood by the Calc package.
9883 For details, see the Org-mode manual.
9885 This function can also be called from Lisp programs and offers
9886 additional arguments: EQUATION can be the formula to apply. If this
9887 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9888 used to speed-up recursive calls by by-passing unnecessary aligns.
9889 SUPPRESS-CONST suppresses the interpretation of constants in the
9890 formula, assuming that this has been done already outside the function.
9891 SUPPRESS-STORE means the formula should not be stored, either because
9892 it is already stored, or because it is a modified equation that should
9893 not overwrite the stored one."
9894 (interactive "P")
9895 (org-table-check-inside-data-field)
9896 (or suppress-analysis (org-table-get-specials))
9897 (if (equal arg '(16))
9898 (let ((eq (org-table-current-field-formula)))
9899 (or eq (error "No equation active for current field"))
9900 (org-table-get-field nil eq)
9901 (org-table-align)
9902 (setq org-table-may-need-update t))
9903 (let* (fields
9904 (ndown (if (integerp arg) arg 1))
9905 (org-table-automatic-realign nil)
9906 (case-fold-search nil)
9907 (down (> ndown 1))
9908 (formula (if (and equation suppress-store)
9909 equation
9910 (org-table-get-formula equation (equal arg '(4)))))
9911 (n0 (org-table-current-column))
9912 (modes (copy-sequence org-calc-default-modes))
9913 (numbers nil) ; was a variable, now fixed default
9914 (keep-empty nil)
9915 n form form0 bw fmt x ev orig c lispp literal)
9916 ;; Parse the format string. Since we have a lot of modes, this is
9917 ;; a lot of work. However, I think calc still uses most of the time.
9918 (if (string-match ";" formula)
9919 (let ((tmp (org-split-string formula ";")))
9920 (setq formula (car tmp)
9921 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9922 (nth 1 tmp)))
9923 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9924 (setq c (string-to-char (match-string 1 fmt))
9925 n (string-to-number (match-string 2 fmt)))
9926 (if (= c ?p)
9927 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9928 (setq modes (org-set-calc-mode
9929 'calc-float-format
9930 (list (cdr (assoc c '((?n . float) (?f . fix)
9931 (?s . sci) (?e . eng))))
9932 n))))
9933 (setq fmt (replace-match "" t t fmt)))
9934 (if (string-match "[NT]" fmt)
9935 (setq numbers (equal (match-string 0 fmt) "N")
9936 fmt (replace-match "" t t fmt)))
9937 (if (string-match "L" fmt)
9938 (setq literal t
9939 fmt (replace-match "" t t fmt)))
9940 (if (string-match "E" fmt)
9941 (setq keep-empty t
9942 fmt (replace-match "" t t fmt)))
9943 (while (string-match "[DRFS]" fmt)
9944 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9945 (setq fmt (replace-match "" t t fmt)))
9946 (unless (string-match "\\S-" fmt)
9947 (setq fmt nil))))
9948 (if (and (not suppress-const) org-table-formula-use-constants)
9949 (setq formula (org-table-formula-substitute-names formula)))
9950 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9951 (while (> ndown 0)
9952 (setq fields (org-split-string
9953 (org-no-properties
9954 (buffer-substring (point-at-bol) (point-at-eol)))
9955 " *| *"))
9956 (if (eq numbers t)
9957 (setq fields (mapcar
9958 (lambda (x) (number-to-string (string-to-number x)))
9959 fields)))
9960 (setq ndown (1- ndown))
9961 (setq form (copy-sequence formula)
9962 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9963 (if (and lispp literal) (setq lispp 'literal))
9964 ;; Check for old vertical references
9965 (setq form (org-rewrite-old-row-references form))
9966 ;; Insert complex ranges
9967 (while (string-match org-table-range-regexp form)
9968 (setq form
9969 (replace-match
9970 (save-match-data
9971 (org-table-make-reference
9972 (org-table-get-range (match-string 0 form) nil n0)
9973 keep-empty numbers lispp))
9974 t t form)))
9975 ;; Insert simple ranges
9976 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9977 (setq form
9978 (replace-match
9979 (save-match-data
9980 (org-table-make-reference
9981 (org-sublist
9982 fields (string-to-number (match-string 1 form))
9983 (string-to-number (match-string 2 form)))
9984 keep-empty numbers lispp))
9985 t t form)))
9986 (setq form0 form)
9987 ;; Insert the references to fields in same row
9988 (while (string-match "\\$\\([0-9]+\\)" form)
9989 (setq n (string-to-number (match-string 1 form))
9990 x (nth (1- (if (= n 0) n0 n)) fields))
9991 (unless x (error "Invalid field specifier \"%s\""
9992 (match-string 0 form)))
9993 (setq form (replace-match
9994 (save-match-data
9995 (org-table-make-reference x nil numbers lispp))
9996 t t form)))
9998 (if lispp
9999 (setq ev (condition-case nil
10000 (eval (eval (read form)))
10001 (error "#ERROR"))
10002 ev (if (numberp ev) (number-to-string ev) ev))
10003 (or (fboundp 'calc-eval)
10004 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10005 (setq ev (calc-eval (cons form modes)
10006 (if numbers 'num))))
10008 (when org-table-formula-debug
10009 (with-output-to-temp-buffer "*Substitution History*"
10010 (princ (format "Substitution history of formula
10011 Orig: %s
10012 $xyz-> %s
10013 @r$c-> %s
10014 $1-> %s\n" orig formula form0 form))
10015 (if (listp ev)
10016 (princ (format " %s^\nError: %s"
10017 (make-string (car ev) ?\-) (nth 1 ev)))
10018 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10019 ev (or fmt "NONE")
10020 (if fmt (format fmt (string-to-number ev)) ev)))))
10021 (setq bw (get-buffer-window "*Substitution History*"))
10022 (shrink-window-if-larger-than-buffer bw)
10023 (unless (and (interactive-p) (not ndown))
10024 (unless (let (inhibit-redisplay)
10025 (y-or-n-p "Debugging Formula. Continue to next? "))
10026 (org-table-align)
10027 (error "Abort"))
10028 (delete-window bw)
10029 (message "")))
10030 (if (listp ev) (setq fmt nil ev "#ERROR"))
10031 (org-table-justify-field-maybe
10032 (if fmt (format fmt (string-to-number ev)) ev))
10033 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10034 (call-interactively 'org-return)
10035 (setq ndown 0)))
10036 (and down (org-table-maybe-recalculate-line))
10037 (or suppress-align (and org-table-may-need-update
10038 (org-table-align))))))
10040 (defun org-table-put-field-property (prop value)
10041 (save-excursion
10042 (put-text-property (progn (skip-chars-backward "^|") (point))
10043 (progn (skip-chars-forward "^|") (point))
10044 prop value)))
10046 (defun org-table-get-range (desc &optional tbeg col highlight)
10047 "Get a calc vector from a column, accorting to descriptor DESC.
10048 Optional arguments TBEG and COL can give the beginning of the table and
10049 the current column, to avoid unnecessary parsing.
10050 HIGHLIGHT means, just highlight the range."
10051 (if (not (equal (string-to-char desc) ?@))
10052 (setq desc (concat "@" desc)))
10053 (save-excursion
10054 (or tbeg (setq tbeg (org-table-begin)))
10055 (or col (setq col (org-table-current-column)))
10056 (let ((thisline (org-current-line))
10057 beg end c1 c2 r1 r2 rangep tmp)
10058 (unless (string-match org-table-range-regexp desc)
10059 (error "Invalid table range specifier `%s'" desc))
10060 (setq rangep (match-end 3)
10061 r1 (and (match-end 1) (match-string 1 desc))
10062 r2 (and (match-end 4) (match-string 4 desc))
10063 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10064 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10066 (and c1 (setq c1 (+ (string-to-number c1)
10067 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10068 (and c2 (setq c2 (+ (string-to-number c2)
10069 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10070 (if (equal r1 "") (setq r1 nil))
10071 (if (equal r2 "") (setq r2 nil))
10072 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10073 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10074 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10075 (if (not r1) (setq r1 thisline))
10076 (if (not r2) (setq r2 thisline))
10077 (if (not c1) (setq c1 col))
10078 (if (not c2) (setq c2 col))
10079 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10080 ;; just one field
10081 (progn
10082 (goto-line r1)
10083 (while (not (looking-at org-table-dataline-regexp))
10084 (beginning-of-line 2))
10085 (prog1 (org-trim (org-table-get-field c1))
10086 (if highlight (org-table-highlight-rectangle (point) (point)))))
10087 ;; A range, return a vector
10088 ;; First sort the numbers to get a regular ractangle
10089 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10090 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10091 (goto-line r1)
10092 (while (not (looking-at org-table-dataline-regexp))
10093 (beginning-of-line 2))
10094 (org-table-goto-column c1)
10095 (setq beg (point))
10096 (goto-line r2)
10097 (while (not (looking-at org-table-dataline-regexp))
10098 (beginning-of-line 0))
10099 (org-table-goto-column c2)
10100 (setq end (point))
10101 (if highlight
10102 (org-table-highlight-rectangle
10103 beg (progn (skip-chars-forward "^|\n") (point))))
10104 ;; return string representation of calc vector
10105 (mapcar 'org-trim
10106 (apply 'append (org-table-copy-region beg end)))))))
10108 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10109 "Analyze descriptor DESC and retrieve the corresponding line number.
10110 The cursor is currently in line CLINE, the table begins in line BLINE,
10111 and TABLE is a vector with line types."
10112 (if (string-match "^[0-9]+$" desc)
10113 (aref org-table-dlines (string-to-number desc))
10114 (setq cline (or cline (org-current-line))
10115 bline (or bline org-table-current-begin-line)
10116 table (or table org-table-current-line-types))
10117 (if (or
10118 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10119 ;; 1 2 3 4 5 6
10120 (and (not (match-end 3)) (not (match-end 6)))
10121 (and (match-end 3) (match-end 6) (not (match-end 5))))
10122 (error "invalid row descriptor `%s'" desc))
10123 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10124 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10125 (odir (and (match-end 5) (match-string 5 desc)))
10126 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10127 (i (- cline bline))
10128 (rel (and (match-end 6)
10129 (or (and (match-end 1) (not (match-end 3)))
10130 (match-end 5)))))
10131 (if (and hn (not hdir))
10132 (progn
10133 (setq i 0 hdir "+")
10134 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10135 (if (and (not hn) on (not odir))
10136 (error "should never happen");;(aref org-table-dlines on)
10137 (if (and hn (> hn 0))
10138 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10139 (if on
10140 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10141 (+ bline i)))))
10143 (defun org-find-row-type (table i type backwards relative n)
10144 (let ((l (length table)))
10145 (while (> n 0)
10146 (while (and (setq i (+ i (if backwards -1 1)))
10147 (>= i 0) (< i l)
10148 (not (eq (aref table i) type))
10149 (if (and relative (eq (aref table i) 'hline))
10150 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10151 t)))
10152 (setq n (1- n)))
10153 (if (or (< i 0) (>= i l))
10154 (error "Row descriptior leads outside table")
10155 i)))
10157 (defun org-rewrite-old-row-references (s)
10158 (if (string-match "&[-+0-9I]" s)
10159 (error "Formula contains old &row reference, please rewrite using @-syntax")
10162 (defun org-table-make-reference (elements keep-empty numbers lispp)
10163 "Convert list ELEMENTS to something appropriate to insert into formula.
10164 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10165 NUMBERS indicates that everything should be converted to numbers.
10166 LISPP means to return something appropriate for a Lisp list."
10167 (if (stringp elements) ; just a single val
10168 (if lispp
10169 (if (eq lispp 'literal)
10170 elements
10171 (prin1-to-string (if numbers (string-to-number elements) elements)))
10172 (if (equal elements "") (setq elements "0"))
10173 (if numbers (number-to-string (string-to-number elements)) elements))
10174 (unless keep-empty
10175 (setq elements
10176 (delq nil
10177 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10178 elements))))
10179 (setq elements (or elements '("0")))
10180 (if lispp
10181 (mapconcat
10182 (lambda (x)
10183 (if (eq lispp 'literal)
10185 (prin1-to-string (if numbers (string-to-number x) x))))
10186 elements " ")
10187 (concat "[" (mapconcat
10188 (lambda (x)
10189 (if numbers (number-to-string (string-to-number x)) x))
10190 elements
10191 ",") "]"))))
10193 (defun org-table-recalculate (&optional all noalign)
10194 "Recalculate the current table line by applying all stored formulas.
10195 With prefix arg ALL, do this for all lines in the table."
10196 (interactive "P")
10197 (or (memq this-command org-recalc-commands)
10198 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10199 (unless (org-at-table-p) (error "Not at a table"))
10200 (if (equal all '(16))
10201 (org-table-iterate)
10202 (org-table-get-specials)
10203 (let* ((eqlist (sort (org-table-get-stored-formulas)
10204 (lambda (a b) (string< (car a) (car b)))))
10205 (inhibit-redisplay (not debug-on-error))
10206 (line-re org-table-dataline-regexp)
10207 (thisline (org-current-line))
10208 (thiscol (org-table-current-column))
10209 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10210 ;; Insert constants in all formulas
10211 (setq eqlist
10212 (mapcar (lambda (x)
10213 (setcdr x (org-table-formula-substitute-names (cdr x)))
10215 eqlist))
10216 ;; Split the equation list
10217 (while (setq eq (pop eqlist))
10218 (if (<= (string-to-char (car eq)) ?9)
10219 (push eq eqlnum)
10220 (push eq eqlname)))
10221 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10222 (if all
10223 (progn
10224 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10225 (goto-char (setq beg (org-table-begin)))
10226 (if (re-search-forward org-table-calculate-mark-regexp end t)
10227 ;; This is a table with marked lines, compute selected lines
10228 (setq line-re org-table-recalculate-regexp)
10229 ;; Move forward to the first non-header line
10230 (if (and (re-search-forward org-table-dataline-regexp end t)
10231 (re-search-forward org-table-hline-regexp end t)
10232 (re-search-forward org-table-dataline-regexp end t))
10233 (setq beg (match-beginning 0))
10234 nil))) ;; just leave beg where it is
10235 (setq beg (point-at-bol)
10236 end (move-marker (make-marker) (1+ (point-at-eol)))))
10237 (goto-char beg)
10238 (and all (message "Re-applying formulas to full table..."))
10240 ;; First find the named fields, and mark them untouchanble
10241 (remove-text-properties beg end '(org-untouchable t))
10242 (while (setq eq (pop eqlname))
10243 (setq name (car eq)
10244 a (assoc name org-table-named-field-locations))
10245 (and (not a)
10246 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10247 (setq a (list name
10248 (aref org-table-dlines
10249 (string-to-number (match-string 1 name)))
10250 (string-to-number (match-string 2 name)))))
10251 (when (and a (or all (equal (nth 1 a) thisline)))
10252 (message "Re-applying formula to field: %s" name)
10253 (goto-line (nth 1 a))
10254 (org-table-goto-column (nth 2 a))
10255 (push (append a (list (cdr eq))) eqlname1)
10256 (org-table-put-field-property :org-untouchable t)))
10258 ;; Now evauluate the column formulas, but skip fields covered by
10259 ;; field formulas
10260 (goto-char beg)
10261 (while (re-search-forward line-re end t)
10262 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10263 ;; Unprotected line, recalculate
10264 (and all (message "Re-applying formulas to full table...(line %d)"
10265 (setq cnt (1+ cnt))))
10266 (setq org-last-recalc-line (org-current-line))
10267 (setq eql eqlnum)
10268 (while (setq entry (pop eql))
10269 (goto-line org-last-recalc-line)
10270 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10271 (unless (get-text-property (point) :org-untouchable)
10272 (org-table-eval-formula nil (cdr entry)
10273 'noalign 'nocst 'nostore 'noanalysis)))))
10275 ;; Now evaluate the field formulas
10276 (while (setq eq (pop eqlname1))
10277 (message "Re-applying formula to field: %s" (car eq))
10278 (goto-line (nth 1 eq))
10279 (org-table-goto-column (nth 2 eq))
10280 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10281 'nostore 'noanalysis))
10283 (goto-line thisline)
10284 (org-table-goto-column thiscol)
10285 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10286 (or noalign (and org-table-may-need-update (org-table-align))
10287 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10289 ;; back to initial position
10290 (message "Re-applying formulas...done")
10291 (goto-line thisline)
10292 (org-table-goto-column thiscol)
10293 (or noalign (and org-table-may-need-update (org-table-align))
10294 (and all (message "Re-applying formulas...done"))))))
10296 (defun org-table-iterate (&optional arg)
10297 "Recalculate the table until it does not change anymore."
10298 (interactive "P")
10299 (let ((imax (if arg (prefix-numeric-value arg) 10))
10300 (i 0)
10301 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10302 thistbl)
10303 (catch 'exit
10304 (while (< i imax)
10305 (setq i (1+ i))
10306 (org-table-recalculate 'all)
10307 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10308 (if (not (string= lasttbl thistbl))
10309 (setq lasttbl thistbl)
10310 (if (> i 1)
10311 (message "Convergence after %d iterations" i)
10312 (message "Table was already stable"))
10313 (throw 'exit t)))
10314 (error "No convergence after %d iterations" i))))
10316 (defun org-table-formula-substitute-names (f)
10317 "Replace $const with values in string F."
10318 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10319 ;; First, check for column names
10320 (while (setq start (string-match org-table-column-name-regexp f start))
10321 (setq start (1+ start))
10322 (setq a (assoc (match-string 1 f) org-table-column-names))
10323 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10324 ;; Parameters and constants
10325 (setq start 0)
10326 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10327 (setq start (1+ start))
10328 (if (setq a (save-match-data
10329 (org-table-get-constant (match-string 1 f))))
10330 (setq f (replace-match
10331 (concat (if pp "(") a (if pp ")")) t t f))))
10332 (if org-table-formula-debug
10333 (put-text-property 0 (length f) :orig-formula f1 f))
10336 (defun org-table-get-constant (const)
10337 "Find the value for a parameter or constant in a formula.
10338 Parameters get priority."
10339 (or (cdr (assoc const org-table-local-parameters))
10340 (cdr (assoc const org-table-formula-constants-local))
10341 (cdr (assoc const org-table-formula-constants))
10342 (and (fboundp 'constants-get) (constants-get const))
10343 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10344 (org-entry-get nil (substring const 5) 'inherit))
10345 "#UNDEFINED_NAME"))
10347 (defvar org-table-fedit-map
10348 (let ((map (make-sparse-keymap)))
10349 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10350 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10351 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10352 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10353 (org-defkey map "\C-c?" 'org-table-show-reference)
10354 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10355 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10356 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10357 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10358 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10359 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10360 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10361 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10362 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10363 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10364 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10365 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10366 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10367 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10368 map))
10370 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10371 '("Edit-Formulas"
10372 ["Finish and Install" org-table-fedit-finish t]
10373 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10374 ["Abort" org-table-fedit-abort t]
10375 "--"
10376 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10377 ["Complete Lisp Symbol" lisp-complete-symbol t]
10378 "--"
10379 "Shift Reference at Point"
10380 ["Up" org-table-fedit-ref-up t]
10381 ["Down" org-table-fedit-ref-down t]
10382 ["Left" org-table-fedit-ref-left t]
10383 ["Right" org-table-fedit-ref-right t]
10385 "Change Test Row for Column Formulas"
10386 ["Up" org-table-fedit-line-up t]
10387 ["Down" org-table-fedit-line-down t]
10388 "--"
10389 ["Scroll Table Window" org-table-fedit-scroll t]
10390 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10391 ["Show Table Grid" org-table-fedit-toggle-coordinates
10392 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10393 org-table-overlay-coordinates)]
10394 "--"
10395 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10396 :style toggle :selected org-table-buffer-is-an]))
10398 (defvar org-pos)
10400 (defun org-table-edit-formulas ()
10401 "Edit the formulas of the current table in a separate buffer."
10402 (interactive)
10403 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10404 (beginning-of-line 0))
10405 (unless (org-at-table-p) (error "Not at a table"))
10406 (org-table-get-specials)
10407 (let ((key (org-table-current-field-formula 'key 'noerror))
10408 (eql (sort (org-table-get-stored-formulas 'noerror)
10409 'org-table-formula-less-p))
10410 (pos (move-marker (make-marker) (point)))
10411 (startline 1)
10412 (wc (current-window-configuration))
10413 (titles '((column . "# Column Formulas\n")
10414 (field . "# Field Formulas\n")
10415 (named . "# Named Field Formulas\n")))
10416 entry s type title)
10417 (org-switch-to-buffer-other-window "*Edit Formulas*")
10418 (erase-buffer)
10419 ;; Keep global-font-lock-mode from turning on font-lock-mode
10420 (let ((font-lock-global-modes '(not fundamental-mode)))
10421 (fundamental-mode))
10422 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10423 (org-set-local 'org-pos pos)
10424 (org-set-local 'org-window-configuration wc)
10425 (use-local-map org-table-fedit-map)
10426 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10427 (easy-menu-add org-table-fedit-menu)
10428 (setq startline (org-current-line))
10429 (while (setq entry (pop eql))
10430 (setq type (cond
10431 ((equal (string-to-char (car entry)) ?@) 'field)
10432 ((string-match "^[0-9]" (car entry)) 'column)
10433 (t 'named)))
10434 (when (setq title (assq type titles))
10435 (or (bobp) (insert "\n"))
10436 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10437 (setq titles (delq title titles)))
10438 (if (equal key (car entry)) (setq startline (org-current-line)))
10439 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10440 (car entry) " = " (cdr entry) "\n"))
10441 (remove-text-properties 0 (length s) '(face nil) s)
10442 (insert s))
10443 (if (eq org-table-use-standard-references t)
10444 (org-table-fedit-toggle-ref-type))
10445 (goto-line startline)
10446 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10448 (defun org-table-fedit-post-command ()
10449 (when (not (memq this-command '(lisp-complete-symbol)))
10450 (let ((win (selected-window)))
10451 (save-excursion
10452 (condition-case nil
10453 (org-table-show-reference)
10454 (error nil))
10455 (select-window win)))))
10457 (defun org-table-formula-to-user (s)
10458 "Convert a formula from internal to user representation."
10459 (if (eq org-table-use-standard-references t)
10460 (org-table-convert-refs-to-an s)
10463 (defun org-table-formula-from-user (s)
10464 "Convert a formula from user to internal representation."
10465 (if org-table-use-standard-references
10466 (org-table-convert-refs-to-rc s)
10469 (defun org-table-convert-refs-to-rc (s)
10470 "Convert spreadsheet references from AB7 to @7$28.
10471 Works for single references, but also for entire formulas and even the
10472 full TBLFM line."
10473 (let ((start 0))
10474 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10475 (cond
10476 ((match-end 3)
10477 ;; format match, just advance
10478 (setq start (match-end 0)))
10479 ((and (> (match-beginning 0) 0)
10480 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10481 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10482 ;; 3.e5 or something like this.
10483 (setq start (match-end 0)))
10485 (setq start (match-beginning 0)
10486 s (replace-match
10487 (if (equal (match-string 2 s) "&")
10488 (format "$%d" (org-letters-to-number (match-string 1 s)))
10489 (format "@%d$%d"
10490 (string-to-number (match-string 2 s))
10491 (org-letters-to-number (match-string 1 s))))
10492 t t s)))))
10495 (defun org-table-convert-refs-to-an (s)
10496 "Convert spreadsheet references from to @7$28 to AB7.
10497 Works for single references, but also for entire formulas and even the
10498 full TBLFM line."
10499 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10500 (setq s (replace-match
10501 (format "%s%d"
10502 (org-number-to-letters
10503 (string-to-number (match-string 2 s)))
10504 (string-to-number (match-string 1 s)))
10505 t t s)))
10506 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10507 (setq s (replace-match (concat "\\1"
10508 (org-number-to-letters
10509 (string-to-number (match-string 2 s))) "&")
10510 t nil s)))
10513 (defun org-letters-to-number (s)
10514 "Convert a base 26 number represented by letters into an integer.
10515 For example: AB -> 28."
10516 (let ((n 0))
10517 (setq s (upcase s))
10518 (while (> (length s) 0)
10519 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10520 s (substring s 1)))
10523 (defun org-number-to-letters (n)
10524 "Convert an integer into a base 26 number represented by letters.
10525 For example: 28 -> AB."
10526 (let ((s ""))
10527 (while (> n 0)
10528 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10529 n (/ (1- n) 26)))
10532 (defun org-table-fedit-convert-buffer (function)
10533 "Convert all references in this buffer, using FUNTION."
10534 (let ((line (org-current-line)))
10535 (goto-char (point-min))
10536 (while (not (eobp))
10537 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10538 (delete-region (point) (point-at-eol))
10539 (or (eobp) (forward-char 1)))
10540 (goto-line line)))
10542 (defun org-table-fedit-toggle-ref-type ()
10543 "Convert all references in the buffer from B3 to @3$2 and back."
10544 (interactive)
10545 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10546 (org-table-fedit-convert-buffer
10547 (if org-table-buffer-is-an
10548 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10549 (message "Reference type switched to %s"
10550 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10552 (defun org-table-fedit-ref-up ()
10553 "Shift the reference at point one row/hline up."
10554 (interactive)
10555 (org-table-fedit-shift-reference 'up))
10556 (defun org-table-fedit-ref-down ()
10557 "Shift the reference at point one row/hline down."
10558 (interactive)
10559 (org-table-fedit-shift-reference 'down))
10560 (defun org-table-fedit-ref-left ()
10561 "Shift the reference at point one field to the left."
10562 (interactive)
10563 (org-table-fedit-shift-reference 'left))
10564 (defun org-table-fedit-ref-right ()
10565 "Shift the reference at point one field to the right."
10566 (interactive)
10567 (org-table-fedit-shift-reference 'right))
10569 (defun org-table-fedit-shift-reference (dir)
10570 (cond
10571 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10572 (if (memq dir '(left right))
10573 (org-rematch-and-replace 1 (eq dir 'left))
10574 (error "Cannot shift reference in this direction")))
10575 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10576 ;; A B3-like reference
10577 (if (memq dir '(up down))
10578 (org-rematch-and-replace 2 (eq dir 'up))
10579 (org-rematch-and-replace 1 (eq dir 'left))))
10580 ((org-at-regexp-p
10581 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10582 ;; An internal reference
10583 (if (memq dir '(up down))
10584 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10585 (org-rematch-and-replace 5 (eq dir 'left))))))
10587 (defun org-rematch-and-replace (n &optional decr hline)
10588 "Re-match the group N, and replace it with the shifted refrence."
10589 (or (match-end n) (error "Cannot shift reference in this direction"))
10590 (goto-char (match-beginning n))
10591 (and (looking-at (regexp-quote (match-string n)))
10592 (replace-match (org-shift-refpart (match-string 0) decr hline)
10593 t t)))
10595 (defun org-shift-refpart (ref &optional decr hline)
10596 "Shift a refrence part REF.
10597 If DECR is set, decrease the references row/column, else increase.
10598 If HLINE is set, this may be a hline reference, it certainly is not
10599 a translation reference."
10600 (save-match-data
10601 (let* ((sign (string-match "^[-+]" ref)) n)
10603 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10604 (cond
10605 ((and hline (string-match "^I+" ref))
10606 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10607 (setq n (+ n (if decr -1 1)))
10608 (if (= n 0) (setq n (+ n (if decr -1 1))))
10609 (if sign
10610 (setq sign (if (< n 0) "-" "+") n (abs n))
10611 (setq n (max 1 n)))
10612 (concat sign (make-string n ?I)))
10614 ((string-match "^[0-9]+" ref)
10615 (setq n (string-to-number (concat sign ref)))
10616 (setq n (+ n (if decr -1 1)))
10617 (if sign
10618 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10619 (number-to-string (max 1 n))))
10621 ((string-match "^[a-zA-Z]+" ref)
10622 (org-number-to-letters
10623 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10625 (t (error "Cannot shift reference"))))))
10627 (defun org-table-fedit-toggle-coordinates ()
10628 "Toggle the display of coordinates in the refrenced table."
10629 (interactive)
10630 (let ((pos (marker-position org-pos)))
10631 (with-current-buffer (marker-buffer org-pos)
10632 (save-excursion
10633 (goto-char pos)
10634 (org-table-toggle-coordinate-overlays)))))
10636 (defun org-table-fedit-finish (&optional arg)
10637 "Parse the buffer for formula definitions and install them.
10638 With prefix ARG, apply the new formulas to the table."
10639 (interactive "P")
10640 (org-table-remove-rectangle-highlight)
10641 (if org-table-use-standard-references
10642 (progn
10643 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10644 (setq org-table-buffer-is-an nil)))
10645 (let ((pos org-pos) eql var form)
10646 (goto-char (point-min))
10647 (while (re-search-forward
10648 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10649 nil t)
10650 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10651 form (match-string 3))
10652 (setq form (org-trim form))
10653 (when (not (equal form ""))
10654 (while (string-match "[ \t]*\n[ \t]*" form)
10655 (setq form (replace-match " " t t form)))
10656 (when (assoc var eql)
10657 (error "Double formulas for %s" var))
10658 (push (cons var form) eql)))
10659 (setq org-pos nil)
10660 (set-window-configuration org-window-configuration)
10661 (select-window (get-buffer-window (marker-buffer pos)))
10662 (goto-char pos)
10663 (unless (org-at-table-p)
10664 (error "Lost table position - cannot install formulae"))
10665 (org-table-store-formulas eql)
10666 (move-marker pos nil)
10667 (kill-buffer "*Edit Formulas*")
10668 (if arg
10669 (org-table-recalculate 'all)
10670 (message "New formulas installed - press C-u C-c C-c to apply."))))
10672 (defun org-table-fedit-abort ()
10673 "Abort editing formulas, without installing the changes."
10674 (interactive)
10675 (org-table-remove-rectangle-highlight)
10676 (let ((pos org-pos))
10677 (set-window-configuration org-window-configuration)
10678 (select-window (get-buffer-window (marker-buffer pos)))
10679 (goto-char pos)
10680 (move-marker pos nil)
10681 (message "Formula editing aborted without installing changes")))
10683 (defun org-table-fedit-lisp-indent ()
10684 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10685 (interactive)
10686 (let ((pos (point)) beg end ind)
10687 (beginning-of-line 1)
10688 (cond
10689 ((looking-at "[ \t]")
10690 (goto-char pos)
10691 (call-interactively 'lisp-indent-line))
10692 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10693 ((not (fboundp 'pp-buffer))
10694 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10695 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10696 (goto-char (- (match-end 0) 2))
10697 (setq beg (point))
10698 (setq ind (make-string (current-column) ?\ ))
10699 (condition-case nil (forward-sexp 1)
10700 (error
10701 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10702 (setq end (point))
10703 (save-restriction
10704 (narrow-to-region beg end)
10705 (if (eq last-command this-command)
10706 (progn
10707 (goto-char (point-min))
10708 (setq this-command nil)
10709 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10710 (replace-match " ")))
10711 (pp-buffer)
10712 (untabify (point-min) (point-max))
10713 (goto-char (1+ (point-min)))
10714 (while (re-search-forward "^." nil t)
10715 (beginning-of-line 1)
10716 (insert ind))
10717 (goto-char (point-max))
10718 (backward-delete-char 1)))
10719 (goto-char beg))
10720 (t nil))))
10722 (defvar org-show-positions nil)
10724 (defun org-table-show-reference (&optional local)
10725 "Show the location/value of the $ expression at point."
10726 (interactive)
10727 (org-table-remove-rectangle-highlight)
10728 (catch 'exit
10729 (let ((pos (if local (point) org-pos))
10730 (face2 'highlight)
10731 (org-inhibit-highlight-removal t)
10732 (win (selected-window))
10733 (org-show-positions nil)
10734 var name e what match dest)
10735 (if local (org-table-get-specials))
10736 (setq what (cond
10737 ((or (org-at-regexp-p org-table-range-regexp2)
10738 (org-at-regexp-p org-table-translate-regexp)
10739 (org-at-regexp-p org-table-range-regexp))
10740 (setq match
10741 (save-match-data
10742 (org-table-convert-refs-to-rc (match-string 0))))
10743 'range)
10744 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10745 ((org-at-regexp-p "\\$[0-9]+") 'column)
10746 ((not local) nil)
10747 (t (error "No reference at point")))
10748 match (and what (or match (match-string 0))))
10749 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10750 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10751 'secondary-selection))
10752 (org-add-hook 'before-change-functions
10753 'org-table-remove-rectangle-highlight)
10754 (if (eq what 'name) (setq var (substring match 1)))
10755 (when (eq what 'range)
10756 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10757 (setq match (org-table-formula-substitute-names match)))
10758 (unless local
10759 (save-excursion
10760 (end-of-line 1)
10761 (re-search-backward "^\\S-" nil t)
10762 (beginning-of-line 1)
10763 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10764 (setq dest
10765 (save-match-data
10766 (org-table-convert-refs-to-rc (match-string 1))))
10767 (org-table-add-rectangle-overlay
10768 (match-beginning 1) (match-end 1) face2))))
10769 (if (and (markerp pos) (marker-buffer pos))
10770 (if (get-buffer-window (marker-buffer pos))
10771 (select-window (get-buffer-window (marker-buffer pos)))
10772 (org-switch-to-buffer-other-window (get-buffer-window
10773 (marker-buffer pos)))))
10774 (goto-char pos)
10775 (org-table-force-dataline)
10776 (when dest
10777 (setq name (substring dest 1))
10778 (cond
10779 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10780 (setq e (assoc name org-table-named-field-locations))
10781 (goto-line (nth 1 e))
10782 (org-table-goto-column (nth 2 e)))
10783 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10784 (let ((l (string-to-number (match-string 1 dest)))
10785 (c (string-to-number (match-string 2 dest))))
10786 (goto-line (aref org-table-dlines l))
10787 (org-table-goto-column c)))
10788 (t (org-table-goto-column (string-to-number name))))
10789 (move-marker pos (point))
10790 (org-table-highlight-rectangle nil nil face2))
10791 (cond
10792 ((equal dest match))
10793 ((not match))
10794 ((eq what 'range)
10795 (condition-case nil
10796 (save-excursion
10797 (org-table-get-range match nil nil 'highlight))
10798 (error nil)))
10799 ((setq e (assoc var org-table-named-field-locations))
10800 (goto-line (nth 1 e))
10801 (org-table-goto-column (nth 2 e))
10802 (org-table-highlight-rectangle (point) (point))
10803 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10804 ((setq e (assoc var org-table-column-names))
10805 (org-table-goto-column (string-to-number (cdr e)))
10806 (org-table-highlight-rectangle (point) (point))
10807 (goto-char (org-table-begin))
10808 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10809 (org-table-end) t)
10810 (progn
10811 (goto-char (match-beginning 1))
10812 (org-table-highlight-rectangle)
10813 (message "Named column (column %s)" (cdr e)))
10814 (error "Column name not found")))
10815 ((eq what 'column)
10816 ;; column number
10817 (org-table-goto-column (string-to-number (substring match 1)))
10818 (org-table-highlight-rectangle (point) (point))
10819 (message "Column %s" (substring match 1)))
10820 ((setq e (assoc var org-table-local-parameters))
10821 (goto-char (org-table-begin))
10822 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10823 (progn
10824 (goto-char (match-beginning 1))
10825 (org-table-highlight-rectangle)
10826 (message "Local parameter."))
10827 (error "Parameter not found")))
10829 (cond
10830 ((not var) (error "No reference at point"))
10831 ((setq e (assoc var org-table-formula-constants-local))
10832 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10833 var (cdr e)))
10834 ((setq e (assoc var org-table-formula-constants))
10835 (message "Constant: $%s=%s in `org-table-formula-constants'."
10836 var (cdr e)))
10837 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10838 (message "Constant: $%s=%s, from `constants.el'%s."
10839 var e (format " (%s units)" constants-unit-system)))
10840 (t (error "Undefined name $%s" var)))))
10841 (goto-char pos)
10842 (when (and org-show-positions
10843 (not (memq this-command '(org-table-fedit-scroll
10844 org-table-fedit-scroll-down))))
10845 (push pos org-show-positions)
10846 (push org-table-current-begin-pos org-show-positions)
10847 (let ((min (apply 'min org-show-positions))
10848 (max (apply 'max org-show-positions)))
10849 (goto-char min) (recenter 0)
10850 (goto-char max)
10851 (or (pos-visible-in-window-p max) (recenter -1))))
10852 (select-window win))))
10854 (defun org-table-force-dataline ()
10855 "Make sure the cursor is in a dataline in a table."
10856 (unless (save-excursion
10857 (beginning-of-line 1)
10858 (looking-at org-table-dataline-regexp))
10859 (let* ((re org-table-dataline-regexp)
10860 (p1 (save-excursion (re-search-forward re nil 'move)))
10861 (p2 (save-excursion (re-search-backward re nil 'move))))
10862 (cond ((and p1 p2)
10863 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10864 p1 p2)))
10865 ((or p1 p2) (goto-char (or p1 p2)))
10866 (t (error "No table dataline around here"))))))
10868 (defun org-table-fedit-line-up ()
10869 "Move cursor one line up in the window showing the table."
10870 (interactive)
10871 (org-table-fedit-move 'previous-line))
10873 (defun org-table-fedit-line-down ()
10874 "Move cursor one line down in the window showing the table."
10875 (interactive)
10876 (org-table-fedit-move 'next-line))
10878 (defun org-table-fedit-move (command)
10879 "Move the cursor in the window shoinw the table.
10880 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10881 (let ((org-table-allow-automatic-line-recalculation nil)
10882 (pos org-pos) (win (selected-window)) p)
10883 (select-window (get-buffer-window (marker-buffer org-pos)))
10884 (setq p (point))
10885 (call-interactively command)
10886 (while (and (org-at-table-p)
10887 (org-at-table-hline-p))
10888 (call-interactively command))
10889 (or (org-at-table-p) (goto-char p))
10890 (move-marker pos (point))
10891 (select-window win)))
10893 (defun org-table-fedit-scroll (N)
10894 (interactive "p")
10895 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10896 (scroll-other-window N)))
10898 (defun org-table-fedit-scroll-down (N)
10899 (interactive "p")
10900 (org-table-fedit-scroll (- N)))
10902 (defvar org-table-rectangle-overlays nil)
10904 (defun org-table-add-rectangle-overlay (beg end &optional face)
10905 "Add a new overlay."
10906 (let ((ov (org-make-overlay beg end)))
10907 (org-overlay-put ov 'face (or face 'secondary-selection))
10908 (push ov org-table-rectangle-overlays)))
10910 (defun org-table-highlight-rectangle (&optional beg end face)
10911 "Highlight rectangular region in a table."
10912 (setq beg (or beg (point)) end (or end (point)))
10913 (let ((b (min beg end))
10914 (e (max beg end))
10915 l1 c1 l2 c2 tmp)
10916 (and (boundp 'org-show-positions)
10917 (setq org-show-positions (cons b (cons e org-show-positions))))
10918 (goto-char (min beg end))
10919 (setq l1 (org-current-line)
10920 c1 (org-table-current-column))
10921 (goto-char (max beg end))
10922 (setq l2 (org-current-line)
10923 c2 (org-table-current-column))
10924 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10925 (goto-line l1)
10926 (beginning-of-line 1)
10927 (loop for line from l1 to l2 do
10928 (when (looking-at org-table-dataline-regexp)
10929 (org-table-goto-column c1)
10930 (skip-chars-backward "^|\n") (setq beg (point))
10931 (org-table-goto-column c2)
10932 (skip-chars-forward "^|\n") (setq end (point))
10933 (org-table-add-rectangle-overlay beg end face))
10934 (beginning-of-line 2))
10935 (goto-char b))
10936 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10938 (defun org-table-remove-rectangle-highlight (&rest ignore)
10939 "Remove the rectangle overlays."
10940 (unless org-inhibit-highlight-removal
10941 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10942 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10943 (setq org-table-rectangle-overlays nil)))
10945 (defvar org-table-coordinate-overlays nil
10946 "Collects the cooordinate grid overlays, so that they can be removed.")
10947 (make-variable-buffer-local 'org-table-coordinate-overlays)
10949 (defun org-table-overlay-coordinates ()
10950 "Add overlays to the table at point, to show row/column coordinates."
10951 (interactive)
10952 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10953 (setq org-table-coordinate-overlays nil)
10954 (save-excursion
10955 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10956 (goto-char (org-table-begin))
10957 (while (org-at-table-p)
10958 (setq eol (point-at-eol))
10959 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10960 (push ov org-table-coordinate-overlays)
10961 (setq hline (looking-at org-table-hline-regexp))
10962 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10963 (format "%4d" (setq id (1+ id)))))
10964 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10965 (when hline
10966 (setq ic 0)
10967 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10968 (setq beg (1+ (match-beginning 0))
10969 ic (1+ ic)
10970 s1 (concat "$" (int-to-string ic))
10971 s2 (org-number-to-letters ic)
10972 str (if (eq org-table-use-standard-references t) s2 s1))
10973 (setq ov (org-make-overlay beg (+ beg (length str))))
10974 (push ov org-table-coordinate-overlays)
10975 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10976 (beginning-of-line 2)))))
10978 (defun org-table-toggle-coordinate-overlays ()
10979 "Toggle the display of Row/Column numbers in tables."
10980 (interactive)
10981 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10982 (message "Row/Column number display turned %s"
10983 (if org-table-overlay-coordinates "on" "off"))
10984 (if (and (org-at-table-p) org-table-overlay-coordinates)
10985 (org-table-align))
10986 (unless org-table-overlay-coordinates
10987 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10988 (setq org-table-coordinate-overlays nil)))
10990 (defun org-table-toggle-formula-debugger ()
10991 "Toggle the formula debugger in tables."
10992 (interactive)
10993 (setq org-table-formula-debug (not org-table-formula-debug))
10994 (message "Formula debugging has been turned %s"
10995 (if org-table-formula-debug "on" "off")))
10997 ;;; The orgtbl minor mode
10999 ;; Define a minor mode which can be used in other modes in order to
11000 ;; integrate the org-mode table editor.
11002 ;; This is really a hack, because the org-mode table editor uses several
11003 ;; keys which normally belong to the major mode, for example the TAB and
11004 ;; RET keys. Here is how it works: The minor mode defines all the keys
11005 ;; necessary to operate the table editor, but wraps the commands into a
11006 ;; function which tests if the cursor is currently inside a table. If that
11007 ;; is the case, the table editor command is executed. However, when any of
11008 ;; those keys is used outside a table, the function uses `key-binding' to
11009 ;; look up if the key has an associated command in another currently active
11010 ;; keymap (minor modes, major mode, global), and executes that command.
11011 ;; There might be problems if any of the keys used by the table editor is
11012 ;; otherwise used as a prefix key.
11014 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11015 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11016 ;; addresses this by checking explicitly for both bindings.
11018 ;; The optimized version (see variable `orgtbl-optimized') takes over
11019 ;; all keys which are bound to `self-insert-command' in the *global map*.
11020 ;; Some modes bind other commands to simple characters, for example
11021 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11022 ;; active, this binding is ignored inside tables and replaced with a
11023 ;; modified self-insert.
11025 (defvar orgtbl-mode nil
11026 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11027 table editor in arbitrary modes.")
11028 (make-variable-buffer-local 'orgtbl-mode)
11030 (defvar orgtbl-mode-map (make-keymap)
11031 "Keymap for `orgtbl-mode'.")
11033 ;;;###autoload
11034 (defun turn-on-orgtbl ()
11035 "Unconditionally turn on `orgtbl-mode'."
11036 (orgtbl-mode 1))
11038 (defvar org-old-auto-fill-inhibit-regexp nil
11039 "Local variable used by `orgtbl-mode'")
11041 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11042 "Matches a line belonging to an orgtbl.")
11044 (defconst orgtbl-extra-font-lock-keywords
11045 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11046 0 (quote 'org-table) 'prepend))
11047 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11049 ;;;###autoload
11050 (defun orgtbl-mode (&optional arg)
11051 "The `org-mode' table editor as a minor mode for use in other modes."
11052 (interactive)
11053 (if (org-mode-p)
11054 ;; Exit without error, in case some hook functions calls this
11055 ;; by accident in org-mode.
11056 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11057 (setq orgtbl-mode
11058 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11059 (if orgtbl-mode
11060 (progn
11061 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11062 ;; Make sure we are first in minor-mode-map-alist
11063 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11064 (and c (setq minor-mode-map-alist
11065 (cons c (delq c minor-mode-map-alist)))))
11066 (org-set-local (quote org-table-may-need-update) t)
11067 (org-add-hook 'before-change-functions 'org-before-change-function
11068 nil 'local)
11069 (org-set-local 'org-old-auto-fill-inhibit-regexp
11070 auto-fill-inhibit-regexp)
11071 (org-set-local 'auto-fill-inhibit-regexp
11072 (if auto-fill-inhibit-regexp
11073 (concat orgtbl-line-start-regexp "\\|"
11074 auto-fill-inhibit-regexp)
11075 orgtbl-line-start-regexp))
11076 (org-add-to-invisibility-spec '(org-cwidth))
11077 (when (fboundp 'font-lock-add-keywords)
11078 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11079 (org-restart-font-lock))
11080 (easy-menu-add orgtbl-mode-menu)
11081 (run-hooks 'orgtbl-mode-hook))
11082 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11083 (org-cleanup-narrow-column-properties)
11084 (org-remove-from-invisibility-spec '(org-cwidth))
11085 (remove-hook 'before-change-functions 'org-before-change-function t)
11086 (when (fboundp 'font-lock-remove-keywords)
11087 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11088 (org-restart-font-lock))
11089 (easy-menu-remove orgtbl-mode-menu)
11090 (force-mode-line-update 'all))))
11092 (defun org-cleanup-narrow-column-properties ()
11093 "Remove all properties related to narrow-column invisibility."
11094 (let ((s 1))
11095 (while (setq s (text-property-any s (point-max)
11096 'display org-narrow-column-arrow))
11097 (remove-text-properties s (1+ s) '(display t)))
11098 (setq s 1)
11099 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11100 (remove-text-properties s (1+ s) '(org-cwidth t)))
11101 (setq s 1)
11102 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11103 (remove-text-properties s (1+ s) '(invisible t)))))
11105 ;; Install it as a minor mode.
11106 (put 'orgtbl-mode :included t)
11107 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11108 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11110 (defun orgtbl-make-binding (fun n &rest keys)
11111 "Create a function for binding in the table minor mode.
11112 FUN is the command to call inside a table. N is used to create a unique
11113 command name. KEYS are keys that should be checked in for a command
11114 to execute outside of tables."
11115 (eval
11116 (list 'defun
11117 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11118 '(arg)
11119 (concat "In tables, run `" (symbol-name fun) "'.\n"
11120 "Outside of tables, run the binding of `"
11121 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11122 "'.")
11123 '(interactive "p")
11124 (list 'if
11125 '(org-at-table-p)
11126 (list 'call-interactively (list 'quote fun))
11127 (list 'let '(orgtbl-mode)
11128 (list 'call-interactively
11129 (append '(or)
11130 (mapcar (lambda (k)
11131 (list 'key-binding k))
11132 keys)
11133 '('orgtbl-error))))))))
11135 (defun orgtbl-error ()
11136 "Error when there is no default binding for a table key."
11137 (interactive)
11138 (error "This key has no function outside tables"))
11140 (defun orgtbl-setup ()
11141 "Setup orgtbl keymaps."
11142 (let ((nfunc 0)
11143 (bindings
11144 (list
11145 '([(meta shift left)] org-table-delete-column)
11146 '([(meta left)] org-table-move-column-left)
11147 '([(meta right)] org-table-move-column-right)
11148 '([(meta shift right)] org-table-insert-column)
11149 '([(meta shift up)] org-table-kill-row)
11150 '([(meta shift down)] org-table-insert-row)
11151 '([(meta up)] org-table-move-row-up)
11152 '([(meta down)] org-table-move-row-down)
11153 '("\C-c\C-w" org-table-cut-region)
11154 '("\C-c\M-w" org-table-copy-region)
11155 '("\C-c\C-y" org-table-paste-rectangle)
11156 '("\C-c-" org-table-insert-hline)
11157 '("\C-c}" org-table-toggle-coordinate-overlays)
11158 '("\C-c{" org-table-toggle-formula-debugger)
11159 '("\C-m" org-table-next-row)
11160 '([(shift return)] org-table-copy-down)
11161 '("\C-c\C-q" org-table-wrap-region)
11162 '("\C-c?" org-table-field-info)
11163 '("\C-c " org-table-blank-field)
11164 '("\C-c+" org-table-sum)
11165 '("\C-c=" org-table-eval-formula)
11166 '("\C-c'" org-table-edit-formulas)
11167 '("\C-c`" org-table-edit-field)
11168 '("\C-c*" org-table-recalculate)
11169 '("\C-c|" org-table-create-or-convert-from-region)
11170 '("\C-c^" org-table-sort-lines)
11171 '([(control ?#)] org-table-rotate-recalc-marks)))
11172 elt key fun cmd)
11173 (while (setq elt (pop bindings))
11174 (setq nfunc (1+ nfunc))
11175 (setq key (org-key (car elt))
11176 fun (nth 1 elt)
11177 cmd (orgtbl-make-binding fun nfunc key))
11178 (org-defkey orgtbl-mode-map key cmd))
11180 ;; Special treatment needed for TAB and RET
11181 (org-defkey orgtbl-mode-map [(return)]
11182 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11183 (org-defkey orgtbl-mode-map "\C-m"
11184 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11186 (org-defkey orgtbl-mode-map [(tab)]
11187 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11188 (org-defkey orgtbl-mode-map "\C-i"
11189 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11191 (org-defkey orgtbl-mode-map [(shift tab)]
11192 (orgtbl-make-binding 'org-table-previous-field 104
11193 [(shift tab)] [(tab)] "\C-i"))
11195 (org-defkey orgtbl-mode-map "\M-\C-m"
11196 (orgtbl-make-binding 'org-table-wrap-region 105
11197 "\M-\C-m" [(meta return)]))
11198 (org-defkey orgtbl-mode-map [(meta return)]
11199 (orgtbl-make-binding 'org-table-wrap-region 106
11200 [(meta return)] "\M-\C-m"))
11202 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11203 (when orgtbl-optimized
11204 ;; If the user wants maximum table support, we need to hijack
11205 ;; some standard editing functions
11206 (org-remap orgtbl-mode-map
11207 'self-insert-command 'orgtbl-self-insert-command
11208 'delete-char 'org-delete-char
11209 'delete-backward-char 'org-delete-backward-char)
11210 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11211 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11212 '("OrgTbl"
11213 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11214 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11215 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11216 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11217 "--"
11218 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11219 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11220 ["Copy Field from Above"
11221 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11222 "--"
11223 ("Column"
11224 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11225 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11226 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11227 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11228 ("Row"
11229 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11230 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11231 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11232 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11233 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11234 "--"
11235 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11236 ("Rectangle"
11237 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11238 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11239 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11240 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11241 "--"
11242 ("Radio tables"
11243 ["Insert table template" orgtbl-insert-radio-table
11244 (assq major-mode orgtbl-radio-table-templates)]
11245 ["Comment/uncomment table" orgtbl-toggle-comment t])
11246 "--"
11247 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11248 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11249 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11250 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11251 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11252 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11253 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11254 ["Sum Column/Rectangle" org-table-sum
11255 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11256 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11257 ["Debug Formulas"
11258 org-table-toggle-formula-debugger :active (org-at-table-p)
11259 :keys "C-c {"
11260 :style toggle :selected org-table-formula-debug]
11261 ["Show Col/Row Numbers"
11262 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11263 :keys "C-c }"
11264 :style toggle :selected org-table-overlay-coordinates]
11268 (defun orgtbl-ctrl-c-ctrl-c (arg)
11269 "If the cursor is inside a table, realign the table.
11270 It it is a table to be sent away to a receiver, do it.
11271 With prefix arg, also recompute table."
11272 (interactive "P")
11273 (let ((pos (point)) action)
11274 (save-excursion
11275 (beginning-of-line 1)
11276 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11277 ((looking-at "[ \t]*|") pos)
11278 ((looking-at "#\\+TBLFM:") 'recalc))))
11279 (cond
11280 ((integerp action)
11281 (goto-char action)
11282 (org-table-maybe-eval-formula)
11283 (if arg
11284 (call-interactively 'org-table-recalculate)
11285 (org-table-maybe-recalculate-line))
11286 (call-interactively 'org-table-align)
11287 (orgtbl-send-table 'maybe))
11288 ((eq action 'recalc)
11289 (save-excursion
11290 (beginning-of-line 1)
11291 (skip-chars-backward " \r\n\t")
11292 (if (org-at-table-p)
11293 (org-call-with-arg 'org-table-recalculate t))))
11294 (t (let (orgtbl-mode)
11295 (call-interactively (key-binding "\C-c\C-c")))))))
11297 (defun orgtbl-tab (arg)
11298 "Justification and field motion for `orgtbl-mode'."
11299 (interactive "P")
11300 (if arg (org-table-edit-field t)
11301 (org-table-justify-field-maybe)
11302 (org-table-next-field)))
11304 (defun orgtbl-ret ()
11305 "Justification and field motion for `orgtbl-mode'."
11306 (interactive)
11307 (org-table-justify-field-maybe)
11308 (org-table-next-row))
11310 (defun orgtbl-self-insert-command (N)
11311 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11312 If the cursor is in a table looking at whitespace, the whitespace is
11313 overwritten, and the table is not marked as requiring realignment."
11314 (interactive "p")
11315 (if (and (org-at-table-p)
11317 (and org-table-auto-blank-field
11318 (member last-command
11319 '(orgtbl-hijacker-command-100
11320 orgtbl-hijacker-command-101
11321 orgtbl-hijacker-command-102
11322 orgtbl-hijacker-command-103
11323 orgtbl-hijacker-command-104
11324 orgtbl-hijacker-command-105))
11325 (org-table-blank-field))
11327 (eq N 1)
11328 (looking-at "[^|\n]* +|"))
11329 (let (org-table-may-need-update)
11330 (goto-char (1- (match-end 0)))
11331 (delete-backward-char 1)
11332 (goto-char (match-beginning 0))
11333 (self-insert-command N))
11334 (setq org-table-may-need-update t)
11335 (let (orgtbl-mode)
11336 (call-interactively (key-binding (vector last-input-event))))))
11338 (defun org-force-self-insert (N)
11339 "Needed to enforce self-insert under remapping."
11340 (interactive "p")
11341 (self-insert-command N))
11343 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11344 "Regula expression matching exponentials as produced by calc.")
11346 (defvar org-table-clean-did-remove-column nil)
11348 (defun orgtbl-export (table target)
11349 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11350 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11351 org-table-last-alignment org-table-last-column-widths
11352 maxcol column)
11353 (if (not (fboundp func))
11354 (error "Cannot export orgtbl table to %s" target))
11355 (setq lines (org-table-clean-before-export lines))
11356 (setq table
11357 (mapcar
11358 (lambda (x)
11359 (if (string-match org-table-hline-regexp x)
11360 'hline
11361 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11362 lines))
11363 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11364 table)))
11365 (loop for i from (1- maxcol) downto 0 do
11366 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11367 (setq column (delq nil column))
11368 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11369 (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))
11370 (funcall func table nil)))
11372 (defun orgtbl-send-table (&optional maybe)
11373 "Send a tranformed version of this table to the receiver position.
11374 With argument MAYBE, fail quietly if no transformation is defined for
11375 this table."
11376 (interactive)
11377 (catch 'exit
11378 (unless (org-at-table-p) (error "Not at a table"))
11379 ;; when non-interactive, we assume align has just happened.
11380 (when (interactive-p) (org-table-align))
11381 (save-excursion
11382 (goto-char (org-table-begin))
11383 (beginning-of-line 0)
11384 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11385 (if maybe
11386 (throw 'exit nil)
11387 (error "Don't know how to transform this table."))))
11388 (let* ((name (match-string 1))
11390 (transform (intern (match-string 2)))
11391 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11392 (skip (plist-get params :skip))
11393 (skipcols (plist-get params :skipcols))
11394 (txt (buffer-substring-no-properties
11395 (org-table-begin) (org-table-end)))
11396 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11397 (lines (org-table-clean-before-export lines))
11398 (i0 (if org-table-clean-did-remove-column 2 1))
11399 (table (mapcar
11400 (lambda (x)
11401 (if (string-match org-table-hline-regexp x)
11402 'hline
11403 (org-remove-by-index
11404 (org-split-string (org-trim x) "\\s-*|\\s-*")
11405 skipcols i0)))
11406 lines))
11407 (fun (if (= i0 2) 'cdr 'identity))
11408 (org-table-last-alignment
11409 (org-remove-by-index (funcall fun org-table-last-alignment)
11410 skipcols i0))
11411 (org-table-last-column-widths
11412 (org-remove-by-index (funcall fun org-table-last-column-widths)
11413 skipcols i0)))
11415 (unless (fboundp transform)
11416 (error "No such transformation function %s" transform))
11417 (setq txt (funcall transform table params))
11418 ;; Find the insertion place
11419 (save-excursion
11420 (goto-char (point-min))
11421 (unless (re-search-forward
11422 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11423 (error "Don't know where to insert translated table"))
11424 (goto-char (match-beginning 0))
11425 (beginning-of-line 2)
11426 (setq beg (point))
11427 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11428 (error "Cannot find end of insertion region"))
11429 (beginning-of-line 1)
11430 (delete-region beg (point))
11431 (goto-char beg)
11432 (insert txt "\n"))
11433 (message "Table converted and installed at receiver location"))))
11435 (defun org-remove-by-index (list indices &optional i0)
11436 "Remove the elements in LIST with indices in INDICES.
11437 First element has index 0, or I0 if given."
11438 (if (not indices)
11439 list
11440 (if (integerp indices) (setq indices (list indices)))
11441 (setq i0 (1- (or i0 0)))
11442 (delq :rm (mapcar (lambda (x)
11443 (setq i0 (1+ i0))
11444 (if (memq i0 indices) :rm x))
11445 list))))
11447 (defun orgtbl-toggle-comment ()
11448 "Comment or uncomment the orgtbl at point."
11449 (interactive)
11450 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11451 (re2 (concat "^" orgtbl-line-start-regexp))
11452 (commented (save-excursion (beginning-of-line 1)
11453 (cond ((looking-at re1) t)
11454 ((looking-at re2) nil)
11455 (t (error "Not at an org table")))))
11456 (re (if commented re1 re2))
11457 beg end)
11458 (save-excursion
11459 (beginning-of-line 1)
11460 (while (looking-at re) (beginning-of-line 0))
11461 (beginning-of-line 2)
11462 (setq beg (point))
11463 (while (looking-at re) (beginning-of-line 2))
11464 (setq end (point)))
11465 (comment-region beg end (if commented '(4) nil))))
11467 (defun orgtbl-insert-radio-table ()
11468 "Insert a radio table template appropriate for this major mode."
11469 (interactive)
11470 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11471 (txt (nth 1 e))
11472 name pos)
11473 (unless e (error "No radio table setup defined for %s" major-mode))
11474 (setq name (read-string "Table name: "))
11475 (while (string-match "%n" txt)
11476 (setq txt (replace-match name t t txt)))
11477 (or (bolp) (insert "\n"))
11478 (setq pos (point))
11479 (insert txt)
11480 (goto-char pos)))
11482 (defun org-get-param (params header i sym &optional hsym)
11483 "Get parameter value for symbol SYM.
11484 If this is a header line, actually get the value for the symbol with an
11485 additional \"h\" inserted after the colon.
11486 If the value is a protperty list, get the element for the current column.
11487 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11488 (let ((val (plist-get params sym)))
11489 (and hsym header (setq val (or (plist-get params hsym) val)))
11490 (if (consp val) (plist-get val i) val)))
11492 (defun orgtbl-to-generic (table params)
11493 "Convert the orgtbl-mode TABLE to some other format.
11494 This generic routine can be used for many standard cases.
11495 TABLE is a list, each entry either the symbol `hline' for a horizontal
11496 separator line, or a list of fields for that line.
11497 PARAMS is a property list of parameters that can influence the conversion.
11498 For the generic converter, some parameters are obligatory: You need to
11499 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11500 :splice, you must have :tstart and :tend.
11502 Valid parameters are
11504 :tstart String to start the table. Ignored when :splice is t.
11505 :tend String to end the table. Ignored when :splice is t.
11507 :splice When set to t, return only table body lines, don't wrap
11508 them into :tstart and :tend. Default is nil.
11510 :hline String to be inserted on horizontal separation lines.
11511 May be nil to ignore hlines.
11513 :lstart String to start a new table line.
11514 :lend String to end a table line
11515 :sep Separator between two fields
11516 :lfmt Format for entire line, with enough %s to capture all fields.
11517 If this is present, :lstart, :lend, and :sep are ignored.
11518 :fmt A format to be used to wrap the field, should contain
11519 %s for the original field value. For example, to wrap
11520 everything in dollars, you could use :fmt \"$%s$\".
11521 This may also be a property list with column numbers and
11522 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11524 :hlstart :hlend :hlsep :hlfmt :hfmt
11525 Same as above, specific for the header lines in the table.
11526 All lines before the first hline are treated as header.
11527 If any of these is not present, the data line value is used.
11529 :efmt Use this format to print numbers with exponentials.
11530 The format should have %s twice for inserting mantissa
11531 and exponent, for example \"%s\\\\times10^{%s}\". This
11532 may also be a property list with column numbers and
11533 formats. :fmt will still be applied after :efmt.
11535 In addition to this, the parameters :skip and :skipcols are always handled
11536 directly by `orgtbl-send-table'. See manual."
11537 (interactive)
11538 (let* ((p params)
11539 (splicep (plist-get p :splice))
11540 (hline (plist-get p :hline))
11541 rtn line i fm efm lfmt h)
11543 ;; Do we have a header?
11544 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11545 (setq h t))
11547 ;; Put header
11548 (unless splicep
11549 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11551 ;; Now loop over all lines
11552 (while (setq line (pop table))
11553 (if (eq line 'hline)
11554 ;; A horizontal separator line
11555 (progn (if hline (push hline rtn))
11556 (setq h nil)) ; no longer in header
11557 ;; A normal line. Convert the fields, push line onto the result list
11558 (setq i 0)
11559 (setq line
11560 (mapcar
11561 (lambda (f)
11562 (setq i (1+ i)
11563 fm (org-get-param p h i :fmt :hfmt)
11564 efm (org-get-param p h i :efmt))
11565 (if (and efm (string-match orgtbl-exp-regexp f))
11566 (setq f (format
11567 efm (match-string 1 f) (match-string 2 f))))
11568 (if fm (setq f (format fm f)))
11570 line))
11571 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11572 (push (apply 'format lfmt line) rtn)
11573 (push (concat
11574 (org-get-param p h i :lstart :hlstart)
11575 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11576 (org-get-param p h i :lend :hlend))
11577 rtn))))
11579 (unless splicep
11580 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11582 (mapconcat 'identity (nreverse rtn) "\n")))
11584 (defun orgtbl-to-latex (table params)
11585 "Convert the orgtbl-mode TABLE to LaTeX.
11586 TABLE is a list, each entry either the symbol `hline' for a horizontal
11587 separator line, or a list of fields for that line.
11588 PARAMS is a property list of parameters that can influence the conversion.
11589 Supports all parameters from `orgtbl-to-generic'. Most important for
11590 LaTeX are:
11592 :splice When set to t, return only table body lines, don't wrap
11593 them into a tabular environment. Default is nil.
11595 :fmt A format to be used to wrap the field, should contain %s for the
11596 original field value. For example, to wrap everything in dollars,
11597 use :fmt \"$%s$\". This may also be a property list with column
11598 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11600 :efmt Format for transforming numbers with exponentials. The format
11601 should have %s twice for inserting mantissa and exponent, for
11602 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11603 This may also be a property list with column numbers and formats.
11605 The general parameters :skip and :skipcols have already been applied when
11606 this function is called."
11607 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11608 org-table-last-alignment ""))
11609 (params2
11610 (list
11611 :tstart (concat "\\begin{tabular}{" alignment "}")
11612 :tend "\\end{tabular}"
11613 :lstart "" :lend " \\\\" :sep " & "
11614 :efmt "%s\\,(%s)" :hline "\\hline")))
11615 (orgtbl-to-generic table (org-combine-plists params2 params))))
11617 (defun orgtbl-to-html (table params)
11618 "Convert the orgtbl-mode TABLE to LaTeX.
11619 TABLE is a list, each entry either the symbol `hline' for a horizontal
11620 separator line, or a list of fields for that line.
11621 PARAMS is a property list of parameters that can influence the conversion.
11622 Currently this function recognizes the following parameters:
11624 :splice When set to t, return only table body lines, don't wrap
11625 them into a <table> environment. Default is nil.
11627 The general parameters :skip and :skipcols have already been applied when
11628 this function is called. The function does *not* use `orgtbl-to-generic',
11629 so you cannot specify parameters for it."
11630 (let* ((splicep (plist-get params :splice))
11631 html)
11632 ;; Just call the formatter we already have
11633 ;; We need to make text lines for it, so put the fields back together.
11634 (setq html (org-format-org-table-html
11635 (mapcar
11636 (lambda (x)
11637 (if (eq x 'hline)
11638 "|----+----|"
11639 (concat "| " (mapconcat 'identity x " | ") " |")))
11640 table)
11641 splicep))
11642 (if (string-match "\n+\\'" html)
11643 (setq html (replace-match "" t t html)))
11644 html))
11646 (defun orgtbl-to-texinfo (table params)
11647 "Convert the orgtbl-mode TABLE to TeXInfo.
11648 TABLE is a list, each entry either the symbol `hline' for a horizontal
11649 separator line, or a list of fields for that line.
11650 PARAMS is a property list of parameters that can influence the conversion.
11651 Supports all parameters from `orgtbl-to-generic'. Most important for
11652 TeXInfo are:
11654 :splice nil/t When set to t, return only table body lines, don't wrap
11655 them into a multitable environment. Default is nil.
11657 :fmt fmt A format to be used to wrap the field, should contain
11658 %s for the original field value. For example, to wrap
11659 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11660 This may also be a property list with column numbers and
11661 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11663 :cf \"f1 f2..\" The column fractions for the table. Bye default these
11664 are computed automatically from the width of the columns
11665 under org-mode.
11667 The general parameters :skip and :skipcols have already been applied when
11668 this function is called."
11669 (let* ((total (float (apply '+ org-table-last-column-widths)))
11670 (colfrac (or (plist-get params :cf)
11671 (mapconcat
11672 (lambda (x) (format "%.3f" (/ (float x) total)))
11673 org-table-last-column-widths " ")))
11674 (params2
11675 (list
11676 :tstart (concat "@multitable @columnfractions " colfrac)
11677 :tend "@end multitable"
11678 :lstart "@item " :lend "" :sep " @tab "
11679 :hlstart "@headitem ")))
11680 (orgtbl-to-generic table (org-combine-plists params2 params))))
11682 ;;;; Link Stuff
11684 ;;; Link abbreviations
11686 (defun org-link-expand-abbrev (link)
11687 "Apply replacements as defined in `org-link-abbrev-alist."
11688 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11689 (let* ((key (match-string 1 link))
11690 (as (or (assoc key org-link-abbrev-alist-local)
11691 (assoc key org-link-abbrev-alist)))
11692 (tag (and (match-end 2) (match-string 3 link)))
11693 rpl)
11694 (if (not as)
11695 link
11696 (setq rpl (cdr as))
11697 (cond
11698 ((symbolp rpl) (funcall rpl tag))
11699 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11700 (t (concat rpl tag)))))
11701 link))
11703 ;;; Storing and inserting links
11705 (defvar org-insert-link-history nil
11706 "Minibuffer history for links inserted with `org-insert-link'.")
11708 (defvar org-stored-links nil
11709 "Contains the links stored with `org-store-link'.")
11711 (defvar org-store-link-plist nil
11712 "Plist with info about the most recently link created with `org-store-link'.")
11714 (defvar org-link-protocols nil
11715 "Link protocols added to Org-mode using `org-add-link-type'.")
11717 (defvar org-store-link-functions nil
11718 "List of functions that are called to create and store a link.
11719 Each function will be called in turn until one returns a non-nil
11720 value. Each function should check if it is responsible for creating
11721 this link (for example by looking at the major mode).
11722 If not, it must exit and return nil.
11723 If yes, it should return a non-nil value after a calling
11724 `org-store-link-props' with a list of properties and values.
11725 Special properties are:
11727 :type The link prefix. like \"http\". This must be given.
11728 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11729 This is obligatory as well.
11730 :description Optional default description for the second pair
11731 of brackets in an Org-mode link. The user can still change
11732 this when inserting this link into an Org-mode buffer.
11734 In addition to these, any additional properties can be specified
11735 and then used in remember templates.")
11737 (defun org-add-link-type (type &optional follow publish)
11738 "Add TYPE to the list of `org-link-types'.
11739 Re-compute all regular expressions depending on `org-link-types'
11740 FOLLOW and PUBLISH are two functions. Both take the link path as
11741 an argument.
11742 FOLLOW should do whatever is necessary to follow the link, for example
11743 to find a file or display a mail message.
11745 PUBLISH takes the path and retuns the string that should be used when
11746 this document is published. FIMXE: This is actually not yet implemented."
11747 (add-to-list 'org-link-types type t)
11748 (org-make-link-regexps)
11749 (add-to-list 'org-link-protocols
11750 (list type follow publish)))
11752 (defun org-add-agenda-custom-command (entry)
11753 "Replace or add a command in `org-agenda-custom-commands'.
11754 This is mostly for hacking and trying a new command - once the command
11755 works you probably want to add it to `org-agenda-custom-commands' for good."
11756 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11757 (if ass
11758 (setcdr ass (cdr entry))
11759 (push entry org-agenda-custom-commands))))
11761 ;;;###autoload
11762 (defun org-store-link (arg)
11763 "\\<org-mode-map>Store an org-link to the current location.
11764 This link can later be inserted into an org-buffer with
11765 \\[org-insert-link].
11766 For some link types, a prefix arg is interpreted:
11767 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11768 For file links, arg negates `org-context-in-file-links'."
11769 (interactive "P")
11770 (setq org-store-link-plist nil) ; reset
11771 (let (link cpltxt desc description search txt)
11772 (cond
11774 ((run-hook-with-args-until-success 'org-store-link-functions)
11775 (setq link (plist-get org-store-link-plist :link)
11776 desc (or (plist-get org-store-link-plist :description) link)))
11778 ((eq major-mode 'bbdb-mode)
11779 (let ((name (bbdb-record-name (bbdb-current-record)))
11780 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11781 (setq cpltxt (concat "bbdb:" (or name company))
11782 link (org-make-link cpltxt))
11783 (org-store-link-props :type "bbdb" :name name :company company)))
11785 ((eq major-mode 'Info-mode)
11786 (setq link (org-make-link "info:"
11787 (file-name-nondirectory Info-current-file)
11788 ":" Info-current-node))
11789 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11790 ":" Info-current-node))
11791 (org-store-link-props :type "info" :file Info-current-file
11792 :node Info-current-node))
11794 ((eq major-mode 'calendar-mode)
11795 (let ((cd (calendar-cursor-to-date)))
11796 (setq link
11797 (format-time-string
11798 (car org-time-stamp-formats)
11799 (apply 'encode-time
11800 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11801 nil nil nil))))
11802 (org-store-link-props :type "calendar" :date cd)))
11804 ((or (eq major-mode 'vm-summary-mode)
11805 (eq major-mode 'vm-presentation-mode))
11806 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11807 (vm-follow-summary-cursor)
11808 (save-excursion
11809 (vm-select-folder-buffer)
11810 (let* ((message (car vm-message-pointer))
11811 (folder buffer-file-name)
11812 (subject (vm-su-subject message))
11813 (to (vm-get-header-contents message "To"))
11814 (from (vm-get-header-contents message "From"))
11815 (message-id (vm-su-message-id message)))
11816 (org-store-link-props :type "vm" :from from :to to :subject subject
11817 :message-id message-id)
11818 (setq message-id (org-remove-angle-brackets message-id))
11819 (setq folder (abbreviate-file-name folder))
11820 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11821 folder)
11822 (setq folder (replace-match "" t t folder)))
11823 (setq cpltxt (org-email-link-description))
11824 (setq link (org-make-link "vm:" folder "#" message-id)))))
11826 ((eq major-mode 'wl-summary-mode)
11827 (let* ((msgnum (wl-summary-message-number))
11828 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11829 msgnum 'message-id))
11830 (wl-message-entity
11831 (if (fboundp 'elmo-message-entity)
11832 (elmo-message-entity
11833 wl-summary-buffer-elmo-folder msgnum)
11834 (elmo-msgdb-overview-get-entity
11835 msgnum (wl-summary-buffer-msgdb))))
11836 (from (wl-summary-line-from))
11837 (to (car (elmo-message-entity-field wl-message-entity 'to)))
11838 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11839 (wl-summary-line-subject))))
11840 (org-store-link-props :type "wl" :from from :to to
11841 :subject subject :message-id message-id)
11842 (setq message-id (org-remove-angle-brackets message-id))
11843 (setq cpltxt (org-email-link-description))
11844 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11845 "#" message-id))))
11847 ((or (equal major-mode 'mh-folder-mode)
11848 (equal major-mode 'mh-show-mode))
11849 (let ((from (org-mhe-get-header "From:"))
11850 (to (org-mhe-get-header "To:"))
11851 (message-id (org-mhe-get-header "Message-Id:"))
11852 (subject (org-mhe-get-header "Subject:")))
11853 (org-store-link-props :type "mh" :from from :to to
11854 :subject subject :message-id message-id)
11855 (setq cpltxt (org-email-link-description))
11856 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11857 (org-remove-angle-brackets message-id)))))
11859 ((eq major-mode 'rmail-mode)
11860 (save-excursion
11861 (save-restriction
11862 (rmail-narrow-to-non-pruned-header)
11863 (let ((folder buffer-file-name)
11864 (message-id (mail-fetch-field "message-id"))
11865 (from (mail-fetch-field "from"))
11866 (to (mail-fetch-field "to"))
11867 (subject (mail-fetch-field "subject")))
11868 (org-store-link-props
11869 :type "rmail" :from from :to to
11870 :subject subject :message-id message-id)
11871 (setq message-id (org-remove-angle-brackets message-id))
11872 (setq cpltxt (org-email-link-description))
11873 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11875 ((eq major-mode 'gnus-group-mode)
11876 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11877 (gnus-group-group-name)) ; version
11878 ((fboundp 'gnus-group-name)
11879 (gnus-group-name))
11880 (t "???"))))
11881 (unless group (error "Not on a group"))
11882 (org-store-link-props :type "gnus" :group group)
11883 (setq cpltxt (concat
11884 (if (org-xor arg org-usenet-links-prefer-google)
11885 "http://groups.google.com/groups?group="
11886 "gnus:")
11887 group)
11888 link (org-make-link cpltxt))))
11890 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11891 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11892 (let* ((group gnus-newsgroup-name)
11893 (article (gnus-summary-article-number))
11894 (header (gnus-summary-article-header article))
11895 (from (mail-header-from header))
11896 (message-id (mail-header-id header))
11897 (date (mail-header-date header))
11898 (subject (gnus-summary-subject-string)))
11899 (org-store-link-props :type "gnus" :from from :subject subject
11900 :message-id message-id :group group)
11901 (setq cpltxt (org-email-link-description))
11902 (if (org-xor arg org-usenet-links-prefer-google)
11903 (setq link
11904 (concat
11905 cpltxt "\n "
11906 (format "http://groups.google.com/groups?as_umsgid=%s"
11907 (org-fixup-message-id-for-http message-id))))
11908 (setq link (org-make-link "gnus:" group
11909 "#" (number-to-string article))))))
11911 ((eq major-mode 'w3-mode)
11912 (setq cpltxt (url-view-url t)
11913 link (org-make-link cpltxt))
11914 (org-store-link-props :type "w3" :url (url-view-url t)))
11916 ((eq major-mode 'w3m-mode)
11917 (setq cpltxt (or w3m-current-title w3m-current-url)
11918 link (org-make-link w3m-current-url))
11919 (org-store-link-props :type "w3m" :url (url-view-url t)))
11921 ((setq search (run-hook-with-args-until-success
11922 'org-create-file-search-functions))
11923 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11924 "::" search))
11925 (setq cpltxt (or description link)))
11927 ((eq major-mode 'image-mode)
11928 (setq cpltxt (concat "file:"
11929 (abbreviate-file-name buffer-file-name))
11930 link (org-make-link cpltxt))
11931 (org-store-link-props :type "image" :file buffer-file-name))
11933 ((eq major-mode 'dired-mode)
11934 ;; link to the file in the current line
11935 (setq cpltxt (concat "file:"
11936 (abbreviate-file-name
11937 (expand-file-name
11938 (dired-get-filename nil t))))
11939 link (org-make-link cpltxt)))
11941 ((and buffer-file-name (org-mode-p))
11942 ;; Just link to current headline
11943 (setq cpltxt (concat "file:"
11944 (abbreviate-file-name buffer-file-name)))
11945 ;; Add a context search string
11946 (when (org-xor org-context-in-file-links arg)
11947 ;; Check if we are on a target
11948 (if (org-in-regexp "<<\\(.*?\\)>>")
11949 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11950 (setq txt (cond
11951 ((org-on-heading-p) nil)
11952 ((org-region-active-p)
11953 (buffer-substring (region-beginning) (region-end)))
11954 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11955 (when (or (null txt) (string-match "\\S-" txt))
11956 (setq cpltxt
11957 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11958 desc "NONE"))))
11959 (if (string-match "::\\'" cpltxt)
11960 (setq cpltxt (substring cpltxt 0 -2)))
11961 (setq link (org-make-link cpltxt)))
11963 ((buffer-file-name (buffer-base-buffer))
11964 ;; Just link to this file here.
11965 (setq cpltxt (concat "file:"
11966 (abbreviate-file-name
11967 (buffer-file-name (buffer-base-buffer)))))
11968 ;; Add a context string
11969 (when (org-xor org-context-in-file-links arg)
11970 (setq txt (if (org-region-active-p)
11971 (buffer-substring (region-beginning) (region-end))
11972 (buffer-substring (point-at-bol) (point-at-eol))))
11973 ;; Only use search option if there is some text.
11974 (when (string-match "\\S-" txt)
11975 (setq cpltxt
11976 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11977 desc "NONE")))
11978 (setq link (org-make-link cpltxt)))
11980 ((interactive-p)
11981 (error "Cannot link to a buffer which is not visiting a file"))
11983 (t (setq link nil)))
11985 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11986 (setq link (or link cpltxt)
11987 desc (or desc cpltxt))
11988 (if (equal desc "NONE") (setq desc nil))
11990 (if (and (interactive-p) link)
11991 (progn
11992 (setq org-stored-links
11993 (cons (list link desc) org-stored-links))
11994 (message "Stored: %s" (or desc link)))
11995 (and link (org-make-link-string link desc)))))
11997 (defun org-store-link-props (&rest plist)
11998 "Store link properties, extract names and addresses."
11999 (let (x adr)
12000 (when (setq x (plist-get plist :from))
12001 (setq adr (mail-extract-address-components x))
12002 (plist-put plist :fromname (car adr))
12003 (plist-put plist :fromaddress (nth 1 adr)))
12004 (when (setq x (plist-get plist :to))
12005 (setq adr (mail-extract-address-components x))
12006 (plist-put plist :toname (car adr))
12007 (plist-put plist :toaddress (nth 1 adr))))
12008 (let ((from (plist-get plist :from))
12009 (to (plist-get plist :to)))
12010 (when (and from to org-from-is-user-regexp)
12011 (plist-put plist :fromto
12012 (if (string-match org-from-is-user-regexp from)
12013 (concat "to %t")
12014 (concat "from %f")))))
12015 (setq org-store-link-plist plist))
12017 (defun org-email-link-description (&optional fmt)
12018 "Return the description part of an email link.
12019 This takes information from `org-store-link-plist' and formats it
12020 according to FMT (default from `org-email-link-description-format')."
12021 (setq fmt (or fmt org-email-link-description-format))
12022 (let* ((p org-store-link-plist)
12023 (to (plist-get p :toaddress))
12024 (from (plist-get p :fromaddress))
12025 (table
12026 (list
12027 (cons "%c" (plist-get p :fromto))
12028 (cons "%F" (plist-get p :from))
12029 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12030 (cons "%T" (plist-get p :to))
12031 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12032 (cons "%s" (plist-get p :subject))
12033 (cons "%m" (plist-get p :message-id)))))
12034 (when (string-match "%c" fmt)
12035 ;; Check if the user wrote this message
12036 (if (and org-from-is-user-regexp from to
12037 (save-match-data (string-match org-from-is-user-regexp from)))
12038 (setq fmt (replace-match "to %t" t t fmt))
12039 (setq fmt (replace-match "from %f" t t fmt))))
12040 (org-replace-escapes fmt table)))
12042 (defun org-make-org-heading-search-string (&optional string heading)
12043 "Make search string for STRING or current headline."
12044 (interactive)
12045 (let ((s (or string (org-get-heading))))
12046 (unless (and string (not heading))
12047 ;; We are using a headline, clean up garbage in there.
12048 (if (string-match org-todo-regexp s)
12049 (setq s (replace-match "" t t s)))
12050 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12051 (setq s (replace-match "" t t s)))
12052 (setq s (org-trim s))
12053 (if (string-match (concat "^\\(" org-quote-string "\\|"
12054 org-comment-string "\\)") s)
12055 (setq s (replace-match "" t t s)))
12056 (while (string-match org-ts-regexp s)
12057 (setq s (replace-match "" t t s))))
12058 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12059 (setq s (replace-match " " t t s)))
12060 (or string (setq s (concat "*" s))) ; Add * for headlines
12061 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12063 (defun org-make-link (&rest strings)
12064 "Concatenate STRINGS."
12065 (apply 'concat strings))
12067 (defun org-make-link-string (link &optional description)
12068 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12069 (unless (string-match "\\S-" link)
12070 (error "Empty link"))
12071 (when (stringp description)
12072 ;; Remove brackets from the description, they are fatal.
12073 (while (string-match "\\[" description)
12074 (setq description (replace-match "{" t t description)))
12075 (while (string-match "\\]" description)
12076 (setq description (replace-match "}" t t description))))
12077 (when (equal (org-link-escape link) description)
12078 ;; No description needed, it is identical
12079 (setq description nil))
12080 (when (and (not description)
12081 (not (equal link (org-link-escape link))))
12082 (setq description link))
12083 (concat "[[" (org-link-escape link) "]"
12084 (if description (concat "[" description "]") "")
12085 "]"))
12087 (defconst org-link-escape-chars
12088 '((?\ . "%20")
12089 (?\[ . "%5B")
12090 (?\] . "%5D")
12091 (?\340 . "%E0") ; `a
12092 (?\342 . "%E2") ; ^a
12093 (?\347 . "%E7") ; ,c
12094 (?\350 . "%E8") ; `e
12095 (?\351 . "%E9") ; 'e
12096 (?\352 . "%EA") ; ^e
12097 (?\356 . "%EE") ; ^i
12098 (?\364 . "%F4") ; ^o
12099 (?\371 . "%F9") ; `u
12100 (?\373 . "%FB") ; ^u
12101 (?\; . "%3B")
12102 (?? . "%3F")
12103 (?= . "%3D")
12104 (?+ . "%2B")
12106 "Association list of escapes for some characters problematic in links.
12107 This is the list that is used for internal purposes.")
12109 (defconst org-link-escape-chars-browser
12110 '((?\ . "%20")) ; 32 for the SPC char
12111 "Association list of escapes for some characters problematic in links.
12112 This is the list that is used before handing over to the browser.")
12114 (defun org-link-escape (text &optional table)
12115 "Escape charaters in TEXT that are problematic for links."
12116 (setq table (or table org-link-escape-chars))
12117 (when text
12118 (let ((re (mapconcat (lambda (x) (regexp-quote
12119 (char-to-string (car x))))
12120 table "\\|")))
12121 (while (string-match re text)
12122 (setq text
12123 (replace-match
12124 (cdr (assoc (string-to-char (match-string 0 text))
12125 table))
12126 t t text)))
12127 text)))
12129 (defun org-link-unescape (text &optional table)
12130 "Reverse the action of `org-link-escape'."
12131 (setq table (or table org-link-escape-chars))
12132 (when text
12133 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12134 table "\\|")))
12135 (while (string-match re text)
12136 (setq text
12137 (replace-match
12138 (char-to-string (car (rassoc (match-string 0 text) table)))
12139 t t text)))
12140 text)))
12142 (defun org-xor (a b)
12143 "Exclusive or."
12144 (if a (not b) b))
12146 (defun org-get-header (header)
12147 "Find a header field in the current buffer."
12148 (save-excursion
12149 (goto-char (point-min))
12150 (let ((case-fold-search t) s)
12151 (cond
12152 ((eq header 'from)
12153 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12154 (setq s (match-string 1)))
12155 (while (string-match "\"" s)
12156 (setq s (replace-match "" t t s)))
12157 (if (string-match "[<(].*" s)
12158 (setq s (replace-match "" t t s))))
12159 ((eq header 'message-id)
12160 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12161 (setq s (match-string 1))))
12162 ((eq header 'subject)
12163 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12164 (setq s (match-string 1)))))
12165 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12166 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12167 s)))
12170 (defun org-fixup-message-id-for-http (s)
12171 "Replace special characters in a message id, so it can be used in an http query."
12172 (while (string-match "<" s)
12173 (setq s (replace-match "%3C" t t s)))
12174 (while (string-match ">" s)
12175 (setq s (replace-match "%3E" t t s)))
12176 (while (string-match "@" s)
12177 (setq s (replace-match "%40" t t s)))
12180 ;;;###autoload
12181 (defun org-insert-link-global ()
12182 "Insert a link like Org-mode does.
12183 This command can be called in any mode to insert a link in Org-mode syntax."
12184 (interactive)
12185 (org-run-like-in-org-mode 'org-insert-link))
12187 (defun org-insert-link (&optional complete-file)
12188 "Insert a link. At the prompt, enter the link.
12190 Completion can be used to select a link previously stored with
12191 `org-store-link'. When the empty string is entered (i.e. if you just
12192 press RET at the prompt), the link defaults to the most recently
12193 stored link. As SPC triggers completion in the minibuffer, you need to
12194 use M-SPC or C-q SPC to force the insertion of a space character.
12196 You will also be prompted for a description, and if one is given, it will
12197 be displayed in the buffer instead of the link.
12199 If there is already a link at point, this command will allow you to edit link
12200 and description parts.
12202 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12203 selected using completion. The path to the file will be relative to
12204 the current directory if the file is in the current directory or a
12205 subdirectory. Otherwise, the link will be the absolute path as
12206 completed in the minibuffer (i.e. normally ~/path/to/file).
12208 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12209 is in the current directory or below.
12210 With three \\[universal-argument] prefixes, negate the meaning of
12211 `org-keep-stored-link-after-insertion'."
12212 (interactive "P")
12213 (let* ((wcf (current-window-configuration))
12214 (region (if (org-region-active-p)
12215 (buffer-substring (region-beginning) (region-end))))
12216 (remove (and region (list (region-beginning) (region-end))))
12217 (desc region)
12218 tmphist ; byte-compile incorrectly complains about this
12219 link entry file)
12220 (cond
12221 ((org-in-regexp org-bracket-link-regexp 1)
12222 ;; We do have a link at point, and we are going to edit it.
12223 (setq remove (list (match-beginning 0) (match-end 0)))
12224 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12225 (setq link (read-string "Link: "
12226 (org-link-unescape
12227 (org-match-string-no-properties 1)))))
12228 ((or (org-in-regexp org-angle-link-re)
12229 (org-in-regexp org-plain-link-re))
12230 ;; Convert to bracket link
12231 (setq remove (list (match-beginning 0) (match-end 0))
12232 link (read-string "Link: "
12233 (org-remove-angle-brackets (match-string 0)))))
12234 ((equal complete-file '(4))
12235 ;; Completing read for file names.
12236 (setq file (read-file-name "File: "))
12237 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12238 (pwd1 (file-name-as-directory (abbreviate-file-name
12239 (expand-file-name ".")))))
12240 (cond
12241 ((equal complete-file '(16))
12242 (setq link (org-make-link
12243 "file:"
12244 (abbreviate-file-name (expand-file-name file)))))
12245 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12246 (setq link (org-make-link "file:" (match-string 1 file))))
12247 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12248 (expand-file-name file))
12249 (setq link (org-make-link
12250 "file:" (match-string 1 (expand-file-name file)))))
12251 (t (setq link (org-make-link "file:" file))))))
12253 ;; Read link, with completion for stored links.
12254 (with-output-to-temp-buffer "*Org Links*"
12255 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12256 (when org-stored-links
12257 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12258 (princ (mapconcat
12259 (lambda (x)
12260 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12261 (reverse org-stored-links) "\n"))))
12262 (let ((cw (selected-window)))
12263 (select-window (get-buffer-window "*Org Links*"))
12264 (shrink-window-if-larger-than-buffer)
12265 (setq truncate-lines t)
12266 (select-window cw))
12267 ;; Fake a link history, containing the stored links.
12268 (setq tmphist (append (mapcar 'car org-stored-links)
12269 org-insert-link-history))
12270 (unwind-protect
12271 (setq link (org-completing-read
12272 "Link: "
12273 (append
12274 (mapcar (lambda (x) (list (concat (car x) ":")))
12275 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12276 (mapcar (lambda (x) (list (concat x ":")))
12277 org-link-types))
12278 nil nil nil
12279 'tmphist
12280 (or (car (car org-stored-links)))))
12281 (set-window-configuration wcf)
12282 (kill-buffer "*Org Links*"))
12283 (setq entry (assoc link org-stored-links))
12284 (or entry (push link org-insert-link-history))
12285 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12286 (not org-keep-stored-link-after-insertion))
12287 (setq org-stored-links (delq (assoc link org-stored-links)
12288 org-stored-links)))
12289 (setq desc (or desc (nth 1 entry)))))
12291 (if (string-match org-plain-link-re link)
12292 ;; URL-like link, normalize the use of angular brackets.
12293 (setq link (org-make-link (org-remove-angle-brackets link))))
12295 ;; Check if we are linking to the current file with a search option
12296 ;; If yes, simplify the link by using only the search option.
12297 (when (and buffer-file-name
12298 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12299 (let* ((path (match-string 1 link))
12300 (case-fold-search nil)
12301 (search (match-string 2 link)))
12302 (save-match-data
12303 (if (equal (file-truename buffer-file-name) (file-truename path))
12304 ;; We are linking to this same file, with a search option
12305 (setq link search)))))
12307 ;; Check if we can/should use a relative path. If yes, simplify the link
12308 (when (string-match "\\<file:\\(.*\\)" link)
12309 (let* ((path (match-string 1 link))
12310 (origpath path)
12311 (desc-is-link (equal link desc))
12312 (case-fold-search nil))
12313 (cond
12314 ((eq org-link-file-path-type 'absolute)
12315 (setq path (abbreviate-file-name (expand-file-name path))))
12316 ((eq org-link-file-path-type 'noabbrev)
12317 (setq path (expand-file-name path)))
12318 ((eq org-link-file-path-type 'relative)
12319 (setq path (file-relative-name path)))
12321 (save-match-data
12322 (if (string-match (concat "^" (regexp-quote
12323 (file-name-as-directory
12324 (expand-file-name "."))))
12325 (expand-file-name path))
12326 ;; We are linking a file with relative path name.
12327 (setq path (substring (expand-file-name path)
12328 (match-end 0)))))))
12329 (setq link (concat "file:" path))
12330 (if (equal desc origpath)
12331 (setq desc path))))
12333 (setq desc (read-string "Description: " desc))
12334 (unless (string-match "\\S-" desc) (setq desc nil))
12335 (if remove (apply 'delete-region remove))
12336 (insert (org-make-link-string link desc))))
12338 (defun org-completing-read (&rest args)
12339 (let ((minibuffer-local-completion-map
12340 (copy-keymap minibuffer-local-completion-map)))
12341 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12342 (apply 'completing-read args)))
12344 ;;; Opening/following a link
12345 (defvar org-link-search-failed nil)
12347 (defun org-next-link ()
12348 "Move forward to the next link.
12349 If the link is in hidden text, expose it."
12350 (interactive)
12351 (when (and org-link-search-failed (eq this-command last-command))
12352 (goto-char (point-min))
12353 (message "Link search wrapped back to beginning of buffer"))
12354 (setq org-link-search-failed nil)
12355 (let* ((pos (point))
12356 (ct (org-context))
12357 (a (assoc :link ct)))
12358 (if a (goto-char (nth 2 a)))
12359 (if (re-search-forward org-any-link-re nil t)
12360 (progn
12361 (goto-char (match-beginning 0))
12362 (if (org-invisible-p) (org-show-context)))
12363 (goto-char pos)
12364 (setq org-link-search-failed t)
12365 (error "No further link found"))))
12367 (defun org-previous-link ()
12368 "Move backward to the previous link.
12369 If the link is in hidden text, expose it."
12370 (interactive)
12371 (when (and org-link-search-failed (eq this-command last-command))
12372 (goto-char (point-max))
12373 (message "Link search wrapped back to end of buffer"))
12374 (setq org-link-search-failed nil)
12375 (let* ((pos (point))
12376 (ct (org-context))
12377 (a (assoc :link ct)))
12378 (if a (goto-char (nth 1 a)))
12379 (if (re-search-backward org-any-link-re nil t)
12380 (progn
12381 (goto-char (match-beginning 0))
12382 (if (org-invisible-p) (org-show-context)))
12383 (goto-char pos)
12384 (setq org-link-search-failed t)
12385 (error "No further link found"))))
12387 (defun org-find-file-at-mouse (ev)
12388 "Open file link or URL at mouse."
12389 (interactive "e")
12390 (mouse-set-point ev)
12391 (org-open-at-point 'in-emacs))
12393 (defun org-open-at-mouse (ev)
12394 "Open file link or URL at mouse."
12395 (interactive "e")
12396 (mouse-set-point ev)
12397 (org-open-at-point))
12399 (defvar org-window-config-before-follow-link nil
12400 "The window configuration before following a link.
12401 This is saved in case the need arises to restore it.")
12403 (defvar org-open-link-marker (make-marker)
12404 "Marker pointing to the location where `org-open-at-point; was called.")
12406 ;;;###autoload
12407 (defun org-open-at-point-global ()
12408 "Follow a link like Org-mode does.
12409 This command can be called in any mode to follow a link that has
12410 Org-mode syntax."
12411 (interactive)
12412 (org-run-like-in-org-mode 'org-open-at-point))
12414 (defun org-open-at-point (&optional in-emacs)
12415 "Open link at or after point.
12416 If there is no link at point, this function will search forward up to
12417 the end of the current subtree.
12418 Normally, files will be opened by an appropriate application. If the
12419 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12420 (interactive "P")
12421 (catch 'abort
12422 (move-marker org-open-link-marker (point))
12423 (setq org-window-config-before-follow-link (current-window-configuration))
12424 (org-remove-occur-highlights nil nil t)
12425 (if (org-at-timestamp-p t)
12426 (org-follow-timestamp-link)
12427 (let (type path link line search (pos (point)))
12428 (catch 'match
12429 (save-excursion
12430 (skip-chars-forward "^]\n\r")
12431 (when (org-in-regexp org-bracket-link-regexp)
12432 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12433 (while (string-match " *\n *" link)
12434 (setq link (replace-match " " t t link)))
12435 (setq link (org-link-expand-abbrev link))
12436 (if (string-match org-link-re-with-space2 link)
12437 (setq type (match-string 1 link) path (match-string 2 link))
12438 (setq type "thisfile" path link))
12439 (throw 'match t)))
12441 (when (get-text-property (point) 'org-linked-text)
12442 (setq type "thisfile"
12443 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12444 (1+ (point)) (point))
12445 path (buffer-substring
12446 (previous-single-property-change pos 'org-linked-text)
12447 (next-single-property-change pos 'org-linked-text)))
12448 (throw 'match t))
12450 (save-excursion
12451 (when (or (org-in-regexp org-angle-link-re)
12452 (org-in-regexp org-plain-link-re))
12453 (setq type (match-string 1) path (match-string 2))
12454 (throw 'match t)))
12455 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12456 (setq type "tree-match"
12457 path (match-string 1))
12458 (throw 'match t))
12459 (save-excursion
12460 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12461 (setq type "tags"
12462 path (match-string 1))
12463 (while (string-match ":" path)
12464 (setq path (replace-match "+" t t path)))
12465 (throw 'match t))))
12466 (unless path
12467 (error "No link found"))
12468 ;; Remove any trailing spaces in path
12469 (if (string-match " +\\'" path)
12470 (setq path (replace-match "" t t path)))
12472 (cond
12474 ((assoc type org-link-protocols)
12475 (funcall (nth 1 (assoc type org-link-protocols)) path))
12477 ((equal type "mailto")
12478 (let ((cmd (car org-link-mailto-program))
12479 (args (cdr org-link-mailto-program)) args1
12480 (address path) (subject "") a)
12481 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12482 (setq address (match-string 1 path)
12483 subject (org-link-escape (match-string 2 path))))
12484 (while args
12485 (cond
12486 ((not (stringp (car args))) (push (pop args) args1))
12487 (t (setq a (pop args))
12488 (if (string-match "%a" a)
12489 (setq a (replace-match address t t a)))
12490 (if (string-match "%s" a)
12491 (setq a (replace-match subject t t a)))
12492 (push a args1))))
12493 (apply cmd (nreverse args1))))
12495 ((member type '("http" "https" "ftp" "news"))
12496 (browse-url (concat type ":" (org-link-escape
12497 path org-link-escape-chars-browser))))
12499 ((member type '("message"))
12500 (browse-url (concat type ":" path)))
12502 ((string= type "tags")
12503 (org-tags-view in-emacs path))
12504 ((string= type "thisfile")
12505 (if in-emacs
12506 (switch-to-buffer-other-window
12507 (org-get-buffer-for-internal-link (current-buffer)))
12508 (org-mark-ring-push))
12509 (let ((cmd `(org-link-search
12510 ,path
12511 ,(cond ((equal in-emacs '(4)) 'occur)
12512 ((equal in-emacs '(16)) 'org-occur)
12513 (t nil))
12514 ,pos)))
12515 (condition-case nil (eval cmd)
12516 (error (progn (widen) (eval cmd))))))
12518 ((string= type "tree-match")
12519 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12521 ((string= type "file")
12522 (if (string-match "::\\([0-9]+\\)\\'" path)
12523 (setq line (string-to-number (match-string 1 path))
12524 path (substring path 0 (match-beginning 0)))
12525 (if (string-match "::\\(.+\\)\\'" path)
12526 (setq search (match-string 1 path)
12527 path (substring path 0 (match-beginning 0)))))
12528 (if (string-match "[*?{]" (file-name-nondirectory path))
12529 (dired path)
12530 (org-open-file path in-emacs line search)))
12532 ((string= type "news")
12533 (org-follow-gnus-link path))
12535 ((string= type "bbdb")
12536 (org-follow-bbdb-link path))
12538 ((string= type "info")
12539 (org-follow-info-link path))
12541 ((string= type "gnus")
12542 (let (group article)
12543 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12544 (error "Error in Gnus link"))
12545 (setq group (match-string 1 path)
12546 article (match-string 3 path))
12547 (org-follow-gnus-link group article)))
12549 ((string= type "vm")
12550 (let (folder article)
12551 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12552 (error "Error in VM link"))
12553 (setq folder (match-string 1 path)
12554 article (match-string 3 path))
12555 ;; in-emacs is the prefix arg, will be interpreted as read-only
12556 (org-follow-vm-link folder article in-emacs)))
12558 ((string= type "wl")
12559 (let (folder article)
12560 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12561 (error "Error in Wanderlust link"))
12562 (setq folder (match-string 1 path)
12563 article (match-string 3 path))
12564 (org-follow-wl-link folder article)))
12566 ((string= type "mhe")
12567 (let (folder article)
12568 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12569 (error "Error in MHE link"))
12570 (setq folder (match-string 1 path)
12571 article (match-string 3 path))
12572 (org-follow-mhe-link folder article)))
12574 ((string= type "rmail")
12575 (let (folder article)
12576 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12577 (error "Error in RMAIL link"))
12578 (setq folder (match-string 1 path)
12579 article (match-string 3 path))
12580 (org-follow-rmail-link folder article)))
12582 ((string= type "shell")
12583 (let ((cmd path))
12584 (if (or (not org-confirm-shell-link-function)
12585 (funcall org-confirm-shell-link-function
12586 (format "Execute \"%s\" in shell? "
12587 (org-add-props cmd nil
12588 'face 'org-warning))))
12589 (progn
12590 (message "Executing %s" cmd)
12591 (shell-command cmd))
12592 (error "Abort"))))
12594 ((string= type "elisp")
12595 (let ((cmd path))
12596 (if (or (not org-confirm-elisp-link-function)
12597 (funcall org-confirm-elisp-link-function
12598 (format "Execute \"%s\" as elisp? "
12599 (org-add-props cmd nil
12600 'face 'org-warning))))
12601 (message "%s => %s" cmd (eval (read cmd)))
12602 (error "Abort"))))
12605 (browse-url-at-point)))))
12606 (move-marker org-open-link-marker nil)))
12608 ;;; File search
12610 (defvar org-create-file-search-functions nil
12611 "List of functions to construct the right search string for a file link.
12612 These functions are called in turn with point at the location to
12613 which the link should point.
12615 A function in the hook should first test if it would like to
12616 handle this file type, for example by checking the major-mode or
12617 the file extension. If it decides not to handle this file, it
12618 should just return nil to give other functions a chance. If it
12619 does handle the file, it must return the search string to be used
12620 when following the link. The search string will be part of the
12621 file link, given after a double colon, and `org-open-at-point'
12622 will automatically search for it. If special measures must be
12623 taken to make the search successful, another function should be
12624 added to the companion hook `org-execute-file-search-functions',
12625 which see.
12627 A function in this hook may also use `setq' to set the variable
12628 `description' to provide a suggestion for the descriptive text to
12629 be used for this link when it gets inserted into an Org-mode
12630 buffer with \\[org-insert-link].")
12632 (defvar org-execute-file-search-functions nil
12633 "List of functions to execute a file search triggered by a link.
12635 Functions added to this hook must accept a single argument, the
12636 search string that was part of the file link, the part after the
12637 double colon. The function must first check if it would like to
12638 handle this search, for example by checking the major-mode or the
12639 file extension. If it decides not to handle this search, it
12640 should just return nil to give other functions a chance. If it
12641 does handle the search, it must return a non-nil value to keep
12642 other functions from trying.
12644 Each function can access the current prefix argument through the
12645 variable `current-prefix-argument'. Note that a single prefix is
12646 used to force opening a link in Emacs, so it may be good to only
12647 use a numeric or double prefix to guide the search function.
12649 In case this is needed, a function in this hook can also restore
12650 the window configuration before `org-open-at-point' was called using:
12652 (set-window-configuration org-window-config-before-follow-link)")
12654 (defun org-link-search (s &optional type avoid-pos)
12655 "Search for a link search option.
12656 If S is surrounded by forward slashes, it is interpreted as a
12657 regular expression. In org-mode files, this will create an `org-occur'
12658 sparse tree. In ordinary files, `occur' will be used to list matches.
12659 If the current buffer is in `dired-mode', grep will be used to search
12660 in all files. If AVOID-POS is given, ignore matches near that position."
12661 (let ((case-fold-search t)
12662 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12663 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12664 (append '(("") (" ") ("\t") ("\n"))
12665 org-emphasis-alist)
12666 "\\|") "\\)"))
12667 (pos (point))
12668 (pre "") (post "")
12669 words re0 re1 re2 re3 re4 re5 re2a reall)
12670 (cond
12671 ;; First check if there are any special
12672 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12673 ;; Now try the builtin stuff
12674 ((save-excursion
12675 (goto-char (point-min))
12676 (and
12677 (re-search-forward
12678 (concat "<<" (regexp-quote s0) ">>") nil t)
12679 (setq pos (match-beginning 0))))
12680 ;; There is an exact target for this
12681 (goto-char pos))
12682 ((string-match "^/\\(.*\\)/$" s)
12683 ;; A regular expression
12684 (cond
12685 ((org-mode-p)
12686 (org-occur (match-string 1 s)))
12687 ;;((eq major-mode 'dired-mode)
12688 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12689 (t (org-do-occur (match-string 1 s)))))
12691 ;; A normal search strings
12692 (when (equal (string-to-char s) ?*)
12693 ;; Anchor on headlines, post may include tags.
12694 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12695 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12696 s (substring s 1)))
12697 (remove-text-properties
12698 0 (length s)
12699 '(face nil mouse-face nil keymap nil fontified nil) s)
12700 ;; Make a series of regular expressions to find a match
12701 (setq words (org-split-string s "[ \n\r\t]+")
12702 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12703 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12704 "\\)" markers)
12705 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12706 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12707 re1 (concat pre re2 post)
12708 re3 (concat pre re4 post)
12709 re5 (concat pre ".*" re4)
12710 re2 (concat pre re2)
12711 re2a (concat pre re2a)
12712 re4 (concat pre re4)
12713 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12714 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12715 re5 "\\)"
12717 (cond
12718 ((eq type 'org-occur) (org-occur reall))
12719 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12720 (t (goto-char (point-min))
12721 (if (or (org-search-not-self 1 re0 nil t)
12722 (org-search-not-self 1 re1 nil t)
12723 (org-search-not-self 1 re2 nil t)
12724 (org-search-not-self 1 re2a nil t)
12725 (org-search-not-self 1 re3 nil t)
12726 (org-search-not-self 1 re4 nil t)
12727 (org-search-not-self 1 re5 nil t)
12729 (goto-char (match-beginning 1))
12730 (goto-char pos)
12731 (error "No match")))))
12733 ;; Normal string-search
12734 (goto-char (point-min))
12735 (if (search-forward s nil t)
12736 (goto-char (match-beginning 0))
12737 (error "No match"))))
12738 (and (org-mode-p) (org-show-context 'link-search))))
12740 (defun org-search-not-self (group &rest args)
12741 "Execute `re-search-forward', but only accept matches that do not
12742 enclose the position of `org-open-link-marker'."
12743 (let ((m org-open-link-marker))
12744 (catch 'exit
12745 (while (apply 're-search-forward args)
12746 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12747 (goto-char (match-end group))
12748 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12749 (> (match-beginning 0) (marker-position m))
12750 (< (match-end 0) (marker-position m)))
12751 (save-match-data
12752 (or (not (org-in-regexp
12753 org-bracket-link-analytic-regexp 1))
12754 (not (match-end 4)) ; no description
12755 (and (<= (match-beginning 4) (point))
12756 (>= (match-end 4) (point))))))
12757 (throw 'exit (point))))))))
12759 (defun org-get-buffer-for-internal-link (buffer)
12760 "Return a buffer to be used for displaying the link target of internal links."
12761 (cond
12762 ((not org-display-internal-link-with-indirect-buffer)
12763 buffer)
12764 ((string-match "(Clone)$" (buffer-name buffer))
12765 (message "Buffer is already a clone, not making another one")
12766 ;; we also do not modify visibility in this case
12767 buffer)
12768 (t ; make a new indirect buffer for displaying the link
12769 (let* ((bn (buffer-name buffer))
12770 (ibn (concat bn "(Clone)"))
12771 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12772 (with-current-buffer ib (org-overview))
12773 ib))))
12775 (defun org-do-occur (regexp &optional cleanup)
12776 "Call the Emacs command `occur'.
12777 If CLEANUP is non-nil, remove the printout of the regular expression
12778 in the *Occur* buffer. This is useful if the regex is long and not useful
12779 to read."
12780 (occur regexp)
12781 (when cleanup
12782 (let ((cwin (selected-window)) win beg end)
12783 (when (setq win (get-buffer-window "*Occur*"))
12784 (select-window win))
12785 (goto-char (point-min))
12786 (when (re-search-forward "match[a-z]+" nil t)
12787 (setq beg (match-end 0))
12788 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12789 (setq end (1- (match-beginning 0)))))
12790 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12791 (goto-char (point-min))
12792 (select-window cwin))))
12794 ;;; The mark ring for links jumps
12796 (defvar org-mark-ring nil
12797 "Mark ring for positions before jumps in Org-mode.")
12798 (defvar org-mark-ring-last-goto nil
12799 "Last position in the mark ring used to go back.")
12800 ;; Fill and close the ring
12801 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12802 (loop for i from 1 to org-mark-ring-length do
12803 (push (make-marker) org-mark-ring))
12804 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12805 org-mark-ring)
12807 (defun org-mark-ring-push (&optional pos buffer)
12808 "Put the current position or POS into the mark ring and rotate it."
12809 (interactive)
12810 (setq pos (or pos (point)))
12811 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12812 (move-marker (car org-mark-ring)
12813 (or pos (point))
12814 (or buffer (current-buffer)))
12815 (message "%s"
12816 (substitute-command-keys
12817 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12819 (defun org-mark-ring-goto (&optional n)
12820 "Jump to the previous position in the mark ring.
12821 With prefix arg N, jump back that many stored positions. When
12822 called several times in succession, walk through the entire ring.
12823 Org-mode commands jumping to a different position in the current file,
12824 or to another Org-mode file, automatically push the old position
12825 onto the ring."
12826 (interactive "p")
12827 (let (p m)
12828 (if (eq last-command this-command)
12829 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12830 (setq p org-mark-ring))
12831 (setq org-mark-ring-last-goto p)
12832 (setq m (car p))
12833 (switch-to-buffer (marker-buffer m))
12834 (goto-char m)
12835 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12837 (defun org-remove-angle-brackets (s)
12838 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12839 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12841 (defun org-add-angle-brackets (s)
12842 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12843 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12846 ;;; Following specific links
12848 (defun org-follow-timestamp-link ()
12849 (cond
12850 ((org-at-date-range-p t)
12851 (let ((org-agenda-start-on-weekday)
12852 (t1 (match-string 1))
12853 (t2 (match-string 2)))
12854 (setq t1 (time-to-days (org-time-string-to-time t1))
12855 t2 (time-to-days (org-time-string-to-time t2)))
12856 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12857 ((org-at-timestamp-p t)
12858 (org-agenda-list nil (time-to-days (org-time-string-to-time
12859 (substring (match-string 1) 0 10)))
12861 (t (error "This should not happen"))))
12864 (defun org-follow-bbdb-link (name)
12865 "Follow a BBDB link to NAME."
12866 (require 'bbdb)
12867 (let ((inhibit-redisplay (not debug-on-error))
12868 (bbdb-electric-p nil))
12869 (catch 'exit
12870 ;; Exact match on name
12871 (bbdb-name (concat "\\`" name "\\'") nil)
12872 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12873 ;; Exact match on name
12874 (bbdb-company (concat "\\`" name "\\'") nil)
12875 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12876 ;; Partial match on name
12877 (bbdb-name name nil)
12878 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12879 ;; Partial match on company
12880 (bbdb-company name nil)
12881 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12882 ;; General match including network address and notes
12883 (bbdb name nil)
12884 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12885 (delete-window (get-buffer-window "*BBDB*"))
12886 (error "No matching BBDB record")))))
12888 (defun org-follow-info-link (name)
12889 "Follow an info file & node link to NAME."
12890 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12891 (string-match "\\(.*\\)" name))
12892 (progn
12893 (require 'info)
12894 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12895 (Info-find-node (match-string 1 name) (match-string 2 name))
12896 (Info-find-node (match-string 1 name) "Top")))
12897 (message "Could not open: %s" name)))
12899 (defun org-follow-gnus-link (&optional group article)
12900 "Follow a Gnus link to GROUP and ARTICLE."
12901 (require 'gnus)
12902 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12903 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12904 (cond ((and group article)
12905 (gnus-group-read-group 1 nil group)
12906 (gnus-summary-goto-article (string-to-number article) nil t))
12907 (group (gnus-group-jump-to-group group))))
12909 (defun org-follow-vm-link (&optional folder article readonly)
12910 "Follow a VM link to FOLDER and ARTICLE."
12911 (require 'vm)
12912 (setq article (org-add-angle-brackets article))
12913 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12914 ;; ange-ftp or efs or tramp access
12915 (let ((user (or (match-string 1 folder) (user-login-name)))
12916 (host (match-string 2 folder))
12917 (file (match-string 3 folder)))
12918 (cond
12919 ((featurep 'tramp)
12920 ;; use tramp to access the file
12921 (if (featurep 'xemacs)
12922 (setq folder (format "[%s@%s]%s" user host file))
12923 (setq folder (format "/%s@%s:%s" user host file))))
12925 ;; use ange-ftp or efs
12926 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12927 (setq folder (format "/%s@%s:%s" user host file))))))
12928 (when folder
12929 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12930 (sit-for 0.1)
12931 (when article
12932 (vm-select-folder-buffer)
12933 (widen)
12934 (let ((case-fold-search t))
12935 (goto-char (point-min))
12936 (if (not (re-search-forward
12937 (concat "^" "message-id: *" (regexp-quote article))))
12938 (error "Could not find the specified message in this folder"))
12939 (vm-isearch-update)
12940 (vm-isearch-narrow)
12941 (vm-beginning-of-message)
12942 (vm-summarize)))))
12944 (defun org-follow-wl-link (folder article)
12945 "Follow a Wanderlust link to FOLDER and ARTICLE."
12946 (if (and (string= folder "%")
12947 article
12948 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12949 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12950 ;; Thus, we recompose folder and article ids.
12951 (setq folder (format "%s#%s" folder (match-string 1 article))
12952 article (match-string 3 article)))
12953 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12954 (error "No such folder: %s" folder))
12955 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12956 (and article
12957 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12958 (wl-summary-redisplay)))
12960 (defun org-follow-rmail-link (folder article)
12961 "Follow an RMAIL link to FOLDER and ARTICLE."
12962 (setq article (org-add-angle-brackets article))
12963 (let (message-number)
12964 (save-excursion
12965 (save-window-excursion
12966 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12967 (setq message-number
12968 (save-restriction
12969 (widen)
12970 (goto-char (point-max))
12971 (if (re-search-backward
12972 (concat "^Message-ID:\\s-+" (regexp-quote
12973 (or article "")))
12974 nil t)
12975 (rmail-what-message))))))
12976 (if message-number
12977 (progn
12978 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12979 (rmail-show-message message-number)
12980 message-number)
12981 (error "Message not found"))))
12983 ;;; mh-e integration based on planner-mode
12984 (defun org-mhe-get-message-real-folder ()
12985 "Return the name of the current message real folder, so if you use
12986 sequences, it will now work."
12987 (save-excursion
12988 (let* ((folder
12989 (if (equal major-mode 'mh-folder-mode)
12990 mh-current-folder
12991 ;; Refer to the show buffer
12992 mh-show-folder-buffer))
12993 (end-index
12994 (if (boundp 'mh-index-folder)
12995 (min (length mh-index-folder) (length folder))))
12997 ;; a simple test on mh-index-data does not work, because
12998 ;; mh-index-data is always nil in a show buffer.
12999 (if (and (boundp 'mh-index-folder)
13000 (string= mh-index-folder (substring folder 0 end-index)))
13001 (if (equal major-mode 'mh-show-mode)
13002 (save-window-excursion
13003 (let (pop-up-frames)
13004 (when (buffer-live-p (get-buffer folder))
13005 (progn
13006 (pop-to-buffer folder)
13007 (org-mhe-get-message-folder-from-index)
13010 (org-mhe-get-message-folder-from-index)
13012 folder
13016 (defun org-mhe-get-message-folder-from-index ()
13017 "Returns the name of the message folder in a index folder buffer."
13018 (save-excursion
13019 (mh-index-previous-folder)
13020 (re-search-forward "^\\(+.*\\)$" nil t)
13021 (message "%s" (match-string 1))))
13023 (defun org-mhe-get-message-folder ()
13024 "Return the name of the current message folder. Be careful if you
13025 use sequences."
13026 (save-excursion
13027 (if (equal major-mode 'mh-folder-mode)
13028 mh-current-folder
13029 ;; Refer to the show buffer
13030 mh-show-folder-buffer)))
13032 (defun org-mhe-get-message-num ()
13033 "Return the number of the current message. Be careful if you
13034 use sequences."
13035 (save-excursion
13036 (if (equal major-mode 'mh-folder-mode)
13037 (mh-get-msg-num nil)
13038 ;; Refer to the show buffer
13039 (mh-show-buffer-message-number))))
13041 (defun org-mhe-get-header (header)
13042 "Return a header of the message in folder mode. This will create a
13043 show buffer for the corresponding message. If you have a more clever
13044 idea..."
13045 (let* ((folder (org-mhe-get-message-folder))
13046 (num (org-mhe-get-message-num))
13047 (buffer (get-buffer-create (concat "show-" folder)))
13048 (header-field))
13049 (with-current-buffer buffer
13050 (mh-display-msg num folder)
13051 (if (equal major-mode 'mh-folder-mode)
13052 (mh-header-display)
13053 (mh-show-header-display))
13054 (set-buffer buffer)
13055 (setq header-field (mh-get-header-field header))
13056 (if (equal major-mode 'mh-folder-mode)
13057 (mh-show)
13058 (mh-show-show))
13059 header-field)))
13061 (defun org-follow-mhe-link (folder article)
13062 "Follow an MHE link to FOLDER and ARTICLE.
13063 If ARTICLE is nil FOLDER is shown. If the configuration variable
13064 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13065 ARTICLE is searched in all folders. Indexed searches (swish++,
13066 namazu, and others supported by MH-E) will always search in all
13067 folders."
13068 (require 'mh-e)
13069 (require 'mh-search)
13070 (require 'mh-utils)
13071 (mh-find-path)
13072 (if (not article)
13073 (mh-visit-folder (mh-normalize-folder-name folder))
13074 (setq article (org-add-angle-brackets article))
13075 (mh-search-choose)
13076 (if (equal mh-searcher 'pick)
13077 (progn
13078 (mh-search folder (list "--message-id" article))
13079 (when (and org-mhe-search-all-folders
13080 (not (org-mhe-get-message-real-folder)))
13081 (kill-this-buffer)
13082 (mh-search "+" (list "--message-id" article))))
13083 (mh-search "+" article))
13084 (if (org-mhe-get-message-real-folder)
13085 (mh-show-msg 1)
13086 (kill-this-buffer)
13087 (error "Message not found"))))
13089 ;;; BibTeX links
13091 ;; Use the custom search meachnism to construct and use search strings for
13092 ;; file links to BibTeX database entries.
13094 (defun org-create-file-search-in-bibtex ()
13095 "Create the search string and description for a BibTeX database entry."
13096 (when (eq major-mode 'bibtex-mode)
13097 ;; yes, we want to construct this search string.
13098 ;; Make a good description for this entry, using names, year and the title
13099 ;; Put it into the `description' variable which is dynamically scoped.
13100 (let ((bibtex-autokey-names 1)
13101 (bibtex-autokey-names-stretch 1)
13102 (bibtex-autokey-name-case-convert-function 'identity)
13103 (bibtex-autokey-name-separator " & ")
13104 (bibtex-autokey-additional-names " et al.")
13105 (bibtex-autokey-year-length 4)
13106 (bibtex-autokey-name-year-separator " ")
13107 (bibtex-autokey-titlewords 3)
13108 (bibtex-autokey-titleword-separator " ")
13109 (bibtex-autokey-titleword-case-convert-function 'identity)
13110 (bibtex-autokey-titleword-length 'infty)
13111 (bibtex-autokey-year-title-separator ": "))
13112 (setq description (bibtex-generate-autokey)))
13113 ;; Now parse the entry, get the key and return it.
13114 (save-excursion
13115 (bibtex-beginning-of-entry)
13116 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13118 (defun org-execute-file-search-in-bibtex (s)
13119 "Find the link search string S as a key for a database entry."
13120 (when (eq major-mode 'bibtex-mode)
13121 ;; Yes, we want to do the search in this file.
13122 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13123 (goto-char (point-min))
13124 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13125 (regexp-quote s) "[ \t\n]*,") nil t)
13126 (goto-char (match-beginning 0)))
13127 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13128 ;; Use double prefix to indicate that any web link should be browsed
13129 (let ((b (current-buffer)) (p (point)))
13130 ;; Restore the window configuration because we just use the web link
13131 (set-window-configuration org-window-config-before-follow-link)
13132 (save-excursion (set-buffer b) (goto-char p)
13133 (bibtex-url)))
13134 (recenter 0)) ; Move entry start to beginning of window
13135 ;; return t to indicate that the search is done.
13138 ;; Finally add the functions to the right hooks.
13139 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13140 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13142 ;; end of Bibtex link setup
13144 ;;; Following file links
13146 (defun org-open-file (path &optional in-emacs line search)
13147 "Open the file at PATH.
13148 First, this expands any special file name abbreviations. Then the
13149 configuration variable `org-file-apps' is checked if it contains an
13150 entry for this file type, and if yes, the corresponding command is launched.
13151 If no application is found, Emacs simply visits the file.
13152 With optional argument IN-EMACS, Emacs will visit the file.
13153 Optional LINE specifies a line to go to, optional SEARCH a string to
13154 search for. If LINE or SEARCH is given, the file will always be
13155 opened in Emacs.
13156 If the file does not exist, an error is thrown."
13157 (setq in-emacs (or in-emacs line search))
13158 (let* ((file (if (equal path "")
13159 buffer-file-name
13160 (substitute-in-file-name (expand-file-name path))))
13161 (apps (append org-file-apps (org-default-apps)))
13162 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13163 (dirp (if remp nil (file-directory-p file)))
13164 (dfile (downcase file))
13165 (old-buffer (current-buffer))
13166 (old-pos (point))
13167 (old-mode major-mode)
13168 ext cmd)
13169 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13170 (setq ext (match-string 1 dfile))
13171 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13172 (setq ext (match-string 1 dfile))))
13173 (if in-emacs
13174 (setq cmd 'emacs)
13175 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13176 (and dirp (cdr (assoc 'directory apps)))
13177 (cdr (assoc ext apps))
13178 (cdr (assoc t apps)))))
13179 (when (eq cmd 'mailcap)
13180 (require 'mailcap)
13181 (mailcap-parse-mailcaps)
13182 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13183 (command (mailcap-mime-info mime-type)))
13184 (if (stringp command)
13185 (setq cmd command)
13186 (setq cmd 'emacs))))
13187 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13188 (not (file-exists-p file))
13189 (not org-open-non-existing-files))
13190 (error "No such file: %s" file))
13191 (cond
13192 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13193 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13194 (while (string-match "['\"]%s['\"]" cmd)
13195 (setq cmd (replace-match "%s" t t cmd)))
13196 (while (string-match "%s" cmd)
13197 (setq cmd (replace-match (shell-quote-argument file) t t cmd)))
13198 (save-window-excursion
13199 (start-process-shell-command cmd nil cmd)))
13200 ((or (stringp cmd)
13201 (eq cmd 'emacs))
13202 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13203 (widen)
13204 (if line (goto-line line)
13205 (if search (org-link-search search))))
13206 ((consp cmd)
13207 (eval cmd))
13208 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13209 (and (org-mode-p) (eq old-mode 'org-mode)
13210 (or (not (equal old-buffer (current-buffer)))
13211 (not (equal old-pos (point))))
13212 (org-mark-ring-push old-pos old-buffer))))
13214 (defun org-default-apps ()
13215 "Return the default applications for this operating system."
13216 (cond
13217 ((eq system-type 'darwin)
13218 org-file-apps-defaults-macosx)
13219 ((eq system-type 'windows-nt)
13220 org-file-apps-defaults-windowsnt)
13221 (t org-file-apps-defaults-gnu)))
13223 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13224 (defun org-file-remote-p (file)
13225 "Test whether FILE specifies a location on a remote system.
13226 Return non-nil if the location is indeed remote.
13228 For example, the filename \"/user@host:/foo\" specifies a location
13229 on the system \"/user@host:\"."
13230 (cond ((fboundp 'file-remote-p)
13231 (file-remote-p file))
13232 ((fboundp 'tramp-handle-file-remote-p)
13233 (tramp-handle-file-remote-p file))
13234 ((and (boundp 'ange-ftp-name-format)
13235 (string-match (car ange-ftp-name-format) file))
13237 (t nil)))
13240 ;;;; Hooks for remember.el, and refiling
13242 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13243 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13245 ;;;###autoload
13246 (defun org-remember-insinuate ()
13247 "Setup remember.el for use wiht Org-mode."
13248 (require 'remember)
13249 (setq remember-annotation-functions '(org-remember-annotation))
13250 (setq remember-handler-functions '(org-remember-handler))
13251 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13253 ;;;###autoload
13254 (defun org-remember-annotation ()
13255 "Return a link to the current location as an annotation for remember.el.
13256 If you are using Org-mode files as target for data storage with
13257 remember.el, then the annotations should include a link compatible with the
13258 conventions in Org-mode. This function returns such a link."
13259 (org-store-link nil))
13261 (defconst org-remember-help
13262 "Select a destination location for the note.
13263 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13264 RET on headline -> Store as sublevel entry to current headline
13265 RET at beg-of-buf -> Append to file as level 2 headline
13266 <left>/<right> -> before/after current headline, same headings level")
13268 (defvar org-remember-previous-location nil)
13269 (defvar org-force-remember-template-char) ;; dynamically scoped
13271 (defun org-select-remember-template (&optional use-char)
13272 (when org-remember-templates
13273 (let* ((templates (mapcar (lambda (x)
13274 (if (stringp (car x))
13275 (append (list (nth 1 x) (car x)) (cddr x))
13276 (append (list (car x) "") (cdr x))))
13277 org-remember-templates))
13278 (char (or use-char
13279 (cond
13280 ((= (length templates) 1)
13281 (caar templates))
13282 ((and (boundp 'org-force-remember-template-char)
13283 org-force-remember-template-char)
13284 (if (stringp org-force-remember-template-char)
13285 (string-to-char org-force-remember-template-char)
13286 org-force-remember-template-char))
13288 (message "Select template: %s"
13289 (mapconcat
13290 (lambda (x)
13291 (cond
13292 ((not (string-match "\\S-" (nth 1 x)))
13293 (format "[%c]" (car x)))
13294 ((equal (downcase (car x))
13295 (downcase (aref (nth 1 x) 0)))
13296 (format "[%c]%s" (car x)
13297 (substring (nth 1 x) 1)))
13298 (t (format "[%c]%s" (car x) (nth 1 x)))))
13299 templates " "))
13300 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13301 (when (equal char0 ?\C-g)
13302 (jump-to-register remember-register)
13303 (kill-buffer remember-buffer))
13304 char0))))))
13305 (cddr (assoc char templates)))))
13307 (defvar x-last-selected-text)
13308 (defvar x-last-selected-text-primary)
13310 ;;;###autoload
13311 (defun org-remember-apply-template (&optional use-char skip-interactive)
13312 "Initialize *remember* buffer with template, invoke `org-mode'.
13313 This function should be placed into `remember-mode-hook' and in fact requires
13314 to be run from that hook to function properly."
13315 (unless (fboundp 'remember-finalize)
13316 (defalias 'remember-finalize 'remember-buffer))
13317 (if org-remember-templates
13318 (let* ((entry (org-select-remember-template use-char))
13319 (tpl (car entry))
13320 (plist-p (if org-store-link-plist t nil))
13321 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13322 (string-match "\\S-" (nth 1 entry)))
13323 (nth 1 entry)
13324 org-default-notes-file))
13325 (headline (nth 2 entry))
13326 (v-c (or (and (eq window-system 'x)
13327 (fboundp 'x-cut-buffer-or-selection-value)
13328 (x-cut-buffer-or-selection-value))
13329 (org-bound-and-true-p x-last-selected-text)
13330 (org-bound-and-true-p x-last-selected-text-primary)
13331 (and (> (length kill-ring) 0) (current-kill 0))))
13332 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13333 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13334 (v-u (concat "[" (substring v-t 1 -1) "]"))
13335 (v-U (concat "[" (substring v-T 1 -1) "]"))
13336 ;; `initial' and `annotation' are bound in `remember'
13337 (v-i (if (boundp 'initial) initial))
13338 (v-a (if (and (boundp 'annotation) annotation)
13339 (if (equal annotation "[[]]") "" annotation)
13340 ""))
13341 (v-A (if (and v-a
13342 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13343 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13344 v-a))
13345 (v-n user-full-name)
13346 (org-startup-folded nil)
13347 org-time-was-given org-end-time-was-given x
13348 prompt completions char time pos default histvar)
13349 (setq org-store-link-plist
13350 (append (list :annotation v-a :initial v-i)
13351 org-store-link-plist))
13352 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13353 (erase-buffer)
13354 (insert (substitute-command-keys
13355 (format
13356 "## Filing location: Select interactively, default, or last used:
13357 ## %s to select file and header location interactively.
13358 ## %s \"%s\" -> \"* %s\"
13359 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13360 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13361 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13362 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13363 (abbreviate-file-name (or file org-default-notes-file))
13364 (or headline "")
13365 (or (car org-remember-previous-location) "???")
13366 (or (cdr org-remember-previous-location) "???"))))
13367 (insert tpl) (goto-char (point-min))
13368 ;; Simple %-escapes
13369 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13370 (when (and initial (equal (match-string 0) "%i"))
13371 (save-match-data
13372 (let* ((lead (buffer-substring
13373 (point-at-bol) (match-beginning 0))))
13374 (setq v-i (mapconcat 'identity
13375 (org-split-string initial "\n")
13376 (concat "\n" lead))))))
13377 (replace-match
13378 (or (eval (intern (concat "v-" (match-string 1)))) "")
13379 t t))
13381 ;; %[] Insert contents of a file.
13382 (goto-char (point-min))
13383 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13384 (let ((start (match-beginning 0))
13385 (end (match-end 0))
13386 (filename (expand-file-name (match-string 1))))
13387 (goto-char start)
13388 (delete-region start end)
13389 (condition-case error
13390 (insert-file-contents filename)
13391 (error (insert (format "%%![Couldn't insert %s: %s]"
13392 filename error))))))
13393 ;; %() embedded elisp
13394 (goto-char (point-min))
13395 (while (re-search-forward "%\\((.+)\\)" nil t)
13396 (goto-char (match-beginning 0))
13397 (let ((template-start (point)))
13398 (forward-char 1)
13399 (let ((result
13400 (condition-case error
13401 (eval (read (current-buffer)))
13402 (error (format "%%![Error: %s]" error)))))
13403 (delete-region template-start (point))
13404 (insert result))))
13406 ;; From the property list
13407 (when plist-p
13408 (goto-char (point-min))
13409 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13410 (and (setq x (or (plist-get org-store-link-plist
13411 (intern (match-string 1))) ""))
13412 (replace-match x t t))))
13414 ;; Turn on org-mode in the remember buffer, set local variables
13415 (org-mode)
13416 (org-set-local 'org-finish-function 'remember-finalize)
13417 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13418 (org-set-local 'org-default-notes-file file))
13419 (if (and headline (stringp headline) (string-match "\\S-" headline))
13420 (org-set-local 'org-remember-default-headline headline))
13421 ;; Interactive template entries
13422 (goto-char (point-min))
13423 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
13424 (setq char (if (match-end 3) (match-string 3))
13425 prompt (if (match-end 2) (match-string 2)))
13426 (goto-char (match-beginning 0))
13427 (replace-match "")
13428 (setq completions nil default nil)
13429 (when prompt
13430 (setq completions (org-split-string prompt "|")
13431 prompt (pop completions)
13432 default (car completions)
13433 histvar (intern (concat
13434 "org-remember-template-prompt-history::"
13435 (or prompt "")))
13436 completions (mapcar 'list completions)))
13437 (cond
13438 ((member char '("G" "g"))
13439 (let* ((org-last-tags-completion-table
13440 (org-global-tags-completion-table
13441 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13442 (org-add-colon-after-tag-completion t)
13443 (ins (completing-read
13444 (if prompt (concat prompt ": ") "Tags: ")
13445 'org-tags-completion-function nil nil nil
13446 'org-tags-history)))
13447 (setq ins (mapconcat 'identity
13448 (org-split-string ins (org-re "[^[:alnum:]]+"))
13449 ":"))
13450 (when (string-match "\\S-" ins)
13451 (or (equal (char-before) ?:) (insert ":"))
13452 (insert ins)
13453 (or (equal (char-after) ?:) (insert ":")))))
13454 (char
13455 (setq org-time-was-given (equal (upcase char) char))
13456 (setq time (org-read-date (equal (upcase char) "U") t nil
13457 prompt))
13458 (org-insert-time-stamp time org-time-was-given
13459 (member char '("u" "U"))
13460 nil nil (list org-end-time-was-given)))
13462 (insert (org-completing-read
13463 (concat (if prompt prompt "Enter string")
13464 (if default (concat " [" default "]"))
13465 ": ")
13466 completions nil nil nil histvar default)))))
13467 (goto-char (point-min))
13468 (if (re-search-forward "%\\?" nil t)
13469 (replace-match "")
13470 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13471 (org-mode)
13472 (org-set-local 'org-finish-function 'remember-finalize))
13473 (when (save-excursion
13474 (goto-char (point-min))
13475 (re-search-forward "%!" nil t))
13476 (replace-match "")
13477 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13479 (defun org-remember-finish-immediately ()
13480 "File remember note immediately.
13481 This should be run in `post-command-hook' and will remove itself
13482 from that hook."
13483 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13484 (when org-finish-function
13485 (funcall org-finish-function)))
13488 ;;;###autoload
13489 (defun org-remember (&optional goto org-force-remember-template-char)
13490 "Call `remember'. If this is already a remember buffer, re-apply template.
13491 If there is an active region, make sure remember uses it as initial content
13492 of the remember buffer.
13494 When called interactively with a `C-u' prefix argument GOTO, don't remember
13495 anything, just go to the file/headline where the selected template usually
13496 stores its notes. With a double prefix arg `C-u C-u', go to the last
13497 note stored by remember.
13499 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13500 associated with a template in `org-remember-templates'."
13501 (interactive "P")
13502 (cond
13503 ((equal goto '(4)) (org-go-to-remember-target))
13504 ((equal goto '(16)) (org-remember-goto-last-stored))
13506 (if (memq org-finish-function '(remember-buffer remember-finalize))
13507 (progn
13508 (when (< (length org-remember-templates) 2)
13509 (error "No other template available"))
13510 (erase-buffer)
13511 (let ((annotation (plist-get org-store-link-plist :annotation))
13512 (initial (plist-get org-store-link-plist :initial)))
13513 (org-remember-apply-template))
13514 (message "Press C-c C-c to remember data"))
13515 (if (org-region-active-p)
13516 (remember (buffer-substring (point) (mark)))
13517 (call-interactively 'remember))))))
13519 (defun org-remember-goto-last-stored ()
13520 "Go to the location where the last remember note was stored."
13521 (interactive)
13522 (bookmark-jump "org-remember-last-stored")
13523 (message "This is the last note stored by remember"))
13525 (defun org-go-to-remember-target (&optional template-key)
13526 "Go to the target location of a remember template.
13527 The user is queried for the template."
13528 (interactive)
13529 (let* ((entry (org-select-remember-template template-key))
13530 (file (nth 1 entry))
13531 (heading (nth 2 entry))
13532 visiting)
13533 (unless (and file (stringp file) (string-match "\\S-" file))
13534 (setq file org-default-notes-file))
13535 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13536 (setq heading org-remember-default-headline))
13537 (setq visiting (org-find-base-buffer-visiting file))
13538 (if (not visiting) (find-file-noselect file))
13539 (switch-to-buffer (or visiting (get-file-buffer file)))
13540 (widen)
13541 (goto-char (point-min))
13542 (if (re-search-forward
13543 (concat "^\\*+[ \t]+" (regexp-quote heading)
13544 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13545 nil t)
13546 (goto-char (match-beginning 0))
13547 (error "Target headline not found: %s" heading))))
13549 (defvar org-note-abort nil) ; dynamically scoped
13551 ;;;###autoload
13552 (defun org-remember-handler ()
13553 "Store stuff from remember.el into an org file.
13554 First prompts for an org file. If the user just presses return, the value
13555 of `org-default-notes-file' is used.
13556 Then the command offers the headings tree of the selected file in order to
13557 file the text at a specific location.
13558 You can either immediately press RET to get the note appended to the
13559 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13560 find a better place. Then press RET or <left> or <right> in insert the note.
13562 Key Cursor position Note gets inserted
13563 -----------------------------------------------------------------------------
13564 RET buffer-start as level 1 heading at end of file
13565 RET on headline as sublevel of the heading at cursor
13566 RET no heading at cursor position, level taken from context.
13567 Or use prefix arg to specify level manually.
13568 <left> on headline as same level, before current heading
13569 <right> on headline as same level, after current heading
13571 So the fastest way to store the note is to press RET RET to append it to
13572 the default file. This way your current train of thought is not
13573 interrupted, in accordance with the principles of remember.el.
13574 You can also get the fast execution without prompting by using
13575 C-u C-c C-c to exit the remember buffer. See also the variable
13576 `org-remember-store-without-prompt'.
13578 Before being stored away, the function ensures that the text has a
13579 headline, i.e. a first line that starts with a \"*\". If not, a headline
13580 is constructed from the current date and some additional data.
13582 If the variable `org-adapt-indentation' is non-nil, the entire text is
13583 also indented so that it starts in the same column as the headline
13584 \(i.e. after the stars).
13586 See also the variable `org-reverse-note-order'."
13587 (goto-char (point-min))
13588 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13589 (replace-match ""))
13590 (goto-char (point-max))
13591 (beginning-of-line 1)
13592 (while (looking-at "[ \t]*$\\|##.*")
13593 (delete-region (1- (point)) (point-max))
13594 (beginning-of-line 1))
13595 (catch 'quit
13596 (if org-note-abort (throw 'quit nil))
13597 (let* ((txt (buffer-substring (point-min) (point-max)))
13598 (fastp (org-xor (equal current-prefix-arg '(4))
13599 org-remember-store-without-prompt))
13600 (file (cond
13601 (fastp org-default-notes-file)
13602 ((and org-remember-use-refile-when-interactive
13603 org-refile-targets)
13604 org-default-notes-file)
13605 (t (org-get-org-file))))
13606 (heading org-remember-default-headline)
13607 (visiting (and file (org-find-base-buffer-visiting file)))
13608 (org-startup-folded nil)
13609 (org-startup-align-all-tables nil)
13610 (org-goto-start-pos 1)
13611 spos exitcmd level indent reversed)
13612 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13613 (setq file (car org-remember-previous-location)
13614 heading (cdr org-remember-previous-location)
13615 fastp t))
13616 (setq current-prefix-arg nil)
13617 (if (string-match "[ \t\n]+\\'" txt)
13618 (setq txt (replace-match "" t t txt)))
13619 ;; Modify text so that it becomes a nice subtree which can be inserted
13620 ;; into an org tree.
13621 (let* ((lines (split-string txt "\n"))
13622 first)
13623 (setq first (car lines) lines (cdr lines))
13624 (if (string-match "^\\*+ " first)
13625 ;; Is already a headline
13626 (setq indent nil)
13627 ;; We need to add a headline: Use time and first buffer line
13628 (setq lines (cons first lines)
13629 first (concat "* " (current-time-string)
13630 " (" (remember-buffer-desc) ")")
13631 indent " "))
13632 (if (and org-adapt-indentation indent)
13633 (setq lines (mapcar
13634 (lambda (x)
13635 (if (string-match "\\S-" x)
13636 (concat indent x) x))
13637 lines)))
13638 (setq txt (concat first "\n"
13639 (mapconcat 'identity lines "\n"))))
13640 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13641 (setq txt (replace-match "\n\n" t t txt))
13642 (if (string-match "[ \t\n]*\\'" txt)
13643 (setq txt (replace-match "\n" t t txt))))
13644 ;; Put the modified text back into the remember buffer, for refile.
13645 (erase-buffer)
13646 (insert txt)
13647 (goto-char (point-min))
13648 (when (and org-remember-use-refile-when-interactive
13649 (not fastp))
13650 (org-refile nil (or visiting (find-file-noselect file)))
13651 (throw 'quit t))
13652 ;; Find the file
13653 (if (not visiting) (find-file-noselect file))
13654 (with-current-buffer (or visiting (get-file-buffer file))
13655 (unless (org-mode-p)
13656 (error "Target files for remember notes must be in Org-mode"))
13657 (save-excursion
13658 (save-restriction
13659 (widen)
13660 (and (goto-char (point-min))
13661 (not (re-search-forward "^\\* " nil t))
13662 (insert "\n* " (or heading "Notes") "\n"))
13663 (setq reversed (org-notes-order-reversed-p))
13665 ;; Find the default location
13666 (when (and heading (stringp heading) (string-match "\\S-" heading))
13667 (goto-char (point-min))
13668 (if (re-search-forward
13669 (concat "^\\*+[ \t]+" (regexp-quote heading)
13670 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13671 nil t)
13672 (setq org-goto-start-pos (match-beginning 0))
13673 (when fastp
13674 (goto-char (point-max))
13675 (unless (bolp) (newline))
13676 (insert "* " heading "\n")
13677 (setq org-goto-start-pos (point-at-bol 0)))))
13679 ;; Ask the User for a location
13680 (if fastp
13681 (setq spos org-goto-start-pos
13682 exitcmd 'return)
13683 (setq spos (org-get-location (current-buffer) org-remember-help)
13684 exitcmd (cdr spos)
13685 spos (car spos)))
13686 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13687 ; not handle this note
13688 (goto-char spos)
13689 (cond ((org-on-heading-p t)
13690 (org-back-to-heading t)
13691 (setq level (funcall outline-level))
13692 (cond
13693 ((eq exitcmd 'return)
13694 ;; sublevel of current
13695 (setq org-remember-previous-location
13696 (cons (abbreviate-file-name file)
13697 (org-get-heading 'notags)))
13698 (if reversed
13699 (outline-next-heading)
13700 (org-end-of-subtree t)
13701 (if (not (bolp))
13702 (if (looking-at "[ \t]*\n")
13703 (beginning-of-line 2)
13704 (end-of-line 1)
13705 (insert "\n"))))
13706 (bookmark-set "org-remember-last-stored")
13707 (org-paste-subtree (org-get-legal-level level 1) txt))
13708 ((eq exitcmd 'left)
13709 ;; before current
13710 (bookmark-set "org-remember-last-stored")
13711 (org-paste-subtree level txt))
13712 ((eq exitcmd 'right)
13713 ;; after current
13714 (org-end-of-subtree t)
13715 (bookmark-set "org-remember-last-stored")
13716 (org-paste-subtree level txt))
13717 (t (error "This should not happen"))))
13719 ((and (bobp) (not reversed))
13720 ;; Put it at the end, one level below level 1
13721 (save-restriction
13722 (widen)
13723 (goto-char (point-max))
13724 (if (not (bolp)) (newline))
13725 (bookmark-set "org-remember-last-stored")
13726 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13728 ((and (bobp) reversed)
13729 ;; Put it at the start, as level 1
13730 (save-restriction
13731 (widen)
13732 (goto-char (point-min))
13733 (re-search-forward "^\\*+ " nil t)
13734 (beginning-of-line 1)
13735 (bookmark-set "org-remember-last-stored")
13736 (org-paste-subtree 1 txt)))
13738 ;; Put it right there, with automatic level determined by
13739 ;; org-paste-subtree or from prefix arg
13740 (bookmark-set "org-remember-last-stored")
13741 (org-paste-subtree
13742 (if (numberp current-prefix-arg) current-prefix-arg)
13743 txt)))
13744 (when remember-save-after-remembering
13745 (save-buffer)
13746 (if (not visiting) (kill-buffer (current-buffer)))))))))
13748 t) ;; return t to indicate that we took care of this note.
13750 (defun org-get-org-file ()
13751 "Read a filename, with default directory `org-directory'."
13752 (let ((default (or org-default-notes-file remember-data-file)))
13753 (read-file-name (format "File name [%s]: " default)
13754 (file-name-as-directory org-directory)
13755 default)))
13757 (defun org-notes-order-reversed-p ()
13758 "Check if the current file should receive notes in reversed order."
13759 (cond
13760 ((not org-reverse-note-order) nil)
13761 ((eq t org-reverse-note-order) t)
13762 ((not (listp org-reverse-note-order)) nil)
13763 (t (catch 'exit
13764 (let ((all org-reverse-note-order)
13765 entry)
13766 (while (setq entry (pop all))
13767 (if (string-match (car entry) buffer-file-name)
13768 (throw 'exit (cdr entry))))
13769 nil)))))
13771 ;;; Refiling
13773 (defvar org-refile-target-table nil
13774 "The list of refile targets, created by `org-refile'.")
13776 (defvar org-agenda-new-buffers nil
13777 "Buffers created to visit agenda files.")
13779 (defun org-get-refile-targets (&optional default-buffer)
13780 "Produce a table with refile targets."
13781 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13782 org-agenda-new-buffers targets txt re files f desc descre)
13783 (with-current-buffer (or default-buffer (current-buffer))
13784 (while (setq entry (pop entries))
13785 (setq files (car entry) desc (cdr entry))
13786 (cond
13787 ((null files) (setq files (list (current-buffer))))
13788 ((eq files 'org-agenda-files)
13789 (setq files (org-agenda-files 'unrestricted)))
13790 ((and (symbolp files) (fboundp files))
13791 (setq files (funcall files)))
13792 ((and (symbolp files) (boundp files))
13793 (setq files (symbol-value files))))
13794 (if (stringp files) (setq files (list files)))
13795 (cond
13796 ((eq (car desc) :tag)
13797 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13798 ((eq (car desc) :todo)
13799 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13800 ((eq (car desc) :regexp)
13801 (setq descre (cdr desc)))
13802 ((eq (car desc) :level)
13803 (setq descre (concat "^\\*\\{" (number-to-string
13804 (if org-odd-levels-only
13805 (1- (* 2 (cdr desc)))
13806 (cdr desc)))
13807 "\\}[ \t]")))
13808 ((eq (car desc) :maxlevel)
13809 (setq descre (concat "^\\*\\{1," (number-to-string
13810 (if org-odd-levels-only
13811 (1- (* 2 (cdr desc)))
13812 (cdr desc)))
13813 "\\}[ \t]")))
13814 (t (error "Bad refiling target description %s" desc)))
13815 (while (setq f (pop files))
13816 (save-excursion
13817 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13818 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13819 (save-excursion
13820 (save-restriction
13821 (widen)
13822 (goto-char (point-min))
13823 (while (re-search-forward descre nil t)
13824 (goto-char (point-at-bol))
13825 (when (looking-at org-complex-heading-regexp)
13826 (setq txt (match-string 4)
13827 re (concat "^" (regexp-quote
13828 (buffer-substring (match-beginning 1)
13829 (match-end 4)))))
13830 (if (match-end 5) (setq re (concat re "[ \t]+"
13831 (regexp-quote
13832 (match-string 5)))))
13833 (setq re (concat re "[ \t]*$"))
13834 (when org-refile-use-outline-path
13835 (setq txt (mapconcat 'identity
13836 (append
13837 (if (eq org-refile-use-outline-path 'file)
13838 (list (file-name-nondirectory
13839 (buffer-file-name (buffer-base-buffer))))
13840 (if (eq org-refile-use-outline-path 'full-file-path)
13841 (list (buffer-file-name (buffer-base-buffer)))))
13842 (org-get-outline-path)
13843 (list txt))
13844 "/")))
13845 (push (list txt f re (point)) targets))
13846 (goto-char (point-at-eol))))))))
13847 (org-release-buffers org-agenda-new-buffers)
13848 (nreverse targets))))
13850 (defun org-get-outline-path ()
13851 (let (rtn)
13852 (save-excursion
13853 (while (org-up-heading-safe)
13854 (when (looking-at org-complex-heading-regexp)
13855 (push (org-match-string-no-properties 4) rtn)))
13856 rtn)))
13858 (defvar org-refile-history nil
13859 "History for refiling operations.")
13861 (defun org-refile (&optional reversed-or-update default-buffer)
13862 "Move the entry at point to another heading.
13863 The list of target headings is compiled using the information in
13864 `org-refile-targets', which see. This list is created upon first use, and
13865 you can update it by calling this command with a double prefix (`C-u C-u').
13866 FIXME: Can we find a better way of updating?
13868 At the target location, the entry is filed as a subitem of the target heading.
13869 Depending on `org-reverse-note-order', the new subitem will either be the
13870 first of the last subitem. A single C-u prefix will toggle the value of this
13871 variable for the duration of the command."
13872 (interactive "P")
13873 (if (equal reversed-or-update '(16))
13874 (progn
13875 (setq org-refile-target-table (org-get-refile-targets default-buffer))
13876 (message "Refile targets updated (%d targets)"
13877 (length org-refile-target-table)))
13878 (when (or (not org-refile-target-table)
13879 (assq nil org-refile-targets))
13880 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
13881 (unless org-refile-target-table
13882 (error "No refile targets"))
13883 (let* ((cbuf (current-buffer))
13884 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13885 (fname (and filename (file-truename filename)))
13886 (tbl (mapcar
13887 (lambda (x)
13888 (if (not (equal fname (file-truename (nth 1 x))))
13889 (cons (concat (car x) " (" (file-name-nondirectory
13890 (nth 1 x)) ")")
13891 (cdr x))
13893 org-refile-target-table))
13894 (completion-ignore-case t)
13895 pos it nbuf file re level reversed)
13896 (when (setq it (completing-read "Refile to: " tbl
13897 nil t nil 'org-refile-history))
13898 (setq it (assoc it tbl)
13899 file (nth 1 it)
13900 re (nth 2 it))
13901 (org-copy-special)
13902 (save-excursion
13903 (set-buffer (setq nbuf (or (find-buffer-visiting file)
13904 (find-file-noselect file))))
13905 (setq reversed (org-notes-order-reversed-p))
13906 (if (equal reversed-or-update '(16)) (setq reversed (not reversed)))
13907 (save-excursion
13908 (save-restriction
13909 (widen)
13910 (goto-char (point-min))
13911 (unless (re-search-forward re nil t)
13912 (error "Cannot find target location - try again with `C-u' prefix."))
13913 (goto-char (match-beginning 0))
13914 (looking-at outline-regexp)
13915 (setq level (org-get-legal-level (funcall outline-level) 1))
13916 (goto-char (or (save-excursion
13917 (if reversed
13918 (outline-next-heading)
13919 (outline-get-next-sibling)))
13920 (point-max)))
13921 (org-paste-subtree level))))
13922 (org-cut-special)
13923 (message "Entry refiled to \"%s\"" (car it))))))
13925 ;;;; Dynamic blocks
13927 (defun org-find-dblock (name)
13928 "Find the first dynamic block with name NAME in the buffer.
13929 If not found, stay at current position and return nil."
13930 (let (pos)
13931 (save-excursion
13932 (goto-char (point-min))
13933 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13934 nil t)
13935 (match-beginning 0))))
13936 (if pos (goto-char pos))
13937 pos))
13939 (defconst org-dblock-start-re
13940 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13941 "Matches the startline of a dynamic block, with parameters.")
13943 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13944 "Matches the end of a dyhamic block.")
13946 (defun org-create-dblock (plist)
13947 "Create a dynamic block section, with parameters taken from PLIST.
13948 PLIST must containe a :name entry which is used as name of the block."
13949 (unless (bolp) (newline))
13950 (let ((name (plist-get plist :name)))
13951 (insert "#+BEGIN: " name)
13952 (while plist
13953 (if (eq (car plist) :name)
13954 (setq plist (cddr plist))
13955 (insert " " (prin1-to-string (pop plist)))))
13956 (insert "\n\n#+END:\n")
13957 (beginning-of-line -2)))
13959 (defun org-prepare-dblock ()
13960 "Prepare dynamic block for refresh.
13961 This empties the block, puts the cursor at the insert position and returns
13962 the property list including an extra property :name with the block name."
13963 (unless (looking-at org-dblock-start-re)
13964 (error "Not at a dynamic block"))
13965 (let* ((begdel (1+ (match-end 0)))
13966 (name (org-no-properties (match-string 1)))
13967 (params (append (list :name name)
13968 (read (concat "(" (match-string 3) ")")))))
13969 (unless (re-search-forward org-dblock-end-re nil t)
13970 (error "Dynamic block not terminated"))
13971 (delete-region begdel (match-beginning 0))
13972 (goto-char begdel)
13973 (open-line 1)
13974 params))
13976 (defun org-map-dblocks (&optional command)
13977 "Apply COMMAND to all dynamic blocks in the current buffer.
13978 If COMMAND is not given, use `org-update-dblock'."
13979 (let ((cmd (or command 'org-update-dblock))
13980 pos)
13981 (save-excursion
13982 (goto-char (point-min))
13983 (while (re-search-forward org-dblock-start-re nil t)
13984 (goto-char (setq pos (match-beginning 0)))
13985 (condition-case nil
13986 (funcall cmd)
13987 (error (message "Error during update of dynamic block")))
13988 (goto-char pos)
13989 (unless (re-search-forward org-dblock-end-re nil t)
13990 (error "Dynamic block not terminated"))))))
13992 (defun org-dblock-update (&optional arg)
13993 "User command for updating dynamic blocks.
13994 Update the dynamic block at point. With prefix ARG, update all dynamic
13995 blocks in the buffer."
13996 (interactive "P")
13997 (if arg
13998 (org-update-all-dblocks)
13999 (or (looking-at org-dblock-start-re)
14000 (org-beginning-of-dblock))
14001 (org-update-dblock)))
14003 (defun org-update-dblock ()
14004 "Update the dynamic block at point
14005 This means to empty the block, parse for parameters and then call
14006 the correct writing function."
14007 (save-window-excursion
14008 (let* ((pos (point))
14009 (line (org-current-line))
14010 (params (org-prepare-dblock))
14011 (name (plist-get params :name))
14012 (cmd (intern (concat "org-dblock-write:" name))))
14013 (message "Updating dynamic block `%s' at line %d..." name line)
14014 (funcall cmd params)
14015 (message "Updating dynamic block `%s' at line %d...done" name line)
14016 (goto-char pos))))
14018 (defun org-beginning-of-dblock ()
14019 "Find the beginning of the dynamic block at point.
14020 Error if there is no scuh block at point."
14021 (let ((pos (point))
14022 beg)
14023 (end-of-line 1)
14024 (if (and (re-search-backward org-dblock-start-re nil t)
14025 (setq beg (match-beginning 0))
14026 (re-search-forward org-dblock-end-re nil t)
14027 (> (match-end 0) pos))
14028 (goto-char beg)
14029 (goto-char pos)
14030 (error "Not in a dynamic block"))))
14032 (defun org-update-all-dblocks ()
14033 "Update all dynamic blocks in the buffer.
14034 This function can be used in a hook."
14035 (when (org-mode-p)
14036 (org-map-dblocks 'org-update-dblock)))
14039 ;;;; Completion
14041 (defconst org-additional-option-like-keywords
14042 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14043 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14044 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14046 (defun org-complete (&optional arg)
14047 "Perform completion on word at point.
14048 At the beginning of a headline, this completes TODO keywords as given in
14049 `org-todo-keywords'.
14050 If the current word is preceded by a backslash, completes the TeX symbols
14051 that are supported for HTML support.
14052 If the current word is preceded by \"#+\", completes special words for
14053 setting file options.
14054 In the line after \"#+STARTUP:, complete valid keywords.\"
14055 At all other locations, this simply calls the value of
14056 `org-completion-fallback-command'."
14057 (interactive "P")
14058 (org-without-partial-completion
14059 (catch 'exit
14060 (let* ((end (point))
14061 (beg1 (save-excursion
14062 (skip-chars-backward (org-re "[:alnum:]_@"))
14063 (point)))
14064 (beg (save-excursion
14065 (skip-chars-backward "a-zA-Z0-9_:$")
14066 (point)))
14067 (confirm (lambda (x) (stringp (car x))))
14068 (searchhead (equal (char-before beg) ?*))
14069 (tag (and (equal (char-before beg1) ?:)
14070 (equal (char-after (point-at-bol)) ?*)))
14071 (prop (and (equal (char-before beg1) ?:)
14072 (not (equal (char-after (point-at-bol)) ?*))))
14073 (texp (equal (char-before beg) ?\\))
14074 (link (equal (char-before beg) ?\[))
14075 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14076 beg)
14077 "#+"))
14078 (startup (string-match "^#\\+STARTUP:.*"
14079 (buffer-substring (point-at-bol) (point))))
14080 (completion-ignore-case opt)
14081 (type nil)
14082 (tbl nil)
14083 (table (cond
14084 (opt
14085 (setq type :opt)
14086 (append
14087 (mapcar
14088 (lambda (x)
14089 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14090 (cons (match-string 2 x) (match-string 1 x)))
14091 (org-split-string (org-get-current-options) "\n"))
14092 (mapcar 'list org-additional-option-like-keywords)))
14093 (startup
14094 (setq type :startup)
14095 org-startup-options)
14096 (link (append org-link-abbrev-alist-local
14097 org-link-abbrev-alist))
14098 (texp
14099 (setq type :tex)
14100 org-html-entities)
14101 ((string-match "\\`\\*+[ \t]+\\'"
14102 (buffer-substring (point-at-bol) beg))
14103 (setq type :todo)
14104 (mapcar 'list org-todo-keywords-1))
14105 (searchhead
14106 (setq type :searchhead)
14107 (save-excursion
14108 (goto-char (point-min))
14109 (while (re-search-forward org-todo-line-regexp nil t)
14110 (push (list
14111 (org-make-org-heading-search-string
14112 (match-string 3) t))
14113 tbl)))
14114 tbl)
14115 (tag (setq type :tag beg beg1)
14116 (or org-tag-alist (org-get-buffer-tags)))
14117 (prop (setq type :prop beg beg1)
14118 (mapcar 'list (org-buffer-property-keys)))
14119 (t (progn
14120 (call-interactively org-completion-fallback-command)
14121 (throw 'exit nil)))))
14122 (pattern (buffer-substring-no-properties beg end))
14123 (completion (try-completion pattern table confirm)))
14124 (cond ((eq completion t)
14125 (if (not (assoc (upcase pattern) table))
14126 (message "Already complete")
14127 (if (equal type :opt)
14128 (insert (substring (cdr (assoc (upcase pattern) table))
14129 (length pattern)))
14130 (if (memq type '(:tag :prop)) (insert ":")))))
14131 ((null completion)
14132 (message "Can't find completion for \"%s\"" pattern)
14133 (ding))
14134 ((not (string= pattern completion))
14135 (delete-region beg end)
14136 (if (string-match " +$" completion)
14137 (setq completion (replace-match "" t t completion)))
14138 (insert completion)
14139 (if (get-buffer-window "*Completions*")
14140 (delete-window (get-buffer-window "*Completions*")))
14141 (if (assoc completion table)
14142 (if (eq type :todo) (insert " ")
14143 (if (memq type '(:tag :prop)) (insert ":"))))
14144 (if (and (equal type :opt) (assoc completion table))
14145 (message "%s" (substitute-command-keys
14146 "Press \\[org-complete] again to insert example settings"))))
14148 (message "Making completion list...")
14149 (let ((list (sort (all-completions pattern table confirm)
14150 'string<)))
14151 (with-output-to-temp-buffer "*Completions*"
14152 (condition-case nil
14153 ;; Protection needed for XEmacs and emacs 21
14154 (display-completion-list list pattern)
14155 (error (display-completion-list list)))))
14156 (message "Making completion list...%s" "done")))))))
14158 ;;;; TODO, DEADLINE, Comments
14160 (defun org-toggle-comment ()
14161 "Change the COMMENT state of an entry."
14162 (interactive)
14163 (save-excursion
14164 (org-back-to-heading)
14165 (let (case-fold-search)
14166 (if (looking-at (concat outline-regexp
14167 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14168 (replace-match "" t t nil 1)
14169 (if (looking-at outline-regexp)
14170 (progn
14171 (goto-char (match-end 0))
14172 (insert org-comment-string " ")))))))
14174 (defvar org-last-todo-state-is-todo nil
14175 "This is non-nil when the last TODO state change led to a TODO state.
14176 If the last change removed the TODO tag or switched to DONE, then
14177 this is nil.")
14179 (defvar org-setting-tags nil) ; dynamically skiped
14181 ;; FIXME: better place
14182 (defun org-property-or-variable-value (var &optional inherit)
14183 "Check if there is a property fixing the value of VAR.
14184 If yes, return this value. If not, return the current value of the variable."
14185 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14186 (if (and prop (stringp prop) (string-match "\\S-" prop))
14187 (read prop)
14188 (symbol-value var))))
14190 (defun org-parse-local-options (string var)
14191 "Parse STRING for startup setting relevant for variable VAR."
14192 (let ((rtn (symbol-value var))
14193 e opts)
14194 (save-match-data
14195 (if (or (not string) (not (string-match "\\S-" string)))
14197 (setq opts (delq nil (mapcar (lambda (x)
14198 (setq e (assoc x org-startup-options))
14199 (if (eq (nth 1 e) var) e nil))
14200 (org-split-string string "[ \t]+"))))
14201 (if (not opts)
14203 (setq rtn nil)
14204 (while (setq e (pop opts))
14205 (if (not (nth 3 e))
14206 (setq rtn (nth 2 e))
14207 (if (not (listp rtn)) (setq rtn nil))
14208 (push (nth 2 e) rtn)))
14209 rtn)))))
14211 (defvar org-blocker-hook nil
14212 "Hook for functions that are allowed to block a state change.
14214 Each function gets as its single argument a property list, see
14215 `org-trigger-hook' for more information about this list.
14217 If any of the functions in this hook returns nil, the state change
14218 is blocked.")
14220 (defvar org-trigger-hook nil
14221 "Hook for functions that are triggered by a state change.
14223 Each function gets as its single argument a property list with at least
14224 the following elements:
14226 (:type type-of-change :position pos-at-entry-start
14227 :from old-state :to new-state)
14229 Depending on the type, more properties may be present.
14231 This mechanism is currently implemented for:
14233 TODO state changes
14234 ------------------
14235 :type todo-state-change
14236 :from previous state (keyword as a string), or nil
14237 :to new state (keyword as a string), or nil")
14240 (defun org-todo (&optional arg)
14241 "Change the TODO state of an item.
14242 The state of an item is given by a keyword at the start of the heading,
14243 like
14244 *** TODO Write paper
14245 *** DONE Call mom
14247 The different keywords are specified in the variable `org-todo-keywords'.
14248 By default the available states are \"TODO\" and \"DONE\".
14249 So for this example: when the item starts with TODO, it is changed to DONE.
14250 When it starts with DONE, the DONE is removed. And when neither TODO nor
14251 DONE are present, add TODO at the beginning of the heading.
14253 With C-u prefix arg, use completion to determine the new state.
14254 With numeric prefix arg, switch to that state.
14256 For calling through lisp, arg is also interpreted in the following way:
14257 'none -> empty state
14258 \"\"(empty string) -> switch to empty state
14259 'done -> switch to DONE
14260 'nextset -> switch to the next set of keywords
14261 'previousset -> switch to the previous set of keywords
14262 \"WAITING\" -> switch to the specified keyword, but only if it
14263 really is a member of `org-todo-keywords'."
14264 (interactive "P")
14265 (save-excursion
14266 (catch 'exit
14267 (org-back-to-heading)
14268 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14269 (or (looking-at (concat " +" org-todo-regexp " *"))
14270 (looking-at " *"))
14271 (let* ((match-data (match-data))
14272 (startpos (point-at-bol))
14273 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14274 (org-log-done (org-parse-local-options logging 'org-log-done))
14275 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
14276 (this (match-string 1))
14277 (hl-pos (match-beginning 0))
14278 (head (org-get-todo-sequence-head this))
14279 (ass (assoc head org-todo-kwd-alist))
14280 (interpret (nth 1 ass))
14281 (done-word (nth 3 ass))
14282 (final-done-word (nth 4 ass))
14283 (last-state (or this ""))
14284 (completion-ignore-case t)
14285 (member (member this org-todo-keywords-1))
14286 (tail (cdr member))
14287 (state (cond
14288 ((and org-todo-key-trigger
14289 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14290 (and (not arg) org-use-fast-todo-selection
14291 (not (eq org-use-fast-todo-selection 'prefix)))))
14292 ;; Use fast selection
14293 (org-fast-todo-selection))
14294 ((and (equal arg '(4))
14295 (or (not org-use-fast-todo-selection)
14296 (not org-todo-key-trigger)))
14297 ;; Read a state with completion
14298 (completing-read "State: " (mapcar (lambda(x) (list x))
14299 org-todo-keywords-1)
14300 nil t))
14301 ((eq arg 'right)
14302 (if this
14303 (if tail (car tail) nil)
14304 (car org-todo-keywords-1)))
14305 ((eq arg 'left)
14306 (if (equal member org-todo-keywords-1)
14308 (if this
14309 (nth (- (length org-todo-keywords-1) (length tail) 2)
14310 org-todo-keywords-1)
14311 (org-last org-todo-keywords-1))))
14312 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14313 (setq arg nil))) ; hack to fall back to cycling
14314 (arg
14315 ;; user or caller requests a specific state
14316 (cond
14317 ((equal arg "") nil)
14318 ((eq arg 'none) nil)
14319 ((eq arg 'done) (or done-word (car org-done-keywords)))
14320 ((eq arg 'nextset)
14321 (or (car (cdr (member head org-todo-heads)))
14322 (car org-todo-heads)))
14323 ((eq arg 'previousset)
14324 (let ((org-todo-heads (reverse org-todo-heads)))
14325 (or (car (cdr (member head org-todo-heads)))
14326 (car org-todo-heads))))
14327 ((car (member arg org-todo-keywords-1)))
14328 ((nth (1- (prefix-numeric-value arg))
14329 org-todo-keywords-1))))
14330 ((null member) (or head (car org-todo-keywords-1)))
14331 ((equal this final-done-word) nil) ;; -> make empty
14332 ((null tail) nil) ;; -> first entry
14333 ((eq interpret 'sequence)
14334 (car tail))
14335 ((memq interpret '(type priority))
14336 (if (eq this-command last-command)
14337 (car tail)
14338 (if (> (length tail) 0)
14339 (or done-word (car org-done-keywords))
14340 nil)))
14341 (t nil)))
14342 (next (if state (concat " " state " ") " "))
14343 (change-plist (list :type 'todo-state-change :from this :to state
14344 :position startpos))
14345 dostates)
14346 (when org-blocker-hook
14347 (unless (save-excursion
14348 (save-match-data
14349 (run-hook-with-args-until-failure
14350 'org-blocker-hook change-plist)))
14351 (if (interactive-p)
14352 (error "TODO state change from %s to %s blocked" this state)
14353 ;; fail silently
14354 (message "TODO state change from %s to %s blocked" this state)
14355 (throw 'exit nil))))
14356 (store-match-data match-data)
14357 (replace-match next t t)
14358 (unless (pos-visible-in-window-p hl-pos)
14359 (message "TODO state changed to %s" (org-trim next)))
14360 (unless head
14361 (setq head (org-get-todo-sequence-head state)
14362 ass (assoc head org-todo-kwd-alist)
14363 interpret (nth 1 ass)
14364 done-word (nth 3 ass)
14365 final-done-word (nth 4 ass)))
14366 (when (memq arg '(nextset previousset))
14367 (message "Keyword-Set %d/%d: %s"
14368 (- (length org-todo-sets) -1
14369 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14370 (length org-todo-sets)
14371 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14372 (setq org-last-todo-state-is-todo
14373 (not (member state org-done-keywords)))
14374 (when (and org-log-done (not (memq arg '(nextset previousset))))
14375 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14376 (or (not org-todo-log-states)
14377 (member state org-todo-log-states))))
14379 (cond
14380 ((and state (member state org-not-done-keywords)
14381 (not (member this org-not-done-keywords)))
14382 ;; This is now a todo state and was not one before
14383 ;; Remove any CLOSED timestamp, and possibly log the state change
14384 (org-add-planning-info nil nil 'closed)
14385 (and dostates (org-add-log-maybe 'state state 'findpos)))
14386 ((and state dostates)
14387 ;; This is a non-nil state, and we need to log it
14388 (org-add-log-maybe 'state state 'findpos))
14389 ((and (member state org-done-keywords)
14390 (not (member this org-done-keywords)))
14391 ;; It is now done, and it was not done before
14392 (org-add-planning-info 'closed (org-current-time))
14393 (org-add-log-maybe 'done state 'findpos))))
14394 ;; Fixup tag positioning
14395 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14396 (run-hooks 'org-after-todo-state-change-hook)
14397 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14398 (if (and arg (not (member state org-done-keywords)))
14399 (setq head (org-get-todo-sequence-head state)))
14400 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14401 ;; Fixup cursor location if close to the keyword
14402 (if (and (outline-on-heading-p)
14403 (not (bolp))
14404 (save-excursion (beginning-of-line 1)
14405 (looking-at org-todo-line-regexp))
14406 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14407 (progn
14408 (goto-char (or (match-end 2) (match-end 1)))
14409 (just-one-space)))
14410 (when org-trigger-hook
14411 (save-excursion
14412 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14414 (defun org-get-todo-sequence-head (kwd)
14415 "Return the head of the TODO sequence to which KWD belongs.
14416 If KWD is not set, check if there is a text property remembering the
14417 right sequence."
14418 (let (p)
14419 (cond
14420 ((not kwd)
14421 (or (get-text-property (point-at-bol) 'org-todo-head)
14422 (progn
14423 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14424 nil (point-at-eol)))
14425 (get-text-property p 'org-todo-head))))
14426 ((not (member kwd org-todo-keywords-1))
14427 (car org-todo-keywords-1))
14428 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14430 (defun org-fast-todo-selection ()
14431 "Fast TODO keyword selection with single keys.
14432 Returns the new TODO keyword, or nil if no state change should occur."
14433 (let* ((fulltable org-todo-key-alist)
14434 (done-keywords org-done-keywords) ;; needed for the faces.
14435 (maxlen (apply 'max (mapcar
14436 (lambda (x)
14437 (if (stringp (car x)) (string-width (car x)) 0))
14438 fulltable)))
14439 (expert nil)
14440 (fwidth (+ maxlen 3 1 3))
14441 (ncol (/ (- (window-width) 4) fwidth))
14442 tg cnt e c tbl
14443 groups ingroup)
14444 (save-window-excursion
14445 (if expert
14446 (set-buffer (get-buffer-create " *Org todo*"))
14447 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14448 (erase-buffer)
14449 (org-set-local 'org-done-keywords done-keywords)
14450 (setq tbl fulltable cnt 0)
14451 (while (setq e (pop tbl))
14452 (cond
14453 ((equal e '(:startgroup))
14454 (push '() groups) (setq ingroup t)
14455 (when (not (= cnt 0))
14456 (setq cnt 0)
14457 (insert "\n"))
14458 (insert "{ "))
14459 ((equal e '(:endgroup))
14460 (setq ingroup nil cnt 0)
14461 (insert "}\n"))
14463 (setq tg (car e) c (cdr e))
14464 (if ingroup (push tg (car groups)))
14465 (setq tg (org-add-props tg nil 'face
14466 (org-get-todo-face tg)))
14467 (if (and (= cnt 0) (not ingroup)) (insert " "))
14468 (insert "[" c "] " tg (make-string
14469 (- fwidth 4 (length tg)) ?\ ))
14470 (when (= (setq cnt (1+ cnt)) ncol)
14471 (insert "\n")
14472 (if ingroup (insert " "))
14473 (setq cnt 0)))))
14474 (insert "\n")
14475 (goto-char (point-min))
14476 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14477 (fit-window-to-buffer))
14478 (message "[a-z..]:Set [SPC]:clear")
14479 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14480 (cond
14481 ((or (= c ?\C-g)
14482 (and (= c ?q) (not (rassoc c fulltable))))
14483 (setq quit-flag t))
14484 ((= c ?\ ) nil)
14485 ((setq e (rassoc c fulltable) tg (car e))
14487 (t (setq quit-flag t))))))
14489 (defun org-get-repeat ()
14490 "Check if tere is a deadline/schedule with repeater in this entry."
14491 (save-match-data
14492 (save-excursion
14493 (org-back-to-heading t)
14494 (if (re-search-forward
14495 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14496 (match-string 1)))))
14498 (defvar org-last-changed-timestamp)
14499 (defvar org-log-post-message)
14500 (defun org-auto-repeat-maybe ()
14501 "Check if the current headline contains a repeated deadline/schedule.
14502 If yes, set TODO state back to what it was and change the base date
14503 of repeating deadline/scheduled time stamps to new date.
14504 This function should be run in the `org-after-todo-state-change-hook'."
14505 ;; last-state is dynamically scoped into this function
14506 (let* ((repeat (org-get-repeat))
14507 (aa (assoc last-state org-todo-kwd-alist))
14508 (interpret (nth 1 aa))
14509 (head (nth 2 aa))
14510 (done-word (nth 3 aa))
14511 (whata '(("d" . day) ("m" . month) ("y" . year)))
14512 (msg "Entry repeats: ")
14513 (org-log-done)
14514 re type n what ts)
14515 (when repeat
14516 (org-todo (if (eq interpret 'type) last-state head))
14517 (when (and org-log-repeat
14518 (not (memq 'org-add-log-note
14519 (default-value 'post-command-hook))))
14520 ;; Make sure a note is taken
14521 (let ((org-log-done '(done)))
14522 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14523 'findpos)))
14524 (org-back-to-heading t)
14525 (org-add-planning-info nil nil 'closed)
14526 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14527 org-deadline-time-regexp "\\)"))
14528 (while (re-search-forward
14529 re (save-excursion (outline-next-heading) (point)) t)
14530 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
14531 ts (match-string (if (match-end 2) 2 4)))
14532 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14533 (setq n (string-to-number (match-string 1 ts))
14534 what (match-string 2 ts))
14535 (if (equal what "w") (setq n (* n 7) what "d"))
14536 (org-timestamp-change n (cdr (assoc what whata))))
14537 (setq msg (concat msg type org-last-changed-timestamp " ")))
14538 (setq org-log-post-message msg)
14539 (message "%s" msg))))
14541 (defun org-show-todo-tree (arg)
14542 "Make a compact tree which shows all headlines marked with TODO.
14543 The tree will show the lines where the regexp matches, and all higher
14544 headlines above the match.
14545 With \\[universal-argument] prefix, also show the DONE entries.
14546 With a numeric prefix N, construct a sparse tree for the Nth element
14547 of `org-todo-keywords-1'."
14548 (interactive "P")
14549 (let ((case-fold-search nil)
14550 (kwd-re
14551 (cond ((null arg) org-not-done-regexp)
14552 ((equal arg '(4))
14553 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14554 (mapcar 'list org-todo-keywords-1))))
14555 (concat "\\("
14556 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14557 "\\)\\>")))
14558 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14559 (regexp-quote (nth (1- (prefix-numeric-value arg))
14560 org-todo-keywords-1)))
14561 (t (error "Invalid prefix argument: %s" arg)))))
14562 (message "%d TODO entries found"
14563 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14565 (defun org-deadline (&optional remove)
14566 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14567 With argument REMOVE, remove any deadline from the item."
14568 (interactive "P")
14569 (if remove
14570 (progn
14571 (org-add-planning-info nil nil 'deadline)
14572 (message "Item no longer has a deadline."))
14573 (org-add-planning-info 'deadline nil 'closed)))
14575 (defun org-schedule (&optional remove)
14576 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14577 With argument REMOVE, remove any scheduling date from the item."
14578 (interactive "P")
14579 (if remove
14580 (progn
14581 (org-add-planning-info nil nil 'scheduled)
14582 (message "Item is no longer scheduled."))
14583 (org-add-planning-info 'scheduled nil 'closed)))
14585 (defun org-add-planning-info (what &optional time &rest remove)
14586 "Insert new timestamp with keyword in the line directly after the headline.
14587 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14588 If non is given, the user is prompted for a date.
14589 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14590 be removed."
14591 (interactive)
14592 (let (org-time-was-given org-end-time-was-given)
14593 (when what (setq time (or time (org-read-date nil 'to-time))))
14594 (when (and org-insert-labeled-timestamps-at-point
14595 (member what '(scheduled deadline)))
14596 (insert
14597 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14598 (org-insert-time-stamp time org-time-was-given
14599 nil nil nil (list org-end-time-was-given))
14600 (setq what nil))
14601 (save-excursion
14602 (save-restriction
14603 (let (col list elt ts buffer-invisibility-spec)
14604 (org-back-to-heading t)
14605 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14606 (goto-char (match-end 1))
14607 (setq col (current-column))
14608 (goto-char (match-end 0))
14609 (if (eobp) (insert "\n") (forward-char 1))
14610 (if (and (not (looking-at outline-regexp))
14611 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14612 "[^\r\n]*"))
14613 (not (equal (match-string 1) org-clock-string)))
14614 (narrow-to-region (match-beginning 0) (match-end 0))
14615 (insert-before-markers "\n")
14616 (backward-char 1)
14617 (narrow-to-region (point) (point))
14618 (indent-to-column col))
14619 ;; Check if we have to remove something.
14620 (setq list (cons what remove))
14621 (while list
14622 (setq elt (pop list))
14623 (goto-char (point-min))
14624 (when (or (and (eq elt 'scheduled)
14625 (re-search-forward org-scheduled-time-regexp nil t))
14626 (and (eq elt 'deadline)
14627 (re-search-forward org-deadline-time-regexp nil t))
14628 (and (eq elt 'closed)
14629 (re-search-forward org-closed-time-regexp nil t)))
14630 (replace-match "")
14631 (if (looking-at "--+<[^>]+>") (replace-match ""))
14632 (if (looking-at " +") (replace-match ""))))
14633 (goto-char (point-max))
14634 (when what
14635 (insert
14636 (if (not (equal (char-before) ?\ )) " " "")
14637 (cond ((eq what 'scheduled) org-scheduled-string)
14638 ((eq what 'deadline) org-deadline-string)
14639 ((eq what 'closed) org-closed-string))
14640 " ")
14641 (setq ts (org-insert-time-stamp
14642 time
14643 (or org-time-was-given
14644 (and (eq what 'closed) org-log-done-with-time))
14645 (eq what 'closed)
14646 nil nil (list org-end-time-was-given)))
14647 (end-of-line 1))
14648 (goto-char (point-min))
14649 (widen)
14650 (if (looking-at "[ \t]+\r?\n")
14651 (replace-match ""))
14652 ts)))))
14654 (defvar org-log-note-marker (make-marker))
14655 (defvar org-log-note-purpose nil)
14656 (defvar org-log-note-state nil)
14657 (defvar org-log-note-window-configuration nil)
14658 (defvar org-log-note-return-to (make-marker))
14659 (defvar org-log-post-message nil
14660 "Message to be displayed after a log note has been stored.
14661 The auto-repeater uses this.")
14663 (defun org-add-log-maybe (&optional purpose state findpos)
14664 "Set up the post command hook to take a note."
14665 (save-excursion
14666 (when (and (listp org-log-done)
14667 (memq purpose org-log-done))
14668 (when findpos
14669 (org-back-to-heading t)
14670 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14671 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14672 "[^\r\n]*\\)?"))
14673 (goto-char (match-end 0))
14674 (unless org-log-states-order-reversed
14675 (and (= (char-after) ?\n) (forward-char 1))
14676 (org-skip-over-state-notes)
14677 (skip-chars-backward " \t\n\r")))
14678 (move-marker org-log-note-marker (point))
14679 (setq org-log-note-purpose purpose)
14680 (setq org-log-note-state state)
14681 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14683 (defun org-skip-over-state-notes ()
14684 "Skip past the list of State notes in an entry."
14685 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14686 (while (looking-at "[ \t]*- State")
14687 (condition-case nil
14688 (org-next-item)
14689 (error (org-end-of-item)))))
14691 (defun org-add-log-note (&optional purpose)
14692 "Pop up a window for taking a note, and add this note later at point."
14693 (remove-hook 'post-command-hook 'org-add-log-note)
14694 (setq org-log-note-window-configuration (current-window-configuration))
14695 (delete-other-windows)
14696 (move-marker org-log-note-return-to (point))
14697 (switch-to-buffer (marker-buffer org-log-note-marker))
14698 (goto-char org-log-note-marker)
14699 (org-switch-to-buffer-other-window "*Org Note*")
14700 (erase-buffer)
14701 (let ((org-inhibit-startup t)) (org-mode))
14702 (insert (format "# Insert note for %s.
14703 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14704 (cond
14705 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14706 ((eq org-log-note-purpose 'done) "closed todo item")
14707 ((eq org-log-note-purpose 'state)
14708 (format "state change to \"%s\"" org-log-note-state))
14709 (t (error "This should not happen")))))
14710 (org-set-local 'org-finish-function 'org-store-log-note))
14712 (defun org-store-log-note ()
14713 "Finish taking a log note, and insert it to where it belongs."
14714 (let ((txt (buffer-string))
14715 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14716 lines ind)
14717 (kill-buffer (current-buffer))
14718 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14719 (setq txt (replace-match "" t t txt)))
14720 (if (string-match "\\s-+\\'" txt)
14721 (setq txt (replace-match "" t t txt)))
14722 (setq lines (org-split-string txt "\n"))
14723 (when (and note (string-match "\\S-" note))
14724 (setq note
14725 (org-replace-escapes
14726 note
14727 (list (cons "%u" (user-login-name))
14728 (cons "%U" user-full-name)
14729 (cons "%t" (format-time-string
14730 (org-time-stamp-format 'long 'inactive)
14731 (current-time)))
14732 (cons "%s" (if org-log-note-state
14733 (concat "\"" org-log-note-state "\"")
14734 "")))))
14735 (if lines (setq note (concat note " \\\\")))
14736 (push note lines))
14737 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14738 (when lines
14739 (save-excursion
14740 (set-buffer (marker-buffer org-log-note-marker))
14741 (save-excursion
14742 (goto-char org-log-note-marker)
14743 (move-marker org-log-note-marker nil)
14744 (end-of-line 1)
14745 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14746 (indent-relative nil)
14747 (insert "- " (pop lines))
14748 (org-indent-line-function)
14749 (beginning-of-line 1)
14750 (looking-at "[ \t]*")
14751 (setq ind (concat (match-string 0) " "))
14752 (end-of-line 1)
14753 (while lines (insert "\n" ind (pop lines)))))))
14754 (set-window-configuration org-log-note-window-configuration)
14755 (with-current-buffer (marker-buffer org-log-note-return-to)
14756 (goto-char org-log-note-return-to))
14757 (move-marker org-log-note-return-to nil)
14758 (and org-log-post-message (message "%s" org-log-post-message)))
14760 ;; FIXME: what else would be useful?
14761 ;; - priority
14762 ;; - date
14764 (defun org-sparse-tree (&optional arg)
14765 "Create a sparse tree, prompt for the details.
14766 This command can create sparse trees. You first need to select the type
14767 of match used to create the tree:
14769 t Show entries with a specific TODO keyword.
14770 T Show entries selected by a tags match.
14771 p Enter a property name and its value (both with completion on existing
14772 names/values) and show entries with that property.
14773 r Show entries matching a regular expression
14774 d Show deadlines due within `org-deadline-warning-days'."
14775 (interactive "P")
14776 (let (ans kwd value)
14777 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14778 (setq ans (read-char-exclusive))
14779 (cond
14780 ((equal ans ?d)
14781 (call-interactively 'org-check-deadlines))
14782 ((equal ans ?b)
14783 (call-interactively 'org-check-before-date))
14784 ((equal ans ?t)
14785 (org-show-todo-tree '(4)))
14786 ((equal ans ?T)
14787 (call-interactively 'org-tags-sparse-tree))
14788 ((member ans '(?p ?P))
14789 (setq kwd (completing-read "Property: "
14790 (mapcar 'list (org-buffer-property-keys))))
14791 (setq value (completing-read "Value: "
14792 (mapcar 'list (org-property-values kwd))))
14793 (unless (string-match "\\`{.*}\\'" value)
14794 (setq value (concat "\"" value "\"")))
14795 (org-tags-sparse-tree arg (concat kwd "=" value)))
14796 ((member ans '(?r ?R ?/))
14797 (call-interactively 'org-occur))
14798 (t (error "No such sparse tree command \"%c\"" ans)))))
14800 (defvar org-occur-highlights nil)
14801 (make-variable-buffer-local 'org-occur-highlights)
14803 (defun org-occur (regexp &optional keep-previous callback)
14804 "Make a compact tree which shows all matches of REGEXP.
14805 The tree will show the lines where the regexp matches, and all higher
14806 headlines above the match. It will also show the heading after the match,
14807 to make sure editing the matching entry is easy.
14808 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14809 call to `org-occur' will be kept, to allow stacking of calls to this
14810 command.
14811 If CALLBACK is non-nil, it is a function which is called to confirm
14812 that the match should indeed be shown."
14813 (interactive "sRegexp: \nP")
14814 (or keep-previous (org-remove-occur-highlights nil nil t))
14815 (let ((cnt 0))
14816 (save-excursion
14817 (goto-char (point-min))
14818 (if (or (not keep-previous) ; do not want to keep
14819 (not org-occur-highlights)) ; no previous matches
14820 ;; hide everything
14821 (org-overview))
14822 (while (re-search-forward regexp nil t)
14823 (when (or (not callback)
14824 (save-match-data (funcall callback)))
14825 (setq cnt (1+ cnt))
14826 (when org-highlight-sparse-tree-matches
14827 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14828 (org-show-context 'occur-tree))))
14829 (when org-remove-highlights-with-change
14830 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14831 nil 'local))
14832 (unless org-sparse-tree-open-archived-trees
14833 (org-hide-archived-subtrees (point-min) (point-max)))
14834 (run-hooks 'org-occur-hook)
14835 (if (interactive-p)
14836 (message "%d match(es) for regexp %s" cnt regexp))
14837 cnt))
14839 (defun org-show-context (&optional key)
14840 "Make sure point and context and visible.
14841 How much context is shown depends upon the variables
14842 `org-show-hierarchy-above', `org-show-following-heading'. and
14843 `org-show-siblings'."
14844 (let ((heading-p (org-on-heading-p t))
14845 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14846 (following-p (org-get-alist-option org-show-following-heading key))
14847 (entry-p (org-get-alist-option org-show-entry-below key))
14848 (siblings-p (org-get-alist-option org-show-siblings key)))
14849 (catch 'exit
14850 ;; Show heading or entry text
14851 (if (and heading-p (not entry-p))
14852 (org-flag-heading nil) ; only show the heading
14853 (and (or entry-p (org-invisible-p) (org-invisible-p2))
14854 (org-show-hidden-entry))) ; show entire entry
14855 (when following-p
14856 ;; Show next sibling, or heading below text
14857 (save-excursion
14858 (and (if heading-p (org-goto-sibling) (outline-next-heading))
14859 (org-flag-heading nil))))
14860 (when siblings-p (org-show-siblings))
14861 (when hierarchy-p
14862 ;; show all higher headings, possibly with siblings
14863 (save-excursion
14864 (while (and (condition-case nil
14865 (progn (org-up-heading-all 1) t)
14866 (error nil))
14867 (not (bobp)))
14868 (org-flag-heading nil)
14869 (when siblings-p (org-show-siblings))))))))
14871 (defun org-reveal (&optional siblings)
14872 "Show current entry, hierarchy above it, and the following headline.
14873 This can be used to show a consistent set of context around locations
14874 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14875 not t for the search context.
14877 With optional argument SIBLINGS, on each level of the hierarchy all
14878 siblings are shown. This repairs the tree structure to what it would
14879 look like when opened with hierarchical calls to `org-cycle'."
14880 (interactive "P")
14881 (let ((org-show-hierarchy-above t)
14882 (org-show-following-heading t)
14883 (org-show-siblings (if siblings t org-show-siblings)))
14884 (org-show-context nil)))
14886 (defun org-highlight-new-match (beg end)
14887 "Highlight from BEG to END and mark the highlight is an occur headline."
14888 (let ((ov (org-make-overlay beg end)))
14889 (org-overlay-put ov 'face 'secondary-selection)
14890 (push ov org-occur-highlights)))
14892 (defun org-remove-occur-highlights (&optional beg end noremove)
14893 "Remove the occur highlights from the buffer.
14894 BEG and END are ignored. If NOREMOVE is nil, remove this function
14895 from the `before-change-functions' in the current buffer."
14896 (interactive)
14897 (unless org-inhibit-highlight-removal
14898 (mapc 'org-delete-overlay org-occur-highlights)
14899 (setq org-occur-highlights nil)
14900 (unless noremove
14901 (remove-hook 'before-change-functions
14902 'org-remove-occur-highlights 'local))))
14904 ;;;; Priorities
14906 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14907 "Regular expression matching the priority indicator.")
14909 (defvar org-remove-priority-next-time nil)
14911 (defun org-priority-up ()
14912 "Increase the priority of the current item."
14913 (interactive)
14914 (org-priority 'up))
14916 (defun org-priority-down ()
14917 "Decrease the priority of the current item."
14918 (interactive)
14919 (org-priority 'down))
14921 (defun org-priority (&optional action)
14922 "Change the priority of an item by ARG.
14923 ACTION can be `set', `up', `down', or a character."
14924 (interactive)
14925 (setq action (or action 'set))
14926 (let (current new news have remove)
14927 (save-excursion
14928 (org-back-to-heading)
14929 (if (looking-at org-priority-regexp)
14930 (setq current (string-to-char (match-string 2))
14931 have t)
14932 (setq current org-default-priority))
14933 (cond
14934 ((or (eq action 'set) (integerp action))
14935 (if (integerp action)
14936 (setq new action)
14937 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14938 (setq new (read-char-exclusive)))
14939 (if (and (= (upcase org-highest-priority) org-highest-priority)
14940 (= (upcase org-lowest-priority) org-lowest-priority))
14941 (setq new (upcase new)))
14942 (cond ((equal new ?\ ) (setq remove t))
14943 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14944 (error "Priority must be between `%c' and `%c'"
14945 org-highest-priority org-lowest-priority))))
14946 ((eq action 'up)
14947 (if (and (not have) (eq last-command this-command))
14948 (setq new org-lowest-priority)
14949 (setq new (if (and org-priority-start-cycle-with-default (not have))
14950 org-default-priority (1- current)))))
14951 ((eq action 'down)
14952 (if (and (not have) (eq last-command this-command))
14953 (setq new org-highest-priority)
14954 (setq new (if (and org-priority-start-cycle-with-default (not have))
14955 org-default-priority (1+ current)))))
14956 (t (error "Invalid action")))
14957 (if (or (< (upcase new) org-highest-priority)
14958 (> (upcase new) org-lowest-priority))
14959 (setq remove t))
14960 (setq news (format "%c" new))
14961 (if have
14962 (if remove
14963 (replace-match "" t t nil 1)
14964 (replace-match news t t nil 2))
14965 (if remove
14966 (error "No priority cookie found in line")
14967 (looking-at org-todo-line-regexp)
14968 (if (match-end 2)
14969 (progn
14970 (goto-char (match-end 2))
14971 (insert " [#" news "]"))
14972 (goto-char (match-beginning 3))
14973 (insert "[#" news "] ")))))
14974 (org-preserve-lc (org-set-tags nil 'align))
14975 (if remove
14976 (message "Priority removed")
14977 (message "Priority of current item set to %s" news))))
14980 (defun org-get-priority (s)
14981 "Find priority cookie and return priority."
14982 (save-match-data
14983 (if (not (string-match org-priority-regexp s))
14984 (* 1000 (- org-lowest-priority org-default-priority))
14985 (* 1000 (- org-lowest-priority
14986 (string-to-char (match-string 2 s)))))))
14988 ;;;; Tags
14990 (defun org-scan-tags (action matcher &optional todo-only)
14991 "Scan headline tags with inheritance and produce output ACTION.
14992 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
14993 evaluated, testing if a given set of tags qualifies a headline for
14994 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
14995 are included in the output."
14996 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
14997 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14998 (org-re
14999 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15000 (props (list 'face nil
15001 'done-face 'org-done
15002 'undone-face nil
15003 'mouse-face 'highlight
15004 'org-not-done-regexp org-not-done-regexp
15005 'org-todo-regexp org-todo-regexp
15006 'keymap org-agenda-keymap
15007 'help-echo
15008 (format "mouse-2 or RET jump to org file %s"
15009 (abbreviate-file-name
15010 (or (buffer-file-name (buffer-base-buffer))
15011 (buffer-name (buffer-base-buffer)))))))
15012 (case-fold-search nil)
15013 lspos
15014 tags tags-list tags-alist (llast 0) rtn level category i txt
15015 todo marker entry priority)
15016 (save-excursion
15017 (goto-char (point-min))
15018 (when (eq action 'sparse-tree)
15019 (org-overview)
15020 (org-remove-occur-highlights))
15021 (while (re-search-forward re nil t)
15022 (catch :skip
15023 (setq todo (if (match-end 1) (match-string 2))
15024 tags (if (match-end 4) (match-string 4)))
15025 (goto-char (setq lspos (1+ (match-beginning 0))))
15026 (setq level (org-reduced-level (funcall outline-level))
15027 category (org-get-category))
15028 (setq i llast llast level)
15029 ;; remove tag lists from same and sublevels
15030 (while (>= i level)
15031 (when (setq entry (assoc i tags-alist))
15032 (setq tags-alist (delete entry tags-alist)))
15033 (setq i (1- i)))
15034 ;; add the nex tags
15035 (when tags
15036 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15037 tags-alist
15038 (cons (cons level tags) tags-alist)))
15039 ;; compile tags for current headline
15040 (setq tags-list
15041 (if org-use-tag-inheritance
15042 (apply 'append (mapcar 'cdr tags-alist))
15043 tags))
15044 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15045 (eval matcher)
15046 (or (not org-agenda-skip-archived-trees)
15047 (not (member org-archive-tag tags-list))))
15048 (and (eq action 'agenda) (org-agenda-skip))
15049 ;; list this headline
15051 (if (eq action 'sparse-tree)
15052 (progn
15053 (and org-highlight-sparse-tree-matches
15054 (org-get-heading) (match-end 0)
15055 (org-highlight-new-match
15056 (match-beginning 0) (match-beginning 1)))
15057 (org-show-context 'tags-tree))
15058 (setq txt (org-format-agenda-item
15060 (concat
15061 (if org-tags-match-list-sublevels
15062 (make-string (1- level) ?.) "")
15063 (org-get-heading))
15064 category tags-list)
15065 priority (org-get-priority txt))
15066 (goto-char lspos)
15067 (setq marker (org-agenda-new-marker))
15068 (org-add-props txt props
15069 'org-marker marker 'org-hd-marker marker 'org-category category
15070 'priority priority 'type "tagsmatch")
15071 (push txt rtn))
15072 ;; if we are to skip sublevels, jump to end of subtree
15073 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15074 (when (and (eq action 'sparse-tree)
15075 (not org-sparse-tree-open-archived-trees))
15076 (org-hide-archived-subtrees (point-min) (point-max)))
15077 (nreverse rtn)))
15079 (defvar todo-only) ;; dynamically scoped
15081 (defun org-tags-sparse-tree (&optional todo-only match)
15082 "Create a sparse tree according to tags string MATCH.
15083 MATCH can contain positive and negative selection of tags, like
15084 \"+WORK+URGENT-WITHBOSS\".
15085 If optional argument TODO_ONLY is non-nil, only select lines that are
15086 also TODO lines."
15087 (interactive "P")
15088 (org-prepare-agenda-buffers (list (current-buffer)))
15089 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15091 (defvar org-cached-props nil)
15092 (defun org-cached-entry-get (pom property)
15093 (if (or (eq t org-use-property-inheritance)
15094 (member property org-use-property-inheritance))
15095 ;; Caching is not possible, check it directly
15096 (org-entry-get pom property 'inherit)
15097 ;; Get all properties, so that we can do complicated checks easily
15098 (cdr (assoc property (or org-cached-props
15099 (setq org-cached-props
15100 (org-entry-properties pom)))))))
15102 (defun org-global-tags-completion-table (&optional files)
15103 "Return the list of all tags in all agenda buffer/files."
15104 (save-excursion
15105 (org-uniquify
15106 (apply 'append
15107 (mapcar
15108 (lambda (file)
15109 (set-buffer (find-file-noselect file))
15110 (org-get-buffer-tags))
15111 (if (and files (car files))
15112 files
15113 (org-agenda-files)))))))
15115 (defun org-make-tags-matcher (match)
15116 "Create the TAGS//TODO matcher form for the selection string MATCH."
15117 ;; todo-only is scoped dynamically into this function, and the function
15118 ;; may change it it the matcher asksk for it.
15119 (unless match
15120 ;; Get a new match request, with completion
15121 (let ((org-last-tags-completion-table
15122 (org-global-tags-completion-table)))
15123 (setq match (completing-read
15124 "Match: " 'org-tags-completion-function nil nil nil
15125 'org-tags-history))))
15127 ;; Parse the string and create a lisp form
15128 (let ((match0 match)
15129 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
15130 minus tag mm
15131 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15132 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15133 (if (string-match "/+" match)
15134 ;; match contains also a todo-matching request
15135 (progn
15136 (setq tagsmatch (substring match 0 (match-beginning 0))
15137 todomatch (substring match (match-end 0)))
15138 (if (string-match "^!" todomatch)
15139 (setq todo-only t todomatch (substring todomatch 1)))
15140 (if (string-match "^\\s-*$" todomatch)
15141 (setq todomatch nil)))
15142 ;; only matching tags
15143 (setq tagsmatch match todomatch nil))
15145 ;; Make the tags matcher
15146 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15147 (setq tagsmatcher t)
15148 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15149 (while (setq term (pop orterms))
15150 (while (and (equal (substring term -1) "\\") orterms)
15151 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15152 (while (string-match re term)
15153 (setq minus (and (match-end 1)
15154 (equal (match-string 1 term) "-"))
15155 tag (match-string 2 term)
15156 re-p (equal (string-to-char tag) ?{)
15157 level-p (match-end 3)
15158 prop-p (match-end 4)
15159 mm (cond
15160 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15161 (level-p `(= level ,(string-to-number
15162 (match-string 3 term))))
15163 (prop-p
15164 (setq pn (match-string 4 term)
15165 pv (match-string 5 term)
15166 cat-p (equal pn "CATEGORY")
15167 re-p (equal (string-to-char pv) ?{)
15168 pv (substring pv 1 -1))
15169 (if (equal pn "CATEGORY")
15170 (setq gv '(get-text-property (point) 'org-category))
15171 (setq gv `(org-cached-entry-get nil ,pn)))
15172 (if re-p
15173 `(string-match ,pv (or ,gv ""))
15174 `(equal ,pv ,gv)))
15175 (t `(member ,(downcase tag) tags-list)))
15176 mm (if minus (list 'not mm) mm)
15177 term (substring term (match-end 0)))
15178 (push mm tagsmatcher))
15179 (push (if (> (length tagsmatcher) 1)
15180 (cons 'and tagsmatcher)
15181 (car tagsmatcher))
15182 orlist)
15183 (setq tagsmatcher nil))
15184 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15185 (setq tagsmatcher
15186 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15188 ;; Make the todo matcher
15189 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15190 (setq todomatcher t)
15191 (setq orterms (org-split-string todomatch "|") orlist nil)
15192 (while (setq term (pop orterms))
15193 (while (string-match re term)
15194 (setq minus (and (match-end 1)
15195 (equal (match-string 1 term) "-"))
15196 kwd (match-string 2 term)
15197 re-p (equal (string-to-char kwd) ?{)
15198 term (substring term (match-end 0))
15199 mm (if re-p
15200 `(string-match ,(substring kwd 1 -1) todo)
15201 (list 'equal 'todo kwd))
15202 mm (if minus (list 'not mm) mm))
15203 (push mm todomatcher))
15204 (push (if (> (length todomatcher) 1)
15205 (cons 'and todomatcher)
15206 (car todomatcher))
15207 orlist)
15208 (setq todomatcher nil))
15209 (setq todomatcher (if (> (length orlist) 1)
15210 (cons 'or orlist) (car orlist))))
15212 ;; Return the string and lisp forms of the matcher
15213 (setq matcher (if todomatcher
15214 (list 'and tagsmatcher todomatcher)
15215 tagsmatcher))
15216 (cons match0 matcher)))
15218 (defun org-match-any-p (re list)
15219 "Does re match any element of list?"
15220 (setq list (mapcar (lambda (x) (string-match re x)) list))
15221 (delq nil list))
15223 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15224 (defvar org-tags-overlay (org-make-overlay 1 1))
15225 (org-detach-overlay org-tags-overlay)
15227 (defun org-align-tags-here (to-col)
15228 ;; Assumes that this is a headline
15229 (let ((pos (point)) (col (current-column)) tags)
15230 (beginning-of-line 1)
15231 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15232 (< pos (match-beginning 2)))
15233 (progn
15234 (setq tags (match-string 2))
15235 (goto-char (match-beginning 1))
15236 (insert " ")
15237 (delete-region (point) (1+ (match-end 0)))
15238 (backward-char 1)
15239 (move-to-column
15240 (max (1+ (current-column))
15241 (1+ col)
15242 (if (> to-col 0)
15243 to-col
15244 (- (abs to-col) (length tags))))
15246 (insert tags)
15247 (move-to-column (min (current-column) col) t))
15248 (goto-char pos))))
15250 (defun org-set-tags (&optional arg just-align)
15251 "Set the tags for the current headline.
15252 With prefix ARG, realign all tags in headings in the current buffer."
15253 (interactive "P")
15254 (let* ((re (concat "^" outline-regexp))
15255 (current (org-get-tags-string))
15256 (col (current-column))
15257 (org-setting-tags t)
15258 table current-tags inherited-tags ; computed below when needed
15259 tags p0 c0 c1 rpl)
15260 (if arg
15261 (save-excursion
15262 (goto-char (point-min))
15263 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15264 (while (re-search-forward re nil t)
15265 (org-set-tags nil t)
15266 (end-of-line 1)))
15267 (message "All tags realigned to column %d" org-tags-column))
15268 (if just-align
15269 (setq tags current)
15270 ;; Get a new set of tags from the user
15271 (save-excursion
15272 (setq table (or org-tag-alist (org-get-buffer-tags))
15273 org-last-tags-completion-table table
15274 current-tags (org-split-string current ":")
15275 inherited-tags (nreverse
15276 (nthcdr (length current-tags)
15277 (nreverse (org-get-tags-at))))
15278 tags
15279 (if (or (eq t org-use-fast-tag-selection)
15280 (and org-use-fast-tag-selection
15281 (delq nil (mapcar 'cdr table))))
15282 (org-fast-tag-selection
15283 current-tags inherited-tags table
15284 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15285 (let ((org-add-colon-after-tag-completion t))
15286 (org-trim
15287 (org-without-partial-completion
15288 (completing-read "Tags: " 'org-tags-completion-function
15289 nil nil current 'org-tags-history)))))))
15290 (while (string-match "[-+&]+" tags)
15291 ;; No boolean logic, just a list
15292 (setq tags (replace-match ":" t t tags))))
15294 (if (string-match "\\`[\t ]*\\'" tags)
15295 (setq tags "")
15296 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15297 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15299 ;; Insert new tags at the correct column
15300 (beginning-of-line 1)
15301 (cond
15302 ((and (equal current "") (equal tags "")))
15303 ((re-search-forward
15304 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15305 (point-at-eol) t)
15306 (if (equal tags "")
15307 (setq rpl "")
15308 (goto-char (match-beginning 0))
15309 (setq c0 (current-column) p0 (point)
15310 c1 (max (1+ c0) (if (> org-tags-column 0)
15311 org-tags-column
15312 (- (- org-tags-column) (length tags))))
15313 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15314 (replace-match rpl t t)
15315 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
15316 tags)
15317 (t (error "Tags alignment failed")))
15318 (move-to-column col)
15319 (unless just-align
15320 (run-hooks 'org-after-tags-change-hook)))))
15322 (defun org-change-tag-in-region (beg end tag off)
15323 "Add or remove TAG for each entry in the region.
15324 This works in the agenda, and also in an org-mode buffer."
15325 (interactive
15326 (list (region-beginning) (region-end)
15327 (let ((org-last-tags-completion-table
15328 (if (org-mode-p)
15329 (org-get-buffer-tags)
15330 (org-global-tags-completion-table))))
15331 (completing-read
15332 "Tag: " 'org-tags-completion-function nil nil nil
15333 'org-tags-history))
15334 (progn
15335 (message "[s]et or [r]emove? ")
15336 (equal (read-char-exclusive) ?r))))
15337 (if (fboundp 'deactivate-mark) (deactivate-mark))
15338 (let ((agendap (equal major-mode 'org-agenda-mode))
15339 l1 l2 m buf pos newhead (cnt 0))
15340 (goto-char end)
15341 (setq l2 (1- (org-current-line)))
15342 (goto-char beg)
15343 (setq l1 (org-current-line))
15344 (loop for l from l1 to l2 do
15345 (goto-line l)
15346 (setq m (get-text-property (point) 'org-hd-marker))
15347 (when (or (and (org-mode-p) (org-on-heading-p))
15348 (and agendap m))
15349 (setq buf (if agendap (marker-buffer m) (current-buffer))
15350 pos (if agendap m (point)))
15351 (with-current-buffer buf
15352 (save-excursion
15353 (save-restriction
15354 (goto-char pos)
15355 (setq cnt (1+ cnt))
15356 (org-toggle-tag tag (if off 'off 'on))
15357 (setq newhead (org-get-heading)))))
15358 (and agendap (org-agenda-change-all-lines newhead m))))
15359 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15361 (defun org-tags-completion-function (string predicate &optional flag)
15362 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15363 (confirm (lambda (x) (stringp (car x)))))
15364 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15365 (setq s1 (match-string 1 string)
15366 s2 (match-string 2 string))
15367 (setq s1 "" s2 string))
15368 (cond
15369 ((eq flag nil)
15370 ;; try completion
15371 (setq rtn (try-completion s2 ctable confirm))
15372 (if (stringp rtn)
15373 (setq rtn
15374 (concat s1 s2 (substring rtn (length s2))
15375 (if (and org-add-colon-after-tag-completion
15376 (assoc rtn ctable))
15377 ":" ""))))
15378 rtn)
15379 ((eq flag t)
15380 ;; all-completions
15381 (all-completions s2 ctable confirm)
15383 ((eq flag 'lambda)
15384 ;; exact match?
15385 (assoc s2 ctable)))
15388 (defun org-fast-tag-insert (kwd tags face &optional end)
15389 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15390 (insert (format "%-12s" (concat kwd ":"))
15391 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15392 (or end "")))
15394 (defun org-fast-tag-show-exit (flag)
15395 (save-excursion
15396 (goto-line 3)
15397 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15398 (replace-match ""))
15399 (when flag
15400 (end-of-line 1)
15401 (move-to-column (- (window-width) 19) t)
15402 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15404 (defun org-set-current-tags-overlay (current prefix)
15405 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15406 (if (featurep 'xemacs)
15407 (org-overlay-display org-tags-overlay (concat prefix s)
15408 'secondary-selection)
15409 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15410 (org-overlay-display org-tags-overlay (concat prefix s)))))
15412 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15413 "Fast tag selection with single keys.
15414 CURRENT is the current list of tags in the headline, INHERITED is the
15415 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15416 possibly with grouping information. TODO-TABLE is a similar table with
15417 TODO keywords, should these have keys assigned to them.
15418 If the keys are nil, a-z are automatically assigned.
15419 Returns the new tags string, or nil to not change the current settings."
15420 (let* ((fulltable (append table todo-table))
15421 (maxlen (apply 'max (mapcar
15422 (lambda (x)
15423 (if (stringp (car x)) (string-width (car x)) 0))
15424 fulltable)))
15425 (buf (current-buffer))
15426 (expert (eq org-fast-tag-selection-single-key 'expert))
15427 (buffer-tags nil)
15428 (fwidth (+ maxlen 3 1 3))
15429 (ncol (/ (- (window-width) 4) fwidth))
15430 (i-face 'org-done)
15431 (c-face 'org-todo)
15432 tg cnt e c char c1 c2 ntable tbl rtn
15433 ov-start ov-end ov-prefix
15434 (exit-after-next org-fast-tag-selection-single-key)
15435 (done-keywords org-done-keywords)
15436 groups ingroup)
15437 (save-excursion
15438 (beginning-of-line 1)
15439 (if (looking-at
15440 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15441 (setq ov-start (match-beginning 1)
15442 ov-end (match-end 1)
15443 ov-prefix "")
15444 (setq ov-start (1- (point-at-eol))
15445 ov-end (1+ ov-start))
15446 (skip-chars-forward "^\n\r")
15447 (setq ov-prefix
15448 (concat
15449 (buffer-substring (1- (point)) (point))
15450 (if (> (current-column) org-tags-column)
15452 (make-string (- org-tags-column (current-column)) ?\ ))))))
15453 (org-move-overlay org-tags-overlay ov-start ov-end)
15454 (save-window-excursion
15455 (if expert
15456 (set-buffer (get-buffer-create " *Org tags*"))
15457 (delete-other-windows)
15458 (split-window-vertically)
15459 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15460 (erase-buffer)
15461 (org-set-local 'org-done-keywords done-keywords)
15462 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15463 (org-fast-tag-insert "Current" current c-face "\n\n")
15464 (org-fast-tag-show-exit exit-after-next)
15465 (org-set-current-tags-overlay current ov-prefix)
15466 (setq tbl fulltable char ?a cnt 0)
15467 (while (setq e (pop tbl))
15468 (cond
15469 ((equal e '(:startgroup))
15470 (push '() groups) (setq ingroup t)
15471 (when (not (= cnt 0))
15472 (setq cnt 0)
15473 (insert "\n"))
15474 (insert "{ "))
15475 ((equal e '(:endgroup))
15476 (setq ingroup nil cnt 0)
15477 (insert "}\n"))
15479 (setq tg (car e) c2 nil)
15480 (if (cdr e)
15481 (setq c (cdr e))
15482 ;; automatically assign a character.
15483 (setq c1 (string-to-char
15484 (downcase (substring
15485 tg (if (= (string-to-char tg) ?@) 1 0)))))
15486 (if (or (rassoc c1 ntable) (rassoc c1 table))
15487 (while (or (rassoc char ntable) (rassoc char table))
15488 (setq char (1+ char)))
15489 (setq c2 c1))
15490 (setq c (or c2 char)))
15491 (if ingroup (push tg (car groups)))
15492 (setq tg (org-add-props tg nil 'face
15493 (cond
15494 ((not (assoc tg table))
15495 (org-get-todo-face tg))
15496 ((member tg current) c-face)
15497 ((member tg inherited) i-face)
15498 (t nil))))
15499 (if (and (= cnt 0) (not ingroup)) (insert " "))
15500 (insert "[" c "] " tg (make-string
15501 (- fwidth 4 (length tg)) ?\ ))
15502 (push (cons tg c) ntable)
15503 (when (= (setq cnt (1+ cnt)) ncol)
15504 (insert "\n")
15505 (if ingroup (insert " "))
15506 (setq cnt 0)))))
15507 (setq ntable (nreverse ntable))
15508 (insert "\n")
15509 (goto-char (point-min))
15510 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15511 (fit-window-to-buffer))
15512 (setq rtn
15513 (catch 'exit
15514 (while t
15515 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15516 (if groups " [!] no groups" " [!]groups")
15517 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15518 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15519 (cond
15520 ((= c ?\r) (throw 'exit t))
15521 ((= c ?!)
15522 (setq groups (not groups))
15523 (goto-char (point-min))
15524 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15525 ((= c ?\C-c)
15526 (if (not expert)
15527 (org-fast-tag-show-exit
15528 (setq exit-after-next (not exit-after-next)))
15529 (setq expert nil)
15530 (delete-other-windows)
15531 (split-window-vertically)
15532 (org-switch-to-buffer-other-window " *Org tags*")
15533 (and (fboundp 'fit-window-to-buffer)
15534 (fit-window-to-buffer))))
15535 ((or (= c ?\C-g)
15536 (and (= c ?q) (not (rassoc c ntable))))
15537 (org-detach-overlay org-tags-overlay)
15538 (setq quit-flag t))
15539 ((= c ?\ )
15540 (setq current nil)
15541 (if exit-after-next (setq exit-after-next 'now)))
15542 ((= c ?\t)
15543 (condition-case nil
15544 (setq tg (completing-read
15545 "Tag: "
15546 (or buffer-tags
15547 (with-current-buffer buf
15548 (org-get-buffer-tags)))))
15549 (quit (setq tg "")))
15550 (when (string-match "\\S-" tg)
15551 (add-to-list 'buffer-tags (list tg))
15552 (if (member tg current)
15553 (setq current (delete tg current))
15554 (push tg current)))
15555 (if exit-after-next (setq exit-after-next 'now)))
15556 ((setq e (rassoc c todo-table) tg (car e))
15557 (with-current-buffer buf
15558 (save-excursion (org-todo tg)))
15559 (if exit-after-next (setq exit-after-next 'now)))
15560 ((setq e (rassoc c ntable) tg (car e))
15561 (if (member tg current)
15562 (setq current (delete tg current))
15563 (loop for g in groups do
15564 (if (member tg g)
15565 (mapc (lambda (x)
15566 (setq current (delete x current)))
15567 g)))
15568 (push tg current))
15569 (if exit-after-next (setq exit-after-next 'now))))
15571 ;; Create a sorted list
15572 (setq current
15573 (sort current
15574 (lambda (a b)
15575 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15576 (if (eq exit-after-next 'now) (throw 'exit t))
15577 (goto-char (point-min))
15578 (beginning-of-line 2)
15579 (delete-region (point) (point-at-eol))
15580 (org-fast-tag-insert "Current" current c-face)
15581 (org-set-current-tags-overlay current ov-prefix)
15582 (while (re-search-forward
15583 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15584 (setq tg (match-string 1))
15585 (add-text-properties
15586 (match-beginning 1) (match-end 1)
15587 (list 'face
15588 (cond
15589 ((member tg current) c-face)
15590 ((member tg inherited) i-face)
15591 (t (get-text-property (match-beginning 1) 'face))))))
15592 (goto-char (point-min)))))
15593 (org-detach-overlay org-tags-overlay)
15594 (if rtn
15595 (mapconcat 'identity current ":")
15596 nil))))
15598 (defun org-get-tags-string ()
15599 "Get the TAGS string in the current headline."
15600 (unless (org-on-heading-p t)
15601 (error "Not on a heading"))
15602 (save-excursion
15603 (beginning-of-line 1)
15604 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15605 (org-match-string-no-properties 1)
15606 "")))
15608 (defun org-get-tags ()
15609 "Get the list of tags specified in the current headline."
15610 (org-split-string (org-get-tags-string) ":"))
15612 (defun org-get-buffer-tags ()
15613 "Get a table of all tags used in the buffer, for completion."
15614 (let (tags)
15615 (save-excursion
15616 (goto-char (point-min))
15617 (while (re-search-forward
15618 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15619 (when (equal (char-after (point-at-bol 0)) ?*)
15620 (mapc (lambda (x) (add-to-list 'tags x))
15621 (org-split-string (org-match-string-no-properties 1) ":")))))
15622 (mapcar 'list tags)))
15625 ;;;; Properties
15627 ;;; Setting and retrieving properties
15629 (defconst org-special-properties
15630 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15631 "TIMESTAMP" "TIMESTAMP_IA")
15632 "The special properties valid in Org-mode.
15634 These are properties that are not defined in the property drawer,
15635 but in some other way.")
15637 (defconst org-default-properties
15638 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15639 "LOCATION" "LOGGING" "COLUMNS")
15640 "Some properties that are used by Org-mode for various purposes.
15641 Being in this list makes sure that they are offered for completion.")
15643 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15644 "Regular expression matching the first line of a property drawer.")
15646 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15647 "Regular expression matching the first line of a property drawer.")
15649 (defun org-property-action ()
15650 "Do an action on properties."
15651 (interactive)
15652 (let (c)
15653 (org-at-property-p)
15654 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15655 (setq c (read-char-exclusive))
15656 (cond
15657 ((equal c ?s)
15658 (call-interactively 'org-set-property))
15659 ((equal c ?d)
15660 (call-interactively 'org-delete-property))
15661 ((equal c ?D)
15662 (call-interactively 'org-delete-property-globally))
15663 ((equal c ?c)
15664 (call-interactively 'org-compute-property-at-point))
15665 (t (error "No such property action %c" c)))))
15667 (defun org-at-property-p ()
15668 "Is the cursor in a property line?"
15669 ;; FIXME: Does not check if we are actually in the drawer.
15670 ;; FIXME: also returns true on any drawers.....
15671 ;; This is used by C-c C-c for property action.
15672 (save-excursion
15673 (beginning-of-line 1)
15674 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15676 (defmacro org-with-point-at (pom &rest body)
15677 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15678 (declare (indent 1) (debug t))
15679 `(save-excursion
15680 (if (markerp pom) (set-buffer (marker-buffer pom)))
15681 (save-excursion
15682 (goto-char (or pom (point)))
15683 ,@body)))
15685 (defun org-get-property-block (&optional beg end force)
15686 "Return the (beg . end) range of the body of the property drawer.
15687 BEG and END can be beginning and end of subtree, if not given
15688 they will be found.
15689 If the drawer does not exist and FORCE is non-nil, create the drawer."
15690 (catch 'exit
15691 (save-excursion
15692 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15693 (end (or end (progn (outline-next-heading) (point)))))
15694 (goto-char beg)
15695 (if (re-search-forward org-property-start-re end t)
15696 (setq beg (1+ (match-end 0)))
15697 (if force
15698 (save-excursion
15699 (org-insert-property-drawer)
15700 (setq end (progn (outline-next-heading) (point))))
15701 (throw 'exit nil))
15702 (goto-char beg)
15703 (if (re-search-forward org-property-start-re end t)
15704 (setq beg (1+ (match-end 0)))))
15705 (if (re-search-forward org-property-end-re end t)
15706 (setq end (match-beginning 0))
15707 (or force (throw 'exit nil))
15708 (goto-char beg)
15709 (setq end beg)
15710 (org-indent-line-function)
15711 (insert ":END:\n"))
15712 (cons beg end)))))
15714 (defun org-entry-properties (&optional pom which)
15715 "Get all properties of the entry at point-or-marker POM.
15716 This includes the TODO keyword, the tags, time strings for deadline,
15717 scheduled, and clocking, and any additional properties defined in the
15718 entry. The return value is an alist, keys may occur multiple times
15719 if the property key was used several times.
15720 POM may also be nil, in which case the current entry is used.
15721 If WHICH is nil or `all', get all properties. If WHICH is
15722 `special' or `standard', only get that subclass."
15723 (setq which (or which 'all))
15724 (org-with-point-at pom
15725 (let ((clockstr (substring org-clock-string 0 -1))
15726 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15727 beg end range props sum-props key value string)
15728 (save-excursion
15729 (when (condition-case nil (org-back-to-heading t) (error nil))
15730 (setq beg (point))
15731 (setq sum-props (get-text-property (point) 'org-summaries))
15732 (setq clocksum (get-text-property (point) :org-clock-minutes))
15733 (outline-next-heading)
15734 (setq end (point))
15735 (when (memq which '(all special))
15736 ;; Get the special properties, like TODO and tags
15737 (goto-char beg)
15738 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15739 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15740 (when (looking-at org-priority-regexp)
15741 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15742 (when (and (setq value (org-get-tags-string))
15743 (string-match "\\S-" value))
15744 (push (cons "TAGS" value) props))
15745 (when (setq value (org-get-tags-at))
15746 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15747 props))
15748 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15749 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15750 string (if (equal key clockstr)
15751 (org-no-properties
15752 (org-trim
15753 (buffer-substring
15754 (match-beginning 3) (goto-char (point-at-eol)))))
15755 (substring (org-match-string-no-properties 3) 1 -1)))
15756 (unless key
15757 (if (= (char-after (match-beginning 3)) ?\[)
15758 (setq key "TIMESTAMP_IA")
15759 (setq key "TIMESTAMP")))
15760 (when (or (equal key clockstr) (not (assoc key props)))
15761 (push (cons key string) props)))
15765 (when (memq which '(all standard))
15766 ;; Get the standard properties, like :PORP: ...
15767 (setq range (org-get-property-block beg end))
15768 (when range
15769 (goto-char (car range))
15770 (while (re-search-forward
15771 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15772 (cdr range) t)
15773 (setq key (org-match-string-no-properties 1)
15774 value (org-trim (or (org-match-string-no-properties 2) "")))
15775 (unless (member key excluded)
15776 (push (cons key (or value "")) props)))))
15777 (if clocksum
15778 (push (cons "CLOCKSUM"
15779 (org-column-number-to-string (/ (float clocksum) 60.)
15780 'add_times))
15781 props))
15782 (append sum-props (nreverse props)))))))
15784 (defun org-entry-get (pom property &optional inherit)
15785 "Get value of PROPERTY for entry at point-or-marker POM.
15786 If INHERIT is non-nil and the entry does not have the property,
15787 then also check higher levels of the hierarchy.
15788 If the property is present but empty, the return value is the empty string.
15789 If the property is not present at all, nil is returned."
15790 (org-with-point-at pom
15791 (if inherit
15792 (org-entry-get-with-inheritance property)
15793 (if (member property org-special-properties)
15794 ;; We need a special property. Use brute force, get all properties.
15795 (cdr (assoc property (org-entry-properties nil 'special)))
15796 (let ((range (org-get-property-block)))
15797 (if (and range
15798 (goto-char (car range))
15799 (re-search-forward
15800 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15801 (cdr range) t))
15802 ;; Found the property, return it.
15803 (if (match-end 1)
15804 (org-match-string-no-properties 1)
15805 "")))))))
15807 (defun org-entry-delete (pom property)
15808 "Delete the property PROPERTY from entry at point-or-marker POM."
15809 (org-with-point-at pom
15810 (if (member property org-special-properties)
15811 nil ; cannot delete these properties.
15812 (let ((range (org-get-property-block)))
15813 (if (and range
15814 (goto-char (car range))
15815 (re-search-forward
15816 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
15817 (cdr range) t))
15818 (progn
15819 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15821 nil)))))
15823 ;; Multi-values properties are properties that contain multiple values
15824 ;; These values are assumed to be single words, separated by whitespace.
15825 (defun org-entry-add-to-multivalued-property (pom property value)
15826 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15827 (let* ((old (org-entry-get pom property))
15828 (values (and old (org-split-string old "[ \t]"))))
15829 (unless (member value values)
15830 (setq values (cons value values))
15831 (org-entry-put pom property
15832 (mapconcat 'identity values " ")))))
15834 (defun org-entry-remove-from-multivalued-property (pom property value)
15835 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15836 (let* ((old (org-entry-get pom property))
15837 (values (and old (org-split-string old "[ \t]"))))
15838 (when (member value values)
15839 (setq values (delete value values))
15840 (org-entry-put pom property
15841 (mapconcat 'identity values " ")))))
15843 (defun org-entry-member-in-multivalued-property (pom property value)
15844 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15845 (let* ((old (org-entry-get pom property))
15846 (values (and old (org-split-string old "[ \t]"))))
15847 (member value values)))
15849 (defvar org-entry-property-inherited-from (make-marker))
15851 (defun org-entry-get-with-inheritance (property)
15852 "Get entry property, and search higher levels if not present."
15853 (let (tmp)
15854 (save-excursion
15855 (save-restriction
15856 (widen)
15857 (catch 'ex
15858 (while t
15859 (when (setq tmp (org-entry-get nil property))
15860 (org-back-to-heading t)
15861 (move-marker org-entry-property-inherited-from (point))
15862 (throw 'ex tmp))
15863 (or (org-up-heading-safe) (throw 'ex nil)))))
15864 (or tmp (cdr (assoc property org-local-properties))
15865 (cdr (assoc property org-global-properties))))))
15867 (defun org-entry-put (pom property value)
15868 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15869 (org-with-point-at pom
15870 (org-back-to-heading t)
15871 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15872 range)
15873 (cond
15874 ((equal property "TODO")
15875 (when (and (stringp value) (string-match "\\S-" value)
15876 (not (member value org-todo-keywords-1)))
15877 (error "\"%s\" is not a valid TODO state" value))
15878 (if (or (not value)
15879 (not (string-match "\\S-" value)))
15880 (setq value 'none))
15881 (org-todo value)
15882 (org-set-tags nil 'align))
15883 ((equal property "PRIORITY")
15884 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15885 (string-to-char value) ?\ ))
15886 (org-set-tags nil 'align))
15887 ((equal property "SCHEDULED")
15888 (if (re-search-forward org-scheduled-time-regexp end t)
15889 (cond
15890 ((eq value 'earlier) (org-timestamp-change -1 'day))
15891 ((eq value 'later) (org-timestamp-change 1 'day))
15892 (t (call-interactively 'org-schedule)))
15893 (call-interactively 'org-schedule)))
15894 ((equal property "DEADLINE")
15895 (if (re-search-forward org-deadline-time-regexp end t)
15896 (cond
15897 ((eq value 'earlier) (org-timestamp-change -1 'day))
15898 ((eq value 'later) (org-timestamp-change 1 'day))
15899 (t (call-interactively 'org-deadline)))
15900 (call-interactively 'org-deadline)))
15901 ((member property org-special-properties)
15902 (error "The %s property can not yet be set with `org-entry-put'"
15903 property))
15904 (t ; a non-special property
15905 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15906 (setq range (org-get-property-block beg end 'force))
15907 (goto-char (car range))
15908 (if (re-search-forward
15909 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15910 (progn
15911 (delete-region (match-beginning 1) (match-end 1))
15912 (goto-char (match-beginning 1)))
15913 (goto-char (cdr range))
15914 (insert "\n")
15915 (backward-char 1)
15916 (org-indent-line-function)
15917 (insert ":" property ":"))
15918 (and value (insert " " value))
15919 (org-indent-line-function)))))))
15921 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15922 "Get all property keys in the current buffer.
15923 With INCLUDE-SPECIALS, also list the special properties that relect things
15924 like tags and TODO state.
15925 With INCLUDE-DEFAULTS, also include properties that has special meaning
15926 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15927 (let (rtn range)
15928 (save-excursion
15929 (save-restriction
15930 (widen)
15931 (goto-char (point-min))
15932 (while (re-search-forward org-property-start-re nil t)
15933 (setq range (org-get-property-block))
15934 (goto-char (car range))
15935 (while (re-search-forward
15936 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15937 (cdr range) t)
15938 (add-to-list 'rtn (org-match-string-no-properties 1)))
15939 (outline-next-heading))))
15941 (when include-specials
15942 (setq rtn (append org-special-properties rtn)))
15944 (when include-defaults
15945 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15947 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15949 (defun org-property-values (key)
15950 "Return a list of all values of property KEY."
15951 (save-excursion
15952 (save-restriction
15953 (widen)
15954 (goto-char (point-min))
15955 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15956 values)
15957 (while (re-search-forward re nil t)
15958 (add-to-list 'values (org-trim (match-string 1))))
15959 (delete "" values)))))
15961 (defun org-insert-property-drawer ()
15962 "Insert a property drawer into the current entry."
15963 (interactive)
15964 (org-back-to-heading t)
15965 (looking-at outline-regexp)
15966 (let ((indent (- (match-end 0)(match-beginning 0)))
15967 (beg (point))
15968 (re (concat "^[ \t]*" org-keyword-time-regexp))
15969 end hiddenp)
15970 (outline-next-heading)
15971 (setq end (point))
15972 (goto-char beg)
15973 (while (re-search-forward re end t))
15974 (setq hiddenp (org-invisible-p))
15975 (end-of-line 1)
15976 (and (equal (char-after) ?\n) (forward-char 1))
15977 (org-skip-over-state-notes)
15978 (skip-chars-backward " \t\n\r")
15979 (if (eq (char-before) ?*) (forward-char 1))
15980 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15981 (beginning-of-line 0)
15982 (indent-to-column indent)
15983 (beginning-of-line 2)
15984 (indent-to-column indent)
15985 (beginning-of-line 0)
15986 (if hiddenp
15987 (save-excursion
15988 (org-back-to-heading t)
15989 (hide-entry))
15990 (org-flag-drawer t))))
15992 (defun org-set-property (property value)
15993 "In the current entry, set PROPERTY to VALUE.
15994 When called interactively, this will prompt for a property name, offering
15995 completion on existing and default properties. And then it will prompt
15996 for a value, offering competion either on allowed values (via an inherited
15997 xxx_ALL property) or on existing values in other instances of this property
15998 in the current file."
15999 (interactive
16000 (let* ((prop (completing-read
16001 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
16002 (cur (org-entry-get nil prop))
16003 (allowed (org-property-get-allowed-values nil prop 'table))
16004 (existing (mapcar 'list (org-property-values prop)))
16005 (val (if allowed
16006 (completing-read "Value: " allowed nil 'req-match)
16007 (completing-read
16008 (concat "Value" (if (and cur (string-match "\\S-" cur))
16009 (concat "[" cur "]") "")
16010 ": ")
16011 existing nil nil "" nil cur))))
16012 (list prop (if (equal val "") cur val))))
16013 (unless (equal (org-entry-get nil property) value)
16014 (org-entry-put nil property value)))
16016 (defun org-delete-property (property)
16017 "In the current entry, delete PROPERTY."
16018 (interactive
16019 (let* ((prop (completing-read
16020 "Property: " (org-entry-properties nil 'standard))))
16021 (list prop)))
16022 (message "Property %s %s" property
16023 (if (org-entry-delete nil property)
16024 "deleted"
16025 "was not present in the entry")))
16027 (defun org-delete-property-globally (property)
16028 "Remove PROPERTY globally, from all entries."
16029 (interactive
16030 (let* ((prop (completing-read
16031 "Globally remove property: "
16032 (mapcar 'list (org-buffer-property-keys)))))
16033 (list prop)))
16034 (save-excursion
16035 (save-restriction
16036 (widen)
16037 (goto-char (point-min))
16038 (let ((cnt 0))
16039 (while (re-search-forward
16040 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16041 nil t)
16042 (setq cnt (1+ cnt))
16043 (replace-match ""))
16044 (message "Property \"%s\" removed from %d entries" property cnt)))))
16046 (defvar org-columns-current-fmt-compiled) ; defined below
16048 (defun org-compute-property-at-point ()
16049 "Compute the property at point.
16050 This looks for an enclosing column format, extracts the operator and
16051 then applies it to the proerty in the column format's scope."
16052 (interactive)
16053 (unless (org-at-property-p)
16054 (error "Not at a property"))
16055 (let ((prop (org-match-string-no-properties 2)))
16056 (org-columns-get-format-and-top-level)
16057 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16058 (error "No operator defined for property %s" prop))
16059 (org-columns-compute prop)))
16061 (defun org-property-get-allowed-values (pom property &optional table)
16062 "Get allowed values for the property PROPERTY.
16063 When TABLE is non-nil, return an alist that can directly be used for
16064 completion."
16065 (let (vals)
16066 (cond
16067 ((equal property "TODO")
16068 (setq vals (org-with-point-at pom
16069 (append org-todo-keywords-1 '("")))))
16070 ((equal property "PRIORITY")
16071 (let ((n org-lowest-priority))
16072 (while (>= n org-highest-priority)
16073 (push (char-to-string n) vals)
16074 (setq n (1- n)))))
16075 ((member property org-special-properties))
16077 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16079 (when (and vals (string-match "\\S-" vals))
16080 (setq vals (car (read-from-string (concat "(" vals ")"))))
16081 (setq vals (mapcar (lambda (x)
16082 (cond ((stringp x) x)
16083 ((numberp x) (number-to-string x))
16084 ((symbolp x) (symbol-name x))
16085 (t "???")))
16086 vals)))))
16087 (if table (mapcar 'list vals) vals)))
16089 (defun org-property-previous-allowed-value (&optional previous)
16090 "Switch to the next allowed value for this property."
16091 (interactive)
16092 (org-property-next-allowed-value t))
16094 (defun org-property-next-allowed-value (&optional previous)
16095 "Switch to the next allowed value for this property."
16096 (interactive)
16097 (unless (org-at-property-p)
16098 (error "Not at a property"))
16099 (let* ((key (match-string 2))
16100 (value (match-string 3))
16101 (allowed (or (org-property-get-allowed-values (point) key)
16102 (and (member value '("[ ]" "[-]" "[X]"))
16103 '("[ ]" "[X]"))))
16104 nval)
16105 (unless allowed
16106 (error "Allowed values for this property have not been defined"))
16107 (if previous (setq allowed (reverse allowed)))
16108 (if (member value allowed)
16109 (setq nval (car (cdr (member value allowed)))))
16110 (setq nval (or nval (car allowed)))
16111 (if (equal nval value)
16112 (error "Only one allowed value for this property"))
16113 (org-at-property-p)
16114 (replace-match (concat " :" key ": " nval) t t)
16115 (org-indent-line-function)
16116 (beginning-of-line 1)
16117 (skip-chars-forward " \t")))
16119 (defun org-find-entry-with-id (ident)
16120 "Locate the entry that contains the ID property with exact value IDENT.
16121 IDENT can be a string, a symbol or a number, this function will search for
16122 the string representation of it.
16123 Return the position where this entry starts, or nil if there is no such entry."
16124 (let ((id (cond
16125 ((stringp ident) ident)
16126 ((symbol-name ident) (symbol-name ident))
16127 ((numberp ident) (number-to-string ident))
16128 (t (error "IDENT %s must be a string, symbol or number" ident))))
16129 (case-fold-search nil))
16130 (save-excursion
16131 (save-restriction
16132 (goto-char (point-min))
16133 (when (re-search-forward
16134 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16135 nil t)
16136 (org-back-to-heading)
16137 (point))))))
16139 ;;; Column View
16141 (defvar org-columns-overlays nil
16142 "Holds the list of current column overlays.")
16144 (defvar org-columns-current-fmt nil
16145 "Local variable, holds the currently active column format.")
16146 (defvar org-columns-current-fmt-compiled nil
16147 "Local variable, holds the currently active column format.
16148 This is the compiled version of the format.")
16149 (defvar org-columns-current-widths nil
16150 "Loval variable, holds the currently widths of fields.")
16151 (defvar org-columns-current-maxwidths nil
16152 "Loval variable, holds the currently active maximum column widths.")
16153 (defvar org-columns-begin-marker (make-marker)
16154 "Points to the position where last a column creation command was called.")
16155 (defvar org-columns-top-level-marker (make-marker)
16156 "Points to the position where current columns region starts.")
16158 (defvar org-columns-map (make-sparse-keymap)
16159 "The keymap valid in column display.")
16161 (defun org-columns-content ()
16162 "Switch to contents view while in columns view."
16163 (interactive)
16164 (org-overview)
16165 (org-content))
16167 (org-defkey org-columns-map "c" 'org-columns-content)
16168 (org-defkey org-columns-map "o" 'org-overview)
16169 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16170 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16171 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16172 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16173 (org-defkey org-columns-map "v" 'org-columns-show-value)
16174 (org-defkey org-columns-map "q" 'org-columns-quit)
16175 (org-defkey org-columns-map "r" 'org-columns-redo)
16176 (org-defkey org-columns-map [left] 'backward-char)
16177 (org-defkey org-columns-map "\M-b" 'backward-char)
16178 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16179 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16180 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16181 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16182 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16183 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16184 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16185 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16186 (org-defkey org-columns-map "<" 'org-columns-narrow)
16187 (org-defkey org-columns-map ">" 'org-columns-widen)
16188 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16189 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16190 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16191 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16193 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16194 '("Column"
16195 ["Edit property" org-columns-edit-value t]
16196 ["Next allowed value" org-columns-next-allowed-value t]
16197 ["Previous allowed value" org-columns-previous-allowed-value t]
16198 ["Show full value" org-columns-show-value t]
16199 ["Edit allowed values" org-columns-edit-allowed t]
16200 "--"
16201 ["Edit column attributes" org-columns-edit-attributes t]
16202 ["Increase column width" org-columns-widen t]
16203 ["Decrease column width" org-columns-narrow t]
16204 "--"
16205 ["Move column right" org-columns-move-right t]
16206 ["Move column left" org-columns-move-left t]
16207 ["Add column" org-columns-new t]
16208 ["Delete column" org-columns-delete t]
16209 "--"
16210 ["CONTENTS" org-columns-content t]
16211 ["OVERVIEW" org-overview t]
16212 ["Refresh columns display" org-columns-redo t]
16213 "--"
16214 ["Open link" org-columns-open-link t]
16215 "--"
16216 ["Quit" org-columns-quit t]))
16218 (defun org-columns-new-overlay (beg end &optional string face)
16219 "Create a new column overlay and add it to the list."
16220 (let ((ov (org-make-overlay beg end)))
16221 (org-overlay-put ov 'face (or face 'secondary-selection))
16222 (org-overlay-display ov string face)
16223 (push ov org-columns-overlays)
16224 ov))
16226 (defun org-columns-display-here (&optional props)
16227 "Overlay the current line with column display."
16228 (interactive)
16229 (let* ((fmt org-columns-current-fmt-compiled)
16230 (beg (point-at-bol))
16231 (level-face (save-excursion
16232 (beginning-of-line 1)
16233 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16234 (org-get-level-face 2))))
16235 (color (list :foreground
16236 (face-attribute (or level-face 'default) :foreground)))
16237 props pom property ass width f string ov column val modval)
16238 ;; Check if the entry is in another buffer.
16239 (unless props
16240 (if (eq major-mode 'org-agenda-mode)
16241 (setq pom (or (get-text-property (point) 'org-hd-marker)
16242 (get-text-property (point) 'org-marker))
16243 props (if pom (org-entry-properties pom) nil))
16244 (setq props (org-entry-properties nil))))
16245 ;; Walk the format
16246 (while (setq column (pop fmt))
16247 (setq property (car column)
16248 ass (if (equal property "ITEM")
16249 (cons "ITEM"
16250 (save-match-data
16251 (org-no-properties
16252 (org-remove-tabs
16253 (buffer-substring-no-properties
16254 (point-at-bol) (point-at-eol))))))
16255 (assoc property props))
16256 width (or (cdr (assoc property org-columns-current-maxwidths))
16257 (nth 2 column)
16258 (length property))
16259 f (format "%%-%d.%ds | " width width)
16260 val (or (cdr ass) "")
16261 modval (if (equal property "ITEM")
16262 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16263 string (format f (or modval val)))
16264 ;; Create the overlay
16265 (org-unmodified
16266 (setq ov (org-columns-new-overlay
16267 beg (setq beg (1+ beg)) string
16268 (list color 'org-column)))
16269 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16270 (org-overlay-put ov 'keymap org-columns-map)
16271 (org-overlay-put ov 'org-columns-key property)
16272 (org-overlay-put ov 'org-columns-value (cdr ass))
16273 (org-overlay-put ov 'org-columns-value-modified modval)
16274 (org-overlay-put ov 'org-columns-pom pom)
16275 (org-overlay-put ov 'org-columns-format f))
16276 (if (or (not (char-after beg))
16277 (equal (char-after beg) ?\n))
16278 (let ((inhibit-read-only t))
16279 (save-excursion
16280 (goto-char beg)
16281 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16282 ;; Make the rest of the line disappear.
16283 (org-unmodified
16284 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16285 (org-overlay-put ov 'invisible t)
16286 (org-overlay-put ov 'keymap org-columns-map)
16287 (org-overlay-put ov 'intangible t)
16288 (push ov org-columns-overlays)
16289 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16290 (org-overlay-put ov 'keymap org-columns-map)
16291 (push ov org-columns-overlays)
16292 (let ((inhibit-read-only t))
16293 (put-text-property (max (point-min) (1- (point-at-bol)))
16294 (min (point-max) (1+ (point-at-eol)))
16295 'read-only "Type `e' to edit property")))))
16297 (defvar org-previous-header-line-format nil
16298 "The header line format before column view was turned on.")
16299 (defvar org-columns-inhibit-recalculation nil
16300 "Inhibit recomputing of columns on column view startup.")
16303 (defvar header-line-format)
16304 (defun org-columns-display-here-title ()
16305 "Overlay the newline before the current line with the table title."
16306 (interactive)
16307 (let ((fmt org-columns-current-fmt-compiled)
16308 string (title "")
16309 property width f column str widths)
16310 (while (setq column (pop fmt))
16311 (setq property (car column)
16312 str (or (nth 1 column) property)
16313 width (or (cdr (assoc property org-columns-current-maxwidths))
16314 (nth 2 column)
16315 (length str))
16316 widths (push width widths)
16317 f (format "%%-%d.%ds | " width width)
16318 string (format f str)
16319 title (concat title string)))
16320 (setq title (concat
16321 (org-add-props " " nil 'display '(space :align-to 0))
16322 (org-add-props title nil 'face '(:weight bold :underline t))))
16323 (org-set-local 'org-previous-header-line-format header-line-format)
16324 (org-set-local 'org-columns-current-widths (nreverse widths))
16325 (setq header-line-format title)))
16327 (defun org-columns-remove-overlays ()
16328 "Remove all currently active column overlays."
16329 (interactive)
16330 (when (marker-buffer org-columns-begin-marker)
16331 (with-current-buffer (marker-buffer org-columns-begin-marker)
16332 (when (local-variable-p 'org-previous-header-line-format)
16333 (setq header-line-format org-previous-header-line-format)
16334 (kill-local-variable 'org-previous-header-line-format))
16335 (move-marker org-columns-begin-marker nil)
16336 (move-marker org-columns-top-level-marker nil)
16337 (org-unmodified
16338 (mapc 'org-delete-overlay org-columns-overlays)
16339 (setq org-columns-overlays nil)
16340 (let ((inhibit-read-only t))
16341 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16343 (defun org-columns-cleanup-item (item fmt)
16344 "Remove from ITEM what is a column in the format FMT."
16345 (if (not org-complex-heading-regexp)
16346 item
16347 (when (string-match org-complex-heading-regexp item)
16348 (concat
16349 (org-add-props (concat (match-string 1 item) " ") nil
16350 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16351 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16352 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16353 " " (match-string 4 item)
16354 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16356 (defun org-columns-show-value ()
16357 "Show the full value of the property."
16358 (interactive)
16359 (let ((value (get-char-property (point) 'org-columns-value)))
16360 (message "Value is: %s" (or value ""))))
16362 (defun org-columns-quit ()
16363 "Remove the column overlays and in this way exit column editing."
16364 (interactive)
16365 (org-unmodified
16366 (org-columns-remove-overlays)
16367 (let ((inhibit-read-only t))
16368 (remove-text-properties (point-min) (point-max) '(read-only t))))
16369 (when (eq major-mode 'org-agenda-mode)
16370 (message
16371 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16373 (defun org-columns-check-computed ()
16374 "Check if this column value is computed.
16375 If yes, throw an error indicating that changing it does not make sense."
16376 (let ((val (get-char-property (point) 'org-columns-value)))
16377 (when (and (stringp val)
16378 (get-char-property 0 'org-computed val))
16379 (error "This value is computed from the entry's children"))))
16381 (defun org-columns-todo (&optional arg)
16382 "Change the TODO state during column view."
16383 (interactive "P")
16384 (org-columns-edit-value "TODO"))
16386 (defun org-columns-set-tags-or-toggle (&optional arg)
16387 "Toggle checkbox at point, or set tags for current headline."
16388 (interactive "P")
16389 (if (string-match "\\`\\[[ xX-]\\]\\'"
16390 (get-char-property (point) 'org-columns-value))
16391 (org-columns-next-allowed-value)
16392 (org-columns-edit-value "TAGS")))
16394 (defun org-columns-edit-value (&optional key)
16395 "Edit the value of the property at point in column view.
16396 Where possible, use the standard interface for changing this line."
16397 (interactive)
16398 (org-columns-check-computed)
16399 (let* ((external-key key)
16400 (col (current-column))
16401 (key (or key (get-char-property (point) 'org-columns-key)))
16402 (value (get-char-property (point) 'org-columns-value))
16403 (bol (point-at-bol)) (eol (point-at-eol))
16404 (pom (or (get-text-property bol 'org-hd-marker)
16405 (point))) ; keep despite of compiler waring
16406 (line-overlays
16407 (delq nil (mapcar (lambda (x)
16408 (and (eq (overlay-buffer x) (current-buffer))
16409 (>= (overlay-start x) bol)
16410 (<= (overlay-start x) eol)
16412 org-columns-overlays)))
16413 nval eval allowed)
16414 (cond
16415 ((equal key "CLOCKSUM")
16416 (error "This special column cannot be edited"))
16417 ((equal key "ITEM")
16418 (setq eval '(org-with-point-at pom
16419 (org-edit-headline))))
16420 ((equal key "TODO")
16421 (setq eval '(org-with-point-at pom
16422 (let ((current-prefix-arg
16423 (if external-key current-prefix-arg '(4))))
16424 (call-interactively 'org-todo)))))
16425 ((equal key "PRIORITY")
16426 (setq eval '(org-with-point-at pom
16427 (call-interactively 'org-priority))))
16428 ((equal key "TAGS")
16429 (setq eval '(org-with-point-at pom
16430 (let ((org-fast-tag-selection-single-key
16431 (if (eq org-fast-tag-selection-single-key 'expert)
16432 t org-fast-tag-selection-single-key)))
16433 (call-interactively 'org-set-tags)))))
16434 ((equal key "DEADLINE")
16435 (setq eval '(org-with-point-at pom
16436 (call-interactively 'org-deadline))))
16437 ((equal key "SCHEDULED")
16438 (setq eval '(org-with-point-at pom
16439 (call-interactively 'org-schedule))))
16441 (setq allowed (org-property-get-allowed-values pom key 'table))
16442 (if allowed
16443 (setq nval (completing-read "Value: " allowed nil t))
16444 (setq nval (read-string "Edit: " value)))
16445 (setq nval (org-trim nval))
16446 (when (not (equal nval value))
16447 (setq eval '(org-entry-put pom key nval)))))
16448 (when eval
16449 (let ((inhibit-read-only t))
16450 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16451 (unwind-protect
16452 (progn
16453 (setq org-columns-overlays
16454 (org-delete-all line-overlays org-columns-overlays))
16455 (mapc 'org-delete-overlay line-overlays)
16456 (org-columns-eval eval))
16457 (org-columns-display-here))))
16458 (move-to-column col)
16459 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16460 (org-columns-update key))))
16462 (defun org-edit-headline () ; FIXME: this is not columns specific
16463 "Edit the current headline, the part without TODO keyword, TAGS."
16464 (org-back-to-heading)
16465 (when (looking-at org-todo-line-regexp)
16466 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16467 (txt (match-string 3))
16468 (post "")
16469 txt2)
16470 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16471 (setq post (match-string 0 txt)
16472 txt (substring txt 0 (match-beginning 0))))
16473 (setq txt2 (read-string "Edit: " txt))
16474 (when (not (equal txt txt2))
16475 (beginning-of-line 1)
16476 (insert pre txt2 post)
16477 (delete-region (point) (point-at-eol))
16478 (org-set-tags nil t)))))
16480 (defun org-columns-edit-allowed ()
16481 "Edit the list of allowed values for the current property."
16482 (interactive)
16483 (let* ((key (get-char-property (point) 'org-columns-key))
16484 (key1 (concat key "_ALL"))
16485 (allowed (org-entry-get (point) key1 t))
16486 nval)
16487 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16488 (setq nval (read-string "Allowed: " allowed))
16489 (org-entry-put
16490 (cond ((marker-position org-entry-property-inherited-from)
16491 org-entry-property-inherited-from)
16492 ((marker-position org-columns-top-level-marker)
16493 org-columns-top-level-marker))
16494 key1 nval)))
16496 (defmacro org-no-warnings (&rest body)
16497 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16499 (defun org-columns-eval (form)
16500 (let (hidep)
16501 (save-excursion
16502 (beginning-of-line 1)
16503 ;; `next-line' is needed here, because it skips invisible line.
16504 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16505 (setq hidep (org-on-heading-p 1)))
16506 (eval form)
16507 (and hidep (hide-entry))))
16509 (defun org-columns-previous-allowed-value ()
16510 "Switch to the previous allowed value for this column."
16511 (interactive)
16512 (org-columns-next-allowed-value t))
16514 (defun org-columns-next-allowed-value (&optional previous)
16515 "Switch to the next allowed value for this column."
16516 (interactive)
16517 (org-columns-check-computed)
16518 (let* ((col (current-column))
16519 (key (get-char-property (point) 'org-columns-key))
16520 (value (get-char-property (point) 'org-columns-value))
16521 (bol (point-at-bol)) (eol (point-at-eol))
16522 (pom (or (get-text-property bol 'org-hd-marker)
16523 (point))) ; keep despite of compiler waring
16524 (line-overlays
16525 (delq nil (mapcar (lambda (x)
16526 (and (eq (overlay-buffer x) (current-buffer))
16527 (>= (overlay-start x) bol)
16528 (<= (overlay-start x) eol)
16530 org-columns-overlays)))
16531 (allowed (or (org-property-get-allowed-values pom key)
16532 (and (equal
16533 (nth 4 (assoc key org-columns-current-fmt-compiled))
16534 'checkbox) '("[ ]" "[X]"))))
16535 nval)
16536 (when (equal key "ITEM")
16537 (error "Cannot edit item headline from here"))
16538 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16539 (error "Allowed values for this property have not been defined"))
16540 (if (member key '("SCHEDULED" "DEADLINE"))
16541 (setq nval (if previous 'earlier 'later))
16542 (if previous (setq allowed (reverse allowed)))
16543 (if (member value allowed)
16544 (setq nval (car (cdr (member value allowed)))))
16545 (setq nval (or nval (car allowed)))
16546 (if (equal nval value)
16547 (error "Only one allowed value for this property")))
16548 (let ((inhibit-read-only t))
16549 (remove-text-properties (1- bol) eol '(read-only t))
16550 (unwind-protect
16551 (progn
16552 (setq org-columns-overlays
16553 (org-delete-all line-overlays org-columns-overlays))
16554 (mapc 'org-delete-overlay line-overlays)
16555 (org-columns-eval '(org-entry-put pom key nval)))
16556 (org-columns-display-here)))
16557 (move-to-column col)
16558 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16559 (org-columns-update key))))
16561 (defun org-verify-version (task)
16562 (cond
16563 ((eq task 'columns)
16564 (if (or (featurep 'xemacs)
16565 (< emacs-major-version 22))
16566 (error "Emacs 22 is required for the columns feature")))))
16568 (defun org-columns-open-link (&optional arg)
16569 (interactive "P")
16570 (let ((key (get-char-property (point) 'org-columns-key))
16571 (value (get-char-property (point) 'org-columns-value)))
16572 (org-open-link-from-string arg)))
16574 (defun org-open-link-from-string (s &optional arg)
16575 "Open a link in the string S, as if it was in Org-mode."
16576 (interactive)
16577 (with-temp-buffer
16578 (let ((org-inhibit-startup t))
16579 (org-mode)
16580 (insert s)
16581 (goto-char (point-min))
16582 (org-open-at-point arg))))
16584 (defun org-columns-get-format-and-top-level ()
16585 (let (fmt)
16586 (when (condition-case nil (org-back-to-heading) (error nil))
16587 (move-marker org-entry-property-inherited-from nil)
16588 (setq fmt (org-entry-get nil "COLUMNS" t)))
16589 (setq fmt (or fmt org-columns-default-format))
16590 (org-set-local 'org-columns-current-fmt fmt)
16591 (org-columns-compile-format fmt)
16592 (if (marker-position org-entry-property-inherited-from)
16593 (move-marker org-columns-top-level-marker
16594 org-entry-property-inherited-from)
16595 (move-marker org-columns-top-level-marker (point)))
16596 fmt))
16598 (defun org-columns ()
16599 "Turn on column view on an org-mode file."
16600 (interactive)
16601 (org-verify-version 'columns)
16602 (org-columns-remove-overlays)
16603 (move-marker org-columns-begin-marker (point))
16604 (let (beg end fmt cache maxwidths clocksump)
16605 (setq fmt (org-columns-get-format-and-top-level))
16606 (save-excursion
16607 (goto-char org-columns-top-level-marker)
16608 (setq beg (point))
16609 (unless org-columns-inhibit-recalculation
16610 (org-columns-compute-all))
16611 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16612 (point-max)))
16613 ;; Get and cache the properties
16614 (goto-char beg)
16615 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16616 (setq clocksump t)
16617 (save-excursion
16618 (save-restriction
16619 (narrow-to-region beg end)
16620 (org-clock-sum))))
16621 (while (re-search-forward (concat "^" outline-regexp) end t)
16622 (push (cons (org-current-line) (org-entry-properties)) cache))
16623 (when cache
16624 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16625 (org-set-local 'org-columns-current-maxwidths maxwidths)
16626 (org-columns-display-here-title)
16627 (mapc (lambda (x)
16628 (goto-line (car x))
16629 (org-columns-display-here (cdr x)))
16630 cache)))))
16632 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16633 "Insert a new column, to the leeft o the current column."
16634 (interactive)
16635 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16636 cell)
16637 (setq prop (completing-read
16638 "Property: " (mapcar 'list (org-buffer-property-keys t))
16639 nil nil prop))
16640 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16641 (setq width (read-string "Column width: " (if width (number-to-string width))))
16642 (if (string-match "\\S-" width)
16643 (setq width (string-to-number width))
16644 (setq width nil))
16645 (setq fmt (completing-read "Summary [none]: "
16646 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16647 nil t))
16648 (if (string-match "\\S-" fmt)
16649 (setq fmt (intern fmt))
16650 (setq fmt nil))
16651 (if (eq fmt 'none) (setq fmt nil))
16652 (if editp
16653 (progn
16654 (setcar editp prop)
16655 (setcdr editp (list title width nil fmt)))
16656 (setq cell (nthcdr (1- (current-column))
16657 org-columns-current-fmt-compiled))
16658 (setcdr cell (cons (list prop title width nil fmt)
16659 (cdr cell))))
16660 (org-columns-store-format)
16661 (org-columns-redo)))
16663 (defun org-columns-delete ()
16664 "Delete the column at point from columns view."
16665 (interactive)
16666 (let* ((n (current-column))
16667 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16668 (when (y-or-n-p
16669 (format "Are you sure you want to remove column \"%s\"? " title))
16670 (setq org-columns-current-fmt-compiled
16671 (delq (nth n org-columns-current-fmt-compiled)
16672 org-columns-current-fmt-compiled))
16673 (org-columns-store-format)
16674 (org-columns-redo)
16675 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16676 (backward-char 1)))))
16678 (defun org-columns-edit-attributes ()
16679 "Edit the attributes of the current column."
16680 (interactive)
16681 (let* ((n (current-column))
16682 (info (nth n org-columns-current-fmt-compiled)))
16683 (apply 'org-columns-new info)))
16685 (defun org-columns-widen (arg)
16686 "Make the column wider by ARG characters."
16687 (interactive "p")
16688 (let* ((n (current-column))
16689 (entry (nth n org-columns-current-fmt-compiled))
16690 (width (or (nth 2 entry)
16691 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16692 (setq width (max 1 (+ width arg)))
16693 (setcar (nthcdr 2 entry) width)
16694 (org-columns-store-format)
16695 (org-columns-redo)))
16697 (defun org-columns-narrow (arg)
16698 "Make the column nrrower by ARG characters."
16699 (interactive "p")
16700 (org-columns-widen (- arg)))
16702 (defun org-columns-move-right ()
16703 "Swap this column with the one to the right."
16704 (interactive)
16705 (let* ((n (current-column))
16706 (cell (nthcdr n org-columns-current-fmt-compiled))
16708 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16709 (error "Cannot shift this column further to the right"))
16710 (setq e (car cell))
16711 (setcar cell (car (cdr cell)))
16712 (setcdr cell (cons e (cdr (cdr cell))))
16713 (org-columns-store-format)
16714 (org-columns-redo)
16715 (forward-char 1)))
16717 (defun org-columns-move-left ()
16718 "Swap this column with the one to the left."
16719 (interactive)
16720 (let* ((n (current-column)))
16721 (when (= n 0)
16722 (error "Cannot shift this column further to the left"))
16723 (backward-char 1)
16724 (org-columns-move-right)
16725 (backward-char 1)))
16727 (defun org-columns-store-format ()
16728 "Store the text version of the current columns format in appropriate place.
16729 This is either in the COLUMNS property of the node starting the current column
16730 display, or in the #+COLUMNS line of the current buffer."
16731 (let (fmt (cnt 0))
16732 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16733 (org-set-local 'org-columns-current-fmt fmt)
16734 (if (marker-position org-columns-top-level-marker)
16735 (save-excursion
16736 (goto-char org-columns-top-level-marker)
16737 (if (and (org-at-heading-p)
16738 (org-entry-get nil "COLUMNS"))
16739 (org-entry-put nil "COLUMNS" fmt)
16740 (goto-char (point-min))
16741 ;; Overwrite all #+COLUMNS lines....
16742 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16743 (setq cnt (1+ cnt))
16744 (replace-match (concat "#+COLUMNS: " fmt) t t))
16745 (unless (> cnt 0)
16746 (goto-char (point-min))
16747 (or (org-on-heading-p t) (outline-next-heading))
16748 (let ((inhibit-read-only t))
16749 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16750 (org-set-local 'org-columns-default-format fmt))))))
16752 (defvar org-overriding-columns-format nil
16753 "When set, overrides any other definition.")
16754 (defvar org-agenda-view-columns-initially nil
16755 "When set, switch to columns view immediately after creating the agenda.")
16757 (defun org-agenda-columns ()
16758 "Turn on column view in the agenda."
16759 (interactive)
16760 (org-verify-version 'columns)
16761 (org-columns-remove-overlays)
16762 (move-marker org-columns-begin-marker (point))
16763 (let (fmt cache maxwidths m)
16764 (cond
16765 ((and (local-variable-p 'org-overriding-columns-format)
16766 org-overriding-columns-format)
16767 (setq fmt org-overriding-columns-format))
16768 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16769 (setq fmt (org-entry-get m "COLUMNS" t)))
16770 ((and (boundp 'org-columns-current-fmt)
16771 (local-variable-p 'org-columns-current-fmt)
16772 org-columns-current-fmt)
16773 (setq fmt org-columns-current-fmt))
16774 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16775 (setq m (get-text-property m 'org-hd-marker))
16776 (setq fmt (org-entry-get m "COLUMNS" t))))
16777 (setq fmt (or fmt org-columns-default-format))
16778 (org-set-local 'org-columns-current-fmt fmt)
16779 (org-columns-compile-format fmt)
16780 (save-excursion
16781 ;; Get and cache the properties
16782 (goto-char (point-min))
16783 (while (not (eobp))
16784 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16785 (get-text-property (point) 'org-marker)))
16786 (push (cons (org-current-line) (org-entry-properties m)) cache))
16787 (beginning-of-line 2))
16788 (when cache
16789 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16790 (org-set-local 'org-columns-current-maxwidths maxwidths)
16791 (org-columns-display-here-title)
16792 (mapc (lambda (x)
16793 (goto-line (car x))
16794 (org-columns-display-here (cdr x)))
16795 cache)))))
16797 (defun org-columns-get-autowidth-alist (s cache)
16798 "Derive the maximum column widths from the format and the cache."
16799 (let ((start 0) rtn)
16800 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
16801 (push (cons (match-string 1 s) 1) rtn)
16802 (setq start (match-end 0)))
16803 (mapc (lambda (x)
16804 (setcdr x (apply 'max
16805 (mapcar
16806 (lambda (y)
16807 (length (or (cdr (assoc (car x) (cdr y))) " ")))
16808 cache))))
16809 rtn)
16810 rtn))
16812 (defun org-columns-compute-all ()
16813 "Compute all columns that have operators defined."
16814 (org-unmodified
16815 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
16816 (let ((columns org-columns-current-fmt-compiled) col)
16817 (while (setq col (pop columns))
16818 (when (nth 3 col)
16819 (save-excursion
16820 (org-columns-compute (car col)))))))
16822 (defun org-columns-update (property)
16823 "Recompute PROPERTY, and update the columns display for it."
16824 (org-columns-compute property)
16825 (let (fmt val pos)
16826 (save-excursion
16827 (mapc (lambda (ov)
16828 (when (equal (org-overlay-get ov 'org-columns-key) property)
16829 (setq pos (org-overlay-start ov))
16830 (goto-char pos)
16831 (when (setq val (cdr (assoc property
16832 (get-text-property
16833 (point-at-bol) 'org-summaries))))
16834 (setq fmt (org-overlay-get ov 'org-columns-format))
16835 (org-overlay-put ov 'org-columns-value val)
16836 (org-overlay-put ov 'display (format fmt val)))))
16837 org-columns-overlays))))
16839 (defun org-columns-compute (property)
16840 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16841 (interactive)
16842 (let* ((re (concat "^" outline-regexp))
16843 (lmax 30) ; Does anyone use deeper levels???
16844 (lsum (make-vector lmax 0))
16845 (lflag (make-vector lmax nil))
16846 (level 0)
16847 (ass (assoc property org-columns-current-fmt-compiled))
16848 (format (nth 4 ass))
16849 (printf (nth 5 ass))
16850 (beg org-columns-top-level-marker)
16851 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
16852 (save-excursion
16853 ;; Find the region to compute
16854 (goto-char beg)
16855 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
16856 (goto-char end)
16857 ;; Walk the tree from the back and do the computations
16858 (while (re-search-backward re beg t)
16859 (setq sumpos (match-beginning 0)
16860 last-level level
16861 level (org-outline-level)
16862 val (org-entry-get nil property)
16863 valflag (and val (string-match "\\S-" val)))
16864 (cond
16865 ((< level last-level)
16866 ;; put the sum of lower levels here as a property
16867 (setq sum (aref lsum last-level) ; current sum
16868 flag (aref lflag last-level) ; any valid entries from children?
16869 str (org-column-number-to-string sum format printf)
16870 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
16871 useval (if flag str1 (if valflag val ""))
16872 sum-alist (get-text-property sumpos 'org-summaries))
16873 (if (assoc property sum-alist)
16874 (setcdr (assoc property sum-alist) useval)
16875 (push (cons property useval) sum-alist)
16876 (org-unmodified
16877 (add-text-properties sumpos (1+ sumpos)
16878 (list 'org-summaries sum-alist))))
16879 (when val
16880 (org-entry-put nil property (if flag str val)))
16881 ;; add current to current level accumulator
16882 (when (or flag valflag)
16883 (aset lsum level (+ (aref lsum level)
16884 (if flag sum (org-column-string-to-number
16885 (if flag str val) format))))
16886 (aset lflag level t))
16887 ;; clear accumulators for deeper levels
16888 (loop for l from (1+ level) to (1- lmax) do
16889 (aset lsum l 0)
16890 (aset lflag l nil)))
16891 ((>= level last-level)
16892 ;; add what we have here to the accumulator for this level
16893 (aset lsum level (+ (aref lsum level)
16894 (org-column-string-to-number (or val "0") format)))
16895 (and valflag (aset lflag level t)))
16896 (t (error "This should not happen")))))))
16898 (defun org-columns-redo ()
16899 "Construct the column display again."
16900 (interactive)
16901 (message "Recomputing columns...")
16902 (save-excursion
16903 (if (marker-position org-columns-begin-marker)
16904 (goto-char org-columns-begin-marker))
16905 (org-columns-remove-overlays)
16906 (if (org-mode-p)
16907 (call-interactively 'org-columns)
16908 (call-interactively 'org-agenda-columns)))
16909 (message "Recomputing columns...done"))
16911 (defun org-columns-not-in-agenda ()
16912 (if (eq major-mode 'org-agenda-mode)
16913 (error "This command is only allowed in Org-mode buffers")))
16916 (defun org-string-to-number (s)
16917 "Convert string to number, and interpret hh:mm:ss."
16918 (if (not (string-match ":" s))
16919 (string-to-number s)
16920 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16921 (while l
16922 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16923 sum)))
16925 (defun org-column-number-to-string (n fmt &optional printf)
16926 "Convert a computed column number to a string value, according to FMT."
16927 (cond
16928 ((eq fmt 'add_times)
16929 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16930 (format "%d:%02d" h m)))
16931 ((eq fmt 'checkbox)
16932 (cond ((= n (floor n)) "[X]")
16933 ((> n 1.) "[-]")
16934 (t "[ ]")))
16935 (printf (format printf n))
16936 ((eq fmt 'currency)
16937 (format "%.2f" n))
16938 (t (number-to-string n))))
16940 (defun org-column-string-to-number (s fmt)
16941 "Convert a column value to a number that can be used for column computing."
16942 (cond
16943 ((string-match ":" s)
16944 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16945 (while l
16946 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16947 sum))
16948 ((eq fmt 'checkbox)
16949 (if (equal s "[X]") 1. 0.000001))
16950 (t (string-to-number s))))
16952 (defun org-columns-uncompile-format (cfmt)
16953 "Turn the compiled columns format back into a string representation."
16954 (let ((rtn "") e s prop title op width fmt printf)
16955 (while (setq e (pop cfmt))
16956 (setq prop (car e)
16957 title (nth 1 e)
16958 width (nth 2 e)
16959 op (nth 3 e)
16960 fmt (nth 4 e)
16961 printf (nth 5 e))
16962 (cond
16963 ((eq fmt 'add_times) (setq op ":"))
16964 ((eq fmt 'checkbox) (setq op "X"))
16965 ((eq fmt 'add_numbers) (setq op "+"))
16966 ((eq fmt 'currency) (setq op "$")))
16967 (if (and op printf) (setq op (concat op ";" printf)))
16968 (if (equal title prop) (setq title nil))
16969 (setq s (concat "%" (if width (number-to-string width))
16970 prop
16971 (if title (concat "(" title ")"))
16972 (if op (concat "{" op "}"))))
16973 (setq rtn (concat rtn " " s)))
16974 (org-trim rtn)))
16976 (defun org-columns-compile-format (fmt)
16977 "Turn a column format string into an alist of specifications.
16978 The alist has one entry for each column in the format. The elements of
16979 that list are:
16980 property the property
16981 title the title field for the columns
16982 width the column width in characters, can be nil for automatic
16983 operator the operator if any
16984 format the output format for computed results, derived from operator
16985 printf a printf format for computed values"
16986 (let ((start 0) width prop title op f printf)
16987 (setq org-columns-current-fmt-compiled nil)
16988 (while (string-match
16989 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16990 fmt start)
16991 (setq start (match-end 0)
16992 width (match-string 1 fmt)
16993 prop (match-string 2 fmt)
16994 title (or (match-string 3 fmt) prop)
16995 op (match-string 4 fmt)
16996 f nil
16997 printf nil)
16998 (if width (setq width (string-to-number width)))
16999 (when (and op (string-match ";" op))
17000 (setq printf (substring op (match-end 0))
17001 op (substring op 0 (match-beginning 0))))
17002 (cond
17003 ((equal op "+") (setq f 'add_numbers))
17004 ((equal op "$") (setq f 'currency))
17005 ((equal op ":") (setq f 'add_times))
17006 ((equal op "X") (setq f 'checkbox)))
17007 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17008 (setq org-columns-current-fmt-compiled
17009 (nreverse org-columns-current-fmt-compiled))))
17012 ;;; Dynamic block for Column view
17014 (defun org-columns-capture-view ()
17015 "Get the column view of the current buffer and return it as a list.
17016 The list will contains the title row and all other rows. Each row is
17017 a list of fields."
17018 (save-excursion
17019 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17020 (n (length title)) row tbl)
17021 (goto-char (point-min))
17022 (while (re-search-forward "^\\*+ " nil t)
17023 (when (get-char-property (match-beginning 0) 'org-columns-key)
17024 (setq row nil)
17025 (loop for i from 0 to (1- n) do
17026 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17027 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17029 row))
17030 (setq row (nreverse row))
17031 (push row tbl)))
17032 (append (list title 'hline) (nreverse tbl)))))
17034 (defun org-dblock-write:columnview (params)
17035 "Write the column view table.
17036 PARAMS is a property list of parameters:
17038 :width enforce same column widths with <N> specifiers.
17039 :id the :ID: property of the entry where the columns view
17040 should be built, as a string. When `local', call locally.
17041 When `global' call column view with the cursor at the beginning
17042 of the buffer (usually this means that the whole buffer switches
17043 to column view).
17044 :hlines When t, insert a hline before each item. When a number, insert
17045 a hline before each level <= that number.
17046 :vlines When t, make each column a colgroup to enforce vertical lines."
17047 (let ((pos (move-marker (make-marker) (point)))
17048 (hlines (plist-get params :hlines))
17049 (vlines (plist-get params :vlines))
17050 tbl id idpos nfields tmp)
17051 (save-excursion
17052 (save-restriction
17053 (when (setq id (plist-get params :id))
17054 (cond ((not id) nil)
17055 ((eq id 'global) (goto-char (point-min)))
17056 ((eq id 'local) nil)
17057 ((setq idpos (org-find-entry-with-id id))
17058 (goto-char idpos))
17059 (t (error "Cannot find entry with :ID: %s" id))))
17060 (org-columns)
17061 (setq tbl (org-columns-capture-view))
17062 (setq nfields (length (car tbl)))
17063 (org-columns-quit)))
17064 (goto-char pos)
17065 (move-marker pos nil)
17066 (when tbl
17067 (when (plist-get params :hlines)
17068 (setq tmp nil)
17069 (while tbl
17070 (if (eq (car tbl) 'hline)
17071 (push (pop tbl) tmp)
17072 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17073 (if (and (not (eq (car tmp) 'hline))
17074 (or (eq hlines t)
17075 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17076 (push 'hline tmp)))
17077 (push (pop tbl) tmp)))
17078 (setq tbl (nreverse tmp)))
17079 (when vlines
17080 (setq tbl (mapcar (lambda (x)
17081 (if (eq 'hline x) x (cons "" x)))
17082 tbl))
17083 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17084 (setq pos (point))
17085 (insert (org-listtable-to-string tbl))
17086 (when (plist-get params :width)
17087 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17088 org-columns-current-widths "|")))
17089 (goto-char pos)
17090 (org-table-align))))
17092 (defun org-listtable-to-string (tbl)
17093 "Convert a listtable TBL to a string that contains the Org-mode table.
17094 The table still need to be alligned. The resulting string has no leading
17095 and tailing newline characters."
17096 (mapconcat
17097 (lambda (x)
17098 (cond
17099 ((listp x)
17100 (concat "|" (mapconcat 'identity x "|") "|"))
17101 ((eq x 'hline) "|-|")
17102 (t (error "Garbage in listtable: %s" x))))
17103 tbl "\n"))
17105 (defun org-insert-columns-dblock ()
17106 "Create a dynamic block capturing a column view table."
17107 (interactive)
17108 (let ((defaults '(:name "columnview" :hlines 1))
17109 (id (completing-read
17110 "Capture columns (local, global, entry with :ID: property) [local]: "
17111 (append '(("global") ("local"))
17112 (mapcar 'list (org-property-values "ID"))))))
17113 (if (equal id "") (setq id 'local))
17114 (if (equal id "global") (setq id 'global))
17115 (setq defaults (append defaults (list :id id)))
17116 (org-create-dblock defaults)
17117 (org-update-dblock)))
17119 ;;;; Timestamps
17121 (defvar org-last-changed-timestamp nil)
17122 (defvar org-time-was-given) ; dynamically scoped parameter
17123 (defvar org-end-time-was-given) ; dynamically scoped parameter
17124 (defvar org-ts-what) ; dynamically scoped parameter
17126 (defun org-time-stamp (arg)
17127 "Prompt for a date/time and insert a time stamp.
17128 If the user specifies a time like HH:MM, or if this command is called
17129 with a prefix argument, the time stamp will contain date and time.
17130 Otherwise, only the date will be included. All parts of a date not
17131 specified by the user will be filled in from the current date/time.
17132 So if you press just return without typing anything, the time stamp
17133 will represent the current date/time. If there is already a timestamp
17134 at the cursor, it will be modified."
17135 (interactive "P")
17136 (let* ((ts nil)
17137 (default-time
17138 ;; Default time is either today, or, when entering a range,
17139 ;; the range start.
17140 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17141 (save-excursion
17142 (re-search-backward
17143 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17144 (- (point) 20) t)))
17145 (apply 'encode-time (org-parse-time-string (match-string 1)))
17146 (current-time)))
17147 (default-input (and ts (org-get-compact-tod ts)))
17148 org-time-was-given org-end-time-was-given time)
17149 (cond
17150 ((and (org-at-timestamp-p)
17151 (eq last-command 'org-time-stamp)
17152 (eq this-command 'org-time-stamp))
17153 (insert "--")
17154 (setq time (let ((this-command this-command))
17155 (org-read-date arg 'totime nil nil default-time default-input)))
17156 (org-insert-time-stamp time (or org-time-was-given arg)))
17157 ((org-at-timestamp-p)
17158 (setq time (let ((this-command this-command))
17159 (org-read-date arg 'totime nil nil default-time default-input)))
17160 (when (org-at-timestamp-p) ; just to get the match data
17161 (replace-match "")
17162 (setq org-last-changed-timestamp
17163 (org-insert-time-stamp
17164 time (or org-time-was-given arg)
17165 nil nil nil (list org-end-time-was-given))))
17166 (message "Timestamp updated"))
17168 (setq time (let ((this-command this-command))
17169 (org-read-date arg 'totime nil nil default-time default-input)))
17170 (org-insert-time-stamp time (or org-time-was-given arg)
17171 nil nil nil (list org-end-time-was-given))))))
17173 ;; FIXME: can we use this for something else????
17174 ;; like computing time differences?????
17175 (defun org-get-compact-tod (s)
17176 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17177 (let* ((t1 (match-string 1 s))
17178 (h1 (string-to-number (match-string 2 s)))
17179 (m1 (string-to-number (match-string 3 s)))
17180 (t2 (and (match-end 4) (match-string 5 s)))
17181 (h2 (and t2 (string-to-number (match-string 6 s))))
17182 (m2 (and t2 (string-to-number (match-string 7 s))))
17183 dh dm)
17184 (if (not t2)
17186 (setq dh (- h2 h1) dm (- m2 m1))
17187 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17188 (concat t1 "+" (number-to-string dh)
17189 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17191 (defun org-time-stamp-inactive (&optional arg)
17192 "Insert an inactive time stamp.
17193 An inactive time stamp is enclosed in square brackets instead of angle
17194 brackets. It is inactive in the sense that it does not trigger agenda entries,
17195 does not link to the calendar and cannot be changed with the S-cursor keys.
17196 So these are more for recording a certain time/date."
17197 (interactive "P")
17198 (let (org-time-was-given org-end-time-was-given time)
17199 (setq time (org-read-date arg 'totime))
17200 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17201 nil nil (list org-end-time-was-given))))
17203 (defvar org-date-ovl (org-make-overlay 1 1))
17204 (org-overlay-put org-date-ovl 'face 'org-warning)
17205 (org-detach-overlay org-date-ovl)
17207 (defvar org-ans1) ; dynamically scoped parameter
17208 (defvar org-ans2) ; dynamically scoped parameter
17210 (defvar org-plain-time-of-day-regexp) ; defined below
17212 (defvar org-read-date-overlay nil)
17213 (defvar org-dcst nil) ; dynamically scoped
17215 (defun org-read-date (&optional with-time to-time from-string prompt
17216 default-time default-input)
17217 "Read a date, possibly a time, and make things smooth for the user.
17218 The prompt will suggest to enter an ISO date, but you can also enter anything
17219 which will at least partially be understood by `parse-time-string'.
17220 Unrecognized parts of the date will default to the current day, month, year,
17221 hour and minute. If this command is called to replace a timestamp at point,
17222 of to enter the second timestamp of a range, the default time is taken from the
17223 existing stamp. For example,
17224 3-2-5 --> 2003-02-05
17225 feb 15 --> currentyear-02-15
17226 sep 12 9 --> 2009-09-12
17227 12:45 --> today 12:45
17228 22 sept 0:34 --> currentyear-09-22 0:34
17229 12 --> currentyear-currentmonth-12
17230 Fri --> nearest Friday (today or later)
17231 etc.
17233 Furthermore you can specify a relative date by giving, as the *first* thing
17234 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17235 change in days weeks, months, years.
17236 With a single plus or minus, the date is relative to today. With a double
17237 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17238 +4d --> four days from today
17239 +4 --> same as above
17240 +2w --> two weeks from today
17241 ++5 --> five days from default date
17243 The function understands only English month and weekday abbreviations,
17244 but this can be configured with the variables `parse-time-months' and
17245 `parse-time-weekdays'.
17247 While prompting, a calendar is popped up - you can also select the
17248 date with the mouse (button 1). The calendar shows a period of three
17249 months. To scroll it to other months, use the keys `>' and `<'.
17250 If you don't like the calendar, turn it off with
17251 \(setq org-read-date-popup-calendar nil)
17253 With optional argument TO-TIME, the date will immediately be converted
17254 to an internal time.
17255 With an optional argument WITH-TIME, the prompt will suggest to also
17256 insert a time. Note that when WITH-TIME is not set, you can still
17257 enter a time, and this function will inform the calling routine about
17258 this change. The calling routine may then choose to change the format
17259 used to insert the time stamp into the buffer to include the time.
17260 With optional argument FROM-STRING, read from this string instead from
17261 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17262 the time/date that is used for everything that is not specified by the
17263 user."
17264 (require 'parse-time)
17265 (let* ((org-time-stamp-rounding-minutes
17266 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17267 (org-dcst org-display-custom-times)
17268 (ct (org-current-time))
17269 (def (or default-time ct))
17270 (defdecode (decode-time def))
17271 (dummy (progn
17272 (when (< (nth 2 defdecode) org-extend-today-until)
17273 (setcar (nthcdr 2 defdecode) -1)
17274 (setcar (nthcdr 1 defdecode) 59)
17275 (setq def (apply 'encode-time defdecode)
17276 defdecode (decode-time def)))))
17277 (calendar-move-hook nil)
17278 (view-diary-entries-initially nil)
17279 (view-calendar-holidays-initially nil)
17280 (timestr (format-time-string
17281 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17282 (prompt (concat (if prompt (concat prompt " ") "")
17283 (format "Date+time [%s]: " timestr)))
17284 ans (org-ans0 "") org-ans1 org-ans2 final)
17286 (cond
17287 (from-string (setq ans from-string))
17288 (org-read-date-popup-calendar
17289 (save-excursion
17290 (save-window-excursion
17291 (calendar)
17292 (calendar-forward-day (- (time-to-days def)
17293 (calendar-absolute-from-gregorian
17294 (calendar-current-date))))
17295 (org-eval-in-calendar nil t)
17296 (let* ((old-map (current-local-map))
17297 (map (copy-keymap calendar-mode-map))
17298 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17299 (org-defkey map (kbd "RET") 'org-calendar-select)
17300 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17301 'org-calendar-select-mouse)
17302 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17303 'org-calendar-select-mouse)
17304 (org-defkey minibuffer-local-map [(meta shift left)]
17305 (lambda () (interactive)
17306 (org-eval-in-calendar '(calendar-backward-month 1))))
17307 (org-defkey minibuffer-local-map [(meta shift right)]
17308 (lambda () (interactive)
17309 (org-eval-in-calendar '(calendar-forward-month 1))))
17310 (org-defkey minibuffer-local-map [(meta shift up)]
17311 (lambda () (interactive)
17312 (org-eval-in-calendar '(calendar-backward-year 1))))
17313 (org-defkey minibuffer-local-map [(meta shift down)]
17314 (lambda () (interactive)
17315 (org-eval-in-calendar '(calendar-forward-year 1))))
17316 (org-defkey minibuffer-local-map [(shift up)]
17317 (lambda () (interactive)
17318 (org-eval-in-calendar '(calendar-backward-week 1))))
17319 (org-defkey minibuffer-local-map [(shift down)]
17320 (lambda () (interactive)
17321 (org-eval-in-calendar '(calendar-forward-week 1))))
17322 (org-defkey minibuffer-local-map [(shift left)]
17323 (lambda () (interactive)
17324 (org-eval-in-calendar '(calendar-backward-day 1))))
17325 (org-defkey minibuffer-local-map [(shift right)]
17326 (lambda () (interactive)
17327 (org-eval-in-calendar '(calendar-forward-day 1))))
17328 (org-defkey minibuffer-local-map ">"
17329 (lambda () (interactive)
17330 (org-eval-in-calendar '(scroll-calendar-left 1))))
17331 (org-defkey minibuffer-local-map "<"
17332 (lambda () (interactive)
17333 (org-eval-in-calendar '(scroll-calendar-right 1))))
17334 (unwind-protect
17335 (progn
17336 (use-local-map map)
17337 (add-hook 'post-command-hook 'org-read-date-display)
17338 (setq org-ans0 (read-string prompt default-input nil nil))
17339 ;; org-ans0: from prompt
17340 ;; org-ans1: from mouse click
17341 ;; org-ans2: from calendar motion
17342 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17343 (remove-hook 'post-command-hook 'org-read-date-display)
17344 (use-local-map old-map)
17345 (when org-read-date-overlay
17346 (org-delete-overlay org-read-date-overlay)
17347 (setq org-read-date-overlay nil)))))))
17349 (t ; Naked prompt only
17350 (unwind-protect
17351 (setq ans (read-string prompt default-input nil timestr))
17352 (when org-read-date-overlay
17353 (org-delete-overlay org-read-date-overlay)
17354 (setq org-read-date-overlay nil)))))
17356 (setq final (org-read-date-analyze ans def defdecode))
17358 (if to-time
17359 (apply 'encode-time final)
17360 (if (and (boundp 'org-time-was-given) org-time-was-given)
17361 (format "%04d-%02d-%02d %02d:%02d"
17362 (nth 5 final) (nth 4 final) (nth 3 final)
17363 (nth 2 final) (nth 1 final))
17364 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17365 (defvar def)
17366 (defvar defdecode)
17367 (defvar with-time)
17368 (defun org-read-date-display ()
17369 "Display the currrent date prompt interpretation in the minibuffer."
17370 (when org-read-date-display-live
17371 (when org-read-date-overlay
17372 (org-delete-overlay org-read-date-overlay))
17373 (let ((p (point)))
17374 (end-of-line 1)
17375 (while (not (equal (buffer-substring
17376 (max (point-min) (- (point) 4)) (point))
17377 " "))
17378 (insert " "))
17379 (goto-char p))
17380 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17381 " " (or org-ans1 org-ans2)))
17382 (org-end-time-was-given nil)
17383 (f (org-read-date-analyze ans def defdecode))
17384 (fmts (if org-dcst
17385 org-time-stamp-custom-formats
17386 org-time-stamp-formats))
17387 (fmt (if (or with-time
17388 (and (boundp 'org-time-was-given) org-time-was-given))
17389 (cdr fmts)
17390 (car fmts)))
17391 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17392 (when (and org-end-time-was-given
17393 (string-match org-plain-time-of-day-regexp txt))
17394 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17395 org-end-time-was-given
17396 (substring txt (match-end 0)))))
17397 (setq org-read-date-overlay
17398 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17399 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17401 (defun org-read-date-analyze (ans def defdecode)
17402 "Analyze the combined answer of the date prompt."
17403 ;; FIXME: cleanup and comment
17404 (let (delta deltan deltaw deltadef year month day
17405 hour minute second wday pm h2 m2 tl wday1)
17407 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17408 (setq ans (replace-match "" t t ans)
17409 deltan (car delta)
17410 deltaw (nth 1 delta)
17411 deltadef (nth 2 delta)))
17413 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17414 (when (string-match
17415 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17416 (setq year (if (match-end 2)
17417 (string-to-number (match-string 2 ans))
17418 (string-to-number (format-time-string "%Y")))
17419 month (string-to-number (match-string 3 ans))
17420 day (string-to-number (match-string 4 ans)))
17421 (if (< year 100) (setq year (+ 2000 year)))
17422 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17423 t nil ans)))
17424 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17425 ;; If there is a time with am/pm, and *no* time without it, we convert
17426 ;; so that matching will be successful.
17427 (loop for i from 1 to 2 do ; twice, for end time as well
17428 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17429 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17430 (setq hour (string-to-number (match-string 1 ans))
17431 minute (if (match-end 3)
17432 (string-to-number (match-string 3 ans))
17434 pm (equal ?p
17435 (string-to-char (downcase (match-string 4 ans)))))
17436 (if (and (= hour 12) (not pm))
17437 (setq hour 0)
17438 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17439 (setq ans (replace-match (format "%02d:%02d" hour minute)
17440 t t ans))))
17442 ;; Check if a time range is given as a duration
17443 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17444 (setq hour (string-to-number (match-string 1 ans))
17445 h2 (+ hour (string-to-number (match-string 3 ans)))
17446 minute (string-to-number (match-string 2 ans))
17447 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17448 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17449 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17451 ;; Check if there is a time range
17452 (when (boundp 'org-end-time-was-given)
17453 (setq org-time-was-given nil)
17454 (when (and (string-match org-plain-time-of-day-regexp ans)
17455 (match-end 8))
17456 (setq org-end-time-was-given (match-string 8 ans))
17457 (setq ans (concat (substring ans 0 (match-beginning 7))
17458 (substring ans (match-end 7))))))
17460 (setq tl (parse-time-string ans)
17461 day (or (nth 3 tl) (nth 3 defdecode))
17462 month (or (nth 4 tl)
17463 (if (and org-read-date-prefer-future
17464 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17465 (1+ (nth 4 defdecode))
17466 (nth 4 defdecode)))
17467 year (or (nth 5 tl)
17468 (if (and org-read-date-prefer-future
17469 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17470 (1+ (nth 5 defdecode))
17471 (nth 5 defdecode)))
17472 hour (or (nth 2 tl) (nth 2 defdecode))
17473 minute (or (nth 1 tl) (nth 1 defdecode))
17474 second (or (nth 0 tl) 0)
17475 wday (nth 6 tl))
17476 (when deltan
17477 (unless deltadef
17478 (let ((now (decode-time (current-time))))
17479 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17480 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17481 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17482 ((equal deltaw "m") (setq month (+ month deltan)))
17483 ((equal deltaw "y") (setq year (+ year deltan)))))
17484 (when (and wday (not (nth 3 tl)))
17485 ;; Weekday was given, but no day, so pick that day in the week
17486 ;; on or after the derived date.
17487 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17488 (unless (equal wday wday1)
17489 (setq day (+ day (% (- wday wday1 -7) 7)))))
17490 (if (and (boundp 'org-time-was-given)
17491 (nth 2 tl))
17492 (setq org-time-was-given t))
17493 (if (< year 100) (setq year (+ 2000 year)))
17494 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17495 (list second minute hour day month year)))
17497 (defvar parse-time-weekdays)
17499 (defun org-read-date-get-relative (s today default)
17500 "Check string S for special relative date string.
17501 TODAY and DEFAULT are internal times, for today and for a default.
17502 Return shift list (N what def-flag)
17503 WHAT is \"d\", \"w\", \"m\", or \"y\" for day. week, month, year.
17504 N is the number if WHATs to shift
17505 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17506 the DEFAULT date rather than TODAY."
17507 (when (string-match
17508 (concat
17509 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17510 "\\([0-9]+\\)?"
17511 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17512 "\\([ \t]\\|$\\)") s)
17513 (let* ((dir (if (match-end 1)
17514 (string-to-char (substring (match-string 1 s) -1))
17515 ?+))
17516 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17517 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17518 (what (if (match-end 3) (match-string 3 s) "d"))
17519 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17520 (date (if rel default today))
17521 (wday (nth 6 (decode-time date)))
17522 delta)
17523 (if wday1
17524 (progn
17525 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17526 (if (= dir ?-) (setq delta (- delta 7)))
17527 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17528 (list delta "d" rel))
17529 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17531 (defun org-eval-in-calendar (form &optional keepdate)
17532 "Eval FORM in the calendar window and return to current window.
17533 Also, store the cursor date in variable org-ans2."
17534 (let ((sw (selected-window)))
17535 (select-window (get-buffer-window "*Calendar*"))
17536 (eval form)
17537 (when (and (not keepdate) (calendar-cursor-to-date))
17538 (let* ((date (calendar-cursor-to-date))
17539 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17540 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17541 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17542 (select-window sw)))
17544 ; ;; Update the prompt to show new default date
17545 ; (save-excursion
17546 ; (goto-char (point-min))
17547 ; (when (and org-ans2
17548 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17549 ; (get-text-property (match-end 0) 'field))
17550 ; (let ((inhibit-read-only t))
17551 ; (replace-match (concat "[" org-ans2 "]") t t)
17552 ; (add-text-properties (point-min) (1+ (match-end 0))
17553 ; (text-properties-at (1+ (point-min)))))))))
17555 (defun org-calendar-select ()
17556 "Return to `org-read-date' with the date currently selected.
17557 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17558 (interactive)
17559 (when (calendar-cursor-to-date)
17560 (let* ((date (calendar-cursor-to-date))
17561 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17562 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17563 (if (active-minibuffer-window) (exit-minibuffer))))
17565 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17566 "Insert a date stamp for the date given by the internal TIME.
17567 WITH-HM means, use the stamp format that includes the time of the day.
17568 INACTIVE means use square brackets instead of angular ones, so that the
17569 stamp will not contribute to the agenda.
17570 PRE and POST are optional strings to be inserted before and after the
17571 stamp.
17572 The command returns the inserted time stamp."
17573 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17574 stamp)
17575 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17576 (insert-before-markers (or pre ""))
17577 (insert-before-markers (setq stamp (format-time-string fmt time)))
17578 (when (listp extra)
17579 (setq extra (car extra))
17580 (if (and (stringp extra)
17581 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17582 (setq extra (format "-%02d:%02d"
17583 (string-to-number (match-string 1 extra))
17584 (string-to-number (match-string 2 extra))))
17585 (setq extra nil)))
17586 (when extra
17587 (backward-char 1)
17588 (insert-before-markers extra)
17589 (forward-char 1))
17590 (insert-before-markers (or post ""))
17591 stamp))
17593 (defun org-toggle-time-stamp-overlays ()
17594 "Toggle the use of custom time stamp formats."
17595 (interactive)
17596 (setq org-display-custom-times (not org-display-custom-times))
17597 (unless org-display-custom-times
17598 (let ((p (point-min)) (bmp (buffer-modified-p)))
17599 (while (setq p (next-single-property-change p 'display))
17600 (if (and (get-text-property p 'display)
17601 (eq (get-text-property p 'face) 'org-date))
17602 (remove-text-properties
17603 p (setq p (next-single-property-change p 'display))
17604 '(display t))))
17605 (set-buffer-modified-p bmp)))
17606 (if (featurep 'xemacs)
17607 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17608 (org-restart-font-lock)
17609 (setq org-table-may-need-update t)
17610 (if org-display-custom-times
17611 (message "Time stamps are overlayed with custom format")
17612 (message "Time stamp overlays removed")))
17614 (defun org-display-custom-time (beg end)
17615 "Overlay modified time stamp format over timestamp between BED and END."
17616 (let* ((ts (buffer-substring beg end))
17617 t1 w1 with-hm tf time str w2 (off 0))
17618 (save-match-data
17619 (setq t1 (org-parse-time-string ts t))
17620 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17621 (setq off (- (match-end 0) (match-beginning 0)))))
17622 (setq end (- end off))
17623 (setq w1 (- end beg)
17624 with-hm (and (nth 1 t1) (nth 2 t1))
17625 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17626 time (org-fix-decoded-time t1)
17627 str (org-add-props
17628 (format-time-string
17629 (substring tf 1 -1) (apply 'encode-time time))
17630 nil 'mouse-face 'highlight)
17631 w2 (length str))
17632 (if (not (= w2 w1))
17633 (add-text-properties (1+ beg) (+ 2 beg)
17634 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17635 (if (featurep 'xemacs)
17636 (progn
17637 (put-text-property beg end 'invisible t)
17638 (put-text-property beg end 'end-glyph (make-glyph str)))
17639 (put-text-property beg end 'display str))))
17641 (defun org-translate-time (string)
17642 "Translate all timestamps in STRING to custom format.
17643 But do this only if the variable `org-display-custom-times' is set."
17644 (when org-display-custom-times
17645 (save-match-data
17646 (let* ((start 0)
17647 (re org-ts-regexp-both)
17648 t1 with-hm inactive tf time str beg end)
17649 (while (setq start (string-match re string start))
17650 (setq beg (match-beginning 0)
17651 end (match-end 0)
17652 t1 (save-match-data
17653 (org-parse-time-string (substring string beg end) t))
17654 with-hm (and (nth 1 t1) (nth 2 t1))
17655 inactive (equal (substring string beg (1+ beg)) "[")
17656 tf (funcall (if with-hm 'cdr 'car)
17657 org-time-stamp-custom-formats)
17658 time (org-fix-decoded-time t1)
17659 str (format-time-string
17660 (concat
17661 (if inactive "[" "<") (substring tf 1 -1)
17662 (if inactive "]" ">"))
17663 (apply 'encode-time time))
17664 string (replace-match str t t string)
17665 start (+ start (length str)))))))
17666 string)
17668 (defun org-fix-decoded-time (time)
17669 "Set 0 instead of nil for the first 6 elements of time.
17670 Don't touch the rest."
17671 (let ((n 0))
17672 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17674 (defun org-days-to-time (timestamp-string)
17675 "Difference between TIMESTAMP-STRING and now in days."
17676 (- (time-to-days (org-time-string-to-time timestamp-string))
17677 (time-to-days (current-time))))
17679 (defun org-deadline-close (timestamp-string &optional ndays)
17680 "Is the time in TIMESTAMP-STRING close to the current date?"
17681 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17682 (and (< (org-days-to-time timestamp-string) ndays)
17683 (not (org-entry-is-done-p))))
17685 (defun org-get-wdays (ts)
17686 "Get the deadline lead time appropriate for timestring TS."
17687 (cond
17688 ((<= org-deadline-warning-days 0)
17689 ;; 0 or negative, enforce this value no matter what
17690 (- org-deadline-warning-days))
17691 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17692 ;; lead time is specified.
17693 (floor (* (string-to-number (match-string 1 ts))
17694 (cdr (assoc (match-string 2 ts)
17695 '(("d" . 1) ("w" . 7)
17696 ("m" . 30.4) ("y" . 365.25)))))))
17697 ;; go for the default.
17698 (t org-deadline-warning-days)))
17700 (defun org-calendar-select-mouse (ev)
17701 "Return to `org-read-date' with the date currently selected.
17702 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17703 (interactive "e")
17704 (mouse-set-point ev)
17705 (when (calendar-cursor-to-date)
17706 (let* ((date (calendar-cursor-to-date))
17707 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17708 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17709 (if (active-minibuffer-window) (exit-minibuffer))))
17711 (defun org-check-deadlines (ndays)
17712 "Check if there are any deadlines due or past due.
17713 A deadline is considered due if it happens within `org-deadline-warning-days'
17714 days from today's date. If the deadline appears in an entry marked DONE,
17715 it is not shown. The prefix arg NDAYS can be used to test that many
17716 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17717 (interactive "P")
17718 (let* ((org-warn-days
17719 (cond
17720 ((equal ndays '(4)) 100000)
17721 (ndays (prefix-numeric-value ndays))
17722 (t (abs org-deadline-warning-days))))
17723 (case-fold-search nil)
17724 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17725 (callback
17726 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17728 (message "%d deadlines past-due or due within %d days"
17729 (org-occur regexp nil callback)
17730 org-warn-days)))
17732 (defun org-check-before-date (date)
17733 "Check if there are deadlines or scheduled entries before DATE."
17734 (interactive (list (org-read-date)))
17735 (let ((case-fold-search nil)
17736 (regexp (concat "\\<\\(" org-deadline-string
17737 "\\|" org-scheduled-string
17738 "\\) *<\\([^>]+\\)>"))
17739 (callback
17740 (lambda () (time-less-p
17741 (org-time-string-to-time (match-string 2))
17742 (org-time-string-to-time date)))))
17743 (message "%d entries before %s"
17744 (org-occur regexp nil callback) date)))
17746 (defun org-evaluate-time-range (&optional to-buffer)
17747 "Evaluate a time range by computing the difference between start and end.
17748 Normally the result is just printed in the echo area, but with prefix arg
17749 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17750 If the time range is actually in a table, the result is inserted into the
17751 next column.
17752 For time difference computation, a year is assumed to be exactly 365
17753 days in order to avoid rounding problems."
17754 (interactive "P")
17756 (org-clock-update-time-maybe)
17757 (save-excursion
17758 (unless (org-at-date-range-p t)
17759 (goto-char (point-at-bol))
17760 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17761 (if (not (org-at-date-range-p t))
17762 (error "Not at a time-stamp range, and none found in current line")))
17763 (let* ((ts1 (match-string 1))
17764 (ts2 (match-string 2))
17765 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17766 (match-end (match-end 0))
17767 (time1 (org-time-string-to-time ts1))
17768 (time2 (org-time-string-to-time ts2))
17769 (t1 (time-to-seconds time1))
17770 (t2 (time-to-seconds time2))
17771 (diff (abs (- t2 t1)))
17772 (negative (< (- t2 t1) 0))
17773 ;; (ys (floor (* 365 24 60 60)))
17774 (ds (* 24 60 60))
17775 (hs (* 60 60))
17776 (fy "%dy %dd %02d:%02d")
17777 (fy1 "%dy %dd")
17778 (fd "%dd %02d:%02d")
17779 (fd1 "%dd")
17780 (fh "%02d:%02d")
17781 y d h m align)
17782 (if havetime
17783 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17785 d (floor (/ diff ds)) diff (mod diff ds)
17786 h (floor (/ diff hs)) diff (mod diff hs)
17787 m (floor (/ diff 60)))
17788 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17790 d (floor (+ (/ diff ds) 0.5))
17791 h 0 m 0))
17792 (if (not to-buffer)
17793 (message "%s" (org-make-tdiff-string y d h m))
17794 (if (org-at-table-p)
17795 (progn
17796 (goto-char match-end)
17797 (setq align t)
17798 (and (looking-at " *|") (goto-char (match-end 0))))
17799 (goto-char match-end))
17800 (if (looking-at
17801 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17802 (replace-match ""))
17803 (if negative (insert " -"))
17804 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17805 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17806 (insert " " (format fh h m))))
17807 (if align (org-table-align))
17808 (message "Time difference inserted")))))
17810 (defun org-make-tdiff-string (y d h m)
17811 (let ((fmt "")
17812 (l nil))
17813 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17814 l (push y l)))
17815 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17816 l (push d l)))
17817 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17818 l (push h l)))
17819 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17820 l (push m l)))
17821 (apply 'format fmt (nreverse l))))
17823 (defun org-time-string-to-time (s)
17824 (apply 'encode-time (org-parse-time-string s)))
17826 (defun org-time-string-to-absolute (s &optional daynr)
17827 "Convert a time stamp to an absolute day number.
17828 If there is a specifyer for a cyclic time stamp, get the closest date to
17829 DAYNR."
17830 (cond
17831 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17832 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17833 daynr
17834 (+ daynr 1000)))
17835 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
17836 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17837 (time-to-days (current-time))) (match-string 0 s)))
17838 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
17840 (defun org-time-from-absolute (d)
17841 "Return the time corresponding to date D.
17842 D may be an absolute day number, or a calendar-type list (month day year)."
17843 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17844 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17846 (defun org-calendar-holiday ()
17847 "List of holidays, for Diary display in Org-mode."
17848 (require 'holidays)
17849 (let ((hl (funcall
17850 (if (fboundp 'calendar-check-holidays)
17851 'calendar-check-holidays 'check-calendar-holidays) date)))
17852 (if hl (mapconcat 'identity hl "; "))))
17854 (defun org-diary-sexp-entry (sexp entry date)
17855 "Process a SEXP diary ENTRY for DATE."
17856 (require 'diary-lib)
17857 (let ((result (if calendar-debug-sexp
17858 (let ((stack-trace-on-error t))
17859 (eval (car (read-from-string sexp))))
17860 (condition-case nil
17861 (eval (car (read-from-string sexp)))
17862 (error
17863 (beep)
17864 (message "Bad sexp at line %d in %s: %s"
17865 (org-current-line)
17866 (buffer-file-name) sexp)
17867 (sleep-for 2))))))
17868 (cond ((stringp result) result)
17869 ((and (consp result)
17870 (stringp (cdr result))) (cdr result))
17871 (result entry)
17872 (t nil))))
17874 (defun org-diary-to-ical-string (frombuf)
17875 "Get iCalendar entries from diary entries in buffer FROMBUF.
17876 This uses the icalendar.el library."
17877 (let* ((tmpdir (if (featurep 'xemacs)
17878 (temp-directory)
17879 temporary-file-directory))
17880 (tmpfile (make-temp-name
17881 (expand-file-name "orgics" tmpdir)))
17882 buf rtn b e)
17883 (save-excursion
17884 (set-buffer frombuf)
17885 (icalendar-export-region (point-min) (point-max) tmpfile)
17886 (setq buf (find-buffer-visiting tmpfile))
17887 (set-buffer buf)
17888 (goto-char (point-min))
17889 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17890 (setq b (match-beginning 0)))
17891 (goto-char (point-max))
17892 (if (re-search-backward "^END:VEVENT" nil t)
17893 (setq e (match-end 0)))
17894 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17895 (kill-buffer buf)
17896 (kill-buffer frombuf)
17897 (delete-file tmpfile)
17898 rtn))
17900 (defun org-closest-date (start current change)
17901 "Find the date closest to CURRENT that is consistent with START and CHANGE."
17902 ;; Make the proper lists from the dates
17903 (catch 'exit
17904 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
17905 dn dw sday cday n1 n2
17906 d m y y1 y2 date1 date2 nmonths nm ny m2)
17908 (setq start (org-date-to-gregorian start)
17909 current (org-date-to-gregorian
17910 (if org-agenda-repeating-timestamp-show-all
17911 current
17912 (time-to-days (current-time))))
17913 sday (calendar-absolute-from-gregorian start)
17914 cday (calendar-absolute-from-gregorian current))
17916 (if (<= cday sday) (throw 'exit sday))
17918 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
17919 (setq dn (string-to-number (match-string 1 change))
17920 dw (cdr (assoc (match-string 2 change) a1)))
17921 (error "Invalid change specifyer: %s" change))
17922 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17923 (cond
17924 ((eq dw 'day)
17925 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17926 n2 (+ n1 dn)))
17927 ((eq dw 'year)
17928 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17929 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17930 (setq date1 (list m d y1)
17931 n1 (calendar-absolute-from-gregorian date1)
17932 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17933 n2 (calendar-absolute-from-gregorian date2)))
17934 ((eq dw 'month)
17935 ;; approx number of month between the tow dates
17936 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17937 ;; How often does dn fit in there?
17938 (setq d (nth 1 start) m (car start) y (nth 2 start)
17939 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17940 m (+ m nm)
17941 ny (floor (/ m 12))
17942 y (+ y ny)
17943 m (- m (* ny 12)))
17944 (while (> m 12) (setq m (- m 12) y (1+ y)))
17945 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17946 (setq m2 (+ m dn) y2 y)
17947 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17948 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17949 (while (< n2 cday)
17950 (setq n1 n2 m m2 y y2)
17951 (setq m2 (+ m dn) y2 y)
17952 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17953 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17955 (if org-agenda-repeating-timestamp-show-all
17956 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
17957 (if (= cday n1) n1 n2)))))
17959 (defun org-date-to-gregorian (date)
17960 "Turn any specification of DATE into a gregorian date for the calendar."
17961 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17962 ((and (listp date) (= (length date) 3)) date)
17963 ((stringp date)
17964 (setq date (org-parse-time-string date))
17965 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17966 ((listp date)
17967 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17969 (defun org-parse-time-string (s &optional nodefault)
17970 "Parse the standard Org-mode time string.
17971 This should be a lot faster than the normal `parse-time-string'.
17972 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17973 hour and minute fields will be nil if not given."
17974 (if (string-match org-ts-regexp0 s)
17975 (list 0
17976 (if (or (match-beginning 8) (not nodefault))
17977 (string-to-number (or (match-string 8 s) "0")))
17978 (if (or (match-beginning 7) (not nodefault))
17979 (string-to-number (or (match-string 7 s) "0")))
17980 (string-to-number (match-string 4 s))
17981 (string-to-number (match-string 3 s))
17982 (string-to-number (match-string 2 s))
17983 nil nil nil)
17984 (make-list 9 0)))
17986 (defun org-timestamp-up (&optional arg)
17987 "Increase the date item at the cursor by one.
17988 If the cursor is on the year, change the year. If it is on the month or
17989 the day, change that.
17990 With prefix ARG, change by that many units."
17991 (interactive "p")
17992 (org-timestamp-change (prefix-numeric-value arg)))
17994 (defun org-timestamp-down (&optional arg)
17995 "Decrease the date item at the cursor by one.
17996 If the cursor is on the year, change the year. If it is on the month or
17997 the day, change that.
17998 With prefix ARG, change by that many units."
17999 (interactive "p")
18000 (org-timestamp-change (- (prefix-numeric-value arg))))
18002 (defun org-timestamp-up-day (&optional arg)
18003 "Increase the date in the time stamp by one day.
18004 With prefix ARG, change that many days."
18005 (interactive "p")
18006 (if (and (not (org-at-timestamp-p t))
18007 (org-on-heading-p))
18008 (org-todo 'up)
18009 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18011 (defun org-timestamp-down-day (&optional arg)
18012 "Decrease the date in the time stamp by one day.
18013 With prefix ARG, change that many days."
18014 (interactive "p")
18015 (if (and (not (org-at-timestamp-p t))
18016 (org-on-heading-p))
18017 (org-todo 'down)
18018 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18020 (defsubst org-pos-in-match-range (pos n)
18021 (and (match-beginning n)
18022 (<= (match-beginning n) pos)
18023 (>= (match-end n) pos)))
18025 (defun org-at-timestamp-p (&optional inactive-ok)
18026 "Determine if the cursor is in or at a timestamp."
18027 (interactive)
18028 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18029 (pos (point))
18030 (ans (or (looking-at tsr)
18031 (save-excursion
18032 (skip-chars-backward "^[<\n\r\t")
18033 (if (> (point) (point-min)) (backward-char 1))
18034 (and (looking-at tsr)
18035 (> (- (match-end 0) pos) -1))))))
18036 (and ans
18037 (boundp 'org-ts-what)
18038 (setq org-ts-what
18039 (cond
18040 ((= pos (match-beginning 0)) 'bracket)
18041 ((= pos (1- (match-end 0))) 'bracket)
18042 ((org-pos-in-match-range pos 2) 'year)
18043 ((org-pos-in-match-range pos 3) 'month)
18044 ((org-pos-in-match-range pos 7) 'hour)
18045 ((org-pos-in-match-range pos 8) 'minute)
18046 ((or (org-pos-in-match-range pos 4)
18047 (org-pos-in-match-range pos 5)) 'day)
18048 ((and (> pos (or (match-end 8) (match-end 5)))
18049 (< pos (match-end 0)))
18050 (- pos (or (match-end 8) (match-end 5))))
18051 (t 'day))))
18052 ans))
18054 (defun org-toggle-timestamp-type ()
18056 (interactive)
18057 (when (org-at-timestamp-p t)
18058 (save-excursion
18059 (goto-char (match-beginning 0))
18060 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18061 (goto-char (1- (match-end 0)))
18062 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18063 (message "Timestamp is now %sactive"
18064 (if (equal (char-before) ?>) "in" ""))))
18066 (defun org-timestamp-change (n &optional what)
18067 "Change the date in the time stamp at point.
18068 The date will be changed by N times WHAT. WHAT can be `day', `month',
18069 `year', `minute', `second'. If WHAT is not given, the cursor position
18070 in the timestamp determines what will be changed."
18071 (let ((pos (point))
18072 with-hm inactive
18073 org-ts-what
18074 extra
18075 ts time time0)
18076 (if (not (org-at-timestamp-p t))
18077 (error "Not at a timestamp"))
18078 (if (and (not what) (eq org-ts-what 'bracket))
18079 (org-toggle-timestamp-type)
18080 (if (and (not what) (not (eq org-ts-what 'day))
18081 org-display-custom-times
18082 (get-text-property (point) 'display)
18083 (not (get-text-property (1- (point)) 'display)))
18084 (setq org-ts-what 'day))
18085 (setq org-ts-what (or what org-ts-what)
18086 inactive (= (char-after (match-beginning 0)) ?\[)
18087 ts (match-string 0))
18088 (replace-match "")
18089 (if (string-match
18090 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18092 (setq extra (match-string 1 ts)))
18093 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18094 (setq with-hm t))
18095 (setq time0 (org-parse-time-string ts))
18096 (setq time
18097 (encode-time (or (car time0) 0)
18098 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18099 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18100 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18101 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18102 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18103 (nthcdr 6 time0)))
18104 (when (integerp org-ts-what)
18105 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18106 (if (eq what 'calendar)
18107 (let ((cal-date (org-get-date-from-calendar)))
18108 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18109 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18110 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18111 (setcar time0 (or (car time0) 0))
18112 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18113 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18114 (setq time (apply 'encode-time time0))))
18115 (setq org-last-changed-timestamp
18116 (org-insert-time-stamp time with-hm inactive nil nil extra))
18117 (org-clock-update-time-maybe)
18118 (goto-char pos)
18119 ;; Try to recenter the calendar window, if any
18120 (if (and org-calendar-follow-timestamp-change
18121 (get-buffer-window "*Calendar*" t)
18122 (memq org-ts-what '(day month year)))
18123 (org-recenter-calendar (time-to-days time))))))
18125 ;; FIXME: does not yet work for lead times
18126 (defun org-modify-ts-extra (s pos n)
18127 "Change the different parts of the lead-time and repeat fields in timestamp."
18128 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18129 ng h m new)
18130 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18131 (cond
18132 ((or (org-pos-in-match-range pos 2)
18133 (org-pos-in-match-range pos 3))
18134 (setq m (string-to-number (match-string 3 s))
18135 h (string-to-number (match-string 2 s)))
18136 (if (org-pos-in-match-range pos 2)
18137 (setq h (+ h n))
18138 (setq m (+ m n)))
18139 (if (< m 0) (setq m (+ m 60) h (1- h)))
18140 (if (> m 59) (setq m (- m 60) h (1+ h)))
18141 (setq h (min 24 (max 0 h)))
18142 (setq ng 1 new (format "-%02d:%02d" h m)))
18143 ((org-pos-in-match-range pos 6)
18144 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18145 ((org-pos-in-match-range pos 5)
18146 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18148 (when ng
18149 (setq s (concat
18150 (substring s 0 (match-beginning ng))
18152 (substring s (match-end ng))))))
18155 (defun org-recenter-calendar (date)
18156 "If the calendar is visible, recenter it to DATE."
18157 (let* ((win (selected-window))
18158 (cwin (get-buffer-window "*Calendar*" t))
18159 (calendar-move-hook nil))
18160 (when cwin
18161 (select-window cwin)
18162 (calendar-goto-date (if (listp date) date
18163 (calendar-gregorian-from-absolute date)))
18164 (select-window win))))
18166 (defun org-goto-calendar (&optional arg)
18167 "Go to the Emacs calendar at the current date.
18168 If there is a time stamp in the current line, go to that date.
18169 A prefix ARG can be used to force the current date."
18170 (interactive "P")
18171 (let ((tsr org-ts-regexp) diff
18172 (calendar-move-hook nil)
18173 (view-calendar-holidays-initially nil)
18174 (view-diary-entries-initially nil))
18175 (if (or (org-at-timestamp-p)
18176 (save-excursion
18177 (beginning-of-line 1)
18178 (looking-at (concat ".*" tsr))))
18179 (let ((d1 (time-to-days (current-time)))
18180 (d2 (time-to-days
18181 (org-time-string-to-time (match-string 1)))))
18182 (setq diff (- d2 d1))))
18183 (calendar)
18184 (calendar-goto-today)
18185 (if (and diff (not arg)) (calendar-forward-day diff))))
18187 (defun org-get-date-from-calendar ()
18188 "Return a list (month day year) of date at point in calendar."
18189 (with-current-buffer "*Calendar*"
18190 (save-match-data
18191 (calendar-cursor-to-date))))
18193 (defun org-date-from-calendar ()
18194 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18195 If there is already a time stamp at the cursor position, update it."
18196 (interactive)
18197 (if (org-at-timestamp-p t)
18198 (org-timestamp-change 0 'calendar)
18199 (let ((cal-date (org-get-date-from-calendar)))
18200 (org-insert-time-stamp
18201 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18203 ;; Make appt aware of appointments from the agenda
18204 ;;;###autoload
18205 (defun org-agenda-to-appt (&optional filter)
18206 "Activate appointments found in `org-agenda-files'.
18207 When prefixed, prompt for a regular expression and use it as a
18208 filter: only add entries if they match this regular expression.
18210 FILTER can be a string. In this case, use this string as a
18211 regular expression to filter results.
18213 FILTER can also be an alist, with the car of each cell being
18214 either 'headline or 'category. For example:
18216 '((headline \"IMPORTANT\")
18217 (category \"Work\"))
18219 will only add headlines containing IMPORTANT or headlines
18220 belonging to the category \"Work\"."
18221 (interactive "P")
18222 (require 'calendar)
18223 (if (equal filter '(4))
18224 (setq filter (read-from-minibuffer "Regexp filter: ")))
18225 (let* ((cnt 0) ; count added events
18226 (org-agenda-new-buffers nil)
18227 (today (org-date-to-gregorian
18228 (time-to-days (current-time))))
18229 (files (org-agenda-files)) entries file)
18230 ;; Get all entries which may contain an appt
18231 (while (setq file (pop files))
18232 (setq entries
18233 (append entries
18234 (org-agenda-get-day-entries
18235 file today
18236 :timestamp :scheduled :deadline))))
18237 (setq entries (delq nil entries))
18238 ;; Map thru entries and find if they pass thru the filter
18239 (mapc
18240 (lambda(x)
18241 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18242 (cat (get-text-property 1 'org-category x))
18243 (tod (get-text-property 1 'time-of-day x))
18244 (ok (or (null filter)
18245 (and (stringp filter) (string-match filter evt))
18246 (and (listp filter)
18247 (or (string-match
18248 (cadr (assoc 'category filter)) cat)
18249 (string-match
18250 (cadr (assoc 'headline filter)) evt))))))
18251 ;; FIXME: Shall we remove text-properties for the appt text?
18252 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18253 (when (and ok tod)
18254 (setq tod (number-to-string tod)
18255 tod (when (string-match
18256 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18257 (concat (match-string 1 tod) ":"
18258 (match-string 2 tod))))
18259 (appt-add tod evt)
18260 (setq cnt (1+ cnt))))) entries)
18261 (org-release-buffers org-agenda-new-buffers)
18262 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18264 ;;; The clock for measuring work time.
18266 (defvar org-mode-line-string "")
18267 (put 'org-mode-line-string 'risky-local-variable t)
18269 (defvar org-mode-line-timer nil)
18270 (defvar org-clock-heading "")
18271 (defvar org-clock-start-time "")
18273 (defun org-update-mode-line ()
18274 (let* ((delta (- (time-to-seconds (current-time))
18275 (time-to-seconds org-clock-start-time)))
18276 (h (floor delta 3600))
18277 (m (floor (- delta (* 3600 h)) 60)))
18278 (setq org-mode-line-string
18279 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18280 'help-echo "Org-mode clock is running"))
18281 (force-mode-line-update)))
18283 (defvar org-clock-marker (make-marker)
18284 "Marker recording the last clock-in.")
18285 (defvar org-clock-mode-line-entry nil
18286 "Information for the modeline about the running clock.")
18288 (defun org-clock-in ()
18289 "Start the clock on the current item.
18290 If necessary, clock-out of the currently active clock."
18291 (interactive)
18292 (org-clock-out t)
18293 (let (ts)
18294 (save-excursion
18295 (org-back-to-heading t)
18296 (when (and org-clock-in-switch-to-state
18297 (not (looking-at (concat outline-regexp "[ \t]*"
18298 org-clock-in-switch-to-state
18299 "\\>"))))
18300 (org-todo org-clock-in-switch-to-state))
18301 (if (and org-clock-heading-function
18302 (functionp org-clock-heading-function))
18303 (setq org-clock-heading (funcall org-clock-heading-function))
18304 (if (looking-at org-complex-heading-regexp)
18305 (setq org-clock-heading (match-string 4))
18306 (setq org-clock-heading "???")))
18307 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18308 (org-clock-find-position)
18310 (insert "\n") (backward-char 1)
18311 (indent-relative)
18312 (insert org-clock-string " ")
18313 (setq org-clock-start-time (current-time))
18314 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18315 (move-marker org-clock-marker (point) (buffer-base-buffer))
18316 (or global-mode-string (setq global-mode-string '("")))
18317 (or (memq 'org-mode-line-string global-mode-string)
18318 (setq global-mode-string
18319 (append global-mode-string '(org-mode-line-string))))
18320 (org-update-mode-line)
18321 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18322 (message "Clock started at %s" ts))))
18324 (defun org-clock-find-position ()
18325 "Find the location where the next clock line should be inserted."
18326 (org-back-to-heading t)
18327 (catch 'exit
18328 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18329 (re (concat "^[ \t]*" org-clock-string))
18330 (cnt 0)
18331 first last)
18332 (goto-char beg)
18333 (when (eobp) (newline) (setq end (max (point) end)))
18334 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18335 ;; we seem to have a CLOCK drawer, so go there.
18336 (beginning-of-line 2)
18337 (throw 'exit t))
18338 ;; Lets count the CLOCK lines
18339 (goto-char beg)
18340 (while (re-search-forward re end t)
18341 (setq first (or first (match-beginning 0))
18342 last (match-beginning 0)
18343 cnt (1+ cnt)))
18344 (when (and (integerp org-clock-into-drawer)
18345 (>= (1+ cnt) org-clock-into-drawer))
18346 ;; Wrap current entries into a new drawer
18347 (goto-char last)
18348 (beginning-of-line 2)
18349 (if (org-at-item-p) (org-end-of-item))
18350 (insert ":END:\n")
18351 (beginning-of-line 0)
18352 (org-indent-line-function)
18353 (goto-char first)
18354 (insert ":CLOCK:\n")
18355 (beginning-of-line 0)
18356 (org-indent-line-function)
18357 (org-flag-drawer t)
18358 (beginning-of-line 2)
18359 (throw 'exit nil))
18361 (goto-char beg)
18362 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18363 (not (equal (match-string 1) org-clock-string)))
18364 ;; Planning info, skip to after it
18365 (beginning-of-line 2)
18366 (or (bolp) (newline)))
18367 (when (eq t org-clock-into-drawer)
18368 (insert ":CLOCK:\n:END:\n")
18369 (beginning-of-line -1)
18370 (org-indent-line-function)
18371 (org-flag-drawer t)
18372 (beginning-of-line 2)
18373 (org-indent-line-function)))))
18375 (defun org-clock-out (&optional fail-quietly)
18376 "Stop the currently running clock.
18377 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18378 (interactive)
18379 (catch 'exit
18380 (if (not (marker-buffer org-clock-marker))
18381 (if fail-quietly (throw 'exit t) (error "No active clock")))
18382 (let (ts te s h m)
18383 (save-excursion
18384 (set-buffer (marker-buffer org-clock-marker))
18385 (goto-char org-clock-marker)
18386 (beginning-of-line 1)
18387 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18388 (equal (match-string 1) org-clock-string))
18389 (setq ts (match-string 2))
18390 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18391 (goto-char (match-end 0))
18392 (delete-region (point) (point-at-eol))
18393 (insert "--")
18394 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18395 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18396 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18397 h (floor (/ s 3600))
18398 s (- s (* 3600 h))
18399 m (floor (/ s 60))
18400 s (- s (* 60 s)))
18401 (insert " => " (format "%2d:%02d" h m))
18402 (move-marker org-clock-marker nil)
18403 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18404 (org-log-done (org-parse-local-options logging 'org-log-done))
18405 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18406 (org-add-log-maybe 'clock-out))
18407 (when org-mode-line-timer
18408 (cancel-timer org-mode-line-timer)
18409 (setq org-mode-line-timer nil))
18410 (setq global-mode-string
18411 (delq 'org-mode-line-string global-mode-string))
18412 (force-mode-line-update)
18413 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18415 (defun org-clock-cancel ()
18416 "Cancel the running clock be removing the start timestamp."
18417 (interactive)
18418 (if (not (marker-buffer org-clock-marker))
18419 (error "No active clock"))
18420 (save-excursion
18421 (set-buffer (marker-buffer org-clock-marker))
18422 (goto-char org-clock-marker)
18423 (delete-region (1- (point-at-bol)) (point-at-eol)))
18424 (setq global-mode-string
18425 (delq 'org-mode-line-string global-mode-string))
18426 (force-mode-line-update)
18427 (message "Clock canceled"))
18429 (defun org-clock-goto (&optional delete-windows)
18430 "Go to the currently clocked-in entry."
18431 (interactive "P")
18432 (if (not (marker-buffer org-clock-marker))
18433 (error "No active clock"))
18434 (switch-to-buffer-other-window
18435 (marker-buffer org-clock-marker))
18436 (if delete-windows (delete-other-windows))
18437 (goto-char org-clock-marker)
18438 (org-show-entry)
18439 (org-back-to-heading)
18440 (recenter))
18442 (defvar org-clock-file-total-minutes nil
18443 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18444 (make-variable-buffer-local 'org-clock-file-total-minutes)
18446 (defun org-clock-sum (&optional tstart tend)
18447 "Sum the times for each subtree.
18448 Puts the resulting times in minutes as a text property on each headline."
18449 (interactive)
18450 (let* ((bmp (buffer-modified-p))
18451 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18452 org-clock-string
18453 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18454 (lmax 30)
18455 (ltimes (make-vector lmax 0))
18456 (t1 0)
18457 (level 0)
18458 ts te dt
18459 time)
18460 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18461 (save-excursion
18462 (goto-char (point-max))
18463 (while (re-search-backward re nil t)
18464 (cond
18465 ((match-end 2)
18466 ;; Two time stamps
18467 (setq ts (match-string 2)
18468 te (match-string 3)
18469 ts (time-to-seconds
18470 (apply 'encode-time (org-parse-time-string ts)))
18471 te (time-to-seconds
18472 (apply 'encode-time (org-parse-time-string te)))
18473 ts (if tstart (max ts tstart) ts)
18474 te (if tend (min te tend) te)
18475 dt (- te ts)
18476 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18477 ((match-end 4)
18478 ;; A naket time
18479 (setq t1 (+ t1 (string-to-number (match-string 5))
18480 (* 60 (string-to-number (match-string 4))))))
18481 (t ;; A headline
18482 (setq level (- (match-end 1) (match-beginning 1)))
18483 (when (or (> t1 0) (> (aref ltimes level) 0))
18484 (loop for l from 0 to level do
18485 (aset ltimes l (+ (aref ltimes l) t1)))
18486 (setq t1 0 time (aref ltimes level))
18487 (loop for l from level to (1- lmax) do
18488 (aset ltimes l 0))
18489 (goto-char (match-beginning 0))
18490 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18491 (setq org-clock-file-total-minutes (aref ltimes 0)))
18492 (set-buffer-modified-p bmp)))
18494 (defun org-clock-display (&optional total-only)
18495 "Show subtree times in the entire buffer.
18496 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18497 in the echo area."
18498 (interactive)
18499 (org-remove-clock-overlays)
18500 (let (time h m p)
18501 (org-clock-sum)
18502 (unless total-only
18503 (save-excursion
18504 (goto-char (point-min))
18505 (while (or (and (equal (setq p (point)) (point-min))
18506 (get-text-property p :org-clock-minutes))
18507 (setq p (next-single-property-change
18508 (point) :org-clock-minutes)))
18509 (goto-char p)
18510 (when (setq time (get-text-property p :org-clock-minutes))
18511 (org-put-clock-overlay time (funcall outline-level))))
18512 (setq h (/ org-clock-file-total-minutes 60)
18513 m (- org-clock-file-total-minutes (* 60 h)))
18514 ;; Arrange to remove the overlays upon next change.
18515 (when org-remove-highlights-with-change
18516 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18517 nil 'local))))
18518 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18520 (defvar org-clock-overlays nil)
18521 (make-variable-buffer-local 'org-clock-overlays)
18523 (defun org-put-clock-overlay (time &optional level)
18524 "Put an overlays on the current line, displaying TIME.
18525 If LEVEL is given, prefix time with a corresponding number of stars.
18526 This creates a new overlay and stores it in `org-clock-overlays', so that it
18527 will be easy to remove."
18528 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18529 (l (if level (org-get-legal-level level 0) 0))
18530 (off 0)
18531 ov tx)
18532 (move-to-column c)
18533 (unless (eolp) (skip-chars-backward "^ \t"))
18534 (skip-chars-backward " \t")
18535 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18536 tx (concat (buffer-substring (1- (point)) (point))
18537 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18538 (org-add-props (format "%s %2d:%02d%s"
18539 (make-string l ?*) h m
18540 (make-string (- 10 l) ?\ ))
18541 '(face secondary-selection))
18542 ""))
18543 (if (not (featurep 'xemacs))
18544 (org-overlay-put ov 'display tx)
18545 (org-overlay-put ov 'invisible t)
18546 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18547 (push ov org-clock-overlays)))
18549 (defun org-remove-clock-overlays (&optional beg end noremove)
18550 "Remove the occur highlights from the buffer.
18551 BEG and END are ignored. If NOREMOVE is nil, remove this function
18552 from the `before-change-functions' in the current buffer."
18553 (interactive)
18554 (unless org-inhibit-highlight-removal
18555 (mapc 'org-delete-overlay org-clock-overlays)
18556 (setq org-clock-overlays nil)
18557 (unless noremove
18558 (remove-hook 'before-change-functions
18559 'org-remove-clock-overlays 'local))))
18561 (defun org-clock-out-if-current ()
18562 "Clock out if the current entry contains the running clock.
18563 This is used to stop the clock after a TODO entry is marked DONE,
18564 and is only done if the variable `org-clock-out-when-done' is not nil."
18565 (when (and org-clock-out-when-done
18566 (member state org-done-keywords)
18567 (equal (marker-buffer org-clock-marker) (current-buffer))
18568 (< (point) org-clock-marker)
18569 (> (save-excursion (outline-next-heading) (point))
18570 org-clock-marker))
18571 ;; Clock out, but don't accept a logging message for this.
18572 (let ((org-log-done (if (and (listp org-log-done)
18573 (member 'clock-out org-log-done))
18574 '(done)
18575 org-log-done)))
18576 (org-clock-out))))
18578 (add-hook 'org-after-todo-state-change-hook
18579 'org-clock-out-if-current)
18581 (defun org-check-running-clock ()
18582 "Check if the current buffer contains the running clock.
18583 If yes, offer to stop it and to save the buffer with the changes."
18584 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18585 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18586 (buffer-name))))
18587 (org-clock-out)
18588 (when (y-or-n-p "Save changed buffer?")
18589 (save-buffer))))
18591 (defun org-clock-report (&optional arg)
18592 "Create a table containing a report about clocked time.
18593 If the cursor is inside an existing clocktable block, then the table
18594 will be updated. If not, a new clocktable will be inserted.
18595 When called with a prefix argument, move to the first clock table in the
18596 buffer and update it."
18597 (interactive "P")
18598 (org-remove-clock-overlays)
18599 (when arg (org-find-dblock "clocktable"))
18600 (if (org-in-clocktable-p)
18601 (goto-char (org-in-clocktable-p))
18602 (org-create-dblock (list :name "clocktable"
18603 :maxlevel 2 :scope 'file)))
18604 (org-update-dblock))
18606 (defun org-in-clocktable-p ()
18607 "Check if the cursor is in a clocktable."
18608 (let ((pos (point)) start)
18609 (save-excursion
18610 (end-of-line 1)
18611 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18612 (setq start (match-beginning 0))
18613 (re-search-forward "^#\\+END:.*" nil t)
18614 (>= (match-end 0) pos)
18615 start))))
18617 (defun org-clock-update-time-maybe ()
18618 "If this is a CLOCK line, update it and return t.
18619 Otherwise, return nil."
18620 (interactive)
18621 (save-excursion
18622 (beginning-of-line 1)
18623 (skip-chars-forward " \t")
18624 (when (looking-at org-clock-string)
18625 (let ((re (concat "[ \t]*" org-clock-string
18626 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18627 "\\([ \t]*=>.*\\)?"))
18628 ts te h m s)
18629 (if (not (looking-at re))
18631 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18632 (end-of-line 1)
18633 (setq ts (match-string 1)
18634 te (match-string 2))
18635 (setq s (- (time-to-seconds
18636 (apply 'encode-time (org-parse-time-string te)))
18637 (time-to-seconds
18638 (apply 'encode-time (org-parse-time-string ts))))
18639 h (floor (/ s 3600))
18640 s (- s (* 3600 h))
18641 m (floor (/ s 60))
18642 s (- s (* 60 s)))
18643 (insert " => " (format "%2d:%02d" h m))
18644 t)))))
18646 (defun org-clock-special-range (key &optional time as-strings)
18647 "Return two times bordering a special time range.
18648 Key is a symbol specifying the range and can be one of `today', `yesterday',
18649 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18650 A week starts Monday 0:00 and ends Sunday 24:00.
18651 The range is determined relative to TIME. TIME defaults to the current time.
18652 The return value is a cons cell with two internal times like the ones
18653 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18654 the returned times will be formatted strings."
18655 (let* ((tm (decode-time (or time (current-time))))
18656 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18657 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18658 (dow (nth 6 tm))
18659 s1 m1 h1 d1 month1 y1 diff ts te fm)
18660 (cond
18661 ((eq key 'today)
18662 (setq h 0 m 0 h1 24 m1 0))
18663 ((eq key 'yesterday)
18664 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18665 ((eq key 'thisweek)
18666 (setq diff (if (= dow 0) 6 (1- dow))
18667 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18668 ((eq key 'lastweek)
18669 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18670 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18671 ((eq key 'thismonth)
18672 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18673 ((eq key 'lastmonth)
18674 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18675 ((eq key 'thisyear)
18676 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18677 ((eq key 'lastyear)
18678 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18679 (t (error "No such time block %s" key)))
18680 (setq ts (encode-time s m h d month y)
18681 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18682 (or d1 d) (or month1 month) (or y1 y)))
18683 (setq fm (cdr org-time-stamp-formats))
18684 (if as-strings
18685 (cons (format-time-string fm ts) (format-time-string fm te))
18686 (cons ts te))))
18688 (defun org-dblock-write:clocktable (params)
18689 "Write the standard clocktable."
18690 (let ((hlchars '((1 . "*") (2 . "/")))
18691 (emph nil)
18692 (ins (make-marker))
18693 (total-time nil)
18694 ipos time h m p level hlc hdl maxlevel
18695 ts te cc block beg end pos scope tbl tostring multifile)
18696 (setq scope (plist-get params :scope)
18697 tostring (plist-get params :tostring)
18698 multifile (plist-get params :multifile)
18699 maxlevel (or (plist-get params :maxlevel) 3)
18700 emph (plist-get params :emphasize)
18701 ts (plist-get params :tstart)
18702 te (plist-get params :tend)
18703 block (plist-get params :block))
18704 (when block
18705 (setq cc (org-clock-special-range block nil t)
18706 ts (car cc) te (cdr cc)))
18707 (if ts (setq ts (time-to-seconds
18708 (apply 'encode-time (org-parse-time-string ts)))))
18709 (if te (setq te (time-to-seconds
18710 (apply 'encode-time (org-parse-time-string te)))))
18711 (move-marker ins (point))
18712 (setq ipos (point))
18714 ;; Get the right scope
18715 (setq pos (point))
18716 (save-restriction
18717 (cond
18718 ((not scope))
18719 ((eq scope 'file) (widen))
18720 ((eq scope 'subtree) (org-narrow-to-subtree))
18721 ((eq scope 'tree)
18722 (while (org-up-heading-safe))
18723 (org-narrow-to-subtree))
18724 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18725 (symbol-name scope)))
18726 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18727 (catch 'exit
18728 (while (org-up-heading-safe)
18729 (looking-at outline-regexp)
18730 (if (<= (org-reduced-level (funcall outline-level)) level)
18731 (throw 'exit nil))))
18732 (org-narrow-to-subtree))
18733 ((or (listp scope) (eq scope 'agenda))
18734 (let* ((files (if (listp scope) scope (org-agenda-files)))
18735 (scope 'agenda)
18736 (p1 (copy-sequence params))
18737 file)
18738 (plist-put p1 :tostring t)
18739 (plist-put p1 :multifile t)
18740 (plist-put p1 :scope 'file)
18741 (org-prepare-agenda-buffers files)
18742 (while (setq file (pop files))
18743 (with-current-buffer (find-buffer-visiting file)
18744 (push (org-clocktable-add-file
18745 file (org-dblock-write:clocktable p1)) tbl)
18746 (setq total-time (+ (or total-time 0)
18747 org-clock-file-total-minutes)))))))
18748 (goto-char pos)
18750 (unless (eq scope 'agenda)
18751 (org-clock-sum ts te)
18752 (goto-char (point-min))
18753 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18754 (goto-char p)
18755 (when (setq time (get-text-property p :org-clock-minutes))
18756 (save-excursion
18757 (beginning-of-line 1)
18758 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18759 (setq level (org-reduced-level
18760 (- (match-end 1) (match-beginning 1))))
18761 (<= level maxlevel))
18762 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18763 hdl (match-string 2)
18764 h (/ time 60)
18765 m (- time (* 60 h)))
18766 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18767 (push (concat
18768 "| " (int-to-string level) "|" hlc hdl hlc " |"
18769 (make-string (1- level) ?|)
18770 hlc (format "%d:%02d" h m) hlc
18771 " |") tbl))))))
18772 (setq tbl (nreverse tbl))
18773 (if tostring
18774 (if tbl (mapconcat 'identity tbl "\n") nil)
18775 (goto-char ins)
18776 (insert-before-markers
18777 "Clock summary at ["
18778 (substring
18779 (format-time-string (cdr org-time-stamp-formats))
18780 1 -1)
18781 "]."
18782 (if block
18783 (format " Considered range is /%s/." block)
18785 "\n\n"
18786 (if (eq scope 'agenda) "|File" "")
18787 "|L|Headline|Time|\n")
18788 (setq total-time (or total-time org-clock-file-total-minutes)
18789 h (/ total-time 60)
18790 m (- total-time (* 60 h)))
18791 (insert-before-markers
18792 "|-\n|"
18793 (if (eq scope 'agenda) "|" "")
18795 "*Total time*| "
18796 (format "*%d:%02d*" h m)
18797 "|\n|-\n")
18798 (setq tbl (delq nil tbl))
18799 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
18800 (equal (substring (car tbl) 0 2) "|-"))
18801 (pop tbl))
18802 (insert-before-markers (mapconcat
18803 'identity (delq nil tbl)
18804 (if (eq scope 'agenda) "\n|-\n" "\n")))
18805 (backward-delete-char 1)
18806 (goto-char ipos)
18807 (skip-chars-forward "^|")
18808 (org-table-align)))))
18810 (defun org-clocktable-add-file (file table)
18811 (if table
18812 (let ((lines (org-split-string table "\n"))
18813 (ff (file-name-nondirectory file)))
18814 (mapconcat 'identity
18815 (mapcar (lambda (x)
18816 (if (string-match org-table-dataline-regexp x)
18817 (concat "|" ff x)
18819 lines)
18820 "\n"))))
18822 ;; FIXME: I don't think anybody uses this, ask David
18823 (defun org-collect-clock-time-entries ()
18824 "Return an internal list with clocking information.
18825 This list has one entry for each CLOCK interval.
18826 FIXME: describe the elements."
18827 (interactive)
18828 (let ((re (concat "^[ \t]*" org-clock-string
18829 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
18830 rtn beg end next cont level title total closedp leafp
18831 clockpos titlepos h m donep)
18832 (save-excursion
18833 (org-clock-sum)
18834 (goto-char (point-min))
18835 (while (re-search-forward re nil t)
18836 (setq clockpos (match-beginning 0)
18837 beg (match-string 1) end (match-string 2)
18838 cont (match-end 0))
18839 (setq beg (apply 'encode-time (org-parse-time-string beg))
18840 end (apply 'encode-time (org-parse-time-string end)))
18841 (org-back-to-heading t)
18842 (setq donep (org-entry-is-done-p))
18843 (setq titlepos (point)
18844 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
18845 h (/ total 60) m (- total (* 60 h))
18846 total (cons h m))
18847 (looking-at "\\(\\*+\\) +\\(.*\\)")
18848 (setq level (- (match-end 1) (match-beginning 1))
18849 title (org-match-string-no-properties 2))
18850 (save-excursion (outline-next-heading) (setq next (point)))
18851 (setq closedp (re-search-forward org-closed-time-regexp next t))
18852 (goto-char next)
18853 (setq leafp (and (looking-at "^\\*+ ")
18854 (<= (- (match-end 0) (point)) level)))
18855 (push (list beg end clockpos closedp donep
18856 total title titlepos level leafp)
18857 rtn)
18858 (goto-char cont)))
18859 (nreverse rtn)))
18861 ;;;; Agenda, and Diary Integration
18863 ;;; Define the Org-agenda-mode
18865 (defvar org-agenda-mode-map (make-sparse-keymap)
18866 "Keymap for `org-agenda-mode'.")
18868 (defvar org-agenda-menu) ; defined later in this file.
18869 (defvar org-agenda-follow-mode nil)
18870 (defvar org-agenda-show-log nil)
18871 (defvar org-agenda-redo-command nil)
18872 (defvar org-agenda-mode-hook nil)
18873 (defvar org-agenda-type nil)
18874 (defvar org-agenda-force-single-file nil)
18876 (defun org-agenda-mode ()
18877 "Mode for time-sorted view on action items in Org-mode files.
18879 The following commands are available:
18881 \\{org-agenda-mode-map}"
18882 (interactive)
18883 (kill-all-local-variables)
18884 (setq org-agenda-undo-list nil
18885 org-agenda-pending-undo-list nil)
18886 (setq major-mode 'org-agenda-mode)
18887 ;; Keep global-font-lock-mode from turning on font-lock-mode
18888 (org-set-local 'font-lock-global-modes (list 'not major-mode))
18889 (setq mode-name "Org-Agenda")
18890 (use-local-map org-agenda-mode-map)
18891 (easy-menu-add org-agenda-menu)
18892 (if org-startup-truncated (setq truncate-lines t))
18893 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
18894 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
18895 ;; Make sure properties are removed when copying text
18896 (when (boundp 'buffer-substring-filters)
18897 (org-set-local 'buffer-substring-filters
18898 (cons (lambda (x)
18899 (set-text-properties 0 (length x) nil x) x)
18900 buffer-substring-filters)))
18901 (unless org-agenda-keep-modes
18902 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
18903 org-agenda-show-log nil))
18904 (easy-menu-change
18905 '("Agenda") "Agenda Files"
18906 (append
18907 (list
18908 (vector
18909 (if (get 'org-agenda-files 'org-restrict)
18910 "Restricted to single file"
18911 "Edit File List")
18912 '(org-edit-agenda-file-list)
18913 (not (get 'org-agenda-files 'org-restrict)))
18914 "--")
18915 (mapcar 'org-file-menu-entry (org-agenda-files))))
18916 (org-agenda-set-mode-name)
18917 (apply
18918 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
18919 (list 'org-agenda-mode-hook)))
18921 (substitute-key-definition 'undo 'org-agenda-undo
18922 org-agenda-mode-map global-map)
18923 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
18924 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
18925 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
18926 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
18927 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
18928 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
18929 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
18930 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
18931 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
18932 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
18933 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
18934 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
18935 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
18936 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
18937 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
18938 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
18939 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
18940 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
18941 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
18942 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
18943 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
18944 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
18945 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
18946 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
18947 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
18948 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
18949 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
18950 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
18951 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
18953 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
18954 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
18955 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
18956 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
18957 (while l (org-defkey org-agenda-mode-map
18958 (int-to-string (pop l)) 'digit-argument)))
18960 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
18961 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
18962 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
18963 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
18964 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
18965 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
18966 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
18967 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
18968 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
18969 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
18970 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
18971 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
18972 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
18973 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
18974 (org-defkey org-agenda-mode-map "n" 'next-line)
18975 (org-defkey org-agenda-mode-map "p" 'previous-line)
18976 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
18977 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
18978 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
18979 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
18980 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
18981 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
18982 (eval-after-load "calendar"
18983 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
18984 'org-calendar-goto-agenda))
18985 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
18986 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
18987 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
18988 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
18989 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
18990 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
18991 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
18992 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
18993 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
18994 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
18995 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
18996 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18997 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
18998 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
18999 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19000 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19001 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19002 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19003 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19004 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19005 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19006 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19008 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19009 "Local keymap for agenda entries from Org-mode.")
19011 (org-defkey org-agenda-keymap
19012 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19013 (org-defkey org-agenda-keymap
19014 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19015 (when org-agenda-mouse-1-follows-link
19016 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19017 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19018 '("Agenda"
19019 ("Agenda Files")
19020 "--"
19021 ["Show" org-agenda-show t]
19022 ["Go To (other window)" org-agenda-goto t]
19023 ["Go To (this window)" org-agenda-switch-to t]
19024 ["Follow Mode" org-agenda-follow-mode
19025 :style toggle :selected org-agenda-follow-mode :active t]
19026 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19027 "--"
19028 ["Cycle TODO" org-agenda-todo t]
19029 ["Archive subtree" org-agenda-archive t]
19030 ["Delete subtree" org-agenda-kill t]
19031 "--"
19032 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19033 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19034 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19035 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19036 "--"
19037 ("Tags and Properties"
19038 ["Show all Tags" org-agenda-show-tags t]
19039 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19040 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19041 "--"
19042 ["Column View" org-columns t])
19043 ("Date/Schedule"
19044 ["Schedule" org-agenda-schedule t]
19045 ["Set Deadline" org-agenda-deadline t]
19046 "--"
19047 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19048 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19049 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19050 ("Clock"
19051 ["Clock in" org-agenda-clock-in t]
19052 ["Clock out" org-agenda-clock-out t]
19053 ["Clock cancel" org-agenda-clock-cancel t]
19054 ["Goto running clock" org-clock-goto t])
19055 ("Priority"
19056 ["Set Priority" org-agenda-priority t]
19057 ["Increase Priority" org-agenda-priority-up t]
19058 ["Decrease Priority" org-agenda-priority-down t]
19059 ["Show Priority" org-agenda-show-priority t])
19060 ("Calendar/Diary"
19061 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19062 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19063 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19064 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19065 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19066 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19067 "--"
19068 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19069 "--"
19070 ("View"
19071 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19072 :style radio :selected (equal org-agenda-ndays 1)]
19073 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19074 :style radio :selected (equal org-agenda-ndays 7)]
19075 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19076 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19077 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19078 :style radio :selected (member org-agenda-ndays '(365 366))]
19079 "--"
19080 ["Show Logbook entries" org-agenda-log-mode
19081 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19082 ["Include Diary" org-agenda-toggle-diary
19083 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19084 ["Use Time Grid" org-agenda-toggle-time-grid
19085 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19086 ["Write view to file" org-write-agenda t]
19087 ["Rebuild buffer" org-agenda-redo t]
19088 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19089 "--"
19090 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19091 "--"
19092 ["Quit" org-agenda-quit t]
19093 ["Exit and Release Buffers" org-agenda-exit t]
19096 ;;; Agenda undo
19098 (defvar org-agenda-allow-remote-undo t
19099 "Non-nil means, allow remote undo from the agenda buffer.")
19100 (defvar org-agenda-undo-list nil
19101 "List of undoable operations in the agenda since last refresh.")
19102 (defvar org-agenda-undo-has-started-in nil
19103 "Buffers that have already seen `undo-start' in the current undo sequence.")
19104 (defvar org-agenda-pending-undo-list nil
19105 "In a series of undo commands, this is the list of remaning undo items.")
19107 (defmacro org-if-unprotected (&rest body)
19108 "Execute BODY if there is no `org-protected' text property at point."
19109 (declare (debug t))
19110 `(unless (get-text-property (point) 'org-protected)
19111 ,@body))
19113 (defmacro org-with-remote-undo (_buffer &rest _body)
19114 "Execute BODY while recording undo information in two buffers."
19115 (declare (indent 1) (debug t))
19116 `(let ((_cline (org-current-line))
19117 (_cmd this-command)
19118 (_buf1 (current-buffer))
19119 (_buf2 ,_buffer)
19120 (_undo1 buffer-undo-list)
19121 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19122 _c1 _c2)
19123 ,@_body
19124 (when org-agenda-allow-remote-undo
19125 (setq _c1 (org-verify-change-for-undo
19126 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19127 _c2 (org-verify-change-for-undo
19128 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19129 (when (or _c1 _c2)
19130 ;; make sure there are undo boundaries
19131 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19132 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19133 ;; remember which buffer to undo
19134 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19135 org-agenda-undo-list)))))
19137 (defun org-agenda-undo ()
19138 "Undo a remote editing step in the agenda.
19139 This undoes changes both in the agenda buffer and in the remote buffer
19140 that have been changed along."
19141 (interactive)
19142 (or org-agenda-allow-remote-undo
19143 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19144 (if (not (eq this-command last-command))
19145 (setq org-agenda-undo-has-started-in nil
19146 org-agenda-pending-undo-list org-agenda-undo-list))
19147 (if (not org-agenda-pending-undo-list)
19148 (error "No further undo information"))
19149 (let* ((entry (pop org-agenda-pending-undo-list))
19150 buf line cmd rembuf)
19151 (setq cmd (pop entry) line (pop entry))
19152 (setq rembuf (nth 2 entry))
19153 (org-with-remote-undo rembuf
19154 (while (bufferp (setq buf (pop entry)))
19155 (if (pop entry)
19156 (with-current-buffer buf
19157 (let ((last-undo-buffer buf)
19158 (inhibit-read-only t))
19159 (unless (memq buf org-agenda-undo-has-started-in)
19160 (push buf org-agenda-undo-has-started-in)
19161 (make-local-variable 'pending-undo-list)
19162 (undo-start))
19163 (while (and pending-undo-list
19164 (listp pending-undo-list)
19165 (not (car pending-undo-list)))
19166 (pop pending-undo-list))
19167 (undo-more 1))))))
19168 (goto-line line)
19169 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19171 (defun org-verify-change-for-undo (l1 l2)
19172 "Verify that a real change occurred between the undo lists L1 and L2."
19173 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19174 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19175 (not (eq l1 l2)))
19177 ;;; Agenda dispatch
19179 (defvar org-agenda-restrict nil)
19180 (defvar org-agenda-restrict-begin (make-marker))
19181 (defvar org-agenda-restrict-end (make-marker))
19182 (defvar org-agenda-last-dispatch-buffer nil)
19183 (defvar org-agenda-overriding-restriction nil)
19185 ;;;###autoload
19186 (defun org-agenda (arg &optional keys restriction)
19187 "Dispatch agenda commands to collect entries to the agenda buffer.
19188 Prompts for a command to execute. Any prefix arg will be passed
19189 on to the selected command. The default selections are:
19191 a Call `org-agenda-list' to display the agenda for current day or week.
19192 t Call `org-todo-list' to display the global todo list.
19193 T Call `org-todo-list' to display the global todo list, select only
19194 entries with a specific TODO keyword (the user gets a prompt).
19195 m Call `org-tags-view' to display headlines with tags matching
19196 a condition (the user is prompted for the condition).
19197 M Like `m', but select only TODO entries, no ordinary headlines.
19198 L Create a timeline for the current buffer.
19199 e Export views to associated files.
19201 More commands can be added by configuring the variable
19202 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19203 searches can be pre-defined in this way.
19205 If the current buffer is in Org-mode and visiting a file, you can also
19206 first press `<' once to indicate that the agenda should be temporarily
19207 \(until the next use of \\[org-agenda]) restricted to the current file.
19208 Pressing `<' twice means to restrict to the current subtree or region
19209 \(if active)."
19210 (interactive "P")
19211 (catch 'exit
19212 (let* ((prefix-descriptions nil)
19213 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19214 (org-agenda-custom-commands
19215 ;; normalize different versions
19216 (delq nil
19217 (mapcar
19218 (lambda (x)
19219 (cond ((stringp (cdr x))
19220 (push x prefix-descriptions)
19221 nil)
19222 ((stringp (nth 1 x)) x)
19223 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19224 (t (cons (car x) (cons "" (cdr x))))))
19225 org-agenda-custom-commands)))
19226 (buf (current-buffer))
19227 (bfn (buffer-file-name (buffer-base-buffer)))
19228 entry key type match lprops ans)
19229 ;; Turn off restriction unless there is an overriding one
19230 (unless org-agenda-overriding-restriction
19231 (put 'org-agenda-files 'org-restrict nil)
19232 (setq org-agenda-restrict nil)
19233 (move-marker org-agenda-restrict-begin nil)
19234 (move-marker org-agenda-restrict-end nil))
19235 ;; Delete old local properties
19236 (put 'org-agenda-redo-command 'org-lprops nil)
19237 ;; Remember where this call originated
19238 (setq org-agenda-last-dispatch-buffer (current-buffer))
19239 (unless keys
19240 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19241 keys (car ans)
19242 restriction (cdr ans)))
19243 ;; Estabish the restriction, if any
19244 (when (and (not org-agenda-overriding-restriction) restriction)
19245 (put 'org-agenda-files 'org-restrict (list bfn))
19246 (cond
19247 ((eq restriction 'region)
19248 (setq org-agenda-restrict t)
19249 (move-marker org-agenda-restrict-begin (region-beginning))
19250 (move-marker org-agenda-restrict-end (region-end)))
19251 ((eq restriction 'subtree)
19252 (save-excursion
19253 (setq org-agenda-restrict t)
19254 (org-back-to-heading t)
19255 (move-marker org-agenda-restrict-begin (point))
19256 (move-marker org-agenda-restrict-end
19257 (progn (org-end-of-subtree t)))))))
19259 (require 'calendar) ; FIXME: can we avoid this for some commands?
19260 ;; For example the todo list should not need it (but does...)
19261 (cond
19262 ((setq entry (assoc keys org-agenda-custom-commands))
19263 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19264 (progn
19265 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19266 (put 'org-agenda-redo-command 'org-lprops lprops)
19267 (cond
19268 ((eq type 'agenda)
19269 (org-let lprops '(org-agenda-list current-prefix-arg)))
19270 ((eq type 'alltodo)
19271 (org-let lprops '(org-todo-list current-prefix-arg)))
19272 ((eq type 'stuck)
19273 (org-let lprops '(org-agenda-list-stuck-projects
19274 current-prefix-arg)))
19275 ((eq type 'tags)
19276 (org-let lprops '(org-tags-view current-prefix-arg match)))
19277 ((eq type 'tags-todo)
19278 (org-let lprops '(org-tags-view '(4) match)))
19279 ((eq type 'todo)
19280 (org-let lprops '(org-todo-list match)))
19281 ((eq type 'tags-tree)
19282 (org-check-for-org-mode)
19283 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19284 ((eq type 'todo-tree)
19285 (org-check-for-org-mode)
19286 (org-let lprops
19287 '(org-occur (concat "^" outline-regexp "[ \t]*"
19288 (regexp-quote match) "\\>"))))
19289 ((eq type 'occur-tree)
19290 (org-check-for-org-mode)
19291 (org-let lprops '(org-occur match)))
19292 ((functionp type)
19293 (org-let lprops '(funcall type match)))
19294 ((fboundp type)
19295 (org-let lprops '(funcall type match)))
19296 (t (error "Invalid custom agenda command type %s" type))))
19297 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19298 ((equal keys "C")
19299 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19300 (customize-variable 'org-agenda-custom-commands))
19301 ((equal keys "a") (call-interactively 'org-agenda-list))
19302 ((equal keys "t") (call-interactively 'org-todo-list))
19303 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19304 ((equal keys "m") (call-interactively 'org-tags-view))
19305 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19306 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19307 ((equal keys "L")
19308 (unless (org-mode-p)
19309 (error "This is not an Org-mode file"))
19310 (unless restriction
19311 (put 'org-agenda-files 'org-restrict (list bfn))
19312 (org-call-with-arg 'org-timeline arg)))
19313 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19314 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19315 ((equal keys "!") (customize-variable 'org-stuck-projects))
19316 (t (error "Invalid agenda key"))))))
19318 (defun org-agenda-normalize-custom-commands (cmds)
19319 (delq nil
19320 (mapcar
19321 (lambda (x)
19322 (cond ((stringp (cdr x)) nil)
19323 ((stringp (nth 1 x)) x)
19324 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19325 (t (cons (car x) (cons "" (cdr x))))))
19326 cmds)))
19328 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19329 "The user interface for selecting an agenda command."
19330 (catch 'exit
19331 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19332 (restrict-ok (and bfn (org-mode-p)))
19333 (region-p (org-region-active-p))
19334 (custom org-agenda-custom-commands)
19335 (selstring "")
19336 restriction second-time
19337 c entry key type match prefixes rmheader header-end custom1 desc)
19338 (save-window-excursion
19339 (delete-other-windows)
19340 (org-switch-to-buffer-other-window " *Agenda Commands*")
19341 (erase-buffer)
19342 (insert (eval-when-compile
19343 (let ((header
19345 Press key for an agenda command: < Buffer,subtree/region restriction
19346 -------------------------------- > Remove restriction
19347 a Agenda for current week or day e Export agenda views
19348 t List of all TODO entries T Entries with special TODO kwd
19349 m Match a TAGS query M Like m, but only TODO entries
19350 L Timeline for current buffer # List stuck projects (!=configure)
19351 / Multi-occur C Configure custom agenda commands
19353 (start 0))
19354 (while (string-match
19355 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19356 header start)
19357 (setq start (match-end 0))
19358 (add-text-properties (match-beginning 2) (match-end 2)
19359 '(face bold) header))
19360 header)))
19361 (setq header-end (move-marker (make-marker) (point)))
19362 (while t
19363 (setq custom1 custom)
19364 (when (eq rmheader t)
19365 (goto-line 1)
19366 (re-search-forward ":" nil t)
19367 (delete-region (match-end 0) (point-at-eol))
19368 (forward-char 1)
19369 (looking-at "-+")
19370 (delete-region (match-end 0) (point-at-eol))
19371 (move-marker header-end (match-end 0)))
19372 (goto-char header-end)
19373 (delete-region (point) (point-max))
19374 (while (setq entry (pop custom1))
19375 (setq key (car entry) desc (nth 1 entry)
19376 type (nth 2 entry) match (nth 3 entry))
19377 (if (> (length key) 1)
19378 (add-to-list 'prefixes (string-to-char key))
19379 (insert
19380 (format
19381 "\n%-4s%-14s: %s"
19382 (org-add-props (copy-sequence key)
19383 '(face bold))
19384 (cond
19385 ((string-match "\\S-" desc) desc)
19386 ((eq type 'agenda) "Agenda for current week or day")
19387 ((eq type 'alltodo) "List of all TODO entries")
19388 ((eq type 'stuck) "List of stuck projects")
19389 ((eq type 'todo) "TODO keyword")
19390 ((eq type 'tags) "Tags query")
19391 ((eq type 'tags-todo) "Tags (TODO)")
19392 ((eq type 'tags-tree) "Tags tree")
19393 ((eq type 'todo-tree) "TODO kwd tree")
19394 ((eq type 'occur-tree) "Occur tree")
19395 ((functionp type) (if (symbolp type)
19396 (symbol-name type)
19397 "Lambda expression"))
19398 (t "???"))
19399 (cond
19400 ((stringp match)
19401 (org-add-props match nil 'face 'org-warning))
19402 (match
19403 (format "set of %d commands" (length match)))
19404 (t ""))))))
19405 (when prefixes
19406 (mapc (lambda (x)
19407 (insert
19408 (format "\n%s %s"
19409 (org-add-props (char-to-string x)
19410 nil 'face 'bold)
19411 (or (cdr (assoc (concat selstring (char-to-string x))
19412 prefix-descriptions))
19413 "Prefix key"))))
19414 prefixes))
19415 (goto-char (point-min))
19416 (when (fboundp 'fit-window-to-buffer)
19417 (if second-time
19418 (if (not (pos-visible-in-window-p (point-max)))
19419 (fit-window-to-buffer))
19420 (setq second-time t)
19421 (fit-window-to-buffer)))
19422 (message "Press key for agenda command%s:"
19423 (if (or restrict-ok org-agenda-overriding-restriction)
19424 (if org-agenda-overriding-restriction
19425 " (restriction lock active)"
19426 (if restriction
19427 (format " (restricted to %s)" restriction)
19428 " (unrestricted)"))
19429 ""))
19430 (setq c (read-char-exclusive))
19431 (message "")
19432 (cond
19433 ((assoc (char-to-string c) custom)
19434 (setq selstring (concat selstring (char-to-string c)))
19435 (throw 'exit (cons selstring restriction)))
19436 ((memq c prefixes)
19437 (setq selstring (concat selstring (char-to-string c))
19438 prefixes nil
19439 rmheader (or rmheader t)
19440 custom (delq nil (mapcar
19441 (lambda (x)
19442 (if (or (= (length (car x)) 1)
19443 (/= (string-to-char (car x)) c))
19445 (cons (substring (car x) 1) (cdr x))))
19446 custom))))
19447 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19448 (message "Restriction is only possible in Org-mode buffers")
19449 (ding) (sit-for 1))
19450 ((eq c ?1)
19451 (org-agenda-remove-restriction-lock 'noupdate)
19452 (setq restriction 'buffer))
19453 ((eq c ?0)
19454 (org-agenda-remove-restriction-lock 'noupdate)
19455 (setq restriction (if region-p 'region 'subtree)))
19456 ((eq c ?<)
19457 (org-agenda-remove-restriction-lock 'noupdate)
19458 (setq restriction
19459 (cond
19460 ((eq restriction 'buffer)
19461 (if region-p 'region 'subtree))
19462 ((memq restriction '(subtree region))
19463 nil)
19464 (t 'buffer))))
19465 ((eq c ?>)
19466 (org-agenda-remove-restriction-lock 'noupdate)
19467 (setq restriction nil))
19468 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19469 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19470 ((and (> (length selstring) 0) (eq c ?\d))
19471 (delete-window)
19472 (org-agenda-get-restriction-and-command prefix-descriptions))
19474 ((equal c ?q) (error "Abort"))
19475 (t (error "Invalid key %c" c))))))))
19477 (defun org-run-agenda-series (name series)
19478 (org-prepare-agenda name)
19479 (let* ((org-agenda-multi t)
19480 (redo (list 'org-run-agenda-series name (list 'quote series)))
19481 (cmds (car series))
19482 (gprops (nth 1 series))
19483 match ;; The byte compiler incorrectly complains about this. Keep it!
19484 cmd type lprops)
19485 (while (setq cmd (pop cmds))
19486 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19487 (cond
19488 ((eq type 'agenda)
19489 (org-let2 gprops lprops
19490 '(call-interactively 'org-agenda-list)))
19491 ((eq type 'alltodo)
19492 (org-let2 gprops lprops
19493 '(call-interactively 'org-todo-list)))
19494 ((eq type 'stuck)
19495 (org-let2 gprops lprops
19496 '(call-interactively 'org-agenda-list-stuck-projects)))
19497 ((eq type 'tags)
19498 (org-let2 gprops lprops
19499 '(org-tags-view current-prefix-arg match)))
19500 ((eq type 'tags-todo)
19501 (org-let2 gprops lprops
19502 '(org-tags-view '(4) match)))
19503 ((eq type 'todo)
19504 (org-let2 gprops lprops
19505 '(org-todo-list match)))
19506 ((fboundp type)
19507 (org-let2 gprops lprops
19508 '(funcall type match)))
19509 (t (error "Invalid type in command series"))))
19510 (widen)
19511 (setq org-agenda-redo-command redo)
19512 (goto-char (point-min)))
19513 (org-finalize-agenda))
19515 ;;;###autoload
19516 (defmacro org-batch-agenda (cmd-key &rest parameters)
19517 "Run an agenda command in batch mode and send the result to STDOUT.
19518 If CMD-KEY is a string of length 1, it is used as a key in
19519 `org-agenda-custom-commands' and triggers this command. If it is a
19520 longer string is is used as a tags/todo match string.
19521 Paramters are alternating variable names and values that will be bound
19522 before running the agenda command."
19523 (let (pars)
19524 (while parameters
19525 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19526 (if (> (length cmd-key) 2)
19527 (eval (list 'let (nreverse pars)
19528 (list 'org-tags-view nil cmd-key)))
19529 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19530 (set-buffer org-agenda-buffer-name)
19531 (princ (org-encode-for-stdout (buffer-string)))))
19533 (defun org-encode-for-stdout (string)
19534 (if (fboundp 'encode-coding-string)
19535 (encode-coding-string string buffer-file-coding-system)
19536 string))
19538 (defvar org-agenda-info nil)
19540 ;;;###autoload
19541 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19542 "Run an agenda command in batch mode and send the result to STDOUT.
19543 If CMD-KEY is a string of length 1, it is used as a key in
19544 `org-agenda-custom-commands' and triggers this command. If it is a
19545 longer string is is used as a tags/todo match string.
19546 Paramters are alternating variable names and values that will be bound
19547 before running the agenda command.
19549 The output gives a line for each selected agenda item. Each
19550 item is a list of comma-separated values, like this:
19552 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19554 category The category of the item
19555 head The headline, without TODO kwd, TAGS and PRIORITY
19556 type The type of the agenda entry, can be
19557 todo selected in TODO match
19558 tagsmatch selected in tags match
19559 diary imported from diary
19560 deadline a deadline on given date
19561 scheduled scheduled on given date
19562 timestamp entry has timestamp on given date
19563 closed entry was closed on given date
19564 upcoming-deadline warning about deadline
19565 past-scheduled forwarded scheduled item
19566 block entry has date block including g. date
19567 todo The todo keyword, if any
19568 tags All tags including inherited ones, separated by colons
19569 date The relevant date, like 2007-2-14
19570 time The time, like 15:00-16:50
19571 extra Sting with extra planning info
19572 priority-l The priority letter if any was given
19573 priority-n The computed numerical priority
19574 agenda-day The day in the agenda where this is listed"
19576 (let (pars)
19577 (while parameters
19578 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19579 (push (list 'org-agenda-remove-tags t) pars)
19580 (if (> (length cmd-key) 2)
19581 (eval (list 'let (nreverse pars)
19582 (list 'org-tags-view nil cmd-key)))
19583 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19584 (set-buffer org-agenda-buffer-name)
19585 (let* ((lines (org-split-string (buffer-string) "\n"))
19586 line)
19587 (while (setq line (pop lines))
19588 (catch 'next
19589 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19590 (setq org-agenda-info
19591 (org-fix-agenda-info (text-properties-at 0 line)))
19592 (princ
19593 (org-encode-for-stdout
19594 (mapconcat 'org-agenda-export-csv-mapper
19595 '(org-category txt type todo tags date time-of-day extra
19596 priority-letter priority agenda-day)
19597 ",")))
19598 (princ "\n"))))))
19600 (defun org-fix-agenda-info (props)
19601 "Make sure all properties on an agenda item have a canonical form,
19602 so the the export commands caneasily use it."
19603 (let (tmp re)
19604 (when (setq tmp (plist-get props 'tags))
19605 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19606 (when (setq tmp (plist-get props 'date))
19607 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19608 (let ((calendar-date-display-form '(year "-" month "-" day)))
19609 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19611 (setq tmp (calendar-date-string tmp)))
19612 (setq props (plist-put props 'date tmp)))
19613 (when (setq tmp (plist-get props 'day))
19614 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19615 (let ((calendar-date-display-form '(year "-" month "-" day)))
19616 (setq tmp (calendar-date-string tmp)))
19617 (setq props (plist-put props 'day tmp))
19618 (setq props (plist-put props 'agenda-day tmp)))
19619 (when (setq tmp (plist-get props 'txt))
19620 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19621 (plist-put props 'priority-letter (match-string 1 tmp))
19622 (setq tmp (replace-match "" t t tmp)))
19623 (when (and (setq re (plist-get props 'org-todo-regexp))
19624 (setq re (concat "\\`\\.*" re " ?"))
19625 (string-match re tmp))
19626 (plist-put props 'todo (match-string 1 tmp))
19627 (setq tmp (replace-match "" t t tmp)))
19628 (plist-put props 'txt tmp)))
19629 props)
19631 (defun org-agenda-export-csv-mapper (prop)
19632 (let ((res (plist-get org-agenda-info prop)))
19633 (setq res
19634 (cond
19635 ((not res) "")
19636 ((stringp res) res)
19637 (t (prin1-to-string res))))
19638 (while (string-match "," res)
19639 (setq res (replace-match ";" t t res)))
19640 (org-trim res)))
19643 ;;;###autoload
19644 (defun org-store-agenda-views (&rest parameters)
19645 (interactive)
19646 (eval (list 'org-batch-store-agenda-views)))
19648 ;; FIXME, why is this a macro?????
19649 ;;;###autoload
19650 (defmacro org-batch-store-agenda-views (&rest parameters)
19651 "Run all custom agenda commands that have a file argument."
19652 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19653 (pop-up-frames nil)
19654 (dir default-directory)
19655 pars cmd thiscmdkey files opts)
19656 (while parameters
19657 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19658 (setq pars (reverse pars))
19659 (save-window-excursion
19660 (while cmds
19661 (setq cmd (pop cmds)
19662 thiscmdkey (car cmd)
19663 opts (nth 4 cmd)
19664 files (nth 5 cmd))
19665 (if (stringp files) (setq files (list files)))
19666 (when files
19667 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19668 (list 'org-agenda nil thiscmdkey)))
19669 (set-buffer org-agenda-buffer-name)
19670 (while files
19671 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19672 (list 'org-write-agenda
19673 (expand-file-name (pop files) dir) t))))
19674 (and (get-buffer org-agenda-buffer-name)
19675 (kill-buffer org-agenda-buffer-name)))))))
19677 (defun org-write-agenda (file &optional nosettings)
19678 "Write the current buffer (an agenda view) as a file.
19679 Depending on the extension of the file name, plain text (.txt),
19680 HTML (.html or .htm) or Postscript (.ps) is produced.
19681 If NOSETTINGS is given, do not scope the settings of
19682 `org-agenda-exporter-settings' into the export commands. This is used when
19683 the settings have already been scoped and we do not wish to overrule other,
19684 higher priority settings."
19685 (interactive "FWrite agenda to file: ")
19686 (if (not (file-writable-p file))
19687 (error "Cannot write agenda to file %s" file))
19688 (cond
19689 ((string-match "\\.html?\\'" file) (require 'htmlize))
19690 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19691 (org-let (if nosettings nil org-agenda-exporter-settings)
19692 '(save-excursion
19693 (save-window-excursion
19694 (cond
19695 ((string-match "\\.html?\\'" file)
19696 (set-buffer (htmlize-buffer (current-buffer)))
19698 (when (and org-agenda-export-html-style
19699 (string-match "<style>" org-agenda-export-html-style))
19700 ;; replace <style> section with org-agenda-export-html-style
19701 (goto-char (point-min))
19702 (kill-region (- (search-forward "<style") 6)
19703 (search-forward "</style>"))
19704 (insert org-agenda-export-html-style))
19705 (write-file file)
19706 (kill-buffer (current-buffer))
19707 (message "HTML written to %s" file))
19708 ((string-match "\\.ps\\'" file)
19709 (ps-print-buffer-with-faces file)
19710 (message "Postscript written to %s" file))
19712 (let ((bs (buffer-string)))
19713 (find-file file)
19714 (insert bs)
19715 (save-buffer 0)
19716 (kill-buffer (current-buffer))
19717 (message "Plain text written to %s" file))))))
19718 (set-buffer org-agenda-buffer-name)))
19720 (defmacro org-no-read-only (&rest body)
19721 "Inhibit read-only for BODY."
19722 `(let ((inhibit-read-only t)) ,@body))
19724 (defun org-check-for-org-mode ()
19725 "Make sure current buffer is in org-mode. Error if not."
19726 (or (org-mode-p)
19727 (error "Cannot execute org-mode agenda command on buffer in %s."
19728 major-mode)))
19730 (defun org-fit-agenda-window ()
19731 "Fit the window to the buffer size."
19732 (and (memq org-agenda-window-setup '(reorganize-frame))
19733 (fboundp 'fit-window-to-buffer)
19734 (fit-window-to-buffer
19736 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19737 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19739 ;;; Agenda file list
19741 (defun org-agenda-files (&optional unrestricted)
19742 "Get the list of agenda files.
19743 Optional UNRESTRICTED means return the full list even if a restriction
19744 is currently in place."
19745 (let ((files
19746 (cond
19747 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19748 ((stringp org-agenda-files) (org-read-agenda-file-list))
19749 ((listp org-agenda-files) org-agenda-files)
19750 (t (error "Invalid value of `org-agenda-files'")))))
19751 (setq files (apply 'append
19752 (mapcar (lambda (f)
19753 (if (file-directory-p f)
19754 (directory-files f t
19755 org-agenda-file-regexp)
19756 (list f)))
19757 files)))
19758 (if org-agenda-skip-unavailable-files
19759 (delq nil
19760 (mapcar (function
19761 (lambda (file)
19762 (and (file-readable-p file) file)))
19763 files))
19764 files))) ; `org-check-agenda-file' will remove them from the list
19766 (defun org-edit-agenda-file-list ()
19767 "Edit the list of agenda files.
19768 Depending on setup, this either uses customize to edit the variable
19769 `org-agenda-files', or it visits the file that is holding the list. In the
19770 latter case, the buffer is set up in a way that saving it automatically kills
19771 the buffer and restores the previous window configuration."
19772 (interactive)
19773 (if (stringp org-agenda-files)
19774 (let ((cw (current-window-configuration)))
19775 (find-file org-agenda-files)
19776 (org-set-local 'org-window-configuration cw)
19777 (org-add-hook 'after-save-hook
19778 (lambda ()
19779 (set-window-configuration
19780 (prog1 org-window-configuration
19781 (kill-buffer (current-buffer))))
19782 (org-install-agenda-files-menu)
19783 (message "New agenda file list installed"))
19784 nil 'local)
19785 (message "%s" (substitute-command-keys
19786 "Edit list and finish with \\[save-buffer]")))
19787 (customize-variable 'org-agenda-files)))
19789 (defun org-store-new-agenda-file-list (list)
19790 "Set new value for the agenda file list and save it correcly."
19791 (if (stringp org-agenda-files)
19792 (let ((f org-agenda-files) b)
19793 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
19794 (with-temp-file f
19795 (insert (mapconcat 'identity list "\n") "\n")))
19796 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
19797 (setq org-agenda-files list)
19798 (customize-save-variable 'org-agenda-files org-agenda-files))))
19800 (defun org-read-agenda-file-list ()
19801 "Read the list of agenda files from a file."
19802 (when (stringp org-agenda-files)
19803 (with-temp-buffer
19804 (insert-file-contents org-agenda-files)
19805 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
19808 ;;;###autoload
19809 (defun org-cycle-agenda-files ()
19810 "Cycle through the files in `org-agenda-files'.
19811 If the current buffer visits an agenda file, find the next one in the list.
19812 If the current buffer does not, find the first agenda file."
19813 (interactive)
19814 (let* ((fs (org-agenda-files t))
19815 (files (append fs (list (car fs))))
19816 (tcf (if buffer-file-name (file-truename buffer-file-name)))
19817 file)
19818 (unless files (error "No agenda files"))
19819 (catch 'exit
19820 (while (setq file (pop files))
19821 (if (equal (file-truename file) tcf)
19822 (when (car files)
19823 (find-file (car files))
19824 (throw 'exit t))))
19825 (find-file (car fs)))
19826 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
19828 (defun org-agenda-file-to-front (&optional to-end)
19829 "Move/add the current file to the top of the agenda file list.
19830 If the file is not present in the list, it is added to the front. If it is
19831 present, it is moved there. With optional argument TO-END, add/move to the
19832 end of the list."
19833 (interactive "P")
19834 (let ((org-agenda-skip-unavailable-files nil)
19835 (file-alist (mapcar (lambda (x)
19836 (cons (file-truename x) x))
19837 (org-agenda-files t)))
19838 (ctf (file-truename buffer-file-name))
19839 x had)
19840 (setq x (assoc ctf file-alist) had x)
19842 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
19843 (if to-end
19844 (setq file-alist (append (delq x file-alist) (list x)))
19845 (setq file-alist (cons x (delq x file-alist))))
19846 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
19847 (org-install-agenda-files-menu)
19848 (message "File %s to %s of agenda file list"
19849 (if had "moved" "added") (if to-end "end" "front"))))
19851 (defun org-remove-file (&optional file)
19852 "Remove current file from the list of files in variable `org-agenda-files'.
19853 These are the files which are being checked for agenda entries.
19854 Optional argument FILE means, use this file instead of the current."
19855 (interactive)
19856 (let* ((org-agenda-skip-unavailable-files nil)
19857 (file (or file buffer-file-name))
19858 (true-file (file-truename file))
19859 (afile (abbreviate-file-name file))
19860 (files (delq nil (mapcar
19861 (lambda (x)
19862 (if (equal true-file
19863 (file-truename x))
19864 nil x))
19865 (org-agenda-files t)))))
19866 (if (not (= (length files) (length (org-agenda-files t))))
19867 (progn
19868 (org-store-new-agenda-file-list files)
19869 (org-install-agenda-files-menu)
19870 (message "Removed file: %s" afile))
19871 (message "File was not in list: %s (not removed)" afile))))
19873 (defun org-file-menu-entry (file)
19874 (vector file (list 'find-file file) t))
19876 (defun org-check-agenda-file (file)
19877 "Make sure FILE exists. If not, ask user what to do."
19878 (when (not (file-exists-p file))
19879 (message "non-existent file %s. [R]emove from list or [A]bort?"
19880 (abbreviate-file-name file))
19881 (let ((r (downcase (read-char-exclusive))))
19882 (cond
19883 ((equal r ?r)
19884 (org-remove-file file)
19885 (throw 'nextfile t))
19886 (t (error "Abort"))))))
19888 ;;; Agenda prepare and finalize
19890 (defvar org-agenda-multi nil) ; dynammically scoped
19891 (defvar org-agenda-buffer-name "*Org Agenda*")
19892 (defvar org-pre-agenda-window-conf nil)
19893 (defvar org-agenda-name nil)
19894 (defun org-prepare-agenda (&optional name)
19895 (setq org-todo-keywords-for-agenda nil)
19896 (setq org-done-keywords-for-agenda nil)
19897 (if org-agenda-multi
19898 (progn
19899 (setq buffer-read-only nil)
19900 (goto-char (point-max))
19901 (unless (or (bobp) org-agenda-compact-blocks)
19902 (insert "\n" (make-string (window-width) ?=) "\n"))
19903 (narrow-to-region (point) (point-max)))
19904 (org-agenda-maybe-reset-markers 'force)
19905 (org-prepare-agenda-buffers (org-agenda-files))
19906 (setq org-todo-keywords-for-agenda
19907 (org-uniquify org-todo-keywords-for-agenda))
19908 (setq org-done-keywords-for-agenda
19909 (org-uniquify org-done-keywords-for-agenda))
19910 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
19911 (awin (get-buffer-window abuf)))
19912 (cond
19913 ((equal (current-buffer) abuf) nil)
19914 (awin (select-window awin))
19915 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
19916 ((equal org-agenda-window-setup 'current-window)
19917 (switch-to-buffer abuf))
19918 ((equal org-agenda-window-setup 'other-window)
19919 (org-switch-to-buffer-other-window abuf))
19920 ((equal org-agenda-window-setup 'other-frame)
19921 (switch-to-buffer-other-frame abuf))
19922 ((equal org-agenda-window-setup 'reorganize-frame)
19923 (delete-other-windows)
19924 (org-switch-to-buffer-other-window abuf))))
19925 (setq buffer-read-only nil)
19926 (erase-buffer)
19927 (org-agenda-mode)
19928 (and name (not org-agenda-name)
19929 (org-set-local 'org-agenda-name name)))
19930 (setq buffer-read-only nil))
19932 (defun org-finalize-agenda ()
19933 "Finishing touch for the agenda buffer, called just before displaying it."
19934 (unless org-agenda-multi
19935 (save-excursion
19936 (let ((inhibit-read-only t))
19937 (goto-char (point-min))
19938 (while (org-activate-bracket-links (point-max))
19939 (add-text-properties (match-beginning 0) (match-end 0)
19940 '(face org-link)))
19941 (org-agenda-align-tags)
19942 (unless org-agenda-with-colors
19943 (remove-text-properties (point-min) (point-max) '(face nil))))
19944 (if (and (boundp 'org-overriding-columns-format)
19945 org-overriding-columns-format)
19946 (org-set-local 'org-overriding-columns-format
19947 org-overriding-columns-format))
19948 (if (and (boundp 'org-agenda-view-columns-initially)
19949 org-agenda-view-columns-initially)
19950 (org-agenda-columns))
19951 (when org-agenda-fontify-priorities
19952 (org-fontify-priorities))
19953 (run-hooks 'org-finalize-agenda-hook))))
19955 (defun org-fontify-priorities ()
19956 "Make highest priority lines bold, and lowest italic."
19957 (interactive)
19958 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
19959 (org-delete-overlay o)))
19960 (org-overlays-in (point-min) (point-max)))
19961 (save-excursion
19962 (let ((inhibit-read-only t)
19963 b e p ov h l)
19964 (goto-char (point-min))
19965 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
19966 (setq h (or (get-char-property (point) 'org-highest-priority)
19967 org-highest-priority)
19968 l (or (get-char-property (point) 'org-lowest-priority)
19969 org-lowest-priority)
19970 p (string-to-char (match-string 1))
19971 b (match-beginning 0) e (point-at-eol)
19972 ov (org-make-overlay b e))
19973 (org-overlay-put
19974 ov 'face
19975 (cond ((listp org-agenda-fontify-priorities)
19976 (cdr (assoc p org-agenda-fontify-priorities)))
19977 ((equal p l) 'italic)
19978 ((equal p h) 'bold)))
19979 (org-overlay-put ov 'org-type 'org-priority)))))
19981 (defun org-prepare-agenda-buffers (files)
19982 "Create buffers for all agenda files, protect archived trees and comments."
19983 (interactive)
19984 (let ((pa '(:org-archived t))
19985 (pc '(:org-comment t))
19986 (pall '(:org-archived t :org-comment t))
19987 (inhibit-read-only t)
19988 (rea (concat ":" org-archive-tag ":"))
19989 bmp file re)
19990 (save-excursion
19991 (save-restriction
19992 (while (setq file (pop files))
19993 (if (bufferp file)
19994 (set-buffer file)
19995 (org-check-agenda-file file)
19996 (set-buffer (org-get-agenda-file-buffer file)))
19997 (widen)
19998 (setq bmp (buffer-modified-p))
19999 (org-refresh-category-properties)
20000 (setq org-todo-keywords-for-agenda
20001 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20002 (setq org-done-keywords-for-agenda
20003 (append org-done-keywords-for-agenda org-done-keywords))
20004 (save-excursion
20005 (remove-text-properties (point-min) (point-max) pall)
20006 (when org-agenda-skip-archived-trees
20007 (goto-char (point-min))
20008 (while (re-search-forward rea nil t)
20009 (if (org-on-heading-p t)
20010 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20011 (goto-char (point-min))
20012 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20013 (while (re-search-forward re nil t)
20014 (add-text-properties
20015 (match-beginning 0) (org-end-of-subtree t) pc)))
20016 (set-buffer-modified-p bmp))))))
20018 (defvar org-agenda-skip-function nil
20019 "Function to be called at each match during agenda construction.
20020 If this function returns nil, the current match should not be skipped.
20021 Otherwise, the function must return a position from where the search
20022 should be continued.
20023 This may also be a Lisp form, it will be evaluated.
20024 Never set this variable using `setq' or so, because then it will apply
20025 to all future agenda commands. Instead, bind it with `let' to scope
20026 it dynamically into the agenda-constructing command. A good way to set
20027 it is through options in org-agenda-custom-commands.")
20029 (defun org-agenda-skip ()
20030 "Throw to `:skip' in places that should be skipped.
20031 Also moves point to the end of the skipped region, so that search can
20032 continue from there."
20033 (let ((p (point-at-bol)) to fp)
20034 (and org-agenda-skip-archived-trees
20035 (get-text-property p :org-archived)
20036 (org-end-of-subtree t)
20037 (throw :skip t))
20038 (and (get-text-property p :org-comment)
20039 (org-end-of-subtree t)
20040 (throw :skip t))
20041 (if (equal (char-after p) ?#) (throw :skip t))
20042 (when (and (or (setq fp (functionp org-agenda-skip-function))
20043 (consp org-agenda-skip-function))
20044 (setq to (save-excursion
20045 (save-match-data
20046 (if fp
20047 (funcall org-agenda-skip-function)
20048 (eval org-agenda-skip-function))))))
20049 (goto-char to)
20050 (throw :skip t))))
20052 (defvar org-agenda-markers nil
20053 "List of all currently active markers created by `org-agenda'.")
20054 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20055 "Creation time of the last agenda marker.")
20057 (defun org-agenda-new-marker (&optional pos)
20058 "Return a new agenda marker.
20059 Org-mode keeps a list of these markers and resets them when they are
20060 no longer in use."
20061 (let ((m (copy-marker (or pos (point)))))
20062 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20063 (push m org-agenda-markers)
20066 (defun org-agenda-maybe-reset-markers (&optional force)
20067 "Reset markers created by `org-agenda'. But only if they are old enough."
20068 (if (or (and force (not org-agenda-multi))
20069 (> (- (time-to-seconds (current-time))
20070 org-agenda-last-marker-time)
20072 (while org-agenda-markers
20073 (move-marker (pop org-agenda-markers) nil))))
20075 (defun org-get-agenda-file-buffer (file)
20076 "Get a buffer visiting FILE. If the buffer needs to be created, add
20077 it to the list of buffers which might be released later."
20078 (let ((buf (org-find-base-buffer-visiting file)))
20079 (if buf
20080 buf ; just return it
20081 ;; Make a new buffer and remember it
20082 (setq buf (find-file-noselect file))
20083 (if buf (push buf org-agenda-new-buffers))
20084 buf)))
20086 (defun org-release-buffers (blist)
20087 "Release all buffers in list, asking the user for confirmation when needed.
20088 When a buffer is unmodified, it is just killed. When modified, it is saved
20089 \(if the user agrees) and then killed."
20090 (let (buf file)
20091 (while (setq buf (pop blist))
20092 (setq file (buffer-file-name buf))
20093 (when (and (buffer-modified-p buf)
20094 file
20095 (y-or-n-p (format "Save file %s? " file)))
20096 (with-current-buffer buf (save-buffer)))
20097 (kill-buffer buf))))
20099 (defun org-get-category (&optional pos)
20100 "Get the category applying to position POS."
20101 (get-text-property (or pos (point)) 'org-category))
20103 ;;; Agenda timeline
20105 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20107 (defun org-timeline (&optional include-all)
20108 "Show a time-sorted view of the entries in the current org file.
20109 Only entries with a time stamp of today or later will be listed. With
20110 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20111 under the current date.
20112 If the buffer contains an active region, only check the region for
20113 dates."
20114 (interactive "P")
20115 (require 'calendar)
20116 (org-compile-prefix-format 'timeline)
20117 (org-set-sorting-strategy 'timeline)
20118 (let* ((dopast t)
20119 (dotodo include-all)
20120 (doclosed org-agenda-show-log)
20121 (entry buffer-file-name)
20122 (date (calendar-current-date))
20123 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20124 (end (if (org-region-active-p) (region-end) (point-max)))
20125 (day-numbers (org-get-all-dates beg end 'no-ranges
20126 t doclosed ; always include today
20127 org-timeline-show-empty-dates))
20128 (org-deadline-warning-days 0)
20129 (org-agenda-only-exact-dates t)
20130 (today (time-to-days (current-time)))
20131 (past t)
20132 args
20133 s e rtn d emptyp)
20134 (setq org-agenda-redo-command
20135 (list 'progn
20136 (list 'org-switch-to-buffer-other-window (current-buffer))
20137 (list 'org-timeline (list 'quote include-all))))
20138 (if (not dopast)
20139 ;; Remove past dates from the list of dates.
20140 (setq day-numbers (delq nil (mapcar (lambda(x)
20141 (if (>= x today) x nil))
20142 day-numbers))))
20143 (org-prepare-agenda (concat "Timeline "
20144 (file-name-nondirectory buffer-file-name)))
20145 (if doclosed (push :closed args))
20146 (push :timestamp args)
20147 (push :deadline args)
20148 (push :scheduled args)
20149 (push :sexp args)
20150 (if dotodo (push :todo args))
20151 (while (setq d (pop day-numbers))
20152 (if (and (listp d) (eq (car d) :omitted))
20153 (progn
20154 (setq s (point))
20155 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20156 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20157 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20158 (if (and (>= d today)
20159 dopast
20160 past)
20161 (progn
20162 (setq past nil)
20163 (insert (make-string 79 ?-) "\n")))
20164 (setq date (calendar-gregorian-from-absolute d))
20165 (setq s (point))
20166 (setq rtn (and (not emptyp)
20167 (apply 'org-agenda-get-day-entries entry
20168 date args)))
20169 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20170 (progn
20171 (insert
20172 (if (stringp org-agenda-format-date)
20173 (format-time-string org-agenda-format-date
20174 (org-time-from-absolute date))
20175 (funcall org-agenda-format-date date))
20176 "\n")
20177 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20178 (put-text-property s (1- (point)) 'org-date-line t)
20179 (if (equal d today)
20180 (put-text-property s (1- (point)) 'org-today t))
20181 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20182 (put-text-property s (1- (point)) 'day d)))))
20183 (goto-char (point-min))
20184 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20185 (point-min)))
20186 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20187 (org-finalize-agenda)
20188 (setq buffer-read-only t)))
20190 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
20191 "Return a list of all relevant day numbers from BEG to END buffer positions.
20192 If NO-RANGES is non-nil, include only the start and end dates of a range,
20193 not every single day in the range. If FORCE-TODAY is non-nil, make
20194 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20195 inactive time stamps (those in square brackets) are included.
20196 When EMPTY is non-nil, also include days without any entries."
20197 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
20198 dates dates1 date day day1 day2 ts1 ts2)
20199 (if force-today
20200 (setq dates (list (time-to-days (current-time)))))
20201 (save-excursion
20202 (goto-char beg)
20203 (while (re-search-forward re end t)
20204 (setq day (time-to-days (org-time-string-to-time
20205 (substring (match-string 1) 0 10))))
20206 (or (memq day dates) (push day dates)))
20207 (unless no-ranges
20208 (goto-char beg)
20209 (while (re-search-forward org-tr-regexp end t)
20210 (setq ts1 (substring (match-string 1) 0 10)
20211 ts2 (substring (match-string 2) 0 10)
20212 day1 (time-to-days (org-time-string-to-time ts1))
20213 day2 (time-to-days (org-time-string-to-time ts2)))
20214 (while (< (setq day1 (1+ day1)) day2)
20215 (or (memq day1 dates) (push day1 dates)))))
20216 (setq dates (sort dates '<))
20217 (when empty
20218 (while (setq day (pop dates))
20219 (setq day2 (car dates))
20220 (push day dates1)
20221 (when (and day2 empty)
20222 (if (or (eq empty t)
20223 (and (numberp empty) (<= (- day2 day) empty)))
20224 (while (< (setq day (1+ day)) day2)
20225 (push (list day) dates1))
20226 (push (cons :omitted (- day2 day)) dates1))))
20227 (setq dates (nreverse dates1)))
20228 dates)))
20230 ;;; Agenda Daily/Weekly
20232 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20233 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20234 (defvar org-agenda-last-arguments nil
20235 "The arguments of the previous call to org-agenda")
20236 (defvar org-starting-day nil) ; local variable in the agenda buffer
20237 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20238 (defvar org-include-all-loc nil) ; local variable
20239 (defvar org-agenda-remove-date nil) ; dynamically scoped
20241 ;;;###autoload
20242 (defun org-agenda-list (&optional include-all start-day ndays)
20243 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20244 The view will be for the current day or week, but from the overview buffer
20245 you will be able to go to other days/weeks.
20247 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20248 all unfinished TODO items will also be shown, before the agenda.
20249 This feature is considered obsolete, please use the TODO list or a block
20250 agenda instead.
20252 With a numeric prefix argument in an interactive call, the agenda will
20253 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20254 the number of days. NDAYS defaults to `org-agenda-ndays'.
20256 START-DAY defaults to TODAY, or to the most recent match for the weekday
20257 given in `org-agenda-start-on-weekday'."
20258 (interactive "P")
20259 (if (and (integerp include-all) (> include-all 0))
20260 (setq ndays include-all include-all nil))
20261 (setq ndays (or ndays org-agenda-ndays)
20262 start-day (or start-day org-agenda-start-day))
20263 (if org-agenda-overriding-arguments
20264 (setq include-all (car org-agenda-overriding-arguments)
20265 start-day (nth 1 org-agenda-overriding-arguments)
20266 ndays (nth 2 org-agenda-overriding-arguments)))
20267 (if (stringp start-day)
20268 ;; Convert to an absolute day number
20269 (setq start-day (time-to-days (org-read-date nil t start-day))))
20270 (setq org-agenda-last-arguments (list include-all start-day ndays))
20271 (org-compile-prefix-format 'agenda)
20272 (org-set-sorting-strategy 'agenda)
20273 (require 'calendar)
20274 (let* ((org-agenda-start-on-weekday
20275 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20276 org-agenda-start-on-weekday nil))
20277 (thefiles (org-agenda-files))
20278 (files thefiles)
20279 (today (time-to-days
20280 (time-subtract (current-time)
20281 (list 0 (* 3600 org-extend-today-until) 0))))
20282 (sd (or start-day today))
20283 (start (if (or (null org-agenda-start-on-weekday)
20284 (< org-agenda-ndays 7))
20286 (let* ((nt (calendar-day-of-week
20287 (calendar-gregorian-from-absolute sd)))
20288 (n1 org-agenda-start-on-weekday)
20289 (d (- nt n1)))
20290 (- sd (+ (if (< d 0) 7 0) d)))))
20291 (day-numbers (list start))
20292 (day-cnt 0)
20293 (inhibit-redisplay (not debug-on-error))
20294 s e rtn rtnall file date d start-pos end-pos todayp nd)
20295 (setq org-agenda-redo-command
20296 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20297 ;; Make the list of days
20298 (setq ndays (or ndays org-agenda-ndays)
20299 nd ndays)
20300 (while (> ndays 1)
20301 (push (1+ (car day-numbers)) day-numbers)
20302 (setq ndays (1- ndays)))
20303 (setq day-numbers (nreverse day-numbers))
20304 (org-prepare-agenda "Day/Week")
20305 (org-set-local 'org-starting-day (car day-numbers))
20306 (org-set-local 'org-include-all-loc include-all)
20307 (org-set-local 'org-agenda-span
20308 (org-agenda-ndays-to-span nd))
20309 (when (and (or include-all org-agenda-include-all-todo)
20310 (member today day-numbers))
20311 (setq files thefiles
20312 rtnall nil)
20313 (while (setq file (pop files))
20314 (catch 'nextfile
20315 (org-check-agenda-file file)
20316 (setq date (calendar-gregorian-from-absolute today)
20317 rtn (org-agenda-get-day-entries
20318 file date :todo))
20319 (setq rtnall (append rtnall rtn))))
20320 (when rtnall
20321 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20322 (add-text-properties (point-min) (1- (point))
20323 (list 'face 'org-agenda-structure))
20324 (insert (org-finalize-agenda-entries rtnall) "\n")))
20325 (unless org-agenda-compact-blocks
20326 (setq s (point))
20327 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20328 "-agenda:\n")
20329 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20330 'org-date-line t)))
20331 (while (setq d (pop day-numbers))
20332 (setq date (calendar-gregorian-from-absolute d)
20333 s (point))
20334 (if (or (setq todayp (= d today))
20335 (and (not start-pos) (= d sd)))
20336 (setq start-pos (point))
20337 (if (and start-pos (not end-pos))
20338 (setq end-pos (point))))
20339 (setq files thefiles
20340 rtnall nil)
20341 (while (setq file (pop files))
20342 (catch 'nextfile
20343 (org-check-agenda-file file)
20344 (if org-agenda-show-log
20345 (setq rtn (org-agenda-get-day-entries
20346 file date
20347 :deadline :scheduled :timestamp :sexp :closed))
20348 (setq rtn (org-agenda-get-day-entries
20349 file date
20350 :deadline :scheduled :sexp :timestamp)))
20351 (setq rtnall (append rtnall rtn))))
20352 (if org-agenda-include-diary
20353 (progn
20354 (require 'diary-lib)
20355 (setq rtn (org-get-entries-from-diary date))
20356 (setq rtnall (append rtnall rtn))))
20357 (if (or rtnall org-agenda-show-all-dates)
20358 (progn
20359 (setq day-cnt (1+ day-cnt))
20360 (insert
20361 (if (stringp org-agenda-format-date)
20362 (format-time-string org-agenda-format-date
20363 (org-time-from-absolute date))
20364 (funcall org-agenda-format-date date))
20365 "\n")
20366 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20367 (put-text-property s (1- (point)) 'org-date-line t)
20368 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20369 (if todayp (put-text-property s (1- (point)) 'org-today t))
20370 (if rtnall (insert
20371 (org-finalize-agenda-entries
20372 (org-agenda-add-time-grid-maybe
20373 rtnall nd todayp))
20374 "\n"))
20375 (put-text-property s (1- (point)) 'day d)
20376 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20377 (goto-char (point-min))
20378 (org-fit-agenda-window)
20379 (unless (and (pos-visible-in-window-p (point-min))
20380 (pos-visible-in-window-p (point-max)))
20381 (goto-char (1- (point-max)))
20382 (recenter -1)
20383 (if (not (pos-visible-in-window-p (or start-pos 1)))
20384 (progn
20385 (goto-char (or start-pos 1))
20386 (recenter 1))))
20387 (goto-char (or start-pos 1))
20388 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20389 (org-finalize-agenda)
20390 (setq buffer-read-only t)
20391 (message "")))
20393 (defun org-agenda-ndays-to-span (n)
20394 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20396 ;;; Agenda TODO list
20398 (defvar org-select-this-todo-keyword nil)
20399 (defvar org-last-arg nil)
20401 ;;;###autoload
20402 (defun org-todo-list (arg)
20403 "Show all TODO entries from all agenda file in a single list.
20404 The prefix arg can be used to select a specific TODO keyword and limit
20405 the list to these. When using \\[universal-argument], you will be prompted
20406 for a keyword. A numeric prefix directly selects the Nth keyword in
20407 `org-todo-keywords-1'."
20408 (interactive "P")
20409 (require 'calendar)
20410 (org-compile-prefix-format 'todo)
20411 (org-set-sorting-strategy 'todo)
20412 (org-prepare-agenda "TODO")
20413 (let* ((today (time-to-days (current-time)))
20414 (date (calendar-gregorian-from-absolute today))
20415 (kwds org-todo-keywords-for-agenda)
20416 (completion-ignore-case t)
20417 (org-select-this-todo-keyword
20418 (if (stringp arg) arg
20419 (and arg (integerp arg) (> arg 0)
20420 (nth (1- arg) kwds))))
20421 rtn rtnall files file pos)
20422 (when (equal arg '(4))
20423 (setq org-select-this-todo-keyword
20424 (completing-read "Keyword (or KWD1|K2D2|...): "
20425 (mapcar 'list kwds) nil nil)))
20426 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20427 (org-set-local 'org-last-arg arg)
20428 (setq org-agenda-redo-command
20429 '(org-todo-list (or current-prefix-arg org-last-arg)))
20430 (setq files (org-agenda-files)
20431 rtnall nil)
20432 (while (setq file (pop files))
20433 (catch 'nextfile
20434 (org-check-agenda-file file)
20435 (setq rtn (org-agenda-get-day-entries file date :todo))
20436 (setq rtnall (append rtnall rtn))))
20437 (if org-agenda-overriding-header
20438 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20439 nil 'face 'org-agenda-structure) "\n")
20440 (insert "Global list of TODO items of type: ")
20441 (add-text-properties (point-min) (1- (point))
20442 (list 'face 'org-agenda-structure))
20443 (setq pos (point))
20444 (insert (or org-select-this-todo-keyword "ALL") "\n")
20445 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20446 (setq pos (point))
20447 (unless org-agenda-multi
20448 (insert "Available with `N r': (0)ALL")
20449 (let ((n 0) s)
20450 (mapc (lambda (x)
20451 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20452 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20453 (insert "\n "))
20454 (insert " " s))
20455 kwds))
20456 (insert "\n"))
20457 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20458 (when rtnall
20459 (insert (org-finalize-agenda-entries rtnall) "\n"))
20460 (goto-char (point-min))
20461 (org-fit-agenda-window)
20462 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20463 (org-finalize-agenda)
20464 (setq buffer-read-only t)))
20466 ;;; Agenda tags match
20468 ;;;###autoload
20469 (defun org-tags-view (&optional todo-only match)
20470 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20471 The prefix arg TODO-ONLY limits the search to TODO entries."
20472 (interactive "P")
20473 (org-compile-prefix-format 'tags)
20474 (org-set-sorting-strategy 'tags)
20475 (let* ((org-tags-match-list-sublevels
20476 (if todo-only t org-tags-match-list-sublevels))
20477 (completion-ignore-case t)
20478 rtn rtnall files file pos matcher
20479 buffer)
20480 (setq matcher (org-make-tags-matcher match)
20481 match (car matcher) matcher (cdr matcher))
20482 (org-prepare-agenda (concat "TAGS " match))
20483 (setq org-agenda-redo-command
20484 (list 'org-tags-view (list 'quote todo-only)
20485 (list 'if 'current-prefix-arg nil match)))
20486 (setq files (org-agenda-files)
20487 rtnall nil)
20488 (while (setq file (pop files))
20489 (catch 'nextfile
20490 (org-check-agenda-file file)
20491 (setq buffer (if (file-exists-p file)
20492 (org-get-agenda-file-buffer file)
20493 (error "No such file %s" file)))
20494 (if (not buffer)
20495 ;; If file does not exist, merror message to agenda
20496 (setq rtn (list
20497 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20498 rtnall (append rtnall rtn))
20499 (with-current-buffer buffer
20500 (unless (org-mode-p)
20501 (error "Agenda file %s is not in `org-mode'" file))
20502 (save-excursion
20503 (save-restriction
20504 (if org-agenda-restrict
20505 (narrow-to-region org-agenda-restrict-begin
20506 org-agenda-restrict-end)
20507 (widen))
20508 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20509 (setq rtnall (append rtnall rtn))))))))
20510 (if org-agenda-overriding-header
20511 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20512 nil 'face 'org-agenda-structure) "\n")
20513 (insert "Headlines with TAGS match: ")
20514 (add-text-properties (point-min) (1- (point))
20515 (list 'face 'org-agenda-structure))
20516 (setq pos (point))
20517 (insert match "\n")
20518 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20519 (setq pos (point))
20520 (unless org-agenda-multi
20521 (insert "Press `C-u r' to search again with new search string\n"))
20522 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20523 (when rtnall
20524 (insert (org-finalize-agenda-entries rtnall) "\n"))
20525 (goto-char (point-min))
20526 (org-fit-agenda-window)
20527 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20528 (org-finalize-agenda)
20529 (setq buffer-read-only t)))
20531 ;;; Agenda Finding stuck projects
20533 (defvar org-agenda-skip-regexp nil
20534 "Regular expression used in skipping subtrees for the agenda.
20535 This is basically a temporary global variable that can be set and then
20536 used by user-defined selections using `org-agenda-skip-function'.")
20538 (defvar org-agenda-overriding-header nil
20539 "When this is set during todo and tags searches, will replace header.")
20541 (defun org-agenda-skip-subtree-when-regexp-matches ()
20542 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20543 If yes, it returns the end position of this tree, causing agenda commands
20544 to skip this subtree. This is a function that can be put into
20545 `org-agenda-skip-function' for the duration of a command."
20546 (let ((end (save-excursion (org-end-of-subtree t)))
20547 skip)
20548 (save-excursion
20549 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20550 (and skip end)))
20552 (defun org-agenda-skip-entry-if (&rest conditions)
20553 "Skip entry if any of CONDITIONS is true.
20554 See `org-agenda-skip-if' for details."
20555 (org-agenda-skip-if nil conditions))
20557 (defun org-agenda-skip-subtree-if (&rest conditions)
20558 "Skip entry if any of CONDITIONS is true.
20559 See `org-agenda-skip-if' for details."
20560 (org-agenda-skip-if t conditions))
20562 (defun org-agenda-skip-if (subtree conditions)
20563 "Checks current entity for CONDITIONS.
20564 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20565 the entry, i.e. the text before the next heading is checked.
20567 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20568 from different tests. Valid conditions are:
20570 scheduled Check if there is a scheduled cookie
20571 notscheduled Check if there is no scheduled cookie
20572 deadline Check if there is a deadline
20573 notdeadline Check if there is no deadline
20574 regexp Check if regexp matches
20575 notregexp Check if regexp does not match.
20577 The regexp is taken from the conditions list, it must come right after
20578 the `regexp' or `notregexp' element.
20580 If any of these conditions is met, this function returns the end point of
20581 the entity, causing the search to continue from there. This is a function
20582 that can be put into `org-agenda-skip-function' for the duration of a command."
20583 (let (beg end m)
20584 (org-back-to-heading t)
20585 (setq beg (point)
20586 end (if subtree
20587 (progn (org-end-of-subtree t) (point))
20588 (progn (outline-next-heading) (1- (point)))))
20589 (goto-char beg)
20590 (and
20592 (and (memq 'scheduled conditions)
20593 (re-search-forward org-scheduled-time-regexp end t))
20594 (and (memq 'notscheduled conditions)
20595 (not (re-search-forward org-scheduled-time-regexp end t)))
20596 (and (memq 'deadline conditions)
20597 (re-search-forward org-deadline-time-regexp end t))
20598 (and (memq 'notdeadline conditions)
20599 (not (re-search-forward org-deadline-time-regexp end t)))
20600 (and (setq m (memq 'regexp conditions))
20601 (stringp (nth 1 m))
20602 (re-search-forward (nth 1 m) end t))
20603 (and (setq m (memq 'notregexp conditions))
20604 (stringp (nth 1 m))
20605 (not (re-search-forward (nth 1 m) end t))))
20606 end)))
20608 ;;;###autoload
20609 (defun org-agenda-list-stuck-projects (&rest ignore)
20610 "Create agenda view for projects that are stuck.
20611 Stuck projects are project that have no next actions. For the definitions
20612 of what a project is and how to check if it stuck, customize the variable
20613 `org-stuck-projects'.
20614 MATCH is being ignored."
20615 (interactive)
20616 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20617 ;; FIXME: we could have used org-agenda-skip-if here.
20618 (org-agenda-overriding-header "List of stuck projects: ")
20619 (matcher (nth 0 org-stuck-projects))
20620 (todo (nth 1 org-stuck-projects))
20621 (todo-wds (if (member "*" todo)
20622 (progn
20623 (org-prepare-agenda-buffers (org-agenda-files))
20624 (org-delete-all
20625 org-done-keywords-for-agenda
20626 (copy-sequence org-todo-keywords-for-agenda)))
20627 todo))
20628 (todo-re (concat "^\\*+[ \t]+\\("
20629 (mapconcat 'identity todo-wds "\\|")
20630 "\\)\\>"))
20631 (tags (nth 2 org-stuck-projects))
20632 (tags-re (if (member "*" tags)
20633 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20634 (concat "^\\*+ .*:\\("
20635 (mapconcat 'identity tags "\\|")
20636 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20637 (gen-re (nth 3 org-stuck-projects))
20638 (re-list
20639 (delq nil
20640 (list
20641 (if todo todo-re)
20642 (if tags tags-re)
20643 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20644 gen-re)))))
20645 (setq org-agenda-skip-regexp
20646 (if re-list
20647 (mapconcat 'identity re-list "\\|")
20648 (error "No information how to identify unstuck projects")))
20649 (org-tags-view nil matcher)
20650 (with-current-buffer org-agenda-buffer-name
20651 (setq org-agenda-redo-command
20652 '(org-agenda-list-stuck-projects
20653 (or current-prefix-arg org-last-arg))))))
20655 ;;; Diary integration
20657 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20659 (defun org-get-entries-from-diary (date)
20660 "Get the (Emacs Calendar) diary entries for DATE."
20661 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20662 (diary-display-hook '(fancy-diary-display))
20663 (pop-up-frames nil)
20664 (list-diary-entries-hook
20665 (cons 'org-diary-default-entry list-diary-entries-hook))
20666 (diary-file-name-prefix-function nil) ; turn this feature off
20667 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20668 entries
20669 (org-disable-agenda-to-diary t))
20670 (save-excursion
20671 (save-window-excursion
20672 (funcall (if (fboundp 'diary-list-entries)
20673 'diary-list-entries 'list-diary-entries)
20674 date 1)))
20675 (if (not (get-buffer fancy-diary-buffer))
20676 (setq entries nil)
20677 (with-current-buffer fancy-diary-buffer
20678 (setq buffer-read-only nil)
20679 (if (zerop (buffer-size))
20680 ;; No entries
20681 (setq entries nil)
20682 ;; Omit the date and other unnecessary stuff
20683 (org-agenda-cleanup-fancy-diary)
20684 ;; Add prefix to each line and extend the text properties
20685 (if (zerop (buffer-size))
20686 (setq entries nil)
20687 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20688 (set-buffer-modified-p nil)
20689 (kill-buffer fancy-diary-buffer)))
20690 (when entries
20691 (setq entries (org-split-string entries "\n"))
20692 (setq entries
20693 (mapcar
20694 (lambda (x)
20695 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20696 ;; Extend the text properties to the beginning of the line
20697 (org-add-props x (text-properties-at (1- (length x)) x)
20698 'type "diary" 'date date))
20699 entries)))))
20701 (defun org-agenda-cleanup-fancy-diary ()
20702 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20703 This gets rid of the date, the underline under the date, and
20704 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20705 date. It also removes lines that contain only whitespace."
20706 (goto-char (point-min))
20707 (if (looking-at ".*?:[ \t]*")
20708 (progn
20709 (replace-match "")
20710 (re-search-forward "\n=+$" nil t)
20711 (replace-match "")
20712 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20713 (re-search-forward "\n=+$" nil t)
20714 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20715 (goto-char (point-min))
20716 (while (re-search-forward "^ +\n" nil t)
20717 (replace-match ""))
20718 (goto-char (point-min))
20719 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20720 (replace-match "")))
20722 ;; Make sure entries from the diary have the right text properties.
20723 (eval-after-load "diary-lib"
20724 '(if (boundp 'diary-modify-entry-list-string-function)
20725 ;; We can rely on the hook, nothing to do
20727 ;; Hook not avaiable, must use advice to make this work
20728 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20729 "Make the position visible."
20730 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20731 (stringp string)
20732 buffer-file-name)
20733 (setq string (org-modify-diary-entry-string string))))))
20735 (defun org-modify-diary-entry-string (string)
20736 "Add text properties to string, allowing org-mode to act on it."
20737 (org-add-props string nil
20738 'mouse-face 'highlight
20739 'keymap org-agenda-keymap
20740 'help-echo (if buffer-file-name
20741 (format "mouse-2 or RET jump to diary file %s"
20742 (abbreviate-file-name buffer-file-name))
20744 'org-agenda-diary-link t
20745 'org-marker (org-agenda-new-marker (point-at-bol))))
20747 (defun org-diary-default-entry ()
20748 "Add a dummy entry to the diary.
20749 Needed to avoid empty dates which mess up holiday display."
20750 ;; Catch the error if dealing with the new add-to-diary-alist
20751 (when org-disable-agenda-to-diary
20752 (condition-case nil
20753 (add-to-diary-list original-date "Org-mode dummy" "")
20754 (error
20755 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
20757 ;;;###autoload
20758 (defun org-diary (&rest args)
20759 "Return diary information from org-files.
20760 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
20761 It accesses org files and extracts information from those files to be
20762 listed in the diary. The function accepts arguments specifying what
20763 items should be listed. The following arguments are allowed:
20765 :timestamp List the headlines of items containing a date stamp or
20766 date range matching the selected date. Deadlines will
20767 also be listed, on the expiration day.
20769 :sexp List entries resulting from diary-like sexps.
20771 :deadline List any deadlines past due, or due within
20772 `org-deadline-warning-days'. The listing occurs only
20773 in the diary for *today*, not at any other date. If
20774 an entry is marked DONE, it is no longer listed.
20776 :scheduled List all items which are scheduled for the given date.
20777 The diary for *today* also contains items which were
20778 scheduled earlier and are not yet marked DONE.
20780 :todo List all TODO items from the org-file. This may be a
20781 long list - so this is not turned on by default.
20782 Like deadlines, these entries only show up in the
20783 diary for *today*, not at any other date.
20785 The call in the diary file should look like this:
20787 &%%(org-diary) ~/path/to/some/orgfile.org
20789 Use a separate line for each org file to check. Or, if you omit the file name,
20790 all files listed in `org-agenda-files' will be checked automatically:
20792 &%%(org-diary)
20794 If you don't give any arguments (as in the example above), the default
20795 arguments (:deadline :scheduled :timestamp :sexp) are used.
20796 So the example above may also be written as
20798 &%%(org-diary :deadline :timestamp :sexp :scheduled)
20800 The function expects the lisp variables `entry' and `date' to be provided
20801 by the caller, because this is how the calendar works. Don't use this
20802 function from a program - use `org-agenda-get-day-entries' instead."
20803 (org-agenda-maybe-reset-markers)
20804 (org-compile-prefix-format 'agenda)
20805 (org-set-sorting-strategy 'agenda)
20806 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20807 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
20808 (list entry)
20809 (org-agenda-files t)))
20810 file rtn results)
20811 (org-prepare-agenda-buffers files)
20812 ;; If this is called during org-agenda, don't return any entries to
20813 ;; the calendar. Org Agenda will list these entries itself.
20814 (if org-disable-agenda-to-diary (setq files nil))
20815 (while (setq file (pop files))
20816 (setq rtn (apply 'org-agenda-get-day-entries file date args))
20817 (setq results (append results rtn)))
20818 (if results
20819 (concat (org-finalize-agenda-entries results) "\n"))))
20821 ;;; Agenda entry finders
20823 (defun org-agenda-get-day-entries (file date &rest args)
20824 "Does the work for `org-diary' and `org-agenda'.
20825 FILE is the path to a file to be checked for entries. DATE is date like
20826 the one returned by `calendar-current-date'. ARGS are symbols indicating
20827 which kind of entries should be extracted. For details about these, see
20828 the documentation of `org-diary'."
20829 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20830 (let* ((org-startup-folded nil)
20831 (org-startup-align-all-tables nil)
20832 (buffer (if (file-exists-p file)
20833 (org-get-agenda-file-buffer file)
20834 (error "No such file %s" file)))
20835 arg results rtn)
20836 (if (not buffer)
20837 ;; If file does not exist, make sure an error message ends up in diary
20838 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20839 (with-current-buffer buffer
20840 (unless (org-mode-p)
20841 (error "Agenda file %s is not in `org-mode'" file))
20842 (let ((case-fold-search nil))
20843 (save-excursion
20844 (save-restriction
20845 (if org-agenda-restrict
20846 (narrow-to-region org-agenda-restrict-begin
20847 org-agenda-restrict-end)
20848 (widen))
20849 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
20850 (while (setq arg (pop args))
20851 (cond
20852 ((and (eq arg :todo)
20853 (equal date (calendar-current-date)))
20854 (setq rtn (org-agenda-get-todos))
20855 (setq results (append results rtn)))
20856 ((eq arg :timestamp)
20857 (setq rtn (org-agenda-get-blocks))
20858 (setq results (append results rtn))
20859 (setq rtn (org-agenda-get-timestamps))
20860 (setq results (append results rtn)))
20861 ((eq arg :sexp)
20862 (setq rtn (org-agenda-get-sexps))
20863 (setq results (append results rtn)))
20864 ((eq arg :scheduled)
20865 (setq rtn (org-agenda-get-scheduled))
20866 (setq results (append results rtn)))
20867 ((eq arg :closed)
20868 (setq rtn (org-agenda-get-closed))
20869 (setq results (append results rtn)))
20870 ((eq arg :deadline)
20871 (setq rtn (org-agenda-get-deadlines))
20872 (setq results (append results rtn))))))))
20873 results))))
20875 (defun org-entry-is-todo-p ()
20876 (member (org-get-todo-state) org-not-done-keywords))
20878 (defun org-entry-is-done-p ()
20879 (member (org-get-todo-state) org-done-keywords))
20881 (defun org-get-todo-state ()
20882 (save-excursion
20883 (org-back-to-heading t)
20884 (and (looking-at org-todo-line-regexp)
20885 (match-end 2)
20886 (match-string 2))))
20888 (defun org-at-date-range-p (&optional inactive-ok)
20889 "Is the cursor inside a date range?"
20890 (interactive)
20891 (save-excursion
20892 (catch 'exit
20893 (let ((pos (point)))
20894 (skip-chars-backward "^[<\r\n")
20895 (skip-chars-backward "<[")
20896 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20897 (>= (match-end 0) pos)
20898 (throw 'exit t))
20899 (skip-chars-backward "^<[\r\n")
20900 (skip-chars-backward "<[")
20901 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20902 (>= (match-end 0) pos)
20903 (throw 'exit t)))
20904 nil)))
20906 (defun org-agenda-get-todos ()
20907 "Return the TODO information for agenda display."
20908 (let* ((props (list 'face nil
20909 'done-face 'org-done
20910 'org-not-done-regexp org-not-done-regexp
20911 'org-todo-regexp org-todo-regexp
20912 'mouse-face 'highlight
20913 'keymap org-agenda-keymap
20914 'help-echo
20915 (format "mouse-2 or RET jump to org file %s"
20916 (abbreviate-file-name buffer-file-name))))
20917 ;; FIXME: get rid of the \n at some point but watch out
20918 (regexp (concat "^\\*+[ \t]+\\("
20919 (if org-select-this-todo-keyword
20920 (if (equal org-select-this-todo-keyword "*")
20921 org-todo-regexp
20922 (concat "\\<\\("
20923 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
20924 "\\)\\>"))
20925 org-not-done-regexp)
20926 "[^\n\r]*\\)"))
20927 marker priority category tags
20928 ee txt beg end)
20929 (goto-char (point-min))
20930 (while (re-search-forward regexp nil t)
20931 (catch :skip
20932 (save-match-data
20933 (beginning-of-line)
20934 (setq beg (point) end (progn (outline-next-heading) (point)))
20935 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
20936 (re-search-forward org-ts-regexp end t))
20937 (and org-agenda-todo-ignore-scheduled (goto-char beg)
20938 (re-search-forward org-scheduled-time-regexp end t))
20939 (and org-agenda-todo-ignore-deadlines (goto-char beg)
20940 (re-search-forward org-deadline-time-regexp end t)
20941 (org-deadline-close (match-string 1))))
20942 (goto-char (1+ beg))
20943 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
20944 (throw :skip nil)))
20945 (goto-char beg)
20946 (org-agenda-skip)
20947 (goto-char (match-beginning 1))
20948 (setq marker (org-agenda-new-marker (match-beginning 0))
20949 category (org-get-category)
20950 tags (org-get-tags-at (point))
20951 txt (org-format-agenda-item "" (match-string 1) category tags)
20952 priority (1+ (org-get-priority txt)))
20953 (org-add-props txt props
20954 'org-marker marker 'org-hd-marker marker
20955 'priority priority 'org-category category
20956 'type "todo")
20957 (push txt ee)
20958 (if org-agenda-todo-list-sublevels
20959 (goto-char (match-end 1))
20960 (org-end-of-subtree 'invisible))))
20961 (nreverse ee)))
20963 (defconst org-agenda-no-heading-message
20964 "No heading for this item in buffer or region.")
20966 (defun org-agenda-get-timestamps ()
20967 "Return the date stamp information for agenda display."
20968 (let* ((props (list 'face nil
20969 'org-not-done-regexp org-not-done-regexp
20970 'org-todo-regexp org-todo-regexp
20971 'mouse-face 'highlight
20972 'keymap org-agenda-keymap
20973 'help-echo
20974 (format "mouse-2 or RET jump to org file %s"
20975 (abbreviate-file-name buffer-file-name))))
20976 (d1 (calendar-absolute-from-gregorian date))
20977 (remove-re
20978 (concat
20979 (regexp-quote
20980 (format-time-string
20981 "<%Y-%m-%d"
20982 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20983 ".*?>"))
20984 (regexp
20985 (concat
20986 (regexp-quote
20987 (substring
20988 (format-time-string
20989 (car org-time-stamp-formats)
20990 (apply 'encode-time ; DATE bound by calendar
20991 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20992 0 11))
20993 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
20994 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
20995 marker hdmarker deadlinep scheduledp donep tmp priority category
20996 ee txt timestr tags b0 b3 e3 head)
20997 (goto-char (point-min))
20998 (while (re-search-forward regexp nil t)
20999 (setq b0 (match-beginning 0)
21000 b3 (match-beginning 3) e3 (match-end 3))
21001 (catch :skip
21002 (and (org-at-date-range-p) (throw :skip nil))
21003 (org-agenda-skip)
21004 (if (and (match-end 1)
21005 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21006 (throw :skip nil))
21007 (if (and e3
21008 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21009 (throw :skip nil))
21010 (setq marker (org-agenda-new-marker b0)
21011 category (org-get-category b0)
21012 tmp (buffer-substring (max (point-min)
21013 (- b0 org-ds-keyword-length))
21015 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21016 deadlinep (string-match org-deadline-regexp tmp)
21017 scheduledp (string-match org-scheduled-regexp tmp)
21018 donep (org-entry-is-done-p))
21019 (if (or scheduledp deadlinep) (throw :skip t))
21020 (if (string-match ">" timestr)
21021 ;; substring should only run to end of time stamp
21022 (setq timestr (substring timestr 0 (match-end 0))))
21023 (save-excursion
21024 (if (re-search-backward "^\\*+ " nil t)
21025 (progn
21026 (goto-char (match-beginning 0))
21027 (setq hdmarker (org-agenda-new-marker)
21028 tags (org-get-tags-at))
21029 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21030 (setq head (match-string 1))
21031 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21032 (setq txt (org-format-agenda-item
21033 nil head category tags timestr nil
21034 remove-re)))
21035 (setq txt org-agenda-no-heading-message))
21036 (setq priority (org-get-priority txt))
21037 (org-add-props txt props
21038 'org-marker marker 'org-hd-marker hdmarker)
21039 (org-add-props txt nil 'priority priority
21040 'org-category category 'date date
21041 'type "timestamp")
21042 (push txt ee))
21043 (outline-next-heading)))
21044 (nreverse ee)))
21046 (defun org-agenda-get-sexps ()
21047 "Return the sexp information for agenda display."
21048 (require 'diary-lib)
21049 (let* ((props (list 'face nil
21050 'mouse-face 'highlight
21051 'keymap org-agenda-keymap
21052 'help-echo
21053 (format "mouse-2 or RET jump to org file %s"
21054 (abbreviate-file-name buffer-file-name))))
21055 (regexp "^&?%%(")
21056 marker category ee txt tags entry result beg b sexp sexp-entry)
21057 (goto-char (point-min))
21058 (while (re-search-forward regexp nil t)
21059 (catch :skip
21060 (org-agenda-skip)
21061 (setq beg (match-beginning 0))
21062 (goto-char (1- (match-end 0)))
21063 (setq b (point))
21064 (forward-sexp 1)
21065 (setq sexp (buffer-substring b (point)))
21066 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21067 (org-trim (match-string 1))
21068 ""))
21069 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21070 (when result
21071 (setq marker (org-agenda-new-marker beg)
21072 category (org-get-category beg))
21074 (if (string-match "\\S-" result)
21075 (setq txt result)
21076 (setq txt "SEXP entry returned empty string"))
21078 (setq txt (org-format-agenda-item
21079 "" txt category tags 'time))
21080 (org-add-props txt props 'org-marker marker)
21081 (org-add-props txt nil
21082 'org-category category 'date date
21083 'type "sexp")
21084 (push txt ee))))
21085 (nreverse ee)))
21087 (defun org-agenda-get-closed ()
21088 "Return the logged TODO entries for agenda display."
21089 (let* ((props (list 'mouse-face 'highlight
21090 'org-not-done-regexp org-not-done-regexp
21091 'org-todo-regexp org-todo-regexp
21092 'keymap org-agenda-keymap
21093 'help-echo
21094 (format "mouse-2 or RET jump to org file %s"
21095 (abbreviate-file-name buffer-file-name))))
21096 (regexp (concat
21097 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21098 (regexp-quote
21099 (substring
21100 (format-time-string
21101 (car org-time-stamp-formats)
21102 (apply 'encode-time ; DATE bound by calendar
21103 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21104 1 11))))
21105 marker hdmarker priority category tags closedp
21106 ee txt timestr)
21107 (goto-char (point-min))
21108 (while (re-search-forward regexp nil t)
21109 (catch :skip
21110 (org-agenda-skip)
21111 (setq marker (org-agenda-new-marker (match-beginning 0))
21112 closedp (equal (match-string 1) org-closed-string)
21113 category (org-get-category (match-beginning 0))
21114 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21115 ;; donep (org-entry-is-done-p)
21117 (if (string-match "\\]" timestr)
21118 ;; substring should only run to end of time stamp
21119 (setq timestr (substring timestr 0 (match-end 0))))
21120 (save-excursion
21121 (if (re-search-backward "^\\*+ " nil t)
21122 (progn
21123 (goto-char (match-beginning 0))
21124 (setq hdmarker (org-agenda-new-marker)
21125 tags (org-get-tags-at))
21126 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21127 (setq txt (org-format-agenda-item
21128 (if closedp "Closed: " "Clocked: ")
21129 (match-string 1) category tags timestr)))
21130 (setq txt org-agenda-no-heading-message))
21131 (setq priority 100000)
21132 (org-add-props txt props
21133 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21134 'priority priority 'org-category category
21135 'type "closed" 'date date
21136 'undone-face 'org-warning 'done-face 'org-done)
21137 (push txt ee))
21138 (outline-next-heading)))
21139 (nreverse ee)))
21141 (defun org-agenda-get-deadlines ()
21142 "Return the deadline information for agenda display."
21143 (let* ((props (list 'mouse-face 'highlight
21144 'org-not-done-regexp org-not-done-regexp
21145 'org-todo-regexp org-todo-regexp
21146 'keymap org-agenda-keymap
21147 'help-echo
21148 (format "mouse-2 or RET jump to org file %s"
21149 (abbreviate-file-name buffer-file-name))))
21150 (regexp org-deadline-time-regexp)
21151 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21152 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21153 d2 diff dfrac wdays pos pos1 category tags
21154 ee txt head face s upcomingp donep timestr)
21155 (goto-char (point-min))
21156 (while (re-search-forward regexp nil t)
21157 (catch :skip
21158 (org-agenda-skip)
21159 (setq s (match-string 1)
21160 pos (1- (match-beginning 1))
21161 d2 (org-time-string-to-absolute (match-string 1) d1)
21162 diff (- d2 d1)
21163 wdays (org-get-wdays s)
21164 dfrac (/ (* 1.0 (- wdays diff)) wdays)
21165 upcomingp (and todayp (> diff 0)))
21166 ;; When to show a deadline in the calendar:
21167 ;; If the expiration is within wdays warning time.
21168 ;; Past-due deadlines are only shown on the current date
21169 (if (or (and (<= diff wdays)
21170 (and todayp (not org-agenda-only-exact-dates)))
21171 (= diff 0))
21172 (save-excursion
21173 (setq category (org-get-category))
21174 (if (re-search-backward "^\\*+[ \t]+" nil t)
21175 (progn
21176 (goto-char (match-end 0))
21177 (setq pos1 (match-beginning 0))
21178 (setq tags (org-get-tags-at pos1))
21179 (setq head (buffer-substring-no-properties
21180 (point)
21181 (progn (skip-chars-forward "^\r\n")
21182 (point))))
21183 (setq donep (string-match org-looking-at-done-regexp head))
21184 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21185 (setq timestr
21186 (concat (substring s (match-beginning 1)) " "))
21187 (setq timestr 'time))
21188 (if (and donep
21189 (or org-agenda-skip-deadline-if-done
21190 (not (= diff 0))))
21191 (setq txt nil)
21192 (setq txt (org-format-agenda-item
21193 (if (= diff 0)
21194 (car org-agenda-deadline-leaders)
21195 (format (nth 1 org-agenda-deadline-leaders)
21196 diff))
21197 head category tags timestr))))
21198 (setq txt org-agenda-no-heading-message))
21199 (when txt
21200 (setq face (org-agenda-deadline-face dfrac))
21201 (org-add-props txt props
21202 'org-marker (org-agenda-new-marker pos)
21203 'org-hd-marker (org-agenda-new-marker pos1)
21204 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
21205 (org-get-priority txt))
21206 'org-category category
21207 'type (if upcomingp "upcoming-deadline" "deadline")
21208 'date (if upcomingp date d2)
21209 'face (if donep 'org-done face)
21210 'undone-face face 'done-face 'org-done)
21211 (push txt ee))))))
21212 (nreverse ee)))
21214 (defun org-agenda-deadline-face (fraction)
21215 "Return the face to displaying a deadline item.
21216 FRACTION is what fraction of the head-warning time has passed."
21217 (let ((faces org-agenda-deadline-faces) f)
21218 (catch 'exit
21219 (while (setq f (pop faces))
21220 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21222 (defun org-agenda-get-scheduled ()
21223 "Return the scheduled information for agenda display."
21224 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21225 'org-todo-regexp org-todo-regexp
21226 'done-face 'org-done
21227 'mouse-face 'highlight
21228 'keymap org-agenda-keymap
21229 'help-echo
21230 (format "mouse-2 or RET jump to org file %s"
21231 (abbreviate-file-name buffer-file-name))))
21232 (regexp org-scheduled-time-regexp)
21233 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21234 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21235 d2 diff pos pos1 category tags
21236 ee txt head pastschedp donep face timestr s)
21237 (goto-char (point-min))
21238 (while (re-search-forward regexp nil t)
21239 (catch :skip
21240 (org-agenda-skip)
21241 (setq s (match-string 1)
21242 pos (1- (match-beginning 1))
21243 d2 (org-time-string-to-absolute (match-string 1) d1)
21244 diff (- d2 d1))
21245 (setq pastschedp (and todayp (< diff 0)))
21246 ;; When to show a scheduled item in the calendar:
21247 ;; If it is on or past the date.
21248 (if (or (and (< diff 0)
21249 (and todayp (not org-agenda-only-exact-dates)))
21250 (= diff 0))
21251 (save-excursion
21252 (setq category (org-get-category))
21253 (if (re-search-backward "^\\*+[ \t]+" nil t)
21254 (progn
21255 (goto-char (match-end 0))
21256 (setq pos1 (match-beginning 0))
21257 (setq tags (org-get-tags-at))
21258 (setq head (buffer-substring-no-properties
21259 (point)
21260 (progn (skip-chars-forward "^\r\n") (point))))
21261 (setq donep (string-match org-looking-at-done-regexp head))
21262 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21263 (setq timestr
21264 (concat (substring s (match-beginning 1)) " "))
21265 (setq timestr 'time))
21266 (if (and donep
21267 (or org-agenda-skip-scheduled-if-done
21268 (not (= diff 0))))
21269 (setq txt nil)
21270 (setq txt (org-format-agenda-item
21271 (if (= diff 0)
21272 (car org-agenda-scheduled-leaders)
21273 (format (nth 1 org-agenda-scheduled-leaders)
21274 (- 1 diff)))
21275 head category tags timestr))))
21276 (setq txt org-agenda-no-heading-message))
21277 (when txt
21278 (setq face (if pastschedp
21279 'org-scheduled-previously
21280 'org-scheduled-today))
21281 (org-add-props txt props
21282 'undone-face face
21283 'face (if donep 'org-done face)
21284 'org-marker (org-agenda-new-marker pos)
21285 'org-hd-marker (org-agenda-new-marker pos1)
21286 'type (if pastschedp "past-scheduled" "scheduled")
21287 'date (if pastschedp d2 date)
21288 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21289 'org-category category)
21290 (push txt ee))))))
21291 (nreverse ee)))
21293 (defun org-agenda-get-blocks ()
21294 "Return the date-range information for agenda display."
21295 (let* ((props (list 'face nil
21296 'org-not-done-regexp org-not-done-regexp
21297 'org-todo-regexp org-todo-regexp
21298 'mouse-face 'highlight
21299 'keymap org-agenda-keymap
21300 'help-echo
21301 (format "mouse-2 or RET jump to org file %s"
21302 (abbreviate-file-name buffer-file-name))))
21303 (regexp org-tr-regexp)
21304 (d0 (calendar-absolute-from-gregorian date))
21305 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21306 donep head)
21307 (goto-char (point-min))
21308 (while (re-search-forward regexp nil t)
21309 (catch :skip
21310 (org-agenda-skip)
21311 (setq pos (point))
21312 (setq timestr (match-string 0)
21313 s1 (match-string 1)
21314 s2 (match-string 2)
21315 d1 (time-to-days (org-time-string-to-time s1))
21316 d2 (time-to-days (org-time-string-to-time s2)))
21317 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21318 ;; Only allow days between the limits, because the normal
21319 ;; date stamps will catch the limits.
21320 (save-excursion
21321 (setq marker (org-agenda-new-marker (point)))
21322 (setq category (org-get-category))
21323 (if (re-search-backward "^\\*+ " nil t)
21324 (progn
21325 (goto-char (match-beginning 0))
21326 (setq hdmarker (org-agenda-new-marker (point)))
21327 (setq tags (org-get-tags-at))
21328 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21329 (setq head (match-string 1))
21330 (and org-agenda-skip-timestamp-if-done
21331 (org-entry-is-done-p)
21332 (throw :skip t))
21333 (setq txt (org-format-agenda-item
21334 (format (if (= d1 d2) "" "(%d/%d): ")
21335 (1+ (- d0 d1)) (1+ (- d2 d1)))
21336 head category tags
21337 (if (= d0 d1) timestr))))
21338 (setq txt org-agenda-no-heading-message))
21339 (org-add-props txt props
21340 'org-marker marker 'org-hd-marker hdmarker
21341 'type "block" 'date date
21342 'priority (org-get-priority txt) 'org-category category)
21343 (push txt ee)))
21344 (goto-char pos)))
21345 ;; Sort the entries by expiration date.
21346 (nreverse ee)))
21348 ;;; Agenda presentation and sorting
21350 (defconst org-plain-time-of-day-regexp
21351 (concat
21352 "\\(\\<[012]?[0-9]"
21353 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21354 "\\(--?"
21355 "\\(\\<[012]?[0-9]"
21356 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21357 "\\)?")
21358 "Regular expression to match a plain time or time range.
21359 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21360 groups carry important information:
21361 0 the full match
21362 1 the first time, range or not
21363 8 the second time, if it is a range.")
21365 (defconst org-plain-time-extension-regexp
21366 (concat
21367 "\\(\\<[012]?[0-9]"
21368 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21369 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21370 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21371 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21372 groups carry important information:
21373 0 the full match
21374 7 hours of duration
21375 9 minutes of duration")
21377 (defconst org-stamp-time-of-day-regexp
21378 (concat
21379 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21380 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21381 "\\(--?"
21382 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21383 "Regular expression to match a timestamp time or time range.
21384 After a match, the following groups carry important information:
21385 0 the full match
21386 1 date plus weekday, for backreferencing to make sure both times on same day
21387 2 the first time, range or not
21388 4 the second time, if it is a range.")
21390 (defvar org-prefix-has-time nil
21391 "A flag, set by `org-compile-prefix-format'.
21392 The flag is set if the currently compiled format contains a `%t'.")
21393 (defvar org-prefix-has-tag nil
21394 "A flag, set by `org-compile-prefix-format'.
21395 The flag is set if the currently compiled format contains a `%T'.")
21397 (defun org-format-agenda-item (extra txt &optional category tags dotime
21398 noprefix remove-re)
21399 "Format TXT to be inserted into the agenda buffer.
21400 In particular, it adds the prefix and corresponding text properties. EXTRA
21401 must be a string and replaces the `%s' specifier in the prefix format.
21402 CATEGORY (string, symbol or nil) may be used to overrule the default
21403 category taken from local variable or file name. It will replace the `%c'
21404 specifier in the format. DOTIME, when non-nil, indicates that a
21405 time-of-day should be extracted from TXT for sorting of this entry, and for
21406 the `%t' specifier in the format. When DOTIME is a string, this string is
21407 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21408 only the correctly processes TXT should be returned - this is used by
21409 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21410 Any match of REMOVE-RE will be removed from TXT."
21411 (save-match-data
21412 ;; Diary entries sometimes have extra whitespace at the beginning
21413 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21414 (let* ((category (or category
21415 org-category
21416 (if buffer-file-name
21417 (file-name-sans-extension
21418 (file-name-nondirectory buffer-file-name))
21419 "")))
21420 (tag (if tags (nth (1- (length tags)) tags) ""))
21421 time ; time and tag are needed for the eval of the prefix format
21422 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21423 (time-of-day (and dotime (org-get-time-of-day ts)))
21424 stamp plain s0 s1 s2 rtn srp)
21425 (when (and dotime time-of-day org-prefix-has-time)
21426 ;; Extract starting and ending time and move them to prefix
21427 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21428 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21429 (setq s0 (match-string 0 ts)
21430 srp (and stamp (match-end 3))
21431 s1 (match-string (if plain 1 2) ts)
21432 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21434 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21435 ;; them, we might want to remove them there to avoid duplication.
21436 ;; The user can turn this off with a variable.
21437 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21438 (string-match (concat (regexp-quote s0) " *") txt)
21439 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21440 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21441 (= (match-beginning 0) 0)
21443 (setq txt (replace-match "" nil nil txt))))
21444 ;; Normalize the time(s) to 24 hour
21445 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21446 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21448 (when (and s1 (not s2) org-agenda-default-appointment-duration
21449 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21450 (let ((m (+ (string-to-number (match-string 2 s1))
21451 (* 60 (string-to-number (match-string 1 s1)))
21452 org-agenda-default-appointment-duration))
21454 (setq h (/ m 60) m (- m (* h 60)))
21455 (setq s2 (format "%02d:%02d" h m))))
21457 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21458 txt)
21459 ;; Tags are in the string
21460 (if (or (eq org-agenda-remove-tags t)
21461 (and org-agenda-remove-tags
21462 org-prefix-has-tag))
21463 (setq txt (replace-match "" t t txt))
21464 (setq txt (replace-match
21465 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21466 (match-string 2 txt))
21467 t t txt))))
21469 (when remove-re
21470 (while (string-match remove-re txt)
21471 (setq txt (replace-match "" t t txt))))
21473 ;; Create the final string
21474 (if noprefix
21475 (setq rtn txt)
21476 ;; Prepare the variables needed in the eval of the compiled format
21477 (setq time (cond (s2 (concat s1 "-" s2))
21478 (s1 (concat s1 "......"))
21479 (t ""))
21480 extra (or extra "")
21481 category (if (symbolp category) (symbol-name category) category))
21482 ;; Evaluate the compiled format
21483 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21485 ;; And finally add the text properties
21486 (org-add-props rtn nil
21487 'org-category (downcase category) 'tags tags
21488 'org-highest-priority org-highest-priority
21489 'org-lowest-priority org-lowest-priority
21490 'prefix-length (- (length rtn) (length txt))
21491 'time-of-day time-of-day
21492 'txt txt
21493 'time time
21494 'extra extra
21495 'dotime dotime))))
21497 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21498 (defvar org-agenda-sorting-strategy-selected nil)
21500 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21501 (catch 'exit
21502 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21503 ((and todayp (member 'today (car org-agenda-time-grid))))
21504 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21505 ((member 'weekly (car org-agenda-time-grid)))
21506 (t (throw 'exit list)))
21507 (let* ((have (delq nil (mapcar
21508 (lambda (x) (get-text-property 1 'time-of-day x))
21509 list)))
21510 (string (nth 1 org-agenda-time-grid))
21511 (gridtimes (nth 2 org-agenda-time-grid))
21512 (req (car org-agenda-time-grid))
21513 (remove (member 'remove-match req))
21514 new time)
21515 (if (and (member 'require-timed req) (not have))
21516 ;; don't show empty grid
21517 (throw 'exit list))
21518 (while (setq time (pop gridtimes))
21519 (unless (and remove (member time have))
21520 (setq time (int-to-string time))
21521 (push (org-format-agenda-item
21522 nil string "" nil
21523 (concat (substring time 0 -2) ":" (substring time -2)))
21524 new)
21525 (put-text-property
21526 1 (length (car new)) 'face 'org-time-grid (car new))))
21527 (if (member 'time-up org-agenda-sorting-strategy-selected)
21528 (append new list)
21529 (append list new)))))
21531 (defun org-compile-prefix-format (key)
21532 "Compile the prefix format into a Lisp form that can be evaluated.
21533 The resulting form is returned and stored in the variable
21534 `org-prefix-format-compiled'."
21535 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21536 (let ((s (cond
21537 ((stringp org-agenda-prefix-format)
21538 org-agenda-prefix-format)
21539 ((assq key org-agenda-prefix-format)
21540 (cdr (assq key org-agenda-prefix-format)))
21541 (t " %-12:c%?-12t% s")))
21542 (start 0)
21543 varform vars var e c f opt)
21544 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21545 s start)
21546 (setq var (cdr (assoc (match-string 4 s)
21547 '(("c" . category) ("t" . time) ("s" . extra)
21548 ("T" . tag))))
21549 c (or (match-string 3 s) "")
21550 opt (match-beginning 1)
21551 start (1+ (match-beginning 0)))
21552 (if (equal var 'time) (setq org-prefix-has-time t))
21553 (if (equal var 'tag) (setq org-prefix-has-tag t))
21554 (setq f (concat "%" (match-string 2 s) "s"))
21555 (if opt
21556 (setq varform
21557 `(if (equal "" ,var)
21559 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21560 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21561 (setq s (replace-match "%s" t nil s))
21562 (push varform vars))
21563 (setq vars (nreverse vars))
21564 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21566 (defun org-set-sorting-strategy (key)
21567 (if (symbolp (car org-agenda-sorting-strategy))
21568 ;; the old format
21569 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21570 (setq org-agenda-sorting-strategy-selected
21571 (or (cdr (assq key org-agenda-sorting-strategy))
21572 (cdr (assq 'agenda org-agenda-sorting-strategy))
21573 '(time-up category-keep priority-down)))))
21575 (defun org-get-time-of-day (s &optional string mod24)
21576 "Check string S for a time of day.
21577 If found, return it as a military time number between 0 and 2400.
21578 If not found, return nil.
21579 The optional STRING argument forces conversion into a 5 character wide string
21580 HH:MM."
21581 (save-match-data
21582 (when
21583 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21584 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21585 (let* ((h (string-to-number (match-string 1 s)))
21586 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21587 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21588 (am-p (equal ampm "am"))
21589 (h1 (cond ((not ampm) h)
21590 ((= h 12) (if am-p 0 12))
21591 (t (+ h (if am-p 0 12)))))
21592 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21593 (mod h1 24) h1))
21594 (t0 (+ (* 100 h2) m))
21595 (t1 (concat (if (>= h1 24) "+" " ")
21596 (if (< t0 100) "0" "")
21597 (if (< t0 10) "0" "")
21598 (int-to-string t0))))
21599 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21601 (defun org-finalize-agenda-entries (list &optional nosort)
21602 "Sort and concatenate the agenda items."
21603 (setq list (mapcar 'org-agenda-highlight-todo list))
21604 (if nosort
21605 list
21606 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21608 (defun org-agenda-highlight-todo (x)
21609 (let (re pl)
21610 (if (eq x 'line)
21611 (save-excursion
21612 (beginning-of-line 1)
21613 (setq re (get-text-property (point) 'org-todo-regexp))
21614 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21615 (when (looking-at (concat "[ \t]*\\.*" re " +"))
21616 (add-text-properties (match-beginning 0) (match-end 0)
21617 (list 'face (org-get-todo-face 0)))
21618 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
21619 (delete-region (match-beginning 1) (1- (match-end 0)))
21620 (goto-char (match-beginning 1))
21621 (insert (format org-agenda-todo-keyword-format s)))))
21622 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21623 pl (get-text-property 0 'prefix-length x))
21624 ; (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21625 ; (add-text-properties
21626 ; (or (match-end 1) (match-end 0)) (match-end 0)
21627 ; (list 'face (org-get-todo-face (match-string 2 x)))
21628 ; x))
21629 (when (and re
21630 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
21631 x (or pl 0)) pl))
21632 (add-text-properties
21633 (or (match-end 1) (match-end 0)) (match-end 0)
21634 (list 'face (org-get-todo-face (match-string 2 x)))
21636 (setq x (concat (substring x 0 (match-end 1))
21637 (format org-agenda-todo-keyword-format
21638 (match-string 2 x))
21640 (substring x (match-end 3)))))
21641 x)))
21643 (defsubst org-cmp-priority (a b)
21644 "Compare the priorities of string A and B."
21645 (let ((pa (or (get-text-property 1 'priority a) 0))
21646 (pb (or (get-text-property 1 'priority b) 0)))
21647 (cond ((> pa pb) +1)
21648 ((< pa pb) -1)
21649 (t nil))))
21651 (defsubst org-cmp-category (a b)
21652 "Compare the string values of categories of strings A and B."
21653 (let ((ca (or (get-text-property 1 'org-category a) ""))
21654 (cb (or (get-text-property 1 'org-category b) "")))
21655 (cond ((string-lessp ca cb) -1)
21656 ((string-lessp cb ca) +1)
21657 (t nil))))
21659 (defsubst org-cmp-tag (a b)
21660 "Compare the string values of categories of strings A and B."
21661 (let ((ta (car (last (get-text-property 1 'tags a))))
21662 (tb (car (last (get-text-property 1 'tags b)))))
21663 (cond ((not ta) +1)
21664 ((not tb) -1)
21665 ((string-lessp ta tb) -1)
21666 ((string-lessp tb ta) +1)
21667 (t nil))))
21669 (defsubst org-cmp-time (a b)
21670 "Compare the time-of-day values of strings A and B."
21671 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21672 (ta (or (get-text-property 1 'time-of-day a) def))
21673 (tb (or (get-text-property 1 'time-of-day b) def)))
21674 (cond ((< ta tb) -1)
21675 ((< tb ta) +1)
21676 (t nil))))
21678 (defun org-entries-lessp (a b)
21679 "Predicate for sorting agenda entries."
21680 ;; The following variables will be used when the form is evaluated.
21681 ;; So even though the compiler complains, keep them.
21682 (let* ((time-up (org-cmp-time a b))
21683 (time-down (if time-up (- time-up) nil))
21684 (priority-up (org-cmp-priority a b))
21685 (priority-down (if priority-up (- priority-up) nil))
21686 (category-up (org-cmp-category a b))
21687 (category-down (if category-up (- category-up) nil))
21688 (category-keep (if category-up +1 nil))
21689 (tag-up (org-cmp-tag a b))
21690 (tag-down (if tag-up (- tag-up) nil)))
21691 (cdr (assoc
21692 (eval (cons 'or org-agenda-sorting-strategy-selected))
21693 '((-1 . t) (1 . nil) (nil . nil))))))
21695 ;;; Agenda restriction lock
21697 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21698 "Overlay to mark the headline to which arenda commands are restricted.")
21699 (org-overlay-put org-agenda-restriction-lock-overlay
21700 'face 'org-agenda-restriction-lock)
21701 (org-overlay-put org-agenda-restriction-lock-overlay
21702 'help-echo "Agendas are currently limited to this subtree.")
21703 (org-detach-overlay org-agenda-restriction-lock-overlay)
21704 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21705 "Overlay marking the agenda restriction line in speedbar.")
21706 (org-overlay-put org-speedbar-restriction-lock-overlay
21707 'face 'org-agenda-restriction-lock)
21708 (org-overlay-put org-speedbar-restriction-lock-overlay
21709 'help-echo "Agendas are currently limited to this item.")
21710 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21712 (defun org-agenda-set-restriction-lock (&optional type)
21713 "Set restriction lock for agenda, to current subtree or file.
21714 Restriction will be the file if TYPE is `file', or if type is the
21715 universal prefix '(4), or if the cursor is before the first headline
21716 in the file. Otherwise, restriction will be to the current subtree."
21717 (interactive "P")
21718 (and (equal type '(4)) (setq type 'file))
21719 (setq type (cond
21720 (type type)
21721 ((org-at-heading-p) 'subtree)
21722 ((condition-case nil (org-back-to-heading t) (error nil))
21723 'subtree)
21724 (t 'file)))
21725 (if (eq type 'subtree)
21726 (progn
21727 (setq org-agenda-restrict t)
21728 (setq org-agenda-overriding-restriction 'subtree)
21729 (put 'org-agenda-files 'org-restrict
21730 (list (buffer-file-name (buffer-base-buffer))))
21731 (org-back-to-heading t)
21732 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21733 (move-marker org-agenda-restrict-begin (point))
21734 (move-marker org-agenda-restrict-end
21735 (save-excursion (org-end-of-subtree t)))
21736 (message "Locking agenda restriction to subtree"))
21737 (put 'org-agenda-files 'org-restrict
21738 (list (buffer-file-name (buffer-base-buffer))))
21739 (setq org-agenda-restrict nil)
21740 (setq org-agenda-overriding-restriction 'file)
21741 (move-marker org-agenda-restrict-begin nil)
21742 (move-marker org-agenda-restrict-end nil)
21743 (message "Locking agenda restriction to file"))
21744 (setq current-prefix-arg nil)
21745 (org-agenda-maybe-redo))
21747 (defun org-agenda-remove-restriction-lock (&optional noupdate)
21748 "Remove the agenda restriction lock."
21749 (interactive "P")
21750 (org-detach-overlay org-agenda-restriction-lock-overlay)
21751 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21752 (setq org-agenda-overriding-restriction nil)
21753 (setq org-agenda-restrict nil)
21754 (put 'org-agenda-files 'org-restrict nil)
21755 (move-marker org-agenda-restrict-begin nil)
21756 (move-marker org-agenda-restrict-end nil)
21757 (setq current-prefix-arg nil)
21758 (message "Agenda restriction lock removed")
21759 (or noupdate (org-agenda-maybe-redo)))
21761 (defun org-agenda-maybe-redo ()
21762 "If there is any window showing the agenda view, update it."
21763 (let ((w (get-buffer-window org-agenda-buffer-name t))
21764 (w0 (selected-window)))
21765 (when w
21766 (select-window w)
21767 (org-agenda-redo)
21768 (select-window w0)
21769 (if org-agenda-overriding-restriction
21770 (message "Agenda view shifted to new %s restriction"
21771 org-agenda-overriding-restriction)
21772 (message "Agenda restriction lock removed")))))
21774 ;;; Agenda commands
21776 (defun org-agenda-check-type (error &rest types)
21777 "Check if agenda buffer is of allowed type.
21778 If ERROR is non-nil, throw an error, otherwise just return nil."
21779 (if (memq org-agenda-type types)
21781 (if error
21782 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
21783 nil)))
21785 (defun org-agenda-quit ()
21786 "Exit agenda by removing the window or the buffer."
21787 (interactive)
21788 (let ((buf (current-buffer)))
21789 (if (not (one-window-p)) (delete-window))
21790 (kill-buffer buf)
21791 (org-agenda-maybe-reset-markers 'force)
21792 (org-columns-remove-overlays))
21793 ;; Maybe restore the pre-agenda window configuration.
21794 (and org-agenda-restore-windows-after-quit
21795 (not (eq org-agenda-window-setup 'other-frame))
21796 org-pre-agenda-window-conf
21797 (set-window-configuration org-pre-agenda-window-conf)))
21799 (defun org-agenda-exit ()
21800 "Exit agenda by removing the window or the buffer.
21801 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
21802 Org-mode buffers visited directly by the user will not be touched."
21803 (interactive)
21804 (org-release-buffers org-agenda-new-buffers)
21805 (setq org-agenda-new-buffers nil)
21806 (org-agenda-quit))
21808 (defun org-agenda-execute (arg)
21809 "Execute another agenda command, keeping same window.\\<global-map>
21810 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
21811 (interactive "P")
21812 (let ((org-agenda-window-setup 'current-window))
21813 (org-agenda arg)))
21815 (defun org-save-all-org-buffers ()
21816 "Save all Org-mode buffers without user confirmation."
21817 (interactive)
21818 (message "Saving all Org-mode buffers...")
21819 (save-some-buffers t 'org-mode-p)
21820 (message "Saving all Org-mode buffers... done"))
21822 (defun org-agenda-redo ()
21823 "Rebuild Agenda.
21824 When this is the global TODO list, a prefix argument will be interpreted."
21825 (interactive)
21826 (let* ((org-agenda-keep-modes t)
21827 (line (org-current-line))
21828 (window-line (- line (org-current-line (window-start))))
21829 (lprops (get 'org-agenda-redo-command 'org-lprops)))
21830 (message "Rebuilding agenda buffer...")
21831 (org-let lprops '(eval org-agenda-redo-command))
21832 (setq org-agenda-undo-list nil
21833 org-agenda-pending-undo-list nil)
21834 (message "Rebuilding agenda buffer...done")
21835 (goto-line line)
21836 (recenter window-line)))
21838 (defun org-agenda-goto-date (date)
21839 "Jump to DATE in agenda."
21840 (interactive (list (org-read-date)))
21841 (org-agenda-list nil date))
21843 (defun org-agenda-goto-today ()
21844 "Go to today."
21845 (interactive)
21846 (org-agenda-check-type t 'timeline 'agenda)
21847 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
21848 (cond
21849 (tdpos (goto-char tdpos))
21850 ((eq org-agenda-type 'agenda)
21851 (let* ((sd (time-to-days
21852 (time-subtract (current-time)
21853 (list 0 (* 3600 org-extend-today-until) 0))))
21854 (comp (org-agenda-compute-time-span sd org-agenda-span))
21855 (org-agenda-overriding-arguments org-agenda-last-arguments))
21856 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
21857 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
21858 (org-agenda-redo)
21859 (org-agenda-find-same-or-today-or-agenda)))
21860 (t (error "Cannot find today")))))
21862 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
21863 (goto-char
21864 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
21865 (text-property-any (point-min) (point-max) 'org-today t)
21866 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
21867 (point-min))))
21869 (defun org-agenda-later (arg)
21870 "Go forward in time by thee current span.
21871 With prefix ARG, go forward that many times the current span."
21872 (interactive "p")
21873 (org-agenda-check-type t 'agenda)
21874 (let* ((span org-agenda-span)
21875 (sd org-starting-day)
21876 (greg (calendar-gregorian-from-absolute sd))
21877 (cnt (get-text-property (point) 'org-day-cnt))
21878 greg2 nd)
21879 (cond
21880 ((eq span 'day)
21881 (setq sd (+ arg sd) nd 1))
21882 ((eq span 'week)
21883 (setq sd (+ (* 7 arg) sd) nd 7))
21884 ((eq span 'month)
21885 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
21886 sd (calendar-absolute-from-gregorian greg2))
21887 (setcar greg2 (1+ (car greg2)))
21888 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
21889 ((eq span 'year)
21890 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
21891 sd (calendar-absolute-from-gregorian greg2))
21892 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
21893 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
21894 (let ((org-agenda-overriding-arguments
21895 (list (car org-agenda-last-arguments) sd nd t)))
21896 (org-agenda-redo)
21897 (org-agenda-find-same-or-today-or-agenda cnt))))
21899 (defun org-agenda-earlier (arg)
21900 "Go backward in time by the current span.
21901 With prefix ARG, go backward that many times the current span."
21902 (interactive "p")
21903 (org-agenda-later (- arg)))
21905 (defun org-agenda-day-view ()
21906 "Switch to daily view for agenda."
21907 (interactive)
21908 (setq org-agenda-ndays 1)
21909 (org-agenda-change-time-span 'day))
21910 (defun org-agenda-week-view ()
21911 "Switch to daily view for agenda."
21912 (interactive)
21913 (setq org-agenda-ndays 7)
21914 (org-agenda-change-time-span 'week))
21915 (defun org-agenda-month-view ()
21916 "Switch to daily view for agenda."
21917 (interactive)
21918 (org-agenda-change-time-span 'month))
21919 (defun org-agenda-year-view ()
21920 "Switch to daily view for agenda."
21921 (interactive)
21922 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
21923 (org-agenda-change-time-span 'year)
21924 (error "Abort")))
21926 (defun org-agenda-change-time-span (span)
21927 "Change the agenda view to SPAN.
21928 SPAN may be `day', `week', `month', `year'."
21929 (org-agenda-check-type t 'agenda)
21930 (if (equal org-agenda-span span)
21931 (error "Viewing span is already \"%s\"" span))
21932 (let* ((sd (or (get-text-property (point) 'day)
21933 org-starting-day))
21934 (computed (org-agenda-compute-time-span sd span))
21935 (org-agenda-overriding-arguments
21936 (list (car org-agenda-last-arguments)
21937 (car computed) (cdr computed) t)))
21938 (org-agenda-redo)
21939 (org-agenda-find-same-or-today-or-agenda))
21940 (org-agenda-set-mode-name)
21941 (message "Switched to %s view" span))
21943 (defun org-agenda-compute-time-span (sd span)
21944 "Compute starting date and number of days for agenda.
21945 SPAN may be `day', `week', `month', `year'. The return value
21946 is a cons cell with the starting date and the number of days,
21947 so that the date SD will be in that range."
21948 (let* ((greg (calendar-gregorian-from-absolute sd))
21950 (cond
21951 ((eq span 'day)
21952 (setq nd 1))
21953 ((eq span 'week)
21954 (let* ((nt (calendar-day-of-week
21955 (calendar-gregorian-from-absolute sd)))
21956 (d (if org-agenda-start-on-weekday
21957 (- nt org-agenda-start-on-weekday)
21958 0)))
21959 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
21960 (setq nd 7)))
21961 ((eq span 'month)
21962 (setq sd (calendar-absolute-from-gregorian
21963 (list (car greg) 1 (nth 2 greg)))
21964 nd (- (calendar-absolute-from-gregorian
21965 (list (1+ (car greg)) 1 (nth 2 greg)))
21966 sd)))
21967 ((eq span 'year)
21968 (setq sd (calendar-absolute-from-gregorian
21969 (list 1 1 (nth 2 greg)))
21970 nd (- (calendar-absolute-from-gregorian
21971 (list 1 1 (1+ (nth 2 greg))))
21972 sd))))
21973 (cons sd nd)))
21975 ;; FIXME: does not work if user makes date format that starts with a blank
21976 (defun org-agenda-next-date-line (&optional arg)
21977 "Jump to the next line indicating a date in agenda buffer."
21978 (interactive "p")
21979 (org-agenda-check-type t 'agenda 'timeline)
21980 (beginning-of-line 1)
21981 (if (looking-at "^\\S-") (forward-char 1))
21982 (if (not (re-search-forward "^\\S-" nil t arg))
21983 (progn
21984 (backward-char 1)
21985 (error "No next date after this line in this buffer")))
21986 (goto-char (match-beginning 0)))
21988 (defun org-agenda-previous-date-line (&optional arg)
21989 "Jump to the previous line indicating a date in agenda buffer."
21990 (interactive "p")
21991 (org-agenda-check-type t 'agenda 'timeline)
21992 (beginning-of-line 1)
21993 (if (not (re-search-backward "^\\S-" nil t arg))
21994 (error "No previous date before this line in this buffer")))
21996 ;; Initialize the highlight
21997 (defvar org-hl (org-make-overlay 1 1))
21998 (org-overlay-put org-hl 'face 'highlight)
22000 (defun org-highlight (begin end &optional buffer)
22001 "Highlight a region with overlay."
22002 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22003 org-hl begin end (or buffer (current-buffer))))
22005 (defun org-unhighlight ()
22006 "Detach overlay INDEX."
22007 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22009 ;; FIXME this is currently not used.
22010 (defun org-highlight-until-next-command (beg end &optional buffer)
22011 (org-highlight beg end buffer)
22012 (add-hook 'pre-command-hook 'org-unhighlight-once))
22013 (defun org-unhighlight-once ()
22014 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22015 (org-unhighlight))
22017 (defun org-agenda-follow-mode ()
22018 "Toggle follow mode in an agenda buffer."
22019 (interactive)
22020 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22021 (org-agenda-set-mode-name)
22022 (message "Follow mode is %s"
22023 (if org-agenda-follow-mode "on" "off")))
22025 (defun org-agenda-log-mode ()
22026 "Toggle log mode in an agenda buffer."
22027 (interactive)
22028 (org-agenda-check-type t 'agenda 'timeline)
22029 (setq org-agenda-show-log (not org-agenda-show-log))
22030 (org-agenda-set-mode-name)
22031 (org-agenda-redo)
22032 (message "Log mode is %s"
22033 (if org-agenda-show-log "on" "off")))
22035 (defun org-agenda-toggle-diary ()
22036 "Toggle diary inclusion in an agenda buffer."
22037 (interactive)
22038 (org-agenda-check-type t 'agenda)
22039 (setq org-agenda-include-diary (not org-agenda-include-diary))
22040 (org-agenda-redo)
22041 (org-agenda-set-mode-name)
22042 (message "Diary inclusion turned %s"
22043 (if org-agenda-include-diary "on" "off")))
22045 (defun org-agenda-toggle-time-grid ()
22046 "Toggle time grid in an agenda buffer."
22047 (interactive)
22048 (org-agenda-check-type t 'agenda)
22049 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22050 (org-agenda-redo)
22051 (org-agenda-set-mode-name)
22052 (message "Time-grid turned %s"
22053 (if org-agenda-use-time-grid "on" "off")))
22055 (defun org-agenda-set-mode-name ()
22056 "Set the mode name to indicate all the small mode settings."
22057 (setq mode-name
22058 (concat "Org-Agenda"
22059 (if (equal org-agenda-ndays 1) " Day" "")
22060 (if (equal org-agenda-ndays 7) " Week" "")
22061 (if org-agenda-follow-mode " Follow" "")
22062 (if org-agenda-include-diary " Diary" "")
22063 (if org-agenda-use-time-grid " Grid" "")
22064 (if org-agenda-show-log " Log" "")))
22065 (force-mode-line-update))
22067 (defun org-agenda-post-command-hook ()
22068 (and (eolp) (not (bolp)) (backward-char 1))
22069 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22070 (if (and org-agenda-follow-mode
22071 (get-text-property (point) 'org-marker))
22072 (org-agenda-show)))
22074 (defun org-agenda-show-priority ()
22075 "Show the priority of the current item.
22076 This priority is composed of the main priority given with the [#A] cookies,
22077 and by additional input from the age of a schedules or deadline entry."
22078 (interactive)
22079 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22080 (message "Priority is %d" (if pri pri -1000))))
22082 (defun org-agenda-show-tags ()
22083 "Show the tags applicable to the current item."
22084 (interactive)
22085 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22086 (if tags
22087 (message "Tags are :%s:"
22088 (org-no-properties (mapconcat 'identity tags ":")))
22089 (message "No tags associated with this line"))))
22091 (defun org-agenda-goto (&optional highlight)
22092 "Go to the Org-mode file which contains the item at point."
22093 (interactive)
22094 (let* ((marker (or (get-text-property (point) 'org-marker)
22095 (org-agenda-error)))
22096 (buffer (marker-buffer marker))
22097 (pos (marker-position marker)))
22098 (switch-to-buffer-other-window buffer)
22099 (widen)
22100 (goto-char pos)
22101 (when (org-mode-p)
22102 (org-show-context 'agenda)
22103 (save-excursion
22104 (and (outline-next-heading)
22105 (org-flag-heading nil)))) ; show the next heading
22106 (run-hooks 'org-agenda-after-show-hook)
22107 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22109 (defvar org-agenda-after-show-hook nil
22110 "Normal hook run after an item has been shown from the agenda.
22111 Point is in the buffer where the item originated.")
22113 (defun org-agenda-kill ()
22114 "Kill the entry or subtree belonging to the current agenda entry."
22115 (interactive)
22116 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22117 (let* ((marker (or (get-text-property (point) 'org-marker)
22118 (org-agenda-error)))
22119 (buffer (marker-buffer marker))
22120 (pos (marker-position marker))
22121 (type (get-text-property (point) 'type))
22122 dbeg dend (n 0) conf)
22123 (org-with-remote-undo buffer
22124 (with-current-buffer buffer
22125 (save-excursion
22126 (goto-char pos)
22127 (if (and (org-mode-p) (not (member type '("sexp"))))
22128 (setq dbeg (progn (org-back-to-heading t) (point))
22129 dend (org-end-of-subtree t t))
22130 (setq dbeg (point-at-bol)
22131 dend (min (point-max) (1+ (point-at-eol)))))
22132 (goto-char dbeg)
22133 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22134 (setq conf (or (eq t org-agenda-confirm-kill)
22135 (and (numberp org-agenda-confirm-kill)
22136 (> n org-agenda-confirm-kill))))
22137 (and conf
22138 (not (y-or-n-p
22139 (format "Delete entry with %d lines in buffer \"%s\"? "
22140 n (buffer-name buffer))))
22141 (error "Abort"))
22142 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22143 (with-current-buffer buffer (delete-region dbeg dend))
22144 (message "Agenda item and source killed"))))
22146 (defun org-agenda-archive ()
22147 "Kill the entry or subtree belonging to the current agenda entry."
22148 (interactive)
22149 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22150 (let* ((marker (or (get-text-property (point) 'org-marker)
22151 (org-agenda-error)))
22152 (buffer (marker-buffer marker))
22153 (pos (marker-position marker)))
22154 (org-with-remote-undo buffer
22155 (with-current-buffer buffer
22156 (if (org-mode-p)
22157 (save-excursion
22158 (goto-char pos)
22159 (org-remove-subtree-entries-from-agenda)
22160 (org-back-to-heading t)
22161 (org-archive-subtree))
22162 (error "Archiving works only in Org-mode files"))))))
22164 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22165 "Remove all lines in the agenda that correspond to a given subtree.
22166 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22167 If this information is not given, the function uses the tree at point."
22168 (let ((buf (or buf (current-buffer))) m p)
22169 (save-excursion
22170 (unless (and beg end)
22171 (org-back-to-heading t)
22172 (setq beg (point))
22173 (org-end-of-subtree t)
22174 (setq end (point)))
22175 (set-buffer (get-buffer org-agenda-buffer-name))
22176 (save-excursion
22177 (goto-char (point-max))
22178 (beginning-of-line 1)
22179 (while (not (bobp))
22180 (when (and (setq m (get-text-property (point) 'org-marker))
22181 (equal buf (marker-buffer m))
22182 (setq p (marker-position m))
22183 (>= p beg)
22184 (<= p end))
22185 (let ((inhibit-read-only t))
22186 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22187 (beginning-of-line 0))))))
22189 (defun org-agenda-open-link ()
22190 "Follow the link in the current line, if any."
22191 (interactive)
22192 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22193 (save-excursion
22194 (save-restriction
22195 (narrow-to-region (point-at-bol) (point-at-eol))
22196 (org-open-at-point))))
22198 (defun org-agenda-copy-local-variable (var)
22199 "Get a variable from a referenced buffer and install it here."
22200 (let ((m (get-text-property (point) 'org-marker)))
22201 (when (and m (buffer-live-p (marker-buffer m)))
22202 (org-set-local var (with-current-buffer (marker-buffer m)
22203 (symbol-value var))))))
22205 (defun org-agenda-switch-to (&optional delete-other-windows)
22206 "Go to the Org-mode file which contains the item at point."
22207 (interactive)
22208 (let* ((marker (or (get-text-property (point) 'org-marker)
22209 (org-agenda-error)))
22210 (buffer (marker-buffer marker))
22211 (pos (marker-position marker)))
22212 (switch-to-buffer buffer)
22213 (and delete-other-windows (delete-other-windows))
22214 (widen)
22215 (goto-char pos)
22216 (when (org-mode-p)
22217 (org-show-context 'agenda)
22218 (save-excursion
22219 (and (outline-next-heading)
22220 (org-flag-heading nil)))))) ; show the next heading
22222 (defun org-agenda-goto-mouse (ev)
22223 "Go to the Org-mode file which contains the item at the mouse click."
22224 (interactive "e")
22225 (mouse-set-point ev)
22226 (org-agenda-goto))
22228 (defun org-agenda-show ()
22229 "Display the Org-mode file which contains the item at point."
22230 (interactive)
22231 (let ((win (selected-window)))
22232 (org-agenda-goto t)
22233 (select-window win)))
22235 (defun org-agenda-recenter (arg)
22236 "Display the Org-mode file which contains the item at point and recenter."
22237 (interactive "P")
22238 (let ((win (selected-window)))
22239 (org-agenda-goto t)
22240 (recenter arg)
22241 (select-window win)))
22243 (defun org-agenda-show-mouse (ev)
22244 "Display the Org-mode file which contains the item at the mouse click."
22245 (interactive "e")
22246 (mouse-set-point ev)
22247 (org-agenda-show))
22249 (defun org-agenda-check-no-diary ()
22250 "Check if the entry is a diary link and abort if yes."
22251 (if (get-text-property (point) 'org-agenda-diary-link)
22252 (org-agenda-error)))
22254 (defun org-agenda-error ()
22255 (error "Command not allowed in this line"))
22257 (defun org-agenda-tree-to-indirect-buffer ()
22258 "Show the subtree corresponding to the current entry in an indirect buffer.
22259 This calls the command `org-tree-to-indirect-buffer' from the original
22260 Org-mode buffer.
22261 With numerical prefix arg ARG, go up to this level and then take that tree.
22262 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22263 dedicated frame)."
22264 (interactive)
22265 (org-agenda-check-no-diary)
22266 (let* ((marker (or (get-text-property (point) 'org-marker)
22267 (org-agenda-error)))
22268 (buffer (marker-buffer marker))
22269 (pos (marker-position marker)))
22270 (with-current-buffer buffer
22271 (save-excursion
22272 (goto-char pos)
22273 (call-interactively 'org-tree-to-indirect-buffer)))))
22275 (defvar org-last-heading-marker (make-marker)
22276 "Marker pointing to the headline that last changed its TODO state
22277 by a remote command from the agenda.")
22279 (defun org-agenda-todo-nextset ()
22280 "Switch TODO entry to next sequence."
22281 (interactive)
22282 (org-agenda-todo 'nextset))
22284 (defun org-agenda-todo-previousset ()
22285 "Switch TODO entry to previous sequence."
22286 (interactive)
22287 (org-agenda-todo 'previousset))
22289 (defun org-agenda-todo (&optional arg)
22290 "Cycle TODO state of line at point, also in Org-mode file.
22291 This changes the line at point, all other lines in the agenda referring to
22292 the same tree node, and the headline of the tree node in the Org-mode file."
22293 (interactive "P")
22294 (org-agenda-check-no-diary)
22295 (let* ((col (current-column))
22296 (marker (or (get-text-property (point) 'org-marker)
22297 (org-agenda-error)))
22298 (buffer (marker-buffer marker))
22299 (pos (marker-position marker))
22300 (hdmarker (get-text-property (point) 'org-hd-marker))
22301 (inhibit-read-only t)
22302 newhead)
22303 (org-with-remote-undo buffer
22304 (with-current-buffer buffer
22305 (widen)
22306 (goto-char pos)
22307 (org-show-context 'agenda)
22308 (save-excursion
22309 (and (outline-next-heading)
22310 (org-flag-heading nil))) ; show the next heading
22311 (org-todo arg)
22312 (and (bolp) (forward-char 1))
22313 (setq newhead (org-get-heading))
22314 (save-excursion
22315 (org-back-to-heading)
22316 (move-marker org-last-heading-marker (point))))
22317 (beginning-of-line 1)
22318 (save-excursion
22319 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22320 (move-to-column col))))
22322 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22323 "Change all lines in the agenda buffer which match HDMARKER.
22324 The new content of the line will be NEWHEAD (as modified by
22325 `org-format-agenda-item'). HDMARKER is checked with
22326 `equal' against all `org-hd-marker' text properties in the file.
22327 If FIXFACE is non-nil, the face of each item is modified acording to
22328 the new TODO state."
22329 (let* ((inhibit-read-only t)
22330 props m pl undone-face done-face finish new dotime cat tags)
22331 (save-excursion
22332 (goto-char (point-max))
22333 (beginning-of-line 1)
22334 (while (not finish)
22335 (setq finish (bobp))
22336 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22337 (equal m hdmarker))
22338 (setq props (text-properties-at (point))
22339 dotime (get-text-property (point) 'dotime)
22340 cat (get-text-property (point) 'org-category)
22341 tags (get-text-property (point) 'tags)
22342 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22343 pl (get-text-property (point) 'prefix-length)
22344 undone-face (get-text-property (point) 'undone-face)
22345 done-face (get-text-property (point) 'done-face))
22346 (move-to-column pl)
22347 (cond
22348 ((equal new "")
22349 (beginning-of-line 1)
22350 (and (looking-at ".*\n?") (replace-match "")))
22351 ((looking-at ".*")
22352 (replace-match new t t)
22353 (beginning-of-line 1)
22354 (add-text-properties (point-at-bol) (point-at-eol) props)
22355 (when fixface
22356 (add-text-properties
22357 (point-at-bol) (point-at-eol)
22358 (list 'face
22359 (if org-last-todo-state-is-todo
22360 undone-face done-face))))
22361 (org-agenda-highlight-todo 'line)
22362 (beginning-of-line 1))
22363 (t (error "Line update did not work"))))
22364 (beginning-of-line 0)))
22365 (org-finalize-agenda)))
22367 (defun org-agenda-align-tags (&optional line)
22368 "Align all tags in agenda items to `org-agenda-tags-column'."
22369 (let ((inhibit-read-only t) l c)
22370 (save-excursion
22371 (goto-char (if line (point-at-bol) (point-min)))
22372 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22373 (if line (point-at-eol) nil) t)
22374 (add-text-properties
22375 (match-beginning 2) (match-end 2)
22376 (list 'face (list 'org-tag (get-text-property
22377 (match-beginning 2) 'face))))
22378 (setq l (- (match-end 2) (match-beginning 2))
22379 c (if (< org-agenda-tags-column 0)
22380 (- (abs org-agenda-tags-column) l)
22381 org-agenda-tags-column))
22382 (delete-region (match-beginning 1) (match-end 1))
22383 (goto-char (match-beginning 1))
22384 (insert (org-add-props
22385 (make-string (max 1 (- c (current-column))) ?\ )
22386 (text-properties-at (point))))))))
22388 (defun org-agenda-priority-up ()
22389 "Increase the priority of line at point, also in Org-mode file."
22390 (interactive)
22391 (org-agenda-priority 'up))
22393 (defun org-agenda-priority-down ()
22394 "Decrease the priority of line at point, also in Org-mode file."
22395 (interactive)
22396 (org-agenda-priority 'down))
22398 (defun org-agenda-priority (&optional force-direction)
22399 "Set the priority of line at point, also in Org-mode file.
22400 This changes the line at point, all other lines in the agenda referring to
22401 the same tree node, and the headline of the tree node in the Org-mode file."
22402 (interactive)
22403 (org-agenda-check-no-diary)
22404 (let* ((marker (or (get-text-property (point) 'org-marker)
22405 (org-agenda-error)))
22406 (hdmarker (get-text-property (point) 'org-hd-marker))
22407 (buffer (marker-buffer hdmarker))
22408 (pos (marker-position hdmarker))
22409 (inhibit-read-only t)
22410 newhead)
22411 (org-with-remote-undo buffer
22412 (with-current-buffer buffer
22413 (widen)
22414 (goto-char pos)
22415 (org-show-context 'agenda)
22416 (save-excursion
22417 (and (outline-next-heading)
22418 (org-flag-heading nil))) ; show the next heading
22419 (funcall 'org-priority force-direction)
22420 (end-of-line 1)
22421 (setq newhead (org-get-heading)))
22422 (org-agenda-change-all-lines newhead hdmarker)
22423 (beginning-of-line 1))))
22425 (defun org-get-tags-at (&optional pos)
22426 "Get a list of all headline tags applicable at POS.
22427 POS defaults to point. If tags are inherited, the list contains
22428 the targets in the same sequence as the headlines appear, i.e.
22429 the tags of the current headline come last."
22430 (interactive)
22431 (let (tags lastpos)
22432 (save-excursion
22433 (save-restriction
22434 (widen)
22435 (goto-char (or pos (point)))
22436 (save-match-data
22437 (org-back-to-heading t)
22438 (condition-case nil
22439 (while (not (equal lastpos (point)))
22440 (setq lastpos (point))
22441 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22442 (setq tags (append (org-split-string
22443 (org-match-string-no-properties 1) ":")
22444 tags)))
22445 (or org-use-tag-inheritance (error ""))
22446 (org-up-heading-all 1))
22447 (error nil))))
22448 tags)))
22450 ;; FIXME: should fix the tags property of the agenda line.
22451 (defun org-agenda-set-tags ()
22452 "Set tags for the current headline."
22453 (interactive)
22454 (org-agenda-check-no-diary)
22455 (if (and (org-region-active-p) (interactive-p))
22456 (call-interactively 'org-change-tag-in-region)
22457 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22458 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22459 (org-agenda-error)))
22460 (buffer (marker-buffer hdmarker))
22461 (pos (marker-position hdmarker))
22462 (inhibit-read-only t)
22463 newhead)
22464 (org-with-remote-undo buffer
22465 (with-current-buffer buffer
22466 (widen)
22467 (goto-char pos)
22468 (save-excursion
22469 (org-show-context 'agenda))
22470 (save-excursion
22471 (and (outline-next-heading)
22472 (org-flag-heading nil))) ; show the next heading
22473 (goto-char pos)
22474 (call-interactively 'org-set-tags)
22475 (end-of-line 1)
22476 (setq newhead (org-get-heading)))
22477 (org-agenda-change-all-lines newhead hdmarker)
22478 (beginning-of-line 1)))))
22480 (defun org-agenda-toggle-archive-tag ()
22481 "Toggle the archive tag for the current entry."
22482 (interactive)
22483 (org-agenda-check-no-diary)
22484 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22485 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22486 (org-agenda-error)))
22487 (buffer (marker-buffer hdmarker))
22488 (pos (marker-position hdmarker))
22489 (inhibit-read-only t)
22490 newhead)
22491 (org-with-remote-undo buffer
22492 (with-current-buffer buffer
22493 (widen)
22494 (goto-char pos)
22495 (org-show-context 'agenda)
22496 (save-excursion
22497 (and (outline-next-heading)
22498 (org-flag-heading nil))) ; show the next heading
22499 (call-interactively 'org-toggle-archive-tag)
22500 (end-of-line 1)
22501 (setq newhead (org-get-heading)))
22502 (org-agenda-change-all-lines newhead hdmarker)
22503 (beginning-of-line 1))))
22505 (defun org-agenda-date-later (arg &optional what)
22506 "Change the date of this item to one day later."
22507 (interactive "p")
22508 (org-agenda-check-type t 'agenda 'timeline)
22509 (org-agenda-check-no-diary)
22510 (let* ((marker (or (get-text-property (point) 'org-marker)
22511 (org-agenda-error)))
22512 (buffer (marker-buffer marker))
22513 (pos (marker-position marker)))
22514 (org-with-remote-undo buffer
22515 (with-current-buffer buffer
22516 (widen)
22517 (goto-char pos)
22518 (if (not (org-at-timestamp-p))
22519 (error "Cannot find time stamp"))
22520 (org-timestamp-change arg (or what 'day)))
22521 (org-agenda-show-new-time marker org-last-changed-timestamp))
22522 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22524 (defun org-agenda-date-earlier (arg &optional what)
22525 "Change the date of this item to one day earlier."
22526 (interactive "p")
22527 (org-agenda-date-later (- arg) what))
22529 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22530 "Show new date stamp via text properties."
22531 ;; We use text properties to make this undoable
22532 (let ((inhibit-read-only t))
22533 (setq stamp (concat " " prefix " => " stamp))
22534 (save-excursion
22535 (goto-char (point-max))
22536 (while (not (bobp))
22537 (when (equal marker (get-text-property (point) 'org-marker))
22538 (move-to-column (- (window-width) (length stamp)) t)
22539 (if (featurep 'xemacs)
22540 ;; Use `duplicable' property to trigger undo recording
22541 (let ((ex (make-extent nil nil))
22542 (gl (make-glyph stamp)))
22543 (set-glyph-face gl 'secondary-selection)
22544 (set-extent-properties
22545 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22546 (insert-extent ex (1- (point)) (point-at-eol)))
22547 (add-text-properties
22548 (1- (point)) (point-at-eol)
22549 (list 'display (org-add-props stamp nil
22550 'face 'secondary-selection))))
22551 (beginning-of-line 1))
22552 (beginning-of-line 0)))))
22554 (defun org-agenda-date-prompt (arg)
22555 "Change the date of this item. Date is prompted for, with default today.
22556 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22557 be used to request time specification in the time stamp."
22558 (interactive "P")
22559 (org-agenda-check-type t 'agenda 'timeline)
22560 (org-agenda-check-no-diary)
22561 (let* ((marker (or (get-text-property (point) 'org-marker)
22562 (org-agenda-error)))
22563 (buffer (marker-buffer marker))
22564 (pos (marker-position marker)))
22565 (org-with-remote-undo buffer
22566 (with-current-buffer buffer
22567 (widen)
22568 (goto-char pos)
22569 (if (not (org-at-timestamp-p))
22570 (error "Cannot find time stamp"))
22571 (org-time-stamp arg)
22572 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22574 (defun org-agenda-schedule (arg)
22575 "Schedule the item at point."
22576 (interactive "P")
22577 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22578 (org-agenda-check-no-diary)
22579 (let* ((marker (or (get-text-property (point) 'org-marker)
22580 (org-agenda-error)))
22581 (buffer (marker-buffer marker))
22582 (pos (marker-position marker))
22583 (org-insert-labeled-timestamps-at-point nil)
22585 (org-with-remote-undo buffer
22586 (with-current-buffer buffer
22587 (widen)
22588 (goto-char pos)
22589 (setq ts (org-schedule arg)))
22590 (org-agenda-show-new-time marker ts "S"))
22591 (message "Item scheduled for %s" ts)))
22593 (defun org-agenda-deadline (arg)
22594 "Schedule the item at point."
22595 (interactive "P")
22596 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22597 (org-agenda-check-no-diary)
22598 (let* ((marker (or (get-text-property (point) 'org-marker)
22599 (org-agenda-error)))
22600 (buffer (marker-buffer marker))
22601 (pos (marker-position marker))
22602 (org-insert-labeled-timestamps-at-point nil)
22604 (org-with-remote-undo buffer
22605 (with-current-buffer buffer
22606 (widen)
22607 (goto-char pos)
22608 (setq ts (org-deadline arg)))
22609 (org-agenda-show-new-time marker ts "S"))
22610 (message "Deadline for this item set to %s" ts)))
22612 (defun org-get-heading (&optional no-tags)
22613 "Return the heading of the current entry, without the stars."
22614 (save-excursion
22615 (org-back-to-heading t)
22616 (if (looking-at
22617 (if no-tags
22618 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22619 "\\*+[ \t]+\\([^\r\n]*\\)"))
22620 (match-string 1) "")))
22622 (defun org-agenda-clock-in (&optional arg)
22623 "Start the clock on the currently selected item."
22624 (interactive "P")
22625 (org-agenda-check-no-diary)
22626 (let* ((marker (or (get-text-property (point) 'org-marker)
22627 (org-agenda-error)))
22628 (pos (marker-position marker)))
22629 (org-with-remote-undo (marker-buffer marker)
22630 (with-current-buffer (marker-buffer marker)
22631 (widen)
22632 (goto-char pos)
22633 (org-clock-in)))))
22635 (defun org-agenda-clock-out (&optional arg)
22636 "Stop the currently running clock."
22637 (interactive "P")
22638 (unless (marker-buffer org-clock-marker)
22639 (error "No running clock"))
22640 (org-with-remote-undo (marker-buffer org-clock-marker)
22641 (org-clock-out)))
22643 (defun org-agenda-clock-cancel (&optional arg)
22644 "Cancel the currently running clock."
22645 (interactive "P")
22646 (unless (marker-buffer org-clock-marker)
22647 (error "No running clock"))
22648 (org-with-remote-undo (marker-buffer org-clock-marker)
22649 (org-clock-cancel)))
22651 (defun org-agenda-diary-entry ()
22652 "Make a diary entry, like the `i' command from the calendar.
22653 All the standard commands work: block, weekly etc."
22654 (interactive)
22655 (org-agenda-check-type t 'agenda 'timeline)
22656 (require 'diary-lib)
22657 (let* ((char (progn
22658 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22659 (read-char-exclusive)))
22660 (cmd (cdr (assoc char
22661 '((?d . insert-diary-entry)
22662 (?w . insert-weekly-diary-entry)
22663 (?m . insert-monthly-diary-entry)
22664 (?y . insert-yearly-diary-entry)
22665 (?a . insert-anniversary-diary-entry)
22666 (?b . insert-block-diary-entry)
22667 (?c . insert-cyclic-diary-entry)))))
22668 (oldf (symbol-function 'calendar-cursor-to-date))
22669 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22670 (point (point))
22671 (mark (or (mark t) (point))))
22672 (unless cmd
22673 (error "No command associated with <%c>" char))
22674 (unless (and (get-text-property point 'day)
22675 (or (not (equal ?b char))
22676 (get-text-property mark 'day)))
22677 (error "Don't know which date to use for diary entry"))
22678 ;; We implement this by hacking the `calendar-cursor-to-date' function
22679 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22680 (let ((calendar-mark-ring
22681 (list (calendar-gregorian-from-absolute
22682 (or (get-text-property mark 'day)
22683 (get-text-property point 'day))))))
22684 (unwind-protect
22685 (progn
22686 (fset 'calendar-cursor-to-date
22687 (lambda (&optional error)
22688 (calendar-gregorian-from-absolute
22689 (get-text-property point 'day))))
22690 (call-interactively cmd))
22691 (fset 'calendar-cursor-to-date oldf)))))
22694 (defun org-agenda-execute-calendar-command (cmd)
22695 "Execute a calendar command from the agenda, with the date associated to
22696 the cursor position."
22697 (org-agenda-check-type t 'agenda 'timeline)
22698 (require 'diary-lib)
22699 (unless (get-text-property (point) 'day)
22700 (error "Don't know which date to use for calendar command"))
22701 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22702 (point (point))
22703 (date (calendar-gregorian-from-absolute
22704 (get-text-property point 'day)))
22705 ;; the following 3 vars are needed in the calendar
22706 (displayed-day (extract-calendar-day date))
22707 (displayed-month (extract-calendar-month date))
22708 (displayed-year (extract-calendar-year date)))
22709 (unwind-protect
22710 (progn
22711 (fset 'calendar-cursor-to-date
22712 (lambda (&optional error)
22713 (calendar-gregorian-from-absolute
22714 (get-text-property point 'day))))
22715 (call-interactively cmd))
22716 (fset 'calendar-cursor-to-date oldf))))
22718 (defun org-agenda-phases-of-moon ()
22719 "Display the phases of the moon for the 3 months around the cursor date."
22720 (interactive)
22721 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22723 (defun org-agenda-holidays ()
22724 "Display the holidays for the 3 months around the cursor date."
22725 (interactive)
22726 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22728 (defun org-agenda-sunrise-sunset (arg)
22729 "Display sunrise and sunset for the cursor date.
22730 Latitude and longitude can be specified with the variables
22731 `calendar-latitude' and `calendar-longitude'. When called with prefix
22732 argument, latitude and longitude will be prompted for."
22733 (interactive "P")
22734 (let ((calendar-longitude (if arg nil calendar-longitude))
22735 (calendar-latitude (if arg nil calendar-latitude))
22736 (calendar-location-name
22737 (if arg "the given coordinates" calendar-location-name)))
22738 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22740 (defun org-agenda-goto-calendar ()
22741 "Open the Emacs calendar with the date at the cursor."
22742 (interactive)
22743 (org-agenda-check-type t 'agenda 'timeline)
22744 (let* ((day (or (get-text-property (point) 'day)
22745 (error "Don't know which date to open in calendar")))
22746 (date (calendar-gregorian-from-absolute day))
22747 (calendar-move-hook nil)
22748 (view-calendar-holidays-initially nil)
22749 (view-diary-entries-initially nil))
22750 (calendar)
22751 (calendar-goto-date date)))
22753 (defun org-calendar-goto-agenda ()
22754 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
22755 This is a command that has to be installed in `calendar-mode-map'."
22756 (interactive)
22757 (org-agenda-list nil (calendar-absolute-from-gregorian
22758 (calendar-cursor-to-date))
22759 nil))
22761 (defun org-agenda-convert-date ()
22762 (interactive)
22763 (org-agenda-check-type t 'agenda 'timeline)
22764 (let ((day (get-text-property (point) 'day))
22765 date s)
22766 (unless day
22767 (error "Don't know which date to convert"))
22768 (setq date (calendar-gregorian-from-absolute day))
22769 (setq s (concat
22770 "Gregorian: " (calendar-date-string date) "\n"
22771 "ISO: " (calendar-iso-date-string date) "\n"
22772 "Day of Yr: " (calendar-day-of-year-string date) "\n"
22773 "Julian: " (calendar-julian-date-string date) "\n"
22774 "Astron. JD: " (calendar-astro-date-string date)
22775 " (Julian date number at noon UTC)\n"
22776 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
22777 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
22778 "French: " (calendar-french-date-string date) "\n"
22779 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
22780 "Mayan: " (calendar-mayan-date-string date) "\n"
22781 "Coptic: " (calendar-coptic-date-string date) "\n"
22782 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
22783 "Persian: " (calendar-persian-date-string date) "\n"
22784 "Chinese: " (calendar-chinese-date-string date) "\n"))
22785 (with-output-to-temp-buffer "*Dates*"
22786 (princ s))
22787 (if (fboundp 'fit-window-to-buffer)
22788 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
22791 ;;;; Embedded LaTeX
22793 (defvar org-cdlatex-mode-map (make-sparse-keymap)
22794 "Keymap for the minor `org-cdlatex-mode'.")
22796 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
22797 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
22798 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
22799 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
22800 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
22802 (defvar org-cdlatex-texmathp-advice-is-done nil
22803 "Flag remembering if we have applied the advice to texmathp already.")
22805 (define-minor-mode org-cdlatex-mode
22806 "Toggle the minor `org-cdlatex-mode'.
22807 This mode supports entering LaTeX environment and math in LaTeX fragments
22808 in Org-mode.
22809 \\{org-cdlatex-mode-map}"
22810 nil " OCDL" nil
22811 (when org-cdlatex-mode (require 'cdlatex))
22812 (unless org-cdlatex-texmathp-advice-is-done
22813 (setq org-cdlatex-texmathp-advice-is-done t)
22814 (defadvice texmathp (around org-math-always-on activate)
22815 "Always return t in org-mode buffers.
22816 This is because we want to insert math symbols without dollars even outside
22817 the LaTeX math segments. If Orgmode thinks that point is actually inside
22818 en embedded LaTeX fragement, let texmathp do its job.
22819 \\[org-cdlatex-mode-map]"
22820 (interactive)
22821 (let (p)
22822 (cond
22823 ((not (org-mode-p)) ad-do-it)
22824 ((eq this-command 'cdlatex-math-symbol)
22825 (setq ad-return-value t
22826 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
22828 (let ((p (org-inside-LaTeX-fragment-p)))
22829 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
22830 (setq ad-return-value t
22831 texmathp-why '("Org-mode embedded math" . 0))
22832 (if p ad-do-it)))))))))
22834 (defun turn-on-org-cdlatex ()
22835 "Unconditionally turn on `org-cdlatex-mode'."
22836 (org-cdlatex-mode 1))
22838 (defun org-inside-LaTeX-fragment-p ()
22839 "Test if point is inside a LaTeX fragment.
22840 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
22841 sequence appearing also before point.
22842 Even though the matchers for math are configurable, this function assumes
22843 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
22844 delimiters are skipped when they have been removed by customization.
22845 The return value is nil, or a cons cell with the delimiter and
22846 and the position of this delimiter.
22848 This function does a reasonably good job, but can locally be fooled by
22849 for example currency specifications. For example it will assume being in
22850 inline math after \"$22.34\". The LaTeX fragment formatter will only format
22851 fragments that are properly closed, but during editing, we have to live
22852 with the uncertainty caused by missing closing delimiters. This function
22853 looks only before point, not after."
22854 (catch 'exit
22855 (let ((pos (point))
22856 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
22857 (lim (progn
22858 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
22859 (point)))
22860 dd-on str (start 0) m re)
22861 (goto-char pos)
22862 (when dodollar
22863 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
22864 re (nth 1 (assoc "$" org-latex-regexps)))
22865 (while (string-match re str start)
22866 (cond
22867 ((= (match-end 0) (length str))
22868 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
22869 ((= (match-end 0) (- (length str) 5))
22870 (throw 'exit nil))
22871 (t (setq start (match-end 0))))))
22872 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
22873 (goto-char pos)
22874 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
22875 (and (match-beginning 2) (throw 'exit nil))
22876 ;; count $$
22877 (while (re-search-backward "\\$\\$" lim t)
22878 (setq dd-on (not dd-on)))
22879 (goto-char pos)
22880 (if dd-on (cons "$$" m))))))
22883 (defun org-try-cdlatex-tab ()
22884 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
22885 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
22886 - inside a LaTeX fragment, or
22887 - after the first word in a line, where an abbreviation expansion could
22888 insert a LaTeX environment."
22889 (when org-cdlatex-mode
22890 (cond
22891 ((save-excursion
22892 (skip-chars-backward "a-zA-Z0-9*")
22893 (skip-chars-backward " \t")
22894 (bolp))
22895 (cdlatex-tab) t)
22896 ((org-inside-LaTeX-fragment-p)
22897 (cdlatex-tab) t)
22898 (t nil))))
22900 (defun org-cdlatex-underscore-caret (&optional arg)
22901 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
22902 Revert to the normal definition outside of these fragments."
22903 (interactive "P")
22904 (if (org-inside-LaTeX-fragment-p)
22905 (call-interactively 'cdlatex-sub-superscript)
22906 (let (org-cdlatex-mode)
22907 (call-interactively (key-binding (vector last-input-event))))))
22909 (defun org-cdlatex-math-modify (&optional arg)
22910 "Execute `cdlatex-math-modify' in LaTeX fragments.
22911 Revert to the normal definition outside of these fragments."
22912 (interactive "P")
22913 (if (org-inside-LaTeX-fragment-p)
22914 (call-interactively 'cdlatex-math-modify)
22915 (let (org-cdlatex-mode)
22916 (call-interactively (key-binding (vector last-input-event))))))
22918 (defvar org-latex-fragment-image-overlays nil
22919 "List of overlays carrying the images of latex fragments.")
22920 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
22922 (defun org-remove-latex-fragment-image-overlays ()
22923 "Remove all overlays with LaTeX fragment images in current buffer."
22924 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
22925 (setq org-latex-fragment-image-overlays nil))
22927 (defun org-preview-latex-fragment (&optional subtree)
22928 "Preview the LaTeX fragment at point, or all locally or globally.
22929 If the cursor is in a LaTeX fragment, create the image and overlay
22930 it over the source code. If there is no fragment at point, display
22931 all fragments in the current text, from one headline to the next. With
22932 prefix SUBTREE, display all fragments in the current subtree. With a
22933 double prefix `C-u C-u', or when the cursor is before the first headline,
22934 display all fragments in the buffer.
22935 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
22936 (interactive "P")
22937 (org-remove-latex-fragment-image-overlays)
22938 (save-excursion
22939 (save-restriction
22940 (let (beg end at msg)
22941 (cond
22942 ((or (equal subtree '(16))
22943 (not (save-excursion
22944 (re-search-backward (concat "^" outline-regexp) nil t))))
22945 (setq beg (point-min) end (point-max)
22946 msg "Creating images for buffer...%s"))
22947 ((equal subtree '(4))
22948 (org-back-to-heading)
22949 (setq beg (point) end (org-end-of-subtree t)
22950 msg "Creating images for subtree...%s"))
22952 (if (setq at (org-inside-LaTeX-fragment-p))
22953 (goto-char (max (point-min) (- (cdr at) 2)))
22954 (org-back-to-heading))
22955 (setq beg (point) end (progn (outline-next-heading) (point))
22956 msg (if at "Creating image...%s"
22957 "Creating images for entry...%s"))))
22958 (message msg "")
22959 (narrow-to-region beg end)
22960 (goto-char beg)
22961 (org-format-latex
22962 (concat "ltxpng/" (file-name-sans-extension
22963 (file-name-nondirectory
22964 buffer-file-name)))
22965 default-directory 'overlays msg at 'forbuffer)
22966 (message msg "done. Use `C-c C-c' to remove images.")))))
22968 (defvar org-latex-regexps
22969 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
22970 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
22971 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
22972 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
22973 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
22974 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
22975 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
22976 "Regular expressions for matching embedded LaTeX.")
22978 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
22979 "Replace LaTeX fragments with links to an image, and produce images."
22980 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
22981 (let* ((prefixnodir (file-name-nondirectory prefix))
22982 (absprefix (expand-file-name prefix dir))
22983 (todir (file-name-directory absprefix))
22984 (opt org-format-latex-options)
22985 (matchers (plist-get opt :matchers))
22986 (re-list org-latex-regexps)
22987 (cnt 0) txt link beg end re e checkdir
22988 m n block linkfile movefile ov)
22989 ;; Check if there are old images files with this prefix, and remove them
22990 (when (file-directory-p todir)
22991 (mapc 'delete-file
22992 (directory-files
22993 todir 'full
22994 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
22995 ;; Check the different regular expressions
22996 (while (setq e (pop re-list))
22997 (setq m (car e) re (nth 1 e) n (nth 2 e)
22998 block (if (nth 3 e) "\n\n" ""))
22999 (when (member m matchers)
23000 (goto-char (point-min))
23001 (while (re-search-forward re nil t)
23002 (when (or (not at) (equal (cdr at) (match-beginning n)))
23003 (setq txt (match-string n)
23004 beg (match-beginning n) end (match-end n)
23005 cnt (1+ cnt)
23006 linkfile (format "%s_%04d.png" prefix cnt)
23007 movefile (format "%s_%04d.png" absprefix cnt)
23008 link (concat block "[[file:" linkfile "]]" block))
23009 (if msg (message msg cnt))
23010 (goto-char beg)
23011 (unless checkdir ; make sure the directory exists
23012 (setq checkdir t)
23013 (or (file-directory-p todir) (make-directory todir)))
23014 (org-create-formula-image
23015 txt movefile opt forbuffer)
23016 (if overlays
23017 (progn
23018 (setq ov (org-make-overlay beg end))
23019 (if (featurep 'xemacs)
23020 (progn
23021 (org-overlay-put ov 'invisible t)
23022 (org-overlay-put
23023 ov 'end-glyph
23024 (make-glyph (vector 'png :file movefile))))
23025 (org-overlay-put
23026 ov 'display
23027 (list 'image :type 'png :file movefile :ascent 'center)))
23028 (push ov org-latex-fragment-image-overlays)
23029 (goto-char end))
23030 (delete-region beg end)
23031 (insert link))))))))
23033 ;; This function borrows from Ganesh Swami's latex2png.el
23034 (defun org-create-formula-image (string tofile options buffer)
23035 (let* ((tmpdir (if (featurep 'xemacs)
23036 (temp-directory)
23037 temporary-file-directory))
23038 (texfilebase (make-temp-name
23039 (expand-file-name "orgtex" tmpdir)))
23040 (texfile (concat texfilebase ".tex"))
23041 (dvifile (concat texfilebase ".dvi"))
23042 (pngfile (concat texfilebase ".png"))
23043 (fnh (face-attribute 'default :height nil))
23044 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23045 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23046 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23047 "Black"))
23048 (bg (or (plist-get options (if buffer :background :html-background))
23049 "Transparent")))
23050 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23051 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23052 (with-temp-file texfile
23053 (insert org-format-latex-header
23054 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23055 (let ((dir default-directory))
23056 (condition-case nil
23057 (progn
23058 (cd tmpdir)
23059 (call-process "latex" nil nil nil texfile))
23060 (error nil))
23061 (cd dir))
23062 (if (not (file-exists-p dvifile))
23063 (progn (message "Failed to create dvi file from %s" texfile) nil)
23064 (call-process "dvipng" nil nil nil
23065 "-E" "-fg" fg "-bg" bg
23066 "-D" dpi
23067 ;;"-x" scale "-y" scale
23068 "-T" "tight"
23069 "-o" pngfile
23070 dvifile)
23071 (if (not (file-exists-p pngfile))
23072 (progn (message "Failed to create png file from %s" texfile) nil)
23073 ;; Use the requested file name and clean up
23074 (copy-file pngfile tofile 'replace)
23075 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23076 (delete-file (concat texfilebase e)))
23077 pngfile))))
23079 (defun org-dvipng-color (attr)
23080 "Return an rgb color specification for dvipng."
23081 (apply 'format "rgb %s %s %s"
23082 (mapcar 'org-normalize-color
23083 (color-values (face-attribute 'default attr nil)))))
23085 (defun org-normalize-color (value)
23086 "Return string to be used as color value for an RGB component."
23087 (format "%g" (/ value 65535.0)))
23089 ;;;; Exporting
23091 ;;; Variables, constants, and parameter plists
23093 (defconst org-level-max 20)
23095 (defvar org-export-html-preamble nil
23096 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23097 (defvar org-export-html-postamble nil
23098 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23099 (defvar org-export-html-auto-preamble t
23100 "Should default preamble be inserted? Set by publishing functions.")
23101 (defvar org-export-html-auto-postamble t
23102 "Should default postamble be inserted? Set by publishing functions.")
23103 (defvar org-current-export-file nil) ; dynamically scoped parameter
23104 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23107 (defconst org-export-plist-vars
23108 '((:language . org-export-default-language)
23109 (:customtime . org-display-custom-times)
23110 (:headline-levels . org-export-headline-levels)
23111 (:section-numbers . org-export-with-section-numbers)
23112 (:table-of-contents . org-export-with-toc)
23113 (:preserve-breaks . org-export-preserve-breaks)
23114 (:archived-trees . org-export-with-archived-trees)
23115 (:emphasize . org-export-with-emphasize)
23116 (:sub-superscript . org-export-with-sub-superscripts)
23117 (:special-strings . org-export-with-special-strings)
23118 (:footnotes . org-export-with-footnotes)
23119 (:drawers . org-export-with-drawers)
23120 (:tags . org-export-with-tags)
23121 (:TeX-macros . org-export-with-TeX-macros)
23122 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23123 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23124 (:fixed-width . org-export-with-fixed-width)
23125 (:timestamps . org-export-with-timestamps)
23126 (:author-info . org-export-author-info)
23127 (:time-stamp-file . org-export-time-stamp-file)
23128 (:tables . org-export-with-tables)
23129 (:table-auto-headline . org-export-highlight-first-table-line)
23130 (:style . org-export-html-style)
23131 (:agenda-style . org-agenda-export-html-style)
23132 (:convert-org-links . org-export-html-link-org-files-as-html)
23133 (:inline-images . org-export-html-inline-images)
23134 (:html-extension . org-export-html-extension)
23135 (:html-table-tag . org-export-html-table-tag)
23136 (:expand-quoted-html . org-export-html-expand)
23137 (:timestamp . org-export-html-with-timestamp)
23138 (:publishing-directory . org-export-publishing-directory)
23139 (:preamble . org-export-html-preamble)
23140 (:postamble . org-export-html-postamble)
23141 (:auto-preamble . org-export-html-auto-preamble)
23142 (:auto-postamble . org-export-html-auto-postamble)
23143 (:author . user-full-name)
23144 (:email . user-mail-address)))
23146 (defun org-default-export-plist ()
23147 "Return the property list with default settings for the export variables."
23148 (let ((l org-export-plist-vars) rtn e)
23149 (while (setq e (pop l))
23150 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23151 rtn))
23153 (defun org-infile-export-plist ()
23154 "Return the property list with file-local settings for export."
23155 (save-excursion
23156 (save-restriction
23157 (widen)
23158 (goto-char 0)
23159 (let ((re (org-make-options-regexp
23160 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23161 p key val text options)
23162 (while (re-search-forward re nil t)
23163 (setq key (org-match-string-no-properties 1)
23164 val (org-match-string-no-properties 2))
23165 (cond
23166 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23167 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23168 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23169 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23170 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23171 ((string-equal key "TEXT")
23172 (setq text (if text (concat text "\n" val) val)))
23173 ((string-equal key "OPTIONS") (setq options val))))
23174 (setq p (plist-put p :text text))
23175 (when options
23176 (let ((op '(("H" . :headline-levels)
23177 ("num" . :section-numbers)
23178 ("toc" . :table-of-contents)
23179 ("\\n" . :preserve-breaks)
23180 ("@" . :expand-quoted-html)
23181 (":" . :fixed-width)
23182 ("|" . :tables)
23183 ("^" . :sub-superscript)
23184 ("-" . :special-strings)
23185 ("f" . :footnotes)
23186 ("d" . :drawers)
23187 ("tags" . :tags)
23188 ("*" . :emphasize)
23189 ("TeX" . :TeX-macros)
23190 ("LaTeX" . :LaTeX-fragments)
23191 ("skip" . :skip-before-1st-heading)
23192 ("author" . :author-info)
23193 ("timestamp" . :time-stamp-file)))
23195 (while (setq o (pop op))
23196 (if (string-match (concat (regexp-quote (car o))
23197 ":\\([^ \t\n\r;,.]*\\)")
23198 options)
23199 (setq p (plist-put p (cdr o)
23200 (car (read-from-string
23201 (match-string 1 options)))))))))
23202 p))))
23204 (defun org-export-directory (type plist)
23205 (let* ((val (plist-get plist :publishing-directory))
23206 (dir (if (listp val)
23207 (or (cdr (assoc type val)) ".")
23208 val)))
23209 dir))
23211 (defun org-skip-comments (lines)
23212 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23213 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23214 (re2 "^\\(\\*+\\)[ \t\n\r]")
23215 (case-fold-search nil)
23216 rtn line level)
23217 (while (setq line (pop lines))
23218 (cond
23219 ((and (string-match re1 line)
23220 (setq level (- (match-end 1) (match-beginning 1))))
23221 ;; Beginning of a COMMENT subtree. Skip it.
23222 (while (and (setq line (pop lines))
23223 (or (not (string-match re2 line))
23224 (> (- (match-end 1) (match-beginning 1)) level))))
23225 (setq lines (cons line lines)))
23226 ((string-match "^#" line)
23227 ;; an ordinary comment line
23229 ((and org-export-table-remove-special-lines
23230 (string-match "^[ \t]*|" line)
23231 (or (string-match "^[ \t]*| *[!_^] *|" line)
23232 (and (string-match "| *<[0-9]+> *|" line)
23233 (not (string-match "| *[^ <|]" line)))))
23234 ;; a special table line that should be removed
23236 (t (setq rtn (cons line rtn)))))
23237 (nreverse rtn)))
23239 (defun org-export (&optional arg)
23240 (interactive)
23241 (let ((help "[t] insert the export option template
23242 \[v] limit export to visible part of outline tree
23244 \[a] export as ASCII
23246 \[h] export as HTML
23247 \[H] export as HTML to temporary buffer
23248 \[R] export region as HTML
23249 \[b] export as HTML and browse immediately
23250 \[x] export as XOXO
23252 \[l] export as LaTeX
23253 \[L] export as LaTeX to temporary buffer
23255 \[i] export current file as iCalendar file
23256 \[I] export all agenda files as iCalendar files
23257 \[c] export agenda files into combined iCalendar file
23259 \[F] publish current file
23260 \[P] publish current project
23261 \[X] publish... (project will be prompted for)
23262 \[A] publish all projects")
23263 (cmds
23264 '((?t . org-insert-export-options-template)
23265 (?v . org-export-visible)
23266 (?a . org-export-as-ascii)
23267 (?h . org-export-as-html)
23268 (?b . org-export-as-html-and-open)
23269 (?H . org-export-as-html-to-buffer)
23270 (?R . org-export-region-as-html)
23271 (?x . org-export-as-xoxo)
23272 (?l . org-export-as-latex)
23273 (?L . org-export-as-latex-to-buffer)
23274 (?i . org-export-icalendar-this-file)
23275 (?I . org-export-icalendar-all-agenda-files)
23276 (?c . org-export-icalendar-combine-agenda-files)
23277 (?F . org-publish-current-file)
23278 (?P . org-publish-current-project)
23279 (?X . org-publish)
23280 (?A . org-publish-all)))
23281 r1 r2 ass)
23282 (save-window-excursion
23283 (delete-other-windows)
23284 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23285 (princ help))
23286 (message "Select command: ")
23287 (setq r1 (read-char-exclusive)))
23288 (setq r2 (if (< r1 27) (+ r1 96) r1))
23289 (if (setq ass (assq r2 cmds))
23290 (call-interactively (cdr ass))
23291 (error "No command associated with key %c" r1))))
23293 (defconst org-html-entities
23294 '(("nbsp")
23295 ("iexcl")
23296 ("cent")
23297 ("pound")
23298 ("curren")
23299 ("yen")
23300 ("brvbar")
23301 ("vert" . "&#124;")
23302 ("sect")
23303 ("uml")
23304 ("copy")
23305 ("ordf")
23306 ("laquo")
23307 ("not")
23308 ("shy")
23309 ("reg")
23310 ("macr")
23311 ("deg")
23312 ("plusmn")
23313 ("sup2")
23314 ("sup3")
23315 ("acute")
23316 ("micro")
23317 ("para")
23318 ("middot")
23319 ("odot"."o")
23320 ("star"."*")
23321 ("cedil")
23322 ("sup1")
23323 ("ordm")
23324 ("raquo")
23325 ("frac14")
23326 ("frac12")
23327 ("frac34")
23328 ("iquest")
23329 ("Agrave")
23330 ("Aacute")
23331 ("Acirc")
23332 ("Atilde")
23333 ("Auml")
23334 ("Aring") ("AA"."&Aring;")
23335 ("AElig")
23336 ("Ccedil")
23337 ("Egrave")
23338 ("Eacute")
23339 ("Ecirc")
23340 ("Euml")
23341 ("Igrave")
23342 ("Iacute")
23343 ("Icirc")
23344 ("Iuml")
23345 ("ETH")
23346 ("Ntilde")
23347 ("Ograve")
23348 ("Oacute")
23349 ("Ocirc")
23350 ("Otilde")
23351 ("Ouml")
23352 ("times")
23353 ("Oslash")
23354 ("Ugrave")
23355 ("Uacute")
23356 ("Ucirc")
23357 ("Uuml")
23358 ("Yacute")
23359 ("THORN")
23360 ("szlig")
23361 ("agrave")
23362 ("aacute")
23363 ("acirc")
23364 ("atilde")
23365 ("auml")
23366 ("aring")
23367 ("aelig")
23368 ("ccedil")
23369 ("egrave")
23370 ("eacute")
23371 ("ecirc")
23372 ("euml")
23373 ("igrave")
23374 ("iacute")
23375 ("icirc")
23376 ("iuml")
23377 ("eth")
23378 ("ntilde")
23379 ("ograve")
23380 ("oacute")
23381 ("ocirc")
23382 ("otilde")
23383 ("ouml")
23384 ("divide")
23385 ("oslash")
23386 ("ugrave")
23387 ("uacute")
23388 ("ucirc")
23389 ("uuml")
23390 ("yacute")
23391 ("thorn")
23392 ("yuml")
23393 ("fnof")
23394 ("Alpha")
23395 ("Beta")
23396 ("Gamma")
23397 ("Delta")
23398 ("Epsilon")
23399 ("Zeta")
23400 ("Eta")
23401 ("Theta")
23402 ("Iota")
23403 ("Kappa")
23404 ("Lambda")
23405 ("Mu")
23406 ("Nu")
23407 ("Xi")
23408 ("Omicron")
23409 ("Pi")
23410 ("Rho")
23411 ("Sigma")
23412 ("Tau")
23413 ("Upsilon")
23414 ("Phi")
23415 ("Chi")
23416 ("Psi")
23417 ("Omega")
23418 ("alpha")
23419 ("beta")
23420 ("gamma")
23421 ("delta")
23422 ("epsilon")
23423 ("varepsilon"."&epsilon;")
23424 ("zeta")
23425 ("eta")
23426 ("theta")
23427 ("iota")
23428 ("kappa")
23429 ("lambda")
23430 ("mu")
23431 ("nu")
23432 ("xi")
23433 ("omicron")
23434 ("pi")
23435 ("rho")
23436 ("sigmaf") ("varsigma"."&sigmaf;")
23437 ("sigma")
23438 ("tau")
23439 ("upsilon")
23440 ("phi")
23441 ("chi")
23442 ("psi")
23443 ("omega")
23444 ("thetasym") ("vartheta"."&thetasym;")
23445 ("upsih")
23446 ("piv")
23447 ("bull") ("bullet"."&bull;")
23448 ("hellip") ("dots"."&hellip;")
23449 ("prime")
23450 ("Prime")
23451 ("oline")
23452 ("frasl")
23453 ("weierp")
23454 ("image")
23455 ("real")
23456 ("trade")
23457 ("alefsym")
23458 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23459 ("uarr") ("uparrow"."&uarr;")
23460 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23461 ("darr")("downarrow"."&darr;")
23462 ("harr") ("leftrightarrow"."&harr;")
23463 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23464 ("lArr") ("Leftarrow"."&lArr;")
23465 ("uArr") ("Uparrow"."&uArr;")
23466 ("rArr") ("Rightarrow"."&rArr;")
23467 ("dArr") ("Downarrow"."&dArr;")
23468 ("hArr") ("Leftrightarrow"."&hArr;")
23469 ("forall")
23470 ("part") ("partial"."&part;")
23471 ("exist") ("exists"."&exist;")
23472 ("empty") ("emptyset"."&empty;")
23473 ("nabla")
23474 ("isin") ("in"."&isin;")
23475 ("notin")
23476 ("ni")
23477 ("prod")
23478 ("sum")
23479 ("minus")
23480 ("lowast") ("ast"."&lowast;")
23481 ("radic")
23482 ("prop") ("proptp"."&prop;")
23483 ("infin") ("infty"."&infin;")
23484 ("ang") ("angle"."&ang;")
23485 ("and") ("wedge"."&and;")
23486 ("or") ("vee"."&or;")
23487 ("cap")
23488 ("cup")
23489 ("int")
23490 ("there4")
23491 ("sim")
23492 ("cong") ("simeq"."&cong;")
23493 ("asymp")("approx"."&asymp;")
23494 ("ne") ("neq"."&ne;")
23495 ("equiv")
23496 ("le")
23497 ("ge")
23498 ("sub") ("subset"."&sub;")
23499 ("sup") ("supset"."&sup;")
23500 ("nsub")
23501 ("sube")
23502 ("supe")
23503 ("oplus")
23504 ("otimes")
23505 ("perp")
23506 ("sdot") ("cdot"."&sdot;")
23507 ("lceil")
23508 ("rceil")
23509 ("lfloor")
23510 ("rfloor")
23511 ("lang")
23512 ("rang")
23513 ("loz") ("Diamond"."&loz;")
23514 ("spades") ("spadesuit"."&spades;")
23515 ("clubs") ("clubsuit"."&clubs;")
23516 ("hearts") ("diamondsuit"."&hearts;")
23517 ("diams") ("diamondsuit"."&diams;")
23518 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23519 ("quot")
23520 ("amp")
23521 ("lt")
23522 ("gt")
23523 ("OElig")
23524 ("oelig")
23525 ("Scaron")
23526 ("scaron")
23527 ("Yuml")
23528 ("circ")
23529 ("tilde")
23530 ("ensp")
23531 ("emsp")
23532 ("thinsp")
23533 ("zwnj")
23534 ("zwj")
23535 ("lrm")
23536 ("rlm")
23537 ("ndash")
23538 ("mdash")
23539 ("lsquo")
23540 ("rsquo")
23541 ("sbquo")
23542 ("ldquo")
23543 ("rdquo")
23544 ("bdquo")
23545 ("dagger")
23546 ("Dagger")
23547 ("permil")
23548 ("lsaquo")
23549 ("rsaquo")
23550 ("euro")
23552 ("arccos"."arccos")
23553 ("arcsin"."arcsin")
23554 ("arctan"."arctan")
23555 ("arg"."arg")
23556 ("cos"."cos")
23557 ("cosh"."cosh")
23558 ("cot"."cot")
23559 ("coth"."coth")
23560 ("csc"."csc")
23561 ("deg"."deg")
23562 ("det"."det")
23563 ("dim"."dim")
23564 ("exp"."exp")
23565 ("gcd"."gcd")
23566 ("hom"."hom")
23567 ("inf"."inf")
23568 ("ker"."ker")
23569 ("lg"."lg")
23570 ("lim"."lim")
23571 ("liminf"."liminf")
23572 ("limsup"."limsup")
23573 ("ln"."ln")
23574 ("log"."log")
23575 ("max"."max")
23576 ("min"."min")
23577 ("Pr"."Pr")
23578 ("sec"."sec")
23579 ("sin"."sin")
23580 ("sinh"."sinh")
23581 ("sup"."sup")
23582 ("tan"."tan")
23583 ("tanh"."tanh")
23585 "Entities for TeX->HTML translation.
23586 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23587 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23588 In that case, \"\\ent\" will be translated to \"&other;\".
23589 The list contains HTML entities for Latin-1, Greek and other symbols.
23590 It is supplemented by a number of commonly used TeX macros with appropriate
23591 translations. There is currently no way for users to extend this.")
23593 ;;; General functions for all backends
23595 (defun org-cleaned-string-for-export (string &rest parameters)
23596 "Cleanup a buffer STRING so that links can be created safely."
23597 (interactive)
23598 (let* ((re-radio (and org-target-link-regexp
23599 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23600 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23601 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23602 (re-archive (concat ":" org-archive-tag ":"))
23603 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23604 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23605 (htmlp (plist-get parameters :for-html))
23606 (asciip (plist-get parameters :for-ascii))
23607 (latexp (plist-get parameters :for-LaTeX))
23608 (commentsp (plist-get parameters :comments))
23609 (archived-trees (plist-get parameters :archived-trees))
23610 (inhibit-read-only t)
23611 (drawers org-drawers)
23612 (exp-drawers (plist-get parameters :drawers))
23613 (outline-regexp "\\*+ ")
23614 a b xx
23615 rtn p)
23616 (with-current-buffer (get-buffer-create " org-mode-tmp")
23617 (erase-buffer)
23618 (insert string)
23619 ;; Remove license-to-kill stuff
23620 (while (setq p (text-property-any (point-min) (point-max)
23621 :org-license-to-kill t))
23622 (delete-region p (next-single-property-change p :org-license-to-kill)))
23624 (let ((org-inhibit-startup t)) (org-mode))
23625 (untabify (point-min) (point-max))
23627 ;; Get the correct stuff before the first headline
23628 (when (plist-get parameters :skip-before-1st-heading)
23629 (goto-char (point-min))
23630 (when (re-search-forward "^\\*+[ \t]" nil t)
23631 (delete-region (point-min) (match-beginning 0))
23632 (goto-char (point-min))
23633 (insert "\n")))
23634 (when (plist-get parameters :add-text)
23635 (goto-char (point-min))
23636 (insert (plist-get parameters :add-text) "\n"))
23638 ;; Get rid of archived trees
23639 (when (not (eq archived-trees t))
23640 (goto-char (point-min))
23641 (while (re-search-forward re-archive nil t)
23642 (if (not (org-on-heading-p t))
23643 (org-end-of-subtree t)
23644 (beginning-of-line 1)
23645 (setq a (if archived-trees
23646 (1+ (point-at-eol)) (point))
23647 b (org-end-of-subtree t))
23648 (if (> b a) (delete-region a b)))))
23650 ;; Get rid of drawers
23651 (unless (eq t exp-drawers)
23652 (goto-char (point-min))
23653 (let ((re (concat "^[ \t]*:\\("
23654 (mapconcat
23655 'identity
23656 (org-delete-all exp-drawers
23657 (copy-sequence drawers))
23658 "\\|")
23659 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23660 (while (re-search-forward re nil t)
23661 (replace-match ""))))
23663 ;; Find targets in comments and move them out of comments,
23664 ;; but mark them as targets that should be invisible
23665 (goto-char (point-min))
23666 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23667 (replace-match "\\1(INVISIBLE)"))
23669 ;; Protect backend specific stuff, throw away the others.
23670 (let ((formatters
23671 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23672 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23673 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23674 fmt)
23675 (goto-char (point-min))
23676 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23677 (goto-char (match-end 0))
23678 (while (not (looking-at "#\\+END_EXAMPLE"))
23679 (insert ": ")
23680 (beginning-of-line 2)))
23681 (goto-char (point-min))
23682 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23683 (add-text-properties (match-beginning 0) (match-end 0)
23684 '(org-protected t)))
23685 (while formatters
23686 (setq fmt (pop formatters))
23687 (when (car fmt)
23688 (goto-char (point-min))
23689 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23690 ":[ \t]*\\(.*\\)") nil t)
23691 (replace-match "\\1" t)
23692 (add-text-properties
23693 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23694 '(org-protected t))))
23695 (goto-char (point-min))
23696 (while (re-search-forward
23697 (concat "^#\\+"
23698 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23699 (cadddr fmt) "\\>.*\n?") nil t)
23700 (if (car fmt)
23701 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23702 '(org-protected t))
23703 (delete-region (match-beginning 0) (match-end 0))))))
23705 ;; Protect quoted subtrees
23706 (goto-char (point-min))
23707 (while (re-search-forward re-quote nil t)
23708 (goto-char (match-beginning 0))
23709 (end-of-line 1)
23710 (add-text-properties (point) (org-end-of-subtree t)
23711 '(org-protected t)))
23713 ;; Protect verbatim elements
23714 (goto-char (point-min))
23715 (while (re-search-forward org-verbatim-re nil t)
23716 (add-text-properties (match-beginning 4) (match-end 4)
23717 '(org-protected t))
23718 (goto-char (1+ (match-end 4))))
23720 ;; Remove subtrees that are commented
23721 (goto-char (point-min))
23722 (while (re-search-forward re-commented nil t)
23723 (goto-char (match-beginning 0))
23724 (delete-region (point) (org-end-of-subtree t)))
23726 ;; Remove special table lines
23727 (when org-export-table-remove-special-lines
23728 (goto-char (point-min))
23729 (while (re-search-forward "^[ \t]*|" nil t)
23730 (beginning-of-line 1)
23731 (if (or (looking-at "[ \t]*| *[!_^] *|")
23732 (and (looking-at ".*?| *<[0-9]+> *|")
23733 (not (looking-at ".*?| *[^ <|]"))))
23734 (delete-region (max (point-min) (1- (point-at-bol)))
23735 (point-at-eol))
23736 (end-of-line 1))))
23738 ;; Specific LaTeX stuff
23739 (when latexp
23740 (require 'org-export-latex nil)
23741 (org-export-latex-cleaned-string))
23743 (when asciip
23744 (org-export-ascii-clean-string))
23746 ;; Specific HTML stuff
23747 (when htmlp
23748 ;; Convert LaTeX fragments to images
23749 (when (plist-get parameters :LaTeX-fragments)
23750 (org-format-latex
23751 (concat "ltxpng/" (file-name-sans-extension
23752 (file-name-nondirectory
23753 org-current-export-file)))
23754 org-current-export-dir nil "Creating LaTeX image %s"))
23755 (message "Exporting..."))
23757 ;; Remove or replace comments
23758 (goto-char (point-min))
23759 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
23760 (if commentsp
23761 (progn (add-text-properties
23762 (match-beginning 0) (match-end 0) '(org-protected t))
23763 (replace-match (format commentsp (match-string 1)) t t))
23764 (replace-match "")))
23766 ;; Find matches for radio targets and turn them into internal links
23767 (goto-char (point-min))
23768 (when re-radio
23769 (while (re-search-forward re-radio nil t)
23770 (org-if-unprotected
23771 (replace-match "\\1[[\\2]]"))))
23773 ;; Find all links that contain a newline and put them into a single line
23774 (goto-char (point-min))
23775 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
23776 (org-if-unprotected
23777 (replace-match "\\1 \\3")
23778 (goto-char (match-beginning 0))))
23781 ;; Normalize links: Convert angle and plain links into bracket links
23782 ;; Expand link abbreviations
23783 (goto-char (point-min))
23784 (while (re-search-forward re-plain-link nil t)
23785 (goto-char (1- (match-end 0)))
23786 (org-if-unprotected
23787 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23788 ":" (match-string 3) "]]")))
23789 ;; added 'org-link face to links
23790 (put-text-property 0 (length s) 'face 'org-link s)
23791 (replace-match s t t))))
23792 (goto-char (point-min))
23793 (while (re-search-forward re-angle-link nil t)
23794 (goto-char (1- (match-end 0)))
23795 (org-if-unprotected
23796 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23797 ":" (match-string 3) "]]")))
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 org-bracket-link-regexp nil t)
23802 (org-if-unprotected
23803 (let* ((s (concat "[[" (setq xx (save-match-data
23804 (org-link-expand-abbrev (match-string 1))))
23806 (if (match-end 3)
23807 (match-string 2)
23808 (concat "[" xx "]"))
23809 "]")))
23810 (put-text-property 0 (length s) 'face 'org-link s)
23811 (replace-match s t t))))
23813 ;; Find multiline emphasis and put them into single line
23814 (when (plist-get parameters :emph-multiline)
23815 (goto-char (point-min))
23816 (while (re-search-forward org-emph-re nil t)
23817 (if (not (= (char-after (match-beginning 3))
23818 (char-after (match-beginning 4))))
23819 (org-if-unprotected
23820 (subst-char-in-region (match-beginning 0) (match-end 0)
23821 ?\n ?\ t)
23822 (goto-char (1- (match-end 0))))
23823 (goto-char (1+ (match-beginning 0))))))
23825 (setq rtn (buffer-string)))
23826 (kill-buffer " org-mode-tmp")
23827 rtn))
23829 (defun org-export-grab-title-from-buffer ()
23830 "Get a title for the current document, from looking at the buffer."
23831 (let ((inhibit-read-only t))
23832 (save-excursion
23833 (goto-char (point-min))
23834 (let ((end (save-excursion (outline-next-heading) (point))))
23835 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
23836 ;; Mark the line so that it will not be exported as normal text.
23837 (org-unmodified
23838 (add-text-properties (match-beginning 0) (match-end 0)
23839 (list :org-license-to-kill t)))
23840 ;; Return the title string
23841 (org-trim (match-string 0)))))))
23843 (defun org-export-get-title-from-subtree ()
23844 "Return subtree title and exclude it from export."
23845 (let (title (m (mark)))
23846 (save-excursion
23847 (goto-char (region-beginning))
23848 (when (and (org-at-heading-p)
23849 (>= (org-end-of-subtree t t) (region-end)))
23850 ;; This is a subtree, we take the title from the first heading
23851 (goto-char (region-beginning))
23852 (looking-at org-todo-line-regexp)
23853 (setq title (match-string 3))
23854 (org-unmodified
23855 (add-text-properties (point) (1+ (point-at-eol))
23856 (list :org-license-to-kill t)))))
23857 title))
23859 (defun org-solidify-link-text (s &optional alist)
23860 "Take link text and make a safe target out of it."
23861 (save-match-data
23862 (let* ((rtn
23863 (mapconcat
23864 'identity
23865 (org-split-string s "[ \t\r\n]+") "--"))
23866 (a (assoc rtn alist)))
23867 (or (cdr a) rtn))))
23869 (defun org-get-min-level (lines)
23870 "Get the minimum level in LINES."
23871 (let ((re "^\\(\\*+\\) ") l min)
23872 (catch 'exit
23873 (while (setq l (pop lines))
23874 (if (string-match re l)
23875 (throw 'exit (org-tr-level (length (match-string 1 l))))))
23876 1)))
23878 ;; Variable holding the vector with section numbers
23879 (defvar org-section-numbers (make-vector org-level-max 0))
23881 (defun org-init-section-numbers ()
23882 "Initialize the vector for the section numbers."
23883 (let* ((level -1)
23884 (numbers (nreverse (org-split-string "" "\\.")))
23885 (depth (1- (length org-section-numbers)))
23886 (i depth) number-string)
23887 (while (>= i 0)
23888 (if (> i level)
23889 (aset org-section-numbers i 0)
23890 (setq number-string (or (car numbers) "0"))
23891 (if (string-match "\\`[A-Z]\\'" number-string)
23892 (aset org-section-numbers i
23893 (- (string-to-char number-string) ?A -1))
23894 (aset org-section-numbers i (string-to-number number-string)))
23895 (pop numbers))
23896 (setq i (1- i)))))
23898 (defun org-section-number (&optional level)
23899 "Return a string with the current section number.
23900 When LEVEL is non-nil, increase section numbers on that level."
23901 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
23902 (when level
23903 (when (> level -1)
23904 (aset org-section-numbers
23905 level (1+ (aref org-section-numbers level))))
23906 (setq idx (1+ level))
23907 (while (<= idx depth)
23908 (if (not (= idx 1))
23909 (aset org-section-numbers idx 0))
23910 (setq idx (1+ idx))))
23911 (setq idx 0)
23912 (while (<= idx depth)
23913 (setq n (aref org-section-numbers idx))
23914 (setq string (concat string (if (not (string= string "")) "." "")
23915 (int-to-string n)))
23916 (setq idx (1+ idx)))
23917 (save-match-data
23918 (if (string-match "\\`\\([@0]\\.\\)+" string)
23919 (setq string (replace-match "" t nil string)))
23920 (if (string-match "\\(\\.0\\)+\\'" string)
23921 (setq string (replace-match "" t nil string))))
23922 string))
23924 ;;; ASCII export
23926 (defvar org-last-level nil) ; dynamically scoped variable
23927 (defvar org-min-level nil) ; dynamically scoped variable
23928 (defvar org-levels-open nil) ; dynamically scoped parameter
23929 (defvar org-ascii-current-indentation nil) ; For communication
23931 (defun org-export-as-ascii (arg)
23932 "Export the outline as a pretty ASCII file.
23933 If there is an active region, export only the region.
23934 The prefix ARG specifies how many levels of the outline should become
23935 underlined headlines. The default is 3."
23936 (interactive "P")
23937 (setq-default org-todo-line-regexp org-todo-line-regexp)
23938 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23939 (org-infile-export-plist)))
23940 (region-p (org-region-active-p))
23941 (subtree-p
23942 (when region-p
23943 (save-excursion
23944 (goto-char (region-beginning))
23945 (and (org-at-heading-p)
23946 (>= (org-end-of-subtree t t) (region-end))))))
23947 (custom-times org-display-custom-times)
23948 (org-ascii-current-indentation '(0 . 0))
23949 (level 0) line txt
23950 (umax nil)
23951 (umax-toc nil)
23952 (case-fold-search nil)
23953 (filename (concat (file-name-as-directory
23954 (org-export-directory :ascii opt-plist))
23955 (file-name-sans-extension
23956 (or (and subtree-p
23957 (org-entry-get (region-beginning)
23958 "EXPORT_FILE_NAME" t))
23959 (file-name-nondirectory buffer-file-name)))
23960 ".txt"))
23961 (filename (if (equal (file-truename filename)
23962 (file-truename buffer-file-name))
23963 (concat filename ".txt")
23964 filename))
23965 (buffer (find-file-noselect filename))
23966 (org-levels-open (make-vector org-level-max nil))
23967 (odd org-odd-levels-only)
23968 (date (plist-get opt-plist :date))
23969 (author (plist-get opt-plist :author))
23970 (title (or (and subtree-p (org-export-get-title-from-subtree))
23971 (plist-get opt-plist :title)
23972 (and (not
23973 (plist-get opt-plist :skip-before-1st-heading))
23974 (org-export-grab-title-from-buffer))
23975 (file-name-sans-extension
23976 (file-name-nondirectory buffer-file-name))))
23977 (email (plist-get opt-plist :email))
23978 (language (plist-get opt-plist :language))
23979 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23980 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
23981 (todo nil)
23982 (lang-words nil)
23983 (region
23984 (buffer-substring
23985 (if (org-region-active-p) (region-beginning) (point-min))
23986 (if (org-region-active-p) (region-end) (point-max))))
23987 (lines (org-split-string
23988 (org-cleaned-string-for-export
23989 region
23990 :for-ascii t
23991 :skip-before-1st-heading
23992 (plist-get opt-plist :skip-before-1st-heading)
23993 :drawers (plist-get opt-plist :drawers)
23994 :verbatim-multiline t
23995 :archived-trees
23996 (plist-get opt-plist :archived-trees)
23997 :add-text (plist-get opt-plist :text))
23998 "\n"))
23999 thetoc have-headings first-heading-pos
24000 table-open table-buffer)
24002 (let ((inhibit-read-only t))
24003 (org-unmodified
24004 (remove-text-properties (point-min) (point-max)
24005 '(:org-license-to-kill t))))
24007 (setq org-min-level (org-get-min-level lines))
24008 (setq org-last-level org-min-level)
24009 (org-init-section-numbers)
24011 (find-file-noselect filename)
24013 (setq lang-words (or (assoc language org-export-language-setup)
24014 (assoc "en" org-export-language-setup)))
24015 (switch-to-buffer-other-window buffer)
24016 (erase-buffer)
24017 (fundamental-mode)
24018 ;; create local variables for all options, to make sure all called
24019 ;; functions get the correct information
24020 (mapc (lambda (x)
24021 (set (make-local-variable (cdr x))
24022 (plist-get opt-plist (car x))))
24023 org-export-plist-vars)
24024 (org-set-local 'org-odd-levels-only odd)
24025 (setq umax (if arg (prefix-numeric-value arg)
24026 org-export-headline-levels))
24027 (setq umax-toc (if (integerp org-export-with-toc)
24028 (min org-export-with-toc umax)
24029 umax))
24031 ;; File header
24032 (if title (org-insert-centered title ?=))
24033 (insert "\n")
24034 (if (and (or author email)
24035 org-export-author-info)
24036 (insert (concat (nth 1 lang-words) ": " (or author "")
24037 (if email (concat " <" email ">") "")
24038 "\n")))
24040 (cond
24041 ((and date (string-match "%" date))
24042 (setq date (format-time-string date (current-time))))
24043 (date)
24044 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24046 (if (and date org-export-time-stamp-file)
24047 (insert (concat (nth 2 lang-words) ": " date"\n")))
24049 (insert "\n\n")
24051 (if org-export-with-toc
24052 (progn
24053 (push (concat (nth 3 lang-words) "\n") thetoc)
24054 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24055 (mapc '(lambda (line)
24056 (if (string-match org-todo-line-regexp
24057 line)
24058 ;; This is a headline
24059 (progn
24060 (setq have-headings t)
24061 (setq level (- (match-end 1) (match-beginning 1))
24062 level (org-tr-level level)
24063 txt (match-string 3 line)
24064 todo
24065 (or (and org-export-mark-todo-in-toc
24066 (match-beginning 2)
24067 (not (member (match-string 2 line)
24068 org-done-keywords)))
24069 ; TODO, not DONE
24070 (and org-export-mark-todo-in-toc
24071 (= level umax-toc)
24072 (org-search-todo-below
24073 line lines level))))
24074 (setq txt (org-html-expand-for-ascii txt))
24076 (while (string-match org-bracket-link-regexp txt)
24077 (setq txt
24078 (replace-match
24079 (match-string (if (match-end 2) 3 1) txt)
24080 t t txt)))
24082 (if (and (memq org-export-with-tags '(not-in-toc nil))
24083 (string-match
24084 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24085 txt))
24086 (setq txt (replace-match "" t t txt)))
24087 (if (string-match quote-re0 txt)
24088 (setq txt (replace-match "" t t txt)))
24090 (if org-export-with-section-numbers
24091 (setq txt (concat (org-section-number level)
24092 " " txt)))
24093 (if (<= level umax-toc)
24094 (progn
24095 (push
24096 (concat
24097 (make-string
24098 (* (max 0 (- level org-min-level)) 4) ?\ )
24099 (format (if todo "%s (*)\n" "%s\n") txt))
24100 thetoc)
24101 (setq org-last-level level))
24102 ))))
24103 lines)
24104 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24106 (org-init-section-numbers)
24107 (while (setq line (pop lines))
24108 ;; Remove the quoted HTML tags.
24109 (setq line (org-html-expand-for-ascii line))
24110 ;; Remove targets
24111 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24112 (setq line (replace-match "" t t line)))
24113 ;; Replace internal links
24114 (while (string-match org-bracket-link-regexp line)
24115 (setq line (replace-match
24116 (if (match-end 3) "[\\3]" "[\\1]")
24117 t nil line)))
24118 (when custom-times
24119 (setq line (org-translate-time line)))
24120 (cond
24121 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24122 ;; a Headline
24123 (setq first-heading-pos (or first-heading-pos (point)))
24124 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24125 txt (match-string 2 line))
24126 (org-ascii-level-start level txt umax lines))
24128 ((and org-export-with-tables
24129 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24130 (if (not table-open)
24131 ;; New table starts
24132 (setq table-open t table-buffer nil))
24133 ;; Accumulate lines
24134 (setq table-buffer (cons line table-buffer))
24135 (when (or (not lines)
24136 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24137 (car lines))))
24138 (setq table-open nil
24139 table-buffer (nreverse table-buffer))
24140 (insert (mapconcat
24141 (lambda (x)
24142 (org-fix-indentation x org-ascii-current-indentation))
24143 (org-format-table-ascii table-buffer)
24144 "\n") "\n")))
24146 (setq line (org-fix-indentation line org-ascii-current-indentation))
24147 (if (and org-export-with-fixed-width
24148 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24149 (setq line (replace-match "\\1" nil nil line)))
24150 (insert line "\n"))))
24152 (normal-mode)
24154 ;; insert the table of contents
24155 (when thetoc
24156 (goto-char (point-min))
24157 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24158 (progn
24159 (goto-char (match-beginning 0))
24160 (replace-match ""))
24161 (goto-char first-heading-pos))
24162 (mapc 'insert thetoc)
24163 (or (looking-at "[ \t]*\n[ \t]*\n")
24164 (insert "\n\n")))
24166 ;; Convert whitespace place holders
24167 (goto-char (point-min))
24168 (let (beg end)
24169 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24170 (setq end (next-single-property-change beg 'org-whitespace))
24171 (goto-char beg)
24172 (delete-region beg end)
24173 (insert (make-string (- end beg) ?\ ))))
24175 (save-buffer)
24176 ;; remove display and invisible chars
24177 (let (beg end)
24178 (goto-char (point-min))
24179 (while (setq beg (next-single-property-change (point) 'display))
24180 (setq end (next-single-property-change beg 'display))
24181 (delete-region beg end)
24182 (goto-char beg)
24183 (insert "=>"))
24184 (goto-char (point-min))
24185 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24186 (setq end (next-single-property-change beg 'org-cwidth))
24187 (delete-region beg end)
24188 (goto-char beg)))
24189 (goto-char (point-min))))
24191 (defun org-export-ascii-clean-string ()
24192 "Do extra work for ASCII export"
24193 (goto-char (point-min))
24194 (while (re-search-forward org-verbatim-re nil t)
24195 (goto-char (match-end 2))
24196 (backward-delete-char 1) (insert "'")
24197 (goto-char (match-beginning 2))
24198 (delete-char 1) (insert "`")
24199 (goto-char (match-end 2))))
24201 (defun org-search-todo-below (line lines level)
24202 "Search the subtree below LINE for any TODO entries."
24203 (let ((rest (cdr (memq line lines)))
24204 (re org-todo-line-regexp)
24205 line lv todo)
24206 (catch 'exit
24207 (while (setq line (pop rest))
24208 (if (string-match re line)
24209 (progn
24210 (setq lv (- (match-end 1) (match-beginning 1))
24211 todo (and (match-beginning 2)
24212 (not (member (match-string 2 line)
24213 org-done-keywords))))
24214 ; TODO, not DONE
24215 (if (<= lv level) (throw 'exit nil))
24216 (if todo (throw 'exit t))))))))
24218 (defun org-html-expand-for-ascii (line)
24219 "Handle quoted HTML for ASCII export."
24220 (if org-export-html-expand
24221 (while (string-match "@<[^<>\n]*>" line)
24222 ;; We just remove the tags for now.
24223 (setq line (replace-match "" nil nil line))))
24224 line)
24226 (defun org-insert-centered (s &optional underline)
24227 "Insert the string S centered and underline it with character UNDERLINE."
24228 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24229 (insert (make-string ind ?\ ) s "\n")
24230 (if underline
24231 (insert (make-string ind ?\ )
24232 (make-string (string-width s) underline)
24233 "\n"))))
24235 (defun org-ascii-level-start (level title umax &optional lines)
24236 "Insert a new level in ASCII export."
24237 (let (char (n (- level umax 1)) (ind 0))
24238 (if (> level umax)
24239 (progn
24240 (insert (make-string (* 2 n) ?\ )
24241 (char-to-string (nth (% n (length org-export-ascii-bullets))
24242 org-export-ascii-bullets))
24243 " " title "\n")
24244 ;; find the indentation of the next non-empty line
24245 (catch 'stop
24246 (while lines
24247 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24248 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24249 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24250 (pop lines)))
24251 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24252 (if (or (not (equal (char-before) ?\n))
24253 (not (equal (char-before (1- (point))) ?\n)))
24254 (insert "\n"))
24255 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24256 (unless org-export-with-tags
24257 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24258 (setq title (replace-match "" t t title))))
24259 (if org-export-with-section-numbers
24260 (setq title (concat (org-section-number level) " " title)))
24261 (insert title "\n" (make-string (string-width title) char) "\n")
24262 (setq org-ascii-current-indentation '(0 . 0)))))
24264 (defun org-export-visible (type arg)
24265 "Create a copy of the visible part of the current buffer, and export it.
24266 The copy is created in a temporary buffer and removed after use.
24267 TYPE is the final key (as a string) that also select the export command in
24268 the `C-c C-e' export dispatcher.
24269 As a special case, if the you type SPC at the prompt, the temporary
24270 org-mode file will not be removed but presented to you so that you can
24271 continue to use it. The prefix arg ARG is passed through to the exporting
24272 command."
24273 (interactive
24274 (list (progn
24275 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24276 (read-char-exclusive))
24277 current-prefix-arg))
24278 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24279 (error "Invalid export key"))
24280 (let* ((binding (cdr (assoc type
24281 '((?a . org-export-as-ascii)
24282 (?\C-a . org-export-as-ascii)
24283 (?b . org-export-as-html-and-open)
24284 (?\C-b . org-export-as-html-and-open)
24285 (?h . org-export-as-html)
24286 (?H . org-export-as-html-to-buffer)
24287 (?R . org-export-region-as-html)
24288 (?x . org-export-as-xoxo)))))
24289 (keepp (equal type ?\ ))
24290 (file buffer-file-name)
24291 (buffer (get-buffer-create "*Org Export Visible*"))
24292 s e)
24293 ;; Need to hack the drawers here.
24294 (save-excursion
24295 (goto-char (point-min))
24296 (while (re-search-forward org-drawer-regexp nil t)
24297 (goto-char (match-beginning 1))
24298 (or (org-invisible-p) (org-flag-drawer nil))))
24299 (with-current-buffer buffer (erase-buffer))
24300 (save-excursion
24301 (setq s (goto-char (point-min)))
24302 (while (not (= (point) (point-max)))
24303 (goto-char (org-find-invisible))
24304 (append-to-buffer buffer s (point))
24305 (setq s (goto-char (org-find-visible))))
24306 (org-cycle-hide-drawers 'all)
24307 (goto-char (point-min))
24308 (unless keepp
24309 ;; Copy all comment lines to the end, to make sure #+ settings are
24310 ;; still available for the second export step. Kind of a hack, but
24311 ;; does do the trick.
24312 (if (looking-at "#[^\r\n]*")
24313 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24314 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24315 (append-to-buffer buffer (1+ (match-beginning 0))
24316 (min (point-max) (1+ (match-end 0))))))
24317 (set-buffer buffer)
24318 (let ((buffer-file-name file)
24319 (org-inhibit-startup t))
24320 (org-mode)
24321 (show-all)
24322 (unless keepp (funcall binding arg))))
24323 (if (not keepp)
24324 (kill-buffer buffer)
24325 (switch-to-buffer-other-window buffer)
24326 (goto-char (point-min)))))
24328 (defun org-find-visible ()
24329 (let ((s (point)))
24330 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24331 (get-char-property s 'invisible)))
24333 (defun org-find-invisible ()
24334 (let ((s (point)))
24335 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24336 (not (get-char-property s 'invisible))))
24339 ;;; HTML export
24341 (defun org-get-current-options ()
24342 "Return a string with current options as keyword options.
24343 Does include HTML export options as well as TODO and CATEGORY stuff."
24344 (format
24345 "#+TITLE: %s
24346 #+AUTHOR: %s
24347 #+EMAIL: %s
24348 #+LANGUAGE: %s
24349 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24350 #+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
24351 #+CATEGORY: %s
24352 #+SEQ_TODO: %s
24353 #+TYP_TODO: %s
24354 #+PRIORITIES: %c %c %c
24355 #+DRAWERS: %s
24356 #+STARTUP: %s %s %s %s %s
24357 #+TAGS: %s
24358 #+ARCHIVE: %s
24359 #+LINK: %s
24361 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24362 org-export-headline-levels
24363 org-export-with-section-numbers
24364 org-export-with-toc
24365 org-export-preserve-breaks
24366 org-export-html-expand
24367 org-export-with-fixed-width
24368 org-export-with-tables
24369 org-export-with-sub-superscripts
24370 org-export-with-special-strings
24371 org-export-with-footnotes
24372 org-export-with-emphasize
24373 org-export-with-TeX-macros
24374 org-export-with-LaTeX-fragments
24375 org-export-skip-text-before-1st-heading
24376 org-export-with-drawers
24377 org-export-with-tags
24378 (file-name-nondirectory buffer-file-name)
24379 "TODO FEEDBACK VERIFY DONE"
24380 "Me Jason Marie DONE"
24381 org-highest-priority org-lowest-priority org-default-priority
24382 (mapconcat 'identity org-drawers " ")
24383 (cdr (assoc org-startup-folded
24384 '((nil . "showall") (t . "overview") (content . "content"))))
24385 (if org-odd-levels-only "odd" "oddeven")
24386 (if org-hide-leading-stars "hidestars" "showstars")
24387 (if org-startup-align-all-tables "align" "noalign")
24388 (cond ((eq t org-log-done) "logdone")
24389 ((not org-log-done) "nologging")
24390 ((listp org-log-done)
24391 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
24392 org-log-done " ")))
24393 (or (mapconcat (lambda (x)
24394 (cond
24395 ((equal '(:startgroup) x) "{")
24396 ((equal '(:endgroup) x) "}")
24397 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24398 (t (car x))))
24399 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24400 org-archive-location
24401 "org file:~/org/%s.org"
24404 (defun org-insert-export-options-template ()
24405 "Insert into the buffer a template with information for exporting."
24406 (interactive)
24407 (if (not (bolp)) (newline))
24408 (let ((s (org-get-current-options)))
24409 (and (string-match "#\\+CATEGORY" s)
24410 (setq s (substring s 0 (match-beginning 0))))
24411 (insert s)))
24413 (defun org-toggle-fixed-width-section (arg)
24414 "Toggle the fixed-width export.
24415 If there is no active region, the QUOTE keyword at the current headline is
24416 inserted or removed. When present, it causes the text between this headline
24417 and the next to be exported as fixed-width text, and unmodified.
24418 If there is an active region, this command adds or removes a colon as the
24419 first character of this line. If the first character of a line is a colon,
24420 this line is also exported in fixed-width font."
24421 (interactive "P")
24422 (let* ((cc 0)
24423 (regionp (org-region-active-p))
24424 (beg (if regionp (region-beginning) (point)))
24425 (end (if regionp (region-end)))
24426 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24427 (case-fold-search nil)
24428 (re "[ \t]*\\(:\\)")
24429 off)
24430 (if regionp
24431 (save-excursion
24432 (goto-char beg)
24433 (setq cc (current-column))
24434 (beginning-of-line 1)
24435 (setq off (looking-at re))
24436 (while (> nlines 0)
24437 (setq nlines (1- nlines))
24438 (beginning-of-line 1)
24439 (cond
24440 (arg
24441 (move-to-column cc t)
24442 (insert ":\n")
24443 (forward-line -1))
24444 ((and off (looking-at re))
24445 (replace-match "" t t nil 1))
24446 ((not off) (move-to-column cc t) (insert ":")))
24447 (forward-line 1)))
24448 (save-excursion
24449 (org-back-to-heading)
24450 (if (looking-at (concat outline-regexp
24451 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24452 (replace-match "" t t nil 1)
24453 (if (looking-at outline-regexp)
24454 (progn
24455 (goto-char (match-end 0))
24456 (insert org-quote-string " "))))))))
24458 (defun org-export-as-html-and-open (arg)
24459 "Export the outline as HTML and immediately open it with a browser.
24460 If there is an active region, export only the region.
24461 The prefix ARG specifies how many levels of the outline should become
24462 headlines. The default is 3. Lower levels will become bulleted lists."
24463 (interactive "P")
24464 (org-export-as-html arg 'hidden)
24465 (org-open-file buffer-file-name))
24467 (defun org-export-as-html-batch ()
24468 "Call `org-export-as-html', may be used in batch processing as
24469 emacs --batch
24470 --load=$HOME/lib/emacs/org.el
24471 --eval \"(setq org-export-headline-levels 2)\"
24472 --visit=MyFile --funcall org-export-as-html-batch"
24473 (org-export-as-html org-export-headline-levels 'hidden))
24475 (defun org-export-as-html-to-buffer (arg)
24476 "Call `org-exort-as-html` with output to a temporary buffer.
24477 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24478 (interactive "P")
24479 (org-export-as-html arg nil nil "*Org HTML Export*")
24480 (switch-to-buffer-other-window "*Org HTML Export*"))
24482 (defun org-replace-region-by-html (beg end)
24483 "Assume the current region has org-mode syntax, and convert it to HTML.
24484 This can be used in any buffer. For example, you could write an
24485 itemized list in org-mode syntax in an HTML buffer and then use this
24486 command to convert it."
24487 (interactive "r")
24488 (let (reg html buf pop-up-frames)
24489 (save-window-excursion
24490 (if (org-mode-p)
24491 (setq html (org-export-region-as-html
24492 beg end t 'string))
24493 (setq reg (buffer-substring beg end)
24494 buf (get-buffer-create "*Org tmp*"))
24495 (with-current-buffer buf
24496 (erase-buffer)
24497 (insert reg)
24498 (org-mode)
24499 (setq html (org-export-region-as-html
24500 (point-min) (point-max) t 'string)))
24501 (kill-buffer buf)))
24502 (delete-region beg end)
24503 (insert html)))
24505 (defun org-export-region-as-html (beg end &optional body-only buffer)
24506 "Convert region from BEG to END in org-mode buffer to HTML.
24507 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24508 contents, and only produce the region of converted text, useful for
24509 cut-and-paste operations.
24510 If BUFFER is a buffer or a string, use/create that buffer as a target
24511 of the converted HTML. If BUFFER is the symbol `string', return the
24512 produced HTML as a string and leave not buffer behind. For example,
24513 a Lisp program could call this function in the following way:
24515 (setq html (org-export-region-as-html beg end t 'string))
24517 When called interactively, the output buffer is selected, and shown
24518 in a window. A non-interactive call will only retunr the buffer."
24519 (interactive "r\nP")
24520 (when (interactive-p)
24521 (setq buffer "*Org HTML Export*"))
24522 (let ((transient-mark-mode t) (zmacs-regions t)
24523 rtn)
24524 (goto-char end)
24525 (set-mark (point)) ;; to activate the region
24526 (goto-char beg)
24527 (setq rtn (org-export-as-html
24528 nil nil nil
24529 buffer body-only))
24530 (if (fboundp 'deactivate-mark) (deactivate-mark))
24531 (if (and (interactive-p) (bufferp rtn))
24532 (switch-to-buffer-other-window rtn)
24533 rtn)))
24535 (defvar html-table-tag nil) ; dynamically scoped into this.
24536 (defun org-export-as-html (arg &optional hidden ext-plist
24537 to-buffer body-only)
24538 "Export the outline as a pretty HTML file.
24539 If there is an active region, export only the region. The prefix
24540 ARG specifies how many levels of the outline should become
24541 headlines. The default is 3. Lower levels will become bulleted
24542 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24543 EXT-PLIST is a property list with external parameters overriding
24544 org-mode's default settings, but still inferior to file-local
24545 settings. When TO-BUFFER is non-nil, create a buffer with that
24546 name and export to that buffer. If TO-BUFFER is the symbol `string',
24547 don't leave any buffer behind but just return the resulting HTML as
24548 a string. When BODY-ONLY is set, don't produce the file header and footer,
24549 simply return the content of <body>...</body>, without even
24550 the body tags themselves."
24551 (interactive "P")
24553 ;; Make sure we have a file name when we need it.
24554 (when (and (not (or to-buffer body-only))
24555 (not buffer-file-name))
24556 (if (buffer-base-buffer)
24557 (org-set-local 'buffer-file-name
24558 (with-current-buffer (buffer-base-buffer)
24559 buffer-file-name))
24560 (error "Need a file name to be able to export.")))
24562 (message "Exporting...")
24563 (setq-default org-todo-line-regexp org-todo-line-regexp)
24564 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24565 (setq-default org-done-keywords org-done-keywords)
24566 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24567 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24568 ext-plist
24569 (org-infile-export-plist)))
24571 (style (plist-get opt-plist :style))
24572 (link-validate (plist-get opt-plist :link-validation-function))
24573 valid thetoc have-headings first-heading-pos
24574 (odd org-odd-levels-only)
24575 (region-p (org-region-active-p))
24576 (subtree-p
24577 (when region-p
24578 (save-excursion
24579 (goto-char (region-beginning))
24580 (and (org-at-heading-p)
24581 (>= (org-end-of-subtree t t) (region-end))))))
24582 ;; The following two are dynamically scoped into other
24583 ;; routines below.
24584 (org-current-export-dir (org-export-directory :html opt-plist))
24585 (org-current-export-file buffer-file-name)
24586 (level 0) (line "") (origline "") txt todo
24587 (umax nil)
24588 (umax-toc nil)
24589 (filename (if to-buffer nil
24590 (expand-file-name
24591 (concat
24592 (file-name-sans-extension
24593 (or (and subtree-p
24594 (org-entry-get (region-beginning)
24595 "EXPORT_FILE_NAME" t))
24596 (file-name-nondirectory buffer-file-name)))
24597 "." org-export-html-extension)
24598 (file-name-as-directory
24599 (org-export-directory :html opt-plist)))))
24600 (current-dir (if buffer-file-name
24601 (file-name-directory buffer-file-name)
24602 default-directory))
24603 (buffer (if to-buffer
24604 (cond
24605 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24606 (t (get-buffer-create to-buffer)))
24607 (find-file-noselect filename)))
24608 (org-levels-open (make-vector org-level-max nil))
24609 (date (plist-get opt-plist :date))
24610 (author (plist-get opt-plist :author))
24611 (title (or (and subtree-p (org-export-get-title-from-subtree))
24612 (plist-get opt-plist :title)
24613 (and (not
24614 (plist-get opt-plist :skip-before-1st-heading))
24615 (org-export-grab-title-from-buffer))
24616 (and buffer-file-name
24617 (file-name-sans-extension
24618 (file-name-nondirectory buffer-file-name)))
24619 "UNTITLED"))
24620 (html-table-tag (plist-get opt-plist :html-table-tag))
24621 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24622 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24623 (inquote nil)
24624 (infixed nil)
24625 (in-local-list nil)
24626 (local-list-num nil)
24627 (local-list-indent nil)
24628 (llt org-plain-list-ordered-item-terminator)
24629 (email (plist-get opt-plist :email))
24630 (language (plist-get opt-plist :language))
24631 (lang-words nil)
24632 (target-alist nil) tg
24633 (head-count 0) cnt
24634 (start 0)
24635 (coding-system (and (boundp 'buffer-file-coding-system)
24636 buffer-file-coding-system))
24637 (coding-system-for-write (or org-export-html-coding-system
24638 coding-system))
24639 (save-buffer-coding-system (or org-export-html-coding-system
24640 coding-system))
24641 (charset (and coding-system-for-write
24642 (fboundp 'coding-system-get)
24643 (coding-system-get coding-system-for-write
24644 'mime-charset)))
24645 (region
24646 (buffer-substring
24647 (if region-p (region-beginning) (point-min))
24648 (if region-p (region-end) (point-max))))
24649 (lines
24650 (org-split-string
24651 (org-cleaned-string-for-export
24652 region
24653 :emph-multiline t
24654 :for-html t
24655 :skip-before-1st-heading
24656 (plist-get opt-plist :skip-before-1st-heading)
24657 :drawers (plist-get opt-plist :drawers)
24658 :archived-trees
24659 (plist-get opt-plist :archived-trees)
24660 :add-text
24661 (plist-get opt-plist :text)
24662 :LaTeX-fragments
24663 (plist-get opt-plist :LaTeX-fragments))
24664 "[\r\n]"))
24665 table-open type
24666 table-buffer table-orig-buffer
24667 ind start-is-num starter didclose
24668 rpl path desc descp desc1 desc2 link
24671 (let ((inhibit-read-only t))
24672 (org-unmodified
24673 (remove-text-properties (point-min) (point-max)
24674 '(:org-license-to-kill t))))
24676 (message "Exporting...")
24678 (setq org-min-level (org-get-min-level lines))
24679 (setq org-last-level org-min-level)
24680 (org-init-section-numbers)
24682 (cond
24683 ((and date (string-match "%" date))
24684 (setq date (format-time-string date (current-time))))
24685 (date)
24686 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24688 ;; Get the language-dependent settings
24689 (setq lang-words (or (assoc language org-export-language-setup)
24690 (assoc "en" org-export-language-setup)))
24692 ;; Switch to the output buffer
24693 (set-buffer buffer)
24694 (let ((inhibit-read-only t)) (erase-buffer))
24695 (fundamental-mode)
24697 (and (fboundp 'set-buffer-file-coding-system)
24698 (set-buffer-file-coding-system coding-system-for-write))
24700 (let ((case-fold-search nil)
24701 (org-odd-levels-only odd))
24702 ;; create local variables for all options, to make sure all called
24703 ;; functions get the correct information
24704 (mapc (lambda (x)
24705 (set (make-local-variable (cdr x))
24706 (plist-get opt-plist (car x))))
24707 org-export-plist-vars)
24708 (setq umax (if arg (prefix-numeric-value arg)
24709 org-export-headline-levels))
24710 (setq umax-toc (if (integerp org-export-with-toc)
24711 (min org-export-with-toc umax)
24712 umax))
24713 (unless body-only
24714 ;; File header
24715 (insert (format
24716 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24717 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24718 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24719 lang=\"%s\" xml:lang=\"%s\">
24720 <head>
24721 <title>%s</title>
24722 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24723 <meta name=\"generator\" content=\"Org-mode\"/>
24724 <meta name=\"generated\" content=\"%s\"/>
24725 <meta name=\"author\" content=\"%s\"/>
24727 </head><body>
24729 language language (org-html-expand title)
24730 (or charset "iso-8859-1") date author style))
24732 (insert (or (plist-get opt-plist :preamble) ""))
24734 (when (plist-get opt-plist :auto-preamble)
24735 (if title (insert (format org-export-html-title-format
24736 (org-html-expand title))))))
24738 (if (and org-export-with-toc (not body-only))
24739 (progn
24740 (push (format "<h%d>%s</h%d>\n"
24741 org-export-html-toplevel-hlevel
24742 (nth 3 lang-words)
24743 org-export-html-toplevel-hlevel)
24744 thetoc)
24745 (push "<ul>\n<li>" thetoc)
24746 (setq lines
24747 (mapcar '(lambda (line)
24748 (if (string-match org-todo-line-regexp line)
24749 ;; This is a headline
24750 (progn
24751 (setq have-headings t)
24752 (setq level (- (match-end 1) (match-beginning 1))
24753 level (org-tr-level level)
24754 txt (save-match-data
24755 (org-html-expand
24756 (org-export-cleanup-toc-line
24757 (match-string 3 line))))
24758 todo
24759 (or (and org-export-mark-todo-in-toc
24760 (match-beginning 2)
24761 (not (member (match-string 2 line)
24762 org-done-keywords)))
24763 ; TODO, not DONE
24764 (and org-export-mark-todo-in-toc
24765 (= level umax-toc)
24766 (org-search-todo-below
24767 line lines level))))
24768 (if (string-match
24769 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
24770 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
24771 (if (string-match quote-re0 txt)
24772 (setq txt (replace-match "" t t txt)))
24773 (if org-export-with-section-numbers
24774 (setq txt (concat (org-section-number level)
24775 " " txt)))
24776 (if (<= level (max umax umax-toc))
24777 (setq head-count (+ head-count 1)))
24778 (if (<= level umax-toc)
24779 (progn
24780 (if (> level org-last-level)
24781 (progn
24782 (setq cnt (- level org-last-level))
24783 (while (>= (setq cnt (1- cnt)) 0)
24784 (push "\n<ul>\n<li>" thetoc))
24785 (push "\n" thetoc)))
24786 (if (< level org-last-level)
24787 (progn
24788 (setq cnt (- org-last-level level))
24789 (while (>= (setq cnt (1- cnt)) 0)
24790 (push "</li>\n</ul>" thetoc))
24791 (push "\n" thetoc)))
24792 ;; Check for targets
24793 (while (string-match org-target-regexp line)
24794 (setq tg (match-string 1 line)
24795 line (replace-match
24796 (concat "@<span class=\"target\">" tg "@</span> ")
24797 t t line))
24798 (push (cons (org-solidify-link-text tg)
24799 (format "sec-%d" head-count))
24800 target-alist))
24801 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
24802 (setq txt (replace-match "" t t txt)))
24803 (push
24804 (format
24805 (if todo
24806 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
24807 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
24808 head-count txt) thetoc)
24810 (setq org-last-level level))
24812 line)
24813 lines))
24814 (while (> org-last-level (1- org-min-level))
24815 (setq org-last-level (1- org-last-level))
24816 (push "</li>\n</ul>\n" thetoc))
24817 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24819 (setq head-count 0)
24820 (org-init-section-numbers)
24822 (while (setq line (pop lines) origline line)
24823 (catch 'nextline
24825 ;; end of quote section?
24826 (when (and inquote (string-match "^\\*+ " line))
24827 (insert "</pre>\n")
24828 (setq inquote nil))
24829 ;; inside a quote section?
24830 (when inquote
24831 (insert (org-html-protect line) "\n")
24832 (throw 'nextline nil))
24834 ;; verbatim lines
24835 (when (and org-export-with-fixed-width
24836 (string-match "^[ \t]*:\\(.*\\)" line))
24837 (when (not infixed)
24838 (setq infixed t)
24839 (insert "<pre>\n"))
24840 (insert (org-html-protect (match-string 1 line)) "\n")
24841 (when (and lines
24842 (not (string-match "^[ \t]*\\(:.*\\)"
24843 (car lines))))
24844 (setq infixed nil)
24845 (insert "</pre>\n"))
24846 (throw 'nextline nil))
24848 ;; Protected HTML
24849 (when (get-text-property 0 'org-protected line)
24850 (let (par)
24851 (when (re-search-backward
24852 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
24853 (setq par (match-string 1))
24854 (replace-match "\\2\n"))
24855 (insert line "\n")
24856 (while (and lines
24857 (or (= (length (car lines)) 0)
24858 (get-text-property 0 'org-protected (car lines))))
24859 (insert (pop lines) "\n"))
24860 (and par (insert "<p>\n")))
24861 (throw 'nextline nil))
24863 ;; Horizontal line
24864 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
24865 (insert "\n<hr/>\n")
24866 (throw 'nextline nil))
24868 ;; make targets to anchors
24869 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
24870 (cond
24871 ((match-end 2)
24872 (setq line (replace-match
24873 (concat "@<a name=\""
24874 (org-solidify-link-text (match-string 1 line))
24875 "\">\\nbsp@</a>")
24876 t t line)))
24877 ((and org-export-with-toc (equal (string-to-char line) ?*))
24878 (setq line (replace-match
24879 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
24880 ; (concat "@<i>" (match-string 1 line) "@</i> ")
24881 t t line)))
24883 (setq line (replace-match
24884 (concat "@<a name=\""
24885 (org-solidify-link-text (match-string 1 line))
24886 "\" class=\"target\">" (match-string 1 line) "@</a> ")
24887 t t line)))))
24889 (setq line (org-html-handle-time-stamps line))
24891 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
24892 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
24893 ;; Also handle sub_superscripts and checkboxes
24894 (or (string-match org-table-hline-regexp line)
24895 (setq line (org-html-expand line)))
24897 ;; Format the links
24898 (setq start 0)
24899 (while (string-match org-bracket-link-analytic-regexp line start)
24900 (setq start (match-beginning 0))
24901 (setq type (if (match-end 2) (match-string 2 line) "internal"))
24902 (setq path (match-string 3 line))
24903 (setq desc1 (if (match-end 5) (match-string 5 line))
24904 desc2 (if (match-end 2) (concat type ":" path) path)
24905 descp (and desc1 (not (equal desc1 desc2)))
24906 desc (or desc1 desc2))
24907 ;; Make an image out of the description if that is so wanted
24908 (when (and descp (org-file-image-p desc))
24909 (save-match-data
24910 (if (string-match "^file:" desc)
24911 (setq desc (substring desc (match-end 0)))))
24912 (setq desc (concat "<img src=\"" desc "\"/>")))
24913 ;; FIXME: do we need to unescape here somewhere?
24914 (cond
24915 ((equal type "internal")
24916 (setq rpl
24917 (concat
24918 "<a href=\"#"
24919 (org-solidify-link-text
24920 (save-match-data (org-link-unescape path)) target-alist)
24921 "\">" desc "</a>")))
24922 ((member type '("http" "https"))
24923 ;; standard URL, just check if we need to inline an image
24924 (if (and (or (eq t org-export-html-inline-images)
24925 (and org-export-html-inline-images (not descp)))
24926 (org-file-image-p path))
24927 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
24928 (setq link (concat type ":" path))
24929 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
24930 ((member type '("ftp" "mailto" "news"))
24931 ;; standard URL
24932 (setq link (concat type ":" path))
24933 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
24934 ((string= type "file")
24935 ;; FILE link
24936 (let* ((filename path)
24937 (abs-p (file-name-absolute-p filename))
24938 thefile file-is-image-p search)
24939 (save-match-data
24940 (if (string-match "::\\(.*\\)" filename)
24941 (setq search (match-string 1 filename)
24942 filename (replace-match "" t nil filename)))
24943 (setq valid
24944 (if (functionp link-validate)
24945 (funcall link-validate filename current-dir)
24947 (setq file-is-image-p (org-file-image-p filename))
24948 (setq thefile (if abs-p (expand-file-name filename) filename))
24949 (when (and org-export-html-link-org-files-as-html
24950 (string-match "\\.org$" thefile))
24951 (setq thefile (concat (substring thefile 0
24952 (match-beginning 0))
24953 "." org-export-html-extension))
24954 (if (and search
24955 ;; make sure this is can be used as target search
24956 (not (string-match "^[0-9]*$" search))
24957 (not (string-match "^\\*" search))
24958 (not (string-match "^/.*/$" search)))
24959 (setq thefile (concat thefile "#"
24960 (org-solidify-link-text
24961 (org-link-unescape search)))))
24962 (when (string-match "^file:" desc)
24963 (setq desc (replace-match "" t t desc))
24964 (if (string-match "\\.org$" desc)
24965 (setq desc (replace-match "" t t desc))))))
24966 (setq rpl (if (and file-is-image-p
24967 (or (eq t org-export-html-inline-images)
24968 (and org-export-html-inline-images
24969 (not descp))))
24970 (concat "<img src=\"" thefile "\"/>")
24971 (concat "<a href=\"" thefile "\">" desc "</a>")))
24972 (if (not valid) (setq rpl desc))))
24973 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
24974 (setq rpl (concat "<i>&lt;" type ":"
24975 (save-match-data (org-link-unescape path))
24976 "&gt;</i>"))))
24977 (setq line (replace-match rpl t t line)
24978 start (+ start (length rpl))))
24980 ;; TODO items
24981 (if (and (string-match org-todo-line-regexp line)
24982 (match-beginning 2))
24984 (setq line
24985 (concat (substring line 0 (match-beginning 2))
24986 "<span class=\""
24987 (if (member (match-string 2 line)
24988 org-done-keywords)
24989 "done" "todo")
24990 "\">" (match-string 2 line)
24991 "</span>" (substring line (match-end 2)))))
24993 ;; Does this contain a reference to a footnote?
24994 (when org-export-with-footnotes
24995 (setq start 0)
24996 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
24997 (if (get-text-property (match-beginning 2) 'org-protected line)
24998 (setq start (match-end 2))
24999 (let ((n (match-string 2 line)))
25000 (setq line
25001 (replace-match
25002 (format
25003 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25004 (match-string 1 line) n n n)
25005 t t line))))))
25007 (cond
25008 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25009 ;; This is a headline
25010 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25011 txt (match-string 2 line))
25012 (if (string-match quote-re0 txt)
25013 (setq txt (replace-match "" t t txt)))
25014 (if (<= level (max umax umax-toc))
25015 (setq head-count (+ head-count 1)))
25016 (when in-local-list
25017 ;; Close any local lists before inserting a new header line
25018 (while local-list-num
25019 (org-close-li)
25020 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25021 (pop local-list-num))
25022 (setq local-list-indent nil
25023 in-local-list nil))
25024 (setq first-heading-pos (or first-heading-pos (point)))
25025 (org-html-level-start level txt umax
25026 (and org-export-with-toc (<= level umax))
25027 head-count)
25028 ;; QUOTES
25029 (when (string-match quote-re line)
25030 (insert "<pre>")
25031 (setq inquote t)))
25033 ((and org-export-with-tables
25034 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25035 (if (not table-open)
25036 ;; New table starts
25037 (setq table-open t table-buffer nil table-orig-buffer nil))
25038 ;; Accumulate lines
25039 (setq table-buffer (cons line table-buffer)
25040 table-orig-buffer (cons origline table-orig-buffer))
25041 (when (or (not lines)
25042 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25043 (car lines))))
25044 (setq table-open nil
25045 table-buffer (nreverse table-buffer)
25046 table-orig-buffer (nreverse table-orig-buffer))
25047 (org-close-par-maybe)
25048 (insert (org-format-table-html table-buffer table-orig-buffer))))
25050 ;; Normal lines
25051 (when (string-match
25052 (cond
25053 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25054 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25055 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25056 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25057 line)
25058 (setq ind (org-get-string-indentation line)
25059 start-is-num (match-beginning 4)
25060 starter (if (match-beginning 2)
25061 (substring (match-string 2 line) 0 -1))
25062 line (substring line (match-beginning 5)))
25063 (unless (string-match "[^ \t]" line)
25064 ;; empty line. Pretend indentation is large.
25065 (setq ind (if org-empty-line-terminates-plain-lists
25067 (1+ (or (car local-list-indent) 1)))))
25068 (setq didclose nil)
25069 (while (and in-local-list
25070 (or (and (= ind (car local-list-indent))
25071 (not starter))
25072 (< ind (car local-list-indent))))
25073 (setq didclose t)
25074 (org-close-li)
25075 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25076 (pop local-list-num) (pop local-list-indent)
25077 (setq in-local-list local-list-indent))
25078 (cond
25079 ((and starter
25080 (or (not in-local-list)
25081 (> ind (car local-list-indent))))
25082 ;; Start new (level of) list
25083 (org-close-par-maybe)
25084 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25085 (push start-is-num local-list-num)
25086 (push ind local-list-indent)
25087 (setq in-local-list t))
25088 (starter
25089 ;; continue current list
25090 (org-close-li)
25091 (insert "<li>\n"))
25092 (didclose
25093 ;; we did close a list, normal text follows: need <p>
25094 (org-open-par)))
25095 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25096 (setq line
25097 (replace-match
25098 (if (equal (match-string 1 line) "X")
25099 "<b>[X]</b>"
25100 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25101 t t line))))
25103 ;; Empty lines start a new paragraph. If hand-formatted lists
25104 ;; are not fully interpreted, lines starting with "-", "+", "*"
25105 ;; also start a new paragraph.
25106 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25108 ;; Is this the start of a footnote?
25109 (when org-export-with-footnotes
25110 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25111 (org-close-par-maybe)
25112 (let ((n (match-string 1 line)))
25113 (setq line (replace-match
25114 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25116 ;; Check if the line break needs to be conserved
25117 (cond
25118 ((string-match "\\\\\\\\[ \t]*$" line)
25119 (setq line (replace-match "<br/>" t t line)))
25120 (org-export-preserve-breaks
25121 (setq line (concat line "<br/>"))))
25123 (insert line "\n")))))
25125 ;; Properly close all local lists and other lists
25126 (when inquote (insert "</pre>\n"))
25127 (when in-local-list
25128 ;; Close any local lists before inserting a new header line
25129 (while local-list-num
25130 (org-close-li)
25131 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25132 (pop local-list-num))
25133 (setq local-list-indent nil
25134 in-local-list nil))
25135 (org-html-level-start 1 nil umax
25136 (and org-export-with-toc (<= level umax))
25137 head-count)
25139 (unless body-only
25140 (when (plist-get opt-plist :auto-postamble)
25141 (insert "<div id=\"postamble\">")
25142 (when (and org-export-author-info author)
25143 (insert "<p class=\"author\"> "
25144 (nth 1 lang-words) ": " author "\n")
25145 (when email
25146 (if (listp (split-string email ",+ *"))
25147 (mapc (lambda(e)
25148 (insert "<a href=\"mailto:" e "\">&lt;"
25149 e "&gt;</a>\n"))
25150 (split-string email ",+ *"))
25151 (insert "<a href=\"mailto:" email "\">&lt;"
25152 email "&gt;</a>\n")))
25153 (insert "</p>\n"))
25154 (when (and date org-export-time-stamp-file)
25155 (insert "<p class=\"date\"> "
25156 (nth 2 lang-words) ": "
25157 date "</p>\n"))
25158 (insert "</div>"))
25160 (if org-export-html-with-timestamp
25161 (insert org-export-html-html-helper-timestamp))
25162 (insert (or (plist-get opt-plist :postamble) ""))
25163 (insert "</body>\n</html>\n"))
25165 (normal-mode)
25166 (if (eq major-mode default-major-mode) (html-mode))
25168 ;; insert the table of contents
25169 (goto-char (point-min))
25170 (when thetoc
25171 (if (or (re-search-forward
25172 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25173 (re-search-forward
25174 "\\[TABLE-OF-CONTENTS\\]" nil t))
25175 (progn
25176 (goto-char (match-beginning 0))
25177 (replace-match ""))
25178 (goto-char first-heading-pos)
25179 (when (looking-at "\\s-*</p>")
25180 (goto-char (match-end 0))
25181 (insert "\n")))
25182 (insert "<div id=\"table-of-contents\">\n")
25183 (mapc 'insert thetoc)
25184 (insert "</div>\n"))
25185 ;; remove empty paragraphs and lists
25186 (goto-char (point-min))
25187 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25188 (replace-match ""))
25189 (goto-char (point-min))
25190 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25191 (replace-match ""))
25192 ;; Convert whitespace place holders
25193 (goto-char (point-min))
25194 (let (beg end n)
25195 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25196 (setq n (get-text-property beg 'org-whitespace)
25197 end (next-single-property-change beg 'org-whitespace))
25198 (goto-char beg)
25199 (delete-region beg end)
25200 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25201 (make-string n ?x)))))
25203 (or to-buffer (save-buffer))
25204 (goto-char (point-min))
25205 (message "Exporting... done")
25206 (if (eq to-buffer 'string)
25207 (prog1 (buffer-substring (point-min) (point-max))
25208 (kill-buffer (current-buffer)))
25209 (current-buffer)))))
25211 (defvar org-table-colgroup-info nil)
25212 (defun org-format-table-ascii (lines)
25213 "Format a table for ascii export."
25214 (if (stringp lines)
25215 (setq lines (org-split-string lines "\n")))
25216 (if (not (string-match "^[ \t]*|" (car lines)))
25217 ;; Table made by table.el - test for spanning
25218 lines
25220 ;; A normal org table
25221 ;; Get rid of hlines at beginning and end
25222 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25223 (setq lines (nreverse lines))
25224 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25225 (setq lines (nreverse lines))
25226 (when org-export-table-remove-special-lines
25227 ;; Check if the table has a marking column. If yes remove the
25228 ;; column and the special lines
25229 (setq lines (org-table-clean-before-export lines)))
25230 ;; Get rid of the vertical lines except for grouping
25231 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25232 rtn line vl1 start)
25233 (while (setq line (pop lines))
25234 (if (string-match org-table-hline-regexp line)
25235 (and (string-match "|\\(.*\\)|" line)
25236 (setq line (replace-match " \\1" t nil line)))
25237 (setq start 0 vl1 vl)
25238 (while (string-match "|" line start)
25239 (setq start (match-end 0))
25240 (or (pop vl1) (setq line (replace-match " " t t line)))))
25241 (push line rtn))
25242 (nreverse rtn))))
25244 (defun org-colgroup-info-to-vline-list (info)
25245 (let (vl new last)
25246 (while info
25247 (setq last new new (pop info))
25248 (if (or (memq last '(:end :startend))
25249 (memq new '(:start :startend)))
25250 (push t vl)
25251 (push nil vl)))
25252 (setq vl (nreverse vl))
25253 (and vl (setcar vl nil))
25254 vl))
25256 (defun org-format-table-html (lines olines)
25257 "Find out which HTML converter to use and return the HTML code."
25258 (if (stringp lines)
25259 (setq lines (org-split-string lines "\n")))
25260 (if (string-match "^[ \t]*|" (car lines))
25261 ;; A normal org table
25262 (org-format-org-table-html lines)
25263 ;; Table made by table.el - test for spanning
25264 (let* ((hlines (delq nil (mapcar
25265 (lambda (x)
25266 (if (string-match "^[ \t]*\\+-" x) x
25267 nil))
25268 lines)))
25269 (first (car hlines))
25270 (ll (and (string-match "\\S-+" first)
25271 (match-string 0 first)))
25272 (re (concat "^[ \t]*" (regexp-quote ll)))
25273 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25274 hlines))))
25275 (if (and (not spanning)
25276 (not org-export-prefer-native-exporter-for-tables))
25277 ;; We can use my own converter with HTML conversions
25278 (org-format-table-table-html lines)
25279 ;; Need to use the code generator in table.el, with the original text.
25280 (org-format-table-table-html-using-table-generate-source olines)))))
25282 (defun org-format-org-table-html (lines &optional splice)
25283 "Format a table into HTML."
25284 ;; Get rid of hlines at beginning and end
25285 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25286 (setq lines (nreverse lines))
25287 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25288 (setq lines (nreverse lines))
25289 (when org-export-table-remove-special-lines
25290 ;; Check if the table has a marking column. If yes remove the
25291 ;; column and the special lines
25292 (setq lines (org-table-clean-before-export lines)))
25294 (let ((head (and org-export-highlight-first-table-line
25295 (delq nil (mapcar
25296 (lambda (x) (string-match "^[ \t]*|-" x))
25297 (cdr lines)))))
25298 (nlines 0) fnum i
25299 tbopen line fields html gr colgropen)
25300 (if splice (setq head nil))
25301 (unless splice (push (if head "<thead>" "<tbody>") html))
25302 (setq tbopen t)
25303 (while (setq line (pop lines))
25304 (catch 'next-line
25305 (if (string-match "^[ \t]*|-" line)
25306 (progn
25307 (unless splice
25308 (push (if head "</thead>" "</tbody>") html)
25309 (if lines (push "<tbody>" html) (setq tbopen nil)))
25310 (setq head nil) ;; head ends here, first time around
25311 ;; ignore this line
25312 (throw 'next-line t)))
25313 ;; Break the line into fields
25314 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25315 (unless fnum (setq fnum (make-vector (length fields) 0)))
25316 (setq nlines (1+ nlines) i -1)
25317 (push (concat "<tr>"
25318 (mapconcat
25319 (lambda (x)
25320 (setq i (1+ i))
25321 (if (and (< i nlines)
25322 (string-match org-table-number-regexp x))
25323 (incf (aref fnum i)))
25324 (if head
25325 (concat (car org-export-table-header-tags) x
25326 (cdr org-export-table-header-tags))
25327 (concat (car org-export-table-data-tags) x
25328 (cdr org-export-table-data-tags))))
25329 fields "")
25330 "</tr>")
25331 html)))
25332 (unless splice (if tbopen (push "</tbody>" html)))
25333 (unless splice (push "</table>\n" html))
25334 (setq html (nreverse html))
25335 (unless splice
25336 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25337 (push (mapconcat
25338 (lambda (x)
25339 (setq gr (pop org-table-colgroup-info))
25340 (format "%s<col align=\"%s\"></col>%s"
25341 (if (memq gr '(:start :startend))
25342 (prog1
25343 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25344 (setq colgropen t))
25346 (if (> (/ (float x) nlines) org-table-number-fraction)
25347 "right" "left")
25348 (if (memq gr '(:end :startend))
25349 (progn (setq colgropen nil) "</colgroup>")
25350 "")))
25351 fnum "")
25352 html)
25353 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25354 (push html-table-tag html))
25355 (concat (mapconcat 'identity html "\n") "\n")))
25357 (defun org-table-clean-before-export (lines)
25358 "Check if the table has a marking column.
25359 If yes remove the column and the special lines."
25360 (setq org-table-colgroup-info nil)
25361 (if (memq nil
25362 (mapcar
25363 (lambda (x) (or (string-match "^[ \t]*|-" x)
25364 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25365 lines))
25366 (progn
25367 (setq org-table-clean-did-remove-column nil)
25368 (delq nil
25369 (mapcar
25370 (lambda (x)
25371 (cond
25372 ((string-match "^[ \t]*| */ *|" x)
25373 (setq org-table-colgroup-info
25374 (mapcar (lambda (x)
25375 (cond ((member x '("<" "&lt;")) :start)
25376 ((member x '(">" "&gt;")) :end)
25377 ((member x '("<>" "&lt;&gt;")) :startend)
25378 (t nil)))
25379 (org-split-string x "[ \t]*|[ \t]*")))
25380 nil)
25381 (t x)))
25382 lines)))
25383 (setq org-table-clean-did-remove-column t)
25384 (delq nil
25385 (mapcar
25386 (lambda (x)
25387 (cond
25388 ((string-match "^[ \t]*| */ *|" x)
25389 (setq org-table-colgroup-info
25390 (mapcar (lambda (x)
25391 (cond ((member x '("<" "&lt;")) :start)
25392 ((member x '(">" "&gt;")) :end)
25393 ((member x '("<>" "&lt;&gt;")) :startend)
25394 (t nil)))
25395 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25396 nil)
25397 ((string-match "^[ \t]*| *[!_^/] *|" x)
25398 nil) ; ignore this line
25399 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25400 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25401 ;; remove the first column
25402 (replace-match "\\1|" t nil x))))
25403 lines))))
25405 (defun org-format-table-table-html (lines)
25406 "Format a table generated by table.el into HTML.
25407 This conversion does *not* use `table-generate-source' from table.el.
25408 This has the advantage that Org-mode's HTML conversions can be used.
25409 But it has the disadvantage, that no cell- or row-spanning is allowed."
25410 (let (line field-buffer
25411 (head org-export-highlight-first-table-line)
25412 fields html empty)
25413 (setq html (concat html-table-tag "\n"))
25414 (while (setq line (pop lines))
25415 (setq empty "&nbsp;")
25416 (catch 'next-line
25417 (if (string-match "^[ \t]*\\+-" line)
25418 (progn
25419 (if field-buffer
25420 (progn
25421 (setq
25422 html
25423 (concat
25424 html
25425 "<tr>"
25426 (mapconcat
25427 (lambda (x)
25428 (if (equal x "") (setq x empty))
25429 (if head
25430 (concat (car org-export-table-header-tags) x
25431 (cdr org-export-table-header-tags))
25432 (concat (car org-export-table-data-tags) x
25433 (cdr org-export-table-data-tags))))
25434 field-buffer "\n")
25435 "</tr>\n"))
25436 (setq head nil)
25437 (setq field-buffer nil)))
25438 ;; Ignore this line
25439 (throw 'next-line t)))
25440 ;; Break the line into fields and store the fields
25441 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25442 (if field-buffer
25443 (setq field-buffer (mapcar
25444 (lambda (x)
25445 (concat x "<br/>" (pop fields)))
25446 field-buffer))
25447 (setq field-buffer fields))))
25448 (setq html (concat html "</table>\n"))
25449 html))
25451 (defun org-format-table-table-html-using-table-generate-source (lines)
25452 "Format a table into html, using `table-generate-source' from table.el.
25453 This has the advantage that cell- or row-spanning is allowed.
25454 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25455 (require 'table)
25456 (with-current-buffer (get-buffer-create " org-tmp1 ")
25457 (erase-buffer)
25458 (insert (mapconcat 'identity lines "\n"))
25459 (goto-char (point-min))
25460 (if (not (re-search-forward "|[^+]" nil t))
25461 (error "Error processing table"))
25462 (table-recognize-table)
25463 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25464 (table-generate-source 'html " org-tmp2 ")
25465 (set-buffer " org-tmp2 ")
25466 (buffer-substring (point-min) (point-max))))
25468 (defun org-html-handle-time-stamps (s)
25469 "Format time stamps in string S, or remove them."
25470 (catch 'exit
25471 (let (r b)
25472 (while (string-match org-maybe-keyword-time-regexp s)
25473 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25474 ;; never export CLOCK
25475 (throw 'exit ""))
25476 (or b (setq b (substring s 0 (match-beginning 0))))
25477 (if (not org-export-with-timestamps)
25478 (setq r (concat r (substring s 0 (match-beginning 0)))
25479 s (substring s (match-end 0)))
25480 (setq r (concat
25481 r (substring s 0 (match-beginning 0))
25482 (if (match-end 1)
25483 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25484 (match-string 1 s)))
25485 (format " @<span class=\"timestamp\">%s@</span>"
25486 (substring
25487 (org-translate-time (match-string 3 s)) 1 -1)))
25488 s (substring s (match-end 0)))))
25489 ;; Line break if line started and ended with time stamp stuff
25490 (if (not r)
25492 (setq r (concat r s))
25493 (unless (string-match "\\S-" (concat b s))
25494 (setq r (concat r "@<br/>")))
25495 r))))
25497 (defun org-html-protect (s)
25498 ;; convert & to &amp;, < to &lt; and > to &gt;
25499 (let ((start 0))
25500 (while (string-match "&" s start)
25501 (setq s (replace-match "&amp;" t t s)
25502 start (1+ (match-beginning 0))))
25503 (while (string-match "<" s)
25504 (setq s (replace-match "&lt;" t t s)))
25505 (while (string-match ">" s)
25506 (setq s (replace-match "&gt;" t t s))))
25509 (defun org-export-cleanup-toc-line (s)
25510 "Remove tags and time staps from lines going into the toc."
25511 (when (memq org-export-with-tags '(not-in-toc nil))
25512 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25513 (setq s (replace-match "" t t s))))
25514 (when org-export-remove-timestamps-from-toc
25515 (while (string-match org-maybe-keyword-time-regexp s)
25516 (setq s (replace-match "" t t s))))
25517 (while (string-match org-bracket-link-regexp s)
25518 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25519 t t s)))
25522 (defun org-html-expand (string)
25523 "Prepare STRING for HTML export. Applies all active conversions.
25524 If there are links in the string, don't modify these."
25525 (let* ((re (concat org-bracket-link-regexp "\\|"
25526 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25527 m s l res)
25528 (while (setq m (string-match re string))
25529 (setq s (substring string 0 m)
25530 l (match-string 0 string)
25531 string (substring string (match-end 0)))
25532 (push (org-html-do-expand s) res)
25533 (push l res))
25534 (push (org-html-do-expand string) res)
25535 (apply 'concat (nreverse res))))
25537 (defun org-html-do-expand (s)
25538 "Apply all active conversions to translate special ASCII to HTML."
25539 (setq s (org-html-protect s))
25540 (if org-export-html-expand
25541 (let ((start 0))
25542 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25543 (setq s (replace-match "<\\1>" t nil s)))))
25544 (if org-export-with-emphasize
25545 (setq s (org-export-html-convert-emphasize s)))
25546 (if org-export-with-special-strings
25547 (setq s (org-export-html-convert-special-strings s)))
25548 (if org-export-with-sub-superscripts
25549 (setq s (org-export-html-convert-sub-super s)))
25550 (if org-export-with-TeX-macros
25551 (let ((start 0) wd ass)
25552 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25553 (if (get-text-property (match-beginning 0) 'org-protected s)
25554 (setq start (match-end 0))
25555 (setq wd (match-string 1 s))
25556 (if (setq ass (assoc wd org-html-entities))
25557 (setq s (replace-match (or (cdr ass)
25558 (concat "&" (car ass) ";"))
25559 t t s))
25560 (setq start (+ start (length wd))))))))
25563 (defun org-create-multibrace-regexp (left right n)
25564 "Create a regular expression which will match a balanced sexp.
25565 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25566 as single character strings.
25567 The regexp returned will match the entire expression including the
25568 delimiters. It will also define a single group which contains the
25569 match except for the outermost delimiters. The maximum depth of
25570 stacked delimiters is N. Escaping delimiters is not possible."
25571 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25572 (or "\\|")
25573 (re nothing)
25574 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25575 (while (> n 1)
25576 (setq n (1- n)
25577 re (concat re or next)
25578 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25579 (concat left "\\(" re "\\)" right)))
25581 (defvar org-match-substring-regexp
25582 (concat
25583 "\\([^\\]\\)\\([_^]\\)\\("
25584 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25585 "\\|"
25586 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25587 "\\|"
25588 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25589 "The regular expression matching a sub- or superscript.")
25591 (defvar org-match-substring-with-braces-regexp
25592 (concat
25593 "\\([^\\]\\)\\([_^]\\)\\("
25594 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25595 "\\)")
25596 "The regular expression matching a sub- or superscript, forcing braces.")
25598 (defconst org-export-html-special-string-regexps
25599 '(("\\\\-" . "&shy;")
25600 ("---\\([^-]\\)" . "&mdash;\\1")
25601 ("--\\([^-]\\)" . "&ndash;\\1")
25602 ("\\.\\.\\." . "&hellip;"))
25603 "Regular expressions for special string conversion.")
25605 (defun org-export-html-convert-special-strings (string)
25606 "Convert special characters in STRING to HTML."
25607 (let ((all org-export-html-special-string-regexps)
25608 e a re rpl start)
25609 (while (setq a (pop all))
25610 (setq re (car a) rpl (cdr a) start 0)
25611 (while (string-match re string start)
25612 (if (get-text-property (match-beginning 0) 'org-protected string)
25613 (setq start (match-end 0))
25614 (setq string (replace-match rpl t nil string)))))
25615 string))
25617 (defun org-export-html-convert-sub-super (string)
25618 "Convert sub- and superscripts in STRING to HTML."
25619 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25620 (while (string-match org-match-substring-regexp string s)
25621 (cond
25622 ((and requireb (match-end 8)) (setq s (match-end 2)))
25623 ((get-text-property (match-beginning 2) 'org-protected string)
25624 (setq s (match-end 2)))
25626 (setq s (match-end 1)
25627 key (if (string= (match-string 2 string) "_") "sub" "sup")
25628 c (or (match-string 8 string)
25629 (match-string 6 string)
25630 (match-string 5 string))
25631 string (replace-match
25632 (concat (match-string 1 string)
25633 "<" key ">" c "</" key ">")
25634 t t string)))))
25635 (while (string-match "\\\\\\([_^]\\)" string)
25636 (setq string (replace-match (match-string 1 string) t t string)))
25637 string))
25639 (defun org-export-html-convert-emphasize (string)
25640 "Apply emphasis."
25641 (let ((s 0) rpl)
25642 (while (string-match org-emph-re string s)
25643 (if (not (equal
25644 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25645 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25646 (setq s (match-beginning 0)
25648 (concat
25649 (match-string 1 string)
25650 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25651 (match-string 4 string)
25652 (nth 3 (assoc (match-string 3 string)
25653 org-emphasis-alist))
25654 (match-string 5 string))
25655 string (replace-match rpl t t string)
25656 s (+ s (- (length rpl) 2)))
25657 (setq s (1+ s))))
25658 string))
25660 (defvar org-par-open nil)
25661 (defun org-open-par ()
25662 "Insert <p>, but first close previous paragraph if any."
25663 (org-close-par-maybe)
25664 (insert "\n<p>")
25665 (setq org-par-open t))
25666 (defun org-close-par-maybe ()
25667 "Close paragraph if there is one open."
25668 (when org-par-open
25669 (insert "</p>")
25670 (setq org-par-open nil)))
25671 (defun org-close-li ()
25672 "Close <li> if necessary."
25673 (org-close-par-maybe)
25674 (insert "</li>\n"))
25676 (defvar body-only) ; dynamically scoped into this.
25677 (defun org-html-level-start (level title umax with-toc head-count)
25678 "Insert a new level in HTML export.
25679 When TITLE is nil, just close all open levels."
25680 (org-close-par-maybe)
25681 (let ((l org-level-max))
25682 (while (>= l level)
25683 (if (aref org-levels-open (1- l))
25684 (progn
25685 (org-html-level-close l umax)
25686 (aset org-levels-open (1- l) nil)))
25687 (setq l (1- l)))
25688 (when title
25689 ;; If title is nil, this means this function is called to close
25690 ;; all levels, so the rest is done only if title is given
25691 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25692 (setq title (replace-match
25693 (if org-export-with-tags
25694 (save-match-data
25695 (concat
25696 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25697 (mapconcat 'identity (org-split-string
25698 (match-string 1 title) ":")
25699 "&nbsp;")
25700 "</span>"))
25702 t t title)))
25703 (if (> level umax)
25704 (progn
25705 (if (aref org-levels-open (1- level))
25706 (progn
25707 (org-close-li)
25708 (insert "<li>" title "<br/>\n"))
25709 (aset org-levels-open (1- level) t)
25710 (org-close-par-maybe)
25711 (insert "<ul>\n<li>" title "<br/>\n")))
25712 (aset org-levels-open (1- level) t)
25713 (if (and org-export-with-section-numbers (not body-only))
25714 (setq title (concat (org-section-number level) " " title)))
25715 (setq level (+ level org-export-html-toplevel-hlevel -1))
25716 (if with-toc
25717 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25718 level level head-count title level))
25719 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25720 (org-open-par)))))
25722 (defun org-html-level-close (level max-outline-level)
25723 "Terminate one level in HTML export."
25724 (if (<= level max-outline-level)
25725 (insert "</div>\n")
25726 (org-close-li)
25727 (insert "</ul>\n")))
25729 ;;; iCalendar export
25731 ;;;###autoload
25732 (defun org-export-icalendar-this-file ()
25733 "Export current file as an iCalendar file.
25734 The iCalendar file will be located in the same directory as the Org-mode
25735 file, but with extension `.ics'."
25736 (interactive)
25737 (org-export-icalendar nil buffer-file-name))
25739 ;;;###autoload
25740 (defun org-export-icalendar-all-agenda-files ()
25741 "Export all files in `org-agenda-files' to iCalendar .ics files.
25742 Each iCalendar file will be located in the same directory as the Org-mode
25743 file, but with extension `.ics'."
25744 (interactive)
25745 (apply 'org-export-icalendar nil (org-agenda-files t)))
25747 ;;;###autoload
25748 (defun org-export-icalendar-combine-agenda-files ()
25749 "Export all files in `org-agenda-files' to a single combined iCalendar file.
25750 The file is stored under the name `org-combined-agenda-icalendar-file'."
25751 (interactive)
25752 (apply 'org-export-icalendar t (org-agenda-files t)))
25754 (defun org-export-icalendar (combine &rest files)
25755 "Create iCalendar files for all elements of FILES.
25756 If COMBINE is non-nil, combine all calendar entries into a single large
25757 file and store it under the name `org-combined-agenda-icalendar-file'."
25758 (save-excursion
25759 (org-prepare-agenda-buffers files)
25760 (let* ((dir (org-export-directory
25761 :ical (list :publishing-directory
25762 org-export-publishing-directory)))
25763 file ical-file ical-buffer category started org-agenda-new-buffers)
25765 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
25766 (when combine
25767 (setq ical-file
25768 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
25769 org-combined-agenda-icalendar-file
25770 (expand-file-name org-combined-agenda-icalendar-file dir))
25771 ical-buffer (org-get-agenda-file-buffer ical-file))
25772 (set-buffer ical-buffer) (erase-buffer))
25773 (while (setq file (pop files))
25774 (catch 'nextfile
25775 (org-check-agenda-file file)
25776 (set-buffer (org-get-agenda-file-buffer file))
25777 (unless combine
25778 (setq ical-file (concat (file-name-as-directory dir)
25779 (file-name-sans-extension
25780 (file-name-nondirectory buffer-file-name))
25781 ".ics"))
25782 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
25783 (with-current-buffer ical-buffer (erase-buffer)))
25784 (setq category (or org-category
25785 (file-name-sans-extension
25786 (file-name-nondirectory buffer-file-name))))
25787 (if (symbolp category) (setq category (symbol-name category)))
25788 (let ((standard-output ical-buffer))
25789 (if combine
25790 (and (not started) (setq started t)
25791 (org-start-icalendar-file org-icalendar-combined-name))
25792 (org-start-icalendar-file category))
25793 (org-print-icalendar-entries combine)
25794 (when (or (and combine (not files)) (not combine))
25795 (org-finish-icalendar-file)
25796 (set-buffer ical-buffer)
25797 (save-buffer)
25798 (run-hooks 'org-after-save-iCalendar-file-hook)))))
25799 (org-release-buffers org-agenda-new-buffers))))
25801 (defvar org-after-save-iCalendar-file-hook nil
25802 "Hook run after an iCalendar file has been saved.
25803 The iCalendar buffer is still current when this hook is run.
25804 A good way to use this is to tell a desktop calenndar application to re-read
25805 the iCalendar file.")
25807 (defun org-print-icalendar-entries (&optional combine)
25808 "Print iCalendar entries for the current Org-mode file to `standard-output'.
25809 When COMBINE is non nil, add the category to each line."
25810 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
25811 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
25812 (dts (org-ical-ts-to-string
25813 (format-time-string (cdr org-time-stamp-formats) (current-time))
25814 "DTSTART"))
25815 hd ts ts2 state status (inc t) pos b sexp rrule
25816 scheduledp deadlinep tmp pri category entry location summary desc
25817 (sexp-buffer (get-buffer-create "*ical-tmp*")))
25818 (org-refresh-category-properties)
25819 (save-excursion
25820 (goto-char (point-min))
25821 (while (re-search-forward re1 nil t)
25822 (catch :skip
25823 (org-agenda-skip)
25824 (setq pos (match-beginning 0)
25825 ts (match-string 0)
25826 inc t
25827 hd (org-get-heading)
25828 summary (org-icalendar-cleanup-string
25829 (org-entry-get nil "SUMMARY"))
25830 desc (org-icalendar-cleanup-string
25831 (or (org-entry-get nil "DESCRIPTION")
25832 (and org-icalendar-include-body (org-get-entry)))
25833 t org-icalendar-include-body)
25834 location (org-icalendar-cleanup-string
25835 (org-entry-get nil "LOCATION"))
25836 category (org-get-category))
25837 (if (looking-at re2)
25838 (progn
25839 (goto-char (match-end 0))
25840 (setq ts2 (match-string 1) inc nil))
25841 (setq tmp (buffer-substring (max (point-min)
25842 (- pos org-ds-keyword-length))
25843 pos)
25844 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
25845 (progn
25846 (setq inc nil)
25847 (replace-match "\\1" t nil ts))
25849 deadlinep (string-match org-deadline-regexp tmp)
25850 scheduledp (string-match org-scheduled-regexp tmp)
25851 ;; donep (org-entry-is-done-p)
25853 (if (or (string-match org-tr-regexp hd)
25854 (string-match org-ts-regexp hd))
25855 (setq hd (replace-match "" t t hd)))
25856 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
25857 (setq rrule
25858 (concat "\nRRULE:FREQ="
25859 (cdr (assoc
25860 (match-string 2 ts)
25861 '(("d" . "DAILY")("w" . "WEEKLY")
25862 ("m" . "MONTHLY")("y" . "YEARLY"))))
25863 ";INTERVAL=" (match-string 1 ts)))
25864 (setq rrule ""))
25865 (setq summary (or summary hd))
25866 (if (string-match org-bracket-link-regexp summary)
25867 (setq summary
25868 (replace-match (if (match-end 3)
25869 (match-string 3 summary)
25870 (match-string 1 summary))
25871 t t summary)))
25872 (if deadlinep (setq summary (concat "DL: " summary)))
25873 (if scheduledp (setq summary (concat "S: " summary)))
25874 (if (string-match "\\`<%%" ts)
25875 (with-current-buffer sexp-buffer
25876 (insert (substring ts 1 -1) " " summary "\n"))
25877 (princ (format "BEGIN:VEVENT
25879 %s%s
25880 SUMMARY:%s%s%s
25881 CATEGORIES:%s
25882 END:VEVENT\n"
25883 (org-ical-ts-to-string ts "DTSTART")
25884 (org-ical-ts-to-string ts2 "DTEND" inc)
25885 rrule summary
25886 (if (and desc (string-match "\\S-" desc))
25887 (concat "\nDESCRIPTION: " desc) "")
25888 (if (and location (string-match "\\S-" location))
25889 (concat "\nLOCATION: " location) "")
25890 category)))))
25892 (when (and org-icalendar-include-sexps
25893 (condition-case nil (require 'icalendar) (error nil))
25894 (fboundp 'icalendar-export-region))
25895 ;; Get all the literal sexps
25896 (goto-char (point-min))
25897 (while (re-search-forward "^&?%%(" nil t)
25898 (catch :skip
25899 (org-agenda-skip)
25900 (setq b (match-beginning 0))
25901 (goto-char (1- (match-end 0)))
25902 (forward-sexp 1)
25903 (end-of-line 1)
25904 (setq sexp (buffer-substring b (point)))
25905 (with-current-buffer sexp-buffer
25906 (insert sexp "\n"))
25907 (princ (org-diary-to-ical-string sexp-buffer)))))
25909 (when org-icalendar-include-todo
25910 (goto-char (point-min))
25911 (while (re-search-forward org-todo-line-regexp nil t)
25912 (catch :skip
25913 (org-agenda-skip)
25914 (setq state (match-string 2))
25915 (setq status (if (member state org-done-keywords)
25916 "COMPLETED" "NEEDS-ACTION"))
25917 (when (and state
25918 (or (not (member state org-done-keywords))
25919 (eq org-icalendar-include-todo 'all))
25920 (not (member org-archive-tag (org-get-tags-at)))
25922 (setq hd (match-string 3)
25923 summary (org-icalendar-cleanup-string
25924 (org-entry-get nil "SUMMARY"))
25925 desc (org-icalendar-cleanup-string
25926 (or (org-entry-get nil "DESCRIPTION")
25927 (and org-icalendar-include-body (org-get-entry)))
25928 t org-icalendar-include-body)
25929 location (org-icalendar-cleanup-string
25930 (org-entry-get nil "LOCATION")))
25931 (if (string-match org-bracket-link-regexp hd)
25932 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
25933 (match-string 1 hd))
25934 t t hd)))
25935 (if (string-match org-priority-regexp hd)
25936 (setq pri (string-to-char (match-string 2 hd))
25937 hd (concat (substring hd 0 (match-beginning 1))
25938 (substring hd (match-end 1))))
25939 (setq pri org-default-priority))
25940 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
25941 (- org-lowest-priority org-highest-priority))))))
25943 (princ (format "BEGIN:VTODO
25945 SUMMARY:%s%s%s
25946 CATEGORIES:%s
25947 SEQUENCE:1
25948 PRIORITY:%d
25949 STATUS:%s
25950 END:VTODO\n"
25952 (or summary hd)
25953 (if (and location (string-match "\\S-" location))
25954 (concat "\nLOCATION: " location) "")
25955 (if (and desc (string-match "\\S-" desc))
25956 (concat "\nDESCRIPTION: " desc) "")
25957 category pri status)))))))))
25959 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
25960 "Take out stuff and quote what needs to be quoted.
25961 When IS-BODY is non-nil, assume that this is the body of an item, clean up
25962 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
25963 characters."
25964 (if (not s)
25966 (when is-body
25967 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
25968 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
25969 (while (string-match re s) (setq s (replace-match "" t t s)))
25970 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
25971 (let ((start 0))
25972 (while (string-match "\\([,;\\]\\)" s start)
25973 (setq start (+ (match-beginning 0) 2)
25974 s (replace-match "\\\\\\1" nil nil s))))
25975 (when is-body
25976 (while (string-match "[ \t]*\n[ \t]*" s)
25977 (setq s (replace-match "\\n" t t s))))
25978 (setq s (org-trim s))
25979 (if is-body
25980 (if maxlength
25981 (if (and (numberp maxlength)
25982 (> (length s) maxlength))
25983 (setq s (substring s 0 maxlength)))))
25986 (defun org-get-entry ()
25987 "Clean-up description string."
25988 (save-excursion
25989 (org-back-to-heading t)
25990 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
25992 (defun org-start-icalendar-file (name)
25993 "Start an iCalendar file by inserting the header."
25994 (let ((user user-full-name)
25995 (name (or name "unknown"))
25996 (timezone (cadr (current-time-zone))))
25997 (princ
25998 (format "BEGIN:VCALENDAR
25999 VERSION:2.0
26000 X-WR-CALNAME:%s
26001 PRODID:-//%s//Emacs with Org-mode//EN
26002 X-WR-TIMEZONE:%s
26003 CALSCALE:GREGORIAN\n" name user timezone))))
26005 (defun org-finish-icalendar-file ()
26006 "Finish an iCalendar file by inserting the END statement."
26007 (princ "END:VCALENDAR\n"))
26009 (defun org-ical-ts-to-string (s keyword &optional inc)
26010 "Take a time string S and convert it to iCalendar format.
26011 KEYWORD is added in front, to make a complete line like DTSTART....
26012 When INC is non-nil, increase the hour by two (if time string contains
26013 a time), or the day by one (if it does not contain a time)."
26014 (let ((t1 (org-parse-time-string s 'nodefault))
26015 t2 fmt have-time time)
26016 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26017 (setq t2 t1 have-time t)
26018 (setq t2 (org-parse-time-string s)))
26019 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26020 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26021 (when inc
26022 (if have-time
26023 (if org-agenda-default-appointment-duration
26024 (setq mi (+ org-agenda-default-appointment-duration mi))
26025 (setq h (+ 2 h)))
26026 (setq d (1+ d))))
26027 (setq time (encode-time s mi h d m y)))
26028 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26029 (concat keyword (format-time-string fmt time))))
26031 ;;; XOXO export
26033 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26034 (with-current-buffer buffer
26035 (apply 'insert output)))
26036 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26038 (defun org-export-as-xoxo (&optional buffer)
26039 "Export the org buffer as XOXO.
26040 The XOXO buffer is named *xoxo-<source buffer name>*"
26041 (interactive (list (current-buffer)))
26042 ;; A quickie abstraction
26044 ;; Output everything as XOXO
26045 (with-current-buffer (get-buffer buffer)
26046 (let* ((pos (point))
26047 (opt-plist (org-combine-plists (org-default-export-plist)
26048 (org-infile-export-plist)))
26049 (filename (concat (file-name-as-directory
26050 (org-export-directory :xoxo opt-plist))
26051 (file-name-sans-extension
26052 (file-name-nondirectory buffer-file-name))
26053 ".html"))
26054 (out (find-file-noselect filename))
26055 (last-level 1)
26056 (hanging-li nil))
26057 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26058 ;; Check the output buffer is empty.
26059 (with-current-buffer out (erase-buffer))
26060 ;; Kick off the output
26061 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26062 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26063 (let* ((hd (match-string-no-properties 1))
26064 (level (length hd))
26065 (text (concat
26066 (match-string-no-properties 2)
26067 (save-excursion
26068 (goto-char (match-end 0))
26069 (let ((str ""))
26070 (catch 'loop
26071 (while 't
26072 (forward-line)
26073 (if (looking-at "^[ \t]\\(.*\\)")
26074 (setq str (concat str (match-string-no-properties 1)))
26075 (throw 'loop str)))))))))
26077 ;; Handle level rendering
26078 (cond
26079 ((> level last-level)
26080 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26082 ((< level last-level)
26083 (dotimes (- (- last-level level) 1)
26084 (if hanging-li
26085 (org-export-as-xoxo-insert-into out "</li>\n"))
26086 (org-export-as-xoxo-insert-into out "</ol>\n"))
26087 (when hanging-li
26088 (org-export-as-xoxo-insert-into out "</li>\n")
26089 (setq hanging-li nil)))
26091 ((equal level last-level)
26092 (if hanging-li
26093 (org-export-as-xoxo-insert-into out "</li>\n")))
26096 (setq last-level level)
26098 ;; And output the new li
26099 (setq hanging-li 't)
26100 (if (equal ?+ (elt text 0))
26101 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26102 (org-export-as-xoxo-insert-into out "<li>" text))))
26104 ;; Finally finish off the ol
26105 (dotimes (- last-level 1)
26106 (if hanging-li
26107 (org-export-as-xoxo-insert-into out "</li>\n"))
26108 (org-export-as-xoxo-insert-into out "</ol>\n"))
26110 (goto-char pos)
26111 ;; Finish the buffer off and clean it up.
26112 (switch-to-buffer-other-window out)
26113 (indent-region (point-min) (point-max) nil)
26114 (save-buffer)
26115 (goto-char (point-min))
26119 ;;;; Key bindings
26121 ;; Make `C-c C-x' a prefix key
26122 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26124 ;; TAB key with modifiers
26125 (org-defkey org-mode-map "\C-i" 'org-cycle)
26126 (org-defkey org-mode-map [(tab)] 'org-cycle)
26127 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26128 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26129 (org-defkey org-mode-map "\M-\t" 'org-complete)
26130 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26131 ;; The following line is necessary under Suse GNU/Linux
26132 (unless (featurep 'xemacs)
26133 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26134 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26135 (define-key org-mode-map [backtab] 'org-shifttab)
26137 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26138 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26139 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26141 ;; Cursor keys with modifiers
26142 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26143 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26144 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26145 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26147 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26148 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26149 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26150 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26152 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26153 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26154 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26155 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26157 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26158 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26160 ;;; Extra keys for tty access.
26161 ;; We only set them when really needed because otherwise the
26162 ;; menus don't show the simple keys
26164 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26165 (not window-system))
26166 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26167 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26168 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26169 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26170 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26171 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26172 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26173 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26174 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26175 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26176 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26177 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26178 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26179 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26180 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26181 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26182 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26183 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26184 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26185 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26186 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26187 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26189 ;; All the other keys
26191 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26192 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26193 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26194 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26195 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26196 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26197 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26198 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26199 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26200 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26201 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26202 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26203 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26204 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26205 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26206 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26207 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26208 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26209 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26210 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26211 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26212 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26213 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26214 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26215 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26216 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26217 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26218 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26219 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26220 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26221 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26222 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26223 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26224 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26225 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26226 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26227 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26228 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26229 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26230 (org-defkey org-mode-map "\C-c^" 'org-sort)
26231 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26232 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26233 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26234 (org-defkey org-mode-map "\C-m" 'org-return)
26235 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26236 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26237 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26238 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26239 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26240 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26241 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26242 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26243 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26244 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26245 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26246 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26247 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26248 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26249 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26250 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26251 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26253 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26254 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26255 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26256 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26258 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26259 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26260 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26261 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26262 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26263 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26264 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26265 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26266 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26267 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26268 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26269 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26271 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26273 (when (featurep 'xemacs)
26274 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26276 (defsubst org-table-p () (org-at-table-p))
26278 (defun org-self-insert-command (N)
26279 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26280 If the cursor is in a table looking at whitespace, the whitespace is
26281 overwritten, and the table is not marked as requiring realignment."
26282 (interactive "p")
26283 (if (and (org-table-p)
26284 (progn
26285 ;; check if we blank the field, and if that triggers align
26286 (and org-table-auto-blank-field
26287 (member last-command
26288 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26289 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26290 ;; got extra space, this field does not determine column width
26291 (let (org-table-may-need-update) (org-table-blank-field))
26292 ;; no extra space, this field may determine column width
26293 (org-table-blank-field)))
26295 (eq N 1)
26296 (looking-at "[^|\n]* |"))
26297 (let (org-table-may-need-update)
26298 (goto-char (1- (match-end 0)))
26299 (delete-backward-char 1)
26300 (goto-char (match-beginning 0))
26301 (self-insert-command N))
26302 (setq org-table-may-need-update t)
26303 (self-insert-command N)
26304 (org-fix-tags-on-the-fly)))
26306 (defun org-fix-tags-on-the-fly ()
26307 (when (and (equal (char-after (point-at-bol)) ?*)
26308 (org-on-heading-p))
26309 (org-align-tags-here org-tags-column)))
26311 (defun org-delete-backward-char (N)
26312 "Like `delete-backward-char', insert whitespace at field end in tables.
26313 When deleting backwards, in tables this function will insert whitespace in
26314 front of the next \"|\" separator, to keep the table aligned. The table will
26315 still be marked for re-alignment if the field did fill the entire column,
26316 because, in this case the deletion might narrow the column."
26317 (interactive "p")
26318 (if (and (org-table-p)
26319 (eq N 1)
26320 (string-match "|" (buffer-substring (point-at-bol) (point)))
26321 (looking-at ".*?|"))
26322 (let ((pos (point))
26323 (noalign (looking-at "[^|\n\r]* |"))
26324 (c org-table-may-need-update))
26325 (backward-delete-char N)
26326 (skip-chars-forward "^|")
26327 (insert " ")
26328 (goto-char (1- pos))
26329 ;; noalign: if there were two spaces at the end, this field
26330 ;; does not determine the width of the column.
26331 (if noalign (setq org-table-may-need-update c)))
26332 (backward-delete-char N)
26333 (org-fix-tags-on-the-fly)))
26335 (defun org-delete-char (N)
26336 "Like `delete-char', but insert whitespace at field end in tables.
26337 When deleting characters, in tables this function will insert whitespace in
26338 front of the next \"|\" separator, to keep the table aligned. The table will
26339 still be marked for re-alignment if the field did fill the entire column,
26340 because, in this case the deletion might narrow the column."
26341 (interactive "p")
26342 (if (and (org-table-p)
26343 (not (bolp))
26344 (not (= (char-after) ?|))
26345 (eq N 1))
26346 (if (looking-at ".*?|")
26347 (let ((pos (point))
26348 (noalign (looking-at "[^|\n\r]* |"))
26349 (c org-table-may-need-update))
26350 (replace-match (concat
26351 (substring (match-string 0) 1 -1)
26352 " |"))
26353 (goto-char pos)
26354 ;; noalign: if there were two spaces at the end, this field
26355 ;; does not determine the width of the column.
26356 (if noalign (setq org-table-may-need-update c)))
26357 (delete-char N))
26358 (delete-char N)
26359 (org-fix-tags-on-the-fly)))
26361 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26362 (put 'org-self-insert-command 'delete-selection t)
26363 (put 'orgtbl-self-insert-command 'delete-selection t)
26364 (put 'org-delete-char 'delete-selection 'supersede)
26365 (put 'org-delete-backward-char 'delete-selection 'supersede)
26367 ;; Make `flyspell-mode' delay after some commands
26368 (put 'org-self-insert-command 'flyspell-delayed t)
26369 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26370 (put 'org-delete-char 'flyspell-delayed t)
26371 (put 'org-delete-backward-char 'flyspell-delayed t)
26373 ;; Make pabbrev-mode expand after org-mode commands
26374 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26375 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26377 ;; How to do this: Measure non-white length of current string
26378 ;; If equal to column width, we should realign.
26380 (defun org-remap (map &rest commands)
26381 "In MAP, remap the functions given in COMMANDS.
26382 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26383 (let (new old)
26384 (while commands
26385 (setq old (pop commands) new (pop commands))
26386 (if (fboundp 'command-remapping)
26387 (org-defkey map (vector 'remap old) new)
26388 (substitute-key-definition old new map global-map)))))
26390 (when (eq org-enable-table-editor 'optimized)
26391 ;; If the user wants maximum table support, we need to hijack
26392 ;; some standard editing functions
26393 (org-remap org-mode-map
26394 'self-insert-command 'org-self-insert-command
26395 'delete-char 'org-delete-char
26396 'delete-backward-char 'org-delete-backward-char)
26397 (org-defkey org-mode-map "|" 'org-force-self-insert))
26399 (defun org-shiftcursor-error ()
26400 "Throw an error because Shift-Cursor command was applied in wrong context."
26401 (error "This command is active in special context like tables, headlines or timestamps"))
26403 (defun org-shifttab (&optional arg)
26404 "Global visibility cycling or move to previous table field.
26405 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26406 on context.
26407 See the individual commands for more information."
26408 (interactive "P")
26409 (cond
26410 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26411 (arg (message "Content view to level: ")
26412 (org-content (prefix-numeric-value arg))
26413 (setq org-cycle-global-status 'overview))
26414 (t (call-interactively 'org-global-cycle))))
26416 (defun org-shiftmetaleft ()
26417 "Promote subtree or delete table column.
26418 Calls `org-promote-subtree', `org-outdent-item',
26419 or `org-table-delete-column', depending on context.
26420 See the individual commands for more information."
26421 (interactive)
26422 (cond
26423 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26424 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26425 ((org-at-item-p) (call-interactively 'org-outdent-item))
26426 (t (org-shiftcursor-error))))
26428 (defun org-shiftmetaright ()
26429 "Demote subtree or insert table column.
26430 Calls `org-demote-subtree', `org-indent-item',
26431 or `org-table-insert-column', depending on context.
26432 See the individual commands for more information."
26433 (interactive)
26434 (cond
26435 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26436 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26437 ((org-at-item-p) (call-interactively 'org-indent-item))
26438 (t (org-shiftcursor-error))))
26440 (defun org-shiftmetaup (&optional arg)
26441 "Move subtree up or kill table row.
26442 Calls `org-move-subtree-up' or `org-table-kill-row' or
26443 `org-move-item-up' depending on context. See the individual commands
26444 for more information."
26445 (interactive "P")
26446 (cond
26447 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26448 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26449 ((org-at-item-p) (call-interactively 'org-move-item-up))
26450 (t (org-shiftcursor-error))))
26451 (defun org-shiftmetadown (&optional arg)
26452 "Move subtree down or insert table row.
26453 Calls `org-move-subtree-down' or `org-table-insert-row' or
26454 `org-move-item-down', depending on context. See the individual
26455 commands for more information."
26456 (interactive "P")
26457 (cond
26458 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26459 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26460 ((org-at-item-p) (call-interactively 'org-move-item-down))
26461 (t (org-shiftcursor-error))))
26463 (defun org-metaleft (&optional arg)
26464 "Promote heading or move table column to left.
26465 Calls `org-do-promote' or `org-table-move-column', depending on context.
26466 With no specific context, calls the Emacs default `backward-word'.
26467 See the individual commands for more information."
26468 (interactive "P")
26469 (cond
26470 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26471 ((or (org-on-heading-p) (org-region-active-p))
26472 (call-interactively 'org-do-promote))
26473 ((org-at-item-p) (call-interactively 'org-outdent-item))
26474 (t (call-interactively 'backward-word))))
26476 (defun org-metaright (&optional arg)
26477 "Demote subtree or move table column to right.
26478 Calls `org-do-demote' or `org-table-move-column', depending on context.
26479 With no specific context, calls the Emacs default `forward-word'.
26480 See the individual commands for more information."
26481 (interactive "P")
26482 (cond
26483 ((org-at-table-p) (call-interactively 'org-table-move-column))
26484 ((or (org-on-heading-p) (org-region-active-p))
26485 (call-interactively 'org-do-demote))
26486 ((org-at-item-p) (call-interactively 'org-indent-item))
26487 (t (call-interactively 'forward-word))))
26489 (defun org-metaup (&optional arg)
26490 "Move subtree up or move table row up.
26491 Calls `org-move-subtree-up' or `org-table-move-row' or
26492 `org-move-item-up', depending on context. See the individual commands
26493 for more information."
26494 (interactive "P")
26495 (cond
26496 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26497 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26498 ((org-at-item-p) (call-interactively 'org-move-item-up))
26499 (t (transpose-lines 1) (beginning-of-line -1))))
26501 (defun org-metadown (&optional arg)
26502 "Move subtree down or move table row down.
26503 Calls `org-move-subtree-down' or `org-table-move-row' or
26504 `org-move-item-down', depending on context. See the individual
26505 commands for more information."
26506 (interactive "P")
26507 (cond
26508 ((org-at-table-p) (call-interactively 'org-table-move-row))
26509 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26510 ((org-at-item-p) (call-interactively 'org-move-item-down))
26511 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26513 (defun org-shiftup (&optional arg)
26514 "Increase item in timestamp or increase priority of current headline.
26515 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26516 depending on context. See the individual commands for more information."
26517 (interactive "P")
26518 (cond
26519 ((org-at-timestamp-p t)
26520 (call-interactively (if org-edit-timestamp-down-means-later
26521 'org-timestamp-down 'org-timestamp-up)))
26522 ((org-on-heading-p) (call-interactively 'org-priority-up))
26523 ((org-at-item-p) (call-interactively 'org-previous-item))
26524 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26526 (defun org-shiftdown (&optional arg)
26527 "Decrease item in timestamp or decrease priority of current headline.
26528 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26529 depending on context. See the individual commands for more information."
26530 (interactive "P")
26531 (cond
26532 ((org-at-timestamp-p t)
26533 (call-interactively (if org-edit-timestamp-down-means-later
26534 'org-timestamp-up 'org-timestamp-down)))
26535 ((org-on-heading-p) (call-interactively 'org-priority-down))
26536 (t (call-interactively 'org-next-item))))
26538 (defun org-shiftright ()
26539 "Next TODO keyword or timestamp one day later, depending on context."
26540 (interactive)
26541 (cond
26542 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26543 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26544 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26545 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26546 (t (org-shiftcursor-error))))
26548 (defun org-shiftleft ()
26549 "Previous TODO keyword or timestamp one day earlier, depending on context."
26550 (interactive)
26551 (cond
26552 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26553 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26554 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26555 ((org-at-property-p)
26556 (call-interactively 'org-property-previous-allowed-value))
26557 (t (org-shiftcursor-error))))
26559 (defun org-shiftcontrolright ()
26560 "Switch to next TODO set."
26561 (interactive)
26562 (cond
26563 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26564 (t (org-shiftcursor-error))))
26566 (defun org-shiftcontrolleft ()
26567 "Switch to previous TODO set."
26568 (interactive)
26569 (cond
26570 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26571 (t (org-shiftcursor-error))))
26573 (defun org-ctrl-c-ret ()
26574 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26575 (interactive)
26576 (cond
26577 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26578 (t (call-interactively 'org-insert-heading))))
26580 (defun org-copy-special ()
26581 "Copy region in table or copy current subtree.
26582 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26583 See the individual commands for more information."
26584 (interactive)
26585 (call-interactively
26586 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26588 (defun org-cut-special ()
26589 "Cut region in table or cut current subtree.
26590 Calls `org-table-copy' or `org-cut-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-cut-region 'org-cut-subtree)))
26596 (defun org-paste-special (arg)
26597 "Paste rectangular region into table, or past subtree relative to level.
26598 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26599 See the individual commands for more information."
26600 (interactive "P")
26601 (if (org-at-table-p)
26602 (org-table-paste-rectangle)
26603 (org-paste-subtree arg)))
26605 (defun org-ctrl-c-ctrl-c (&optional arg)
26606 "Set tags in headline, or update according to changed information at point.
26608 This command does many different things, depending on context:
26610 - If the cursor is in a headline, prompt for tags and insert them
26611 into the current line, aligned to `org-tags-column'. When called
26612 with prefix arg, realign all tags in the current buffer.
26614 - If the cursor is in one of the special #+KEYWORD lines, this
26615 triggers scanning the buffer for these lines and updating the
26616 information.
26618 - If the cursor is inside a table, realign the table. This command
26619 works even if the automatic table editor has been turned off.
26621 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26622 the entire table.
26624 - If the cursor is a the beginning of a dynamic block, update it.
26626 - If the cursor is inside a table created by the table.el package,
26627 activate that table.
26629 - If the current buffer is a remember buffer, close note and file it.
26630 with a prefix argument, file it without further interaction to the default
26631 location.
26633 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26634 links in this buffer.
26636 - If the cursor is on a numbered item in a plain list, renumber the
26637 ordered list.
26639 - If the cursor is on a checkbox, toggle it."
26640 (interactive "P")
26641 (let ((org-enable-table-editor t))
26642 (cond
26643 ((or org-clock-overlays
26644 org-occur-highlights
26645 org-latex-fragment-image-overlays)
26646 (org-remove-clock-overlays)
26647 (org-remove-occur-highlights)
26648 (org-remove-latex-fragment-image-overlays)
26649 (message "Temporary highlights/overlays removed from current buffer"))
26650 ((and (local-variable-p 'org-finish-function (current-buffer))
26651 (fboundp org-finish-function))
26652 (funcall org-finish-function))
26653 ((org-at-property-p)
26654 (call-interactively 'org-property-action))
26655 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26656 ((org-on-heading-p) (call-interactively 'org-set-tags))
26657 ((org-at-table.el-p)
26658 (require 'table)
26659 (beginning-of-line 1)
26660 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26661 (call-interactively 'table-recognize-table))
26662 ((org-at-table-p)
26663 (org-table-maybe-eval-formula)
26664 (if arg
26665 (call-interactively 'org-table-recalculate)
26666 (org-table-maybe-recalculate-line))
26667 (call-interactively 'org-table-align))
26668 ((org-at-item-checkbox-p)
26669 (call-interactively 'org-toggle-checkbox))
26670 ((org-at-item-p)
26671 (call-interactively 'org-maybe-renumber-ordered-list))
26672 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26673 ;; Dynamic block
26674 (beginning-of-line 1)
26675 (org-update-dblock))
26676 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26677 (cond
26678 ((equal (match-string 1) "TBLFM")
26679 ;; Recalculate the table before this line
26680 (save-excursion
26681 (beginning-of-line 1)
26682 (skip-chars-backward " \r\n\t")
26683 (if (org-at-table-p)
26684 (org-call-with-arg 'org-table-recalculate t))))
26686 (call-interactively 'org-mode-restart))))
26687 (t (error "C-c C-c can do nothing useful at this location.")))))
26689 (defun org-mode-restart ()
26690 "Restart Org-mode, to scan again for special lines.
26691 Also updates the keyword regular expressions."
26692 (interactive)
26693 (let ((org-inhibit-startup t)) (org-mode))
26694 (message "Org-mode restarted to refresh keyword and special line setup"))
26696 (defun org-kill-note-or-show-branches ()
26697 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26698 (interactive)
26699 (if (not org-finish-function)
26700 (call-interactively 'show-branches)
26701 (let ((org-note-abort t))
26702 (funcall org-finish-function))))
26704 (defun org-return (&optional indent)
26705 "Goto next table row or insert a newline.
26706 Calls `org-table-next-row' or `newline', depending on context.
26707 See the individual commands for more information."
26708 (interactive)
26709 (cond
26710 ((bobp) (if indent (newline-and-indent) (newline)))
26711 ((org-at-table-p)
26712 (org-table-justify-field-maybe)
26713 (call-interactively 'org-table-next-row))
26714 (t (if indent (newline-and-indent) (newline)))))
26716 (defun org-return-indent ()
26717 (interactive)
26718 "Goto next table row or insert a newline and indent.
26719 Calls `org-table-next-row' or `newline-and-indent', depending on
26720 context. See the individual commands for more information."
26721 (org-return t))
26723 (defun org-ctrl-c-minus ()
26724 "Insert separator line in table or modify bullet type in list.
26725 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26726 depending on context."
26727 (interactive)
26728 (cond
26729 ((org-at-table-p)
26730 (call-interactively 'org-table-insert-hline))
26731 ((org-on-heading-p)
26732 ;; Convert to item
26733 (save-excursion
26734 (beginning-of-line 1)
26735 (if (looking-at "\\*+ ")
26736 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26737 ((org-in-item-p)
26738 (call-interactively 'org-cycle-list-bullet))
26739 (t (error "`C-c -' does have no function here."))))
26741 (defun org-meta-return (&optional arg)
26742 "Insert a new heading or wrap a region in a table.
26743 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
26744 See the individual commands for more information."
26745 (interactive "P")
26746 (cond
26747 ((org-at-table-p)
26748 (call-interactively 'org-table-wrap-region))
26749 (t (call-interactively 'org-insert-heading))))
26751 ;;; Menu entries
26753 ;; Define the Org-mode menus
26754 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
26755 '("Tbl"
26756 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
26757 ["Next Field" org-cycle (org-at-table-p)]
26758 ["Previous Field" org-shifttab (org-at-table-p)]
26759 ["Next Row" org-return (org-at-table-p)]
26760 "--"
26761 ["Blank Field" org-table-blank-field (org-at-table-p)]
26762 ["Edit Field" org-table-edit-field (org-at-table-p)]
26763 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
26764 "--"
26765 ("Column"
26766 ["Move Column Left" org-metaleft (org-at-table-p)]
26767 ["Move Column Right" org-metaright (org-at-table-p)]
26768 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
26769 ["Insert Column" org-shiftmetaright (org-at-table-p)])
26770 ("Row"
26771 ["Move Row Up" org-metaup (org-at-table-p)]
26772 ["Move Row Down" org-metadown (org-at-table-p)]
26773 ["Delete Row" org-shiftmetaup (org-at-table-p)]
26774 ["Insert Row" org-shiftmetadown (org-at-table-p)]
26775 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
26776 "--"
26777 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
26778 ("Rectangle"
26779 ["Copy Rectangle" org-copy-special (org-at-table-p)]
26780 ["Cut Rectangle" org-cut-special (org-at-table-p)]
26781 ["Paste Rectangle" org-paste-special (org-at-table-p)]
26782 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
26783 "--"
26784 ("Calculate"
26785 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
26786 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
26787 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
26788 "--"
26789 ["Recalculate line" org-table-recalculate (org-at-table-p)]
26790 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
26791 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
26792 "--"
26793 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
26794 "--"
26795 ["Sum Column/Rectangle" org-table-sum
26796 (or (org-at-table-p) (org-region-active-p))]
26797 ["Which Column?" org-table-current-column (org-at-table-p)])
26798 ["Debug Formulas"
26799 org-table-toggle-formula-debugger
26800 :style toggle :selected org-table-formula-debug]
26801 ["Show Col/Row Numbers"
26802 org-table-toggle-coordinate-overlays
26803 :style toggle :selected org-table-overlay-coordinates]
26804 "--"
26805 ["Create" org-table-create (and (not (org-at-table-p))
26806 org-enable-table-editor)]
26807 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
26808 ["Import from File" org-table-import (not (org-at-table-p))]
26809 ["Export to File" org-table-export (org-at-table-p)]
26810 "--"
26811 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
26813 (easy-menu-define org-org-menu org-mode-map "Org menu"
26814 '("Org"
26815 ("Show/Hide"
26816 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
26817 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
26818 ["Sparse Tree" org-occur t]
26819 ["Reveal Context" org-reveal t]
26820 ["Show All" show-all t]
26821 "--"
26822 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
26823 "--"
26824 ["New Heading" org-insert-heading t]
26825 ("Navigate Headings"
26826 ["Up" outline-up-heading t]
26827 ["Next" outline-next-visible-heading t]
26828 ["Previous" outline-previous-visible-heading t]
26829 ["Next Same Level" outline-forward-same-level t]
26830 ["Previous Same Level" outline-backward-same-level t]
26831 "--"
26832 ["Jump" org-goto t])
26833 ("Edit Structure"
26834 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
26835 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
26836 "--"
26837 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
26838 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
26839 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
26840 "--"
26841 ["Promote Heading" org-metaleft (not (org-at-table-p))]
26842 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
26843 ["Demote Heading" org-metaright (not (org-at-table-p))]
26844 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
26845 "--"
26846 ["Sort Region/Children" org-sort (not (org-at-table-p))]
26847 "--"
26848 ["Convert to odd levels" org-convert-to-odd-levels t]
26849 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
26850 ("Editing"
26851 ["Emphasis..." org-emphasize t])
26852 ("Archive"
26853 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
26854 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
26855 ; :active t :keys "C-u C-c C-x C-a"]
26856 ["Sparse trees open ARCHIVE trees"
26857 (setq org-sparse-tree-open-archived-trees
26858 (not org-sparse-tree-open-archived-trees))
26859 :style toggle :selected org-sparse-tree-open-archived-trees]
26860 ["Cycling opens ARCHIVE trees"
26861 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
26862 :style toggle :selected org-cycle-open-archived-trees]
26863 ["Agenda includes ARCHIVE trees"
26864 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
26865 :style toggle :selected (not org-agenda-skip-archived-trees)]
26866 "--"
26867 ["Move Subtree to Archive" org-advertized-archive-subtree t]
26868 ; ["Check and Move Children" (org-archive-subtree '(4))
26869 ; :active t :keys "C-u C-c C-x C-s"]
26871 "--"
26872 ("TODO Lists"
26873 ["TODO/DONE/-" org-todo t]
26874 ("Select keyword"
26875 ["Next keyword" org-shiftright (org-on-heading-p)]
26876 ["Previous keyword" org-shiftleft (org-on-heading-p)]
26877 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
26878 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
26879 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
26880 ["Show TODO Tree" org-show-todo-tree t]
26881 ["Global TODO list" org-todo-list t]
26882 "--"
26883 ["Set Priority" org-priority t]
26884 ["Priority Up" org-shiftup t]
26885 ["Priority Down" org-shiftdown t])
26886 ("TAGS and Properties"
26887 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
26888 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
26889 "--"
26890 ["Set property" 'org-set-property t]
26891 ["Column view of properties" org-columns t]
26892 ["Insert Column View DBlock" org-insert-columns-dblock t])
26893 ("Dates and Scheduling"
26894 ["Timestamp" org-time-stamp t]
26895 ["Timestamp (inactive)" org-time-stamp-inactive t]
26896 ("Change Date"
26897 ["1 Day Later" org-shiftright t]
26898 ["1 Day Earlier" org-shiftleft t]
26899 ["1 ... Later" org-shiftup t]
26900 ["1 ... Earlier" org-shiftdown t])
26901 ["Compute Time Range" org-evaluate-time-range t]
26902 ["Schedule Item" org-schedule t]
26903 ["Deadline" org-deadline t]
26904 "--"
26905 ["Custom time format" org-toggle-time-stamp-overlays
26906 :style radio :selected org-display-custom-times]
26907 "--"
26908 ["Goto Calendar" org-goto-calendar t]
26909 ["Date from Calendar" org-date-from-calendar t])
26910 ("Logging work"
26911 ["Clock in" org-clock-in t]
26912 ["Clock out" org-clock-out t]
26913 ["Clock cancel" org-clock-cancel t]
26914 ["Goto running clock" org-clock-goto t]
26915 ["Display times" org-clock-display t]
26916 ["Create clock table" org-clock-report t]
26917 "--"
26918 ["Record DONE time"
26919 (progn (setq org-log-done (not org-log-done))
26920 (message "Switching to %s will %s record a timestamp"
26921 (car org-done-keywords)
26922 (if org-log-done "automatically" "not")))
26923 :style toggle :selected org-log-done])
26924 "--"
26925 ["Agenda Command..." org-agenda t]
26926 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
26927 ("File List for Agenda")
26928 ("Special views current file"
26929 ["TODO Tree" org-show-todo-tree t]
26930 ["Check Deadlines" org-check-deadlines t]
26931 ["Timeline" org-timeline t]
26932 ["Tags Tree" org-tags-sparse-tree t])
26933 "--"
26934 ("Hyperlinks"
26935 ["Store Link (Global)" org-store-link t]
26936 ["Insert Link" org-insert-link t]
26937 ["Follow Link" org-open-at-point t]
26938 "--"
26939 ["Next link" org-next-link t]
26940 ["Previous link" org-previous-link t]
26941 "--"
26942 ["Descriptive Links"
26943 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
26944 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
26945 ["Literal Links"
26946 (progn
26947 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
26948 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
26949 "--"
26950 ["Export/Publish..." org-export t]
26951 ("LaTeX"
26952 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
26953 :selected org-cdlatex-mode]
26954 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
26955 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
26956 ["Modify math symbol" org-cdlatex-math-modify
26957 (org-inside-LaTeX-fragment-p)]
26958 ["Export LaTeX fragments as images"
26959 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
26960 :style toggle :selected org-export-with-LaTeX-fragments])
26961 "--"
26962 ("Documentation"
26963 ["Show Version" org-version t]
26964 ["Info Documentation" org-info t])
26965 ("Customize"
26966 ["Browse Org Group" org-customize t]
26967 "--"
26968 ["Expand This Menu" org-create-customize-menu
26969 (fboundp 'customize-menu-create)])
26970 "--"
26971 ["Refresh setup" org-mode-restart t]
26974 (defun org-info (&optional node)
26975 "Read documentation for Org-mode in the info system.
26976 With optional NODE, go directly to that node."
26977 (interactive)
26978 (require 'info)
26979 (Info-goto-node (format "(org)%s" (or node ""))))
26981 (defun org-install-agenda-files-menu ()
26982 (let ((bl (buffer-list)))
26983 (save-excursion
26984 (while bl
26985 (set-buffer (pop bl))
26986 (if (org-mode-p) (setq bl nil)))
26987 (when (org-mode-p)
26988 (easy-menu-change
26989 '("Org") "File List for Agenda"
26990 (append
26991 (list
26992 ["Edit File List" (org-edit-agenda-file-list) t]
26993 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
26994 ["Remove Current File from List" org-remove-file t]
26995 ["Cycle through agenda files" org-cycle-agenda-files t]
26996 ["Occur in all agenda files" org-occur-in-agenda-files t]
26997 "--")
26998 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27000 ;;;; Documentation
27002 (defun org-customize ()
27003 "Call the customize function with org as argument."
27004 (interactive)
27005 (customize-browse 'org))
27007 (defun org-create-customize-menu ()
27008 "Create a full customization menu for Org-mode, insert it into the menu."
27009 (interactive)
27010 (if (fboundp 'customize-menu-create)
27011 (progn
27012 (easy-menu-change
27013 '("Org") "Customize"
27014 `(["Browse Org group" org-customize t]
27015 "--"
27016 ,(customize-menu-create 'org)
27017 ["Set" Custom-set t]
27018 ["Save" Custom-save t]
27019 ["Reset to Current" Custom-reset-current t]
27020 ["Reset to Saved" Custom-reset-saved t]
27021 ["Reset to Standard Settings" Custom-reset-standard t]))
27022 (message "\"Org\"-menu now contains full customization menu"))
27023 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27025 ;;;; Miscellaneous stuff
27028 ;;; Generally useful functions
27030 (defun org-context ()
27031 "Return a list of contexts of the current cursor position.
27032 If several contexts apply, all are returned.
27033 Each context entry is a list with a symbol naming the context, and
27034 two positions indicating start and end of the context. Possible
27035 contexts are:
27037 :headline anywhere in a headline
27038 :headline-stars on the leading stars in a headline
27039 :todo-keyword on a TODO keyword (including DONE) in a headline
27040 :tags on the TAGS in a headline
27041 :priority on the priority cookie in a headline
27042 :item on the first line of a plain list item
27043 :item-bullet on the bullet/number of a plain list item
27044 :checkbox on the checkbox in a plain list item
27045 :table in an org-mode table
27046 :table-special on a special filed in a table
27047 :table-table in a table.el table
27048 :link on a hyperlink
27049 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27050 :target on a <<target>>
27051 :radio-target on a <<<radio-target>>>
27052 :latex-fragment on a LaTeX fragment
27053 :latex-preview on a LaTeX fragment with overlayed preview image
27055 This function expects the position to be visible because it uses font-lock
27056 faces as a help to recognize the following contexts: :table-special, :link,
27057 and :keyword."
27058 (let* ((f (get-text-property (point) 'face))
27059 (faces (if (listp f) f (list f)))
27060 (p (point)) clist o)
27061 ;; First the large context
27062 (cond
27063 ((org-on-heading-p t)
27064 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27065 (when (progn
27066 (beginning-of-line 1)
27067 (looking-at org-todo-line-tags-regexp))
27068 (push (org-point-in-group p 1 :headline-stars) clist)
27069 (push (org-point-in-group p 2 :todo-keyword) clist)
27070 (push (org-point-in-group p 4 :tags) clist))
27071 (goto-char p)
27072 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27073 (if (looking-at "\\[#[A-Z0-9]\\]")
27074 (push (org-point-in-group p 0 :priority) clist)))
27076 ((org-at-item-p)
27077 (push (org-point-in-group p 2 :item-bullet) clist)
27078 (push (list :item (point-at-bol)
27079 (save-excursion (org-end-of-item) (point)))
27080 clist)
27081 (and (org-at-item-checkbox-p)
27082 (push (org-point-in-group p 0 :checkbox) clist)))
27084 ((org-at-table-p)
27085 (push (list :table (org-table-begin) (org-table-end)) clist)
27086 (if (memq 'org-formula faces)
27087 (push (list :table-special
27088 (previous-single-property-change p 'face)
27089 (next-single-property-change p 'face)) clist)))
27090 ((org-at-table-p 'any)
27091 (push (list :table-table) clist)))
27092 (goto-char p)
27094 ;; Now the small context
27095 (cond
27096 ((org-at-timestamp-p)
27097 (push (org-point-in-group p 0 :timestamp) clist))
27098 ((memq 'org-link faces)
27099 (push (list :link
27100 (previous-single-property-change p 'face)
27101 (next-single-property-change p 'face)) clist))
27102 ((memq 'org-special-keyword faces)
27103 (push (list :keyword
27104 (previous-single-property-change p 'face)
27105 (next-single-property-change p 'face)) clist))
27106 ((org-on-target-p)
27107 (push (org-point-in-group p 0 :target) clist)
27108 (goto-char (1- (match-beginning 0)))
27109 (if (looking-at org-radio-target-regexp)
27110 (push (org-point-in-group p 0 :radio-target) clist))
27111 (goto-char p))
27112 ((setq o (car (delq nil
27113 (mapcar
27114 (lambda (x)
27115 (if (memq x org-latex-fragment-image-overlays) x))
27116 (org-overlays-at (point))))))
27117 (push (list :latex-fragment
27118 (org-overlay-start o) (org-overlay-end o)) clist)
27119 (push (list :latex-preview
27120 (org-overlay-start o) (org-overlay-end o)) clist))
27121 ((org-inside-LaTeX-fragment-p)
27122 ;; FIXME: positions wrong.
27123 (push (list :latex-fragment (point) (point)) clist)))
27125 (setq clist (nreverse (delq nil clist)))
27126 clist))
27128 ;; FIXME: Compare with at-regexp-p Do we need both?
27129 (defun org-in-regexp (re &optional nlines visually)
27130 "Check if point is inside a match of regexp.
27131 Normally only the current line is checked, but you can include NLINES extra
27132 lines both before and after point into the search.
27133 If VISUALLY is set, require that the cursor is not after the match but
27134 really on, so that the block visually is on the match."
27135 (catch 'exit
27136 (let ((pos (point))
27137 (eol (point-at-eol (+ 1 (or nlines 0))))
27138 (inc (if visually 1 0)))
27139 (save-excursion
27140 (beginning-of-line (- 1 (or nlines 0)))
27141 (while (re-search-forward re eol t)
27142 (if (and (<= (match-beginning 0) pos)
27143 (>= (+ inc (match-end 0)) pos))
27144 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27146 (defun org-at-regexp-p (regexp)
27147 "Is point inside a match of REGEXP in the current line?"
27148 (catch 'exit
27149 (save-excursion
27150 (let ((pos (point)) (end (point-at-eol)))
27151 (beginning-of-line 1)
27152 (while (re-search-forward regexp end t)
27153 (if (and (<= (match-beginning 0) pos)
27154 (>= (match-end 0) pos))
27155 (throw 'exit t)))
27156 nil))))
27158 (defun org-occur-in-agenda-files (regexp &optional nlines)
27159 "Call `multi-occur' with buffers for all agenda files."
27160 (interactive "sOrg-files matching: \np")
27161 (let* ((files (org-agenda-files))
27162 (tnames (mapcar 'file-truename files))
27163 (extra org-agenda-multi-occur-extra-files)
27165 (while (setq f (pop extra))
27166 (unless (member (file-truename f) tnames)
27167 (add-to-list 'files f 'append)
27168 (add-to-list 'tnames (file-truename f) 'append)))
27169 (multi-occur
27170 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27171 regexp)))
27173 (defun org-uniquify (list)
27174 "Remove duplicate elements from LIST."
27175 (let (res)
27176 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27177 res))
27179 (defun org-delete-all (elts list)
27180 "Remove all elements in ELTS from LIST."
27181 (while elts
27182 (setq list (delete (pop elts) list)))
27183 list)
27185 (defun org-back-over-empty-lines ()
27186 "Move backwards over witespace, to the beginning of the first empty line.
27187 Returns the number o empty lines passed."
27188 (let ((pos (point)))
27189 (skip-chars-backward " \t\n\r")
27190 (beginning-of-line 2)
27191 (goto-char (min (point) pos))
27192 (count-lines (point) pos)))
27194 (defun org-skip-whitespace ()
27195 (skip-chars-forward " \t\n\r"))
27197 (defun org-point-in-group (point group &optional context)
27198 "Check if POINT is in match-group GROUP.
27199 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27200 match. If the match group does ot exist or point is not inside it,
27201 return nil."
27202 (and (match-beginning group)
27203 (>= point (match-beginning group))
27204 (<= point (match-end group))
27205 (if context
27206 (list context (match-beginning group) (match-end group))
27207 t)))
27209 (defun org-switch-to-buffer-other-window (&rest args)
27210 "Switch to buffer in a second window on the current frame.
27211 In particular, do not allow pop-up frames."
27212 (let (pop-up-frames special-display-buffer-names special-display-regexps
27213 special-display-function)
27214 (apply 'switch-to-buffer-other-window args)))
27216 (defun org-combine-plists (&rest plists)
27217 "Create a single property list from all plists in PLISTS.
27218 The process starts by copying the first list, and then setting properties
27219 from the other lists. Settings in the last list are the most significant
27220 ones and overrule settings in the other lists."
27221 (let ((rtn (copy-sequence (pop plists)))
27222 p v ls)
27223 (while plists
27224 (setq ls (pop plists))
27225 (while ls
27226 (setq p (pop ls) v (pop ls))
27227 (setq rtn (plist-put rtn p v))))
27228 rtn))
27230 (defun org-move-line-down (arg)
27231 "Move the current line down. With prefix argument, move it past ARG lines."
27232 (interactive "p")
27233 (let ((col (current-column))
27234 beg end pos)
27235 (beginning-of-line 1) (setq beg (point))
27236 (beginning-of-line 2) (setq end (point))
27237 (beginning-of-line (+ 1 arg))
27238 (setq pos (move-marker (make-marker) (point)))
27239 (insert (delete-and-extract-region beg end))
27240 (goto-char pos)
27241 (move-to-column col)))
27243 (defun org-move-line-up (arg)
27244 "Move the current line up. With prefix argument, move it past ARG lines."
27245 (interactive "p")
27246 (let ((col (current-column))
27247 beg end pos)
27248 (beginning-of-line 1) (setq beg (point))
27249 (beginning-of-line 2) (setq end (point))
27250 (beginning-of-line (- arg))
27251 (setq pos (move-marker (make-marker) (point)))
27252 (insert (delete-and-extract-region beg end))
27253 (goto-char pos)
27254 (move-to-column col)))
27256 (defun org-replace-escapes (string table)
27257 "Replace %-escapes in STRING with values in TABLE.
27258 TABLE is an association list with keys like \"%a\" and string values.
27259 The sequences in STRING may contain normal field width and padding information,
27260 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27261 so values can contain further %-escapes if they are define later in TABLE."
27262 (let ((case-fold-search nil)
27263 e re rpl)
27264 (while (setq e (pop table))
27265 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27266 (while (string-match re string)
27267 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27268 (cdr e)))
27269 (setq string (replace-match rpl t t string))))
27270 string))
27273 (defun org-sublist (list start end)
27274 "Return a section of LIST, from START to END.
27275 Counting starts at 1."
27276 (let (rtn (c start))
27277 (setq list (nthcdr (1- start) list))
27278 (while (and list (<= c end))
27279 (push (pop list) rtn)
27280 (setq c (1+ c)))
27281 (nreverse rtn)))
27283 (defun org-find-base-buffer-visiting (file)
27284 "Like `find-buffer-visiting' but alway return the base buffer and
27285 not an indirect buffer"
27286 (let ((buf (find-buffer-visiting file)))
27287 (if buf
27288 (or (buffer-base-buffer buf) buf)
27289 nil)))
27291 (defun org-image-file-name-regexp ()
27292 "Return regexp matching the file names of images."
27293 (if (fboundp 'image-file-name-regexp)
27294 (image-file-name-regexp)
27295 (let ((image-file-name-extensions
27296 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27297 "xbm" "xpm" "pbm" "pgm" "ppm")))
27298 (concat "\\."
27299 (regexp-opt (nconc (mapcar 'upcase
27300 image-file-name-extensions)
27301 image-file-name-extensions)
27303 "\\'"))))
27305 (defun org-file-image-p (file)
27306 "Return non-nil if FILE is an image."
27307 (save-match-data
27308 (string-match (org-image-file-name-regexp) file)))
27310 ;;; Paragraph filling stuff.
27311 ;; We want this to be just right, so use the full arsenal.
27313 (defun org-indent-line-function ()
27314 "Indent line like previous, but further if previous was headline or item."
27315 (interactive)
27316 (let* ((pos (point))
27317 (itemp (org-at-item-p))
27318 column bpos bcol tpos tcol bullet btype bullet-type)
27319 ;; Find the previous relevant line
27320 (beginning-of-line 1)
27321 (cond
27322 ((looking-at "#") (setq column 0))
27323 ((looking-at "\\*+ ") (setq column 0))
27325 (beginning-of-line 0)
27326 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27327 (beginning-of-line 0))
27328 (cond
27329 ((looking-at "\\*+[ \t]+")
27330 (goto-char (match-end 0))
27331 (setq column (current-column)))
27332 ((org-in-item-p)
27333 (org-beginning-of-item)
27334 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27335 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27336 (setq bpos (match-beginning 1) tpos (match-end 0)
27337 bcol (progn (goto-char bpos) (current-column))
27338 tcol (progn (goto-char tpos) (current-column))
27339 bullet (match-string 1)
27340 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27341 (if (not itemp)
27342 (setq column tcol)
27343 (goto-char pos)
27344 (beginning-of-line 1)
27345 (if (looking-at "\\S-")
27346 (progn
27347 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27348 (setq bullet (match-string 1)
27349 btype (if (string-match "[0-9]" bullet) "n" bullet))
27350 (setq column (if (equal btype bullet-type) bcol tcol)))
27351 (setq column (org-get-indentation)))))
27352 (t (setq column (org-get-indentation))))))
27353 (goto-char pos)
27354 (if (<= (current-column) (current-indentation))
27355 (indent-line-to column)
27356 (save-excursion (indent-line-to column)))
27357 (setq column (current-column))
27358 (beginning-of-line 1)
27359 (if (looking-at
27360 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27361 (replace-match (concat "\\1" (format org-property-format
27362 (match-string 2) (match-string 3)))
27363 t nil))
27364 (move-to-column column)))
27366 (defun org-set-autofill-regexps ()
27367 (interactive)
27368 ;; In the paragraph separator we include headlines, because filling
27369 ;; text in a line directly attached to a headline would otherwise
27370 ;; fill the headline as well.
27371 (org-set-local 'comment-start-skip "^#+[ \t]*")
27372 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27373 ;; The paragraph starter includes hand-formatted lists.
27374 (org-set-local 'paragraph-start
27375 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27376 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27377 ;; But only if the user has not turned off tables or fixed-width regions
27378 (org-set-local
27379 'auto-fill-inhibit-regexp
27380 (concat "\\*+ \\|#\\+"
27381 "\\|[ \t]*" org-keyword-time-regexp
27382 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27383 (concat
27384 "\\|[ \t]*["
27385 (if org-enable-table-editor "|" "")
27386 (if org-enable-fixed-width-editor ":" "")
27387 "]"))))
27388 ;; We use our own fill-paragraph function, to make sure that tables
27389 ;; and fixed-width regions are not wrapped. That function will pass
27390 ;; through to `fill-paragraph' when appropriate.
27391 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27392 ; Adaptive filling: To get full control, first make sure that
27393 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27394 (org-set-local 'adaptive-fill-regexp "\000")
27395 (org-set-local 'adaptive-fill-function
27396 'org-adaptive-fill-function))
27398 (defun org-fill-paragraph (&optional justify)
27399 "Re-align a table, pass through to fill-paragraph if no table."
27400 (let ((table-p (org-at-table-p))
27401 (table.el-p (org-at-table.el-p)))
27402 (cond ((and (equal (char-after (point-at-bol)) ?*)
27403 (save-excursion (goto-char (point-at-bol))
27404 (looking-at outline-regexp)))
27405 t) ; skip headlines
27406 (table.el-p t) ; skip table.el tables
27407 (table-p (org-table-align) t) ; align org-mode tables
27408 (t nil)))) ; call paragraph-fill
27410 ;; For reference, this is the default value of adaptive-fill-regexp
27411 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27413 (defun org-adaptive-fill-function ()
27414 "Return a fill prefix for org-mode files.
27415 In particular, this makes sure hanging paragraphs for hand-formatted lists
27416 work correctly."
27417 (cond ((looking-at "#[ \t]+")
27418 (match-string 0))
27419 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27420 (save-excursion
27421 (goto-char (match-end 0))
27422 (make-string (current-column) ?\ )))
27423 (t nil)))
27425 ;;;; Functions extending outline functionality
27427 (defun org-beginning-of-line (&optional arg)
27428 "Go to the beginning of the current line. If that is invisible, continue
27429 to a visible line beginning. This makes the function of C-a more intuitive.
27430 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27431 first attempt, and only move to after the tags when the cursor is already
27432 beyond the end of the headline."
27433 (interactive "P")
27434 (let ((pos (point)))
27435 (beginning-of-line 1)
27436 (if (bobp)
27438 (backward-char 1)
27439 (if (org-invisible-p)
27440 (while (and (not (bobp)) (org-invisible-p))
27441 (backward-char 1)
27442 (beginning-of-line 1))
27443 (forward-char 1)))
27444 (when org-special-ctrl-a/e
27445 (cond
27446 ((and (looking-at org-todo-line-regexp)
27447 (= (char-after (match-end 1)) ?\ ))
27448 (goto-char
27449 (if (eq org-special-ctrl-a/e t)
27450 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27451 ((= pos (point)) (match-beginning 3))
27452 (t (point)))
27453 (cond ((> pos (point)) (point))
27454 ((not (eq last-command this-command)) (point))
27455 (t (match-beginning 3))))))
27456 ((org-at-item-p)
27457 (goto-char
27458 (if (eq org-special-ctrl-a/e t)
27459 (cond ((> pos (match-end 4)) (match-end 4))
27460 ((= pos (point)) (match-end 4))
27461 (t (point)))
27462 (cond ((> pos (point)) (point))
27463 ((not (eq last-command this-command)) (point))
27464 (t (match-end 4))))))))))
27466 (defun org-end-of-line (&optional arg)
27467 "Go to the end of the line.
27468 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27469 first attempt, and only move to after the tags when the cursor is already
27470 beyond the end of the headline."
27471 (interactive "P")
27472 (if (or (not org-special-ctrl-a/e)
27473 (not (org-on-heading-p)))
27474 (end-of-line arg)
27475 (let ((pos (point)))
27476 (beginning-of-line 1)
27477 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27478 (if (eq org-special-ctrl-a/e t)
27479 (if (or (< pos (match-beginning 1))
27480 (= pos (match-end 0)))
27481 (goto-char (match-beginning 1))
27482 (goto-char (match-end 0)))
27483 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27484 (goto-char (match-end 0))
27485 (goto-char (match-beginning 1))))
27486 (end-of-line arg)))))
27488 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27489 (define-key org-mode-map "\C-e" 'org-end-of-line)
27491 (defun org-invisible-p ()
27492 "Check if point is at a character currently not visible."
27493 ;; Early versions of noutline don't have `outline-invisible-p'.
27494 (if (fboundp 'outline-invisible-p)
27495 (outline-invisible-p)
27496 (get-char-property (point) 'invisible)))
27498 (defun org-invisible-p2 ()
27499 "Check if point is at a character currently not visible."
27500 (save-excursion
27501 (if (and (eolp) (not (bobp))) (backward-char 1))
27502 ;; Early versions of noutline don't have `outline-invisible-p'.
27503 (if (fboundp 'outline-invisible-p)
27504 (outline-invisible-p)
27505 (get-char-property (point) 'invisible))))
27507 (defalias 'org-back-to-heading 'outline-back-to-heading)
27508 (defalias 'org-on-heading-p 'outline-on-heading-p)
27509 (defalias 'org-at-heading-p 'outline-on-heading-p)
27510 (defun org-at-heading-or-item-p ()
27511 (or (org-on-heading-p) (org-at-item-p)))
27513 (defun org-on-target-p ()
27514 (or (org-in-regexp org-radio-target-regexp)
27515 (org-in-regexp org-target-regexp)))
27517 (defun org-up-heading-all (arg)
27518 "Move to the heading line of which the present line is a subheading.
27519 This function considers both visible and invisible heading lines.
27520 With argument, move up ARG levels."
27521 (if (fboundp 'outline-up-heading-all)
27522 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27523 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27525 (defun org-up-heading-safe ()
27526 "Move to the heading line of which the present line is a subheading.
27527 This version will not throw an error. It will return the level of the
27528 headline found, or nil if no higher level is found."
27529 (let ((pos (point)) start-level level
27530 (re (concat "^" outline-regexp)))
27531 (catch 'exit
27532 (outline-back-to-heading t)
27533 (setq start-level (funcall outline-level))
27534 (if (equal start-level 1) (throw 'exit nil))
27535 (while (re-search-backward re nil t)
27536 (setq level (funcall outline-level))
27537 (if (< level start-level) (throw 'exit level)))
27538 nil)))
27540 (defun org-first-sibling-p ()
27541 "Is this heading the first child of its parents?"
27542 (interactive)
27543 (let ((re (concat "^" outline-regexp))
27544 level l)
27545 (unless (org-at-heading-p t)
27546 (error "Not at a heading"))
27547 (setq level (funcall outline-level))
27548 (save-excursion
27549 (if (not (re-search-backward re nil t))
27551 (setq l (funcall outline-level))
27552 (< l level)))))
27554 (defun org-goto-sibling (&optional previous)
27555 "Goto the next sibling, even if it is invisible.
27556 When PREVIOUS is set, go to the previous sibling instead. Returns t
27557 when a sibling was found. When none is found, return nil and don't
27558 move point."
27559 (let ((fun (if previous 're-search-backward 're-search-forward))
27560 (pos (point))
27561 (re (concat "^" outline-regexp))
27562 level l)
27563 (when (condition-case nil (org-back-to-heading t) (error nil))
27564 (setq level (funcall outline-level))
27565 (catch 'exit
27566 (or previous (forward-char 1))
27567 (while (funcall fun re nil t)
27568 (setq l (funcall outline-level))
27569 (when (< l level) (goto-char pos) (throw 'exit nil))
27570 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27571 (goto-char pos)
27572 nil))))
27574 (defun org-show-siblings ()
27575 "Show all siblings of the current headline."
27576 (save-excursion
27577 (while (org-goto-sibling) (org-flag-heading nil)))
27578 (save-excursion
27579 (while (org-goto-sibling 'previous)
27580 (org-flag-heading nil))))
27582 (defun org-show-hidden-entry ()
27583 "Show an entry where even the heading is hidden."
27584 (save-excursion
27585 (org-show-entry)))
27587 (defun org-flag-heading (flag &optional entry)
27588 "Flag the current heading. FLAG non-nil means make invisible.
27589 When ENTRY is non-nil, show the entire entry."
27590 (save-excursion
27591 (org-back-to-heading t)
27592 ;; Check if we should show the entire entry
27593 (if entry
27594 (progn
27595 (org-show-entry)
27596 (save-excursion
27597 (and (outline-next-heading)
27598 (org-flag-heading nil))))
27599 (outline-flag-region (max (point-min) (1- (point)))
27600 (save-excursion (outline-end-of-heading) (point))
27601 flag))))
27603 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27604 ;; This is an exact copy of the original function, but it uses
27605 ;; `org-back-to-heading', to make it work also in invisible
27606 ;; trees. And is uses an invisible-OK argument.
27607 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27608 (org-back-to-heading invisible-OK)
27609 (let ((first t)
27610 (level (funcall outline-level)))
27611 (while (and (not (eobp))
27612 (or first (> (funcall outline-level) level)))
27613 (setq first nil)
27614 (outline-next-heading))
27615 (unless to-heading
27616 (if (memq (preceding-char) '(?\n ?\^M))
27617 (progn
27618 ;; Go to end of line before heading
27619 (forward-char -1)
27620 (if (memq (preceding-char) '(?\n ?\^M))
27621 ;; leave blank line before heading
27622 (forward-char -1))))))
27623 (point))
27625 (defun org-show-subtree ()
27626 "Show everything after this heading at deeper levels."
27627 (outline-flag-region
27628 (point)
27629 (save-excursion
27630 (outline-end-of-subtree) (outline-next-heading) (point))
27631 nil))
27633 (defun org-show-entry ()
27634 "Show the body directly following this heading.
27635 Show the heading too, if it is currently invisible."
27636 (interactive)
27637 (save-excursion
27638 (condition-case nil
27639 (progn
27640 (org-back-to-heading t)
27641 (outline-flag-region
27642 (max (point-min) (1- (point)))
27643 (save-excursion
27644 (re-search-forward
27645 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27646 (or (match-beginning 1) (point-max)))
27647 nil))
27648 (error nil))))
27650 (defun org-make-options-regexp (kwds)
27651 "Make a regular expression for keyword lines."
27652 (concat
27654 "#?[ \t]*\\+\\("
27655 (mapconcat 'regexp-quote kwds "\\|")
27656 "\\):[ \t]*"
27657 "\\(.+\\)"))
27659 ;; Make isearch reveal the necessary context
27660 (defun org-isearch-end ()
27661 "Reveal context after isearch exits."
27662 (when isearch-success ; only if search was successful
27663 (if (featurep 'xemacs)
27664 ;; Under XEmacs, the hook is run in the correct place,
27665 ;; we directly show the context.
27666 (org-show-context 'isearch)
27667 ;; In Emacs the hook runs *before* restoring the overlays.
27668 ;; So we have to use a one-time post-command-hook to do this.
27669 ;; (Emacs 22 has a special variable, see function `org-mode')
27670 (unless (and (boundp 'isearch-mode-end-hook-quit)
27671 isearch-mode-end-hook-quit)
27672 ;; Only when the isearch was not quitted.
27673 (org-add-hook 'post-command-hook 'org-isearch-post-command
27674 'append 'local)))))
27676 (defun org-isearch-post-command ()
27677 "Remove self from hook, and show context."
27678 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27679 (org-show-context 'isearch))
27682 ;;;; Integration with and fixes for other packages
27684 ;;; Imenu support
27686 (defvar org-imenu-markers nil
27687 "All markers currently used by Imenu.")
27688 (make-variable-buffer-local 'org-imenu-markers)
27690 (defun org-imenu-new-marker (&optional pos)
27691 "Return a new marker for use by Imenu, and remember the marker."
27692 (let ((m (make-marker)))
27693 (move-marker m (or pos (point)))
27694 (push m org-imenu-markers)
27697 (defun org-imenu-get-tree ()
27698 "Produce the index for Imenu."
27699 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
27700 (setq org-imenu-markers nil)
27701 (let* ((n org-imenu-depth)
27702 (re (concat "^" outline-regexp))
27703 (subs (make-vector (1+ n) nil))
27704 (last-level 0)
27705 m tree level head)
27706 (save-excursion
27707 (save-restriction
27708 (widen)
27709 (goto-char (point-max))
27710 (while (re-search-backward re nil t)
27711 (setq level (org-reduced-level (funcall outline-level)))
27712 (when (<= level n)
27713 (looking-at org-complex-heading-regexp)
27714 (setq head (org-match-string-no-properties 4)
27715 m (org-imenu-new-marker))
27716 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
27717 (if (>= level last-level)
27718 (push (cons head m) (aref subs level))
27719 (push (cons head (aref subs (1+ level))) (aref subs level))
27720 (loop for i from (1+ level) to n do (aset subs i nil)))
27721 (setq last-level level)))))
27722 (aref subs 1)))
27724 (eval-after-load "imenu"
27725 '(progn
27726 (add-hook 'imenu-after-jump-hook
27727 (lambda () (org-show-context 'org-goto)))))
27729 ;; Speedbar support
27731 (defun org-speedbar-set-agenda-restriction ()
27732 "Restrict future agenda commands to the location at point in speedbar.
27733 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
27734 (interactive)
27735 (let (p m tp np dir txt w)
27736 (cond
27737 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27738 'org-imenu t))
27739 (setq m (get-text-property p 'org-imenu-marker))
27740 (save-excursion
27741 (save-restriction
27742 (set-buffer (marker-buffer m))
27743 (goto-char m)
27744 (org-agenda-set-restriction-lock 'subtree))))
27745 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27746 'speedbar-function 'speedbar-find-file))
27747 (setq tp (previous-single-property-change
27748 (1+ p) 'speedbar-function)
27749 np (next-single-property-change
27750 tp 'speedbar-function)
27751 dir (speedbar-line-directory)
27752 txt (buffer-substring-no-properties (or tp (point-min))
27753 (or np (point-max))))
27754 (save-excursion
27755 (save-restriction
27756 (set-buffer (find-file-noselect
27757 (let ((default-directory dir))
27758 (expand-file-name txt))))
27759 (unless (org-mode-p)
27760 (error "Cannot restrict to non-Org-mode file"))
27761 (org-agenda-set-restriction-lock 'file))))
27762 (t (error "Don't know how to restrict Org-mode's agenda")))
27763 (org-move-overlay org-speedbar-restriction-lock-overlay
27764 (point-at-bol) (point-at-eol))
27765 (setq current-prefix-arg nil)
27766 (org-agenda-maybe-redo)))
27768 (eval-after-load "speedbar"
27769 '(progn
27770 (speedbar-add-supported-extension ".org")
27771 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
27772 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
27773 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
27774 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27775 (add-hook 'speedbar-visiting-tag-hook
27776 (lambda () (org-show-context 'org-goto)))))
27779 ;;; Fixes and Hacks
27781 ;; Make flyspell not check words in links, to not mess up our keymap
27782 (defun org-mode-flyspell-verify ()
27783 "Don't let flyspell put overlays at active buttons."
27784 (not (get-text-property (point) 'keymap)))
27786 ;; Make `bookmark-jump' show the jump location if it was hidden.
27787 (eval-after-load "bookmark"
27788 '(if (boundp 'bookmark-after-jump-hook)
27789 ;; We can use the hook
27790 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
27791 ;; Hook not available, use advice
27792 (defadvice bookmark-jump (after org-make-visible activate)
27793 "Make the position visible."
27794 (org-bookmark-jump-unhide))))
27796 (defun org-bookmark-jump-unhide ()
27797 "Unhide the current position, to show the bookmark location."
27798 (and (org-mode-p)
27799 (or (org-invisible-p)
27800 (save-excursion (goto-char (max (point-min) (1- (point))))
27801 (org-invisible-p)))
27802 (org-show-context 'bookmark-jump)))
27804 ;; Fix a bug in htmlize where there are text properties (face nil)
27805 (eval-after-load "htmlize"
27806 '(progn
27807 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
27808 "Make sure there are no nil faces"
27809 (setq ad-return-value (delq nil ad-return-value)))))
27811 ;; Make session.el ignore our circular variable
27812 (eval-after-load "session"
27813 '(add-to-list 'session-globals-exclude 'org-mark-ring))
27815 ;;;; Experimental code
27817 (defun org-closed-in-range ()
27818 "Sparse tree of items closed in a certain time range.
27819 Still experimental, may disappear in the future."
27820 (interactive)
27821 ;; Get the time interval from the user.
27822 (let* ((time1 (time-to-seconds
27823 (org-read-date nil 'to-time nil "Starting date: ")))
27824 (time2 (time-to-seconds
27825 (org-read-date nil 'to-time nil "End date:")))
27826 ;; callback function
27827 (callback (lambda ()
27828 (let ((time
27829 (time-to-seconds
27830 (apply 'encode-time
27831 (org-parse-time-string
27832 (match-string 1))))))
27833 ;; check if time in interval
27834 (and (>= time time1) (<= time time2))))))
27835 ;; make tree, check each match with the callback
27836 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
27838 ;;;; Finish up
27840 (provide 'org)
27842 (run-hooks 'org-load-hook)
27844 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
27845 ;;; org.el ends here