Intermediate state, I am just trying comiting now.
[org-mode.git] / org.el
blob6de4a2a36390ff5c1016f5add1b9be5fa8d9b198
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.20
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
81 (require 'easymenu)
83 ;;;; Customization variables
85 ;;; Version
87 (defconst org-version "5.20"
88 "The version number of the file org.el.")
89 (defun org-version ()
90 (interactive)
91 (message "Org-mode version %s" org-version))
93 ;;; Compatibility constants
94 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
95 (defconst org-format-transports-properties-p
96 (let ((x "a"))
97 (add-text-properties 0 1 '(test t) x)
98 (get-text-property 0 'test (format "%s" x)))
99 "Does format transport text properties?")
101 (defmacro org-bound-and-true-p (var)
102 "Return the value of symbol VAR if it is bound, else nil."
103 `(and (boundp (quote ,var)) ,var))
105 (defmacro org-unmodified (&rest body)
106 "Execute body without changing `buffer-modified-p'."
107 `(set-buffer-modified-p
108 (prog1 (buffer-modified-p) ,@body)))
110 (defmacro org-re (s)
111 "Replace posix classes in regular expression."
112 (if (featurep 'xemacs)
113 (let ((ss s))
114 (save-match-data
115 (while (string-match "\\[:alnum:\\]" ss)
116 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
117 (while (string-match "\\[:alpha:\\]" ss)
118 (setq ss (replace-match "a-zA-Z" t t ss)))
119 ss))
122 (defmacro org-preserve-lc (&rest body)
123 `(let ((_line (org-current-line))
124 (_col (current-column)))
125 (unwind-protect
126 (progn ,@body)
127 (goto-line _line)
128 (move-to-column _col))))
130 (defmacro org-without-partial-completion (&rest body)
131 `(let ((pc-mode (and (boundp 'partial-completion-mode)
132 partial-completion-mode)))
133 (unwind-protect
134 (progn
135 (if pc-mode (partial-completion-mode -1))
136 ,@body)
137 (if pc-mode (partial-completion-mode 1)))))
139 ;;; The custom variables
141 (defgroup org nil
142 "Outline-based notes management and organizer."
143 :tag "Org"
144 :group 'outlines
145 :group 'hypermedia
146 :group 'calendar)
148 ;; FIXME: Needs a separate group...
149 (defcustom org-completion-fallback-command 'hippie-expand
150 "The expansion command called by \\[org-complete] in normal context.
151 Normal means, no org-mode-specific context."
152 :group 'org
153 :type 'function)
155 (defgroup org-startup nil
156 "Options concerning startup of Org-mode."
157 :tag "Org Startup"
158 :group 'org)
160 (defcustom org-startup-folded t
161 "Non-nil means, entering Org-mode will switch to OVERVIEW.
162 This can also be configured on a per-file basis by adding one of
163 the following lines anywhere in the buffer:
165 #+STARTUP: fold
166 #+STARTUP: nofold
167 #+STARTUP: content"
168 :group 'org-startup
169 :type '(choice
170 (const :tag "nofold: show all" nil)
171 (const :tag "fold: overview" t)
172 (const :tag "content: all headlines" content)))
174 (defcustom org-startup-truncated t
175 "Non-nil means, entering Org-mode will set `truncate-lines'.
176 This is useful since some lines containing links can be very long and
177 uninteresting. Also tables look terrible when wrapped."
178 :group 'org-startup
179 :type 'boolean)
181 (defcustom org-startup-align-all-tables nil
182 "Non-nil means, align all tables when visiting a file.
183 This is useful when the column width in tables is forced with <N> cookies
184 in table fields. Such tables will look correct only after the first re-align.
185 This can also be configured on a per-file basis by adding one of
186 the following lines anywhere in the buffer:
187 #+STARTUP: align
188 #+STARTUP: noalign"
189 :group 'org-startup
190 :type 'boolean)
192 (defcustom org-insert-mode-line-in-empty-file nil
193 "Non-nil means insert the first line setting Org-mode in empty files.
194 When the function `org-mode' is called interactively in an empty file, this
195 normally means that the file name does not automatically trigger Org-mode.
196 To ensure that the file will always be in Org-mode in the future, a
197 line enforcing Org-mode will be inserted into the buffer, if this option
198 has been set."
199 :group 'org-startup
200 :type 'boolean)
202 (defcustom org-replace-disputed-keys nil
203 "Non-nil means use alternative key bindings for some keys.
204 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
205 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
206 If you want to use Org-mode together with one of these other modes,
207 or more generally if you would like to move some Org-mode commands to
208 other keys, set this variable and configure the keys with the variable
209 `org-disputed-keys'.
211 This option is only relevant at load-time of Org-mode, and must be set
212 *before* org.el is loaded. Changing it requires a restart of Emacs to
213 become effective."
214 :group 'org-startup
215 :type 'boolean)
217 (if (fboundp 'defvaralias)
218 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
220 (defcustom org-disputed-keys
221 '(([(shift up)] . [(meta p)])
222 ([(shift down)] . [(meta n)])
223 ([(shift left)] . [(meta -)])
224 ([(shift right)] . [(meta +)])
225 ([(control shift right)] . [(meta shift +)])
226 ([(control shift left)] . [(meta shift -)]))
227 "Keys for which Org-mode and other modes compete.
228 This is an alist, cars are the default keys, second element specifies
229 the alternative to use when `org-replace-disputed-keys' is t.
231 Keys can be specified in any syntax supported by `define-key'.
232 The value of this option takes effect only at Org-mode's startup,
233 therefore you'll have to restart Emacs to apply it after changing."
234 :group 'org-startup
235 :type 'alist)
237 (defun org-key (key)
238 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
239 Or return the original if not disputed."
240 (if org-replace-disputed-keys
241 (let* ((nkey (key-description key))
242 (x (org-find-if (lambda (x)
243 (equal (key-description (car x)) nkey))
244 org-disputed-keys)))
245 (if x (cdr x) key))
246 key))
248 (defun org-find-if (predicate seq)
249 (catch 'exit
250 (while seq
251 (if (funcall predicate (car seq))
252 (throw 'exit (car seq))
253 (pop seq)))))
255 (defun org-defkey (keymap key def)
256 "Define a key, possibly translated, as returned by `org-key'."
257 (define-key keymap (org-key key) def))
259 (defcustom org-ellipsis nil
260 "The ellipsis to use in the Org-mode outline.
261 When nil, just use the standard three dots. When a string, use that instead,
262 When a face, use the standart 3 dots, but with the specified face.
263 The change affects only Org-mode (which will then use its own display table).
264 Changing this requires executing `M-x org-mode' in a buffer to become
265 effective."
266 :group 'org-startup
267 :type '(choice (const :tag "Default" nil)
268 (face :tag "Face" :value org-warning)
269 (string :tag "String" :value "...#")))
271 (defvar org-display-table nil
272 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
274 (defgroup org-keywords nil
275 "Keywords in Org-mode."
276 :tag "Org Keywords"
277 :group 'org)
279 (defcustom org-deadline-string "DEADLINE:"
280 "String to mark deadline entries.
281 A deadline is this string, followed by a time stamp. Should be a word,
282 terminated by a colon. You can insert a schedule keyword and
283 a timestamp with \\[org-deadline].
284 Changes become only effective after restarting Emacs."
285 :group 'org-keywords
286 :type 'string)
288 (defcustom org-scheduled-string "SCHEDULED:"
289 "String to mark scheduled TODO entries.
290 A schedule is this string, followed by a time stamp. Should be a word,
291 terminated by a colon. You can insert a schedule keyword and
292 a timestamp with \\[org-schedule].
293 Changes become only effective after restarting Emacs."
294 :group 'org-keywords
295 :type 'string)
297 (defcustom org-closed-string "CLOSED:"
298 "String used as the prefix for timestamps logging closing a TODO entry."
299 :group 'org-keywords
300 :type 'string)
302 (defcustom org-clock-string "CLOCK:"
303 "String used as prefix for timestamps clocking work hours on an item."
304 :group 'org-keywords
305 :type 'string)
307 (defcustom org-comment-string "COMMENT"
308 "Entries starting with this keyword will never be exported.
309 An entry can be toggled between COMMENT and normal with
310 \\[org-toggle-comment].
311 Changes become only effective after restarting Emacs."
312 :group 'org-keywords
313 :type 'string)
315 (defcustom org-quote-string "QUOTE"
316 "Entries starting with this keyword will be exported in fixed-width font.
317 Quoting applies only to the text in the entry following the headline, and does
318 not extend beyond the next headline, even if that is lower level.
319 An entry can be toggled between QUOTE and normal with
320 \\[org-toggle-fixed-width-section]."
321 :group 'org-keywords
322 :type 'string)
324 (defconst org-repeat-re
325 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
326 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
327 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
328 "Regular expression for specifying repeated events.
329 After a match, group 1 contains the repeat expression.")
331 (defgroup org-structure nil
332 "Options concerning the general structure of Org-mode files."
333 :tag "Org Structure"
334 :group 'org)
336 (defgroup org-reveal-location nil
337 "Options about how to make context of a location visible."
338 :tag "Org Reveal Location"
339 :group 'org-structure)
341 (defconst org-context-choice
342 '(choice
343 (const :tag "Always" t)
344 (const :tag "Never" nil)
345 (repeat :greedy t :tag "Individual contexts"
346 (cons
347 (choice :tag "Context"
348 (const agenda)
349 (const org-goto)
350 (const occur-tree)
351 (const tags-tree)
352 (const link-search)
353 (const mark-goto)
354 (const bookmark-jump)
355 (const isearch)
356 (const default))
357 (boolean))))
358 "Contexts for the reveal options.")
360 (defcustom org-show-hierarchy-above '((default . t))
361 "Non-nil means, show full hierarchy when revealing a location.
362 Org-mode often shows locations in an org-mode file which might have
363 been invisible before. When this is set, the hierarchy of headings
364 above the exposed location is shown.
365 Turning this off for example for sparse trees makes them very compact.
366 Instead of t, this can also be an alist specifying this option for different
367 contexts. Valid contexts are
368 agenda when exposing an entry from the agenda
369 org-goto when using the command `org-goto' on key C-c C-j
370 occur-tree when using the command `org-occur' on key C-c /
371 tags-tree when constructing a sparse tree based on tags matches
372 link-search when exposing search matches associated with a link
373 mark-goto when exposing the jump goal of a mark
374 bookmark-jump when exposing a bookmark location
375 isearch when exiting from an incremental search
376 default default for all contexts not set explicitly"
377 :group 'org-reveal-location
378 :type org-context-choice)
380 (defcustom org-show-following-heading '((default . nil))
381 "Non-nil means, show following heading when revealing a location.
382 Org-mode often shows locations in an org-mode file which might have
383 been invisible before. When this is set, the heading following the
384 match is shown.
385 Turning this off for example for sparse trees makes them very compact,
386 but makes it harder to edit the location of the match. In such a case,
387 use the command \\[org-reveal] to show more context.
388 Instead of t, this can also be an alist specifying this option for different
389 contexts. See `org-show-hierarchy-above' for valid contexts."
390 :group 'org-reveal-location
391 :type org-context-choice)
393 (defcustom org-show-siblings '((default . nil) (isearch t))
394 "Non-nil means, show all sibling heading when revealing a location.
395 Org-mode often shows locations in an org-mode file which might have
396 been invisible before. When this is set, the sibling of the current entry
397 heading are all made visible. If `org-show-hierarchy-above' is t,
398 the same happens on each level of the hierarchy above the current entry.
400 By default this is on for the isearch context, off for all other contexts.
401 Turning this off for example for sparse trees makes them very compact,
402 but makes it harder to edit the location of the match. In such a case,
403 use the command \\[org-reveal] to show more context.
404 Instead of t, this can also be an alist specifying this option for different
405 contexts. See `org-show-hierarchy-above' for valid contexts."
406 :group 'org-reveal-location
407 :type org-context-choice)
409 (defcustom org-show-entry-below '((default . nil))
410 "Non-nil means, show the entry below a headline when revealing a location.
411 Org-mode often shows locations in an org-mode file which might have
412 been invisible before. When this is set, the text below the headline that is
413 exposed is also shown.
415 By default this is off for all contexts.
416 Instead of t, this can also be an alist specifying this option for different
417 contexts. See `org-show-hierarchy-above' for valid contexts."
418 :group 'org-reveal-location
419 :type org-context-choice)
421 (defgroup org-cycle nil
422 "Options concerning visibility cycling in Org-mode."
423 :tag "Org Cycle"
424 :group 'org-structure)
426 (defcustom org-drawers '("PROPERTIES" "CLOCK")
427 "Names of drawers. Drawers are not opened by cycling on the headline above.
428 Drawers only open with a TAB on the drawer line itself. A drawer looks like
429 this:
430 :DRAWERNAME:
431 .....
432 :END:
433 The drawer \"PROPERTIES\" is special for capturing properties through
434 the property API.
436 Drawers can be defined on the per-file basis with a line like:
438 #+DRAWERS: HIDDEN STATE PROPERTIES"
439 :group 'org-structure
440 :type '(repeat (string :tag "Drawer Name")))
442 (defcustom org-cycle-global-at-bob nil
443 "Cycle globally if cursor is at beginning of buffer and not at a headline.
444 This makes it possible to do global cycling without having to use S-TAB or
445 C-u TAB. For this special case to work, the first line of the buffer
446 must not be a headline - it may be empty ot some other text. When used in
447 this way, `org-cycle-hook' is disables temporarily, to make sure the
448 cursor stays at the beginning of the buffer.
449 When this option is nil, don't do anything special at the beginning
450 of the buffer."
451 :group 'org-cycle
452 :type 'boolean)
454 (defcustom org-cycle-emulate-tab t
455 "Where should `org-cycle' emulate TAB.
456 nil Never
457 white Only in completely white lines
458 whitestart Only at the beginning of lines, before the first non-white char
459 t Everywhere except in headlines
460 exc-hl-bol Everywhere except at the start of a headline
461 If TAB is used in a place where it does not emulate TAB, the current subtree
462 visibility is cycled."
463 :group 'org-cycle
464 :type '(choice (const :tag "Never" nil)
465 (const :tag "Only in completely white lines" white)
466 (const :tag "Before first char in a line" whitestart)
467 (const :tag "Everywhere except in headlines" t)
468 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
471 (defcustom org-cycle-separator-lines 2
472 "Number of empty lines needed to keep an empty line between collapsed trees.
473 If you leave an empty line between the end of a subtree and the following
474 headline, this empty line is hidden when the subtree is folded.
475 Org-mode will leave (exactly) one empty line visible if the number of
476 empty lines is equal or larger to the number given in this variable.
477 So the default 2 means, at least 2 empty lines after the end of a subtree
478 are needed to produce free space between a collapsed subtree and the
479 following headline.
481 Special case: when 0, never leave empty lines in collapsed view."
482 :group 'org-cycle
483 :type 'integer)
485 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
486 org-cycle-hide-drawers
487 org-cycle-show-empty-lines
488 org-optimize-window-after-visibility-change)
489 "Hook that is run after `org-cycle' has changed the buffer visibility.
490 The function(s) in this hook must accept a single argument which indicates
491 the new state that was set by the most recent `org-cycle' command. The
492 argument is a symbol. After a global state change, it can have the values
493 `overview', `content', or `all'. After a local state change, it can have
494 the values `folded', `children', or `subtree'."
495 :group 'org-cycle
496 :type 'hook)
498 (defgroup org-edit-structure nil
499 "Options concerning structure editing in Org-mode."
500 :tag "Org Edit Structure"
501 :group 'org-structure)
503 (defcustom org-special-ctrl-a/e nil
504 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
505 When t, `C-a' will bring back the cursor to the beginning of the
506 headline text, i.e. after the stars and after a possible TODO keyword.
507 In an item, this will be the position after the bullet.
508 When the cursor is already at that position, another `C-a' will bring
509 it to the beginning of the line.
510 `C-e' will jump to the end of the headline, ignoring the presence of tags
511 in the headline. A second `C-e' will then jump to the true end of the
512 line, after any tags.
513 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
514 and only a directly following, identical keypress will bring the cursor
515 to the special positions."
516 :group 'org-edit-structure
517 :type '(choice
518 (const :tag "off" nil)
519 (const :tag "after bullet first" t)
520 (const :tag "border first" reversed)))
522 (if (fboundp 'defvaralias)
523 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
525 (defcustom org-odd-levels-only nil
526 "Non-nil means, skip even levels and only use odd levels for the outline.
527 This has the effect that two stars are being added/taken away in
528 promotion/demotion commands. It also influences how levels are
529 handled by the exporters.
530 Changing it requires restart of `font-lock-mode' to become effective
531 for fontification also in regions already fontified.
532 You may also set this on a per-file basis by adding one of the following
533 lines to the buffer:
535 #+STARTUP: odd
536 #+STARTUP: oddeven"
537 :group 'org-edit-structure
538 :group 'org-font-lock
539 :type 'boolean)
541 (defcustom org-adapt-indentation t
542 "Non-nil means, adapt indentation when promoting and demoting.
543 When this is set and the *entire* text in an entry is indented, the
544 indentation is increased by one space in a demotion command, and
545 decreased by one in a promotion command. If any line in the entry
546 body starts at column 0, indentation is not changed at all."
547 :group 'org-edit-structure
548 :type 'boolean)
550 (defcustom org-blank-before-new-entry '((heading . nil)
551 (plain-list-item . nil))
552 "Should `org-insert-heading' leave a blank line before new heading/item?
553 The value is an alist, with `heading' and `plain-list-item' as car,
554 and a boolean flag as cdr."
555 :group 'org-edit-structure
556 :type '(list
557 (cons (const heading) (boolean))
558 (cons (const plain-list-item) (boolean))))
560 (defcustom org-insert-heading-hook nil
561 "Hook being run after inserting a new heading."
562 :group 'org-edit-structure
563 :type 'hook)
565 (defcustom org-enable-fixed-width-editor t
566 "Non-nil means, lines starting with \":\" are treated as fixed-width.
567 This currently only means, they are never auto-wrapped.
568 When nil, such lines will be treated like ordinary lines.
569 See also the QUOTE keyword."
570 :group 'org-edit-structure
571 :type 'boolean)
573 (defcustom org-goto-auto-isearch t
574 "Non-nil means, typing characters in org-goto starts incremental search."
575 :group 'org-edit-structure
576 :type 'boolean)
578 (defgroup org-sparse-trees nil
579 "Options concerning sparse trees in Org-mode."
580 :tag "Org Sparse Trees"
581 :group 'org-structure)
583 (defcustom org-highlight-sparse-tree-matches t
584 "Non-nil means, highlight all matches that define a sparse tree.
585 The highlights will automatically disappear the next time the buffer is
586 changed by an edit command."
587 :group 'org-sparse-trees
588 :type 'boolean)
590 (defcustom org-remove-highlights-with-change t
591 "Non-nil means, any change to the buffer will remove temporary highlights.
592 Such highlights are created by `org-occur' and `org-clock-display'.
593 When nil, `C-c C-c needs to be used to get rid of the highlights.
594 The highlights created by `org-preview-latex-fragment' always need
595 `C-c C-c' to be removed."
596 :group 'org-sparse-trees
597 :group 'org-time
598 :type 'boolean)
601 (defcustom org-occur-hook '(org-first-headline-recenter)
602 "Hook that is run after `org-occur' has constructed a sparse tree.
603 This can be used to recenter the window to show as much of the structure
604 as possible."
605 :group 'org-sparse-trees
606 :type 'hook)
608 (defgroup org-plain-lists nil
609 "Options concerning plain lists in Org-mode."
610 :tag "Org Plain lists"
611 :group 'org-structure)
613 (defcustom org-cycle-include-plain-lists nil
614 "Non-nil means, include plain lists into visibility cycling.
615 This means that during cycling, plain list items will *temporarily* be
616 interpreted as outline headlines with a level given by 1000+i where i is the
617 indentation of the bullet. In all other operations, plain list items are
618 not seen as headlines. For example, you cannot assign a TODO keyword to
619 such an item."
620 :group 'org-plain-lists
621 :type 'boolean)
623 (defcustom org-plain-list-ordered-item-terminator t
624 "The character that makes a line with leading number an ordered list item.
625 Valid values are ?. and ?\). To get both terminators, use t. While
626 ?. may look nicer, it creates the danger that a line with leading
627 number may be incorrectly interpreted as an item. ?\) therefore is
628 the safe choice."
629 :group 'org-plain-lists
630 :type '(choice (const :tag "dot like in \"2.\"" ?.)
631 (const :tag "paren like in \"2)\"" ?\))
632 (const :tab "both" t)))
634 (defcustom org-auto-renumber-ordered-lists t
635 "Non-nil means, automatically renumber ordered plain lists.
636 Renumbering happens when the sequence have been changed with
637 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
638 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
639 :group 'org-plain-lists
640 :type 'boolean)
642 (defcustom org-provide-checkbox-statistics t
643 "Non-nil means, update checkbox statistics after insert and toggle.
644 When this is set, checkbox statistics is updated each time you either insert
645 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
646 with \\[org-ctrl-c-ctrl-c\\]."
647 :group 'org-plain-lists
648 :type 'boolean)
650 (defgroup org-archive nil
651 "Options concerning archiving in Org-mode."
652 :tag "Org Archive"
653 :group 'org-structure)
655 (defcustom org-archive-tag "ARCHIVE"
656 "The tag that marks a subtree as archived.
657 An archived subtree does not open during visibility cycling, and does
658 not contribute to the agenda listings.
659 After changing this, font-lock must be restarted in the relevant buffers to
660 get the proper fontification."
661 :group 'org-archive
662 :group 'org-keywords
663 :type 'string)
665 (defcustom org-agenda-skip-archived-trees t
666 "Non-nil means, the agenda will skip any items located in archived trees.
667 An archived tree is a tree marked with the tag ARCHIVE."
668 :group 'org-archive
669 :group 'org-agenda-skip
670 :type 'boolean)
672 (defcustom org-cycle-open-archived-trees nil
673 "Non-nil means, `org-cycle' will open archived trees.
674 An archived tree is a tree marked with the tag ARCHIVE.
675 When nil, archived trees will stay folded. You can still open them with
676 normal outline commands like `show-all', but not with the cycling commands."
677 :group 'org-archive
678 :group 'org-cycle
679 :type 'boolean)
681 (defcustom org-sparse-tree-open-archived-trees nil
682 "Non-nil means sparse tree construction shows matches in archived trees.
683 When nil, matches in these trees are highlighted, but the trees are kept in
684 collapsed state."
685 :group 'org-archive
686 :group 'org-sparse-trees
687 :type 'boolean)
689 (defcustom org-archive-location "%s_archive::"
690 "The location where subtrees should be archived.
691 This string consists of two parts, separated by a double-colon.
693 The first part is a file name - when omitted, archiving happens in the same
694 file. %s will be replaced by the current file name (without directory part).
695 Archiving to a different file is useful to keep archived entries from
696 contributing to the Org-mode Agenda.
698 The part after the double colon is a headline. The archived entries will be
699 filed under that headline. When omitted, the subtrees are simply filed away
700 at the end of the file, as top-level entries.
702 Here are a few examples:
703 \"%s_archive::\"
704 If the current file is Projects.org, archive in file
705 Projects.org_archive, as top-level trees. This is the default.
707 \"::* Archived Tasks\"
708 Archive in the current file, under the top-level headline
709 \"* Archived Tasks\".
711 \"~/org/archive.org::\"
712 Archive in file ~/org/archive.org (absolute path), as top-level trees.
714 \"basement::** Finished Tasks\"
715 Archive in file ./basement (relative path), as level 3 trees
716 below the level 2 heading \"** Finished Tasks\".
718 You may set this option on a per-file basis by adding to the buffer a
719 line like
721 #+ARCHIVE: basement::** Finished Tasks"
722 :group 'org-archive
723 :type 'string)
725 (defcustom org-archive-mark-done t
726 "Non-nil means, mark entries as DONE when they are moved to the archive file.
727 This can be a string to set the keyword to use. When t, Org-mode will
728 use the first keyword in its list that means done."
729 :group 'org-archive
730 :type '(choice
731 (const :tag "No" nil)
732 (const :tag "Yes" t)
733 (string :tag "Use this keyword")))
735 (defcustom org-archive-stamp-time t
736 "Non-nil means, add a time stamp to entries moved to an archive file.
737 This variable is obsolete and has no effect anymore, instead add ot remove
738 `time' from the variablle `org-archive-save-context-info'."
739 :group 'org-archive
740 :type 'boolean)
742 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
743 "Parts of context info that should be stored as properties when archiving.
744 When a subtree is moved to an archive file, it looses information given by
745 context, like inherited tags, the category, and possibly also the TODO
746 state (depending on the variable `org-archive-mark-done').
747 This variable can be a list of any of the following symbols:
749 time The time of archiving.
750 file The file where the entry originates.
751 itags The local tags, in the headline of the subtree.
752 ltags The tags the subtree inherits from further up the hierarchy.
753 todo The pre-archive TODO state.
754 category The category, taken from file name or #+CATEGORY lines.
755 olpath The outline path to the item. These are all headlines above
756 the current item, separated by /, like a file path.
758 For each symbol present in the list, a property will be created in
759 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
760 information."
761 :group 'org-archive
762 :type '(set :greedy t
763 (const :tag "Time" time)
764 (const :tag "File" file)
765 (const :tag "Category" category)
766 (const :tag "TODO state" todo)
767 (const :tag "TODO state" priority)
768 (const :tag "Inherited tags" itags)
769 (const :tag "Outline path" olpath)
770 (const :tag "Local tags" ltags)))
772 (defgroup org-imenu-and-speedbar nil
773 "Options concerning imenu and speedbar in Org-mode."
774 :tag "Org Imenu and Speedbar"
775 :group 'org-structure)
777 (defcustom org-imenu-depth 2
778 "The maximum level for Imenu access to Org-mode headlines.
779 This also applied for speedbar access."
780 :group 'org-imenu-and-speedbar
781 :type 'number)
783 (defgroup org-table nil
784 "Options concerning tables in Org-mode."
785 :tag "Org Table"
786 :group 'org)
788 (defcustom org-enable-table-editor 'optimized
789 "Non-nil means, lines starting with \"|\" are handled by the table editor.
790 When nil, such lines will be treated like ordinary lines.
792 When equal to the symbol `optimized', the table editor will be optimized to
793 do the following:
794 - Automatic overwrite mode in front of whitespace in table fields.
795 This makes the structure of the table stay in tact as long as the edited
796 field does not exceed the column width.
797 - Minimize the number of realigns. Normally, the table is aligned each time
798 TAB or RET are pressed to move to another field. With optimization this
799 happens only if changes to a field might have changed the column width.
800 Optimization requires replacing the functions `self-insert-command',
801 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
802 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
803 very good at guessing when a re-align will be necessary, but you can always
804 force one with \\[org-ctrl-c-ctrl-c].
806 If you would like to use the optimized version in Org-mode, but the
807 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
809 This variable can be used to turn on and off the table editor during a session,
810 but in order to toggle optimization, a restart is required.
812 See also the variable `org-table-auto-blank-field'."
813 :group 'org-table
814 :type '(choice
815 (const :tag "off" nil)
816 (const :tag "on" t)
817 (const :tag "on, optimized" optimized)))
819 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
820 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
821 In the optimized version, the table editor takes over all simple keys that
822 normally just insert a character. In tables, the characters are inserted
823 in a way to minimize disturbing the table structure (i.e. in overwrite mode
824 for empty fields). Outside tables, the correct binding of the keys is
825 restored.
827 The default for this option is t if the optimized version is also used in
828 Org-mode. See the variable `org-enable-table-editor' for details. Changing
829 this variable requires a restart of Emacs to become effective."
830 :group 'org-table
831 :type 'boolean)
833 (defcustom orgtbl-radio-table-templates
834 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
835 % END RECEIVE ORGTBL %n
836 \\begin{comment}
837 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
838 | | |
839 \\end{comment}\n")
840 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
841 @c END RECEIVE ORGTBL %n
842 @ignore
843 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
844 | | |
845 @end ignore\n")
846 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
847 <!-- END RECEIVE ORGTBL %n -->
848 <!--
849 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
850 | | |
851 -->\n"))
852 "Templates for radio tables in different major modes.
853 All occurrences of %n in a template will be replaced with the name of the
854 table, obtained by prompting the user."
855 :group 'org-table
856 :type '(repeat
857 (list (symbol :tag "Major mode")
858 (string :tag "Format"))))
860 (defgroup org-table-settings nil
861 "Settings for tables in Org-mode."
862 :tag "Org Table Settings"
863 :group 'org-table)
865 (defcustom org-table-default-size "5x2"
866 "The default size for newly created tables, Columns x Rows."
867 :group 'org-table-settings
868 :type 'string)
870 (defcustom org-table-number-regexp
871 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
872 "Regular expression for recognizing numbers in table columns.
873 If a table column contains mostly numbers, it will be aligned to the
874 right. If not, it will be aligned to the left.
876 The default value of this option is a regular expression which allows
877 anything which looks remotely like a number as used in scientific
878 context. For example, all of the following will be considered a
879 number:
880 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
882 Other options offered by the customize interface are more restrictive."
883 :group 'org-table-settings
884 :type '(choice
885 (const :tag "Positive Integers"
886 "^[0-9]+$")
887 (const :tag "Integers"
888 "^[-+]?[0-9]+$")
889 (const :tag "Floating Point Numbers"
890 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
891 (const :tag "Floating Point Number or Integer"
892 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
893 (const :tag "Exponential, Floating point, Integer"
894 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
895 (const :tag "Very General Number-Like, including hex"
896 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
897 (string :tag "Regexp:")))
899 (defcustom org-table-number-fraction 0.5
900 "Fraction of numbers in a column required to make the column align right.
901 In a column all non-white fields are considered. If at least this
902 fraction of fields is matched by `org-table-number-fraction',
903 alignment to the right border applies."
904 :group 'org-table-settings
905 :type 'number)
907 (defgroup org-table-editing nil
908 "Behavior of tables during editing in Org-mode."
909 :tag "Org Table Editing"
910 :group 'org-table)
912 (defcustom org-table-automatic-realign t
913 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
914 When nil, aligning is only done with \\[org-table-align], or after column
915 removal/insertion."
916 :group 'org-table-editing
917 :type 'boolean)
919 (defcustom org-table-auto-blank-field t
920 "Non-nil means, automatically blank table field when starting to type into it.
921 This only happens when typing immediately after a field motion
922 command (TAB, S-TAB or RET).
923 Only relevant when `org-enable-table-editor' is equal to `optimized'."
924 :group 'org-table-editing
925 :type 'boolean)
927 (defcustom org-table-tab-jumps-over-hlines t
928 "Non-nil means, tab in the last column of a table with jump over a hline.
929 If a horizontal separator line is following the current line,
930 `org-table-next-field' can either create a new row before that line, or jump
931 over the line. When this option is nil, a new line will be created before
932 this line."
933 :group 'org-table-editing
934 :type 'boolean)
936 (defcustom org-table-tab-recognizes-table.el t
937 "Non-nil means, TAB will automatically notice a table.el table.
938 When it sees such a table, it moves point into it and - if necessary -
939 calls `table-recognize-table'."
940 :group 'org-table-editing
941 :type 'boolean)
943 (defgroup org-table-calculation nil
944 "Options concerning tables in Org-mode."
945 :tag "Org Table Calculation"
946 :group 'org-table)
948 (defcustom org-table-use-standard-references t
949 "Should org-mode work with table refrences like B3 instead of @3$2?
950 Possible values are:
951 nil never use them
952 from accept as input, do not present for editing
953 t: accept as input and present for editing"
954 :group 'org-table-calculation
955 :type '(choice
956 (const :tag "Never, don't even check unser input for them" nil)
957 (const :tag "Always, both as user input, and when editing" t)
958 (const :tag "Convert user input, don't offer during editing" 'from)))
960 (defcustom org-table-copy-increment t
961 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
962 :group 'org-table-calculation
963 :type 'boolean)
965 (defcustom org-calc-default-modes
966 '(calc-internal-prec 12
967 calc-float-format (float 5)
968 calc-angle-mode deg
969 calc-prefer-frac nil
970 calc-symbolic-mode nil
971 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
972 calc-display-working-message t
974 "List with Calc mode settings for use in calc-eval for table formulas.
975 The list must contain alternating symbols (Calc modes variables and values).
976 Don't remove any of the default settings, just change the values. Org-mode
977 relies on the variables to be present in the list."
978 :group 'org-table-calculation
979 :type 'plist)
981 (defcustom org-table-formula-evaluate-inline t
982 "Non-nil means, TAB and RET evaluate a formula in current table field.
983 If the current field starts with an equal sign, it is assumed to be a formula
984 which should be evaluated as described in the manual and in the documentation
985 string of the command `org-table-eval-formula'. This feature requires the
986 Emacs calc package.
987 When this variable is nil, formula calculation is only available through
988 the command \\[org-table-eval-formula]."
989 :group 'org-table-calculation
990 :type 'boolean)
992 (defcustom org-table-formula-use-constants t
993 "Non-nil means, interpret constants in formulas in tables.
994 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
995 by the value given in `org-table-formula-constants', or by a value obtained
996 from the `constants.el' package."
997 :group 'org-table-calculation
998 :type 'boolean)
1000 (defcustom org-table-formula-constants nil
1001 "Alist with constant names and values, for use in table formulas.
1002 The car of each element is a name of a constant, without the `$' before it.
1003 The cdr is the value as a string. For example, if you'd like to use the
1004 speed of light in a formula, you would configure
1006 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1008 and then use it in an equation like `$1*$c'.
1010 Constants can also be defined on a per-file basis using a line like
1012 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1013 :group 'org-table-calculation
1014 :type '(repeat
1015 (cons (string :tag "name")
1016 (string :tag "value"))))
1018 (defvar org-table-formula-constants-local nil
1019 "Local version of `org-table-formula-constants'.")
1020 (make-variable-buffer-local 'org-table-formula-constants-local)
1022 (defcustom org-table-allow-automatic-line-recalculation t
1023 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1024 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1025 :group 'org-table-calculation
1026 :type 'boolean)
1028 (defgroup org-link nil
1029 "Options concerning links in Org-mode."
1030 :tag "Org Link"
1031 :group 'org)
1033 (defvar org-link-abbrev-alist-local nil
1034 "Buffer-local version of `org-link-abbrev-alist', which see.
1035 The value of this is taken from the #+LINK lines.")
1036 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1038 (defcustom org-link-abbrev-alist nil
1039 "Alist of link abbreviations.
1040 The car of each element is a string, to be replaced at the start of a link.
1041 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1042 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1044 [[linkkey:tag][description]]
1046 If REPLACE is a string, the tag will simply be appended to create the link.
1047 If the string contains \"%s\", the tag will be inserted there.
1049 REPLACE may also be a function that will be called with the tag as the
1050 only argument to create the link, which should be returned as a string.
1052 See the manual for examples."
1053 :group 'org-link
1054 :type 'alist)
1056 (defcustom org-descriptive-links t
1057 "Non-nil means, hide link part and only show description of bracket links.
1058 Bracket links are like [[link][descritpion]]. This variable sets the initial
1059 state in new org-mode buffers. The setting can then be toggled on a
1060 per-buffer basis from the Org->Hyperlinks menu."
1061 :group 'org-link
1062 :type 'boolean)
1064 (defcustom org-link-file-path-type 'adaptive
1065 "How the path name in file links should be stored.
1066 Valid values are:
1068 relative Relative to the current directory, i.e. the directory of the file
1069 into which the link is being inserted.
1070 absolute Absolute path, if possible with ~ for home directory.
1071 noabbrev Absolute path, no abbreviation of home directory.
1072 adaptive Use relative path for files in the current directory and sub-
1073 directories of it. For other files, use an absolute path."
1074 :group 'org-link
1075 :type '(choice
1076 (const relative)
1077 (const absolute)
1078 (const noabbrev)
1079 (const adaptive)))
1081 (defcustom org-activate-links '(bracket angle plain radio tag date)
1082 "Types of links that should be activated in Org-mode files.
1083 This is a list of symbols, each leading to the activation of a certain link
1084 type. In principle, it does not hurt to turn on most link types - there may
1085 be a small gain when turning off unused link types. The types are:
1087 bracket The recommended [[link][description]] or [[link]] links with hiding.
1088 angular Links in angular brackes that may contain whitespace like
1089 <bbdb:Carsten Dominik>.
1090 plain Plain links in normal text, no whitespace, like http://google.com.
1091 radio Text that is matched by a radio target, see manual for details.
1092 tag Tag settings in a headline (link to tag search).
1093 date Time stamps (link to calendar).
1095 Changing this variable requires a restart of Emacs to become effective."
1096 :group 'org-link
1097 :type '(set (const :tag "Double bracket links (new style)" bracket)
1098 (const :tag "Angular bracket links (old style)" angular)
1099 (const :tag "plain text links" plain)
1100 (const :tag "Radio target matches" radio)
1101 (const :tag "Tags" tag)
1102 (const :tag "Tags" target)
1103 (const :tag "Timestamps" date)))
1105 (defgroup org-link-store nil
1106 "Options concerning storing links in Org-mode"
1107 :tag "Org Store Link"
1108 :group 'org-link)
1110 (defcustom org-email-link-description-format "Email %c: %.30s"
1111 "Format of the description part of a link to an email or usenet message.
1112 The following %-excapes will be replaced by corresponding information:
1114 %F full \"From\" field
1115 %f name, taken from \"From\" field, address if no name
1116 %T full \"To\" field
1117 %t first name in \"To\" field, address if no name
1118 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1119 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1120 %s subject
1121 %m message-id.
1123 You may use normal field width specification between the % and the letter.
1124 This is for example useful to limit the length of the subject.
1126 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1127 :group 'org-link-store
1128 :type 'string)
1130 (defcustom org-from-is-user-regexp
1131 (let (r1 r2)
1132 (when (and user-mail-address (not (string= user-mail-address "")))
1133 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1134 (when (and user-full-name (not (string= user-full-name "")))
1135 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1136 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1137 "Regexp mached against the \"From:\" header of an email or usenet message.
1138 It should match if the message is from the user him/herself."
1139 :group 'org-link-store
1140 :type 'regexp)
1142 (defcustom org-context-in-file-links t
1143 "Non-nil means, file links from `org-store-link' contain context.
1144 A search string will be added to the file name with :: as separator and
1145 used to find the context when the link is activated by the command
1146 `org-open-at-point'.
1147 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1148 negates this setting for the duration of the command."
1149 :group 'org-link-store
1150 :type 'boolean)
1152 (defcustom org-keep-stored-link-after-insertion nil
1153 "Non-nil means, keep link in list for entire session.
1155 The command `org-store-link' adds a link pointing to the current
1156 location to an internal list. These links accumulate during a session.
1157 The command `org-insert-link' can be used to insert links into any
1158 Org-mode file (offering completion for all stored links). When this
1159 option is nil, every link which has been inserted once using \\[org-insert-link]
1160 will be removed from the list, to make completing the unused links
1161 more efficient."
1162 :group 'org-link-store
1163 :type 'boolean)
1165 (defcustom org-usenet-links-prefer-google nil
1166 "Non-nil means, `org-store-link' will create web links to Google groups.
1167 When nil, Gnus will be used for such links.
1168 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1169 negates this setting for the duration of the command."
1170 :group 'org-link-store
1171 :type 'boolean)
1173 (defgroup org-link-follow nil
1174 "Options concerning following links in Org-mode"
1175 :tag "Org Follow Link"
1176 :group 'org-link)
1178 (defcustom org-tab-follows-link nil
1179 "Non-nil means, on links TAB will follow the link.
1180 Needs to be set before org.el is loaded."
1181 :group 'org-link-follow
1182 :type 'boolean)
1184 (defcustom org-return-follows-link nil
1185 "Non-nil means, on links RET will follow the link.
1186 Needs to be set before org.el is loaded."
1187 :group 'org-link-follow
1188 :type 'boolean)
1190 (defcustom org-mouse-1-follows-link t
1191 "Non-nil means, mouse-1 on a link will follow the link.
1192 A longer mouse click will still set point. Does not wortk on XEmacs.
1193 Needs to be set before org.el is loaded."
1194 :group 'org-link-follow
1195 :type 'boolean)
1197 (defcustom org-mark-ring-length 4
1198 "Number of different positions to be recorded in the ring
1199 Changing this requires a restart of Emacs to work correctly."
1200 :group 'org-link-follow
1201 :type 'interger)
1203 (defcustom org-link-frame-setup
1204 '((vm . vm-visit-folder-other-frame)
1205 (gnus . gnus-other-frame)
1206 (file . find-file-other-window))
1207 "Setup the frame configuration for following links.
1208 When following a link with Emacs, it may often be useful to display
1209 this link in another window or frame. This variable can be used to
1210 set this up for the different types of links.
1211 For VM, use any of
1212 `vm-visit-folder'
1213 `vm-visit-folder-other-frame'
1214 For Gnus, use any of
1215 `gnus'
1216 `gnus-other-frame'
1217 For FILE, use any of
1218 `find-file'
1219 `find-file-other-window'
1220 `find-file-other-frame'
1221 For the calendar, use the variable `calendar-setup'.
1222 For BBDB, it is currently only possible to display the matches in
1223 another window."
1224 :group 'org-link-follow
1225 :type '(list
1226 (cons (const vm)
1227 (choice
1228 (const vm-visit-folder)
1229 (const vm-visit-folder-other-window)
1230 (const vm-visit-folder-other-frame)))
1231 (cons (const gnus)
1232 (choice
1233 (const gnus)
1234 (const gnus-other-frame)))
1235 (cons (const file)
1236 (choice
1237 (const find-file)
1238 (const find-file-other-window)
1239 (const find-file-other-frame)))))
1241 (defcustom org-display-internal-link-with-indirect-buffer nil
1242 "Non-nil means, use indirect buffer to display infile links.
1243 Activating internal links (from one location in a file to another location
1244 in the same file) normally just jumps to the location. When the link is
1245 activated with a C-u prefix (or with mouse-3), the link is displayed in
1246 another window. When this option is set, the other window actually displays
1247 an indirect buffer clone of the current buffer, to avoid any visibility
1248 changes to the current buffer."
1249 :group 'org-link-follow
1250 :type 'boolean)
1252 (defcustom org-open-non-existing-files nil
1253 "Non-nil means, `org-open-file' will open non-existing files.
1254 When nil, an error will be generated."
1255 :group 'org-link-follow
1256 :type 'boolean)
1258 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1259 "Function and arguments to call for following mailto links.
1260 This is a list with the first element being a lisp function, and the
1261 remaining elements being arguments to the function. In string arguments,
1262 %a will be replaced by the address, and %s will be replaced by the subject
1263 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1264 :group 'org-link-follow
1265 :type '(choice
1266 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1267 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1268 (const :tag "message-mail" (message-mail "%a" "%s"))
1269 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1271 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1272 "Non-nil means, ask for confirmation before executing shell links.
1273 Shell links can be dangerous: just think about a link
1275 [[shell:rm -rf ~/*][Google Search]]
1277 This link would show up in your Org-mode document as \"Google Search\",
1278 but really it would remove your entire home directory.
1279 Therefore we advise against setting this variable to nil.
1280 Just change it to `y-or-n-p' of you want to confirm with a
1281 single keystroke rather than having to type \"yes\"."
1282 :group 'org-link-follow
1283 :type '(choice
1284 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1285 (const :tag "with y-or-n (faster)" y-or-n-p)
1286 (const :tag "no confirmation (dangerous)" nil)))
1288 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1289 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1290 Elisp links can be dangerous: just think about a link
1292 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1294 This link would show up in your Org-mode document as \"Google Search\",
1295 but really it would remove your entire home directory.
1296 Therefore we advise against setting this variable to nil.
1297 Just change it to `y-or-n-p' of you want to confirm with a
1298 single keystroke rather than having to type \"yes\"."
1299 :group 'org-link-follow
1300 :type '(choice
1301 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1302 (const :tag "with y-or-n (faster)" y-or-n-p)
1303 (const :tag "no confirmation (dangerous)" nil)))
1305 (defconst org-file-apps-defaults-gnu
1306 '((remote . emacs)
1307 (t . mailcap))
1308 "Default file applications on a UNIX or GNU/Linux system.
1309 See `org-file-apps'.")
1311 (defconst org-file-apps-defaults-macosx
1312 '((remote . emacs)
1313 (t . "open %s")
1314 ("ps" . "gv %s")
1315 ("ps.gz" . "gv %s")
1316 ("eps" . "gv %s")
1317 ("eps.gz" . "gv %s")
1318 ("dvi" . "xdvi %s")
1319 ("fig" . "xfig %s"))
1320 "Default file applications on a MacOS X system.
1321 The system \"open\" is known as a default, but we use X11 applications
1322 for some files for which the OS does not have a good default.
1323 See `org-file-apps'.")
1325 (defconst org-file-apps-defaults-windowsnt
1326 (list
1327 '(remote . emacs)
1328 (cons t
1329 (list (if (featurep 'xemacs)
1330 'mswindows-shell-execute
1331 'w32-shell-execute)
1332 "open" 'file)))
1333 "Default file applications on a Windows NT system.
1334 The system \"open\" is used for most files.
1335 See `org-file-apps'.")
1337 (defcustom org-file-apps
1339 ("txt" . emacs)
1340 ("tex" . emacs)
1341 ("ltx" . emacs)
1342 ("org" . emacs)
1343 ("el" . emacs)
1344 ("bib" . emacs)
1346 "External applications for opening `file:path' items in a document.
1347 Org-mode uses system defaults for different file types, but
1348 you can use this variable to set the application for a given file
1349 extension. The entries in this list are cons cells where the car identifies
1350 files and the cdr the corresponding command. Possible values for the
1351 file identifier are
1352 \"ext\" A string identifying an extension
1353 `directory' Matches a directory
1354 `remote' Matches a remote file, accessible through tramp or efs.
1355 Remote files most likely should be visited through Emacs
1356 because external applications cannot handle such paths.
1357 t Default for all remaining files
1359 Possible values for the command are:
1360 `emacs' The file will be visited by the current Emacs process.
1361 `default' Use the default application for this file type.
1362 string A command to be executed by a shell; %s will be replaced
1363 by the path to the file.
1364 sexp A Lisp form which will be evaluated. The file path will
1365 be available in the Lisp variable `file'.
1366 For more examples, see the system specific constants
1367 `org-file-apps-defaults-macosx'
1368 `org-file-apps-defaults-windowsnt'
1369 `org-file-apps-defaults-gnu'."
1370 :group 'org-link-follow
1371 :type '(repeat
1372 (cons (choice :value ""
1373 (string :tag "Extension")
1374 (const :tag "Default for unrecognized files" t)
1375 (const :tag "Remote file" remote)
1376 (const :tag "Links to a directory" directory))
1377 (choice :value ""
1378 (const :tag "Visit with Emacs" emacs)
1379 (const :tag "Use system default" default)
1380 (string :tag "Command")
1381 (sexp :tag "Lisp form")))))
1383 (defcustom org-mhe-search-all-folders nil
1384 "Non-nil means, that the search for the mh-message will be extended to
1385 all folders if the message cannot be found in the folder given in the link.
1386 Searching all folders is very efficient with one of the search engines
1387 supported by MH-E, but will be slow with pick."
1388 :group 'org-link-follow
1389 :type 'boolean)
1391 (defgroup org-remember nil
1392 "Options concerning interaction with remember.el."
1393 :tag "Org Remember"
1394 :group 'org)
1396 (defcustom org-directory "~/org"
1397 "Directory with org files.
1398 This directory will be used as default to prompt for org files.
1399 Used by the hooks for remember.el."
1400 :group 'org-remember
1401 :type 'directory)
1403 (defcustom org-default-notes-file "~/.notes"
1404 "Default target for storing notes.
1405 Used by the hooks for remember.el. This can be a string, or nil to mean
1406 the value of `remember-data-file'.
1407 You can set this on a per-template basis with the variable
1408 `org-remember-templates'."
1409 :group 'org-remember
1410 :type '(choice
1411 (const :tag "Default from remember-data-file" nil)
1412 file))
1414 (defcustom org-remember-store-without-prompt t
1415 "Non-nil means, `C-c C-c' stores remember note without further promts.
1416 In this case, you need `C-u C-c C-c' to get the prompts for
1417 note file and headline.
1418 When this variable is nil, `C-c C-c' give you the prompts, and
1419 `C-u C-c C-c' trigger the fasttrack."
1420 :group 'org-remember
1421 :type 'boolean)
1423 (defcustom org-remember-interactive-interface 'refile
1424 "The interface to be used for interactive filing of remember notes.
1425 This is only used when the interactive mode for selecting a filing
1426 location is used (see the variable `org-remember-store-without-prompt').
1427 Allowed vaues are:
1428 outline The interface shows an outline of the relevant file
1429 and the correct heading is found by moving through
1430 the outline or by searching with incremental search.
1431 outline-path-completion Headlines in the current buffer are offered via
1432 completion.
1433 refile Use the refile interface, and offer headlines,
1434 possibly from different buffers."
1435 :group 'org-remember
1436 :type '(choice
1437 (const :tag "Refile" refile)
1438 (const :tag "Outline" outline)
1439 (const :tag "Outline-path-completion" outline-path-completion)))
1441 (defcustom org-goto-interface 'outline
1442 "The default interface to be used for `org-goto'.
1443 Allowed vaues are:
1444 outline The interface shows an outline of the relevant file
1445 and the correct heading is found by moving through
1446 the outline or by searching with incremental search.
1447 outline-path-completion Headlines in the current buffer are offered via
1448 completion."
1449 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1450 :type '(choice
1451 (const :tag "Outline" outline)
1452 (const :tag "Outline-path-completion" outline-path-completion)))
1454 (defcustom org-remember-default-headline ""
1455 "The headline that should be the default location in the notes file.
1456 When filing remember notes, the cursor will start at that position.
1457 You can set this on a per-template basis with the variable
1458 `org-remember-templates'."
1459 :group 'org-remember
1460 :type 'string)
1462 (defcustom org-remember-templates nil
1463 "Templates for the creation of remember buffers.
1464 When nil, just let remember make the buffer.
1465 When not nil, this is a list of 5-element lists. In each entry, the first
1466 element is the name of the template, which should be a single short word.
1467 The second element is a character, a unique key to select this template.
1468 The third element is the template. The fourth element is optional and can
1469 specify a destination file for remember items created with this template.
1470 The default file is given by `org-default-notes-file'. An optional fifth
1471 element can specify the headline in that file that should be offered
1472 first when the user is asked to file the entry. The default headline is
1473 given in the variable `org-remember-default-headline'.
1475 The template specifies the structure of the remember buffer. It should have
1476 a first line starting with a star, to act as the org-mode headline.
1477 Furthermore, the following %-escapes will be replaced with content:
1479 %^{prompt} Prompt the user for a string and replace this sequence with it.
1480 A default value and a completion table ca be specified like this:
1481 %^{prompt|default|completion2|completion3|...}
1482 %t time stamp, date only
1483 %T time stamp with date and time
1484 %u, %U like the above, but inactive time stamps
1485 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1486 You may define a prompt like %^{Please specify birthday}t
1487 %n user name (taken from `user-full-name')
1488 %a annotation, normally the link created with org-store-link
1489 %i initial content, the region when remember is called with C-u.
1490 If %i is indented, the entire inserted text will be indented
1491 as well.
1492 %c content of the clipboard, or current kill ring head
1493 %^g prompt for tags, with completion on tags in target file
1494 %^G prompt for tags, with completion all tags in all agenda files
1495 %:keyword specific information for certain link types, see below
1496 %[pathname] insert the contents of the file given by `pathname'
1497 %(sexp) evaluate elisp `(sexp)' and replace with the result
1498 %! Store this note immediately after filling the template
1500 %? After completing the template, position cursor here.
1502 Apart from these general escapes, you can access information specific to the
1503 link type that is created. For example, calling `remember' in emails or gnus
1504 will record the author and the subject of the message, which you can access
1505 with %:author and %:subject, respectively. Here is a complete list of what
1506 is recorded for each link type.
1508 Link type | Available information
1509 -------------------+------------------------------------------------------
1510 bbdb | %:type %:name %:company
1511 vm, wl, mh, rmail | %:type %:subject %:message-id
1512 | %:from %:fromname %:fromaddress
1513 | %:to %:toname %:toaddress
1514 | %:fromto (either \"to NAME\" or \"from NAME\")
1515 gnus | %:group, for messages also all email fields
1516 w3, w3m | %:type %:url
1517 info | %:type %:file %:node
1518 calendar | %:type %:date"
1519 :group 'org-remember
1520 :get (lambda (var) ; Make sure all entries have 5 elements
1521 (mapcar (lambda (x)
1522 (if (not (stringp (car x))) (setq x (cons "" x)))
1523 (cond ((= (length x) 4) (append x '("")))
1524 ((= (length x) 3) (append x '("" "")))
1525 (t x)))
1526 (default-value var)))
1527 :type '(repeat
1528 :tag "enabled"
1529 (list :value ("" ?a "\n" nil nil)
1530 (string :tag "Name")
1531 (character :tag "Selection Key")
1532 (string :tag "Template")
1533 (choice
1534 (file :tag "Destination file")
1535 (const :tag "Prompt for file" nil))
1536 (choice
1537 (string :tag "Destination headline")
1538 (const :tag "Selection interface for heading")))))
1540 (defcustom org-reverse-note-order nil
1541 "Non-nil means, store new notes at the beginning of a file or entry.
1542 When nil, new notes will be filed to the end of a file or entry.
1543 This can also be a list with cons cells of regular expressions that
1544 are matched against file names, and values."
1545 :group 'org-remember
1546 :type '(choice
1547 (const :tag "Reverse always" t)
1548 (const :tag "Reverse never" nil)
1549 (repeat :tag "By file name regexp"
1550 (cons regexp boolean))))
1552 (defcustom org-refile-targets nil
1553 "Targets for refiling entries with \\[org-refile].
1554 This is list of cons cells. Each cell contains:
1555 - a specification of the files to be considered, either a list of files,
1556 or a symbol whose function or value fields will be used to retrieve
1557 a file name or a list of file names. Nil means, refile to a different
1558 heading in the current buffer.
1559 - A specification of how to find candidate refile targets. This may be
1560 any of
1561 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1562 This tag has to be present in all target headlines, inheritance will
1563 not be considered.
1564 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1565 todo keyword.
1566 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1567 headlines that are refiling targets.
1568 - a cons cell (:level . N). Any headline of level N is considered a target.
1569 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1570 ;; FIXME: what if there are a var and func with same name???
1571 :group 'org-remember
1572 :type '(repeat
1573 (cons
1574 (choice :value org-agenda-files
1575 (const :tag "All agenda files" org-agenda-files)
1576 (const :tag "Current buffer" nil)
1577 (function) (variable) (file))
1578 (choice :tag "Identify target headline by"
1579 (cons :tag "Specific tag" (const :tag) (string))
1580 (cons :tag "TODO keyword" (const :todo) (string))
1581 (cons :tag "Regular expression" (const :regexp) (regexp))
1582 (cons :tag "Level number" (const :level) (integer))
1583 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1585 (defcustom org-refile-use-outline-path nil
1586 "Non-nil means, provide refile targets as paths.
1587 So a level 3 headline will be available as level1/level2/level3.
1588 When the value is `file', also include the file name (without directory)
1589 into the path. When `full-file-path', include the full file path."
1590 :group 'org-remember
1591 :type '(choice
1592 (const :tag "Not" nil)
1593 (const :tag "Yes" t)
1594 (const :tag "Start with file name" file)
1595 (const :tag "Start with full file path" full-file-path)))
1597 (defgroup org-todo nil
1598 "Options concerning TODO items in Org-mode."
1599 :tag "Org TODO"
1600 :group 'org)
1602 (defgroup org-progress nil
1603 "Options concerning Progress logging in Org-mode."
1604 :tag "Org Progress"
1605 :group 'org-time)
1607 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1608 "List of TODO entry keyword sequences and their interpretation.
1609 \\<org-mode-map>This is a list of sequences.
1611 Each sequence starts with a symbol, either `sequence' or `type',
1612 indicating if the keywords should be interpreted as a sequence of
1613 action steps, or as different types of TODO items. The first
1614 keywords are states requiring action - these states will select a headline
1615 for inclusion into the global TODO list Org-mode produces. If one of
1616 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1617 signify that no further action is necessary. If \"|\" is not found,
1618 the last keyword is treated as the only DONE state of the sequence.
1620 The command \\[org-todo] cycles an entry through these states, and one
1621 additional state where no keyword is present. For details about this
1622 cycling, see the manual.
1624 TODO keywords and interpretation can also be set on a per-file basis with
1625 the special #+SEQ_TODO and #+TYP_TODO lines.
1627 For backward compatibility, this variable may also be just a list
1628 of keywords - in this case the interptetation (sequence or type) will be
1629 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1630 :group 'org-todo
1631 :group 'org-keywords
1632 :type '(choice
1633 (repeat :tag "Old syntax, just keywords"
1634 (string :tag "Keyword"))
1635 (repeat :tag "New syntax"
1636 (cons
1637 (choice
1638 :tag "Interpretation"
1639 (const :tag "Sequence (cycling hits every state)" sequence)
1640 (const :tag "Type (cycling directly to DONE)" type))
1641 (repeat
1642 (string :tag "Keyword"))))))
1644 (defvar org-todo-keywords-1 nil)
1645 (make-variable-buffer-local 'org-todo-keywords-1)
1646 (defvar org-todo-keywords-for-agenda nil)
1647 (defvar org-done-keywords-for-agenda nil)
1648 (defvar org-not-done-keywords nil)
1649 (make-variable-buffer-local 'org-not-done-keywords)
1650 (defvar org-done-keywords nil)
1651 (make-variable-buffer-local 'org-done-keywords)
1652 (defvar org-todo-heads nil)
1653 (make-variable-buffer-local 'org-todo-heads)
1654 (defvar org-todo-sets nil)
1655 (make-variable-buffer-local 'org-todo-sets)
1656 (defvar org-todo-log-states nil)
1657 (make-variable-buffer-local 'org-todo-log-states)
1658 (defvar org-todo-kwd-alist nil)
1659 (make-variable-buffer-local 'org-todo-kwd-alist)
1660 (defvar org-todo-key-alist nil)
1661 (make-variable-buffer-local 'org-todo-key-alist)
1662 (defvar org-todo-key-trigger nil)
1663 (make-variable-buffer-local 'org-todo-key-trigger)
1665 (defcustom org-todo-interpretation 'sequence
1666 "Controls how TODO keywords are interpreted.
1667 This variable is in principle obsolete and is only used for
1668 backward compatibility, if the interpretation of todo keywords is
1669 not given already in `org-todo-keywords'. See that variable for
1670 more information."
1671 :group 'org-todo
1672 :group 'org-keywords
1673 :type '(choice (const sequence)
1674 (const type)))
1676 (defcustom org-use-fast-todo-selection 'prefix
1677 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1678 This variable describes if and under what circumstances the cycling
1679 mechanism for TODO keywords will be replaced by a single-key, direct
1680 selection scheme.
1682 When nil, fast selection is never used.
1684 When the symbol `prefix', it will be used when `org-todo' is called with
1685 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1686 in an agenda buffer.
1688 When t, fast selection is used by default. In this case, the prefix
1689 argument forces cycling instead.
1691 In all cases, the special interface is only used if access keys have actually
1692 been assigned by the user, i.e. if keywords in the configuration are followed
1693 by a letter in parenthesis, like TODO(t)."
1694 :group 'org-todo
1695 :type '(choice
1696 (const :tag "Never" nil)
1697 (const :tag "By default" t)
1698 (const :tag "Only with C-u C-c C-t" prefix)))
1700 (defcustom org-after-todo-state-change-hook nil
1701 "Hook which is run after the state of a TODO item was changed.
1702 The new state (a string with a TODO keyword, or nil) is available in the
1703 Lisp variable `state'."
1704 :group 'org-todo
1705 :type 'hook)
1707 (defcustom org-log-done nil
1708 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1709 When the state of an entry is changed from nothing or a DONE state to
1710 a not-done TODO state, remove a previous closing date.
1712 This can also be a list of symbols indicating under which conditions
1713 the time stamp recording the action should be annotated with a short note.
1714 Valid members of this list are
1716 done Offer to record a note when marking entries done
1717 state Offer to record a note whenever changing the TODO state
1718 of an item. This is only relevant if TODO keywords are
1719 interpreted as sequence, see variable `org-todo-interpretation'.
1720 When `state' is set, this includes tracking `done'.
1721 clock-out Offer to record a note when clocking out of an item.
1723 A separate window will then pop up and allow you to type a note.
1724 After finishing with C-c C-c, the note will be added directly after the
1725 timestamp, as a plain list item. See also the variable
1726 `org-log-note-headings'.
1728 Logging can also be configured on a per-file basis by adding one of
1729 the following lines anywhere in the buffer:
1731 #+STARTUP: logdone
1732 #+STARTUP: nologging
1733 #+STARTUP: lognotedone
1734 #+STARTUP: lognotestate
1735 #+STARTUP: lognoteclock-out
1737 You can have local logging settings for a subtree by setting the LOGGING
1738 property to one or more of these keywords."
1739 :group 'org-todo
1740 :group 'org-progress
1741 :type '(choice
1742 (const :tag "off" nil)
1743 (const :tag "on" t)
1744 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1745 (const :tag "when item is marked DONE" done)
1746 (const :tag "when TODO state changes" state)
1747 (const :tag "when clocking out" clock-out))))
1749 (defcustom org-log-done-with-time t
1750 "Non-nil means, the CLOSED time stamp will contain date and time.
1751 When nil, only the date will be recorded."
1752 :group 'org-progress
1753 :type 'boolean)
1755 (defcustom org-log-note-headings
1756 '((done . "CLOSING NOTE %t")
1757 (state . "State %-12s %t")
1758 (clock-out . ""))
1759 "Headings for notes added when clocking out or closing TODO items.
1760 The value is an alist, with the car being a symbol indicating the note
1761 context, and the cdr is the heading to be used. The heading may also be the
1762 empty string.
1763 %t in the heading will be replaced by a time stamp.
1764 %s will be replaced by the new TODO state, in double quotes.
1765 %u will be replaced by the user name.
1766 %U will be replaced by the full user name."
1767 :group 'org-todo
1768 :group 'org-progress
1769 :type '(list :greedy t
1770 (cons (const :tag "Heading when closing an item" done) string)
1771 (cons (const :tag
1772 "Heading when changing todo state (todo sequence only)"
1773 state) string)
1774 (cons (const :tag "Heading when clocking out" clock-out) string)))
1776 (defcustom org-log-states-order-reversed t
1777 "Non-nil means, the latest state change note will be directly after heading.
1778 When nil, the notes will be orderer according to time."
1779 :group 'org-todo
1780 :group 'org-progress
1781 :type 'boolean)
1783 (defcustom org-log-repeat t
1784 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1785 When nil, no note will be taken.
1786 This option can also be set with on a per-file-basis with
1788 #+STARTUP: logrepeat
1789 #+STARTUP: nologrepeat
1791 You can have local logging settings for a subtree by setting the LOGGING
1792 property to one or more of these keywords."
1793 :group 'org-todo
1794 :group 'org-progress
1795 :type 'boolean)
1797 (defcustom org-clock-into-drawer 2
1798 "Should clocking info be wrapped into a drawer?
1799 When t, clocking info will always be inserted into a :CLOCK: drawer.
1800 If necessary, the drawer will be created.
1801 When nil, the drawer will not be created, but used when present.
1802 When an integer and the number of clocking entries in an item
1803 reaches or exceeds this number, a drawer will be created."
1804 :group 'org-todo
1805 :group 'org-progress
1806 :type '(choice
1807 (const :tag "Always" t)
1808 (const :tag "Only when drawer exists" nil)
1809 (integer :tag "When at least N clock entries")))
1811 (defcustom org-clock-out-when-done t
1812 "When t, the clock will be stopped when the relevant entry is marked DONE.
1813 Nil means, clock will keep running until stopped explicitly with
1814 `C-c C-x C-o', or until the clock is started in a different item."
1815 :group 'org-progress
1816 :type 'boolean)
1818 (defcustom org-clock-in-switch-to-state nil
1819 "Set task to a special todo state while clocking it.
1820 The value should be the state to which the entry should be switched."
1821 :group 'org-progress
1822 :group 'org-todo
1823 :type '(choice
1824 (const :tag "Don't force a state" nil)
1825 (string :tag "State")))
1827 (defgroup org-priorities nil
1828 "Priorities in Org-mode."
1829 :tag "Org Priorities"
1830 :group 'org-todo)
1832 (defcustom org-highest-priority ?A
1833 "The highest priority of TODO items. A character like ?A, ?B etc.
1834 Must have a smaller ASCII number than `org-lowest-priority'."
1835 :group 'org-priorities
1836 :type 'character)
1838 (defcustom org-lowest-priority ?C
1839 "The lowest priority of TODO items. A character like ?A, ?B etc.
1840 Must have a larger ASCII number than `org-highest-priority'."
1841 :group 'org-priorities
1842 :type 'character)
1844 (defcustom org-default-priority ?B
1845 "The default priority of TODO items.
1846 This is the priority an item get if no explicit priority is given."
1847 :group 'org-priorities
1848 :type 'character)
1850 (defcustom org-priority-start-cycle-with-default t
1851 "Non-nil means, start with default priority when starting to cycle.
1852 When this is nil, the first step in the cycle will be (depending on the
1853 command used) one higher or lower that the default priority."
1854 :group 'org-priorities
1855 :type 'boolean)
1857 (defgroup org-time nil
1858 "Options concerning time stamps and deadlines in Org-mode."
1859 :tag "Org Time"
1860 :group 'org)
1862 (defcustom org-insert-labeled-timestamps-at-point nil
1863 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1864 When nil, these labeled time stamps are forces into the second line of an
1865 entry, just after the headline. When scheduling from the global TODO list,
1866 the time stamp will always be forced into the second line."
1867 :group 'org-time
1868 :type 'boolean)
1870 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1871 "Formats for `format-time-string' which are used for time stamps.
1872 It is not recommended to change this constant.")
1874 (defcustom org-time-stamp-rounding-minutes 0
1875 "Number of minutes to round time stamps to upon insertion.
1876 When zero, insert the time unmodified. Useful rounding numbers
1877 should be factors of 60, so for example 5, 10, 15.
1878 When this is not zero, you can still force an exact time-stamp by using
1879 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1880 :group 'org-time
1881 :type 'integer)
1883 (defcustom org-display-custom-times nil
1884 "Non-nil means, overlay custom formats over all time stamps.
1885 The formats are defined through the variable `org-time-stamp-custom-formats'.
1886 To turn this on on a per-file basis, insert anywhere in the file:
1887 #+STARTUP: customtime"
1888 :group 'org-time
1889 :set 'set-default
1890 :type 'sexp)
1891 (make-variable-buffer-local 'org-display-custom-times)
1893 (defcustom org-time-stamp-custom-formats
1894 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1895 "Custom formats for time stamps. See `format-time-string' for the syntax.
1896 These are overlayed over the default ISO format if the variable
1897 `org-display-custom-times' is set. Time like %H:%M should be at the
1898 end of the second format."
1899 :group 'org-time
1900 :type 'sexp)
1902 (defun org-time-stamp-format (&optional long inactive)
1903 "Get the right format for a time string."
1904 (let ((f (if long (cdr org-time-stamp-formats)
1905 (car org-time-stamp-formats))))
1906 (if inactive
1907 (concat "[" (substring f 1 -1) "]")
1908 f)))
1910 (defcustom org-read-date-prefer-future t
1911 "Non-nil means, assume future for incomplete date input from user.
1912 This affects the following situations:
1913 1. The user gives a day, but no month.
1914 For example, if today is the 15th, and you enter \"3\", Org-mode will
1915 read this as the third of *next* month. However, if you enter \"17\",
1916 it will be considered as *this* month.
1917 2. The user gives a month but not a year.
1918 For example, if it is april and you enter \"feb 2\", this will be read
1919 as feb 2, *next* year. \"May 5\", however, will be this year.
1921 When this option is nil, the current month and year will always be used
1922 as defaults."
1923 :group 'org-time
1924 :type 'boolean)
1926 (defcustom org-read-date-display-live t
1927 "Non-nil means, display current interpretation of date prompt live.
1928 This display will be in an overlay, in the minibuffer."
1929 :group 'org-time
1930 :type 'boolean)
1932 (defcustom org-read-date-popup-calendar t
1933 "Non-nil means, pop up a calendar when prompting for a date.
1934 In the calendar, the date can be selected with mouse-1. However, the
1935 minibuffer will also be active, and you can simply enter the date as well.
1936 When nil, only the minibuffer will be available."
1937 :group 'org-time
1938 :type 'boolean)
1939 (if (fboundp 'defvaralias)
1940 (defvaralias 'org-popup-calendar-for-date-prompt
1941 'org-read-date-popup-calendar))
1943 (defcustom org-extend-today-until 0
1944 "The hour when your day really ends.
1945 This has influence for the following applications:
1946 - When switching the agenda to \"today\". It it is still earlier than
1947 the time given here, the day recognized as TODAY is actually yesterday.
1948 - When a date is read from the user and it is still before the time given
1949 here, the current date and time will be assumed to be yesterday, 23:59.
1951 FIXME:
1952 IMPORTANT: This is still a very experimental feature, it may disappear
1953 again or it may be extended to mean more things."
1954 :group 'org-time
1955 :type 'number)
1957 (defcustom org-edit-timestamp-down-means-later nil
1958 "Non-nil means, S-down will increase the time in a time stamp.
1959 When nil, S-up will increase."
1960 :group 'org-time
1961 :type 'boolean)
1963 (defcustom org-calendar-follow-timestamp-change t
1964 "Non-nil means, make the calendar window follow timestamp changes.
1965 When a timestamp is modified and the calendar window is visible, it will be
1966 moved to the new date."
1967 :group 'org-time
1968 :type 'boolean)
1970 (defcustom org-clock-heading-function nil
1971 "When non-nil, should be a function to create `org-clock-heading'.
1972 This is the string shown in the mode line when a clock is running.
1973 The function is called with point at the beginning of the headline."
1974 :group 'org-time ; FIXME: Should we have a separate group????
1975 :type 'function)
1977 (defgroup org-tags nil
1978 "Options concerning tags in Org-mode."
1979 :tag "Org Tags"
1980 :group 'org)
1982 (defcustom org-tag-alist nil
1983 "List of tags allowed in Org-mode files.
1984 When this list is nil, Org-mode will base TAG input on what is already in the
1985 buffer.
1986 The value of this variable is an alist, the car of each entry must be a
1987 keyword as a string, the cdr may be a character that is used to select
1988 that tag through the fast-tag-selection interface.
1989 See the manual for details."
1990 :group 'org-tags
1991 :type '(repeat
1992 (choice
1993 (cons (string :tag "Tag name")
1994 (character :tag "Access char"))
1995 (const :tag "Start radio group" (:startgroup))
1996 (const :tag "End radio group" (:endgroup)))))
1998 (defcustom org-use-fast-tag-selection 'auto
1999 "Non-nil means, use fast tag selection scheme.
2000 This is a special interface to select and deselect tags with single keys.
2001 When nil, fast selection is never used.
2002 When the symbol `auto', fast selection is used if and only if selection
2003 characters for tags have been configured, either through the variable
2004 `org-tag-alist' or through a #+TAGS line in the buffer.
2005 When t, fast selection is always used and selection keys are assigned
2006 automatically if necessary."
2007 :group 'org-tags
2008 :type '(choice
2009 (const :tag "Always" t)
2010 (const :tag "Never" nil)
2011 (const :tag "When selection characters are configured" 'auto)))
2013 (defcustom org-fast-tag-selection-single-key nil
2014 "Non-nil means, fast tag selection exits after first change.
2015 When nil, you have to press RET to exit it.
2016 During fast tag selection, you can toggle this flag with `C-c'.
2017 This variable can also have the value `expert'. In this case, the window
2018 displaying the tags menu is not even shown, until you press C-c again."
2019 :group 'org-tags
2020 :type '(choice
2021 (const :tag "No" nil)
2022 (const :tag "Yes" t)
2023 (const :tag "Expert" expert)))
2025 (defvar org-fast-tag-selection-include-todo nil
2026 "Non-nil means, fast tags selection interface will also offer TODO states.
2027 This is an undocumented feature, you should not rely on it.")
2029 (defcustom org-tags-column -80
2030 "The column to which tags should be indented in a headline.
2031 If this number is positive, it specifies the column. If it is negative,
2032 it means that the tags should be flushright to that column. For example,
2033 -80 works well for a normal 80 character screen."
2034 :group 'org-tags
2035 :type 'integer)
2037 (defcustom org-auto-align-tags t
2038 "Non-nil means, realign tags after pro/demotion of TODO state change.
2039 These operations change the length of a headline and therefore shift
2040 the tags around. With this options turned on, after each such operation
2041 the tags are again aligned to `org-tags-column'."
2042 :group 'org-tags
2043 :type 'boolean)
2045 (defcustom org-use-tag-inheritance t
2046 "Non-nil means, tags in levels apply also for sublevels.
2047 When nil, only the tags directly given in a specific line apply there.
2048 If you turn off this option, you very likely want to turn on the
2049 companion option `org-tags-match-list-sublevels'."
2050 :group 'org-tags
2051 :type 'boolean)
2053 (defcustom org-tags-match-list-sublevels nil
2054 "Non-nil means list also sublevels of headlines matching tag search.
2055 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2056 the sublevels of a headline matching a tag search often also match
2057 the same search. Listing all of them can create very long lists.
2058 Setting this variable to nil causes subtrees of a match to be skipped.
2059 This option is off by default, because inheritance in on. If you turn
2060 inheritance off, you very likely want to turn this option on.
2062 As a special case, if the tag search is restricted to TODO items, the
2063 value of this variable is ignored and sublevels are always checked, to
2064 make sure all corresponding TODO items find their way into the list."
2065 :group 'org-tags
2066 :type 'boolean)
2068 (defvar org-tags-history nil
2069 "History of minibuffer reads for tags.")
2070 (defvar org-last-tags-completion-table nil
2071 "The last used completion table for tags.")
2072 (defvar org-after-tags-change-hook nil
2073 "Hook that is run after the tags in a line have changed.")
2075 (defgroup org-properties nil
2076 "Options concerning properties in Org-mode."
2077 :tag "Org Properties"
2078 :group 'org)
2080 (defcustom org-property-format "%-10s %s"
2081 "How property key/value pairs should be formatted by `indent-line'.
2082 When `indent-line' hits a property definition, it will format the line
2083 according to this format, mainly to make sure that the values are
2084 lined-up with respect to each other."
2085 :group 'org-properties
2086 :type 'string)
2088 (defcustom org-use-property-inheritance nil
2089 "Non-nil means, properties apply also for sublevels.
2090 This setting is only relevant during property searches, not when querying
2091 an entry with `org-entry-get'. To retrieve a property with inheritance,
2092 you need to call `org-entry-get' with the inheritance flag.
2093 Turning this on can cause significant overhead when doing a search, so
2094 this is turned off by default.
2095 When nil, only the properties directly given in the current entry count.
2096 The value may also be a list of properties that shouldhave inheritance.
2098 However, note that some special properties use inheritance under special
2099 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2100 and the properties ending in \"_ALL\" when they are used as descriptor
2101 for valid values of a property."
2102 :group 'org-properties
2103 :type '(choice
2104 (const :tag "Not" nil)
2105 (const :tag "Always" nil)
2106 (repeat :tag "Specific properties" (string :tag "Property"))))
2108 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2109 "The default column format, if no other format has been defined.
2110 This variable can be set on the per-file basis by inserting a line
2112 #+COLUMNS: %25ITEM ....."
2113 :group 'org-properties
2114 :type 'string)
2116 (defcustom org-global-properties nil
2117 "List of property/value pairs that can be inherited by any entry.
2118 You can set buffer-local values for this by adding lines like
2120 #+PROPERTY: NAME VALUE"
2121 :group 'org-properties
2122 :type '(repeat
2123 (cons (string :tag "Property")
2124 (string :tag "Value"))))
2126 (defvar org-local-properties nil
2127 "List of property/value pairs that can be inherited by any entry.
2128 Valid for the current buffer.
2129 This variable is populated from #+PROPERTY lines.")
2131 (defgroup org-agenda nil
2132 "Options concerning agenda views in Org-mode."
2133 :tag "Org Agenda"
2134 :group 'org)
2136 (defvar org-category nil
2137 "Variable used by org files to set a category for agenda display.
2138 Such files should use a file variable to set it, for example
2140 # -*- mode: org; org-category: \"ELisp\"
2142 or contain a special line
2144 #+CATEGORY: ELisp
2146 If the file does not specify a category, then file's base name
2147 is used instead.")
2148 (make-variable-buffer-local 'org-category)
2150 (defcustom org-agenda-files nil
2151 "The files to be used for agenda display.
2152 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2153 \\[org-remove-file]. You can also use customize to edit the list.
2155 If an entry is a directory, all files in that directory that are matched by
2156 `org-agenda-file-regexp' will be part of the file list.
2158 If the value of the variable is not a list but a single file name, then
2159 the list of agenda files is actually stored and maintained in that file, one
2160 agenda file per line."
2161 :group 'org-agenda
2162 :type '(choice
2163 (repeat :tag "List of files and directories" file)
2164 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2166 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2167 "Regular expression to match files for `org-agenda-files'.
2168 If any element in the list in that variable contains a directory instead
2169 of a normal file, all files in that directory that are matched by this
2170 regular expression will be included."
2171 :group 'org-agenda
2172 :type 'regexp)
2174 (defcustom org-agenda-skip-unavailable-files nil
2175 "t means to just skip non-reachable files in `org-agenda-files'.
2176 Nil means to remove them, after a query, from the list."
2177 :group 'org-agenda
2178 :type 'boolean)
2180 (defcustom org-agenda-multi-occur-extra-files nil
2181 "List of extra files to be searched by `org-occur-in-agenda-files'.
2182 The files in `org-agenda-files' are always searched."
2183 :group 'org-agenda
2184 :type '(repeat file))
2186 (defcustom org-agenda-confirm-kill 1
2187 "When set, remote killing from the agenda buffer needs confirmation.
2188 When t, a confirmation is always needed. When a number N, confirmation is
2189 only needed when the text to be killed contains more than N non-white lines."
2190 :group 'org-agenda
2191 :type '(choice
2192 (const :tag "Never" nil)
2193 (const :tag "Always" t)
2194 (number :tag "When more than N lines")))
2196 (defcustom org-calendar-to-agenda-key [?c]
2197 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2198 The command `org-calendar-goto-agenda' will be bound to this key. The
2199 default is the character `c' because then `c' can be used to switch back and
2200 forth between agenda and calendar."
2201 :group 'org-agenda
2202 :type 'sexp)
2204 (defcustom org-agenda-compact-blocks nil
2205 "Non-nil means, make the block agenda more compact.
2206 This is done by leaving out unnecessary lines."
2207 :group 'org-agenda
2208 :type nil)
2210 (defgroup org-agenda-export nil
2211 "Options concerning exporting agenda views in Org-mode."
2212 :tag "Org Agenda Export"
2213 :group 'org-agenda)
2215 (defcustom org-agenda-with-colors t
2216 "Non-nil means, use colors in agenda views."
2217 :group 'org-agenda-export
2218 :type 'boolean)
2220 (defcustom org-agenda-exporter-settings nil
2221 "Alist of variable/value pairs that should be active during agenda export.
2222 This is a good place to set uptions for ps-print and for htmlize."
2223 :group 'org-agenda-export
2224 :type '(repeat
2225 (list
2226 (variable)
2227 (sexp :tag "Value"))))
2229 (defcustom org-agenda-export-html-style ""
2230 "The style specification for exported HTML Agenda files.
2231 If this variable contains a string, it will replace the default <style>
2232 section as produced by `htmlize'.
2233 Since there are different ways of setting style information, this variable
2234 needs to contain the full HTML structure to provide a style, including the
2235 surrounding HTML tags. The style specifications should include definitions
2236 the fonts used by the agenda, here is an example:
2238 <style type=\"text/css\">
2239 p { font-weight: normal; color: gray; }
2240 .org-agenda-structure {
2241 font-size: 110%;
2242 color: #003399;
2243 font-weight: 600;
2245 .org-todo {
2246 color: #cc6666;Week-agenda:
2247 font-weight: bold;
2249 .org-done {
2250 color: #339933;
2252 .title { text-align: center; }
2253 .todo, .deadline { color: red; }
2254 .done { color: green; }
2255 </style>
2257 or, if you want to keep the style in a file,
2259 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2261 As the value of this option simply gets inserted into the HTML <head> header,
2262 you can \"misuse\" it to also add other text to the header. However,
2263 <style>...</style> is required, if not present the variable will be ignored."
2264 :group 'org-agenda-export
2265 :group 'org-export-html
2266 :type 'string)
2268 (defgroup org-agenda-custom-commands nil
2269 "Options concerning agenda views in Org-mode."
2270 :tag "Org Agenda Custom Commands"
2271 :group 'org-agenda)
2273 (defcustom org-agenda-custom-commands nil
2274 "Custom commands for the agenda.
2275 These commands will be offered on the splash screen displayed by the
2276 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2278 (key desc type match options files)
2280 key The key (one or more characters as a string) to be associated
2281 with the command.
2282 desc A description of the commend, when omitted or nil, a default
2283 description is built using MATCH.
2284 type The command type, any of the following symbols:
2285 todo Entries with a specific TODO keyword, in all agenda files.
2286 tags Tags match in all agenda files.
2287 tags-todo Tags match in all agenda files, TODO entries only.
2288 todo-tree Sparse tree of specific TODO keyword in *current* file.
2289 tags-tree Sparse tree with all tags matches in *current* file.
2290 occur-tree Occur sparse tree for *current* file.
2291 ... A user-defined function.
2292 match What to search for:
2293 - a single keyword for TODO keyword searches
2294 - a tags match expression for tags searches
2295 - a regular expression for occur searches
2296 options A list of option settings, similar to that in a let form, so like
2297 this: ((opt1 val1) (opt2 val2) ...)
2298 files A list of files file to write the produced agenda buffer to
2299 with the command `org-store-agenda-views'.
2300 If a file name ends in \".html\", an HTML version of the buffer
2301 is written out. If it ends in \".ps\", a postscript version is
2302 produced. Otherwide, only the plain text is written to the file.
2304 You can also define a set of commands, to create a composite agenda buffer.
2305 In this case, an entry looks like this:
2307 (key desc (cmd1 cmd2 ...) general-options file)
2309 where
2311 desc A description string to be displayed in the dispatcher menu.
2312 cmd An agenda command, similar to the above. However, tree commands
2313 are no allowed, but instead you can get agenda and global todo list.
2314 So valid commands for a set are:
2315 (agenda)
2316 (alltodo)
2317 (stuck)
2318 (todo \"match\" options files)
2319 (tags \"match\" options files)
2320 (tags-todo \"match\" options files)
2322 Each command can carry a list of options, and another set of options can be
2323 given for the whole set of commands. Individual command options take
2324 precedence over the general options.
2326 When using several characters as key to a command, the first characters
2327 are prefix commands. For the dispatcher to display useful information, you
2328 should provide a description for the prefix, like
2330 (setq org-agenda-custom-commands
2331 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2332 (\"hl\" tags \"+HOME+Lisa\")
2333 (\"hp\" tags \"+HOME+Peter\")
2334 (\"hk\" tags \"+HOME+Kim\")))"
2335 :group 'org-agenda-custom-commands
2336 :type '(repeat
2337 (choice :value ("a" "" tags "" nil)
2338 (list :tag "Single command"
2339 (string :tag "Access Key(s) ")
2340 (option (string :tag "Description"))
2341 (choice
2342 (const :tag "Agenda" agenda)
2343 (const :tag "TODO list" alltodo)
2344 (const :tag "Stuck projects" stuck)
2345 (const :tag "Tags search (all agenda files)" tags)
2346 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2347 (const :tag "TODO keyword search (all agenda files)" todo)
2348 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2349 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2350 (const :tag "Occur tree (current buffer)" occur-tree)
2351 (sexp :tag "Other, user-defined function"))
2352 (string :tag "Match")
2353 (repeat :tag "Local options"
2354 (list (variable :tag "Option") (sexp :tag "Value")))
2355 (option (repeat :tag "Export" (file :tag "Export to"))))
2356 (list :tag "Command series, all agenda files"
2357 (string :tag "Access Key(s)")
2358 (string :tag "Description ")
2359 (repeat
2360 (choice
2361 (const :tag "Agenda" (agenda))
2362 (const :tag "TODO list" (alltodo))
2363 (const :tag "Stuck projects" (stuck))
2364 (list :tag "Tags search"
2365 (const :format "" tags)
2366 (string :tag "Match")
2367 (repeat :tag "Local options"
2368 (list (variable :tag "Option")
2369 (sexp :tag "Value"))))
2371 (list :tag "Tags search, TODO entries only"
2372 (const :format "" tags-todo)
2373 (string :tag "Match")
2374 (repeat :tag "Local options"
2375 (list (variable :tag "Option")
2376 (sexp :tag "Value"))))
2378 (list :tag "TODO keyword search"
2379 (const :format "" todo)
2380 (string :tag "Match")
2381 (repeat :tag "Local options"
2382 (list (variable :tag "Option")
2383 (sexp :tag "Value"))))
2385 (list :tag "Other, user-defined function"
2386 (symbol :tag "function")
2387 (string :tag "Match")
2388 (repeat :tag "Local options"
2389 (list (variable :tag "Option")
2390 (sexp :tag "Value"))))))
2392 (repeat :tag "General options"
2393 (list (variable :tag "Option")
2394 (sexp :tag "Value")))
2395 (option (repeat :tag "Export" (file :tag "Export to"))))
2396 (cons :tag "Prefix key documentation"
2397 (string :tag "Access Key(s)")
2398 (string :tag "Description ")))))
2400 (defcustom org-stuck-projects
2401 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2402 "How to identify stuck projects.
2403 This is a list of four items:
2404 1. A tags/todo matcher string that is used to identify a project.
2405 The entire tree below a headline matched by this is considered one project.
2406 2. A list of TODO keywords identifying non-stuck projects.
2407 If the project subtree contains any headline with one of these todo
2408 keywords, the project is considered to be not stuck. If you specify
2409 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2410 3. A list of tags identifying non-stuck projects.
2411 If the project subtree contains any headline with one of these tags,
2412 the project is considered to be not stuck. If you specify \"*\" as
2413 a tag, any tag will mark the project unstuck.
2414 4. An arbitrary regular expression matching non-stuck projects.
2416 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2417 or `C-c a #' to produce the list."
2418 :group 'org-agenda-custom-commands
2419 :type '(list
2420 (string :tag "Tags/TODO match to identify a project")
2421 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2422 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2423 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2426 (defgroup org-agenda-skip nil
2427 "Options concerning skipping parts of agenda files."
2428 :tag "Org Agenda Skip"
2429 :group 'org-agenda)
2431 (defcustom org-agenda-todo-list-sublevels t
2432 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2433 When nil, the sublevels of a TODO entry are not checked, resulting in
2434 potentially much shorter TODO lists."
2435 :group 'org-agenda-skip
2436 :group 'org-todo
2437 :type 'boolean)
2439 (defcustom org-agenda-todo-ignore-with-date nil
2440 "Non-nil means, don't show entries with a date in the global todo list.
2441 You can use this if you prefer to mark mere appointments with a TODO keyword,
2442 but don't want them to show up in the TODO list.
2443 When this is set, it also covers deadlines and scheduled items, the settings
2444 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2445 will be ignored."
2446 :group 'org-agenda-skip
2447 :group 'org-todo
2448 :type 'boolean)
2450 (defcustom org-agenda-todo-ignore-scheduled nil
2451 "Non-nil means, don't show scheduled entries in the global todo list.
2452 The idea behind this is that by scheduling it, you have already taken care
2453 of this item.
2454 See also `org-agenda-todo-ignore-with-date'."
2455 :group 'org-agenda-skip
2456 :group 'org-todo
2457 :type 'boolean)
2459 (defcustom org-agenda-todo-ignore-deadlines nil
2460 "Non-nil means, don't show near deadline entries in the global todo list.
2461 Near means closer than `org-deadline-warning-days' days.
2462 The idea behind this is that such items will appear in the agenda anyway.
2463 See also `org-agenda-todo-ignore-with-date'."
2464 :group 'org-agenda-skip
2465 :group 'org-todo
2466 :type 'boolean)
2468 (defcustom org-agenda-skip-scheduled-if-done nil
2469 "Non-nil means don't show scheduled items in agenda when they are done.
2470 This is relevant for the daily/weekly agenda, not for the TODO list. And
2471 it applies only to the actual date of the scheduling. Warnings about
2472 an item with a past scheduling dates are always turned off when the item
2473 is DONE."
2474 :group 'org-agenda-skip
2475 :type 'boolean)
2477 (defcustom org-agenda-skip-deadline-if-done nil
2478 "Non-nil means don't show deadines when the corresponding item is done.
2479 When nil, the deadline is still shown and should give you a happy feeling.
2480 This is relevant for the daily/weekly agenda. And it applied only to the
2481 actualy date of the deadline. Warnings about approching and past-due
2482 deadlines are always turned off when the item is DONE."
2483 :group 'org-agenda-skip
2484 :type 'boolean)
2486 (defcustom org-agenda-skip-timestamp-if-done nil
2487 "Non-nil means don't select item by timestamp or -range if it is DONE."
2488 :group 'org-agenda-skip
2489 :type 'boolean)
2491 (defcustom org-timeline-show-empty-dates 3
2492 "Non-nil means, `org-timeline' also shows dates without an entry.
2493 When nil, only the days which actually have entries are shown.
2494 When t, all days between the first and the last date are shown.
2495 When an integer, show also empty dates, but if there is a gap of more than
2496 N days, just insert a special line indicating the size of the gap."
2497 :group 'org-agenda-skip
2498 :type '(choice
2499 (const :tag "None" nil)
2500 (const :tag "All" t)
2501 (number :tag "at most")))
2504 (defgroup org-agenda-startup nil
2505 "Options concerning initial settings in the Agenda in Org Mode."
2506 :tag "Org Agenda Startup"
2507 :group 'org-agenda)
2509 (defcustom org-finalize-agenda-hook nil
2510 "Hook run just before displaying an agenda buffer."
2511 :group 'org-agenda-startup
2512 :type 'hook)
2514 (defcustom org-agenda-mouse-1-follows-link nil
2515 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2516 A longer mouse click will still set point. Does not wortk on XEmacs.
2517 Needs to be set before org.el is loaded."
2518 :group 'org-agenda-startup
2519 :type 'boolean)
2521 (defcustom org-agenda-start-with-follow-mode nil
2522 "The initial value of follow-mode in a newly created agenda window."
2523 :group 'org-agenda-startup
2524 :type 'boolean)
2526 (defgroup org-agenda-windows nil
2527 "Options concerning the windows used by the Agenda in Org Mode."
2528 :tag "Org Agenda Windows"
2529 :group 'org-agenda)
2531 (defcustom org-agenda-window-setup 'reorganize-frame
2532 "How the agenda buffer should be displayed.
2533 Possible values for this option are:
2535 current-window Show agenda in the current window, keeping all other windows.
2536 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2537 other-window Use `switch-to-buffer-other-window' to display agenda.
2538 reorganize-frame Show only two windows on the current frame, the current
2539 window and the agenda.
2540 See also the variable `org-agenda-restore-windows-after-quit'."
2541 :group 'org-agenda-windows
2542 :type '(choice
2543 (const current-window)
2544 (const other-frame)
2545 (const other-window)
2546 (const reorganize-frame)))
2548 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2549 "The min and max height of the agenda window as a fraction of frame height.
2550 The value of the variable is a cons cell with two numbers between 0 and 1.
2551 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2552 :group 'org-agenda-windows
2553 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2555 (defcustom org-agenda-restore-windows-after-quit nil
2556 "Non-nil means, restore window configuration open exiting agenda.
2557 Before the window configuration is changed for displaying the agenda,
2558 the current status is recorded. When the agenda is exited with
2559 `q' or `x' and this option is set, the old state is restored. If
2560 `org-agenda-window-setup' is `other-frame', the value of this
2561 option will be ignored.."
2562 :group 'org-agenda-windows
2563 :type 'boolean)
2565 (defcustom org-indirect-buffer-display 'other-window
2566 "How should indirect tree buffers be displayed?
2567 This applies to indirect buffers created with the commands
2568 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2569 Valid values are:
2570 current-window Display in the current window
2571 other-window Just display in another window.
2572 dedicated-frame Create one new frame, and re-use it each time.
2573 new-frame Make a new frame each time. Note that in this case
2574 previously-made indirect buffers are kept, and you need to
2575 kill these buffers yourself."
2576 :group 'org-structure
2577 :group 'org-agenda-windows
2578 :type '(choice
2579 (const :tag "In current window" current-window)
2580 (const :tag "In current frame, other window" other-window)
2581 (const :tag "Each time a new frame" new-frame)
2582 (const :tag "One dedicated frame" dedicated-frame)))
2584 (defgroup org-agenda-daily/weekly nil
2585 "Options concerning the daily/weekly agenda."
2586 :tag "Org Agenda Daily/Weekly"
2587 :group 'org-agenda)
2589 (defcustom org-agenda-ndays 7
2590 "Number of days to include in overview display.
2591 Should be 1 or 7."
2592 :group 'org-agenda-daily/weekly
2593 :type 'number)
2595 (defcustom org-agenda-start-on-weekday 1
2596 "Non-nil means, start the overview always on the specified weekday.
2597 0 denotes Sunday, 1 denotes Monday etc.
2598 When nil, always start on the current day."
2599 :group 'org-agenda-daily/weekly
2600 :type '(choice (const :tag "Today" nil)
2601 (number :tag "Weekday No.")))
2603 (defcustom org-agenda-show-all-dates t
2604 "Non-nil means, `org-agenda' shows every day in the selected range.
2605 When nil, only the days which actually have entries are shown."
2606 :group 'org-agenda-daily/weekly
2607 :type 'boolean)
2609 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2610 "Format string for displaying dates in the agenda.
2611 Used by the daily/weekly agenda and by the timeline. This should be
2612 a format string understood by `format-time-string', or a function returning
2613 the formatted date as a string. The function must take a single argument,
2614 a calendar-style date list like (month day year)."
2615 :group 'org-agenda-daily/weekly
2616 :type '(choice
2617 (string :tag "Format string")
2618 (function :tag "Function")))
2620 (defun org-agenda-format-date-aligned (date)
2621 "Format a date string for display in the daily/weekly agenda, or timeline.
2622 This function makes sure that dates are aligned for easy reading."
2623 (format "%-9s %2d %s %4d"
2624 (calendar-day-name date)
2625 (extract-calendar-day date)
2626 (calendar-month-name (extract-calendar-month date))
2627 (extract-calendar-year date)))
2629 (defcustom org-agenda-include-diary nil
2630 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2631 :group 'org-agenda-daily/weekly
2632 :type 'boolean)
2634 (defcustom org-agenda-include-all-todo nil
2635 "Set means weekly/daily agenda will always contain all TODO entries.
2636 The TODO entries will be listed at the top of the agenda, before
2637 the entries for specific days."
2638 :group 'org-agenda-daily/weekly
2639 :type 'boolean)
2641 (defcustom org-agenda-repeating-timestamp-show-all t
2642 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2643 When nil, only one occurence is shown, either today or the
2644 nearest into the future."
2645 :group 'org-agenda-daily/weekly
2646 :type 'boolean)
2648 (defcustom org-deadline-warning-days 14
2649 "No. of days before expiration during which a deadline becomes active.
2650 This variable governs the display in sparse trees and in the agenda.
2651 When negative, it means use this number (the absolute value of it)
2652 even if a deadline has a different individual lead time specified."
2653 :group 'org-time
2654 :group 'org-agenda-daily/weekly
2655 :type 'number)
2657 (defcustom org-scheduled-past-days 10000
2658 "No. of days to continue listing scheduled items that are not marked DONE.
2659 When an item is scheduled on a date, it shows up in the agenda on this
2660 day and will be listed until it is marked done for the number of days
2661 given here."
2662 :group 'org-agenda-daily/weekly
2663 :type 'number)
2665 (defgroup org-agenda-time-grid nil
2666 "Options concerning the time grid in the Org-mode Agenda."
2667 :tag "Org Agenda Time Grid"
2668 :group 'org-agenda)
2670 (defcustom org-agenda-use-time-grid t
2671 "Non-nil means, show a time grid in the agenda schedule.
2672 A time grid is a set of lines for specific times (like every two hours between
2673 8:00 and 20:00). The items scheduled for a day at specific times are
2674 sorted in between these lines.
2675 For details about when the grid will be shown, and what it will look like, see
2676 the variable `org-agenda-time-grid'."
2677 :group 'org-agenda-time-grid
2678 :type 'boolean)
2680 (defcustom org-agenda-time-grid
2681 '((daily today require-timed)
2682 "----------------"
2683 (800 1000 1200 1400 1600 1800 2000))
2685 "The settings for time grid for agenda display.
2686 This is a list of three items. The first item is again a list. It contains
2687 symbols specifying conditions when the grid should be displayed:
2689 daily if the agenda shows a single day
2690 weekly if the agenda shows an entire week
2691 today show grid on current date, independent of daily/weekly display
2692 require-timed show grid only if at least one item has a time specification
2694 The second item is a string which will be places behing the grid time.
2696 The third item is a list of integers, indicating the times that should have
2697 a grid line."
2698 :group 'org-agenda-time-grid
2699 :type
2700 '(list
2701 (set :greedy t :tag "Grid Display Options"
2702 (const :tag "Show grid in single day agenda display" daily)
2703 (const :tag "Show grid in weekly agenda display" weekly)
2704 (const :tag "Always show grid for today" today)
2705 (const :tag "Show grid only if any timed entries are present"
2706 require-timed)
2707 (const :tag "Skip grid times already present in an entry"
2708 remove-match))
2709 (string :tag "Grid String")
2710 (repeat :tag "Grid Times" (integer :tag "Time"))))
2712 (defgroup org-agenda-sorting nil
2713 "Options concerning sorting in the Org-mode Agenda."
2714 :tag "Org Agenda Sorting"
2715 :group 'org-agenda)
2717 (defconst org-sorting-choice
2718 '(choice
2719 (const time-up) (const time-down)
2720 (const category-keep) (const category-up) (const category-down)
2721 (const tag-down) (const tag-up)
2722 (const priority-up) (const priority-down))
2723 "Sorting choices.")
2725 (defcustom org-agenda-sorting-strategy
2726 '((agenda time-up category-keep priority-down)
2727 (todo category-keep priority-down)
2728 (tags category-keep priority-down))
2729 "Sorting structure for the agenda items of a single day.
2730 This is a list of symbols which will be used in sequence to determine
2731 if an entry should be listed before another entry. The following
2732 symbols are recognized:
2734 time-up Put entries with time-of-day indications first, early first
2735 time-down Put entries with time-of-day indications first, late first
2736 category-keep Keep the default order of categories, corresponding to the
2737 sequence in `org-agenda-files'.
2738 category-up Sort alphabetically by category, A-Z.
2739 category-down Sort alphabetically by category, Z-A.
2740 tag-up Sort alphabetically by last tag, A-Z.
2741 tag-down Sort alphabetically by last tag, Z-A.
2742 priority-up Sort numerically by priority, high priority last.
2743 priority-down Sort numerically by priority, high priority first.
2745 The different possibilities will be tried in sequence, and testing stops
2746 if one comparison returns a \"not-equal\". For example, the default
2747 '(time-up category-keep priority-down)
2748 means: Pull out all entries having a specified time of day and sort them,
2749 in order to make a time schedule for the current day the first thing in the
2750 agenda listing for the day. Of the entries without a time indication, keep
2751 the grouped in categories, don't sort the categories, but keep them in
2752 the sequence given in `org-agenda-files'. Within each category sort by
2753 priority.
2755 Leaving out `category-keep' would mean that items will be sorted across
2756 categories by priority.
2758 Instead of a single list, this can also be a set of list for specific
2759 contents, with a context symbol in the car of the list, any of
2760 `agenda', `todo', `tags' for the corresponding agenda views."
2761 :group 'org-agenda-sorting
2762 :type `(choice
2763 (repeat :tag "General" ,org-sorting-choice)
2764 (list :tag "Individually"
2765 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2766 (repeat ,org-sorting-choice))
2767 (cons (const :tag "Strategy for TODO lists" todo)
2768 (repeat ,org-sorting-choice))
2769 (cons (const :tag "Strategy for Tags matches" tags)
2770 (repeat ,org-sorting-choice)))))
2772 (defcustom org-sort-agenda-notime-is-late t
2773 "Non-nil means, items without time are considered late.
2774 This is only relevant for sorting. When t, items which have no explicit
2775 time like 15:30 will be considered as 99:01, i.e. later than any items which
2776 do have a time. When nil, the default time is before 0:00. You can use this
2777 option to decide if the schedule for today should come before or after timeless
2778 agenda entries."
2779 :group 'org-agenda-sorting
2780 :type 'boolean)
2782 (defgroup org-agenda-line-format nil
2783 "Options concerning the entry prefix in the Org-mode agenda display."
2784 :tag "Org Agenda Line Format"
2785 :group 'org-agenda)
2787 (defcustom org-agenda-prefix-format
2788 '((agenda . " %-12:c%?-12t% s")
2789 (timeline . " % s")
2790 (todo . " %-12:c")
2791 (tags . " %-12:c"))
2792 "Format specifications for the prefix of items in the agenda views.
2793 An alist with four entries, for the different agenda types. The keys to the
2794 sublists are `agenda', `timeline', `todo', and `tags'. The values
2795 are format strings.
2796 This format works similar to a printf format, with the following meaning:
2798 %c the category of the item, \"Diary\" for entries from the diary, or
2799 as given by the CATEGORY keyword or derived from the file name.
2800 %T the *last* tag of the item. Last because inherited tags come
2801 first in the list.
2802 %t the time-of-day specification if one applies to the entry, in the
2803 format HH:MM
2804 %s Scheduling/Deadline information, a short string
2806 All specifiers work basically like the standard `%s' of printf, but may
2807 contain two additional characters: A question mark just after the `%' and
2808 a whitespace/punctuation character just before the final letter.
2810 If the first character after `%' is a question mark, the entire field
2811 will only be included if the corresponding value applies to the
2812 current entry. This is useful for fields which should have fixed
2813 width when present, but zero width when absent. For example,
2814 \"%?-12t\" will result in a 12 character time field if a time of the
2815 day is specified, but will completely disappear in entries which do
2816 not contain a time.
2818 If there is punctuation or whitespace character just before the final
2819 format letter, this character will be appended to the field value if
2820 the value is not empty. For example, the format \"%-12:c\" leads to
2821 \"Diary: \" if the category is \"Diary\". If the category were be
2822 empty, no additional colon would be interted.
2824 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2825 - Indent the line with two space characters
2826 - Give the category in a 12 chars wide field, padded with whitespace on
2827 the right (because of `-'). Append a colon if there is a category
2828 (because of `:').
2829 - If there is a time-of-day, put it into a 12 chars wide field. If no
2830 time, don't put in an empty field, just skip it (because of '?').
2831 - Finally, put the scheduling information and append a whitespace.
2833 As another example, if you don't want the time-of-day of entries in
2834 the prefix, you could use:
2836 (setq org-agenda-prefix-format \" %-11:c% s\")
2838 See also the variables `org-agenda-remove-times-when-in-prefix' and
2839 `org-agenda-remove-tags'."
2840 :type '(choice
2841 (string :tag "General format")
2842 (list :greedy t :tag "View dependent"
2843 (cons (const agenda) (string :tag "Format"))
2844 (cons (const timeline) (string :tag "Format"))
2845 (cons (const todo) (string :tag "Format"))
2846 (cons (const tags) (string :tag "Format"))))
2847 :group 'org-agenda-line-format)
2849 (defvar org-prefix-format-compiled nil
2850 "The compiled version of the most recently used prefix format.
2851 See the variable `org-agenda-prefix-format'.")
2853 (defcustom org-agenda-todo-keyword-format "%-1s"
2854 "Format for the TODO keyword in agenda lines.
2855 Set this to something like \"%-12s\" if you want all TODO keywords
2856 to occupy a fixed space in the agenda display."
2857 :group 'org-agenda-line-format
2858 :type 'string)
2860 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2861 "Text preceeding scheduled items in the agenda view.
2862 This is a list with two strings. The first applies when the item is
2863 scheduled on the current day. The second applies when it has been scheduled
2864 previously, it may contain a %d to capture how many days ago the item was
2865 scheduled."
2866 :group 'org-agenda-line-format
2867 :type '(list
2868 (string :tag "Scheduled today ")
2869 (string :tag "Scheduled previously")))
2871 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2872 "Text preceeding deadline items in the agenda view.
2873 This is a list with two strings. The first applies when the item has its
2874 deadline on the current day. The second applies when it is in the past or
2875 in the future, it may contain %d to capture how many days away the deadline
2876 is (was)."
2877 :group 'org-agenda-line-format
2878 :type '(list
2879 (string :tag "Deadline today ")
2880 (string :tag "Deadline relative")))
2882 (defcustom org-agenda-remove-times-when-in-prefix t
2883 "Non-nil means, remove duplicate time specifications in agenda items.
2884 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2885 time-of-day specification in a headline or diary entry is extracted and
2886 placed into the prefix. If this option is non-nil, the original specification
2887 \(a timestamp or -range, or just a plain time(range) specification like
2888 11:30-4pm) will be removed for agenda display. This makes the agenda less
2889 cluttered.
2890 The option can be t or nil. It may also be the symbol `beg', indicating
2891 that the time should only be removed what it is located at the beginning of
2892 the headline/diary entry."
2893 :group 'org-agenda-line-format
2894 :type '(choice
2895 (const :tag "Always" t)
2896 (const :tag "Never" nil)
2897 (const :tag "When at beginning of entry" beg)))
2900 (defcustom org-agenda-default-appointment-duration nil
2901 "Default duration for appointments that only have a starting time.
2902 When nil, no duration is specified in such cases.
2903 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2904 :group 'org-agenda-line-format
2905 :type '(choice
2906 (integer :tag "Minutes")
2907 (const :tag "No default duration")))
2910 (defcustom org-agenda-remove-tags nil
2911 "Non-nil means, remove the tags from the headline copy in the agenda.
2912 When this is the symbol `prefix', only remove tags when
2913 `org-agenda-prefix-format' contains a `%T' specifier."
2914 :group 'org-agenda-line-format
2915 :type '(choice
2916 (const :tag "Always" t)
2917 (const :tag "Never" nil)
2918 (const :tag "When prefix format contains %T" prefix)))
2920 (if (fboundp 'defvaralias)
2921 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2922 'org-agenda-remove-tags))
2924 (defcustom org-agenda-tags-column -80
2925 "Shift tags in agenda items to this column.
2926 If this number is positive, it specifies the column. If it is negative,
2927 it means that the tags should be flushright to that column. For example,
2928 -80 works well for a normal 80 character screen."
2929 :group 'org-agenda-line-format
2930 :type 'integer)
2932 (if (fboundp 'defvaralias)
2933 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2935 (defcustom org-agenda-fontify-priorities t
2936 "Non-nil means, highlight low and high priorities in agenda.
2937 When t, the highest priority entries are bold, lowest priority italic.
2938 This may also be an association list of priority faces. The face may be
2939 a names face, or a list like `(:background \"Red\")'."
2940 :group 'org-agenda-line-format
2941 :type '(choice
2942 (const :tag "Never" nil)
2943 (const :tag "Defaults" t)
2944 (repeat :tag "Specify"
2945 (list (character :tag "Priority" :value ?A)
2946 (sexp :tag "face")))))
2948 (defgroup org-latex nil
2949 "Options for embedding LaTeX code into Org-mode"
2950 :tag "Org LaTeX"
2951 :group 'org)
2953 (defcustom org-format-latex-options
2954 '(:foreground default :background default :scale 1.0
2955 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2956 :matchers ("begin" "$" "$$" "\\(" "\\["))
2957 "Options for creating images from LaTeX fragments.
2958 This is a property list with the following properties:
2959 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2960 `default' means use the forground of the default face.
2961 :background the background color, or \"Transparent\".
2962 `default' means use the background of the default face.
2963 :scale a scaling factor for the size of the images
2964 :html-foreground, :html-background, :html-scale
2965 The same numbers for HTML export.
2966 :matchers a list indicating which matchers should be used to
2967 find LaTeX fragments. Valid members of this list are:
2968 \"begin\" find environments
2969 \"$\" find math expressions surrounded by $...$
2970 \"$$\" find math expressions surrounded by $$....$$
2971 \"\\(\" find math expressions surrounded by \\(...\\)
2972 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2973 :group 'org-latex
2974 :type 'plist)
2976 (defcustom org-format-latex-header "\\documentclass{article}
2977 \\usepackage{fullpage} % do not remove
2978 \\usepackage{amssymb}
2979 \\usepackage[usenames]{color}
2980 \\usepackage{amsmath}
2981 \\usepackage{latexsym}
2982 \\usepackage[mathscr]{eucal}
2983 \\pagestyle{empty} % do not remove"
2984 "The document header used for processing LaTeX fragments."
2985 :group 'org-latex
2986 :type 'string)
2988 (defgroup org-export nil
2989 "Options for exporting org-listings."
2990 :tag "Org Export"
2991 :group 'org)
2993 (defgroup org-export-general nil
2994 "General options for exporting Org-mode files."
2995 :tag "Org Export General"
2996 :group 'org-export)
2998 ;; FIXME
2999 (defvar org-export-publishing-directory nil)
3001 (defcustom org-export-with-special-strings t
3002 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3003 When this option is turned on, these strings will be exported as:
3005 Org HTML LaTeX
3006 -----+----------+--------
3007 \\- &shy; \\-
3008 -- &ndash; --
3009 --- &mdash; ---
3010 ... &hellip; \ldots
3012 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3013 :group 'org-export-translation
3014 :type 'boolean)
3016 (defcustom org-export-language-setup
3017 '(("en" "Author" "Date" "Table of Contents")
3018 ("cs" "Autor" "Datum" "Obsah")
3019 ("da" "Ophavsmand" "Dato" "Indhold")
3020 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3021 ("es" "Autor" "Fecha" "\xcdndice")
3022 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3023 ("it" "Autore" "Data" "Indice")
3024 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3025 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3026 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3027 "Terms used in export text, translated to different languages.
3028 Use the variable `org-export-default-language' to set the language,
3029 or use the +OPTION lines for a per-file setting."
3030 :group 'org-export-general
3031 :type '(repeat
3032 (list
3033 (string :tag "HTML language tag")
3034 (string :tag "Author")
3035 (string :tag "Date")
3036 (string :tag "Table of Contents"))))
3038 (defcustom org-export-default-language "en"
3039 "The default language of HTML export, as a string.
3040 This should have an association in `org-export-language-setup'."
3041 :group 'org-export-general
3042 :type 'string)
3044 (defcustom org-export-skip-text-before-1st-heading t
3045 "Non-nil means, skip all text before the first headline when exporting.
3046 When nil, that text is exported as well."
3047 :group 'org-export-general
3048 :type 'boolean)
3050 (defcustom org-export-headline-levels 3
3051 "The last level which is still exported as a headline.
3052 Inferior levels will produce itemize lists when exported.
3053 Note that a numeric prefix argument to an exporter function overrides
3054 this setting.
3056 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3057 :group 'org-export-general
3058 :type 'number)
3060 (defcustom org-export-with-section-numbers t
3061 "Non-nil means, add section numbers to headlines when exporting.
3063 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3064 :group 'org-export-general
3065 :type 'boolean)
3067 (defcustom org-export-with-toc t
3068 "Non-nil means, create a table of contents in exported files.
3069 The TOC contains headlines with levels up to`org-export-headline-levels'.
3070 When an integer, include levels up to N in the toc, this may then be
3071 different from `org-export-headline-levels', but it will not be allowed
3072 to be larger than the number of headline levels.
3073 When nil, no table of contents is made.
3075 Headlines which contain any TODO items will be marked with \"(*)\" in
3076 ASCII export, and with red color in HTML output, if the option
3077 `org-export-mark-todo-in-toc' is set.
3079 In HTML output, the TOC will be clickable.
3081 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3082 or \"toc:3\"."
3083 :group 'org-export-general
3084 :type '(choice
3085 (const :tag "No Table of Contents" nil)
3086 (const :tag "Full Table of Contents" t)
3087 (integer :tag "TOC to level")))
3089 (defcustom org-export-mark-todo-in-toc nil
3090 "Non-nil means, mark TOC lines that contain any open TODO items."
3091 :group 'org-export-general
3092 :type 'boolean)
3094 (defcustom org-export-preserve-breaks nil
3095 "Non-nil means, preserve all line breaks when exporting.
3096 Normally, in HTML output paragraphs will be reformatted. In ASCII
3097 export, line breaks will always be preserved, regardless of this variable.
3099 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3100 :group 'org-export-general
3101 :type 'boolean)
3103 (defcustom org-export-with-archived-trees 'headline
3104 "Whether subtrees with the ARCHIVE tag should be exported.
3105 This can have three different values
3106 nil Do not export, pretend this tree is not present
3107 t Do export the entire tree
3108 headline Only export the headline, but skip the tree below it."
3109 :group 'org-export-general
3110 :group 'org-archive
3111 :type '(choice
3112 (const :tag "not at all" nil)
3113 (const :tag "headline only" 'headline)
3114 (const :tag "entirely" t)))
3116 (defcustom org-export-author-info t
3117 "Non-nil means, insert author name and email into the exported file.
3119 This option can also be set with the +OPTIONS line,
3120 e.g. \"author-info:nil\"."
3121 :group 'org-export-general
3122 :type 'boolean)
3124 (defcustom org-export-time-stamp-file t
3125 "Non-nil means, insert a time stamp into the exported file.
3126 The time stamp shows when the file was created.
3128 This option can also be set with the +OPTIONS line,
3129 e.g. \"timestamp:nil\"."
3130 :group 'org-export-general
3131 :type 'boolean)
3133 (defcustom org-export-with-timestamps t
3134 "If nil, do not export time stamps and associated keywords."
3135 :group 'org-export-general
3136 :type 'boolean)
3138 (defcustom org-export-remove-timestamps-from-toc t
3139 "If nil, remove timestamps from the table of contents entries."
3140 :group 'org-export-general
3141 :type 'boolean)
3143 (defcustom org-export-with-tags 'not-in-toc
3144 "If nil, do not export tags, just remove them from headlines.
3145 If this is the symbol `not-in-toc', tags will be removed from table of
3146 contents entries, but still be shown in the headlines of the document.
3148 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3149 :group 'org-export-general
3150 :type '(choice
3151 (const :tag "Off" nil)
3152 (const :tag "Not in TOC" not-in-toc)
3153 (const :tag "On" t)))
3155 (defcustom org-export-with-drawers nil
3156 "Non-nil means, export with drawers like the property drawer.
3157 When t, all drawers are exported. This may also be a list of
3158 drawer names to export."
3159 :group 'org-export-general
3160 :type '(choice
3161 (const :tag "All drawers" t)
3162 (const :tag "None" nil)
3163 (repeat :tag "Selected drawers"
3164 (string :tag "Drawer name"))))
3166 (defgroup org-export-translation nil
3167 "Options for translating special ascii sequences for the export backends."
3168 :tag "Org Export Translation"
3169 :group 'org-export)
3171 (defcustom org-export-with-emphasize t
3172 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3173 If the export target supports emphasizing text, the word will be
3174 typeset in bold, italic, or underlined, respectively. Works only for
3175 single words, but you can say: I *really* *mean* *this*.
3176 Not all export backends support this.
3178 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3179 :group 'org-export-translation
3180 :type 'boolean)
3182 (defcustom org-export-with-footnotes t
3183 "If nil, export [1] as a footnote marker.
3184 Lines starting with [1] will be formatted as footnotes.
3186 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3187 :group 'org-export-translation
3188 :type 'boolean)
3190 (defcustom org-export-with-sub-superscripts t
3191 "Non-nil means, interpret \"_\" and \"^\" for export.
3192 When this option is turned on, you can use TeX-like syntax for sub- and
3193 superscripts. Several characters after \"_\" or \"^\" will be
3194 considered as a single item - so grouping with {} is normally not
3195 needed. For example, the following things will be parsed as single
3196 sub- or superscripts.
3198 10^24 or 10^tau several digits will be considered 1 item.
3199 10^-12 or 10^-tau a leading sign with digits or a word
3200 x^2-y^3 will be read as x^2 - y^3, because items are
3201 terminated by almost any nonword/nondigit char.
3202 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3204 Still, ambiguity is possible - so when in doubt use {} to enclose the
3205 sub/superscript. If you set this variable to the symbol `{}',
3206 the braces are *required* in order to trigger interpretations as
3207 sub/superscript. This can be helpful in documents that need \"_\"
3208 frequently in plain text.
3210 Not all export backends support this, but HTML does.
3212 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3213 :group 'org-export-translation
3214 :type '(choice
3215 (const :tag "Always interpret" t)
3216 (const :tag "Only with braces" {})
3217 (const :tag "Never interpret" nil)))
3219 (defcustom org-export-with-special-strings t
3220 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3221 When this option is turned on, these strings will be exported as:
3223 \\- : &shy;
3224 -- : &ndash;
3225 --- : &mdash;
3227 Not all export backends support this, but HTML does.
3229 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3230 :group 'org-export-translation
3231 :type 'boolean)
3233 (defcustom org-export-with-TeX-macros t
3234 "Non-nil means, interpret simple TeX-like macros when exporting.
3235 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3236 No only real TeX macros will work here, but the standard HTML entities
3237 for math can be used as macro names as well. For a list of supported
3238 names in HTML export, see the constant `org-html-entities'.
3239 Not all export backends support this.
3241 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3242 :group 'org-export-translation
3243 :group 'org-export-latex
3244 :type 'boolean)
3246 (defcustom org-export-with-LaTeX-fragments nil
3247 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3248 When set, the exporter will find LaTeX environments if the \\begin line is
3249 the first non-white thing on a line. It will also find the math delimiters
3250 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3251 display math.
3253 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3254 :group 'org-export-translation
3255 :group 'org-export-latex
3256 :type 'boolean)
3258 (defcustom org-export-with-fixed-width t
3259 "Non-nil means, lines starting with \":\" will be in fixed width font.
3260 This can be used to have pre-formatted text, fragments of code etc. For
3261 example:
3262 : ;; Some Lisp examples
3263 : (while (defc cnt)
3264 : (ding))
3265 will be looking just like this in also HTML. See also the QUOTE keyword.
3266 Not all export backends support this.
3268 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3269 :group 'org-export-translation
3270 :type 'boolean)
3272 (defcustom org-match-sexp-depth 3
3273 "Number of stacked braces for sub/superscript matching.
3274 This has to be set before loading org.el to be effective."
3275 :group 'org-export-translation
3276 :type 'integer)
3278 (defgroup org-export-tables nil
3279 "Options for exporting tables in Org-mode."
3280 :tag "Org Export Tables"
3281 :group 'org-export)
3283 (defcustom org-export-with-tables t
3284 "If non-nil, lines starting with \"|\" define a table.
3285 For example:
3287 | Name | Address | Birthday |
3288 |-------------+----------+-----------|
3289 | Arthur Dent | England | 29.2.2100 |
3291 Not all export backends support this.
3293 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3294 :group 'org-export-tables
3295 :type 'boolean)
3297 (defcustom org-export-highlight-first-table-line t
3298 "Non-nil means, highlight the first table line.
3299 In HTML export, this means use <th> instead of <td>.
3300 In tables created with table.el, this applies to the first table line.
3301 In Org-mode tables, all lines before the first horizontal separator
3302 line will be formatted with <th> tags."
3303 :group 'org-export-tables
3304 :type 'boolean)
3306 (defcustom org-export-table-remove-special-lines t
3307 "Remove special lines and marking characters in calculating tables.
3308 This removes the special marking character column from tables that are set
3309 up for spreadsheet calculations. It also removes the entire lines
3310 marked with `!', `_', or `^'. The lines with `$' are kept, because
3311 the values of constants may be useful to have."
3312 :group 'org-export-tables
3313 :type 'boolean)
3315 (defcustom org-export-prefer-native-exporter-for-tables nil
3316 "Non-nil means, always export tables created with table.el natively.
3317 Natively means, use the HTML code generator in table.el.
3318 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3319 the table does not use row- or column-spanning). This has the
3320 advantage, that the automatic HTML conversions for math symbols and
3321 sub/superscripts can be applied. Org-mode's HTML generator is also
3322 much faster."
3323 :group 'org-export-tables
3324 :type 'boolean)
3326 (defgroup org-export-ascii nil
3327 "Options specific for ASCII export of Org-mode files."
3328 :tag "Org Export ASCII"
3329 :group 'org-export)
3331 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3332 "Characters for underlining headings in ASCII export.
3333 In the given sequence, these characters will be used for level 1, 2, ..."
3334 :group 'org-export-ascii
3335 :type '(repeat character))
3337 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3338 "Bullet characters for headlines converted to lists in ASCII export.
3339 The first character is used for the first lest level generated in this
3340 way, and so on. If there are more levels than characters given here,
3341 the list will be repeated.
3342 Note that plain lists will keep the same bullets as the have in the
3343 Org-mode file."
3344 :group 'org-export-ascii
3345 :type '(repeat character))
3347 (defgroup org-export-xml nil
3348 "Options specific for XML export of Org-mode files."
3349 :tag "Org Export XML"
3350 :group 'org-export)
3352 (defgroup org-export-html nil
3353 "Options specific for HTML export of Org-mode files."
3354 :tag "Org Export HTML"
3355 :group 'org-export)
3357 (defcustom org-export-html-coding-system nil
3359 :group 'org-export-html
3360 :type 'coding-system)
3362 (defcustom org-export-html-extension "html"
3363 "The extension for exported HTML files."
3364 :group 'org-export-html
3365 :type 'string)
3367 (defcustom org-export-html-style
3368 "<style type=\"text/css\">
3369 html {
3370 font-family: Times, serif;
3371 font-size: 12pt;
3373 .title { text-align: center; }
3374 .todo { color: red; }
3375 .done { color: green; }
3376 .timestamp { color: grey }
3377 .timestamp-kwd { color: CadetBlue }
3378 .tag { background-color:lightblue; font-weight:normal }
3379 .target { background-color: lavender; }
3380 pre {
3381 border: 1pt solid #AEBDCC;
3382 background-color: #F3F5F7;
3383 padding: 5pt;
3384 font-family: courier, monospace;
3386 table { border-collapse: collapse; }
3387 td, th {
3388 vertical-align: top;
3389 <!--border: 1pt solid #ADB9CC;-->
3391 </style>"
3392 "The default style specification for exported HTML files.
3393 Since there are different ways of setting style information, this variable
3394 needs to contain the full HTML structure to provide a style, including the
3395 surrounding HTML tags. The style specifications should include definitions
3396 for new classes todo, done, title, and deadline. For example, legal values
3397 would be:
3399 <style type=\"text/css\">
3400 p { font-weight: normal; color: gray; }
3401 h1 { color: black; }
3402 .title { text-align: center; }
3403 .todo, .deadline { color: red; }
3404 .done { color: green; }
3405 </style>
3407 or, if you want to keep the style in a file,
3409 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3411 As the value of this option simply gets inserted into the HTML <head> header,
3412 you can \"misuse\" it to add arbitrary text to the header."
3413 :group 'org-export-html
3414 :type 'string)
3417 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3418 "Format for typesetting the document title in HTML export."
3419 :group 'org-export-html
3420 :type 'string)
3422 (defcustom org-export-html-toplevel-hlevel 2
3423 "The <H> level for level 1 headings in HTML export."
3424 :group 'org-export-html
3425 :type 'string)
3427 (defcustom org-export-html-link-org-files-as-html t
3428 "Non-nil means, make file links to `file.org' point to `file.html'.
3429 When org-mode is exporting an org-mode file to HTML, links to
3430 non-html files are directly put into a href tag in HTML.
3431 However, links to other Org-mode files (recognized by the
3432 extension `.org.) should become links to the corresponding html
3433 file, assuming that the linked org-mode file will also be
3434 converted to HTML.
3435 When nil, the links still point to the plain `.org' file."
3436 :group 'org-export-html
3437 :type 'boolean)
3439 (defcustom org-export-html-inline-images 'maybe
3440 "Non-nil means, inline images into exported HTML pages.
3441 This is done using an <img> tag. When nil, an anchor with href is used to
3442 link to the image. If this option is `maybe', then images in links with
3443 an empty description will be inlined, while images with a description will
3444 be linked only."
3445 :group 'org-export-html
3446 :type '(choice (const :tag "Never" nil)
3447 (const :tag "Always" t)
3448 (const :tag "When there is no description" maybe)))
3450 ;; FIXME: rename
3451 (defcustom org-export-html-expand t
3452 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3453 When nil, these tags will be exported as plain text and therefore
3454 not be interpreted by a browser.
3456 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3457 :group 'org-export-html
3458 :type 'boolean)
3460 (defcustom org-export-html-table-tag
3461 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3462 "The HTML tag that is used to start a table.
3463 This must be a <table> tag, but you may change the options like
3464 borders and spacing."
3465 :group 'org-export-html
3466 :type 'string)
3468 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3469 "The opening tag for table header fields.
3470 This is customizable so that alignment options can be specified."
3471 :group 'org-export-tables
3472 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3474 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3475 "The opening tag for table data fields.
3476 This is customizable so that alignment options can be specified."
3477 :group 'org-export-tables
3478 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3480 (defcustom org-export-html-with-timestamp nil
3481 "If non-nil, write `org-export-html-html-helper-timestamp'
3482 into the exported HTML text. Otherwise, the buffer will just be saved
3483 to a file."
3484 :group 'org-export-html
3485 :type 'boolean)
3487 (defcustom org-export-html-html-helper-timestamp
3488 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3489 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3490 :group 'org-export-html
3491 :type 'string)
3493 (defgroup org-export-icalendar nil
3494 "Options specific for iCalendar export of Org-mode files."
3495 :tag "Org Export iCalendar"
3496 :group 'org-export)
3498 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3499 "The file name for the iCalendar file covering all agenda files.
3500 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3501 The file name should be absolute, the file will be overwritten without warning."
3502 :group 'org-export-icalendar
3503 :type 'file)
3505 (defcustom org-icalendar-include-todo nil
3506 "Non-nil means, export to iCalendar files should also cover TODO items."
3507 :group 'org-export-icalendar
3508 :type '(choice
3509 (const :tag "None" nil)
3510 (const :tag "Unfinished" t)
3511 (const :tag "All" all)))
3513 (defcustom org-icalendar-include-sexps t
3514 "Non-nil means, export to iCalendar files should also cover sexp entries.
3515 These are entries like in the diary, but directly in an Org-mode file."
3516 :group 'org-export-icalendar
3517 :type 'boolean)
3519 (defcustom org-icalendar-include-body 100
3520 "Amount of text below headline to be included in iCalendar export.
3521 This is a number of characters that should maximally be included.
3522 Properties, scheduling and clocking lines will always be removed.
3523 The text will be inserted into the DESCRIPTION field."
3524 :group 'org-export-icalendar
3525 :type '(choice
3526 (const :tag "Nothing" nil)
3527 (const :tag "Everything" t)
3528 (integer :tag "Max characters")))
3530 (defcustom org-icalendar-combined-name "OrgMode"
3531 "Calendar name for the combined iCalendar representing all agenda files."
3532 :group 'org-export-icalendar
3533 :type 'string)
3535 (defgroup org-font-lock nil
3536 "Font-lock settings for highlighting in Org-mode."
3537 :tag "Org Font Lock"
3538 :group 'org)
3540 (defcustom org-level-color-stars-only nil
3541 "Non-nil means fontify only the stars in each headline.
3542 When nil, the entire headline is fontified.
3543 Changing it requires restart of `font-lock-mode' to become effective
3544 also in regions already fontified."
3545 :group 'org-font-lock
3546 :type 'boolean)
3548 (defcustom org-hide-leading-stars nil
3549 "Non-nil means, hide the first N-1 stars in a headline.
3550 This works by using the face `org-hide' for these stars. This
3551 face is white for a light background, and black for a dark
3552 background. You may have to customize the face `org-hide' to
3553 make this work.
3554 Changing it requires restart of `font-lock-mode' to become effective
3555 also in regions already fontified.
3556 You may also set this on a per-file basis by adding one of the following
3557 lines to the buffer:
3559 #+STARTUP: hidestars
3560 #+STARTUP: showstars"
3561 :group 'org-font-lock
3562 :type 'boolean)
3564 (defcustom org-fontify-done-headline nil
3565 "Non-nil means, change the face of a headline if it is marked DONE.
3566 Normally, only the TODO/DONE keyword indicates the state of a headline.
3567 When this is non-nil, the headline after the keyword is set to the
3568 `org-headline-done' as an additional indication."
3569 :group 'org-font-lock
3570 :type 'boolean)
3572 (defcustom org-fontify-emphasized-text t
3573 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3574 Changing this variable requires a restart of Emacs to take effect."
3575 :group 'org-font-lock
3576 :type 'boolean)
3578 (defcustom org-highlight-latex-fragments-and-specials nil
3579 "Non-nil means, fontify what is treated specially by the exporters."
3580 :group 'org-font-lock
3581 :type 'boolean)
3583 (defcustom org-hide-emphasis-markers nil
3584 "Non-nil mean font-lock should hide the emphasis marker characters."
3585 :group 'org-font-lock
3586 :type 'boolean)
3588 (defvar org-emph-re nil
3589 "Regular expression for matching emphasis.")
3590 (defvar org-verbatim-re nil
3591 "Regular expression for matching verbatim text.")
3592 (defvar org-emphasis-regexp-components) ; defined just below
3593 (defvar org-emphasis-alist) ; defined just below
3594 (defun org-set-emph-re (var val)
3595 "Set variable and compute the emphasis regular expression."
3596 (set var val)
3597 (when (and (boundp 'org-emphasis-alist)
3598 (boundp 'org-emphasis-regexp-components)
3599 org-emphasis-alist org-emphasis-regexp-components)
3600 (let* ((e org-emphasis-regexp-components)
3601 (pre (car e))
3602 (post (nth 1 e))
3603 (border (nth 2 e))
3604 (body (nth 3 e))
3605 (nl (nth 4 e))
3606 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3607 (body1 (concat body "*?"))
3608 (markers (mapconcat 'car org-emphasis-alist ""))
3609 (vmarkers (mapconcat
3610 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3611 org-emphasis-alist "")))
3612 ;; make sure special characters appear at the right position in the class
3613 (if (string-match "\\^" markers)
3614 (setq markers (concat (replace-match "" t t markers) "^")))
3615 (if (string-match "-" markers)
3616 (setq markers (concat (replace-match "" t t markers) "-")))
3617 (if (string-match "\\^" vmarkers)
3618 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3619 (if (string-match "-" vmarkers)
3620 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3621 (if (> nl 0)
3622 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3623 (int-to-string nl) "\\}")))
3624 ;; Make the regexp
3625 (setq org-emph-re
3626 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3627 "\\("
3628 "\\([" markers "]\\)"
3629 "\\("
3630 "[^" border "]\\|"
3631 "[^" border (if (and nil stacked) markers) "]"
3632 body1
3633 "[^" border (if (and nil stacked) markers) "]"
3634 "\\)"
3635 "\\3\\)"
3636 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3637 (setq org-verbatim-re
3638 (concat "\\([" pre "]\\|^\\)"
3639 "\\("
3640 "\\([" vmarkers "]\\)"
3641 "\\("
3642 "[^" border "]\\|"
3643 "[^" border "]"
3644 body1
3645 "[^" border "]"
3646 "\\)"
3647 "\\3\\)"
3648 "\\([" post "]\\|$\\)")))))
3650 (defcustom org-emphasis-regexp-components
3651 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3652 "Components used to build the regular expression for emphasis.
3653 This is a list with 6 entries. Terminology: In an emphasis string
3654 like \" *strong word* \", we call the initial space PREMATCH, the final
3655 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3656 and \"trong wor\" is the body. The different components in this variable
3657 specify what is allowed/forbidden in each part:
3659 pre Chars allowed as prematch. Beginning of line will be allowed too.
3660 post Chars allowed as postmatch. End of line will be allowed too.
3661 border The chars *forbidden* as border characters.
3662 body-regexp A regexp like \".\" to match a body character. Don't use
3663 non-shy groups here, and don't allow newline here.
3664 newline The maximum number of newlines allowed in an emphasis exp.
3666 Use customize to modify this, or restart Emacs after changing it."
3667 :group 'org-font-lock
3668 :set 'org-set-emph-re
3669 :type '(list
3670 (sexp :tag "Allowed chars in pre ")
3671 (sexp :tag "Allowed chars in post ")
3672 (sexp :tag "Forbidden chars in border ")
3673 (sexp :tag "Regexp for body ")
3674 (integer :tag "number of newlines allowed")
3675 (option (boolean :tag "Stacking (DISABLED) "))))
3677 (defcustom org-emphasis-alist
3678 '(("*" bold "<b>" "</b>")
3679 ("/" italic "<i>" "</i>")
3680 ("_" underline "<u>" "</u>")
3681 ("=" org-code "<code>" "</code>" verbatim)
3682 ("~" org-verbatim "" "" verbatim)
3683 ("+" (:strike-through t) "<del>" "</del>")
3685 "Special syntax for emphasized text.
3686 Text starting and ending with a special character will be emphasized, for
3687 example *bold*, _underlined_ and /italic/. This variable sets the marker
3688 characters, the face to be used by font-lock for highlighting in Org-mode
3689 Emacs buffers, and the HTML tags to be used for this.
3690 Use customize to modify this, or restart Emacs after changing it."
3691 :group 'org-font-lock
3692 :set 'org-set-emph-re
3693 :type '(repeat
3694 (list
3695 (string :tag "Marker character")
3696 (choice
3697 (face :tag "Font-lock-face")
3698 (plist :tag "Face property list"))
3699 (string :tag "HTML start tag")
3700 (string :tag "HTML end tag")
3701 (option (const verbatim)))))
3703 ;;; The faces
3705 (defgroup org-faces nil
3706 "Faces in Org-mode."
3707 :tag "Org Faces"
3708 :group 'org-font-lock)
3710 (defun org-compatible-face (inherits specs)
3711 "Make a compatible face specification.
3712 If INHERITS is an existing face and if the Emacs version supports it,
3713 just inherit the face. If not, use SPECS to define the face.
3714 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3715 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3716 to the top of the list. The `min-colors' attribute will be removed from
3717 any other entries, and any resulting duplicates will be removed entirely."
3718 (cond
3719 ((and inherits (facep inherits)
3720 (not (featurep 'xemacs)) (> emacs-major-version 22))
3721 ;; In Emacs 23, we use inheritance where possible.
3722 ;; We only do this in Emacs 23, because only there the outline
3723 ;; faces have been changed to the original org-mode-level-faces.
3724 (list (list t :inherit inherits)))
3725 ((or (featurep 'xemacs) (< emacs-major-version 22))
3726 ;; These do not understand the `min-colors' attribute.
3727 (let (r e a)
3728 (while (setq e (pop specs))
3729 (cond
3730 ((memq (car e) '(t default)) (push e r))
3731 ((setq a (member '(min-colors 8) (car e)))
3732 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3733 (cdr e)))))
3734 ((setq a (assq 'min-colors (car e)))
3735 (setq e (cons (delq a (car e)) (cdr e)))
3736 (or (assoc (car e) r) (push e r)))
3737 (t (or (assoc (car e) r) (push e r)))))
3738 (nreverse r)))
3739 (t specs)))
3740 (put 'org-compatible-face 'lisp-indent-function 1)
3742 (defface org-hide
3743 '((((background light)) (:foreground "white"))
3744 (((background dark)) (:foreground "black")))
3745 "Face used to hide leading stars in headlines.
3746 The forground color of this face should be equal to the background
3747 color of the frame."
3748 :group 'org-faces)
3750 (defface org-level-1 ;; font-lock-function-name-face
3751 (org-compatible-face 'outline-1
3752 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3753 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3754 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3755 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3756 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3757 (t (:bold t))))
3758 "Face used for level 1 headlines."
3759 :group 'org-faces)
3761 (defface org-level-2 ;; font-lock-variable-name-face
3762 (org-compatible-face 'outline-2
3763 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3764 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3765 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3766 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3767 (t (:bold t))))
3768 "Face used for level 2 headlines."
3769 :group 'org-faces)
3771 (defface org-level-3 ;; font-lock-keyword-face
3772 (org-compatible-face 'outline-3
3773 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3774 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3775 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3776 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3777 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3778 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3779 (t (:bold t))))
3780 "Face used for level 3 headlines."
3781 :group 'org-faces)
3783 (defface org-level-4 ;; font-lock-comment-face
3784 (org-compatible-face 'outline-4
3785 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3786 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3787 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3788 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3789 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3790 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3791 (t (:bold t))))
3792 "Face used for level 4 headlines."
3793 :group 'org-faces)
3795 (defface org-level-5 ;; font-lock-type-face
3796 (org-compatible-face 'outline-5
3797 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3798 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3799 (((class color) (min-colors 8)) (:foreground "green"))))
3800 "Face used for level 5 headlines."
3801 :group 'org-faces)
3803 (defface org-level-6 ;; font-lock-constant-face
3804 (org-compatible-face 'outline-6
3805 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3806 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3807 (((class color) (min-colors 8)) (:foreground "magenta"))))
3808 "Face used for level 6 headlines."
3809 :group 'org-faces)
3811 (defface org-level-7 ;; font-lock-builtin-face
3812 (org-compatible-face 'outline-7
3813 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3814 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3815 (((class color) (min-colors 8)) (:foreground "blue"))))
3816 "Face used for level 7 headlines."
3817 :group 'org-faces)
3819 (defface org-level-8 ;; font-lock-string-face
3820 (org-compatible-face 'outline-8
3821 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3822 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3823 (((class color) (min-colors 8)) (:foreground "green"))))
3824 "Face used for level 8 headlines."
3825 :group 'org-faces)
3827 (defface org-special-keyword ;; font-lock-string-face
3828 (org-compatible-face nil
3829 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3830 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3831 (t (:italic t))))
3832 "Face used for special keywords."
3833 :group 'org-faces)
3835 (defface org-drawer ;; font-lock-function-name-face
3836 (org-compatible-face nil
3837 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3838 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3839 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3840 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3841 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3842 (t (:bold t))))
3843 "Face used for drawers."
3844 :group 'org-faces)
3846 (defface org-property-value nil
3847 "Face used for the value of a property."
3848 :group 'org-faces)
3850 (defface org-column
3851 (org-compatible-face nil
3852 '((((class color) (min-colors 16) (background light))
3853 (:background "grey90"))
3854 (((class color) (min-colors 16) (background dark))
3855 (:background "grey30"))
3856 (((class color) (min-colors 8))
3857 (:background "cyan" :foreground "black"))
3858 (t (:inverse-video t))))
3859 "Face for column display of entry properties."
3860 :group 'org-faces)
3862 (when (fboundp 'set-face-attribute)
3863 ;; Make sure that a fixed-width face is used when we have a column table.
3864 (set-face-attribute 'org-column nil
3865 :height (face-attribute 'default :height)
3866 :family (face-attribute 'default :family)))
3868 (defface org-warning
3869 (org-compatible-face 'font-lock-warning-face
3870 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3871 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3872 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3873 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3874 (t (:bold t))))
3875 "Face for deadlines and TODO keywords."
3876 :group 'org-faces)
3878 (defface org-archived ; similar to shadow
3879 (org-compatible-face 'shadow
3880 '((((class color grayscale) (min-colors 88) (background light))
3881 (:foreground "grey50"))
3882 (((class color grayscale) (min-colors 88) (background dark))
3883 (:foreground "grey70"))
3884 (((class color) (min-colors 8) (background light))
3885 (:foreground "green"))
3886 (((class color) (min-colors 8) (background dark))
3887 (:foreground "yellow"))))
3888 "Face for headline with the ARCHIVE tag."
3889 :group 'org-faces)
3891 (defface org-link
3892 '((((class color) (background light)) (:foreground "Purple" :underline t))
3893 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3894 (t (:underline t)))
3895 "Face for links."
3896 :group 'org-faces)
3898 (defface org-ellipsis
3899 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3900 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3901 (t (:strike-through t)))
3902 "Face for the ellipsis in folded text."
3903 :group 'org-faces)
3905 (defface org-target
3906 '((((class color) (background light)) (:underline t))
3907 (((class color) (background dark)) (:underline t))
3908 (t (:underline t)))
3909 "Face for links."
3910 :group 'org-faces)
3912 (defface org-date
3913 '((((class color) (background light)) (:foreground "Purple" :underline t))
3914 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3915 (t (:underline t)))
3916 "Face for links."
3917 :group 'org-faces)
3919 (defface org-sexp-date
3920 '((((class color) (background light)) (:foreground "Purple"))
3921 (((class color) (background dark)) (:foreground "Cyan"))
3922 (t (:underline t)))
3923 "Face for links."
3924 :group 'org-faces)
3926 (defface org-tag
3927 '((t (:bold t)))
3928 "Face for tags."
3929 :group 'org-faces)
3931 (defface org-todo ; font-lock-warning-face
3932 (org-compatible-face nil
3933 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3934 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3935 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3936 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3937 (t (:inverse-video t :bold t))))
3938 "Face for TODO keywords."
3939 :group 'org-faces)
3941 (defface org-done ;; font-lock-type-face
3942 (org-compatible-face nil
3943 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3944 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3945 (((class color) (min-colors 8)) (:foreground "green"))
3946 (t (:bold t))))
3947 "Face used for todo keywords that indicate DONE items."
3948 :group 'org-faces)
3950 (defface org-headline-done ;; font-lock-string-face
3951 (org-compatible-face nil
3952 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3953 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3954 (((class color) (min-colors 8) (background light)) (:bold nil))))
3955 "Face used to indicate that a headline is DONE.
3956 This face is only used if `org-fontify-done-headline' is set. If applies
3957 to the part of the headline after the DONE keyword."
3958 :group 'org-faces)
3960 (defcustom org-todo-keyword-faces nil
3961 "Faces for specific TODO keywords.
3962 This is a list of cons cells, with TODO keywords in the car
3963 and faces in the cdr. The face can be a symbol, or a property
3964 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3965 :group 'org-faces
3966 :group 'org-todo
3967 :type '(repeat
3968 (cons
3969 (string :tag "keyword")
3970 (sexp :tag "face"))))
3972 (defface org-table ;; font-lock-function-name-face
3973 (org-compatible-face nil
3974 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3975 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3976 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3977 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3978 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3979 (((class color) (min-colors 8) (background dark)))))
3980 "Face used for tables."
3981 :group 'org-faces)
3983 (defface org-formula
3984 (org-compatible-face nil
3985 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3986 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3987 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3988 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3989 (t (:bold t :italic t))))
3990 "Face for formulas."
3991 :group 'org-faces)
3993 (defface org-code
3994 (org-compatible-face nil
3995 '((((class color grayscale) (min-colors 88) (background light))
3996 (:foreground "grey50"))
3997 (((class color grayscale) (min-colors 88) (background dark))
3998 (:foreground "grey70"))
3999 (((class color) (min-colors 8) (background light))
4000 (:foreground "green"))
4001 (((class color) (min-colors 8) (background dark))
4002 (:foreground "yellow"))))
4003 "Face for fixed-with text like code snippets."
4004 :group 'org-faces
4005 :version "22.1")
4007 (defface org-verbatim
4008 (org-compatible-face nil
4009 '((((class color grayscale) (min-colors 88) (background light))
4010 (:foreground "grey50" :underline t))
4011 (((class color grayscale) (min-colors 88) (background dark))
4012 (:foreground "grey70" :underline t))
4013 (((class color) (min-colors 8) (background light))
4014 (:foreground "green" :underline t))
4015 (((class color) (min-colors 8) (background dark))
4016 (:foreground "yellow" :underline t))))
4017 "Face for fixed-with text like code snippets."
4018 :group 'org-faces
4019 :version "22.1")
4021 (defface org-agenda-structure ;; font-lock-function-name-face
4022 (org-compatible-face nil
4023 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4024 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4025 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4026 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4027 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4028 (t (:bold t))))
4029 "Face used in agenda for captions and dates."
4030 :group 'org-faces)
4032 (defface org-scheduled-today
4033 (org-compatible-face nil
4034 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4035 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4036 (((class color) (min-colors 8)) (:foreground "green"))
4037 (t (:bold t :italic t))))
4038 "Face for items scheduled for a certain day."
4039 :group 'org-faces)
4041 (defface org-scheduled-previously
4042 (org-compatible-face nil
4043 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4044 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4045 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4046 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4047 (t (:bold t))))
4048 "Face for items scheduled previously, and not yet done."
4049 :group 'org-faces)
4051 (defface org-upcoming-deadline
4052 (org-compatible-face nil
4053 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4054 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4055 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4056 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4057 (t (:bold t))))
4058 "Face for items scheduled previously, and not yet done."
4059 :group 'org-faces)
4061 (defcustom org-agenda-deadline-faces
4062 '((1.0 . org-warning)
4063 (0.5 . org-upcoming-deadline)
4064 (0.0 . default))
4065 "Faces for showing deadlines in the agenda.
4066 This is a list of cons cells. The cdr of each cell is a face to be used,
4067 and it can also just be like '(:foreground \"yellow\").
4068 Each car is a fraction of the head-warning time that must have passed for
4069 this the face in the cdr to be used for display. The numbers must be
4070 given in descending order. The head-warning time is normally taken
4071 from `org-deadline-warning-days', but can also be specified in the deadline
4072 timestamp itself, like this:
4074 DEADLINE: <2007-08-13 Mon -8d>
4076 You may use d for days, w for weeks, m for months and y for years. Months
4077 and years will only be treated in an approximate fashion (30.4 days for a
4078 month and 365.24 days for a year)."
4079 :group 'org-faces
4080 :group 'org-agenda-daily/weekly
4081 :type '(repeat
4082 (cons
4083 (number :tag "Fraction of head-warning time passed")
4084 (sexp :tag "Face"))))
4086 ;; FIXME: this is not a good face yet.
4087 (defface org-agenda-restriction-lock
4088 (org-compatible-face nil
4089 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4090 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4091 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4092 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4093 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4094 (t (:inverse-video t))))
4095 "Face for showing the agenda restriction lock."
4096 :group 'org-faces)
4098 (defface org-time-grid ;; font-lock-variable-name-face
4099 (org-compatible-face nil
4100 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4101 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4102 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4103 "Face used for time grids."
4104 :group 'org-faces)
4106 (defconst org-level-faces
4107 '(org-level-1 org-level-2 org-level-3 org-level-4
4108 org-level-5 org-level-6 org-level-7 org-level-8
4111 (defcustom org-n-level-faces (length org-level-faces)
4112 "The number different faces to be used for headlines.
4113 Org-mode defines 8 different headline faces, so this can be at most 8.
4114 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4115 :type 'number
4116 :group 'org-faces)
4118 ;;; Functions and variables from ther packages
4119 ;; Declared here to avoid compiler warnings
4121 (eval-and-compile
4122 (unless (fboundp 'declare-function)
4123 (defmacro declare-function (fn file &optional arglist fileonly))))
4125 ;; XEmacs only
4126 (defvar outline-mode-menu-heading)
4127 (defvar outline-mode-menu-show)
4128 (defvar outline-mode-menu-hide)
4129 (defvar zmacs-regions) ; XEmacs regions
4131 ;; Emacs only
4132 (defvar mark-active)
4134 ;; Various packages
4135 ;; FIXME: get the argument lists for the UNKNOWN stuff
4136 (declare-function add-to-diary-list "diary-lib"
4137 (date string specifier &optional marker globcolor literal))
4138 (declare-function table--at-cell-p "table" (position &optional object at-column))
4139 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4140 (declare-function Info-goto-node "info" (nodename &optional fork))
4141 (declare-function bbdb "ext:bbdb-com" (string elidep))
4142 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4143 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4144 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4145 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4146 (declare-function bbdb-record-name "ext:bbdb" (record))
4147 (declare-function bibtex-beginning-of-entry "bibtex" ())
4148 (declare-function bibtex-generate-autokey "bibtex" ())
4149 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4150 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4151 (defvar calc-embedded-close-formula)
4152 (defvar calc-embedded-open-formula)
4153 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4154 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4155 (declare-function calendar-check-holidays "holidays" (date))
4156 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4157 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4158 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4159 (declare-function calendar-forward-day "cal-move" (arg))
4160 (declare-function calendar-french-date-string "cal-french" (&optional date))
4161 (declare-function calendar-goto-date "cal-move" (date))
4162 (declare-function calendar-goto-today "cal-move" ())
4163 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4164 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4165 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4166 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4167 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4168 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4169 (defvar calendar-mode-map)
4170 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4171 (declare-function cdlatex-tab "ext:cdlatex" ())
4172 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4173 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4174 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4175 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4176 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4177 (defvar font-lock-unfontify-region-function)
4178 (declare-function gnus-article-show-summary "gnus-art" ())
4179 (declare-function gnus-summary-last-subject "gnus-sum" ())
4180 (defvar gnus-other-frame-object)
4181 (defvar gnus-group-name)
4182 (defvar gnus-article-current)
4183 (defvar Info-current-file)
4184 (defvar Info-current-node)
4185 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4186 (declare-function mh-find-path "mh-utils" ())
4187 (declare-function mh-get-header-field "mh-utils" (field))
4188 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4189 (declare-function mh-header-display "mh-show" ())
4190 (declare-function mh-index-previous-folder "mh-search" ())
4191 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4192 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4193 (declare-function mh-search-choose "mh-search" (&optional searcher))
4194 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4195 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4196 (declare-function mh-show-header-display "mh-show" t t)
4197 (declare-function mh-show-msg "mh-show" (msg))
4198 (declare-function mh-show-show "mh-show" t t)
4199 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4200 (defvar mh-progs)
4201 (defvar mh-current-folder)
4202 (defvar mh-show-folder-buffer)
4203 (defvar mh-index-folder)
4204 (defvar mh-searcher)
4205 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4206 (declare-function parse-time-string "parse-time" (string))
4207 (declare-function remember "remember" (&optional initial))
4208 (declare-function remember-buffer-desc "remember" ())
4209 (defvar remember-save-after-remembering)
4210 (defvar remember-data-file)
4211 (defvar remember-register)
4212 (defvar remember-buffer)
4213 (defvar remember-handler-functions)
4214 (defvar remember-annotation-functions)
4215 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4216 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4217 (declare-function rmail-what-message "rmail" ())
4218 (defvar texmathp-why)
4219 (declare-function vm-beginning-of-message "ext:vm-page" ())
4220 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4221 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4222 (declare-function vm-isearch-narrow "ext:vm-search" ())
4223 (declare-function vm-isearch-update "ext:vm-search" ())
4224 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4225 (declare-function vm-su-message-id "ext:vm-summary" (m))
4226 (declare-function vm-su-subject "ext:vm-summary" (m))
4227 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4228 (defvar vm-message-pointer)
4229 (defvar vm-folder-directory)
4230 (defvar w3m-current-url)
4231 (defvar w3m-current-title)
4232 ;; backward compatibility to old version of wl
4233 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4234 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4235 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4236 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4237 (declare-function wl-summary-line-from "ext:wl-summary" ())
4238 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4239 (declare-function wl-summary-message-number "ext:wl-summary" ())
4240 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4241 (defvar wl-summary-buffer-elmo-folder)
4242 (defvar wl-summary-buffer-folder-name)
4243 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4245 (defvar org-latex-regexps)
4246 (defvar constants-unit-system)
4248 ;;; Variables for pre-computed regular expressions, all buffer local
4250 (defvar org-drawer-regexp nil
4251 "Matches first line of a hidden block.")
4252 (make-variable-buffer-local 'org-drawer-regexp)
4253 (defvar org-todo-regexp nil
4254 "Matches any of the TODO state keywords.")
4255 (make-variable-buffer-local 'org-todo-regexp)
4256 (defvar org-not-done-regexp nil
4257 "Matches any of the TODO state keywords except the last one.")
4258 (make-variable-buffer-local 'org-not-done-regexp)
4259 (defvar org-todo-line-regexp nil
4260 "Matches a headline and puts TODO state into group 2 if present.")
4261 (make-variable-buffer-local 'org-todo-line-regexp)
4262 (defvar org-complex-heading-regexp nil
4263 "Matches a headline and puts everything into groups:
4264 group 1: the stars
4265 group 2: The todo keyword, maybe
4266 group 3: Priority cookie
4267 group 4: True headline
4268 group 5: Tags")
4269 (make-variable-buffer-local 'org-complex-heading-regexp)
4270 (defvar org-todo-line-tags-regexp nil
4271 "Matches a headline and puts TODO state into group 2 if present.
4272 Also put tags into group 4 if tags are present.")
4273 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4274 (defvar org-nl-done-regexp nil
4275 "Matches newline followed by a headline with the DONE keyword.")
4276 (make-variable-buffer-local 'org-nl-done-regexp)
4277 (defvar org-looking-at-done-regexp nil
4278 "Matches the DONE keyword a point.")
4279 (make-variable-buffer-local 'org-looking-at-done-regexp)
4280 (defvar org-ds-keyword-length 12
4281 "Maximum length of the Deadline and SCHEDULED keywords.")
4282 (make-variable-buffer-local 'org-ds-keyword-length)
4283 (defvar org-deadline-regexp nil
4284 "Matches the DEADLINE keyword.")
4285 (make-variable-buffer-local 'org-deadline-regexp)
4286 (defvar org-deadline-time-regexp nil
4287 "Matches the DEADLINE keyword together with a time stamp.")
4288 (make-variable-buffer-local 'org-deadline-time-regexp)
4289 (defvar org-deadline-line-regexp nil
4290 "Matches the DEADLINE keyword and the rest of the line.")
4291 (make-variable-buffer-local 'org-deadline-line-regexp)
4292 (defvar org-scheduled-regexp nil
4293 "Matches the SCHEDULED keyword.")
4294 (make-variable-buffer-local 'org-scheduled-regexp)
4295 (defvar org-scheduled-time-regexp nil
4296 "Matches the SCHEDULED keyword together with a time stamp.")
4297 (make-variable-buffer-local 'org-scheduled-time-regexp)
4298 (defvar org-closed-time-regexp nil
4299 "Matches the CLOSED keyword together with a time stamp.")
4300 (make-variable-buffer-local 'org-closed-time-regexp)
4302 (defvar org-keyword-time-regexp nil
4303 "Matches any of the 4 keywords, together with the time stamp.")
4304 (make-variable-buffer-local 'org-keyword-time-regexp)
4305 (defvar org-keyword-time-not-clock-regexp nil
4306 "Matches any of the 3 keywords, together with the time stamp.")
4307 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4308 (defvar org-maybe-keyword-time-regexp nil
4309 "Matches a timestamp, possibly preceeded by a keyword.")
4310 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4311 (defvar org-planning-or-clock-line-re nil
4312 "Matches a line with planning or clock info.")
4313 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4315 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4316 rear-nonsticky t mouse-map t fontified t)
4317 "Properties to remove when a string without properties is wanted.")
4319 (defsubst org-match-string-no-properties (num &optional string)
4320 (if (featurep 'xemacs)
4321 (let ((s (match-string num string)))
4322 (remove-text-properties 0 (length s) org-rm-props s)
4324 (match-string-no-properties num string)))
4326 (defsubst org-no-properties (s)
4327 (if (fboundp 'set-text-properties)
4328 (set-text-properties 0 (length s) nil s)
4329 (remove-text-properties 0 (length s) org-rm-props s))
4332 (defsubst org-get-alist-option (option key)
4333 (cond ((eq key t) t)
4334 ((eq option t) t)
4335 ((assoc key option) (cdr (assoc key option)))
4336 (t (cdr (assq 'default option)))))
4338 (defsubst org-inhibit-invisibility ()
4339 "Modified `buffer-invisibility-spec' for Emacs 21.
4340 Some ops with invisible text do not work correctly on Emacs 21. For these
4341 we turn off invisibility temporarily. Use this in a `let' form."
4342 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4344 (defsubst org-set-local (var value)
4345 "Make VAR local in current buffer and set it to VALUE."
4346 (set (make-variable-buffer-local var) value))
4348 (defsubst org-mode-p ()
4349 "Check if the current buffer is in Org-mode."
4350 (eq major-mode 'org-mode))
4352 (defsubst org-last (list)
4353 "Return the last element of LIST."
4354 (car (last list)))
4356 (defun org-let (list &rest body)
4357 (eval (cons 'let (cons list body))))
4358 (put 'org-let 'lisp-indent-function 1)
4360 (defun org-let2 (list1 list2 &rest body)
4361 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4362 (put 'org-let2 'lisp-indent-function 2)
4363 (defconst org-startup-options
4364 '(("fold" org-startup-folded t)
4365 ("overview" org-startup-folded t)
4366 ("nofold" org-startup-folded nil)
4367 ("showall" org-startup-folded nil)
4368 ("content" org-startup-folded content)
4369 ("hidestars" org-hide-leading-stars t)
4370 ("showstars" org-hide-leading-stars nil)
4371 ("odd" org-odd-levels-only t)
4372 ("oddeven" org-odd-levels-only nil)
4373 ("align" org-startup-align-all-tables t)
4374 ("noalign" org-startup-align-all-tables nil)
4375 ("customtime" org-display-custom-times t)
4376 ("logging" org-log-done t)
4377 ("logdone" org-log-done t)
4378 ("nologging" org-log-done nil)
4379 ("lognotedone" org-log-done done push)
4380 ("lognotestate" org-log-done state push)
4381 ("lognoteclock-out" org-log-done clock-out push)
4382 ("logrepeat" org-log-repeat t)
4383 ("nologrepeat" org-log-repeat nil)
4384 ("constcgs" constants-unit-system cgs)
4385 ("constSI" constants-unit-system SI))
4386 "Variable associated with STARTUP options for org-mode.
4387 Each element is a list of three items: The startup options as written
4388 in the #+STARTUP line, the corresponding variable, and the value to
4389 set this variable to if the option is found. An optional forth element PUSH
4390 means to push this value onto the list in the variable.")
4392 (defun org-set-regexps-and-options ()
4393 "Precompute regular expressions for current buffer."
4394 (when (org-mode-p)
4395 (org-set-local 'org-todo-kwd-alist nil)
4396 (org-set-local 'org-todo-key-alist nil)
4397 (org-set-local 'org-todo-key-trigger nil)
4398 (org-set-local 'org-todo-keywords-1 nil)
4399 (org-set-local 'org-done-keywords nil)
4400 (org-set-local 'org-todo-heads nil)
4401 (org-set-local 'org-todo-sets nil)
4402 (org-set-local 'org-todo-log-states nil)
4403 (let ((re (org-make-options-regexp
4404 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4405 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4406 "CONSTANTS" "PROPERTY" "DRAWERS")))
4407 (splitre "[ \t]+")
4408 kwds kws0 kwsa key value cat arch tags const links hw dws
4409 tail sep kws1 prio props drawers
4410 ex log)
4411 (save-excursion
4412 (save-restriction
4413 (widen)
4414 (goto-char (point-min))
4415 (while (re-search-forward re nil t)
4416 (setq key (match-string 1) value (org-match-string-no-properties 2))
4417 (cond
4418 ((equal key "CATEGORY")
4419 (if (string-match "[ \t]+$" value)
4420 (setq value (replace-match "" t t value)))
4421 (setq cat value))
4422 ((member key '("SEQ_TODO" "TODO"))
4423 (push (cons 'sequence (org-split-string value splitre)) kwds))
4424 ((equal key "TYP_TODO")
4425 (push (cons 'type (org-split-string value splitre)) kwds))
4426 ((equal key "TAGS")
4427 (setq tags (append tags (org-split-string value splitre))))
4428 ((equal key "COLUMNS")
4429 (org-set-local 'org-columns-default-format value))
4430 ((equal key "LINK")
4431 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4432 (push (cons (match-string 1 value)
4433 (org-trim (match-string 2 value)))
4434 links)))
4435 ((equal key "PRIORITIES")
4436 (setq prio (org-split-string value " +")))
4437 ((equal key "PROPERTY")
4438 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4439 (push (cons (match-string 1 value) (match-string 2 value))
4440 props)))
4441 ((equal key "DRAWERS")
4442 (setq drawers (org-split-string value splitre)))
4443 ((equal key "CONSTANTS")
4444 (setq const (append const (org-split-string value splitre))))
4445 ((equal key "STARTUP")
4446 (let ((opts (org-split-string value splitre))
4447 l var val)
4448 (while (setq l (pop opts))
4449 (when (setq l (assoc l org-startup-options))
4450 (setq var (nth 1 l) val (nth 2 l))
4451 (if (not (nth 3 l))
4452 (set (make-local-variable var) val)
4453 (if (not (listp (symbol-value var)))
4454 (set (make-local-variable var) nil))
4455 (set (make-local-variable var) (symbol-value var))
4456 (add-to-list var val))))))
4457 ((equal key "ARCHIVE")
4458 (string-match " *$" value)
4459 (setq arch (replace-match "" t t value))
4460 (remove-text-properties 0 (length arch)
4461 '(face t fontified t) arch)))
4463 (when cat
4464 (org-set-local 'org-category (intern cat))
4465 (push (cons "CATEGORY" cat) props))
4466 (when prio
4467 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4468 (setq prio (mapcar 'string-to-char prio))
4469 (org-set-local 'org-highest-priority (nth 0 prio))
4470 (org-set-local 'org-lowest-priority (nth 1 prio))
4471 (org-set-local 'org-default-priority (nth 2 prio)))
4472 (and props (org-set-local 'org-local-properties (nreverse props)))
4473 (and drawers (org-set-local 'org-drawers drawers))
4474 (and arch (org-set-local 'org-archive-location arch))
4475 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4476 ;; Process the TODO keywords
4477 (unless kwds
4478 ;; Use the global values as if they had been given locally.
4479 (setq kwds (default-value 'org-todo-keywords))
4480 (if (stringp (car kwds))
4481 (setq kwds (list (cons org-todo-interpretation
4482 (default-value 'org-todo-keywords)))))
4483 (setq kwds (reverse kwds)))
4484 (setq kwds (nreverse kwds))
4485 (let (inter kws kw)
4486 (while (setq kws (pop kwds))
4487 (setq inter (pop kws) sep (member "|" kws)
4488 kws0 (delete "|" (copy-sequence kws))
4489 kwsa nil
4490 kws1 (mapcar
4491 (lambda (x)
4492 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4493 (progn
4494 (setq kw (match-string 1 x)
4495 ex (and (match-end 2) (match-string 2 x))
4496 log (and ex (string-match "@" ex))
4497 key (and ex (substring ex 0 1)))
4498 (if (equal key "@") (setq key nil))
4499 (push (cons kw (and key (string-to-char key))) kwsa)
4500 (and log (push kw org-todo-log-states))
4502 (error "Invalid TODO keyword %s" x)))
4503 kws0)
4504 kwsa (if kwsa (append '((:startgroup))
4505 (nreverse kwsa)
4506 '((:endgroup))))
4507 hw (car kws1)
4508 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4509 tail (list inter hw (car dws) (org-last dws)))
4510 (add-to-list 'org-todo-heads hw 'append)
4511 (push kws1 org-todo-sets)
4512 (setq org-done-keywords (append org-done-keywords dws nil))
4513 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4514 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4515 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4516 (setq org-todo-sets (nreverse org-todo-sets)
4517 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4518 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4519 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4520 ;; Process the constants
4521 (when const
4522 (let (e cst)
4523 (while (setq e (pop const))
4524 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4525 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4526 (setq org-table-formula-constants-local cst)))
4528 ;; Process the tags.
4529 (when tags
4530 (let (e tgs)
4531 (while (setq e (pop tags))
4532 (cond
4533 ((equal e "{") (push '(:startgroup) tgs))
4534 ((equal e "}") (push '(:endgroup) tgs))
4535 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4536 (push (cons (match-string 1 e)
4537 (string-to-char (match-string 2 e)))
4538 tgs))
4539 (t (push (list e) tgs))))
4540 (org-set-local 'org-tag-alist nil)
4541 (while (setq e (pop tgs))
4542 (or (and (stringp (car e))
4543 (assoc (car e) org-tag-alist))
4544 (push e org-tag-alist))))))
4546 ;; Compute the regular expressions and other local variables
4547 (if (not org-done-keywords)
4548 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4549 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4550 (length org-scheduled-string)))
4551 org-drawer-regexp
4552 (concat "^[ \t]*:\\("
4553 (mapconcat 'regexp-quote org-drawers "\\|")
4554 "\\):[ \t]*$")
4555 org-not-done-keywords
4556 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4557 org-todo-regexp
4558 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4559 "\\|") "\\)\\>")
4560 org-not-done-regexp
4561 (concat "\\<\\("
4562 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4563 "\\)\\>")
4564 org-todo-line-regexp
4565 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4566 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4567 "\\)\\>\\)?[ \t]*\\(.*\\)")
4568 org-complex-heading-regexp
4569 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4570 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4571 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4572 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4573 org-nl-done-regexp
4574 (concat "\n\\*+[ \t]+"
4575 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4576 "\\)" "\\>")
4577 org-todo-line-tags-regexp
4578 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4579 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4580 (org-re
4581 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4582 org-looking-at-done-regexp
4583 (concat "^" "\\(?:"
4584 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4585 "\\>")
4586 org-deadline-regexp (concat "\\<" org-deadline-string)
4587 org-deadline-time-regexp
4588 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4589 org-deadline-line-regexp
4590 (concat "\\<\\(" org-deadline-string "\\).*")
4591 org-scheduled-regexp
4592 (concat "\\<" org-scheduled-string)
4593 org-scheduled-time-regexp
4594 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4595 org-closed-time-regexp
4596 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4597 org-keyword-time-regexp
4598 (concat "\\<\\(" org-scheduled-string
4599 "\\|" org-deadline-string
4600 "\\|" org-closed-string
4601 "\\|" org-clock-string "\\)"
4602 " *[[<]\\([^]>]+\\)[]>]")
4603 org-keyword-time-not-clock-regexp
4604 (concat "\\<\\(" org-scheduled-string
4605 "\\|" org-deadline-string
4606 "\\|" org-closed-string
4607 "\\)"
4608 " *[[<]\\([^]>]+\\)[]>]")
4609 org-maybe-keyword-time-regexp
4610 (concat "\\(\\<\\(" org-scheduled-string
4611 "\\|" org-deadline-string
4612 "\\|" org-closed-string
4613 "\\|" org-clock-string "\\)\\)?"
4614 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4615 org-planning-or-clock-line-re
4616 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4617 "\\|" org-deadline-string
4618 "\\|" org-closed-string "\\|" org-clock-string
4619 "\\)\\>\\)")
4621 (org-compute-latex-and-specials-regexp)
4622 (org-set-font-lock-defaults)))
4624 (defun org-remove-keyword-keys (list)
4625 (mapcar (lambda (x)
4626 (if (string-match "(..?)$" x)
4627 (substring x 0 (match-beginning 0))
4629 list))
4631 ;; FIXME: this could be done much better, using second characters etc.
4632 (defun org-assign-fast-keys (alist)
4633 "Assign fast keys to a keyword-key alist.
4634 Respect keys that are already there."
4635 (let (new e k c c1 c2 (char ?a))
4636 (while (setq e (pop alist))
4637 (cond
4638 ((equal e '(:startgroup)) (push e new))
4639 ((equal e '(:endgroup)) (push e new))
4641 (setq k (car e) c2 nil)
4642 (if (cdr e)
4643 (setq c (cdr e))
4644 ;; automatically assign a character.
4645 (setq c1 (string-to-char
4646 (downcase (substring
4647 k (if (= (string-to-char k) ?@) 1 0)))))
4648 (if (or (rassoc c1 new) (rassoc c1 alist))
4649 (while (or (rassoc char new) (rassoc char alist))
4650 (setq char (1+ char)))
4651 (setq c2 c1))
4652 (setq c (or c2 char)))
4653 (push (cons k c) new))))
4654 (nreverse new)))
4656 ;;; Some variables ujsed in various places
4658 (defvar org-window-configuration nil
4659 "Used in various places to store a window configuration.")
4660 (defvar org-finish-function nil
4661 "Function to be called when `C-c C-c' is used.
4662 This is for getting out of special buffers like remember.")
4665 ;; FIXME: Occasionally check by commenting these, to make sure
4666 ;; no other functions uses these, forgetting to let-bind them.
4667 (defvar entry)
4668 (defvar state)
4669 (defvar last-state)
4670 (defvar date)
4671 (defvar description)
4673 ;; Defined somewhere in this file, but used before definition.
4674 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4675 (defvar org-agenda-buffer-name)
4676 (defvar org-agenda-undo-list)
4677 (defvar org-agenda-pending-undo-list)
4678 (defvar org-agenda-overriding-header)
4679 (defvar orgtbl-mode)
4680 (defvar org-html-entities)
4681 (defvar org-struct-menu)
4682 (defvar org-org-menu)
4683 (defvar org-tbl-menu)
4684 (defvar org-agenda-keymap)
4686 ;;;; Emacs/XEmacs compatibility
4688 ;; Overlay compatibility functions
4689 (defun org-make-overlay (beg end &optional buffer)
4690 (if (featurep 'xemacs)
4691 (make-extent beg end buffer)
4692 (make-overlay beg end buffer)))
4693 (defun org-delete-overlay (ovl)
4694 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4695 (defun org-detach-overlay (ovl)
4696 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4697 (defun org-move-overlay (ovl beg end &optional buffer)
4698 (if (featurep 'xemacs)
4699 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4700 (move-overlay ovl beg end buffer)))
4701 (defun org-overlay-put (ovl prop value)
4702 (if (featurep 'xemacs)
4703 (set-extent-property ovl prop value)
4704 (overlay-put ovl prop value)))
4705 (defun org-overlay-display (ovl text &optional face evap)
4706 "Make overlay OVL display TEXT with face FACE."
4707 (if (featurep 'xemacs)
4708 (let ((gl (make-glyph text)))
4709 (and face (set-glyph-face gl face))
4710 (set-extent-property ovl 'invisible t)
4711 (set-extent-property ovl 'end-glyph gl))
4712 (overlay-put ovl 'display text)
4713 (if face (overlay-put ovl 'face face))
4714 (if evap (overlay-put ovl 'evaporate t))))
4715 (defun org-overlay-before-string (ovl text &optional face evap)
4716 "Make overlay OVL display TEXT with face FACE."
4717 (if (featurep 'xemacs)
4718 (let ((gl (make-glyph text)))
4719 (and face (set-glyph-face gl face))
4720 (set-extent-property ovl 'begin-glyph gl))
4721 (if face (org-add-props text nil 'face face))
4722 (overlay-put ovl 'before-string text)
4723 (if evap (overlay-put ovl 'evaporate t))))
4724 (defun org-overlay-get (ovl prop)
4725 (if (featurep 'xemacs)
4726 (extent-property ovl prop)
4727 (overlay-get ovl prop)))
4728 (defun org-overlays-at (pos)
4729 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4730 (defun org-overlays-in (&optional start end)
4731 (if (featurep 'xemacs)
4732 (extent-list nil start end)
4733 (overlays-in start end)))
4734 (defun org-overlay-start (o)
4735 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4736 (defun org-overlay-end (o)
4737 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4738 (defun org-find-overlays (prop &optional pos delete)
4739 "Find all overlays specifying PROP at POS or point.
4740 If DELETE is non-nil, delete all those overlays."
4741 (let ((overlays (org-overlays-at (or pos (point))))
4742 ov found)
4743 (while (setq ov (pop overlays))
4744 (if (org-overlay-get ov prop)
4745 (if delete (org-delete-overlay ov) (push ov found))))
4746 found))
4748 ;; Region compatibility
4750 (defun org-add-hook (hook function &optional append local)
4751 "Add-hook, compatible with both Emacsen."
4752 (if (and local (featurep 'xemacs))
4753 (add-local-hook hook function append)
4754 (add-hook hook function append local)))
4756 (defvar org-ignore-region nil
4757 "To temporarily disable the active region.")
4759 (defun org-region-active-p ()
4760 "Is `transient-mark-mode' on and the region active?
4761 Works on both Emacs and XEmacs."
4762 (if org-ignore-region
4764 (if (featurep 'xemacs)
4765 (and zmacs-regions (region-active-p))
4766 (if (fboundp 'use-region-p)
4767 (use-region-p)
4768 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4770 ;; Invisibility compatibility
4772 (defun org-add-to-invisibility-spec (arg)
4773 "Add elements to `buffer-invisibility-spec'.
4774 See documentation for `buffer-invisibility-spec' for the kind of elements
4775 that can be added."
4776 (cond
4777 ((fboundp 'add-to-invisibility-spec)
4778 (add-to-invisibility-spec arg))
4779 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4780 (setq buffer-invisibility-spec (list arg)))
4782 (setq buffer-invisibility-spec
4783 (cons arg buffer-invisibility-spec)))))
4785 (defun org-remove-from-invisibility-spec (arg)
4786 "Remove elements from `buffer-invisibility-spec'."
4787 (if (fboundp 'remove-from-invisibility-spec)
4788 (remove-from-invisibility-spec arg)
4789 (if (consp buffer-invisibility-spec)
4790 (setq buffer-invisibility-spec
4791 (delete arg buffer-invisibility-spec)))))
4793 (defun org-in-invisibility-spec-p (arg)
4794 "Is ARG a member of `buffer-invisibility-spec'?"
4795 (if (consp buffer-invisibility-spec)
4796 (member arg buffer-invisibility-spec)
4797 nil))
4799 ;;;; Define the Org-mode
4801 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4802 (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."))
4805 ;; We use a before-change function to check if a table might need
4806 ;; an update.
4807 (defvar org-table-may-need-update t
4808 "Indicates that a table might need an update.
4809 This variable is set by `org-before-change-function'.
4810 `org-table-align' sets it back to nil.")
4811 (defvar org-mode-map)
4812 (defvar org-mode-hook nil)
4813 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4814 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4815 (defvar org-table-buffer-is-an nil)
4816 (defconst org-outline-regexp "\\*+ ")
4818 ;;;###autoload
4819 (define-derived-mode org-mode outline-mode "Org"
4820 "Outline-based notes management and organizer, alias
4821 \"Carsten's outline-mode for keeping track of everything.\"
4823 Org-mode develops organizational tasks around a NOTES file which
4824 contains information about projects as plain text. Org-mode is
4825 implemented on top of outline-mode, which is ideal to keep the content
4826 of large files well structured. It supports ToDo items, deadlines and
4827 time stamps, which magically appear in the diary listing of the Emacs
4828 calendar. Tables are easily created with a built-in table editor.
4829 Plain text URL-like links connect to websites, emails (VM), Usenet
4830 messages (Gnus), BBDB entries, and any files related to the project.
4831 For printing and sharing of notes, an Org-mode file (or a part of it)
4832 can be exported as a structured ASCII or HTML file.
4834 The following commands are available:
4836 \\{org-mode-map}"
4838 ;; Get rid of Outline menus, they are not needed
4839 ;; Need to do this here because define-derived-mode sets up
4840 ;; the keymap so late. Still, it is a waste to call this each time
4841 ;; we switch another buffer into org-mode.
4842 (if (featurep 'xemacs)
4843 (when (boundp 'outline-mode-menu-heading)
4844 ;; Assume this is Greg's port, it used easymenu
4845 (easy-menu-remove outline-mode-menu-heading)
4846 (easy-menu-remove outline-mode-menu-show)
4847 (easy-menu-remove outline-mode-menu-hide))
4848 (define-key org-mode-map [menu-bar headings] 'undefined)
4849 (define-key org-mode-map [menu-bar hide] 'undefined)
4850 (define-key org-mode-map [menu-bar show] 'undefined))
4852 (easy-menu-add org-org-menu)
4853 (easy-menu-add org-tbl-menu)
4854 (org-install-agenda-files-menu)
4855 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4856 (org-add-to-invisibility-spec '(org-cwidth))
4857 (when (featurep 'xemacs)
4858 (org-set-local 'line-move-ignore-invisible t))
4859 (org-set-local 'outline-regexp org-outline-regexp)
4860 (org-set-local 'outline-level 'org-outline-level)
4861 (when (and org-ellipsis
4862 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4863 (fboundp 'make-glyph-code))
4864 (unless org-display-table
4865 (setq org-display-table (make-display-table)))
4866 (set-display-table-slot
4867 org-display-table 4
4868 (vconcat (mapcar
4869 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4870 org-ellipsis)))
4871 (if (stringp org-ellipsis) org-ellipsis "..."))))
4872 (setq buffer-display-table org-display-table))
4873 (org-set-regexps-and-options)
4874 ;; Calc embedded
4875 (org-set-local 'calc-embedded-open-mode "# ")
4876 (modify-syntax-entry ?# "<")
4877 (modify-syntax-entry ?@ "w")
4878 (if org-startup-truncated (setq truncate-lines t))
4879 (org-set-local 'font-lock-unfontify-region-function
4880 'org-unfontify-region)
4881 ;; Activate before-change-function
4882 (org-set-local 'org-table-may-need-update t)
4883 (org-add-hook 'before-change-functions 'org-before-change-function nil
4884 'local)
4885 ;; Check for running clock before killing a buffer
4886 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4887 ;; Paragraphs and auto-filling
4888 (org-set-autofill-regexps)
4889 (setq indent-line-function 'org-indent-line-function)
4890 (org-update-radio-target-regexp)
4892 ;; Comment characters
4893 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4894 (org-set-local 'comment-padding " ")
4896 ;; Imenu
4897 (org-set-local 'imenu-create-index-function
4898 'org-imenu-get-tree)
4900 ;; Make isearch reveal context
4901 (if (or (featurep 'xemacs)
4902 (not (boundp 'outline-isearch-open-invisible-function)))
4903 ;; Emacs 21 and XEmacs make use of the hook
4904 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4905 ;; Emacs 22 deals with this through a special variable
4906 (org-set-local 'outline-isearch-open-invisible-function
4907 (lambda (&rest ignore) (org-show-context 'isearch))))
4909 ;; If empty file that did not turn on org-mode automatically, make it to.
4910 (if (and org-insert-mode-line-in-empty-file
4911 (interactive-p)
4912 (= (point-min) (point-max)))
4913 (insert "# -*- mode: org -*-\n\n"))
4915 (unless org-inhibit-startup
4916 (when org-startup-align-all-tables
4917 (let ((bmp (buffer-modified-p)))
4918 (org-table-map-tables 'org-table-align)
4919 (set-buffer-modified-p bmp)))
4920 (org-cycle-hide-drawers 'all)
4921 (cond
4922 ((eq org-startup-folded t)
4923 (org-cycle '(4)))
4924 ((eq org-startup-folded 'content)
4925 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4926 (org-cycle '(4)) (org-cycle '(4)))))))
4928 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4930 (defsubst org-call-with-arg (command arg)
4931 "Call COMMAND interactively, but pretend prefix are was ARG."
4932 (let ((current-prefix-arg arg)) (call-interactively command)))
4934 (defsubst org-current-line (&optional pos)
4935 (save-excursion
4936 (and pos (goto-char pos))
4937 ;; works also in narrowed buffer, because we start at 1, not point-min
4938 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4940 (defun org-current-time ()
4941 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4942 (if (> org-time-stamp-rounding-minutes 0)
4943 (let ((r org-time-stamp-rounding-minutes)
4944 (time (decode-time)))
4945 (apply 'encode-time
4946 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4947 (nthcdr 2 time))))
4948 (current-time)))
4950 (defun org-add-props (string plist &rest props)
4951 "Add text properties to entire string, from beginning to end.
4952 PLIST may be a list of properties, PROPS are individual properties and values
4953 that will be added to PLIST. Returns the string that was modified."
4954 (add-text-properties
4955 0 (length string) (if props (append plist props) plist) string)
4956 string)
4957 (put 'org-add-props 'lisp-indent-function 2)
4960 ;;;; Font-Lock stuff, including the activators
4962 (defvar org-mouse-map (make-sparse-keymap))
4963 (org-defkey org-mouse-map
4964 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4965 (org-defkey org-mouse-map
4966 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4967 (when org-mouse-1-follows-link
4968 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4969 (when org-tab-follows-link
4970 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4971 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4972 (when org-return-follows-link
4973 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4974 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4976 (require 'font-lock)
4978 (defconst org-non-link-chars "]\t\n\r<>")
4979 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4980 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
4981 (defvar org-link-re-with-space nil
4982 "Matches a link with spaces, optional angular brackets around it.")
4983 (defvar org-link-re-with-space2 nil
4984 "Matches a link with spaces, optional angular brackets around it.")
4985 (defvar org-angle-link-re nil
4986 "Matches link with angular brackets, spaces are allowed.")
4987 (defvar org-plain-link-re nil
4988 "Matches plain link, without spaces.")
4989 (defvar org-bracket-link-regexp nil
4990 "Matches a link in double brackets.")
4991 (defvar org-bracket-link-analytic-regexp nil
4992 "Regular expression used to analyze links.
4993 Here is what the match groups contain after a match:
4994 1: http:
4995 2: http
4996 3: path
4997 4: [desc]
4998 5: desc")
4999 (defvar org-any-link-re nil
5000 "Regular expression matching any link.")
5002 (defun org-make-link-regexps ()
5003 "Update the link regular expressions.
5004 This should be called after the variable `org-link-types' has changed."
5005 (setq org-link-re-with-space
5006 (concat
5007 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5008 "\\([^" org-non-link-chars " ]"
5009 "[^" org-non-link-chars "]*"
5010 "[^" org-non-link-chars " ]\\)>?")
5011 org-link-re-with-space2
5012 (concat
5013 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5014 "\\([^" org-non-link-chars " ]"
5015 "[^]\t\n\r]*"
5016 "[^" org-non-link-chars " ]\\)>?")
5017 org-angle-link-re
5018 (concat
5019 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5020 "\\([^" org-non-link-chars " ]"
5021 "[^" org-non-link-chars "]*"
5022 "\\)>")
5023 org-plain-link-re
5024 (concat
5025 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5026 "\\([^]\t\n\r<>,;() ]+\\)")
5027 org-bracket-link-regexp
5028 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5029 org-bracket-link-analytic-regexp
5030 (concat
5031 "\\[\\["
5032 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5033 "\\([^]]+\\)"
5034 "\\]"
5035 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5036 "\\]")
5037 org-any-link-re
5038 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5039 org-angle-link-re "\\)\\|\\("
5040 org-plain-link-re "\\)")))
5042 (org-make-link-regexps)
5044 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5045 "Regular expression for fast time stamp matching.")
5046 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5047 "Regular expression for fast time stamp matching.")
5048 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5049 "Regular expression matching time strings for analysis.
5050 This one does not require the space after the date.")
5051 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5052 "Regular expression matching time strings for analysis.")
5053 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5054 "Regular expression matching time stamps, with groups.")
5055 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5056 "Regular expression matching time stamps (also [..]), with groups.")
5057 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5058 "Regular expression matching a time stamp range.")
5059 (defconst org-tr-regexp-both
5060 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5061 "Regular expression matching a time stamp range.")
5062 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5063 org-ts-regexp "\\)?")
5064 "Regular expression matching a time stamp or time stamp range.")
5065 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5066 org-ts-regexp-both "\\)?")
5067 "Regular expression matching a time stamp or time stamp range.
5068 The time stamps may be either active or inactive.")
5070 (defvar org-emph-face nil)
5072 (defun org-do-emphasis-faces (limit)
5073 "Run through the buffer and add overlays to links."
5074 (let (rtn)
5075 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5076 (if (not (= (char-after (match-beginning 3))
5077 (char-after (match-beginning 4))))
5078 (progn
5079 (setq rtn t)
5080 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5081 'face
5082 (nth 1 (assoc (match-string 3)
5083 org-emphasis-alist)))
5084 (add-text-properties (match-beginning 2) (match-end 2)
5085 '(font-lock-multiline t))
5086 (when org-hide-emphasis-markers
5087 (add-text-properties (match-end 4) (match-beginning 5)
5088 '(invisible org-link))
5089 (add-text-properties (match-beginning 3) (match-end 3)
5090 '(invisible org-link)))))
5091 (backward-char 1))
5092 rtn))
5094 (defun org-emphasize (&optional char)
5095 "Insert or change an emphasis, i.e. a font like bold or italic.
5096 If there is an active region, change that region to a new emphasis.
5097 If there is no region, just insert the marker characters and position
5098 the cursor between them.
5099 CHAR should be either the marker character, or the first character of the
5100 HTML tag associated with that emphasis. If CHAR is a space, the means
5101 to remove the emphasis of the selected region.
5102 If char is not given (for example in an interactive call) it
5103 will be prompted for."
5104 (interactive)
5105 (let ((eal org-emphasis-alist) e det
5106 (erc org-emphasis-regexp-components)
5107 (prompt "")
5108 (string "") beg end move tag c s)
5109 (if (org-region-active-p)
5110 (setq beg (region-beginning) end (region-end)
5111 string (buffer-substring beg end))
5112 (setq move t))
5114 (while (setq e (pop eal))
5115 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5116 c (aref tag 0))
5117 (push (cons c (string-to-char (car e))) det)
5118 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5119 (substring tag 1)))))
5120 (unless char
5121 (message "%s" (concat "Emphasis marker or tag:" prompt))
5122 (setq char (read-char-exclusive)))
5123 (setq char (or (cdr (assoc char det)) char))
5124 (if (equal char ?\ )
5125 (setq s "" move nil)
5126 (unless (assoc (char-to-string char) org-emphasis-alist)
5127 (error "No such emphasis marker: \"%c\"" char))
5128 (setq s (char-to-string char)))
5129 (while (and (> (length string) 1)
5130 (equal (substring string 0 1) (substring string -1))
5131 (assoc (substring string 0 1) org-emphasis-alist))
5132 (setq string (substring string 1 -1)))
5133 (setq string (concat s string s))
5134 (if beg (delete-region beg end))
5135 (unless (or (bolp)
5136 (string-match (concat "[" (nth 0 erc) "\n]")
5137 (char-to-string (char-before (point)))))
5138 (insert " "))
5139 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5140 (char-to-string (char-after (point))))
5141 (insert " ") (backward-char 1))
5142 (insert string)
5143 (and move (backward-char 1))))
5145 (defconst org-nonsticky-props
5146 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5149 (defun org-activate-plain-links (limit)
5150 "Run through the buffer and add overlays to links."
5151 (catch 'exit
5152 (let (f)
5153 (while (re-search-forward org-plain-link-re limit t)
5154 (setq f (get-text-property (match-beginning 0) 'face))
5155 (if (or (eq f 'org-tag)
5156 (and (listp f) (memq 'org-tag f)))
5158 (add-text-properties (match-beginning 0) (match-end 0)
5159 (list 'mouse-face 'highlight
5160 'rear-nonsticky org-nonsticky-props
5161 'keymap org-mouse-map
5163 (throw 'exit t))))))
5165 (defun org-activate-code (limit)
5166 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5167 (unless (get-text-property (match-beginning 1) 'face)
5168 (remove-text-properties (match-beginning 0) (match-end 0)
5169 '(display t invisible t intangible t))
5170 t)))
5172 (defun org-activate-angle-links (limit)
5173 "Run through the buffer and add overlays to links."
5174 (if (re-search-forward org-angle-link-re limit t)
5175 (progn
5176 (add-text-properties (match-beginning 0) (match-end 0)
5177 (list 'mouse-face 'highlight
5178 'rear-nonsticky org-nonsticky-props
5179 'keymap org-mouse-map
5181 t)))
5183 (defmacro org-maybe-intangible (props)
5184 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5185 In emacs 21, invisible text is not avoided by the command loop, so the
5186 intangible property is needed to make sure point skips this text.
5187 In Emacs 22, this is not necessary. The intangible text property has
5188 led to problems with flyspell. These problems are fixed in flyspell.el,
5189 but we still avoid setting the property in Emacs 22 and later.
5190 We use a macro so that the test can happen at compilation time."
5191 (if (< emacs-major-version 22)
5192 `(append '(intangible t) ,props)
5193 props))
5195 (defun org-activate-bracket-links (limit)
5196 "Run through the buffer and add overlays to bracketed links."
5197 (if (re-search-forward org-bracket-link-regexp limit t)
5198 (let* ((help (concat "LINK: "
5199 (org-match-string-no-properties 1)))
5200 ;; FIXME: above we should remove the escapes.
5201 ;; but that requires another match, protecting match data,
5202 ;; a lot of overhead for font-lock.
5203 (ip (org-maybe-intangible
5204 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5205 'keymap org-mouse-map 'mouse-face 'highlight
5206 'font-lock-multiline t 'help-echo help)))
5207 (vp (list 'rear-nonsticky org-nonsticky-props
5208 'keymap org-mouse-map 'mouse-face 'highlight
5209 ' font-lock-multiline t 'help-echo help)))
5210 ;; We need to remove the invisible property here. Table narrowing
5211 ;; may have made some of this invisible.
5212 (remove-text-properties (match-beginning 0) (match-end 0)
5213 '(invisible nil))
5214 (if (match-end 3)
5215 (progn
5216 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5217 (add-text-properties (match-beginning 3) (match-end 3) vp)
5218 (add-text-properties (match-end 3) (match-end 0) ip))
5219 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5220 (add-text-properties (match-beginning 1) (match-end 1) vp)
5221 (add-text-properties (match-end 1) (match-end 0) ip))
5222 t)))
5224 (defun org-activate-dates (limit)
5225 "Run through the buffer and add overlays to dates."
5226 (if (re-search-forward org-tsr-regexp-both limit t)
5227 (progn
5228 (add-text-properties (match-beginning 0) (match-end 0)
5229 (list 'mouse-face 'highlight
5230 'rear-nonsticky org-nonsticky-props
5231 'keymap org-mouse-map))
5232 (when org-display-custom-times
5233 (if (match-end 3)
5234 (org-display-custom-time (match-beginning 3) (match-end 3)))
5235 (org-display-custom-time (match-beginning 1) (match-end 1)))
5236 t)))
5238 (defvar org-target-link-regexp nil
5239 "Regular expression matching radio targets in plain text.")
5240 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5241 "Regular expression matching a link target.")
5242 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5243 "Regular expression matching a radio target.")
5244 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5245 "Regular expression matching any target.")
5247 (defun org-activate-target-links (limit)
5248 "Run through the buffer and add overlays to target matches."
5249 (when org-target-link-regexp
5250 (let ((case-fold-search t))
5251 (if (re-search-forward org-target-link-regexp limit t)
5252 (progn
5253 (add-text-properties (match-beginning 0) (match-end 0)
5254 (list 'mouse-face 'highlight
5255 'rear-nonsticky org-nonsticky-props
5256 'keymap org-mouse-map
5257 'help-echo "Radio target link"
5258 'org-linked-text t))
5259 t)))))
5261 (defun org-update-radio-target-regexp ()
5262 "Find all radio targets in this file and update the regular expression."
5263 (interactive)
5264 (when (memq 'radio org-activate-links)
5265 (setq org-target-link-regexp
5266 (org-make-target-link-regexp (org-all-targets 'radio)))
5267 (org-restart-font-lock)))
5269 (defun org-hide-wide-columns (limit)
5270 (let (s e)
5271 (setq s (text-property-any (point) (or limit (point-max))
5272 'org-cwidth t))
5273 (when s
5274 (setq e (next-single-property-change s 'org-cwidth))
5275 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5276 (goto-char e)
5277 t)))
5279 (defvar org-latex-and-specials-regexp nil
5280 "Regular expression for highlighting export special stuff.")
5281 (defvar org-match-substring-regexp)
5282 (defvar org-match-substring-with-braces-regexp)
5283 (defvar org-export-html-special-string-regexps)
5285 (defun org-compute-latex-and-specials-regexp ()
5286 "Compute regular expression for stuff treated specially by exporters."
5287 (if (not org-highlight-latex-fragments-and-specials)
5288 (org-set-local 'org-latex-and-specials-regexp nil)
5289 (let*
5290 ((matchers (plist-get org-format-latex-options :matchers))
5291 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5292 org-latex-regexps)))
5293 (options (org-combine-plists (org-default-export-plist)
5294 (org-infile-export-plist)))
5295 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5296 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5297 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5298 (org-export-html-expand (plist-get options :expand-quoted-html))
5299 (org-export-with-special-strings (plist-get options :special-strings))
5300 (re-sub
5301 (cond
5302 ((equal org-export-with-sub-superscripts '{})
5303 (list org-match-substring-with-braces-regexp))
5304 (org-export-with-sub-superscripts
5305 (list org-match-substring-regexp))
5306 (t nil)))
5307 (re-latex
5308 (if org-export-with-LaTeX-fragments
5309 (mapcar (lambda (x) (nth 1 x)) latexs)))
5310 (re-macros
5311 (if org-export-with-TeX-macros
5312 (list (concat "\\\\"
5313 (regexp-opt
5314 (append (mapcar 'car org-html-entities)
5315 (if (boundp 'org-latex-entities)
5316 org-latex-entities nil))
5317 'words))) ; FIXME
5319 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5320 (re-special (if org-export-with-special-strings
5321 (mapcar (lambda (x) (car x))
5322 org-export-html-special-string-regexps)))
5323 (re-rest
5324 (delq nil
5325 (list
5326 (if org-export-html-expand "@<[^>\n]+>")
5327 ))))
5328 (org-set-local
5329 'org-latex-and-specials-regexp
5330 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5331 re-rest) "\\|")))))
5333 (defface org-latex-and-export-specials
5334 (let ((font (cond ((assq :inherit custom-face-attributes)
5335 '(:inherit underline))
5336 (t '(:underline t)))))
5337 `((((class grayscale) (background light))
5338 (:foreground "DimGray" ,@font))
5339 (((class grayscale) (background dark))
5340 (:foreground "LightGray" ,@font))
5341 (((class color) (background light))
5342 (:foreground "SaddleBrown"))
5343 (((class color) (background dark))
5344 (:foreground "burlywood"))
5345 (t (,@font))))
5346 "Face used to highlight math latex and other special exporter stuff."
5347 :group 'org-faces)
5349 (defun org-do-latex-and-special-faces (limit)
5350 "Run through the buffer and add overlays to links."
5351 (when org-latex-and-specials-regexp
5352 (let (rtn d)
5353 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5354 limit t))
5355 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5356 'face))
5357 '(org-code org-verbatim underline)))
5358 (progn
5359 (setq rtn t
5360 d (cond ((member (char-after (1+ (match-beginning 0)))
5361 '(?_ ?^)) 1)
5362 (t 0)))
5363 (font-lock-prepend-text-property
5364 (+ d (match-beginning 0)) (match-end 0)
5365 'face 'org-latex-and-export-specials)
5366 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5367 '(font-lock-multiline t)))))
5368 rtn)))
5370 (defun org-restart-font-lock ()
5371 "Restart font-lock-mode, to force refontification."
5372 (when (and (boundp 'font-lock-mode) font-lock-mode)
5373 (font-lock-mode -1)
5374 (font-lock-mode 1)))
5376 (defun org-all-targets (&optional radio)
5377 "Return a list of all targets in this file.
5378 With optional argument RADIO, only find radio targets."
5379 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5380 rtn)
5381 (save-excursion
5382 (goto-char (point-min))
5383 (while (re-search-forward re nil t)
5384 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5385 rtn)))
5387 (defun org-make-target-link-regexp (targets)
5388 "Make regular expression matching all strings in TARGETS.
5389 The regular expression finds the targets also if there is a line break
5390 between words."
5391 (and targets
5392 (concat
5393 "\\<\\("
5394 (mapconcat
5395 (lambda (x)
5396 (while (string-match " +" x)
5397 (setq x (replace-match "\\s-+" t t x)))
5399 targets
5400 "\\|")
5401 "\\)\\>")))
5403 (defun org-activate-tags (limit)
5404 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5405 (progn
5406 (add-text-properties (match-beginning 1) (match-end 1)
5407 (list 'mouse-face 'highlight
5408 'rear-nonsticky org-nonsticky-props
5409 'keymap org-mouse-map))
5410 t)))
5412 (defun org-outline-level ()
5413 (save-excursion
5414 (looking-at outline-regexp)
5415 (if (match-beginning 1)
5416 (+ (org-get-string-indentation (match-string 1)) 1000)
5417 (1- (- (match-end 0) (match-beginning 0))))))
5419 (defvar org-font-lock-keywords nil)
5421 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5422 "Regular expression matching a property line.")
5424 (defun org-set-font-lock-defaults ()
5425 (let* ((em org-fontify-emphasized-text)
5426 (lk org-activate-links)
5427 (org-font-lock-extra-keywords
5428 (list
5429 ;; Headlines
5430 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5431 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5432 ;; Table lines
5433 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5434 (1 'org-table t))
5435 ;; Table internals
5436 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5437 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5438 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5439 ;; Drawers
5440 (list org-drawer-regexp '(0 'org-special-keyword t))
5441 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5442 ;; Properties
5443 (list org-property-re
5444 '(1 'org-special-keyword t)
5445 '(3 'org-property-value t))
5446 (if org-format-transports-properties-p
5447 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5448 ;; Links
5449 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5450 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5451 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5452 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5453 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5454 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5455 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5456 '(org-hide-wide-columns (0 nil append))
5457 ;; TODO lines
5458 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5459 '(1 (org-get-todo-face 1) t))
5460 ;; DONE
5461 (if org-fontify-done-headline
5462 (list (concat "^[*]+ +\\<\\("
5463 (mapconcat 'regexp-quote org-done-keywords "\\|")
5464 "\\)\\(.*\\)")
5465 '(2 'org-headline-done t))
5466 nil)
5467 ;; Priorities
5468 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5469 ;; Special keywords
5470 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5471 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5472 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5473 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5474 ;; Emphasis
5475 (if em
5476 (if (featurep 'xemacs)
5477 '(org-do-emphasis-faces (0 nil append))
5478 '(org-do-emphasis-faces)))
5479 ;; Checkboxes
5480 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5481 2 'bold prepend)
5482 (if org-provide-checkbox-statistics
5483 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5484 (0 (org-get-checkbox-statistics-face) t)))
5485 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5486 '(1 'org-archived prepend))
5487 ;; Specials
5488 '(org-do-latex-and-special-faces)
5489 ;; Code
5490 '(org-activate-code (1 'org-code t))
5491 ;; COMMENT
5492 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5493 "\\|" org-quote-string "\\)\\>")
5494 '(1 'org-special-keyword t))
5495 '("^#.*" (0 'font-lock-comment-face t))
5497 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5498 ;; Now set the full font-lock-keywords
5499 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5500 (org-set-local 'font-lock-defaults
5501 '(org-font-lock-keywords t nil nil backward-paragraph))
5502 (kill-local-variable 'font-lock-keywords) nil))
5504 (defvar org-m nil)
5505 (defvar org-l nil)
5506 (defvar org-f nil)
5507 (defun org-get-level-face (n)
5508 "Get the right face for match N in font-lock matching of healdines."
5509 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5510 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5511 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5512 (cond
5513 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5514 ((eq n 2) org-f)
5515 (t (if org-level-color-stars-only nil org-f))))
5517 (defun org-get-todo-face (kwd)
5518 "Get the right face for a TODO keyword KWD.
5519 If KWD is a number, get the corresponding match group."
5520 (if (numberp kwd) (setq kwd (match-string kwd)))
5521 (or (cdr (assoc kwd org-todo-keyword-faces))
5522 (and (member kwd org-done-keywords) 'org-done)
5523 'org-todo))
5525 (defun org-unfontify-region (beg end &optional maybe_loudly)
5526 "Remove fontification and activation overlays from links."
5527 (font-lock-default-unfontify-region beg end)
5528 (let* ((buffer-undo-list t)
5529 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5530 (inhibit-modification-hooks t)
5531 deactivate-mark buffer-file-name buffer-file-truename)
5532 (remove-text-properties beg end
5533 '(mouse-face t keymap t org-linked-text t
5534 invisible t intangible t))))
5536 ;;;; Visibility cycling, including org-goto and indirect buffer
5538 ;;; Cycling
5540 (defvar org-cycle-global-status nil)
5541 (make-variable-buffer-local 'org-cycle-global-status)
5542 (defvar org-cycle-subtree-status nil)
5543 (make-variable-buffer-local 'org-cycle-subtree-status)
5545 ;;;###autoload
5546 (defun org-cycle (&optional arg)
5547 "Visibility cycling for Org-mode.
5549 - When this function is called with a prefix argument, rotate the entire
5550 buffer through 3 states (global cycling)
5551 1. OVERVIEW: Show only top-level headlines.
5552 2. CONTENTS: Show all headlines of all levels, but no body text.
5553 3. SHOW ALL: Show everything.
5555 - When point is at the beginning of a headline, rotate the subtree started
5556 by this line through 3 different states (local cycling)
5557 1. FOLDED: Only the main headline is shown.
5558 2. CHILDREN: The main headline and the direct children are shown.
5559 From this state, you can move to one of the children
5560 and zoom in further.
5561 3. SUBTREE: Show the entire subtree, including body text.
5563 - When there is a numeric prefix, go up to a heading with level ARG, do
5564 a `show-subtree' and return to the previous cursor position. If ARG
5565 is negative, go up that many levels.
5567 - When point is not at the beginning of a headline, execute
5568 `indent-relative', like TAB normally does. See the option
5569 `org-cycle-emulate-tab' for details.
5571 - Special case: if point is at the beginning of the buffer and there is
5572 no headline in line 1, this function will act as if called with prefix arg.
5573 But only if also the variable `org-cycle-global-at-bob' is t."
5574 (interactive "P")
5575 (let* ((outline-regexp
5576 (if (and (org-mode-p) org-cycle-include-plain-lists)
5577 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5578 outline-regexp))
5579 (bob-special (and org-cycle-global-at-bob (bobp)
5580 (not (looking-at outline-regexp))))
5581 (org-cycle-hook
5582 (if bob-special
5583 (delq 'org-optimize-window-after-visibility-change
5584 (copy-sequence org-cycle-hook))
5585 org-cycle-hook))
5586 (pos (point)))
5588 (if (or bob-special (equal arg '(4)))
5589 ;; special case: use global cycling
5590 (setq arg t))
5592 (cond
5594 ((org-at-table-p 'any)
5595 ;; Enter the table or move to the next field in the table
5596 (or (org-table-recognize-table.el)
5597 (progn
5598 (if arg (org-table-edit-field t)
5599 (org-table-justify-field-maybe)
5600 (call-interactively 'org-table-next-field)))))
5602 ((eq arg t) ;; Global cycling
5604 (cond
5605 ((and (eq last-command this-command)
5606 (eq org-cycle-global-status 'overview))
5607 ;; We just created the overview - now do table of contents
5608 ;; This can be slow in very large buffers, so indicate action
5609 (message "CONTENTS...")
5610 (org-content)
5611 (message "CONTENTS...done")
5612 (setq org-cycle-global-status 'contents)
5613 (run-hook-with-args 'org-cycle-hook 'contents))
5615 ((and (eq last-command this-command)
5616 (eq org-cycle-global-status 'contents))
5617 ;; We just showed the table of contents - now show everything
5618 (show-all)
5619 (message "SHOW ALL")
5620 (setq org-cycle-global-status 'all)
5621 (run-hook-with-args 'org-cycle-hook 'all))
5624 ;; Default action: go to overview
5625 (org-overview)
5626 (message "OVERVIEW")
5627 (setq org-cycle-global-status 'overview)
5628 (run-hook-with-args 'org-cycle-hook 'overview))))
5630 ((and org-drawers org-drawer-regexp
5631 (save-excursion
5632 (beginning-of-line 1)
5633 (looking-at org-drawer-regexp)))
5634 ;; Toggle block visibility
5635 (org-flag-drawer
5636 (not (get-char-property (match-end 0) 'invisible))))
5638 ((integerp arg)
5639 ;; Show-subtree, ARG levels up from here.
5640 (save-excursion
5641 (org-back-to-heading)
5642 (outline-up-heading (if (< arg 0) (- arg)
5643 (- (funcall outline-level) arg)))
5644 (org-show-subtree)))
5646 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5647 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5648 ;; At a heading: rotate between three different views
5649 (org-back-to-heading)
5650 (let ((goal-column 0) eoh eol eos)
5651 ;; First, some boundaries
5652 (save-excursion
5653 (org-back-to-heading)
5654 (save-excursion
5655 (beginning-of-line 2)
5656 (while (and (not (eobp)) ;; this is like `next-line'
5657 (get-char-property (1- (point)) 'invisible))
5658 (beginning-of-line 2)) (setq eol (point)))
5659 (outline-end-of-heading) (setq eoh (point))
5660 (org-end-of-subtree t)
5661 (unless (eobp)
5662 (skip-chars-forward " \t\n")
5663 (beginning-of-line 1) ; in case this is an item
5665 (setq eos (1- (point))))
5666 ;; Find out what to do next and set `this-command'
5667 (cond
5668 ((= eos eoh)
5669 ;; Nothing is hidden behind this heading
5670 (message "EMPTY ENTRY")
5671 (setq org-cycle-subtree-status nil)
5672 (save-excursion
5673 (goto-char eos)
5674 (outline-next-heading)
5675 (if (org-invisible-p) (org-flag-heading nil))))
5676 ((or (>= eol eos)
5677 (not (string-match "\\S-" (buffer-substring eol eos))))
5678 ;; Entire subtree is hidden in one line: open it
5679 (org-show-entry)
5680 (show-children)
5681 (message "CHILDREN")
5682 (save-excursion
5683 (goto-char eos)
5684 (outline-next-heading)
5685 (if (org-invisible-p) (org-flag-heading nil)))
5686 (setq org-cycle-subtree-status 'children)
5687 (run-hook-with-args 'org-cycle-hook 'children))
5688 ((and (eq last-command this-command)
5689 (eq org-cycle-subtree-status 'children))
5690 ;; We just showed the children, now show everything.
5691 (org-show-subtree)
5692 (message "SUBTREE")
5693 (setq org-cycle-subtree-status 'subtree)
5694 (run-hook-with-args 'org-cycle-hook 'subtree))
5696 ;; Default action: hide the subtree.
5697 (hide-subtree)
5698 (message "FOLDED")
5699 (setq org-cycle-subtree-status 'folded)
5700 (run-hook-with-args 'org-cycle-hook 'folded)))))
5702 ;; TAB emulation
5703 (buffer-read-only (org-back-to-heading))
5705 ((org-try-cdlatex-tab))
5707 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5708 (or (not (bolp))
5709 (not (looking-at outline-regexp))))
5710 (call-interactively (global-key-binding "\t")))
5712 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5713 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5714 (or (and (eq org-cycle-emulate-tab 'white)
5715 (= (match-end 0) (point-at-eol)))
5716 (and (eq org-cycle-emulate-tab 'whitestart)
5717 (>= (match-end 0) pos))))
5719 (eq org-cycle-emulate-tab t))
5720 ; (if (and (looking-at "[ \n\r\t]")
5721 ; (string-match "^[ \t]*$" (buffer-substring
5722 ; (point-at-bol) (point))))
5723 ; (progn
5724 ; (beginning-of-line 1)
5725 ; (and (looking-at "[ \t]+") (replace-match ""))))
5726 (call-interactively (global-key-binding "\t")))
5728 (t (save-excursion
5729 (org-back-to-heading)
5730 (org-cycle))))))
5732 ;;;###autoload
5733 (defun org-global-cycle (&optional arg)
5734 "Cycle the global visibility. For details see `org-cycle'."
5735 (interactive "P")
5736 (let ((org-cycle-include-plain-lists
5737 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5738 (if (integerp arg)
5739 (progn
5740 (show-all)
5741 (hide-sublevels arg)
5742 (setq org-cycle-global-status 'contents))
5743 (org-cycle '(4)))))
5745 (defun org-overview ()
5746 "Switch to overview mode, shoing only top-level headlines.
5747 Really, this shows all headlines with level equal or greater than the level
5748 of the first headline in the buffer. This is important, because if the
5749 first headline is not level one, then (hide-sublevels 1) gives confusing
5750 results."
5751 (interactive)
5752 (let ((level (save-excursion
5753 (goto-char (point-min))
5754 (if (re-search-forward (concat "^" outline-regexp) nil t)
5755 (progn
5756 (goto-char (match-beginning 0))
5757 (funcall outline-level))))))
5758 (and level (hide-sublevels level))))
5760 (defun org-content (&optional arg)
5761 "Show all headlines in the buffer, like a table of contents.
5762 With numerical argument N, show content up to level N."
5763 (interactive "P")
5764 (save-excursion
5765 ;; Visit all headings and show their offspring
5766 (and (integerp arg) (org-overview))
5767 (goto-char (point-max))
5768 (catch 'exit
5769 (while (and (progn (condition-case nil
5770 (outline-previous-visible-heading 1)
5771 (error (goto-char (point-min))))
5773 (looking-at outline-regexp))
5774 (if (integerp arg)
5775 (show-children (1- arg))
5776 (show-branches))
5777 (if (bobp) (throw 'exit nil))))))
5780 (defun org-optimize-window-after-visibility-change (state)
5781 "Adjust the window after a change in outline visibility.
5782 This function is the default value of the hook `org-cycle-hook'."
5783 (when (get-buffer-window (current-buffer))
5784 (cond
5785 ; ((eq state 'overview) (org-first-headline-recenter 1))
5786 ; ((eq state 'overview) (org-beginning-of-line))
5787 ((eq state 'content) nil)
5788 ((eq state 'all) nil)
5789 ((eq state 'folded) nil)
5790 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5791 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5793 (defun org-compact-display-after-subtree-move ()
5794 (let (beg end)
5795 (save-excursion
5796 (if (org-up-heading-safe)
5797 (progn
5798 (hide-subtree)
5799 (show-entry)
5800 (show-children)
5801 (org-cycle-show-empty-lines 'children)
5802 (org-cycle-hide-drawers 'children))
5803 (org-overview)))))
5805 (defun org-cycle-show-empty-lines (state)
5806 "Show empty lines above all visible headlines.
5807 The region to be covered depends on STATE when called through
5808 `org-cycle-hook'. Lisp program can use t for STATE to get the
5809 entire buffer covered. Note that an empty line is only shown if there
5810 are at least `org-cycle-separator-lines' empty lines before the headeline."
5811 (when (> org-cycle-separator-lines 0)
5812 (save-excursion
5813 (let* ((n org-cycle-separator-lines)
5814 (re (cond
5815 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5816 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5817 (t (let ((ns (number-to-string (- n 2))))
5818 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5819 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5820 beg end)
5821 (cond
5822 ((memq state '(overview contents t))
5823 (setq beg (point-min) end (point-max)))
5824 ((memq state '(children folded))
5825 (setq beg (point) end (progn (org-end-of-subtree t t)
5826 (beginning-of-line 2)
5827 (point)))))
5828 (when beg
5829 (goto-char beg)
5830 (while (re-search-forward re end t)
5831 (if (not (get-char-property (match-end 1) 'invisible))
5832 (outline-flag-region
5833 (match-beginning 1) (match-end 1) nil)))))))
5834 ;; Never hide empty lines at the end of the file.
5835 (save-excursion
5836 (goto-char (point-max))
5837 (outline-previous-heading)
5838 (outline-end-of-heading)
5839 (if (and (looking-at "[ \t\n]+")
5840 (= (match-end 0) (point-max)))
5841 (outline-flag-region (point) (match-end 0) nil))))
5843 (defun org-subtree-end-visible-p ()
5844 "Is the end of the current subtree visible?"
5845 (pos-visible-in-window-p
5846 (save-excursion (org-end-of-subtree t) (point))))
5848 (defun org-first-headline-recenter (&optional N)
5849 "Move cursor to the first headline and recenter the headline.
5850 Optional argument N means, put the headline into the Nth line of the window."
5851 (goto-char (point-min))
5852 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5853 (beginning-of-line)
5854 (recenter (prefix-numeric-value N))))
5856 ;;; Org-goto
5858 (defvar org-goto-window-configuration nil)
5859 (defvar org-goto-marker nil)
5860 (defvar org-goto-map
5861 (let ((map (make-sparse-keymap)))
5862 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5863 (while (setq cmd (pop cmds))
5864 (substitute-key-definition cmd cmd map global-map)))
5865 (suppress-keymap map)
5866 (org-defkey map "\C-m" 'org-goto-ret)
5867 (org-defkey map [(return)] 'org-goto-ret)
5868 (org-defkey map [(left)] 'org-goto-left)
5869 (org-defkey map [(right)] 'org-goto-right)
5870 (org-defkey map [(control ?g)] 'org-goto-quit)
5871 (org-defkey map "\C-i" 'org-cycle)
5872 (org-defkey map [(tab)] 'org-cycle)
5873 (org-defkey map [(down)] 'outline-next-visible-heading)
5874 (org-defkey map [(up)] 'outline-previous-visible-heading)
5875 (if org-goto-auto-isearch
5876 (define-key-after map [t] 'org-goto-local-auto-isearch)
5877 (org-defkey map "q" 'org-goto-quit)
5878 (org-defkey map "n" 'outline-next-visible-heading)
5879 (org-defkey map "p" 'outline-previous-visible-heading)
5880 (org-defkey map "f" 'outline-forward-same-level)
5881 (org-defkey map "b" 'outline-backward-same-level)
5882 (org-defkey map "u" 'outline-up-heading))
5883 (org-defkey map "/" 'org-occur)
5884 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5885 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5886 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5887 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5888 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5889 map))
5891 (defconst org-goto-help
5892 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5893 RET=jump to location [Q]uit and return to previous location
5894 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5896 (defvar org-goto-start-pos) ; dynamically scoped parameter
5898 (defun org-goto (&optional alternative-interface)
5899 "Look up a different location in the current file, keeping current visibility.
5901 When you want look-up or go to a different location in a document, the
5902 fastest way is often to fold the entire buffer and then dive into the tree.
5903 This method has the disadvantage, that the previous location will be folded,
5904 which may not be what you want.
5906 This command works around this by showing a copy of the current buffer
5907 in an indirect buffer, in overview mode. You can dive into the tree in
5908 that copy, use org-occur and incremental search to find a location.
5909 When pressing RET or `Q', the command returns to the original buffer in
5910 which the visibility is still unchanged. After RET is will also jump to
5911 the location selected in the indirect buffer and expose the
5912 the headline hierarchy above."
5913 (interactive "P")
5914 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
5915 (org-refile-use-outline-path t)
5916 (interface
5917 (if (not alternative-interface)
5918 org-goto-interface
5919 (if (eq org-goto-interface 'outline)
5920 'outline-path-completion
5921 'outline)))
5922 (org-goto-start-pos (point))
5923 (selected-point
5924 (if (eq interface 'outline)
5925 (car (org-get-location (current-buffer) org-goto-help))
5926 (nth 3 (org-refile-get-location "Goto: ")))))
5927 (if selected-point
5928 (progn
5929 (org-mark-ring-push org-goto-start-pos)
5930 (goto-char selected-point)
5931 (if (or (org-invisible-p) (org-invisible-p2))
5932 (org-show-context 'org-goto)))
5933 (message "Quit"))))
5935 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5936 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5938 (defun org-get-location (buf help)
5939 "Let the user select a location in the Org-mode buffer BUF.
5940 This function uses a recursive edit. It returns the selected position
5941 or nil."
5942 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5943 (isearch-hide-immediately nil)
5944 (isearch-search-fun-function
5945 (lambda () 'org-goto-local-search-forward-headings))
5946 (org-goto-selected-point org-goto-exit-command))
5947 (save-excursion
5948 (save-window-excursion
5949 (delete-other-windows)
5950 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5951 (switch-to-buffer
5952 (condition-case nil
5953 (make-indirect-buffer (current-buffer) "*org-goto*")
5954 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5955 (with-output-to-temp-buffer "*Help*"
5956 (princ help))
5957 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5958 (setq buffer-read-only nil)
5959 (let ((org-startup-truncated t)
5960 (org-startup-folded nil)
5961 (org-startup-align-all-tables nil))
5962 (org-mode)
5963 (org-overview))
5964 (setq buffer-read-only t)
5965 (if (and (boundp 'org-goto-start-pos)
5966 (integer-or-marker-p org-goto-start-pos))
5967 (let ((org-show-hierarchy-above t)
5968 (org-show-siblings t)
5969 (org-show-following-heading t))
5970 (goto-char org-goto-start-pos)
5971 (and (org-invisible-p) (org-show-context)))
5972 (goto-char (point-min)))
5973 (org-beginning-of-line)
5974 (message "Select location and press RET")
5975 (use-local-map org-goto-map)
5976 (recursive-edit)
5978 (kill-buffer "*org-goto*")
5979 (cons org-goto-selected-point org-goto-exit-command)))
5981 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5982 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5983 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5984 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5986 (defun org-goto-local-search-forward-headings (string bound noerror)
5987 "Search and make sure that anu matches are in headlines."
5988 (catch 'return
5989 (while (search-forward string bound noerror)
5990 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5991 (and (member :headline context)
5992 (not (member :tags context))))
5993 (throw 'return (point))))))
5995 (defun org-goto-local-auto-isearch ()
5996 "Start isearch."
5997 (interactive)
5998 (goto-char (point-min))
5999 (let ((keys (this-command-keys)))
6000 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6001 (isearch-mode t)
6002 (isearch-process-search-char (string-to-char keys)))))
6004 (defun org-goto-ret (&optional arg)
6005 "Finish `org-goto' by going to the new location."
6006 (interactive "P")
6007 (setq org-goto-selected-point (point)
6008 org-goto-exit-command 'return)
6009 (throw 'exit nil))
6011 (defun org-goto-left ()
6012 "Finish `org-goto' by going to the new location."
6013 (interactive)
6014 (if (org-on-heading-p)
6015 (progn
6016 (beginning-of-line 1)
6017 (setq org-goto-selected-point (point)
6018 org-goto-exit-command 'left)
6019 (throw 'exit nil))
6020 (error "Not on a heading")))
6022 (defun org-goto-right ()
6023 "Finish `org-goto' by going to the new location."
6024 (interactive)
6025 (if (org-on-heading-p)
6026 (progn
6027 (setq org-goto-selected-point (point)
6028 org-goto-exit-command 'right)
6029 (throw 'exit nil))
6030 (error "Not on a heading")))
6032 (defun org-goto-quit ()
6033 "Finish `org-goto' without cursor motion."
6034 (interactive)
6035 (setq org-goto-selected-point nil)
6036 (setq org-goto-exit-command 'quit)
6037 (throw 'exit nil))
6039 ;;; Indirect buffer display of subtrees
6041 (defvar org-indirect-dedicated-frame nil
6042 "This is the frame being used for indirect tree display.")
6043 (defvar org-last-indirect-buffer nil)
6045 (defun org-tree-to-indirect-buffer (&optional arg)
6046 "Create indirect buffer and narrow it to current subtree.
6047 With numerical prefix ARG, go up to this level and then take that tree.
6048 If ARG is negative, go up that many levels.
6049 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6050 indirect buffer previously made with this command, to avoid proliferation of
6051 indirect buffers. However, when you call the command with a `C-u' prefix, or
6052 when `org-indirect-buffer-display' is `new-frame', the last buffer
6053 is kept so that you can work with several indirect buffers at the same time.
6054 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6055 requests that a new frame be made for the new buffer, so that the dedicated
6056 frame is not changed."
6057 (interactive "P")
6058 (let ((cbuf (current-buffer))
6059 (cwin (selected-window))
6060 (pos (point))
6061 beg end level heading ibuf)
6062 (save-excursion
6063 (org-back-to-heading t)
6064 (when (numberp arg)
6065 (setq level (org-outline-level))
6066 (if (< arg 0) (setq arg (+ level arg)))
6067 (while (> (setq level (org-outline-level)) arg)
6068 (outline-up-heading 1 t)))
6069 (setq beg (point)
6070 heading (org-get-heading))
6071 (org-end-of-subtree t) (setq end (point)))
6072 (if (and (buffer-live-p org-last-indirect-buffer)
6073 (not (eq org-indirect-buffer-display 'new-frame))
6074 (not arg))
6075 (kill-buffer org-last-indirect-buffer))
6076 (setq ibuf (org-get-indirect-buffer cbuf)
6077 org-last-indirect-buffer ibuf)
6078 (cond
6079 ((or (eq org-indirect-buffer-display 'new-frame)
6080 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6081 (select-frame (make-frame))
6082 (delete-other-windows)
6083 (switch-to-buffer ibuf)
6084 (org-set-frame-title heading))
6085 ((eq org-indirect-buffer-display 'dedicated-frame)
6086 (raise-frame
6087 (select-frame (or (and org-indirect-dedicated-frame
6088 (frame-live-p org-indirect-dedicated-frame)
6089 org-indirect-dedicated-frame)
6090 (setq org-indirect-dedicated-frame (make-frame)))))
6091 (delete-other-windows)
6092 (switch-to-buffer ibuf)
6093 (org-set-frame-title (concat "Indirect: " heading)))
6094 ((eq org-indirect-buffer-display 'current-window)
6095 (switch-to-buffer ibuf))
6096 ((eq org-indirect-buffer-display 'other-window)
6097 (pop-to-buffer ibuf))
6098 (t (error "Invalid value.")))
6099 (if (featurep 'xemacs)
6100 (save-excursion (org-mode) (turn-on-font-lock)))
6101 (narrow-to-region beg end)
6102 (show-all)
6103 (goto-char pos)
6104 (and (window-live-p cwin) (select-window cwin))))
6106 (defun org-get-indirect-buffer (&optional buffer)
6107 (setq buffer (or buffer (current-buffer)))
6108 (let ((n 1) (base (buffer-name buffer)) bname)
6109 (while (buffer-live-p
6110 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6111 (setq n (1+ n)))
6112 (condition-case nil
6113 (make-indirect-buffer buffer bname 'clone)
6114 (error (make-indirect-buffer buffer bname)))))
6116 (defun org-set-frame-title (title)
6117 "Set the title of the current frame to the string TITLE."
6118 ;; FIXME: how to name a single frame in XEmacs???
6119 (unless (featurep 'xemacs)
6120 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6122 ;;;; Structure editing
6124 ;;; Inserting headlines
6126 (defun org-insert-heading (&optional force-heading)
6127 "Insert a new heading or item with same depth at point.
6128 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6129 If point is at the beginning of a headline, insert a sibling before the
6130 current headline. If point is in the middle of a headline, split the headline
6131 at that position and make the rest of the headline part of the sibling below
6132 the current headline."
6133 (interactive "P")
6134 (if (= (buffer-size) 0)
6135 (insert "\n* ")
6136 (when (or force-heading (not (org-insert-item)))
6137 (let* ((head (save-excursion
6138 (condition-case nil
6139 (progn
6140 (org-back-to-heading)
6141 (match-string 0))
6142 (error "*"))))
6143 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6144 pos)
6145 (cond
6146 ((and (org-on-heading-p) (bolp)
6147 (or (bobp)
6148 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6149 (open-line (if blank 2 1)))
6150 ((and (bolp)
6151 (or (bobp)
6152 (save-excursion
6153 (backward-char 1) (not (org-invisible-p)))))
6154 nil)
6155 (t (newline (if blank 2 1))))
6156 (insert head) (just-one-space)
6157 (setq pos (point))
6158 (end-of-line 1)
6159 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6160 (run-hooks 'org-insert-heading-hook)))))
6162 (defun org-insert-heading-after-current ()
6163 "Insert a new heading with same level as current, after current subtree."
6164 (interactive)
6165 (org-back-to-heading)
6166 (org-insert-heading)
6167 (org-move-subtree-down)
6168 (end-of-line 1))
6170 (defun org-insert-todo-heading (arg)
6171 "Insert a new heading with the same level and TODO state as current heading.
6172 If the heading has no TODO state, or if the state is DONE, use the first
6173 state (TODO by default). Also with prefix arg, force first state."
6174 (interactive "P")
6175 (when (not (org-insert-item 'checkbox))
6176 (org-insert-heading)
6177 (save-excursion
6178 (org-back-to-heading)
6179 (outline-previous-heading)
6180 (looking-at org-todo-line-regexp))
6181 (if (or arg
6182 (not (match-beginning 2))
6183 (member (match-string 2) org-done-keywords))
6184 (insert (car org-todo-keywords-1) " ")
6185 (insert (match-string 2) " "))))
6187 (defun org-insert-subheading (arg)
6188 "Insert a new subheading and demote it.
6189 Works for outline headings and for plain lists alike."
6190 (interactive "P")
6191 (org-insert-heading arg)
6192 (cond
6193 ((org-on-heading-p) (org-do-demote))
6194 ((org-at-item-p) (org-indent-item 1))))
6196 (defun org-insert-todo-subheading (arg)
6197 "Insert a new subheading with TODO keyword or checkbox and demote it.
6198 Works for outline headings and for plain lists alike."
6199 (interactive "P")
6200 (org-insert-todo-heading arg)
6201 (cond
6202 ((org-on-heading-p) (org-do-demote))
6203 ((org-at-item-p) (org-indent-item 1))))
6205 ;;; Promotion and Demotion
6207 (defun org-promote-subtree ()
6208 "Promote the entire subtree.
6209 See also `org-promote'."
6210 (interactive)
6211 (save-excursion
6212 (org-map-tree 'org-promote))
6213 (org-fix-position-after-promote))
6215 (defun org-demote-subtree ()
6216 "Demote the entire subtree. See `org-demote'.
6217 See also `org-promote'."
6218 (interactive)
6219 (save-excursion
6220 (org-map-tree 'org-demote))
6221 (org-fix-position-after-promote))
6224 (defun org-do-promote ()
6225 "Promote the current heading higher up the tree.
6226 If the region is active in `transient-mark-mode', promote all headings
6227 in the region."
6228 (interactive)
6229 (save-excursion
6230 (if (org-region-active-p)
6231 (org-map-region 'org-promote (region-beginning) (region-end))
6232 (org-promote)))
6233 (org-fix-position-after-promote))
6235 (defun org-do-demote ()
6236 "Demote the current heading lower down the tree.
6237 If the region is active in `transient-mark-mode', demote all headings
6238 in the region."
6239 (interactive)
6240 (save-excursion
6241 (if (org-region-active-p)
6242 (org-map-region 'org-demote (region-beginning) (region-end))
6243 (org-demote)))
6244 (org-fix-position-after-promote))
6246 (defun org-fix-position-after-promote ()
6247 "Make sure that after pro/demotion cursor position is right."
6248 (let ((pos (point)))
6249 (when (save-excursion
6250 (beginning-of-line 1)
6251 (looking-at org-todo-line-regexp)
6252 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6253 (cond ((eobp) (insert " "))
6254 ((eolp) (insert " "))
6255 ((equal (char-after) ?\ ) (forward-char 1))))))
6257 (defun org-reduced-level (l)
6258 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6260 (defun org-get-legal-level (level &optional change)
6261 "Rectify a level change under the influence of `org-odd-levels-only'
6262 LEVEL is a current level, CHANGE is by how much the level should be
6263 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6264 even level numbers will become the next higher odd number."
6265 (if org-odd-levels-only
6266 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6267 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6268 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6269 (max 1 (+ level change))))
6271 (defun org-promote ()
6272 "Promote the current heading higher up the tree.
6273 If the region is active in `transient-mark-mode', promote all headings
6274 in the region."
6275 (org-back-to-heading t)
6276 (let* ((level (save-match-data (funcall outline-level)))
6277 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6278 (diff (abs (- level (length up-head) -1))))
6279 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6280 (replace-match up-head nil t)
6281 ;; Fixup tag positioning
6282 (and org-auto-align-tags (org-set-tags nil t))
6283 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6285 (defun org-demote ()
6286 "Demote the current heading lower down the tree.
6287 If the region is active in `transient-mark-mode', demote all headings
6288 in the region."
6289 (org-back-to-heading t)
6290 (let* ((level (save-match-data (funcall outline-level)))
6291 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6292 (diff (abs (- level (length down-head) -1))))
6293 (replace-match down-head nil t)
6294 ;; Fixup tag positioning
6295 (and org-auto-align-tags (org-set-tags nil t))
6296 (if org-adapt-indentation (org-fixup-indentation diff))))
6298 (defun org-map-tree (fun)
6299 "Call FUN for every heading underneath the current one."
6300 (org-back-to-heading)
6301 (let ((level (funcall outline-level)))
6302 (save-excursion
6303 (funcall fun)
6304 (while (and (progn
6305 (outline-next-heading)
6306 (> (funcall outline-level) level))
6307 (not (eobp)))
6308 (funcall fun)))))
6310 (defun org-map-region (fun beg end)
6311 "Call FUN for every heading between BEG and END."
6312 (let ((org-ignore-region t))
6313 (save-excursion
6314 (setq end (copy-marker end))
6315 (goto-char beg)
6316 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6317 (< (point) end))
6318 (funcall fun))
6319 (while (and (progn
6320 (outline-next-heading)
6321 (< (point) end))
6322 (not (eobp)))
6323 (funcall fun)))))
6325 (defun org-fixup-indentation (diff)
6326 "Change the indentation in the current entry by DIFF
6327 However, if any line in the current entry has no indentation, or if it
6328 would end up with no indentation after the change, nothing at all is done."
6329 (save-excursion
6330 (let ((end (save-excursion (outline-next-heading)
6331 (point-marker)))
6332 (prohibit (if (> diff 0)
6333 "^\\S-"
6334 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6335 col)
6336 (unless (save-excursion (end-of-line 1)
6337 (re-search-forward prohibit end t))
6338 (while (and (< (point) end)
6339 (re-search-forward "^[ \t]+" end t))
6340 (goto-char (match-end 0))
6341 (setq col (current-column))
6342 (if (< diff 0) (replace-match ""))
6343 (indent-to (+ diff col))))
6344 (move-marker end nil))))
6346 (defun org-convert-to-odd-levels ()
6347 "Convert an org-mode file with all levels allowed to one with odd levels.
6348 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6349 level 5 etc."
6350 (interactive)
6351 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6352 (let ((org-odd-levels-only nil) n)
6353 (save-excursion
6354 (goto-char (point-min))
6355 (while (re-search-forward "^\\*\\*+ " nil t)
6356 (setq n (- (length (match-string 0)) 2))
6357 (while (>= (setq n (1- n)) 0)
6358 (org-demote))
6359 (end-of-line 1))))))
6362 (defun org-convert-to-oddeven-levels ()
6363 "Convert an org-mode file with only odd levels to one with odd and even levels.
6364 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6365 section with an even level, conversion would destroy the structure of the file. An error
6366 is signaled in this case."
6367 (interactive)
6368 (goto-char (point-min))
6369 ;; First check if there are no even levels
6370 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6371 (org-show-context t)
6372 (error "Not all levels are odd in this file. Conversion not possible."))
6373 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6374 (let ((org-odd-levels-only nil) n)
6375 (save-excursion
6376 (goto-char (point-min))
6377 (while (re-search-forward "^\\*\\*+ " nil t)
6378 (setq n (/ (1- (length (match-string 0))) 2))
6379 (while (>= (setq n (1- n)) 0)
6380 (org-promote))
6381 (end-of-line 1))))))
6383 (defun org-tr-level (n)
6384 "Make N odd if required."
6385 (if org-odd-levels-only (1+ (/ n 2)) n))
6387 ;;; Vertical tree motion, cutting and pasting of subtrees
6389 (defun org-move-subtree-up (&optional arg)
6390 "Move the current subtree up past ARG headlines of the same level."
6391 (interactive "p")
6392 (org-move-subtree-down (- (prefix-numeric-value arg))))
6394 (defun org-move-subtree-down (&optional arg)
6395 "Move the current subtree down past ARG headlines of the same level."
6396 (interactive "p")
6397 (setq arg (prefix-numeric-value arg))
6398 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6399 'outline-get-last-sibling))
6400 (ins-point (make-marker))
6401 (cnt (abs arg))
6402 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6403 ;; Select the tree
6404 (org-back-to-heading)
6405 (setq beg0 (point))
6406 (save-excursion
6407 (setq ne-beg (org-back-over-empty-lines))
6408 (setq beg (point)))
6409 (save-match-data
6410 (save-excursion (outline-end-of-heading)
6411 (setq folded (org-invisible-p)))
6412 (outline-end-of-subtree))
6413 (outline-next-heading)
6414 (setq ne-end (org-back-over-empty-lines))
6415 (setq end (point))
6416 (goto-char beg0)
6417 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6418 ;; include less whitespace
6419 (save-excursion
6420 (goto-char beg)
6421 (forward-line (- ne-beg ne-end))
6422 (setq beg (point))))
6423 ;; Find insertion point, with error handling
6424 (while (> cnt 0)
6425 (or (and (funcall movfunc) (looking-at outline-regexp))
6426 (progn (goto-char beg0)
6427 (error "Cannot move past superior level or buffer limit")))
6428 (setq cnt (1- cnt)))
6429 (if (> arg 0)
6430 ;; Moving forward - still need to move over subtree
6431 (progn (org-end-of-subtree t t)
6432 (save-excursion
6433 (org-back-over-empty-lines)
6434 (or (bolp) (newline)))))
6435 (setq ne-ins (org-back-over-empty-lines))
6436 (move-marker ins-point (point))
6437 (setq txt (buffer-substring beg end))
6438 (delete-region beg end)
6439 (outline-flag-region (1- beg) beg nil)
6440 (outline-flag-region (1- (point)) (point) nil)
6441 (insert txt)
6442 (or (bolp) (insert "\n"))
6443 (setq ins-end (point))
6444 (goto-char ins-point)
6445 (org-skip-whitespace)
6446 (when (and (< arg 0)
6447 (org-first-sibling-p)
6448 (> ne-ins ne-beg))
6449 ;; Move whitespace back to beginning
6450 (save-excursion
6451 (goto-char ins-end)
6452 (let ((kill-whole-line t))
6453 (kill-line (- ne-ins ne-beg)) (point)))
6454 (insert (make-string (- ne-ins ne-beg) ?\n)))
6455 (move-marker ins-point nil)
6456 (org-compact-display-after-subtree-move)
6457 (unless folded
6458 (org-show-entry)
6459 (show-children)
6460 (org-cycle-hide-drawers 'children))))
6462 (defvar org-subtree-clip ""
6463 "Clipboard for cut and paste of subtrees.
6464 This is actually only a copy of the kill, because we use the normal kill
6465 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6467 (defvar org-subtree-clip-folded nil
6468 "Was the last copied subtree folded?
6469 This is used to fold the tree back after pasting.")
6471 (defun org-cut-subtree (&optional n)
6472 "Cut the current subtree into the clipboard.
6473 With prefix arg N, cut this many sequential subtrees.
6474 This is a short-hand for marking the subtree and then cutting it."
6475 (interactive "p")
6476 (org-copy-subtree n 'cut))
6478 (defun org-copy-subtree (&optional n cut)
6479 "Cut the current subtree into the clipboard.
6480 With prefix arg N, cut this many sequential subtrees.
6481 This is a short-hand for marking the subtree and then copying it.
6482 If CUT is non-nil, actually cut the subtree."
6483 (interactive "p")
6484 (let (beg end folded (beg0 (point)))
6485 (if (interactive-p)
6486 (org-back-to-heading nil) ; take what looks like a subtree
6487 (org-back-to-heading t)) ; take what is really there
6488 (org-back-over-empty-lines)
6489 (setq beg (point))
6490 (skip-chars-forward " \t\r\n")
6491 (save-match-data
6492 (save-excursion (outline-end-of-heading)
6493 (setq folded (org-invisible-p)))
6494 (condition-case nil
6495 (outline-forward-same-level (1- n))
6496 (error nil))
6497 (org-end-of-subtree t t))
6498 (org-back-over-empty-lines)
6499 (setq end (point))
6500 (goto-char beg0)
6501 (when (> end beg)
6502 (setq org-subtree-clip-folded folded)
6503 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6504 (setq org-subtree-clip (current-kill 0))
6505 (message "%s: Subtree(s) with %d characters"
6506 (if cut "Cut" "Copied")
6507 (length org-subtree-clip)))))
6509 (defun org-paste-subtree (&optional level tree)
6510 "Paste the clipboard as a subtree, with modification of headline level.
6511 The entire subtree is promoted or demoted in order to match a new headline
6512 level. By default, the new level is derived from the visible headings
6513 before and after the insertion point, and taken to be the inferior headline
6514 level of the two. So if the previous visible heading is level 3 and the
6515 next is level 4 (or vice versa), level 4 will be used for insertion.
6516 This makes sure that the subtree remains an independent subtree and does
6517 not swallow low level entries.
6519 You can also force a different level, either by using a numeric prefix
6520 argument, or by inserting the heading marker by hand. For example, if the
6521 cursor is after \"*****\", then the tree will be shifted to level 5.
6523 If you want to insert the tree as is, just use \\[yank].
6525 If optional TREE is given, use this text instead of the kill ring."
6526 (interactive "P")
6527 (unless (org-kill-is-subtree-p tree)
6528 (error "%s"
6529 (substitute-command-keys
6530 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6531 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6532 (^re (concat "^\\(" outline-regexp "\\)"))
6533 (re (concat "\\(" outline-regexp "\\)"))
6534 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6536 (old-level (if (string-match ^re txt)
6537 (- (match-end 0) (match-beginning 0) 1)
6538 -1))
6539 (force-level (cond (level (prefix-numeric-value level))
6540 ((string-match
6541 ^re_ (buffer-substring (point-at-bol) (point)))
6542 (- (match-end 1) (match-beginning 1)))
6543 (t nil)))
6544 (previous-level (save-excursion
6545 (condition-case nil
6546 (progn
6547 (outline-previous-visible-heading 1)
6548 (if (looking-at re)
6549 (- (match-end 0) (match-beginning 0) 1)
6551 (error 1))))
6552 (next-level (save-excursion
6553 (condition-case nil
6554 (progn
6555 (or (looking-at outline-regexp)
6556 (outline-next-visible-heading 1))
6557 (if (looking-at re)
6558 (- (match-end 0) (match-beginning 0) 1)
6560 (error 1))))
6561 (new-level (or force-level (max previous-level next-level)))
6562 (shift (if (or (= old-level -1)
6563 (= new-level -1)
6564 (= old-level new-level))
6566 (- new-level old-level)))
6567 (delta (if (> shift 0) -1 1))
6568 (func (if (> shift 0) 'org-demote 'org-promote))
6569 (org-odd-levels-only nil)
6570 beg end)
6571 ;; Remove the forced level indicator
6572 (if force-level
6573 (delete-region (point-at-bol) (point)))
6574 ;; Paste
6575 (beginning-of-line 1)
6576 (org-back-over-empty-lines) ;; FIXME: correct fix????
6577 (setq beg (point))
6578 (insert-before-markers txt) ;; FIXME: correct fix????
6579 (unless (string-match "\n\\'" txt) (insert "\n"))
6580 (setq end (point))
6581 (goto-char beg)
6582 (skip-chars-forward " \t\n\r")
6583 (setq beg (point))
6584 ;; Shift if necessary
6585 (unless (= shift 0)
6586 (save-restriction
6587 (narrow-to-region beg end)
6588 (while (not (= shift 0))
6589 (org-map-region func (point-min) (point-max))
6590 (setq shift (+ delta shift)))
6591 (goto-char (point-min))))
6592 (when (interactive-p)
6593 (message "Clipboard pasted as level %d subtree" new-level))
6594 (if (and kill-ring
6595 (eq org-subtree-clip (current-kill 0))
6596 org-subtree-clip-folded)
6597 ;; The tree was folded before it was killed/copied
6598 (hide-subtree))))
6600 (defun org-kill-is-subtree-p (&optional txt)
6601 "Check if the current kill is an outline subtree, or a set of trees.
6602 Returns nil if kill does not start with a headline, or if the first
6603 headline level is not the largest headline level in the tree.
6604 So this will actually accept several entries of equal levels as well,
6605 which is OK for `org-paste-subtree'.
6606 If optional TXT is given, check this string instead of the current kill."
6607 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6608 (start-level (and kill
6609 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6610 org-outline-regexp "\\)")
6611 kill)
6612 (- (match-end 2) (match-beginning 2) 1)))
6613 (re (concat "^" org-outline-regexp))
6614 (start (1+ (match-beginning 2))))
6615 (if (not start-level)
6616 (progn
6617 nil) ;; does not even start with a heading
6618 (catch 'exit
6619 (while (setq start (string-match re kill (1+ start)))
6620 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6621 (throw 'exit nil)))
6622 t))))
6624 (defun org-narrow-to-subtree ()
6625 "Narrow buffer to the current subtree."
6626 (interactive)
6627 (save-excursion
6628 (narrow-to-region
6629 (progn (org-back-to-heading) (point))
6630 (progn (org-end-of-subtree t t) (point)))))
6633 ;;; Outline Sorting
6635 (defun org-sort (with-case)
6636 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6637 Optional argument WITH-CASE means sort case-sensitively."
6638 (interactive "P")
6639 (if (org-at-table-p)
6640 (org-call-with-arg 'org-table-sort-lines with-case)
6641 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6643 (defvar org-priority-regexp) ; defined later in the file
6645 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6646 "Sort entries on a certain level of an outline tree.
6647 If there is an active region, the entries in the region are sorted.
6648 Else, if the cursor is before the first entry, sort the top-level items.
6649 Else, the children of the entry at point are sorted.
6651 Sorting can be alphabetically, numerically, and by date/time as given by
6652 the first time stamp in the entry. The command prompts for the sorting
6653 type unless it has been given to the function through the SORTING-TYPE
6654 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6655 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6656 called with point at the beginning of the record. It must return either
6657 a string or a number that should serve as the sorting key for that record.
6659 Comparing entries ignores case by default. However, with an optional argument
6660 WITH-CASE, the sorting considers case as well."
6661 (interactive "P")
6662 (let ((case-func (if with-case 'identity 'downcase))
6663 start beg end stars re re2
6664 txt what tmp plain-list-p)
6665 ;; Find beginning and end of region to sort
6666 (cond
6667 ((org-region-active-p)
6668 ;; we will sort the region
6669 (setq end (region-end)
6670 what "region")
6671 (goto-char (region-beginning))
6672 (if (not (org-on-heading-p)) (outline-next-heading))
6673 (setq start (point)))
6674 ((org-at-item-p)
6675 ;; we will sort this plain list
6676 (org-beginning-of-item-list) (setq start (point))
6677 (org-end-of-item-list) (setq end (point))
6678 (goto-char start)
6679 (setq plain-list-p t
6680 what "plain list"))
6681 ((or (org-on-heading-p)
6682 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6683 ;; we will sort the children of the current headline
6684 (org-back-to-heading)
6685 (setq start (point)
6686 end (progn (org-end-of-subtree t t)
6687 (org-back-over-empty-lines)
6688 (point))
6689 what "children")
6690 (goto-char start)
6691 (show-subtree)
6692 (outline-next-heading))
6694 ;; we will sort the top-level entries in this file
6695 (goto-char (point-min))
6696 (or (org-on-heading-p) (outline-next-heading))
6697 (setq start (point) end (point-max) what "top-level")
6698 (goto-char start)
6699 (show-all)))
6701 (setq beg (point))
6702 (if (>= beg end) (error "Nothing to sort"))
6704 (unless plain-list-p
6705 (looking-at "\\(\\*+\\)")
6706 (setq stars (match-string 1)
6707 re (concat "^" (regexp-quote stars) " +")
6708 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6709 txt (buffer-substring beg end))
6710 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6711 (if (and (not (equal stars "*")) (string-match re2 txt))
6712 (error "Region to sort contains a level above the first entry")))
6714 (unless sorting-type
6715 (message
6716 (if plain-list-p
6717 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6718 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6719 what)
6720 (setq sorting-type (read-char-exclusive))
6722 (and (= (downcase sorting-type) ?f)
6723 (setq getkey-func
6724 (completing-read "Sort using function: "
6725 obarray 'fboundp t nil nil))
6726 (setq getkey-func (intern getkey-func)))
6728 (and (= (downcase sorting-type) ?r)
6729 (setq property
6730 (completing-read "Property: "
6731 (mapcar 'list (org-buffer-property-keys t))
6732 nil t))))
6734 (message "Sorting entries...")
6736 (save-restriction
6737 (narrow-to-region start end)
6739 (let ((dcst (downcase sorting-type))
6740 (now (current-time)))
6741 (sort-subr
6742 (/= dcst sorting-type)
6743 ;; This function moves to the beginning character of the "record" to
6744 ;; be sorted.
6745 (if plain-list-p
6746 (lambda nil
6747 (if (org-at-item-p) t (goto-char (point-max))))
6748 (lambda nil
6749 (if (re-search-forward re nil t)
6750 (goto-char (match-beginning 0))
6751 (goto-char (point-max)))))
6752 ;; This function moves to the last character of the "record" being
6753 ;; sorted.
6754 (if plain-list-p
6755 'org-end-of-item
6756 (lambda nil
6757 (save-match-data
6758 (condition-case nil
6759 (outline-forward-same-level 1)
6760 (error
6761 (goto-char (point-max)))))))
6763 ;; This function returns the value that gets sorted against.
6764 (if plain-list-p
6765 (lambda nil
6766 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6767 (cond
6768 ((= dcst ?n)
6769 (string-to-number (buffer-substring (match-end 0)
6770 (point-at-eol))))
6771 ((= dcst ?a)
6772 (buffer-substring (match-end 0) (point-at-eol)))
6773 ((= dcst ?t)
6774 (if (re-search-forward org-ts-regexp
6775 (point-at-eol) t)
6776 (org-time-string-to-time (match-string 0))
6777 now))
6778 ((= dcst ?f)
6779 (if getkey-func
6780 (progn
6781 (setq tmp (funcall getkey-func))
6782 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6783 tmp)
6784 (error "Invalid key function `%s'" getkey-func)))
6785 (t (error "Invalid sorting type `%c'" sorting-type)))))
6786 (lambda nil
6787 (cond
6788 ((= dcst ?n)
6789 (if (looking-at outline-regexp)
6790 (string-to-number (buffer-substring (match-end 0)
6791 (point-at-eol)))
6792 nil))
6793 ((= dcst ?a)
6794 (funcall case-func (buffer-substring (point-at-bol)
6795 (point-at-eol))))
6796 ((= dcst ?t)
6797 (if (re-search-forward org-ts-regexp
6798 (save-excursion
6799 (forward-line 2)
6800 (point)) t)
6801 (org-time-string-to-time (match-string 0))
6802 now))
6803 ((= dcst ?p)
6804 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6805 (string-to-char (match-string 2))
6806 org-default-priority))
6807 ((= dcst ?r)
6808 (or (org-entry-get nil property) ""))
6809 ((= dcst ?f)
6810 (if getkey-func
6811 (progn
6812 (setq tmp (funcall getkey-func))
6813 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6814 tmp)
6815 (error "Invalid key function `%s'" getkey-func)))
6816 (t (error "Invalid sorting type `%c'" sorting-type)))))
6818 (cond
6819 ((= dcst ?a) 'string<)
6820 ((= dcst ?t) 'time-less-p)
6821 (t nil)))))
6822 (message "Sorting entries...done")))
6824 (defun org-do-sort (table what &optional with-case sorting-type)
6825 "Sort TABLE of WHAT according to SORTING-TYPE.
6826 The user will be prompted for the SORTING-TYPE if the call to this
6827 function does not specify it. WHAT is only for the prompt, to indicate
6828 what is being sorted. The sorting key will be extracted from
6829 the car of the elements of the table.
6830 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6831 (unless sorting-type
6832 (message
6833 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6834 what)
6835 (setq sorting-type (read-char-exclusive)))
6836 (let ((dcst (downcase sorting-type))
6837 extractfun comparefun)
6838 ;; Define the appropriate functions
6839 (cond
6840 ((= dcst ?n)
6841 (setq extractfun 'string-to-number
6842 comparefun (if (= dcst sorting-type) '< '>)))
6843 ((= dcst ?a)
6844 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6845 (lambda(x) (downcase (org-sort-remove-invisible x))))
6846 comparefun (if (= dcst sorting-type)
6847 'string<
6848 (lambda (a b) (and (not (string< a b))
6849 (not (string= a b)))))))
6850 ((= dcst ?t)
6851 (setq extractfun
6852 (lambda (x)
6853 (if (string-match org-ts-regexp x)
6854 (time-to-seconds
6855 (org-time-string-to-time (match-string 0 x)))
6857 comparefun (if (= dcst sorting-type) '< '>)))
6858 (t (error "Invalid sorting type `%c'" sorting-type)))
6860 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6861 table)
6862 (lambda (a b) (funcall comparefun (car a) (car b))))))
6864 ;;;; Plain list items, including checkboxes
6866 ;;; Plain list items
6868 (defun org-at-item-p ()
6869 "Is point in a line starting a hand-formatted item?"
6870 (let ((llt org-plain-list-ordered-item-terminator))
6871 (save-excursion
6872 (goto-char (point-at-bol))
6873 (looking-at
6874 (cond
6875 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6876 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6877 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6878 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6880 (defun org-in-item-p ()
6881 "It the cursor inside a plain list item.
6882 Does not have to be the first line."
6883 (save-excursion
6884 (condition-case nil
6885 (progn
6886 (org-beginning-of-item)
6887 (org-at-item-p)
6889 (error nil))))
6891 (defun org-insert-item (&optional checkbox)
6892 "Insert a new item at the current level.
6893 Return t when things worked, nil when we are not in an item."
6894 (when (save-excursion
6895 (condition-case nil
6896 (progn
6897 (org-beginning-of-item)
6898 (org-at-item-p)
6899 (if (org-invisible-p) (error "Invisible item"))
6901 (error nil)))
6902 (let* ((bul (match-string 0))
6903 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6904 (match-end 0)))
6905 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6906 pos)
6907 (cond
6908 ((and (org-at-item-p) (<= (point) eow))
6909 ;; before the bullet
6910 (beginning-of-line 1)
6911 (open-line (if blank 2 1)))
6912 ((<= (point) eow)
6913 (beginning-of-line 1))
6914 (t (newline (if blank 2 1))))
6915 (insert bul (if checkbox "[ ]" ""))
6916 (just-one-space)
6917 (setq pos (point))
6918 (end-of-line 1)
6919 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6920 (org-maybe-renumber-ordered-list)
6921 (and checkbox (org-update-checkbox-count-maybe))
6924 ;;; Checkboxes
6926 (defun org-at-item-checkbox-p ()
6927 "Is point at a line starting a plain-list item with a checklet?"
6928 (and (org-at-item-p)
6929 (save-excursion
6930 (goto-char (match-end 0))
6931 (skip-chars-forward " \t")
6932 (looking-at "\\[[- X]\\]"))))
6934 (defun org-toggle-checkbox (&optional arg)
6935 "Toggle the checkbox in the current line."
6936 (interactive "P")
6937 (catch 'exit
6938 (let (beg end status (firstnew 'unknown))
6939 (cond
6940 ((org-region-active-p)
6941 (setq beg (region-beginning) end (region-end)))
6942 ((org-on-heading-p)
6943 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6944 ((org-at-item-checkbox-p)
6945 (let ((pos (point)))
6946 (replace-match
6947 (cond (arg "[-]")
6948 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6949 (t "[ ]"))
6950 t t)
6951 (goto-char pos))
6952 (throw 'exit t))
6953 (t (error "Not at a checkbox or heading, and no active region")))
6954 (save-excursion
6955 (goto-char beg)
6956 (while (< (point) end)
6957 (when (org-at-item-checkbox-p)
6958 (setq status (equal (match-string 0) "[X]"))
6959 (when (eq firstnew 'unknown)
6960 (setq firstnew (not status)))
6961 (replace-match
6962 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6963 (beginning-of-line 2)))))
6964 (org-update-checkbox-count-maybe))
6966 (defun org-update-checkbox-count-maybe ()
6967 "Update checkbox statistics unless turned off by user."
6968 (when org-provide-checkbox-statistics
6969 (org-update-checkbox-count)))
6971 (defun org-update-checkbox-count (&optional all)
6972 "Update the checkbox statistics in the current section.
6973 This will find all statistic cookies like [57%] and [6/12] and update them
6974 with the current numbers. With optional prefix argument ALL, do this for
6975 the whole buffer."
6976 (interactive "P")
6977 (save-excursion
6978 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6979 (beg (condition-case nil
6980 (progn (outline-back-to-heading) (point))
6981 (error (point-min))))
6982 (end (move-marker (make-marker)
6983 (progn (outline-next-heading) (point))))
6984 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6985 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6986 b1 e1 f1 c-on c-off lim (cstat 0))
6987 (when all
6988 (goto-char (point-min))
6989 (outline-next-heading)
6990 (setq beg (point) end (point-max)))
6991 (goto-char beg)
6992 (while (re-search-forward re end t)
6993 (setq cstat (1+ cstat)
6994 b1 (match-beginning 0)
6995 e1 (match-end 0)
6996 f1 (match-beginning 1)
6997 lim (cond
6998 ((org-on-heading-p) (outline-next-heading) (point))
6999 ((org-at-item-p) (org-end-of-item) (point))
7000 (t nil))
7001 c-on 0 c-off 0)
7002 (goto-char e1)
7003 (when lim
7004 (while (re-search-forward re-box lim t)
7005 (if (member (match-string 2) '("[ ]" "[-]"))
7006 (setq c-off (1+ c-off))
7007 (setq c-on (1+ c-on))))
7008 ; (delete-region b1 e1)
7009 (goto-char b1)
7010 (insert (if f1
7011 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7012 (format "[%d/%d]" c-on (+ c-on c-off))))
7013 (and (looking-at "\\[.*?\\]")
7014 (replace-match ""))))
7015 (when (interactive-p)
7016 (message "Checkbox satistics updated %s (%d places)"
7017 (if all "in entire file" "in current outline entry") cstat)))))
7019 (defun org-get-checkbox-statistics-face ()
7020 "Select the face for checkbox statistics.
7021 The face will be `org-done' when all relevant boxes are checked. Otherwise
7022 it will be `org-todo'."
7023 (if (match-end 1)
7024 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7025 (if (and (> (match-end 2) (match-beginning 2))
7026 (equal (match-string 2) (match-string 3)))
7027 'org-done
7028 'org-todo)))
7030 (defun org-get-indentation (&optional line)
7031 "Get the indentation of the current line, interpreting tabs.
7032 When LINE is given, assume it represents a line and compute its indentation."
7033 (if line
7034 (if (string-match "^ *" (org-remove-tabs line))
7035 (match-end 0))
7036 (save-excursion
7037 (beginning-of-line 1)
7038 (skip-chars-forward " \t")
7039 (current-column))))
7041 (defun org-remove-tabs (s &optional width)
7042 "Replace tabulators in S with spaces.
7043 Assumes that s is a single line, starting in column 0."
7044 (setq width (or width tab-width))
7045 (while (string-match "\t" s)
7046 (setq s (replace-match
7047 (make-string
7048 (- (* width (/ (+ (match-beginning 0) width) width))
7049 (match-beginning 0)) ?\ )
7050 t t s)))
7053 (defun org-fix-indentation (line ind)
7054 "Fix indentation in LINE.
7055 IND is a cons cell with target and minimum indentation.
7056 If the current indenation in LINE is smaller than the minimum,
7057 leave it alone. If it is larger than ind, set it to the target."
7058 (let* ((l (org-remove-tabs line))
7059 (i (org-get-indentation l))
7060 (i1 (car ind)) (i2 (cdr ind)))
7061 (if (>= i i2) (setq l (substring line i2)))
7062 (if (> i1 0)
7063 (concat (make-string i1 ?\ ) l)
7064 l)))
7066 (defcustom org-empty-line-terminates-plain-lists nil
7067 "Non-nil means, an empty line ends all plain list levels.
7068 When nil, empty lines are part of the preceeding item."
7069 :group 'org-plain-lists
7070 :type 'boolean)
7072 (defun org-beginning-of-item ()
7073 "Go to the beginning of the current hand-formatted item.
7074 If the cursor is not in an item, throw an error."
7075 (interactive)
7076 (let ((pos (point))
7077 (limit (save-excursion
7078 (condition-case nil
7079 (progn
7080 (org-back-to-heading)
7081 (beginning-of-line 2) (point))
7082 (error (point-min)))))
7083 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7084 ind ind1)
7085 (if (org-at-item-p)
7086 (beginning-of-line 1)
7087 (beginning-of-line 1)
7088 (skip-chars-forward " \t")
7089 (setq ind (current-column))
7090 (if (catch 'exit
7091 (while t
7092 (beginning-of-line 0)
7093 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7095 (if (looking-at "[ \t]*$")
7096 (setq ind1 ind-empty)
7097 (skip-chars-forward " \t")
7098 (setq ind1 (current-column)))
7099 (if (< ind1 ind)
7100 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7102 (goto-char pos)
7103 (error "Not in an item")))))
7105 (defun org-end-of-item ()
7106 "Go to the end of the current hand-formatted item.
7107 If the cursor is not in an item, throw an error."
7108 (interactive)
7109 (let* ((pos (point))
7110 ind1
7111 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7112 (limit (save-excursion (outline-next-heading) (point)))
7113 (ind (save-excursion
7114 (org-beginning-of-item)
7115 (skip-chars-forward " \t")
7116 (current-column)))
7117 (end (catch 'exit
7118 (while t
7119 (beginning-of-line 2)
7120 (if (eobp) (throw 'exit (point)))
7121 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7122 (if (looking-at "[ \t]*$")
7123 (setq ind1 ind-empty)
7124 (skip-chars-forward " \t")
7125 (setq ind1 (current-column)))
7126 (if (<= ind1 ind)
7127 (throw 'exit (point-at-bol)))))))
7128 (if end
7129 (goto-char end)
7130 (goto-char pos)
7131 (error "Not in an item"))))
7133 (defun org-next-item ()
7134 "Move to the beginning of the next item in the current plain list.
7135 Error if not at a plain list, or if this is the last item in the list."
7136 (interactive)
7137 (let (ind ind1 (pos (point)))
7138 (org-beginning-of-item)
7139 (setq ind (org-get-indentation))
7140 (org-end-of-item)
7141 (setq ind1 (org-get-indentation))
7142 (unless (and (org-at-item-p) (= ind ind1))
7143 (goto-char pos)
7144 (error "On last item"))))
7146 (defun org-previous-item ()
7147 "Move to the beginning of the previous item in the current plain list.
7148 Error if not at a plain list, or if this is the first item in the list."
7149 (interactive)
7150 (let (beg ind ind1 (pos (point)))
7151 (org-beginning-of-item)
7152 (setq beg (point))
7153 (setq ind (org-get-indentation))
7154 (goto-char beg)
7155 (catch 'exit
7156 (while t
7157 (beginning-of-line 0)
7158 (if (looking-at "[ \t]*$")
7160 (if (<= (setq ind1 (org-get-indentation)) ind)
7161 (throw 'exit t)))))
7162 (condition-case nil
7163 (if (or (not (org-at-item-p))
7164 (< ind1 (1- ind)))
7165 (error "")
7166 (org-beginning-of-item))
7167 (error (goto-char pos)
7168 (error "On first item")))))
7170 (defun org-first-list-item-p ()
7171 "Is this heading the item in a plain list?"
7172 (unless (org-at-item-p)
7173 (error "Not at a plain list item"))
7174 (org-beginning-of-item)
7175 (= (point) (save-excursion (org-beginning-of-item-list))))
7177 (defun org-move-item-down ()
7178 "Move the plain list item at point down, i.e. swap with following item.
7179 Subitems (items with larger indentation) are considered part of the item,
7180 so this really moves item trees."
7181 (interactive)
7182 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7183 (org-beginning-of-item)
7184 (setq beg0 (point))
7185 (save-excursion
7186 (setq ne-beg (org-back-over-empty-lines))
7187 (setq beg (point)))
7188 (goto-char beg0)
7189 (setq ind (org-get-indentation))
7190 (org-end-of-item)
7191 (setq end0 (point))
7192 (setq ind1 (org-get-indentation))
7193 (setq ne-end (org-back-over-empty-lines))
7194 (setq end (point))
7195 (goto-char beg0)
7196 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7197 ;; include less whitespace
7198 (save-excursion
7199 (goto-char beg)
7200 (forward-line (- ne-beg ne-end))
7201 (setq beg (point))))
7202 (goto-char end0)
7203 (if (and (org-at-item-p) (= ind ind1))
7204 (progn
7205 (org-end-of-item)
7206 (org-back-over-empty-lines)
7207 (setq txt (buffer-substring beg end))
7208 (save-excursion
7209 (delete-region beg end))
7210 (setq pos (point))
7211 (insert txt)
7212 (goto-char pos) (org-skip-whitespace)
7213 (org-maybe-renumber-ordered-list))
7214 (goto-char pos)
7215 (error "Cannot move this item further down"))))
7217 (defun org-move-item-up (arg)
7218 "Move the plain list item at point up, i.e. swap with previous item.
7219 Subitems (items with larger indentation) are considered part of the item,
7220 so this really moves item trees."
7221 (interactive "p")
7222 (let (beg beg0 end end0 ind ind1 (pos (point)) txt
7223 ne-beg ne-end ne-ins ins-end)
7224 (org-beginning-of-item)
7225 (setq beg0 (point))
7226 (setq ind (org-get-indentation))
7227 (save-excursion
7228 (setq ne-beg (org-back-over-empty-lines))
7229 (setq beg (point)))
7230 (goto-char beg0)
7231 (org-end-of-item)
7232 (setq ne-end (org-back-over-empty-lines))
7233 (setq end (point))
7234 (goto-char beg0)
7235 (catch 'exit
7236 (while t
7237 (beginning-of-line 0)
7238 (if (looking-at "[ \t]*$")
7239 (if org-empty-line-terminates-plain-lists
7240 (progn
7241 (goto-char pos)
7242 (error "Cannot move this item further up"))
7243 nil)
7244 (if (<= (setq ind1 (org-get-indentation)) ind)
7245 (throw 'exit t)))))
7246 (condition-case nil
7247 (org-beginning-of-item)
7248 (error (goto-char beg)
7249 (error "Cannot move this item further up")))
7250 (setq ind1 (org-get-indentation))
7251 (if (and (org-at-item-p) (= ind ind1))
7252 (progn
7253 (setq ne-ins (org-back-over-empty-lines))
7254 (setq txt (buffer-substring beg end))
7255 (save-excursion
7256 (delete-region beg end))
7257 (setq pos (point))
7258 (insert txt)
7259 (setq ins-end (point))
7260 (goto-char pos) (org-skip-whitespace)
7262 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7263 ;; Move whitespace back to beginning
7264 (save-excursion
7265 (goto-char ins-end)
7266 (let ((kill-whole-line t))
7267 (kill-line (- ne-ins ne-beg)) (point)))
7268 (insert (make-string (- ne-ins ne-beg) ?\n)))
7270 (org-maybe-renumber-ordered-list))
7271 (goto-char pos)
7272 (error "Cannot move this item further up"))))
7274 (defun org-maybe-renumber-ordered-list ()
7275 "Renumber the ordered list at point if setup allows it.
7276 This tests the user option `org-auto-renumber-ordered-lists' before
7277 doing the renumbering."
7278 (interactive)
7279 (when (and org-auto-renumber-ordered-lists
7280 (org-at-item-p))
7281 (if (match-beginning 3)
7282 (org-renumber-ordered-list 1)
7283 (org-fix-bullet-type))))
7285 (defun org-maybe-renumber-ordered-list-safe ()
7286 (condition-case nil
7287 (save-excursion
7288 (org-maybe-renumber-ordered-list))
7289 (error nil)))
7291 (defun org-cycle-list-bullet (&optional which)
7292 "Cycle through the different itemize/enumerate bullets.
7293 This cycle the entire list level through the sequence:
7295 `-' -> `+' -> `*' -> `1.' -> `1)'
7297 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7298 0 meand `-', 1 means `+' etc."
7299 (interactive "P")
7300 (org-preserve-lc
7301 (org-beginning-of-item-list)
7302 (org-at-item-p)
7303 (beginning-of-line 1)
7304 (let ((current (match-string 0))
7305 (prevp (eq which 'previous))
7306 new)
7307 (setq new (cond
7308 ((and (numberp which)
7309 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7310 ((string-match "-" current) (if prevp "1)" "+"))
7311 ((string-match "\\+" current)
7312 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7313 ((string-match "\\*" current) (if prevp "+" "1."))
7314 ((string-match "\\." current) (if prevp "*" "1)"))
7315 ((string-match ")" current) (if prevp "1." "-"))
7316 (t (error "This should not happen"))))
7317 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7318 (org-fix-bullet-type)
7319 (org-maybe-renumber-ordered-list))))
7321 (defun org-get-string-indentation (s)
7322 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7323 (let ((n -1) (i 0) (w tab-width) c)
7324 (catch 'exit
7325 (while (< (setq n (1+ n)) (length s))
7326 (setq c (aref s n))
7327 (cond ((= c ?\ ) (setq i (1+ i)))
7328 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7329 (t (throw 'exit t)))))
7332 (defun org-renumber-ordered-list (arg)
7333 "Renumber an ordered plain list.
7334 Cursor needs to be in the first line of an item, the line that starts
7335 with something like \"1.\" or \"2)\"."
7336 (interactive "p")
7337 (unless (and (org-at-item-p)
7338 (match-beginning 3))
7339 (error "This is not an ordered list"))
7340 (let ((line (org-current-line))
7341 (col (current-column))
7342 (ind (org-get-string-indentation
7343 (buffer-substring (point-at-bol) (match-beginning 3))))
7344 ;; (term (substring (match-string 3) -1))
7345 ind1 (n (1- arg))
7346 fmt)
7347 ;; find where this list begins
7348 (org-beginning-of-item-list)
7349 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7350 (setq fmt (concat "%d" (match-string 1)))
7351 (beginning-of-line 0)
7352 ;; walk forward and replace these numbers
7353 (catch 'exit
7354 (while t
7355 (catch 'next
7356 (beginning-of-line 2)
7357 (if (eobp) (throw 'exit nil))
7358 (if (looking-at "[ \t]*$") (throw 'next nil))
7359 (skip-chars-forward " \t") (setq ind1 (current-column))
7360 (if (> ind1 ind) (throw 'next t))
7361 (if (< ind1 ind) (throw 'exit t))
7362 (if (not (org-at-item-p)) (throw 'exit nil))
7363 (delete-region (match-beginning 2) (match-end 2))
7364 (goto-char (match-beginning 2))
7365 (insert (format fmt (setq n (1+ n)))))))
7366 (goto-line line)
7367 (move-to-column col)))
7369 (defun org-fix-bullet-type ()
7370 "Make sure all items in this list have the same bullet as the firsst item."
7371 (interactive)
7372 (unless (org-at-item-p) (error "This is not a list"))
7373 (let ((line (org-current-line))
7374 (col (current-column))
7375 (ind (current-indentation))
7376 ind1 bullet)
7377 ;; find where this list begins
7378 (org-beginning-of-item-list)
7379 (beginning-of-line 1)
7380 ;; find out what the bullet type is
7381 (looking-at "[ \t]*\\(\\S-+\\)")
7382 (setq bullet (match-string 1))
7383 ;; walk forward and replace these numbers
7384 (beginning-of-line 0)
7385 (catch 'exit
7386 (while t
7387 (catch 'next
7388 (beginning-of-line 2)
7389 (if (eobp) (throw 'exit nil))
7390 (if (looking-at "[ \t]*$") (throw 'next nil))
7391 (skip-chars-forward " \t") (setq ind1 (current-column))
7392 (if (> ind1 ind) (throw 'next t))
7393 (if (< ind1 ind) (throw 'exit t))
7394 (if (not (org-at-item-p)) (throw 'exit nil))
7395 (skip-chars-forward " \t")
7396 (looking-at "\\S-+")
7397 (replace-match bullet))))
7398 (goto-line line)
7399 (move-to-column col)
7400 (if (string-match "[0-9]" bullet)
7401 (org-renumber-ordered-list 1))))
7403 (defun org-beginning-of-item-list ()
7404 "Go to the beginning of the current item list.
7405 I.e. to the first item in this list."
7406 (interactive)
7407 (org-beginning-of-item)
7408 (let ((pos (point-at-bol))
7409 (ind (org-get-indentation))
7410 ind1)
7411 ;; find where this list begins
7412 (catch 'exit
7413 (while t
7414 (catch 'next
7415 (beginning-of-line 0)
7416 (if (looking-at "[ \t]*$")
7417 (throw (if (bobp) 'exit 'next) t))
7418 (skip-chars-forward " \t") (setq ind1 (current-column))
7419 (if (or (< ind1 ind)
7420 (and (= ind1 ind)
7421 (not (org-at-item-p)))
7422 (bobp))
7423 (throw 'exit t)
7424 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7425 (goto-char pos)))
7428 (defun org-end-of-item-list ()
7429 "Go to the end of the current item list.
7430 I.e. to the text after the last item."
7431 (interactive)
7432 (org-beginning-of-item)
7433 (let ((pos (point-at-bol))
7434 (ind (org-get-indentation))
7435 ind1)
7436 ;; find where this list begins
7437 (catch 'exit
7438 (while t
7439 (catch 'next
7440 (beginning-of-line 2)
7441 (if (looking-at "[ \t]*$")
7442 (throw (if (eobp) 'exit 'next) t))
7443 (skip-chars-forward " \t") (setq ind1 (current-column))
7444 (if (or (< ind1 ind)
7445 (and (= ind1 ind)
7446 (not (org-at-item-p)))
7447 (eobp))
7448 (progn
7449 (setq pos (point-at-bol))
7450 (throw 'exit t))))))
7451 (goto-char pos)))
7454 (defvar org-last-indent-begin-marker (make-marker))
7455 (defvar org-last-indent-end-marker (make-marker))
7457 (defun org-outdent-item (arg)
7458 "Outdent a local list item."
7459 (interactive "p")
7460 (org-indent-item (- arg)))
7462 (defun org-indent-item (arg)
7463 "Indent a local list item."
7464 (interactive "p")
7465 (unless (org-at-item-p)
7466 (error "Not on an item"))
7467 (save-excursion
7468 (let (beg end ind ind1 tmp delta ind-down ind-up)
7469 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7470 (setq beg org-last-indent-begin-marker
7471 end org-last-indent-end-marker)
7472 (org-beginning-of-item)
7473 (setq beg (move-marker org-last-indent-begin-marker (point)))
7474 (org-end-of-item)
7475 (setq end (move-marker org-last-indent-end-marker (point))))
7476 (goto-char beg)
7477 (setq tmp (org-item-indent-positions)
7478 ind (car tmp)
7479 ind-down (nth 2 tmp)
7480 ind-up (nth 1 tmp)
7481 delta (if (> arg 0)
7482 (if ind-down (- ind-down ind) 2)
7483 (if ind-up (- ind-up ind) -2)))
7484 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7485 (while (< (point) end)
7486 (beginning-of-line 1)
7487 (skip-chars-forward " \t") (setq ind1 (current-column))
7488 (delete-region (point-at-bol) (point))
7489 (or (eolp) (indent-to-column (+ ind1 delta)))
7490 (beginning-of-line 2))))
7491 (org-fix-bullet-type)
7492 (org-maybe-renumber-ordered-list-safe)
7493 (save-excursion
7494 (beginning-of-line 0)
7495 (condition-case nil (org-beginning-of-item) (error nil))
7496 (org-maybe-renumber-ordered-list-safe)))
7498 (defun org-item-indent-positions ()
7499 "Return indentation for plain list items.
7500 This returns a list with three values: The current indentation, the
7501 parent indentation and the indentation a child should habe.
7502 Assumes cursor in item line."
7503 (let* ((bolpos (point-at-bol))
7504 (ind (org-get-indentation))
7505 ind-down ind-up pos)
7506 (save-excursion
7507 (org-beginning-of-item-list)
7508 (skip-chars-backward "\n\r \t")
7509 (when (org-in-item-p)
7510 (org-beginning-of-item)
7511 (setq ind-up (org-get-indentation))))
7512 (setq pos (point))
7513 (save-excursion
7514 (cond
7515 ((and (condition-case nil (progn (org-previous-item) t)
7516 (error nil))
7517 (or (forward-char 1) t)
7518 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7519 (setq ind-down (org-get-indentation)))
7520 ((and (goto-char pos)
7521 (org-at-item-p))
7522 (goto-char (match-end 0))
7523 (skip-chars-forward " \t")
7524 (setq ind-down (current-column)))))
7525 (list ind ind-up ind-down)))
7527 ;;; The orgstruct minor mode
7529 ;; Define a minor mode which can be used in other modes in order to
7530 ;; integrate the org-mode structure editing commands.
7532 ;; This is really a hack, because the org-mode structure commands use
7533 ;; keys which normally belong to the major mode. Here is how it
7534 ;; works: The minor mode defines all the keys necessary to operate the
7535 ;; structure commands, but wraps the commands into a function which
7536 ;; tests if the cursor is currently at a headline or a plain list
7537 ;; item. If that is the case, the structure command is used,
7538 ;; temporarily setting many Org-mode variables like regular
7539 ;; expressions for filling etc. However, when any of those keys is
7540 ;; used at a different location, function uses `key-binding' to look
7541 ;; up if the key has an associated command in another currently active
7542 ;; keymap (minor modes, major mode, global), and executes that
7543 ;; command. There might be problems if any of the keys is otherwise
7544 ;; used as a prefix key.
7546 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7547 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7548 ;; addresses this by checking explicitly for both bindings.
7550 (defvar orgstruct-mode-map (make-sparse-keymap)
7551 "Keymap for the minor `orgstruct-mode'.")
7553 (defvar org-local-vars nil
7554 "List of local variables, for use by `orgstruct-mode'")
7556 ;;;###autoload
7557 (define-minor-mode orgstruct-mode
7558 "Toggle the minor more `orgstruct-mode'.
7559 This mode is for using Org-mode structure commands in other modes.
7560 The following key behave as if Org-mode was active, if the cursor
7561 is on a headline, or on a plain list item (both in the definition
7562 of Org-mode).
7564 M-up Move entry/item up
7565 M-down Move entry/item down
7566 M-left Promote
7567 M-right Demote
7568 M-S-up Move entry/item up
7569 M-S-down Move entry/item down
7570 M-S-left Promote subtree
7571 M-S-right Demote subtree
7572 M-q Fill paragraph and items like in Org-mode
7573 C-c ^ Sort entries
7574 C-c - Cycle list bullet
7575 TAB Cycle item visibility
7576 M-RET Insert new heading/item
7577 S-M-RET Insert new TODO heading / Chekbox item
7578 C-c C-c Set tags / toggle checkbox"
7579 nil " OrgStruct" nil
7580 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7582 ;;;###autoload
7583 (defun turn-on-orgstruct ()
7584 "Unconditionally turn on `orgstruct-mode'."
7585 (orgstruct-mode 1))
7587 ;;;###autoload
7588 (defun turn-on-orgstruct++ ()
7589 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7590 In addition to setting orgstruct-mode, this also exports all indentation and
7591 autofilling variables from org-mode into the buffer. Note that turning
7592 off orgstruct-mode will *not* remove these additional settings."
7593 (orgstruct-mode 1)
7594 (let (var val)
7595 (mapc
7596 (lambda (x)
7597 (when (string-match
7598 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7599 (symbol-name (car x)))
7600 (setq var (car x) val (nth 1 x))
7601 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7602 org-local-vars)))
7604 (defun orgstruct-error ()
7605 "Error when there is no default binding for a structure key."
7606 (interactive)
7607 (error "This key has no function outside structure elements"))
7609 (defun orgstruct-setup ()
7610 "Setup orgstruct keymaps."
7611 (let ((nfunc 0)
7612 (bindings
7613 (list
7614 '([(meta up)] org-metaup)
7615 '([(meta down)] org-metadown)
7616 '([(meta left)] org-metaleft)
7617 '([(meta right)] org-metaright)
7618 '([(meta shift up)] org-shiftmetaup)
7619 '([(meta shift down)] org-shiftmetadown)
7620 '([(meta shift left)] org-shiftmetaleft)
7621 '([(meta shift right)] org-shiftmetaright)
7622 '([(shift up)] org-shiftup)
7623 '([(shift down)] org-shiftdown)
7624 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7625 '("\M-q" fill-paragraph)
7626 '("\C-c^" org-sort)
7627 '("\C-c-" org-cycle-list-bullet)))
7628 elt key fun cmd)
7629 (while (setq elt (pop bindings))
7630 (setq nfunc (1+ nfunc))
7631 (setq key (org-key (car elt))
7632 fun (nth 1 elt)
7633 cmd (orgstruct-make-binding fun nfunc key))
7634 (org-defkey orgstruct-mode-map key cmd))
7636 ;; Special treatment needed for TAB and RET
7637 (org-defkey orgstruct-mode-map [(tab)]
7638 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7639 (org-defkey orgstruct-mode-map "\C-i"
7640 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7642 (org-defkey orgstruct-mode-map "\M-\C-m"
7643 (orgstruct-make-binding 'org-insert-heading 105
7644 "\M-\C-m" [(meta return)]))
7645 (org-defkey orgstruct-mode-map [(meta return)]
7646 (orgstruct-make-binding 'org-insert-heading 106
7647 [(meta return)] "\M-\C-m"))
7649 (org-defkey orgstruct-mode-map [(shift meta return)]
7650 (orgstruct-make-binding 'org-insert-todo-heading 107
7651 [(meta return)] "\M-\C-m"))
7653 (unless org-local-vars
7654 (setq org-local-vars (org-get-local-variables)))
7658 (defun orgstruct-make-binding (fun n &rest keys)
7659 "Create a function for binding in the structure minor mode.
7660 FUN is the command to call inside a table. N is used to create a unique
7661 command name. KEYS are keys that should be checked in for a command
7662 to execute outside of tables."
7663 (eval
7664 (list 'defun
7665 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7666 '(arg)
7667 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7668 "Outside of structure, run the binding of `"
7669 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7670 "'.")
7671 '(interactive "p")
7672 (list 'if
7673 '(org-context-p 'headline 'item)
7674 (list 'org-run-like-in-org-mode (list 'quote fun))
7675 (list 'let '(orgstruct-mode)
7676 (list 'call-interactively
7677 (append '(or)
7678 (mapcar (lambda (k)
7679 (list 'key-binding k))
7680 keys)
7681 '('orgstruct-error))))))))
7683 (defun org-context-p (&rest contexts)
7684 "Check if local context is and of CONTEXTS.
7685 Possible values in the list of contexts are `table', `headline', and `item'."
7686 (let ((pos (point)))
7687 (goto-char (point-at-bol))
7688 (prog1 (or (and (memq 'table contexts)
7689 (looking-at "[ \t]*|"))
7690 (and (memq 'headline contexts)
7691 (looking-at "\\*+"))
7692 (and (memq 'item contexts)
7693 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7694 (goto-char pos))))
7696 (defun org-get-local-variables ()
7697 "Return a list of all local variables in an org-mode buffer."
7698 (let (varlist)
7699 (with-current-buffer (get-buffer-create "*Org tmp*")
7700 (erase-buffer)
7701 (org-mode)
7702 (setq varlist (buffer-local-variables)))
7703 (kill-buffer "*Org tmp*")
7704 (delq nil
7705 (mapcar
7706 (lambda (x)
7707 (setq x
7708 (if (symbolp x)
7709 (list x)
7710 (list (car x) (list 'quote (cdr x)))))
7711 (if (string-match
7712 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7713 (symbol-name (car x)))
7714 x nil))
7715 varlist))))
7717 ;;;###autoload
7718 (defun org-run-like-in-org-mode (cmd)
7719 (unless org-local-vars
7720 (setq org-local-vars (org-get-local-variables)))
7721 (eval (list 'let org-local-vars
7722 (list 'call-interactively (list 'quote cmd)))))
7724 ;;;; Archiving
7726 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7728 (defun org-archive-subtree (&optional find-done)
7729 "Move the current subtree to the archive.
7730 The archive can be a certain top-level heading in the current file, or in
7731 a different file. The tree will be moved to that location, the subtree
7732 heading be marked DONE, and the current time will be added.
7734 When called with prefix argument FIND-DONE, find whole trees without any
7735 open TODO items and archive them (after getting confirmation from the user).
7736 If the cursor is not at a headline when this comand is called, try all level
7737 1 trees. If the cursor is on a headline, only try the direct children of
7738 this heading."
7739 (interactive "P")
7740 (if find-done
7741 (org-archive-all-done)
7742 ;; Save all relevant TODO keyword-relatex variables
7744 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7745 (tr-org-todo-keywords-1 org-todo-keywords-1)
7746 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7747 (tr-org-done-keywords org-done-keywords)
7748 (tr-org-todo-regexp org-todo-regexp)
7749 (tr-org-todo-line-regexp org-todo-line-regexp)
7750 (tr-org-odd-levels-only org-odd-levels-only)
7751 (this-buffer (current-buffer))
7752 (org-archive-location org-archive-location)
7753 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7754 ;; start of variables that will be used for saving context
7755 ;; The compiler complains about them - keep them anyway!
7756 (file (abbreviate-file-name (buffer-file-name)))
7757 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7758 (time (format-time-string
7759 (substring (cdr org-time-stamp-formats) 1 -1)
7760 (current-time)))
7761 afile heading buffer level newfile-p
7762 category todo priority
7763 ;; start of variables that will be used for savind context
7764 ltags itags prop)
7766 ;; Try to find a local archive location
7767 (save-excursion
7768 (save-restriction
7769 (widen)
7770 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7771 (if (and prop (string-match "\\S-" prop))
7772 (setq org-archive-location prop)
7773 (if (or (re-search-backward re nil t)
7774 (re-search-forward re nil t))
7775 (setq org-archive-location (match-string 1))))))
7777 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7778 (progn
7779 (setq afile (format (match-string 1 org-archive-location)
7780 (file-name-nondirectory buffer-file-name))
7781 heading (match-string 2 org-archive-location)))
7782 (error "Invalid `org-archive-location'"))
7783 (if (> (length afile) 0)
7784 (setq newfile-p (not (file-exists-p afile))
7785 buffer (find-file-noselect afile))
7786 (setq buffer (current-buffer)))
7787 (unless buffer
7788 (error "Cannot access file \"%s\"" afile))
7789 (if (and (> (length heading) 0)
7790 (string-match "^\\*+" heading))
7791 (setq level (match-end 0))
7792 (setq heading nil level 0))
7793 (save-excursion
7794 (org-back-to-heading t)
7795 ;; Get context information that will be lost by moving the tree
7796 (org-refresh-category-properties)
7797 (setq category (org-get-category)
7798 todo (and (looking-at org-todo-line-regexp)
7799 (match-string 2))
7800 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7801 ltags (org-get-tags)
7802 itags (org-delete-all ltags (org-get-tags-at)))
7803 (setq ltags (mapconcat 'identity ltags " ")
7804 itags (mapconcat 'identity itags " "))
7805 ;; We first only copy, in case something goes wrong
7806 ;; we need to protect this-command, to avoid kill-region sets it,
7807 ;; which would lead to duplication of subtrees
7808 (let (this-command) (org-copy-subtree))
7809 (set-buffer buffer)
7810 ;; Enforce org-mode for the archive buffer
7811 (if (not (org-mode-p))
7812 ;; Force the mode for future visits.
7813 (let ((org-insert-mode-line-in-empty-file t)
7814 (org-inhibit-startup t))
7815 (call-interactively 'org-mode)))
7816 (when newfile-p
7817 (goto-char (point-max))
7818 (insert (format "\nArchived entries from file %s\n\n"
7819 (buffer-file-name this-buffer))))
7820 ;; Force the TODO keywords of the original buffer
7821 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7822 (org-todo-keywords-1 tr-org-todo-keywords-1)
7823 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7824 (org-done-keywords tr-org-done-keywords)
7825 (org-todo-regexp tr-org-todo-regexp)
7826 (org-todo-line-regexp tr-org-todo-line-regexp)
7827 (org-odd-levels-only
7828 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7829 org-odd-levels-only
7830 tr-org-odd-levels-only)))
7831 (goto-char (point-min))
7832 (if heading
7833 (progn
7834 (if (re-search-forward
7835 (concat "^" (regexp-quote heading)
7836 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7837 nil t)
7838 (goto-char (match-end 0))
7839 ;; Heading not found, just insert it at the end
7840 (goto-char (point-max))
7841 (or (bolp) (insert "\n"))
7842 (insert "\n" heading "\n")
7843 (end-of-line 0))
7844 ;; Make the subtree visible
7845 (show-subtree)
7846 (org-end-of-subtree t)
7847 (skip-chars-backward " \t\r\n")
7848 (and (looking-at "[ \t\r\n]*")
7849 (replace-match "\n\n")))
7850 ;; No specific heading, just go to end of file.
7851 (goto-char (point-max)) (insert "\n"))
7852 ;; Paste
7853 (org-paste-subtree (org-get-legal-level level 1))
7855 ;; Mark the entry as done
7856 (when (and org-archive-mark-done
7857 (looking-at org-todo-line-regexp)
7858 (or (not (match-end 2))
7859 (not (member (match-string 2) org-done-keywords))))
7860 (let (org-log-done)
7861 (org-todo
7862 (car (or (member org-archive-mark-done org-done-keywords)
7863 org-done-keywords)))))
7865 ;; Add the context info
7866 (when org-archive-save-context-info
7867 (let ((l org-archive-save-context-info) e n v)
7868 (while (setq e (pop l))
7869 (when (and (setq v (symbol-value e))
7870 (stringp v) (string-match "\\S-" v))
7871 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7872 (org-entry-put (point) n v)))))
7874 ;; Save the buffer, if it is not the same buffer.
7875 (if (not (eq this-buffer buffer)) (save-buffer))))
7876 ;; Here we are back in the original buffer. Everything seems to have
7877 ;; worked. So now cut the tree and finish up.
7878 (let (this-command) (org-cut-subtree))
7879 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7880 (message "Subtree archived %s"
7881 (if (eq this-buffer buffer)
7882 (concat "under heading: " heading)
7883 (concat "in file: " (abbreviate-file-name afile)))))))
7885 (defun org-refresh-category-properties ()
7886 "Refresh category text properties in teh buffer."
7887 (let ((def-cat (cond
7888 ((null org-category)
7889 (if buffer-file-name
7890 (file-name-sans-extension
7891 (file-name-nondirectory buffer-file-name))
7892 "???"))
7893 ((symbolp org-category) (symbol-name org-category))
7894 (t org-category)))
7895 beg end cat pos optionp)
7896 (org-unmodified
7897 (save-excursion
7898 (save-restriction
7899 (widen)
7900 (goto-char (point-min))
7901 (put-text-property (point) (point-max) 'org-category def-cat)
7902 (while (re-search-forward
7903 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7904 (setq pos (match-end 0)
7905 optionp (equal (char-after (match-beginning 0)) ?#)
7906 cat (org-trim (match-string 2)))
7907 (if optionp
7908 (setq beg (point-at-bol) end (point-max))
7909 (org-back-to-heading t)
7910 (setq beg (point) end (org-end-of-subtree t t)))
7911 (put-text-property beg end 'org-category cat)
7912 (goto-char pos)))))))
7914 (defun org-archive-all-done (&optional tag)
7915 "Archive sublevels of the current tree without open TODO items.
7916 If the cursor is not on a headline, try all level 1 trees. If
7917 it is on a headline, try all direct children.
7918 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7919 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7920 (rea (concat ".*:" org-archive-tag ":"))
7921 (begm (make-marker))
7922 (endm (make-marker))
7923 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7924 "Move subtree to archive (no open TODO items)? "))
7925 beg end (cntarch 0))
7926 (if (org-on-heading-p)
7927 (progn
7928 (setq re1 (concat "^" (regexp-quote
7929 (make-string
7930 (1+ (- (match-end 0) (match-beginning 0) 1))
7931 ?*))
7932 " "))
7933 (move-marker begm (point))
7934 (move-marker endm (org-end-of-subtree t)))
7935 (setq re1 "^* ")
7936 (move-marker begm (point-min))
7937 (move-marker endm (point-max)))
7938 (save-excursion
7939 (goto-char begm)
7940 (while (re-search-forward re1 endm t)
7941 (setq beg (match-beginning 0)
7942 end (save-excursion (org-end-of-subtree t) (point)))
7943 (goto-char beg)
7944 (if (re-search-forward re end t)
7945 (goto-char end)
7946 (goto-char beg)
7947 (if (and (or (not tag) (not (looking-at rea)))
7948 (y-or-n-p question))
7949 (progn
7950 (if tag
7951 (org-toggle-tag org-archive-tag 'on)
7952 (org-archive-subtree))
7953 (setq cntarch (1+ cntarch)))
7954 (goto-char end)))))
7955 (message "%d trees archived" cntarch)))
7957 (defun org-cycle-hide-drawers (state)
7958 "Re-hide all drawers after a visibility state change."
7959 (when (and (org-mode-p)
7960 (not (memq state '(overview folded))))
7961 (save-excursion
7962 (let* ((globalp (memq state '(contents all)))
7963 (beg (if globalp (point-min) (point)))
7964 (end (if globalp (point-max) (org-end-of-subtree t))))
7965 (goto-char beg)
7966 (while (re-search-forward org-drawer-regexp end t)
7967 (org-flag-drawer t))))))
7969 (defun org-flag-drawer (flag)
7970 (save-excursion
7971 (beginning-of-line 1)
7972 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7973 (let ((b (match-end 0))
7974 (outline-regexp org-outline-regexp))
7975 (if (re-search-forward
7976 "^[ \t]*:END:"
7977 (save-excursion (outline-next-heading) (point)) t)
7978 (outline-flag-region b (point-at-eol) flag)
7979 (error ":END: line missing"))))))
7981 (defun org-cycle-hide-archived-subtrees (state)
7982 "Re-hide all archived subtrees after a visibility state change."
7983 (when (and (not org-cycle-open-archived-trees)
7984 (not (memq state '(overview folded))))
7985 (save-excursion
7986 (let* ((globalp (memq state '(contents all)))
7987 (beg (if globalp (point-min) (point)))
7988 (end (if globalp (point-max) (org-end-of-subtree t))))
7989 (org-hide-archived-subtrees beg end)
7990 (goto-char beg)
7991 (if (looking-at (concat ".*:" org-archive-tag ":"))
7992 (message "%s" (substitute-command-keys
7993 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7995 (defun org-force-cycle-archived ()
7996 "Cycle subtree even if it is archived."
7997 (interactive)
7998 (setq this-command 'org-cycle)
7999 (let ((org-cycle-open-archived-trees t))
8000 (call-interactively 'org-cycle)))
8002 (defun org-hide-archived-subtrees (beg end)
8003 "Re-hide all archived subtrees after a visibility state change."
8004 (save-excursion
8005 (let* ((re (concat ":" org-archive-tag ":")))
8006 (goto-char beg)
8007 (while (re-search-forward re end t)
8008 (and (org-on-heading-p) (hide-subtree))
8009 (org-end-of-subtree t)))))
8011 (defun org-toggle-tag (tag &optional onoff)
8012 "Toggle the tag TAG for the current line.
8013 If ONOFF is `on' or `off', don't toggle but set to this state."
8014 (unless (org-on-heading-p t) (error "Not on headling"))
8015 (let (res current)
8016 (save-excursion
8017 (beginning-of-line)
8018 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8019 (point-at-eol) t)
8020 (progn
8021 (setq current (match-string 1))
8022 (replace-match ""))
8023 (setq current ""))
8024 (setq current (nreverse (org-split-string current ":")))
8025 (cond
8026 ((eq onoff 'on)
8027 (setq res t)
8028 (or (member tag current) (push tag current)))
8029 ((eq onoff 'off)
8030 (or (not (member tag current)) (setq current (delete tag current))))
8031 (t (if (member tag current)
8032 (setq current (delete tag current))
8033 (setq res t)
8034 (push tag current))))
8035 (end-of-line 1)
8036 (if current
8037 (progn
8038 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8039 (org-set-tags nil t))
8040 (delete-horizontal-space))
8041 (run-hooks 'org-after-tags-change-hook))
8042 res))
8044 (defun org-toggle-archive-tag (&optional arg)
8045 "Toggle the archive tag for the current headline.
8046 With prefix ARG, check all children of current headline and offer tagging
8047 the children that do not contain any open TODO items."
8048 (interactive "P")
8049 (if arg
8050 (org-archive-all-done 'tag)
8051 (let (set)
8052 (save-excursion
8053 (org-back-to-heading t)
8054 (setq set (org-toggle-tag org-archive-tag))
8055 (when set (hide-subtree)))
8056 (and set (beginning-of-line 1))
8057 (message "Subtree %s" (if set "archived" "unarchived")))))
8060 ;;;; Tables
8062 ;;; The table editor
8064 ;; Watch out: Here we are talking about two different kind of tables.
8065 ;; Most of the code is for the tables created with the Org-mode table editor.
8066 ;; Sometimes, we talk about tables created and edited with the table.el
8067 ;; Emacs package. We call the former org-type tables, and the latter
8068 ;; table.el-type tables.
8070 (defun org-before-change-function (beg end)
8071 "Every change indicates that a table might need an update."
8072 (setq org-table-may-need-update t))
8074 (defconst org-table-line-regexp "^[ \t]*|"
8075 "Detects an org-type table line.")
8076 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8077 "Detects an org-type table line.")
8078 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8079 "Detects a table line marked for automatic recalculation.")
8080 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8081 "Detects a table line marked for automatic recalculation.")
8082 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8083 "Detects a table line marked for automatic recalculation.")
8084 (defconst org-table-hline-regexp "^[ \t]*|-"
8085 "Detects an org-type table hline.")
8086 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8087 "Detects a table-type table hline.")
8088 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8089 "Detects an org-type or table-type table.")
8090 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8091 "Searching from within a table (any type) this finds the first line
8092 outside the table.")
8093 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8094 "Searching from within a table (any type) this finds the first line
8095 outside the table.")
8097 (defvar org-table-last-highlighted-reference nil)
8098 (defvar org-table-formula-history nil)
8100 (defvar org-table-column-names nil
8101 "Alist with column names, derived from the `!' line.")
8102 (defvar org-table-column-name-regexp nil
8103 "Regular expression matching the current column names.")
8104 (defvar org-table-local-parameters nil
8105 "Alist with parameter names, derived from the `$' line.")
8106 (defvar org-table-named-field-locations nil
8107 "Alist with locations of named fields.")
8109 (defvar org-table-current-line-types nil
8110 "Table row types, non-nil only for the duration of a comand.")
8111 (defvar org-table-current-begin-line nil
8112 "Table begin line, non-nil only for the duration of a comand.")
8113 (defvar org-table-current-begin-pos nil
8114 "Table begin position, non-nil only for the duration of a comand.")
8115 (defvar org-table-dlines nil
8116 "Vector of data line line numbers in the current table.")
8117 (defvar org-table-hlines nil
8118 "Vector of hline line numbers in the current table.")
8120 (defconst org-table-range-regexp
8121 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8122 ;; 1 2 3 4 5
8123 "Regular expression for matching ranges in formulas.")
8125 (defconst org-table-range-regexp2
8126 (concat
8127 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8128 "\\.\\."
8129 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8130 "Match a range for reference display.")
8132 (defconst org-table-translate-regexp
8133 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8134 "Match a reference that needs translation, for reference display.")
8136 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8138 (defun org-table-create-with-table.el ()
8139 "Use the table.el package to insert a new table.
8140 If there is already a table at point, convert between Org-mode tables
8141 and table.el tables."
8142 (interactive)
8143 (require 'table)
8144 (cond
8145 ((org-at-table.el-p)
8146 (if (y-or-n-p "Convert table to Org-mode table? ")
8147 (org-table-convert)))
8148 ((org-at-table-p)
8149 (if (y-or-n-p "Convert table to table.el table? ")
8150 (org-table-convert)))
8151 (t (call-interactively 'table-insert))))
8153 (defun org-table-create-or-convert-from-region (arg)
8154 "Convert region to table, or create an empty table.
8155 If there is an active region, convert it to a table, using the function
8156 `org-table-convert-region'. See the documentation of that function
8157 to learn how the prefix argument is interpreted to determine the field
8158 separator.
8159 If there is no such region, create an empty table with `org-table-create'."
8160 (interactive "P")
8161 (if (org-region-active-p)
8162 (org-table-convert-region (region-beginning) (region-end) arg)
8163 (org-table-create arg)))
8165 (defun org-table-create (&optional size)
8166 "Query for a size and insert a table skeleton.
8167 SIZE is a string Columns x Rows like for example \"3x2\"."
8168 (interactive "P")
8169 (unless size
8170 (setq size (read-string
8171 (concat "Table size Columns x Rows [e.g. "
8172 org-table-default-size "]: ")
8173 "" nil org-table-default-size)))
8175 (let* ((pos (point))
8176 (indent (make-string (current-column) ?\ ))
8177 (split (org-split-string size " *x *"))
8178 (rows (string-to-number (nth 1 split)))
8179 (columns (string-to-number (car split)))
8180 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8181 "\n")))
8182 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8183 (point-at-bol) (point)))
8184 (beginning-of-line 1)
8185 (newline))
8186 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8187 (dotimes (i rows) (insert line))
8188 (goto-char pos)
8189 (if (> rows 1)
8190 ;; Insert a hline after the first row.
8191 (progn
8192 (end-of-line 1)
8193 (insert "\n|-")
8194 (goto-char pos)))
8195 (org-table-align)))
8197 (defun org-table-convert-region (beg0 end0 &optional separator)
8198 "Convert region to a table.
8199 The region goes from BEG0 to END0, but these borders will be moved
8200 slightly, to make sure a beginning of line in the first line is included.
8202 SEPARATOR specifies the field separator in the lines. It can have the
8203 following values:
8205 '(4) Use the comma as a field separator
8206 '(16) Use a TAB as field separator
8207 integer When a number, use that many spaces as field separator
8208 nil When nil, the command tries to be smart and figure out the
8209 separator in the following way:
8210 - when each line contains a TAB, assume TAB-separated material
8211 - when each line contains a comme, assume CSV material
8212 - else, assume one or more SPACE charcters as separator."
8213 (interactive "rP")
8214 (let* ((beg (min beg0 end0))
8215 (end (max beg0 end0))
8217 (goto-char beg)
8218 (beginning-of-line 1)
8219 (setq beg (move-marker (make-marker) (point)))
8220 (goto-char end)
8221 (if (bolp) (backward-char 1) (end-of-line 1))
8222 (setq end (move-marker (make-marker) (point)))
8223 ;; Get the right field separator
8224 (unless separator
8225 (goto-char beg)
8226 (setq separator
8227 (cond
8228 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8229 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8230 (t 1))))
8231 (setq re (cond
8232 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8233 ((equal separator '(16)) "^\\|\t")
8234 ((integerp separator)
8235 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8236 (t (error "This should not happen"))))
8237 (goto-char beg)
8238 (while (re-search-forward re end t)
8239 (replace-match "| " t t))
8240 (goto-char beg)
8241 (insert " ")
8242 (org-table-align)))
8244 (defun org-table-import (file arg)
8245 "Import FILE as a table.
8246 The file is assumed to be tab-separated. Such files can be produced by most
8247 spreadsheet and database applications. If no tabs (at least one per line)
8248 are found, lines will be split on whitespace into fields."
8249 (interactive "f\nP")
8250 (or (bolp) (newline))
8251 (let ((beg (point))
8252 (pm (point-max)))
8253 (insert-file-contents file)
8254 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8256 (defun org-table-export ()
8257 "Export table as a tab-separated file.
8258 Such a file can be imported into a spreadsheet program like Excel."
8259 (interactive)
8260 (let* ((beg (org-table-begin))
8261 (end (org-table-end))
8262 (table (buffer-substring beg end))
8263 (file (read-file-name "Export table to: "))
8264 buf)
8265 (unless (or (not (file-exists-p file))
8266 (y-or-n-p (format "Overwrite file %s? " file)))
8267 (error "Abort"))
8268 (with-current-buffer (find-file-noselect file)
8269 (setq buf (current-buffer))
8270 (erase-buffer)
8271 (fundamental-mode)
8272 (insert table)
8273 (goto-char (point-min))
8274 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8275 (replace-match "" t t)
8276 (end-of-line 1))
8277 (goto-char (point-min))
8278 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8279 (replace-match "" t t)
8280 (goto-char (min (1+ (point)) (point-max))))
8281 (goto-char (point-min))
8282 (while (re-search-forward "^-[-+]*$" nil t)
8283 (replace-match "")
8284 (if (looking-at "\n")
8285 (delete-char 1)))
8286 (goto-char (point-min))
8287 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8288 (replace-match "\t" t t))
8289 (save-buffer))
8290 (kill-buffer buf)))
8292 (defvar org-table-aligned-begin-marker (make-marker)
8293 "Marker at the beginning of the table last aligned.
8294 Used to check if cursor still is in that table, to minimize realignment.")
8295 (defvar org-table-aligned-end-marker (make-marker)
8296 "Marker at the end of the table last aligned.
8297 Used to check if cursor still is in that table, to minimize realignment.")
8298 (defvar org-table-last-alignment nil
8299 "List of flags for flushright alignment, from the last re-alignment.
8300 This is being used to correctly align a single field after TAB or RET.")
8301 (defvar org-table-last-column-widths nil
8302 "List of max width of fields in each column.
8303 This is being used to correctly align a single field after TAB or RET.")
8304 (defvar org-table-overlay-coordinates nil
8305 "Overlay coordinates after each align of a table.")
8306 (make-variable-buffer-local 'org-table-overlay-coordinates)
8308 (defvar org-last-recalc-line nil)
8309 (defconst org-narrow-column-arrow "=>"
8310 "Used as display property in narrowed table columns.")
8312 (defun org-table-align ()
8313 "Align the table at point by aligning all vertical bars."
8314 (interactive)
8315 (let* (
8316 ;; Limits of table
8317 (beg (org-table-begin))
8318 (end (org-table-end))
8319 ;; Current cursor position
8320 (linepos (org-current-line))
8321 (colpos (org-table-current-column))
8322 (winstart (window-start))
8323 (winstartline (org-current-line (min winstart (1- (point-max)))))
8324 lines (new "") lengths l typenums ty fields maxfields i
8325 column
8326 (indent "") cnt frac
8327 rfmt hfmt
8328 (spaces '(1 . 1))
8329 (sp1 (car spaces))
8330 (sp2 (cdr spaces))
8331 (rfmt1 (concat
8332 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8333 (hfmt1 (concat
8334 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8335 emptystrings links dates emph narrow fmax f1 len c e)
8336 (untabify beg end)
8337 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8338 ;; Check if we have links or dates
8339 (goto-char beg)
8340 (setq links (re-search-forward org-bracket-link-regexp end t))
8341 (goto-char beg)
8342 (setq emph (and org-hide-emphasis-markers
8343 (re-search-forward org-emph-re end t)))
8344 (goto-char beg)
8345 (setq dates (and org-display-custom-times
8346 (re-search-forward org-ts-regexp-both end t)))
8347 ;; Make sure the link properties are right
8348 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8349 ;; Make sure the date properties are right
8350 (when dates (goto-char beg) (while (org-activate-dates end)))
8351 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8353 ;; Check if we are narrowing any columns
8354 (goto-char beg)
8355 (setq narrow (and org-format-transports-properties-p
8356 (re-search-forward "<[0-9]+>" end t)))
8357 ;; Get the rows
8358 (setq lines (org-split-string
8359 (buffer-substring beg end) "\n"))
8360 ;; Store the indentation of the first line
8361 (if (string-match "^ *" (car lines))
8362 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8363 ;; Mark the hlines by setting the corresponding element to nil
8364 ;; At the same time, we remove trailing space.
8365 (setq lines (mapcar (lambda (l)
8366 (if (string-match "^ *|-" l)
8368 (if (string-match "[ \t]+$" l)
8369 (substring l 0 (match-beginning 0))
8370 l)))
8371 lines))
8372 ;; Get the data fields by splitting the lines.
8373 (setq fields (mapcar
8374 (lambda (l)
8375 (org-split-string l " *| *"))
8376 (delq nil (copy-sequence lines))))
8377 ;; How many fields in the longest line?
8378 (condition-case nil
8379 (setq maxfields (apply 'max (mapcar 'length fields)))
8380 (error
8381 (kill-region beg end)
8382 (org-table-create org-table-default-size)
8383 (error "Empty table - created default table")))
8384 ;; A list of empty strings to fill any short rows on output
8385 (setq emptystrings (make-list maxfields ""))
8386 ;; Check for special formatting.
8387 (setq i -1)
8388 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8389 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8390 ;; Check if there is an explicit width specified
8391 (when narrow
8392 (setq c column fmax nil)
8393 (while c
8394 (setq e (pop c))
8395 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8396 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8397 ;; Find fields that are wider than fmax, and shorten them
8398 (when fmax
8399 (loop for xx in column do
8400 (when (and (stringp xx)
8401 (> (org-string-width xx) fmax))
8402 (org-add-props xx nil
8403 'help-echo
8404 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8405 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8406 (unless (> f1 1)
8407 (error "Cannot narrow field starting with wide link \"%s\""
8408 (match-string 0 xx)))
8409 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8410 (add-text-properties (- f1 2) f1
8411 (list 'display org-narrow-column-arrow)
8412 xx)))))
8413 ;; Get the maximum width for each column
8414 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8415 ;; Get the fraction of numbers, to decide about alignment of the column
8416 (setq cnt 0 frac 0.0)
8417 (loop for x in column do
8418 (if (equal x "")
8420 (setq frac ( / (+ (* frac cnt)
8421 (if (string-match org-table-number-regexp x) 1 0))
8422 (setq cnt (1+ cnt))))))
8423 (push (>= frac org-table-number-fraction) typenums))
8424 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8426 ;; Store the alignment of this table, for later editing of single fields
8427 (setq org-table-last-alignment typenums
8428 org-table-last-column-widths lengths)
8430 ;; With invisible characters, `format' does not get the field width right
8431 ;; So we need to make these fields wide by hand.
8432 (when (or links emph)
8433 (loop for i from 0 upto (1- maxfields) do
8434 (setq len (nth i lengths))
8435 (loop for j from 0 upto (1- (length fields)) do
8436 (setq c (nthcdr i (car (nthcdr j fields))))
8437 (if (and (stringp (car c))
8438 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8439 ; (string-match org-bracket-link-regexp (car c))
8440 (< (org-string-width (car c)) len))
8441 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8443 ;; Compute the formats needed for output of the table
8444 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8445 (while (setq l (pop lengths))
8446 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8447 (setq rfmt (concat rfmt (format rfmt1 ty l))
8448 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8449 (setq rfmt (concat rfmt "\n")
8450 hfmt (concat (substring hfmt 0 -1) "|\n"))
8452 (setq new (mapconcat
8453 (lambda (l)
8454 (if l (apply 'format rfmt
8455 (append (pop fields) emptystrings))
8456 hfmt))
8457 lines ""))
8458 ;; Replace the old one
8459 (delete-region beg end)
8460 (move-marker end nil)
8461 (move-marker org-table-aligned-begin-marker (point))
8462 (insert new)
8463 (move-marker org-table-aligned-end-marker (point))
8464 (when (and orgtbl-mode (not (org-mode-p)))
8465 (goto-char org-table-aligned-begin-marker)
8466 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8467 ;; Try to move to the old location
8468 (goto-line winstartline)
8469 (setq winstart (point-at-bol))
8470 (goto-line linepos)
8471 (set-window-start (selected-window) winstart 'noforce)
8472 (org-table-goto-column colpos)
8473 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8474 (setq org-table-may-need-update nil)
8477 (defun org-string-width (s)
8478 "Compute width of string, ignoring invisible characters.
8479 This ignores character with invisibility property `org-link', and also
8480 characters with property `org-cwidth', because these will become invisible
8481 upon the next fontification round."
8482 (let (b l)
8483 (when (or (eq t buffer-invisibility-spec)
8484 (assq 'org-link buffer-invisibility-spec))
8485 (while (setq b (text-property-any 0 (length s)
8486 'invisible 'org-link s))
8487 (setq s (concat (substring s 0 b)
8488 (substring s (or (next-single-property-change
8489 b 'invisible s) (length s)))))))
8490 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8491 (setq s (concat (substring s 0 b)
8492 (substring s (or (next-single-property-change
8493 b 'org-cwidth s) (length s))))))
8494 (setq l (string-width s) b -1)
8495 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8496 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8499 (defun org-table-begin (&optional table-type)
8500 "Find the beginning of the table and return its position.
8501 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8502 (save-excursion
8503 (if (not (re-search-backward
8504 (if table-type org-table-any-border-regexp
8505 org-table-border-regexp)
8506 nil t))
8507 (progn (goto-char (point-min)) (point))
8508 (goto-char (match-beginning 0))
8509 (beginning-of-line 2)
8510 (point))))
8512 (defun org-table-end (&optional table-type)
8513 "Find the end of the table and return its position.
8514 With argument TABLE-TYPE, go to the end of a table.el-type table."
8515 (save-excursion
8516 (if (not (re-search-forward
8517 (if table-type org-table-any-border-regexp
8518 org-table-border-regexp)
8519 nil t))
8520 (goto-char (point-max))
8521 (goto-char (match-beginning 0)))
8522 (point-marker)))
8524 (defun org-table-justify-field-maybe (&optional new)
8525 "Justify the current field, text to left, number to right.
8526 Optional argument NEW may specify text to replace the current field content."
8527 (cond
8528 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8529 ((org-at-table-hline-p))
8530 ((and (not new)
8531 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8532 (current-buffer)))
8533 (< (point) org-table-aligned-begin-marker)
8534 (>= (point) org-table-aligned-end-marker)))
8535 ;; This is not the same table, force a full re-align
8536 (setq org-table-may-need-update t))
8537 (t ;; realign the current field, based on previous full realign
8538 (let* ((pos (point)) s
8539 (col (org-table-current-column))
8540 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8541 l f n o e)
8542 (when (> col 0)
8543 (skip-chars-backward "^|\n")
8544 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8545 (progn
8546 (setq s (match-string 1)
8547 o (match-string 0)
8548 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8549 e (not (= (match-beginning 2) (match-end 2))))
8550 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8551 l (if e "|" (setq org-table-may-need-update t) ""))
8552 n (format f s))
8553 (if new
8554 (if (<= (length new) l) ;; FIXME: length -> str-width?
8555 (setq n (format f new))
8556 (setq n (concat new "|") org-table-may-need-update t)))
8557 (or (equal n o)
8558 (let (org-table-may-need-update)
8559 (replace-match n t t))))
8560 (setq org-table-may-need-update t))
8561 (goto-char pos))))))
8563 (defun org-table-next-field ()
8564 "Go to the next field in the current table, creating new lines as needed.
8565 Before doing so, re-align the table if necessary."
8566 (interactive)
8567 (org-table-maybe-eval-formula)
8568 (org-table-maybe-recalculate-line)
8569 (if (and org-table-automatic-realign
8570 org-table-may-need-update)
8571 (org-table-align))
8572 (let ((end (org-table-end)))
8573 (if (org-at-table-hline-p)
8574 (end-of-line 1))
8575 (condition-case nil
8576 (progn
8577 (re-search-forward "|" end)
8578 (if (looking-at "[ \t]*$")
8579 (re-search-forward "|" end))
8580 (if (and (looking-at "-")
8581 org-table-tab-jumps-over-hlines
8582 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8583 (goto-char (match-beginning 1)))
8584 (if (looking-at "-")
8585 (progn
8586 (beginning-of-line 0)
8587 (org-table-insert-row 'below))
8588 (if (looking-at " ") (forward-char 1))))
8589 (error
8590 (org-table-insert-row 'below)))))
8592 (defun org-table-previous-field ()
8593 "Go to the previous field in the table.
8594 Before doing so, re-align the table if necessary."
8595 (interactive)
8596 (org-table-justify-field-maybe)
8597 (org-table-maybe-recalculate-line)
8598 (if (and org-table-automatic-realign
8599 org-table-may-need-update)
8600 (org-table-align))
8601 (if (org-at-table-hline-p)
8602 (end-of-line 1))
8603 (re-search-backward "|" (org-table-begin))
8604 (re-search-backward "|" (org-table-begin))
8605 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8606 (re-search-backward "|" (org-table-begin)))
8607 (if (looking-at "| ?")
8608 (goto-char (match-end 0))))
8610 (defun org-table-next-row ()
8611 "Go to the next row (same column) in the current table.
8612 Before doing so, re-align the table if necessary."
8613 (interactive)
8614 (org-table-maybe-eval-formula)
8615 (org-table-maybe-recalculate-line)
8616 (if (or (looking-at "[ \t]*$")
8617 (save-excursion (skip-chars-backward " \t") (bolp)))
8618 (newline)
8619 (if (and org-table-automatic-realign
8620 org-table-may-need-update)
8621 (org-table-align))
8622 (let ((col (org-table-current-column)))
8623 (beginning-of-line 2)
8624 (if (or (not (org-at-table-p))
8625 (org-at-table-hline-p))
8626 (progn
8627 (beginning-of-line 0)
8628 (org-table-insert-row 'below)))
8629 (org-table-goto-column col)
8630 (skip-chars-backward "^|\n\r")
8631 (if (looking-at " ") (forward-char 1)))))
8633 (defun org-table-copy-down (n)
8634 "Copy a field down in the current column.
8635 If the field at the cursor is empty, copy into it the content of the nearest
8636 non-empty field above. With argument N, use the Nth non-empty field.
8637 If the current field is not empty, it is copied down to the next row, and
8638 the cursor is moved with it. Therefore, repeating this command causes the
8639 column to be filled row-by-row.
8640 If the variable `org-table-copy-increment' is non-nil and the field is an
8641 integer or a timestamp, it will be incremented while copying. In the case of
8642 a timestamp, if the cursor is on the year, change the year. If it is on the
8643 month or the day, change that. Point will stay on the current date field
8644 in order to easily repeat the interval."
8645 (interactive "p")
8646 (let* ((colpos (org-table-current-column))
8647 (col (current-column))
8648 (field (org-table-get-field))
8649 (non-empty (string-match "[^ \t]" field))
8650 (beg (org-table-begin))
8651 txt)
8652 (org-table-check-inside-data-field)
8653 (if non-empty
8654 (progn
8655 (setq txt (org-trim field))
8656 (org-table-next-row)
8657 (org-table-blank-field))
8658 (save-excursion
8659 (setq txt
8660 (catch 'exit
8661 (while (progn (beginning-of-line 1)
8662 (re-search-backward org-table-dataline-regexp
8663 beg t))
8664 (org-table-goto-column colpos t)
8665 (if (and (looking-at
8666 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8667 (= (setq n (1- n)) 0))
8668 (throw 'exit (match-string 1))))))))
8669 (if txt
8670 (progn
8671 (if (and org-table-copy-increment
8672 (string-match "^[0-9]+$" txt))
8673 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8674 (insert txt)
8675 (move-to-column col)
8676 (if (and org-table-copy-increment (org-at-timestamp-p t))
8677 (org-timestamp-up 1)
8678 (org-table-maybe-recalculate-line))
8679 (org-table-align)
8680 (move-to-column col))
8681 (error "No non-empty field found"))))
8683 (defun org-table-check-inside-data-field ()
8684 "Is point inside a table data field?
8685 I.e. not on a hline or before the first or after the last column?
8686 This actually throws an error, so it aborts the current command."
8687 (if (or (not (org-at-table-p))
8688 (= (org-table-current-column) 0)
8689 (org-at-table-hline-p)
8690 (looking-at "[ \t]*$"))
8691 (error "Not in table data field")))
8693 (defvar org-table-clip nil
8694 "Clipboard for table regions.")
8696 (defun org-table-blank-field ()
8697 "Blank the current table field or active region."
8698 (interactive)
8699 (org-table-check-inside-data-field)
8700 (if (and (interactive-p) (org-region-active-p))
8701 (let (org-table-clip)
8702 (org-table-cut-region (region-beginning) (region-end)))
8703 (skip-chars-backward "^|")
8704 (backward-char 1)
8705 (if (looking-at "|[^|\n]+")
8706 (let* ((pos (match-beginning 0))
8707 (match (match-string 0))
8708 (len (org-string-width match)))
8709 (replace-match (concat "|" (make-string (1- len) ?\ )))
8710 (goto-char (+ 2 pos))
8711 (substring match 1)))))
8713 (defun org-table-get-field (&optional n replace)
8714 "Return the value of the field in column N of current row.
8715 N defaults to current field.
8716 If REPLACE is a string, replace field with this value. The return value
8717 is always the old value."
8718 (and n (org-table-goto-column n))
8719 (skip-chars-backward "^|\n")
8720 (backward-char 1)
8721 (if (looking-at "|[^|\r\n]*")
8722 (let* ((pos (match-beginning 0))
8723 (val (buffer-substring (1+ pos) (match-end 0))))
8724 (if replace
8725 (replace-match (concat "|" replace) t t))
8726 (goto-char (min (point-at-eol) (+ 2 pos)))
8727 val)
8728 (forward-char 1) ""))
8730 (defun org-table-field-info (arg)
8731 "Show info about the current field, and highlight any reference at point."
8732 (interactive "P")
8733 (org-table-get-specials)
8734 (save-excursion
8735 (let* ((pos (point))
8736 (col (org-table-current-column))
8737 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8738 (name (car (rassoc (list (org-current-line) col)
8739 org-table-named-field-locations)))
8740 (eql (org-table-get-stored-formulas))
8741 (dline (org-table-current-dline))
8742 (ref (format "@%d$%d" dline col))
8743 (ref1 (org-table-convert-refs-to-an ref))
8744 (fequation (or (assoc name eql) (assoc ref eql)))
8745 (cequation (assoc (int-to-string col) eql))
8746 (eqn (or fequation cequation)))
8747 (goto-char pos)
8748 (condition-case nil
8749 (org-table-show-reference 'local)
8750 (error nil))
8751 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8752 dline col
8753 (if cname (concat " or $" cname) "")
8754 dline col ref1
8755 (if name (concat " or $" name) "")
8756 ;; FIXME: formula info not correct if special table line
8757 (if eqn
8758 (concat ", formula: "
8759 (org-table-formula-to-user
8760 (concat
8761 (if (string-match "^[$@]"(car eqn)) "" "$")
8762 (car eqn) "=" (cdr eqn))))
8763 "")))))
8765 (defun org-table-current-column ()
8766 "Find out which column we are in.
8767 When called interactively, column is also displayed in echo area."
8768 (interactive)
8769 (if (interactive-p) (org-table-check-inside-data-field))
8770 (save-excursion
8771 (let ((cnt 0) (pos (point)))
8772 (beginning-of-line 1)
8773 (while (search-forward "|" pos t)
8774 (setq cnt (1+ cnt)))
8775 (if (interactive-p) (message "This is table column %d" cnt))
8776 cnt)))
8778 (defun org-table-current-dline ()
8779 "Find out what table data line we are in.
8780 Only datalins count for this."
8781 (interactive)
8782 (if (interactive-p) (org-table-check-inside-data-field))
8783 (save-excursion
8784 (let ((cnt 0) (pos (point)))
8785 (goto-char (org-table-begin))
8786 (while (<= (point) pos)
8787 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8788 (beginning-of-line 2))
8789 (if (interactive-p) (message "This is table line %d" cnt))
8790 cnt)))
8792 (defun org-table-goto-column (n &optional on-delim force)
8793 "Move the cursor to the Nth column in the current table line.
8794 With optional argument ON-DELIM, stop with point before the left delimiter
8795 of the field.
8796 If there are less than N fields, just go to after the last delimiter.
8797 However, when FORCE is non-nil, create new columns if necessary."
8798 (interactive "p")
8799 (let ((pos (point-at-eol)))
8800 (beginning-of-line 1)
8801 (when (> n 0)
8802 (while (and (> (setq n (1- n)) -1)
8803 (or (search-forward "|" pos t)
8804 (and force
8805 (progn (end-of-line 1)
8806 (skip-chars-backward "^|")
8807 (insert " | "))))))
8808 ; (backward-char 2) t)))))
8809 (when (and force (not (looking-at ".*|")))
8810 (save-excursion (end-of-line 1) (insert " | ")))
8811 (if on-delim
8812 (backward-char 1)
8813 (if (looking-at " ") (forward-char 1))))))
8815 (defun org-at-table-p (&optional table-type)
8816 "Return t if the cursor is inside an org-type table.
8817 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8818 (if org-enable-table-editor
8819 (save-excursion
8820 (beginning-of-line 1)
8821 (looking-at (if table-type org-table-any-line-regexp
8822 org-table-line-regexp)))
8823 nil))
8825 (defun org-at-table.el-p ()
8826 "Return t if and only if we are at a table.el table."
8827 (and (org-at-table-p 'any)
8828 (save-excursion
8829 (goto-char (org-table-begin 'any))
8830 (looking-at org-table1-hline-regexp))))
8832 (defun org-table-recognize-table.el ()
8833 "If there is a table.el table nearby, recognize it and move into it."
8834 (if org-table-tab-recognizes-table.el
8835 (if (org-at-table.el-p)
8836 (progn
8837 (beginning-of-line 1)
8838 (if (looking-at org-table-dataline-regexp)
8840 (if (looking-at org-table1-hline-regexp)
8841 (progn
8842 (beginning-of-line 2)
8843 (if (looking-at org-table-any-border-regexp)
8844 (beginning-of-line -1)))))
8845 (if (re-search-forward "|" (org-table-end t) t)
8846 (progn
8847 (require 'table)
8848 (if (table--at-cell-p (point))
8850 (message "recognizing table.el table...")
8851 (table-recognize-table)
8852 (message "recognizing table.el table...done")))
8853 (error "This should not happen..."))
8855 nil)
8856 nil))
8858 (defun org-at-table-hline-p ()
8859 "Return t if the cursor is inside a hline in a table."
8860 (if org-enable-table-editor
8861 (save-excursion
8862 (beginning-of-line 1)
8863 (looking-at org-table-hline-regexp))
8864 nil))
8866 (defun org-table-insert-column ()
8867 "Insert a new column into the table."
8868 (interactive)
8869 (if (not (org-at-table-p))
8870 (error "Not at a table"))
8871 (org-table-find-dataline)
8872 (let* ((col (max 1 (org-table-current-column)))
8873 (beg (org-table-begin))
8874 (end (org-table-end))
8875 ;; Current cursor position
8876 (linepos (org-current-line))
8877 (colpos col))
8878 (goto-char beg)
8879 (while (< (point) end)
8880 (if (org-at-table-hline-p)
8882 (org-table-goto-column col t)
8883 (insert "| "))
8884 (beginning-of-line 2))
8885 (move-marker end nil)
8886 (goto-line linepos)
8887 (org-table-goto-column colpos)
8888 (org-table-align)
8889 (org-table-fix-formulas "$" nil (1- col) 1)))
8891 (defun org-table-find-dataline ()
8892 "Find a dataline in the current table, which is needed for column commands."
8893 (if (and (org-at-table-p)
8894 (not (org-at-table-hline-p)))
8896 (let ((col (current-column))
8897 (end (org-table-end)))
8898 (move-to-column col)
8899 (while (and (< (point) end)
8900 (or (not (= (current-column) col))
8901 (org-at-table-hline-p)))
8902 (beginning-of-line 2)
8903 (move-to-column col))
8904 (if (and (org-at-table-p)
8905 (not (org-at-table-hline-p)))
8907 (error
8908 "Please position cursor in a data line for column operations")))))
8910 (defun org-table-delete-column ()
8911 "Delete a column from the table."
8912 (interactive)
8913 (if (not (org-at-table-p))
8914 (error "Not at a table"))
8915 (org-table-find-dataline)
8916 (org-table-check-inside-data-field)
8917 (let* ((col (org-table-current-column))
8918 (beg (org-table-begin))
8919 (end (org-table-end))
8920 ;; Current cursor position
8921 (linepos (org-current-line))
8922 (colpos col))
8923 (goto-char beg)
8924 (while (< (point) end)
8925 (if (org-at-table-hline-p)
8927 (org-table-goto-column col t)
8928 (and (looking-at "|[^|\n]+|")
8929 (replace-match "|")))
8930 (beginning-of-line 2))
8931 (move-marker end nil)
8932 (goto-line linepos)
8933 (org-table-goto-column colpos)
8934 (org-table-align)
8935 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8936 col -1 col)))
8938 (defun org-table-move-column-right ()
8939 "Move column to the right."
8940 (interactive)
8941 (org-table-move-column nil))
8942 (defun org-table-move-column-left ()
8943 "Move column to the left."
8944 (interactive)
8945 (org-table-move-column 'left))
8947 (defun org-table-move-column (&optional left)
8948 "Move the current column to the right. With arg LEFT, move to the left."
8949 (interactive "P")
8950 (if (not (org-at-table-p))
8951 (error "Not at a table"))
8952 (org-table-find-dataline)
8953 (org-table-check-inside-data-field)
8954 (let* ((col (org-table-current-column))
8955 (col1 (if left (1- col) col))
8956 (beg (org-table-begin))
8957 (end (org-table-end))
8958 ;; Current cursor position
8959 (linepos (org-current-line))
8960 (colpos (if left (1- col) (1+ col))))
8961 (if (and left (= col 1))
8962 (error "Cannot move column further left"))
8963 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8964 (error "Cannot move column further right"))
8965 (goto-char beg)
8966 (while (< (point) end)
8967 (if (org-at-table-hline-p)
8969 (org-table-goto-column col1 t)
8970 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8971 (replace-match "|\\2|\\1|")))
8972 (beginning-of-line 2))
8973 (move-marker end nil)
8974 (goto-line linepos)
8975 (org-table-goto-column colpos)
8976 (org-table-align)
8977 (org-table-fix-formulas
8978 "$" (list (cons (number-to-string col) (number-to-string colpos))
8979 (cons (number-to-string colpos) (number-to-string col))))))
8981 (defun org-table-move-row-down ()
8982 "Move table row down."
8983 (interactive)
8984 (org-table-move-row nil))
8985 (defun org-table-move-row-up ()
8986 "Move table row up."
8987 (interactive)
8988 (org-table-move-row 'up))
8990 (defun org-table-move-row (&optional up)
8991 "Move the current table line down. With arg UP, move it up."
8992 (interactive "P")
8993 (let* ((col (current-column))
8994 (pos (point))
8995 (hline1p (save-excursion (beginning-of-line 1)
8996 (looking-at org-table-hline-regexp)))
8997 (dline1 (org-table-current-dline))
8998 (dline2 (+ dline1 (if up -1 1)))
8999 (tonew (if up 0 2))
9000 txt hline2p)
9001 (beginning-of-line tonew)
9002 (unless (org-at-table-p)
9003 (goto-char pos)
9004 (error "Cannot move row further"))
9005 (setq hline2p (looking-at org-table-hline-regexp))
9006 (goto-char pos)
9007 (beginning-of-line 1)
9008 (setq pos (point))
9009 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9010 (delete-region (point) (1+ (point-at-eol)))
9011 (beginning-of-line tonew)
9012 (insert txt)
9013 (beginning-of-line 0)
9014 (move-to-column col)
9015 (unless (or hline1p hline2p)
9016 (org-table-fix-formulas
9017 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9018 (cons (number-to-string dline2) (number-to-string dline1)))))))
9020 (defun org-table-insert-row (&optional arg)
9021 "Insert a new row above the current line into the table.
9022 With prefix ARG, insert below the current line."
9023 (interactive "P")
9024 (if (not (org-at-table-p))
9025 (error "Not at a table"))
9026 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9027 (new (org-table-clean-line line)))
9028 ;; Fix the first field if necessary
9029 (if (string-match "^[ \t]*| *[#$] *|" line)
9030 (setq new (replace-match (match-string 0 line) t t new)))
9031 (beginning-of-line (if arg 2 1))
9032 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9033 (beginning-of-line 0)
9034 (re-search-forward "| ?" (point-at-eol) t)
9035 (and (or org-table-may-need-update org-table-overlay-coordinates)
9036 (org-table-align))
9037 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9039 (defun org-table-insert-hline (&optional above)
9040 "Insert a horizontal-line below the current line into the table.
9041 With prefix ABOVE, insert above the current line."
9042 (interactive "P")
9043 (if (not (org-at-table-p))
9044 (error "Not at a table"))
9045 (let ((line (org-table-clean-line
9046 (buffer-substring (point-at-bol) (point-at-eol))))
9047 (col (current-column)))
9048 (while (string-match "|\\( +\\)|" line)
9049 (setq line (replace-match
9050 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9051 ?-) "|") t t line)))
9052 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9053 (beginning-of-line (if above 1 2))
9054 (insert line "\n")
9055 (beginning-of-line (if above 1 -1))
9056 (move-to-column col)
9057 (and org-table-overlay-coordinates (org-table-align))))
9059 (defun org-table-hline-and-move (&optional same-column)
9060 "Insert a hline and move to the row below that line."
9061 (interactive "P")
9062 (let ((col (org-table-current-column)))
9063 (org-table-maybe-eval-formula)
9064 (org-table-maybe-recalculate-line)
9065 (org-table-insert-hline)
9066 (end-of-line 2)
9067 (if (looking-at "\n[ \t]*|-")
9068 (progn (insert "\n|") (org-table-align))
9069 (org-table-next-field))
9070 (if same-column (org-table-goto-column col))))
9072 (defun org-table-clean-line (s)
9073 "Convert a table line S into a string with only \"|\" and space.
9074 In particular, this does handle wide and invisible characters."
9075 (if (string-match "^[ \t]*|-" s)
9076 ;; It's a hline, just map the characters
9077 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9078 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9079 (setq s (replace-match
9080 (concat "|" (make-string (org-string-width (match-string 1 s))
9081 ?\ ) "|")
9082 t t s)))
9085 (defun org-table-kill-row ()
9086 "Delete the current row or horizontal line from the table."
9087 (interactive)
9088 (if (not (org-at-table-p))
9089 (error "Not at a table"))
9090 (let ((col (current-column))
9091 (dline (org-table-current-dline)))
9092 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9093 (if (not (org-at-table-p)) (beginning-of-line 0))
9094 (move-to-column col)
9095 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9096 dline -1 dline)))
9098 (defun org-table-sort-lines (with-case &optional sorting-type)
9099 "Sort table lines according to the column at point.
9101 The position of point indicates the column to be used for
9102 sorting, and the range of lines is the range between the nearest
9103 horizontal separator lines, or the entire table of no such lines
9104 exist. If point is before the first column, you will be prompted
9105 for the sorting column. If there is an active region, the mark
9106 specifies the first line and the sorting column, while point
9107 should be in the last line to be included into the sorting.
9109 The command then prompts for the sorting type which can be
9110 alphabetically, numerically, or by time (as given in a time stamp
9111 in the field). Sorting in reverse order is also possible.
9113 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9115 If SORTING-TYPE is specified when this function is called from a Lisp
9116 program, no prompting will take place. SORTING-TYPE must be a character,
9117 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9118 should be done in reverse order."
9119 (interactive "P")
9120 (let* ((thisline (org-current-line))
9121 (thiscol (org-table-current-column))
9122 beg end bcol ecol tend tbeg column lns pos)
9123 (when (equal thiscol 0)
9124 (if (interactive-p)
9125 (setq thiscol
9126 (string-to-number
9127 (read-string "Use column N for sorting: ")))
9128 (setq thiscol 1))
9129 (org-table-goto-column thiscol))
9130 (org-table-check-inside-data-field)
9131 (if (org-region-active-p)
9132 (progn
9133 (setq beg (region-beginning) end (region-end))
9134 (goto-char beg)
9135 (setq column (org-table-current-column)
9136 beg (point-at-bol))
9137 (goto-char end)
9138 (setq end (point-at-bol 2)))
9139 (setq column (org-table-current-column)
9140 pos (point)
9141 tbeg (org-table-begin)
9142 tend (org-table-end))
9143 (if (re-search-backward org-table-hline-regexp tbeg t)
9144 (setq beg (point-at-bol 2))
9145 (goto-char tbeg)
9146 (setq beg (point-at-bol 1)))
9147 (goto-char pos)
9148 (if (re-search-forward org-table-hline-regexp tend t)
9149 (setq end (point-at-bol 1))
9150 (goto-char tend)
9151 (setq end (point-at-bol))))
9152 (setq beg (move-marker (make-marker) beg)
9153 end (move-marker (make-marker) end))
9154 (untabify beg end)
9155 (goto-char beg)
9156 (org-table-goto-column column)
9157 (skip-chars-backward "^|")
9158 (setq bcol (current-column))
9159 (org-table-goto-column (1+ column))
9160 (skip-chars-backward "^|")
9161 (setq ecol (1- (current-column)))
9162 (org-table-goto-column column)
9163 (setq lns (mapcar (lambda(x) (cons
9164 (org-sort-remove-invisible
9165 (nth (1- column)
9166 (org-split-string x "[ \t]*|[ \t]*")))
9168 (org-split-string (buffer-substring beg end) "\n")))
9169 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9170 (delete-region beg end)
9171 (move-marker beg nil)
9172 (move-marker end nil)
9173 (insert (mapconcat 'cdr lns "\n") "\n")
9174 (goto-line thisline)
9175 (org-table-goto-column thiscol)
9176 (message "%d lines sorted, based on column %d" (length lns) column)))
9178 ;; FIXME: maybe we will not need this? Table sorting is broken....
9179 (defun org-sort-remove-invisible (s)
9180 (remove-text-properties 0 (length s) org-rm-props s)
9181 (while (string-match org-bracket-link-regexp s)
9182 (setq s (replace-match (if (match-end 2)
9183 (match-string 3 s)
9184 (match-string 1 s)) t t s)))
9187 (defun org-table-cut-region (beg end)
9188 "Copy region in table to the clipboard and blank all relevant fields."
9189 (interactive "r")
9190 (org-table-copy-region beg end 'cut))
9192 (defun org-table-copy-region (beg end &optional cut)
9193 "Copy rectangular region in table to clipboard.
9194 A special clipboard is used which can only be accessed
9195 with `org-table-paste-rectangle'."
9196 (interactive "rP")
9197 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9198 region cols
9199 (rpl (if cut " " nil)))
9200 (goto-char beg)
9201 (org-table-check-inside-data-field)
9202 (setq l01 (org-current-line)
9203 c01 (org-table-current-column))
9204 (goto-char end)
9205 (org-table-check-inside-data-field)
9206 (setq l02 (org-current-line)
9207 c02 (org-table-current-column))
9208 (setq l1 (min l01 l02) l2 (max l01 l02)
9209 c1 (min c01 c02) c2 (max c01 c02))
9210 (catch 'exit
9211 (while t
9212 (catch 'nextline
9213 (if (> l1 l2) (throw 'exit t))
9214 (goto-line l1)
9215 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9216 (setq cols nil ic1 c1 ic2 c2)
9217 (while (< ic1 (1+ ic2))
9218 (push (org-table-get-field ic1 rpl) cols)
9219 (setq ic1 (1+ ic1)))
9220 (push (nreverse cols) region)
9221 (setq l1 (1+ l1)))))
9222 (setq org-table-clip (nreverse region))
9223 (if cut (org-table-align))
9224 org-table-clip))
9226 (defun org-table-paste-rectangle ()
9227 "Paste a rectangular region into a table.
9228 The upper right corner ends up in the current field. All involved fields
9229 will be overwritten. If the rectangle does not fit into the present table,
9230 the table is enlarged as needed. The process ignores horizontal separator
9231 lines."
9232 (interactive)
9233 (unless (and org-table-clip (listp org-table-clip))
9234 (error "First cut/copy a region to paste!"))
9235 (org-table-check-inside-data-field)
9236 (let* ((clip org-table-clip)
9237 (line (org-current-line))
9238 (col (org-table-current-column))
9239 (org-enable-table-editor t)
9240 (org-table-automatic-realign nil)
9241 c cols field)
9242 (while (setq cols (pop clip))
9243 (while (org-at-table-hline-p) (beginning-of-line 2))
9244 (if (not (org-at-table-p))
9245 (progn (end-of-line 0) (org-table-next-field)))
9246 (setq c col)
9247 (while (setq field (pop cols))
9248 (org-table-goto-column c nil 'force)
9249 (org-table-get-field nil field)
9250 (setq c (1+ c)))
9251 (beginning-of-line 2))
9252 (goto-line line)
9253 (org-table-goto-column col)
9254 (org-table-align)))
9256 (defun org-table-convert ()
9257 "Convert from `org-mode' table to table.el and back.
9258 Obviously, this only works within limits. When an Org-mode table is
9259 converted to table.el, all horizontal separator lines get lost, because
9260 table.el uses these as cell boundaries and has no notion of horizontal lines.
9261 A table.el table can be converted to an Org-mode table only if it does not
9262 do row or column spanning. Multiline cells will become multiple cells.
9263 Beware, Org-mode does not test if the table can be successfully converted - it
9264 blindly applies a recipe that works for simple tables."
9265 (interactive)
9266 (require 'table)
9267 (if (org-at-table.el-p)
9268 ;; convert to Org-mode table
9269 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9270 (end (move-marker (make-marker) (org-table-end t))))
9271 (table-unrecognize-region beg end)
9272 (goto-char beg)
9273 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9274 (replace-match ""))
9275 (goto-char beg))
9276 (if (org-at-table-p)
9277 ;; convert to table.el table
9278 (let ((beg (move-marker (make-marker) (org-table-begin)))
9279 (end (move-marker (make-marker) (org-table-end))))
9280 ;; first, get rid of all horizontal lines
9281 (goto-char beg)
9282 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9283 (replace-match ""))
9284 ;; insert a hline before first
9285 (goto-char beg)
9286 (org-table-insert-hline 'above)
9287 (beginning-of-line -1)
9288 ;; insert a hline after each line
9289 (while (progn (beginning-of-line 3) (< (point) end))
9290 (org-table-insert-hline))
9291 (goto-char beg)
9292 (setq end (move-marker end (org-table-end)))
9293 ;; replace "+" at beginning and ending of hlines
9294 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9295 (replace-match "\\1+-"))
9296 (goto-char beg)
9297 (while (re-search-forward "-|[ \t]*$" end t)
9298 (replace-match "-+"))
9299 (goto-char beg)))))
9301 (defun org-table-wrap-region (arg)
9302 "Wrap several fields in a column like a paragraph.
9303 This is useful if you'd like to spread the contents of a field over several
9304 lines, in order to keep the table compact.
9306 If there is an active region, and both point and mark are in the same column,
9307 the text in the column is wrapped to minimum width for the given number of
9308 lines. Generally, this makes the table more compact. A prefix ARG may be
9309 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9310 formats the selected text to two lines. If the region was longer than two
9311 lines, the remaining lines remain empty. A negative prefix argument reduces
9312 the current number of lines by that amount. The wrapped text is pasted back
9313 into the table. If you formatted it to more lines than it was before, fields
9314 further down in the table get overwritten - so you might need to make space in
9315 the table first.
9317 If there is no region, the current field is split at the cursor position and
9318 the text fragment to the right of the cursor is prepended to the field one
9319 line down.
9321 If there is no region, but you specify a prefix ARG, the current field gets
9322 blank, and the content is appended to the field above."
9323 (interactive "P")
9324 (org-table-check-inside-data-field)
9325 (if (org-region-active-p)
9326 ;; There is a region: fill as a paragraph
9327 (let* ((beg (region-beginning))
9328 (cline (save-excursion (goto-char beg) (org-current-line)))
9329 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9330 nlines)
9331 (org-table-cut-region (region-beginning) (region-end))
9332 (if (> (length (car org-table-clip)) 1)
9333 (error "Region must be limited to single column"))
9334 (setq nlines (if arg
9335 (if (< arg 1)
9336 (+ (length org-table-clip) arg)
9337 arg)
9338 (length org-table-clip)))
9339 (setq org-table-clip
9340 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9341 nil nlines)))
9342 (goto-line cline)
9343 (org-table-goto-column ccol)
9344 (org-table-paste-rectangle))
9345 ;; No region, split the current field at point
9346 (if arg
9347 ;; combine with field above
9348 (let ((s (org-table-blank-field))
9349 (col (org-table-current-column)))
9350 (beginning-of-line 0)
9351 (while (org-at-table-hline-p) (beginning-of-line 0))
9352 (org-table-goto-column col)
9353 (skip-chars-forward "^|")
9354 (skip-chars-backward " ")
9355 (insert " " (org-trim s))
9356 (org-table-align))
9357 ;; split field
9358 (when (looking-at "\\([^|]+\\)+|")
9359 (let ((s (match-string 1)))
9360 (replace-match " |")
9361 (goto-char (match-beginning 0))
9362 (org-table-next-row)
9363 (insert (org-trim s) " ")
9364 (org-table-align))))))
9366 (defvar org-field-marker nil)
9368 (defun org-table-edit-field (arg)
9369 "Edit table field in a different window.
9370 This is mainly useful for fields that contain hidden parts.
9371 When called with a \\[universal-argument] prefix, just make the full field visible so that
9372 it can be edited in place."
9373 (interactive "P")
9374 (if arg
9375 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9376 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9377 (remove-text-properties b e '(org-cwidth t invisible t
9378 display t intangible t))
9379 (if (and (boundp 'font-lock-mode) font-lock-mode)
9380 (font-lock-fontify-block)))
9381 (let ((pos (move-marker (make-marker) (point)))
9382 (field (org-table-get-field))
9383 (cw (current-window-configuration))
9385 (org-switch-to-buffer-other-window "*Org tmp*")
9386 (erase-buffer)
9387 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9388 (let ((org-inhibit-startup t)) (org-mode))
9389 (goto-char (setq p (point-max)))
9390 (insert (org-trim field))
9391 (remove-text-properties p (point-max)
9392 '(invisible t org-cwidth t display t
9393 intangible t))
9394 (goto-char p)
9395 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9396 (org-set-local 'org-window-configuration cw)
9397 (org-set-local 'org-field-marker pos)
9398 (message "Edit and finish with C-c C-c"))))
9400 (defun org-table-finish-edit-field ()
9401 "Finish editing a table data field.
9402 Remove all newline characters, insert the result into the table, realign
9403 the table and kill the editing buffer."
9404 (let ((pos org-field-marker)
9405 (cw org-window-configuration)
9406 (cb (current-buffer))
9407 text)
9408 (goto-char (point-min))
9409 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9410 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9411 (replace-match " "))
9412 (setq text (org-trim (buffer-string)))
9413 (set-window-configuration cw)
9414 (kill-buffer cb)
9415 (select-window (get-buffer-window (marker-buffer pos)))
9416 (goto-char pos)
9417 (move-marker pos nil)
9418 (org-table-check-inside-data-field)
9419 (org-table-get-field nil text)
9420 (org-table-align)
9421 (message "New field value inserted")))
9423 (defun org-trim (s)
9424 "Remove whitespace at beginning and end of string."
9425 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9426 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9429 (defun org-wrap (string &optional width lines)
9430 "Wrap string to either a number of lines, or a width in characters.
9431 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9432 that costs. If there is a word longer than WIDTH, the text is actually
9433 wrapped to the length of that word.
9434 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9435 many lines, whatever width that takes.
9436 The return value is a list of lines, without newlines at the end."
9437 (let* ((words (org-split-string string "[ \t\n]+"))
9438 (maxword (apply 'max (mapcar 'org-string-width words)))
9439 w ll)
9440 (cond (width
9441 (org-do-wrap words (max maxword width)))
9442 (lines
9443 (setq w maxword)
9444 (setq ll (org-do-wrap words maxword))
9445 (if (<= (length ll) lines)
9447 (setq ll words)
9448 (while (> (length ll) lines)
9449 (setq w (1+ w))
9450 (setq ll (org-do-wrap words w)))
9451 ll))
9452 (t (error "Cannot wrap this")))))
9455 (defun org-do-wrap (words width)
9456 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9457 (let (lines line)
9458 (while words
9459 (setq line (pop words))
9460 (while (and words (< (+ (length line) (length (car words))) width))
9461 (setq line (concat line " " (pop words))))
9462 (setq lines (push line lines)))
9463 (nreverse lines)))
9465 (defun org-split-string (string &optional separators)
9466 "Splits STRING into substrings at SEPARATORS.
9467 No empty strings are returned if there are matches at the beginning
9468 and end of string."
9469 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9470 (start 0)
9471 notfirst
9472 (list nil))
9473 (while (and (string-match rexp string
9474 (if (and notfirst
9475 (= start (match-beginning 0))
9476 (< start (length string)))
9477 (1+ start) start))
9478 (< (match-beginning 0) (length string)))
9479 (setq notfirst t)
9480 (or (eq (match-beginning 0) 0)
9481 (and (eq (match-beginning 0) (match-end 0))
9482 (eq (match-beginning 0) start))
9483 (setq list
9484 (cons (substring string start (match-beginning 0))
9485 list)))
9486 (setq start (match-end 0)))
9487 (or (eq start (length string))
9488 (setq list
9489 (cons (substring string start)
9490 list)))
9491 (nreverse list)))
9493 (defun org-table-map-tables (function)
9494 "Apply FUNCTION to the start of all tables in the buffer."
9495 (save-excursion
9496 (save-restriction
9497 (widen)
9498 (goto-char (point-min))
9499 (while (re-search-forward org-table-any-line-regexp nil t)
9500 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9501 (beginning-of-line 1)
9502 (if (looking-at org-table-line-regexp)
9503 (save-excursion (funcall function)))
9504 (re-search-forward org-table-any-border-regexp nil 1))))
9505 (message "Mapping tables: done"))
9507 (defvar org-timecnt) ; dynamically scoped parameter
9509 (defun org-table-sum (&optional beg end nlast)
9510 "Sum numbers in region of current table column.
9511 The result will be displayed in the echo area, and will be available
9512 as kill to be inserted with \\[yank].
9514 If there is an active region, it is interpreted as a rectangle and all
9515 numbers in that rectangle will be summed. If there is no active
9516 region and point is located in a table column, sum all numbers in that
9517 column.
9519 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9520 numbers are assumed to be times as well (in decimal hours) and the
9521 numbers are added as such.
9523 If NLAST is a number, only the NLAST fields will actually be summed."
9524 (interactive)
9525 (save-excursion
9526 (let (col (org-timecnt 0) diff h m s org-table-clip)
9527 (cond
9528 ((and beg end)) ; beg and end given explicitly
9529 ((org-region-active-p)
9530 (setq beg (region-beginning) end (region-end)))
9532 (setq col (org-table-current-column))
9533 (goto-char (org-table-begin))
9534 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9535 (error "No table data"))
9536 (org-table-goto-column col)
9537 (setq beg (point))
9538 (goto-char (org-table-end))
9539 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9540 (error "No table data"))
9541 (org-table-goto-column col)
9542 (setq end (point))))
9543 (let* ((items (apply 'append (org-table-copy-region beg end)))
9544 (items1 (cond ((not nlast) items)
9545 ((>= nlast (length items)) items)
9546 (t (setq items (reverse items))
9547 (setcdr (nthcdr (1- nlast) items) nil)
9548 (nreverse items))))
9549 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9550 items1)))
9551 (res (apply '+ numbers))
9552 (sres (if (= org-timecnt 0)
9553 (format "%g" res)
9554 (setq diff (* 3600 res)
9555 h (floor (/ diff 3600)) diff (mod diff 3600)
9556 m (floor (/ diff 60)) diff (mod diff 60)
9557 s diff)
9558 (format "%d:%02d:%02d" h m s))))
9559 (kill-new sres)
9560 (if (interactive-p)
9561 (message "%s"
9562 (substitute-command-keys
9563 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9564 (length numbers) sres))))
9565 sres))))
9567 (defun org-table-get-number-for-summing (s)
9568 (let (n)
9569 (if (string-match "^ *|? *" s)
9570 (setq s (replace-match "" nil nil s)))
9571 (if (string-match " *|? *$" s)
9572 (setq s (replace-match "" nil nil s)))
9573 (setq n (string-to-number s))
9574 (cond
9575 ((and (string-match "0" s)
9576 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9577 ((string-match "\\`[ \t]+\\'" s) nil)
9578 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9579 (let ((h (string-to-number (or (match-string 1 s) "0")))
9580 (m (string-to-number (or (match-string 2 s) "0")))
9581 (s (string-to-number (or (match-string 4 s) "0"))))
9582 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9583 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9584 ((equal n 0) nil)
9585 (t n))))
9587 (defun org-table-current-field-formula (&optional key noerror)
9588 "Return the formula active for the current field.
9589 Assumes that specials are in place.
9590 If KEY is given, return the key to this formula.
9591 Otherwise return the formula preceeded with \"=\" or \":=\"."
9592 (let* ((name (car (rassoc (list (org-current-line)
9593 (org-table-current-column))
9594 org-table-named-field-locations)))
9595 (col (org-table-current-column))
9596 (scol (int-to-string col))
9597 (ref (format "@%d$%d" (org-table-current-dline) col))
9598 (stored-list (org-table-get-stored-formulas noerror))
9599 (ass (or (assoc name stored-list)
9600 (assoc ref stored-list)
9601 (assoc scol stored-list))))
9602 (if key
9603 (car ass)
9604 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9605 (cdr ass))))))
9607 (defun org-table-get-formula (&optional equation named)
9608 "Read a formula from the minibuffer, offer stored formula as default.
9609 When NAMED is non-nil, look for a named equation."
9610 (let* ((stored-list (org-table-get-stored-formulas))
9611 (name (car (rassoc (list (org-current-line)
9612 (org-table-current-column))
9613 org-table-named-field-locations)))
9614 (ref (format "@%d$%d" (org-table-current-dline)
9615 (org-table-current-column)))
9616 (refass (assoc ref stored-list))
9617 (scol (if named
9618 (if name name ref)
9619 (int-to-string (org-table-current-column))))
9620 (dummy (and (or name refass) (not named)
9621 (not (y-or-n-p "Replace field formula with column formula? " ))
9622 (error "Abort")))
9623 (name (or name ref))
9624 (org-table-may-need-update nil)
9625 (stored (cdr (assoc scol stored-list)))
9626 (eq (cond
9627 ((and stored equation (string-match "^ *=? *$" equation))
9628 stored)
9629 ((stringp equation)
9630 equation)
9631 (t (org-table-formula-from-user
9632 (read-string
9633 (org-table-formula-to-user
9634 (format "%s formula %s%s="
9635 (if named "Field" "Column")
9636 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9637 scol))
9638 (if stored (org-table-formula-to-user stored) "")
9639 'org-table-formula-history
9640 )))))
9641 mustsave)
9642 (when (not (string-match "\\S-" eq))
9643 ;; remove formula
9644 (setq stored-list (delq (assoc scol stored-list) stored-list))
9645 (org-table-store-formulas stored-list)
9646 (error "Formula removed"))
9647 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9648 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9649 (if (and name (not named))
9650 ;; We set the column equation, delete the named one.
9651 (setq stored-list (delq (assoc name stored-list) stored-list)
9652 mustsave t))
9653 (if stored
9654 (setcdr (assoc scol stored-list) eq)
9655 (setq stored-list (cons (cons scol eq) stored-list)))
9656 (if (or mustsave (not (equal stored eq)))
9657 (org-table-store-formulas stored-list))
9658 eq))
9660 (defun org-table-store-formulas (alist)
9661 "Store the list of formulas below the current table."
9662 (setq alist (sort alist 'org-table-formula-less-p))
9663 (save-excursion
9664 (goto-char (org-table-end))
9665 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9666 (progn
9667 ;; don't overwrite TBLFM, we might use text properties to store stuff
9668 (goto-char (match-beginning 2))
9669 (delete-region (match-beginning 2) (match-end 0)))
9670 (insert "#+TBLFM:"))
9671 (insert " "
9672 (mapconcat (lambda (x)
9673 (concat
9674 (if (equal (string-to-char (car x)) ?@) "" "$")
9675 (car x) "=" (cdr x)))
9676 alist "::")
9677 "\n")))
9679 (defsubst org-table-formula-make-cmp-string (a)
9680 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9681 (concat
9682 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9683 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9684 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9686 (defun org-table-formula-less-p (a b)
9687 "Compare two formulas for sorting."
9688 (let ((as (org-table-formula-make-cmp-string (car a)))
9689 (bs (org-table-formula-make-cmp-string (car b))))
9690 (and as bs (string< as bs))))
9692 (defun org-table-get-stored-formulas (&optional noerror)
9693 "Return an alist with the stored formulas directly after current table."
9694 (interactive)
9695 (let (scol eq eq-alist strings string seen)
9696 (save-excursion
9697 (goto-char (org-table-end))
9698 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9699 (setq strings (org-split-string (match-string 2) " *:: *"))
9700 (while (setq string (pop strings))
9701 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9702 (setq scol (if (match-end 2)
9703 (match-string 2 string)
9704 (match-string 1 string))
9705 eq (match-string 3 string)
9706 eq-alist (cons (cons scol eq) eq-alist))
9707 (if (member scol seen)
9708 (if noerror
9709 (progn
9710 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9711 (ding)
9712 (sit-for 2))
9713 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9714 (push scol seen))))))
9715 (nreverse eq-alist)))
9717 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9718 "Modify the equations after the table structure has been edited.
9719 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9720 For all numbers larger than LIMIT, shift them by DELTA."
9721 (save-excursion
9722 (goto-char (org-table-end))
9723 (when (looking-at "#\\+TBLFM:")
9724 (let ((re (concat key "\\([0-9]+\\)"))
9725 (re2
9726 (when remove
9727 (if (equal key "$")
9728 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9729 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9730 s n a)
9731 (when remove
9732 (while (re-search-forward re2 (point-at-eol) t)
9733 (replace-match "")))
9734 (while (re-search-forward re (point-at-eol) t)
9735 (setq s (match-string 1) n (string-to-number s))
9736 (cond
9737 ((setq a (assoc s replace))
9738 (replace-match (concat key (cdr a)) t t))
9739 ((and limit (> n limit))
9740 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9742 (defun org-table-get-specials ()
9743 "Get the column names and local parameters for this table."
9744 (save-excursion
9745 (let ((beg (org-table-begin)) (end (org-table-end))
9746 names name fields fields1 field cnt
9747 c v l line col types dlines hlines)
9748 (setq org-table-column-names nil
9749 org-table-local-parameters nil
9750 org-table-named-field-locations nil
9751 org-table-current-begin-line nil
9752 org-table-current-begin-pos nil
9753 org-table-current-line-types nil)
9754 (goto-char beg)
9755 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9756 (setq names (org-split-string (match-string 1) " *| *")
9757 cnt 1)
9758 (while (setq name (pop names))
9759 (setq cnt (1+ cnt))
9760 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9761 (push (cons name (int-to-string cnt)) org-table-column-names))))
9762 (setq org-table-column-names (nreverse org-table-column-names))
9763 (setq org-table-column-name-regexp
9764 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9765 (goto-char beg)
9766 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9767 (setq fields (org-split-string (match-string 1) " *| *"))
9768 (while (setq field (pop fields))
9769 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9770 (push (cons (match-string 1 field) (match-string 2 field))
9771 org-table-local-parameters))))
9772 (goto-char beg)
9773 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9774 (setq c (match-string 1)
9775 fields (org-split-string (match-string 2) " *| *"))
9776 (save-excursion
9777 (beginning-of-line (if (equal c "_") 2 0))
9778 (setq line (org-current-line) col 1)
9779 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9780 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9781 (while (and fields1 (setq field (pop fields)))
9782 (setq v (pop fields1) col (1+ col))
9783 (when (and (stringp field) (stringp v)
9784 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9785 (push (cons field v) org-table-local-parameters)
9786 (push (list field line col) org-table-named-field-locations))))
9787 ;; Analyse the line types
9788 (goto-char beg)
9789 (setq org-table-current-begin-line (org-current-line)
9790 org-table-current-begin-pos (point)
9791 l org-table-current-begin-line)
9792 (while (looking-at "[ \t]*|\\(-\\)?")
9793 (push (if (match-end 1) 'hline 'dline) types)
9794 (if (match-end 1) (push l hlines) (push l dlines))
9795 (beginning-of-line 2)
9796 (setq l (1+ l)))
9797 (setq org-table-current-line-types (apply 'vector (nreverse types))
9798 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9799 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9801 (defun org-table-maybe-eval-formula ()
9802 "Check if the current field starts with \"=\" or \":=\".
9803 If yes, store the formula and apply it."
9804 ;; We already know we are in a table. Get field will only return a formula
9805 ;; when appropriate. It might return a separator line, but no problem.
9806 (when org-table-formula-evaluate-inline
9807 (let* ((field (org-trim (or (org-table-get-field) "")))
9808 named eq)
9809 (when (string-match "^:?=\\(.*\\)" field)
9810 (setq named (equal (string-to-char field) ?:)
9811 eq (match-string 1 field))
9812 (if (or (fboundp 'calc-eval)
9813 (equal (substring eq 0 (min 2 (length eq))) "'("))
9814 (org-table-eval-formula (if named '(4) nil)
9815 (org-table-formula-from-user eq))
9816 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9818 (defvar org-recalc-commands nil
9819 "List of commands triggering the recalculation of a line.
9820 Will be filled automatically during use.")
9822 (defvar org-recalc-marks
9823 '((" " . "Unmarked: no special line, no automatic recalculation")
9824 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9825 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9826 ("!" . "Column name definition line. Reference in formula as $name.")
9827 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9828 ("_" . "Names for values in row below this one.")
9829 ("^" . "Names for values in row above this one.")))
9831 (defun org-table-rotate-recalc-marks (&optional newchar)
9832 "Rotate the recalculation mark in the first column.
9833 If in any row, the first field is not consistent with a mark,
9834 insert a new column for the markers.
9835 When there is an active region, change all the lines in the region,
9836 after prompting for the marking character.
9837 After each change, a message will be displayed indicating the meaning
9838 of the new mark."
9839 (interactive)
9840 (unless (org-at-table-p) (error "Not at a table"))
9841 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9842 (beg (org-table-begin))
9843 (end (org-table-end))
9844 (l (org-current-line))
9845 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9846 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9847 (have-col
9848 (save-excursion
9849 (goto-char beg)
9850 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9851 (col (org-table-current-column))
9852 (forcenew (car (assoc newchar org-recalc-marks)))
9853 epos new)
9854 (when l1
9855 (message "Change region to what mark? Type # * ! $ or SPC: ")
9856 (setq newchar (char-to-string (read-char-exclusive))
9857 forcenew (car (assoc newchar org-recalc-marks))))
9858 (if (and newchar (not forcenew))
9859 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9860 newchar))
9861 (if l1 (goto-line l1))
9862 (save-excursion
9863 (beginning-of-line 1)
9864 (unless (looking-at org-table-dataline-regexp)
9865 (error "Not at a table data line")))
9866 (unless have-col
9867 (org-table-goto-column 1)
9868 (org-table-insert-column)
9869 (org-table-goto-column (1+ col)))
9870 (setq epos (point-at-eol))
9871 (save-excursion
9872 (beginning-of-line 1)
9873 (org-table-get-field
9874 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9875 (concat " "
9876 (setq new (or forcenew
9877 (cadr (member (match-string 1) marks))))
9878 " ")
9879 " # ")))
9880 (if (and l1 l2)
9881 (progn
9882 (goto-line l1)
9883 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9884 (and (looking-at org-table-dataline-regexp)
9885 (org-table-get-field 1 (concat " " new " "))))
9886 (goto-line l1)))
9887 (if (not (= epos (point-at-eol))) (org-table-align))
9888 (goto-line l)
9889 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
9891 (defun org-table-maybe-recalculate-line ()
9892 "Recompute the current line if marked for it, and if we haven't just done it."
9893 (interactive)
9894 (and org-table-allow-automatic-line-recalculation
9895 (not (and (memq last-command org-recalc-commands)
9896 (equal org-last-recalc-line (org-current-line))))
9897 (save-excursion (beginning-of-line 1)
9898 (looking-at org-table-auto-recalculate-regexp))
9899 (org-table-recalculate) t))
9901 (defvar org-table-formula-debug nil
9902 "Non-nil means, debug table formulas.
9903 When nil, simply write \"#ERROR\" in corrupted fields.")
9904 (make-variable-buffer-local 'org-table-formula-debug)
9906 (defvar modes)
9907 (defsubst org-set-calc-mode (var &optional value)
9908 (if (stringp var)
9909 (setq var (assoc var '(("D" calc-angle-mode deg)
9910 ("R" calc-angle-mode rad)
9911 ("F" calc-prefer-frac t)
9912 ("S" calc-symbolic-mode t)))
9913 value (nth 2 var) var (nth 1 var)))
9914 (if (memq var modes)
9915 (setcar (cdr (memq var modes)) value)
9916 (cons var (cons value modes)))
9917 modes)
9919 (defun org-table-eval-formula (&optional arg equation
9920 suppress-align suppress-const
9921 suppress-store suppress-analysis)
9922 "Replace the table field value at the cursor by the result of a calculation.
9924 This function makes use of Dave Gillespie's Calc package, in my view the
9925 most exciting program ever written for GNU Emacs. So you need to have Calc
9926 installed in order to use this function.
9928 In a table, this command replaces the value in the current field with the
9929 result of a formula. It also installs the formula as the \"current\" column
9930 formula, by storing it in a special line below the table. When called
9931 with a `C-u' prefix, the current field must ba a named field, and the
9932 formula is installed as valid in only this specific field.
9934 When called with two `C-u' prefixes, insert the active equation
9935 for the field back into the current field, so that it can be
9936 edited there. This is useful in order to use \\[org-table-show-reference]
9937 to check the referenced fields.
9939 When called, the command first prompts for a formula, which is read in
9940 the minibuffer. Previously entered formulas are available through the
9941 history list, and the last used formula is offered as a default.
9942 These stored formulas are adapted correctly when moving, inserting, or
9943 deleting columns with the corresponding commands.
9945 The formula can be any algebraic expression understood by the Calc package.
9946 For details, see the Org-mode manual.
9948 This function can also be called from Lisp programs and offers
9949 additional arguments: EQUATION can be the formula to apply. If this
9950 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9951 used to speed-up recursive calls by by-passing unnecessary aligns.
9952 SUPPRESS-CONST suppresses the interpretation of constants in the
9953 formula, assuming that this has been done already outside the function.
9954 SUPPRESS-STORE means the formula should not be stored, either because
9955 it is already stored, or because it is a modified equation that should
9956 not overwrite the stored one."
9957 (interactive "P")
9958 (org-table-check-inside-data-field)
9959 (or suppress-analysis (org-table-get-specials))
9960 (if (equal arg '(16))
9961 (let ((eq (org-table-current-field-formula)))
9962 (or eq (error "No equation active for current field"))
9963 (org-table-get-field nil eq)
9964 (org-table-align)
9965 (setq org-table-may-need-update t))
9966 (let* (fields
9967 (ndown (if (integerp arg) arg 1))
9968 (org-table-automatic-realign nil)
9969 (case-fold-search nil)
9970 (down (> ndown 1))
9971 (formula (if (and equation suppress-store)
9972 equation
9973 (org-table-get-formula equation (equal arg '(4)))))
9974 (n0 (org-table-current-column))
9975 (modes (copy-sequence org-calc-default-modes))
9976 (numbers nil) ; was a variable, now fixed default
9977 (keep-empty nil)
9978 n form form0 bw fmt x ev orig c lispp literal)
9979 ;; Parse the format string. Since we have a lot of modes, this is
9980 ;; a lot of work. However, I think calc still uses most of the time.
9981 (if (string-match ";" formula)
9982 (let ((tmp (org-split-string formula ";")))
9983 (setq formula (car tmp)
9984 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9985 (nth 1 tmp)))
9986 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9987 (setq c (string-to-char (match-string 1 fmt))
9988 n (string-to-number (match-string 2 fmt)))
9989 (if (= c ?p)
9990 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9991 (setq modes (org-set-calc-mode
9992 'calc-float-format
9993 (list (cdr (assoc c '((?n . float) (?f . fix)
9994 (?s . sci) (?e . eng))))
9995 n))))
9996 (setq fmt (replace-match "" t t fmt)))
9997 (if (string-match "[NT]" fmt)
9998 (setq numbers (equal (match-string 0 fmt) "N")
9999 fmt (replace-match "" t t fmt)))
10000 (if (string-match "L" fmt)
10001 (setq literal t
10002 fmt (replace-match "" t t fmt)))
10003 (if (string-match "E" fmt)
10004 (setq keep-empty t
10005 fmt (replace-match "" t t fmt)))
10006 (while (string-match "[DRFS]" fmt)
10007 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10008 (setq fmt (replace-match "" t t fmt)))
10009 (unless (string-match "\\S-" fmt)
10010 (setq fmt nil))))
10011 (if (and (not suppress-const) org-table-formula-use-constants)
10012 (setq formula (org-table-formula-substitute-names formula)))
10013 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10014 (while (> ndown 0)
10015 (setq fields (org-split-string
10016 (org-no-properties
10017 (buffer-substring (point-at-bol) (point-at-eol)))
10018 " *| *"))
10019 (if (eq numbers t)
10020 (setq fields (mapcar
10021 (lambda (x) (number-to-string (string-to-number x)))
10022 fields)))
10023 (setq ndown (1- ndown))
10024 (setq form (copy-sequence formula)
10025 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10026 (if (and lispp literal) (setq lispp 'literal))
10027 ;; Check for old vertical references
10028 (setq form (org-rewrite-old-row-references form))
10029 ;; Insert complex ranges
10030 (while (string-match org-table-range-regexp form)
10031 (setq form
10032 (replace-match
10033 (save-match-data
10034 (org-table-make-reference
10035 (org-table-get-range (match-string 0 form) nil n0)
10036 keep-empty numbers lispp))
10037 t t form)))
10038 ;; Insert simple ranges
10039 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10040 (setq form
10041 (replace-match
10042 (save-match-data
10043 (org-table-make-reference
10044 (org-sublist
10045 fields (string-to-number (match-string 1 form))
10046 (string-to-number (match-string 2 form)))
10047 keep-empty numbers lispp))
10048 t t form)))
10049 (setq form0 form)
10050 ;; Insert the references to fields in same row
10051 (while (string-match "\\$\\([0-9]+\\)" form)
10052 (setq n (string-to-number (match-string 1 form))
10053 x (nth (1- (if (= n 0) n0 n)) fields))
10054 (unless x (error "Invalid field specifier \"%s\""
10055 (match-string 0 form)))
10056 (setq form (replace-match
10057 (save-match-data
10058 (org-table-make-reference x nil numbers lispp))
10059 t t form)))
10061 (if lispp
10062 (setq ev (condition-case nil
10063 (eval (eval (read form)))
10064 (error "#ERROR"))
10065 ev (if (numberp ev) (number-to-string ev) ev))
10066 (or (fboundp 'calc-eval)
10067 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10068 (setq ev (calc-eval (cons form modes)
10069 (if numbers 'num))))
10071 (when org-table-formula-debug
10072 (with-output-to-temp-buffer "*Substitution History*"
10073 (princ (format "Substitution history of formula
10074 Orig: %s
10075 $xyz-> %s
10076 @r$c-> %s
10077 $1-> %s\n" orig formula form0 form))
10078 (if (listp ev)
10079 (princ (format " %s^\nError: %s"
10080 (make-string (car ev) ?\-) (nth 1 ev)))
10081 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10082 ev (or fmt "NONE")
10083 (if fmt (format fmt (string-to-number ev)) ev)))))
10084 (setq bw (get-buffer-window "*Substitution History*"))
10085 (shrink-window-if-larger-than-buffer bw)
10086 (unless (and (interactive-p) (not ndown))
10087 (unless (let (inhibit-redisplay)
10088 (y-or-n-p "Debugging Formula. Continue to next? "))
10089 (org-table-align)
10090 (error "Abort"))
10091 (delete-window bw)
10092 (message "")))
10093 (if (listp ev) (setq fmt nil ev "#ERROR"))
10094 (org-table-justify-field-maybe
10095 (if fmt (format fmt (string-to-number ev)) ev))
10096 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10097 (call-interactively 'org-return)
10098 (setq ndown 0)))
10099 (and down (org-table-maybe-recalculate-line))
10100 (or suppress-align (and org-table-may-need-update
10101 (org-table-align))))))
10103 (defun org-table-put-field-property (prop value)
10104 (save-excursion
10105 (put-text-property (progn (skip-chars-backward "^|") (point))
10106 (progn (skip-chars-forward "^|") (point))
10107 prop value)))
10109 (defun org-table-get-range (desc &optional tbeg col highlight)
10110 "Get a calc vector from a column, accorting to descriptor DESC.
10111 Optional arguments TBEG and COL can give the beginning of the table and
10112 the current column, to avoid unnecessary parsing.
10113 HIGHLIGHT means, just highlight the range."
10114 (if (not (equal (string-to-char desc) ?@))
10115 (setq desc (concat "@" desc)))
10116 (save-excursion
10117 (or tbeg (setq tbeg (org-table-begin)))
10118 (or col (setq col (org-table-current-column)))
10119 (let ((thisline (org-current-line))
10120 beg end c1 c2 r1 r2 rangep tmp)
10121 (unless (string-match org-table-range-regexp desc)
10122 (error "Invalid table range specifier `%s'" desc))
10123 (setq rangep (match-end 3)
10124 r1 (and (match-end 1) (match-string 1 desc))
10125 r2 (and (match-end 4) (match-string 4 desc))
10126 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10127 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10129 (and c1 (setq c1 (+ (string-to-number c1)
10130 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10131 (and c2 (setq c2 (+ (string-to-number c2)
10132 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10133 (if (equal r1 "") (setq r1 nil))
10134 (if (equal r2 "") (setq r2 nil))
10135 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10136 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10137 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10138 (if (not r1) (setq r1 thisline))
10139 (if (not r2) (setq r2 thisline))
10140 (if (not c1) (setq c1 col))
10141 (if (not c2) (setq c2 col))
10142 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10143 ;; just one field
10144 (progn
10145 (goto-line r1)
10146 (while (not (looking-at org-table-dataline-regexp))
10147 (beginning-of-line 2))
10148 (prog1 (org-trim (org-table-get-field c1))
10149 (if highlight (org-table-highlight-rectangle (point) (point)))))
10150 ;; A range, return a vector
10151 ;; First sort the numbers to get a regular ractangle
10152 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10153 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10154 (goto-line r1)
10155 (while (not (looking-at org-table-dataline-regexp))
10156 (beginning-of-line 2))
10157 (org-table-goto-column c1)
10158 (setq beg (point))
10159 (goto-line r2)
10160 (while (not (looking-at org-table-dataline-regexp))
10161 (beginning-of-line 0))
10162 (org-table-goto-column c2)
10163 (setq end (point))
10164 (if highlight
10165 (org-table-highlight-rectangle
10166 beg (progn (skip-chars-forward "^|\n") (point))))
10167 ;; return string representation of calc vector
10168 (mapcar 'org-trim
10169 (apply 'append (org-table-copy-region beg end)))))))
10171 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10172 "Analyze descriptor DESC and retrieve the corresponding line number.
10173 The cursor is currently in line CLINE, the table begins in line BLINE,
10174 and TABLE is a vector with line types."
10175 (if (string-match "^[0-9]+$" desc)
10176 (aref org-table-dlines (string-to-number desc))
10177 (setq cline (or cline (org-current-line))
10178 bline (or bline org-table-current-begin-line)
10179 table (or table org-table-current-line-types))
10180 (if (or
10181 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10182 ;; 1 2 3 4 5 6
10183 (and (not (match-end 3)) (not (match-end 6)))
10184 (and (match-end 3) (match-end 6) (not (match-end 5))))
10185 (error "invalid row descriptor `%s'" desc))
10186 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10187 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10188 (odir (and (match-end 5) (match-string 5 desc)))
10189 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10190 (i (- cline bline))
10191 (rel (and (match-end 6)
10192 (or (and (match-end 1) (not (match-end 3)))
10193 (match-end 5)))))
10194 (if (and hn (not hdir))
10195 (progn
10196 (setq i 0 hdir "+")
10197 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10198 (if (and (not hn) on (not odir))
10199 (error "should never happen");;(aref org-table-dlines on)
10200 (if (and hn (> hn 0))
10201 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10202 (if on
10203 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10204 (+ bline i)))))
10206 (defun org-find-row-type (table i type backwards relative n)
10207 (let ((l (length table)))
10208 (while (> n 0)
10209 (while (and (setq i (+ i (if backwards -1 1)))
10210 (>= i 0) (< i l)
10211 (not (eq (aref table i) type))
10212 (if (and relative (eq (aref table i) 'hline))
10213 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10214 t)))
10215 (setq n (1- n)))
10216 (if (or (< i 0) (>= i l))
10217 (error "Row descriptior leads outside table")
10218 i)))
10220 (defun org-rewrite-old-row-references (s)
10221 (if (string-match "&[-+0-9I]" s)
10222 (error "Formula contains old &row reference, please rewrite using @-syntax")
10225 (defun org-table-make-reference (elements keep-empty numbers lispp)
10226 "Convert list ELEMENTS to something appropriate to insert into formula.
10227 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10228 NUMBERS indicates that everything should be converted to numbers.
10229 LISPP means to return something appropriate for a Lisp list."
10230 (if (stringp elements) ; just a single val
10231 (if lispp
10232 (if (eq lispp 'literal)
10233 elements
10234 (prin1-to-string (if numbers (string-to-number elements) elements)))
10235 (if (equal elements "") (setq elements "0"))
10236 (if numbers (number-to-string (string-to-number elements)) elements))
10237 (unless keep-empty
10238 (setq elements
10239 (delq nil
10240 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10241 elements))))
10242 (setq elements (or elements '("0")))
10243 (if lispp
10244 (mapconcat
10245 (lambda (x)
10246 (if (eq lispp 'literal)
10248 (prin1-to-string (if numbers (string-to-number x) x))))
10249 elements " ")
10250 (concat "[" (mapconcat
10251 (lambda (x)
10252 (if numbers (number-to-string (string-to-number x)) x))
10253 elements
10254 ",") "]"))))
10256 (defun org-table-recalculate (&optional all noalign)
10257 "Recalculate the current table line by applying all stored formulas.
10258 With prefix arg ALL, do this for all lines in the table."
10259 (interactive "P")
10260 (or (memq this-command org-recalc-commands)
10261 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10262 (unless (org-at-table-p) (error "Not at a table"))
10263 (if (equal all '(16))
10264 (org-table-iterate)
10265 (org-table-get-specials)
10266 (let* ((eqlist (sort (org-table-get-stored-formulas)
10267 (lambda (a b) (string< (car a) (car b)))))
10268 (inhibit-redisplay (not debug-on-error))
10269 (line-re org-table-dataline-regexp)
10270 (thisline (org-current-line))
10271 (thiscol (org-table-current-column))
10272 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10273 ;; Insert constants in all formulas
10274 (setq eqlist
10275 (mapcar (lambda (x)
10276 (setcdr x (org-table-formula-substitute-names (cdr x)))
10278 eqlist))
10279 ;; Split the equation list
10280 (while (setq eq (pop eqlist))
10281 (if (<= (string-to-char (car eq)) ?9)
10282 (push eq eqlnum)
10283 (push eq eqlname)))
10284 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10285 (if all
10286 (progn
10287 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10288 (goto-char (setq beg (org-table-begin)))
10289 (if (re-search-forward org-table-calculate-mark-regexp end t)
10290 ;; This is a table with marked lines, compute selected lines
10291 (setq line-re org-table-recalculate-regexp)
10292 ;; Move forward to the first non-header line
10293 (if (and (re-search-forward org-table-dataline-regexp end t)
10294 (re-search-forward org-table-hline-regexp end t)
10295 (re-search-forward org-table-dataline-regexp end t))
10296 (setq beg (match-beginning 0))
10297 nil))) ;; just leave beg where it is
10298 (setq beg (point-at-bol)
10299 end (move-marker (make-marker) (1+ (point-at-eol)))))
10300 (goto-char beg)
10301 (and all (message "Re-applying formulas to full table..."))
10303 ;; First find the named fields, and mark them untouchanble
10304 (remove-text-properties beg end '(org-untouchable t))
10305 (while (setq eq (pop eqlname))
10306 (setq name (car eq)
10307 a (assoc name org-table-named-field-locations))
10308 (and (not a)
10309 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10310 (setq a (list name
10311 (aref org-table-dlines
10312 (string-to-number (match-string 1 name)))
10313 (string-to-number (match-string 2 name)))))
10314 (when (and a (or all (equal (nth 1 a) thisline)))
10315 (message "Re-applying formula to field: %s" name)
10316 (goto-line (nth 1 a))
10317 (org-table-goto-column (nth 2 a))
10318 (push (append a (list (cdr eq))) eqlname1)
10319 (org-table-put-field-property :org-untouchable t)))
10321 ;; Now evauluate the column formulas, but skip fields covered by
10322 ;; field formulas
10323 (goto-char beg)
10324 (while (re-search-forward line-re end t)
10325 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10326 ;; Unprotected line, recalculate
10327 (and all (message "Re-applying formulas to full table...(line %d)"
10328 (setq cnt (1+ cnt))))
10329 (setq org-last-recalc-line (org-current-line))
10330 (setq eql eqlnum)
10331 (while (setq entry (pop eql))
10332 (goto-line org-last-recalc-line)
10333 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10334 (unless (get-text-property (point) :org-untouchable)
10335 (org-table-eval-formula nil (cdr entry)
10336 'noalign 'nocst 'nostore 'noanalysis)))))
10338 ;; Now evaluate the field formulas
10339 (while (setq eq (pop eqlname1))
10340 (message "Re-applying formula to field: %s" (car eq))
10341 (goto-line (nth 1 eq))
10342 (org-table-goto-column (nth 2 eq))
10343 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10344 'nostore 'noanalysis))
10346 (goto-line thisline)
10347 (org-table-goto-column thiscol)
10348 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10349 (or noalign (and org-table-may-need-update (org-table-align))
10350 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10352 ;; back to initial position
10353 (message "Re-applying formulas...done")
10354 (goto-line thisline)
10355 (org-table-goto-column thiscol)
10356 (or noalign (and org-table-may-need-update (org-table-align))
10357 (and all (message "Re-applying formulas...done"))))))
10359 (defun org-table-iterate (&optional arg)
10360 "Recalculate the table until it does not change anymore."
10361 (interactive "P")
10362 (let ((imax (if arg (prefix-numeric-value arg) 10))
10363 (i 0)
10364 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10365 thistbl)
10366 (catch 'exit
10367 (while (< i imax)
10368 (setq i (1+ i))
10369 (org-table-recalculate 'all)
10370 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10371 (if (not (string= lasttbl thistbl))
10372 (setq lasttbl thistbl)
10373 (if (> i 1)
10374 (message "Convergence after %d iterations" i)
10375 (message "Table was already stable"))
10376 (throw 'exit t)))
10377 (error "No convergence after %d iterations" i))))
10379 (defun org-table-formula-substitute-names (f)
10380 "Replace $const with values in string F."
10381 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10382 ;; First, check for column names
10383 (while (setq start (string-match org-table-column-name-regexp f start))
10384 (setq start (1+ start))
10385 (setq a (assoc (match-string 1 f) org-table-column-names))
10386 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10387 ;; Parameters and constants
10388 (setq start 0)
10389 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10390 (setq start (1+ start))
10391 (if (setq a (save-match-data
10392 (org-table-get-constant (match-string 1 f))))
10393 (setq f (replace-match
10394 (concat (if pp "(") a (if pp ")")) t t f))))
10395 (if org-table-formula-debug
10396 (put-text-property 0 (length f) :orig-formula f1 f))
10399 (defun org-table-get-constant (const)
10400 "Find the value for a parameter or constant in a formula.
10401 Parameters get priority."
10402 (or (cdr (assoc const org-table-local-parameters))
10403 (cdr (assoc const org-table-formula-constants-local))
10404 (cdr (assoc const org-table-formula-constants))
10405 (and (fboundp 'constants-get) (constants-get const))
10406 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10407 (org-entry-get nil (substring const 5) 'inherit))
10408 "#UNDEFINED_NAME"))
10410 (defvar org-table-fedit-map
10411 (let ((map (make-sparse-keymap)))
10412 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10413 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10414 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10415 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10416 (org-defkey map "\C-c?" 'org-table-show-reference)
10417 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10418 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10419 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10420 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10421 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10422 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10423 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10424 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10425 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10426 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10427 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10428 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10429 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10430 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10431 map))
10433 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10434 '("Edit-Formulas"
10435 ["Finish and Install" org-table-fedit-finish t]
10436 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10437 ["Abort" org-table-fedit-abort t]
10438 "--"
10439 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10440 ["Complete Lisp Symbol" lisp-complete-symbol t]
10441 "--"
10442 "Shift Reference at Point"
10443 ["Up" org-table-fedit-ref-up t]
10444 ["Down" org-table-fedit-ref-down t]
10445 ["Left" org-table-fedit-ref-left t]
10446 ["Right" org-table-fedit-ref-right t]
10448 "Change Test Row for Column Formulas"
10449 ["Up" org-table-fedit-line-up t]
10450 ["Down" org-table-fedit-line-down t]
10451 "--"
10452 ["Scroll Table Window" org-table-fedit-scroll t]
10453 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10454 ["Show Table Grid" org-table-fedit-toggle-coordinates
10455 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10456 org-table-overlay-coordinates)]
10457 "--"
10458 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10459 :style toggle :selected org-table-buffer-is-an]))
10461 (defvar org-pos)
10463 (defun org-table-edit-formulas ()
10464 "Edit the formulas of the current table in a separate buffer."
10465 (interactive)
10466 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10467 (beginning-of-line 0))
10468 (unless (org-at-table-p) (error "Not at a table"))
10469 (org-table-get-specials)
10470 (let ((key (org-table-current-field-formula 'key 'noerror))
10471 (eql (sort (org-table-get-stored-formulas 'noerror)
10472 'org-table-formula-less-p))
10473 (pos (move-marker (make-marker) (point)))
10474 (startline 1)
10475 (wc (current-window-configuration))
10476 (titles '((column . "# Column Formulas\n")
10477 (field . "# Field Formulas\n")
10478 (named . "# Named Field Formulas\n")))
10479 entry s type title)
10480 (org-switch-to-buffer-other-window "*Edit Formulas*")
10481 (erase-buffer)
10482 ;; Keep global-font-lock-mode from turning on font-lock-mode
10483 (let ((font-lock-global-modes '(not fundamental-mode)))
10484 (fundamental-mode))
10485 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10486 (org-set-local 'org-pos pos)
10487 (org-set-local 'org-window-configuration wc)
10488 (use-local-map org-table-fedit-map)
10489 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10490 (easy-menu-add org-table-fedit-menu)
10491 (setq startline (org-current-line))
10492 (while (setq entry (pop eql))
10493 (setq type (cond
10494 ((equal (string-to-char (car entry)) ?@) 'field)
10495 ((string-match "^[0-9]" (car entry)) 'column)
10496 (t 'named)))
10497 (when (setq title (assq type titles))
10498 (or (bobp) (insert "\n"))
10499 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10500 (setq titles (delq title titles)))
10501 (if (equal key (car entry)) (setq startline (org-current-line)))
10502 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10503 (car entry) " = " (cdr entry) "\n"))
10504 (remove-text-properties 0 (length s) '(face nil) s)
10505 (insert s))
10506 (if (eq org-table-use-standard-references t)
10507 (org-table-fedit-toggle-ref-type))
10508 (goto-line startline)
10509 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10511 (defun org-table-fedit-post-command ()
10512 (when (not (memq this-command '(lisp-complete-symbol)))
10513 (let ((win (selected-window)))
10514 (save-excursion
10515 (condition-case nil
10516 (org-table-show-reference)
10517 (error nil))
10518 (select-window win)))))
10520 (defun org-table-formula-to-user (s)
10521 "Convert a formula from internal to user representation."
10522 (if (eq org-table-use-standard-references t)
10523 (org-table-convert-refs-to-an s)
10526 (defun org-table-formula-from-user (s)
10527 "Convert a formula from user to internal representation."
10528 (if org-table-use-standard-references
10529 (org-table-convert-refs-to-rc s)
10532 (defun org-table-convert-refs-to-rc (s)
10533 "Convert spreadsheet references from AB7 to @7$28.
10534 Works for single references, but also for entire formulas and even the
10535 full TBLFM line."
10536 (let ((start 0))
10537 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10538 (cond
10539 ((match-end 3)
10540 ;; format match, just advance
10541 (setq start (match-end 0)))
10542 ((and (> (match-beginning 0) 0)
10543 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10544 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10545 ;; 3.e5 or something like this.
10546 (setq start (match-end 0)))
10548 (setq start (match-beginning 0)
10549 s (replace-match
10550 (if (equal (match-string 2 s) "&")
10551 (format "$%d" (org-letters-to-number (match-string 1 s)))
10552 (format "@%d$%d"
10553 (string-to-number (match-string 2 s))
10554 (org-letters-to-number (match-string 1 s))))
10555 t t s)))))
10558 (defun org-table-convert-refs-to-an (s)
10559 "Convert spreadsheet references from to @7$28 to AB7.
10560 Works for single references, but also for entire formulas and even the
10561 full TBLFM line."
10562 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10563 (setq s (replace-match
10564 (format "%s%d"
10565 (org-number-to-letters
10566 (string-to-number (match-string 2 s)))
10567 (string-to-number (match-string 1 s)))
10568 t t s)))
10569 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10570 (setq s (replace-match (concat "\\1"
10571 (org-number-to-letters
10572 (string-to-number (match-string 2 s))) "&")
10573 t nil s)))
10576 (defun org-letters-to-number (s)
10577 "Convert a base 26 number represented by letters into an integer.
10578 For example: AB -> 28."
10579 (let ((n 0))
10580 (setq s (upcase s))
10581 (while (> (length s) 0)
10582 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10583 s (substring s 1)))
10586 (defun org-number-to-letters (n)
10587 "Convert an integer into a base 26 number represented by letters.
10588 For example: 28 -> AB."
10589 (let ((s ""))
10590 (while (> n 0)
10591 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10592 n (/ (1- n) 26)))
10595 (defun org-table-fedit-convert-buffer (function)
10596 "Convert all references in this buffer, using FUNTION."
10597 (let ((line (org-current-line)))
10598 (goto-char (point-min))
10599 (while (not (eobp))
10600 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10601 (delete-region (point) (point-at-eol))
10602 (or (eobp) (forward-char 1)))
10603 (goto-line line)))
10605 (defun org-table-fedit-toggle-ref-type ()
10606 "Convert all references in the buffer from B3 to @3$2 and back."
10607 (interactive)
10608 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10609 (org-table-fedit-convert-buffer
10610 (if org-table-buffer-is-an
10611 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10612 (message "Reference type switched to %s"
10613 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10615 (defun org-table-fedit-ref-up ()
10616 "Shift the reference at point one row/hline up."
10617 (interactive)
10618 (org-table-fedit-shift-reference 'up))
10619 (defun org-table-fedit-ref-down ()
10620 "Shift the reference at point one row/hline down."
10621 (interactive)
10622 (org-table-fedit-shift-reference 'down))
10623 (defun org-table-fedit-ref-left ()
10624 "Shift the reference at point one field to the left."
10625 (interactive)
10626 (org-table-fedit-shift-reference 'left))
10627 (defun org-table-fedit-ref-right ()
10628 "Shift the reference at point one field to the right."
10629 (interactive)
10630 (org-table-fedit-shift-reference 'right))
10632 (defun org-table-fedit-shift-reference (dir)
10633 (cond
10634 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10635 (if (memq dir '(left right))
10636 (org-rematch-and-replace 1 (eq dir 'left))
10637 (error "Cannot shift reference in this direction")))
10638 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10639 ;; A B3-like reference
10640 (if (memq dir '(up down))
10641 (org-rematch-and-replace 2 (eq dir 'up))
10642 (org-rematch-and-replace 1 (eq dir 'left))))
10643 ((org-at-regexp-p
10644 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10645 ;; An internal reference
10646 (if (memq dir '(up down))
10647 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10648 (org-rematch-and-replace 5 (eq dir 'left))))))
10650 (defun org-rematch-and-replace (n &optional decr hline)
10651 "Re-match the group N, and replace it with the shifted refrence."
10652 (or (match-end n) (error "Cannot shift reference in this direction"))
10653 (goto-char (match-beginning n))
10654 (and (looking-at (regexp-quote (match-string n)))
10655 (replace-match (org-shift-refpart (match-string 0) decr hline)
10656 t t)))
10658 (defun org-shift-refpart (ref &optional decr hline)
10659 "Shift a refrence part REF.
10660 If DECR is set, decrease the references row/column, else increase.
10661 If HLINE is set, this may be a hline reference, it certainly is not
10662 a translation reference."
10663 (save-match-data
10664 (let* ((sign (string-match "^[-+]" ref)) n)
10666 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10667 (cond
10668 ((and hline (string-match "^I+" ref))
10669 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10670 (setq n (+ n (if decr -1 1)))
10671 (if (= n 0) (setq n (+ n (if decr -1 1))))
10672 (if sign
10673 (setq sign (if (< n 0) "-" "+") n (abs n))
10674 (setq n (max 1 n)))
10675 (concat sign (make-string n ?I)))
10677 ((string-match "^[0-9]+" ref)
10678 (setq n (string-to-number (concat sign ref)))
10679 (setq n (+ n (if decr -1 1)))
10680 (if sign
10681 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10682 (number-to-string (max 1 n))))
10684 ((string-match "^[a-zA-Z]+" ref)
10685 (org-number-to-letters
10686 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10688 (t (error "Cannot shift reference"))))))
10690 (defun org-table-fedit-toggle-coordinates ()
10691 "Toggle the display of coordinates in the refrenced table."
10692 (interactive)
10693 (let ((pos (marker-position org-pos)))
10694 (with-current-buffer (marker-buffer org-pos)
10695 (save-excursion
10696 (goto-char pos)
10697 (org-table-toggle-coordinate-overlays)))))
10699 (defun org-table-fedit-finish (&optional arg)
10700 "Parse the buffer for formula definitions and install them.
10701 With prefix ARG, apply the new formulas to the table."
10702 (interactive "P")
10703 (org-table-remove-rectangle-highlight)
10704 (if org-table-use-standard-references
10705 (progn
10706 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10707 (setq org-table-buffer-is-an nil)))
10708 (let ((pos org-pos) eql var form)
10709 (goto-char (point-min))
10710 (while (re-search-forward
10711 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10712 nil t)
10713 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10714 form (match-string 3))
10715 (setq form (org-trim form))
10716 (when (not (equal form ""))
10717 (while (string-match "[ \t]*\n[ \t]*" form)
10718 (setq form (replace-match " " t t form)))
10719 (when (assoc var eql)
10720 (error "Double formulas for %s" var))
10721 (push (cons var form) eql)))
10722 (setq org-pos nil)
10723 (set-window-configuration org-window-configuration)
10724 (select-window (get-buffer-window (marker-buffer pos)))
10725 (goto-char pos)
10726 (unless (org-at-table-p)
10727 (error "Lost table position - cannot install formulae"))
10728 (org-table-store-formulas eql)
10729 (move-marker pos nil)
10730 (kill-buffer "*Edit Formulas*")
10731 (if arg
10732 (org-table-recalculate 'all)
10733 (message "New formulas installed - press C-u C-c C-c to apply."))))
10735 (defun org-table-fedit-abort ()
10736 "Abort editing formulas, without installing the changes."
10737 (interactive)
10738 (org-table-remove-rectangle-highlight)
10739 (let ((pos org-pos))
10740 (set-window-configuration org-window-configuration)
10741 (select-window (get-buffer-window (marker-buffer pos)))
10742 (goto-char pos)
10743 (move-marker pos nil)
10744 (message "Formula editing aborted without installing changes")))
10746 (defun org-table-fedit-lisp-indent ()
10747 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10748 (interactive)
10749 (let ((pos (point)) beg end ind)
10750 (beginning-of-line 1)
10751 (cond
10752 ((looking-at "[ \t]")
10753 (goto-char pos)
10754 (call-interactively 'lisp-indent-line))
10755 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10756 ((not (fboundp 'pp-buffer))
10757 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10758 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10759 (goto-char (- (match-end 0) 2))
10760 (setq beg (point))
10761 (setq ind (make-string (current-column) ?\ ))
10762 (condition-case nil (forward-sexp 1)
10763 (error
10764 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10765 (setq end (point))
10766 (save-restriction
10767 (narrow-to-region beg end)
10768 (if (eq last-command this-command)
10769 (progn
10770 (goto-char (point-min))
10771 (setq this-command nil)
10772 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10773 (replace-match " ")))
10774 (pp-buffer)
10775 (untabify (point-min) (point-max))
10776 (goto-char (1+ (point-min)))
10777 (while (re-search-forward "^." nil t)
10778 (beginning-of-line 1)
10779 (insert ind))
10780 (goto-char (point-max))
10781 (backward-delete-char 1)))
10782 (goto-char beg))
10783 (t nil))))
10785 (defvar org-show-positions nil)
10787 (defun org-table-show-reference (&optional local)
10788 "Show the location/value of the $ expression at point."
10789 (interactive)
10790 (org-table-remove-rectangle-highlight)
10791 (catch 'exit
10792 (let ((pos (if local (point) org-pos))
10793 (face2 'highlight)
10794 (org-inhibit-highlight-removal t)
10795 (win (selected-window))
10796 (org-show-positions nil)
10797 var name e what match dest)
10798 (if local (org-table-get-specials))
10799 (setq what (cond
10800 ((or (org-at-regexp-p org-table-range-regexp2)
10801 (org-at-regexp-p org-table-translate-regexp)
10802 (org-at-regexp-p org-table-range-regexp))
10803 (setq match
10804 (save-match-data
10805 (org-table-convert-refs-to-rc (match-string 0))))
10806 'range)
10807 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10808 ((org-at-regexp-p "\\$[0-9]+") 'column)
10809 ((not local) nil)
10810 (t (error "No reference at point")))
10811 match (and what (or match (match-string 0))))
10812 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10813 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10814 'secondary-selection))
10815 (org-add-hook 'before-change-functions
10816 'org-table-remove-rectangle-highlight)
10817 (if (eq what 'name) (setq var (substring match 1)))
10818 (when (eq what 'range)
10819 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10820 (setq match (org-table-formula-substitute-names match)))
10821 (unless local
10822 (save-excursion
10823 (end-of-line 1)
10824 (re-search-backward "^\\S-" nil t)
10825 (beginning-of-line 1)
10826 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10827 (setq dest
10828 (save-match-data
10829 (org-table-convert-refs-to-rc (match-string 1))))
10830 (org-table-add-rectangle-overlay
10831 (match-beginning 1) (match-end 1) face2))))
10832 (if (and (markerp pos) (marker-buffer pos))
10833 (if (get-buffer-window (marker-buffer pos))
10834 (select-window (get-buffer-window (marker-buffer pos)))
10835 (org-switch-to-buffer-other-window (get-buffer-window
10836 (marker-buffer pos)))))
10837 (goto-char pos)
10838 (org-table-force-dataline)
10839 (when dest
10840 (setq name (substring dest 1))
10841 (cond
10842 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10843 (setq e (assoc name org-table-named-field-locations))
10844 (goto-line (nth 1 e))
10845 (org-table-goto-column (nth 2 e)))
10846 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10847 (let ((l (string-to-number (match-string 1 dest)))
10848 (c (string-to-number (match-string 2 dest))))
10849 (goto-line (aref org-table-dlines l))
10850 (org-table-goto-column c)))
10851 (t (org-table-goto-column (string-to-number name))))
10852 (move-marker pos (point))
10853 (org-table-highlight-rectangle nil nil face2))
10854 (cond
10855 ((equal dest match))
10856 ((not match))
10857 ((eq what 'range)
10858 (condition-case nil
10859 (save-excursion
10860 (org-table-get-range match nil nil 'highlight))
10861 (error nil)))
10862 ((setq e (assoc var org-table-named-field-locations))
10863 (goto-line (nth 1 e))
10864 (org-table-goto-column (nth 2 e))
10865 (org-table-highlight-rectangle (point) (point))
10866 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10867 ((setq e (assoc var org-table-column-names))
10868 (org-table-goto-column (string-to-number (cdr e)))
10869 (org-table-highlight-rectangle (point) (point))
10870 (goto-char (org-table-begin))
10871 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10872 (org-table-end) t)
10873 (progn
10874 (goto-char (match-beginning 1))
10875 (org-table-highlight-rectangle)
10876 (message "Named column (column %s)" (cdr e)))
10877 (error "Column name not found")))
10878 ((eq what 'column)
10879 ;; column number
10880 (org-table-goto-column (string-to-number (substring match 1)))
10881 (org-table-highlight-rectangle (point) (point))
10882 (message "Column %s" (substring match 1)))
10883 ((setq e (assoc var org-table-local-parameters))
10884 (goto-char (org-table-begin))
10885 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10886 (progn
10887 (goto-char (match-beginning 1))
10888 (org-table-highlight-rectangle)
10889 (message "Local parameter."))
10890 (error "Parameter not found")))
10892 (cond
10893 ((not var) (error "No reference at point"))
10894 ((setq e (assoc var org-table-formula-constants-local))
10895 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10896 var (cdr e)))
10897 ((setq e (assoc var org-table-formula-constants))
10898 (message "Constant: $%s=%s in `org-table-formula-constants'."
10899 var (cdr e)))
10900 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10901 (message "Constant: $%s=%s, from `constants.el'%s."
10902 var e (format " (%s units)" constants-unit-system)))
10903 (t (error "Undefined name $%s" var)))))
10904 (goto-char pos)
10905 (when (and org-show-positions
10906 (not (memq this-command '(org-table-fedit-scroll
10907 org-table-fedit-scroll-down))))
10908 (push pos org-show-positions)
10909 (push org-table-current-begin-pos org-show-positions)
10910 (let ((min (apply 'min org-show-positions))
10911 (max (apply 'max org-show-positions)))
10912 (goto-char min) (recenter 0)
10913 (goto-char max)
10914 (or (pos-visible-in-window-p max) (recenter -1))))
10915 (select-window win))))
10917 (defun org-table-force-dataline ()
10918 "Make sure the cursor is in a dataline in a table."
10919 (unless (save-excursion
10920 (beginning-of-line 1)
10921 (looking-at org-table-dataline-regexp))
10922 (let* ((re org-table-dataline-regexp)
10923 (p1 (save-excursion (re-search-forward re nil 'move)))
10924 (p2 (save-excursion (re-search-backward re nil 'move))))
10925 (cond ((and p1 p2)
10926 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10927 p1 p2)))
10928 ((or p1 p2) (goto-char (or p1 p2)))
10929 (t (error "No table dataline around here"))))))
10931 (defun org-table-fedit-line-up ()
10932 "Move cursor one line up in the window showing the table."
10933 (interactive)
10934 (org-table-fedit-move 'previous-line))
10936 (defun org-table-fedit-line-down ()
10937 "Move cursor one line down in the window showing the table."
10938 (interactive)
10939 (org-table-fedit-move 'next-line))
10941 (defun org-table-fedit-move (command)
10942 "Move the cursor in the window shoinw the table.
10943 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10944 (let ((org-table-allow-automatic-line-recalculation nil)
10945 (pos org-pos) (win (selected-window)) p)
10946 (select-window (get-buffer-window (marker-buffer org-pos)))
10947 (setq p (point))
10948 (call-interactively command)
10949 (while (and (org-at-table-p)
10950 (org-at-table-hline-p))
10951 (call-interactively command))
10952 (or (org-at-table-p) (goto-char p))
10953 (move-marker pos (point))
10954 (select-window win)))
10956 (defun org-table-fedit-scroll (N)
10957 (interactive "p")
10958 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10959 (scroll-other-window N)))
10961 (defun org-table-fedit-scroll-down (N)
10962 (interactive "p")
10963 (org-table-fedit-scroll (- N)))
10965 (defvar org-table-rectangle-overlays nil)
10967 (defun org-table-add-rectangle-overlay (beg end &optional face)
10968 "Add a new overlay."
10969 (let ((ov (org-make-overlay beg end)))
10970 (org-overlay-put ov 'face (or face 'secondary-selection))
10971 (push ov org-table-rectangle-overlays)))
10973 (defun org-table-highlight-rectangle (&optional beg end face)
10974 "Highlight rectangular region in a table."
10975 (setq beg (or beg (point)) end (or end (point)))
10976 (let ((b (min beg end))
10977 (e (max beg end))
10978 l1 c1 l2 c2 tmp)
10979 (and (boundp 'org-show-positions)
10980 (setq org-show-positions (cons b (cons e org-show-positions))))
10981 (goto-char (min beg end))
10982 (setq l1 (org-current-line)
10983 c1 (org-table-current-column))
10984 (goto-char (max beg end))
10985 (setq l2 (org-current-line)
10986 c2 (org-table-current-column))
10987 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10988 (goto-line l1)
10989 (beginning-of-line 1)
10990 (loop for line from l1 to l2 do
10991 (when (looking-at org-table-dataline-regexp)
10992 (org-table-goto-column c1)
10993 (skip-chars-backward "^|\n") (setq beg (point))
10994 (org-table-goto-column c2)
10995 (skip-chars-forward "^|\n") (setq end (point))
10996 (org-table-add-rectangle-overlay beg end face))
10997 (beginning-of-line 2))
10998 (goto-char b))
10999 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11001 (defun org-table-remove-rectangle-highlight (&rest ignore)
11002 "Remove the rectangle overlays."
11003 (unless org-inhibit-highlight-removal
11004 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11005 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11006 (setq org-table-rectangle-overlays nil)))
11008 (defvar org-table-coordinate-overlays nil
11009 "Collects the cooordinate grid overlays, so that they can be removed.")
11010 (make-variable-buffer-local 'org-table-coordinate-overlays)
11012 (defun org-table-overlay-coordinates ()
11013 "Add overlays to the table at point, to show row/column coordinates."
11014 (interactive)
11015 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11016 (setq org-table-coordinate-overlays nil)
11017 (save-excursion
11018 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11019 (goto-char (org-table-begin))
11020 (while (org-at-table-p)
11021 (setq eol (point-at-eol))
11022 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11023 (push ov org-table-coordinate-overlays)
11024 (setq hline (looking-at org-table-hline-regexp))
11025 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11026 (format "%4d" (setq id (1+ id)))))
11027 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11028 (when hline
11029 (setq ic 0)
11030 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11031 (setq beg (1+ (match-beginning 0))
11032 ic (1+ ic)
11033 s1 (concat "$" (int-to-string ic))
11034 s2 (org-number-to-letters ic)
11035 str (if (eq org-table-use-standard-references t) s2 s1))
11036 (setq ov (org-make-overlay beg (+ beg (length str))))
11037 (push ov org-table-coordinate-overlays)
11038 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11039 (beginning-of-line 2)))))
11041 (defun org-table-toggle-coordinate-overlays ()
11042 "Toggle the display of Row/Column numbers in tables."
11043 (interactive)
11044 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11045 (message "Row/Column number display turned %s"
11046 (if org-table-overlay-coordinates "on" "off"))
11047 (if (and (org-at-table-p) org-table-overlay-coordinates)
11048 (org-table-align))
11049 (unless org-table-overlay-coordinates
11050 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11051 (setq org-table-coordinate-overlays nil)))
11053 (defun org-table-toggle-formula-debugger ()
11054 "Toggle the formula debugger in tables."
11055 (interactive)
11056 (setq org-table-formula-debug (not org-table-formula-debug))
11057 (message "Formula debugging has been turned %s"
11058 (if org-table-formula-debug "on" "off")))
11060 ;;; The orgtbl minor mode
11062 ;; Define a minor mode which can be used in other modes in order to
11063 ;; integrate the org-mode table editor.
11065 ;; This is really a hack, because the org-mode table editor uses several
11066 ;; keys which normally belong to the major mode, for example the TAB and
11067 ;; RET keys. Here is how it works: The minor mode defines all the keys
11068 ;; necessary to operate the table editor, but wraps the commands into a
11069 ;; function which tests if the cursor is currently inside a table. If that
11070 ;; is the case, the table editor command is executed. However, when any of
11071 ;; those keys is used outside a table, the function uses `key-binding' to
11072 ;; look up if the key has an associated command in another currently active
11073 ;; keymap (minor modes, major mode, global), and executes that command.
11074 ;; There might be problems if any of the keys used by the table editor is
11075 ;; otherwise used as a prefix key.
11077 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11078 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11079 ;; addresses this by checking explicitly for both bindings.
11081 ;; The optimized version (see variable `orgtbl-optimized') takes over
11082 ;; all keys which are bound to `self-insert-command' in the *global map*.
11083 ;; Some modes bind other commands to simple characters, for example
11084 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11085 ;; active, this binding is ignored inside tables and replaced with a
11086 ;; modified self-insert.
11088 (defvar orgtbl-mode nil
11089 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11090 table editor in arbitrary modes.")
11091 (make-variable-buffer-local 'orgtbl-mode)
11093 (defvar orgtbl-mode-map (make-keymap)
11094 "Keymap for `orgtbl-mode'.")
11096 ;;;###autoload
11097 (defun turn-on-orgtbl ()
11098 "Unconditionally turn on `orgtbl-mode'."
11099 (orgtbl-mode 1))
11101 (defvar org-old-auto-fill-inhibit-regexp nil
11102 "Local variable used by `orgtbl-mode'")
11104 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11105 "Matches a line belonging to an orgtbl.")
11107 (defconst orgtbl-extra-font-lock-keywords
11108 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11109 0 (quote 'org-table) 'prepend))
11110 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11112 ;;;###autoload
11113 (defun orgtbl-mode (&optional arg)
11114 "The `org-mode' table editor as a minor mode for use in other modes."
11115 (interactive)
11116 (if (org-mode-p)
11117 ;; Exit without error, in case some hook functions calls this
11118 ;; by accident in org-mode.
11119 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11120 (setq orgtbl-mode
11121 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11122 (if orgtbl-mode
11123 (progn
11124 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11125 ;; Make sure we are first in minor-mode-map-alist
11126 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11127 (and c (setq minor-mode-map-alist
11128 (cons c (delq c minor-mode-map-alist)))))
11129 (org-set-local (quote org-table-may-need-update) t)
11130 (org-add-hook 'before-change-functions 'org-before-change-function
11131 nil 'local)
11132 (org-set-local 'org-old-auto-fill-inhibit-regexp
11133 auto-fill-inhibit-regexp)
11134 (org-set-local 'auto-fill-inhibit-regexp
11135 (if auto-fill-inhibit-regexp
11136 (concat orgtbl-line-start-regexp "\\|"
11137 auto-fill-inhibit-regexp)
11138 orgtbl-line-start-regexp))
11139 (org-add-to-invisibility-spec '(org-cwidth))
11140 (when (fboundp 'font-lock-add-keywords)
11141 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11142 (org-restart-font-lock))
11143 (easy-menu-add orgtbl-mode-menu)
11144 (run-hooks 'orgtbl-mode-hook))
11145 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11146 (org-cleanup-narrow-column-properties)
11147 (org-remove-from-invisibility-spec '(org-cwidth))
11148 (remove-hook 'before-change-functions 'org-before-change-function t)
11149 (when (fboundp 'font-lock-remove-keywords)
11150 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11151 (org-restart-font-lock))
11152 (easy-menu-remove orgtbl-mode-menu)
11153 (force-mode-line-update 'all))))
11155 (defun org-cleanup-narrow-column-properties ()
11156 "Remove all properties related to narrow-column invisibility."
11157 (let ((s 1))
11158 (while (setq s (text-property-any s (point-max)
11159 'display org-narrow-column-arrow))
11160 (remove-text-properties s (1+ s) '(display t)))
11161 (setq s 1)
11162 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11163 (remove-text-properties s (1+ s) '(org-cwidth t)))
11164 (setq s 1)
11165 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11166 (remove-text-properties s (1+ s) '(invisible t)))))
11168 ;; Install it as a minor mode.
11169 (put 'orgtbl-mode :included t)
11170 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11171 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11173 (defun orgtbl-make-binding (fun n &rest keys)
11174 "Create a function for binding in the table minor mode.
11175 FUN is the command to call inside a table. N is used to create a unique
11176 command name. KEYS are keys that should be checked in for a command
11177 to execute outside of tables."
11178 (eval
11179 (list 'defun
11180 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11181 '(arg)
11182 (concat "In tables, run `" (symbol-name fun) "'.\n"
11183 "Outside of tables, run the binding of `"
11184 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11185 "'.")
11186 '(interactive "p")
11187 (list 'if
11188 '(org-at-table-p)
11189 (list 'call-interactively (list 'quote fun))
11190 (list 'let '(orgtbl-mode)
11191 (list 'call-interactively
11192 (append '(or)
11193 (mapcar (lambda (k)
11194 (list 'key-binding k))
11195 keys)
11196 '('orgtbl-error))))))))
11198 (defun orgtbl-error ()
11199 "Error when there is no default binding for a table key."
11200 (interactive)
11201 (error "This key has no function outside tables"))
11203 (defun orgtbl-setup ()
11204 "Setup orgtbl keymaps."
11205 (let ((nfunc 0)
11206 (bindings
11207 (list
11208 '([(meta shift left)] org-table-delete-column)
11209 '([(meta left)] org-table-move-column-left)
11210 '([(meta right)] org-table-move-column-right)
11211 '([(meta shift right)] org-table-insert-column)
11212 '([(meta shift up)] org-table-kill-row)
11213 '([(meta shift down)] org-table-insert-row)
11214 '([(meta up)] org-table-move-row-up)
11215 '([(meta down)] org-table-move-row-down)
11216 '("\C-c\C-w" org-table-cut-region)
11217 '("\C-c\M-w" org-table-copy-region)
11218 '("\C-c\C-y" org-table-paste-rectangle)
11219 '("\C-c-" org-table-insert-hline)
11220 '("\C-c}" org-table-toggle-coordinate-overlays)
11221 '("\C-c{" org-table-toggle-formula-debugger)
11222 '("\C-m" org-table-next-row)
11223 '([(shift return)] org-table-copy-down)
11224 '("\C-c\C-q" org-table-wrap-region)
11225 '("\C-c?" org-table-field-info)
11226 '("\C-c " org-table-blank-field)
11227 '("\C-c+" org-table-sum)
11228 '("\C-c=" org-table-eval-formula)
11229 '("\C-c'" org-table-edit-formulas)
11230 '("\C-c`" org-table-edit-field)
11231 '("\C-c*" org-table-recalculate)
11232 '("\C-c|" org-table-create-or-convert-from-region)
11233 '("\C-c^" org-table-sort-lines)
11234 '([(control ?#)] org-table-rotate-recalc-marks)))
11235 elt key fun cmd)
11236 (while (setq elt (pop bindings))
11237 (setq nfunc (1+ nfunc))
11238 (setq key (org-key (car elt))
11239 fun (nth 1 elt)
11240 cmd (orgtbl-make-binding fun nfunc key))
11241 (org-defkey orgtbl-mode-map key cmd))
11243 ;; Special treatment needed for TAB and RET
11244 (org-defkey orgtbl-mode-map [(return)]
11245 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11246 (org-defkey orgtbl-mode-map "\C-m"
11247 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11249 (org-defkey orgtbl-mode-map [(tab)]
11250 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11251 (org-defkey orgtbl-mode-map "\C-i"
11252 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11254 (org-defkey orgtbl-mode-map [(shift tab)]
11255 (orgtbl-make-binding 'org-table-previous-field 104
11256 [(shift tab)] [(tab)] "\C-i"))
11258 (org-defkey orgtbl-mode-map "\M-\C-m"
11259 (orgtbl-make-binding 'org-table-wrap-region 105
11260 "\M-\C-m" [(meta return)]))
11261 (org-defkey orgtbl-mode-map [(meta return)]
11262 (orgtbl-make-binding 'org-table-wrap-region 106
11263 [(meta return)] "\M-\C-m"))
11265 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11266 (when orgtbl-optimized
11267 ;; If the user wants maximum table support, we need to hijack
11268 ;; some standard editing functions
11269 (org-remap orgtbl-mode-map
11270 'self-insert-command 'orgtbl-self-insert-command
11271 'delete-char 'org-delete-char
11272 'delete-backward-char 'org-delete-backward-char)
11273 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11274 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11275 '("OrgTbl"
11276 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11277 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11278 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11279 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11280 "--"
11281 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11282 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11283 ["Copy Field from Above"
11284 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11285 "--"
11286 ("Column"
11287 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11288 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11289 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11290 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11291 ("Row"
11292 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11293 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11294 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11295 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11296 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11297 "--"
11298 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11299 ("Rectangle"
11300 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11301 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11302 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11303 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11304 "--"
11305 ("Radio tables"
11306 ["Insert table template" orgtbl-insert-radio-table
11307 (assq major-mode orgtbl-radio-table-templates)]
11308 ["Comment/uncomment table" orgtbl-toggle-comment t])
11309 "--"
11310 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11311 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11312 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11313 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11314 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11315 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11316 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11317 ["Sum Column/Rectangle" org-table-sum
11318 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11319 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11320 ["Debug Formulas"
11321 org-table-toggle-formula-debugger :active (org-at-table-p)
11322 :keys "C-c {"
11323 :style toggle :selected org-table-formula-debug]
11324 ["Show Col/Row Numbers"
11325 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11326 :keys "C-c }"
11327 :style toggle :selected org-table-overlay-coordinates]
11331 (defun orgtbl-ctrl-c-ctrl-c (arg)
11332 "If the cursor is inside a table, realign the table.
11333 It it is a table to be sent away to a receiver, do it.
11334 With prefix arg, also recompute table."
11335 (interactive "P")
11336 (let ((pos (point)) action)
11337 (save-excursion
11338 (beginning-of-line 1)
11339 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11340 ((looking-at "[ \t]*|") pos)
11341 ((looking-at "#\\+TBLFM:") 'recalc))))
11342 (cond
11343 ((integerp action)
11344 (goto-char action)
11345 (org-table-maybe-eval-formula)
11346 (if arg
11347 (call-interactively 'org-table-recalculate)
11348 (org-table-maybe-recalculate-line))
11349 (call-interactively 'org-table-align)
11350 (orgtbl-send-table 'maybe))
11351 ((eq action 'recalc)
11352 (save-excursion
11353 (beginning-of-line 1)
11354 (skip-chars-backward " \r\n\t")
11355 (if (org-at-table-p)
11356 (org-call-with-arg 'org-table-recalculate t))))
11357 (t (let (orgtbl-mode)
11358 (call-interactively (key-binding "\C-c\C-c")))))))
11360 (defun orgtbl-tab (arg)
11361 "Justification and field motion for `orgtbl-mode'."
11362 (interactive "P")
11363 (if arg (org-table-edit-field t)
11364 (org-table-justify-field-maybe)
11365 (org-table-next-field)))
11367 (defun orgtbl-ret ()
11368 "Justification and field motion for `orgtbl-mode'."
11369 (interactive)
11370 (org-table-justify-field-maybe)
11371 (org-table-next-row))
11373 (defun orgtbl-self-insert-command (N)
11374 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11375 If the cursor is in a table looking at whitespace, the whitespace is
11376 overwritten, and the table is not marked as requiring realignment."
11377 (interactive "p")
11378 (if (and (org-at-table-p)
11380 (and org-table-auto-blank-field
11381 (member last-command
11382 '(orgtbl-hijacker-command-100
11383 orgtbl-hijacker-command-101
11384 orgtbl-hijacker-command-102
11385 orgtbl-hijacker-command-103
11386 orgtbl-hijacker-command-104
11387 orgtbl-hijacker-command-105))
11388 (org-table-blank-field))
11390 (eq N 1)
11391 (looking-at "[^|\n]* +|"))
11392 (let (org-table-may-need-update)
11393 (goto-char (1- (match-end 0)))
11394 (delete-backward-char 1)
11395 (goto-char (match-beginning 0))
11396 (self-insert-command N))
11397 (setq org-table-may-need-update t)
11398 (let (orgtbl-mode)
11399 (call-interactively (key-binding (vector last-input-event))))))
11401 (defun org-force-self-insert (N)
11402 "Needed to enforce self-insert under remapping."
11403 (interactive "p")
11404 (self-insert-command N))
11406 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11407 "Regula expression matching exponentials as produced by calc.")
11409 (defvar org-table-clean-did-remove-column nil)
11411 (defun orgtbl-export (table target)
11412 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11413 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11414 org-table-last-alignment org-table-last-column-widths
11415 maxcol column)
11416 (if (not (fboundp func))
11417 (error "Cannot export orgtbl table to %s" target))
11418 (setq lines (org-table-clean-before-export lines))
11419 (setq table
11420 (mapcar
11421 (lambda (x)
11422 (if (string-match org-table-hline-regexp x)
11423 'hline
11424 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11425 lines))
11426 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11427 table)))
11428 (loop for i from (1- maxcol) downto 0 do
11429 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11430 (setq column (delq nil column))
11431 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11432 (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))
11433 (funcall func table nil)))
11435 (defun orgtbl-send-table (&optional maybe)
11436 "Send a tranformed version of this table to the receiver position.
11437 With argument MAYBE, fail quietly if no transformation is defined for
11438 this table."
11439 (interactive)
11440 (catch 'exit
11441 (unless (org-at-table-p) (error "Not at a table"))
11442 ;; when non-interactive, we assume align has just happened.
11443 (when (interactive-p) (org-table-align))
11444 (save-excursion
11445 (goto-char (org-table-begin))
11446 (beginning-of-line 0)
11447 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11448 (if maybe
11449 (throw 'exit nil)
11450 (error "Don't know how to transform this table."))))
11451 (let* ((name (match-string 1))
11453 (transform (intern (match-string 2)))
11454 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11455 (skip (plist-get params :skip))
11456 (skipcols (plist-get params :skipcols))
11457 (txt (buffer-substring-no-properties
11458 (org-table-begin) (org-table-end)))
11459 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11460 (lines (org-table-clean-before-export lines))
11461 (i0 (if org-table-clean-did-remove-column 2 1))
11462 (table (mapcar
11463 (lambda (x)
11464 (if (string-match org-table-hline-regexp x)
11465 'hline
11466 (org-remove-by-index
11467 (org-split-string (org-trim x) "\\s-*|\\s-*")
11468 skipcols i0)))
11469 lines))
11470 (fun (if (= i0 2) 'cdr 'identity))
11471 (org-table-last-alignment
11472 (org-remove-by-index (funcall fun org-table-last-alignment)
11473 skipcols i0))
11474 (org-table-last-column-widths
11475 (org-remove-by-index (funcall fun org-table-last-column-widths)
11476 skipcols i0)))
11478 (unless (fboundp transform)
11479 (error "No such transformation function %s" transform))
11480 (setq txt (funcall transform table params))
11481 ;; Find the insertion place
11482 (save-excursion
11483 (goto-char (point-min))
11484 (unless (re-search-forward
11485 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11486 (error "Don't know where to insert translated table"))
11487 (goto-char (match-beginning 0))
11488 (beginning-of-line 2)
11489 (setq beg (point))
11490 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11491 (error "Cannot find end of insertion region"))
11492 (beginning-of-line 1)
11493 (delete-region beg (point))
11494 (goto-char beg)
11495 (insert txt "\n"))
11496 (message "Table converted and installed at receiver location"))))
11498 (defun org-remove-by-index (list indices &optional i0)
11499 "Remove the elements in LIST with indices in INDICES.
11500 First element has index 0, or I0 if given."
11501 (if (not indices)
11502 list
11503 (if (integerp indices) (setq indices (list indices)))
11504 (setq i0 (1- (or i0 0)))
11505 (delq :rm (mapcar (lambda (x)
11506 (setq i0 (1+ i0))
11507 (if (memq i0 indices) :rm x))
11508 list))))
11510 (defun orgtbl-toggle-comment ()
11511 "Comment or uncomment the orgtbl at point."
11512 (interactive)
11513 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11514 (re2 (concat "^" orgtbl-line-start-regexp))
11515 (commented (save-excursion (beginning-of-line 1)
11516 (cond ((looking-at re1) t)
11517 ((looking-at re2) nil)
11518 (t (error "Not at an org table")))))
11519 (re (if commented re1 re2))
11520 beg end)
11521 (save-excursion
11522 (beginning-of-line 1)
11523 (while (looking-at re) (beginning-of-line 0))
11524 (beginning-of-line 2)
11525 (setq beg (point))
11526 (while (looking-at re) (beginning-of-line 2))
11527 (setq end (point)))
11528 (comment-region beg end (if commented '(4) nil))))
11530 (defun orgtbl-insert-radio-table ()
11531 "Insert a radio table template appropriate for this major mode."
11532 (interactive)
11533 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11534 (txt (nth 1 e))
11535 name pos)
11536 (unless e (error "No radio table setup defined for %s" major-mode))
11537 (setq name (read-string "Table name: "))
11538 (while (string-match "%n" txt)
11539 (setq txt (replace-match name t t txt)))
11540 (or (bolp) (insert "\n"))
11541 (setq pos (point))
11542 (insert txt)
11543 (goto-char pos)))
11545 (defun org-get-param (params header i sym &optional hsym)
11546 "Get parameter value for symbol SYM.
11547 If this is a header line, actually get the value for the symbol with an
11548 additional \"h\" inserted after the colon.
11549 If the value is a protperty list, get the element for the current column.
11550 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11551 (let ((val (plist-get params sym)))
11552 (and hsym header (setq val (or (plist-get params hsym) val)))
11553 (if (consp val) (plist-get val i) val)))
11555 (defun orgtbl-to-generic (table params)
11556 "Convert the orgtbl-mode TABLE to some other format.
11557 This generic routine can be used for many standard cases.
11558 TABLE is a list, each entry either the symbol `hline' for a horizontal
11559 separator line, or a list of fields for that line.
11560 PARAMS is a property list of parameters that can influence the conversion.
11561 For the generic converter, some parameters are obligatory: You need to
11562 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11563 :splice, you must have :tstart and :tend.
11565 Valid parameters are
11567 :tstart String to start the table. Ignored when :splice is t.
11568 :tend String to end the table. Ignored when :splice is t.
11570 :splice When set to t, return only table body lines, don't wrap
11571 them into :tstart and :tend. Default is nil.
11573 :hline String to be inserted on horizontal separation lines.
11574 May be nil to ignore hlines.
11576 :lstart String to start a new table line.
11577 :lend String to end a table line
11578 :sep Separator between two fields
11579 :lfmt Format for entire line, with enough %s to capture all fields.
11580 If this is present, :lstart, :lend, and :sep are ignored.
11581 :fmt A format to be used to wrap the field, should contain
11582 %s for the original field value. For example, to wrap
11583 everything in dollars, you could use :fmt \"$%s$\".
11584 This may also be a property list with column numbers and
11585 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11587 :hlstart :hlend :hlsep :hlfmt :hfmt
11588 Same as above, specific for the header lines in the table.
11589 All lines before the first hline are treated as header.
11590 If any of these is not present, the data line value is used.
11592 :efmt Use this format to print numbers with exponentials.
11593 The format should have %s twice for inserting mantissa
11594 and exponent, for example \"%s\\\\times10^{%s}\". This
11595 may also be a property list with column numbers and
11596 formats. :fmt will still be applied after :efmt.
11598 In addition to this, the parameters :skip and :skipcols are always handled
11599 directly by `orgtbl-send-table'. See manual."
11600 (interactive)
11601 (let* ((p params)
11602 (splicep (plist-get p :splice))
11603 (hline (plist-get p :hline))
11604 rtn line i fm efm lfmt h)
11606 ;; Do we have a header?
11607 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11608 (setq h t))
11610 ;; Put header
11611 (unless splicep
11612 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11614 ;; Now loop over all lines
11615 (while (setq line (pop table))
11616 (if (eq line 'hline)
11617 ;; A horizontal separator line
11618 (progn (if hline (push hline rtn))
11619 (setq h nil)) ; no longer in header
11620 ;; A normal line. Convert the fields, push line onto the result list
11621 (setq i 0)
11622 (setq line
11623 (mapcar
11624 (lambda (f)
11625 (setq i (1+ i)
11626 fm (org-get-param p h i :fmt :hfmt)
11627 efm (org-get-param p h i :efmt))
11628 (if (and efm (string-match orgtbl-exp-regexp f))
11629 (setq f (format
11630 efm (match-string 1 f) (match-string 2 f))))
11631 (if fm (setq f (format fm f)))
11633 line))
11634 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11635 (push (apply 'format lfmt line) rtn)
11636 (push (concat
11637 (org-get-param p h i :lstart :hlstart)
11638 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11639 (org-get-param p h i :lend :hlend))
11640 rtn))))
11642 (unless splicep
11643 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11645 (mapconcat 'identity (nreverse rtn) "\n")))
11647 (defun orgtbl-to-latex (table params)
11648 "Convert the orgtbl-mode TABLE to LaTeX.
11649 TABLE is a list, each entry either the symbol `hline' for a horizontal
11650 separator line, or a list of fields for that line.
11651 PARAMS is a property list of parameters that can influence the conversion.
11652 Supports all parameters from `orgtbl-to-generic'. Most important for
11653 LaTeX are:
11655 :splice When set to t, return only table body lines, don't wrap
11656 them into a tabular environment. Default is nil.
11658 :fmt A format to be used to wrap the field, should contain %s for the
11659 original field value. For example, to wrap everything in dollars,
11660 use :fmt \"$%s$\". This may also be a property list with column
11661 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11663 :efmt Format for transforming numbers with exponentials. The format
11664 should have %s twice for inserting mantissa and exponent, for
11665 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11666 This may also be a property list with column numbers and formats.
11668 The general parameters :skip and :skipcols have already been applied when
11669 this function is called."
11670 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11671 org-table-last-alignment ""))
11672 (params2
11673 (list
11674 :tstart (concat "\\begin{tabular}{" alignment "}")
11675 :tend "\\end{tabular}"
11676 :lstart "" :lend " \\\\" :sep " & "
11677 :efmt "%s\\,(%s)" :hline "\\hline")))
11678 (orgtbl-to-generic table (org-combine-plists params2 params))))
11680 (defun orgtbl-to-html (table params)
11681 "Convert the orgtbl-mode TABLE to LaTeX.
11682 TABLE is a list, each entry either the symbol `hline' for a horizontal
11683 separator line, or a list of fields for that line.
11684 PARAMS is a property list of parameters that can influence the conversion.
11685 Currently this function recognizes the following parameters:
11687 :splice When set to t, return only table body lines, don't wrap
11688 them into a <table> environment. Default is nil.
11690 The general parameters :skip and :skipcols have already been applied when
11691 this function is called. The function does *not* use `orgtbl-to-generic',
11692 so you cannot specify parameters for it."
11693 (let* ((splicep (plist-get params :splice))
11694 html)
11695 ;; Just call the formatter we already have
11696 ;; We need to make text lines for it, so put the fields back together.
11697 (setq html (org-format-org-table-html
11698 (mapcar
11699 (lambda (x)
11700 (if (eq x 'hline)
11701 "|----+----|"
11702 (concat "| " (mapconcat 'identity x " | ") " |")))
11703 table)
11704 splicep))
11705 (if (string-match "\n+\\'" html)
11706 (setq html (replace-match "" t t html)))
11707 html))
11709 (defun orgtbl-to-texinfo (table params)
11710 "Convert the orgtbl-mode TABLE to TeXInfo.
11711 TABLE is a list, each entry either the symbol `hline' for a horizontal
11712 separator line, or a list of fields for that line.
11713 PARAMS is a property list of parameters that can influence the conversion.
11714 Supports all parameters from `orgtbl-to-generic'. Most important for
11715 TeXInfo are:
11717 :splice nil/t When set to t, return only table body lines, don't wrap
11718 them into a multitable environment. Default is nil.
11720 :fmt fmt A format to be used to wrap the field, should contain
11721 %s for the original field value. For example, to wrap
11722 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11723 This may also be a property list with column numbers and
11724 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11726 :cf \"f1 f2..\" The column fractions for the table. By default these
11727 are computed automatically from the width of the columns
11728 under org-mode.
11730 The general parameters :skip and :skipcols have already been applied when
11731 this function is called."
11732 (let* ((total (float (apply '+ org-table-last-column-widths)))
11733 (colfrac (or (plist-get params :cf)
11734 (mapconcat
11735 (lambda (x) (format "%.3f" (/ (float x) total)))
11736 org-table-last-column-widths " ")))
11737 (params2
11738 (list
11739 :tstart (concat "@multitable @columnfractions " colfrac)
11740 :tend "@end multitable"
11741 :lstart "@item " :lend "" :sep " @tab "
11742 :hlstart "@headitem ")))
11743 (orgtbl-to-generic table (org-combine-plists params2 params))))
11745 ;;;; Link Stuff
11747 ;;; Link abbreviations
11749 (defun org-link-expand-abbrev (link)
11750 "Apply replacements as defined in `org-link-abbrev-alist."
11751 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11752 (let* ((key (match-string 1 link))
11753 (as (or (assoc key org-link-abbrev-alist-local)
11754 (assoc key org-link-abbrev-alist)))
11755 (tag (and (match-end 2) (match-string 3 link)))
11756 rpl)
11757 (if (not as)
11758 link
11759 (setq rpl (cdr as))
11760 (cond
11761 ((symbolp rpl) (funcall rpl tag))
11762 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11763 (t (concat rpl tag)))))
11764 link))
11766 ;;; Storing and inserting links
11768 (defvar org-insert-link-history nil
11769 "Minibuffer history for links inserted with `org-insert-link'.")
11771 (defvar org-stored-links nil
11772 "Contains the links stored with `org-store-link'.")
11774 (defvar org-store-link-plist nil
11775 "Plist with info about the most recently link created with `org-store-link'.")
11777 (defvar org-link-protocols nil
11778 "Link protocols added to Org-mode using `org-add-link-type'.")
11780 (defvar org-store-link-functions nil
11781 "List of functions that are called to create and store a link.
11782 Each function will be called in turn until one returns a non-nil
11783 value. Each function should check if it is responsible for creating
11784 this link (for example by looking at the major mode).
11785 If not, it must exit and return nil.
11786 If yes, it should return a non-nil value after a calling
11787 `org-store-link-props' with a list of properties and values.
11788 Special properties are:
11790 :type The link prefix. like \"http\". This must be given.
11791 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11792 This is obligatory as well.
11793 :description Optional default description for the second pair
11794 of brackets in an Org-mode link. The user can still change
11795 this when inserting this link into an Org-mode buffer.
11797 In addition to these, any additional properties can be specified
11798 and then used in remember templates.")
11800 (defun org-add-link-type (type &optional follow publish)
11801 "Add TYPE to the list of `org-link-types'.
11802 Re-compute all regular expressions depending on `org-link-types'
11803 FOLLOW and PUBLISH are two functions. Both take the link path as
11804 an argument.
11805 FOLLOW should do whatever is necessary to follow the link, for example
11806 to find a file or display a mail message.
11808 PUBLISH takes the path and retuns the string that should be used when
11809 this document is published. FIMXE: This is actually not yet implemented."
11810 (add-to-list 'org-link-types type t)
11811 (org-make-link-regexps)
11812 (add-to-list 'org-link-protocols
11813 (list type follow publish)))
11815 (defun org-add-agenda-custom-command (entry)
11816 "Replace or add a command in `org-agenda-custom-commands'.
11817 This is mostly for hacking and trying a new command - once the command
11818 works you probably want to add it to `org-agenda-custom-commands' for good."
11819 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11820 (if ass
11821 (setcdr ass (cdr entry))
11822 (push entry org-agenda-custom-commands))))
11824 ;;;###autoload
11825 (defun org-store-link (arg)
11826 "\\<org-mode-map>Store an org-link to the current location.
11827 This link can later be inserted into an org-buffer with
11828 \\[org-insert-link].
11829 For some link types, a prefix arg is interpreted:
11830 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11831 For file links, arg negates `org-context-in-file-links'."
11832 (interactive "P")
11833 (setq org-store-link-plist nil) ; reset
11834 (let (link cpltxt desc description search txt)
11835 (cond
11837 ((run-hook-with-args-until-success 'org-store-link-functions)
11838 (setq link (plist-get org-store-link-plist :link)
11839 desc (or (plist-get org-store-link-plist :description) link)))
11841 ((eq major-mode 'bbdb-mode)
11842 (let ((name (bbdb-record-name (bbdb-current-record)))
11843 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11844 (setq cpltxt (concat "bbdb:" (or name company))
11845 link (org-make-link cpltxt))
11846 (org-store-link-props :type "bbdb" :name name :company company)))
11848 ((eq major-mode 'Info-mode)
11849 (setq link (org-make-link "info:"
11850 (file-name-nondirectory Info-current-file)
11851 ":" Info-current-node))
11852 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11853 ":" Info-current-node))
11854 (org-store-link-props :type "info" :file Info-current-file
11855 :node Info-current-node))
11857 ((eq major-mode 'calendar-mode)
11858 (let ((cd (calendar-cursor-to-date)))
11859 (setq link
11860 (format-time-string
11861 (car org-time-stamp-formats)
11862 (apply 'encode-time
11863 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11864 nil nil nil))))
11865 (org-store-link-props :type "calendar" :date cd)))
11867 ((or (eq major-mode 'vm-summary-mode)
11868 (eq major-mode 'vm-presentation-mode))
11869 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11870 (vm-follow-summary-cursor)
11871 (save-excursion
11872 (vm-select-folder-buffer)
11873 (let* ((message (car vm-message-pointer))
11874 (folder buffer-file-name)
11875 (subject (vm-su-subject message))
11876 (to (vm-get-header-contents message "To"))
11877 (from (vm-get-header-contents message "From"))
11878 (message-id (vm-su-message-id message)))
11879 (org-store-link-props :type "vm" :from from :to to :subject subject
11880 :message-id message-id)
11881 (setq message-id (org-remove-angle-brackets message-id))
11882 (setq folder (abbreviate-file-name folder))
11883 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11884 folder)
11885 (setq folder (replace-match "" t t folder)))
11886 (setq cpltxt (org-email-link-description))
11887 (setq link (org-make-link "vm:" folder "#" message-id)))))
11889 ((eq major-mode 'wl-summary-mode)
11890 (let* ((msgnum (wl-summary-message-number))
11891 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11892 msgnum 'message-id))
11893 (wl-message-entity
11894 (if (fboundp 'elmo-message-entity)
11895 (elmo-message-entity
11896 wl-summary-buffer-elmo-folder msgnum)
11897 (elmo-msgdb-overview-get-entity
11898 msgnum (wl-summary-buffer-msgdb))))
11899 (from (wl-summary-line-from))
11900 (to (car (elmo-message-entity-field wl-message-entity 'to)))
11901 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11902 (wl-summary-line-subject))))
11903 (org-store-link-props :type "wl" :from from :to to
11904 :subject subject :message-id message-id)
11905 (setq message-id (org-remove-angle-brackets message-id))
11906 (setq cpltxt (org-email-link-description))
11907 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11908 "#" message-id))))
11910 ((or (equal major-mode 'mh-folder-mode)
11911 (equal major-mode 'mh-show-mode))
11912 (let ((from (org-mhe-get-header "From:"))
11913 (to (org-mhe-get-header "To:"))
11914 (message-id (org-mhe-get-header "Message-Id:"))
11915 (subject (org-mhe-get-header "Subject:")))
11916 (org-store-link-props :type "mh" :from from :to to
11917 :subject subject :message-id message-id)
11918 (setq cpltxt (org-email-link-description))
11919 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11920 (org-remove-angle-brackets message-id)))))
11922 ((eq major-mode 'rmail-mode)
11923 (save-excursion
11924 (save-restriction
11925 (rmail-narrow-to-non-pruned-header)
11926 (let ((folder buffer-file-name)
11927 (message-id (mail-fetch-field "message-id"))
11928 (from (mail-fetch-field "from"))
11929 (to (mail-fetch-field "to"))
11930 (subject (mail-fetch-field "subject")))
11931 (org-store-link-props
11932 :type "rmail" :from from :to to
11933 :subject subject :message-id message-id)
11934 (setq message-id (org-remove-angle-brackets message-id))
11935 (setq cpltxt (org-email-link-description))
11936 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11938 ((eq major-mode 'gnus-group-mode)
11939 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11940 (gnus-group-group-name)) ; version
11941 ((fboundp 'gnus-group-name)
11942 (gnus-group-name))
11943 (t "???"))))
11944 (unless group (error "Not on a group"))
11945 (org-store-link-props :type "gnus" :group group)
11946 (setq cpltxt (concat
11947 (if (org-xor arg org-usenet-links-prefer-google)
11948 "http://groups.google.com/groups?group="
11949 "gnus:")
11950 group)
11951 link (org-make-link cpltxt))))
11953 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11954 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11955 (let* ((group gnus-newsgroup-name)
11956 (article (gnus-summary-article-number))
11957 (header (gnus-summary-article-header article))
11958 (from (mail-header-from header))
11959 (message-id (mail-header-id header))
11960 (date (mail-header-date header))
11961 (subject (gnus-summary-subject-string)))
11962 (org-store-link-props :type "gnus" :from from :subject subject
11963 :message-id message-id :group group)
11964 (setq cpltxt (org-email-link-description))
11965 (if (org-xor arg org-usenet-links-prefer-google)
11966 (setq link
11967 (concat
11968 cpltxt "\n "
11969 (format "http://groups.google.com/groups?as_umsgid=%s"
11970 (org-fixup-message-id-for-http message-id))))
11971 (setq link (org-make-link "gnus:" group
11972 "#" (number-to-string article))))))
11974 ((eq major-mode 'w3-mode)
11975 (setq cpltxt (url-view-url t)
11976 link (org-make-link cpltxt))
11977 (org-store-link-props :type "w3" :url (url-view-url t)))
11979 ((eq major-mode 'w3m-mode)
11980 (setq cpltxt (or w3m-current-title w3m-current-url)
11981 link (org-make-link w3m-current-url))
11982 (org-store-link-props :type "w3m" :url (url-view-url t)))
11984 ((setq search (run-hook-with-args-until-success
11985 'org-create-file-search-functions))
11986 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11987 "::" search))
11988 (setq cpltxt (or description link)))
11990 ((eq major-mode 'image-mode)
11991 (setq cpltxt (concat "file:"
11992 (abbreviate-file-name buffer-file-name))
11993 link (org-make-link cpltxt))
11994 (org-store-link-props :type "image" :file buffer-file-name))
11996 ((eq major-mode 'dired-mode)
11997 ;; link to the file in the current line
11998 (setq cpltxt (concat "file:"
11999 (abbreviate-file-name
12000 (expand-file-name
12001 (dired-get-filename nil t))))
12002 link (org-make-link cpltxt)))
12004 ((and buffer-file-name (org-mode-p))
12005 ;; Just link to current headline
12006 (setq cpltxt (concat "file:"
12007 (abbreviate-file-name buffer-file-name)))
12008 ;; Add a context search string
12009 (when (org-xor org-context-in-file-links arg)
12010 ;; Check if we are on a target
12011 (if (org-in-regexp "<<\\(.*?\\)>>")
12012 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12013 (setq txt (cond
12014 ((org-on-heading-p) nil)
12015 ((org-region-active-p)
12016 (buffer-substring (region-beginning) (region-end)))
12017 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12018 (when (or (null txt) (string-match "\\S-" txt))
12019 (setq cpltxt
12020 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12021 desc "NONE"))))
12022 (if (string-match "::\\'" cpltxt)
12023 (setq cpltxt (substring cpltxt 0 -2)))
12024 (setq link (org-make-link cpltxt)))
12026 ((buffer-file-name (buffer-base-buffer))
12027 ;; Just link to this file here.
12028 (setq cpltxt (concat "file:"
12029 (abbreviate-file-name
12030 (buffer-file-name (buffer-base-buffer)))))
12031 ;; Add a context string
12032 (when (org-xor org-context-in-file-links arg)
12033 (setq txt (if (org-region-active-p)
12034 (buffer-substring (region-beginning) (region-end))
12035 (buffer-substring (point-at-bol) (point-at-eol))))
12036 ;; Only use search option if there is some text.
12037 (when (string-match "\\S-" txt)
12038 (setq cpltxt
12039 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12040 desc "NONE")))
12041 (setq link (org-make-link cpltxt)))
12043 ((interactive-p)
12044 (error "Cannot link to a buffer which is not visiting a file"))
12046 (t (setq link nil)))
12048 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12049 (setq link (or link cpltxt)
12050 desc (or desc cpltxt))
12051 (if (equal desc "NONE") (setq desc nil))
12053 (if (and (interactive-p) link)
12054 (progn
12055 (setq org-stored-links
12056 (cons (list link desc) org-stored-links))
12057 (message "Stored: %s" (or desc link)))
12058 (and link (org-make-link-string link desc)))))
12060 (defun org-store-link-props (&rest plist)
12061 "Store link properties, extract names and addresses."
12062 (let (x adr)
12063 (when (setq x (plist-get plist :from))
12064 (setq adr (mail-extract-address-components x))
12065 (plist-put plist :fromname (car adr))
12066 (plist-put plist :fromaddress (nth 1 adr)))
12067 (when (setq x (plist-get plist :to))
12068 (setq adr (mail-extract-address-components x))
12069 (plist-put plist :toname (car adr))
12070 (plist-put plist :toaddress (nth 1 adr))))
12071 (let ((from (plist-get plist :from))
12072 (to (plist-get plist :to)))
12073 (when (and from to org-from-is-user-regexp)
12074 (plist-put plist :fromto
12075 (if (string-match org-from-is-user-regexp from)
12076 (concat "to %t")
12077 (concat "from %f")))))
12078 (setq org-store-link-plist plist))
12080 (defun org-email-link-description (&optional fmt)
12081 "Return the description part of an email link.
12082 This takes information from `org-store-link-plist' and formats it
12083 according to FMT (default from `org-email-link-description-format')."
12084 (setq fmt (or fmt org-email-link-description-format))
12085 (let* ((p org-store-link-plist)
12086 (to (plist-get p :toaddress))
12087 (from (plist-get p :fromaddress))
12088 (table
12089 (list
12090 (cons "%c" (plist-get p :fromto))
12091 (cons "%F" (plist-get p :from))
12092 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12093 (cons "%T" (plist-get p :to))
12094 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12095 (cons "%s" (plist-get p :subject))
12096 (cons "%m" (plist-get p :message-id)))))
12097 (when (string-match "%c" fmt)
12098 ;; Check if the user wrote this message
12099 (if (and org-from-is-user-regexp from to
12100 (save-match-data (string-match org-from-is-user-regexp from)))
12101 (setq fmt (replace-match "to %t" t t fmt))
12102 (setq fmt (replace-match "from %f" t t fmt))))
12103 (org-replace-escapes fmt table)))
12105 (defun org-make-org-heading-search-string (&optional string heading)
12106 "Make search string for STRING or current headline."
12107 (interactive)
12108 (let ((s (or string (org-get-heading))))
12109 (unless (and string (not heading))
12110 ;; We are using a headline, clean up garbage in there.
12111 (if (string-match org-todo-regexp s)
12112 (setq s (replace-match "" t t s)))
12113 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12114 (setq s (replace-match "" t t s)))
12115 (setq s (org-trim s))
12116 (if (string-match (concat "^\\(" org-quote-string "\\|"
12117 org-comment-string "\\)") s)
12118 (setq s (replace-match "" t t s)))
12119 (while (string-match org-ts-regexp s)
12120 (setq s (replace-match "" t t s))))
12121 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12122 (setq s (replace-match " " t t s)))
12123 (or string (setq s (concat "*" s))) ; Add * for headlines
12124 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12126 (defun org-make-link (&rest strings)
12127 "Concatenate STRINGS."
12128 (apply 'concat strings))
12130 (defun org-make-link-string (link &optional description)
12131 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12132 (unless (string-match "\\S-" link)
12133 (error "Empty link"))
12134 (when (stringp description)
12135 ;; Remove brackets from the description, they are fatal.
12136 (while (string-match "\\[" description)
12137 (setq description (replace-match "{" t t description)))
12138 (while (string-match "\\]" description)
12139 (setq description (replace-match "}" t t description))))
12140 (when (equal (org-link-escape link) description)
12141 ;; No description needed, it is identical
12142 (setq description nil))
12143 (when (and (not description)
12144 (not (equal link (org-link-escape link))))
12145 (setq description link))
12146 (concat "[[" (org-link-escape link) "]"
12147 (if description (concat "[" description "]") "")
12148 "]"))
12150 (defconst org-link-escape-chars
12151 '((?\ . "%20")
12152 (?\[ . "%5B")
12153 (?\] . "%5D")
12154 (?\340 . "%E0") ; `a
12155 (?\342 . "%E2") ; ^a
12156 (?\347 . "%E7") ; ,c
12157 (?\350 . "%E8") ; `e
12158 (?\351 . "%E9") ; 'e
12159 (?\352 . "%EA") ; ^e
12160 (?\356 . "%EE") ; ^i
12161 (?\364 . "%F4") ; ^o
12162 (?\371 . "%F9") ; `u
12163 (?\373 . "%FB") ; ^u
12164 (?\; . "%3B")
12165 (?? . "%3F")
12166 (?= . "%3D")
12167 (?+ . "%2B")
12169 "Association list of escapes for some characters problematic in links.
12170 This is the list that is used for internal purposes.")
12172 (defconst org-link-escape-chars-browser
12173 '((?\ . "%20")) ; 32 for the SPC char
12174 "Association list of escapes for some characters problematic in links.
12175 This is the list that is used before handing over to the browser.")
12177 (defun org-link-escape (text &optional table)
12178 "Escape charaters in TEXT that are problematic for links."
12179 (setq table (or table org-link-escape-chars))
12180 (when text
12181 (let ((re (mapconcat (lambda (x) (regexp-quote
12182 (char-to-string (car x))))
12183 table "\\|")))
12184 (while (string-match re text)
12185 (setq text
12186 (replace-match
12187 (cdr (assoc (string-to-char (match-string 0 text))
12188 table))
12189 t t text)))
12190 text)))
12192 (defun org-link-unescape (text &optional table)
12193 "Reverse the action of `org-link-escape'."
12194 (setq table (or table org-link-escape-chars))
12195 (when text
12196 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12197 table "\\|")))
12198 (while (string-match re text)
12199 (setq text
12200 (replace-match
12201 (char-to-string (car (rassoc (match-string 0 text) table)))
12202 t t text)))
12203 text)))
12205 (defun org-xor (a b)
12206 "Exclusive or."
12207 (if a (not b) b))
12209 (defun org-get-header (header)
12210 "Find a header field in the current buffer."
12211 (save-excursion
12212 (goto-char (point-min))
12213 (let ((case-fold-search t) s)
12214 (cond
12215 ((eq header 'from)
12216 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12217 (setq s (match-string 1)))
12218 (while (string-match "\"" s)
12219 (setq s (replace-match "" t t s)))
12220 (if (string-match "[<(].*" s)
12221 (setq s (replace-match "" t t s))))
12222 ((eq header 'message-id)
12223 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12224 (setq s (match-string 1))))
12225 ((eq header 'subject)
12226 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12227 (setq s (match-string 1)))))
12228 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12229 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12230 s)))
12233 (defun org-fixup-message-id-for-http (s)
12234 "Replace special characters in a message id, so it can be used in an http query."
12235 (while (string-match "<" s)
12236 (setq s (replace-match "%3C" t t s)))
12237 (while (string-match ">" s)
12238 (setq s (replace-match "%3E" t t s)))
12239 (while (string-match "@" s)
12240 (setq s (replace-match "%40" t t s)))
12243 ;;;###autoload
12244 (defun org-insert-link-global ()
12245 "Insert a link like Org-mode does.
12246 This command can be called in any mode to insert a link in Org-mode syntax."
12247 (interactive)
12248 (org-run-like-in-org-mode 'org-insert-link))
12250 (defun org-insert-link (&optional complete-file)
12251 "Insert a link. At the prompt, enter the link.
12253 Completion can be used to select a link previously stored with
12254 `org-store-link'. When the empty string is entered (i.e. if you just
12255 press RET at the prompt), the link defaults to the most recently
12256 stored link. As SPC triggers completion in the minibuffer, you need to
12257 use M-SPC or C-q SPC to force the insertion of a space character.
12259 You will also be prompted for a description, and if one is given, it will
12260 be displayed in the buffer instead of the link.
12262 If there is already a link at point, this command will allow you to edit link
12263 and description parts.
12265 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12266 selected using completion. The path to the file will be relative to
12267 the current directory if the file is in the current directory or a
12268 subdirectory. Otherwise, the link will be the absolute path as
12269 completed in the minibuffer (i.e. normally ~/path/to/file).
12271 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12272 is in the current directory or below.
12273 With three \\[universal-argument] prefixes, negate the meaning of
12274 `org-keep-stored-link-after-insertion'."
12275 (interactive "P")
12276 (let* ((wcf (current-window-configuration))
12277 (region (if (org-region-active-p)
12278 (buffer-substring (region-beginning) (region-end))))
12279 (remove (and region (list (region-beginning) (region-end))))
12280 (desc region)
12281 tmphist ; byte-compile incorrectly complains about this
12282 link entry file)
12283 (cond
12284 ((org-in-regexp org-bracket-link-regexp 1)
12285 ;; We do have a link at point, and we are going to edit it.
12286 (setq remove (list (match-beginning 0) (match-end 0)))
12287 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12288 (setq link (read-string "Link: "
12289 (org-link-unescape
12290 (org-match-string-no-properties 1)))))
12291 ((or (org-in-regexp org-angle-link-re)
12292 (org-in-regexp org-plain-link-re))
12293 ;; Convert to bracket link
12294 (setq remove (list (match-beginning 0) (match-end 0))
12295 link (read-string "Link: "
12296 (org-remove-angle-brackets (match-string 0)))))
12297 ((equal complete-file '(4))
12298 ;; Completing read for file names.
12299 (setq file (read-file-name "File: "))
12300 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12301 (pwd1 (file-name-as-directory (abbreviate-file-name
12302 (expand-file-name ".")))))
12303 (cond
12304 ((equal complete-file '(16))
12305 (setq link (org-make-link
12306 "file:"
12307 (abbreviate-file-name (expand-file-name file)))))
12308 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12309 (setq link (org-make-link "file:" (match-string 1 file))))
12310 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12311 (expand-file-name file))
12312 (setq link (org-make-link
12313 "file:" (match-string 1 (expand-file-name file)))))
12314 (t (setq link (org-make-link "file:" file))))))
12316 ;; Read link, with completion for stored links.
12317 (with-output-to-temp-buffer "*Org Links*"
12318 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12319 (when org-stored-links
12320 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12321 (princ (mapconcat
12322 (lambda (x)
12323 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12324 (reverse org-stored-links) "\n"))))
12325 (let ((cw (selected-window)))
12326 (select-window (get-buffer-window "*Org Links*"))
12327 (shrink-window-if-larger-than-buffer)
12328 (setq truncate-lines t)
12329 (select-window cw))
12330 ;; Fake a link history, containing the stored links.
12331 (setq tmphist (append (mapcar 'car org-stored-links)
12332 org-insert-link-history))
12333 (unwind-protect
12334 (setq link (org-completing-read
12335 "Link: "
12336 (append
12337 (mapcar (lambda (x) (list (concat (car x) ":")))
12338 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12339 (mapcar (lambda (x) (list (concat x ":")))
12340 org-link-types))
12341 nil nil nil
12342 'tmphist
12343 (or (car (car org-stored-links)))))
12344 (set-window-configuration wcf)
12345 (kill-buffer "*Org Links*"))
12346 (setq entry (assoc link org-stored-links))
12347 (or entry (push link org-insert-link-history))
12348 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12349 (not org-keep-stored-link-after-insertion))
12350 (setq org-stored-links (delq (assoc link org-stored-links)
12351 org-stored-links)))
12352 (setq desc (or desc (nth 1 entry)))))
12354 (if (string-match org-plain-link-re link)
12355 ;; URL-like link, normalize the use of angular brackets.
12356 (setq link (org-make-link (org-remove-angle-brackets link))))
12358 ;; Check if we are linking to the current file with a search option
12359 ;; If yes, simplify the link by using only the search option.
12360 (when (and buffer-file-name
12361 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12362 (let* ((path (match-string 1 link))
12363 (case-fold-search nil)
12364 (search (match-string 2 link)))
12365 (save-match-data
12366 (if (equal (file-truename buffer-file-name) (file-truename path))
12367 ;; We are linking to this same file, with a search option
12368 (setq link search)))))
12370 ;; Check if we can/should use a relative path. If yes, simplify the link
12371 (when (string-match "\\<file:\\(.*\\)" link)
12372 (let* ((path (match-string 1 link))
12373 (origpath path)
12374 (desc-is-link (equal link desc))
12375 (case-fold-search nil))
12376 (cond
12377 ((eq org-link-file-path-type 'absolute)
12378 (setq path (abbreviate-file-name (expand-file-name path))))
12379 ((eq org-link-file-path-type 'noabbrev)
12380 (setq path (expand-file-name path)))
12381 ((eq org-link-file-path-type 'relative)
12382 (setq path (file-relative-name path)))
12384 (save-match-data
12385 (if (string-match (concat "^" (regexp-quote
12386 (file-name-as-directory
12387 (expand-file-name "."))))
12388 (expand-file-name path))
12389 ;; We are linking a file with relative path name.
12390 (setq path (substring (expand-file-name path)
12391 (match-end 0)))))))
12392 (setq link (concat "file:" path))
12393 (if (equal desc origpath)
12394 (setq desc path))))
12396 (setq desc (read-string "Description: " desc))
12397 (unless (string-match "\\S-" desc) (setq desc nil))
12398 (if remove (apply 'delete-region remove))
12399 (insert (org-make-link-string link desc))))
12401 (defun org-completing-read (&rest args)
12402 (let ((minibuffer-local-completion-map
12403 (copy-keymap minibuffer-local-completion-map)))
12404 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12405 (apply 'completing-read args)))
12407 ;;; Opening/following a link
12408 (defvar org-link-search-failed nil)
12410 (defun org-next-link ()
12411 "Move forward to the next link.
12412 If the link is in hidden text, expose it."
12413 (interactive)
12414 (when (and org-link-search-failed (eq this-command last-command))
12415 (goto-char (point-min))
12416 (message "Link search wrapped back to beginning of buffer"))
12417 (setq org-link-search-failed nil)
12418 (let* ((pos (point))
12419 (ct (org-context))
12420 (a (assoc :link ct)))
12421 (if a (goto-char (nth 2 a)))
12422 (if (re-search-forward org-any-link-re nil t)
12423 (progn
12424 (goto-char (match-beginning 0))
12425 (if (org-invisible-p) (org-show-context)))
12426 (goto-char pos)
12427 (setq org-link-search-failed t)
12428 (error "No further link found"))))
12430 (defun org-previous-link ()
12431 "Move backward to the previous link.
12432 If the link is in hidden text, expose it."
12433 (interactive)
12434 (when (and org-link-search-failed (eq this-command last-command))
12435 (goto-char (point-max))
12436 (message "Link search wrapped back to end of buffer"))
12437 (setq org-link-search-failed nil)
12438 (let* ((pos (point))
12439 (ct (org-context))
12440 (a (assoc :link ct)))
12441 (if a (goto-char (nth 1 a)))
12442 (if (re-search-backward org-any-link-re nil t)
12443 (progn
12444 (goto-char (match-beginning 0))
12445 (if (org-invisible-p) (org-show-context)))
12446 (goto-char pos)
12447 (setq org-link-search-failed t)
12448 (error "No further link found"))))
12450 (defun org-find-file-at-mouse (ev)
12451 "Open file link or URL at mouse."
12452 (interactive "e")
12453 (mouse-set-point ev)
12454 (org-open-at-point 'in-emacs))
12456 (defun org-open-at-mouse (ev)
12457 "Open file link or URL at mouse."
12458 (interactive "e")
12459 (mouse-set-point ev)
12460 (org-open-at-point))
12462 (defvar org-window-config-before-follow-link nil
12463 "The window configuration before following a link.
12464 This is saved in case the need arises to restore it.")
12466 (defvar org-open-link-marker (make-marker)
12467 "Marker pointing to the location where `org-open-at-point; was called.")
12469 ;;;###autoload
12470 (defun org-open-at-point-global ()
12471 "Follow a link like Org-mode does.
12472 This command can be called in any mode to follow a link that has
12473 Org-mode syntax."
12474 (interactive)
12475 (org-run-like-in-org-mode 'org-open-at-point))
12477 (defun org-open-at-point (&optional in-emacs)
12478 "Open link at or after point.
12479 If there is no link at point, this function will search forward up to
12480 the end of the current subtree.
12481 Normally, files will be opened by an appropriate application. If the
12482 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12483 (interactive "P")
12484 (catch 'abort
12485 (move-marker org-open-link-marker (point))
12486 (setq org-window-config-before-follow-link (current-window-configuration))
12487 (org-remove-occur-highlights nil nil t)
12488 (if (org-at-timestamp-p t)
12489 (org-follow-timestamp-link)
12490 (let (type path link line search (pos (point)))
12491 (catch 'match
12492 (save-excursion
12493 (skip-chars-forward "^]\n\r")
12494 (when (org-in-regexp org-bracket-link-regexp)
12495 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12496 (while (string-match " *\n *" link)
12497 (setq link (replace-match " " t t link)))
12498 (setq link (org-link-expand-abbrev link))
12499 (if (string-match org-link-re-with-space2 link)
12500 (setq type (match-string 1 link) path (match-string 2 link))
12501 (setq type "thisfile" path link))
12502 (throw 'match t)))
12504 (when (get-text-property (point) 'org-linked-text)
12505 (setq type "thisfile"
12506 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12507 (1+ (point)) (point))
12508 path (buffer-substring
12509 (previous-single-property-change pos 'org-linked-text)
12510 (next-single-property-change pos 'org-linked-text)))
12511 (throw 'match t))
12513 (save-excursion
12514 (when (or (org-in-regexp org-angle-link-re)
12515 (org-in-regexp org-plain-link-re))
12516 (setq type (match-string 1) path (match-string 2))
12517 (throw 'match t)))
12518 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12519 (setq type "tree-match"
12520 path (match-string 1))
12521 (throw 'match t))
12522 (save-excursion
12523 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12524 (setq type "tags"
12525 path (match-string 1))
12526 (while (string-match ":" path)
12527 (setq path (replace-match "+" t t path)))
12528 (throw 'match t))))
12529 (unless path
12530 (error "No link found"))
12531 ;; Remove any trailing spaces in path
12532 (if (string-match " +\\'" path)
12533 (setq path (replace-match "" t t path)))
12535 (cond
12537 ((assoc type org-link-protocols)
12538 (funcall (nth 1 (assoc type org-link-protocols)) path))
12540 ((equal type "mailto")
12541 (let ((cmd (car org-link-mailto-program))
12542 (args (cdr org-link-mailto-program)) args1
12543 (address path) (subject "") a)
12544 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12545 (setq address (match-string 1 path)
12546 subject (org-link-escape (match-string 2 path))))
12547 (while args
12548 (cond
12549 ((not (stringp (car args))) (push (pop args) args1))
12550 (t (setq a (pop args))
12551 (if (string-match "%a" a)
12552 (setq a (replace-match address t t a)))
12553 (if (string-match "%s" a)
12554 (setq a (replace-match subject t t a)))
12555 (push a args1))))
12556 (apply cmd (nreverse args1))))
12558 ((member type '("http" "https" "ftp" "news"))
12559 (browse-url (concat type ":" (org-link-escape
12560 path org-link-escape-chars-browser))))
12562 ((member type '("message"))
12563 (browse-url (concat type ":" path)))
12565 ((string= type "tags")
12566 (org-tags-view in-emacs path))
12567 ((string= type "thisfile")
12568 (if in-emacs
12569 (switch-to-buffer-other-window
12570 (org-get-buffer-for-internal-link (current-buffer)))
12571 (org-mark-ring-push))
12572 (let ((cmd `(org-link-search
12573 ,path
12574 ,(cond ((equal in-emacs '(4)) 'occur)
12575 ((equal in-emacs '(16)) 'org-occur)
12576 (t nil))
12577 ,pos)))
12578 (condition-case nil (eval cmd)
12579 (error (progn (widen) (eval cmd))))))
12581 ((string= type "tree-match")
12582 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12584 ((string= type "file")
12585 (if (string-match "::\\([0-9]+\\)\\'" path)
12586 (setq line (string-to-number (match-string 1 path))
12587 path (substring path 0 (match-beginning 0)))
12588 (if (string-match "::\\(.+\\)\\'" path)
12589 (setq search (match-string 1 path)
12590 path (substring path 0 (match-beginning 0)))))
12591 (if (string-match "[*?{]" (file-name-nondirectory path))
12592 (dired path)
12593 (org-open-file path in-emacs line search)))
12595 ((string= type "news")
12596 (org-follow-gnus-link path))
12598 ((string= type "bbdb")
12599 (org-follow-bbdb-link path))
12601 ((string= type "info")
12602 (org-follow-info-link path))
12604 ((string= type "gnus")
12605 (let (group article)
12606 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12607 (error "Error in Gnus link"))
12608 (setq group (match-string 1 path)
12609 article (match-string 3 path))
12610 (org-follow-gnus-link group article)))
12612 ((string= type "vm")
12613 (let (folder article)
12614 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12615 (error "Error in VM link"))
12616 (setq folder (match-string 1 path)
12617 article (match-string 3 path))
12618 ;; in-emacs is the prefix arg, will be interpreted as read-only
12619 (org-follow-vm-link folder article in-emacs)))
12621 ((string= type "wl")
12622 (let (folder article)
12623 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12624 (error "Error in Wanderlust link"))
12625 (setq folder (match-string 1 path)
12626 article (match-string 3 path))
12627 (org-follow-wl-link folder article)))
12629 ((string= type "mhe")
12630 (let (folder article)
12631 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12632 (error "Error in MHE link"))
12633 (setq folder (match-string 1 path)
12634 article (match-string 3 path))
12635 (org-follow-mhe-link folder article)))
12637 ((string= type "rmail")
12638 (let (folder article)
12639 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12640 (error "Error in RMAIL link"))
12641 (setq folder (match-string 1 path)
12642 article (match-string 3 path))
12643 (org-follow-rmail-link folder article)))
12645 ((string= type "shell")
12646 (let ((cmd path))
12647 (if (or (not org-confirm-shell-link-function)
12648 (funcall org-confirm-shell-link-function
12649 (format "Execute \"%s\" in shell? "
12650 (org-add-props cmd nil
12651 'face 'org-warning))))
12652 (progn
12653 (message "Executing %s" cmd)
12654 (shell-command cmd))
12655 (error "Abort"))))
12657 ((string= type "elisp")
12658 (let ((cmd path))
12659 (if (or (not org-confirm-elisp-link-function)
12660 (funcall org-confirm-elisp-link-function
12661 (format "Execute \"%s\" as elisp? "
12662 (org-add-props cmd nil
12663 'face 'org-warning))))
12664 (message "%s => %s" cmd (eval (read cmd)))
12665 (error "Abort"))))
12668 (browse-url-at-point)))))
12669 (move-marker org-open-link-marker nil)))
12671 ;;; File search
12673 (defvar org-create-file-search-functions nil
12674 "List of functions to construct the right search string for a file link.
12675 These functions are called in turn with point at the location to
12676 which the link should point.
12678 A function in the hook should first test if it would like to
12679 handle this file type, for example by checking the major-mode or
12680 the file extension. If it decides not to handle this file, it
12681 should just return nil to give other functions a chance. If it
12682 does handle the file, it must return the search string to be used
12683 when following the link. The search string will be part of the
12684 file link, given after a double colon, and `org-open-at-point'
12685 will automatically search for it. If special measures must be
12686 taken to make the search successful, another function should be
12687 added to the companion hook `org-execute-file-search-functions',
12688 which see.
12690 A function in this hook may also use `setq' to set the variable
12691 `description' to provide a suggestion for the descriptive text to
12692 be used for this link when it gets inserted into an Org-mode
12693 buffer with \\[org-insert-link].")
12695 (defvar org-execute-file-search-functions nil
12696 "List of functions to execute a file search triggered by a link.
12698 Functions added to this hook must accept a single argument, the
12699 search string that was part of the file link, the part after the
12700 double colon. The function must first check if it would like to
12701 handle this search, for example by checking the major-mode or the
12702 file extension. If it decides not to handle this search, it
12703 should just return nil to give other functions a chance. If it
12704 does handle the search, it must return a non-nil value to keep
12705 other functions from trying.
12707 Each function can access the current prefix argument through the
12708 variable `current-prefix-argument'. Note that a single prefix is
12709 used to force opening a link in Emacs, so it may be good to only
12710 use a numeric or double prefix to guide the search function.
12712 In case this is needed, a function in this hook can also restore
12713 the window configuration before `org-open-at-point' was called using:
12715 (set-window-configuration org-window-config-before-follow-link)")
12717 (defun org-link-search (s &optional type avoid-pos)
12718 "Search for a link search option.
12719 If S is surrounded by forward slashes, it is interpreted as a
12720 regular expression. In org-mode files, this will create an `org-occur'
12721 sparse tree. In ordinary files, `occur' will be used to list matches.
12722 If the current buffer is in `dired-mode', grep will be used to search
12723 in all files. If AVOID-POS is given, ignore matches near that position."
12724 (let ((case-fold-search t)
12725 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12726 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12727 (append '(("") (" ") ("\t") ("\n"))
12728 org-emphasis-alist)
12729 "\\|") "\\)"))
12730 (pos (point))
12731 (pre "") (post "")
12732 words re0 re1 re2 re3 re4 re5 re2a reall)
12733 (cond
12734 ;; First check if there are any special
12735 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12736 ;; Now try the builtin stuff
12737 ((save-excursion
12738 (goto-char (point-min))
12739 (and
12740 (re-search-forward
12741 (concat "<<" (regexp-quote s0) ">>") nil t)
12742 (setq pos (match-beginning 0))))
12743 ;; There is an exact target for this
12744 (goto-char pos))
12745 ((string-match "^/\\(.*\\)/$" s)
12746 ;; A regular expression
12747 (cond
12748 ((org-mode-p)
12749 (org-occur (match-string 1 s)))
12750 ;;((eq major-mode 'dired-mode)
12751 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12752 (t (org-do-occur (match-string 1 s)))))
12754 ;; A normal search strings
12755 (when (equal (string-to-char s) ?*)
12756 ;; Anchor on headlines, post may include tags.
12757 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12758 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12759 s (substring s 1)))
12760 (remove-text-properties
12761 0 (length s)
12762 '(face nil mouse-face nil keymap nil fontified nil) s)
12763 ;; Make a series of regular expressions to find a match
12764 (setq words (org-split-string s "[ \n\r\t]+")
12765 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12766 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12767 "\\)" markers)
12768 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12769 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12770 re1 (concat pre re2 post)
12771 re3 (concat pre re4 post)
12772 re5 (concat pre ".*" re4)
12773 re2 (concat pre re2)
12774 re2a (concat pre re2a)
12775 re4 (concat pre re4)
12776 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12777 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12778 re5 "\\)"
12780 (cond
12781 ((eq type 'org-occur) (org-occur reall))
12782 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12783 (t (goto-char (point-min))
12784 (if (or (org-search-not-self 1 re0 nil t)
12785 (org-search-not-self 1 re1 nil t)
12786 (org-search-not-self 1 re2 nil t)
12787 (org-search-not-self 1 re2a nil t)
12788 (org-search-not-self 1 re3 nil t)
12789 (org-search-not-self 1 re4 nil t)
12790 (org-search-not-self 1 re5 nil t)
12792 (goto-char (match-beginning 1))
12793 (goto-char pos)
12794 (error "No match")))))
12796 ;; Normal string-search
12797 (goto-char (point-min))
12798 (if (search-forward s nil t)
12799 (goto-char (match-beginning 0))
12800 (error "No match"))))
12801 (and (org-mode-p) (org-show-context 'link-search))))
12803 (defun org-search-not-self (group &rest args)
12804 "Execute `re-search-forward', but only accept matches that do not
12805 enclose the position of `org-open-link-marker'."
12806 (let ((m org-open-link-marker))
12807 (catch 'exit
12808 (while (apply 're-search-forward args)
12809 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12810 (goto-char (match-end group))
12811 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12812 (> (match-beginning 0) (marker-position m))
12813 (< (match-end 0) (marker-position m)))
12814 (save-match-data
12815 (or (not (org-in-regexp
12816 org-bracket-link-analytic-regexp 1))
12817 (not (match-end 4)) ; no description
12818 (and (<= (match-beginning 4) (point))
12819 (>= (match-end 4) (point))))))
12820 (throw 'exit (point))))))))
12822 (defun org-get-buffer-for-internal-link (buffer)
12823 "Return a buffer to be used for displaying the link target of internal links."
12824 (cond
12825 ((not org-display-internal-link-with-indirect-buffer)
12826 buffer)
12827 ((string-match "(Clone)$" (buffer-name buffer))
12828 (message "Buffer is already a clone, not making another one")
12829 ;; we also do not modify visibility in this case
12830 buffer)
12831 (t ; make a new indirect buffer for displaying the link
12832 (let* ((bn (buffer-name buffer))
12833 (ibn (concat bn "(Clone)"))
12834 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12835 (with-current-buffer ib (org-overview))
12836 ib))))
12838 (defun org-do-occur (regexp &optional cleanup)
12839 "Call the Emacs command `occur'.
12840 If CLEANUP is non-nil, remove the printout of the regular expression
12841 in the *Occur* buffer. This is useful if the regex is long and not useful
12842 to read."
12843 (occur regexp)
12844 (when cleanup
12845 (let ((cwin (selected-window)) win beg end)
12846 (when (setq win (get-buffer-window "*Occur*"))
12847 (select-window win))
12848 (goto-char (point-min))
12849 (when (re-search-forward "match[a-z]+" nil t)
12850 (setq beg (match-end 0))
12851 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12852 (setq end (1- (match-beginning 0)))))
12853 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12854 (goto-char (point-min))
12855 (select-window cwin))))
12857 ;;; The mark ring for links jumps
12859 (defvar org-mark-ring nil
12860 "Mark ring for positions before jumps in Org-mode.")
12861 (defvar org-mark-ring-last-goto nil
12862 "Last position in the mark ring used to go back.")
12863 ;; Fill and close the ring
12864 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12865 (loop for i from 1 to org-mark-ring-length do
12866 (push (make-marker) org-mark-ring))
12867 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12868 org-mark-ring)
12870 (defun org-mark-ring-push (&optional pos buffer)
12871 "Put the current position or POS into the mark ring and rotate it."
12872 (interactive)
12873 (setq pos (or pos (point)))
12874 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12875 (move-marker (car org-mark-ring)
12876 (or pos (point))
12877 (or buffer (current-buffer)))
12878 (message "%s"
12879 (substitute-command-keys
12880 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12882 (defun org-mark-ring-goto (&optional n)
12883 "Jump to the previous position in the mark ring.
12884 With prefix arg N, jump back that many stored positions. When
12885 called several times in succession, walk through the entire ring.
12886 Org-mode commands jumping to a different position in the current file,
12887 or to another Org-mode file, automatically push the old position
12888 onto the ring."
12889 (interactive "p")
12890 (let (p m)
12891 (if (eq last-command this-command)
12892 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12893 (setq p org-mark-ring))
12894 (setq org-mark-ring-last-goto p)
12895 (setq m (car p))
12896 (switch-to-buffer (marker-buffer m))
12897 (goto-char m)
12898 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12900 (defun org-remove-angle-brackets (s)
12901 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12902 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12904 (defun org-add-angle-brackets (s)
12905 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12906 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12909 ;;; Following specific links
12911 (defun org-follow-timestamp-link ()
12912 (cond
12913 ((org-at-date-range-p t)
12914 (let ((org-agenda-start-on-weekday)
12915 (t1 (match-string 1))
12916 (t2 (match-string 2)))
12917 (setq t1 (time-to-days (org-time-string-to-time t1))
12918 t2 (time-to-days (org-time-string-to-time t2)))
12919 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12920 ((org-at-timestamp-p t)
12921 (org-agenda-list nil (time-to-days (org-time-string-to-time
12922 (substring (match-string 1) 0 10)))
12924 (t (error "This should not happen"))))
12927 (defun org-follow-bbdb-link (name)
12928 "Follow a BBDB link to NAME."
12929 (require 'bbdb)
12930 (let ((inhibit-redisplay (not debug-on-error))
12931 (bbdb-electric-p nil))
12932 (catch 'exit
12933 ;; Exact match on name
12934 (bbdb-name (concat "\\`" name "\\'") nil)
12935 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12936 ;; Exact match on name
12937 (bbdb-company (concat "\\`" name "\\'") nil)
12938 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12939 ;; Partial match on name
12940 (bbdb-name name nil)
12941 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12942 ;; Partial match on company
12943 (bbdb-company name nil)
12944 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12945 ;; General match including network address and notes
12946 (bbdb name nil)
12947 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12948 (delete-window (get-buffer-window "*BBDB*"))
12949 (error "No matching BBDB record")))))
12951 (defun org-follow-info-link (name)
12952 "Follow an info file & node link to NAME."
12953 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12954 (string-match "\\(.*\\)" name))
12955 (progn
12956 (require 'info)
12957 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12958 (Info-find-node (match-string 1 name) (match-string 2 name))
12959 (Info-find-node (match-string 1 name) "Top")))
12960 (message "Could not open: %s" name)))
12962 (defun org-follow-gnus-link (&optional group article)
12963 "Follow a Gnus link to GROUP and ARTICLE."
12964 (require 'gnus)
12965 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12966 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12967 (cond ((and group article)
12968 (gnus-group-read-group 1 nil group)
12969 (gnus-summary-goto-article (string-to-number article) nil t))
12970 (group (gnus-group-jump-to-group group))))
12972 (defun org-follow-vm-link (&optional folder article readonly)
12973 "Follow a VM link to FOLDER and ARTICLE."
12974 (require 'vm)
12975 (setq article (org-add-angle-brackets article))
12976 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12977 ;; ange-ftp or efs or tramp access
12978 (let ((user (or (match-string 1 folder) (user-login-name)))
12979 (host (match-string 2 folder))
12980 (file (match-string 3 folder)))
12981 (cond
12982 ((featurep 'tramp)
12983 ;; use tramp to access the file
12984 (if (featurep 'xemacs)
12985 (setq folder (format "[%s@%s]%s" user host file))
12986 (setq folder (format "/%s@%s:%s" user host file))))
12988 ;; use ange-ftp or efs
12989 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12990 (setq folder (format "/%s@%s:%s" user host file))))))
12991 (when folder
12992 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12993 (sit-for 0.1)
12994 (when article
12995 (vm-select-folder-buffer)
12996 (widen)
12997 (let ((case-fold-search t))
12998 (goto-char (point-min))
12999 (if (not (re-search-forward
13000 (concat "^" "message-id: *" (regexp-quote article))))
13001 (error "Could not find the specified message in this folder"))
13002 (vm-isearch-update)
13003 (vm-isearch-narrow)
13004 (vm-beginning-of-message)
13005 (vm-summarize)))))
13007 (defun org-follow-wl-link (folder article)
13008 "Follow a Wanderlust link to FOLDER and ARTICLE."
13009 (if (and (string= folder "%")
13010 article
13011 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13012 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13013 ;; Thus, we recompose folder and article ids.
13014 (setq folder (format "%s#%s" folder (match-string 1 article))
13015 article (match-string 3 article)))
13016 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13017 (error "No such folder: %s" folder))
13018 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13019 (and article
13020 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13021 (wl-summary-redisplay)))
13023 (defun org-follow-rmail-link (folder article)
13024 "Follow an RMAIL link to FOLDER and ARTICLE."
13025 (setq article (org-add-angle-brackets article))
13026 (let (message-number)
13027 (save-excursion
13028 (save-window-excursion
13029 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13030 (setq message-number
13031 (save-restriction
13032 (widen)
13033 (goto-char (point-max))
13034 (if (re-search-backward
13035 (concat "^Message-ID:\\s-+" (regexp-quote
13036 (or article "")))
13037 nil t)
13038 (rmail-what-message))))))
13039 (if message-number
13040 (progn
13041 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13042 (rmail-show-message message-number)
13043 message-number)
13044 (error "Message not found"))))
13046 ;;; mh-e integration based on planner-mode
13047 (defun org-mhe-get-message-real-folder ()
13048 "Return the name of the current message real folder, so if you use
13049 sequences, it will now work."
13050 (save-excursion
13051 (let* ((folder
13052 (if (equal major-mode 'mh-folder-mode)
13053 mh-current-folder
13054 ;; Refer to the show buffer
13055 mh-show-folder-buffer))
13056 (end-index
13057 (if (boundp 'mh-index-folder)
13058 (min (length mh-index-folder) (length folder))))
13060 ;; a simple test on mh-index-data does not work, because
13061 ;; mh-index-data is always nil in a show buffer.
13062 (if (and (boundp 'mh-index-folder)
13063 (string= mh-index-folder (substring folder 0 end-index)))
13064 (if (equal major-mode 'mh-show-mode)
13065 (save-window-excursion
13066 (let (pop-up-frames)
13067 (when (buffer-live-p (get-buffer folder))
13068 (progn
13069 (pop-to-buffer folder)
13070 (org-mhe-get-message-folder-from-index)
13073 (org-mhe-get-message-folder-from-index)
13075 folder
13079 (defun org-mhe-get-message-folder-from-index ()
13080 "Returns the name of the message folder in a index folder buffer."
13081 (save-excursion
13082 (mh-index-previous-folder)
13083 (re-search-forward "^\\(+.*\\)$" nil t)
13084 (message "%s" (match-string 1))))
13086 (defun org-mhe-get-message-folder ()
13087 "Return the name of the current message folder. Be careful if you
13088 use sequences."
13089 (save-excursion
13090 (if (equal major-mode 'mh-folder-mode)
13091 mh-current-folder
13092 ;; Refer to the show buffer
13093 mh-show-folder-buffer)))
13095 (defun org-mhe-get-message-num ()
13096 "Return the number of the current message. Be careful if you
13097 use sequences."
13098 (save-excursion
13099 (if (equal major-mode 'mh-folder-mode)
13100 (mh-get-msg-num nil)
13101 ;; Refer to the show buffer
13102 (mh-show-buffer-message-number))))
13104 (defun org-mhe-get-header (header)
13105 "Return a header of the message in folder mode. This will create a
13106 show buffer for the corresponding message. If you have a more clever
13107 idea..."
13108 (let* ((folder (org-mhe-get-message-folder))
13109 (num (org-mhe-get-message-num))
13110 (buffer (get-buffer-create (concat "show-" folder)))
13111 (header-field))
13112 (with-current-buffer buffer
13113 (mh-display-msg num folder)
13114 (if (equal major-mode 'mh-folder-mode)
13115 (mh-header-display)
13116 (mh-show-header-display))
13117 (set-buffer buffer)
13118 (setq header-field (mh-get-header-field header))
13119 (if (equal major-mode 'mh-folder-mode)
13120 (mh-show)
13121 (mh-show-show))
13122 header-field)))
13124 (defun org-follow-mhe-link (folder article)
13125 "Follow an MHE link to FOLDER and ARTICLE.
13126 If ARTICLE is nil FOLDER is shown. If the configuration variable
13127 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13128 ARTICLE is searched in all folders. Indexed searches (swish++,
13129 namazu, and others supported by MH-E) will always search in all
13130 folders."
13131 (require 'mh-e)
13132 (require 'mh-search)
13133 (require 'mh-utils)
13134 (mh-find-path)
13135 (if (not article)
13136 (mh-visit-folder (mh-normalize-folder-name folder))
13137 (setq article (org-add-angle-brackets article))
13138 (mh-search-choose)
13139 (if (equal mh-searcher 'pick)
13140 (progn
13141 (mh-search folder (list "--message-id" article))
13142 (when (and org-mhe-search-all-folders
13143 (not (org-mhe-get-message-real-folder)))
13144 (kill-this-buffer)
13145 (mh-search "+" (list "--message-id" article))))
13146 (mh-search "+" article))
13147 (if (org-mhe-get-message-real-folder)
13148 (mh-show-msg 1)
13149 (kill-this-buffer)
13150 (error "Message not found"))))
13152 ;;; BibTeX links
13154 ;; Use the custom search meachnism to construct and use search strings for
13155 ;; file links to BibTeX database entries.
13157 (defun org-create-file-search-in-bibtex ()
13158 "Create the search string and description for a BibTeX database entry."
13159 (when (eq major-mode 'bibtex-mode)
13160 ;; yes, we want to construct this search string.
13161 ;; Make a good description for this entry, using names, year and the title
13162 ;; Put it into the `description' variable which is dynamically scoped.
13163 (let ((bibtex-autokey-names 1)
13164 (bibtex-autokey-names-stretch 1)
13165 (bibtex-autokey-name-case-convert-function 'identity)
13166 (bibtex-autokey-name-separator " & ")
13167 (bibtex-autokey-additional-names " et al.")
13168 (bibtex-autokey-year-length 4)
13169 (bibtex-autokey-name-year-separator " ")
13170 (bibtex-autokey-titlewords 3)
13171 (bibtex-autokey-titleword-separator " ")
13172 (bibtex-autokey-titleword-case-convert-function 'identity)
13173 (bibtex-autokey-titleword-length 'infty)
13174 (bibtex-autokey-year-title-separator ": "))
13175 (setq description (bibtex-generate-autokey)))
13176 ;; Now parse the entry, get the key and return it.
13177 (save-excursion
13178 (bibtex-beginning-of-entry)
13179 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13181 (defun org-execute-file-search-in-bibtex (s)
13182 "Find the link search string S as a key for a database entry."
13183 (when (eq major-mode 'bibtex-mode)
13184 ;; Yes, we want to do the search in this file.
13185 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13186 (goto-char (point-min))
13187 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13188 (regexp-quote s) "[ \t\n]*,") nil t)
13189 (goto-char (match-beginning 0)))
13190 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13191 ;; Use double prefix to indicate that any web link should be browsed
13192 (let ((b (current-buffer)) (p (point)))
13193 ;; Restore the window configuration because we just use the web link
13194 (set-window-configuration org-window-config-before-follow-link)
13195 (save-excursion (set-buffer b) (goto-char p)
13196 (bibtex-url)))
13197 (recenter 0)) ; Move entry start to beginning of window
13198 ;; return t to indicate that the search is done.
13201 ;; Finally add the functions to the right hooks.
13202 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13203 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13205 ;; end of Bibtex link setup
13207 ;;; Following file links
13209 (defun org-open-file (path &optional in-emacs line search)
13210 "Open the file at PATH.
13211 First, this expands any special file name abbreviations. Then the
13212 configuration variable `org-file-apps' is checked if it contains an
13213 entry for this file type, and if yes, the corresponding command is launched.
13214 If no application is found, Emacs simply visits the file.
13215 With optional argument IN-EMACS, Emacs will visit the file.
13216 Optional LINE specifies a line to go to, optional SEARCH a string to
13217 search for. If LINE or SEARCH is given, the file will always be
13218 opened in Emacs.
13219 If the file does not exist, an error is thrown."
13220 (setq in-emacs (or in-emacs line search))
13221 (let* ((file (if (equal path "")
13222 buffer-file-name
13223 (substitute-in-file-name (expand-file-name path))))
13224 (apps (append org-file-apps (org-default-apps)))
13225 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13226 (dirp (if remp nil (file-directory-p file)))
13227 (dfile (downcase file))
13228 (old-buffer (current-buffer))
13229 (old-pos (point))
13230 (old-mode major-mode)
13231 ext cmd)
13232 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13233 (setq ext (match-string 1 dfile))
13234 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13235 (setq ext (match-string 1 dfile))))
13236 (if in-emacs
13237 (setq cmd 'emacs)
13238 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13239 (and dirp (cdr (assoc 'directory apps)))
13240 (cdr (assoc ext apps))
13241 (cdr (assoc t apps)))))
13242 (when (eq cmd 'mailcap)
13243 (require 'mailcap)
13244 (mailcap-parse-mailcaps)
13245 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13246 (command (mailcap-mime-info mime-type)))
13247 (if (stringp command)
13248 (setq cmd command)
13249 (setq cmd 'emacs))))
13250 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13251 (not (file-exists-p file))
13252 (not org-open-non-existing-files))
13253 (error "No such file: %s" file))
13254 (cond
13255 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13256 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13257 (while (string-match "['\"]%s['\"]" cmd)
13258 (setq cmd (replace-match "%s" t t cmd)))
13259 (while (string-match "%s" cmd)
13260 (setq cmd (replace-match
13261 (save-match-data (shell-quote-argument file))
13262 t t cmd)))
13263 (save-window-excursion
13264 (start-process-shell-command cmd nil cmd)))
13265 ((or (stringp cmd)
13266 (eq cmd 'emacs))
13267 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13268 (widen)
13269 (if line (goto-line line)
13270 (if search (org-link-search search))))
13271 ((consp cmd)
13272 (eval cmd))
13273 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13274 (and (org-mode-p) (eq old-mode 'org-mode)
13275 (or (not (equal old-buffer (current-buffer)))
13276 (not (equal old-pos (point))))
13277 (org-mark-ring-push old-pos old-buffer))))
13279 (defun org-default-apps ()
13280 "Return the default applications for this operating system."
13281 (cond
13282 ((eq system-type 'darwin)
13283 org-file-apps-defaults-macosx)
13284 ((eq system-type 'windows-nt)
13285 org-file-apps-defaults-windowsnt)
13286 (t org-file-apps-defaults-gnu)))
13288 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13289 (defun org-file-remote-p (file)
13290 "Test whether FILE specifies a location on a remote system.
13291 Return non-nil if the location is indeed remote.
13293 For example, the filename \"/user@host:/foo\" specifies a location
13294 on the system \"/user@host:\"."
13295 (cond ((fboundp 'file-remote-p)
13296 (file-remote-p file))
13297 ((fboundp 'tramp-handle-file-remote-p)
13298 (tramp-handle-file-remote-p file))
13299 ((and (boundp 'ange-ftp-name-format)
13300 (string-match (car ange-ftp-name-format) file))
13302 (t nil)))
13305 ;;;; Hooks for remember.el, and refiling
13307 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13308 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13310 ;;;###autoload
13311 (defun org-remember-insinuate ()
13312 "Setup remember.el for use wiht Org-mode."
13313 (require 'remember)
13314 (setq remember-annotation-functions '(org-remember-annotation))
13315 (setq remember-handler-functions '(org-remember-handler))
13316 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13318 ;;;###autoload
13319 (defun org-remember-annotation ()
13320 "Return a link to the current location as an annotation for remember.el.
13321 If you are using Org-mode files as target for data storage with
13322 remember.el, then the annotations should include a link compatible with the
13323 conventions in Org-mode. This function returns such a link."
13324 (org-store-link nil))
13326 (defconst org-remember-help
13327 "Select a destination location for the note.
13328 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13329 RET on headline -> Store as sublevel entry to current headline
13330 RET at beg-of-buf -> Append to file as level 2 headline
13331 <left>/<right> -> before/after current headline, same headings level")
13333 (defvar org-remember-previous-location nil)
13334 (defvar org-force-remember-template-char) ;; dynamically scoped
13336 (defun org-select-remember-template (&optional use-char)
13337 (when org-remember-templates
13338 (let* ((templates (mapcar (lambda (x)
13339 (if (stringp (car x))
13340 (append (list (nth 1 x) (car x)) (cddr x))
13341 (append (list (car x) "") (cdr x))))
13342 org-remember-templates))
13343 (char (or use-char
13344 (cond
13345 ((= (length templates) 1)
13346 (caar templates))
13347 ((and (boundp 'org-force-remember-template-char)
13348 org-force-remember-template-char)
13349 (if (stringp org-force-remember-template-char)
13350 (string-to-char org-force-remember-template-char)
13351 org-force-remember-template-char))
13353 (message "Select template: %s"
13354 (mapconcat
13355 (lambda (x)
13356 (cond
13357 ((not (string-match "\\S-" (nth 1 x)))
13358 (format "[%c]" (car x)))
13359 ((equal (downcase (car x))
13360 (downcase (aref (nth 1 x) 0)))
13361 (format "[%c]%s" (car x)
13362 (substring (nth 1 x) 1)))
13363 (t (format "[%c]%s" (car x) (nth 1 x)))))
13364 templates " "))
13365 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13366 (when (equal char0 ?\C-g)
13367 (jump-to-register remember-register)
13368 (kill-buffer remember-buffer))
13369 char0))))))
13370 (cddr (assoc char templates)))))
13372 (defvar x-last-selected-text)
13373 (defvar x-last-selected-text-primary)
13375 ;;;###autoload
13376 (defun org-remember-apply-template (&optional use-char skip-interactive)
13377 "Initialize *remember* buffer with template, invoke `org-mode'.
13378 This function should be placed into `remember-mode-hook' and in fact requires
13379 to be run from that hook to function properly."
13380 (if org-remember-templates
13381 (let* ((entry (org-select-remember-template use-char))
13382 (tpl (car entry))
13383 (plist-p (if org-store-link-plist t nil))
13384 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13385 (string-match "\\S-" (nth 1 entry)))
13386 (nth 1 entry)
13387 org-default-notes-file))
13388 (headline (nth 2 entry))
13389 (v-c (or (and (eq window-system 'x)
13390 (fboundp 'x-cut-buffer-or-selection-value)
13391 (x-cut-buffer-or-selection-value))
13392 (org-bound-and-true-p x-last-selected-text)
13393 (org-bound-and-true-p x-last-selected-text-primary)
13394 (and (> (length kill-ring) 0) (current-kill 0))))
13395 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13396 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13397 (v-u (concat "[" (substring v-t 1 -1) "]"))
13398 (v-U (concat "[" (substring v-T 1 -1) "]"))
13399 ;; `initial' and `annotation' are bound in `remember'
13400 (v-i (if (boundp 'initial) initial))
13401 (v-a (if (and (boundp 'annotation) annotation)
13402 (if (equal annotation "[[]]") "" annotation)
13403 ""))
13404 (v-A (if (and v-a
13405 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13406 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13407 v-a))
13408 (v-n user-full-name)
13409 (org-startup-folded nil)
13410 org-time-was-given org-end-time-was-given x
13411 prompt completions char time pos default histvar)
13412 (setq org-store-link-plist
13413 (append (list :annotation v-a :initial v-i)
13414 org-store-link-plist))
13415 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13416 (erase-buffer)
13417 (insert (substitute-command-keys
13418 (format
13419 "## Filing location: Select interactively, default, or last used:
13420 ## %s to select file and header location interactively.
13421 ## %s \"%s\" -> \"* %s\"
13422 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13423 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13424 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13425 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13426 (abbreviate-file-name (or file org-default-notes-file))
13427 (or headline "")
13428 (or (car org-remember-previous-location) "???")
13429 (or (cdr org-remember-previous-location) "???"))))
13430 (insert tpl) (goto-char (point-min))
13431 ;; Simple %-escapes
13432 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13433 (when (and initial (equal (match-string 0) "%i"))
13434 (save-match-data
13435 (let* ((lead (buffer-substring
13436 (point-at-bol) (match-beginning 0))))
13437 (setq v-i (mapconcat 'identity
13438 (org-split-string initial "\n")
13439 (concat "\n" lead))))))
13440 (replace-match
13441 (or (eval (intern (concat "v-" (match-string 1)))) "")
13442 t t))
13444 ;; %[] Insert contents of a file.
13445 (goto-char (point-min))
13446 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13447 (let ((start (match-beginning 0))
13448 (end (match-end 0))
13449 (filename (expand-file-name (match-string 1))))
13450 (goto-char start)
13451 (delete-region start end)
13452 (condition-case error
13453 (insert-file-contents filename)
13454 (error (insert (format "%%![Couldn't insert %s: %s]"
13455 filename error))))))
13456 ;; %() embedded elisp
13457 (goto-char (point-min))
13458 (while (re-search-forward "%\\((.+)\\)" nil t)
13459 (goto-char (match-beginning 0))
13460 (let ((template-start (point)))
13461 (forward-char 1)
13462 (let ((result
13463 (condition-case error
13464 (eval (read (current-buffer)))
13465 (error (format "%%![Error: %s]" error)))))
13466 (delete-region template-start (point))
13467 (insert result))))
13469 ;; From the property list
13470 (when plist-p
13471 (goto-char (point-min))
13472 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13473 (and (setq x (or (plist-get org-store-link-plist
13474 (intern (match-string 1))) ""))
13475 (replace-match x t t))))
13477 ;; Turn on org-mode in the remember buffer, set local variables
13478 (org-mode)
13479 (org-set-local 'org-finish-function 'org-remember-finalize)
13480 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13481 (org-set-local 'org-default-notes-file file))
13482 (if (and headline (stringp headline) (string-match "\\S-" headline))
13483 (org-set-local 'org-remember-default-headline headline))
13484 ;; Interactive template entries
13485 (goto-char (point-min))
13486 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13487 (setq char (if (match-end 3) (match-string 3))
13488 prompt (if (match-end 2) (match-string 2)))
13489 (goto-char (match-beginning 0))
13490 (replace-match "")
13491 (setq completions nil default nil)
13492 (when prompt
13493 (setq completions (org-split-string prompt "|")
13494 prompt (pop completions)
13495 default (car completions)
13496 histvar (intern (concat
13497 "org-remember-template-prompt-history::"
13498 (or prompt "")))
13499 completions (mapcar 'list completions)))
13500 (cond
13501 ((member char '("G" "g"))
13502 (let* ((org-last-tags-completion-table
13503 (org-global-tags-completion-table
13504 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13505 (org-add-colon-after-tag-completion t)
13506 (ins (completing-read
13507 (if prompt (concat prompt ": ") "Tags: ")
13508 'org-tags-completion-function nil nil nil
13509 'org-tags-history)))
13510 (setq ins (mapconcat 'identity
13511 (org-split-string ins (org-re "[^[:alnum:]]+"))
13512 ":"))
13513 (when (string-match "\\S-" ins)
13514 (or (equal (char-before) ?:) (insert ":"))
13515 (insert ins)
13516 (or (equal (char-after) ?:) (insert ":")))))
13517 (char
13518 (setq org-time-was-given (equal (upcase char) char))
13519 (setq time (org-read-date (equal (upcase char) "U") t nil
13520 prompt))
13521 (org-insert-time-stamp time org-time-was-given
13522 (member char '("u" "U"))
13523 nil nil (list org-end-time-was-given)))
13525 (insert (org-completing-read
13526 (concat (if prompt prompt "Enter string")
13527 (if default (concat " [" default "]"))
13528 ": ")
13529 completions nil nil nil histvar default)))))
13530 (goto-char (point-min))
13531 (if (re-search-forward "%\\?" nil t)
13532 (replace-match "")
13533 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13534 (org-mode)
13535 (org-set-local 'org-finish-function 'org-remember-finalize))
13536 (when (save-excursion
13537 (goto-char (point-min))
13538 (re-search-forward "%!" nil t))
13539 (replace-match "")
13540 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13542 (defun org-remember-finish-immediately ()
13543 "File remember note immediately.
13544 This should be run in `post-command-hook' and will remove itself
13545 from that hook."
13546 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13547 (when org-finish-function
13548 (funcall org-finish-function)))
13550 (defun org-remember-finalize ()
13551 "Finalize the remember process."
13552 (unless (fboundp 'remember-finalize)
13553 (defalias 'remember-finalize 'remember-buffer))
13554 (when (and org-clock-marker
13555 (equal (marker-buffer org-clock-marker) (current-buffer)))
13556 ;; FIXME: test this, this is w/o notetaking!
13557 (let (org-log-done) (org-clock-out)))
13558 (when buffer-file-name
13559 (save-buffer)
13560 (setq buffer-file-name nil))
13561 (remember-finalize))
13563 ;;;###autoload
13564 (defun org-remember (&optional goto org-force-remember-template-char)
13565 "Call `remember'. If this is already a remember buffer, re-apply template.
13566 If there is an active region, make sure remember uses it as initial content
13567 of the remember buffer.
13569 When called interactively with a `C-u' prefix argument GOTO, don't remember
13570 anything, just go to the file/headline where the selected template usually
13571 stores its notes. With a double prefix arg `C-u C-u', go to the last
13572 note stored by remember.
13574 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13575 associated with a template in `org-remember-templates'."
13576 (interactive "P")
13577 (cond
13578 ((equal goto '(4)) (org-go-to-remember-target))
13579 ((equal goto '(16)) (org-remember-goto-last-stored))
13581 (if (memq org-finish-function '(remember-buffer remember-finalize))
13582 (progn
13583 (when (< (length org-remember-templates) 2)
13584 (error "No other template available"))
13585 (erase-buffer)
13586 (let ((annotation (plist-get org-store-link-plist :annotation))
13587 (initial (plist-get org-store-link-plist :initial)))
13588 (org-remember-apply-template))
13589 (message "Press C-c C-c to remember data"))
13590 (if (org-region-active-p)
13591 (remember (buffer-substring (point) (mark)))
13592 (call-interactively 'remember))))))
13594 (defun org-remember-goto-last-stored ()
13595 "Go to the location where the last remember note was stored."
13596 (interactive)
13597 (bookmark-jump "org-remember-last-stored")
13598 (message "This is the last note stored by remember"))
13600 (defun org-go-to-remember-target (&optional template-key)
13601 "Go to the target location of a remember template.
13602 The user is queried for the template."
13603 (interactive)
13604 (let* ((entry (org-select-remember-template template-key))
13605 (file (nth 1 entry))
13606 (heading (nth 2 entry))
13607 visiting)
13608 (unless (and file (stringp file) (string-match "\\S-" file))
13609 (setq file org-default-notes-file))
13610 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13611 (setq heading org-remember-default-headline))
13612 (setq visiting (org-find-base-buffer-visiting file))
13613 (if (not visiting) (find-file-noselect file))
13614 (switch-to-buffer (or visiting (get-file-buffer file)))
13615 (widen)
13616 (goto-char (point-min))
13617 (if (re-search-forward
13618 (concat "^\\*+[ \t]+" (regexp-quote heading)
13619 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13620 nil t)
13621 (goto-char (match-beginning 0))
13622 (error "Target headline not found: %s" heading))))
13624 (defvar org-note-abort nil) ; dynamically scoped
13626 ;;;###autoload
13627 (defun org-remember-handler ()
13628 "Store stuff from remember.el into an org file.
13629 First prompts for an org file. If the user just presses return, the value
13630 of `org-default-notes-file' is used.
13631 Then the command offers the headings tree of the selected file in order to
13632 file the text at a specific location.
13633 You can either immediately press RET to get the note appended to the
13634 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13635 find a better place. Then press RET or <left> or <right> in insert the note.
13637 Key Cursor position Note gets inserted
13638 -----------------------------------------------------------------------------
13639 RET buffer-start as level 1 heading at end of file
13640 RET on headline as sublevel of the heading at cursor
13641 RET no heading at cursor position, level taken from context.
13642 Or use prefix arg to specify level manually.
13643 <left> on headline as same level, before current heading
13644 <right> on headline as same level, after current heading
13646 So the fastest way to store the note is to press RET RET to append it to
13647 the default file. This way your current train of thought is not
13648 interrupted, in accordance with the principles of remember.el.
13649 You can also get the fast execution without prompting by using
13650 C-u C-c C-c to exit the remember buffer. See also the variable
13651 `org-remember-store-without-prompt'.
13653 Before being stored away, the function ensures that the text has a
13654 headline, i.e. a first line that starts with a \"*\". If not, a headline
13655 is constructed from the current date and some additional data.
13657 If the variable `org-adapt-indentation' is non-nil, the entire text is
13658 also indented so that it starts in the same column as the headline
13659 \(i.e. after the stars).
13661 See also the variable `org-reverse-note-order'."
13662 (goto-char (point-min))
13663 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13664 (replace-match ""))
13665 (goto-char (point-max))
13666 (beginning-of-line 1)
13667 (while (looking-at "[ \t]*$\\|##.*")
13668 (delete-region (1- (point)) (point-max))
13669 (beginning-of-line 1))
13670 (catch 'quit
13671 (if org-note-abort (throw 'quit nil))
13672 (let* ((txt (buffer-substring (point-min) (point-max)))
13673 (fastp (org-xor (equal current-prefix-arg '(4))
13674 org-remember-store-without-prompt))
13675 (file (cond
13676 (fastp org-default-notes-file)
13677 ((and (eq org-remember-interactive-interface 'refile)
13678 org-refile-targets)
13679 org-default-notes-file)
13680 ((not (and (equal current-prefix-arg '(16))
13681 org-remember-previous-location))
13682 (org-get-org-file))))
13683 (heading org-remember-default-headline)
13684 (visiting (and file (org-find-base-buffer-visiting file)))
13685 (org-startup-folded nil)
13686 (org-startup-align-all-tables nil)
13687 (org-goto-start-pos 1)
13688 spos exitcmd level indent reversed)
13689 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13690 (setq file (car org-remember-previous-location)
13691 heading (cdr org-remember-previous-location)
13692 fastp t))
13693 (setq current-prefix-arg nil)
13694 (if (string-match "[ \t\n]+\\'" txt)
13695 (setq txt (replace-match "" t t txt)))
13696 ;; Modify text so that it becomes a nice subtree which can be inserted
13697 ;; into an org tree.
13698 (let* ((lines (split-string txt "\n"))
13699 first)
13700 (setq first (car lines) lines (cdr lines))
13701 (if (string-match "^\\*+ " first)
13702 ;; Is already a headline
13703 (setq indent nil)
13704 ;; We need to add a headline: Use time and first buffer line
13705 (setq lines (cons first lines)
13706 first (concat "* " (current-time-string)
13707 " (" (remember-buffer-desc) ")")
13708 indent " "))
13709 (if (and org-adapt-indentation indent)
13710 (setq lines (mapcar
13711 (lambda (x)
13712 (if (string-match "\\S-" x)
13713 (concat indent x) x))
13714 lines)))
13715 (setq txt (concat first "\n"
13716 (mapconcat 'identity lines "\n"))))
13717 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13718 (setq txt (replace-match "\n\n" t t txt))
13719 (if (string-match "[ \t\n]*\\'" txt)
13720 (setq txt (replace-match "\n" t t txt))))
13721 ;; Put the modified text back into the remember buffer, for refile.
13722 (erase-buffer)
13723 (insert txt)
13724 (goto-char (point-min))
13725 (when (and (eq org-remember-interactive-interface 'refile)
13726 (not fastp))
13727 (org-refile nil (or visiting (find-file-noselect file)))
13728 (throw 'quit t))
13729 ;; Find the file
13730 (if (not visiting) (find-file-noselect file))
13731 (with-current-buffer (or visiting (get-file-buffer file))
13732 (unless (org-mode-p)
13733 (error "Target files for remember notes must be in Org-mode"))
13734 (save-excursion
13735 (save-restriction
13736 (widen)
13737 (and (goto-char (point-min))
13738 (not (re-search-forward "^\\* " nil t))
13739 (insert "\n* " (or heading "Notes") "\n"))
13740 (setq reversed (org-notes-order-reversed-p))
13742 ;; Find the default location
13743 (when (and heading (stringp heading) (string-match "\\S-" heading))
13744 (goto-char (point-min))
13745 (if (re-search-forward
13746 (concat "^\\*+[ \t]+" (regexp-quote heading)
13747 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13748 nil t)
13749 (setq org-goto-start-pos (match-beginning 0))
13750 (when fastp
13751 (goto-char (point-max))
13752 (unless (bolp) (newline))
13753 (insert "* " heading "\n")
13754 (setq org-goto-start-pos (point-at-bol 0)))))
13756 ;; Ask the User for a location, using the appropriate interface
13757 (cond
13758 (fastp (setq spos org-goto-start-pos
13759 exitcmd 'return))
13760 ((eq org-remember-interactive-interface 'outline)
13761 (setq spos (org-get-location (current-buffer)
13762 org-remember-help)
13763 exitcmd (cdr spos)
13764 spos (car spos)))
13765 ((eq org-remember-interactive-interface 'outline-path-completion)
13766 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13767 (org-refile-use-outline-path t))
13768 (setq spos (org-refile-get-location "Heading: ")
13769 exitcmd 'return
13770 spos (nth 3 spos))))
13771 (t (error "this should not hapen")))
13772 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13773 ; not handle this note
13774 (goto-char spos)
13775 (cond ((org-on-heading-p t)
13776 (org-back-to-heading t)
13777 (setq level (funcall outline-level))
13778 (cond
13779 ((eq exitcmd 'return)
13780 ;; sublevel of current
13781 (setq org-remember-previous-location
13782 (cons (abbreviate-file-name file)
13783 (org-get-heading 'notags)))
13784 (if reversed
13785 (outline-next-heading)
13786 (org-end-of-subtree t)
13787 (if (not (bolp))
13788 (if (looking-at "[ \t]*\n")
13789 (beginning-of-line 2)
13790 (end-of-line 1)
13791 (insert "\n"))))
13792 (bookmark-set "org-remember-last-stored")
13793 (org-paste-subtree (org-get-legal-level level 1) txt))
13794 ((eq exitcmd 'left)
13795 ;; before current
13796 (bookmark-set "org-remember-last-stored")
13797 (org-paste-subtree level txt))
13798 ((eq exitcmd 'right)
13799 ;; after current
13800 (org-end-of-subtree t)
13801 (bookmark-set "org-remember-last-stored")
13802 (org-paste-subtree level txt))
13803 (t (error "This should not happen"))))
13805 ((and (bobp) (not reversed))
13806 ;; Put it at the end, one level below level 1
13807 (save-restriction
13808 (widen)
13809 (goto-char (point-max))
13810 (if (not (bolp)) (newline))
13811 (bookmark-set "org-remember-last-stored")
13812 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13814 ((and (bobp) reversed)
13815 ;; Put it at the start, as level 1
13816 (save-restriction
13817 (widen)
13818 (goto-char (point-min))
13819 (re-search-forward "^\\*+ " nil t)
13820 (beginning-of-line 1)
13821 (bookmark-set "org-remember-last-stored")
13822 (org-paste-subtree 1 txt)))
13824 ;; Put it right there, with automatic level determined by
13825 ;; org-paste-subtree or from prefix arg
13826 (bookmark-set "org-remember-last-stored")
13827 (org-paste-subtree
13828 (if (numberp current-prefix-arg) current-prefix-arg)
13829 txt)))
13830 (when remember-save-after-remembering
13831 (save-buffer)
13832 (if (not visiting) (kill-buffer (current-buffer)))))))))
13834 t) ;; return t to indicate that we took care of this note.
13836 (defun org-get-org-file ()
13837 "Read a filename, with default directory `org-directory'."
13838 (let ((default (or org-default-notes-file remember-data-file)))
13839 (read-file-name (format "File name [%s]: " default)
13840 (file-name-as-directory org-directory)
13841 default)))
13843 (defun org-notes-order-reversed-p ()
13844 "Check if the current file should receive notes in reversed order."
13845 (cond
13846 ((not org-reverse-note-order) nil)
13847 ((eq t org-reverse-note-order) t)
13848 ((not (listp org-reverse-note-order)) nil)
13849 (t (catch 'exit
13850 (let ((all org-reverse-note-order)
13851 entry)
13852 (while (setq entry (pop all))
13853 (if (string-match (car entry) buffer-file-name)
13854 (throw 'exit (cdr entry))))
13855 nil)))))
13857 ;;; Refiling
13859 (defvar org-refile-target-table nil
13860 "The list of refile targets, created by `org-refile'.")
13862 (defvar org-agenda-new-buffers nil
13863 "Buffers created to visit agenda files.")
13865 (defun org-get-refile-targets (&optional default-buffer)
13866 "Produce a table with refile targets."
13867 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13868 targets txt re files f desc descre)
13869 (with-current-buffer (or default-buffer (current-buffer))
13870 (while (setq entry (pop entries))
13871 (setq files (car entry) desc (cdr entry))
13872 (cond
13873 ((null files) (setq files (list (current-buffer))))
13874 ((eq files 'org-agenda-files)
13875 (setq files (org-agenda-files 'unrestricted)))
13876 ((and (symbolp files) (fboundp files))
13877 (setq files (funcall files)))
13878 ((and (symbolp files) (boundp files))
13879 (setq files (symbol-value files))))
13880 (if (stringp files) (setq files (list files)))
13881 (cond
13882 ((eq (car desc) :tag)
13883 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13884 ((eq (car desc) :todo)
13885 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13886 ((eq (car desc) :regexp)
13887 (setq descre (cdr desc)))
13888 ((eq (car desc) :level)
13889 (setq descre (concat "^\\*\\{" (number-to-string
13890 (if org-odd-levels-only
13891 (1- (* 2 (cdr desc)))
13892 (cdr desc)))
13893 "\\}[ \t]")))
13894 ((eq (car desc) :maxlevel)
13895 (setq descre (concat "^\\*\\{1," (number-to-string
13896 (if org-odd-levels-only
13897 (1- (* 2 (cdr desc)))
13898 (cdr desc)))
13899 "\\}[ \t]")))
13900 (t (error "Bad refiling target description %s" desc)))
13901 (while (setq f (pop files))
13902 (save-excursion
13903 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13904 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13905 (save-excursion
13906 (save-restriction
13907 (widen)
13908 (goto-char (point-min))
13909 (while (re-search-forward descre nil t)
13910 (goto-char (point-at-bol))
13911 (when (looking-at org-complex-heading-regexp)
13912 (setq txt (match-string 4)
13913 re (concat "^" (regexp-quote
13914 (buffer-substring (match-beginning 1)
13915 (match-end 4)))))
13916 (if (match-end 5) (setq re (concat re "[ \t]+"
13917 (regexp-quote
13918 (match-string 5)))))
13919 (setq re (concat re "[ \t]*$"))
13920 (when org-refile-use-outline-path
13921 (setq txt (mapconcat 'identity
13922 (append
13923 (if (eq org-refile-use-outline-path 'file)
13924 (list (file-name-nondirectory
13925 (buffer-file-name (buffer-base-buffer))))
13926 (if (eq org-refile-use-outline-path 'full-file-path)
13927 (list (buffer-file-name (buffer-base-buffer)))))
13928 (org-get-outline-path)
13929 (list txt))
13930 "/")))
13931 (push (list txt f re (point)) targets))
13932 (goto-char (point-at-eol))))))))
13933 (nreverse targets))))
13935 (defun org-get-outline-path ()
13936 "Return the outline path to the current entry, as a list."
13937 (let (rtn)
13938 (save-excursion
13939 (while (org-up-heading-safe)
13940 (when (looking-at org-complex-heading-regexp)
13941 (push (org-match-string-no-properties 4) rtn)))
13942 rtn)))
13944 (defvar org-refile-history nil
13945 "History for refiling operations.")
13947 (defun org-refile (&optional goto default-buffer)
13948 "Move the entry at point to another heading.
13949 The list of target headings is compiled using the information in
13950 `org-refile-targets', which see. This list is created upon first use, and
13951 you can update it by calling this command with a double prefix (`C-u C-u').
13952 FIXME: Can we find a better way of updating?
13954 At the target location, the entry is filed as a subitem of the target heading.
13955 Depending on `org-reverse-note-order', the new subitem will either be the
13956 first of the last subitem.
13958 With prefix are GOTO, the command will only visit the target location,
13959 not actually move anything.
13960 With a double prefix `C-c C-c', go to the location where the last refiling
13961 operation has put the subtree.
13963 With a double prefix argument, the command can be used to jump to any
13964 heading in the current buffer."
13965 (interactive "P")
13966 (let* ((cbuf (current-buffer))
13967 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13968 (fname (and filename (file-truename filename)))
13969 pos it nbuf file re level reversed)
13970 (if (equal goto '(16))
13971 (org-refile-goto-last-stored)
13972 (when (setq it (org-refile-get-location
13973 (if goto "Goto: " "Refile to: ") default-buffer))
13974 (setq file (nth 1 it)
13975 re (nth 2 it)
13976 pos (nth 3 it))
13977 (setq nbuf (or (find-buffer-visiting file)
13978 (find-file-noselect file)))
13979 (if goto
13980 (progn
13981 (switch-to-buffer nbuf)
13982 (goto-char pos)
13983 (org-show-context 'org-goto))
13984 (org-copy-special)
13985 (save-excursion
13986 (set-buffer (setq nbuf (or (find-buffer-visiting file)
13987 (find-file-noselect file))))
13988 (setq reversed (org-notes-order-reversed-p))
13989 (save-excursion
13990 (save-restriction
13991 (widen)
13992 (goto-char pos)
13993 (looking-at outline-regexp)
13994 (setq level (org-get-legal-level (funcall outline-level) 1))
13995 (goto-char (or (save-excursion
13996 (if reversed
13997 (outline-next-heading)
13998 (outline-get-next-sibling)))
13999 (point-max)))
14000 (bookmark-set "org-refile-last-stored")
14001 (org-paste-subtree level))))
14002 (org-cut-special)
14003 (message "Entry refiled to \"%s\"" (car it)))))))
14005 (defun org-refile-goto-last-stored ()
14006 "Go to the location where the last refile was stored."
14007 (interactive)
14008 (bookmark-jump "org-refile-last-stored")
14009 (message "This is the location of the last refile"))
14011 (defun org-refile-get-location (&optional prompt default-buffer)
14012 "Prompt the user for a refile location, using PROMPT."
14013 (let ((org-refile-targets org-refile-targets)
14014 (org-refile-use-outline-path org-refile-use-outline-path))
14015 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14016 (unless org-refile-target-table
14017 (error "No refile targets"))
14018 (let* ((cbuf (current-buffer))
14019 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14020 (fname (and filename (file-truename filename)))
14021 (tbl (mapcar
14022 (lambda (x)
14023 (if (not (equal fname (file-truename (nth 1 x))))
14024 (cons (concat (car x) " (" (file-name-nondirectory
14025 (nth 1 x)) ")")
14026 (cdr x))
14028 org-refile-target-table))
14029 (completion-ignore-case t)
14030 pos it nbuf file re level reversed)
14031 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14032 tbl)))
14034 ;;;; Dynamic blocks
14036 (defun org-find-dblock (name)
14037 "Find the first dynamic block with name NAME in the buffer.
14038 If not found, stay at current position and return nil."
14039 (let (pos)
14040 (save-excursion
14041 (goto-char (point-min))
14042 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14043 nil t)
14044 (match-beginning 0))))
14045 (if pos (goto-char pos))
14046 pos))
14048 (defconst org-dblock-start-re
14049 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14050 "Matches the startline of a dynamic block, with parameters.")
14052 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14053 "Matches the end of a dyhamic block.")
14055 (defun org-create-dblock (plist)
14056 "Create a dynamic block section, with parameters taken from PLIST.
14057 PLIST must containe a :name entry which is used as name of the block."
14058 (unless (bolp) (newline))
14059 (let ((name (plist-get plist :name)))
14060 (insert "#+BEGIN: " name)
14061 (while plist
14062 (if (eq (car plist) :name)
14063 (setq plist (cddr plist))
14064 (insert " " (prin1-to-string (pop plist)))))
14065 (insert "\n\n#+END:\n")
14066 (beginning-of-line -2)))
14068 (defun org-prepare-dblock ()
14069 "Prepare dynamic block for refresh.
14070 This empties the block, puts the cursor at the insert position and returns
14071 the property list including an extra property :name with the block name."
14072 (unless (looking-at org-dblock-start-re)
14073 (error "Not at a dynamic block"))
14074 (let* ((begdel (1+ (match-end 0)))
14075 (name (org-no-properties (match-string 1)))
14076 (params (append (list :name name)
14077 (read (concat "(" (match-string 3) ")")))))
14078 (unless (re-search-forward org-dblock-end-re nil t)
14079 (error "Dynamic block not terminated"))
14080 (delete-region begdel (match-beginning 0))
14081 (goto-char begdel)
14082 (open-line 1)
14083 params))
14085 (defun org-map-dblocks (&optional command)
14086 "Apply COMMAND to all dynamic blocks in the current buffer.
14087 If COMMAND is not given, use `org-update-dblock'."
14088 (let ((cmd (or command 'org-update-dblock))
14089 pos)
14090 (save-excursion
14091 (goto-char (point-min))
14092 (while (re-search-forward org-dblock-start-re nil t)
14093 (goto-char (setq pos (match-beginning 0)))
14094 (condition-case nil
14095 (funcall cmd)
14096 (error (message "Error during update of dynamic block")))
14097 (goto-char pos)
14098 (unless (re-search-forward org-dblock-end-re nil t)
14099 (error "Dynamic block not terminated"))))))
14101 (defun org-dblock-update (&optional arg)
14102 "User command for updating dynamic blocks.
14103 Update the dynamic block at point. With prefix ARG, update all dynamic
14104 blocks in the buffer."
14105 (interactive "P")
14106 (if arg
14107 (org-update-all-dblocks)
14108 (or (looking-at org-dblock-start-re)
14109 (org-beginning-of-dblock))
14110 (org-update-dblock)))
14112 (defun org-update-dblock ()
14113 "Update the dynamic block at point
14114 This means to empty the block, parse for parameters and then call
14115 the correct writing function."
14116 (save-window-excursion
14117 (let* ((pos (point))
14118 (line (org-current-line))
14119 (params (org-prepare-dblock))
14120 (name (plist-get params :name))
14121 (cmd (intern (concat "org-dblock-write:" name))))
14122 (message "Updating dynamic block `%s' at line %d..." name line)
14123 (funcall cmd params)
14124 (message "Updating dynamic block `%s' at line %d...done" name line)
14125 (goto-char pos))))
14127 (defun org-beginning-of-dblock ()
14128 "Find the beginning of the dynamic block at point.
14129 Error if there is no scuh block at point."
14130 (let ((pos (point))
14131 beg)
14132 (end-of-line 1)
14133 (if (and (re-search-backward org-dblock-start-re nil t)
14134 (setq beg (match-beginning 0))
14135 (re-search-forward org-dblock-end-re nil t)
14136 (> (match-end 0) pos))
14137 (goto-char beg)
14138 (goto-char pos)
14139 (error "Not in a dynamic block"))))
14141 (defun org-update-all-dblocks ()
14142 "Update all dynamic blocks in the buffer.
14143 This function can be used in a hook."
14144 (when (org-mode-p)
14145 (org-map-dblocks 'org-update-dblock)))
14148 ;;;; Completion
14150 (defconst org-additional-option-like-keywords
14151 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14152 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14153 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14155 (defun org-complete (&optional arg)
14156 "Perform completion on word at point.
14157 At the beginning of a headline, this completes TODO keywords as given in
14158 `org-todo-keywords'.
14159 If the current word is preceded by a backslash, completes the TeX symbols
14160 that are supported for HTML support.
14161 If the current word is preceded by \"#+\", completes special words for
14162 setting file options.
14163 In the line after \"#+STARTUP:, complete valid keywords.\"
14164 At all other locations, this simply calls the value of
14165 `org-completion-fallback-command'."
14166 (interactive "P")
14167 (org-without-partial-completion
14168 (catch 'exit
14169 (let* ((end (point))
14170 (beg1 (save-excursion
14171 (skip-chars-backward (org-re "[:alnum:]_@"))
14172 (point)))
14173 (beg (save-excursion
14174 (skip-chars-backward "a-zA-Z0-9_:$")
14175 (point)))
14176 (confirm (lambda (x) (stringp (car x))))
14177 (searchhead (equal (char-before beg) ?*))
14178 (tag (and (equal (char-before beg1) ?:)
14179 (equal (char-after (point-at-bol)) ?*)))
14180 (prop (and (equal (char-before beg1) ?:)
14181 (not (equal (char-after (point-at-bol)) ?*))))
14182 (texp (equal (char-before beg) ?\\))
14183 (link (equal (char-before beg) ?\[))
14184 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14185 beg)
14186 "#+"))
14187 (startup (string-match "^#\\+STARTUP:.*"
14188 (buffer-substring (point-at-bol) (point))))
14189 (completion-ignore-case opt)
14190 (type nil)
14191 (tbl nil)
14192 (table (cond
14193 (opt
14194 (setq type :opt)
14195 (append
14196 (mapcar
14197 (lambda (x)
14198 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14199 (cons (match-string 2 x) (match-string 1 x)))
14200 (org-split-string (org-get-current-options) "\n"))
14201 (mapcar 'list org-additional-option-like-keywords)))
14202 (startup
14203 (setq type :startup)
14204 org-startup-options)
14205 (link (append org-link-abbrev-alist-local
14206 org-link-abbrev-alist))
14207 (texp
14208 (setq type :tex)
14209 org-html-entities)
14210 ((string-match "\\`\\*+[ \t]+\\'"
14211 (buffer-substring (point-at-bol) beg))
14212 (setq type :todo)
14213 (mapcar 'list org-todo-keywords-1))
14214 (searchhead
14215 (setq type :searchhead)
14216 (save-excursion
14217 (goto-char (point-min))
14218 (while (re-search-forward org-todo-line-regexp nil t)
14219 (push (list
14220 (org-make-org-heading-search-string
14221 (match-string 3) t))
14222 tbl)))
14223 tbl)
14224 (tag (setq type :tag beg beg1)
14225 (or org-tag-alist (org-get-buffer-tags)))
14226 (prop (setq type :prop beg beg1)
14227 (mapcar 'list (org-buffer-property-keys)))
14228 (t (progn
14229 (call-interactively org-completion-fallback-command)
14230 (throw 'exit nil)))))
14231 (pattern (buffer-substring-no-properties beg end))
14232 (completion (try-completion pattern table confirm)))
14233 (cond ((eq completion t)
14234 (if (not (assoc (upcase pattern) table))
14235 (message "Already complete")
14236 (if (equal type :opt)
14237 (insert (substring (cdr (assoc (upcase pattern) table))
14238 (length pattern)))
14239 (if (memq type '(:tag :prop)) (insert ":")))))
14240 ((null completion)
14241 (message "Can't find completion for \"%s\"" pattern)
14242 (ding))
14243 ((not (string= pattern completion))
14244 (delete-region beg end)
14245 (if (string-match " +$" completion)
14246 (setq completion (replace-match "" t t completion)))
14247 (insert completion)
14248 (if (get-buffer-window "*Completions*")
14249 (delete-window (get-buffer-window "*Completions*")))
14250 (if (assoc completion table)
14251 (if (eq type :todo) (insert " ")
14252 (if (memq type '(:tag :prop)) (insert ":"))))
14253 (if (and (equal type :opt) (assoc completion table))
14254 (message "%s" (substitute-command-keys
14255 "Press \\[org-complete] again to insert example settings"))))
14257 (message "Making completion list...")
14258 (let ((list (sort (all-completions pattern table confirm)
14259 'string<)))
14260 (with-output-to-temp-buffer "*Completions*"
14261 (condition-case nil
14262 ;; Protection needed for XEmacs and emacs 21
14263 (display-completion-list list pattern)
14264 (error (display-completion-list list)))))
14265 (message "Making completion list...%s" "done")))))))
14267 ;;;; TODO, DEADLINE, Comments
14269 (defun org-toggle-comment ()
14270 "Change the COMMENT state of an entry."
14271 (interactive)
14272 (save-excursion
14273 (org-back-to-heading)
14274 (let (case-fold-search)
14275 (if (looking-at (concat outline-regexp
14276 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14277 (replace-match "" t t nil 1)
14278 (if (looking-at outline-regexp)
14279 (progn
14280 (goto-char (match-end 0))
14281 (insert org-comment-string " ")))))))
14283 (defvar org-last-todo-state-is-todo nil
14284 "This is non-nil when the last TODO state change led to a TODO state.
14285 If the last change removed the TODO tag or switched to DONE, then
14286 this is nil.")
14288 (defvar org-setting-tags nil) ; dynamically skiped
14290 ;; FIXME: better place
14291 (defun org-property-or-variable-value (var &optional inherit)
14292 "Check if there is a property fixing the value of VAR.
14293 If yes, return this value. If not, return the current value of the variable."
14294 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14295 (if (and prop (stringp prop) (string-match "\\S-" prop))
14296 (read prop)
14297 (symbol-value var))))
14299 (defun org-parse-local-options (string var)
14300 "Parse STRING for startup setting relevant for variable VAR."
14301 (let ((rtn (symbol-value var))
14302 e opts)
14303 (save-match-data
14304 (if (or (not string) (not (string-match "\\S-" string)))
14306 (setq opts (delq nil (mapcar (lambda (x)
14307 (setq e (assoc x org-startup-options))
14308 (if (eq (nth 1 e) var) e nil))
14309 (org-split-string string "[ \t]+"))))
14310 (if (not opts)
14312 (setq rtn nil)
14313 (while (setq e (pop opts))
14314 (if (not (nth 3 e))
14315 (setq rtn (nth 2 e))
14316 (if (not (listp rtn)) (setq rtn nil))
14317 (push (nth 2 e) rtn)))
14318 rtn)))))
14320 (defvar org-blocker-hook nil
14321 "Hook for functions that are allowed to block a state change.
14323 Each function gets as its single argument a property list, see
14324 `org-trigger-hook' for more information about this list.
14326 If any of the functions in this hook returns nil, the state change
14327 is blocked.")
14329 (defvar org-trigger-hook nil
14330 "Hook for functions that are triggered by a state change.
14332 Each function gets as its single argument a property list with at least
14333 the following elements:
14335 (:type type-of-change :position pos-at-entry-start
14336 :from old-state :to new-state)
14338 Depending on the type, more properties may be present.
14340 This mechanism is currently implemented for:
14342 TODO state changes
14343 ------------------
14344 :type todo-state-change
14345 :from previous state (keyword as a string), or nil
14346 :to new state (keyword as a string), or nil")
14349 (defun org-todo (&optional arg)
14350 "Change the TODO state of an item.
14351 The state of an item is given by a keyword at the start of the heading,
14352 like
14353 *** TODO Write paper
14354 *** DONE Call mom
14356 The different keywords are specified in the variable `org-todo-keywords'.
14357 By default the available states are \"TODO\" and \"DONE\".
14358 So for this example: when the item starts with TODO, it is changed to DONE.
14359 When it starts with DONE, the DONE is removed. And when neither TODO nor
14360 DONE are present, add TODO at the beginning of the heading.
14362 With C-u prefix arg, use completion to determine the new state.
14363 With numeric prefix arg, switch to that state.
14365 For calling through lisp, arg is also interpreted in the following way:
14366 'none -> empty state
14367 \"\"(empty string) -> switch to empty state
14368 'done -> switch to DONE
14369 'nextset -> switch to the next set of keywords
14370 'previousset -> switch to the previous set of keywords
14371 \"WAITING\" -> switch to the specified keyword, but only if it
14372 really is a member of `org-todo-keywords'."
14373 (interactive "P")
14374 (save-excursion
14375 (catch 'exit
14376 (org-back-to-heading)
14377 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14378 (or (looking-at (concat " +" org-todo-regexp " *"))
14379 (looking-at " *"))
14380 (let* ((match-data (match-data))
14381 (startpos (point-at-bol))
14382 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14383 (org-log-done (org-parse-local-options logging 'org-log-done))
14384 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
14385 (this (match-string 1))
14386 (hl-pos (match-beginning 0))
14387 (head (org-get-todo-sequence-head this))
14388 (ass (assoc head org-todo-kwd-alist))
14389 (interpret (nth 1 ass))
14390 (done-word (nth 3 ass))
14391 (final-done-word (nth 4 ass))
14392 (last-state (or this ""))
14393 (completion-ignore-case t)
14394 (member (member this org-todo-keywords-1))
14395 (tail (cdr member))
14396 (state (cond
14397 ((and org-todo-key-trigger
14398 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14399 (and (not arg) org-use-fast-todo-selection
14400 (not (eq org-use-fast-todo-selection 'prefix)))))
14401 ;; Use fast selection
14402 (org-fast-todo-selection))
14403 ((and (equal arg '(4))
14404 (or (not org-use-fast-todo-selection)
14405 (not org-todo-key-trigger)))
14406 ;; Read a state with completion
14407 (completing-read "State: " (mapcar (lambda(x) (list x))
14408 org-todo-keywords-1)
14409 nil t))
14410 ((eq arg 'right)
14411 (if this
14412 (if tail (car tail) nil)
14413 (car org-todo-keywords-1)))
14414 ((eq arg 'left)
14415 (if (equal member org-todo-keywords-1)
14417 (if this
14418 (nth (- (length org-todo-keywords-1) (length tail) 2)
14419 org-todo-keywords-1)
14420 (org-last org-todo-keywords-1))))
14421 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14422 (setq arg nil))) ; hack to fall back to cycling
14423 (arg
14424 ;; user or caller requests a specific state
14425 (cond
14426 ((equal arg "") nil)
14427 ((eq arg 'none) nil)
14428 ((eq arg 'done) (or done-word (car org-done-keywords)))
14429 ((eq arg 'nextset)
14430 (or (car (cdr (member head org-todo-heads)))
14431 (car org-todo-heads)))
14432 ((eq arg 'previousset)
14433 (let ((org-todo-heads (reverse org-todo-heads)))
14434 (or (car (cdr (member head org-todo-heads)))
14435 (car org-todo-heads))))
14436 ((car (member arg org-todo-keywords-1)))
14437 ((nth (1- (prefix-numeric-value arg))
14438 org-todo-keywords-1))))
14439 ((null member) (or head (car org-todo-keywords-1)))
14440 ((equal this final-done-word) nil) ;; -> make empty
14441 ((null tail) nil) ;; -> first entry
14442 ((eq interpret 'sequence)
14443 (car tail))
14444 ((memq interpret '(type priority))
14445 (if (eq this-command last-command)
14446 (car tail)
14447 (if (> (length tail) 0)
14448 (or done-word (car org-done-keywords))
14449 nil)))
14450 (t nil)))
14451 (next (if state (concat " " state " ") " "))
14452 (change-plist (list :type 'todo-state-change :from this :to state
14453 :position startpos))
14454 dostates)
14455 (when org-blocker-hook
14456 (unless (save-excursion
14457 (save-match-data
14458 (run-hook-with-args-until-failure
14459 'org-blocker-hook change-plist)))
14460 (if (interactive-p)
14461 (error "TODO state change from %s to %s blocked" this state)
14462 ;; fail silently
14463 (message "TODO state change from %s to %s blocked" this state)
14464 (throw 'exit nil))))
14465 (store-match-data match-data)
14466 (replace-match next t t)
14467 (unless (pos-visible-in-window-p hl-pos)
14468 (message "TODO state changed to %s" (org-trim next)))
14469 (unless head
14470 (setq head (org-get-todo-sequence-head state)
14471 ass (assoc head org-todo-kwd-alist)
14472 interpret (nth 1 ass)
14473 done-word (nth 3 ass)
14474 final-done-word (nth 4 ass)))
14475 (when (memq arg '(nextset previousset))
14476 (message "Keyword-Set %d/%d: %s"
14477 (- (length org-todo-sets) -1
14478 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14479 (length org-todo-sets)
14480 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14481 (setq org-last-todo-state-is-todo
14482 (not (member state org-done-keywords)))
14483 (when (and org-log-done (not (memq arg '(nextset previousset))))
14484 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14485 (or (not org-todo-log-states)
14486 (member state org-todo-log-states))))
14488 (cond
14489 ((and state (member state org-not-done-keywords)
14490 (not (member this org-not-done-keywords)))
14491 ;; This is now a todo state and was not one before
14492 ;; Remove any CLOSED timestamp, and possibly log the state change
14493 (org-add-planning-info nil nil 'closed)
14494 (and dostates (org-add-log-maybe 'state state 'findpos)))
14495 ((and state dostates)
14496 ;; This is a non-nil state, and we need to log it
14497 (org-add-log-maybe 'state state 'findpos))
14498 ((and (member state org-done-keywords)
14499 (not (member this org-done-keywords)))
14500 ;; It is now done, and it was not done before
14501 (org-add-planning-info 'closed (org-current-time))
14502 (org-add-log-maybe 'done state 'findpos))))
14503 ;; Fixup tag positioning
14504 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14505 (run-hooks 'org-after-todo-state-change-hook)
14506 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14507 (if (and arg (not (member state org-done-keywords)))
14508 (setq head (org-get-todo-sequence-head state)))
14509 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14510 ;; Fixup cursor location if close to the keyword
14511 (if (and (outline-on-heading-p)
14512 (not (bolp))
14513 (save-excursion (beginning-of-line 1)
14514 (looking-at org-todo-line-regexp))
14515 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14516 (progn
14517 (goto-char (or (match-end 2) (match-end 1)))
14518 (just-one-space)))
14519 (when org-trigger-hook
14520 (save-excursion
14521 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14523 (defun org-get-todo-sequence-head (kwd)
14524 "Return the head of the TODO sequence to which KWD belongs.
14525 If KWD is not set, check if there is a text property remembering the
14526 right sequence."
14527 (let (p)
14528 (cond
14529 ((not kwd)
14530 (or (get-text-property (point-at-bol) 'org-todo-head)
14531 (progn
14532 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14533 nil (point-at-eol)))
14534 (get-text-property p 'org-todo-head))))
14535 ((not (member kwd org-todo-keywords-1))
14536 (car org-todo-keywords-1))
14537 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14539 (defun org-fast-todo-selection ()
14540 "Fast TODO keyword selection with single keys.
14541 Returns the new TODO keyword, or nil if no state change should occur."
14542 (let* ((fulltable org-todo-key-alist)
14543 (done-keywords org-done-keywords) ;; needed for the faces.
14544 (maxlen (apply 'max (mapcar
14545 (lambda (x)
14546 (if (stringp (car x)) (string-width (car x)) 0))
14547 fulltable)))
14548 (expert nil)
14549 (fwidth (+ maxlen 3 1 3))
14550 (ncol (/ (- (window-width) 4) fwidth))
14551 tg cnt e c tbl
14552 groups ingroup)
14553 (save-window-excursion
14554 (if expert
14555 (set-buffer (get-buffer-create " *Org todo*"))
14556 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14557 (erase-buffer)
14558 (org-set-local 'org-done-keywords done-keywords)
14559 (setq tbl fulltable cnt 0)
14560 (while (setq e (pop tbl))
14561 (cond
14562 ((equal e '(:startgroup))
14563 (push '() groups) (setq ingroup t)
14564 (when (not (= cnt 0))
14565 (setq cnt 0)
14566 (insert "\n"))
14567 (insert "{ "))
14568 ((equal e '(:endgroup))
14569 (setq ingroup nil cnt 0)
14570 (insert "}\n"))
14572 (setq tg (car e) c (cdr e))
14573 (if ingroup (push tg (car groups)))
14574 (setq tg (org-add-props tg nil 'face
14575 (org-get-todo-face tg)))
14576 (if (and (= cnt 0) (not ingroup)) (insert " "))
14577 (insert "[" c "] " tg (make-string
14578 (- fwidth 4 (length tg)) ?\ ))
14579 (when (= (setq cnt (1+ cnt)) ncol)
14580 (insert "\n")
14581 (if ingroup (insert " "))
14582 (setq cnt 0)))))
14583 (insert "\n")
14584 (goto-char (point-min))
14585 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14586 (fit-window-to-buffer))
14587 (message "[a-z..]:Set [SPC]:clear")
14588 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14589 (cond
14590 ((or (= c ?\C-g)
14591 (and (= c ?q) (not (rassoc c fulltable))))
14592 (setq quit-flag t))
14593 ((= c ?\ ) nil)
14594 ((setq e (rassoc c fulltable) tg (car e))
14596 (t (setq quit-flag t))))))
14598 (defun org-get-repeat ()
14599 "Check if tere is a deadline/schedule with repeater in this entry."
14600 (save-match-data
14601 (save-excursion
14602 (org-back-to-heading t)
14603 (if (re-search-forward
14604 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14605 (match-string 1)))))
14607 (defvar org-last-changed-timestamp)
14608 (defvar org-log-post-message)
14609 (defun org-auto-repeat-maybe ()
14610 "Check if the current headline contains a repeated deadline/schedule.
14611 If yes, set TODO state back to what it was and change the base date
14612 of repeating deadline/scheduled time stamps to new date.
14613 This function should be run in the `org-after-todo-state-change-hook'."
14614 ;; last-state is dynamically scoped into this function
14615 (let* ((repeat (org-get-repeat))
14616 (aa (assoc last-state org-todo-kwd-alist))
14617 (interpret (nth 1 aa))
14618 (head (nth 2 aa))
14619 (done-word (nth 3 aa))
14620 (whata '(("d" . day) ("m" . month) ("y" . year)))
14621 (msg "Entry repeats: ")
14622 (org-log-done)
14623 re type n what ts)
14624 (when repeat
14625 (org-todo (if (eq interpret 'type) last-state head))
14626 (when (and org-log-repeat
14627 (not (memq 'org-add-log-note
14628 (default-value 'post-command-hook))))
14629 ;; Make sure a note is taken
14630 (let ((org-log-done '(done)))
14631 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14632 'findpos)))
14633 (org-back-to-heading t)
14634 (org-add-planning-info nil nil 'closed)
14635 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14636 org-deadline-time-regexp "\\)\\|\\("
14637 org-ts-regexp "\\)"))
14638 (while (re-search-forward
14639 re (save-excursion (outline-next-heading) (point)) t)
14640 (setq type (if (match-end 1) org-scheduled-string
14641 (if (match-end 3) org-deadline-string "Plain:"))
14642 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14643 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14644 (setq n (string-to-number (match-string 1 ts))
14645 what (match-string 2 ts))
14646 (if (equal what "w") (setq n (* n 7) what "d"))
14647 (org-timestamp-change n (cdr (assoc what whata)))
14648 (setq msg (concat msg type org-last-changed-timestamp " "))))
14649 (setq org-log-post-message msg)
14650 (message "%s" msg))))
14652 (defun org-show-todo-tree (arg)
14653 "Make a compact tree which shows all headlines marked with TODO.
14654 The tree will show the lines where the regexp matches, and all higher
14655 headlines above the match.
14656 With \\[universal-argument] prefix, also show the DONE entries.
14657 With a numeric prefix N, construct a sparse tree for the Nth element
14658 of `org-todo-keywords-1'."
14659 (interactive "P")
14660 (let ((case-fold-search nil)
14661 (kwd-re
14662 (cond ((null arg) org-not-done-regexp)
14663 ((equal arg '(4))
14664 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14665 (mapcar 'list org-todo-keywords-1))))
14666 (concat "\\("
14667 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14668 "\\)\\>")))
14669 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14670 (regexp-quote (nth (1- (prefix-numeric-value arg))
14671 org-todo-keywords-1)))
14672 (t (error "Invalid prefix argument: %s" arg)))))
14673 (message "%d TODO entries found"
14674 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14676 (defun org-deadline (&optional remove)
14677 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14678 With argument REMOVE, remove any deadline from the item."
14679 (interactive "P")
14680 (if remove
14681 (progn
14682 (org-add-planning-info nil nil 'deadline)
14683 (message "Item no longer has a deadline."))
14684 (org-add-planning-info 'deadline nil 'closed)))
14686 (defun org-schedule (&optional remove)
14687 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14688 With argument REMOVE, remove any scheduling date from the item."
14689 (interactive "P")
14690 (if remove
14691 (progn
14692 (org-add-planning-info nil nil 'scheduled)
14693 (message "Item is no longer scheduled."))
14694 (org-add-planning-info 'scheduled nil 'closed)))
14696 (defun org-add-planning-info (what &optional time &rest remove)
14697 "Insert new timestamp with keyword in the line directly after the headline.
14698 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14699 If non is given, the user is prompted for a date.
14700 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14701 be removed."
14702 (interactive)
14703 (let (org-time-was-given org-end-time-was-given)
14704 (when what (setq time (or time (org-read-date nil 'to-time))))
14705 (when (and org-insert-labeled-timestamps-at-point
14706 (member what '(scheduled deadline)))
14707 (insert
14708 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14709 (org-insert-time-stamp time org-time-was-given
14710 nil nil nil (list org-end-time-was-given))
14711 (setq what nil))
14712 (save-excursion
14713 (save-restriction
14714 (let (col list elt ts buffer-invisibility-spec)
14715 (org-back-to-heading t)
14716 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14717 (goto-char (match-end 1))
14718 (setq col (current-column))
14719 (goto-char (match-end 0))
14720 (if (eobp) (insert "\n") (forward-char 1))
14721 (if (and (not (looking-at outline-regexp))
14722 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14723 "[^\r\n]*"))
14724 (not (equal (match-string 1) org-clock-string)))
14725 (narrow-to-region (match-beginning 0) (match-end 0))
14726 (insert-before-markers "\n")
14727 (backward-char 1)
14728 (narrow-to-region (point) (point))
14729 (indent-to-column col))
14730 ;; Check if we have to remove something.
14731 (setq list (cons what remove))
14732 (while list
14733 (setq elt (pop list))
14734 (goto-char (point-min))
14735 (when (or (and (eq elt 'scheduled)
14736 (re-search-forward org-scheduled-time-regexp nil t))
14737 (and (eq elt 'deadline)
14738 (re-search-forward org-deadline-time-regexp nil t))
14739 (and (eq elt 'closed)
14740 (re-search-forward org-closed-time-regexp nil t)))
14741 (replace-match "")
14742 (if (looking-at "--+<[^>]+>") (replace-match ""))
14743 (if (looking-at " +") (replace-match ""))))
14744 (goto-char (point-max))
14745 (when what
14746 (insert
14747 (if (not (equal (char-before) ?\ )) " " "")
14748 (cond ((eq what 'scheduled) org-scheduled-string)
14749 ((eq what 'deadline) org-deadline-string)
14750 ((eq what 'closed) org-closed-string))
14751 " ")
14752 (setq ts (org-insert-time-stamp
14753 time
14754 (or org-time-was-given
14755 (and (eq what 'closed) org-log-done-with-time))
14756 (eq what 'closed)
14757 nil nil (list org-end-time-was-given)))
14758 (end-of-line 1))
14759 (goto-char (point-min))
14760 (widen)
14761 (if (looking-at "[ \t]+\r?\n")
14762 (replace-match ""))
14763 ts)))))
14765 (defvar org-log-note-marker (make-marker))
14766 (defvar org-log-note-purpose nil)
14767 (defvar org-log-note-state nil)
14768 (defvar org-log-note-window-configuration nil)
14769 (defvar org-log-note-return-to (make-marker))
14770 (defvar org-log-post-message nil
14771 "Message to be displayed after a log note has been stored.
14772 The auto-repeater uses this.")
14774 (defun org-add-log-maybe (&optional purpose state findpos)
14775 "Set up the post command hook to take a note."
14776 (save-excursion
14777 (when (and (listp org-log-done)
14778 (memq purpose org-log-done))
14779 (when findpos
14780 (org-back-to-heading t)
14781 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14782 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14783 "[^\r\n]*\\)?"))
14784 (goto-char (match-end 0))
14785 (unless org-log-states-order-reversed
14786 (and (= (char-after) ?\n) (forward-char 1))
14787 (org-skip-over-state-notes)
14788 (skip-chars-backward " \t\n\r")))
14789 (move-marker org-log-note-marker (point))
14790 (setq org-log-note-purpose purpose)
14791 (setq org-log-note-state state)
14792 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14794 (defun org-skip-over-state-notes ()
14795 "Skip past the list of State notes in an entry."
14796 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14797 (while (looking-at "[ \t]*- State")
14798 (condition-case nil
14799 (org-next-item)
14800 (error (org-end-of-item)))))
14802 (defun org-add-log-note (&optional purpose)
14803 "Pop up a window for taking a note, and add this note later at point."
14804 (remove-hook 'post-command-hook 'org-add-log-note)
14805 (setq org-log-note-window-configuration (current-window-configuration))
14806 (delete-other-windows)
14807 (move-marker org-log-note-return-to (point))
14808 (switch-to-buffer (marker-buffer org-log-note-marker))
14809 (goto-char org-log-note-marker)
14810 (org-switch-to-buffer-other-window "*Org Note*")
14811 (erase-buffer)
14812 (let ((org-inhibit-startup t)) (org-mode))
14813 (insert (format "# Insert note for %s.
14814 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14815 (cond
14816 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14817 ((eq org-log-note-purpose 'done) "closed todo item")
14818 ((eq org-log-note-purpose 'state)
14819 (format "state change to \"%s\"" org-log-note-state))
14820 (t (error "This should not happen")))))
14821 (org-set-local 'org-finish-function 'org-store-log-note))
14823 (defun org-store-log-note ()
14824 "Finish taking a log note, and insert it to where it belongs."
14825 (let ((txt (buffer-string))
14826 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14827 lines ind)
14828 (kill-buffer (current-buffer))
14829 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14830 (setq txt (replace-match "" t t txt)))
14831 (if (string-match "\\s-+\\'" txt)
14832 (setq txt (replace-match "" t t txt)))
14833 (setq lines (org-split-string txt "\n"))
14834 (when (and note (string-match "\\S-" note))
14835 (setq note
14836 (org-replace-escapes
14837 note
14838 (list (cons "%u" (user-login-name))
14839 (cons "%U" user-full-name)
14840 (cons "%t" (format-time-string
14841 (org-time-stamp-format 'long 'inactive)
14842 (current-time)))
14843 (cons "%s" (if org-log-note-state
14844 (concat "\"" org-log-note-state "\"")
14845 "")))))
14846 (if lines (setq note (concat note " \\\\")))
14847 (push note lines))
14848 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14849 (when lines
14850 (save-excursion
14851 (set-buffer (marker-buffer org-log-note-marker))
14852 (save-excursion
14853 (goto-char org-log-note-marker)
14854 (move-marker org-log-note-marker nil)
14855 (end-of-line 1)
14856 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14857 (indent-relative nil)
14858 (insert "- " (pop lines))
14859 (org-indent-line-function)
14860 (beginning-of-line 1)
14861 (looking-at "[ \t]*")
14862 (setq ind (concat (match-string 0) " "))
14863 (end-of-line 1)
14864 (while lines (insert "\n" ind (pop lines)))))))
14865 (set-window-configuration org-log-note-window-configuration)
14866 (with-current-buffer (marker-buffer org-log-note-return-to)
14867 (goto-char org-log-note-return-to))
14868 (move-marker org-log-note-return-to nil)
14869 (and org-log-post-message (message "%s" org-log-post-message)))
14871 ;; FIXME: what else would be useful?
14872 ;; - priority
14873 ;; - date
14875 (defun org-sparse-tree (&optional arg)
14876 "Create a sparse tree, prompt for the details.
14877 This command can create sparse trees. You first need to select the type
14878 of match used to create the tree:
14880 t Show entries with a specific TODO keyword.
14881 T Show entries selected by a tags match.
14882 p Enter a property name and its value (both with completion on existing
14883 names/values) and show entries with that property.
14884 r Show entries matching a regular expression
14885 d Show deadlines due within `org-deadline-warning-days'."
14886 (interactive "P")
14887 (let (ans kwd value)
14888 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14889 (setq ans (read-char-exclusive))
14890 (cond
14891 ((equal ans ?d)
14892 (call-interactively 'org-check-deadlines))
14893 ((equal ans ?b)
14894 (call-interactively 'org-check-before-date))
14895 ((equal ans ?t)
14896 (org-show-todo-tree '(4)))
14897 ((equal ans ?T)
14898 (call-interactively 'org-tags-sparse-tree))
14899 ((member ans '(?p ?P))
14900 (setq kwd (completing-read "Property: "
14901 (mapcar 'list (org-buffer-property-keys))))
14902 (setq value (completing-read "Value: "
14903 (mapcar 'list (org-property-values kwd))))
14904 (unless (string-match "\\`{.*}\\'" value)
14905 (setq value (concat "\"" value "\"")))
14906 (org-tags-sparse-tree arg (concat kwd "=" value)))
14907 ((member ans '(?r ?R ?/))
14908 (call-interactively 'org-occur))
14909 (t (error "No such sparse tree command \"%c\"" ans)))))
14911 (defvar org-occur-highlights nil)
14912 (make-variable-buffer-local 'org-occur-highlights)
14914 (defun org-occur (regexp &optional keep-previous callback)
14915 "Make a compact tree which shows all matches of REGEXP.
14916 The tree will show the lines where the regexp matches, and all higher
14917 headlines above the match. It will also show the heading after the match,
14918 to make sure editing the matching entry is easy.
14919 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14920 call to `org-occur' will be kept, to allow stacking of calls to this
14921 command.
14922 If CALLBACK is non-nil, it is a function which is called to confirm
14923 that the match should indeed be shown."
14924 (interactive "sRegexp: \nP")
14925 (or keep-previous (org-remove-occur-highlights nil nil t))
14926 (let ((cnt 0))
14927 (save-excursion
14928 (goto-char (point-min))
14929 (if (or (not keep-previous) ; do not want to keep
14930 (not org-occur-highlights)) ; no previous matches
14931 ;; hide everything
14932 (org-overview))
14933 (while (re-search-forward regexp nil t)
14934 (when (or (not callback)
14935 (save-match-data (funcall callback)))
14936 (setq cnt (1+ cnt))
14937 (when org-highlight-sparse-tree-matches
14938 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14939 (org-show-context 'occur-tree))))
14940 (when org-remove-highlights-with-change
14941 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14942 nil 'local))
14943 (unless org-sparse-tree-open-archived-trees
14944 (org-hide-archived-subtrees (point-min) (point-max)))
14945 (run-hooks 'org-occur-hook)
14946 (if (interactive-p)
14947 (message "%d match(es) for regexp %s" cnt regexp))
14948 cnt))
14950 (defun org-show-context (&optional key)
14951 "Make sure point and context and visible.
14952 How much context is shown depends upon the variables
14953 `org-show-hierarchy-above', `org-show-following-heading'. and
14954 `org-show-siblings'."
14955 (let ((heading-p (org-on-heading-p t))
14956 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14957 (following-p (org-get-alist-option org-show-following-heading key))
14958 (entry-p (org-get-alist-option org-show-entry-below key))
14959 (siblings-p (org-get-alist-option org-show-siblings key)))
14960 (catch 'exit
14961 ;; Show heading or entry text
14962 (if (and heading-p (not entry-p))
14963 (org-flag-heading nil) ; only show the heading
14964 (and (or entry-p (org-invisible-p) (org-invisible-p2))
14965 (org-show-hidden-entry))) ; show entire entry
14966 (when following-p
14967 ;; Show next sibling, or heading below text
14968 (save-excursion
14969 (and (if heading-p (org-goto-sibling) (outline-next-heading))
14970 (org-flag-heading nil))))
14971 (when siblings-p (org-show-siblings))
14972 (when hierarchy-p
14973 ;; show all higher headings, possibly with siblings
14974 (save-excursion
14975 (while (and (condition-case nil
14976 (progn (org-up-heading-all 1) t)
14977 (error nil))
14978 (not (bobp)))
14979 (org-flag-heading nil)
14980 (when siblings-p (org-show-siblings))))))))
14982 (defun org-reveal (&optional siblings)
14983 "Show current entry, hierarchy above it, and the following headline.
14984 This can be used to show a consistent set of context around locations
14985 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14986 not t for the search context.
14988 With optional argument SIBLINGS, on each level of the hierarchy all
14989 siblings are shown. This repairs the tree structure to what it would
14990 look like when opened with hierarchical calls to `org-cycle'."
14991 (interactive "P")
14992 (let ((org-show-hierarchy-above t)
14993 (org-show-following-heading t)
14994 (org-show-siblings (if siblings t org-show-siblings)))
14995 (org-show-context nil)))
14997 (defun org-highlight-new-match (beg end)
14998 "Highlight from BEG to END and mark the highlight is an occur headline."
14999 (let ((ov (org-make-overlay beg end)))
15000 (org-overlay-put ov 'face 'secondary-selection)
15001 (push ov org-occur-highlights)))
15003 (defun org-remove-occur-highlights (&optional beg end noremove)
15004 "Remove the occur highlights from the buffer.
15005 BEG and END are ignored. If NOREMOVE is nil, remove this function
15006 from the `before-change-functions' in the current buffer."
15007 (interactive)
15008 (unless org-inhibit-highlight-removal
15009 (mapc 'org-delete-overlay org-occur-highlights)
15010 (setq org-occur-highlights nil)
15011 (unless noremove
15012 (remove-hook 'before-change-functions
15013 'org-remove-occur-highlights 'local))))
15015 ;;;; Priorities
15017 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15018 "Regular expression matching the priority indicator.")
15020 (defvar org-remove-priority-next-time nil)
15022 (defun org-priority-up ()
15023 "Increase the priority of the current item."
15024 (interactive)
15025 (org-priority 'up))
15027 (defun org-priority-down ()
15028 "Decrease the priority of the current item."
15029 (interactive)
15030 (org-priority 'down))
15032 (defun org-priority (&optional action)
15033 "Change the priority of an item by ARG.
15034 ACTION can be `set', `up', `down', or a character."
15035 (interactive)
15036 (setq action (or action 'set))
15037 (let (current new news have remove)
15038 (save-excursion
15039 (org-back-to-heading)
15040 (if (looking-at org-priority-regexp)
15041 (setq current (string-to-char (match-string 2))
15042 have t)
15043 (setq current org-default-priority))
15044 (cond
15045 ((or (eq action 'set) (integerp action))
15046 (if (integerp action)
15047 (setq new action)
15048 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15049 (setq new (read-char-exclusive)))
15050 (if (and (= (upcase org-highest-priority) org-highest-priority)
15051 (= (upcase org-lowest-priority) org-lowest-priority))
15052 (setq new (upcase new)))
15053 (cond ((equal new ?\ ) (setq remove t))
15054 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15055 (error "Priority must be between `%c' and `%c'"
15056 org-highest-priority org-lowest-priority))))
15057 ((eq action 'up)
15058 (if (and (not have) (eq last-command this-command))
15059 (setq new org-lowest-priority)
15060 (setq new (if (and org-priority-start-cycle-with-default (not have))
15061 org-default-priority (1- current)))))
15062 ((eq action 'down)
15063 (if (and (not have) (eq last-command this-command))
15064 (setq new org-highest-priority)
15065 (setq new (if (and org-priority-start-cycle-with-default (not have))
15066 org-default-priority (1+ current)))))
15067 (t (error "Invalid action")))
15068 (if (or (< (upcase new) org-highest-priority)
15069 (> (upcase new) org-lowest-priority))
15070 (setq remove t))
15071 (setq news (format "%c" new))
15072 (if have
15073 (if remove
15074 (replace-match "" t t nil 1)
15075 (replace-match news t t nil 2))
15076 (if remove
15077 (error "No priority cookie found in line")
15078 (looking-at org-todo-line-regexp)
15079 (if (match-end 2)
15080 (progn
15081 (goto-char (match-end 2))
15082 (insert " [#" news "]"))
15083 (goto-char (match-beginning 3))
15084 (insert "[#" news "] ")))))
15085 (org-preserve-lc (org-set-tags nil 'align))
15086 (if remove
15087 (message "Priority removed")
15088 (message "Priority of current item set to %s" news))))
15091 (defun org-get-priority (s)
15092 "Find priority cookie and return priority."
15093 (save-match-data
15094 (if (not (string-match org-priority-regexp s))
15095 (* 1000 (- org-lowest-priority org-default-priority))
15096 (* 1000 (- org-lowest-priority
15097 (string-to-char (match-string 2 s)))))))
15099 ;;;; Tags
15101 (defun org-scan-tags (action matcher &optional todo-only)
15102 "Scan headline tags with inheritance and produce output ACTION.
15103 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15104 evaluated, testing if a given set of tags qualifies a headline for
15105 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15106 are included in the output."
15107 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15108 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15109 (org-re
15110 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15111 (props (list 'face nil
15112 'done-face 'org-done
15113 'undone-face nil
15114 'mouse-face 'highlight
15115 'org-not-done-regexp org-not-done-regexp
15116 'org-todo-regexp org-todo-regexp
15117 'keymap org-agenda-keymap
15118 'help-echo
15119 (format "mouse-2 or RET jump to org file %s"
15120 (abbreviate-file-name
15121 (or (buffer-file-name (buffer-base-buffer))
15122 (buffer-name (buffer-base-buffer)))))))
15123 (case-fold-search nil)
15124 lspos
15125 tags tags-list tags-alist (llast 0) rtn level category i txt
15126 todo marker entry priority)
15127 (save-excursion
15128 (goto-char (point-min))
15129 (when (eq action 'sparse-tree)
15130 (org-overview)
15131 (org-remove-occur-highlights))
15132 (while (re-search-forward re nil t)
15133 (catch :skip
15134 (setq todo (if (match-end 1) (match-string 2))
15135 tags (if (match-end 4) (match-string 4)))
15136 (goto-char (setq lspos (1+ (match-beginning 0))))
15137 (setq level (org-reduced-level (funcall outline-level))
15138 category (org-get-category))
15139 (setq i llast llast level)
15140 ;; remove tag lists from same and sublevels
15141 (while (>= i level)
15142 (when (setq entry (assoc i tags-alist))
15143 (setq tags-alist (delete entry tags-alist)))
15144 (setq i (1- i)))
15145 ;; add the nex tags
15146 (when tags
15147 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15148 tags-alist
15149 (cons (cons level tags) tags-alist)))
15150 ;; compile tags for current headline
15151 (setq tags-list
15152 (if org-use-tag-inheritance
15153 (apply 'append (mapcar 'cdr tags-alist))
15154 tags))
15155 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15156 (eval matcher)
15157 (or (not org-agenda-skip-archived-trees)
15158 (not (member org-archive-tag tags-list))))
15159 (and (eq action 'agenda) (org-agenda-skip))
15160 ;; list this headline
15162 (if (eq action 'sparse-tree)
15163 (progn
15164 (and org-highlight-sparse-tree-matches
15165 (org-get-heading) (match-end 0)
15166 (org-highlight-new-match
15167 (match-beginning 0) (match-beginning 1)))
15168 (org-show-context 'tags-tree))
15169 (setq txt (org-format-agenda-item
15171 (concat
15172 (if org-tags-match-list-sublevels
15173 (make-string (1- level) ?.) "")
15174 (org-get-heading))
15175 category tags-list)
15176 priority (org-get-priority txt))
15177 (goto-char lspos)
15178 (setq marker (org-agenda-new-marker))
15179 (org-add-props txt props
15180 'org-marker marker 'org-hd-marker marker 'org-category category
15181 'priority priority 'type "tagsmatch")
15182 (push txt rtn))
15183 ;; if we are to skip sublevels, jump to end of subtree
15184 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15185 (when (and (eq action 'sparse-tree)
15186 (not org-sparse-tree-open-archived-trees))
15187 (org-hide-archived-subtrees (point-min) (point-max)))
15188 (nreverse rtn)))
15190 (defvar todo-only) ;; dynamically scoped
15192 (defun org-tags-sparse-tree (&optional todo-only match)
15193 "Create a sparse tree according to tags string MATCH.
15194 MATCH can contain positive and negative selection of tags, like
15195 \"+WORK+URGENT-WITHBOSS\".
15196 If optional argument TODO_ONLY is non-nil, only select lines that are
15197 also TODO lines."
15198 (interactive "P")
15199 (org-prepare-agenda-buffers (list (current-buffer)))
15200 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15202 (defvar org-cached-props nil)
15203 (defun org-cached-entry-get (pom property)
15204 (if (or (eq t org-use-property-inheritance)
15205 (member property org-use-property-inheritance))
15206 ;; Caching is not possible, check it directly
15207 (org-entry-get pom property 'inherit)
15208 ;; Get all properties, so that we can do complicated checks easily
15209 (cdr (assoc property (or org-cached-props
15210 (setq org-cached-props
15211 (org-entry-properties pom)))))))
15213 (defun org-global-tags-completion-table (&optional files)
15214 "Return the list of all tags in all agenda buffer/files."
15215 (save-excursion
15216 (org-uniquify
15217 (delq nil
15218 (apply 'append
15219 (mapcar
15220 (lambda (file)
15221 (set-buffer (find-file-noselect file))
15222 (append (org-get-buffer-tags)
15223 (mapcar (lambda (x) (if (stringp (car-safe x))
15224 (list (car-safe x)) nil))
15225 org-tag-alist)))
15226 (if (and files (car files))
15227 files
15228 (org-agenda-files))))))))
15230 (defun org-make-tags-matcher (match)
15231 "Create the TAGS//TODO matcher form for the selection string MATCH."
15232 ;; todo-only is scoped dynamically into this function, and the function
15233 ;; may change it it the matcher asksk for it.
15234 (unless match
15235 ;; Get a new match request, with completion
15236 (let ((org-last-tags-completion-table
15237 (org-global-tags-completion-table)))
15238 (setq match (completing-read
15239 "Match: " 'org-tags-completion-function nil nil nil
15240 'org-tags-history))))
15242 ;; Parse the string and create a lisp form
15243 (let ((match0 match)
15244 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
15245 minus tag mm
15246 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15247 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15248 (if (string-match "/+" match)
15249 ;; match contains also a todo-matching request
15250 (progn
15251 (setq tagsmatch (substring match 0 (match-beginning 0))
15252 todomatch (substring match (match-end 0)))
15253 (if (string-match "^!" todomatch)
15254 (setq todo-only t todomatch (substring todomatch 1)))
15255 (if (string-match "^\\s-*$" todomatch)
15256 (setq todomatch nil)))
15257 ;; only matching tags
15258 (setq tagsmatch match todomatch nil))
15260 ;; Make the tags matcher
15261 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15262 (setq tagsmatcher t)
15263 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15264 (while (setq term (pop orterms))
15265 (while (and (equal (substring term -1) "\\") orterms)
15266 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15267 (while (string-match re term)
15268 (setq minus (and (match-end 1)
15269 (equal (match-string 1 term) "-"))
15270 tag (match-string 2 term)
15271 re-p (equal (string-to-char tag) ?{)
15272 level-p (match-end 3)
15273 prop-p (match-end 4)
15274 mm (cond
15275 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15276 (level-p `(= level ,(string-to-number
15277 (match-string 3 term))))
15278 (prop-p
15279 (setq pn (match-string 4 term)
15280 pv (match-string 5 term)
15281 cat-p (equal pn "CATEGORY")
15282 re-p (equal (string-to-char pv) ?{)
15283 pv (substring pv 1 -1))
15284 (if (equal pn "CATEGORY")
15285 (setq gv '(get-text-property (point) 'org-category))
15286 (setq gv `(org-cached-entry-get nil ,pn)))
15287 (if re-p
15288 `(string-match ,pv (or ,gv ""))
15289 `(equal ,pv ,gv)))
15290 (t `(member ,(downcase tag) tags-list)))
15291 mm (if minus (list 'not mm) mm)
15292 term (substring term (match-end 0)))
15293 (push mm tagsmatcher))
15294 (push (if (> (length tagsmatcher) 1)
15295 (cons 'and tagsmatcher)
15296 (car tagsmatcher))
15297 orlist)
15298 (setq tagsmatcher nil))
15299 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15300 (setq tagsmatcher
15301 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15303 ;; Make the todo matcher
15304 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15305 (setq todomatcher t)
15306 (setq orterms (org-split-string todomatch "|") orlist nil)
15307 (while (setq term (pop orterms))
15308 (while (string-match re term)
15309 (setq minus (and (match-end 1)
15310 (equal (match-string 1 term) "-"))
15311 kwd (match-string 2 term)
15312 re-p (equal (string-to-char kwd) ?{)
15313 term (substring term (match-end 0))
15314 mm (if re-p
15315 `(string-match ,(substring kwd 1 -1) todo)
15316 (list 'equal 'todo kwd))
15317 mm (if minus (list 'not mm) mm))
15318 (push mm todomatcher))
15319 (push (if (> (length todomatcher) 1)
15320 (cons 'and todomatcher)
15321 (car todomatcher))
15322 orlist)
15323 (setq todomatcher nil))
15324 (setq todomatcher (if (> (length orlist) 1)
15325 (cons 'or orlist) (car orlist))))
15327 ;; Return the string and lisp forms of the matcher
15328 (setq matcher (if todomatcher
15329 (list 'and tagsmatcher todomatcher)
15330 tagsmatcher))
15331 (cons match0 matcher)))
15333 (defun org-match-any-p (re list)
15334 "Does re match any element of list?"
15335 (setq list (mapcar (lambda (x) (string-match re x)) list))
15336 (delq nil list))
15338 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15339 (defvar org-tags-overlay (org-make-overlay 1 1))
15340 (org-detach-overlay org-tags-overlay)
15342 (defun org-align-tags-here (to-col)
15343 ;; Assumes that this is a headline
15344 (let ((pos (point)) (col (current-column)) tags)
15345 (beginning-of-line 1)
15346 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15347 (< pos (match-beginning 2)))
15348 (progn
15349 (setq tags (match-string 2))
15350 (goto-char (match-beginning 1))
15351 (insert " ")
15352 (delete-region (point) (1+ (match-end 0)))
15353 (backward-char 1)
15354 (move-to-column
15355 (max (1+ (current-column))
15356 (1+ col)
15357 (if (> to-col 0)
15358 to-col
15359 (- (abs to-col) (length tags))))
15361 (insert tags)
15362 (move-to-column (min (current-column) col) t))
15363 (goto-char pos))))
15365 (defun org-set-tags (&optional arg just-align)
15366 "Set the tags for the current headline.
15367 With prefix ARG, realign all tags in headings in the current buffer."
15368 (interactive "P")
15369 (let* ((re (concat "^" outline-regexp))
15370 (current (org-get-tags-string))
15371 (col (current-column))
15372 (org-setting-tags t)
15373 table current-tags inherited-tags ; computed below when needed
15374 tags p0 c0 c1 rpl)
15375 (if arg
15376 (save-excursion
15377 (goto-char (point-min))
15378 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15379 (while (re-search-forward re nil t)
15380 (org-set-tags nil t)
15381 (end-of-line 1)))
15382 (message "All tags realigned to column %d" org-tags-column))
15383 (if just-align
15384 (setq tags current)
15385 ;; Get a new set of tags from the user
15386 (save-excursion
15387 (setq table (or org-tag-alist (org-get-buffer-tags))
15388 org-last-tags-completion-table table
15389 current-tags (org-split-string current ":")
15390 inherited-tags (nreverse
15391 (nthcdr (length current-tags)
15392 (nreverse (org-get-tags-at))))
15393 tags
15394 (if (or (eq t org-use-fast-tag-selection)
15395 (and org-use-fast-tag-selection
15396 (delq nil (mapcar 'cdr table))))
15397 (org-fast-tag-selection
15398 current-tags inherited-tags table
15399 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15400 (let ((org-add-colon-after-tag-completion t))
15401 (org-trim
15402 (org-without-partial-completion
15403 (completing-read "Tags: " 'org-tags-completion-function
15404 nil nil current 'org-tags-history)))))))
15405 (while (string-match "[-+&]+" tags)
15406 ;; No boolean logic, just a list
15407 (setq tags (replace-match ":" t t tags))))
15409 (if (string-match "\\`[\t ]*\\'" tags)
15410 (setq tags "")
15411 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15412 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15414 ;; Insert new tags at the correct column
15415 (beginning-of-line 1)
15416 (cond
15417 ((and (equal current "") (equal tags "")))
15418 ((re-search-forward
15419 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15420 (point-at-eol) t)
15421 (if (equal tags "")
15422 (setq rpl "")
15423 (goto-char (match-beginning 0))
15424 (setq c0 (current-column) p0 (point)
15425 c1 (max (1+ c0) (if (> org-tags-column 0)
15426 org-tags-column
15427 (- (- org-tags-column) (length tags))))
15428 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15429 (replace-match rpl t t)
15430 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
15431 tags)
15432 (t (error "Tags alignment failed")))
15433 (move-to-column col)
15434 (unless just-align
15435 (run-hooks 'org-after-tags-change-hook)))))
15437 (defun org-change-tag-in-region (beg end tag off)
15438 "Add or remove TAG for each entry in the region.
15439 This works in the agenda, and also in an org-mode buffer."
15440 (interactive
15441 (list (region-beginning) (region-end)
15442 (let ((org-last-tags-completion-table
15443 (if (org-mode-p)
15444 (org-get-buffer-tags)
15445 (org-global-tags-completion-table))))
15446 (completing-read
15447 "Tag: " 'org-tags-completion-function nil nil nil
15448 'org-tags-history))
15449 (progn
15450 (message "[s]et or [r]emove? ")
15451 (equal (read-char-exclusive) ?r))))
15452 (if (fboundp 'deactivate-mark) (deactivate-mark))
15453 (let ((agendap (equal major-mode 'org-agenda-mode))
15454 l1 l2 m buf pos newhead (cnt 0))
15455 (goto-char end)
15456 (setq l2 (1- (org-current-line)))
15457 (goto-char beg)
15458 (setq l1 (org-current-line))
15459 (loop for l from l1 to l2 do
15460 (goto-line l)
15461 (setq m (get-text-property (point) 'org-hd-marker))
15462 (when (or (and (org-mode-p) (org-on-heading-p))
15463 (and agendap m))
15464 (setq buf (if agendap (marker-buffer m) (current-buffer))
15465 pos (if agendap m (point)))
15466 (with-current-buffer buf
15467 (save-excursion
15468 (save-restriction
15469 (goto-char pos)
15470 (setq cnt (1+ cnt))
15471 (org-toggle-tag tag (if off 'off 'on))
15472 (setq newhead (org-get-heading)))))
15473 (and agendap (org-agenda-change-all-lines newhead m))))
15474 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15476 (defun org-tags-completion-function (string predicate &optional flag)
15477 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15478 (confirm (lambda (x) (stringp (car x)))))
15479 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15480 (setq s1 (match-string 1 string)
15481 s2 (match-string 2 string))
15482 (setq s1 "" s2 string))
15483 (cond
15484 ((eq flag nil)
15485 ;; try completion
15486 (setq rtn (try-completion s2 ctable confirm))
15487 (if (stringp rtn)
15488 (setq rtn
15489 (concat s1 s2 (substring rtn (length s2))
15490 (if (and org-add-colon-after-tag-completion
15491 (assoc rtn ctable))
15492 ":" ""))))
15493 rtn)
15494 ((eq flag t)
15495 ;; all-completions
15496 (all-completions s2 ctable confirm)
15498 ((eq flag 'lambda)
15499 ;; exact match?
15500 (assoc s2 ctable)))
15503 (defun org-fast-tag-insert (kwd tags face &optional end)
15504 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15505 (insert (format "%-12s" (concat kwd ":"))
15506 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15507 (or end "")))
15509 (defun org-fast-tag-show-exit (flag)
15510 (save-excursion
15511 (goto-line 3)
15512 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15513 (replace-match ""))
15514 (when flag
15515 (end-of-line 1)
15516 (move-to-column (- (window-width) 19) t)
15517 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15519 (defun org-set-current-tags-overlay (current prefix)
15520 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15521 (if (featurep 'xemacs)
15522 (org-overlay-display org-tags-overlay (concat prefix s)
15523 'secondary-selection)
15524 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15525 (org-overlay-display org-tags-overlay (concat prefix s)))))
15527 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15528 "Fast tag selection with single keys.
15529 CURRENT is the current list of tags in the headline, INHERITED is the
15530 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15531 possibly with grouping information. TODO-TABLE is a similar table with
15532 TODO keywords, should these have keys assigned to them.
15533 If the keys are nil, a-z are automatically assigned.
15534 Returns the new tags string, or nil to not change the current settings."
15535 (let* ((fulltable (append table todo-table))
15536 (maxlen (apply 'max (mapcar
15537 (lambda (x)
15538 (if (stringp (car x)) (string-width (car x)) 0))
15539 fulltable)))
15540 (buf (current-buffer))
15541 (expert (eq org-fast-tag-selection-single-key 'expert))
15542 (buffer-tags nil)
15543 (fwidth (+ maxlen 3 1 3))
15544 (ncol (/ (- (window-width) 4) fwidth))
15545 (i-face 'org-done)
15546 (c-face 'org-todo)
15547 tg cnt e c char c1 c2 ntable tbl rtn
15548 ov-start ov-end ov-prefix
15549 (exit-after-next org-fast-tag-selection-single-key)
15550 (done-keywords org-done-keywords)
15551 groups ingroup)
15552 (save-excursion
15553 (beginning-of-line 1)
15554 (if (looking-at
15555 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15556 (setq ov-start (match-beginning 1)
15557 ov-end (match-end 1)
15558 ov-prefix "")
15559 (setq ov-start (1- (point-at-eol))
15560 ov-end (1+ ov-start))
15561 (skip-chars-forward "^\n\r")
15562 (setq ov-prefix
15563 (concat
15564 (buffer-substring (1- (point)) (point))
15565 (if (> (current-column) org-tags-column)
15567 (make-string (- org-tags-column (current-column)) ?\ ))))))
15568 (org-move-overlay org-tags-overlay ov-start ov-end)
15569 (save-window-excursion
15570 (if expert
15571 (set-buffer (get-buffer-create " *Org tags*"))
15572 (delete-other-windows)
15573 (split-window-vertically)
15574 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15575 (erase-buffer)
15576 (org-set-local 'org-done-keywords done-keywords)
15577 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15578 (org-fast-tag-insert "Current" current c-face "\n\n")
15579 (org-fast-tag-show-exit exit-after-next)
15580 (org-set-current-tags-overlay current ov-prefix)
15581 (setq tbl fulltable char ?a cnt 0)
15582 (while (setq e (pop tbl))
15583 (cond
15584 ((equal e '(:startgroup))
15585 (push '() groups) (setq ingroup t)
15586 (when (not (= cnt 0))
15587 (setq cnt 0)
15588 (insert "\n"))
15589 (insert "{ "))
15590 ((equal e '(:endgroup))
15591 (setq ingroup nil cnt 0)
15592 (insert "}\n"))
15594 (setq tg (car e) c2 nil)
15595 (if (cdr e)
15596 (setq c (cdr e))
15597 ;; automatically assign a character.
15598 (setq c1 (string-to-char
15599 (downcase (substring
15600 tg (if (= (string-to-char tg) ?@) 1 0)))))
15601 (if (or (rassoc c1 ntable) (rassoc c1 table))
15602 (while (or (rassoc char ntable) (rassoc char table))
15603 (setq char (1+ char)))
15604 (setq c2 c1))
15605 (setq c (or c2 char)))
15606 (if ingroup (push tg (car groups)))
15607 (setq tg (org-add-props tg nil 'face
15608 (cond
15609 ((not (assoc tg table))
15610 (org-get-todo-face tg))
15611 ((member tg current) c-face)
15612 ((member tg inherited) i-face)
15613 (t nil))))
15614 (if (and (= cnt 0) (not ingroup)) (insert " "))
15615 (insert "[" c "] " tg (make-string
15616 (- fwidth 4 (length tg)) ?\ ))
15617 (push (cons tg c) ntable)
15618 (when (= (setq cnt (1+ cnt)) ncol)
15619 (insert "\n")
15620 (if ingroup (insert " "))
15621 (setq cnt 0)))))
15622 (setq ntable (nreverse ntable))
15623 (insert "\n")
15624 (goto-char (point-min))
15625 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15626 (fit-window-to-buffer))
15627 (setq rtn
15628 (catch 'exit
15629 (while t
15630 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15631 (if groups " [!] no groups" " [!]groups")
15632 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15633 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15634 (cond
15635 ((= c ?\r) (throw 'exit t))
15636 ((= c ?!)
15637 (setq groups (not groups))
15638 (goto-char (point-min))
15639 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15640 ((= c ?\C-c)
15641 (if (not expert)
15642 (org-fast-tag-show-exit
15643 (setq exit-after-next (not exit-after-next)))
15644 (setq expert nil)
15645 (delete-other-windows)
15646 (split-window-vertically)
15647 (org-switch-to-buffer-other-window " *Org tags*")
15648 (and (fboundp 'fit-window-to-buffer)
15649 (fit-window-to-buffer))))
15650 ((or (= c ?\C-g)
15651 (and (= c ?q) (not (rassoc c ntable))))
15652 (org-detach-overlay org-tags-overlay)
15653 (setq quit-flag t))
15654 ((= c ?\ )
15655 (setq current nil)
15656 (if exit-after-next (setq exit-after-next 'now)))
15657 ((= c ?\t)
15658 (condition-case nil
15659 (setq tg (completing-read
15660 "Tag: "
15661 (or buffer-tags
15662 (with-current-buffer buf
15663 (org-get-buffer-tags)))))
15664 (quit (setq tg "")))
15665 (when (string-match "\\S-" tg)
15666 (add-to-list 'buffer-tags (list tg))
15667 (if (member tg current)
15668 (setq current (delete tg current))
15669 (push tg current)))
15670 (if exit-after-next (setq exit-after-next 'now)))
15671 ((setq e (rassoc c todo-table) tg (car e))
15672 (with-current-buffer buf
15673 (save-excursion (org-todo tg)))
15674 (if exit-after-next (setq exit-after-next 'now)))
15675 ((setq e (rassoc c ntable) tg (car e))
15676 (if (member tg current)
15677 (setq current (delete tg current))
15678 (loop for g in groups do
15679 (if (member tg g)
15680 (mapc (lambda (x)
15681 (setq current (delete x current)))
15682 g)))
15683 (push tg current))
15684 (if exit-after-next (setq exit-after-next 'now))))
15686 ;; Create a sorted list
15687 (setq current
15688 (sort current
15689 (lambda (a b)
15690 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15691 (if (eq exit-after-next 'now) (throw 'exit t))
15692 (goto-char (point-min))
15693 (beginning-of-line 2)
15694 (delete-region (point) (point-at-eol))
15695 (org-fast-tag-insert "Current" current c-face)
15696 (org-set-current-tags-overlay current ov-prefix)
15697 (while (re-search-forward
15698 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15699 (setq tg (match-string 1))
15700 (add-text-properties
15701 (match-beginning 1) (match-end 1)
15702 (list 'face
15703 (cond
15704 ((member tg current) c-face)
15705 ((member tg inherited) i-face)
15706 (t (get-text-property (match-beginning 1) 'face))))))
15707 (goto-char (point-min)))))
15708 (org-detach-overlay org-tags-overlay)
15709 (if rtn
15710 (mapconcat 'identity current ":")
15711 nil))))
15713 (defun org-get-tags-string ()
15714 "Get the TAGS string in the current headline."
15715 (unless (org-on-heading-p t)
15716 (error "Not on a heading"))
15717 (save-excursion
15718 (beginning-of-line 1)
15719 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15720 (org-match-string-no-properties 1)
15721 "")))
15723 (defun org-get-tags ()
15724 "Get the list of tags specified in the current headline."
15725 (org-split-string (org-get-tags-string) ":"))
15727 (defun org-get-buffer-tags ()
15728 "Get a table of all tags used in the buffer, for completion."
15729 (let (tags)
15730 (save-excursion
15731 (goto-char (point-min))
15732 (while (re-search-forward
15733 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15734 (when (equal (char-after (point-at-bol 0)) ?*)
15735 (mapc (lambda (x) (add-to-list 'tags x))
15736 (org-split-string (org-match-string-no-properties 1) ":")))))
15737 (mapcar 'list tags)))
15740 ;;;; Properties
15742 ;;; Setting and retrieving properties
15744 (defconst org-special-properties
15745 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15746 "TIMESTAMP" "TIMESTAMP_IA")
15747 "The special properties valid in Org-mode.
15749 These are properties that are not defined in the property drawer,
15750 but in some other way.")
15752 (defconst org-default-properties
15753 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15754 "LOCATION" "LOGGING" "COLUMNS")
15755 "Some properties that are used by Org-mode for various purposes.
15756 Being in this list makes sure that they are offered for completion.")
15758 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15759 "Regular expression matching the first line of a property drawer.")
15761 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15762 "Regular expression matching the first line of a property drawer.")
15764 (defun org-property-action ()
15765 "Do an action on properties."
15766 (interactive)
15767 (let (c)
15768 (org-at-property-p)
15769 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15770 (setq c (read-char-exclusive))
15771 (cond
15772 ((equal c ?s)
15773 (call-interactively 'org-set-property))
15774 ((equal c ?d)
15775 (call-interactively 'org-delete-property))
15776 ((equal c ?D)
15777 (call-interactively 'org-delete-property-globally))
15778 ((equal c ?c)
15779 (call-interactively 'org-compute-property-at-point))
15780 (t (error "No such property action %c" c)))))
15782 (defun org-at-property-p ()
15783 "Is the cursor in a property line?"
15784 ;; FIXME: Does not check if we are actually in the drawer.
15785 ;; FIXME: also returns true on any drawers.....
15786 ;; This is used by C-c C-c for property action.
15787 (save-excursion
15788 (beginning-of-line 1)
15789 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15791 (defmacro org-with-point-at (pom &rest body)
15792 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15793 (declare (indent 1) (debug t))
15794 `(save-excursion
15795 (if (markerp pom) (set-buffer (marker-buffer pom)))
15796 (save-excursion
15797 (goto-char (or pom (point)))
15798 ,@body)))
15800 (defun org-get-property-block (&optional beg end force)
15801 "Return the (beg . end) range of the body of the property drawer.
15802 BEG and END can be beginning and end of subtree, if not given
15803 they will be found.
15804 If the drawer does not exist and FORCE is non-nil, create the drawer."
15805 (catch 'exit
15806 (save-excursion
15807 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15808 (end (or end (progn (outline-next-heading) (point)))))
15809 (goto-char beg)
15810 (if (re-search-forward org-property-start-re end t)
15811 (setq beg (1+ (match-end 0)))
15812 (if force
15813 (save-excursion
15814 (org-insert-property-drawer)
15815 (setq end (progn (outline-next-heading) (point))))
15816 (throw 'exit nil))
15817 (goto-char beg)
15818 (if (re-search-forward org-property-start-re end t)
15819 (setq beg (1+ (match-end 0)))))
15820 (if (re-search-forward org-property-end-re end t)
15821 (setq end (match-beginning 0))
15822 (or force (throw 'exit nil))
15823 (goto-char beg)
15824 (setq end beg)
15825 (org-indent-line-function)
15826 (insert ":END:\n"))
15827 (cons beg end)))))
15829 (defun org-entry-properties (&optional pom which)
15830 "Get all properties of the entry at point-or-marker POM.
15831 This includes the TODO keyword, the tags, time strings for deadline,
15832 scheduled, and clocking, and any additional properties defined in the
15833 entry. The return value is an alist, keys may occur multiple times
15834 if the property key was used several times.
15835 POM may also be nil, in which case the current entry is used.
15836 If WHICH is nil or `all', get all properties. If WHICH is
15837 `special' or `standard', only get that subclass."
15838 (setq which (or which 'all))
15839 (org-with-point-at pom
15840 (let ((clockstr (substring org-clock-string 0 -1))
15841 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15842 beg end range props sum-props key value string clocksum)
15843 (save-excursion
15844 (when (condition-case nil (org-back-to-heading t) (error nil))
15845 (setq beg (point))
15846 (setq sum-props (get-text-property (point) 'org-summaries))
15847 (setq clocksum (get-text-property (point) :org-clock-minutes))
15848 (outline-next-heading)
15849 (setq end (point))
15850 (when (memq which '(all special))
15851 ;; Get the special properties, like TODO and tags
15852 (goto-char beg)
15853 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15854 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15855 (when (looking-at org-priority-regexp)
15856 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15857 (when (and (setq value (org-get-tags-string))
15858 (string-match "\\S-" value))
15859 (push (cons "TAGS" value) props))
15860 (when (setq value (org-get-tags-at))
15861 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15862 props))
15863 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15864 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15865 string (if (equal key clockstr)
15866 (org-no-properties
15867 (org-trim
15868 (buffer-substring
15869 (match-beginning 3) (goto-char (point-at-eol)))))
15870 (substring (org-match-string-no-properties 3) 1 -1)))
15871 (unless key
15872 (if (= (char-after (match-beginning 3)) ?\[)
15873 (setq key "TIMESTAMP_IA")
15874 (setq key "TIMESTAMP")))
15875 (when (or (equal key clockstr) (not (assoc key props)))
15876 (push (cons key string) props)))
15880 (when (memq which '(all standard))
15881 ;; Get the standard properties, like :PORP: ...
15882 (setq range (org-get-property-block beg end))
15883 (when range
15884 (goto-char (car range))
15885 (while (re-search-forward
15886 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15887 (cdr range) t)
15888 (setq key (org-match-string-no-properties 1)
15889 value (org-trim (or (org-match-string-no-properties 2) "")))
15890 (unless (member key excluded)
15891 (push (cons key (or value "")) props)))))
15892 (if clocksum
15893 (push (cons "CLOCKSUM"
15894 (org-column-number-to-string (/ (float clocksum) 60.)
15895 'add_times))
15896 props))
15897 (append sum-props (nreverse props)))))))
15899 (defun org-entry-get (pom property &optional inherit)
15900 "Get value of PROPERTY for entry at point-or-marker POM.
15901 If INHERIT is non-nil and the entry does not have the property,
15902 then also check higher levels of the hierarchy.
15903 If the property is present but empty, the return value is the empty string.
15904 If the property is not present at all, nil is returned."
15905 (org-with-point-at pom
15906 (if inherit
15907 (org-entry-get-with-inheritance property)
15908 (if (member property org-special-properties)
15909 ;; We need a special property. Use brute force, get all properties.
15910 (cdr (assoc property (org-entry-properties nil 'special)))
15911 (let ((range (org-get-property-block)))
15912 (if (and range
15913 (goto-char (car range))
15914 (re-search-forward
15915 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15916 (cdr range) t))
15917 ;; Found the property, return it.
15918 (if (match-end 1)
15919 (org-match-string-no-properties 1)
15920 "")))))))
15922 (defun org-entry-delete (pom property)
15923 "Delete the property PROPERTY from entry at point-or-marker POM."
15924 (org-with-point-at pom
15925 (if (member property org-special-properties)
15926 nil ; cannot delete these properties.
15927 (let ((range (org-get-property-block)))
15928 (if (and range
15929 (goto-char (car range))
15930 (re-search-forward
15931 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
15932 (cdr range) t))
15933 (progn
15934 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15936 nil)))))
15938 ;; Multi-values properties are properties that contain multiple values
15939 ;; These values are assumed to be single words, separated by whitespace.
15940 (defun org-entry-add-to-multivalued-property (pom property value)
15941 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15942 (let* ((old (org-entry-get pom property))
15943 (values (and old (org-split-string old "[ \t]"))))
15944 (unless (member value values)
15945 (setq values (cons value values))
15946 (org-entry-put pom property
15947 (mapconcat 'identity values " ")))))
15949 (defun org-entry-remove-from-multivalued-property (pom property value)
15950 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15951 (let* ((old (org-entry-get pom property))
15952 (values (and old (org-split-string old "[ \t]"))))
15953 (when (member value values)
15954 (setq values (delete value values))
15955 (org-entry-put pom property
15956 (mapconcat 'identity values " ")))))
15958 (defun org-entry-member-in-multivalued-property (pom property value)
15959 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15960 (let* ((old (org-entry-get pom property))
15961 (values (and old (org-split-string old "[ \t]"))))
15962 (member value values)))
15964 (defvar org-entry-property-inherited-from (make-marker))
15966 (defun org-entry-get-with-inheritance (property)
15967 "Get entry property, and search higher levels if not present."
15968 (let (tmp)
15969 (save-excursion
15970 (save-restriction
15971 (widen)
15972 (catch 'ex
15973 (while t
15974 (when (setq tmp (org-entry-get nil property))
15975 (org-back-to-heading t)
15976 (move-marker org-entry-property-inherited-from (point))
15977 (throw 'ex tmp))
15978 (or (org-up-heading-safe) (throw 'ex nil)))))
15979 (or tmp (cdr (assoc property org-local-properties))
15980 (cdr (assoc property org-global-properties))))))
15982 (defun org-entry-put (pom property value)
15983 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15984 (org-with-point-at pom
15985 (org-back-to-heading t)
15986 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15987 range)
15988 (cond
15989 ((equal property "TODO")
15990 (when (and (stringp value) (string-match "\\S-" value)
15991 (not (member value org-todo-keywords-1)))
15992 (error "\"%s\" is not a valid TODO state" value))
15993 (if (or (not value)
15994 (not (string-match "\\S-" value)))
15995 (setq value 'none))
15996 (org-todo value)
15997 (org-set-tags nil 'align))
15998 ((equal property "PRIORITY")
15999 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16000 (string-to-char value) ?\ ))
16001 (org-set-tags nil 'align))
16002 ((equal property "SCHEDULED")
16003 (if (re-search-forward org-scheduled-time-regexp end t)
16004 (cond
16005 ((eq value 'earlier) (org-timestamp-change -1 'day))
16006 ((eq value 'later) (org-timestamp-change 1 'day))
16007 (t (call-interactively 'org-schedule)))
16008 (call-interactively 'org-schedule)))
16009 ((equal property "DEADLINE")
16010 (if (re-search-forward org-deadline-time-regexp end t)
16011 (cond
16012 ((eq value 'earlier) (org-timestamp-change -1 'day))
16013 ((eq value 'later) (org-timestamp-change 1 'day))
16014 (t (call-interactively 'org-deadline)))
16015 (call-interactively 'org-deadline)))
16016 ((member property org-special-properties)
16017 (error "The %s property can not yet be set with `org-entry-put'"
16018 property))
16019 (t ; a non-special property
16020 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16021 (setq range (org-get-property-block beg end 'force))
16022 (goto-char (car range))
16023 (if (re-search-forward
16024 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16025 (progn
16026 (delete-region (match-beginning 1) (match-end 1))
16027 (goto-char (match-beginning 1)))
16028 (goto-char (cdr range))
16029 (insert "\n")
16030 (backward-char 1)
16031 (org-indent-line-function)
16032 (insert ":" property ":"))
16033 (and value (insert " " value))
16034 (org-indent-line-function)))))))
16036 (defun org-buffer-property-keys (&optional include-specials include-defaults)
16037 "Get all property keys in the current buffer.
16038 With INCLUDE-SPECIALS, also list the special properties that relect things
16039 like tags and TODO state.
16040 With INCLUDE-DEFAULTS, also include properties that has special meaning
16041 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
16042 (let (rtn range)
16043 (save-excursion
16044 (save-restriction
16045 (widen)
16046 (goto-char (point-min))
16047 (while (re-search-forward org-property-start-re nil t)
16048 (setq range (org-get-property-block))
16049 (goto-char (car range))
16050 (while (re-search-forward
16051 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
16052 (cdr range) t)
16053 (add-to-list 'rtn (org-match-string-no-properties 1)))
16054 (outline-next-heading))))
16056 (when include-specials
16057 (setq rtn (append org-special-properties rtn)))
16059 (when include-defaults
16060 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16062 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16064 (defun org-property-values (key)
16065 "Return a list of all values of property KEY."
16066 (save-excursion
16067 (save-restriction
16068 (widen)
16069 (goto-char (point-min))
16070 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16071 values)
16072 (while (re-search-forward re nil t)
16073 (add-to-list 'values (org-trim (match-string 1))))
16074 (delete "" values)))))
16076 (defun org-insert-property-drawer ()
16077 "Insert a property drawer into the current entry."
16078 (interactive)
16079 (org-back-to-heading t)
16080 (looking-at outline-regexp)
16081 (let ((indent (- (match-end 0)(match-beginning 0)))
16082 (beg (point))
16083 (re (concat "^[ \t]*" org-keyword-time-regexp))
16084 end hiddenp)
16085 (outline-next-heading)
16086 (setq end (point))
16087 (goto-char beg)
16088 (while (re-search-forward re end t))
16089 (setq hiddenp (org-invisible-p))
16090 (end-of-line 1)
16091 (and (equal (char-after) ?\n) (forward-char 1))
16092 (org-skip-over-state-notes)
16093 (skip-chars-backward " \t\n\r")
16094 (if (eq (char-before) ?*) (forward-char 1))
16095 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16096 (beginning-of-line 0)
16097 (indent-to-column indent)
16098 (beginning-of-line 2)
16099 (indent-to-column indent)
16100 (beginning-of-line 0)
16101 (if hiddenp
16102 (save-excursion
16103 (org-back-to-heading t)
16104 (hide-entry))
16105 (org-flag-drawer t))))
16107 (defun org-set-property (property value)
16108 "In the current entry, set PROPERTY to VALUE.
16109 When called interactively, this will prompt for a property name, offering
16110 completion on existing and default properties. And then it will prompt
16111 for a value, offering competion either on allowed values (via an inherited
16112 xxx_ALL property) or on existing values in other instances of this property
16113 in the current file."
16114 (interactive
16115 (let* ((prop (completing-read
16116 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
16117 (cur (org-entry-get nil prop))
16118 (allowed (org-property-get-allowed-values nil prop 'table))
16119 (existing (mapcar 'list (org-property-values prop)))
16120 (val (if allowed
16121 (completing-read "Value: " allowed nil 'req-match)
16122 (completing-read
16123 (concat "Value" (if (and cur (string-match "\\S-" cur))
16124 (concat "[" cur "]") "")
16125 ": ")
16126 existing nil nil "" nil cur))))
16127 (list prop (if (equal val "") cur val))))
16128 (unless (equal (org-entry-get nil property) value)
16129 (org-entry-put nil property value)))
16131 (defun org-delete-property (property)
16132 "In the current entry, delete PROPERTY."
16133 (interactive
16134 (let* ((prop (completing-read
16135 "Property: " (org-entry-properties nil 'standard))))
16136 (list prop)))
16137 (message "Property %s %s" property
16138 (if (org-entry-delete nil property)
16139 "deleted"
16140 "was not present in the entry")))
16142 (defun org-delete-property-globally (property)
16143 "Remove PROPERTY globally, from all entries."
16144 (interactive
16145 (let* ((prop (completing-read
16146 "Globally remove property: "
16147 (mapcar 'list (org-buffer-property-keys)))))
16148 (list prop)))
16149 (save-excursion
16150 (save-restriction
16151 (widen)
16152 (goto-char (point-min))
16153 (let ((cnt 0))
16154 (while (re-search-forward
16155 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16156 nil t)
16157 (setq cnt (1+ cnt))
16158 (replace-match ""))
16159 (message "Property \"%s\" removed from %d entries" property cnt)))))
16161 (defvar org-columns-current-fmt-compiled) ; defined below
16163 (defun org-compute-property-at-point ()
16164 "Compute the property at point.
16165 This looks for an enclosing column format, extracts the operator and
16166 then applies it to the proerty in the column format's scope."
16167 (interactive)
16168 (unless (org-at-property-p)
16169 (error "Not at a property"))
16170 (let ((prop (org-match-string-no-properties 2)))
16171 (org-columns-get-format-and-top-level)
16172 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16173 (error "No operator defined for property %s" prop))
16174 (org-columns-compute prop)))
16176 (defun org-property-get-allowed-values (pom property &optional table)
16177 "Get allowed values for the property PROPERTY.
16178 When TABLE is non-nil, return an alist that can directly be used for
16179 completion."
16180 (let (vals)
16181 (cond
16182 ((equal property "TODO")
16183 (setq vals (org-with-point-at pom
16184 (append org-todo-keywords-1 '("")))))
16185 ((equal property "PRIORITY")
16186 (let ((n org-lowest-priority))
16187 (while (>= n org-highest-priority)
16188 (push (char-to-string n) vals)
16189 (setq n (1- n)))))
16190 ((member property org-special-properties))
16192 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16194 (when (and vals (string-match "\\S-" vals))
16195 (setq vals (car (read-from-string (concat "(" vals ")"))))
16196 (setq vals (mapcar (lambda (x)
16197 (cond ((stringp x) x)
16198 ((numberp x) (number-to-string x))
16199 ((symbolp x) (symbol-name x))
16200 (t "???")))
16201 vals)))))
16202 (if table (mapcar 'list vals) vals)))
16204 (defun org-property-previous-allowed-value (&optional previous)
16205 "Switch to the next allowed value for this property."
16206 (interactive)
16207 (org-property-next-allowed-value t))
16209 (defun org-property-next-allowed-value (&optional previous)
16210 "Switch to the next allowed value for this property."
16211 (interactive)
16212 (unless (org-at-property-p)
16213 (error "Not at a property"))
16214 (let* ((key (match-string 2))
16215 (value (match-string 3))
16216 (allowed (or (org-property-get-allowed-values (point) key)
16217 (and (member value '("[ ]" "[-]" "[X]"))
16218 '("[ ]" "[X]"))))
16219 nval)
16220 (unless allowed
16221 (error "Allowed values for this property have not been defined"))
16222 (if previous (setq allowed (reverse allowed)))
16223 (if (member value allowed)
16224 (setq nval (car (cdr (member value allowed)))))
16225 (setq nval (or nval (car allowed)))
16226 (if (equal nval value)
16227 (error "Only one allowed value for this property"))
16228 (org-at-property-p)
16229 (replace-match (concat " :" key ": " nval) t t)
16230 (org-indent-line-function)
16231 (beginning-of-line 1)
16232 (skip-chars-forward " \t")))
16234 (defun org-find-entry-with-id (ident)
16235 "Locate the entry that contains the ID property with exact value IDENT.
16236 IDENT can be a string, a symbol or a number, this function will search for
16237 the string representation of it.
16238 Return the position where this entry starts, or nil if there is no such entry."
16239 (let ((id (cond
16240 ((stringp ident) ident)
16241 ((symbol-name ident) (symbol-name ident))
16242 ((numberp ident) (number-to-string ident))
16243 (t (error "IDENT %s must be a string, symbol or number" ident))))
16244 (case-fold-search nil))
16245 (save-excursion
16246 (save-restriction
16247 (goto-char (point-min))
16248 (when (re-search-forward
16249 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16250 nil t)
16251 (org-back-to-heading)
16252 (point))))))
16254 ;;; Column View
16256 (defvar org-columns-overlays nil
16257 "Holds the list of current column overlays.")
16259 (defvar org-columns-current-fmt nil
16260 "Local variable, holds the currently active column format.")
16261 (defvar org-columns-current-fmt-compiled nil
16262 "Local variable, holds the currently active column format.
16263 This is the compiled version of the format.")
16264 (defvar org-columns-current-widths nil
16265 "Loval variable, holds the currently widths of fields.")
16266 (defvar org-columns-current-maxwidths nil
16267 "Loval variable, holds the currently active maximum column widths.")
16268 (defvar org-columns-begin-marker (make-marker)
16269 "Points to the position where last a column creation command was called.")
16270 (defvar org-columns-top-level-marker (make-marker)
16271 "Points to the position where current columns region starts.")
16273 (defvar org-columns-map (make-sparse-keymap)
16274 "The keymap valid in column display.")
16276 (defun org-columns-content ()
16277 "Switch to contents view while in columns view."
16278 (interactive)
16279 (org-overview)
16280 (org-content))
16282 (org-defkey org-columns-map "c" 'org-columns-content)
16283 (org-defkey org-columns-map "o" 'org-overview)
16284 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16285 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16286 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16287 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16288 (org-defkey org-columns-map "v" 'org-columns-show-value)
16289 (org-defkey org-columns-map "q" 'org-columns-quit)
16290 (org-defkey org-columns-map "r" 'org-columns-redo)
16291 (org-defkey org-columns-map "g" 'org-columns-redo)
16292 (org-defkey org-columns-map [left] 'backward-char)
16293 (org-defkey org-columns-map "\M-b" 'backward-char)
16294 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16295 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16296 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16297 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16298 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16299 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16300 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16301 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16302 (org-defkey org-columns-map "<" 'org-columns-narrow)
16303 (org-defkey org-columns-map ">" 'org-columns-widen)
16304 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16305 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16306 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16307 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16309 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16310 '("Column"
16311 ["Edit property" org-columns-edit-value t]
16312 ["Next allowed value" org-columns-next-allowed-value t]
16313 ["Previous allowed value" org-columns-previous-allowed-value t]
16314 ["Show full value" org-columns-show-value t]
16315 ["Edit allowed values" org-columns-edit-allowed t]
16316 "--"
16317 ["Edit column attributes" org-columns-edit-attributes t]
16318 ["Increase column width" org-columns-widen t]
16319 ["Decrease column width" org-columns-narrow t]
16320 "--"
16321 ["Move column right" org-columns-move-right t]
16322 ["Move column left" org-columns-move-left t]
16323 ["Add column" org-columns-new t]
16324 ["Delete column" org-columns-delete t]
16325 "--"
16326 ["CONTENTS" org-columns-content t]
16327 ["OVERVIEW" org-overview t]
16328 ["Refresh columns display" org-columns-redo t]
16329 "--"
16330 ["Open link" org-columns-open-link t]
16331 "--"
16332 ["Quit" org-columns-quit t]))
16334 (defun org-columns-new-overlay (beg end &optional string face)
16335 "Create a new column overlay and add it to the list."
16336 (let ((ov (org-make-overlay beg end)))
16337 (org-overlay-put ov 'face (or face 'secondary-selection))
16338 (org-overlay-display ov string face)
16339 (push ov org-columns-overlays)
16340 ov))
16342 (defun org-columns-display-here (&optional props)
16343 "Overlay the current line with column display."
16344 (interactive)
16345 (let* ((fmt org-columns-current-fmt-compiled)
16346 (beg (point-at-bol))
16347 (level-face (save-excursion
16348 (beginning-of-line 1)
16349 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16350 (org-get-level-face 2))))
16351 (color (list :foreground
16352 (face-attribute (or level-face 'default) :foreground)))
16353 props pom property ass width f string ov column val modval)
16354 ;; Check if the entry is in another buffer.
16355 (unless props
16356 (if (eq major-mode 'org-agenda-mode)
16357 (setq pom (or (get-text-property (point) 'org-hd-marker)
16358 (get-text-property (point) 'org-marker))
16359 props (if pom (org-entry-properties pom) nil))
16360 (setq props (org-entry-properties nil))))
16361 ;; Walk the format
16362 (while (setq column (pop fmt))
16363 (setq property (car column)
16364 ass (if (equal property "ITEM")
16365 (cons "ITEM"
16366 (save-match-data
16367 (org-no-properties
16368 (org-remove-tabs
16369 (buffer-substring-no-properties
16370 (point-at-bol) (point-at-eol))))))
16371 (assoc property props))
16372 width (or (cdr (assoc property org-columns-current-maxwidths))
16373 (nth 2 column)
16374 (length property))
16375 f (format "%%-%d.%ds | " width width)
16376 val (or (cdr ass) "")
16377 modval (if (equal property "ITEM")
16378 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16379 string (format f (or modval val)))
16380 ;; Create the overlay
16381 (org-unmodified
16382 (setq ov (org-columns-new-overlay
16383 beg (setq beg (1+ beg)) string
16384 (list color 'org-column)))
16385 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16386 (org-overlay-put ov 'keymap org-columns-map)
16387 (org-overlay-put ov 'org-columns-key property)
16388 (org-overlay-put ov 'org-columns-value (cdr ass))
16389 (org-overlay-put ov 'org-columns-value-modified modval)
16390 (org-overlay-put ov 'org-columns-pom pom)
16391 (org-overlay-put ov 'org-columns-format f))
16392 (if (or (not (char-after beg))
16393 (equal (char-after beg) ?\n))
16394 (let ((inhibit-read-only t))
16395 (save-excursion
16396 (goto-char beg)
16397 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16398 ;; Make the rest of the line disappear.
16399 (org-unmodified
16400 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16401 (org-overlay-put ov 'invisible t)
16402 (org-overlay-put ov 'keymap org-columns-map)
16403 (org-overlay-put ov 'intangible t)
16404 (push ov org-columns-overlays)
16405 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16406 (org-overlay-put ov 'keymap org-columns-map)
16407 (push ov org-columns-overlays)
16408 (let ((inhibit-read-only t))
16409 (put-text-property (max (point-min) (1- (point-at-bol)))
16410 (min (point-max) (1+ (point-at-eol)))
16411 'read-only "Type `e' to edit property")))))
16413 (defvar org-previous-header-line-format nil
16414 "The header line format before column view was turned on.")
16415 (defvar org-columns-inhibit-recalculation nil
16416 "Inhibit recomputing of columns on column view startup.")
16419 (defvar header-line-format)
16420 (defun org-columns-display-here-title ()
16421 "Overlay the newline before the current line with the table title."
16422 (interactive)
16423 (let ((fmt org-columns-current-fmt-compiled)
16424 string (title "")
16425 property width f column str widths)
16426 (while (setq column (pop fmt))
16427 (setq property (car column)
16428 str (or (nth 1 column) property)
16429 width (or (cdr (assoc property org-columns-current-maxwidths))
16430 (nth 2 column)
16431 (length str))
16432 widths (push width widths)
16433 f (format "%%-%d.%ds | " width width)
16434 string (format f str)
16435 title (concat title string)))
16436 (setq title (concat
16437 (org-add-props " " nil 'display '(space :align-to 0))
16438 (org-add-props title nil 'face '(:weight bold :underline t))))
16439 (org-set-local 'org-previous-header-line-format header-line-format)
16440 (org-set-local 'org-columns-current-widths (nreverse widths))
16441 (setq header-line-format title)))
16443 (defun org-columns-remove-overlays ()
16444 "Remove all currently active column overlays."
16445 (interactive)
16446 (when (marker-buffer org-columns-begin-marker)
16447 (with-current-buffer (marker-buffer org-columns-begin-marker)
16448 (when (local-variable-p 'org-previous-header-line-format)
16449 (setq header-line-format org-previous-header-line-format)
16450 (kill-local-variable 'org-previous-header-line-format))
16451 (move-marker org-columns-begin-marker nil)
16452 (move-marker org-columns-top-level-marker nil)
16453 (org-unmodified
16454 (mapc 'org-delete-overlay org-columns-overlays)
16455 (setq org-columns-overlays nil)
16456 (let ((inhibit-read-only t))
16457 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16459 (defun org-columns-cleanup-item (item fmt)
16460 "Remove from ITEM what is a column in the format FMT."
16461 (if (not org-complex-heading-regexp)
16462 item
16463 (when (string-match org-complex-heading-regexp item)
16464 (concat
16465 (org-add-props (concat (match-string 1 item) " ") nil
16466 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16467 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16468 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16469 " " (match-string 4 item)
16470 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16472 (defun org-columns-show-value ()
16473 "Show the full value of the property."
16474 (interactive)
16475 (let ((value (get-char-property (point) 'org-columns-value)))
16476 (message "Value is: %s" (or value ""))))
16478 (defun org-columns-quit ()
16479 "Remove the column overlays and in this way exit column editing."
16480 (interactive)
16481 (org-unmodified
16482 (org-columns-remove-overlays)
16483 (let ((inhibit-read-only t))
16484 (remove-text-properties (point-min) (point-max) '(read-only t))))
16485 (when (eq major-mode 'org-agenda-mode)
16486 (message
16487 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16489 (defun org-columns-check-computed ()
16490 "Check if this column value is computed.
16491 If yes, throw an error indicating that changing it does not make sense."
16492 (let ((val (get-char-property (point) 'org-columns-value)))
16493 (when (and (stringp val)
16494 (get-char-property 0 'org-computed val))
16495 (error "This value is computed from the entry's children"))))
16497 (defun org-columns-todo (&optional arg)
16498 "Change the TODO state during column view."
16499 (interactive "P")
16500 (org-columns-edit-value "TODO"))
16502 (defun org-columns-set-tags-or-toggle (&optional arg)
16503 "Toggle checkbox at point, or set tags for current headline."
16504 (interactive "P")
16505 (if (string-match "\\`\\[[ xX-]\\]\\'"
16506 (get-char-property (point) 'org-columns-value))
16507 (org-columns-next-allowed-value)
16508 (org-columns-edit-value "TAGS")))
16510 (defun org-columns-edit-value (&optional key)
16511 "Edit the value of the property at point in column view.
16512 Where possible, use the standard interface for changing this line."
16513 (interactive)
16514 (org-columns-check-computed)
16515 (let* ((external-key key)
16516 (col (current-column))
16517 (key (or key (get-char-property (point) 'org-columns-key)))
16518 (value (get-char-property (point) 'org-columns-value))
16519 (bol (point-at-bol)) (eol (point-at-eol))
16520 (pom (or (get-text-property bol 'org-hd-marker)
16521 (point))) ; keep despite of compiler waring
16522 (line-overlays
16523 (delq nil (mapcar (lambda (x)
16524 (and (eq (overlay-buffer x) (current-buffer))
16525 (>= (overlay-start x) bol)
16526 (<= (overlay-start x) eol)
16528 org-columns-overlays)))
16529 nval eval allowed)
16530 (cond
16531 ((equal key "CLOCKSUM")
16532 (error "This special column cannot be edited"))
16533 ((equal key "ITEM")
16534 (setq eval '(org-with-point-at pom
16535 (org-edit-headline))))
16536 ((equal key "TODO")
16537 (setq eval '(org-with-point-at pom
16538 (let ((current-prefix-arg
16539 (if external-key current-prefix-arg '(4))))
16540 (call-interactively 'org-todo)))))
16541 ((equal key "PRIORITY")
16542 (setq eval '(org-with-point-at pom
16543 (call-interactively 'org-priority))))
16544 ((equal key "TAGS")
16545 (setq eval '(org-with-point-at pom
16546 (let ((org-fast-tag-selection-single-key
16547 (if (eq org-fast-tag-selection-single-key 'expert)
16548 t org-fast-tag-selection-single-key)))
16549 (call-interactively 'org-set-tags)))))
16550 ((equal key "DEADLINE")
16551 (setq eval '(org-with-point-at pom
16552 (call-interactively 'org-deadline))))
16553 ((equal key "SCHEDULED")
16554 (setq eval '(org-with-point-at pom
16555 (call-interactively 'org-schedule))))
16557 (setq allowed (org-property-get-allowed-values pom key 'table))
16558 (if allowed
16559 (setq nval (completing-read "Value: " allowed nil t))
16560 (setq nval (read-string "Edit: " value)))
16561 (setq nval (org-trim nval))
16562 (when (not (equal nval value))
16563 (setq eval '(org-entry-put pom key nval)))))
16564 (when eval
16565 (let ((inhibit-read-only t))
16566 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16567 (unwind-protect
16568 (progn
16569 (setq org-columns-overlays
16570 (org-delete-all line-overlays org-columns-overlays))
16571 (mapc 'org-delete-overlay line-overlays)
16572 (org-columns-eval eval))
16573 (org-columns-display-here))))
16574 (move-to-column col)
16575 (if (and (org-mode-p)
16576 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16577 (org-columns-update key))))
16579 (defun org-edit-headline () ; FIXME: this is not columns specific
16580 "Edit the current headline, the part without TODO keyword, TAGS."
16581 (org-back-to-heading)
16582 (when (looking-at org-todo-line-regexp)
16583 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16584 (txt (match-string 3))
16585 (post "")
16586 txt2)
16587 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16588 (setq post (match-string 0 txt)
16589 txt (substring txt 0 (match-beginning 0))))
16590 (setq txt2 (read-string "Edit: " txt))
16591 (when (not (equal txt txt2))
16592 (beginning-of-line 1)
16593 (insert pre txt2 post)
16594 (delete-region (point) (point-at-eol))
16595 (org-set-tags nil t)))))
16597 (defun org-columns-edit-allowed ()
16598 "Edit the list of allowed values for the current property."
16599 (interactive)
16600 (let* ((key (get-char-property (point) 'org-columns-key))
16601 (key1 (concat key "_ALL"))
16602 (allowed (org-entry-get (point) key1 t))
16603 nval)
16604 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16605 (setq nval (read-string "Allowed: " allowed))
16606 (org-entry-put
16607 (cond ((marker-position org-entry-property-inherited-from)
16608 org-entry-property-inherited-from)
16609 ((marker-position org-columns-top-level-marker)
16610 org-columns-top-level-marker))
16611 key1 nval)))
16613 (defmacro org-no-warnings (&rest body)
16614 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16616 (defun org-columns-eval (form)
16617 (let (hidep)
16618 (save-excursion
16619 (beginning-of-line 1)
16620 ;; `next-line' is needed here, because it skips invisible line.
16621 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16622 (setq hidep (org-on-heading-p 1)))
16623 (eval form)
16624 (and hidep (hide-entry))))
16626 (defun org-columns-previous-allowed-value ()
16627 "Switch to the previous allowed value for this column."
16628 (interactive)
16629 (org-columns-next-allowed-value t))
16631 (defun org-columns-next-allowed-value (&optional previous)
16632 "Switch to the next allowed value for this column."
16633 (interactive)
16634 (org-columns-check-computed)
16635 (let* ((col (current-column))
16636 (key (get-char-property (point) 'org-columns-key))
16637 (value (get-char-property (point) 'org-columns-value))
16638 (bol (point-at-bol)) (eol (point-at-eol))
16639 (pom (or (get-text-property bol 'org-hd-marker)
16640 (point))) ; keep despite of compiler waring
16641 (line-overlays
16642 (delq nil (mapcar (lambda (x)
16643 (and (eq (overlay-buffer x) (current-buffer))
16644 (>= (overlay-start x) bol)
16645 (<= (overlay-start x) eol)
16647 org-columns-overlays)))
16648 (allowed (or (org-property-get-allowed-values pom key)
16649 (and (equal
16650 (nth 4 (assoc key org-columns-current-fmt-compiled))
16651 'checkbox) '("[ ]" "[X]"))))
16652 nval)
16653 (when (equal key "ITEM")
16654 (error "Cannot edit item headline from here"))
16655 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16656 (error "Allowed values for this property have not been defined"))
16657 (if (member key '("SCHEDULED" "DEADLINE"))
16658 (setq nval (if previous 'earlier 'later))
16659 (if previous (setq allowed (reverse allowed)))
16660 (if (member value allowed)
16661 (setq nval (car (cdr (member value allowed)))))
16662 (setq nval (or nval (car allowed)))
16663 (if (equal nval value)
16664 (error "Only one allowed value for this property")))
16665 (let ((inhibit-read-only t))
16666 (remove-text-properties (1- bol) eol '(read-only t))
16667 (unwind-protect
16668 (progn
16669 (setq org-columns-overlays
16670 (org-delete-all line-overlays org-columns-overlays))
16671 (mapc 'org-delete-overlay line-overlays)
16672 (org-columns-eval '(org-entry-put pom key nval)))
16673 (org-columns-display-here)))
16674 (move-to-column col)
16675 (if (and (org-mode-p)
16676 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16677 (org-columns-update key))))
16679 (defun org-verify-version (task)
16680 (cond
16681 ((eq task 'columns)
16682 (if (or (featurep 'xemacs)
16683 (< emacs-major-version 22))
16684 (error "Emacs 22 is required for the columns feature")))))
16686 (defun org-columns-open-link (&optional arg)
16687 (interactive "P")
16688 (let ((key (get-char-property (point) 'org-columns-key))
16689 (value (get-char-property (point) 'org-columns-value)))
16690 (org-open-link-from-string arg)))
16692 (defun org-open-link-from-string (s &optional arg)
16693 "Open a link in the string S, as if it was in Org-mode."
16694 (interactive)
16695 (with-temp-buffer
16696 (let ((org-inhibit-startup t))
16697 (org-mode)
16698 (insert s)
16699 (goto-char (point-min))
16700 (org-open-at-point arg))))
16702 (defun org-columns-get-format-and-top-level ()
16703 (let (fmt)
16704 (when (condition-case nil (org-back-to-heading) (error nil))
16705 (move-marker org-entry-property-inherited-from nil)
16706 (setq fmt (org-entry-get nil "COLUMNS" t)))
16707 (setq fmt (or fmt org-columns-default-format))
16708 (org-set-local 'org-columns-current-fmt fmt)
16709 (org-columns-compile-format fmt)
16710 (if (marker-position org-entry-property-inherited-from)
16711 (move-marker org-columns-top-level-marker
16712 org-entry-property-inherited-from)
16713 (move-marker org-columns-top-level-marker (point)))
16714 fmt))
16716 (defun org-columns ()
16717 "Turn on column view on an org-mode file."
16718 (interactive)
16719 (org-verify-version 'columns)
16720 (org-columns-remove-overlays)
16721 (move-marker org-columns-begin-marker (point))
16722 (let (beg end fmt cache maxwidths clocksump)
16723 (setq fmt (org-columns-get-format-and-top-level))
16724 (save-excursion
16725 (goto-char org-columns-top-level-marker)
16726 (setq beg (point))
16727 (unless org-columns-inhibit-recalculation
16728 (org-columns-compute-all))
16729 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16730 (point-max)))
16731 ;; Get and cache the properties
16732 (goto-char beg)
16733 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16734 (setq clocksump t)
16735 (save-excursion
16736 (save-restriction
16737 (narrow-to-region beg end)
16738 (org-clock-sum))))
16739 (while (re-search-forward (concat "^" outline-regexp) end t)
16740 (push (cons (org-current-line) (org-entry-properties)) cache))
16741 (when cache
16742 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16743 (org-set-local 'org-columns-current-maxwidths maxwidths)
16744 (org-columns-display-here-title)
16745 (mapc (lambda (x)
16746 (goto-line (car x))
16747 (org-columns-display-here (cdr x)))
16748 cache)))))
16750 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16751 "Insert a new column, to the leeft o the current column."
16752 (interactive)
16753 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16754 cell)
16755 (setq prop (completing-read
16756 "Property: " (mapcar 'list (org-buffer-property-keys t))
16757 nil nil prop))
16758 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16759 (setq width (read-string "Column width: " (if width (number-to-string width))))
16760 (if (string-match "\\S-" width)
16761 (setq width (string-to-number width))
16762 (setq width nil))
16763 (setq fmt (completing-read "Summary [none]: "
16764 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16765 nil t))
16766 (if (string-match "\\S-" fmt)
16767 (setq fmt (intern fmt))
16768 (setq fmt nil))
16769 (if (eq fmt 'none) (setq fmt nil))
16770 (if editp
16771 (progn
16772 (setcar editp prop)
16773 (setcdr editp (list title width nil fmt)))
16774 (setq cell (nthcdr (1- (current-column))
16775 org-columns-current-fmt-compiled))
16776 (setcdr cell (cons (list prop title width nil fmt)
16777 (cdr cell))))
16778 (org-columns-store-format)
16779 (org-columns-redo)))
16781 (defun org-columns-delete ()
16782 "Delete the column at point from columns view."
16783 (interactive)
16784 (let* ((n (current-column))
16785 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16786 (when (y-or-n-p
16787 (format "Are you sure you want to remove column \"%s\"? " title))
16788 (setq org-columns-current-fmt-compiled
16789 (delq (nth n org-columns-current-fmt-compiled)
16790 org-columns-current-fmt-compiled))
16791 (org-columns-store-format)
16792 (org-columns-redo)
16793 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16794 (backward-char 1)))))
16796 (defun org-columns-edit-attributes ()
16797 "Edit the attributes of the current column."
16798 (interactive)
16799 (let* ((n (current-column))
16800 (info (nth n org-columns-current-fmt-compiled)))
16801 (apply 'org-columns-new info)))
16803 (defun org-columns-widen (arg)
16804 "Make the column wider by ARG characters."
16805 (interactive "p")
16806 (let* ((n (current-column))
16807 (entry (nth n org-columns-current-fmt-compiled))
16808 (width (or (nth 2 entry)
16809 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16810 (setq width (max 1 (+ width arg)))
16811 (setcar (nthcdr 2 entry) width)
16812 (org-columns-store-format)
16813 (org-columns-redo)))
16815 (defun org-columns-narrow (arg)
16816 "Make the column nrrower by ARG characters."
16817 (interactive "p")
16818 (org-columns-widen (- arg)))
16820 (defun org-columns-move-right ()
16821 "Swap this column with the one to the right."
16822 (interactive)
16823 (let* ((n (current-column))
16824 (cell (nthcdr n org-columns-current-fmt-compiled))
16826 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16827 (error "Cannot shift this column further to the right"))
16828 (setq e (car cell))
16829 (setcar cell (car (cdr cell)))
16830 (setcdr cell (cons e (cdr (cdr cell))))
16831 (org-columns-store-format)
16832 (org-columns-redo)
16833 (forward-char 1)))
16835 (defun org-columns-move-left ()
16836 "Swap this column with the one to the left."
16837 (interactive)
16838 (let* ((n (current-column)))
16839 (when (= n 0)
16840 (error "Cannot shift this column further to the left"))
16841 (backward-char 1)
16842 (org-columns-move-right)
16843 (backward-char 1)))
16845 (defun org-columns-store-format ()
16846 "Store the text version of the current columns format in appropriate place.
16847 This is either in the COLUMNS property of the node starting the current column
16848 display, or in the #+COLUMNS line of the current buffer."
16849 (let (fmt (cnt 0))
16850 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16851 (org-set-local 'org-columns-current-fmt fmt)
16852 (if (marker-position org-columns-top-level-marker)
16853 (save-excursion
16854 (goto-char org-columns-top-level-marker)
16855 (if (and (org-at-heading-p)
16856 (org-entry-get nil "COLUMNS"))
16857 (org-entry-put nil "COLUMNS" fmt)
16858 (goto-char (point-min))
16859 ;; Overwrite all #+COLUMNS lines....
16860 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16861 (setq cnt (1+ cnt))
16862 (replace-match (concat "#+COLUMNS: " fmt) t t))
16863 (unless (> cnt 0)
16864 (goto-char (point-min))
16865 (or (org-on-heading-p t) (outline-next-heading))
16866 (let ((inhibit-read-only t))
16867 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16868 (org-set-local 'org-columns-default-format fmt))))))
16870 (defvar org-overriding-columns-format nil
16871 "When set, overrides any other definition.")
16872 (defvar org-agenda-view-columns-initially nil
16873 "When set, switch to columns view immediately after creating the agenda.")
16875 (defun org-agenda-columns ()
16876 "Turn on column view in the agenda."
16877 (interactive)
16878 (org-verify-version 'columns)
16879 (org-columns-remove-overlays)
16880 (move-marker org-columns-begin-marker (point))
16881 (let (fmt cache maxwidths m)
16882 (cond
16883 ((and (local-variable-p 'org-overriding-columns-format)
16884 org-overriding-columns-format)
16885 (setq fmt org-overriding-columns-format))
16886 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16887 (setq fmt (org-entry-get m "COLUMNS" t)))
16888 ((and (boundp 'org-columns-current-fmt)
16889 (local-variable-p 'org-columns-current-fmt)
16890 org-columns-current-fmt)
16891 (setq fmt org-columns-current-fmt))
16892 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16893 (setq m (get-text-property m 'org-hd-marker))
16894 (setq fmt (org-entry-get m "COLUMNS" t))))
16895 (setq fmt (or fmt org-columns-default-format))
16896 (org-set-local 'org-columns-current-fmt fmt)
16897 (org-columns-compile-format fmt)
16898 (save-excursion
16899 ;; Get and cache the properties
16900 (goto-char (point-min))
16901 (while (not (eobp))
16902 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16903 (get-text-property (point) 'org-marker)))
16904 (push (cons (org-current-line) (org-entry-properties m)) cache))
16905 (beginning-of-line 2))
16906 (when cache
16907 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16908 (org-set-local 'org-columns-current-maxwidths maxwidths)
16909 (org-columns-display-here-title)
16910 (mapc (lambda (x)
16911 (goto-line (car x))
16912 (org-columns-display-here (cdr x)))
16913 cache)))))
16915 (defun org-columns-get-autowidth-alist (s cache)
16916 "Derive the maximum column widths from the format and the cache."
16917 (let ((start 0) rtn)
16918 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
16919 (push (cons (match-string 1 s) 1) rtn)
16920 (setq start (match-end 0)))
16921 (mapc (lambda (x)
16922 (setcdr x (apply 'max
16923 (mapcar
16924 (lambda (y)
16925 (length (or (cdr (assoc (car x) (cdr y))) " ")))
16926 cache))))
16927 rtn)
16928 rtn))
16930 (defun org-columns-compute-all ()
16931 "Compute all columns that have operators defined."
16932 (org-unmodified
16933 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
16934 (let ((columns org-columns-current-fmt-compiled) col)
16935 (while (setq col (pop columns))
16936 (when (nth 3 col)
16937 (save-excursion
16938 (org-columns-compute (car col)))))))
16940 (defun org-columns-update (property)
16941 "Recompute PROPERTY, and update the columns display for it."
16942 (org-columns-compute property)
16943 (let (fmt val pos)
16944 (save-excursion
16945 (mapc (lambda (ov)
16946 (when (equal (org-overlay-get ov 'org-columns-key) property)
16947 (setq pos (org-overlay-start ov))
16948 (goto-char pos)
16949 (when (setq val (cdr (assoc property
16950 (get-text-property
16951 (point-at-bol) 'org-summaries))))
16952 (setq fmt (org-overlay-get ov 'org-columns-format))
16953 (org-overlay-put ov 'org-columns-value val)
16954 (org-overlay-put ov 'display (format fmt val)))))
16955 org-columns-overlays))))
16957 (defun org-columns-compute (property)
16958 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16959 (interactive)
16960 (let* ((re (concat "^" outline-regexp))
16961 (lmax 30) ; Does anyone use deeper levels???
16962 (lsum (make-vector lmax 0))
16963 (lflag (make-vector lmax nil))
16964 (level 0)
16965 (ass (assoc property org-columns-current-fmt-compiled))
16966 (format (nth 4 ass))
16967 (printf (nth 5 ass))
16968 (beg org-columns-top-level-marker)
16969 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
16970 (save-excursion
16971 ;; Find the region to compute
16972 (goto-char beg)
16973 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
16974 (goto-char end)
16975 ;; Walk the tree from the back and do the computations
16976 (while (re-search-backward re beg t)
16977 (setq sumpos (match-beginning 0)
16978 last-level level
16979 level (org-outline-level)
16980 val (org-entry-get nil property)
16981 valflag (and val (string-match "\\S-" val)))
16982 (cond
16983 ((< level last-level)
16984 ;; put the sum of lower levels here as a property
16985 (setq sum (aref lsum last-level) ; current sum
16986 flag (aref lflag last-level) ; any valid entries from children?
16987 str (org-column-number-to-string sum format printf)
16988 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
16989 useval (if flag str1 (if valflag val ""))
16990 sum-alist (get-text-property sumpos 'org-summaries))
16991 (if (assoc property sum-alist)
16992 (setcdr (assoc property sum-alist) useval)
16993 (push (cons property useval) sum-alist)
16994 (org-unmodified
16995 (add-text-properties sumpos (1+ sumpos)
16996 (list 'org-summaries sum-alist))))
16997 (when val
16998 (org-entry-put nil property (if flag str val)))
16999 ;; add current to current level accumulator
17000 (when (or flag valflag)
17001 (aset lsum level (+ (aref lsum level)
17002 (if flag sum (org-column-string-to-number
17003 (if flag str val) format))))
17004 (aset lflag level t))
17005 ;; clear accumulators for deeper levels
17006 (loop for l from (1+ level) to (1- lmax) do
17007 (aset lsum l 0)
17008 (aset lflag l nil)))
17009 ((>= level last-level)
17010 ;; add what we have here to the accumulator for this level
17011 (aset lsum level (+ (aref lsum level)
17012 (org-column-string-to-number (or val "0") format)))
17013 (and valflag (aset lflag level t)))
17014 (t (error "This should not happen")))))))
17016 (defun org-columns-redo ()
17017 "Construct the column display again."
17018 (interactive)
17019 (message "Recomputing columns...")
17020 (save-excursion
17021 (if (marker-position org-columns-begin-marker)
17022 (goto-char org-columns-begin-marker))
17023 (org-columns-remove-overlays)
17024 (if (org-mode-p)
17025 (call-interactively 'org-columns)
17026 (call-interactively 'org-agenda-columns)))
17027 (message "Recomputing columns...done"))
17029 (defun org-columns-not-in-agenda ()
17030 (if (eq major-mode 'org-agenda-mode)
17031 (error "This command is only allowed in Org-mode buffers")))
17034 (defun org-string-to-number (s)
17035 "Convert string to number, and interpret hh:mm:ss."
17036 (if (not (string-match ":" s))
17037 (string-to-number s)
17038 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17039 (while l
17040 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17041 sum)))
17043 (defun org-column-number-to-string (n fmt &optional printf)
17044 "Convert a computed column number to a string value, according to FMT."
17045 (cond
17046 ((eq fmt 'add_times)
17047 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17048 (format "%d:%02d" h m)))
17049 ((eq fmt 'checkbox)
17050 (cond ((= n (floor n)) "[X]")
17051 ((> n 1.) "[-]")
17052 (t "[ ]")))
17053 (printf (format printf n))
17054 ((eq fmt 'currency)
17055 (format "%.2f" n))
17056 (t (number-to-string n))))
17058 (defun org-column-string-to-number (s fmt)
17059 "Convert a column value to a number that can be used for column computing."
17060 (cond
17061 ((string-match ":" s)
17062 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17063 (while l
17064 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17065 sum))
17066 ((eq fmt 'checkbox)
17067 (if (equal s "[X]") 1. 0.000001))
17068 (t (string-to-number s))))
17070 (defun org-columns-uncompile-format (cfmt)
17071 "Turn the compiled columns format back into a string representation."
17072 (let ((rtn "") e s prop title op width fmt printf)
17073 (while (setq e (pop cfmt))
17074 (setq prop (car e)
17075 title (nth 1 e)
17076 width (nth 2 e)
17077 op (nth 3 e)
17078 fmt (nth 4 e)
17079 printf (nth 5 e))
17080 (cond
17081 ((eq fmt 'add_times) (setq op ":"))
17082 ((eq fmt 'checkbox) (setq op "X"))
17083 ((eq fmt 'add_numbers) (setq op "+"))
17084 ((eq fmt 'currency) (setq op "$")))
17085 (if (and op printf) (setq op (concat op ";" printf)))
17086 (if (equal title prop) (setq title nil))
17087 (setq s (concat "%" (if width (number-to-string width))
17088 prop
17089 (if title (concat "(" title ")"))
17090 (if op (concat "{" op "}"))))
17091 (setq rtn (concat rtn " " s)))
17092 (org-trim rtn)))
17094 (defun org-columns-compile-format (fmt)
17095 "Turn a column format string into an alist of specifications.
17096 The alist has one entry for each column in the format. The elements of
17097 that list are:
17098 property the property
17099 title the title field for the columns
17100 width the column width in characters, can be nil for automatic
17101 operator the operator if any
17102 format the output format for computed results, derived from operator
17103 printf a printf format for computed values"
17104 (let ((start 0) width prop title op f printf)
17105 (setq org-columns-current-fmt-compiled nil)
17106 (while (string-match
17107 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17108 fmt start)
17109 (setq start (match-end 0)
17110 width (match-string 1 fmt)
17111 prop (match-string 2 fmt)
17112 title (or (match-string 3 fmt) prop)
17113 op (match-string 4 fmt)
17114 f nil
17115 printf nil)
17116 (if width (setq width (string-to-number width)))
17117 (when (and op (string-match ";" op))
17118 (setq printf (substring op (match-end 0))
17119 op (substring op 0 (match-beginning 0))))
17120 (cond
17121 ((equal op "+") (setq f 'add_numbers))
17122 ((equal op "$") (setq f 'currency))
17123 ((equal op ":") (setq f 'add_times))
17124 ((equal op "X") (setq f 'checkbox)))
17125 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17126 (setq org-columns-current-fmt-compiled
17127 (nreverse org-columns-current-fmt-compiled))))
17130 ;;; Dynamic block for Column view
17132 (defun org-columns-capture-view ()
17133 "Get the column view of the current buffer and return it as a list.
17134 The list will contains the title row and all other rows. Each row is
17135 a list of fields."
17136 (save-excursion
17137 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17138 (n (length title)) row tbl)
17139 (goto-char (point-min))
17140 (while (re-search-forward "^\\*+ " nil t)
17141 (when (get-char-property (match-beginning 0) 'org-columns-key)
17142 (setq row nil)
17143 (loop for i from 0 to (1- n) do
17144 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17145 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17147 row))
17148 (setq row (nreverse row))
17149 (push row tbl)))
17150 (append (list title 'hline) (nreverse tbl)))))
17152 (defun org-dblock-write:columnview (params)
17153 "Write the column view table.
17154 PARAMS is a property list of parameters:
17156 :width enforce same column widths with <N> specifiers.
17157 :id the :ID: property of the entry where the columns view
17158 should be built, as a string. When `local', call locally.
17159 When `global' call column view with the cursor at the beginning
17160 of the buffer (usually this means that the whole buffer switches
17161 to column view).
17162 :hlines When t, insert a hline before each item. When a number, insert
17163 a hline before each level <= that number.
17164 :vlines When t, make each column a colgroup to enforce vertical lines."
17165 (let ((pos (move-marker (make-marker) (point)))
17166 (hlines (plist-get params :hlines))
17167 (vlines (plist-get params :vlines))
17168 tbl id idpos nfields tmp)
17169 (save-excursion
17170 (save-restriction
17171 (when (setq id (plist-get params :id))
17172 (cond ((not id) nil)
17173 ((eq id 'global) (goto-char (point-min)))
17174 ((eq id 'local) nil)
17175 ((setq idpos (org-find-entry-with-id id))
17176 (goto-char idpos))
17177 (t (error "Cannot find entry with :ID: %s" id))))
17178 (org-columns)
17179 (setq tbl (org-columns-capture-view))
17180 (setq nfields (length (car tbl)))
17181 (org-columns-quit)))
17182 (goto-char pos)
17183 (move-marker pos nil)
17184 (when tbl
17185 (when (plist-get params :hlines)
17186 (setq tmp nil)
17187 (while tbl
17188 (if (eq (car tbl) 'hline)
17189 (push (pop tbl) tmp)
17190 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17191 (if (and (not (eq (car tmp) 'hline))
17192 (or (eq hlines t)
17193 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17194 (push 'hline tmp)))
17195 (push (pop tbl) tmp)))
17196 (setq tbl (nreverse tmp)))
17197 (when vlines
17198 (setq tbl (mapcar (lambda (x)
17199 (if (eq 'hline x) x (cons "" x)))
17200 tbl))
17201 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17202 (setq pos (point))
17203 (insert (org-listtable-to-string tbl))
17204 (when (plist-get params :width)
17205 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17206 org-columns-current-widths "|")))
17207 (goto-char pos)
17208 (org-table-align))))
17210 (defun org-listtable-to-string (tbl)
17211 "Convert a listtable TBL to a string that contains the Org-mode table.
17212 The table still need to be alligned. The resulting string has no leading
17213 and tailing newline characters."
17214 (mapconcat
17215 (lambda (x)
17216 (cond
17217 ((listp x)
17218 (concat "|" (mapconcat 'identity x "|") "|"))
17219 ((eq x 'hline) "|-|")
17220 (t (error "Garbage in listtable: %s" x))))
17221 tbl "\n"))
17223 (defun org-insert-columns-dblock ()
17224 "Create a dynamic block capturing a column view table."
17225 (interactive)
17226 (let ((defaults '(:name "columnview" :hlines 1))
17227 (id (completing-read
17228 "Capture columns (local, global, entry with :ID: property) [local]: "
17229 (append '(("global") ("local"))
17230 (mapcar 'list (org-property-values "ID"))))))
17231 (if (equal id "") (setq id 'local))
17232 (if (equal id "global") (setq id 'global))
17233 (setq defaults (append defaults (list :id id)))
17234 (org-create-dblock defaults)
17235 (org-update-dblock)))
17237 ;;;; Timestamps
17239 (defvar org-last-changed-timestamp nil)
17240 (defvar org-time-was-given) ; dynamically scoped parameter
17241 (defvar org-end-time-was-given) ; dynamically scoped parameter
17242 (defvar org-ts-what) ; dynamically scoped parameter
17244 (defun org-time-stamp (arg)
17245 "Prompt for a date/time and insert a time stamp.
17246 If the user specifies a time like HH:MM, or if this command is called
17247 with a prefix argument, the time stamp will contain date and time.
17248 Otherwise, only the date will be included. All parts of a date not
17249 specified by the user will be filled in from the current date/time.
17250 So if you press just return without typing anything, the time stamp
17251 will represent the current date/time. If there is already a timestamp
17252 at the cursor, it will be modified."
17253 (interactive "P")
17254 (let* ((ts nil)
17255 (default-time
17256 ;; Default time is either today, or, when entering a range,
17257 ;; the range start.
17258 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17259 (save-excursion
17260 (re-search-backward
17261 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17262 (- (point) 20) t)))
17263 (apply 'encode-time (org-parse-time-string (match-string 1)))
17264 (current-time)))
17265 (default-input (and ts (org-get-compact-tod ts)))
17266 org-time-was-given org-end-time-was-given time)
17267 (cond
17268 ((and (org-at-timestamp-p)
17269 (eq last-command 'org-time-stamp)
17270 (eq this-command 'org-time-stamp))
17271 (insert "--")
17272 (setq time (let ((this-command this-command))
17273 (org-read-date arg 'totime nil nil default-time default-input)))
17274 (org-insert-time-stamp time (or org-time-was-given arg)))
17275 ((org-at-timestamp-p)
17276 (setq time (let ((this-command this-command))
17277 (org-read-date arg 'totime nil nil default-time default-input)))
17278 (when (org-at-timestamp-p) ; just to get the match data
17279 (replace-match "")
17280 (setq org-last-changed-timestamp
17281 (org-insert-time-stamp
17282 time (or org-time-was-given arg)
17283 nil nil nil (list org-end-time-was-given))))
17284 (message "Timestamp updated"))
17286 (setq time (let ((this-command this-command))
17287 (org-read-date arg 'totime nil nil default-time default-input)))
17288 (org-insert-time-stamp time (or org-time-was-given arg)
17289 nil nil nil (list org-end-time-was-given))))))
17291 ;; FIXME: can we use this for something else????
17292 ;; like computing time differences?????
17293 (defun org-get-compact-tod (s)
17294 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17295 (let* ((t1 (match-string 1 s))
17296 (h1 (string-to-number (match-string 2 s)))
17297 (m1 (string-to-number (match-string 3 s)))
17298 (t2 (and (match-end 4) (match-string 5 s)))
17299 (h2 (and t2 (string-to-number (match-string 6 s))))
17300 (m2 (and t2 (string-to-number (match-string 7 s))))
17301 dh dm)
17302 (if (not t2)
17304 (setq dh (- h2 h1) dm (- m2 m1))
17305 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17306 (concat t1 "+" (number-to-string dh)
17307 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17309 (defun org-time-stamp-inactive (&optional arg)
17310 "Insert an inactive time stamp.
17311 An inactive time stamp is enclosed in square brackets instead of angle
17312 brackets. It is inactive in the sense that it does not trigger agenda entries,
17313 does not link to the calendar and cannot be changed with the S-cursor keys.
17314 So these are more for recording a certain time/date."
17315 (interactive "P")
17316 (let (org-time-was-given org-end-time-was-given time)
17317 (setq time (org-read-date arg 'totime))
17318 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17319 nil nil (list org-end-time-was-given))))
17321 (defvar org-date-ovl (org-make-overlay 1 1))
17322 (org-overlay-put org-date-ovl 'face 'org-warning)
17323 (org-detach-overlay org-date-ovl)
17325 (defvar org-ans1) ; dynamically scoped parameter
17326 (defvar org-ans2) ; dynamically scoped parameter
17328 (defvar org-plain-time-of-day-regexp) ; defined below
17330 (defvar org-read-date-overlay nil)
17331 (defvar org-dcst nil) ; dynamically scoped
17333 (defun org-read-date (&optional with-time to-time from-string prompt
17334 default-time default-input)
17335 "Read a date, possibly a time, and make things smooth for the user.
17336 The prompt will suggest to enter an ISO date, but you can also enter anything
17337 which will at least partially be understood by `parse-time-string'.
17338 Unrecognized parts of the date will default to the current day, month, year,
17339 hour and minute. If this command is called to replace a timestamp at point,
17340 of to enter the second timestamp of a range, the default time is taken from the
17341 existing stamp. For example,
17342 3-2-5 --> 2003-02-05
17343 feb 15 --> currentyear-02-15
17344 sep 12 9 --> 2009-09-12
17345 12:45 --> today 12:45
17346 22 sept 0:34 --> currentyear-09-22 0:34
17347 12 --> currentyear-currentmonth-12
17348 Fri --> nearest Friday (today or later)
17349 etc.
17351 Furthermore you can specify a relative date by giving, as the *first* thing
17352 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17353 change in days weeks, months, years.
17354 With a single plus or minus, the date is relative to today. With a double
17355 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17356 +4d --> four days from today
17357 +4 --> same as above
17358 +2w --> two weeks from today
17359 ++5 --> five days from default date
17361 The function understands only English month and weekday abbreviations,
17362 but this can be configured with the variables `parse-time-months' and
17363 `parse-time-weekdays'.
17365 While prompting, a calendar is popped up - you can also select the
17366 date with the mouse (button 1). The calendar shows a period of three
17367 months. To scroll it to other months, use the keys `>' and `<'.
17368 If you don't like the calendar, turn it off with
17369 \(setq org-read-date-popup-calendar nil)
17371 With optional argument TO-TIME, the date will immediately be converted
17372 to an internal time.
17373 With an optional argument WITH-TIME, the prompt will suggest to also
17374 insert a time. Note that when WITH-TIME is not set, you can still
17375 enter a time, and this function will inform the calling routine about
17376 this change. The calling routine may then choose to change the format
17377 used to insert the time stamp into the buffer to include the time.
17378 With optional argument FROM-STRING, read from this string instead from
17379 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17380 the time/date that is used for everything that is not specified by the
17381 user."
17382 (require 'parse-time)
17383 (let* ((org-time-stamp-rounding-minutes
17384 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17385 (org-dcst org-display-custom-times)
17386 (ct (org-current-time))
17387 (def (or default-time ct))
17388 (defdecode (decode-time def))
17389 (dummy (progn
17390 (when (< (nth 2 defdecode) org-extend-today-until)
17391 (setcar (nthcdr 2 defdecode) -1)
17392 (setcar (nthcdr 1 defdecode) 59)
17393 (setq def (apply 'encode-time defdecode)
17394 defdecode (decode-time def)))))
17395 (calendar-move-hook nil)
17396 (view-diary-entries-initially nil)
17397 (view-calendar-holidays-initially nil)
17398 (timestr (format-time-string
17399 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17400 (prompt (concat (if prompt (concat prompt " ") "")
17401 (format "Date+time [%s]: " timestr)))
17402 ans (org-ans0 "") org-ans1 org-ans2 final)
17404 (cond
17405 (from-string (setq ans from-string))
17406 (org-read-date-popup-calendar
17407 (save-excursion
17408 (save-window-excursion
17409 (calendar)
17410 (calendar-forward-day (- (time-to-days def)
17411 (calendar-absolute-from-gregorian
17412 (calendar-current-date))))
17413 (org-eval-in-calendar nil t)
17414 (let* ((old-map (current-local-map))
17415 (map (copy-keymap calendar-mode-map))
17416 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17417 (org-defkey map (kbd "RET") 'org-calendar-select)
17418 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17419 'org-calendar-select-mouse)
17420 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17421 'org-calendar-select-mouse)
17422 (org-defkey minibuffer-local-map [(meta shift left)]
17423 (lambda () (interactive)
17424 (org-eval-in-calendar '(calendar-backward-month 1))))
17425 (org-defkey minibuffer-local-map [(meta shift right)]
17426 (lambda () (interactive)
17427 (org-eval-in-calendar '(calendar-forward-month 1))))
17428 (org-defkey minibuffer-local-map [(meta shift up)]
17429 (lambda () (interactive)
17430 (org-eval-in-calendar '(calendar-backward-year 1))))
17431 (org-defkey minibuffer-local-map [(meta shift down)]
17432 (lambda () (interactive)
17433 (org-eval-in-calendar '(calendar-forward-year 1))))
17434 (org-defkey minibuffer-local-map [(shift up)]
17435 (lambda () (interactive)
17436 (org-eval-in-calendar '(calendar-backward-week 1))))
17437 (org-defkey minibuffer-local-map [(shift down)]
17438 (lambda () (interactive)
17439 (org-eval-in-calendar '(calendar-forward-week 1))))
17440 (org-defkey minibuffer-local-map [(shift left)]
17441 (lambda () (interactive)
17442 (org-eval-in-calendar '(calendar-backward-day 1))))
17443 (org-defkey minibuffer-local-map [(shift right)]
17444 (lambda () (interactive)
17445 (org-eval-in-calendar '(calendar-forward-day 1))))
17446 (org-defkey minibuffer-local-map ">"
17447 (lambda () (interactive)
17448 (org-eval-in-calendar '(scroll-calendar-left 1))))
17449 (org-defkey minibuffer-local-map "<"
17450 (lambda () (interactive)
17451 (org-eval-in-calendar '(scroll-calendar-right 1))))
17452 (unwind-protect
17453 (progn
17454 (use-local-map map)
17455 (add-hook 'post-command-hook 'org-read-date-display)
17456 (setq org-ans0 (read-string prompt default-input nil nil))
17457 ;; org-ans0: from prompt
17458 ;; org-ans1: from mouse click
17459 ;; org-ans2: from calendar motion
17460 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17461 (remove-hook 'post-command-hook 'org-read-date-display)
17462 (use-local-map old-map)
17463 (when org-read-date-overlay
17464 (org-delete-overlay org-read-date-overlay)
17465 (setq org-read-date-overlay nil)))))))
17467 (t ; Naked prompt only
17468 (unwind-protect
17469 (setq ans (read-string prompt default-input nil timestr))
17470 (when org-read-date-overlay
17471 (org-delete-overlay org-read-date-overlay)
17472 (setq org-read-date-overlay nil)))))
17474 (setq final (org-read-date-analyze ans def defdecode))
17476 (if to-time
17477 (apply 'encode-time final)
17478 (if (and (boundp 'org-time-was-given) org-time-was-given)
17479 (format "%04d-%02d-%02d %02d:%02d"
17480 (nth 5 final) (nth 4 final) (nth 3 final)
17481 (nth 2 final) (nth 1 final))
17482 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17483 (defvar def)
17484 (defvar defdecode)
17485 (defvar with-time)
17486 (defun org-read-date-display ()
17487 "Display the currrent date prompt interpretation in the minibuffer."
17488 (when org-read-date-display-live
17489 (when org-read-date-overlay
17490 (org-delete-overlay org-read-date-overlay))
17491 (let ((p (point)))
17492 (end-of-line 1)
17493 (while (not (equal (buffer-substring
17494 (max (point-min) (- (point) 4)) (point))
17495 " "))
17496 (insert " "))
17497 (goto-char p))
17498 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17499 " " (or org-ans1 org-ans2)))
17500 (org-end-time-was-given nil)
17501 (f (org-read-date-analyze ans def defdecode))
17502 (fmts (if org-dcst
17503 org-time-stamp-custom-formats
17504 org-time-stamp-formats))
17505 (fmt (if (or with-time
17506 (and (boundp 'org-time-was-given) org-time-was-given))
17507 (cdr fmts)
17508 (car fmts)))
17509 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17510 (when (and org-end-time-was-given
17511 (string-match org-plain-time-of-day-regexp txt))
17512 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17513 org-end-time-was-given
17514 (substring txt (match-end 0)))))
17515 (setq org-read-date-overlay
17516 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17517 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17519 (defun org-read-date-analyze (ans def defdecode)
17520 "Analyze the combined answer of the date prompt."
17521 ;; FIXME: cleanup and comment
17522 (let (delta deltan deltaw deltadef year month day
17523 hour minute second wday pm h2 m2 tl wday1)
17525 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17526 (setq ans (replace-match "" t t ans)
17527 deltan (car delta)
17528 deltaw (nth 1 delta)
17529 deltadef (nth 2 delta)))
17531 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17532 (when (string-match
17533 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17534 (setq year (if (match-end 2)
17535 (string-to-number (match-string 2 ans))
17536 (string-to-number (format-time-string "%Y")))
17537 month (string-to-number (match-string 3 ans))
17538 day (string-to-number (match-string 4 ans)))
17539 (if (< year 100) (setq year (+ 2000 year)))
17540 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17541 t nil ans)))
17542 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17543 ;; If there is a time with am/pm, and *no* time without it, we convert
17544 ;; so that matching will be successful.
17545 (loop for i from 1 to 2 do ; twice, for end time as well
17546 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17547 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17548 (setq hour (string-to-number (match-string 1 ans))
17549 minute (if (match-end 3)
17550 (string-to-number (match-string 3 ans))
17552 pm (equal ?p
17553 (string-to-char (downcase (match-string 4 ans)))))
17554 (if (and (= hour 12) (not pm))
17555 (setq hour 0)
17556 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17557 (setq ans (replace-match (format "%02d:%02d" hour minute)
17558 t t ans))))
17560 ;; Check if a time range is given as a duration
17561 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17562 (setq hour (string-to-number (match-string 1 ans))
17563 h2 (+ hour (string-to-number (match-string 3 ans)))
17564 minute (string-to-number (match-string 2 ans))
17565 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17566 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17567 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17569 ;; Check if there is a time range
17570 (when (boundp 'org-end-time-was-given)
17571 (setq org-time-was-given nil)
17572 (when (and (string-match org-plain-time-of-day-regexp ans)
17573 (match-end 8))
17574 (setq org-end-time-was-given (match-string 8 ans))
17575 (setq ans (concat (substring ans 0 (match-beginning 7))
17576 (substring ans (match-end 7))))))
17578 (setq tl (parse-time-string ans)
17579 day (or (nth 3 tl) (nth 3 defdecode))
17580 month (or (nth 4 tl)
17581 (if (and org-read-date-prefer-future
17582 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17583 (1+ (nth 4 defdecode))
17584 (nth 4 defdecode)))
17585 year (or (nth 5 tl)
17586 (if (and org-read-date-prefer-future
17587 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17588 (1+ (nth 5 defdecode))
17589 (nth 5 defdecode)))
17590 hour (or (nth 2 tl) (nth 2 defdecode))
17591 minute (or (nth 1 tl) (nth 1 defdecode))
17592 second (or (nth 0 tl) 0)
17593 wday (nth 6 tl))
17594 (when deltan
17595 (unless deltadef
17596 (let ((now (decode-time (current-time))))
17597 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17598 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17599 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17600 ((equal deltaw "m") (setq month (+ month deltan)))
17601 ((equal deltaw "y") (setq year (+ year deltan)))))
17602 (when (and wday (not (nth 3 tl)))
17603 ;; Weekday was given, but no day, so pick that day in the week
17604 ;; on or after the derived date.
17605 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17606 (unless (equal wday wday1)
17607 (setq day (+ day (% (- wday wday1 -7) 7)))))
17608 (if (and (boundp 'org-time-was-given)
17609 (nth 2 tl))
17610 (setq org-time-was-given t))
17611 (if (< year 100) (setq year (+ 2000 year)))
17612 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17613 (list second minute hour day month year)))
17615 (defvar parse-time-weekdays)
17617 (defun org-read-date-get-relative (s today default)
17618 "Check string S for special relative date string.
17619 TODAY and DEFAULT are internal times, for today and for a default.
17620 Return shift list (N what def-flag)
17621 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17622 N is the number of WHATs to shift.
17623 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17624 the DEFAULT date rather than TODAY."
17625 (when (string-match
17626 (concat
17627 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17628 "\\([0-9]+\\)?"
17629 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17630 "\\([ \t]\\|$\\)") s)
17631 (let* ((dir (if (match-end 1)
17632 (string-to-char (substring (match-string 1 s) -1))
17633 ?+))
17634 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17635 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17636 (what (if (match-end 3) (match-string 3 s) "d"))
17637 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17638 (date (if rel default today))
17639 (wday (nth 6 (decode-time date)))
17640 delta)
17641 (if wday1
17642 (progn
17643 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17644 (if (= dir ?-) (setq delta (- delta 7)))
17645 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17646 (list delta "d" rel))
17647 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17649 (defun org-eval-in-calendar (form &optional keepdate)
17650 "Eval FORM in the calendar window and return to current window.
17651 Also, store the cursor date in variable org-ans2."
17652 (let ((sw (selected-window)))
17653 (select-window (get-buffer-window "*Calendar*"))
17654 (eval form)
17655 (when (and (not keepdate) (calendar-cursor-to-date))
17656 (let* ((date (calendar-cursor-to-date))
17657 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17658 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17659 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17660 (select-window sw)))
17662 ; ;; Update the prompt to show new default date
17663 ; (save-excursion
17664 ; (goto-char (point-min))
17665 ; (when (and org-ans2
17666 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17667 ; (get-text-property (match-end 0) 'field))
17668 ; (let ((inhibit-read-only t))
17669 ; (replace-match (concat "[" org-ans2 "]") t t)
17670 ; (add-text-properties (point-min) (1+ (match-end 0))
17671 ; (text-properties-at (1+ (point-min)))))))))
17673 (defun org-calendar-select ()
17674 "Return to `org-read-date' with the date currently selected.
17675 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17676 (interactive)
17677 (when (calendar-cursor-to-date)
17678 (let* ((date (calendar-cursor-to-date))
17679 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17680 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17681 (if (active-minibuffer-window) (exit-minibuffer))))
17683 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17684 "Insert a date stamp for the date given by the internal TIME.
17685 WITH-HM means, use the stamp format that includes the time of the day.
17686 INACTIVE means use square brackets instead of angular ones, so that the
17687 stamp will not contribute to the agenda.
17688 PRE and POST are optional strings to be inserted before and after the
17689 stamp.
17690 The command returns the inserted time stamp."
17691 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17692 stamp)
17693 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17694 (insert-before-markers (or pre ""))
17695 (insert-before-markers (setq stamp (format-time-string fmt time)))
17696 (when (listp extra)
17697 (setq extra (car extra))
17698 (if (and (stringp extra)
17699 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17700 (setq extra (format "-%02d:%02d"
17701 (string-to-number (match-string 1 extra))
17702 (string-to-number (match-string 2 extra))))
17703 (setq extra nil)))
17704 (when extra
17705 (backward-char 1)
17706 (insert-before-markers extra)
17707 (forward-char 1))
17708 (insert-before-markers (or post ""))
17709 stamp))
17711 (defun org-toggle-time-stamp-overlays ()
17712 "Toggle the use of custom time stamp formats."
17713 (interactive)
17714 (setq org-display-custom-times (not org-display-custom-times))
17715 (unless org-display-custom-times
17716 (let ((p (point-min)) (bmp (buffer-modified-p)))
17717 (while (setq p (next-single-property-change p 'display))
17718 (if (and (get-text-property p 'display)
17719 (eq (get-text-property p 'face) 'org-date))
17720 (remove-text-properties
17721 p (setq p (next-single-property-change p 'display))
17722 '(display t))))
17723 (set-buffer-modified-p bmp)))
17724 (if (featurep 'xemacs)
17725 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17726 (org-restart-font-lock)
17727 (setq org-table-may-need-update t)
17728 (if org-display-custom-times
17729 (message "Time stamps are overlayed with custom format")
17730 (message "Time stamp overlays removed")))
17732 (defun org-display-custom-time (beg end)
17733 "Overlay modified time stamp format over timestamp between BED and END."
17734 (let* ((ts (buffer-substring beg end))
17735 t1 w1 with-hm tf time str w2 (off 0))
17736 (save-match-data
17737 (setq t1 (org-parse-time-string ts t))
17738 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17739 (setq off (- (match-end 0) (match-beginning 0)))))
17740 (setq end (- end off))
17741 (setq w1 (- end beg)
17742 with-hm (and (nth 1 t1) (nth 2 t1))
17743 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17744 time (org-fix-decoded-time t1)
17745 str (org-add-props
17746 (format-time-string
17747 (substring tf 1 -1) (apply 'encode-time time))
17748 nil 'mouse-face 'highlight)
17749 w2 (length str))
17750 (if (not (= w2 w1))
17751 (add-text-properties (1+ beg) (+ 2 beg)
17752 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17753 (if (featurep 'xemacs)
17754 (progn
17755 (put-text-property beg end 'invisible t)
17756 (put-text-property beg end 'end-glyph (make-glyph str)))
17757 (put-text-property beg end 'display str))))
17759 (defun org-translate-time (string)
17760 "Translate all timestamps in STRING to custom format.
17761 But do this only if the variable `org-display-custom-times' is set."
17762 (when org-display-custom-times
17763 (save-match-data
17764 (let* ((start 0)
17765 (re org-ts-regexp-both)
17766 t1 with-hm inactive tf time str beg end)
17767 (while (setq start (string-match re string start))
17768 (setq beg (match-beginning 0)
17769 end (match-end 0)
17770 t1 (save-match-data
17771 (org-parse-time-string (substring string beg end) t))
17772 with-hm (and (nth 1 t1) (nth 2 t1))
17773 inactive (equal (substring string beg (1+ beg)) "[")
17774 tf (funcall (if with-hm 'cdr 'car)
17775 org-time-stamp-custom-formats)
17776 time (org-fix-decoded-time t1)
17777 str (format-time-string
17778 (concat
17779 (if inactive "[" "<") (substring tf 1 -1)
17780 (if inactive "]" ">"))
17781 (apply 'encode-time time))
17782 string (replace-match str t t string)
17783 start (+ start (length str)))))))
17784 string)
17786 (defun org-fix-decoded-time (time)
17787 "Set 0 instead of nil for the first 6 elements of time.
17788 Don't touch the rest."
17789 (let ((n 0))
17790 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17792 (defun org-days-to-time (timestamp-string)
17793 "Difference between TIMESTAMP-STRING and now in days."
17794 (- (time-to-days (org-time-string-to-time timestamp-string))
17795 (time-to-days (current-time))))
17797 (defun org-deadline-close (timestamp-string &optional ndays)
17798 "Is the time in TIMESTAMP-STRING close to the current date?"
17799 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17800 (and (< (org-days-to-time timestamp-string) ndays)
17801 (not (org-entry-is-done-p))))
17803 (defun org-get-wdays (ts)
17804 "Get the deadline lead time appropriate for timestring TS."
17805 (cond
17806 ((<= org-deadline-warning-days 0)
17807 ;; 0 or negative, enforce this value no matter what
17808 (- org-deadline-warning-days))
17809 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17810 ;; lead time is specified.
17811 (floor (* (string-to-number (match-string 1 ts))
17812 (cdr (assoc (match-string 2 ts)
17813 '(("d" . 1) ("w" . 7)
17814 ("m" . 30.4) ("y" . 365.25)))))))
17815 ;; go for the default.
17816 (t org-deadline-warning-days)))
17818 (defun org-calendar-select-mouse (ev)
17819 "Return to `org-read-date' with the date currently selected.
17820 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17821 (interactive "e")
17822 (mouse-set-point ev)
17823 (when (calendar-cursor-to-date)
17824 (let* ((date (calendar-cursor-to-date))
17825 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17826 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17827 (if (active-minibuffer-window) (exit-minibuffer))))
17829 (defun org-check-deadlines (ndays)
17830 "Check if there are any deadlines due or past due.
17831 A deadline is considered due if it happens within `org-deadline-warning-days'
17832 days from today's date. If the deadline appears in an entry marked DONE,
17833 it is not shown. The prefix arg NDAYS can be used to test that many
17834 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17835 (interactive "P")
17836 (let* ((org-warn-days
17837 (cond
17838 ((equal ndays '(4)) 100000)
17839 (ndays (prefix-numeric-value ndays))
17840 (t (abs org-deadline-warning-days))))
17841 (case-fold-search nil)
17842 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17843 (callback
17844 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17846 (message "%d deadlines past-due or due within %d days"
17847 (org-occur regexp nil callback)
17848 org-warn-days)))
17850 (defun org-check-before-date (date)
17851 "Check if there are deadlines or scheduled entries before DATE."
17852 (interactive (list (org-read-date)))
17853 (let ((case-fold-search nil)
17854 (regexp (concat "\\<\\(" org-deadline-string
17855 "\\|" org-scheduled-string
17856 "\\) *<\\([^>]+\\)>"))
17857 (callback
17858 (lambda () (time-less-p
17859 (org-time-string-to-time (match-string 2))
17860 (org-time-string-to-time date)))))
17861 (message "%d entries before %s"
17862 (org-occur regexp nil callback) date)))
17864 (defun org-evaluate-time-range (&optional to-buffer)
17865 "Evaluate a time range by computing the difference between start and end.
17866 Normally the result is just printed in the echo area, but with prefix arg
17867 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17868 If the time range is actually in a table, the result is inserted into the
17869 next column.
17870 For time difference computation, a year is assumed to be exactly 365
17871 days in order to avoid rounding problems."
17872 (interactive "P")
17874 (org-clock-update-time-maybe)
17875 (save-excursion
17876 (unless (org-at-date-range-p t)
17877 (goto-char (point-at-bol))
17878 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17879 (if (not (org-at-date-range-p t))
17880 (error "Not at a time-stamp range, and none found in current line")))
17881 (let* ((ts1 (match-string 1))
17882 (ts2 (match-string 2))
17883 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17884 (match-end (match-end 0))
17885 (time1 (org-time-string-to-time ts1))
17886 (time2 (org-time-string-to-time ts2))
17887 (t1 (time-to-seconds time1))
17888 (t2 (time-to-seconds time2))
17889 (diff (abs (- t2 t1)))
17890 (negative (< (- t2 t1) 0))
17891 ;; (ys (floor (* 365 24 60 60)))
17892 (ds (* 24 60 60))
17893 (hs (* 60 60))
17894 (fy "%dy %dd %02d:%02d")
17895 (fy1 "%dy %dd")
17896 (fd "%dd %02d:%02d")
17897 (fd1 "%dd")
17898 (fh "%02d:%02d")
17899 y d h m align)
17900 (if havetime
17901 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17903 d (floor (/ diff ds)) diff (mod diff ds)
17904 h (floor (/ diff hs)) diff (mod diff hs)
17905 m (floor (/ diff 60)))
17906 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17908 d (floor (+ (/ diff ds) 0.5))
17909 h 0 m 0))
17910 (if (not to-buffer)
17911 (message "%s" (org-make-tdiff-string y d h m))
17912 (if (org-at-table-p)
17913 (progn
17914 (goto-char match-end)
17915 (setq align t)
17916 (and (looking-at " *|") (goto-char (match-end 0))))
17917 (goto-char match-end))
17918 (if (looking-at
17919 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17920 (replace-match ""))
17921 (if negative (insert " -"))
17922 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17923 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17924 (insert " " (format fh h m))))
17925 (if align (org-table-align))
17926 (message "Time difference inserted")))))
17928 (defun org-make-tdiff-string (y d h m)
17929 (let ((fmt "")
17930 (l nil))
17931 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17932 l (push y l)))
17933 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17934 l (push d l)))
17935 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17936 l (push h l)))
17937 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17938 l (push m l)))
17939 (apply 'format fmt (nreverse l))))
17941 (defun org-time-string-to-time (s)
17942 (apply 'encode-time (org-parse-time-string s)))
17944 (defun org-time-string-to-absolute (s &optional daynr prefer)
17945 "Convert a time stamp to an absolute day number.
17946 If there is a specifyer for a cyclic time stamp, get the closest date to
17947 DAYNR."
17948 (cond
17949 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17950 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17951 daynr
17952 (+ daynr 1000)))
17953 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
17954 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17955 (time-to-days (current-time))) (match-string 0 s)
17956 prefer))
17957 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
17959 (defun org-time-from-absolute (d)
17960 "Return the time corresponding to date D.
17961 D may be an absolute day number, or a calendar-type list (month day year)."
17962 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17963 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17965 (defun org-calendar-holiday ()
17966 "List of holidays, for Diary display in Org-mode."
17967 (require 'holidays)
17968 (let ((hl (funcall
17969 (if (fboundp 'calendar-check-holidays)
17970 'calendar-check-holidays 'check-calendar-holidays) date)))
17971 (if hl (mapconcat 'identity hl "; "))))
17973 (defun org-diary-sexp-entry (sexp entry date)
17974 "Process a SEXP diary ENTRY for DATE."
17975 (require 'diary-lib)
17976 (let ((result (if calendar-debug-sexp
17977 (let ((stack-trace-on-error t))
17978 (eval (car (read-from-string sexp))))
17979 (condition-case nil
17980 (eval (car (read-from-string sexp)))
17981 (error
17982 (beep)
17983 (message "Bad sexp at line %d in %s: %s"
17984 (org-current-line)
17985 (buffer-file-name) sexp)
17986 (sleep-for 2))))))
17987 (cond ((stringp result) result)
17988 ((and (consp result)
17989 (stringp (cdr result))) (cdr result))
17990 (result entry)
17991 (t nil))))
17993 (defun org-diary-to-ical-string (frombuf)
17994 "Get iCalendar entries from diary entries in buffer FROMBUF.
17995 This uses the icalendar.el library."
17996 (let* ((tmpdir (if (featurep 'xemacs)
17997 (temp-directory)
17998 temporary-file-directory))
17999 (tmpfile (make-temp-name
18000 (expand-file-name "orgics" tmpdir)))
18001 buf rtn b e)
18002 (save-excursion
18003 (set-buffer frombuf)
18004 (icalendar-export-region (point-min) (point-max) tmpfile)
18005 (setq buf (find-buffer-visiting tmpfile))
18006 (set-buffer buf)
18007 (goto-char (point-min))
18008 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18009 (setq b (match-beginning 0)))
18010 (goto-char (point-max))
18011 (if (re-search-backward "^END:VEVENT" nil t)
18012 (setq e (match-end 0)))
18013 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18014 (kill-buffer buf)
18015 (kill-buffer frombuf)
18016 (delete-file tmpfile)
18017 rtn))
18019 (defun org-closest-date (start current change prefer)
18020 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18021 When PREFER is `past' return a date that is either CURRENT or past.
18022 When PREFER is `future', return a date that is either CURRENT or future."
18023 ;; Make the proper lists from the dates
18024 (catch 'exit
18025 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18026 dn dw sday cday n1 n2
18027 d m y y1 y2 date1 date2 nmonths nm ny m2)
18029 (setq start (org-date-to-gregorian start)
18030 current (org-date-to-gregorian
18031 (if org-agenda-repeating-timestamp-show-all
18032 current
18033 (time-to-days (current-time))))
18034 sday (calendar-absolute-from-gregorian start)
18035 cday (calendar-absolute-from-gregorian current))
18037 (if (<= cday sday) (throw 'exit sday))
18039 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18040 (setq dn (string-to-number (match-string 1 change))
18041 dw (cdr (assoc (match-string 2 change) a1)))
18042 (error "Invalid change specifyer: %s" change))
18043 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18044 (cond
18045 ((eq dw 'day)
18046 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18047 n2 (+ n1 dn)))
18048 ((eq dw 'year)
18049 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18050 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18051 (setq date1 (list m d y1)
18052 n1 (calendar-absolute-from-gregorian date1)
18053 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18054 n2 (calendar-absolute-from-gregorian date2)))
18055 ((eq dw 'month)
18056 ;; approx number of month between the tow dates
18057 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18058 ;; How often does dn fit in there?
18059 (setq d (nth 1 start) m (car start) y (nth 2 start)
18060 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18061 m (+ m nm)
18062 ny (floor (/ m 12))
18063 y (+ y ny)
18064 m (- m (* ny 12)))
18065 (while (> m 12) (setq m (- m 12) y (1+ y)))
18066 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18067 (setq m2 (+ m dn) y2 y)
18068 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18069 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18070 (while (< n2 cday)
18071 (setq n1 n2 m m2 y y2)
18072 (setq m2 (+ m dn) y2 y)
18073 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18074 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18076 (if org-agenda-repeating-timestamp-show-all
18077 (cond
18078 ((eq prefer 'past) n1)
18079 ((eq prefer 'future) (if (= cday n1) n1 n2))
18080 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18081 (cond
18082 ((eq prefer 'past) n1)
18083 ((eq prefer 'future) (if (= cday n1) n1 n2))
18084 (t (if (= cday n1) n1 n2)))))))
18086 (defun org-date-to-gregorian (date)
18087 "Turn any specification of DATE into a gregorian date for the calendar."
18088 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18089 ((and (listp date) (= (length date) 3)) date)
18090 ((stringp date)
18091 (setq date (org-parse-time-string date))
18092 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18093 ((listp date)
18094 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18096 (defun org-parse-time-string (s &optional nodefault)
18097 "Parse the standard Org-mode time string.
18098 This should be a lot faster than the normal `parse-time-string'.
18099 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18100 hour and minute fields will be nil if not given."
18101 (if (string-match org-ts-regexp0 s)
18102 (list 0
18103 (if (or (match-beginning 8) (not nodefault))
18104 (string-to-number (or (match-string 8 s) "0")))
18105 (if (or (match-beginning 7) (not nodefault))
18106 (string-to-number (or (match-string 7 s) "0")))
18107 (string-to-number (match-string 4 s))
18108 (string-to-number (match-string 3 s))
18109 (string-to-number (match-string 2 s))
18110 nil nil nil)
18111 (make-list 9 0)))
18113 (defun org-timestamp-up (&optional arg)
18114 "Increase the date item at the cursor by one.
18115 If the cursor is on the year, change the year. If it is on the month or
18116 the day, change that.
18117 With prefix ARG, change by that many units."
18118 (interactive "p")
18119 (org-timestamp-change (prefix-numeric-value arg)))
18121 (defun org-timestamp-down (&optional arg)
18122 "Decrease the date item at the cursor by one.
18123 If the cursor is on the year, change the year. If it is on the month or
18124 the day, change that.
18125 With prefix ARG, change by that many units."
18126 (interactive "p")
18127 (org-timestamp-change (- (prefix-numeric-value arg))))
18129 (defun org-timestamp-up-day (&optional arg)
18130 "Increase the date in the time stamp by one day.
18131 With prefix ARG, change that many days."
18132 (interactive "p")
18133 (if (and (not (org-at-timestamp-p t))
18134 (org-on-heading-p))
18135 (org-todo 'up)
18136 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18138 (defun org-timestamp-down-day (&optional arg)
18139 "Decrease the date in the time stamp by one day.
18140 With prefix ARG, change that many days."
18141 (interactive "p")
18142 (if (and (not (org-at-timestamp-p t))
18143 (org-on-heading-p))
18144 (org-todo 'down)
18145 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18147 (defsubst org-pos-in-match-range (pos n)
18148 (and (match-beginning n)
18149 (<= (match-beginning n) pos)
18150 (>= (match-end n) pos)))
18152 (defun org-at-timestamp-p (&optional inactive-ok)
18153 "Determine if the cursor is in or at a timestamp."
18154 (interactive)
18155 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18156 (pos (point))
18157 (ans (or (looking-at tsr)
18158 (save-excursion
18159 (skip-chars-backward "^[<\n\r\t")
18160 (if (> (point) (point-min)) (backward-char 1))
18161 (and (looking-at tsr)
18162 (> (- (match-end 0) pos) -1))))))
18163 (and ans
18164 (boundp 'org-ts-what)
18165 (setq org-ts-what
18166 (cond
18167 ((= pos (match-beginning 0)) 'bracket)
18168 ((= pos (1- (match-end 0))) 'bracket)
18169 ((org-pos-in-match-range pos 2) 'year)
18170 ((org-pos-in-match-range pos 3) 'month)
18171 ((org-pos-in-match-range pos 7) 'hour)
18172 ((org-pos-in-match-range pos 8) 'minute)
18173 ((or (org-pos-in-match-range pos 4)
18174 (org-pos-in-match-range pos 5)) 'day)
18175 ((and (> pos (or (match-end 8) (match-end 5)))
18176 (< pos (match-end 0)))
18177 (- pos (or (match-end 8) (match-end 5))))
18178 (t 'day))))
18179 ans))
18181 (defun org-toggle-timestamp-type ()
18183 (interactive)
18184 (when (org-at-timestamp-p t)
18185 (save-excursion
18186 (goto-char (match-beginning 0))
18187 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18188 (goto-char (1- (match-end 0)))
18189 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18190 (message "Timestamp is now %sactive"
18191 (if (equal (char-before) ?>) "in" ""))))
18193 (defun org-timestamp-change (n &optional what)
18194 "Change the date in the time stamp at point.
18195 The date will be changed by N times WHAT. WHAT can be `day', `month',
18196 `year', `minute', `second'. If WHAT is not given, the cursor position
18197 in the timestamp determines what will be changed."
18198 (let ((pos (point))
18199 with-hm inactive
18200 org-ts-what
18201 extra
18202 ts time time0)
18203 (if (not (org-at-timestamp-p t))
18204 (error "Not at a timestamp"))
18205 (if (and (not what) (eq org-ts-what 'bracket))
18206 (org-toggle-timestamp-type)
18207 (if (and (not what) (not (eq org-ts-what 'day))
18208 org-display-custom-times
18209 (get-text-property (point) 'display)
18210 (not (get-text-property (1- (point)) 'display)))
18211 (setq org-ts-what 'day))
18212 (setq org-ts-what (or what org-ts-what)
18213 inactive (= (char-after (match-beginning 0)) ?\[)
18214 ts (match-string 0))
18215 (replace-match "")
18216 (if (string-match
18217 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18219 (setq extra (match-string 1 ts)))
18220 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18221 (setq with-hm t))
18222 (setq time0 (org-parse-time-string ts))
18223 (setq time
18224 (encode-time (or (car time0) 0)
18225 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18226 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18227 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18228 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18229 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18230 (nthcdr 6 time0)))
18231 (when (integerp org-ts-what)
18232 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18233 (if (eq what 'calendar)
18234 (let ((cal-date (org-get-date-from-calendar)))
18235 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18236 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18237 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18238 (setcar time0 (or (car time0) 0))
18239 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18240 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18241 (setq time (apply 'encode-time time0))))
18242 (setq org-last-changed-timestamp
18243 (org-insert-time-stamp time with-hm inactive nil nil extra))
18244 (org-clock-update-time-maybe)
18245 (goto-char pos)
18246 ;; Try to recenter the calendar window, if any
18247 (if (and org-calendar-follow-timestamp-change
18248 (get-buffer-window "*Calendar*" t)
18249 (memq org-ts-what '(day month year)))
18250 (org-recenter-calendar (time-to-days time))))))
18252 ;; FIXME: does not yet work for lead times
18253 (defun org-modify-ts-extra (s pos n)
18254 "Change the different parts of the lead-time and repeat fields in timestamp."
18255 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18256 ng h m new)
18257 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18258 (cond
18259 ((or (org-pos-in-match-range pos 2)
18260 (org-pos-in-match-range pos 3))
18261 (setq m (string-to-number (match-string 3 s))
18262 h (string-to-number (match-string 2 s)))
18263 (if (org-pos-in-match-range pos 2)
18264 (setq h (+ h n))
18265 (setq m (+ m n)))
18266 (if (< m 0) (setq m (+ m 60) h (1- h)))
18267 (if (> m 59) (setq m (- m 60) h (1+ h)))
18268 (setq h (min 24 (max 0 h)))
18269 (setq ng 1 new (format "-%02d:%02d" h m)))
18270 ((org-pos-in-match-range pos 6)
18271 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18272 ((org-pos-in-match-range pos 5)
18273 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18275 (when ng
18276 (setq s (concat
18277 (substring s 0 (match-beginning ng))
18279 (substring s (match-end ng))))))
18282 (defun org-recenter-calendar (date)
18283 "If the calendar is visible, recenter it to DATE."
18284 (let* ((win (selected-window))
18285 (cwin (get-buffer-window "*Calendar*" t))
18286 (calendar-move-hook nil))
18287 (when cwin
18288 (select-window cwin)
18289 (calendar-goto-date (if (listp date) date
18290 (calendar-gregorian-from-absolute date)))
18291 (select-window win))))
18293 (defun org-goto-calendar (&optional arg)
18294 "Go to the Emacs calendar at the current date.
18295 If there is a time stamp in the current line, go to that date.
18296 A prefix ARG can be used to force the current date."
18297 (interactive "P")
18298 (let ((tsr org-ts-regexp) diff
18299 (calendar-move-hook nil)
18300 (view-calendar-holidays-initially nil)
18301 (view-diary-entries-initially nil))
18302 (if (or (org-at-timestamp-p)
18303 (save-excursion
18304 (beginning-of-line 1)
18305 (looking-at (concat ".*" tsr))))
18306 (let ((d1 (time-to-days (current-time)))
18307 (d2 (time-to-days
18308 (org-time-string-to-time (match-string 1)))))
18309 (setq diff (- d2 d1))))
18310 (calendar)
18311 (calendar-goto-today)
18312 (if (and diff (not arg)) (calendar-forward-day diff))))
18314 (defun org-get-date-from-calendar ()
18315 "Return a list (month day year) of date at point in calendar."
18316 (with-current-buffer "*Calendar*"
18317 (save-match-data
18318 (calendar-cursor-to-date))))
18320 (defun org-date-from-calendar ()
18321 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18322 If there is already a time stamp at the cursor position, update it."
18323 (interactive)
18324 (if (org-at-timestamp-p t)
18325 (org-timestamp-change 0 'calendar)
18326 (let ((cal-date (org-get-date-from-calendar)))
18327 (org-insert-time-stamp
18328 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18330 ;; Make appt aware of appointments from the agenda
18331 ;;;###autoload
18332 (defun org-agenda-to-appt (&optional filter)
18333 "Activate appointments found in `org-agenda-files'.
18334 When prefixed, prompt for a regular expression and use it as a
18335 filter: only add entries if they match this regular expression.
18337 FILTER can be a string. In this case, use this string as a
18338 regular expression to filter results.
18340 FILTER can also be an alist, with the car of each cell being
18341 either 'headline or 'category. For example:
18343 '((headline \"IMPORTANT\")
18344 (category \"Work\"))
18346 will only add headlines containing IMPORTANT or headlines
18347 belonging to the category \"Work\"."
18348 (interactive "P")
18349 (require 'calendar)
18350 (if (equal filter '(4))
18351 (setq filter (read-from-minibuffer "Regexp filter: ")))
18352 (let* ((cnt 0) ; count added events
18353 (org-agenda-new-buffers nil)
18354 (today (org-date-to-gregorian
18355 (time-to-days (current-time))))
18356 (files (org-agenda-files)) entries file)
18357 ;; Get all entries which may contain an appt
18358 (while (setq file (pop files))
18359 (setq entries
18360 (append entries
18361 (org-agenda-get-day-entries
18362 file today
18363 :timestamp :scheduled :deadline))))
18364 (setq entries (delq nil entries))
18365 ;; Map thru entries and find if they pass thru the filter
18366 (mapc
18367 (lambda(x)
18368 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18369 (cat (get-text-property 1 'org-category x))
18370 (tod (get-text-property 1 'time-of-day x))
18371 (ok (or (null filter)
18372 (and (stringp filter) (string-match filter evt))
18373 (and (listp filter)
18374 (or (string-match
18375 (cadr (assoc 'category filter)) cat)
18376 (string-match
18377 (cadr (assoc 'headline filter)) evt))))))
18378 ;; FIXME: Shall we remove text-properties for the appt text?
18379 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18380 (when (and ok tod)
18381 (setq tod (number-to-string tod)
18382 tod (when (string-match
18383 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18384 (concat (match-string 1 tod) ":"
18385 (match-string 2 tod))))
18386 (appt-add tod evt)
18387 (setq cnt (1+ cnt))))) entries)
18388 (org-release-buffers org-agenda-new-buffers)
18389 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18391 ;;; The clock for measuring work time.
18393 (defvar org-mode-line-string "")
18394 (put 'org-mode-line-string 'risky-local-variable t)
18396 (defvar org-mode-line-timer nil)
18397 (defvar org-clock-heading "")
18398 (defvar org-clock-start-time "")
18400 (defun org-update-mode-line ()
18401 (let* ((delta (- (time-to-seconds (current-time))
18402 (time-to-seconds org-clock-start-time)))
18403 (h (floor delta 3600))
18404 (m (floor (- delta (* 3600 h)) 60)))
18405 (setq org-mode-line-string
18406 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18407 'help-echo "Org-mode clock is running"))
18408 (force-mode-line-update)))
18410 (defvar org-clock-marker (make-marker)
18411 "Marker recording the last clock-in.")
18412 (defvar org-clock-mode-line-entry nil
18413 "Information for the modeline about the running clock.")
18415 (defun org-clock-in ()
18416 "Start the clock on the current item.
18417 If necessary, clock-out of the currently active clock."
18418 (interactive)
18419 (org-clock-out t)
18420 (let (ts)
18421 (save-excursion
18422 (org-back-to-heading t)
18423 (when (and org-clock-in-switch-to-state
18424 (not (looking-at (concat outline-regexp "[ \t]*"
18425 org-clock-in-switch-to-state
18426 "\\>"))))
18427 (org-todo org-clock-in-switch-to-state))
18428 (if (and org-clock-heading-function
18429 (functionp org-clock-heading-function))
18430 (setq org-clock-heading (funcall org-clock-heading-function))
18431 (if (looking-at org-complex-heading-regexp)
18432 (setq org-clock-heading (match-string 4))
18433 (setq org-clock-heading "???")))
18434 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18435 (org-clock-find-position)
18437 (insert "\n") (backward-char 1)
18438 (indent-relative)
18439 (insert org-clock-string " ")
18440 (setq org-clock-start-time (current-time))
18441 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18442 (move-marker org-clock-marker (point) (buffer-base-buffer))
18443 (or global-mode-string (setq global-mode-string '("")))
18444 (or (memq 'org-mode-line-string global-mode-string)
18445 (setq global-mode-string
18446 (append global-mode-string '(org-mode-line-string))))
18447 (org-update-mode-line)
18448 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18449 (message "Clock started at %s" ts))))
18451 (defun org-clock-find-position ()
18452 "Find the location where the next clock line should be inserted."
18453 (org-back-to-heading t)
18454 (catch 'exit
18455 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18456 (re (concat "^[ \t]*" org-clock-string))
18457 (cnt 0)
18458 first last)
18459 (goto-char beg)
18460 (when (eobp) (newline) (setq end (max (point) end)))
18461 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18462 ;; we seem to have a CLOCK drawer, so go there.
18463 (beginning-of-line 2)
18464 (throw 'exit t))
18465 ;; Lets count the CLOCK lines
18466 (goto-char beg)
18467 (while (re-search-forward re end t)
18468 (setq first (or first (match-beginning 0))
18469 last (match-beginning 0)
18470 cnt (1+ cnt)))
18471 (when (and (integerp org-clock-into-drawer)
18472 (>= (1+ cnt) org-clock-into-drawer))
18473 ;; Wrap current entries into a new drawer
18474 (goto-char last)
18475 (beginning-of-line 2)
18476 (if (org-at-item-p) (org-end-of-item))
18477 (insert ":END:\n")
18478 (beginning-of-line 0)
18479 (org-indent-line-function)
18480 (goto-char first)
18481 (insert ":CLOCK:\n")
18482 (beginning-of-line 0)
18483 (org-indent-line-function)
18484 (org-flag-drawer t)
18485 (beginning-of-line 2)
18486 (throw 'exit nil))
18488 (goto-char beg)
18489 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18490 (not (equal (match-string 1) org-clock-string)))
18491 ;; Planning info, skip to after it
18492 (beginning-of-line 2)
18493 (or (bolp) (newline)))
18494 (when (eq t org-clock-into-drawer)
18495 (insert ":CLOCK:\n:END:\n")
18496 (beginning-of-line -1)
18497 (org-indent-line-function)
18498 (org-flag-drawer t)
18499 (beginning-of-line 2)
18500 (org-indent-line-function)))))
18502 (defun org-clock-out (&optional fail-quietly)
18503 "Stop the currently running clock.
18504 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18505 (interactive)
18506 (catch 'exit
18507 (if (not (marker-buffer org-clock-marker))
18508 (if fail-quietly (throw 'exit t) (error "No active clock")))
18509 (let (ts te s h m)
18510 (save-excursion
18511 (set-buffer (marker-buffer org-clock-marker))
18512 (goto-char org-clock-marker)
18513 (beginning-of-line 1)
18514 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18515 (equal (match-string 1) org-clock-string))
18516 (setq ts (match-string 2))
18517 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18518 (goto-char (match-end 0))
18519 (delete-region (point) (point-at-eol))
18520 (insert "--")
18521 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18522 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18523 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18524 h (floor (/ s 3600))
18525 s (- s (* 3600 h))
18526 m (floor (/ s 60))
18527 s (- s (* 60 s)))
18528 (insert " => " (format "%2d:%02d" h m))
18529 (move-marker org-clock-marker nil)
18530 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18531 (org-log-done (org-parse-local-options logging 'org-log-done))
18532 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18533 (org-add-log-maybe 'clock-out))
18534 (when org-mode-line-timer
18535 (cancel-timer org-mode-line-timer)
18536 (setq org-mode-line-timer nil))
18537 (setq global-mode-string
18538 (delq 'org-mode-line-string global-mode-string))
18539 (force-mode-line-update)
18540 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18542 (defun org-clock-cancel ()
18543 "Cancel the running clock be removing the start timestamp."
18544 (interactive)
18545 (if (not (marker-buffer org-clock-marker))
18546 (error "No active clock"))
18547 (save-excursion
18548 (set-buffer (marker-buffer org-clock-marker))
18549 (goto-char org-clock-marker)
18550 (delete-region (1- (point-at-bol)) (point-at-eol)))
18551 (setq global-mode-string
18552 (delq 'org-mode-line-string global-mode-string))
18553 (force-mode-line-update)
18554 (message "Clock canceled"))
18556 (defun org-clock-goto (&optional delete-windows)
18557 "Go to the currently clocked-in entry."
18558 (interactive "P")
18559 (if (not (marker-buffer org-clock-marker))
18560 (error "No active clock"))
18561 (switch-to-buffer-other-window
18562 (marker-buffer org-clock-marker))
18563 (if delete-windows (delete-other-windows))
18564 (goto-char org-clock-marker)
18565 (org-show-entry)
18566 (org-back-to-heading)
18567 (recenter))
18569 (defvar org-clock-file-total-minutes nil
18570 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18571 (make-variable-buffer-local 'org-clock-file-total-minutes)
18573 (defun org-clock-sum (&optional tstart tend)
18574 "Sum the times for each subtree.
18575 Puts the resulting times in minutes as a text property on each headline."
18576 (interactive)
18577 (let* ((bmp (buffer-modified-p))
18578 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18579 org-clock-string
18580 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18581 (lmax 30)
18582 (ltimes (make-vector lmax 0))
18583 (t1 0)
18584 (level 0)
18585 ts te dt
18586 time)
18587 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18588 (save-excursion
18589 (goto-char (point-max))
18590 (while (re-search-backward re nil t)
18591 (cond
18592 ((match-end 2)
18593 ;; Two time stamps
18594 (setq ts (match-string 2)
18595 te (match-string 3)
18596 ts (time-to-seconds
18597 (apply 'encode-time (org-parse-time-string ts)))
18598 te (time-to-seconds
18599 (apply 'encode-time (org-parse-time-string te)))
18600 ts (if tstart (max ts tstart) ts)
18601 te (if tend (min te tend) te)
18602 dt (- te ts)
18603 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18604 ((match-end 4)
18605 ;; A naket time
18606 (setq t1 (+ t1 (string-to-number (match-string 5))
18607 (* 60 (string-to-number (match-string 4))))))
18608 (t ;; A headline
18609 (setq level (- (match-end 1) (match-beginning 1)))
18610 (when (or (> t1 0) (> (aref ltimes level) 0))
18611 (loop for l from 0 to level do
18612 (aset ltimes l (+ (aref ltimes l) t1)))
18613 (setq t1 0 time (aref ltimes level))
18614 (loop for l from level to (1- lmax) do
18615 (aset ltimes l 0))
18616 (goto-char (match-beginning 0))
18617 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18618 (setq org-clock-file-total-minutes (aref ltimes 0)))
18619 (set-buffer-modified-p bmp)))
18621 (defun org-clock-display (&optional total-only)
18622 "Show subtree times in the entire buffer.
18623 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18624 in the echo area."
18625 (interactive)
18626 (org-remove-clock-overlays)
18627 (let (time h m p)
18628 (org-clock-sum)
18629 (unless total-only
18630 (save-excursion
18631 (goto-char (point-min))
18632 (while (or (and (equal (setq p (point)) (point-min))
18633 (get-text-property p :org-clock-minutes))
18634 (setq p (next-single-property-change
18635 (point) :org-clock-minutes)))
18636 (goto-char p)
18637 (when (setq time (get-text-property p :org-clock-minutes))
18638 (org-put-clock-overlay time (funcall outline-level))))
18639 (setq h (/ org-clock-file-total-minutes 60)
18640 m (- org-clock-file-total-minutes (* 60 h)))
18641 ;; Arrange to remove the overlays upon next change.
18642 (when org-remove-highlights-with-change
18643 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18644 nil 'local))))
18645 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18647 (defvar org-clock-overlays nil)
18648 (make-variable-buffer-local 'org-clock-overlays)
18650 (defun org-put-clock-overlay (time &optional level)
18651 "Put an overlays on the current line, displaying TIME.
18652 If LEVEL is given, prefix time with a corresponding number of stars.
18653 This creates a new overlay and stores it in `org-clock-overlays', so that it
18654 will be easy to remove."
18655 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18656 (l (if level (org-get-legal-level level 0) 0))
18657 (off 0)
18658 ov tx)
18659 (move-to-column c)
18660 (unless (eolp) (skip-chars-backward "^ \t"))
18661 (skip-chars-backward " \t")
18662 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18663 tx (concat (buffer-substring (1- (point)) (point))
18664 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18665 (org-add-props (format "%s %2d:%02d%s"
18666 (make-string l ?*) h m
18667 (make-string (- 10 l) ?\ ))
18668 '(face secondary-selection))
18669 ""))
18670 (if (not (featurep 'xemacs))
18671 (org-overlay-put ov 'display tx)
18672 (org-overlay-put ov 'invisible t)
18673 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18674 (push ov org-clock-overlays)))
18676 (defun org-remove-clock-overlays (&optional beg end noremove)
18677 "Remove the occur highlights from the buffer.
18678 BEG and END are ignored. If NOREMOVE is nil, remove this function
18679 from the `before-change-functions' in the current buffer."
18680 (interactive)
18681 (unless org-inhibit-highlight-removal
18682 (mapc 'org-delete-overlay org-clock-overlays)
18683 (setq org-clock-overlays nil)
18684 (unless noremove
18685 (remove-hook 'before-change-functions
18686 'org-remove-clock-overlays 'local))))
18688 (defun org-clock-out-if-current ()
18689 "Clock out if the current entry contains the running clock.
18690 This is used to stop the clock after a TODO entry is marked DONE,
18691 and is only done if the variable `org-clock-out-when-done' is not nil."
18692 (when (and org-clock-out-when-done
18693 (member state org-done-keywords)
18694 (equal (marker-buffer org-clock-marker) (current-buffer))
18695 (< (point) org-clock-marker)
18696 (> (save-excursion (outline-next-heading) (point))
18697 org-clock-marker))
18698 ;; Clock out, but don't accept a logging message for this.
18699 (let ((org-log-done (if (and (listp org-log-done)
18700 (member 'clock-out org-log-done))
18701 '(done)
18702 org-log-done)))
18703 (org-clock-out))))
18705 (add-hook 'org-after-todo-state-change-hook
18706 'org-clock-out-if-current)
18708 (defun org-check-running-clock ()
18709 "Check if the current buffer contains the running clock.
18710 If yes, offer to stop it and to save the buffer with the changes."
18711 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18712 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18713 (buffer-name))))
18714 (org-clock-out)
18715 (when (y-or-n-p "Save changed buffer?")
18716 (save-buffer))))
18718 (defun org-clock-report (&optional arg)
18719 "Create a table containing a report about clocked time.
18720 If the cursor is inside an existing clocktable block, then the table
18721 will be updated. If not, a new clocktable will be inserted.
18722 When called with a prefix argument, move to the first clock table in the
18723 buffer and update it."
18724 (interactive "P")
18725 (org-remove-clock-overlays)
18726 (when arg (org-find-dblock "clocktable"))
18727 (if (org-in-clocktable-p)
18728 (goto-char (org-in-clocktable-p))
18729 (org-create-dblock (list :name "clocktable"
18730 :maxlevel 2 :scope 'file)))
18731 (org-update-dblock))
18733 (defun org-in-clocktable-p ()
18734 "Check if the cursor is in a clocktable."
18735 (let ((pos (point)) start)
18736 (save-excursion
18737 (end-of-line 1)
18738 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18739 (setq start (match-beginning 0))
18740 (re-search-forward "^#\\+END:.*" nil t)
18741 (>= (match-end 0) pos)
18742 start))))
18744 (defun org-clock-update-time-maybe ()
18745 "If this is a CLOCK line, update it and return t.
18746 Otherwise, return nil."
18747 (interactive)
18748 (save-excursion
18749 (beginning-of-line 1)
18750 (skip-chars-forward " \t")
18751 (when (looking-at org-clock-string)
18752 (let ((re (concat "[ \t]*" org-clock-string
18753 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18754 "\\([ \t]*=>.*\\)?"))
18755 ts te h m s)
18756 (if (not (looking-at re))
18758 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18759 (end-of-line 1)
18760 (setq ts (match-string 1)
18761 te (match-string 2))
18762 (setq s (- (time-to-seconds
18763 (apply 'encode-time (org-parse-time-string te)))
18764 (time-to-seconds
18765 (apply 'encode-time (org-parse-time-string ts))))
18766 h (floor (/ s 3600))
18767 s (- s (* 3600 h))
18768 m (floor (/ s 60))
18769 s (- s (* 60 s)))
18770 (insert " => " (format "%2d:%02d" h m))
18771 t)))))
18773 (defun org-clock-special-range (key &optional time as-strings)
18774 "Return two times bordering a special time range.
18775 Key is a symbol specifying the range and can be one of `today', `yesterday',
18776 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18777 A week starts Monday 0:00 and ends Sunday 24:00.
18778 The range is determined relative to TIME. TIME defaults to the current time.
18779 The return value is a cons cell with two internal times like the ones
18780 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18781 the returned times will be formatted strings."
18782 (let* ((tm (decode-time (or time (current-time))))
18783 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18784 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18785 (dow (nth 6 tm))
18786 s1 m1 h1 d1 month1 y1 diff ts te fm)
18787 (cond
18788 ((eq key 'today)
18789 (setq h 0 m 0 h1 24 m1 0))
18790 ((eq key 'yesterday)
18791 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18792 ((eq key 'thisweek)
18793 (setq diff (if (= dow 0) 6 (1- dow))
18794 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18795 ((eq key 'lastweek)
18796 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18797 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18798 ((eq key 'thismonth)
18799 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18800 ((eq key 'lastmonth)
18801 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18802 ((eq key 'thisyear)
18803 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18804 ((eq key 'lastyear)
18805 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18806 (t (error "No such time block %s" key)))
18807 (setq ts (encode-time s m h d month y)
18808 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18809 (or d1 d) (or month1 month) (or y1 y)))
18810 (setq fm (cdr org-time-stamp-formats))
18811 (if as-strings
18812 (cons (format-time-string fm ts) (format-time-string fm te))
18813 (cons ts te))))
18815 (defun org-dblock-write:clocktable (params)
18816 "Write the standard clocktable."
18817 (catch 'exit
18818 (let* ((hlchars '((1 . "*") (2 . "/")))
18819 (ins (make-marker))
18820 (total-time nil)
18821 (scope (plist-get params :scope))
18822 (tostring (plist-get params :tostring))
18823 (multifile (plist-get params :multifile))
18824 (header (plist-get params :header))
18825 (maxlevel (or (plist-get params :maxlevel) 3))
18826 (step (plist-get params :step))
18827 (emph (plist-get params :emphasize))
18828 (ts (plist-get params :tstart))
18829 (te (plist-get params :tend))
18830 (block (plist-get params :block))
18831 ipos time h m p level hlc hdl
18832 cc beg end pos tbl)
18833 (when step
18834 (org-clocktable-steps params)
18835 (throw 'exit nil))
18836 (when block
18837 (setq cc (org-clock-special-range block nil t)
18838 ts (car cc) te (cdr cc)))
18839 (if ts (setq ts (time-to-seconds
18840 (apply 'encode-time (org-parse-time-string ts)))))
18841 (if te (setq te (time-to-seconds
18842 (apply 'encode-time (org-parse-time-string te)))))
18843 (move-marker ins (point))
18844 (setq ipos (point))
18846 ;; Get the right scope
18847 (setq pos (point))
18848 (save-restriction
18849 (cond
18850 ((not scope))
18851 ((eq scope 'file) (widen))
18852 ((eq scope 'subtree) (org-narrow-to-subtree))
18853 ((eq scope 'tree)
18854 (while (org-up-heading-safe))
18855 (org-narrow-to-subtree))
18856 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18857 (symbol-name scope)))
18858 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18859 (catch 'exit
18860 (while (org-up-heading-safe)
18861 (looking-at outline-regexp)
18862 (if (<= (org-reduced-level (funcall outline-level)) level)
18863 (throw 'exit nil))))
18864 (org-narrow-to-subtree))
18865 ((or (listp scope) (eq scope 'agenda))
18866 (let* ((files (if (listp scope) scope (org-agenda-files)))
18867 (scope 'agenda)
18868 (p1 (copy-sequence params))
18869 file)
18870 (plist-put p1 :tostring t)
18871 (plist-put p1 :multifile t)
18872 (plist-put p1 :scope 'file)
18873 (org-prepare-agenda-buffers files)
18874 (while (setq file (pop files))
18875 (with-current-buffer (find-buffer-visiting file)
18876 (push (org-clocktable-add-file
18877 file (org-dblock-write:clocktable p1)) tbl)
18878 (setq total-time (+ (or total-time 0)
18879 org-clock-file-total-minutes)))))))
18880 (goto-char pos)
18882 (unless (eq scope 'agenda)
18883 (org-clock-sum ts te)
18884 (goto-char (point-min))
18885 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18886 (goto-char p)
18887 (when (setq time (get-text-property p :org-clock-minutes))
18888 (save-excursion
18889 (beginning-of-line 1)
18890 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18891 (setq level (org-reduced-level
18892 (- (match-end 1) (match-beginning 1))))
18893 (<= level maxlevel))
18894 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18895 hdl (match-string 2)
18896 h (/ time 60)
18897 m (- time (* 60 h)))
18898 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18899 (push (concat
18900 "| " (int-to-string level) "|" hlc hdl hlc " |"
18901 (make-string (1- level) ?|)
18902 hlc (format "%d:%02d" h m) hlc
18903 " |") tbl))))))
18904 (setq tbl (nreverse tbl))
18905 (if tostring
18906 (if tbl (mapconcat 'identity tbl "\n") nil)
18907 (goto-char ins)
18908 (insert-before-markers
18909 (or header
18910 (concat
18911 "Clock summary at ["
18912 (substring
18913 (format-time-string (cdr org-time-stamp-formats))
18914 1 -1)
18915 "]."
18916 (if block
18917 (format " Considered range is /%s/." block)
18919 "\n\n"))
18920 (if (eq scope 'agenda) "|File" "")
18921 "|L|Headline|Time|\n")
18922 (setq total-time (or total-time org-clock-file-total-minutes)
18923 h (/ total-time 60)
18924 m (- total-time (* 60 h)))
18925 (insert-before-markers
18926 "|-\n|"
18927 (if (eq scope 'agenda) "|" "")
18929 "*Total time*| "
18930 (format "*%d:%02d*" h m)
18931 "|\n|-\n")
18932 (setq tbl (delq nil tbl))
18933 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
18934 (equal (substring (car tbl) 0 2) "|-"))
18935 (pop tbl))
18936 (insert-before-markers (mapconcat
18937 'identity (delq nil tbl)
18938 (if (eq scope 'agenda) "\n|-\n" "\n")))
18939 (backward-delete-char 1)
18940 (goto-char ipos)
18941 (skip-chars-forward "^|")
18942 (org-table-align))))))
18944 (defun org-clocktable-steps (params)
18945 (let* ((p1 (copy-sequence params))
18946 (ts (plist-get p1 :tstart))
18947 (te (plist-get p1 :tend))
18948 (step0 (plist-get p1 :step))
18949 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
18950 (block (plist-get p1 :block))
18952 (when block
18953 (setq cc (org-clock-special-range block nil t)
18954 ts (car cc) te (cdr cc)))
18955 (if ts (setq ts (time-to-seconds
18956 (apply 'encode-time (org-parse-time-string ts)))))
18957 (if te (setq te (time-to-seconds
18958 (apply 'encode-time (org-parse-time-string te)))))
18959 (plist-put p1 :header "")
18960 (plist-put p1 :step nil)
18961 (plist-put p1 :block nil)
18962 (while (< ts te)
18963 (or (bolp) (insert "\n"))
18964 (plist-put p1 :tstart (format-time-string
18965 (car org-time-stamp-formats)
18966 (seconds-to-time ts)))
18967 (plist-put p1 :tend (format-time-string
18968 (car org-time-stamp-formats)
18969 (seconds-to-time (setq ts (+ ts step)))))
18970 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
18971 (plist-get p1 :tstart) "\n")
18972 (org-dblock-write:clocktable p1)
18973 (re-search-forward "#\\+END:")
18974 (end-of-line 0))))
18977 (defun org-clocktable-add-file (file table)
18978 (if table
18979 (let ((lines (org-split-string table "\n"))
18980 (ff (file-name-nondirectory file)))
18981 (mapconcat 'identity
18982 (mapcar (lambda (x)
18983 (if (string-match org-table-dataline-regexp x)
18984 (concat "|" ff x)
18986 lines)
18987 "\n"))))
18989 ;; FIXME: I don't think anybody uses this, ask David
18990 (defun org-collect-clock-time-entries ()
18991 "Return an internal list with clocking information.
18992 This list has one entry for each CLOCK interval.
18993 FIXME: describe the elements."
18994 (interactive)
18995 (let ((re (concat "^[ \t]*" org-clock-string
18996 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
18997 rtn beg end next cont level title total closedp leafp
18998 clockpos titlepos h m donep)
18999 (save-excursion
19000 (org-clock-sum)
19001 (goto-char (point-min))
19002 (while (re-search-forward re nil t)
19003 (setq clockpos (match-beginning 0)
19004 beg (match-string 1) end (match-string 2)
19005 cont (match-end 0))
19006 (setq beg (apply 'encode-time (org-parse-time-string beg))
19007 end (apply 'encode-time (org-parse-time-string end)))
19008 (org-back-to-heading t)
19009 (setq donep (org-entry-is-done-p))
19010 (setq titlepos (point)
19011 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19012 h (/ total 60) m (- total (* 60 h))
19013 total (cons h m))
19014 (looking-at "\\(\\*+\\) +\\(.*\\)")
19015 (setq level (- (match-end 1) (match-beginning 1))
19016 title (org-match-string-no-properties 2))
19017 (save-excursion (outline-next-heading) (setq next (point)))
19018 (setq closedp (re-search-forward org-closed-time-regexp next t))
19019 (goto-char next)
19020 (setq leafp (and (looking-at "^\\*+ ")
19021 (<= (- (match-end 0) (point)) level)))
19022 (push (list beg end clockpos closedp donep
19023 total title titlepos level leafp)
19024 rtn)
19025 (goto-char cont)))
19026 (nreverse rtn)))
19028 ;;;; Agenda, and Diary Integration
19030 ;;; Define the Org-agenda-mode
19032 (defvar org-agenda-mode-map (make-sparse-keymap)
19033 "Keymap for `org-agenda-mode'.")
19035 (defvar org-agenda-menu) ; defined later in this file.
19036 (defvar org-agenda-follow-mode nil)
19037 (defvar org-agenda-show-log nil)
19038 (defvar org-agenda-redo-command nil)
19039 (defvar org-agenda-mode-hook nil)
19040 (defvar org-agenda-type nil)
19041 (defvar org-agenda-force-single-file nil)
19043 (defun org-agenda-mode ()
19044 "Mode for time-sorted view on action items in Org-mode files.
19046 The following commands are available:
19048 \\{org-agenda-mode-map}"
19049 (interactive)
19050 (kill-all-local-variables)
19051 (setq org-agenda-undo-list nil
19052 org-agenda-pending-undo-list nil)
19053 (setq major-mode 'org-agenda-mode)
19054 ;; Keep global-font-lock-mode from turning on font-lock-mode
19055 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19056 (setq mode-name "Org-Agenda")
19057 (use-local-map org-agenda-mode-map)
19058 (easy-menu-add org-agenda-menu)
19059 (if org-startup-truncated (setq truncate-lines t))
19060 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19061 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19062 ;; Make sure properties are removed when copying text
19063 (when (boundp 'buffer-substring-filters)
19064 (org-set-local 'buffer-substring-filters
19065 (cons (lambda (x)
19066 (set-text-properties 0 (length x) nil x) x)
19067 buffer-substring-filters)))
19068 (unless org-agenda-keep-modes
19069 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19070 org-agenda-show-log nil))
19071 (easy-menu-change
19072 '("Agenda") "Agenda Files"
19073 (append
19074 (list
19075 (vector
19076 (if (get 'org-agenda-files 'org-restrict)
19077 "Restricted to single file"
19078 "Edit File List")
19079 '(org-edit-agenda-file-list)
19080 (not (get 'org-agenda-files 'org-restrict)))
19081 "--")
19082 (mapcar 'org-file-menu-entry (org-agenda-files))))
19083 (org-agenda-set-mode-name)
19084 (apply
19085 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19086 (list 'org-agenda-mode-hook)))
19088 (substitute-key-definition 'undo 'org-agenda-undo
19089 org-agenda-mode-map global-map)
19090 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19091 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19092 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19093 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19094 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19095 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19096 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19097 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19098 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19099 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19100 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19101 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19102 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19103 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19104 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19105 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19106 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19107 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19108 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19109 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19110 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19111 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19112 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19113 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19114 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19115 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19116 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19117 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19118 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19120 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19121 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19122 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19123 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19124 (while l (org-defkey org-agenda-mode-map
19125 (int-to-string (pop l)) 'digit-argument)))
19127 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19128 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19129 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19130 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19131 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19132 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19133 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19134 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19135 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19136 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19137 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19138 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19139 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19140 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19141 (org-defkey org-agenda-mode-map "n" 'next-line)
19142 (org-defkey org-agenda-mode-map "p" 'previous-line)
19143 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19144 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19145 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19146 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19147 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19148 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19149 (eval-after-load "calendar"
19150 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19151 'org-calendar-goto-agenda))
19152 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19153 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19154 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19155 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19156 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19157 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19158 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19159 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19160 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19161 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19162 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19163 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19164 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19165 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19166 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19167 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19168 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19169 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19170 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19171 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19172 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19173 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19175 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19176 "Local keymap for agenda entries from Org-mode.")
19178 (org-defkey org-agenda-keymap
19179 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19180 (org-defkey org-agenda-keymap
19181 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19182 (when org-agenda-mouse-1-follows-link
19183 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19184 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19185 '("Agenda"
19186 ("Agenda Files")
19187 "--"
19188 ["Show" org-agenda-show t]
19189 ["Go To (other window)" org-agenda-goto t]
19190 ["Go To (this window)" org-agenda-switch-to t]
19191 ["Follow Mode" org-agenda-follow-mode
19192 :style toggle :selected org-agenda-follow-mode :active t]
19193 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19194 "--"
19195 ["Cycle TODO" org-agenda-todo t]
19196 ["Archive subtree" org-agenda-archive t]
19197 ["Delete subtree" org-agenda-kill t]
19198 "--"
19199 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19200 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19201 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19202 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19203 "--"
19204 ("Tags and Properties"
19205 ["Show all Tags" org-agenda-show-tags t]
19206 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19207 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19208 "--"
19209 ["Column View" org-columns t])
19210 ("Date/Schedule"
19211 ["Schedule" org-agenda-schedule t]
19212 ["Set Deadline" org-agenda-deadline t]
19213 "--"
19214 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19215 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19216 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19217 ("Clock"
19218 ["Clock in" org-agenda-clock-in t]
19219 ["Clock out" org-agenda-clock-out t]
19220 ["Clock cancel" org-agenda-clock-cancel t]
19221 ["Goto running clock" org-clock-goto t])
19222 ("Priority"
19223 ["Set Priority" org-agenda-priority t]
19224 ["Increase Priority" org-agenda-priority-up t]
19225 ["Decrease Priority" org-agenda-priority-down t]
19226 ["Show Priority" org-agenda-show-priority t])
19227 ("Calendar/Diary"
19228 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19229 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19230 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19231 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19232 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19233 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19234 "--"
19235 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19236 "--"
19237 ("View"
19238 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19239 :style radio :selected (equal org-agenda-ndays 1)]
19240 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19241 :style radio :selected (equal org-agenda-ndays 7)]
19242 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19243 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19244 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19245 :style radio :selected (member org-agenda-ndays '(365 366))]
19246 "--"
19247 ["Show Logbook entries" org-agenda-log-mode
19248 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19249 ["Include Diary" org-agenda-toggle-diary
19250 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19251 ["Use Time Grid" org-agenda-toggle-time-grid
19252 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19253 ["Write view to file" org-write-agenda t]
19254 ["Rebuild buffer" org-agenda-redo t]
19255 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19256 "--"
19257 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19258 "--"
19259 ["Quit" org-agenda-quit t]
19260 ["Exit and Release Buffers" org-agenda-exit t]
19263 ;;; Agenda undo
19265 (defvar org-agenda-allow-remote-undo t
19266 "Non-nil means, allow remote undo from the agenda buffer.")
19267 (defvar org-agenda-undo-list nil
19268 "List of undoable operations in the agenda since last refresh.")
19269 (defvar org-agenda-undo-has-started-in nil
19270 "Buffers that have already seen `undo-start' in the current undo sequence.")
19271 (defvar org-agenda-pending-undo-list nil
19272 "In a series of undo commands, this is the list of remaning undo items.")
19274 (defmacro org-if-unprotected (&rest body)
19275 "Execute BODY if there is no `org-protected' text property at point."
19276 (declare (debug t))
19277 `(unless (get-text-property (point) 'org-protected)
19278 ,@body))
19280 (defmacro org-with-remote-undo (_buffer &rest _body)
19281 "Execute BODY while recording undo information in two buffers."
19282 (declare (indent 1) (debug t))
19283 `(let ((_cline (org-current-line))
19284 (_cmd this-command)
19285 (_buf1 (current-buffer))
19286 (_buf2 ,_buffer)
19287 (_undo1 buffer-undo-list)
19288 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19289 _c1 _c2)
19290 ,@_body
19291 (when org-agenda-allow-remote-undo
19292 (setq _c1 (org-verify-change-for-undo
19293 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19294 _c2 (org-verify-change-for-undo
19295 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19296 (when (or _c1 _c2)
19297 ;; make sure there are undo boundaries
19298 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19299 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19300 ;; remember which buffer to undo
19301 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19302 org-agenda-undo-list)))))
19304 (defun org-agenda-undo ()
19305 "Undo a remote editing step in the agenda.
19306 This undoes changes both in the agenda buffer and in the remote buffer
19307 that have been changed along."
19308 (interactive)
19309 (or org-agenda-allow-remote-undo
19310 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19311 (if (not (eq this-command last-command))
19312 (setq org-agenda-undo-has-started-in nil
19313 org-agenda-pending-undo-list org-agenda-undo-list))
19314 (if (not org-agenda-pending-undo-list)
19315 (error "No further undo information"))
19316 (let* ((entry (pop org-agenda-pending-undo-list))
19317 buf line cmd rembuf)
19318 (setq cmd (pop entry) line (pop entry))
19319 (setq rembuf (nth 2 entry))
19320 (org-with-remote-undo rembuf
19321 (while (bufferp (setq buf (pop entry)))
19322 (if (pop entry)
19323 (with-current-buffer buf
19324 (let ((last-undo-buffer buf)
19325 (inhibit-read-only t))
19326 (unless (memq buf org-agenda-undo-has-started-in)
19327 (push buf org-agenda-undo-has-started-in)
19328 (make-local-variable 'pending-undo-list)
19329 (undo-start))
19330 (while (and pending-undo-list
19331 (listp pending-undo-list)
19332 (not (car pending-undo-list)))
19333 (pop pending-undo-list))
19334 (undo-more 1))))))
19335 (goto-line line)
19336 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19338 (defun org-verify-change-for-undo (l1 l2)
19339 "Verify that a real change occurred between the undo lists L1 and L2."
19340 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19341 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19342 (not (eq l1 l2)))
19344 ;;; Agenda dispatch
19346 (defvar org-agenda-restrict nil)
19347 (defvar org-agenda-restrict-begin (make-marker))
19348 (defvar org-agenda-restrict-end (make-marker))
19349 (defvar org-agenda-last-dispatch-buffer nil)
19350 (defvar org-agenda-overriding-restriction nil)
19352 ;;;###autoload
19353 (defun org-agenda (arg &optional keys restriction)
19354 "Dispatch agenda commands to collect entries to the agenda buffer.
19355 Prompts for a command to execute. Any prefix arg will be passed
19356 on to the selected command. The default selections are:
19358 a Call `org-agenda-list' to display the agenda for current day or week.
19359 t Call `org-todo-list' to display the global todo list.
19360 T Call `org-todo-list' to display the global todo list, select only
19361 entries with a specific TODO keyword (the user gets a prompt).
19362 m Call `org-tags-view' to display headlines with tags matching
19363 a condition (the user is prompted for the condition).
19364 M Like `m', but select only TODO entries, no ordinary headlines.
19365 L Create a timeline for the current buffer.
19366 e Export views to associated files.
19368 More commands can be added by configuring the variable
19369 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19370 searches can be pre-defined in this way.
19372 If the current buffer is in Org-mode and visiting a file, you can also
19373 first press `<' once to indicate that the agenda should be temporarily
19374 \(until the next use of \\[org-agenda]) restricted to the current file.
19375 Pressing `<' twice means to restrict to the current subtree or region
19376 \(if active)."
19377 (interactive "P")
19378 (catch 'exit
19379 (let* ((prefix-descriptions nil)
19380 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19381 (org-agenda-custom-commands
19382 ;; normalize different versions
19383 (delq nil
19384 (mapcar
19385 (lambda (x)
19386 (cond ((stringp (cdr x))
19387 (push x prefix-descriptions)
19388 nil)
19389 ((stringp (nth 1 x)) x)
19390 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19391 (t (cons (car x) (cons "" (cdr x))))))
19392 org-agenda-custom-commands)))
19393 (buf (current-buffer))
19394 (bfn (buffer-file-name (buffer-base-buffer)))
19395 entry key type match lprops ans)
19396 ;; Turn off restriction unless there is an overriding one
19397 (unless org-agenda-overriding-restriction
19398 (put 'org-agenda-files 'org-restrict nil)
19399 (setq org-agenda-restrict nil)
19400 (move-marker org-agenda-restrict-begin nil)
19401 (move-marker org-agenda-restrict-end nil))
19402 ;; Delete old local properties
19403 (put 'org-agenda-redo-command 'org-lprops nil)
19404 ;; Remember where this call originated
19405 (setq org-agenda-last-dispatch-buffer (current-buffer))
19406 (unless keys
19407 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19408 keys (car ans)
19409 restriction (cdr ans)))
19410 ;; Estabish the restriction, if any
19411 (when (and (not org-agenda-overriding-restriction) restriction)
19412 (put 'org-agenda-files 'org-restrict (list bfn))
19413 (cond
19414 ((eq restriction 'region)
19415 (setq org-agenda-restrict t)
19416 (move-marker org-agenda-restrict-begin (region-beginning))
19417 (move-marker org-agenda-restrict-end (region-end)))
19418 ((eq restriction 'subtree)
19419 (save-excursion
19420 (setq org-agenda-restrict t)
19421 (org-back-to-heading t)
19422 (move-marker org-agenda-restrict-begin (point))
19423 (move-marker org-agenda-restrict-end
19424 (progn (org-end-of-subtree t)))))))
19426 (require 'calendar) ; FIXME: can we avoid this for some commands?
19427 ;; For example the todo list should not need it (but does...)
19428 (cond
19429 ((setq entry (assoc keys org-agenda-custom-commands))
19430 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19431 (progn
19432 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19433 (put 'org-agenda-redo-command 'org-lprops lprops)
19434 (cond
19435 ((eq type 'agenda)
19436 (org-let lprops '(org-agenda-list current-prefix-arg)))
19437 ((eq type 'alltodo)
19438 (org-let lprops '(org-todo-list current-prefix-arg)))
19439 ((eq type 'stuck)
19440 (org-let lprops '(org-agenda-list-stuck-projects
19441 current-prefix-arg)))
19442 ((eq type 'tags)
19443 (org-let lprops '(org-tags-view current-prefix-arg match)))
19444 ((eq type 'tags-todo)
19445 (org-let lprops '(org-tags-view '(4) match)))
19446 ((eq type 'todo)
19447 (org-let lprops '(org-todo-list match)))
19448 ((eq type 'tags-tree)
19449 (org-check-for-org-mode)
19450 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19451 ((eq type 'todo-tree)
19452 (org-check-for-org-mode)
19453 (org-let lprops
19454 '(org-occur (concat "^" outline-regexp "[ \t]*"
19455 (regexp-quote match) "\\>"))))
19456 ((eq type 'occur-tree)
19457 (org-check-for-org-mode)
19458 (org-let lprops '(org-occur match)))
19459 ((functionp type)
19460 (org-let lprops '(funcall type match)))
19461 ((fboundp type)
19462 (org-let lprops '(funcall type match)))
19463 (t (error "Invalid custom agenda command type %s" type))))
19464 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19465 ((equal keys "C")
19466 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19467 (customize-variable 'org-agenda-custom-commands))
19468 ((equal keys "a") (call-interactively 'org-agenda-list))
19469 ((equal keys "t") (call-interactively 'org-todo-list))
19470 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19471 ((equal keys "m") (call-interactively 'org-tags-view))
19472 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19473 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19474 ((equal keys "L")
19475 (unless (org-mode-p)
19476 (error "This is not an Org-mode file"))
19477 (unless restriction
19478 (put 'org-agenda-files 'org-restrict (list bfn))
19479 (org-call-with-arg 'org-timeline arg)))
19480 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19481 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19482 ((equal keys "!") (customize-variable 'org-stuck-projects))
19483 (t (error "Invalid agenda key"))))))
19485 (defun org-agenda-normalize-custom-commands (cmds)
19486 (delq nil
19487 (mapcar
19488 (lambda (x)
19489 (cond ((stringp (cdr x)) nil)
19490 ((stringp (nth 1 x)) x)
19491 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19492 (t (cons (car x) (cons "" (cdr x))))))
19493 cmds)))
19495 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19496 "The user interface for selecting an agenda command."
19497 (catch 'exit
19498 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19499 (restrict-ok (and bfn (org-mode-p)))
19500 (region-p (org-region-active-p))
19501 (custom org-agenda-custom-commands)
19502 (selstring "")
19503 restriction second-time
19504 c entry key type match prefixes rmheader header-end custom1 desc)
19505 (save-window-excursion
19506 (delete-other-windows)
19507 (org-switch-to-buffer-other-window " *Agenda Commands*")
19508 (erase-buffer)
19509 (insert (eval-when-compile
19510 (let ((header
19512 Press key for an agenda command: < Buffer,subtree/region restriction
19513 -------------------------------- > Remove restriction
19514 a Agenda for current week or day e Export agenda views
19515 t List of all TODO entries T Entries with special TODO kwd
19516 m Match a TAGS query M Like m, but only TODO entries
19517 L Timeline for current buffer # List stuck projects (!=configure)
19518 / Multi-occur C Configure custom agenda commands
19520 (start 0))
19521 (while (string-match
19522 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19523 header start)
19524 (setq start (match-end 0))
19525 (add-text-properties (match-beginning 2) (match-end 2)
19526 '(face bold) header))
19527 header)))
19528 (setq header-end (move-marker (make-marker) (point)))
19529 (while t
19530 (setq custom1 custom)
19531 (when (eq rmheader t)
19532 (goto-line 1)
19533 (re-search-forward ":" nil t)
19534 (delete-region (match-end 0) (point-at-eol))
19535 (forward-char 1)
19536 (looking-at "-+")
19537 (delete-region (match-end 0) (point-at-eol))
19538 (move-marker header-end (match-end 0)))
19539 (goto-char header-end)
19540 (delete-region (point) (point-max))
19541 (while (setq entry (pop custom1))
19542 (setq key (car entry) desc (nth 1 entry)
19543 type (nth 2 entry) match (nth 3 entry))
19544 (if (> (length key) 1)
19545 (add-to-list 'prefixes (string-to-char key))
19546 (insert
19547 (format
19548 "\n%-4s%-14s: %s"
19549 (org-add-props (copy-sequence key)
19550 '(face bold))
19551 (cond
19552 ((string-match "\\S-" desc) desc)
19553 ((eq type 'agenda) "Agenda for current week or day")
19554 ((eq type 'alltodo) "List of all TODO entries")
19555 ((eq type 'stuck) "List of stuck projects")
19556 ((eq type 'todo) "TODO keyword")
19557 ((eq type 'tags) "Tags query")
19558 ((eq type 'tags-todo) "Tags (TODO)")
19559 ((eq type 'tags-tree) "Tags tree")
19560 ((eq type 'todo-tree) "TODO kwd tree")
19561 ((eq type 'occur-tree) "Occur tree")
19562 ((functionp type) (if (symbolp type)
19563 (symbol-name type)
19564 "Lambda expression"))
19565 (t "???"))
19566 (cond
19567 ((stringp match)
19568 (org-add-props match nil 'face 'org-warning))
19569 (match
19570 (format "set of %d commands" (length match)))
19571 (t ""))))))
19572 (when prefixes
19573 (mapc (lambda (x)
19574 (insert
19575 (format "\n%s %s"
19576 (org-add-props (char-to-string x)
19577 nil 'face 'bold)
19578 (or (cdr (assoc (concat selstring (char-to-string x))
19579 prefix-descriptions))
19580 "Prefix key"))))
19581 prefixes))
19582 (goto-char (point-min))
19583 (when (fboundp 'fit-window-to-buffer)
19584 (if second-time
19585 (if (not (pos-visible-in-window-p (point-max)))
19586 (fit-window-to-buffer))
19587 (setq second-time t)
19588 (fit-window-to-buffer)))
19589 (message "Press key for agenda command%s:"
19590 (if (or restrict-ok org-agenda-overriding-restriction)
19591 (if org-agenda-overriding-restriction
19592 " (restriction lock active)"
19593 (if restriction
19594 (format " (restricted to %s)" restriction)
19595 " (unrestricted)"))
19596 ""))
19597 (setq c (read-char-exclusive))
19598 (message "")
19599 (cond
19600 ((assoc (char-to-string c) custom)
19601 (setq selstring (concat selstring (char-to-string c)))
19602 (throw 'exit (cons selstring restriction)))
19603 ((memq c prefixes)
19604 (setq selstring (concat selstring (char-to-string c))
19605 prefixes nil
19606 rmheader (or rmheader t)
19607 custom (delq nil (mapcar
19608 (lambda (x)
19609 (if (or (= (length (car x)) 1)
19610 (/= (string-to-char (car x)) c))
19612 (cons (substring (car x) 1) (cdr x))))
19613 custom))))
19614 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19615 (message "Restriction is only possible in Org-mode buffers")
19616 (ding) (sit-for 1))
19617 ((eq c ?1)
19618 (org-agenda-remove-restriction-lock 'noupdate)
19619 (setq restriction 'buffer))
19620 ((eq c ?0)
19621 (org-agenda-remove-restriction-lock 'noupdate)
19622 (setq restriction (if region-p 'region 'subtree)))
19623 ((eq c ?<)
19624 (org-agenda-remove-restriction-lock 'noupdate)
19625 (setq restriction
19626 (cond
19627 ((eq restriction 'buffer)
19628 (if region-p 'region 'subtree))
19629 ((memq restriction '(subtree region))
19630 nil)
19631 (t 'buffer))))
19632 ((eq c ?>)
19633 (org-agenda-remove-restriction-lock 'noupdate)
19634 (setq restriction nil))
19635 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19636 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19637 ((and (> (length selstring) 0) (eq c ?\d))
19638 (delete-window)
19639 (org-agenda-get-restriction-and-command prefix-descriptions))
19641 ((equal c ?q) (error "Abort"))
19642 (t (error "Invalid key %c" c))))))))
19644 (defun org-run-agenda-series (name series)
19645 (org-prepare-agenda name)
19646 (let* ((org-agenda-multi t)
19647 (redo (list 'org-run-agenda-series name (list 'quote series)))
19648 (cmds (car series))
19649 (gprops (nth 1 series))
19650 match ;; The byte compiler incorrectly complains about this. Keep it!
19651 cmd type lprops)
19652 (while (setq cmd (pop cmds))
19653 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19654 (cond
19655 ((eq type 'agenda)
19656 (org-let2 gprops lprops
19657 '(call-interactively 'org-agenda-list)))
19658 ((eq type 'alltodo)
19659 (org-let2 gprops lprops
19660 '(call-interactively 'org-todo-list)))
19661 ((eq type 'stuck)
19662 (org-let2 gprops lprops
19663 '(call-interactively 'org-agenda-list-stuck-projects)))
19664 ((eq type 'tags)
19665 (org-let2 gprops lprops
19666 '(org-tags-view current-prefix-arg match)))
19667 ((eq type 'tags-todo)
19668 (org-let2 gprops lprops
19669 '(org-tags-view '(4) match)))
19670 ((eq type 'todo)
19671 (org-let2 gprops lprops
19672 '(org-todo-list match)))
19673 ((fboundp type)
19674 (org-let2 gprops lprops
19675 '(funcall type match)))
19676 (t (error "Invalid type in command series"))))
19677 (widen)
19678 (setq org-agenda-redo-command redo)
19679 (goto-char (point-min)))
19680 (org-finalize-agenda))
19682 ;;;###autoload
19683 (defmacro org-batch-agenda (cmd-key &rest parameters)
19684 "Run an agenda command in batch mode and send the result to STDOUT.
19685 If CMD-KEY is a string of length 1, it is used as a key in
19686 `org-agenda-custom-commands' and triggers this command. If it is a
19687 longer string it is used as a tags/todo match string.
19688 Paramters are alternating variable names and values that will be bound
19689 before running the agenda command."
19690 (let (pars)
19691 (while parameters
19692 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19693 (if (> (length cmd-key) 2)
19694 (eval (list 'let (nreverse pars)
19695 (list 'org-tags-view nil cmd-key)))
19696 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19697 (set-buffer org-agenda-buffer-name)
19698 (princ (org-encode-for-stdout (buffer-string)))))
19700 (defun org-encode-for-stdout (string)
19701 (if (fboundp 'encode-coding-string)
19702 (encode-coding-string string buffer-file-coding-system)
19703 string))
19705 (defvar org-agenda-info nil)
19707 ;;;###autoload
19708 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19709 "Run an agenda command in batch mode and send the result to STDOUT.
19710 If CMD-KEY is a string of length 1, it is used as a key in
19711 `org-agenda-custom-commands' and triggers this command. If it is a
19712 longer string it is used as a tags/todo match string.
19713 Paramters are alternating variable names and values that will be bound
19714 before running the agenda command.
19716 The output gives a line for each selected agenda item. Each
19717 item is a list of comma-separated values, like this:
19719 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19721 category The category of the item
19722 head The headline, without TODO kwd, TAGS and PRIORITY
19723 type The type of the agenda entry, can be
19724 todo selected in TODO match
19725 tagsmatch selected in tags match
19726 diary imported from diary
19727 deadline a deadline on given date
19728 scheduled scheduled on given date
19729 timestamp entry has timestamp on given date
19730 closed entry was closed on given date
19731 upcoming-deadline warning about deadline
19732 past-scheduled forwarded scheduled item
19733 block entry has date block including g. date
19734 todo The todo keyword, if any
19735 tags All tags including inherited ones, separated by colons
19736 date The relevant date, like 2007-2-14
19737 time The time, like 15:00-16:50
19738 extra Sting with extra planning info
19739 priority-l The priority letter if any was given
19740 priority-n The computed numerical priority
19741 agenda-day The day in the agenda where this is listed"
19743 (let (pars)
19744 (while parameters
19745 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19746 (push (list 'org-agenda-remove-tags t) pars)
19747 (if (> (length cmd-key) 2)
19748 (eval (list 'let (nreverse pars)
19749 (list 'org-tags-view nil cmd-key)))
19750 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19751 (set-buffer org-agenda-buffer-name)
19752 (let* ((lines (org-split-string (buffer-string) "\n"))
19753 line)
19754 (while (setq line (pop lines))
19755 (catch 'next
19756 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19757 (setq org-agenda-info
19758 (org-fix-agenda-info (text-properties-at 0 line)))
19759 (princ
19760 (org-encode-for-stdout
19761 (mapconcat 'org-agenda-export-csv-mapper
19762 '(org-category txt type todo tags date time-of-day extra
19763 priority-letter priority agenda-day)
19764 ",")))
19765 (princ "\n"))))))
19767 (defun org-fix-agenda-info (props)
19768 "Make sure all properties on an agenda item have a canonical form,
19769 so the export commands can easily use it."
19770 (let (tmp re)
19771 (when (setq tmp (plist-get props 'tags))
19772 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19773 (when (setq tmp (plist-get props 'date))
19774 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19775 (let ((calendar-date-display-form '(year "-" month "-" day)))
19776 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19778 (setq tmp (calendar-date-string tmp)))
19779 (setq props (plist-put props 'date tmp)))
19780 (when (setq tmp (plist-get props 'day))
19781 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19782 (let ((calendar-date-display-form '(year "-" month "-" day)))
19783 (setq tmp (calendar-date-string tmp)))
19784 (setq props (plist-put props 'day tmp))
19785 (setq props (plist-put props 'agenda-day tmp)))
19786 (when (setq tmp (plist-get props 'txt))
19787 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19788 (plist-put props 'priority-letter (match-string 1 tmp))
19789 (setq tmp (replace-match "" t t tmp)))
19790 (when (and (setq re (plist-get props 'org-todo-regexp))
19791 (setq re (concat "\\`\\.*" re " ?"))
19792 (string-match re tmp))
19793 (plist-put props 'todo (match-string 1 tmp))
19794 (setq tmp (replace-match "" t t tmp)))
19795 (plist-put props 'txt tmp)))
19796 props)
19798 (defun org-agenda-export-csv-mapper (prop)
19799 (let ((res (plist-get org-agenda-info prop)))
19800 (setq res
19801 (cond
19802 ((not res) "")
19803 ((stringp res) res)
19804 (t (prin1-to-string res))))
19805 (while (string-match "," res)
19806 (setq res (replace-match ";" t t res)))
19807 (org-trim res)))
19810 ;;;###autoload
19811 (defun org-store-agenda-views (&rest parameters)
19812 (interactive)
19813 (eval (list 'org-batch-store-agenda-views)))
19815 ;; FIXME, why is this a macro?????
19816 ;;;###autoload
19817 (defmacro org-batch-store-agenda-views (&rest parameters)
19818 "Run all custom agenda commands that have a file argument."
19819 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19820 (pop-up-frames nil)
19821 (dir default-directory)
19822 pars cmd thiscmdkey files opts)
19823 (while parameters
19824 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19825 (setq pars (reverse pars))
19826 (save-window-excursion
19827 (while cmds
19828 (setq cmd (pop cmds)
19829 thiscmdkey (car cmd)
19830 opts (nth 4 cmd)
19831 files (nth 5 cmd))
19832 (if (stringp files) (setq files (list files)))
19833 (when files
19834 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19835 (list 'org-agenda nil thiscmdkey)))
19836 (set-buffer org-agenda-buffer-name)
19837 (while files
19838 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19839 (list 'org-write-agenda
19840 (expand-file-name (pop files) dir) t))))
19841 (and (get-buffer org-agenda-buffer-name)
19842 (kill-buffer org-agenda-buffer-name)))))))
19844 (defun org-write-agenda (file &optional nosettings)
19845 "Write the current buffer (an agenda view) as a file.
19846 Depending on the extension of the file name, plain text (.txt),
19847 HTML (.html or .htm) or Postscript (.ps) is produced.
19848 If NOSETTINGS is given, do not scope the settings of
19849 `org-agenda-exporter-settings' into the export commands. This is used when
19850 the settings have already been scoped and we do not wish to overrule other,
19851 higher priority settings."
19852 (interactive "FWrite agenda to file: ")
19853 (if (not (file-writable-p file))
19854 (error "Cannot write agenda to file %s" file))
19855 (cond
19856 ((string-match "\\.html?\\'" file) (require 'htmlize))
19857 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19858 (org-let (if nosettings nil org-agenda-exporter-settings)
19859 '(save-excursion
19860 (save-window-excursion
19861 (cond
19862 ((string-match "\\.html?\\'" file)
19863 (set-buffer (htmlize-buffer (current-buffer)))
19865 (when (and org-agenda-export-html-style
19866 (string-match "<style>" org-agenda-export-html-style))
19867 ;; replace <style> section with org-agenda-export-html-style
19868 (goto-char (point-min))
19869 (kill-region (- (search-forward "<style") 6)
19870 (search-forward "</style>"))
19871 (insert org-agenda-export-html-style))
19872 (write-file file)
19873 (kill-buffer (current-buffer))
19874 (message "HTML written to %s" file))
19875 ((string-match "\\.ps\\'" file)
19876 (ps-print-buffer-with-faces file)
19877 (message "Postscript written to %s" file))
19879 (let ((bs (buffer-string)))
19880 (find-file file)
19881 (insert bs)
19882 (save-buffer 0)
19883 (kill-buffer (current-buffer))
19884 (message "Plain text written to %s" file))))))
19885 (set-buffer org-agenda-buffer-name)))
19887 (defmacro org-no-read-only (&rest body)
19888 "Inhibit read-only for BODY."
19889 `(let ((inhibit-read-only t)) ,@body))
19891 (defun org-check-for-org-mode ()
19892 "Make sure current buffer is in org-mode. Error if not."
19893 (or (org-mode-p)
19894 (error "Cannot execute org-mode agenda command on buffer in %s."
19895 major-mode)))
19897 (defun org-fit-agenda-window ()
19898 "Fit the window to the buffer size."
19899 (and (memq org-agenda-window-setup '(reorganize-frame))
19900 (fboundp 'fit-window-to-buffer)
19901 (fit-window-to-buffer
19903 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19904 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19906 ;;; Agenda file list
19908 (defun org-agenda-files (&optional unrestricted)
19909 "Get the list of agenda files.
19910 Optional UNRESTRICTED means return the full list even if a restriction
19911 is currently in place."
19912 (let ((files
19913 (cond
19914 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19915 ((stringp org-agenda-files) (org-read-agenda-file-list))
19916 ((listp org-agenda-files) org-agenda-files)
19917 (t (error "Invalid value of `org-agenda-files'")))))
19918 (setq files (apply 'append
19919 (mapcar (lambda (f)
19920 (if (file-directory-p f)
19921 (directory-files f t
19922 org-agenda-file-regexp)
19923 (list f)))
19924 files)))
19925 (if org-agenda-skip-unavailable-files
19926 (delq nil
19927 (mapcar (function
19928 (lambda (file)
19929 (and (file-readable-p file) file)))
19930 files))
19931 files))) ; `org-check-agenda-file' will remove them from the list
19933 (defun org-edit-agenda-file-list ()
19934 "Edit the list of agenda files.
19935 Depending on setup, this either uses customize to edit the variable
19936 `org-agenda-files', or it visits the file that is holding the list. In the
19937 latter case, the buffer is set up in a way that saving it automatically kills
19938 the buffer and restores the previous window configuration."
19939 (interactive)
19940 (if (stringp org-agenda-files)
19941 (let ((cw (current-window-configuration)))
19942 (find-file org-agenda-files)
19943 (org-set-local 'org-window-configuration cw)
19944 (org-add-hook 'after-save-hook
19945 (lambda ()
19946 (set-window-configuration
19947 (prog1 org-window-configuration
19948 (kill-buffer (current-buffer))))
19949 (org-install-agenda-files-menu)
19950 (message "New agenda file list installed"))
19951 nil 'local)
19952 (message "%s" (substitute-command-keys
19953 "Edit list and finish with \\[save-buffer]")))
19954 (customize-variable 'org-agenda-files)))
19956 (defun org-store-new-agenda-file-list (list)
19957 "Set new value for the agenda file list and save it correcly."
19958 (if (stringp org-agenda-files)
19959 (let ((f org-agenda-files) b)
19960 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
19961 (with-temp-file f
19962 (insert (mapconcat 'identity list "\n") "\n")))
19963 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
19964 (setq org-agenda-files list)
19965 (customize-save-variable 'org-agenda-files org-agenda-files))))
19967 (defun org-read-agenda-file-list ()
19968 "Read the list of agenda files from a file."
19969 (when (stringp org-agenda-files)
19970 (with-temp-buffer
19971 (insert-file-contents org-agenda-files)
19972 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
19975 ;;;###autoload
19976 (defun org-cycle-agenda-files ()
19977 "Cycle through the files in `org-agenda-files'.
19978 If the current buffer visits an agenda file, find the next one in the list.
19979 If the current buffer does not, find the first agenda file."
19980 (interactive)
19981 (let* ((fs (org-agenda-files t))
19982 (files (append fs (list (car fs))))
19983 (tcf (if buffer-file-name (file-truename buffer-file-name)))
19984 file)
19985 (unless files (error "No agenda files"))
19986 (catch 'exit
19987 (while (setq file (pop files))
19988 (if (equal (file-truename file) tcf)
19989 (when (car files)
19990 (find-file (car files))
19991 (throw 'exit t))))
19992 (find-file (car fs)))
19993 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
19995 (defun org-agenda-file-to-front (&optional to-end)
19996 "Move/add the current file to the top of the agenda file list.
19997 If the file is not present in the list, it is added to the front. If it is
19998 present, it is moved there. With optional argument TO-END, add/move to the
19999 end of the list."
20000 (interactive "P")
20001 (let ((org-agenda-skip-unavailable-files nil)
20002 (file-alist (mapcar (lambda (x)
20003 (cons (file-truename x) x))
20004 (org-agenda-files t)))
20005 (ctf (file-truename buffer-file-name))
20006 x had)
20007 (setq x (assoc ctf file-alist) had x)
20009 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20010 (if to-end
20011 (setq file-alist (append (delq x file-alist) (list x)))
20012 (setq file-alist (cons x (delq x file-alist))))
20013 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20014 (org-install-agenda-files-menu)
20015 (message "File %s to %s of agenda file list"
20016 (if had "moved" "added") (if to-end "end" "front"))))
20018 (defun org-remove-file (&optional file)
20019 "Remove current file from the list of files in variable `org-agenda-files'.
20020 These are the files which are being checked for agenda entries.
20021 Optional argument FILE means, use this file instead of the current."
20022 (interactive)
20023 (let* ((org-agenda-skip-unavailable-files nil)
20024 (file (or file buffer-file-name))
20025 (true-file (file-truename file))
20026 (afile (abbreviate-file-name file))
20027 (files (delq nil (mapcar
20028 (lambda (x)
20029 (if (equal true-file
20030 (file-truename x))
20031 nil x))
20032 (org-agenda-files t)))))
20033 (if (not (= (length files) (length (org-agenda-files t))))
20034 (progn
20035 (org-store-new-agenda-file-list files)
20036 (org-install-agenda-files-menu)
20037 (message "Removed file: %s" afile))
20038 (message "File was not in list: %s (not removed)" afile))))
20040 (defun org-file-menu-entry (file)
20041 (vector file (list 'find-file file) t))
20043 (defun org-check-agenda-file (file)
20044 "Make sure FILE exists. If not, ask user what to do."
20045 (when (not (file-exists-p file))
20046 (message "non-existent file %s. [R]emove from list or [A]bort?"
20047 (abbreviate-file-name file))
20048 (let ((r (downcase (read-char-exclusive))))
20049 (cond
20050 ((equal r ?r)
20051 (org-remove-file file)
20052 (throw 'nextfile t))
20053 (t (error "Abort"))))))
20055 ;;; Agenda prepare and finalize
20057 (defvar org-agenda-multi nil) ; dynammically scoped
20058 (defvar org-agenda-buffer-name "*Org Agenda*")
20059 (defvar org-pre-agenda-window-conf nil)
20060 (defvar org-agenda-name nil)
20061 (defun org-prepare-agenda (&optional name)
20062 (setq org-todo-keywords-for-agenda nil)
20063 (setq org-done-keywords-for-agenda nil)
20064 (if org-agenda-multi
20065 (progn
20066 (setq buffer-read-only nil)
20067 (goto-char (point-max))
20068 (unless (or (bobp) org-agenda-compact-blocks)
20069 (insert "\n" (make-string (window-width) ?=) "\n"))
20070 (narrow-to-region (point) (point-max)))
20071 (org-agenda-maybe-reset-markers 'force)
20072 (org-prepare-agenda-buffers (org-agenda-files))
20073 (setq org-todo-keywords-for-agenda
20074 (org-uniquify org-todo-keywords-for-agenda))
20075 (setq org-done-keywords-for-agenda
20076 (org-uniquify org-done-keywords-for-agenda))
20077 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20078 (awin (get-buffer-window abuf)))
20079 (cond
20080 ((equal (current-buffer) abuf) nil)
20081 (awin (select-window awin))
20082 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20083 ((equal org-agenda-window-setup 'current-window)
20084 (switch-to-buffer abuf))
20085 ((equal org-agenda-window-setup 'other-window)
20086 (org-switch-to-buffer-other-window abuf))
20087 ((equal org-agenda-window-setup 'other-frame)
20088 (switch-to-buffer-other-frame abuf))
20089 ((equal org-agenda-window-setup 'reorganize-frame)
20090 (delete-other-windows)
20091 (org-switch-to-buffer-other-window abuf))))
20092 (setq buffer-read-only nil)
20093 (erase-buffer)
20094 (org-agenda-mode)
20095 (and name (not org-agenda-name)
20096 (org-set-local 'org-agenda-name name)))
20097 (setq buffer-read-only nil))
20099 (defun org-finalize-agenda ()
20100 "Finishing touch for the agenda buffer, called just before displaying it."
20101 (unless org-agenda-multi
20102 (save-excursion
20103 (let ((inhibit-read-only t))
20104 (goto-char (point-min))
20105 (while (org-activate-bracket-links (point-max))
20106 (add-text-properties (match-beginning 0) (match-end 0)
20107 '(face org-link)))
20108 (org-agenda-align-tags)
20109 (unless org-agenda-with-colors
20110 (remove-text-properties (point-min) (point-max) '(face nil))))
20111 (if (and (boundp 'org-overriding-columns-format)
20112 org-overriding-columns-format)
20113 (org-set-local 'org-overriding-columns-format
20114 org-overriding-columns-format))
20115 (if (and (boundp 'org-agenda-view-columns-initially)
20116 org-agenda-view-columns-initially)
20117 (org-agenda-columns))
20118 (when org-agenda-fontify-priorities
20119 (org-fontify-priorities))
20120 (run-hooks 'org-finalize-agenda-hook)
20121 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20124 (defun org-fontify-priorities ()
20125 "Make highest priority lines bold, and lowest italic."
20126 (interactive)
20127 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20128 (org-delete-overlay o)))
20129 (org-overlays-in (point-min) (point-max)))
20130 (save-excursion
20131 (let ((inhibit-read-only t)
20132 b e p ov h l)
20133 (goto-char (point-min))
20134 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20135 (setq h (or (get-char-property (point) 'org-highest-priority)
20136 org-highest-priority)
20137 l (or (get-char-property (point) 'org-lowest-priority)
20138 org-lowest-priority)
20139 p (string-to-char (match-string 1))
20140 b (match-beginning 0) e (point-at-eol)
20141 ov (org-make-overlay b e))
20142 (org-overlay-put
20143 ov 'face
20144 (cond ((listp org-agenda-fontify-priorities)
20145 (cdr (assoc p org-agenda-fontify-priorities)))
20146 ((equal p l) 'italic)
20147 ((equal p h) 'bold)))
20148 (org-overlay-put ov 'org-type 'org-priority)))))
20150 (defun org-prepare-agenda-buffers (files)
20151 "Create buffers for all agenda files, protect archived trees and comments."
20152 (interactive)
20153 (let ((pa '(:org-archived t))
20154 (pc '(:org-comment t))
20155 (pall '(:org-archived t :org-comment t))
20156 (inhibit-read-only t)
20157 (rea (concat ":" org-archive-tag ":"))
20158 bmp file re)
20159 (save-excursion
20160 (save-restriction
20161 (while (setq file (pop files))
20162 (if (bufferp file)
20163 (set-buffer file)
20164 (org-check-agenda-file file)
20165 (set-buffer (org-get-agenda-file-buffer file)))
20166 (widen)
20167 (setq bmp (buffer-modified-p))
20168 (org-refresh-category-properties)
20169 (setq org-todo-keywords-for-agenda
20170 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20171 (setq org-done-keywords-for-agenda
20172 (append org-done-keywords-for-agenda org-done-keywords))
20173 (save-excursion
20174 (remove-text-properties (point-min) (point-max) pall)
20175 (when org-agenda-skip-archived-trees
20176 (goto-char (point-min))
20177 (while (re-search-forward rea nil t)
20178 (if (org-on-heading-p t)
20179 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20180 (goto-char (point-min))
20181 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20182 (while (re-search-forward re nil t)
20183 (add-text-properties
20184 (match-beginning 0) (org-end-of-subtree t) pc)))
20185 (set-buffer-modified-p bmp))))))
20187 (defvar org-agenda-skip-function nil
20188 "Function to be called at each match during agenda construction.
20189 If this function returns nil, the current match should not be skipped.
20190 Otherwise, the function must return a position from where the search
20191 should be continued.
20192 This may also be a Lisp form, it will be evaluated.
20193 Never set this variable using `setq' or so, because then it will apply
20194 to all future agenda commands. Instead, bind it with `let' to scope
20195 it dynamically into the agenda-constructing command. A good way to set
20196 it is through options in org-agenda-custom-commands.")
20198 (defun org-agenda-skip ()
20199 "Throw to `:skip' in places that should be skipped.
20200 Also moves point to the end of the skipped region, so that search can
20201 continue from there."
20202 (let ((p (point-at-bol)) to fp)
20203 (and org-agenda-skip-archived-trees
20204 (get-text-property p :org-archived)
20205 (org-end-of-subtree t)
20206 (throw :skip t))
20207 (and (get-text-property p :org-comment)
20208 (org-end-of-subtree t)
20209 (throw :skip t))
20210 (if (equal (char-after p) ?#) (throw :skip t))
20211 (when (and (or (setq fp (functionp org-agenda-skip-function))
20212 (consp org-agenda-skip-function))
20213 (setq to (save-excursion
20214 (save-match-data
20215 (if fp
20216 (funcall org-agenda-skip-function)
20217 (eval org-agenda-skip-function))))))
20218 (goto-char to)
20219 (throw :skip t))))
20221 (defvar org-agenda-markers nil
20222 "List of all currently active markers created by `org-agenda'.")
20223 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20224 "Creation time of the last agenda marker.")
20226 (defun org-agenda-new-marker (&optional pos)
20227 "Return a new agenda marker.
20228 Org-mode keeps a list of these markers and resets them when they are
20229 no longer in use."
20230 (let ((m (copy-marker (or pos (point)))))
20231 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20232 (push m org-agenda-markers)
20235 (defun org-agenda-maybe-reset-markers (&optional force)
20236 "Reset markers created by `org-agenda'. But only if they are old enough."
20237 (if (or (and force (not org-agenda-multi))
20238 (> (- (time-to-seconds (current-time))
20239 org-agenda-last-marker-time)
20241 (while org-agenda-markers
20242 (move-marker (pop org-agenda-markers) nil))))
20244 (defun org-get-agenda-file-buffer (file)
20245 "Get a buffer visiting FILE. If the buffer needs to be created, add
20246 it to the list of buffers which might be released later."
20247 (let ((buf (org-find-base-buffer-visiting file)))
20248 (if buf
20249 buf ; just return it
20250 ;; Make a new buffer and remember it
20251 (setq buf (find-file-noselect file))
20252 (if buf (push buf org-agenda-new-buffers))
20253 buf)))
20255 (defun org-release-buffers (blist)
20256 "Release all buffers in list, asking the user for confirmation when needed.
20257 When a buffer is unmodified, it is just killed. When modified, it is saved
20258 \(if the user agrees) and then killed."
20259 (let (buf file)
20260 (while (setq buf (pop blist))
20261 (setq file (buffer-file-name buf))
20262 (when (and (buffer-modified-p buf)
20263 file
20264 (y-or-n-p (format "Save file %s? " file)))
20265 (with-current-buffer buf (save-buffer)))
20266 (kill-buffer buf))))
20268 (defun org-get-category (&optional pos)
20269 "Get the category applying to position POS."
20270 (get-text-property (or pos (point)) 'org-category))
20272 ;;; Agenda timeline
20274 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20276 (defun org-timeline (&optional include-all)
20277 "Show a time-sorted view of the entries in the current org file.
20278 Only entries with a time stamp of today or later will be listed. With
20279 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20280 under the current date.
20281 If the buffer contains an active region, only check the region for
20282 dates."
20283 (interactive "P")
20284 (require 'calendar)
20285 (org-compile-prefix-format 'timeline)
20286 (org-set-sorting-strategy 'timeline)
20287 (let* ((dopast t)
20288 (dotodo include-all)
20289 (doclosed org-agenda-show-log)
20290 (entry buffer-file-name)
20291 (date (calendar-current-date))
20292 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20293 (end (if (org-region-active-p) (region-end) (point-max)))
20294 (day-numbers (org-get-all-dates beg end 'no-ranges
20295 t doclosed ; always include today
20296 org-timeline-show-empty-dates))
20297 (org-deadline-warning-days 0)
20298 (org-agenda-only-exact-dates t)
20299 (today (time-to-days (current-time)))
20300 (past t)
20301 args
20302 s e rtn d emptyp)
20303 (setq org-agenda-redo-command
20304 (list 'progn
20305 (list 'org-switch-to-buffer-other-window (current-buffer))
20306 (list 'org-timeline (list 'quote include-all))))
20307 (if (not dopast)
20308 ;; Remove past dates from the list of dates.
20309 (setq day-numbers (delq nil (mapcar (lambda(x)
20310 (if (>= x today) x nil))
20311 day-numbers))))
20312 (org-prepare-agenda (concat "Timeline "
20313 (file-name-nondirectory buffer-file-name)))
20314 (if doclosed (push :closed args))
20315 (push :timestamp args)
20316 (push :deadline args)
20317 (push :scheduled args)
20318 (push :sexp args)
20319 (if dotodo (push :todo args))
20320 (while (setq d (pop day-numbers))
20321 (if (and (listp d) (eq (car d) :omitted))
20322 (progn
20323 (setq s (point))
20324 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20325 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20326 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20327 (if (and (>= d today)
20328 dopast
20329 past)
20330 (progn
20331 (setq past nil)
20332 (insert (make-string 79 ?-) "\n")))
20333 (setq date (calendar-gregorian-from-absolute d))
20334 (setq s (point))
20335 (setq rtn (and (not emptyp)
20336 (apply 'org-agenda-get-day-entries entry
20337 date args)))
20338 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20339 (progn
20340 (insert
20341 (if (stringp org-agenda-format-date)
20342 (format-time-string org-agenda-format-date
20343 (org-time-from-absolute date))
20344 (funcall org-agenda-format-date date))
20345 "\n")
20346 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20347 (put-text-property s (1- (point)) 'org-date-line t)
20348 (if (equal d today)
20349 (put-text-property s (1- (point)) 'org-today t))
20350 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20351 (put-text-property s (1- (point)) 'day d)))))
20352 (goto-char (point-min))
20353 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20354 (point-min)))
20355 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20356 (org-finalize-agenda)
20357 (setq buffer-read-only t)))
20359 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20360 "Return a list of all relevant day numbers from BEG to END buffer positions.
20361 If NO-RANGES is non-nil, include only the start and end dates of a range,
20362 not every single day in the range. If FORCE-TODAY is non-nil, make
20363 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20364 inactive time stamps (those in square brackets) are included.
20365 When EMPTY is non-nil, also include days without any entries."
20366 (let ((re (concat
20367 (if pre-re pre-re "")
20368 (if inactive org-ts-regexp-both org-ts-regexp)))
20369 dates dates1 date day day1 day2 ts1 ts2)
20370 (if force-today
20371 (setq dates (list (time-to-days (current-time)))))
20372 (save-excursion
20373 (goto-char beg)
20374 (while (re-search-forward re end t)
20375 (setq day (time-to-days (org-time-string-to-time
20376 (substring (match-string 1) 0 10))))
20377 (or (memq day dates) (push day dates)))
20378 (unless no-ranges
20379 (goto-char beg)
20380 (while (re-search-forward org-tr-regexp end t)
20381 (setq ts1 (substring (match-string 1) 0 10)
20382 ts2 (substring (match-string 2) 0 10)
20383 day1 (time-to-days (org-time-string-to-time ts1))
20384 day2 (time-to-days (org-time-string-to-time ts2)))
20385 (while (< (setq day1 (1+ day1)) day2)
20386 (or (memq day1 dates) (push day1 dates)))))
20387 (setq dates (sort dates '<))
20388 (when empty
20389 (while (setq day (pop dates))
20390 (setq day2 (car dates))
20391 (push day dates1)
20392 (when (and day2 empty)
20393 (if (or (eq empty t)
20394 (and (numberp empty) (<= (- day2 day) empty)))
20395 (while (< (setq day (1+ day)) day2)
20396 (push (list day) dates1))
20397 (push (cons :omitted (- day2 day)) dates1))))
20398 (setq dates (nreverse dates1)))
20399 dates)))
20401 ;;; Agenda Daily/Weekly
20403 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20404 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20405 (defvar org-agenda-last-arguments nil
20406 "The arguments of the previous call to org-agenda")
20407 (defvar org-starting-day nil) ; local variable in the agenda buffer
20408 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20409 (defvar org-include-all-loc nil) ; local variable
20410 (defvar org-agenda-remove-date nil) ; dynamically scoped
20412 ;;;###autoload
20413 (defun org-agenda-list (&optional include-all start-day ndays)
20414 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20415 The view will be for the current day or week, but from the overview buffer
20416 you will be able to go to other days/weeks.
20418 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20419 all unfinished TODO items will also be shown, before the agenda.
20420 This feature is considered obsolete, please use the TODO list or a block
20421 agenda instead.
20423 With a numeric prefix argument in an interactive call, the agenda will
20424 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20425 the number of days. NDAYS defaults to `org-agenda-ndays'.
20427 START-DAY defaults to TODAY, or to the most recent match for the weekday
20428 given in `org-agenda-start-on-weekday'."
20429 (interactive "P")
20430 (if (and (integerp include-all) (> include-all 0))
20431 (setq ndays include-all include-all nil))
20432 (setq ndays (or ndays org-agenda-ndays)
20433 start-day (or start-day org-agenda-start-day))
20434 (if org-agenda-overriding-arguments
20435 (setq include-all (car org-agenda-overriding-arguments)
20436 start-day (nth 1 org-agenda-overriding-arguments)
20437 ndays (nth 2 org-agenda-overriding-arguments)))
20438 (if (stringp start-day)
20439 ;; Convert to an absolute day number
20440 (setq start-day (time-to-days (org-read-date nil t start-day))))
20441 (setq org-agenda-last-arguments (list include-all start-day ndays))
20442 (org-compile-prefix-format 'agenda)
20443 (org-set-sorting-strategy 'agenda)
20444 (require 'calendar)
20445 (let* ((org-agenda-start-on-weekday
20446 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20447 org-agenda-start-on-weekday nil))
20448 (thefiles (org-agenda-files))
20449 (files thefiles)
20450 (today (time-to-days
20451 (time-subtract (current-time)
20452 (list 0 (* 3600 org-extend-today-until) 0))))
20453 (sd (or start-day today))
20454 (start (if (or (null org-agenda-start-on-weekday)
20455 (< org-agenda-ndays 7))
20457 (let* ((nt (calendar-day-of-week
20458 (calendar-gregorian-from-absolute sd)))
20459 (n1 org-agenda-start-on-weekday)
20460 (d (- nt n1)))
20461 (- sd (+ (if (< d 0) 7 0) d)))))
20462 (day-numbers (list start))
20463 (day-cnt 0)
20464 (inhibit-redisplay (not debug-on-error))
20465 s e rtn rtnall file date d start-pos end-pos todayp nd)
20466 (setq org-agenda-redo-command
20467 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20468 ;; Make the list of days
20469 (setq ndays (or ndays org-agenda-ndays)
20470 nd ndays)
20471 (while (> ndays 1)
20472 (push (1+ (car day-numbers)) day-numbers)
20473 (setq ndays (1- ndays)))
20474 (setq day-numbers (nreverse day-numbers))
20475 (org-prepare-agenda "Day/Week")
20476 (org-set-local 'org-starting-day (car day-numbers))
20477 (org-set-local 'org-include-all-loc include-all)
20478 (org-set-local 'org-agenda-span
20479 (org-agenda-ndays-to-span nd))
20480 (when (and (or include-all org-agenda-include-all-todo)
20481 (member today day-numbers))
20482 (setq files thefiles
20483 rtnall nil)
20484 (while (setq file (pop files))
20485 (catch 'nextfile
20486 (org-check-agenda-file file)
20487 (setq date (calendar-gregorian-from-absolute today)
20488 rtn (org-agenda-get-day-entries
20489 file date :todo))
20490 (setq rtnall (append rtnall rtn))))
20491 (when rtnall
20492 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20493 (add-text-properties (point-min) (1- (point))
20494 (list 'face 'org-agenda-structure))
20495 (insert (org-finalize-agenda-entries rtnall) "\n")))
20496 (unless org-agenda-compact-blocks
20497 (setq s (point))
20498 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20499 "-agenda:\n")
20500 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20501 'org-date-line t)))
20502 (while (setq d (pop day-numbers))
20503 (setq date (calendar-gregorian-from-absolute d)
20504 s (point))
20505 (if (or (setq todayp (= d today))
20506 (and (not start-pos) (= d sd)))
20507 (setq start-pos (point))
20508 (if (and start-pos (not end-pos))
20509 (setq end-pos (point))))
20510 (setq files thefiles
20511 rtnall nil)
20512 (while (setq file (pop files))
20513 (catch 'nextfile
20514 (org-check-agenda-file file)
20515 (if org-agenda-show-log
20516 (setq rtn (org-agenda-get-day-entries
20517 file date
20518 :deadline :scheduled :timestamp :sexp :closed))
20519 (setq rtn (org-agenda-get-day-entries
20520 file date
20521 :deadline :scheduled :sexp :timestamp)))
20522 (setq rtnall (append rtnall rtn))))
20523 (if org-agenda-include-diary
20524 (progn
20525 (require 'diary-lib)
20526 (setq rtn (org-get-entries-from-diary date))
20527 (setq rtnall (append rtnall rtn))))
20528 (if (or rtnall org-agenda-show-all-dates)
20529 (progn
20530 (setq day-cnt (1+ day-cnt))
20531 (insert
20532 (if (stringp org-agenda-format-date)
20533 (format-time-string org-agenda-format-date
20534 (org-time-from-absolute date))
20535 (funcall org-agenda-format-date date))
20536 "\n")
20537 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20538 (put-text-property s (1- (point)) 'org-date-line t)
20539 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20540 (if todayp (put-text-property s (1- (point)) 'org-today t))
20541 (if rtnall (insert
20542 (org-finalize-agenda-entries
20543 (org-agenda-add-time-grid-maybe
20544 rtnall nd todayp))
20545 "\n"))
20546 (put-text-property s (1- (point)) 'day d)
20547 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20548 (goto-char (point-min))
20549 (org-fit-agenda-window)
20550 (unless (and (pos-visible-in-window-p (point-min))
20551 (pos-visible-in-window-p (point-max)))
20552 (goto-char (1- (point-max)))
20553 (recenter -1)
20554 (if (not (pos-visible-in-window-p (or start-pos 1)))
20555 (progn
20556 (goto-char (or start-pos 1))
20557 (recenter 1))))
20558 (goto-char (or start-pos 1))
20559 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20560 (org-finalize-agenda)
20561 (setq buffer-read-only t)
20562 (message "")))
20564 (defun org-agenda-ndays-to-span (n)
20565 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20567 ;;; Agenda TODO list
20569 (defvar org-select-this-todo-keyword nil)
20570 (defvar org-last-arg nil)
20572 ;;;###autoload
20573 (defun org-todo-list (arg)
20574 "Show all TODO entries from all agenda file in a single list.
20575 The prefix arg can be used to select a specific TODO keyword and limit
20576 the list to these. When using \\[universal-argument], you will be prompted
20577 for a keyword. A numeric prefix directly selects the Nth keyword in
20578 `org-todo-keywords-1'."
20579 (interactive "P")
20580 (require 'calendar)
20581 (org-compile-prefix-format 'todo)
20582 (org-set-sorting-strategy 'todo)
20583 (org-prepare-agenda "TODO")
20584 (let* ((today (time-to-days (current-time)))
20585 (date (calendar-gregorian-from-absolute today))
20586 (kwds org-todo-keywords-for-agenda)
20587 (completion-ignore-case t)
20588 (org-select-this-todo-keyword
20589 (if (stringp arg) arg
20590 (and arg (integerp arg) (> arg 0)
20591 (nth (1- arg) kwds))))
20592 rtn rtnall files file pos)
20593 (when (equal arg '(4))
20594 (setq org-select-this-todo-keyword
20595 (completing-read "Keyword (or KWD1|K2D2|...): "
20596 (mapcar 'list kwds) nil nil)))
20597 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20598 (org-set-local 'org-last-arg arg)
20599 (setq org-agenda-redo-command
20600 '(org-todo-list (or current-prefix-arg org-last-arg)))
20601 (setq files (org-agenda-files)
20602 rtnall nil)
20603 (while (setq file (pop files))
20604 (catch 'nextfile
20605 (org-check-agenda-file file)
20606 (setq rtn (org-agenda-get-day-entries file date :todo))
20607 (setq rtnall (append rtnall rtn))))
20608 (if org-agenda-overriding-header
20609 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20610 nil 'face 'org-agenda-structure) "\n")
20611 (insert "Global list of TODO items of type: ")
20612 (add-text-properties (point-min) (1- (point))
20613 (list 'face 'org-agenda-structure))
20614 (setq pos (point))
20615 (insert (or org-select-this-todo-keyword "ALL") "\n")
20616 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20617 (setq pos (point))
20618 (unless org-agenda-multi
20619 (insert "Available with `N r': (0)ALL")
20620 (let ((n 0) s)
20621 (mapc (lambda (x)
20622 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20623 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20624 (insert "\n "))
20625 (insert " " s))
20626 kwds))
20627 (insert "\n"))
20628 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20629 (when rtnall
20630 (insert (org-finalize-agenda-entries rtnall) "\n"))
20631 (goto-char (point-min))
20632 (org-fit-agenda-window)
20633 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20634 (org-finalize-agenda)
20635 (setq buffer-read-only t)))
20637 ;;; Agenda tags match
20639 ;;;###autoload
20640 (defun org-tags-view (&optional todo-only match)
20641 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20642 The prefix arg TODO-ONLY limits the search to TODO entries."
20643 (interactive "P")
20644 (org-compile-prefix-format 'tags)
20645 (org-set-sorting-strategy 'tags)
20646 (let* ((org-tags-match-list-sublevels
20647 (if todo-only t org-tags-match-list-sublevels))
20648 (completion-ignore-case t)
20649 rtn rtnall files file pos matcher
20650 buffer)
20651 (setq matcher (org-make-tags-matcher match)
20652 match (car matcher) matcher (cdr matcher))
20653 (org-prepare-agenda (concat "TAGS " match))
20654 (setq org-agenda-redo-command
20655 (list 'org-tags-view (list 'quote todo-only)
20656 (list 'if 'current-prefix-arg nil match)))
20657 (setq files (org-agenda-files)
20658 rtnall nil)
20659 (while (setq file (pop files))
20660 (catch 'nextfile
20661 (org-check-agenda-file file)
20662 (setq buffer (if (file-exists-p file)
20663 (org-get-agenda-file-buffer file)
20664 (error "No such file %s" file)))
20665 (if (not buffer)
20666 ;; If file does not exist, merror message to agenda
20667 (setq rtn (list
20668 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20669 rtnall (append rtnall rtn))
20670 (with-current-buffer buffer
20671 (unless (org-mode-p)
20672 (error "Agenda file %s is not in `org-mode'" file))
20673 (save-excursion
20674 (save-restriction
20675 (if org-agenda-restrict
20676 (narrow-to-region org-agenda-restrict-begin
20677 org-agenda-restrict-end)
20678 (widen))
20679 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20680 (setq rtnall (append rtnall rtn))))))))
20681 (if org-agenda-overriding-header
20682 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20683 nil 'face 'org-agenda-structure) "\n")
20684 (insert "Headlines with TAGS match: ")
20685 (add-text-properties (point-min) (1- (point))
20686 (list 'face 'org-agenda-structure))
20687 (setq pos (point))
20688 (insert match "\n")
20689 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20690 (setq pos (point))
20691 (unless org-agenda-multi
20692 (insert "Press `C-u r' to search again with new search string\n"))
20693 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20694 (when rtnall
20695 (insert (org-finalize-agenda-entries rtnall) "\n"))
20696 (goto-char (point-min))
20697 (org-fit-agenda-window)
20698 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20699 (org-finalize-agenda)
20700 (setq buffer-read-only t)))
20702 ;;; Agenda Finding stuck projects
20704 (defvar org-agenda-skip-regexp nil
20705 "Regular expression used in skipping subtrees for the agenda.
20706 This is basically a temporary global variable that can be set and then
20707 used by user-defined selections using `org-agenda-skip-function'.")
20709 (defvar org-agenda-overriding-header nil
20710 "When this is set during todo and tags searches, will replace header.")
20712 (defun org-agenda-skip-subtree-when-regexp-matches ()
20713 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20714 If yes, it returns the end position of this tree, causing agenda commands
20715 to skip this subtree. This is a function that can be put into
20716 `org-agenda-skip-function' for the duration of a command."
20717 (let ((end (save-excursion (org-end-of-subtree t)))
20718 skip)
20719 (save-excursion
20720 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20721 (and skip end)))
20723 (defun org-agenda-skip-entry-if (&rest conditions)
20724 "Skip entry if any of CONDITIONS is true.
20725 See `org-agenda-skip-if' for details."
20726 (org-agenda-skip-if nil conditions))
20728 (defun org-agenda-skip-subtree-if (&rest conditions)
20729 "Skip entry if any of CONDITIONS is true.
20730 See `org-agenda-skip-if' for details."
20731 (org-agenda-skip-if t conditions))
20733 (defun org-agenda-skip-if (subtree conditions)
20734 "Checks current entity for CONDITIONS.
20735 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20736 the entry, i.e. the text before the next heading is checked.
20738 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20739 from different tests. Valid conditions are:
20741 scheduled Check if there is a scheduled cookie
20742 notscheduled Check if there is no scheduled cookie
20743 deadline Check if there is a deadline
20744 notdeadline Check if there is no deadline
20745 regexp Check if regexp matches
20746 notregexp Check if regexp does not match.
20748 The regexp is taken from the conditions list, it must come right after
20749 the `regexp' or `notregexp' element.
20751 If any of these conditions is met, this function returns the end point of
20752 the entity, causing the search to continue from there. This is a function
20753 that can be put into `org-agenda-skip-function' for the duration of a command."
20754 (let (beg end m)
20755 (org-back-to-heading t)
20756 (setq beg (point)
20757 end (if subtree
20758 (progn (org-end-of-subtree t) (point))
20759 (progn (outline-next-heading) (1- (point)))))
20760 (goto-char beg)
20761 (and
20763 (and (memq 'scheduled conditions)
20764 (re-search-forward org-scheduled-time-regexp end t))
20765 (and (memq 'notscheduled conditions)
20766 (not (re-search-forward org-scheduled-time-regexp end t)))
20767 (and (memq 'deadline conditions)
20768 (re-search-forward org-deadline-time-regexp end t))
20769 (and (memq 'notdeadline conditions)
20770 (not (re-search-forward org-deadline-time-regexp end t)))
20771 (and (setq m (memq 'regexp conditions))
20772 (stringp (nth 1 m))
20773 (re-search-forward (nth 1 m) end t))
20774 (and (setq m (memq 'notregexp conditions))
20775 (stringp (nth 1 m))
20776 (not (re-search-forward (nth 1 m) end t))))
20777 end)))
20779 ;;;###autoload
20780 (defun org-agenda-list-stuck-projects (&rest ignore)
20781 "Create agenda view for projects that are stuck.
20782 Stuck projects are project that have no next actions. For the definitions
20783 of what a project is and how to check if it stuck, customize the variable
20784 `org-stuck-projects'.
20785 MATCH is being ignored."
20786 (interactive)
20787 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20788 ;; FIXME: we could have used org-agenda-skip-if here.
20789 (org-agenda-overriding-header "List of stuck projects: ")
20790 (matcher (nth 0 org-stuck-projects))
20791 (todo (nth 1 org-stuck-projects))
20792 (todo-wds (if (member "*" todo)
20793 (progn
20794 (org-prepare-agenda-buffers (org-agenda-files))
20795 (org-delete-all
20796 org-done-keywords-for-agenda
20797 (copy-sequence org-todo-keywords-for-agenda)))
20798 todo))
20799 (todo-re (concat "^\\*+[ \t]+\\("
20800 (mapconcat 'identity todo-wds "\\|")
20801 "\\)\\>"))
20802 (tags (nth 2 org-stuck-projects))
20803 (tags-re (if (member "*" tags)
20804 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20805 (concat "^\\*+ .*:\\("
20806 (mapconcat 'identity tags "\\|")
20807 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20808 (gen-re (nth 3 org-stuck-projects))
20809 (re-list
20810 (delq nil
20811 (list
20812 (if todo todo-re)
20813 (if tags tags-re)
20814 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20815 gen-re)))))
20816 (setq org-agenda-skip-regexp
20817 (if re-list
20818 (mapconcat 'identity re-list "\\|")
20819 (error "No information how to identify unstuck projects")))
20820 (org-tags-view nil matcher)
20821 (with-current-buffer org-agenda-buffer-name
20822 (setq org-agenda-redo-command
20823 '(org-agenda-list-stuck-projects
20824 (or current-prefix-arg org-last-arg))))))
20826 ;;; Diary integration
20828 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20830 (defun org-get-entries-from-diary (date)
20831 "Get the (Emacs Calendar) diary entries for DATE."
20832 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20833 (diary-display-hook '(fancy-diary-display))
20834 (pop-up-frames nil)
20835 (list-diary-entries-hook
20836 (cons 'org-diary-default-entry list-diary-entries-hook))
20837 (diary-file-name-prefix-function nil) ; turn this feature off
20838 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20839 entries
20840 (org-disable-agenda-to-diary t))
20841 (save-excursion
20842 (save-window-excursion
20843 (funcall (if (fboundp 'diary-list-entries)
20844 'diary-list-entries 'list-diary-entries)
20845 date 1)))
20846 (if (not (get-buffer fancy-diary-buffer))
20847 (setq entries nil)
20848 (with-current-buffer fancy-diary-buffer
20849 (setq buffer-read-only nil)
20850 (if (zerop (buffer-size))
20851 ;; No entries
20852 (setq entries nil)
20853 ;; Omit the date and other unnecessary stuff
20854 (org-agenda-cleanup-fancy-diary)
20855 ;; Add prefix to each line and extend the text properties
20856 (if (zerop (buffer-size))
20857 (setq entries nil)
20858 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20859 (set-buffer-modified-p nil)
20860 (kill-buffer fancy-diary-buffer)))
20861 (when entries
20862 (setq entries (org-split-string entries "\n"))
20863 (setq entries
20864 (mapcar
20865 (lambda (x)
20866 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20867 ;; Extend the text properties to the beginning of the line
20868 (org-add-props x (text-properties-at (1- (length x)) x)
20869 'type "diary" 'date date))
20870 entries)))))
20872 (defun org-agenda-cleanup-fancy-diary ()
20873 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20874 This gets rid of the date, the underline under the date, and
20875 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20876 date. It also removes lines that contain only whitespace."
20877 (goto-char (point-min))
20878 (if (looking-at ".*?:[ \t]*")
20879 (progn
20880 (replace-match "")
20881 (re-search-forward "\n=+$" nil t)
20882 (replace-match "")
20883 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20884 (re-search-forward "\n=+$" nil t)
20885 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20886 (goto-char (point-min))
20887 (while (re-search-forward "^ +\n" nil t)
20888 (replace-match ""))
20889 (goto-char (point-min))
20890 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20891 (replace-match "")))
20893 ;; Make sure entries from the diary have the right text properties.
20894 (eval-after-load "diary-lib"
20895 '(if (boundp 'diary-modify-entry-list-string-function)
20896 ;; We can rely on the hook, nothing to do
20898 ;; Hook not avaiable, must use advice to make this work
20899 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20900 "Make the position visible."
20901 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20902 (stringp string)
20903 buffer-file-name)
20904 (setq string (org-modify-diary-entry-string string))))))
20906 (defun org-modify-diary-entry-string (string)
20907 "Add text properties to string, allowing org-mode to act on it."
20908 (org-add-props string nil
20909 'mouse-face 'highlight
20910 'keymap org-agenda-keymap
20911 'help-echo (if buffer-file-name
20912 (format "mouse-2 or RET jump to diary file %s"
20913 (abbreviate-file-name buffer-file-name))
20915 'org-agenda-diary-link t
20916 'org-marker (org-agenda-new-marker (point-at-bol))))
20918 (defun org-diary-default-entry ()
20919 "Add a dummy entry to the diary.
20920 Needed to avoid empty dates which mess up holiday display."
20921 ;; Catch the error if dealing with the new add-to-diary-alist
20922 (when org-disable-agenda-to-diary
20923 (condition-case nil
20924 (add-to-diary-list original-date "Org-mode dummy" "")
20925 (error
20926 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
20928 ;;;###autoload
20929 (defun org-diary (&rest args)
20930 "Return diary information from org-files.
20931 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
20932 It accesses org files and extracts information from those files to be
20933 listed in the diary. The function accepts arguments specifying what
20934 items should be listed. The following arguments are allowed:
20936 :timestamp List the headlines of items containing a date stamp or
20937 date range matching the selected date. Deadlines will
20938 also be listed, on the expiration day.
20940 :sexp List entries resulting from diary-like sexps.
20942 :deadline List any deadlines past due, or due within
20943 `org-deadline-warning-days'. The listing occurs only
20944 in the diary for *today*, not at any other date. If
20945 an entry is marked DONE, it is no longer listed.
20947 :scheduled List all items which are scheduled for the given date.
20948 The diary for *today* also contains items which were
20949 scheduled earlier and are not yet marked DONE.
20951 :todo List all TODO items from the org-file. This may be a
20952 long list - so this is not turned on by default.
20953 Like deadlines, these entries only show up in the
20954 diary for *today*, not at any other date.
20956 The call in the diary file should look like this:
20958 &%%(org-diary) ~/path/to/some/orgfile.org
20960 Use a separate line for each org file to check. Or, if you omit the file name,
20961 all files listed in `org-agenda-files' will be checked automatically:
20963 &%%(org-diary)
20965 If you don't give any arguments (as in the example above), the default
20966 arguments (:deadline :scheduled :timestamp :sexp) are used.
20967 So the example above may also be written as
20969 &%%(org-diary :deadline :timestamp :sexp :scheduled)
20971 The function expects the lisp variables `entry' and `date' to be provided
20972 by the caller, because this is how the calendar works. Don't use this
20973 function from a program - use `org-agenda-get-day-entries' instead."
20974 (org-agenda-maybe-reset-markers)
20975 (org-compile-prefix-format 'agenda)
20976 (org-set-sorting-strategy 'agenda)
20977 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20978 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
20979 (list entry)
20980 (org-agenda-files t)))
20981 file rtn results)
20982 (org-prepare-agenda-buffers files)
20983 ;; If this is called during org-agenda, don't return any entries to
20984 ;; the calendar. Org Agenda will list these entries itself.
20985 (if org-disable-agenda-to-diary (setq files nil))
20986 (while (setq file (pop files))
20987 (setq rtn (apply 'org-agenda-get-day-entries file date args))
20988 (setq results (append results rtn)))
20989 (if results
20990 (concat (org-finalize-agenda-entries results) "\n"))))
20992 ;;; Agenda entry finders
20994 (defun org-agenda-get-day-entries (file date &rest args)
20995 "Does the work for `org-diary' and `org-agenda'.
20996 FILE is the path to a file to be checked for entries. DATE is date like
20997 the one returned by `calendar-current-date'. ARGS are symbols indicating
20998 which kind of entries should be extracted. For details about these, see
20999 the documentation of `org-diary'."
21000 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21001 (let* ((org-startup-folded nil)
21002 (org-startup-align-all-tables nil)
21003 (buffer (if (file-exists-p file)
21004 (org-get-agenda-file-buffer file)
21005 (error "No such file %s" file)))
21006 arg results rtn)
21007 (if (not buffer)
21008 ;; If file does not exist, make sure an error message ends up in diary
21009 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21010 (with-current-buffer buffer
21011 (unless (org-mode-p)
21012 (error "Agenda file %s is not in `org-mode'" file))
21013 (let ((case-fold-search nil))
21014 (save-excursion
21015 (save-restriction
21016 (if org-agenda-restrict
21017 (narrow-to-region org-agenda-restrict-begin
21018 org-agenda-restrict-end)
21019 (widen))
21020 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21021 (while (setq arg (pop args))
21022 (cond
21023 ((and (eq arg :todo)
21024 (equal date (calendar-current-date)))
21025 (setq rtn (org-agenda-get-todos))
21026 (setq results (append results rtn)))
21027 ((eq arg :timestamp)
21028 (setq rtn (org-agenda-get-blocks))
21029 (setq results (append results rtn))
21030 (setq rtn (org-agenda-get-timestamps))
21031 (setq results (append results rtn)))
21032 ((eq arg :sexp)
21033 (setq rtn (org-agenda-get-sexps))
21034 (setq results (append results rtn)))
21035 ((eq arg :scheduled)
21036 (setq rtn (org-agenda-get-scheduled))
21037 (setq results (append results rtn)))
21038 ((eq arg :closed)
21039 (setq rtn (org-agenda-get-closed))
21040 (setq results (append results rtn)))
21041 ((eq arg :deadline)
21042 (setq rtn (org-agenda-get-deadlines))
21043 (setq results (append results rtn))))))))
21044 results))))
21046 (defun org-entry-is-todo-p ()
21047 (member (org-get-todo-state) org-not-done-keywords))
21049 (defun org-entry-is-done-p ()
21050 (member (org-get-todo-state) org-done-keywords))
21052 (defun org-get-todo-state ()
21053 (save-excursion
21054 (org-back-to-heading t)
21055 (and (looking-at org-todo-line-regexp)
21056 (match-end 2)
21057 (match-string 2))))
21059 (defun org-at-date-range-p (&optional inactive-ok)
21060 "Is the cursor inside a date range?"
21061 (interactive)
21062 (save-excursion
21063 (catch 'exit
21064 (let ((pos (point)))
21065 (skip-chars-backward "^[<\r\n")
21066 (skip-chars-backward "<[")
21067 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21068 (>= (match-end 0) pos)
21069 (throw 'exit t))
21070 (skip-chars-backward "^<[\r\n")
21071 (skip-chars-backward "<[")
21072 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21073 (>= (match-end 0) pos)
21074 (throw 'exit t)))
21075 nil)))
21077 (defun org-agenda-get-todos ()
21078 "Return the TODO information for agenda display."
21079 (let* ((props (list 'face nil
21080 'done-face 'org-done
21081 'org-not-done-regexp org-not-done-regexp
21082 'org-todo-regexp org-todo-regexp
21083 'mouse-face 'highlight
21084 'keymap org-agenda-keymap
21085 'help-echo
21086 (format "mouse-2 or RET jump to org file %s"
21087 (abbreviate-file-name buffer-file-name))))
21088 ;; FIXME: get rid of the \n at some point but watch out
21089 (regexp (concat "^\\*+[ \t]+\\("
21090 (if org-select-this-todo-keyword
21091 (if (equal org-select-this-todo-keyword "*")
21092 org-todo-regexp
21093 (concat "\\<\\("
21094 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21095 "\\)\\>"))
21096 org-not-done-regexp)
21097 "[^\n\r]*\\)"))
21098 marker priority category tags
21099 ee txt beg end)
21100 (goto-char (point-min))
21101 (while (re-search-forward regexp nil t)
21102 (catch :skip
21103 (save-match-data
21104 (beginning-of-line)
21105 (setq beg (point) end (progn (outline-next-heading) (point)))
21106 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21107 (re-search-forward org-ts-regexp end t))
21108 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21109 (re-search-forward org-scheduled-time-regexp end t))
21110 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21111 (re-search-forward org-deadline-time-regexp end t)
21112 (org-deadline-close (match-string 1))))
21113 (goto-char (1+ beg))
21114 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21115 (throw :skip nil)))
21116 (goto-char beg)
21117 (org-agenda-skip)
21118 (goto-char (match-beginning 1))
21119 (setq marker (org-agenda-new-marker (match-beginning 0))
21120 category (org-get-category)
21121 tags (org-get-tags-at (point))
21122 txt (org-format-agenda-item "" (match-string 1) category tags)
21123 priority (1+ (org-get-priority txt)))
21124 (org-add-props txt props
21125 'org-marker marker 'org-hd-marker marker
21126 'priority priority 'org-category category
21127 'type "todo")
21128 (push txt ee)
21129 (if org-agenda-todo-list-sublevels
21130 (goto-char (match-end 1))
21131 (org-end-of-subtree 'invisible))))
21132 (nreverse ee)))
21134 (defconst org-agenda-no-heading-message
21135 "No heading for this item in buffer or region.")
21137 (defun org-agenda-get-timestamps ()
21138 "Return the date stamp information for agenda display."
21139 (let* ((props (list 'face nil
21140 'org-not-done-regexp org-not-done-regexp
21141 'org-todo-regexp org-todo-regexp
21142 'mouse-face 'highlight
21143 'keymap org-agenda-keymap
21144 'help-echo
21145 (format "mouse-2 or RET jump to org file %s"
21146 (abbreviate-file-name buffer-file-name))))
21147 (d1 (calendar-absolute-from-gregorian date))
21148 (remove-re
21149 (concat
21150 (regexp-quote
21151 (format-time-string
21152 "<%Y-%m-%d"
21153 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21154 ".*?>"))
21155 (regexp
21156 (concat
21157 (regexp-quote
21158 (substring
21159 (format-time-string
21160 (car org-time-stamp-formats)
21161 (apply 'encode-time ; DATE bound by calendar
21162 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21163 0 11))
21164 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21165 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21166 marker hdmarker deadlinep scheduledp donep tmp priority category
21167 ee txt timestr tags b0 b3 e3 head)
21168 (goto-char (point-min))
21169 (while (re-search-forward regexp nil t)
21170 (setq b0 (match-beginning 0)
21171 b3 (match-beginning 3) e3 (match-end 3))
21172 (catch :skip
21173 (and (org-at-date-range-p) (throw :skip nil))
21174 (org-agenda-skip)
21175 (if (and (match-end 1)
21176 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21177 (throw :skip nil))
21178 (if (and e3
21179 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21180 (throw :skip nil))
21181 (setq marker (org-agenda-new-marker b0)
21182 category (org-get-category b0)
21183 tmp (buffer-substring (max (point-min)
21184 (- b0 org-ds-keyword-length))
21186 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21187 deadlinep (string-match org-deadline-regexp tmp)
21188 scheduledp (string-match org-scheduled-regexp tmp)
21189 donep (org-entry-is-done-p))
21190 (if (or scheduledp deadlinep) (throw :skip t))
21191 (if (string-match ">" timestr)
21192 ;; substring should only run to end of time stamp
21193 (setq timestr (substring timestr 0 (match-end 0))))
21194 (save-excursion
21195 (if (re-search-backward "^\\*+ " nil t)
21196 (progn
21197 (goto-char (match-beginning 0))
21198 (setq hdmarker (org-agenda-new-marker)
21199 tags (org-get-tags-at))
21200 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21201 (setq head (match-string 1))
21202 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21203 (setq txt (org-format-agenda-item
21204 nil head category tags timestr nil
21205 remove-re)))
21206 (setq txt org-agenda-no-heading-message))
21207 (setq priority (org-get-priority txt))
21208 (org-add-props txt props
21209 'org-marker marker 'org-hd-marker hdmarker)
21210 (org-add-props txt nil 'priority priority
21211 'org-category category 'date date
21212 'type "timestamp")
21213 (push txt ee))
21214 (outline-next-heading)))
21215 (nreverse ee)))
21217 (defun org-agenda-get-sexps ()
21218 "Return the sexp information for agenda display."
21219 (require 'diary-lib)
21220 (let* ((props (list 'face nil
21221 'mouse-face 'highlight
21222 'keymap org-agenda-keymap
21223 'help-echo
21224 (format "mouse-2 or RET jump to org file %s"
21225 (abbreviate-file-name buffer-file-name))))
21226 (regexp "^&?%%(")
21227 marker category ee txt tags entry result beg b sexp sexp-entry)
21228 (goto-char (point-min))
21229 (while (re-search-forward regexp nil t)
21230 (catch :skip
21231 (org-agenda-skip)
21232 (setq beg (match-beginning 0))
21233 (goto-char (1- (match-end 0)))
21234 (setq b (point))
21235 (forward-sexp 1)
21236 (setq sexp (buffer-substring b (point)))
21237 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21238 (org-trim (match-string 1))
21239 ""))
21240 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21241 (when result
21242 (setq marker (org-agenda-new-marker beg)
21243 category (org-get-category beg))
21245 (if (string-match "\\S-" result)
21246 (setq txt result)
21247 (setq txt "SEXP entry returned empty string"))
21249 (setq txt (org-format-agenda-item
21250 "" txt category tags 'time))
21251 (org-add-props txt props 'org-marker marker)
21252 (org-add-props txt nil
21253 'org-category category 'date date
21254 'type "sexp")
21255 (push txt ee))))
21256 (nreverse ee)))
21258 (defun org-agenda-get-closed ()
21259 "Return the logged TODO entries for agenda display."
21260 (let* ((props (list 'mouse-face 'highlight
21261 'org-not-done-regexp org-not-done-regexp
21262 'org-todo-regexp org-todo-regexp
21263 'keymap org-agenda-keymap
21264 'help-echo
21265 (format "mouse-2 or RET jump to org file %s"
21266 (abbreviate-file-name buffer-file-name))))
21267 (regexp (concat
21268 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21269 (regexp-quote
21270 (substring
21271 (format-time-string
21272 (car org-time-stamp-formats)
21273 (apply 'encode-time ; DATE bound by calendar
21274 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21275 1 11))))
21276 marker hdmarker priority category tags closedp
21277 ee txt timestr)
21278 (goto-char (point-min))
21279 (while (re-search-forward regexp nil t)
21280 (catch :skip
21281 (org-agenda-skip)
21282 (setq marker (org-agenda-new-marker (match-beginning 0))
21283 closedp (equal (match-string 1) org-closed-string)
21284 category (org-get-category (match-beginning 0))
21285 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21286 ;; donep (org-entry-is-done-p)
21288 (if (string-match "\\]" timestr)
21289 ;; substring should only run to end of time stamp
21290 (setq timestr (substring timestr 0 (match-end 0))))
21291 (save-excursion
21292 (if (re-search-backward "^\\*+ " nil t)
21293 (progn
21294 (goto-char (match-beginning 0))
21295 (setq hdmarker (org-agenda-new-marker)
21296 tags (org-get-tags-at))
21297 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21298 (setq txt (org-format-agenda-item
21299 (if closedp "Closed: " "Clocked: ")
21300 (match-string 1) category tags timestr)))
21301 (setq txt org-agenda-no-heading-message))
21302 (setq priority 100000)
21303 (org-add-props txt props
21304 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21305 'priority priority 'org-category category
21306 'type "closed" 'date date
21307 'undone-face 'org-warning 'done-face 'org-done)
21308 (push txt ee))
21309 (outline-next-heading)))
21310 (nreverse ee)))
21312 (defun org-agenda-get-deadlines ()
21313 "Return the deadline information for agenda display."
21314 (let* ((props (list 'mouse-face 'highlight
21315 'org-not-done-regexp org-not-done-regexp
21316 'org-todo-regexp org-todo-regexp
21317 'keymap org-agenda-keymap
21318 'help-echo
21319 (format "mouse-2 or RET jump to org file %s"
21320 (abbreviate-file-name buffer-file-name))))
21321 (regexp org-deadline-time-regexp)
21322 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21323 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21324 d2 diff dfrac wdays pos pos1 category tags
21325 ee txt head face s upcomingp donep timestr)
21326 (goto-char (point-min))
21327 (while (re-search-forward regexp nil t)
21328 (catch :skip
21329 (org-agenda-skip)
21330 (setq s (match-string 1)
21331 pos (1- (match-beginning 1))
21332 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21333 diff (- d2 d1)
21334 wdays (org-get-wdays s)
21335 dfrac (/ (* 1.0 (- wdays diff)) wdays)
21336 upcomingp (and todayp (> diff 0)))
21337 ;; When to show a deadline in the calendar:
21338 ;; If the expiration is within wdays warning time.
21339 ;; Past-due deadlines are only shown on the current date
21340 (if (or (and (<= diff wdays)
21341 (and todayp (not org-agenda-only-exact-dates)))
21342 (= diff 0))
21343 (save-excursion
21344 (setq category (org-get-category))
21345 (if (re-search-backward "^\\*+[ \t]+" nil t)
21346 (progn
21347 (goto-char (match-end 0))
21348 (setq pos1 (match-beginning 0))
21349 (setq tags (org-get-tags-at pos1))
21350 (setq head (buffer-substring-no-properties
21351 (point)
21352 (progn (skip-chars-forward "^\r\n")
21353 (point))))
21354 (setq donep (string-match org-looking-at-done-regexp head))
21355 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21356 (setq timestr
21357 (concat (substring s (match-beginning 1)) " "))
21358 (setq timestr 'time))
21359 (if (and donep
21360 (or org-agenda-skip-deadline-if-done
21361 (not (= diff 0))))
21362 (setq txt nil)
21363 (setq txt (org-format-agenda-item
21364 (if (= diff 0)
21365 (car org-agenda-deadline-leaders)
21366 (format (nth 1 org-agenda-deadline-leaders)
21367 diff))
21368 head category tags timestr))))
21369 (setq txt org-agenda-no-heading-message))
21370 (when txt
21371 (setq face (org-agenda-deadline-face dfrac))
21372 (org-add-props txt props
21373 'org-marker (org-agenda-new-marker pos)
21374 'org-hd-marker (org-agenda-new-marker pos1)
21375 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
21376 (org-get-priority txt))
21377 'org-category category
21378 'type (if upcomingp "upcoming-deadline" "deadline")
21379 'date (if upcomingp date d2)
21380 'face (if donep 'org-done face)
21381 'undone-face face 'done-face 'org-done)
21382 (push txt ee))))))
21383 (nreverse ee)))
21385 (defun org-agenda-deadline-face (fraction)
21386 "Return the face to displaying a deadline item.
21387 FRACTION is what fraction of the head-warning time has passed."
21388 (let ((faces org-agenda-deadline-faces) f)
21389 (catch 'exit
21390 (while (setq f (pop faces))
21391 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21393 (defun org-agenda-get-scheduled ()
21394 "Return the scheduled information for agenda display."
21395 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21396 'org-todo-regexp org-todo-regexp
21397 'done-face 'org-done
21398 'mouse-face 'highlight
21399 'keymap org-agenda-keymap
21400 'help-echo
21401 (format "mouse-2 or RET jump to org file %s"
21402 (abbreviate-file-name buffer-file-name))))
21403 (regexp org-scheduled-time-regexp)
21404 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21405 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21406 d2 diff pos pos1 category tags
21407 ee txt head pastschedp donep face timestr s)
21408 (goto-char (point-min))
21409 (while (re-search-forward regexp nil t)
21410 (catch :skip
21411 (org-agenda-skip)
21412 (setq s (match-string 1)
21413 pos (1- (match-beginning 1))
21414 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21415 ;;; is this right?
21416 ;;; do we need to do this for deadleine too????
21417 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21418 diff (- d2 d1))
21419 (setq pastschedp (and todayp (< diff 0)))
21420 ;; When to show a scheduled item in the calendar:
21421 ;; If it is on or past the date.
21422 (if (or (and (< diff 0)
21423 (and todayp (not org-agenda-only-exact-dates)))
21424 (= diff 0))
21425 (save-excursion
21426 (setq category (org-get-category))
21427 (if (re-search-backward "^\\*+[ \t]+" nil t)
21428 (progn
21429 (goto-char (match-end 0))
21430 (setq pos1 (match-beginning 0))
21431 (setq tags (org-get-tags-at))
21432 (setq head (buffer-substring-no-properties
21433 (point)
21434 (progn (skip-chars-forward "^\r\n") (point))))
21435 (setq donep (string-match org-looking-at-done-regexp head))
21436 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21437 (setq timestr
21438 (concat (substring s (match-beginning 1)) " "))
21439 (setq timestr 'time))
21440 (if (and donep
21441 (or org-agenda-skip-scheduled-if-done
21442 (not (= diff 0))))
21443 (setq txt nil)
21444 (setq txt (org-format-agenda-item
21445 (if (= diff 0)
21446 (car org-agenda-scheduled-leaders)
21447 (format (nth 1 org-agenda-scheduled-leaders)
21448 (- 1 diff)))
21449 head category tags timestr))))
21450 (setq txt org-agenda-no-heading-message))
21451 (when txt
21452 (setq face (if pastschedp
21453 'org-scheduled-previously
21454 'org-scheduled-today))
21455 (org-add-props txt props
21456 'undone-face face
21457 'face (if donep 'org-done face)
21458 'org-marker (org-agenda-new-marker pos)
21459 'org-hd-marker (org-agenda-new-marker pos1)
21460 'type (if pastschedp "past-scheduled" "scheduled")
21461 'date (if pastschedp d2 date)
21462 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21463 'org-category category)
21464 (push txt ee))))))
21465 (nreverse ee)))
21467 (defun org-agenda-get-blocks ()
21468 "Return the date-range information for agenda display."
21469 (let* ((props (list 'face nil
21470 'org-not-done-regexp org-not-done-regexp
21471 'org-todo-regexp org-todo-regexp
21472 'mouse-face 'highlight
21473 'keymap org-agenda-keymap
21474 'help-echo
21475 (format "mouse-2 or RET jump to org file %s"
21476 (abbreviate-file-name buffer-file-name))))
21477 (regexp org-tr-regexp)
21478 (d0 (calendar-absolute-from-gregorian date))
21479 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21480 donep head)
21481 (goto-char (point-min))
21482 (while (re-search-forward regexp nil t)
21483 (catch :skip
21484 (org-agenda-skip)
21485 (setq pos (point))
21486 (setq timestr (match-string 0)
21487 s1 (match-string 1)
21488 s2 (match-string 2)
21489 d1 (time-to-days (org-time-string-to-time s1))
21490 d2 (time-to-days (org-time-string-to-time s2)))
21491 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21492 ;; Only allow days between the limits, because the normal
21493 ;; date stamps will catch the limits.
21494 (save-excursion
21495 (setq marker (org-agenda-new-marker (point)))
21496 (setq category (org-get-category))
21497 (if (re-search-backward "^\\*+ " nil t)
21498 (progn
21499 (goto-char (match-beginning 0))
21500 (setq hdmarker (org-agenda-new-marker (point)))
21501 (setq tags (org-get-tags-at))
21502 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21503 (setq head (match-string 1))
21504 (and org-agenda-skip-timestamp-if-done
21505 (org-entry-is-done-p)
21506 (throw :skip t))
21507 (setq txt (org-format-agenda-item
21508 (format (if (= d1 d2) "" "(%d/%d): ")
21509 (1+ (- d0 d1)) (1+ (- d2 d1)))
21510 head category tags
21511 (if (= d0 d1) timestr))))
21512 (setq txt org-agenda-no-heading-message))
21513 (org-add-props txt props
21514 'org-marker marker 'org-hd-marker hdmarker
21515 'type "block" 'date date
21516 'priority (org-get-priority txt) 'org-category category)
21517 (push txt ee)))
21518 (goto-char pos)))
21519 ;; Sort the entries by expiration date.
21520 (nreverse ee)))
21522 ;;; Agenda presentation and sorting
21524 (defconst org-plain-time-of-day-regexp
21525 (concat
21526 "\\(\\<[012]?[0-9]"
21527 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21528 "\\(--?"
21529 "\\(\\<[012]?[0-9]"
21530 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21531 "\\)?")
21532 "Regular expression to match a plain time or time range.
21533 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21534 groups carry important information:
21535 0 the full match
21536 1 the first time, range or not
21537 8 the second time, if it is a range.")
21539 (defconst org-plain-time-extension-regexp
21540 (concat
21541 "\\(\\<[012]?[0-9]"
21542 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21543 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21544 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21545 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21546 groups carry important information:
21547 0 the full match
21548 7 hours of duration
21549 9 minutes of duration")
21551 (defconst org-stamp-time-of-day-regexp
21552 (concat
21553 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21554 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21555 "\\(--?"
21556 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21557 "Regular expression to match a timestamp time or time range.
21558 After a match, the following groups carry important information:
21559 0 the full match
21560 1 date plus weekday, for backreferencing to make sure both times on same day
21561 2 the first time, range or not
21562 4 the second time, if it is a range.")
21564 (defvar org-prefix-has-time nil
21565 "A flag, set by `org-compile-prefix-format'.
21566 The flag is set if the currently compiled format contains a `%t'.")
21567 (defvar org-prefix-has-tag nil
21568 "A flag, set by `org-compile-prefix-format'.
21569 The flag is set if the currently compiled format contains a `%T'.")
21571 (defun org-format-agenda-item (extra txt &optional category tags dotime
21572 noprefix remove-re)
21573 "Format TXT to be inserted into the agenda buffer.
21574 In particular, it adds the prefix and corresponding text properties. EXTRA
21575 must be a string and replaces the `%s' specifier in the prefix format.
21576 CATEGORY (string, symbol or nil) may be used to overrule the default
21577 category taken from local variable or file name. It will replace the `%c'
21578 specifier in the format. DOTIME, when non-nil, indicates that a
21579 time-of-day should be extracted from TXT for sorting of this entry, and for
21580 the `%t' specifier in the format. When DOTIME is a string, this string is
21581 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21582 only the correctly processes TXT should be returned - this is used by
21583 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21584 Any match of REMOVE-RE will be removed from TXT."
21585 (save-match-data
21586 ;; Diary entries sometimes have extra whitespace at the beginning
21587 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21588 (let* ((category (or category
21589 org-category
21590 (if buffer-file-name
21591 (file-name-sans-extension
21592 (file-name-nondirectory buffer-file-name))
21593 "")))
21594 (tag (if tags (nth (1- (length tags)) tags) ""))
21595 time ; time and tag are needed for the eval of the prefix format
21596 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21597 (time-of-day (and dotime (org-get-time-of-day ts)))
21598 stamp plain s0 s1 s2 rtn srp)
21599 (when (and dotime time-of-day org-prefix-has-time)
21600 ;; Extract starting and ending time and move them to prefix
21601 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21602 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21603 (setq s0 (match-string 0 ts)
21604 srp (and stamp (match-end 3))
21605 s1 (match-string (if plain 1 2) ts)
21606 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21608 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21609 ;; them, we might want to remove them there to avoid duplication.
21610 ;; The user can turn this off with a variable.
21611 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21612 (string-match (concat (regexp-quote s0) " *") txt)
21613 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21614 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21615 (= (match-beginning 0) 0)
21617 (setq txt (replace-match "" nil nil txt))))
21618 ;; Normalize the time(s) to 24 hour
21619 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21620 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21622 (when (and s1 (not s2) org-agenda-default-appointment-duration
21623 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21624 (let ((m (+ (string-to-number (match-string 2 s1))
21625 (* 60 (string-to-number (match-string 1 s1)))
21626 org-agenda-default-appointment-duration))
21628 (setq h (/ m 60) m (- m (* h 60)))
21629 (setq s2 (format "%02d:%02d" h m))))
21631 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21632 txt)
21633 ;; Tags are in the string
21634 (if (or (eq org-agenda-remove-tags t)
21635 (and org-agenda-remove-tags
21636 org-prefix-has-tag))
21637 (setq txt (replace-match "" t t txt))
21638 (setq txt (replace-match
21639 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21640 (match-string 2 txt))
21641 t t txt))))
21643 (when remove-re
21644 (while (string-match remove-re txt)
21645 (setq txt (replace-match "" t t txt))))
21647 ;; Create the final string
21648 (if noprefix
21649 (setq rtn txt)
21650 ;; Prepare the variables needed in the eval of the compiled format
21651 (setq time (cond (s2 (concat s1 "-" s2))
21652 (s1 (concat s1 "......"))
21653 (t ""))
21654 extra (or extra "")
21655 category (if (symbolp category) (symbol-name category) category))
21656 ;; Evaluate the compiled format
21657 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21659 ;; And finally add the text properties
21660 (org-add-props rtn nil
21661 'org-category (downcase category) 'tags tags
21662 'org-highest-priority org-highest-priority
21663 'org-lowest-priority org-lowest-priority
21664 'prefix-length (- (length rtn) (length txt))
21665 'time-of-day time-of-day
21666 'txt txt
21667 'time time
21668 'extra extra
21669 'dotime dotime))))
21671 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21672 (defvar org-agenda-sorting-strategy-selected nil)
21674 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21675 (catch 'exit
21676 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21677 ((and todayp (member 'today (car org-agenda-time-grid))))
21678 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21679 ((member 'weekly (car org-agenda-time-grid)))
21680 (t (throw 'exit list)))
21681 (let* ((have (delq nil (mapcar
21682 (lambda (x) (get-text-property 1 'time-of-day x))
21683 list)))
21684 (string (nth 1 org-agenda-time-grid))
21685 (gridtimes (nth 2 org-agenda-time-grid))
21686 (req (car org-agenda-time-grid))
21687 (remove (member 'remove-match req))
21688 new time)
21689 (if (and (member 'require-timed req) (not have))
21690 ;; don't show empty grid
21691 (throw 'exit list))
21692 (while (setq time (pop gridtimes))
21693 (unless (and remove (member time have))
21694 (setq time (int-to-string time))
21695 (push (org-format-agenda-item
21696 nil string "" nil
21697 (concat (substring time 0 -2) ":" (substring time -2)))
21698 new)
21699 (put-text-property
21700 1 (length (car new)) 'face 'org-time-grid (car new))))
21701 (if (member 'time-up org-agenda-sorting-strategy-selected)
21702 (append new list)
21703 (append list new)))))
21705 (defun org-compile-prefix-format (key)
21706 "Compile the prefix format into a Lisp form that can be evaluated.
21707 The resulting form is returned and stored in the variable
21708 `org-prefix-format-compiled'."
21709 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21710 (let ((s (cond
21711 ((stringp org-agenda-prefix-format)
21712 org-agenda-prefix-format)
21713 ((assq key org-agenda-prefix-format)
21714 (cdr (assq key org-agenda-prefix-format)))
21715 (t " %-12:c%?-12t% s")))
21716 (start 0)
21717 varform vars var e c f opt)
21718 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21719 s start)
21720 (setq var (cdr (assoc (match-string 4 s)
21721 '(("c" . category) ("t" . time) ("s" . extra)
21722 ("T" . tag))))
21723 c (or (match-string 3 s) "")
21724 opt (match-beginning 1)
21725 start (1+ (match-beginning 0)))
21726 (if (equal var 'time) (setq org-prefix-has-time t))
21727 (if (equal var 'tag) (setq org-prefix-has-tag t))
21728 (setq f (concat "%" (match-string 2 s) "s"))
21729 (if opt
21730 (setq varform
21731 `(if (equal "" ,var)
21733 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21734 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21735 (setq s (replace-match "%s" t nil s))
21736 (push varform vars))
21737 (setq vars (nreverse vars))
21738 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21740 (defun org-set-sorting-strategy (key)
21741 (if (symbolp (car org-agenda-sorting-strategy))
21742 ;; the old format
21743 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21744 (setq org-agenda-sorting-strategy-selected
21745 (or (cdr (assq key org-agenda-sorting-strategy))
21746 (cdr (assq 'agenda org-agenda-sorting-strategy))
21747 '(time-up category-keep priority-down)))))
21749 (defun org-get-time-of-day (s &optional string mod24)
21750 "Check string S for a time of day.
21751 If found, return it as a military time number between 0 and 2400.
21752 If not found, return nil.
21753 The optional STRING argument forces conversion into a 5 character wide string
21754 HH:MM."
21755 (save-match-data
21756 (when
21757 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21758 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21759 (let* ((h (string-to-number (match-string 1 s)))
21760 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21761 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21762 (am-p (equal ampm "am"))
21763 (h1 (cond ((not ampm) h)
21764 ((= h 12) (if am-p 0 12))
21765 (t (+ h (if am-p 0 12)))))
21766 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21767 (mod h1 24) h1))
21768 (t0 (+ (* 100 h2) m))
21769 (t1 (concat (if (>= h1 24) "+" " ")
21770 (if (< t0 100) "0" "")
21771 (if (< t0 10) "0" "")
21772 (int-to-string t0))))
21773 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21775 (defun org-finalize-agenda-entries (list &optional nosort)
21776 "Sort and concatenate the agenda items."
21777 (setq list (mapcar 'org-agenda-highlight-todo list))
21778 (if nosort
21779 list
21780 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21782 (defun org-agenda-highlight-todo (x)
21783 (let (re pl)
21784 (if (eq x 'line)
21785 (save-excursion
21786 (beginning-of-line 1)
21787 (setq re (get-text-property (point) 'org-todo-regexp))
21788 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21789 (when (looking-at (concat "[ \t]*\\.*" re " +"))
21790 (add-text-properties (match-beginning 0) (match-end 0)
21791 (list 'face (org-get-todo-face 0)))
21792 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
21793 (delete-region (match-beginning 1) (1- (match-end 0)))
21794 (goto-char (match-beginning 1))
21795 (insert (format org-agenda-todo-keyword-format s)))))
21796 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21797 pl (get-text-property 0 'prefix-length x))
21798 ; (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21799 ; (add-text-properties
21800 ; (or (match-end 1) (match-end 0)) (match-end 0)
21801 ; (list 'face (org-get-todo-face (match-string 2 x)))
21802 ; x))
21803 (when (and re
21804 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
21805 x (or pl 0)) pl))
21806 (add-text-properties
21807 (or (match-end 1) (match-end 0)) (match-end 0)
21808 (list 'face (org-get-todo-face (match-string 2 x)))
21810 (setq x (concat (substring x 0 (match-end 1))
21811 (format org-agenda-todo-keyword-format
21812 (match-string 2 x))
21814 (substring x (match-end 3)))))
21815 x)))
21817 (defsubst org-cmp-priority (a b)
21818 "Compare the priorities of string A and B."
21819 (let ((pa (or (get-text-property 1 'priority a) 0))
21820 (pb (or (get-text-property 1 'priority b) 0)))
21821 (cond ((> pa pb) +1)
21822 ((< pa pb) -1)
21823 (t nil))))
21825 (defsubst org-cmp-category (a b)
21826 "Compare the string values of categories of strings A and B."
21827 (let ((ca (or (get-text-property 1 'org-category a) ""))
21828 (cb (or (get-text-property 1 'org-category b) "")))
21829 (cond ((string-lessp ca cb) -1)
21830 ((string-lessp cb ca) +1)
21831 (t nil))))
21833 (defsubst org-cmp-tag (a b)
21834 "Compare the string values of categories of strings A and B."
21835 (let ((ta (car (last (get-text-property 1 'tags a))))
21836 (tb (car (last (get-text-property 1 'tags b)))))
21837 (cond ((not ta) +1)
21838 ((not tb) -1)
21839 ((string-lessp ta tb) -1)
21840 ((string-lessp tb ta) +1)
21841 (t nil))))
21843 (defsubst org-cmp-time (a b)
21844 "Compare the time-of-day values of strings A and B."
21845 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21846 (ta (or (get-text-property 1 'time-of-day a) def))
21847 (tb (or (get-text-property 1 'time-of-day b) def)))
21848 (cond ((< ta tb) -1)
21849 ((< tb ta) +1)
21850 (t nil))))
21852 (defun org-entries-lessp (a b)
21853 "Predicate for sorting agenda entries."
21854 ;; The following variables will be used when the form is evaluated.
21855 ;; So even though the compiler complains, keep them.
21856 (let* ((time-up (org-cmp-time a b))
21857 (time-down (if time-up (- time-up) nil))
21858 (priority-up (org-cmp-priority a b))
21859 (priority-down (if priority-up (- priority-up) nil))
21860 (category-up (org-cmp-category a b))
21861 (category-down (if category-up (- category-up) nil))
21862 (category-keep (if category-up +1 nil))
21863 (tag-up (org-cmp-tag a b))
21864 (tag-down (if tag-up (- tag-up) nil)))
21865 (cdr (assoc
21866 (eval (cons 'or org-agenda-sorting-strategy-selected))
21867 '((-1 . t) (1 . nil) (nil . nil))))))
21869 ;;; Agenda restriction lock
21871 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21872 "Overlay to mark the headline to which arenda commands are restricted.")
21873 (org-overlay-put org-agenda-restriction-lock-overlay
21874 'face 'org-agenda-restriction-lock)
21875 (org-overlay-put org-agenda-restriction-lock-overlay
21876 'help-echo "Agendas are currently limited to this subtree.")
21877 (org-detach-overlay org-agenda-restriction-lock-overlay)
21878 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21879 "Overlay marking the agenda restriction line in speedbar.")
21880 (org-overlay-put org-speedbar-restriction-lock-overlay
21881 'face 'org-agenda-restriction-lock)
21882 (org-overlay-put org-speedbar-restriction-lock-overlay
21883 'help-echo "Agendas are currently limited to this item.")
21884 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21886 (defun org-agenda-set-restriction-lock (&optional type)
21887 "Set restriction lock for agenda, to current subtree or file.
21888 Restriction will be the file if TYPE is `file', or if type is the
21889 universal prefix '(4), or if the cursor is before the first headline
21890 in the file. Otherwise, restriction will be to the current subtree."
21891 (interactive "P")
21892 (and (equal type '(4)) (setq type 'file))
21893 (setq type (cond
21894 (type type)
21895 ((org-at-heading-p) 'subtree)
21896 ((condition-case nil (org-back-to-heading t) (error nil))
21897 'subtree)
21898 (t 'file)))
21899 (if (eq type 'subtree)
21900 (progn
21901 (setq org-agenda-restrict t)
21902 (setq org-agenda-overriding-restriction 'subtree)
21903 (put 'org-agenda-files 'org-restrict
21904 (list (buffer-file-name (buffer-base-buffer))))
21905 (org-back-to-heading t)
21906 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21907 (move-marker org-agenda-restrict-begin (point))
21908 (move-marker org-agenda-restrict-end
21909 (save-excursion (org-end-of-subtree t)))
21910 (message "Locking agenda restriction to subtree"))
21911 (put 'org-agenda-files 'org-restrict
21912 (list (buffer-file-name (buffer-base-buffer))))
21913 (setq org-agenda-restrict nil)
21914 (setq org-agenda-overriding-restriction 'file)
21915 (move-marker org-agenda-restrict-begin nil)
21916 (move-marker org-agenda-restrict-end nil)
21917 (message "Locking agenda restriction to file"))
21918 (setq current-prefix-arg nil)
21919 (org-agenda-maybe-redo))
21921 (defun org-agenda-remove-restriction-lock (&optional noupdate)
21922 "Remove the agenda restriction lock."
21923 (interactive "P")
21924 (org-detach-overlay org-agenda-restriction-lock-overlay)
21925 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21926 (setq org-agenda-overriding-restriction nil)
21927 (setq org-agenda-restrict nil)
21928 (put 'org-agenda-files 'org-restrict nil)
21929 (move-marker org-agenda-restrict-begin nil)
21930 (move-marker org-agenda-restrict-end nil)
21931 (setq current-prefix-arg nil)
21932 (message "Agenda restriction lock removed")
21933 (or noupdate (org-agenda-maybe-redo)))
21935 (defun org-agenda-maybe-redo ()
21936 "If there is any window showing the agenda view, update it."
21937 (let ((w (get-buffer-window org-agenda-buffer-name t))
21938 (w0 (selected-window)))
21939 (when w
21940 (select-window w)
21941 (org-agenda-redo)
21942 (select-window w0)
21943 (if org-agenda-overriding-restriction
21944 (message "Agenda view shifted to new %s restriction"
21945 org-agenda-overriding-restriction)
21946 (message "Agenda restriction lock removed")))))
21948 ;;; Agenda commands
21950 (defun org-agenda-check-type (error &rest types)
21951 "Check if agenda buffer is of allowed type.
21952 If ERROR is non-nil, throw an error, otherwise just return nil."
21953 (if (memq org-agenda-type types)
21955 (if error
21956 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
21957 nil)))
21959 (defun org-agenda-quit ()
21960 "Exit agenda by removing the window or the buffer."
21961 (interactive)
21962 (let ((buf (current-buffer)))
21963 (if (not (one-window-p)) (delete-window))
21964 (kill-buffer buf)
21965 (org-agenda-maybe-reset-markers 'force)
21966 (org-columns-remove-overlays))
21967 ;; Maybe restore the pre-agenda window configuration.
21968 (and org-agenda-restore-windows-after-quit
21969 (not (eq org-agenda-window-setup 'other-frame))
21970 org-pre-agenda-window-conf
21971 (set-window-configuration org-pre-agenda-window-conf)))
21973 (defun org-agenda-exit ()
21974 "Exit agenda by removing the window or the buffer.
21975 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
21976 Org-mode buffers visited directly by the user will not be touched."
21977 (interactive)
21978 (org-release-buffers org-agenda-new-buffers)
21979 (setq org-agenda-new-buffers nil)
21980 (org-agenda-quit))
21982 (defun org-agenda-execute (arg)
21983 "Execute another agenda command, keeping same window.\\<global-map>
21984 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
21985 (interactive "P")
21986 (let ((org-agenda-window-setup 'current-window))
21987 (org-agenda arg)))
21989 (defun org-save-all-org-buffers ()
21990 "Save all Org-mode buffers without user confirmation."
21991 (interactive)
21992 (message "Saving all Org-mode buffers...")
21993 (save-some-buffers t 'org-mode-p)
21994 (message "Saving all Org-mode buffers... done"))
21996 (defun org-agenda-redo ()
21997 "Rebuild Agenda.
21998 When this is the global TODO list, a prefix argument will be interpreted."
21999 (interactive)
22000 (let* ((org-agenda-keep-modes t)
22001 (line (org-current-line))
22002 (window-line (- line (org-current-line (window-start))))
22003 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22004 (message "Rebuilding agenda buffer...")
22005 (org-let lprops '(eval org-agenda-redo-command))
22006 (setq org-agenda-undo-list nil
22007 org-agenda-pending-undo-list nil)
22008 (message "Rebuilding agenda buffer...done")
22009 (goto-line line)
22010 (recenter window-line)))
22012 (defun org-agenda-goto-date (date)
22013 "Jump to DATE in agenda."
22014 (interactive (list (org-read-date)))
22015 (org-agenda-list nil date))
22017 (defun org-agenda-goto-today ()
22018 "Go to today."
22019 (interactive)
22020 (org-agenda-check-type t 'timeline 'agenda)
22021 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22022 (cond
22023 (tdpos (goto-char tdpos))
22024 ((eq org-agenda-type 'agenda)
22025 (let* ((sd (time-to-days
22026 (time-subtract (current-time)
22027 (list 0 (* 3600 org-extend-today-until) 0))))
22028 (comp (org-agenda-compute-time-span sd org-agenda-span))
22029 (org-agenda-overriding-arguments org-agenda-last-arguments))
22030 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22031 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22032 (org-agenda-redo)
22033 (org-agenda-find-same-or-today-or-agenda)))
22034 (t (error "Cannot find today")))))
22036 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22037 (goto-char
22038 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22039 (text-property-any (point-min) (point-max) 'org-today t)
22040 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22041 (point-min))))
22043 (defun org-agenda-later (arg)
22044 "Go forward in time by thee current span.
22045 With prefix ARG, go forward that many times the current span."
22046 (interactive "p")
22047 (org-agenda-check-type t 'agenda)
22048 (let* ((span org-agenda-span)
22049 (sd org-starting-day)
22050 (greg (calendar-gregorian-from-absolute sd))
22051 (cnt (get-text-property (point) 'org-day-cnt))
22052 greg2 nd)
22053 (cond
22054 ((eq span 'day)
22055 (setq sd (+ arg sd) nd 1))
22056 ((eq span 'week)
22057 (setq sd (+ (* 7 arg) sd) nd 7))
22058 ((eq span 'month)
22059 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22060 sd (calendar-absolute-from-gregorian greg2))
22061 (setcar greg2 (1+ (car greg2)))
22062 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22063 ((eq span 'year)
22064 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22065 sd (calendar-absolute-from-gregorian greg2))
22066 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22067 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22068 (let ((org-agenda-overriding-arguments
22069 (list (car org-agenda-last-arguments) sd nd t)))
22070 (org-agenda-redo)
22071 (org-agenda-find-same-or-today-or-agenda cnt))))
22073 (defun org-agenda-earlier (arg)
22074 "Go backward in time by the current span.
22075 With prefix ARG, go backward that many times the current span."
22076 (interactive "p")
22077 (org-agenda-later (- arg)))
22079 (defun org-agenda-day-view ()
22080 "Switch to daily view for agenda."
22081 (interactive)
22082 (setq org-agenda-ndays 1)
22083 (org-agenda-change-time-span 'day))
22084 (defun org-agenda-week-view ()
22085 "Switch to daily view for agenda."
22086 (interactive)
22087 (setq org-agenda-ndays 7)
22088 (org-agenda-change-time-span 'week))
22089 (defun org-agenda-month-view ()
22090 "Switch to daily view for agenda."
22091 (interactive)
22092 (org-agenda-change-time-span 'month))
22093 (defun org-agenda-year-view ()
22094 "Switch to daily view for agenda."
22095 (interactive)
22096 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22097 (org-agenda-change-time-span 'year)
22098 (error "Abort")))
22100 (defun org-agenda-change-time-span (span)
22101 "Change the agenda view to SPAN.
22102 SPAN may be `day', `week', `month', `year'."
22103 (org-agenda-check-type t 'agenda)
22104 (if (equal org-agenda-span span)
22105 (error "Viewing span is already \"%s\"" span))
22106 (let* ((sd (or (get-text-property (point) 'day)
22107 org-starting-day))
22108 (computed (org-agenda-compute-time-span sd span))
22109 (org-agenda-overriding-arguments
22110 (list (car org-agenda-last-arguments)
22111 (car computed) (cdr computed) t)))
22112 (org-agenda-redo)
22113 (org-agenda-find-same-or-today-or-agenda))
22114 (org-agenda-set-mode-name)
22115 (message "Switched to %s view" span))
22117 (defun org-agenda-compute-time-span (sd span)
22118 "Compute starting date and number of days for agenda.
22119 SPAN may be `day', `week', `month', `year'. The return value
22120 is a cons cell with the starting date and the number of days,
22121 so that the date SD will be in that range."
22122 (let* ((greg (calendar-gregorian-from-absolute sd))
22124 (cond
22125 ((eq span 'day)
22126 (setq nd 1))
22127 ((eq span 'week)
22128 (let* ((nt (calendar-day-of-week
22129 (calendar-gregorian-from-absolute sd)))
22130 (d (if org-agenda-start-on-weekday
22131 (- nt org-agenda-start-on-weekday)
22132 0)))
22133 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22134 (setq nd 7)))
22135 ((eq span 'month)
22136 (setq sd (calendar-absolute-from-gregorian
22137 (list (car greg) 1 (nth 2 greg)))
22138 nd (- (calendar-absolute-from-gregorian
22139 (list (1+ (car greg)) 1 (nth 2 greg)))
22140 sd)))
22141 ((eq span 'year)
22142 (setq sd (calendar-absolute-from-gregorian
22143 (list 1 1 (nth 2 greg)))
22144 nd (- (calendar-absolute-from-gregorian
22145 (list 1 1 (1+ (nth 2 greg))))
22146 sd))))
22147 (cons sd nd)))
22149 ;; FIXME: does not work if user makes date format that starts with a blank
22150 (defun org-agenda-next-date-line (&optional arg)
22151 "Jump to the next line indicating a date in agenda buffer."
22152 (interactive "p")
22153 (org-agenda-check-type t 'agenda 'timeline)
22154 (beginning-of-line 1)
22155 (if (looking-at "^\\S-") (forward-char 1))
22156 (if (not (re-search-forward "^\\S-" nil t arg))
22157 (progn
22158 (backward-char 1)
22159 (error "No next date after this line in this buffer")))
22160 (goto-char (match-beginning 0)))
22162 (defun org-agenda-previous-date-line (&optional arg)
22163 "Jump to the previous line indicating a date in agenda buffer."
22164 (interactive "p")
22165 (org-agenda-check-type t 'agenda 'timeline)
22166 (beginning-of-line 1)
22167 (if (not (re-search-backward "^\\S-" nil t arg))
22168 (error "No previous date before this line in this buffer")))
22170 ;; Initialize the highlight
22171 (defvar org-hl (org-make-overlay 1 1))
22172 (org-overlay-put org-hl 'face 'highlight)
22174 (defun org-highlight (begin end &optional buffer)
22175 "Highlight a region with overlay."
22176 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22177 org-hl begin end (or buffer (current-buffer))))
22179 (defun org-unhighlight ()
22180 "Detach overlay INDEX."
22181 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22183 ;; FIXME this is currently not used.
22184 (defun org-highlight-until-next-command (beg end &optional buffer)
22185 (org-highlight beg end buffer)
22186 (add-hook 'pre-command-hook 'org-unhighlight-once))
22187 (defun org-unhighlight-once ()
22188 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22189 (org-unhighlight))
22191 (defun org-agenda-follow-mode ()
22192 "Toggle follow mode in an agenda buffer."
22193 (interactive)
22194 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22195 (org-agenda-set-mode-name)
22196 (message "Follow mode is %s"
22197 (if org-agenda-follow-mode "on" "off")))
22199 (defun org-agenda-log-mode ()
22200 "Toggle log mode in an agenda buffer."
22201 (interactive)
22202 (org-agenda-check-type t 'agenda 'timeline)
22203 (setq org-agenda-show-log (not org-agenda-show-log))
22204 (org-agenda-set-mode-name)
22205 (org-agenda-redo)
22206 (message "Log mode is %s"
22207 (if org-agenda-show-log "on" "off")))
22209 (defun org-agenda-toggle-diary ()
22210 "Toggle diary inclusion in an agenda buffer."
22211 (interactive)
22212 (org-agenda-check-type t 'agenda)
22213 (setq org-agenda-include-diary (not org-agenda-include-diary))
22214 (org-agenda-redo)
22215 (org-agenda-set-mode-name)
22216 (message "Diary inclusion turned %s"
22217 (if org-agenda-include-diary "on" "off")))
22219 (defun org-agenda-toggle-time-grid ()
22220 "Toggle time grid in an agenda buffer."
22221 (interactive)
22222 (org-agenda-check-type t 'agenda)
22223 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22224 (org-agenda-redo)
22225 (org-agenda-set-mode-name)
22226 (message "Time-grid turned %s"
22227 (if org-agenda-use-time-grid "on" "off")))
22229 (defun org-agenda-set-mode-name ()
22230 "Set the mode name to indicate all the small mode settings."
22231 (setq mode-name
22232 (concat "Org-Agenda"
22233 (if (equal org-agenda-ndays 1) " Day" "")
22234 (if (equal org-agenda-ndays 7) " Week" "")
22235 (if org-agenda-follow-mode " Follow" "")
22236 (if org-agenda-include-diary " Diary" "")
22237 (if org-agenda-use-time-grid " Grid" "")
22238 (if org-agenda-show-log " Log" "")))
22239 (force-mode-line-update))
22241 (defun org-agenda-post-command-hook ()
22242 (and (eolp) (not (bolp)) (backward-char 1))
22243 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22244 (if (and org-agenda-follow-mode
22245 (get-text-property (point) 'org-marker))
22246 (org-agenda-show)))
22248 (defun org-agenda-show-priority ()
22249 "Show the priority of the current item.
22250 This priority is composed of the main priority given with the [#A] cookies,
22251 and by additional input from the age of a schedules or deadline entry."
22252 (interactive)
22253 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22254 (message "Priority is %d" (if pri pri -1000))))
22256 (defun org-agenda-show-tags ()
22257 "Show the tags applicable to the current item."
22258 (interactive)
22259 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22260 (if tags
22261 (message "Tags are :%s:"
22262 (org-no-properties (mapconcat 'identity tags ":")))
22263 (message "No tags associated with this line"))))
22265 (defun org-agenda-goto (&optional highlight)
22266 "Go to the Org-mode file which contains the item at point."
22267 (interactive)
22268 (let* ((marker (or (get-text-property (point) 'org-marker)
22269 (org-agenda-error)))
22270 (buffer (marker-buffer marker))
22271 (pos (marker-position marker)))
22272 (switch-to-buffer-other-window buffer)
22273 (widen)
22274 (goto-char pos)
22275 (when (org-mode-p)
22276 (org-show-context 'agenda)
22277 (save-excursion
22278 (and (outline-next-heading)
22279 (org-flag-heading nil)))) ; show the next heading
22280 (run-hooks 'org-agenda-after-show-hook)
22281 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22283 (defvar org-agenda-after-show-hook nil
22284 "Normal hook run after an item has been shown from the agenda.
22285 Point is in the buffer where the item originated.")
22287 (defun org-agenda-kill ()
22288 "Kill the entry or subtree belonging to the current agenda entry."
22289 (interactive)
22290 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22291 (let* ((marker (or (get-text-property (point) 'org-marker)
22292 (org-agenda-error)))
22293 (buffer (marker-buffer marker))
22294 (pos (marker-position marker))
22295 (type (get-text-property (point) 'type))
22296 dbeg dend (n 0) conf)
22297 (org-with-remote-undo buffer
22298 (with-current-buffer buffer
22299 (save-excursion
22300 (goto-char pos)
22301 (if (and (org-mode-p) (not (member type '("sexp"))))
22302 (setq dbeg (progn (org-back-to-heading t) (point))
22303 dend (org-end-of-subtree t t))
22304 (setq dbeg (point-at-bol)
22305 dend (min (point-max) (1+ (point-at-eol)))))
22306 (goto-char dbeg)
22307 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22308 (setq conf (or (eq t org-agenda-confirm-kill)
22309 (and (numberp org-agenda-confirm-kill)
22310 (> n org-agenda-confirm-kill))))
22311 (and conf
22312 (not (y-or-n-p
22313 (format "Delete entry with %d lines in buffer \"%s\"? "
22314 n (buffer-name buffer))))
22315 (error "Abort"))
22316 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22317 (with-current-buffer buffer (delete-region dbeg dend))
22318 (message "Agenda item and source killed"))))
22320 (defun org-agenda-archive ()
22321 "Kill the entry or subtree belonging to the current agenda entry."
22322 (interactive)
22323 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22324 (let* ((marker (or (get-text-property (point) 'org-marker)
22325 (org-agenda-error)))
22326 (buffer (marker-buffer marker))
22327 (pos (marker-position marker)))
22328 (org-with-remote-undo buffer
22329 (with-current-buffer buffer
22330 (if (org-mode-p)
22331 (save-excursion
22332 (goto-char pos)
22333 (org-remove-subtree-entries-from-agenda)
22334 (org-back-to-heading t)
22335 (org-archive-subtree))
22336 (error "Archiving works only in Org-mode files"))))))
22338 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22339 "Remove all lines in the agenda that correspond to a given subtree.
22340 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22341 If this information is not given, the function uses the tree at point."
22342 (let ((buf (or buf (current-buffer))) m p)
22343 (save-excursion
22344 (unless (and beg end)
22345 (org-back-to-heading t)
22346 (setq beg (point))
22347 (org-end-of-subtree t)
22348 (setq end (point)))
22349 (set-buffer (get-buffer org-agenda-buffer-name))
22350 (save-excursion
22351 (goto-char (point-max))
22352 (beginning-of-line 1)
22353 (while (not (bobp))
22354 (when (and (setq m (get-text-property (point) 'org-marker))
22355 (equal buf (marker-buffer m))
22356 (setq p (marker-position m))
22357 (>= p beg)
22358 (<= p end))
22359 (let ((inhibit-read-only t))
22360 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22361 (beginning-of-line 0))))))
22363 (defun org-agenda-open-link ()
22364 "Follow the link in the current line, if any."
22365 (interactive)
22366 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22367 (save-excursion
22368 (save-restriction
22369 (narrow-to-region (point-at-bol) (point-at-eol))
22370 (org-open-at-point))))
22372 (defun org-agenda-copy-local-variable (var)
22373 "Get a variable from a referenced buffer and install it here."
22374 (let ((m (get-text-property (point) 'org-marker)))
22375 (when (and m (buffer-live-p (marker-buffer m)))
22376 (org-set-local var (with-current-buffer (marker-buffer m)
22377 (symbol-value var))))))
22379 (defun org-agenda-switch-to (&optional delete-other-windows)
22380 "Go to the Org-mode file which contains the item at point."
22381 (interactive)
22382 (let* ((marker (or (get-text-property (point) 'org-marker)
22383 (org-agenda-error)))
22384 (buffer (marker-buffer marker))
22385 (pos (marker-position marker)))
22386 (switch-to-buffer buffer)
22387 (and delete-other-windows (delete-other-windows))
22388 (widen)
22389 (goto-char pos)
22390 (when (org-mode-p)
22391 (org-show-context 'agenda)
22392 (save-excursion
22393 (and (outline-next-heading)
22394 (org-flag-heading nil)))))) ; show the next heading
22396 (defun org-agenda-goto-mouse (ev)
22397 "Go to the Org-mode file which contains the item at the mouse click."
22398 (interactive "e")
22399 (mouse-set-point ev)
22400 (org-agenda-goto))
22402 (defun org-agenda-show ()
22403 "Display the Org-mode file which contains the item at point."
22404 (interactive)
22405 (let ((win (selected-window)))
22406 (org-agenda-goto t)
22407 (select-window win)))
22409 (defun org-agenda-recenter (arg)
22410 "Display the Org-mode file which contains the item at point and recenter."
22411 (interactive "P")
22412 (let ((win (selected-window)))
22413 (org-agenda-goto t)
22414 (recenter arg)
22415 (select-window win)))
22417 (defun org-agenda-show-mouse (ev)
22418 "Display the Org-mode file which contains the item at the mouse click."
22419 (interactive "e")
22420 (mouse-set-point ev)
22421 (org-agenda-show))
22423 (defun org-agenda-check-no-diary ()
22424 "Check if the entry is a diary link and abort if yes."
22425 (if (get-text-property (point) 'org-agenda-diary-link)
22426 (org-agenda-error)))
22428 (defun org-agenda-error ()
22429 (error "Command not allowed in this line"))
22431 (defun org-agenda-tree-to-indirect-buffer ()
22432 "Show the subtree corresponding to the current entry in an indirect buffer.
22433 This calls the command `org-tree-to-indirect-buffer' from the original
22434 Org-mode buffer.
22435 With numerical prefix arg ARG, go up to this level and then take that tree.
22436 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22437 dedicated frame)."
22438 (interactive)
22439 (org-agenda-check-no-diary)
22440 (let* ((marker (or (get-text-property (point) 'org-marker)
22441 (org-agenda-error)))
22442 (buffer (marker-buffer marker))
22443 (pos (marker-position marker)))
22444 (with-current-buffer buffer
22445 (save-excursion
22446 (goto-char pos)
22447 (call-interactively 'org-tree-to-indirect-buffer)))))
22449 (defvar org-last-heading-marker (make-marker)
22450 "Marker pointing to the headline that last changed its TODO state
22451 by a remote command from the agenda.")
22453 (defun org-agenda-todo-nextset ()
22454 "Switch TODO entry to next sequence."
22455 (interactive)
22456 (org-agenda-todo 'nextset))
22458 (defun org-agenda-todo-previousset ()
22459 "Switch TODO entry to previous sequence."
22460 (interactive)
22461 (org-agenda-todo 'previousset))
22463 (defun org-agenda-todo (&optional arg)
22464 "Cycle TODO state of line at point, also in Org-mode file.
22465 This changes the line at point, all other lines in the agenda referring to
22466 the same tree node, and the headline of the tree node in the Org-mode file."
22467 (interactive "P")
22468 (org-agenda-check-no-diary)
22469 (let* ((col (current-column))
22470 (marker (or (get-text-property (point) 'org-marker)
22471 (org-agenda-error)))
22472 (buffer (marker-buffer marker))
22473 (pos (marker-position marker))
22474 (hdmarker (get-text-property (point) 'org-hd-marker))
22475 (inhibit-read-only t)
22476 newhead)
22477 (org-with-remote-undo buffer
22478 (with-current-buffer buffer
22479 (widen)
22480 (goto-char pos)
22481 (org-show-context 'agenda)
22482 (save-excursion
22483 (and (outline-next-heading)
22484 (org-flag-heading nil))) ; show the next heading
22485 (org-todo arg)
22486 (and (bolp) (forward-char 1))
22487 (setq newhead (org-get-heading))
22488 (save-excursion
22489 (org-back-to-heading)
22490 (move-marker org-last-heading-marker (point))))
22491 (beginning-of-line 1)
22492 (save-excursion
22493 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22494 (move-to-column col))))
22496 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22497 "Change all lines in the agenda buffer which match HDMARKER.
22498 The new content of the line will be NEWHEAD (as modified by
22499 `org-format-agenda-item'). HDMARKER is checked with
22500 `equal' against all `org-hd-marker' text properties in the file.
22501 If FIXFACE is non-nil, the face of each item is modified acording to
22502 the new TODO state."
22503 (let* ((inhibit-read-only t)
22504 props m pl undone-face done-face finish new dotime cat tags)
22505 (save-excursion
22506 (goto-char (point-max))
22507 (beginning-of-line 1)
22508 (while (not finish)
22509 (setq finish (bobp))
22510 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22511 (equal m hdmarker))
22512 (setq props (text-properties-at (point))
22513 dotime (get-text-property (point) 'dotime)
22514 cat (get-text-property (point) 'org-category)
22515 tags (get-text-property (point) 'tags)
22516 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22517 pl (get-text-property (point) 'prefix-length)
22518 undone-face (get-text-property (point) 'undone-face)
22519 done-face (get-text-property (point) 'done-face))
22520 (move-to-column pl)
22521 (cond
22522 ((equal new "")
22523 (beginning-of-line 1)
22524 (and (looking-at ".*\n?") (replace-match "")))
22525 ((looking-at ".*")
22526 (replace-match new t t)
22527 (beginning-of-line 1)
22528 (add-text-properties (point-at-bol) (point-at-eol) props)
22529 (when fixface
22530 (add-text-properties
22531 (point-at-bol) (point-at-eol)
22532 (list 'face
22533 (if org-last-todo-state-is-todo
22534 undone-face done-face))))
22535 (org-agenda-highlight-todo 'line)
22536 (beginning-of-line 1))
22537 (t (error "Line update did not work"))))
22538 (beginning-of-line 0)))
22539 (org-finalize-agenda)))
22541 (defun org-agenda-align-tags (&optional line)
22542 "Align all tags in agenda items to `org-agenda-tags-column'."
22543 (let ((inhibit-read-only t) l c)
22544 (save-excursion
22545 (goto-char (if line (point-at-bol) (point-min)))
22546 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22547 (if line (point-at-eol) nil) t)
22548 (add-text-properties
22549 (match-beginning 2) (match-end 2)
22550 (list 'face (list 'org-tag (get-text-property
22551 (match-beginning 2) 'face))))
22552 (setq l (- (match-end 2) (match-beginning 2))
22553 c (if (< org-agenda-tags-column 0)
22554 (- (abs org-agenda-tags-column) l)
22555 org-agenda-tags-column))
22556 (delete-region (match-beginning 1) (match-end 1))
22557 (goto-char (match-beginning 1))
22558 (insert (org-add-props
22559 (make-string (max 1 (- c (current-column))) ?\ )
22560 (text-properties-at (point))))))))
22562 (defun org-agenda-priority-up ()
22563 "Increase the priority of line at point, also in Org-mode file."
22564 (interactive)
22565 (org-agenda-priority 'up))
22567 (defun org-agenda-priority-down ()
22568 "Decrease the priority of line at point, also in Org-mode file."
22569 (interactive)
22570 (org-agenda-priority 'down))
22572 (defun org-agenda-priority (&optional force-direction)
22573 "Set the priority of line at point, also in Org-mode file.
22574 This changes the line at point, all other lines in the agenda referring to
22575 the same tree node, and the headline of the tree node in the Org-mode file."
22576 (interactive)
22577 (org-agenda-check-no-diary)
22578 (let* ((marker (or (get-text-property (point) 'org-marker)
22579 (org-agenda-error)))
22580 (hdmarker (get-text-property (point) 'org-hd-marker))
22581 (buffer (marker-buffer hdmarker))
22582 (pos (marker-position hdmarker))
22583 (inhibit-read-only t)
22584 newhead)
22585 (org-with-remote-undo buffer
22586 (with-current-buffer buffer
22587 (widen)
22588 (goto-char pos)
22589 (org-show-context 'agenda)
22590 (save-excursion
22591 (and (outline-next-heading)
22592 (org-flag-heading nil))) ; show the next heading
22593 (funcall 'org-priority force-direction)
22594 (end-of-line 1)
22595 (setq newhead (org-get-heading)))
22596 (org-agenda-change-all-lines newhead hdmarker)
22597 (beginning-of-line 1))))
22599 (defun org-get-tags-at (&optional pos)
22600 "Get a list of all headline tags applicable at POS.
22601 POS defaults to point. If tags are inherited, the list contains
22602 the targets in the same sequence as the headlines appear, i.e.
22603 the tags of the current headline come last."
22604 (interactive)
22605 (let (tags lastpos)
22606 (save-excursion
22607 (save-restriction
22608 (widen)
22609 (goto-char (or pos (point)))
22610 (save-match-data
22611 (org-back-to-heading t)
22612 (condition-case nil
22613 (while (not (equal lastpos (point)))
22614 (setq lastpos (point))
22615 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22616 (setq tags (append (org-split-string
22617 (org-match-string-no-properties 1) ":")
22618 tags)))
22619 (or org-use-tag-inheritance (error ""))
22620 (org-up-heading-all 1))
22621 (error nil))))
22622 tags)))
22624 ;; FIXME: should fix the tags property of the agenda line.
22625 (defun org-agenda-set-tags ()
22626 "Set tags for the current headline."
22627 (interactive)
22628 (org-agenda-check-no-diary)
22629 (if (and (org-region-active-p) (interactive-p))
22630 (call-interactively 'org-change-tag-in-region)
22631 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22632 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22633 (org-agenda-error)))
22634 (buffer (marker-buffer hdmarker))
22635 (pos (marker-position hdmarker))
22636 (inhibit-read-only t)
22637 newhead)
22638 (org-with-remote-undo buffer
22639 (with-current-buffer buffer
22640 (widen)
22641 (goto-char pos)
22642 (save-excursion
22643 (org-show-context 'agenda))
22644 (save-excursion
22645 (and (outline-next-heading)
22646 (org-flag-heading nil))) ; show the next heading
22647 (goto-char pos)
22648 (call-interactively 'org-set-tags)
22649 (end-of-line 1)
22650 (setq newhead (org-get-heading)))
22651 (org-agenda-change-all-lines newhead hdmarker)
22652 (beginning-of-line 1)))))
22654 (defun org-agenda-toggle-archive-tag ()
22655 "Toggle the archive tag for the current entry."
22656 (interactive)
22657 (org-agenda-check-no-diary)
22658 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22659 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22660 (org-agenda-error)))
22661 (buffer (marker-buffer hdmarker))
22662 (pos (marker-position hdmarker))
22663 (inhibit-read-only t)
22664 newhead)
22665 (org-with-remote-undo buffer
22666 (with-current-buffer buffer
22667 (widen)
22668 (goto-char pos)
22669 (org-show-context 'agenda)
22670 (save-excursion
22671 (and (outline-next-heading)
22672 (org-flag-heading nil))) ; show the next heading
22673 (call-interactively 'org-toggle-archive-tag)
22674 (end-of-line 1)
22675 (setq newhead (org-get-heading)))
22676 (org-agenda-change-all-lines newhead hdmarker)
22677 (beginning-of-line 1))))
22679 (defun org-agenda-date-later (arg &optional what)
22680 "Change the date of this item to one day later."
22681 (interactive "p")
22682 (org-agenda-check-type t 'agenda 'timeline)
22683 (org-agenda-check-no-diary)
22684 (let* ((marker (or (get-text-property (point) 'org-marker)
22685 (org-agenda-error)))
22686 (buffer (marker-buffer marker))
22687 (pos (marker-position marker)))
22688 (org-with-remote-undo buffer
22689 (with-current-buffer buffer
22690 (widen)
22691 (goto-char pos)
22692 (if (not (org-at-timestamp-p))
22693 (error "Cannot find time stamp"))
22694 (org-timestamp-change arg (or what 'day)))
22695 (org-agenda-show-new-time marker org-last-changed-timestamp))
22696 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22698 (defun org-agenda-date-earlier (arg &optional what)
22699 "Change the date of this item to one day earlier."
22700 (interactive "p")
22701 (org-agenda-date-later (- arg) what))
22703 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22704 "Show new date stamp via text properties."
22705 ;; We use text properties to make this undoable
22706 (let ((inhibit-read-only t))
22707 (setq stamp (concat " " prefix " => " stamp))
22708 (save-excursion
22709 (goto-char (point-max))
22710 (while (not (bobp))
22711 (when (equal marker (get-text-property (point) 'org-marker))
22712 (move-to-column (- (window-width) (length stamp)) t)
22713 (if (featurep 'xemacs)
22714 ;; Use `duplicable' property to trigger undo recording
22715 (let ((ex (make-extent nil nil))
22716 (gl (make-glyph stamp)))
22717 (set-glyph-face gl 'secondary-selection)
22718 (set-extent-properties
22719 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22720 (insert-extent ex (1- (point)) (point-at-eol)))
22721 (add-text-properties
22722 (1- (point)) (point-at-eol)
22723 (list 'display (org-add-props stamp nil
22724 'face 'secondary-selection))))
22725 (beginning-of-line 1))
22726 (beginning-of-line 0)))))
22728 (defun org-agenda-date-prompt (arg)
22729 "Change the date of this item. Date is prompted for, with default today.
22730 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22731 be used to request time specification in the time stamp."
22732 (interactive "P")
22733 (org-agenda-check-type t 'agenda 'timeline)
22734 (org-agenda-check-no-diary)
22735 (let* ((marker (or (get-text-property (point) 'org-marker)
22736 (org-agenda-error)))
22737 (buffer (marker-buffer marker))
22738 (pos (marker-position marker)))
22739 (org-with-remote-undo buffer
22740 (with-current-buffer buffer
22741 (widen)
22742 (goto-char pos)
22743 (if (not (org-at-timestamp-p))
22744 (error "Cannot find time stamp"))
22745 (org-time-stamp arg)
22746 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22748 (defun org-agenda-schedule (arg)
22749 "Schedule the item at point."
22750 (interactive "P")
22751 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22752 (org-agenda-check-no-diary)
22753 (let* ((marker (or (get-text-property (point) 'org-marker)
22754 (org-agenda-error)))
22755 (buffer (marker-buffer marker))
22756 (pos (marker-position marker))
22757 (org-insert-labeled-timestamps-at-point nil)
22759 (org-with-remote-undo buffer
22760 (with-current-buffer buffer
22761 (widen)
22762 (goto-char pos)
22763 (setq ts (org-schedule arg)))
22764 (org-agenda-show-new-time marker ts "S"))
22765 (message "Item scheduled for %s" ts)))
22767 (defun org-agenda-deadline (arg)
22768 "Schedule the item at point."
22769 (interactive "P")
22770 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22771 (org-agenda-check-no-diary)
22772 (let* ((marker (or (get-text-property (point) 'org-marker)
22773 (org-agenda-error)))
22774 (buffer (marker-buffer marker))
22775 (pos (marker-position marker))
22776 (org-insert-labeled-timestamps-at-point nil)
22778 (org-with-remote-undo buffer
22779 (with-current-buffer buffer
22780 (widen)
22781 (goto-char pos)
22782 (setq ts (org-deadline arg)))
22783 (org-agenda-show-new-time marker ts "S"))
22784 (message "Deadline for this item set to %s" ts)))
22786 (defun org-get-heading (&optional no-tags)
22787 "Return the heading of the current entry, without the stars."
22788 (save-excursion
22789 (org-back-to-heading t)
22790 (if (looking-at
22791 (if no-tags
22792 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22793 "\\*+[ \t]+\\([^\r\n]*\\)"))
22794 (match-string 1) "")))
22796 (defun org-agenda-clock-in (&optional arg)
22797 "Start the clock on the currently selected item."
22798 (interactive "P")
22799 (org-agenda-check-no-diary)
22800 (let* ((marker (or (get-text-property (point) 'org-marker)
22801 (org-agenda-error)))
22802 (pos (marker-position marker)))
22803 (org-with-remote-undo (marker-buffer marker)
22804 (with-current-buffer (marker-buffer marker)
22805 (widen)
22806 (goto-char pos)
22807 (org-clock-in)))))
22809 (defun org-agenda-clock-out (&optional arg)
22810 "Stop the currently running clock."
22811 (interactive "P")
22812 (unless (marker-buffer org-clock-marker)
22813 (error "No running clock"))
22814 (org-with-remote-undo (marker-buffer org-clock-marker)
22815 (org-clock-out)))
22817 (defun org-agenda-clock-cancel (&optional arg)
22818 "Cancel the currently running clock."
22819 (interactive "P")
22820 (unless (marker-buffer org-clock-marker)
22821 (error "No running clock"))
22822 (org-with-remote-undo (marker-buffer org-clock-marker)
22823 (org-clock-cancel)))
22825 (defun org-agenda-diary-entry ()
22826 "Make a diary entry, like the `i' command from the calendar.
22827 All the standard commands work: block, weekly etc."
22828 (interactive)
22829 (org-agenda-check-type t 'agenda 'timeline)
22830 (require 'diary-lib)
22831 (let* ((char (progn
22832 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22833 (read-char-exclusive)))
22834 (cmd (cdr (assoc char
22835 '((?d . insert-diary-entry)
22836 (?w . insert-weekly-diary-entry)
22837 (?m . insert-monthly-diary-entry)
22838 (?y . insert-yearly-diary-entry)
22839 (?a . insert-anniversary-diary-entry)
22840 (?b . insert-block-diary-entry)
22841 (?c . insert-cyclic-diary-entry)))))
22842 (oldf (symbol-function 'calendar-cursor-to-date))
22843 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22844 (point (point))
22845 (mark (or (mark t) (point))))
22846 (unless cmd
22847 (error "No command associated with <%c>" char))
22848 (unless (and (get-text-property point 'day)
22849 (or (not (equal ?b char))
22850 (get-text-property mark 'day)))
22851 (error "Don't know which date to use for diary entry"))
22852 ;; We implement this by hacking the `calendar-cursor-to-date' function
22853 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22854 (let ((calendar-mark-ring
22855 (list (calendar-gregorian-from-absolute
22856 (or (get-text-property mark 'day)
22857 (get-text-property point 'day))))))
22858 (unwind-protect
22859 (progn
22860 (fset 'calendar-cursor-to-date
22861 (lambda (&optional error)
22862 (calendar-gregorian-from-absolute
22863 (get-text-property point 'day))))
22864 (call-interactively cmd))
22865 (fset 'calendar-cursor-to-date oldf)))))
22868 (defun org-agenda-execute-calendar-command (cmd)
22869 "Execute a calendar command from the agenda, with the date associated to
22870 the cursor position."
22871 (org-agenda-check-type t 'agenda 'timeline)
22872 (require 'diary-lib)
22873 (unless (get-text-property (point) 'day)
22874 (error "Don't know which date to use for calendar command"))
22875 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22876 (point (point))
22877 (date (calendar-gregorian-from-absolute
22878 (get-text-property point 'day)))
22879 ;; the following 3 vars are needed in the calendar
22880 (displayed-day (extract-calendar-day date))
22881 (displayed-month (extract-calendar-month date))
22882 (displayed-year (extract-calendar-year date)))
22883 (unwind-protect
22884 (progn
22885 (fset 'calendar-cursor-to-date
22886 (lambda (&optional error)
22887 (calendar-gregorian-from-absolute
22888 (get-text-property point 'day))))
22889 (call-interactively cmd))
22890 (fset 'calendar-cursor-to-date oldf))))
22892 (defun org-agenda-phases-of-moon ()
22893 "Display the phases of the moon for the 3 months around the cursor date."
22894 (interactive)
22895 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22897 (defun org-agenda-holidays ()
22898 "Display the holidays for the 3 months around the cursor date."
22899 (interactive)
22900 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22902 (defun org-agenda-sunrise-sunset (arg)
22903 "Display sunrise and sunset for the cursor date.
22904 Latitude and longitude can be specified with the variables
22905 `calendar-latitude' and `calendar-longitude'. When called with prefix
22906 argument, latitude and longitude will be prompted for."
22907 (interactive "P")
22908 (let ((calendar-longitude (if arg nil calendar-longitude))
22909 (calendar-latitude (if arg nil calendar-latitude))
22910 (calendar-location-name
22911 (if arg "the given coordinates" calendar-location-name)))
22912 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22914 (defun org-agenda-goto-calendar ()
22915 "Open the Emacs calendar with the date at the cursor."
22916 (interactive)
22917 (org-agenda-check-type t 'agenda 'timeline)
22918 (let* ((day (or (get-text-property (point) 'day)
22919 (error "Don't know which date to open in calendar")))
22920 (date (calendar-gregorian-from-absolute day))
22921 (calendar-move-hook nil)
22922 (view-calendar-holidays-initially nil)
22923 (view-diary-entries-initially nil))
22924 (calendar)
22925 (calendar-goto-date date)))
22927 (defun org-calendar-goto-agenda ()
22928 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
22929 This is a command that has to be installed in `calendar-mode-map'."
22930 (interactive)
22931 (org-agenda-list nil (calendar-absolute-from-gregorian
22932 (calendar-cursor-to-date))
22933 nil))
22935 (defun org-agenda-convert-date ()
22936 (interactive)
22937 (org-agenda-check-type t 'agenda 'timeline)
22938 (let ((day (get-text-property (point) 'day))
22939 date s)
22940 (unless day
22941 (error "Don't know which date to convert"))
22942 (setq date (calendar-gregorian-from-absolute day))
22943 (setq s (concat
22944 "Gregorian: " (calendar-date-string date) "\n"
22945 "ISO: " (calendar-iso-date-string date) "\n"
22946 "Day of Yr: " (calendar-day-of-year-string date) "\n"
22947 "Julian: " (calendar-julian-date-string date) "\n"
22948 "Astron. JD: " (calendar-astro-date-string date)
22949 " (Julian date number at noon UTC)\n"
22950 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
22951 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
22952 "French: " (calendar-french-date-string date) "\n"
22953 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
22954 "Mayan: " (calendar-mayan-date-string date) "\n"
22955 "Coptic: " (calendar-coptic-date-string date) "\n"
22956 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
22957 "Persian: " (calendar-persian-date-string date) "\n"
22958 "Chinese: " (calendar-chinese-date-string date) "\n"))
22959 (with-output-to-temp-buffer "*Dates*"
22960 (princ s))
22961 (if (fboundp 'fit-window-to-buffer)
22962 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
22965 ;;;; Embedded LaTeX
22967 (defvar org-cdlatex-mode-map (make-sparse-keymap)
22968 "Keymap for the minor `org-cdlatex-mode'.")
22970 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
22971 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
22972 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
22973 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
22974 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
22976 (defvar org-cdlatex-texmathp-advice-is-done nil
22977 "Flag remembering if we have applied the advice to texmathp already.")
22979 (define-minor-mode org-cdlatex-mode
22980 "Toggle the minor `org-cdlatex-mode'.
22981 This mode supports entering LaTeX environment and math in LaTeX fragments
22982 in Org-mode.
22983 \\{org-cdlatex-mode-map}"
22984 nil " OCDL" nil
22985 (when org-cdlatex-mode (require 'cdlatex))
22986 (unless org-cdlatex-texmathp-advice-is-done
22987 (setq org-cdlatex-texmathp-advice-is-done t)
22988 (defadvice texmathp (around org-math-always-on activate)
22989 "Always return t in org-mode buffers.
22990 This is because we want to insert math symbols without dollars even outside
22991 the LaTeX math segments. If Orgmode thinks that point is actually inside
22992 en embedded LaTeX fragement, let texmathp do its job.
22993 \\[org-cdlatex-mode-map]"
22994 (interactive)
22995 (let (p)
22996 (cond
22997 ((not (org-mode-p)) ad-do-it)
22998 ((eq this-command 'cdlatex-math-symbol)
22999 (setq ad-return-value t
23000 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23002 (let ((p (org-inside-LaTeX-fragment-p)))
23003 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23004 (setq ad-return-value t
23005 texmathp-why '("Org-mode embedded math" . 0))
23006 (if p ad-do-it)))))))))
23008 (defun turn-on-org-cdlatex ()
23009 "Unconditionally turn on `org-cdlatex-mode'."
23010 (org-cdlatex-mode 1))
23012 (defun org-inside-LaTeX-fragment-p ()
23013 "Test if point is inside a LaTeX fragment.
23014 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23015 sequence appearing also before point.
23016 Even though the matchers for math are configurable, this function assumes
23017 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23018 delimiters are skipped when they have been removed by customization.
23019 The return value is nil, or a cons cell with the delimiter and
23020 and the position of this delimiter.
23022 This function does a reasonably good job, but can locally be fooled by
23023 for example currency specifications. For example it will assume being in
23024 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23025 fragments that are properly closed, but during editing, we have to live
23026 with the uncertainty caused by missing closing delimiters. This function
23027 looks only before point, not after."
23028 (catch 'exit
23029 (let ((pos (point))
23030 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23031 (lim (progn
23032 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23033 (point)))
23034 dd-on str (start 0) m re)
23035 (goto-char pos)
23036 (when dodollar
23037 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23038 re (nth 1 (assoc "$" org-latex-regexps)))
23039 (while (string-match re str start)
23040 (cond
23041 ((= (match-end 0) (length str))
23042 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23043 ((= (match-end 0) (- (length str) 5))
23044 (throw 'exit nil))
23045 (t (setq start (match-end 0))))))
23046 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23047 (goto-char pos)
23048 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23049 (and (match-beginning 2) (throw 'exit nil))
23050 ;; count $$
23051 (while (re-search-backward "\\$\\$" lim t)
23052 (setq dd-on (not dd-on)))
23053 (goto-char pos)
23054 (if dd-on (cons "$$" m))))))
23057 (defun org-try-cdlatex-tab ()
23058 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23059 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23060 - inside a LaTeX fragment, or
23061 - after the first word in a line, where an abbreviation expansion could
23062 insert a LaTeX environment."
23063 (when org-cdlatex-mode
23064 (cond
23065 ((save-excursion
23066 (skip-chars-backward "a-zA-Z0-9*")
23067 (skip-chars-backward " \t")
23068 (bolp))
23069 (cdlatex-tab) t)
23070 ((org-inside-LaTeX-fragment-p)
23071 (cdlatex-tab) t)
23072 (t nil))))
23074 (defun org-cdlatex-underscore-caret (&optional arg)
23075 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23076 Revert to the normal definition outside of these fragments."
23077 (interactive "P")
23078 (if (org-inside-LaTeX-fragment-p)
23079 (call-interactively 'cdlatex-sub-superscript)
23080 (let (org-cdlatex-mode)
23081 (call-interactively (key-binding (vector last-input-event))))))
23083 (defun org-cdlatex-math-modify (&optional arg)
23084 "Execute `cdlatex-math-modify' in LaTeX fragments.
23085 Revert to the normal definition outside of these fragments."
23086 (interactive "P")
23087 (if (org-inside-LaTeX-fragment-p)
23088 (call-interactively 'cdlatex-math-modify)
23089 (let (org-cdlatex-mode)
23090 (call-interactively (key-binding (vector last-input-event))))))
23092 (defvar org-latex-fragment-image-overlays nil
23093 "List of overlays carrying the images of latex fragments.")
23094 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23096 (defun org-remove-latex-fragment-image-overlays ()
23097 "Remove all overlays with LaTeX fragment images in current buffer."
23098 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23099 (setq org-latex-fragment-image-overlays nil))
23101 (defun org-preview-latex-fragment (&optional subtree)
23102 "Preview the LaTeX fragment at point, or all locally or globally.
23103 If the cursor is in a LaTeX fragment, create the image and overlay
23104 it over the source code. If there is no fragment at point, display
23105 all fragments in the current text, from one headline to the next. With
23106 prefix SUBTREE, display all fragments in the current subtree. With a
23107 double prefix `C-u C-u', or when the cursor is before the first headline,
23108 display all fragments in the buffer.
23109 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23110 (interactive "P")
23111 (org-remove-latex-fragment-image-overlays)
23112 (save-excursion
23113 (save-restriction
23114 (let (beg end at msg)
23115 (cond
23116 ((or (equal subtree '(16))
23117 (not (save-excursion
23118 (re-search-backward (concat "^" outline-regexp) nil t))))
23119 (setq beg (point-min) end (point-max)
23120 msg "Creating images for buffer...%s"))
23121 ((equal subtree '(4))
23122 (org-back-to-heading)
23123 (setq beg (point) end (org-end-of-subtree t)
23124 msg "Creating images for subtree...%s"))
23126 (if (setq at (org-inside-LaTeX-fragment-p))
23127 (goto-char (max (point-min) (- (cdr at) 2)))
23128 (org-back-to-heading))
23129 (setq beg (point) end (progn (outline-next-heading) (point))
23130 msg (if at "Creating image...%s"
23131 "Creating images for entry...%s"))))
23132 (message msg "")
23133 (narrow-to-region beg end)
23134 (goto-char beg)
23135 (org-format-latex
23136 (concat "ltxpng/" (file-name-sans-extension
23137 (file-name-nondirectory
23138 buffer-file-name)))
23139 default-directory 'overlays msg at 'forbuffer)
23140 (message msg "done. Use `C-c C-c' to remove images.")))))
23142 (defvar org-latex-regexps
23143 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23144 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23145 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23146 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23147 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23148 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23149 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23150 "Regular expressions for matching embedded LaTeX.")
23152 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23153 "Replace LaTeX fragments with links to an image, and produce images."
23154 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23155 (let* ((prefixnodir (file-name-nondirectory prefix))
23156 (absprefix (expand-file-name prefix dir))
23157 (todir (file-name-directory absprefix))
23158 (opt org-format-latex-options)
23159 (matchers (plist-get opt :matchers))
23160 (re-list org-latex-regexps)
23161 (cnt 0) txt link beg end re e checkdir
23162 m n block linkfile movefile ov)
23163 ;; Check if there are old images files with this prefix, and remove them
23164 (when (file-directory-p todir)
23165 (mapc 'delete-file
23166 (directory-files
23167 todir 'full
23168 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23169 ;; Check the different regular expressions
23170 (while (setq e (pop re-list))
23171 (setq m (car e) re (nth 1 e) n (nth 2 e)
23172 block (if (nth 3 e) "\n\n" ""))
23173 (when (member m matchers)
23174 (goto-char (point-min))
23175 (while (re-search-forward re nil t)
23176 (when (or (not at) (equal (cdr at) (match-beginning n)))
23177 (setq txt (match-string n)
23178 beg (match-beginning n) end (match-end n)
23179 cnt (1+ cnt)
23180 linkfile (format "%s_%04d.png" prefix cnt)
23181 movefile (format "%s_%04d.png" absprefix cnt)
23182 link (concat block "[[file:" linkfile "]]" block))
23183 (if msg (message msg cnt))
23184 (goto-char beg)
23185 (unless checkdir ; make sure the directory exists
23186 (setq checkdir t)
23187 (or (file-directory-p todir) (make-directory todir)))
23188 (org-create-formula-image
23189 txt movefile opt forbuffer)
23190 (if overlays
23191 (progn
23192 (setq ov (org-make-overlay beg end))
23193 (if (featurep 'xemacs)
23194 (progn
23195 (org-overlay-put ov 'invisible t)
23196 (org-overlay-put
23197 ov 'end-glyph
23198 (make-glyph (vector 'png :file movefile))))
23199 (org-overlay-put
23200 ov 'display
23201 (list 'image :type 'png :file movefile :ascent 'center)))
23202 (push ov org-latex-fragment-image-overlays)
23203 (goto-char end))
23204 (delete-region beg end)
23205 (insert link))))))))
23207 ;; This function borrows from Ganesh Swami's latex2png.el
23208 (defun org-create-formula-image (string tofile options buffer)
23209 (let* ((tmpdir (if (featurep 'xemacs)
23210 (temp-directory)
23211 temporary-file-directory))
23212 (texfilebase (make-temp-name
23213 (expand-file-name "orgtex" tmpdir)))
23214 (texfile (concat texfilebase ".tex"))
23215 (dvifile (concat texfilebase ".dvi"))
23216 (pngfile (concat texfilebase ".png"))
23217 (fnh (face-attribute 'default :height nil))
23218 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23219 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23220 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23221 "Black"))
23222 (bg (or (plist-get options (if buffer :background :html-background))
23223 "Transparent")))
23224 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23225 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23226 (with-temp-file texfile
23227 (insert org-format-latex-header
23228 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23229 (let ((dir default-directory))
23230 (condition-case nil
23231 (progn
23232 (cd tmpdir)
23233 (call-process "latex" nil nil nil texfile))
23234 (error nil))
23235 (cd dir))
23236 (if (not (file-exists-p dvifile))
23237 (progn (message "Failed to create dvi file from %s" texfile) nil)
23238 (call-process "dvipng" nil nil nil
23239 "-E" "-fg" fg "-bg" bg
23240 "-D" dpi
23241 ;;"-x" scale "-y" scale
23242 "-T" "tight"
23243 "-o" pngfile
23244 dvifile)
23245 (if (not (file-exists-p pngfile))
23246 (progn (message "Failed to create png file from %s" texfile) nil)
23247 ;; Use the requested file name and clean up
23248 (copy-file pngfile tofile 'replace)
23249 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23250 (delete-file (concat texfilebase e)))
23251 pngfile))))
23253 (defun org-dvipng-color (attr)
23254 "Return an rgb color specification for dvipng."
23255 (apply 'format "rgb %s %s %s"
23256 (mapcar 'org-normalize-color
23257 (color-values (face-attribute 'default attr nil)))))
23259 (defun org-normalize-color (value)
23260 "Return string to be used as color value for an RGB component."
23261 (format "%g" (/ value 65535.0)))
23263 ;;;; Exporting
23265 ;;; Variables, constants, and parameter plists
23267 (defconst org-level-max 20)
23269 (defvar org-export-html-preamble nil
23270 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23271 (defvar org-export-html-postamble nil
23272 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23273 (defvar org-export-html-auto-preamble t
23274 "Should default preamble be inserted? Set by publishing functions.")
23275 (defvar org-export-html-auto-postamble t
23276 "Should default postamble be inserted? Set by publishing functions.")
23277 (defvar org-current-export-file nil) ; dynamically scoped parameter
23278 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23281 (defconst org-export-plist-vars
23282 '((:language . org-export-default-language)
23283 (:customtime . org-display-custom-times)
23284 (:headline-levels . org-export-headline-levels)
23285 (:section-numbers . org-export-with-section-numbers)
23286 (:table-of-contents . org-export-with-toc)
23287 (:preserve-breaks . org-export-preserve-breaks)
23288 (:archived-trees . org-export-with-archived-trees)
23289 (:emphasize . org-export-with-emphasize)
23290 (:sub-superscript . org-export-with-sub-superscripts)
23291 (:special-strings . org-export-with-special-strings)
23292 (:footnotes . org-export-with-footnotes)
23293 (:drawers . org-export-with-drawers)
23294 (:tags . org-export-with-tags)
23295 (:TeX-macros . org-export-with-TeX-macros)
23296 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23297 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23298 (:fixed-width . org-export-with-fixed-width)
23299 (:timestamps . org-export-with-timestamps)
23300 (:author-info . org-export-author-info)
23301 (:time-stamp-file . org-export-time-stamp-file)
23302 (:tables . org-export-with-tables)
23303 (:table-auto-headline . org-export-highlight-first-table-line)
23304 (:style . org-export-html-style)
23305 (:agenda-style . org-agenda-export-html-style)
23306 (:convert-org-links . org-export-html-link-org-files-as-html)
23307 (:inline-images . org-export-html-inline-images)
23308 (:html-extension . org-export-html-extension)
23309 (:html-table-tag . org-export-html-table-tag)
23310 (:expand-quoted-html . org-export-html-expand)
23311 (:timestamp . org-export-html-with-timestamp)
23312 (:publishing-directory . org-export-publishing-directory)
23313 (:preamble . org-export-html-preamble)
23314 (:postamble . org-export-html-postamble)
23315 (:auto-preamble . org-export-html-auto-preamble)
23316 (:auto-postamble . org-export-html-auto-postamble)
23317 (:author . user-full-name)
23318 (:email . user-mail-address)))
23320 (defun org-default-export-plist ()
23321 "Return the property list with default settings for the export variables."
23322 (let ((l org-export-plist-vars) rtn e)
23323 (while (setq e (pop l))
23324 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23325 rtn))
23327 (defun org-infile-export-plist ()
23328 "Return the property list with file-local settings for export."
23329 (save-excursion
23330 (save-restriction
23331 (widen)
23332 (goto-char 0)
23333 (let ((re (org-make-options-regexp
23334 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23335 p key val text options)
23336 (while (re-search-forward re nil t)
23337 (setq key (org-match-string-no-properties 1)
23338 val (org-match-string-no-properties 2))
23339 (cond
23340 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23341 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23342 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23343 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23344 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23345 ((string-equal key "TEXT")
23346 (setq text (if text (concat text "\n" val) val)))
23347 ((string-equal key "OPTIONS") (setq options val))))
23348 (setq p (plist-put p :text text))
23349 (when options
23350 (let ((op '(("H" . :headline-levels)
23351 ("num" . :section-numbers)
23352 ("toc" . :table-of-contents)
23353 ("\\n" . :preserve-breaks)
23354 ("@" . :expand-quoted-html)
23355 (":" . :fixed-width)
23356 ("|" . :tables)
23357 ("^" . :sub-superscript)
23358 ("-" . :special-strings)
23359 ("f" . :footnotes)
23360 ("d" . :drawers)
23361 ("tags" . :tags)
23362 ("*" . :emphasize)
23363 ("TeX" . :TeX-macros)
23364 ("LaTeX" . :LaTeX-fragments)
23365 ("skip" . :skip-before-1st-heading)
23366 ("author" . :author-info)
23367 ("timestamp" . :time-stamp-file)))
23369 (while (setq o (pop op))
23370 (if (string-match (concat (regexp-quote (car o))
23371 ":\\([^ \t\n\r;,.]*\\)")
23372 options)
23373 (setq p (plist-put p (cdr o)
23374 (car (read-from-string
23375 (match-string 1 options)))))))))
23376 p))))
23378 (defun org-export-directory (type plist)
23379 (let* ((val (plist-get plist :publishing-directory))
23380 (dir (if (listp val)
23381 (or (cdr (assoc type val)) ".")
23382 val)))
23383 dir))
23385 (defun org-skip-comments (lines)
23386 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23387 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23388 (re2 "^\\(\\*+\\)[ \t\n\r]")
23389 (case-fold-search nil)
23390 rtn line level)
23391 (while (setq line (pop lines))
23392 (cond
23393 ((and (string-match re1 line)
23394 (setq level (- (match-end 1) (match-beginning 1))))
23395 ;; Beginning of a COMMENT subtree. Skip it.
23396 (while (and (setq line (pop lines))
23397 (or (not (string-match re2 line))
23398 (> (- (match-end 1) (match-beginning 1)) level))))
23399 (setq lines (cons line lines)))
23400 ((string-match "^#" line)
23401 ;; an ordinary comment line
23403 ((and org-export-table-remove-special-lines
23404 (string-match "^[ \t]*|" line)
23405 (or (string-match "^[ \t]*| *[!_^] *|" line)
23406 (and (string-match "| *<[0-9]+> *|" line)
23407 (not (string-match "| *[^ <|]" line)))))
23408 ;; a special table line that should be removed
23410 (t (setq rtn (cons line rtn)))))
23411 (nreverse rtn)))
23413 (defun org-export (&optional arg)
23414 (interactive)
23415 (let ((help "[t] insert the export option template
23416 \[v] limit export to visible part of outline tree
23418 \[a] export as ASCII
23420 \[h] export as HTML
23421 \[H] export as HTML to temporary buffer
23422 \[R] export region as HTML
23423 \[b] export as HTML and browse immediately
23424 \[x] export as XOXO
23426 \[l] export as LaTeX
23427 \[L] export as LaTeX to temporary buffer
23429 \[i] export current file as iCalendar file
23430 \[I] export all agenda files as iCalendar files
23431 \[c] export agenda files into combined iCalendar file
23433 \[F] publish current file
23434 \[P] publish current project
23435 \[X] publish... (project will be prompted for)
23436 \[A] publish all projects")
23437 (cmds
23438 '((?t . org-insert-export-options-template)
23439 (?v . org-export-visible)
23440 (?a . org-export-as-ascii)
23441 (?h . org-export-as-html)
23442 (?b . org-export-as-html-and-open)
23443 (?H . org-export-as-html-to-buffer)
23444 (?R . org-export-region-as-html)
23445 (?x . org-export-as-xoxo)
23446 (?l . org-export-as-latex)
23447 (?L . org-export-as-latex-to-buffer)
23448 (?i . org-export-icalendar-this-file)
23449 (?I . org-export-icalendar-all-agenda-files)
23450 (?c . org-export-icalendar-combine-agenda-files)
23451 (?F . org-publish-current-file)
23452 (?P . org-publish-current-project)
23453 (?X . org-publish)
23454 (?A . org-publish-all)))
23455 r1 r2 ass)
23456 (save-window-excursion
23457 (delete-other-windows)
23458 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23459 (princ help))
23460 (message "Select command: ")
23461 (setq r1 (read-char-exclusive)))
23462 (setq r2 (if (< r1 27) (+ r1 96) r1))
23463 (if (setq ass (assq r2 cmds))
23464 (call-interactively (cdr ass))
23465 (error "No command associated with key %c" r1))))
23467 (defconst org-html-entities
23468 '(("nbsp")
23469 ("iexcl")
23470 ("cent")
23471 ("pound")
23472 ("curren")
23473 ("yen")
23474 ("brvbar")
23475 ("vert" . "&#124;")
23476 ("sect")
23477 ("uml")
23478 ("copy")
23479 ("ordf")
23480 ("laquo")
23481 ("not")
23482 ("shy")
23483 ("reg")
23484 ("macr")
23485 ("deg")
23486 ("plusmn")
23487 ("sup2")
23488 ("sup3")
23489 ("acute")
23490 ("micro")
23491 ("para")
23492 ("middot")
23493 ("odot"."o")
23494 ("star"."*")
23495 ("cedil")
23496 ("sup1")
23497 ("ordm")
23498 ("raquo")
23499 ("frac14")
23500 ("frac12")
23501 ("frac34")
23502 ("iquest")
23503 ("Agrave")
23504 ("Aacute")
23505 ("Acirc")
23506 ("Atilde")
23507 ("Auml")
23508 ("Aring") ("AA"."&Aring;")
23509 ("AElig")
23510 ("Ccedil")
23511 ("Egrave")
23512 ("Eacute")
23513 ("Ecirc")
23514 ("Euml")
23515 ("Igrave")
23516 ("Iacute")
23517 ("Icirc")
23518 ("Iuml")
23519 ("ETH")
23520 ("Ntilde")
23521 ("Ograve")
23522 ("Oacute")
23523 ("Ocirc")
23524 ("Otilde")
23525 ("Ouml")
23526 ("times")
23527 ("Oslash")
23528 ("Ugrave")
23529 ("Uacute")
23530 ("Ucirc")
23531 ("Uuml")
23532 ("Yacute")
23533 ("THORN")
23534 ("szlig")
23535 ("agrave")
23536 ("aacute")
23537 ("acirc")
23538 ("atilde")
23539 ("auml")
23540 ("aring")
23541 ("aelig")
23542 ("ccedil")
23543 ("egrave")
23544 ("eacute")
23545 ("ecirc")
23546 ("euml")
23547 ("igrave")
23548 ("iacute")
23549 ("icirc")
23550 ("iuml")
23551 ("eth")
23552 ("ntilde")
23553 ("ograve")
23554 ("oacute")
23555 ("ocirc")
23556 ("otilde")
23557 ("ouml")
23558 ("divide")
23559 ("oslash")
23560 ("ugrave")
23561 ("uacute")
23562 ("ucirc")
23563 ("uuml")
23564 ("yacute")
23565 ("thorn")
23566 ("yuml")
23567 ("fnof")
23568 ("Alpha")
23569 ("Beta")
23570 ("Gamma")
23571 ("Delta")
23572 ("Epsilon")
23573 ("Zeta")
23574 ("Eta")
23575 ("Theta")
23576 ("Iota")
23577 ("Kappa")
23578 ("Lambda")
23579 ("Mu")
23580 ("Nu")
23581 ("Xi")
23582 ("Omicron")
23583 ("Pi")
23584 ("Rho")
23585 ("Sigma")
23586 ("Tau")
23587 ("Upsilon")
23588 ("Phi")
23589 ("Chi")
23590 ("Psi")
23591 ("Omega")
23592 ("alpha")
23593 ("beta")
23594 ("gamma")
23595 ("delta")
23596 ("epsilon")
23597 ("varepsilon"."&epsilon;")
23598 ("zeta")
23599 ("eta")
23600 ("theta")
23601 ("iota")
23602 ("kappa")
23603 ("lambda")
23604 ("mu")
23605 ("nu")
23606 ("xi")
23607 ("omicron")
23608 ("pi")
23609 ("rho")
23610 ("sigmaf") ("varsigma"."&sigmaf;")
23611 ("sigma")
23612 ("tau")
23613 ("upsilon")
23614 ("phi")
23615 ("chi")
23616 ("psi")
23617 ("omega")
23618 ("thetasym") ("vartheta"."&thetasym;")
23619 ("upsih")
23620 ("piv")
23621 ("bull") ("bullet"."&bull;")
23622 ("hellip") ("dots"."&hellip;")
23623 ("prime")
23624 ("Prime")
23625 ("oline")
23626 ("frasl")
23627 ("weierp")
23628 ("image")
23629 ("real")
23630 ("trade")
23631 ("alefsym")
23632 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23633 ("uarr") ("uparrow"."&uarr;")
23634 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23635 ("darr")("downarrow"."&darr;")
23636 ("harr") ("leftrightarrow"."&harr;")
23637 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23638 ("lArr") ("Leftarrow"."&lArr;")
23639 ("uArr") ("Uparrow"."&uArr;")
23640 ("rArr") ("Rightarrow"."&rArr;")
23641 ("dArr") ("Downarrow"."&dArr;")
23642 ("hArr") ("Leftrightarrow"."&hArr;")
23643 ("forall")
23644 ("part") ("partial"."&part;")
23645 ("exist") ("exists"."&exist;")
23646 ("empty") ("emptyset"."&empty;")
23647 ("nabla")
23648 ("isin") ("in"."&isin;")
23649 ("notin")
23650 ("ni")
23651 ("prod")
23652 ("sum")
23653 ("minus")
23654 ("lowast") ("ast"."&lowast;")
23655 ("radic")
23656 ("prop") ("proptp"."&prop;")
23657 ("infin") ("infty"."&infin;")
23658 ("ang") ("angle"."&ang;")
23659 ("and") ("wedge"."&and;")
23660 ("or") ("vee"."&or;")
23661 ("cap")
23662 ("cup")
23663 ("int")
23664 ("there4")
23665 ("sim")
23666 ("cong") ("simeq"."&cong;")
23667 ("asymp")("approx"."&asymp;")
23668 ("ne") ("neq"."&ne;")
23669 ("equiv")
23670 ("le")
23671 ("ge")
23672 ("sub") ("subset"."&sub;")
23673 ("sup") ("supset"."&sup;")
23674 ("nsub")
23675 ("sube")
23676 ("supe")
23677 ("oplus")
23678 ("otimes")
23679 ("perp")
23680 ("sdot") ("cdot"."&sdot;")
23681 ("lceil")
23682 ("rceil")
23683 ("lfloor")
23684 ("rfloor")
23685 ("lang")
23686 ("rang")
23687 ("loz") ("Diamond"."&loz;")
23688 ("spades") ("spadesuit"."&spades;")
23689 ("clubs") ("clubsuit"."&clubs;")
23690 ("hearts") ("diamondsuit"."&hearts;")
23691 ("diams") ("diamondsuit"."&diams;")
23692 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23693 ("quot")
23694 ("amp")
23695 ("lt")
23696 ("gt")
23697 ("OElig")
23698 ("oelig")
23699 ("Scaron")
23700 ("scaron")
23701 ("Yuml")
23702 ("circ")
23703 ("tilde")
23704 ("ensp")
23705 ("emsp")
23706 ("thinsp")
23707 ("zwnj")
23708 ("zwj")
23709 ("lrm")
23710 ("rlm")
23711 ("ndash")
23712 ("mdash")
23713 ("lsquo")
23714 ("rsquo")
23715 ("sbquo")
23716 ("ldquo")
23717 ("rdquo")
23718 ("bdquo")
23719 ("dagger")
23720 ("Dagger")
23721 ("permil")
23722 ("lsaquo")
23723 ("rsaquo")
23724 ("euro")
23726 ("arccos"."arccos")
23727 ("arcsin"."arcsin")
23728 ("arctan"."arctan")
23729 ("arg"."arg")
23730 ("cos"."cos")
23731 ("cosh"."cosh")
23732 ("cot"."cot")
23733 ("coth"."coth")
23734 ("csc"."csc")
23735 ("deg"."deg")
23736 ("det"."det")
23737 ("dim"."dim")
23738 ("exp"."exp")
23739 ("gcd"."gcd")
23740 ("hom"."hom")
23741 ("inf"."inf")
23742 ("ker"."ker")
23743 ("lg"."lg")
23744 ("lim"."lim")
23745 ("liminf"."liminf")
23746 ("limsup"."limsup")
23747 ("ln"."ln")
23748 ("log"."log")
23749 ("max"."max")
23750 ("min"."min")
23751 ("Pr"."Pr")
23752 ("sec"."sec")
23753 ("sin"."sin")
23754 ("sinh"."sinh")
23755 ("sup"."sup")
23756 ("tan"."tan")
23757 ("tanh"."tanh")
23759 "Entities for TeX->HTML translation.
23760 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23761 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23762 In that case, \"\\ent\" will be translated to \"&other;\".
23763 The list contains HTML entities for Latin-1, Greek and other symbols.
23764 It is supplemented by a number of commonly used TeX macros with appropriate
23765 translations. There is currently no way for users to extend this.")
23767 ;;; General functions for all backends
23769 (defun org-cleaned-string-for-export (string &rest parameters)
23770 "Cleanup a buffer STRING so that links can be created safely."
23771 (interactive)
23772 (let* ((re-radio (and org-target-link-regexp
23773 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23774 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23775 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23776 (re-archive (concat ":" org-archive-tag ":"))
23777 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23778 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23779 (htmlp (plist-get parameters :for-html))
23780 (asciip (plist-get parameters :for-ascii))
23781 (latexp (plist-get parameters :for-LaTeX))
23782 (commentsp (plist-get parameters :comments))
23783 (archived-trees (plist-get parameters :archived-trees))
23784 (inhibit-read-only t)
23785 (drawers org-drawers)
23786 (exp-drawers (plist-get parameters :drawers))
23787 (outline-regexp "\\*+ ")
23788 a b xx
23789 rtn p)
23790 (with-current-buffer (get-buffer-create " org-mode-tmp")
23791 (erase-buffer)
23792 (insert string)
23793 ;; Remove license-to-kill stuff
23794 (while (setq p (text-property-any (point-min) (point-max)
23795 :org-license-to-kill t))
23796 (delete-region p (next-single-property-change p :org-license-to-kill)))
23798 (let ((org-inhibit-startup t)) (org-mode))
23799 (untabify (point-min) (point-max))
23801 ;; Get the correct stuff before the first headline
23802 (when (plist-get parameters :skip-before-1st-heading)
23803 (goto-char (point-min))
23804 (when (re-search-forward "^\\*+[ \t]" nil t)
23805 (delete-region (point-min) (match-beginning 0))
23806 (goto-char (point-min))
23807 (insert "\n")))
23808 (when (plist-get parameters :add-text)
23809 (goto-char (point-min))
23810 (insert (plist-get parameters :add-text) "\n"))
23812 ;; Get rid of archived trees
23813 (when (not (eq archived-trees t))
23814 (goto-char (point-min))
23815 (while (re-search-forward re-archive nil t)
23816 (if (not (org-on-heading-p t))
23817 (org-end-of-subtree t)
23818 (beginning-of-line 1)
23819 (setq a (if archived-trees
23820 (1+ (point-at-eol)) (point))
23821 b (org-end-of-subtree t))
23822 (if (> b a) (delete-region a b)))))
23824 ;; Get rid of drawers
23825 (unless (eq t exp-drawers)
23826 (goto-char (point-min))
23827 (let ((re (concat "^[ \t]*:\\("
23828 (mapconcat
23829 'identity
23830 (org-delete-all exp-drawers
23831 (copy-sequence drawers))
23832 "\\|")
23833 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23834 (while (re-search-forward re nil t)
23835 (replace-match ""))))
23837 ;; Find targets in comments and move them out of comments,
23838 ;; but mark them as targets that should be invisible
23839 (goto-char (point-min))
23840 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23841 (replace-match "\\1(INVISIBLE)"))
23843 ;; Protect backend specific stuff, throw away the others.
23844 (let ((formatters
23845 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23846 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23847 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23848 fmt)
23849 (goto-char (point-min))
23850 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23851 (goto-char (match-end 0))
23852 (while (not (looking-at "#\\+END_EXAMPLE"))
23853 (insert ": ")
23854 (beginning-of-line 2)))
23855 (goto-char (point-min))
23856 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23857 (add-text-properties (match-beginning 0) (match-end 0)
23858 '(org-protected t)))
23859 (while formatters
23860 (setq fmt (pop formatters))
23861 (when (car fmt)
23862 (goto-char (point-min))
23863 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23864 ":[ \t]*\\(.*\\)") nil t)
23865 (replace-match "\\1" t)
23866 (add-text-properties
23867 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23868 '(org-protected t))))
23869 (goto-char (point-min))
23870 (while (re-search-forward
23871 (concat "^#\\+"
23872 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23873 (cadddr fmt) "\\>.*\n?") nil t)
23874 (if (car fmt)
23875 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23876 '(org-protected t))
23877 (delete-region (match-beginning 0) (match-end 0))))))
23879 ;; Protect quoted subtrees
23880 (goto-char (point-min))
23881 (while (re-search-forward re-quote nil t)
23882 (goto-char (match-beginning 0))
23883 (end-of-line 1)
23884 (add-text-properties (point) (org-end-of-subtree t)
23885 '(org-protected t)))
23887 ;; Protect verbatim elements
23888 (goto-char (point-min))
23889 (while (re-search-forward org-verbatim-re nil t)
23890 (add-text-properties (match-beginning 4) (match-end 4)
23891 '(org-protected t))
23892 (goto-char (1+ (match-end 4))))
23894 ;; Remove subtrees that are commented
23895 (goto-char (point-min))
23896 (while (re-search-forward re-commented nil t)
23897 (goto-char (match-beginning 0))
23898 (delete-region (point) (org-end-of-subtree t)))
23900 ;; Remove special table lines
23901 (when org-export-table-remove-special-lines
23902 (goto-char (point-min))
23903 (while (re-search-forward "^[ \t]*|" nil t)
23904 (beginning-of-line 1)
23905 (if (or (looking-at "[ \t]*| *[!_^] *|")
23906 (and (looking-at ".*?| *<[0-9]+> *|")
23907 (not (looking-at ".*?| *[^ <|]"))))
23908 (delete-region (max (point-min) (1- (point-at-bol)))
23909 (point-at-eol))
23910 (end-of-line 1))))
23912 ;; Specific LaTeX stuff
23913 (when latexp
23914 (require 'org-export-latex nil)
23915 (org-export-latex-cleaned-string))
23917 (when asciip
23918 (org-export-ascii-clean-string))
23920 ;; Specific HTML stuff
23921 (when htmlp
23922 ;; Convert LaTeX fragments to images
23923 (when (plist-get parameters :LaTeX-fragments)
23924 (org-format-latex
23925 (concat "ltxpng/" (file-name-sans-extension
23926 (file-name-nondirectory
23927 org-current-export-file)))
23928 org-current-export-dir nil "Creating LaTeX image %s"))
23929 (message "Exporting..."))
23931 ;; Remove or replace comments
23932 (goto-char (point-min))
23933 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
23934 (if commentsp
23935 (progn (add-text-properties
23936 (match-beginning 0) (match-end 0) '(org-protected t))
23937 (replace-match (format commentsp (match-string 1)) t t))
23938 (replace-match "")))
23940 ;; Find matches for radio targets and turn them into internal links
23941 (goto-char (point-min))
23942 (when re-radio
23943 (while (re-search-forward re-radio nil t)
23944 (org-if-unprotected
23945 (replace-match "\\1[[\\2]]"))))
23947 ;; Find all links that contain a newline and put them into a single line
23948 (goto-char (point-min))
23949 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
23950 (org-if-unprotected
23951 (replace-match "\\1 \\3")
23952 (goto-char (match-beginning 0))))
23955 ;; Normalize links: Convert angle and plain links into bracket links
23956 ;; Expand link abbreviations
23957 (goto-char (point-min))
23958 (while (re-search-forward re-plain-link nil t)
23959 (goto-char (1- (match-end 0)))
23960 (org-if-unprotected
23961 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23962 ":" (match-string 3) "]]")))
23963 ;; added 'org-link face to links
23964 (put-text-property 0 (length s) 'face 'org-link s)
23965 (replace-match s t t))))
23966 (goto-char (point-min))
23967 (while (re-search-forward re-angle-link nil t)
23968 (goto-char (1- (match-end 0)))
23969 (org-if-unprotected
23970 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23971 ":" (match-string 3) "]]")))
23972 (put-text-property 0 (length s) 'face 'org-link s)
23973 (replace-match s t t))))
23974 (goto-char (point-min))
23975 (while (re-search-forward org-bracket-link-regexp nil t)
23976 (org-if-unprotected
23977 (let* ((s (concat "[[" (setq xx (save-match-data
23978 (org-link-expand-abbrev (match-string 1))))
23980 (if (match-end 3)
23981 (match-string 2)
23982 (concat "[" xx "]"))
23983 "]")))
23984 (put-text-property 0 (length s) 'face 'org-link s)
23985 (replace-match s t t))))
23987 ;; Find multiline emphasis and put them into single line
23988 (when (plist-get parameters :emph-multiline)
23989 (goto-char (point-min))
23990 (while (re-search-forward org-emph-re nil t)
23991 (if (not (= (char-after (match-beginning 3))
23992 (char-after (match-beginning 4))))
23993 (org-if-unprotected
23994 (subst-char-in-region (match-beginning 0) (match-end 0)
23995 ?\n ?\ t)
23996 (goto-char (1- (match-end 0))))
23997 (goto-char (1+ (match-beginning 0))))))
23999 (setq rtn (buffer-string)))
24000 (kill-buffer " org-mode-tmp")
24001 rtn))
24003 (defun org-export-grab-title-from-buffer ()
24004 "Get a title for the current document, from looking at the buffer."
24005 (let ((inhibit-read-only t))
24006 (save-excursion
24007 (goto-char (point-min))
24008 (let ((end (save-excursion (outline-next-heading) (point))))
24009 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24010 ;; Mark the line so that it will not be exported as normal text.
24011 (org-unmodified
24012 (add-text-properties (match-beginning 0) (match-end 0)
24013 (list :org-license-to-kill t)))
24014 ;; Return the title string
24015 (org-trim (match-string 0)))))))
24017 (defun org-export-get-title-from-subtree ()
24018 "Return subtree title and exclude it from export."
24019 (let (title (m (mark)))
24020 (save-excursion
24021 (goto-char (region-beginning))
24022 (when (and (org-at-heading-p)
24023 (>= (org-end-of-subtree t t) (region-end)))
24024 ;; This is a subtree, we take the title from the first heading
24025 (goto-char (region-beginning))
24026 (looking-at org-todo-line-regexp)
24027 (setq title (match-string 3))
24028 (org-unmodified
24029 (add-text-properties (point) (1+ (point-at-eol))
24030 (list :org-license-to-kill t)))))
24031 title))
24033 (defun org-solidify-link-text (s &optional alist)
24034 "Take link text and make a safe target out of it."
24035 (save-match-data
24036 (let* ((rtn
24037 (mapconcat
24038 'identity
24039 (org-split-string s "[ \t\r\n]+") "--"))
24040 (a (assoc rtn alist)))
24041 (or (cdr a) rtn))))
24043 (defun org-get-min-level (lines)
24044 "Get the minimum level in LINES."
24045 (let ((re "^\\(\\*+\\) ") l min)
24046 (catch 'exit
24047 (while (setq l (pop lines))
24048 (if (string-match re l)
24049 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24050 1)))
24052 ;; Variable holding the vector with section numbers
24053 (defvar org-section-numbers (make-vector org-level-max 0))
24055 (defun org-init-section-numbers ()
24056 "Initialize the vector for the section numbers."
24057 (let* ((level -1)
24058 (numbers (nreverse (org-split-string "" "\\.")))
24059 (depth (1- (length org-section-numbers)))
24060 (i depth) number-string)
24061 (while (>= i 0)
24062 (if (> i level)
24063 (aset org-section-numbers i 0)
24064 (setq number-string (or (car numbers) "0"))
24065 (if (string-match "\\`[A-Z]\\'" number-string)
24066 (aset org-section-numbers i
24067 (- (string-to-char number-string) ?A -1))
24068 (aset org-section-numbers i (string-to-number number-string)))
24069 (pop numbers))
24070 (setq i (1- i)))))
24072 (defun org-section-number (&optional level)
24073 "Return a string with the current section number.
24074 When LEVEL is non-nil, increase section numbers on that level."
24075 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24076 (when level
24077 (when (> level -1)
24078 (aset org-section-numbers
24079 level (1+ (aref org-section-numbers level))))
24080 (setq idx (1+ level))
24081 (while (<= idx depth)
24082 (if (not (= idx 1))
24083 (aset org-section-numbers idx 0))
24084 (setq idx (1+ idx))))
24085 (setq idx 0)
24086 (while (<= idx depth)
24087 (setq n (aref org-section-numbers idx))
24088 (setq string (concat string (if (not (string= string "")) "." "")
24089 (int-to-string n)))
24090 (setq idx (1+ idx)))
24091 (save-match-data
24092 (if (string-match "\\`\\([@0]\\.\\)+" string)
24093 (setq string (replace-match "" t nil string)))
24094 (if (string-match "\\(\\.0\\)+\\'" string)
24095 (setq string (replace-match "" t nil string))))
24096 string))
24098 ;;; ASCII export
24100 (defvar org-last-level nil) ; dynamically scoped variable
24101 (defvar org-min-level nil) ; dynamically scoped variable
24102 (defvar org-levels-open nil) ; dynamically scoped parameter
24103 (defvar org-ascii-current-indentation nil) ; For communication
24105 (defun org-export-as-ascii (arg)
24106 "Export the outline as a pretty ASCII file.
24107 If there is an active region, export only the region.
24108 The prefix ARG specifies how many levels of the outline should become
24109 underlined headlines. The default is 3."
24110 (interactive "P")
24111 (setq-default org-todo-line-regexp org-todo-line-regexp)
24112 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24113 (org-infile-export-plist)))
24114 (region-p (org-region-active-p))
24115 (subtree-p
24116 (when region-p
24117 (save-excursion
24118 (goto-char (region-beginning))
24119 (and (org-at-heading-p)
24120 (>= (org-end-of-subtree t t) (region-end))))))
24121 (custom-times org-display-custom-times)
24122 (org-ascii-current-indentation '(0 . 0))
24123 (level 0) line txt
24124 (umax nil)
24125 (umax-toc nil)
24126 (case-fold-search nil)
24127 (filename (concat (file-name-as-directory
24128 (org-export-directory :ascii opt-plist))
24129 (file-name-sans-extension
24130 (or (and subtree-p
24131 (org-entry-get (region-beginning)
24132 "EXPORT_FILE_NAME" t))
24133 (file-name-nondirectory buffer-file-name)))
24134 ".txt"))
24135 (filename (if (equal (file-truename filename)
24136 (file-truename buffer-file-name))
24137 (concat filename ".txt")
24138 filename))
24139 (buffer (find-file-noselect filename))
24140 (org-levels-open (make-vector org-level-max nil))
24141 (odd org-odd-levels-only)
24142 (date (plist-get opt-plist :date))
24143 (author (plist-get opt-plist :author))
24144 (title (or (and subtree-p (org-export-get-title-from-subtree))
24145 (plist-get opt-plist :title)
24146 (and (not
24147 (plist-get opt-plist :skip-before-1st-heading))
24148 (org-export-grab-title-from-buffer))
24149 (file-name-sans-extension
24150 (file-name-nondirectory buffer-file-name))))
24151 (email (plist-get opt-plist :email))
24152 (language (plist-get opt-plist :language))
24153 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24154 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24155 (todo nil)
24156 (lang-words nil)
24157 (region
24158 (buffer-substring
24159 (if (org-region-active-p) (region-beginning) (point-min))
24160 (if (org-region-active-p) (region-end) (point-max))))
24161 (lines (org-split-string
24162 (org-cleaned-string-for-export
24163 region
24164 :for-ascii t
24165 :skip-before-1st-heading
24166 (plist-get opt-plist :skip-before-1st-heading)
24167 :drawers (plist-get opt-plist :drawers)
24168 :verbatim-multiline t
24169 :archived-trees
24170 (plist-get opt-plist :archived-trees)
24171 :add-text (plist-get opt-plist :text))
24172 "\n"))
24173 thetoc have-headings first-heading-pos
24174 table-open table-buffer)
24176 (let ((inhibit-read-only t))
24177 (org-unmodified
24178 (remove-text-properties (point-min) (point-max)
24179 '(:org-license-to-kill t))))
24181 (setq org-min-level (org-get-min-level lines))
24182 (setq org-last-level org-min-level)
24183 (org-init-section-numbers)
24185 (find-file-noselect filename)
24187 (setq lang-words (or (assoc language org-export-language-setup)
24188 (assoc "en" org-export-language-setup)))
24189 (switch-to-buffer-other-window buffer)
24190 (erase-buffer)
24191 (fundamental-mode)
24192 ;; create local variables for all options, to make sure all called
24193 ;; functions get the correct information
24194 (mapc (lambda (x)
24195 (set (make-local-variable (cdr x))
24196 (plist-get opt-plist (car x))))
24197 org-export-plist-vars)
24198 (org-set-local 'org-odd-levels-only odd)
24199 (setq umax (if arg (prefix-numeric-value arg)
24200 org-export-headline-levels))
24201 (setq umax-toc (if (integerp org-export-with-toc)
24202 (min org-export-with-toc umax)
24203 umax))
24205 ;; File header
24206 (if title (org-insert-centered title ?=))
24207 (insert "\n")
24208 (if (and (or author email)
24209 org-export-author-info)
24210 (insert (concat (nth 1 lang-words) ": " (or author "")
24211 (if email (concat " <" email ">") "")
24212 "\n")))
24214 (cond
24215 ((and date (string-match "%" date))
24216 (setq date (format-time-string date (current-time))))
24217 (date)
24218 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24220 (if (and date org-export-time-stamp-file)
24221 (insert (concat (nth 2 lang-words) ": " date"\n")))
24223 (insert "\n\n")
24225 (if org-export-with-toc
24226 (progn
24227 (push (concat (nth 3 lang-words) "\n") thetoc)
24228 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24229 (mapc '(lambda (line)
24230 (if (string-match org-todo-line-regexp
24231 line)
24232 ;; This is a headline
24233 (progn
24234 (setq have-headings t)
24235 (setq level (- (match-end 1) (match-beginning 1))
24236 level (org-tr-level level)
24237 txt (match-string 3 line)
24238 todo
24239 (or (and org-export-mark-todo-in-toc
24240 (match-beginning 2)
24241 (not (member (match-string 2 line)
24242 org-done-keywords)))
24243 ; TODO, not DONE
24244 (and org-export-mark-todo-in-toc
24245 (= level umax-toc)
24246 (org-search-todo-below
24247 line lines level))))
24248 (setq txt (org-html-expand-for-ascii txt))
24250 (while (string-match org-bracket-link-regexp txt)
24251 (setq txt
24252 (replace-match
24253 (match-string (if (match-end 2) 3 1) txt)
24254 t t txt)))
24256 (if (and (memq org-export-with-tags '(not-in-toc nil))
24257 (string-match
24258 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24259 txt))
24260 (setq txt (replace-match "" t t txt)))
24261 (if (string-match quote-re0 txt)
24262 (setq txt (replace-match "" t t txt)))
24264 (if org-export-with-section-numbers
24265 (setq txt (concat (org-section-number level)
24266 " " txt)))
24267 (if (<= level umax-toc)
24268 (progn
24269 (push
24270 (concat
24271 (make-string
24272 (* (max 0 (- level org-min-level)) 4) ?\ )
24273 (format (if todo "%s (*)\n" "%s\n") txt))
24274 thetoc)
24275 (setq org-last-level level))
24276 ))))
24277 lines)
24278 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24280 (org-init-section-numbers)
24281 (while (setq line (pop lines))
24282 ;; Remove the quoted HTML tags.
24283 (setq line (org-html-expand-for-ascii line))
24284 ;; Remove targets
24285 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24286 (setq line (replace-match "" t t line)))
24287 ;; Replace internal links
24288 (while (string-match org-bracket-link-regexp line)
24289 (setq line (replace-match
24290 (if (match-end 3) "[\\3]" "[\\1]")
24291 t nil line)))
24292 (when custom-times
24293 (setq line (org-translate-time line)))
24294 (cond
24295 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24296 ;; a Headline
24297 (setq first-heading-pos (or first-heading-pos (point)))
24298 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24299 txt (match-string 2 line))
24300 (org-ascii-level-start level txt umax lines))
24302 ((and org-export-with-tables
24303 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24304 (if (not table-open)
24305 ;; New table starts
24306 (setq table-open t table-buffer nil))
24307 ;; Accumulate lines
24308 (setq table-buffer (cons line table-buffer))
24309 (when (or (not lines)
24310 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24311 (car lines))))
24312 (setq table-open nil
24313 table-buffer (nreverse table-buffer))
24314 (insert (mapconcat
24315 (lambda (x)
24316 (org-fix-indentation x org-ascii-current-indentation))
24317 (org-format-table-ascii table-buffer)
24318 "\n") "\n")))
24320 (setq line (org-fix-indentation line org-ascii-current-indentation))
24321 (if (and org-export-with-fixed-width
24322 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24323 (setq line (replace-match "\\1" nil nil line)))
24324 (insert line "\n"))))
24326 (normal-mode)
24328 ;; insert the table of contents
24329 (when thetoc
24330 (goto-char (point-min))
24331 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24332 (progn
24333 (goto-char (match-beginning 0))
24334 (replace-match ""))
24335 (goto-char first-heading-pos))
24336 (mapc 'insert thetoc)
24337 (or (looking-at "[ \t]*\n[ \t]*\n")
24338 (insert "\n\n")))
24340 ;; Convert whitespace place holders
24341 (goto-char (point-min))
24342 (let (beg end)
24343 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24344 (setq end (next-single-property-change beg 'org-whitespace))
24345 (goto-char beg)
24346 (delete-region beg end)
24347 (insert (make-string (- end beg) ?\ ))))
24349 (save-buffer)
24350 ;; remove display and invisible chars
24351 (let (beg end)
24352 (goto-char (point-min))
24353 (while (setq beg (next-single-property-change (point) 'display))
24354 (setq end (next-single-property-change beg 'display))
24355 (delete-region beg end)
24356 (goto-char beg)
24357 (insert "=>"))
24358 (goto-char (point-min))
24359 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24360 (setq end (next-single-property-change beg 'org-cwidth))
24361 (delete-region beg end)
24362 (goto-char beg)))
24363 (goto-char (point-min))))
24365 (defun org-export-ascii-clean-string ()
24366 "Do extra work for ASCII export"
24367 (goto-char (point-min))
24368 (while (re-search-forward org-verbatim-re nil t)
24369 (goto-char (match-end 2))
24370 (backward-delete-char 1) (insert "'")
24371 (goto-char (match-beginning 2))
24372 (delete-char 1) (insert "`")
24373 (goto-char (match-end 2))))
24375 (defun org-search-todo-below (line lines level)
24376 "Search the subtree below LINE for any TODO entries."
24377 (let ((rest (cdr (memq line lines)))
24378 (re org-todo-line-regexp)
24379 line lv todo)
24380 (catch 'exit
24381 (while (setq line (pop rest))
24382 (if (string-match re line)
24383 (progn
24384 (setq lv (- (match-end 1) (match-beginning 1))
24385 todo (and (match-beginning 2)
24386 (not (member (match-string 2 line)
24387 org-done-keywords))))
24388 ; TODO, not DONE
24389 (if (<= lv level) (throw 'exit nil))
24390 (if todo (throw 'exit t))))))))
24392 (defun org-html-expand-for-ascii (line)
24393 "Handle quoted HTML for ASCII export."
24394 (if org-export-html-expand
24395 (while (string-match "@<[^<>\n]*>" line)
24396 ;; We just remove the tags for now.
24397 (setq line (replace-match "" nil nil line))))
24398 line)
24400 (defun org-insert-centered (s &optional underline)
24401 "Insert the string S centered and underline it with character UNDERLINE."
24402 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24403 (insert (make-string ind ?\ ) s "\n")
24404 (if underline
24405 (insert (make-string ind ?\ )
24406 (make-string (string-width s) underline)
24407 "\n"))))
24409 (defun org-ascii-level-start (level title umax &optional lines)
24410 "Insert a new level in ASCII export."
24411 (let (char (n (- level umax 1)) (ind 0))
24412 (if (> level umax)
24413 (progn
24414 (insert (make-string (* 2 n) ?\ )
24415 (char-to-string (nth (% n (length org-export-ascii-bullets))
24416 org-export-ascii-bullets))
24417 " " title "\n")
24418 ;; find the indentation of the next non-empty line
24419 (catch 'stop
24420 (while lines
24421 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24422 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24423 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24424 (pop lines)))
24425 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24426 (if (or (not (equal (char-before) ?\n))
24427 (not (equal (char-before (1- (point))) ?\n)))
24428 (insert "\n"))
24429 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24430 (unless org-export-with-tags
24431 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24432 (setq title (replace-match "" t t title))))
24433 (if org-export-with-section-numbers
24434 (setq title (concat (org-section-number level) " " title)))
24435 (insert title "\n" (make-string (string-width title) char) "\n")
24436 (setq org-ascii-current-indentation '(0 . 0)))))
24438 (defun org-export-visible (type arg)
24439 "Create a copy of the visible part of the current buffer, and export it.
24440 The copy is created in a temporary buffer and removed after use.
24441 TYPE is the final key (as a string) that also select the export command in
24442 the `C-c C-e' export dispatcher.
24443 As a special case, if the you type SPC at the prompt, the temporary
24444 org-mode file will not be removed but presented to you so that you can
24445 continue to use it. The prefix arg ARG is passed through to the exporting
24446 command."
24447 (interactive
24448 (list (progn
24449 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24450 (read-char-exclusive))
24451 current-prefix-arg))
24452 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24453 (error "Invalid export key"))
24454 (let* ((binding (cdr (assoc type
24455 '((?a . org-export-as-ascii)
24456 (?\C-a . org-export-as-ascii)
24457 (?b . org-export-as-html-and-open)
24458 (?\C-b . org-export-as-html-and-open)
24459 (?h . org-export-as-html)
24460 (?H . org-export-as-html-to-buffer)
24461 (?R . org-export-region-as-html)
24462 (?x . org-export-as-xoxo)))))
24463 (keepp (equal type ?\ ))
24464 (file buffer-file-name)
24465 (buffer (get-buffer-create "*Org Export Visible*"))
24466 s e)
24467 ;; Need to hack the drawers here.
24468 (save-excursion
24469 (goto-char (point-min))
24470 (while (re-search-forward org-drawer-regexp nil t)
24471 (goto-char (match-beginning 1))
24472 (or (org-invisible-p) (org-flag-drawer nil))))
24473 (with-current-buffer buffer (erase-buffer))
24474 (save-excursion
24475 (setq s (goto-char (point-min)))
24476 (while (not (= (point) (point-max)))
24477 (goto-char (org-find-invisible))
24478 (append-to-buffer buffer s (point))
24479 (setq s (goto-char (org-find-visible))))
24480 (org-cycle-hide-drawers 'all)
24481 (goto-char (point-min))
24482 (unless keepp
24483 ;; Copy all comment lines to the end, to make sure #+ settings are
24484 ;; still available for the second export step. Kind of a hack, but
24485 ;; does do the trick.
24486 (if (looking-at "#[^\r\n]*")
24487 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24488 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24489 (append-to-buffer buffer (1+ (match-beginning 0))
24490 (min (point-max) (1+ (match-end 0))))))
24491 (set-buffer buffer)
24492 (let ((buffer-file-name file)
24493 (org-inhibit-startup t))
24494 (org-mode)
24495 (show-all)
24496 (unless keepp (funcall binding arg))))
24497 (if (not keepp)
24498 (kill-buffer buffer)
24499 (switch-to-buffer-other-window buffer)
24500 (goto-char (point-min)))))
24502 (defun org-find-visible ()
24503 (let ((s (point)))
24504 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24505 (get-char-property s 'invisible)))
24507 (defun org-find-invisible ()
24508 (let ((s (point)))
24509 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24510 (not (get-char-property s 'invisible))))
24513 ;;; HTML export
24515 (defun org-get-current-options ()
24516 "Return a string with current options as keyword options.
24517 Does include HTML export options as well as TODO and CATEGORY stuff."
24518 (format
24519 "#+TITLE: %s
24520 #+AUTHOR: %s
24521 #+EMAIL: %s
24522 #+LANGUAGE: %s
24523 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24524 #+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
24525 #+CATEGORY: %s
24526 #+SEQ_TODO: %s
24527 #+TYP_TODO: %s
24528 #+PRIORITIES: %c %c %c
24529 #+DRAWERS: %s
24530 #+STARTUP: %s %s %s %s %s
24531 #+TAGS: %s
24532 #+ARCHIVE: %s
24533 #+LINK: %s
24535 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24536 org-export-headline-levels
24537 org-export-with-section-numbers
24538 org-export-with-toc
24539 org-export-preserve-breaks
24540 org-export-html-expand
24541 org-export-with-fixed-width
24542 org-export-with-tables
24543 org-export-with-sub-superscripts
24544 org-export-with-special-strings
24545 org-export-with-footnotes
24546 org-export-with-emphasize
24547 org-export-with-TeX-macros
24548 org-export-with-LaTeX-fragments
24549 org-export-skip-text-before-1st-heading
24550 org-export-with-drawers
24551 org-export-with-tags
24552 (file-name-nondirectory buffer-file-name)
24553 "TODO FEEDBACK VERIFY DONE"
24554 "Me Jason Marie DONE"
24555 org-highest-priority org-lowest-priority org-default-priority
24556 (mapconcat 'identity org-drawers " ")
24557 (cdr (assoc org-startup-folded
24558 '((nil . "showall") (t . "overview") (content . "content"))))
24559 (if org-odd-levels-only "odd" "oddeven")
24560 (if org-hide-leading-stars "hidestars" "showstars")
24561 (if org-startup-align-all-tables "align" "noalign")
24562 (cond ((eq t org-log-done) "logdone")
24563 ((not org-log-done) "nologging")
24564 ((listp org-log-done)
24565 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
24566 org-log-done " ")))
24567 (or (mapconcat (lambda (x)
24568 (cond
24569 ((equal '(:startgroup) x) "{")
24570 ((equal '(:endgroup) x) "}")
24571 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24572 (t (car x))))
24573 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24574 org-archive-location
24575 "org file:~/org/%s.org"
24578 (defun org-insert-export-options-template ()
24579 "Insert into the buffer a template with information for exporting."
24580 (interactive)
24581 (if (not (bolp)) (newline))
24582 (let ((s (org-get-current-options)))
24583 (and (string-match "#\\+CATEGORY" s)
24584 (setq s (substring s 0 (match-beginning 0))))
24585 (insert s)))
24587 (defun org-toggle-fixed-width-section (arg)
24588 "Toggle the fixed-width export.
24589 If there is no active region, the QUOTE keyword at the current headline is
24590 inserted or removed. When present, it causes the text between this headline
24591 and the next to be exported as fixed-width text, and unmodified.
24592 If there is an active region, this command adds or removes a colon as the
24593 first character of this line. If the first character of a line is a colon,
24594 this line is also exported in fixed-width font."
24595 (interactive "P")
24596 (let* ((cc 0)
24597 (regionp (org-region-active-p))
24598 (beg (if regionp (region-beginning) (point)))
24599 (end (if regionp (region-end)))
24600 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24601 (case-fold-search nil)
24602 (re "[ \t]*\\(:\\)")
24603 off)
24604 (if regionp
24605 (save-excursion
24606 (goto-char beg)
24607 (setq cc (current-column))
24608 (beginning-of-line 1)
24609 (setq off (looking-at re))
24610 (while (> nlines 0)
24611 (setq nlines (1- nlines))
24612 (beginning-of-line 1)
24613 (cond
24614 (arg
24615 (move-to-column cc t)
24616 (insert ":\n")
24617 (forward-line -1))
24618 ((and off (looking-at re))
24619 (replace-match "" t t nil 1))
24620 ((not off) (move-to-column cc t) (insert ":")))
24621 (forward-line 1)))
24622 (save-excursion
24623 (org-back-to-heading)
24624 (if (looking-at (concat outline-regexp
24625 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24626 (replace-match "" t t nil 1)
24627 (if (looking-at outline-regexp)
24628 (progn
24629 (goto-char (match-end 0))
24630 (insert org-quote-string " "))))))))
24632 (defun org-export-as-html-and-open (arg)
24633 "Export the outline as HTML and immediately open it with a browser.
24634 If there is an active region, export only the region.
24635 The prefix ARG specifies how many levels of the outline should become
24636 headlines. The default is 3. Lower levels will become bulleted lists."
24637 (interactive "P")
24638 (org-export-as-html arg 'hidden)
24639 (org-open-file buffer-file-name))
24641 (defun org-export-as-html-batch ()
24642 "Call `org-export-as-html', may be used in batch processing as
24643 emacs --batch
24644 --load=$HOME/lib/emacs/org.el
24645 --eval \"(setq org-export-headline-levels 2)\"
24646 --visit=MyFile --funcall org-export-as-html-batch"
24647 (org-export-as-html org-export-headline-levels 'hidden))
24649 (defun org-export-as-html-to-buffer (arg)
24650 "Call `org-exort-as-html` with output to a temporary buffer.
24651 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24652 (interactive "P")
24653 (org-export-as-html arg nil nil "*Org HTML Export*")
24654 (switch-to-buffer-other-window "*Org HTML Export*"))
24656 (defun org-replace-region-by-html (beg end)
24657 "Assume the current region has org-mode syntax, and convert it to HTML.
24658 This can be used in any buffer. For example, you could write an
24659 itemized list in org-mode syntax in an HTML buffer and then use this
24660 command to convert it."
24661 (interactive "r")
24662 (let (reg html buf pop-up-frames)
24663 (save-window-excursion
24664 (if (org-mode-p)
24665 (setq html (org-export-region-as-html
24666 beg end t 'string))
24667 (setq reg (buffer-substring beg end)
24668 buf (get-buffer-create "*Org tmp*"))
24669 (with-current-buffer buf
24670 (erase-buffer)
24671 (insert reg)
24672 (org-mode)
24673 (setq html (org-export-region-as-html
24674 (point-min) (point-max) t 'string)))
24675 (kill-buffer buf)))
24676 (delete-region beg end)
24677 (insert html)))
24679 (defun org-export-region-as-html (beg end &optional body-only buffer)
24680 "Convert region from BEG to END in org-mode buffer to HTML.
24681 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24682 contents, and only produce the region of converted text, useful for
24683 cut-and-paste operations.
24684 If BUFFER is a buffer or a string, use/create that buffer as a target
24685 of the converted HTML. If BUFFER is the symbol `string', return the
24686 produced HTML as a string and leave not buffer behind. For example,
24687 a Lisp program could call this function in the following way:
24689 (setq html (org-export-region-as-html beg end t 'string))
24691 When called interactively, the output buffer is selected, and shown
24692 in a window. A non-interactive call will only retunr the buffer."
24693 (interactive "r\nP")
24694 (when (interactive-p)
24695 (setq buffer "*Org HTML Export*"))
24696 (let ((transient-mark-mode t) (zmacs-regions t)
24697 rtn)
24698 (goto-char end)
24699 (set-mark (point)) ;; to activate the region
24700 (goto-char beg)
24701 (setq rtn (org-export-as-html
24702 nil nil nil
24703 buffer body-only))
24704 (if (fboundp 'deactivate-mark) (deactivate-mark))
24705 (if (and (interactive-p) (bufferp rtn))
24706 (switch-to-buffer-other-window rtn)
24707 rtn)))
24709 (defvar html-table-tag nil) ; dynamically scoped into this.
24710 (defun org-export-as-html (arg &optional hidden ext-plist
24711 to-buffer body-only)
24712 "Export the outline as a pretty HTML file.
24713 If there is an active region, export only the region. The prefix
24714 ARG specifies how many levels of the outline should become
24715 headlines. The default is 3. Lower levels will become bulleted
24716 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24717 EXT-PLIST is a property list with external parameters overriding
24718 org-mode's default settings, but still inferior to file-local
24719 settings. When TO-BUFFER is non-nil, create a buffer with that
24720 name and export to that buffer. If TO-BUFFER is the symbol `string',
24721 don't leave any buffer behind but just return the resulting HTML as
24722 a string. When BODY-ONLY is set, don't produce the file header and footer,
24723 simply return the content of <body>...</body>, without even
24724 the body tags themselves."
24725 (interactive "P")
24727 ;; Make sure we have a file name when we need it.
24728 (when (and (not (or to-buffer body-only))
24729 (not buffer-file-name))
24730 (if (buffer-base-buffer)
24731 (org-set-local 'buffer-file-name
24732 (with-current-buffer (buffer-base-buffer)
24733 buffer-file-name))
24734 (error "Need a file name to be able to export.")))
24736 (message "Exporting...")
24737 (setq-default org-todo-line-regexp org-todo-line-regexp)
24738 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24739 (setq-default org-done-keywords org-done-keywords)
24740 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24741 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24742 ext-plist
24743 (org-infile-export-plist)))
24745 (style (plist-get opt-plist :style))
24746 (link-validate (plist-get opt-plist :link-validation-function))
24747 valid thetoc have-headings first-heading-pos
24748 (odd org-odd-levels-only)
24749 (region-p (org-region-active-p))
24750 (subtree-p
24751 (when region-p
24752 (save-excursion
24753 (goto-char (region-beginning))
24754 (and (org-at-heading-p)
24755 (>= (org-end-of-subtree t t) (region-end))))))
24756 ;; The following two are dynamically scoped into other
24757 ;; routines below.
24758 (org-current-export-dir (org-export-directory :html opt-plist))
24759 (org-current-export-file buffer-file-name)
24760 (level 0) (line "") (origline "") txt todo
24761 (umax nil)
24762 (umax-toc nil)
24763 (filename (if to-buffer nil
24764 (expand-file-name
24765 (concat
24766 (file-name-sans-extension
24767 (or (and subtree-p
24768 (org-entry-get (region-beginning)
24769 "EXPORT_FILE_NAME" t))
24770 (file-name-nondirectory buffer-file-name)))
24771 "." org-export-html-extension)
24772 (file-name-as-directory
24773 (org-export-directory :html opt-plist)))))
24774 (current-dir (if buffer-file-name
24775 (file-name-directory buffer-file-name)
24776 default-directory))
24777 (buffer (if to-buffer
24778 (cond
24779 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24780 (t (get-buffer-create to-buffer)))
24781 (find-file-noselect filename)))
24782 (org-levels-open (make-vector org-level-max nil))
24783 (date (plist-get opt-plist :date))
24784 (author (plist-get opt-plist :author))
24785 (title (or (and subtree-p (org-export-get-title-from-subtree))
24786 (plist-get opt-plist :title)
24787 (and (not
24788 (plist-get opt-plist :skip-before-1st-heading))
24789 (org-export-grab-title-from-buffer))
24790 (and buffer-file-name
24791 (file-name-sans-extension
24792 (file-name-nondirectory buffer-file-name)))
24793 "UNTITLED"))
24794 (html-table-tag (plist-get opt-plist :html-table-tag))
24795 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24796 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24797 (inquote nil)
24798 (infixed nil)
24799 (in-local-list nil)
24800 (local-list-num nil)
24801 (local-list-indent nil)
24802 (llt org-plain-list-ordered-item-terminator)
24803 (email (plist-get opt-plist :email))
24804 (language (plist-get opt-plist :language))
24805 (lang-words nil)
24806 (target-alist nil) tg
24807 (head-count 0) cnt
24808 (start 0)
24809 (coding-system (and (boundp 'buffer-file-coding-system)
24810 buffer-file-coding-system))
24811 (coding-system-for-write (or org-export-html-coding-system
24812 coding-system))
24813 (save-buffer-coding-system (or org-export-html-coding-system
24814 coding-system))
24815 (charset (and coding-system-for-write
24816 (fboundp 'coding-system-get)
24817 (coding-system-get coding-system-for-write
24818 'mime-charset)))
24819 (region
24820 (buffer-substring
24821 (if region-p (region-beginning) (point-min))
24822 (if region-p (region-end) (point-max))))
24823 (lines
24824 (org-split-string
24825 (org-cleaned-string-for-export
24826 region
24827 :emph-multiline t
24828 :for-html t
24829 :skip-before-1st-heading
24830 (plist-get opt-plist :skip-before-1st-heading)
24831 :drawers (plist-get opt-plist :drawers)
24832 :archived-trees
24833 (plist-get opt-plist :archived-trees)
24834 :add-text
24835 (plist-get opt-plist :text)
24836 :LaTeX-fragments
24837 (plist-get opt-plist :LaTeX-fragments))
24838 "[\r\n]"))
24839 table-open type
24840 table-buffer table-orig-buffer
24841 ind start-is-num starter didclose
24842 rpl path desc descp desc1 desc2 link
24845 (let ((inhibit-read-only t))
24846 (org-unmodified
24847 (remove-text-properties (point-min) (point-max)
24848 '(:org-license-to-kill t))))
24850 (message "Exporting...")
24852 (setq org-min-level (org-get-min-level lines))
24853 (setq org-last-level org-min-level)
24854 (org-init-section-numbers)
24856 (cond
24857 ((and date (string-match "%" date))
24858 (setq date (format-time-string date (current-time))))
24859 (date)
24860 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24862 ;; Get the language-dependent settings
24863 (setq lang-words (or (assoc language org-export-language-setup)
24864 (assoc "en" org-export-language-setup)))
24866 ;; Switch to the output buffer
24867 (set-buffer buffer)
24868 (let ((inhibit-read-only t)) (erase-buffer))
24869 (fundamental-mode)
24871 (and (fboundp 'set-buffer-file-coding-system)
24872 (set-buffer-file-coding-system coding-system-for-write))
24874 (let ((case-fold-search nil)
24875 (org-odd-levels-only odd))
24876 ;; create local variables for all options, to make sure all called
24877 ;; functions get the correct information
24878 (mapc (lambda (x)
24879 (set (make-local-variable (cdr x))
24880 (plist-get opt-plist (car x))))
24881 org-export-plist-vars)
24882 (setq umax (if arg (prefix-numeric-value arg)
24883 org-export-headline-levels))
24884 (setq umax-toc (if (integerp org-export-with-toc)
24885 (min org-export-with-toc umax)
24886 umax))
24887 (unless body-only
24888 ;; File header
24889 (insert (format
24890 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24891 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24892 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24893 lang=\"%s\" xml:lang=\"%s\">
24894 <head>
24895 <title>%s</title>
24896 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24897 <meta name=\"generator\" content=\"Org-mode\"/>
24898 <meta name=\"generated\" content=\"%s\"/>
24899 <meta name=\"author\" content=\"%s\"/>
24901 </head><body>
24903 language language (org-html-expand title)
24904 (or charset "iso-8859-1") date author style))
24906 (insert (or (plist-get opt-plist :preamble) ""))
24908 (when (plist-get opt-plist :auto-preamble)
24909 (if title (insert (format org-export-html-title-format
24910 (org-html-expand title))))))
24912 (if (and org-export-with-toc (not body-only))
24913 (progn
24914 (push (format "<h%d>%s</h%d>\n"
24915 org-export-html-toplevel-hlevel
24916 (nth 3 lang-words)
24917 org-export-html-toplevel-hlevel)
24918 thetoc)
24919 (push "<ul>\n<li>" thetoc)
24920 (setq lines
24921 (mapcar '(lambda (line)
24922 (if (string-match org-todo-line-regexp line)
24923 ;; This is a headline
24924 (progn
24925 (setq have-headings t)
24926 (setq level (- (match-end 1) (match-beginning 1))
24927 level (org-tr-level level)
24928 txt (save-match-data
24929 (org-html-expand
24930 (org-export-cleanup-toc-line
24931 (match-string 3 line))))
24932 todo
24933 (or (and org-export-mark-todo-in-toc
24934 (match-beginning 2)
24935 (not (member (match-string 2 line)
24936 org-done-keywords)))
24937 ; TODO, not DONE
24938 (and org-export-mark-todo-in-toc
24939 (= level umax-toc)
24940 (org-search-todo-below
24941 line lines level))))
24942 (if (string-match
24943 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
24944 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
24945 (if (string-match quote-re0 txt)
24946 (setq txt (replace-match "" t t txt)))
24947 (if org-export-with-section-numbers
24948 (setq txt (concat (org-section-number level)
24949 " " txt)))
24950 (if (<= level (max umax umax-toc))
24951 (setq head-count (+ head-count 1)))
24952 (if (<= level umax-toc)
24953 (progn
24954 (if (> level org-last-level)
24955 (progn
24956 (setq cnt (- level org-last-level))
24957 (while (>= (setq cnt (1- cnt)) 0)
24958 (push "\n<ul>\n<li>" thetoc))
24959 (push "\n" thetoc)))
24960 (if (< level org-last-level)
24961 (progn
24962 (setq cnt (- org-last-level level))
24963 (while (>= (setq cnt (1- cnt)) 0)
24964 (push "</li>\n</ul>" thetoc))
24965 (push "\n" thetoc)))
24966 ;; Check for targets
24967 (while (string-match org-target-regexp line)
24968 (setq tg (match-string 1 line)
24969 line (replace-match
24970 (concat "@<span class=\"target\">" tg "@</span> ")
24971 t t line))
24972 (push (cons (org-solidify-link-text tg)
24973 (format "sec-%d" head-count))
24974 target-alist))
24975 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
24976 (setq txt (replace-match "" t t txt)))
24977 (push
24978 (format
24979 (if todo
24980 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
24981 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
24982 head-count txt) thetoc)
24984 (setq org-last-level level))
24986 line)
24987 lines))
24988 (while (> org-last-level (1- org-min-level))
24989 (setq org-last-level (1- org-last-level))
24990 (push "</li>\n</ul>\n" thetoc))
24991 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24993 (setq head-count 0)
24994 (org-init-section-numbers)
24996 (while (setq line (pop lines) origline line)
24997 (catch 'nextline
24999 ;; end of quote section?
25000 (when (and inquote (string-match "^\\*+ " line))
25001 (insert "</pre>\n")
25002 (setq inquote nil))
25003 ;; inside a quote section?
25004 (when inquote
25005 (insert (org-html-protect line) "\n")
25006 (throw 'nextline nil))
25008 ;; verbatim lines
25009 (when (and org-export-with-fixed-width
25010 (string-match "^[ \t]*:\\(.*\\)" line))
25011 (when (not infixed)
25012 (setq infixed t)
25013 (insert "<pre>\n"))
25014 (insert (org-html-protect (match-string 1 line)) "\n")
25015 (when (and lines
25016 (not (string-match "^[ \t]*\\(:.*\\)"
25017 (car lines))))
25018 (setq infixed nil)
25019 (insert "</pre>\n"))
25020 (throw 'nextline nil))
25022 ;; Protected HTML
25023 (when (get-text-property 0 'org-protected line)
25024 (let (par)
25025 (when (re-search-backward
25026 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25027 (setq par (match-string 1))
25028 (replace-match "\\2\n"))
25029 (insert line "\n")
25030 (while (and lines
25031 (or (= (length (car lines)) 0)
25032 (get-text-property 0 'org-protected (car lines))))
25033 (insert (pop lines) "\n"))
25034 (and par (insert "<p>\n")))
25035 (throw 'nextline nil))
25037 ;; Horizontal line
25038 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25039 (insert "\n<hr/>\n")
25040 (throw 'nextline nil))
25042 ;; make targets to anchors
25043 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25044 (cond
25045 ((match-end 2)
25046 (setq line (replace-match
25047 (concat "@<a name=\""
25048 (org-solidify-link-text (match-string 1 line))
25049 "\">\\nbsp@</a>")
25050 t t line)))
25051 ((and org-export-with-toc (equal (string-to-char line) ?*))
25052 (setq line (replace-match
25053 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25054 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25055 t t line)))
25057 (setq line (replace-match
25058 (concat "@<a name=\""
25059 (org-solidify-link-text (match-string 1 line))
25060 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25061 t t line)))))
25063 (setq line (org-html-handle-time-stamps line))
25065 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25066 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25067 ;; Also handle sub_superscripts and checkboxes
25068 (or (string-match org-table-hline-regexp line)
25069 (setq line (org-html-expand line)))
25071 ;; Format the links
25072 (setq start 0)
25073 (while (string-match org-bracket-link-analytic-regexp line start)
25074 (setq start (match-beginning 0))
25075 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25076 (setq path (match-string 3 line))
25077 (setq desc1 (if (match-end 5) (match-string 5 line))
25078 desc2 (if (match-end 2) (concat type ":" path) path)
25079 descp (and desc1 (not (equal desc1 desc2)))
25080 desc (or desc1 desc2))
25081 ;; Make an image out of the description if that is so wanted
25082 (when (and descp (org-file-image-p desc))
25083 (save-match-data
25084 (if (string-match "^file:" desc)
25085 (setq desc (substring desc (match-end 0)))))
25086 (setq desc (concat "<img src=\"" desc "\"/>")))
25087 ;; FIXME: do we need to unescape here somewhere?
25088 (cond
25089 ((equal type "internal")
25090 (setq rpl
25091 (concat
25092 "<a href=\"#"
25093 (org-solidify-link-text
25094 (save-match-data (org-link-unescape path)) target-alist)
25095 "\">" desc "</a>")))
25096 ((member type '("http" "https"))
25097 ;; standard URL, just check if we need to inline an image
25098 (if (and (or (eq t org-export-html-inline-images)
25099 (and org-export-html-inline-images (not descp)))
25100 (org-file-image-p path))
25101 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25102 (setq link (concat type ":" path))
25103 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25104 ((member type '("ftp" "mailto" "news"))
25105 ;; standard URL
25106 (setq link (concat type ":" path))
25107 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25108 ((string= type "file")
25109 ;; FILE link
25110 (let* ((filename path)
25111 (abs-p (file-name-absolute-p filename))
25112 thefile file-is-image-p search)
25113 (save-match-data
25114 (if (string-match "::\\(.*\\)" filename)
25115 (setq search (match-string 1 filename)
25116 filename (replace-match "" t nil filename)))
25117 (setq valid
25118 (if (functionp link-validate)
25119 (funcall link-validate filename current-dir)
25121 (setq file-is-image-p (org-file-image-p filename))
25122 (setq thefile (if abs-p (expand-file-name filename) filename))
25123 (when (and org-export-html-link-org-files-as-html
25124 (string-match "\\.org$" thefile))
25125 (setq thefile (concat (substring thefile 0
25126 (match-beginning 0))
25127 "." org-export-html-extension))
25128 (if (and search
25129 ;; make sure this is can be used as target search
25130 (not (string-match "^[0-9]*$" search))
25131 (not (string-match "^\\*" search))
25132 (not (string-match "^/.*/$" search)))
25133 (setq thefile (concat thefile "#"
25134 (org-solidify-link-text
25135 (org-link-unescape search)))))
25136 (when (string-match "^file:" desc)
25137 (setq desc (replace-match "" t t desc))
25138 (if (string-match "\\.org$" desc)
25139 (setq desc (replace-match "" t t desc))))))
25140 (setq rpl (if (and file-is-image-p
25141 (or (eq t org-export-html-inline-images)
25142 (and org-export-html-inline-images
25143 (not descp))))
25144 (concat "<img src=\"" thefile "\"/>")
25145 (concat "<a href=\"" thefile "\">" desc "</a>")))
25146 (if (not valid) (setq rpl desc))))
25147 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25148 (setq rpl (concat "<i>&lt;" type ":"
25149 (save-match-data (org-link-unescape path))
25150 "&gt;</i>"))))
25151 (setq line (replace-match rpl t t line)
25152 start (+ start (length rpl))))
25154 ;; TODO items
25155 (if (and (string-match org-todo-line-regexp line)
25156 (match-beginning 2))
25158 (setq line
25159 (concat (substring line 0 (match-beginning 2))
25160 "<span class=\""
25161 (if (member (match-string 2 line)
25162 org-done-keywords)
25163 "done" "todo")
25164 "\">" (match-string 2 line)
25165 "</span>" (substring line (match-end 2)))))
25167 ;; Does this contain a reference to a footnote?
25168 (when org-export-with-footnotes
25169 (setq start 0)
25170 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25171 (if (get-text-property (match-beginning 2) 'org-protected line)
25172 (setq start (match-end 2))
25173 (let ((n (match-string 2 line)))
25174 (setq line
25175 (replace-match
25176 (format
25177 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25178 (match-string 1 line) n n n)
25179 t t line))))))
25181 (cond
25182 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25183 ;; This is a headline
25184 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25185 txt (match-string 2 line))
25186 (if (string-match quote-re0 txt)
25187 (setq txt (replace-match "" t t txt)))
25188 (if (<= level (max umax umax-toc))
25189 (setq head-count (+ head-count 1)))
25190 (when in-local-list
25191 ;; Close any local lists before inserting a new header line
25192 (while local-list-num
25193 (org-close-li)
25194 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25195 (pop local-list-num))
25196 (setq local-list-indent nil
25197 in-local-list nil))
25198 (setq first-heading-pos (or first-heading-pos (point)))
25199 (org-html-level-start level txt umax
25200 (and org-export-with-toc (<= level umax))
25201 head-count)
25202 ;; QUOTES
25203 (when (string-match quote-re line)
25204 (insert "<pre>")
25205 (setq inquote t)))
25207 ((and org-export-with-tables
25208 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25209 (if (not table-open)
25210 ;; New table starts
25211 (setq table-open t table-buffer nil table-orig-buffer nil))
25212 ;; Accumulate lines
25213 (setq table-buffer (cons line table-buffer)
25214 table-orig-buffer (cons origline table-orig-buffer))
25215 (when (or (not lines)
25216 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25217 (car lines))))
25218 (setq table-open nil
25219 table-buffer (nreverse table-buffer)
25220 table-orig-buffer (nreverse table-orig-buffer))
25221 (org-close-par-maybe)
25222 (insert (org-format-table-html table-buffer table-orig-buffer))))
25224 ;; Normal lines
25225 (when (string-match
25226 (cond
25227 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25228 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25229 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25230 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25231 line)
25232 (setq ind (org-get-string-indentation line)
25233 start-is-num (match-beginning 4)
25234 starter (if (match-beginning 2)
25235 (substring (match-string 2 line) 0 -1))
25236 line (substring line (match-beginning 5)))
25237 (unless (string-match "[^ \t]" line)
25238 ;; empty line. Pretend indentation is large.
25239 (setq ind (if org-empty-line-terminates-plain-lists
25241 (1+ (or (car local-list-indent) 1)))))
25242 (setq didclose nil)
25243 (while (and in-local-list
25244 (or (and (= ind (car local-list-indent))
25245 (not starter))
25246 (< ind (car local-list-indent))))
25247 (setq didclose t)
25248 (org-close-li)
25249 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25250 (pop local-list-num) (pop local-list-indent)
25251 (setq in-local-list local-list-indent))
25252 (cond
25253 ((and starter
25254 (or (not in-local-list)
25255 (> ind (car local-list-indent))))
25256 ;; Start new (level of) list
25257 (org-close-par-maybe)
25258 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25259 (push start-is-num local-list-num)
25260 (push ind local-list-indent)
25261 (setq in-local-list t))
25262 (starter
25263 ;; continue current list
25264 (org-close-li)
25265 (insert "<li>\n"))
25266 (didclose
25267 ;; we did close a list, normal text follows: need <p>
25268 (org-open-par)))
25269 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25270 (setq line
25271 (replace-match
25272 (if (equal (match-string 1 line) "X")
25273 "<b>[X]</b>"
25274 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25275 t t line))))
25277 ;; Empty lines start a new paragraph. If hand-formatted lists
25278 ;; are not fully interpreted, lines starting with "-", "+", "*"
25279 ;; also start a new paragraph.
25280 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25282 ;; Is this the start of a footnote?
25283 (when org-export-with-footnotes
25284 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25285 (org-close-par-maybe)
25286 (let ((n (match-string 1 line)))
25287 (setq line (replace-match
25288 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25290 ;; Check if the line break needs to be conserved
25291 (cond
25292 ((string-match "\\\\\\\\[ \t]*$" line)
25293 (setq line (replace-match "<br/>" t t line)))
25294 (org-export-preserve-breaks
25295 (setq line (concat line "<br/>"))))
25297 (insert line "\n")))))
25299 ;; Properly close all local lists and other lists
25300 (when inquote (insert "</pre>\n"))
25301 (when in-local-list
25302 ;; Close any local lists before inserting a new header line
25303 (while local-list-num
25304 (org-close-li)
25305 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25306 (pop local-list-num))
25307 (setq local-list-indent nil
25308 in-local-list nil))
25309 (org-html-level-start 1 nil umax
25310 (and org-export-with-toc (<= level umax))
25311 head-count)
25313 (unless body-only
25314 (when (plist-get opt-plist :auto-postamble)
25315 (insert "<div id=\"postamble\">")
25316 (when (and org-export-author-info author)
25317 (insert "<p class=\"author\"> "
25318 (nth 1 lang-words) ": " author "\n")
25319 (when email
25320 (if (listp (split-string email ",+ *"))
25321 (mapc (lambda(e)
25322 (insert "<a href=\"mailto:" e "\">&lt;"
25323 e "&gt;</a>\n"))
25324 (split-string email ",+ *"))
25325 (insert "<a href=\"mailto:" email "\">&lt;"
25326 email "&gt;</a>\n")))
25327 (insert "</p>\n"))
25328 (when (and date org-export-time-stamp-file)
25329 (insert "<p class=\"date\"> "
25330 (nth 2 lang-words) ": "
25331 date "</p>\n"))
25332 (insert "</div>"))
25334 (if org-export-html-with-timestamp
25335 (insert org-export-html-html-helper-timestamp))
25336 (insert (or (plist-get opt-plist :postamble) ""))
25337 (insert "</body>\n</html>\n"))
25339 (normal-mode)
25340 (if (eq major-mode default-major-mode) (html-mode))
25342 ;; insert the table of contents
25343 (goto-char (point-min))
25344 (when thetoc
25345 (if (or (re-search-forward
25346 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25347 (re-search-forward
25348 "\\[TABLE-OF-CONTENTS\\]" nil t))
25349 (progn
25350 (goto-char (match-beginning 0))
25351 (replace-match ""))
25352 (goto-char first-heading-pos)
25353 (when (looking-at "\\s-*</p>")
25354 (goto-char (match-end 0))
25355 (insert "\n")))
25356 (insert "<div id=\"table-of-contents\">\n")
25357 (mapc 'insert thetoc)
25358 (insert "</div>\n"))
25359 ;; remove empty paragraphs and lists
25360 (goto-char (point-min))
25361 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25362 (replace-match ""))
25363 (goto-char (point-min))
25364 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25365 (replace-match ""))
25366 ;; Convert whitespace place holders
25367 (goto-char (point-min))
25368 (let (beg end n)
25369 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25370 (setq n (get-text-property beg 'org-whitespace)
25371 end (next-single-property-change beg 'org-whitespace))
25372 (goto-char beg)
25373 (delete-region beg end)
25374 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25375 (make-string n ?x)))))
25377 (or to-buffer (save-buffer))
25378 (goto-char (point-min))
25379 (message "Exporting... done")
25380 (if (eq to-buffer 'string)
25381 (prog1 (buffer-substring (point-min) (point-max))
25382 (kill-buffer (current-buffer)))
25383 (current-buffer)))))
25385 (defvar org-table-colgroup-info nil)
25386 (defun org-format-table-ascii (lines)
25387 "Format a table for ascii export."
25388 (if (stringp lines)
25389 (setq lines (org-split-string lines "\n")))
25390 (if (not (string-match "^[ \t]*|" (car lines)))
25391 ;; Table made by table.el - test for spanning
25392 lines
25394 ;; A normal org table
25395 ;; Get rid of hlines at beginning and end
25396 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25397 (setq lines (nreverse lines))
25398 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25399 (setq lines (nreverse lines))
25400 (when org-export-table-remove-special-lines
25401 ;; Check if the table has a marking column. If yes remove the
25402 ;; column and the special lines
25403 (setq lines (org-table-clean-before-export lines)))
25404 ;; Get rid of the vertical lines except for grouping
25405 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25406 rtn line vl1 start)
25407 (while (setq line (pop lines))
25408 (if (string-match org-table-hline-regexp line)
25409 (and (string-match "|\\(.*\\)|" line)
25410 (setq line (replace-match " \\1" t nil line)))
25411 (setq start 0 vl1 vl)
25412 (while (string-match "|" line start)
25413 (setq start (match-end 0))
25414 (or (pop vl1) (setq line (replace-match " " t t line)))))
25415 (push line rtn))
25416 (nreverse rtn))))
25418 (defun org-colgroup-info-to-vline-list (info)
25419 (let (vl new last)
25420 (while info
25421 (setq last new new (pop info))
25422 (if (or (memq last '(:end :startend))
25423 (memq new '(:start :startend)))
25424 (push t vl)
25425 (push nil vl)))
25426 (setq vl (nreverse vl))
25427 (and vl (setcar vl nil))
25428 vl))
25430 (defun org-format-table-html (lines olines)
25431 "Find out which HTML converter to use and return the HTML code."
25432 (if (stringp lines)
25433 (setq lines (org-split-string lines "\n")))
25434 (if (string-match "^[ \t]*|" (car lines))
25435 ;; A normal org table
25436 (org-format-org-table-html lines)
25437 ;; Table made by table.el - test for spanning
25438 (let* ((hlines (delq nil (mapcar
25439 (lambda (x)
25440 (if (string-match "^[ \t]*\\+-" x) x
25441 nil))
25442 lines)))
25443 (first (car hlines))
25444 (ll (and (string-match "\\S-+" first)
25445 (match-string 0 first)))
25446 (re (concat "^[ \t]*" (regexp-quote ll)))
25447 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25448 hlines))))
25449 (if (and (not spanning)
25450 (not org-export-prefer-native-exporter-for-tables))
25451 ;; We can use my own converter with HTML conversions
25452 (org-format-table-table-html lines)
25453 ;; Need to use the code generator in table.el, with the original text.
25454 (org-format-table-table-html-using-table-generate-source olines)))))
25456 (defun org-format-org-table-html (lines &optional splice)
25457 "Format a table into HTML."
25458 ;; Get rid of hlines at beginning and end
25459 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25460 (setq lines (nreverse lines))
25461 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25462 (setq lines (nreverse lines))
25463 (when org-export-table-remove-special-lines
25464 ;; Check if the table has a marking column. If yes remove the
25465 ;; column and the special lines
25466 (setq lines (org-table-clean-before-export lines)))
25468 (let ((head (and org-export-highlight-first-table-line
25469 (delq nil (mapcar
25470 (lambda (x) (string-match "^[ \t]*|-" x))
25471 (cdr lines)))))
25472 (nlines 0) fnum i
25473 tbopen line fields html gr colgropen)
25474 (if splice (setq head nil))
25475 (unless splice (push (if head "<thead>" "<tbody>") html))
25476 (setq tbopen t)
25477 (while (setq line (pop lines))
25478 (catch 'next-line
25479 (if (string-match "^[ \t]*|-" line)
25480 (progn
25481 (unless splice
25482 (push (if head "</thead>" "</tbody>") html)
25483 (if lines (push "<tbody>" html) (setq tbopen nil)))
25484 (setq head nil) ;; head ends here, first time around
25485 ;; ignore this line
25486 (throw 'next-line t)))
25487 ;; Break the line into fields
25488 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25489 (unless fnum (setq fnum (make-vector (length fields) 0)))
25490 (setq nlines (1+ nlines) i -1)
25491 (push (concat "<tr>"
25492 (mapconcat
25493 (lambda (x)
25494 (setq i (1+ i))
25495 (if (and (< i nlines)
25496 (string-match org-table-number-regexp x))
25497 (incf (aref fnum i)))
25498 (if head
25499 (concat (car org-export-table-header-tags) x
25500 (cdr org-export-table-header-tags))
25501 (concat (car org-export-table-data-tags) x
25502 (cdr org-export-table-data-tags))))
25503 fields "")
25504 "</tr>")
25505 html)))
25506 (unless splice (if tbopen (push "</tbody>" html)))
25507 (unless splice (push "</table>\n" html))
25508 (setq html (nreverse html))
25509 (unless splice
25510 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25511 (push (mapconcat
25512 (lambda (x)
25513 (setq gr (pop org-table-colgroup-info))
25514 (format "%s<col align=\"%s\"></col>%s"
25515 (if (memq gr '(:start :startend))
25516 (prog1
25517 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25518 (setq colgropen t))
25520 (if (> (/ (float x) nlines) org-table-number-fraction)
25521 "right" "left")
25522 (if (memq gr '(:end :startend))
25523 (progn (setq colgropen nil) "</colgroup>")
25524 "")))
25525 fnum "")
25526 html)
25527 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25528 (push html-table-tag html))
25529 (concat (mapconcat 'identity html "\n") "\n")))
25531 (defun org-table-clean-before-export (lines)
25532 "Check if the table has a marking column.
25533 If yes remove the column and the special lines."
25534 (setq org-table-colgroup-info nil)
25535 (if (memq nil
25536 (mapcar
25537 (lambda (x) (or (string-match "^[ \t]*|-" x)
25538 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25539 lines))
25540 (progn
25541 (setq org-table-clean-did-remove-column nil)
25542 (delq nil
25543 (mapcar
25544 (lambda (x)
25545 (cond
25546 ((string-match "^[ \t]*| */ *|" x)
25547 (setq org-table-colgroup-info
25548 (mapcar (lambda (x)
25549 (cond ((member x '("<" "&lt;")) :start)
25550 ((member x '(">" "&gt;")) :end)
25551 ((member x '("<>" "&lt;&gt;")) :startend)
25552 (t nil)))
25553 (org-split-string x "[ \t]*|[ \t]*")))
25554 nil)
25555 (t x)))
25556 lines)))
25557 (setq org-table-clean-did-remove-column t)
25558 (delq nil
25559 (mapcar
25560 (lambda (x)
25561 (cond
25562 ((string-match "^[ \t]*| */ *|" x)
25563 (setq org-table-colgroup-info
25564 (mapcar (lambda (x)
25565 (cond ((member x '("<" "&lt;")) :start)
25566 ((member x '(">" "&gt;")) :end)
25567 ((member x '("<>" "&lt;&gt;")) :startend)
25568 (t nil)))
25569 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25570 nil)
25571 ((string-match "^[ \t]*| *[!_^/] *|" x)
25572 nil) ; ignore this line
25573 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25574 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25575 ;; remove the first column
25576 (replace-match "\\1|" t nil x))))
25577 lines))))
25579 (defun org-format-table-table-html (lines)
25580 "Format a table generated by table.el into HTML.
25581 This conversion does *not* use `table-generate-source' from table.el.
25582 This has the advantage that Org-mode's HTML conversions can be used.
25583 But it has the disadvantage, that no cell- or row-spanning is allowed."
25584 (let (line field-buffer
25585 (head org-export-highlight-first-table-line)
25586 fields html empty)
25587 (setq html (concat html-table-tag "\n"))
25588 (while (setq line (pop lines))
25589 (setq empty "&nbsp;")
25590 (catch 'next-line
25591 (if (string-match "^[ \t]*\\+-" line)
25592 (progn
25593 (if field-buffer
25594 (progn
25595 (setq
25596 html
25597 (concat
25598 html
25599 "<tr>"
25600 (mapconcat
25601 (lambda (x)
25602 (if (equal x "") (setq x empty))
25603 (if head
25604 (concat (car org-export-table-header-tags) x
25605 (cdr org-export-table-header-tags))
25606 (concat (car org-export-table-data-tags) x
25607 (cdr org-export-table-data-tags))))
25608 field-buffer "\n")
25609 "</tr>\n"))
25610 (setq head nil)
25611 (setq field-buffer nil)))
25612 ;; Ignore this line
25613 (throw 'next-line t)))
25614 ;; Break the line into fields and store the fields
25615 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25616 (if field-buffer
25617 (setq field-buffer (mapcar
25618 (lambda (x)
25619 (concat x "<br/>" (pop fields)))
25620 field-buffer))
25621 (setq field-buffer fields))))
25622 (setq html (concat html "</table>\n"))
25623 html))
25625 (defun org-format-table-table-html-using-table-generate-source (lines)
25626 "Format a table into html, using `table-generate-source' from table.el.
25627 This has the advantage that cell- or row-spanning is allowed.
25628 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25629 (require 'table)
25630 (with-current-buffer (get-buffer-create " org-tmp1 ")
25631 (erase-buffer)
25632 (insert (mapconcat 'identity lines "\n"))
25633 (goto-char (point-min))
25634 (if (not (re-search-forward "|[^+]" nil t))
25635 (error "Error processing table"))
25636 (table-recognize-table)
25637 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25638 (table-generate-source 'html " org-tmp2 ")
25639 (set-buffer " org-tmp2 ")
25640 (buffer-substring (point-min) (point-max))))
25642 (defun org-html-handle-time-stamps (s)
25643 "Format time stamps in string S, or remove them."
25644 (catch 'exit
25645 (let (r b)
25646 (while (string-match org-maybe-keyword-time-regexp s)
25647 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25648 ;; never export CLOCK
25649 (throw 'exit ""))
25650 (or b (setq b (substring s 0 (match-beginning 0))))
25651 (if (not org-export-with-timestamps)
25652 (setq r (concat r (substring s 0 (match-beginning 0)))
25653 s (substring s (match-end 0)))
25654 (setq r (concat
25655 r (substring s 0 (match-beginning 0))
25656 (if (match-end 1)
25657 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25658 (match-string 1 s)))
25659 (format " @<span class=\"timestamp\">%s@</span>"
25660 (substring
25661 (org-translate-time (match-string 3 s)) 1 -1)))
25662 s (substring s (match-end 0)))))
25663 ;; Line break if line started and ended with time stamp stuff
25664 (if (not r)
25666 (setq r (concat r s))
25667 (unless (string-match "\\S-" (concat b s))
25668 (setq r (concat r "@<br/>")))
25669 r))))
25671 (defun org-html-protect (s)
25672 ;; convert & to &amp;, < to &lt; and > to &gt;
25673 (let ((start 0))
25674 (while (string-match "&" s start)
25675 (setq s (replace-match "&amp;" t t s)
25676 start (1+ (match-beginning 0))))
25677 (while (string-match "<" s)
25678 (setq s (replace-match "&lt;" t t s)))
25679 (while (string-match ">" s)
25680 (setq s (replace-match "&gt;" t t s))))
25683 (defun org-export-cleanup-toc-line (s)
25684 "Remove tags and time staps from lines going into the toc."
25685 (when (memq org-export-with-tags '(not-in-toc nil))
25686 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25687 (setq s (replace-match "" t t s))))
25688 (when org-export-remove-timestamps-from-toc
25689 (while (string-match org-maybe-keyword-time-regexp s)
25690 (setq s (replace-match "" t t s))))
25691 (while (string-match org-bracket-link-regexp s)
25692 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25693 t t s)))
25696 (defun org-html-expand (string)
25697 "Prepare STRING for HTML export. Applies all active conversions.
25698 If there are links in the string, don't modify these."
25699 (let* ((re (concat org-bracket-link-regexp "\\|"
25700 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25701 m s l res)
25702 (while (setq m (string-match re string))
25703 (setq s (substring string 0 m)
25704 l (match-string 0 string)
25705 string (substring string (match-end 0)))
25706 (push (org-html-do-expand s) res)
25707 (push l res))
25708 (push (org-html-do-expand string) res)
25709 (apply 'concat (nreverse res))))
25711 (defun org-html-do-expand (s)
25712 "Apply all active conversions to translate special ASCII to HTML."
25713 (setq s (org-html-protect s))
25714 (if org-export-html-expand
25715 (let ((start 0))
25716 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25717 (setq s (replace-match "<\\1>" t nil s)))))
25718 (if org-export-with-emphasize
25719 (setq s (org-export-html-convert-emphasize s)))
25720 (if org-export-with-special-strings
25721 (setq s (org-export-html-convert-special-strings s)))
25722 (if org-export-with-sub-superscripts
25723 (setq s (org-export-html-convert-sub-super s)))
25724 (if org-export-with-TeX-macros
25725 (let ((start 0) wd ass)
25726 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25727 (if (get-text-property (match-beginning 0) 'org-protected s)
25728 (setq start (match-end 0))
25729 (setq wd (match-string 1 s))
25730 (if (setq ass (assoc wd org-html-entities))
25731 (setq s (replace-match (or (cdr ass)
25732 (concat "&" (car ass) ";"))
25733 t t s))
25734 (setq start (+ start (length wd))))))))
25737 (defun org-create-multibrace-regexp (left right n)
25738 "Create a regular expression which will match a balanced sexp.
25739 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25740 as single character strings.
25741 The regexp returned will match the entire expression including the
25742 delimiters. It will also define a single group which contains the
25743 match except for the outermost delimiters. The maximum depth of
25744 stacked delimiters is N. Escaping delimiters is not possible."
25745 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25746 (or "\\|")
25747 (re nothing)
25748 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25749 (while (> n 1)
25750 (setq n (1- n)
25751 re (concat re or next)
25752 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25753 (concat left "\\(" re "\\)" right)))
25755 (defvar org-match-substring-regexp
25756 (concat
25757 "\\([^\\]\\)\\([_^]\\)\\("
25758 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25759 "\\|"
25760 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25761 "\\|"
25762 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25763 "The regular expression matching a sub- or superscript.")
25765 (defvar org-match-substring-with-braces-regexp
25766 (concat
25767 "\\([^\\]\\)\\([_^]\\)\\("
25768 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25769 "\\)")
25770 "The regular expression matching a sub- or superscript, forcing braces.")
25772 (defconst org-export-html-special-string-regexps
25773 '(("\\\\-" . "&shy;")
25774 ("---\\([^-]\\)" . "&mdash;\\1")
25775 ("--\\([^-]\\)" . "&ndash;\\1")
25776 ("\\.\\.\\." . "&hellip;"))
25777 "Regular expressions for special string conversion.")
25779 (defun org-export-html-convert-special-strings (string)
25780 "Convert special characters in STRING to HTML."
25781 (let ((all org-export-html-special-string-regexps)
25782 e a re rpl start)
25783 (while (setq a (pop all))
25784 (setq re (car a) rpl (cdr a) start 0)
25785 (while (string-match re string start)
25786 (if (get-text-property (match-beginning 0) 'org-protected string)
25787 (setq start (match-end 0))
25788 (setq string (replace-match rpl t nil string)))))
25789 string))
25791 (defun org-export-html-convert-sub-super (string)
25792 "Convert sub- and superscripts in STRING to HTML."
25793 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25794 (while (string-match org-match-substring-regexp string s)
25795 (cond
25796 ((and requireb (match-end 8)) (setq s (match-end 2)))
25797 ((get-text-property (match-beginning 2) 'org-protected string)
25798 (setq s (match-end 2)))
25800 (setq s (match-end 1)
25801 key (if (string= (match-string 2 string) "_") "sub" "sup")
25802 c (or (match-string 8 string)
25803 (match-string 6 string)
25804 (match-string 5 string))
25805 string (replace-match
25806 (concat (match-string 1 string)
25807 "<" key ">" c "</" key ">")
25808 t t string)))))
25809 (while (string-match "\\\\\\([_^]\\)" string)
25810 (setq string (replace-match (match-string 1 string) t t string)))
25811 string))
25813 (defun org-export-html-convert-emphasize (string)
25814 "Apply emphasis."
25815 (let ((s 0) rpl)
25816 (while (string-match org-emph-re string s)
25817 (if (not (equal
25818 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25819 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25820 (setq s (match-beginning 0)
25822 (concat
25823 (match-string 1 string)
25824 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25825 (match-string 4 string)
25826 (nth 3 (assoc (match-string 3 string)
25827 org-emphasis-alist))
25828 (match-string 5 string))
25829 string (replace-match rpl t t string)
25830 s (+ s (- (length rpl) 2)))
25831 (setq s (1+ s))))
25832 string))
25834 (defvar org-par-open nil)
25835 (defun org-open-par ()
25836 "Insert <p>, but first close previous paragraph if any."
25837 (org-close-par-maybe)
25838 (insert "\n<p>")
25839 (setq org-par-open t))
25840 (defun org-close-par-maybe ()
25841 "Close paragraph if there is one open."
25842 (when org-par-open
25843 (insert "</p>")
25844 (setq org-par-open nil)))
25845 (defun org-close-li ()
25846 "Close <li> if necessary."
25847 (org-close-par-maybe)
25848 (insert "</li>\n"))
25850 (defvar body-only) ; dynamically scoped into this.
25851 (defun org-html-level-start (level title umax with-toc head-count)
25852 "Insert a new level in HTML export.
25853 When TITLE is nil, just close all open levels."
25854 (org-close-par-maybe)
25855 (let ((l org-level-max))
25856 (while (>= l level)
25857 (if (aref org-levels-open (1- l))
25858 (progn
25859 (org-html-level-close l umax)
25860 (aset org-levels-open (1- l) nil)))
25861 (setq l (1- l)))
25862 (when title
25863 ;; If title is nil, this means this function is called to close
25864 ;; all levels, so the rest is done only if title is given
25865 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25866 (setq title (replace-match
25867 (if org-export-with-tags
25868 (save-match-data
25869 (concat
25870 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25871 (mapconcat 'identity (org-split-string
25872 (match-string 1 title) ":")
25873 "&nbsp;")
25874 "</span>"))
25876 t t title)))
25877 (if (> level umax)
25878 (progn
25879 (if (aref org-levels-open (1- level))
25880 (progn
25881 (org-close-li)
25882 (insert "<li>" title "<br/>\n"))
25883 (aset org-levels-open (1- level) t)
25884 (org-close-par-maybe)
25885 (insert "<ul>\n<li>" title "<br/>\n")))
25886 (aset org-levels-open (1- level) t)
25887 (if (and org-export-with-section-numbers (not body-only))
25888 (setq title (concat (org-section-number level) " " title)))
25889 (setq level (+ level org-export-html-toplevel-hlevel -1))
25890 (if with-toc
25891 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25892 level level head-count title level))
25893 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25894 (org-open-par)))))
25896 (defun org-html-level-close (level max-outline-level)
25897 "Terminate one level in HTML export."
25898 (if (<= level max-outline-level)
25899 (insert "</div>\n")
25900 (org-close-li)
25901 (insert "</ul>\n")))
25903 ;;; iCalendar export
25905 ;;;###autoload
25906 (defun org-export-icalendar-this-file ()
25907 "Export current file as an iCalendar file.
25908 The iCalendar file will be located in the same directory as the Org-mode
25909 file, but with extension `.ics'."
25910 (interactive)
25911 (org-export-icalendar nil buffer-file-name))
25913 ;;;###autoload
25914 (defun org-export-icalendar-all-agenda-files ()
25915 "Export all files in `org-agenda-files' to iCalendar .ics files.
25916 Each iCalendar file will be located in the same directory as the Org-mode
25917 file, but with extension `.ics'."
25918 (interactive)
25919 (apply 'org-export-icalendar nil (org-agenda-files t)))
25921 ;;;###autoload
25922 (defun org-export-icalendar-combine-agenda-files ()
25923 "Export all files in `org-agenda-files' to a single combined iCalendar file.
25924 The file is stored under the name `org-combined-agenda-icalendar-file'."
25925 (interactive)
25926 (apply 'org-export-icalendar t (org-agenda-files t)))
25928 (defun org-export-icalendar (combine &rest files)
25929 "Create iCalendar files for all elements of FILES.
25930 If COMBINE is non-nil, combine all calendar entries into a single large
25931 file and store it under the name `org-combined-agenda-icalendar-file'."
25932 (save-excursion
25933 (org-prepare-agenda-buffers files)
25934 (let* ((dir (org-export-directory
25935 :ical (list :publishing-directory
25936 org-export-publishing-directory)))
25937 file ical-file ical-buffer category started org-agenda-new-buffers)
25939 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
25940 (when combine
25941 (setq ical-file
25942 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
25943 org-combined-agenda-icalendar-file
25944 (expand-file-name org-combined-agenda-icalendar-file dir))
25945 ical-buffer (org-get-agenda-file-buffer ical-file))
25946 (set-buffer ical-buffer) (erase-buffer))
25947 (while (setq file (pop files))
25948 (catch 'nextfile
25949 (org-check-agenda-file file)
25950 (set-buffer (org-get-agenda-file-buffer file))
25951 (unless combine
25952 (setq ical-file (concat (file-name-as-directory dir)
25953 (file-name-sans-extension
25954 (file-name-nondirectory buffer-file-name))
25955 ".ics"))
25956 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
25957 (with-current-buffer ical-buffer (erase-buffer)))
25958 (setq category (or org-category
25959 (file-name-sans-extension
25960 (file-name-nondirectory buffer-file-name))))
25961 (if (symbolp category) (setq category (symbol-name category)))
25962 (let ((standard-output ical-buffer))
25963 (if combine
25964 (and (not started) (setq started t)
25965 (org-start-icalendar-file org-icalendar-combined-name))
25966 (org-start-icalendar-file category))
25967 (org-print-icalendar-entries combine)
25968 (when (or (and combine (not files)) (not combine))
25969 (org-finish-icalendar-file)
25970 (set-buffer ical-buffer)
25971 (save-buffer)
25972 (run-hooks 'org-after-save-iCalendar-file-hook)))))
25973 (org-release-buffers org-agenda-new-buffers))))
25975 (defvar org-after-save-iCalendar-file-hook nil
25976 "Hook run after an iCalendar file has been saved.
25977 The iCalendar buffer is still current when this hook is run.
25978 A good way to use this is to tell a desktop calenndar application to re-read
25979 the iCalendar file.")
25981 (defun org-print-icalendar-entries (&optional combine)
25982 "Print iCalendar entries for the current Org-mode file to `standard-output'.
25983 When COMBINE is non nil, add the category to each line."
25984 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
25985 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
25986 (dts (org-ical-ts-to-string
25987 (format-time-string (cdr org-time-stamp-formats) (current-time))
25988 "DTSTART"))
25989 hd ts ts2 state status (inc t) pos b sexp rrule
25990 scheduledp deadlinep tmp pri category entry location summary desc
25991 (sexp-buffer (get-buffer-create "*ical-tmp*")))
25992 (org-refresh-category-properties)
25993 (save-excursion
25994 (goto-char (point-min))
25995 (while (re-search-forward re1 nil t)
25996 (catch :skip
25997 (org-agenda-skip)
25998 (setq pos (match-beginning 0)
25999 ts (match-string 0)
26000 inc t
26001 hd (org-get-heading)
26002 summary (org-icalendar-cleanup-string
26003 (org-entry-get nil "SUMMARY"))
26004 desc (org-icalendar-cleanup-string
26005 (or (org-entry-get nil "DESCRIPTION")
26006 (and org-icalendar-include-body (org-get-entry)))
26007 t org-icalendar-include-body)
26008 location (org-icalendar-cleanup-string
26009 (org-entry-get nil "LOCATION"))
26010 category (org-get-category))
26011 (if (looking-at re2)
26012 (progn
26013 (goto-char (match-end 0))
26014 (setq ts2 (match-string 1) inc nil))
26015 (setq tmp (buffer-substring (max (point-min)
26016 (- pos org-ds-keyword-length))
26017 pos)
26018 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26019 (progn
26020 (setq inc nil)
26021 (replace-match "\\1" t nil ts))
26023 deadlinep (string-match org-deadline-regexp tmp)
26024 scheduledp (string-match org-scheduled-regexp tmp)
26025 ;; donep (org-entry-is-done-p)
26027 (if (or (string-match org-tr-regexp hd)
26028 (string-match org-ts-regexp hd))
26029 (setq hd (replace-match "" t t hd)))
26030 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26031 (setq rrule
26032 (concat "\nRRULE:FREQ="
26033 (cdr (assoc
26034 (match-string 2 ts)
26035 '(("d" . "DAILY")("w" . "WEEKLY")
26036 ("m" . "MONTHLY")("y" . "YEARLY"))))
26037 ";INTERVAL=" (match-string 1 ts)))
26038 (setq rrule ""))
26039 (setq summary (or summary hd))
26040 (if (string-match org-bracket-link-regexp summary)
26041 (setq summary
26042 (replace-match (if (match-end 3)
26043 (match-string 3 summary)
26044 (match-string 1 summary))
26045 t t summary)))
26046 (if deadlinep (setq summary (concat "DL: " summary)))
26047 (if scheduledp (setq summary (concat "S: " summary)))
26048 (if (string-match "\\`<%%" ts)
26049 (with-current-buffer sexp-buffer
26050 (insert (substring ts 1 -1) " " summary "\n"))
26051 (princ (format "BEGIN:VEVENT
26053 %s%s
26054 SUMMARY:%s%s%s
26055 CATEGORIES:%s
26056 END:VEVENT\n"
26057 (org-ical-ts-to-string ts "DTSTART")
26058 (org-ical-ts-to-string ts2 "DTEND" inc)
26059 rrule summary
26060 (if (and desc (string-match "\\S-" desc))
26061 (concat "\nDESCRIPTION: " desc) "")
26062 (if (and location (string-match "\\S-" location))
26063 (concat "\nLOCATION: " location) "")
26064 category)))))
26066 (when (and org-icalendar-include-sexps
26067 (condition-case nil (require 'icalendar) (error nil))
26068 (fboundp 'icalendar-export-region))
26069 ;; Get all the literal sexps
26070 (goto-char (point-min))
26071 (while (re-search-forward "^&?%%(" nil t)
26072 (catch :skip
26073 (org-agenda-skip)
26074 (setq b (match-beginning 0))
26075 (goto-char (1- (match-end 0)))
26076 (forward-sexp 1)
26077 (end-of-line 1)
26078 (setq sexp (buffer-substring b (point)))
26079 (with-current-buffer sexp-buffer
26080 (insert sexp "\n"))
26081 (princ (org-diary-to-ical-string sexp-buffer)))))
26083 (when org-icalendar-include-todo
26084 (goto-char (point-min))
26085 (while (re-search-forward org-todo-line-regexp nil t)
26086 (catch :skip
26087 (org-agenda-skip)
26088 (setq state (match-string 2))
26089 (setq status (if (member state org-done-keywords)
26090 "COMPLETED" "NEEDS-ACTION"))
26091 (when (and state
26092 (or (not (member state org-done-keywords))
26093 (eq org-icalendar-include-todo 'all))
26094 (not (member org-archive-tag (org-get-tags-at)))
26096 (setq hd (match-string 3)
26097 summary (org-icalendar-cleanup-string
26098 (org-entry-get nil "SUMMARY"))
26099 desc (org-icalendar-cleanup-string
26100 (or (org-entry-get nil "DESCRIPTION")
26101 (and org-icalendar-include-body (org-get-entry)))
26102 t org-icalendar-include-body)
26103 location (org-icalendar-cleanup-string
26104 (org-entry-get nil "LOCATION")))
26105 (if (string-match org-bracket-link-regexp hd)
26106 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26107 (match-string 1 hd))
26108 t t hd)))
26109 (if (string-match org-priority-regexp hd)
26110 (setq pri (string-to-char (match-string 2 hd))
26111 hd (concat (substring hd 0 (match-beginning 1))
26112 (substring hd (match-end 1))))
26113 (setq pri org-default-priority))
26114 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26115 (- org-lowest-priority org-highest-priority))))))
26117 (princ (format "BEGIN:VTODO
26119 SUMMARY:%s%s%s
26120 CATEGORIES:%s
26121 SEQUENCE:1
26122 PRIORITY:%d
26123 STATUS:%s
26124 END:VTODO\n"
26126 (or summary hd)
26127 (if (and location (string-match "\\S-" location))
26128 (concat "\nLOCATION: " location) "")
26129 (if (and desc (string-match "\\S-" desc))
26130 (concat "\nDESCRIPTION: " desc) "")
26131 category pri status)))))))))
26133 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26134 "Take out stuff and quote what needs to be quoted.
26135 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26136 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26137 characters."
26138 (if (not s)
26140 (when is-body
26141 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26142 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26143 (while (string-match re s) (setq s (replace-match "" t t s)))
26144 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26145 (let ((start 0))
26146 (while (string-match "\\([,;\\]\\)" s start)
26147 (setq start (+ (match-beginning 0) 2)
26148 s (replace-match "\\\\\\1" nil nil s))))
26149 (when is-body
26150 (while (string-match "[ \t]*\n[ \t]*" s)
26151 (setq s (replace-match "\\n" t t s))))
26152 (setq s (org-trim s))
26153 (if is-body
26154 (if maxlength
26155 (if (and (numberp maxlength)
26156 (> (length s) maxlength))
26157 (setq s (substring s 0 maxlength)))))
26160 (defun org-get-entry ()
26161 "Clean-up description string."
26162 (save-excursion
26163 (org-back-to-heading t)
26164 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26166 (defun org-start-icalendar-file (name)
26167 "Start an iCalendar file by inserting the header."
26168 (let ((user user-full-name)
26169 (name (or name "unknown"))
26170 (timezone (cadr (current-time-zone))))
26171 (princ
26172 (format "BEGIN:VCALENDAR
26173 VERSION:2.0
26174 X-WR-CALNAME:%s
26175 PRODID:-//%s//Emacs with Org-mode//EN
26176 X-WR-TIMEZONE:%s
26177 CALSCALE:GREGORIAN\n" name user timezone))))
26179 (defun org-finish-icalendar-file ()
26180 "Finish an iCalendar file by inserting the END statement."
26181 (princ "END:VCALENDAR\n"))
26183 (defun org-ical-ts-to-string (s keyword &optional inc)
26184 "Take a time string S and convert it to iCalendar format.
26185 KEYWORD is added in front, to make a complete line like DTSTART....
26186 When INC is non-nil, increase the hour by two (if time string contains
26187 a time), or the day by one (if it does not contain a time)."
26188 (let ((t1 (org-parse-time-string s 'nodefault))
26189 t2 fmt have-time time)
26190 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26191 (setq t2 t1 have-time t)
26192 (setq t2 (org-parse-time-string s)))
26193 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26194 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26195 (when inc
26196 (if have-time
26197 (if org-agenda-default-appointment-duration
26198 (setq mi (+ org-agenda-default-appointment-duration mi))
26199 (setq h (+ 2 h)))
26200 (setq d (1+ d))))
26201 (setq time (encode-time s mi h d m y)))
26202 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26203 (concat keyword (format-time-string fmt time))))
26205 ;;; XOXO export
26207 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26208 (with-current-buffer buffer
26209 (apply 'insert output)))
26210 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26212 (defun org-export-as-xoxo (&optional buffer)
26213 "Export the org buffer as XOXO.
26214 The XOXO buffer is named *xoxo-<source buffer name>*"
26215 (interactive (list (current-buffer)))
26216 ;; A quickie abstraction
26218 ;; Output everything as XOXO
26219 (with-current-buffer (get-buffer buffer)
26220 (let* ((pos (point))
26221 (opt-plist (org-combine-plists (org-default-export-plist)
26222 (org-infile-export-plist)))
26223 (filename (concat (file-name-as-directory
26224 (org-export-directory :xoxo opt-plist))
26225 (file-name-sans-extension
26226 (file-name-nondirectory buffer-file-name))
26227 ".html"))
26228 (out (find-file-noselect filename))
26229 (last-level 1)
26230 (hanging-li nil))
26231 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26232 ;; Check the output buffer is empty.
26233 (with-current-buffer out (erase-buffer))
26234 ;; Kick off the output
26235 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26236 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26237 (let* ((hd (match-string-no-properties 1))
26238 (level (length hd))
26239 (text (concat
26240 (match-string-no-properties 2)
26241 (save-excursion
26242 (goto-char (match-end 0))
26243 (let ((str ""))
26244 (catch 'loop
26245 (while 't
26246 (forward-line)
26247 (if (looking-at "^[ \t]\\(.*\\)")
26248 (setq str (concat str (match-string-no-properties 1)))
26249 (throw 'loop str)))))))))
26251 ;; Handle level rendering
26252 (cond
26253 ((> level last-level)
26254 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26256 ((< level last-level)
26257 (dotimes (- (- last-level level) 1)
26258 (if hanging-li
26259 (org-export-as-xoxo-insert-into out "</li>\n"))
26260 (org-export-as-xoxo-insert-into out "</ol>\n"))
26261 (when hanging-li
26262 (org-export-as-xoxo-insert-into out "</li>\n")
26263 (setq hanging-li nil)))
26265 ((equal level last-level)
26266 (if hanging-li
26267 (org-export-as-xoxo-insert-into out "</li>\n")))
26270 (setq last-level level)
26272 ;; And output the new li
26273 (setq hanging-li 't)
26274 (if (equal ?+ (elt text 0))
26275 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26276 (org-export-as-xoxo-insert-into out "<li>" text))))
26278 ;; Finally finish off the ol
26279 (dotimes (- last-level 1)
26280 (if hanging-li
26281 (org-export-as-xoxo-insert-into out "</li>\n"))
26282 (org-export-as-xoxo-insert-into out "</ol>\n"))
26284 (goto-char pos)
26285 ;; Finish the buffer off and clean it up.
26286 (switch-to-buffer-other-window out)
26287 (indent-region (point-min) (point-max) nil)
26288 (save-buffer)
26289 (goto-char (point-min))
26293 ;;;; Key bindings
26295 ;; Make `C-c C-x' a prefix key
26296 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26298 ;; TAB key with modifiers
26299 (org-defkey org-mode-map "\C-i" 'org-cycle)
26300 (org-defkey org-mode-map [(tab)] 'org-cycle)
26301 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26302 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26303 (org-defkey org-mode-map "\M-\t" 'org-complete)
26304 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26305 ;; The following line is necessary under Suse GNU/Linux
26306 (unless (featurep 'xemacs)
26307 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26308 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26309 (define-key org-mode-map [backtab] 'org-shifttab)
26311 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26312 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26313 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26315 ;; Cursor keys with modifiers
26316 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26317 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26318 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26319 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26321 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26322 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26323 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26324 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26326 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26327 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26328 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26329 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26331 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26332 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26334 ;;; Extra keys for tty access.
26335 ;; We only set them when really needed because otherwise the
26336 ;; menus don't show the simple keys
26338 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26339 (not window-system))
26340 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26341 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26342 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26343 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26344 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26345 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26346 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26347 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26348 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26349 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26350 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26351 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26352 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26353 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26354 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26355 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26356 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26357 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26358 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26359 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26360 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26361 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26363 ;; All the other keys
26365 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26366 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26367 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26368 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26369 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26370 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26371 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26372 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26373 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26374 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26375 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26376 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26377 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26378 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26379 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26380 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26381 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26382 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26383 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26384 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26385 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26386 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26387 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26388 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26389 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26390 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26391 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26392 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26393 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26394 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26395 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26396 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26397 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26398 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26399 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26400 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26401 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26402 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26403 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26404 (org-defkey org-mode-map "\C-c^" 'org-sort)
26405 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26406 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26407 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26408 (org-defkey org-mode-map "\C-m" 'org-return)
26409 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26410 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26411 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26412 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26413 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26414 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26415 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26416 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26417 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26418 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26419 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26420 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26421 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26422 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26423 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26424 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26425 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26427 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26428 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26429 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26430 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26432 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26433 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26434 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26435 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26436 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26437 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26438 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26439 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26440 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26441 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26442 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26443 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26445 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26447 (when (featurep 'xemacs)
26448 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26450 (defsubst org-table-p () (org-at-table-p))
26452 (defun org-self-insert-command (N)
26453 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26454 If the cursor is in a table looking at whitespace, the whitespace is
26455 overwritten, and the table is not marked as requiring realignment."
26456 (interactive "p")
26457 (if (and (org-table-p)
26458 (progn
26459 ;; check if we blank the field, and if that triggers align
26460 (and org-table-auto-blank-field
26461 (member last-command
26462 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26463 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26464 ;; got extra space, this field does not determine column width
26465 (let (org-table-may-need-update) (org-table-blank-field))
26466 ;; no extra space, this field may determine column width
26467 (org-table-blank-field)))
26469 (eq N 1)
26470 (looking-at "[^|\n]* |"))
26471 (let (org-table-may-need-update)
26472 (goto-char (1- (match-end 0)))
26473 (delete-backward-char 1)
26474 (goto-char (match-beginning 0))
26475 (self-insert-command N))
26476 (setq org-table-may-need-update t)
26477 (self-insert-command N)
26478 (org-fix-tags-on-the-fly)))
26480 (defun org-fix-tags-on-the-fly ()
26481 (when (and (equal (char-after (point-at-bol)) ?*)
26482 (org-on-heading-p))
26483 (org-align-tags-here org-tags-column)))
26485 (defun org-delete-backward-char (N)
26486 "Like `delete-backward-char', insert whitespace at field end in tables.
26487 When deleting backwards, in tables this function will insert whitespace in
26488 front of the next \"|\" separator, to keep the table aligned. The table will
26489 still be marked for re-alignment if the field did fill the entire column,
26490 because, in this case the deletion might narrow the column."
26491 (interactive "p")
26492 (if (and (org-table-p)
26493 (eq N 1)
26494 (string-match "|" (buffer-substring (point-at-bol) (point)))
26495 (looking-at ".*?|"))
26496 (let ((pos (point))
26497 (noalign (looking-at "[^|\n\r]* |"))
26498 (c org-table-may-need-update))
26499 (backward-delete-char N)
26500 (skip-chars-forward "^|")
26501 (insert " ")
26502 (goto-char (1- pos))
26503 ;; noalign: if there were two spaces at the end, this field
26504 ;; does not determine the width of the column.
26505 (if noalign (setq org-table-may-need-update c)))
26506 (backward-delete-char N)
26507 (org-fix-tags-on-the-fly)))
26509 (defun org-delete-char (N)
26510 "Like `delete-char', but insert whitespace at field end in tables.
26511 When deleting characters, in tables this function will insert whitespace in
26512 front of the next \"|\" separator, to keep the table aligned. The table will
26513 still be marked for re-alignment if the field did fill the entire column,
26514 because, in this case the deletion might narrow the column."
26515 (interactive "p")
26516 (if (and (org-table-p)
26517 (not (bolp))
26518 (not (= (char-after) ?|))
26519 (eq N 1))
26520 (if (looking-at ".*?|")
26521 (let ((pos (point))
26522 (noalign (looking-at "[^|\n\r]* |"))
26523 (c org-table-may-need-update))
26524 (replace-match (concat
26525 (substring (match-string 0) 1 -1)
26526 " |"))
26527 (goto-char pos)
26528 ;; noalign: if there were two spaces at the end, this field
26529 ;; does not determine the width of the column.
26530 (if noalign (setq org-table-may-need-update c)))
26531 (delete-char N))
26532 (delete-char N)
26533 (org-fix-tags-on-the-fly)))
26535 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26536 (put 'org-self-insert-command 'delete-selection t)
26537 (put 'orgtbl-self-insert-command 'delete-selection t)
26538 (put 'org-delete-char 'delete-selection 'supersede)
26539 (put 'org-delete-backward-char 'delete-selection 'supersede)
26541 ;; Make `flyspell-mode' delay after some commands
26542 (put 'org-self-insert-command 'flyspell-delayed t)
26543 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26544 (put 'org-delete-char 'flyspell-delayed t)
26545 (put 'org-delete-backward-char 'flyspell-delayed t)
26547 ;; Make pabbrev-mode expand after org-mode commands
26548 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26549 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26551 ;; How to do this: Measure non-white length of current string
26552 ;; If equal to column width, we should realign.
26554 (defun org-remap (map &rest commands)
26555 "In MAP, remap the functions given in COMMANDS.
26556 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26557 (let (new old)
26558 (while commands
26559 (setq old (pop commands) new (pop commands))
26560 (if (fboundp 'command-remapping)
26561 (org-defkey map (vector 'remap old) new)
26562 (substitute-key-definition old new map global-map)))))
26564 (when (eq org-enable-table-editor 'optimized)
26565 ;; If the user wants maximum table support, we need to hijack
26566 ;; some standard editing functions
26567 (org-remap org-mode-map
26568 'self-insert-command 'org-self-insert-command
26569 'delete-char 'org-delete-char
26570 'delete-backward-char 'org-delete-backward-char)
26571 (org-defkey org-mode-map "|" 'org-force-self-insert))
26573 (defun org-shiftcursor-error ()
26574 "Throw an error because Shift-Cursor command was applied in wrong context."
26575 (error "This command is active in special context like tables, headlines or timestamps"))
26577 (defun org-shifttab (&optional arg)
26578 "Global visibility cycling or move to previous table field.
26579 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26580 on context.
26581 See the individual commands for more information."
26582 (interactive "P")
26583 (cond
26584 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26585 (arg (message "Content view to level: ")
26586 (org-content (prefix-numeric-value arg))
26587 (setq org-cycle-global-status 'overview))
26588 (t (call-interactively 'org-global-cycle))))
26590 (defun org-shiftmetaleft ()
26591 "Promote subtree or delete table column.
26592 Calls `org-promote-subtree', `org-outdent-item',
26593 or `org-table-delete-column', depending on context.
26594 See the individual commands for more information."
26595 (interactive)
26596 (cond
26597 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26598 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26599 ((org-at-item-p) (call-interactively 'org-outdent-item))
26600 (t (org-shiftcursor-error))))
26602 (defun org-shiftmetaright ()
26603 "Demote subtree or insert table column.
26604 Calls `org-demote-subtree', `org-indent-item',
26605 or `org-table-insert-column', depending on context.
26606 See the individual commands for more information."
26607 (interactive)
26608 (cond
26609 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26610 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26611 ((org-at-item-p) (call-interactively 'org-indent-item))
26612 (t (org-shiftcursor-error))))
26614 (defun org-shiftmetaup (&optional arg)
26615 "Move subtree up or kill table row.
26616 Calls `org-move-subtree-up' or `org-table-kill-row' or
26617 `org-move-item-up' depending on context. See the individual commands
26618 for more information."
26619 (interactive "P")
26620 (cond
26621 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26622 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26623 ((org-at-item-p) (call-interactively 'org-move-item-up))
26624 (t (org-shiftcursor-error))))
26625 (defun org-shiftmetadown (&optional arg)
26626 "Move subtree down or insert table row.
26627 Calls `org-move-subtree-down' or `org-table-insert-row' or
26628 `org-move-item-down', depending on context. See the individual
26629 commands for more information."
26630 (interactive "P")
26631 (cond
26632 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26633 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26634 ((org-at-item-p) (call-interactively 'org-move-item-down))
26635 (t (org-shiftcursor-error))))
26637 (defun org-metaleft (&optional arg)
26638 "Promote heading or move table column to left.
26639 Calls `org-do-promote' or `org-table-move-column', depending on context.
26640 With no specific context, calls the Emacs default `backward-word'.
26641 See the individual commands for more information."
26642 (interactive "P")
26643 (cond
26644 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26645 ((or (org-on-heading-p) (org-region-active-p))
26646 (call-interactively 'org-do-promote))
26647 ((org-at-item-p) (call-interactively 'org-outdent-item))
26648 (t (call-interactively 'backward-word))))
26650 (defun org-metaright (&optional arg)
26651 "Demote subtree or move table column to right.
26652 Calls `org-do-demote' or `org-table-move-column', depending on context.
26653 With no specific context, calls the Emacs default `forward-word'.
26654 See the individual commands for more information."
26655 (interactive "P")
26656 (cond
26657 ((org-at-table-p) (call-interactively 'org-table-move-column))
26658 ((or (org-on-heading-p) (org-region-active-p))
26659 (call-interactively 'org-do-demote))
26660 ((org-at-item-p) (call-interactively 'org-indent-item))
26661 (t (call-interactively 'forward-word))))
26663 (defun org-metaup (&optional arg)
26664 "Move subtree up or move table row up.
26665 Calls `org-move-subtree-up' or `org-table-move-row' or
26666 `org-move-item-up', depending on context. See the individual commands
26667 for more information."
26668 (interactive "P")
26669 (cond
26670 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26671 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26672 ((org-at-item-p) (call-interactively 'org-move-item-up))
26673 (t (transpose-lines 1) (beginning-of-line -1))))
26675 (defun org-metadown (&optional arg)
26676 "Move subtree down or move table row down.
26677 Calls `org-move-subtree-down' or `org-table-move-row' or
26678 `org-move-item-down', depending on context. See the individual
26679 commands for more information."
26680 (interactive "P")
26681 (cond
26682 ((org-at-table-p) (call-interactively 'org-table-move-row))
26683 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26684 ((org-at-item-p) (call-interactively 'org-move-item-down))
26685 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26687 (defun org-shiftup (&optional arg)
26688 "Increase item in timestamp or increase priority of current headline.
26689 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26690 depending on context. See the individual commands for more information."
26691 (interactive "P")
26692 (cond
26693 ((org-at-timestamp-p t)
26694 (call-interactively (if org-edit-timestamp-down-means-later
26695 'org-timestamp-down 'org-timestamp-up)))
26696 ((org-on-heading-p) (call-interactively 'org-priority-up))
26697 ((org-at-item-p) (call-interactively 'org-previous-item))
26698 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26700 (defun org-shiftdown (&optional arg)
26701 "Decrease item in timestamp or decrease priority of current headline.
26702 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26703 depending on context. See the individual commands for more information."
26704 (interactive "P")
26705 (cond
26706 ((org-at-timestamp-p t)
26707 (call-interactively (if org-edit-timestamp-down-means-later
26708 'org-timestamp-up 'org-timestamp-down)))
26709 ((org-on-heading-p) (call-interactively 'org-priority-down))
26710 (t (call-interactively 'org-next-item))))
26712 (defun org-shiftright ()
26713 "Next TODO keyword or timestamp one day later, depending on context."
26714 (interactive)
26715 (cond
26716 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26717 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26718 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26719 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26720 (t (org-shiftcursor-error))))
26722 (defun org-shiftleft ()
26723 "Previous TODO keyword or timestamp one day earlier, depending on context."
26724 (interactive)
26725 (cond
26726 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26727 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26728 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26729 ((org-at-property-p)
26730 (call-interactively 'org-property-previous-allowed-value))
26731 (t (org-shiftcursor-error))))
26733 (defun org-shiftcontrolright ()
26734 "Switch to next TODO set."
26735 (interactive)
26736 (cond
26737 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26738 (t (org-shiftcursor-error))))
26740 (defun org-shiftcontrolleft ()
26741 "Switch to previous TODO set."
26742 (interactive)
26743 (cond
26744 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26745 (t (org-shiftcursor-error))))
26747 (defun org-ctrl-c-ret ()
26748 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26749 (interactive)
26750 (cond
26751 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26752 (t (call-interactively 'org-insert-heading))))
26754 (defun org-copy-special ()
26755 "Copy region in table or copy current subtree.
26756 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26757 See the individual commands for more information."
26758 (interactive)
26759 (call-interactively
26760 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26762 (defun org-cut-special ()
26763 "Cut region in table or cut current subtree.
26764 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26765 See the individual commands for more information."
26766 (interactive)
26767 (call-interactively
26768 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26770 (defun org-paste-special (arg)
26771 "Paste rectangular region into table, or past subtree relative to level.
26772 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26773 See the individual commands for more information."
26774 (interactive "P")
26775 (if (org-at-table-p)
26776 (org-table-paste-rectangle)
26777 (org-paste-subtree arg)))
26779 (defun org-ctrl-c-ctrl-c (&optional arg)
26780 "Set tags in headline, or update according to changed information at point.
26782 This command does many different things, depending on context:
26784 - If the cursor is in a headline, prompt for tags and insert them
26785 into the current line, aligned to `org-tags-column'. When called
26786 with prefix arg, realign all tags in the current buffer.
26788 - If the cursor is in one of the special #+KEYWORD lines, this
26789 triggers scanning the buffer for these lines and updating the
26790 information.
26792 - If the cursor is inside a table, realign the table. This command
26793 works even if the automatic table editor has been turned off.
26795 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26796 the entire table.
26798 - If the cursor is a the beginning of a dynamic block, update it.
26800 - If the cursor is inside a table created by the table.el package,
26801 activate that table.
26803 - If the current buffer is a remember buffer, close note and file it.
26804 with a prefix argument, file it without further interaction to the default
26805 location.
26807 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26808 links in this buffer.
26810 - If the cursor is on a numbered item in a plain list, renumber the
26811 ordered list.
26813 - If the cursor is on a checkbox, toggle it."
26814 (interactive "P")
26815 (let ((org-enable-table-editor t))
26816 (cond
26817 ((or org-clock-overlays
26818 org-occur-highlights
26819 org-latex-fragment-image-overlays)
26820 (org-remove-clock-overlays)
26821 (org-remove-occur-highlights)
26822 (org-remove-latex-fragment-image-overlays)
26823 (message "Temporary highlights/overlays removed from current buffer"))
26824 ((and (local-variable-p 'org-finish-function (current-buffer))
26825 (fboundp org-finish-function))
26826 (funcall org-finish-function))
26827 ((org-at-property-p)
26828 (call-interactively 'org-property-action))
26829 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26830 ((org-on-heading-p) (call-interactively 'org-set-tags))
26831 ((org-at-table.el-p)
26832 (require 'table)
26833 (beginning-of-line 1)
26834 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26835 (call-interactively 'table-recognize-table))
26836 ((org-at-table-p)
26837 (org-table-maybe-eval-formula)
26838 (if arg
26839 (call-interactively 'org-table-recalculate)
26840 (org-table-maybe-recalculate-line))
26841 (call-interactively 'org-table-align))
26842 ((org-at-item-checkbox-p)
26843 (call-interactively 'org-toggle-checkbox))
26844 ((org-at-item-p)
26845 (call-interactively 'org-maybe-renumber-ordered-list))
26846 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26847 ;; Dynamic block
26848 (beginning-of-line 1)
26849 (org-update-dblock))
26850 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26851 (cond
26852 ((equal (match-string 1) "TBLFM")
26853 ;; Recalculate the table before this line
26854 (save-excursion
26855 (beginning-of-line 1)
26856 (skip-chars-backward " \r\n\t")
26857 (if (org-at-table-p)
26858 (org-call-with-arg 'org-table-recalculate t))))
26860 (call-interactively 'org-mode-restart))))
26861 (t (error "C-c C-c can do nothing useful at this location.")))))
26863 (defun org-mode-restart ()
26864 "Restart Org-mode, to scan again for special lines.
26865 Also updates the keyword regular expressions."
26866 (interactive)
26867 (let ((org-inhibit-startup t)) (org-mode))
26868 (message "Org-mode restarted to refresh keyword and special line setup"))
26870 (defun org-kill-note-or-show-branches ()
26871 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26872 (interactive)
26873 (if (not org-finish-function)
26874 (call-interactively 'show-branches)
26875 (let ((org-note-abort t))
26876 (funcall org-finish-function))))
26878 (defun org-return (&optional indent)
26879 "Goto next table row or insert a newline.
26880 Calls `org-table-next-row' or `newline', depending on context.
26881 See the individual commands for more information."
26882 (interactive)
26883 (cond
26884 ((bobp) (if indent (newline-and-indent) (newline)))
26885 ((org-at-table-p)
26886 (org-table-justify-field-maybe)
26887 (call-interactively 'org-table-next-row))
26888 (t (if indent (newline-and-indent) (newline)))))
26890 (defun org-return-indent ()
26891 (interactive)
26892 "Goto next table row or insert a newline and indent.
26893 Calls `org-table-next-row' or `newline-and-indent', depending on
26894 context. See the individual commands for more information."
26895 (org-return t))
26897 (defun org-ctrl-c-minus ()
26898 "Insert separator line in table or modify bullet type in list.
26899 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26900 depending on context."
26901 (interactive)
26902 (cond
26903 ((org-at-table-p)
26904 (call-interactively 'org-table-insert-hline))
26905 ((org-on-heading-p)
26906 ;; Convert to item
26907 (save-excursion
26908 (beginning-of-line 1)
26909 (if (looking-at "\\*+ ")
26910 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26911 ((org-in-item-p)
26912 (call-interactively 'org-cycle-list-bullet))
26913 (t (error "`C-c -' does have no function here."))))
26915 (defun org-meta-return (&optional arg)
26916 "Insert a new heading or wrap a region in a table.
26917 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
26918 See the individual commands for more information."
26919 (interactive "P")
26920 (cond
26921 ((org-at-table-p)
26922 (call-interactively 'org-table-wrap-region))
26923 (t (call-interactively 'org-insert-heading))))
26925 ;;; Menu entries
26927 ;; Define the Org-mode menus
26928 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
26929 '("Tbl"
26930 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
26931 ["Next Field" org-cycle (org-at-table-p)]
26932 ["Previous Field" org-shifttab (org-at-table-p)]
26933 ["Next Row" org-return (org-at-table-p)]
26934 "--"
26935 ["Blank Field" org-table-blank-field (org-at-table-p)]
26936 ["Edit Field" org-table-edit-field (org-at-table-p)]
26937 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
26938 "--"
26939 ("Column"
26940 ["Move Column Left" org-metaleft (org-at-table-p)]
26941 ["Move Column Right" org-metaright (org-at-table-p)]
26942 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
26943 ["Insert Column" org-shiftmetaright (org-at-table-p)])
26944 ("Row"
26945 ["Move Row Up" org-metaup (org-at-table-p)]
26946 ["Move Row Down" org-metadown (org-at-table-p)]
26947 ["Delete Row" org-shiftmetaup (org-at-table-p)]
26948 ["Insert Row" org-shiftmetadown (org-at-table-p)]
26949 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
26950 "--"
26951 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
26952 ("Rectangle"
26953 ["Copy Rectangle" org-copy-special (org-at-table-p)]
26954 ["Cut Rectangle" org-cut-special (org-at-table-p)]
26955 ["Paste Rectangle" org-paste-special (org-at-table-p)]
26956 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
26957 "--"
26958 ("Calculate"
26959 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
26960 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
26961 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
26962 "--"
26963 ["Recalculate line" org-table-recalculate (org-at-table-p)]
26964 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
26965 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
26966 "--"
26967 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
26968 "--"
26969 ["Sum Column/Rectangle" org-table-sum
26970 (or (org-at-table-p) (org-region-active-p))]
26971 ["Which Column?" org-table-current-column (org-at-table-p)])
26972 ["Debug Formulas"
26973 org-table-toggle-formula-debugger
26974 :style toggle :selected org-table-formula-debug]
26975 ["Show Col/Row Numbers"
26976 org-table-toggle-coordinate-overlays
26977 :style toggle :selected org-table-overlay-coordinates]
26978 "--"
26979 ["Create" org-table-create (and (not (org-at-table-p))
26980 org-enable-table-editor)]
26981 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
26982 ["Import from File" org-table-import (not (org-at-table-p))]
26983 ["Export to File" org-table-export (org-at-table-p)]
26984 "--"
26985 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
26987 (easy-menu-define org-org-menu org-mode-map "Org menu"
26988 '("Org"
26989 ("Show/Hide"
26990 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
26991 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
26992 ["Sparse Tree" org-occur t]
26993 ["Reveal Context" org-reveal t]
26994 ["Show All" show-all t]
26995 "--"
26996 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
26997 "--"
26998 ["New Heading" org-insert-heading t]
26999 ("Navigate Headings"
27000 ["Up" outline-up-heading t]
27001 ["Next" outline-next-visible-heading t]
27002 ["Previous" outline-previous-visible-heading t]
27003 ["Next Same Level" outline-forward-same-level t]
27004 ["Previous Same Level" outline-backward-same-level t]
27005 "--"
27006 ["Jump" org-goto t])
27007 ("Edit Structure"
27008 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27009 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27010 "--"
27011 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27012 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27013 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27014 "--"
27015 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27016 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27017 ["Demote Heading" org-metaright (not (org-at-table-p))]
27018 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27019 "--"
27020 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27021 "--"
27022 ["Convert to odd levels" org-convert-to-odd-levels t]
27023 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27024 ("Editing"
27025 ["Emphasis..." org-emphasize t])
27026 ("Archive"
27027 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27028 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27029 ; :active t :keys "C-u C-c C-x C-a"]
27030 ["Sparse trees open ARCHIVE trees"
27031 (setq org-sparse-tree-open-archived-trees
27032 (not org-sparse-tree-open-archived-trees))
27033 :style toggle :selected org-sparse-tree-open-archived-trees]
27034 ["Cycling opens ARCHIVE trees"
27035 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27036 :style toggle :selected org-cycle-open-archived-trees]
27037 ["Agenda includes ARCHIVE trees"
27038 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27039 :style toggle :selected (not org-agenda-skip-archived-trees)]
27040 "--"
27041 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27042 ; ["Check and Move Children" (org-archive-subtree '(4))
27043 ; :active t :keys "C-u C-c C-x C-s"]
27045 "--"
27046 ("TODO Lists"
27047 ["TODO/DONE/-" org-todo t]
27048 ("Select keyword"
27049 ["Next keyword" org-shiftright (org-on-heading-p)]
27050 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27051 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27052 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27053 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27054 ["Show TODO Tree" org-show-todo-tree t]
27055 ["Global TODO list" org-todo-list t]
27056 "--"
27057 ["Set Priority" org-priority t]
27058 ["Priority Up" org-shiftup t]
27059 ["Priority Down" org-shiftdown t])
27060 ("TAGS and Properties"
27061 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27062 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27063 "--"
27064 ["Set property" 'org-set-property t]
27065 ["Column view of properties" org-columns t]
27066 ["Insert Column View DBlock" org-insert-columns-dblock t])
27067 ("Dates and Scheduling"
27068 ["Timestamp" org-time-stamp t]
27069 ["Timestamp (inactive)" org-time-stamp-inactive t]
27070 ("Change Date"
27071 ["1 Day Later" org-shiftright t]
27072 ["1 Day Earlier" org-shiftleft t]
27073 ["1 ... Later" org-shiftup t]
27074 ["1 ... Earlier" org-shiftdown t])
27075 ["Compute Time Range" org-evaluate-time-range t]
27076 ["Schedule Item" org-schedule t]
27077 ["Deadline" org-deadline t]
27078 "--"
27079 ["Custom time format" org-toggle-time-stamp-overlays
27080 :style radio :selected org-display-custom-times]
27081 "--"
27082 ["Goto Calendar" org-goto-calendar t]
27083 ["Date from Calendar" org-date-from-calendar t])
27084 ("Logging work"
27085 ["Clock in" org-clock-in t]
27086 ["Clock out" org-clock-out t]
27087 ["Clock cancel" org-clock-cancel t]
27088 ["Goto running clock" org-clock-goto t]
27089 ["Display times" org-clock-display t]
27090 ["Create clock table" org-clock-report t]
27091 "--"
27092 ["Record DONE time"
27093 (progn (setq org-log-done (not org-log-done))
27094 (message "Switching to %s will %s record a timestamp"
27095 (car org-done-keywords)
27096 (if org-log-done "automatically" "not")))
27097 :style toggle :selected org-log-done])
27098 "--"
27099 ["Agenda Command..." org-agenda t]
27100 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27101 ("File List for Agenda")
27102 ("Special views current file"
27103 ["TODO Tree" org-show-todo-tree t]
27104 ["Check Deadlines" org-check-deadlines t]
27105 ["Timeline" org-timeline t]
27106 ["Tags Tree" org-tags-sparse-tree t])
27107 "--"
27108 ("Hyperlinks"
27109 ["Store Link (Global)" org-store-link t]
27110 ["Insert Link" org-insert-link t]
27111 ["Follow Link" org-open-at-point t]
27112 "--"
27113 ["Next link" org-next-link t]
27114 ["Previous link" org-previous-link t]
27115 "--"
27116 ["Descriptive Links"
27117 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27118 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27119 ["Literal Links"
27120 (progn
27121 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27122 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27123 "--"
27124 ["Export/Publish..." org-export t]
27125 ("LaTeX"
27126 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27127 :selected org-cdlatex-mode]
27128 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27129 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27130 ["Modify math symbol" org-cdlatex-math-modify
27131 (org-inside-LaTeX-fragment-p)]
27132 ["Export LaTeX fragments as images"
27133 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27134 :style toggle :selected org-export-with-LaTeX-fragments])
27135 "--"
27136 ("Documentation"
27137 ["Show Version" org-version t]
27138 ["Info Documentation" org-info t])
27139 ("Customize"
27140 ["Browse Org Group" org-customize t]
27141 "--"
27142 ["Expand This Menu" org-create-customize-menu
27143 (fboundp 'customize-menu-create)])
27144 "--"
27145 ["Refresh setup" org-mode-restart t]
27148 (defun org-info (&optional node)
27149 "Read documentation for Org-mode in the info system.
27150 With optional NODE, go directly to that node."
27151 (interactive)
27152 (require 'info)
27153 (Info-goto-node (format "(org)%s" (or node ""))))
27155 (defun org-install-agenda-files-menu ()
27156 (let ((bl (buffer-list)))
27157 (save-excursion
27158 (while bl
27159 (set-buffer (pop bl))
27160 (if (org-mode-p) (setq bl nil)))
27161 (when (org-mode-p)
27162 (easy-menu-change
27163 '("Org") "File List for Agenda"
27164 (append
27165 (list
27166 ["Edit File List" (org-edit-agenda-file-list) t]
27167 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27168 ["Remove Current File from List" org-remove-file t]
27169 ["Cycle through agenda files" org-cycle-agenda-files t]
27170 ["Occur in all agenda files" org-occur-in-agenda-files t]
27171 "--")
27172 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27174 ;;;; Documentation
27176 (defun org-customize ()
27177 "Call the customize function with org as argument."
27178 (interactive)
27179 (customize-browse 'org))
27181 (defun org-create-customize-menu ()
27182 "Create a full customization menu for Org-mode, insert it into the menu."
27183 (interactive)
27184 (if (fboundp 'customize-menu-create)
27185 (progn
27186 (easy-menu-change
27187 '("Org") "Customize"
27188 `(["Browse Org group" org-customize t]
27189 "--"
27190 ,(customize-menu-create 'org)
27191 ["Set" Custom-set t]
27192 ["Save" Custom-save t]
27193 ["Reset to Current" Custom-reset-current t]
27194 ["Reset to Saved" Custom-reset-saved t]
27195 ["Reset to Standard Settings" Custom-reset-standard t]))
27196 (message "\"Org\"-menu now contains full customization menu"))
27197 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27199 ;;;; Miscellaneous stuff
27202 ;;; Generally useful functions
27204 (defun org-context ()
27205 "Return a list of contexts of the current cursor position.
27206 If several contexts apply, all are returned.
27207 Each context entry is a list with a symbol naming the context, and
27208 two positions indicating start and end of the context. Possible
27209 contexts are:
27211 :headline anywhere in a headline
27212 :headline-stars on the leading stars in a headline
27213 :todo-keyword on a TODO keyword (including DONE) in a headline
27214 :tags on the TAGS in a headline
27215 :priority on the priority cookie in a headline
27216 :item on the first line of a plain list item
27217 :item-bullet on the bullet/number of a plain list item
27218 :checkbox on the checkbox in a plain list item
27219 :table in an org-mode table
27220 :table-special on a special filed in a table
27221 :table-table in a table.el table
27222 :link on a hyperlink
27223 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27224 :target on a <<target>>
27225 :radio-target on a <<<radio-target>>>
27226 :latex-fragment on a LaTeX fragment
27227 :latex-preview on a LaTeX fragment with overlayed preview image
27229 This function expects the position to be visible because it uses font-lock
27230 faces as a help to recognize the following contexts: :table-special, :link,
27231 and :keyword."
27232 (let* ((f (get-text-property (point) 'face))
27233 (faces (if (listp f) f (list f)))
27234 (p (point)) clist o)
27235 ;; First the large context
27236 (cond
27237 ((org-on-heading-p t)
27238 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27239 (when (progn
27240 (beginning-of-line 1)
27241 (looking-at org-todo-line-tags-regexp))
27242 (push (org-point-in-group p 1 :headline-stars) clist)
27243 (push (org-point-in-group p 2 :todo-keyword) clist)
27244 (push (org-point-in-group p 4 :tags) clist))
27245 (goto-char p)
27246 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27247 (if (looking-at "\\[#[A-Z0-9]\\]")
27248 (push (org-point-in-group p 0 :priority) clist)))
27250 ((org-at-item-p)
27251 (push (org-point-in-group p 2 :item-bullet) clist)
27252 (push (list :item (point-at-bol)
27253 (save-excursion (org-end-of-item) (point)))
27254 clist)
27255 (and (org-at-item-checkbox-p)
27256 (push (org-point-in-group p 0 :checkbox) clist)))
27258 ((org-at-table-p)
27259 (push (list :table (org-table-begin) (org-table-end)) clist)
27260 (if (memq 'org-formula faces)
27261 (push (list :table-special
27262 (previous-single-property-change p 'face)
27263 (next-single-property-change p 'face)) clist)))
27264 ((org-at-table-p 'any)
27265 (push (list :table-table) clist)))
27266 (goto-char p)
27268 ;; Now the small context
27269 (cond
27270 ((org-at-timestamp-p)
27271 (push (org-point-in-group p 0 :timestamp) clist))
27272 ((memq 'org-link faces)
27273 (push (list :link
27274 (previous-single-property-change p 'face)
27275 (next-single-property-change p 'face)) clist))
27276 ((memq 'org-special-keyword faces)
27277 (push (list :keyword
27278 (previous-single-property-change p 'face)
27279 (next-single-property-change p 'face)) clist))
27280 ((org-on-target-p)
27281 (push (org-point-in-group p 0 :target) clist)
27282 (goto-char (1- (match-beginning 0)))
27283 (if (looking-at org-radio-target-regexp)
27284 (push (org-point-in-group p 0 :radio-target) clist))
27285 (goto-char p))
27286 ((setq o (car (delq nil
27287 (mapcar
27288 (lambda (x)
27289 (if (memq x org-latex-fragment-image-overlays) x))
27290 (org-overlays-at (point))))))
27291 (push (list :latex-fragment
27292 (org-overlay-start o) (org-overlay-end o)) clist)
27293 (push (list :latex-preview
27294 (org-overlay-start o) (org-overlay-end o)) clist))
27295 ((org-inside-LaTeX-fragment-p)
27296 ;; FIXME: positions wrong.
27297 (push (list :latex-fragment (point) (point)) clist)))
27299 (setq clist (nreverse (delq nil clist)))
27300 clist))
27302 ;; FIXME: Compare with at-regexp-p Do we need both?
27303 (defun org-in-regexp (re &optional nlines visually)
27304 "Check if point is inside a match of regexp.
27305 Normally only the current line is checked, but you can include NLINES extra
27306 lines both before and after point into the search.
27307 If VISUALLY is set, require that the cursor is not after the match but
27308 really on, so that the block visually is on the match."
27309 (catch 'exit
27310 (let ((pos (point))
27311 (eol (point-at-eol (+ 1 (or nlines 0))))
27312 (inc (if visually 1 0)))
27313 (save-excursion
27314 (beginning-of-line (- 1 (or nlines 0)))
27315 (while (re-search-forward re eol t)
27316 (if (and (<= (match-beginning 0) pos)
27317 (>= (+ inc (match-end 0)) pos))
27318 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27320 (defun org-at-regexp-p (regexp)
27321 "Is point inside a match of REGEXP in the current line?"
27322 (catch 'exit
27323 (save-excursion
27324 (let ((pos (point)) (end (point-at-eol)))
27325 (beginning-of-line 1)
27326 (while (re-search-forward regexp end t)
27327 (if (and (<= (match-beginning 0) pos)
27328 (>= (match-end 0) pos))
27329 (throw 'exit t)))
27330 nil))))
27332 (defun org-occur-in-agenda-files (regexp &optional nlines)
27333 "Call `multi-occur' with buffers for all agenda files."
27334 (interactive "sOrg-files matching: \np")
27335 (let* ((files (org-agenda-files))
27336 (tnames (mapcar 'file-truename files))
27337 (extra org-agenda-multi-occur-extra-files)
27339 (while (setq f (pop extra))
27340 (unless (member (file-truename f) tnames)
27341 (add-to-list 'files f 'append)
27342 (add-to-list 'tnames (file-truename f) 'append)))
27343 (multi-occur
27344 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27345 regexp)))
27347 (if (boundp 'occur-mode-find-occurrence-hook)
27348 ;; Emacs 23
27349 (add-hook 'occur-mode-find-occurrence-hook
27350 (lambda ()
27351 (when (org-mode-p)
27352 (org-reveal))))
27353 ;; Emacs 22
27354 (defadvice occur-mode-goto-occurrence
27355 (after org-occur-reveal activate)
27356 (and (org-mode-p) (org-reveal)))
27357 (defadvice occur-mode-goto-occurrence-other-window
27358 (after org-occur-reveal activate)
27359 (and (org-mode-p) (org-reveal)))
27360 (defadvice occur-mode-display-occurrence
27361 (after org-occur-reveal activate)
27362 (when (org-mode-p)
27363 (let ((pos (occur-mode-find-occurrence)))
27364 (with-current-buffer (marker-buffer pos)
27365 (save-excursion
27366 (goto-char pos)
27367 (org-reveal)))))))
27369 (defun org-uniquify (list)
27370 "Remove duplicate elements from LIST."
27371 (let (res)
27372 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27373 res))
27375 (defun org-delete-all (elts list)
27376 "Remove all elements in ELTS from LIST."
27377 (while elts
27378 (setq list (delete (pop elts) list)))
27379 list)
27381 (defun org-back-over-empty-lines ()
27382 "Move backwards over witespace, to the beginning of the first empty line.
27383 Returns the number o empty lines passed."
27384 (let ((pos (point)))
27385 (skip-chars-backward " \t\n\r")
27386 (beginning-of-line 2)
27387 (goto-char (min (point) pos))
27388 (count-lines (point) pos)))
27390 (defun org-skip-whitespace ()
27391 (skip-chars-forward " \t\n\r"))
27393 (defun org-point-in-group (point group &optional context)
27394 "Check if POINT is in match-group GROUP.
27395 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27396 match. If the match group does ot exist or point is not inside it,
27397 return nil."
27398 (and (match-beginning group)
27399 (>= point (match-beginning group))
27400 (<= point (match-end group))
27401 (if context
27402 (list context (match-beginning group) (match-end group))
27403 t)))
27405 (defun org-switch-to-buffer-other-window (&rest args)
27406 "Switch to buffer in a second window on the current frame.
27407 In particular, do not allow pop-up frames."
27408 (let (pop-up-frames special-display-buffer-names special-display-regexps
27409 special-display-function)
27410 (apply 'switch-to-buffer-other-window args)))
27412 (defun org-combine-plists (&rest plists)
27413 "Create a single property list from all plists in PLISTS.
27414 The process starts by copying the first list, and then setting properties
27415 from the other lists. Settings in the last list are the most significant
27416 ones and overrule settings in the other lists."
27417 (let ((rtn (copy-sequence (pop plists)))
27418 p v ls)
27419 (while plists
27420 (setq ls (pop plists))
27421 (while ls
27422 (setq p (pop ls) v (pop ls))
27423 (setq rtn (plist-put rtn p v))))
27424 rtn))
27426 (defun org-move-line-down (arg)
27427 "Move the current line down. With prefix argument, move it past ARG lines."
27428 (interactive "p")
27429 (let ((col (current-column))
27430 beg end pos)
27431 (beginning-of-line 1) (setq beg (point))
27432 (beginning-of-line 2) (setq end (point))
27433 (beginning-of-line (+ 1 arg))
27434 (setq pos (move-marker (make-marker) (point)))
27435 (insert (delete-and-extract-region beg end))
27436 (goto-char pos)
27437 (move-to-column col)))
27439 (defun org-move-line-up (arg)
27440 "Move the current line up. With prefix argument, move it past ARG lines."
27441 (interactive "p")
27442 (let ((col (current-column))
27443 beg end pos)
27444 (beginning-of-line 1) (setq beg (point))
27445 (beginning-of-line 2) (setq end (point))
27446 (beginning-of-line (- arg))
27447 (setq pos (move-marker (make-marker) (point)))
27448 (insert (delete-and-extract-region beg end))
27449 (goto-char pos)
27450 (move-to-column col)))
27452 (defun org-replace-escapes (string table)
27453 "Replace %-escapes in STRING with values in TABLE.
27454 TABLE is an association list with keys like \"%a\" and string values.
27455 The sequences in STRING may contain normal field width and padding information,
27456 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27457 so values can contain further %-escapes if they are define later in TABLE."
27458 (let ((case-fold-search nil)
27459 e re rpl)
27460 (while (setq e (pop table))
27461 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27462 (while (string-match re string)
27463 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27464 (cdr e)))
27465 (setq string (replace-match rpl t t string))))
27466 string))
27469 (defun org-sublist (list start end)
27470 "Return a section of LIST, from START to END.
27471 Counting starts at 1."
27472 (let (rtn (c start))
27473 (setq list (nthcdr (1- start) list))
27474 (while (and list (<= c end))
27475 (push (pop list) rtn)
27476 (setq c (1+ c)))
27477 (nreverse rtn)))
27479 (defun org-find-base-buffer-visiting (file)
27480 "Like `find-buffer-visiting' but alway return the base buffer and
27481 not an indirect buffer"
27482 (let ((buf (find-buffer-visiting file)))
27483 (if buf
27484 (or (buffer-base-buffer buf) buf)
27485 nil)))
27487 (defun org-image-file-name-regexp ()
27488 "Return regexp matching the file names of images."
27489 (if (fboundp 'image-file-name-regexp)
27490 (image-file-name-regexp)
27491 (let ((image-file-name-extensions
27492 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27493 "xbm" "xpm" "pbm" "pgm" "ppm")))
27494 (concat "\\."
27495 (regexp-opt (nconc (mapcar 'upcase
27496 image-file-name-extensions)
27497 image-file-name-extensions)
27499 "\\'"))))
27501 (defun org-file-image-p (file)
27502 "Return non-nil if FILE is an image."
27503 (save-match-data
27504 (string-match (org-image-file-name-regexp) file)))
27506 ;;; Paragraph filling stuff.
27507 ;; We want this to be just right, so use the full arsenal.
27509 (defun org-indent-line-function ()
27510 "Indent line like previous, but further if previous was headline or item."
27511 (interactive)
27512 (let* ((pos (point))
27513 (itemp (org-at-item-p))
27514 column bpos bcol tpos tcol bullet btype bullet-type)
27515 ;; Find the previous relevant line
27516 (beginning-of-line 1)
27517 (cond
27518 ((looking-at "#") (setq column 0))
27519 ((looking-at "\\*+ ") (setq column 0))
27521 (beginning-of-line 0)
27522 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27523 (beginning-of-line 0))
27524 (cond
27525 ((looking-at "\\*+[ \t]+")
27526 (goto-char (match-end 0))
27527 (setq column (current-column)))
27528 ((org-in-item-p)
27529 (org-beginning-of-item)
27530 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27531 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27532 (setq bpos (match-beginning 1) tpos (match-end 0)
27533 bcol (progn (goto-char bpos) (current-column))
27534 tcol (progn (goto-char tpos) (current-column))
27535 bullet (match-string 1)
27536 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27537 (if (not itemp)
27538 (setq column tcol)
27539 (goto-char pos)
27540 (beginning-of-line 1)
27541 (if (looking-at "\\S-")
27542 (progn
27543 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27544 (setq bullet (match-string 1)
27545 btype (if (string-match "[0-9]" bullet) "n" bullet))
27546 (setq column (if (equal btype bullet-type) bcol tcol)))
27547 (setq column (org-get-indentation)))))
27548 (t (setq column (org-get-indentation))))))
27549 (goto-char pos)
27550 (if (<= (current-column) (current-indentation))
27551 (indent-line-to column)
27552 (save-excursion (indent-line-to column)))
27553 (setq column (current-column))
27554 (beginning-of-line 1)
27555 (if (looking-at
27556 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27557 (replace-match (concat "\\1" (format org-property-format
27558 (match-string 2) (match-string 3)))
27559 t nil))
27560 (move-to-column column)))
27562 (defun org-set-autofill-regexps ()
27563 (interactive)
27564 ;; In the paragraph separator we include headlines, because filling
27565 ;; text in a line directly attached to a headline would otherwise
27566 ;; fill the headline as well.
27567 (org-set-local 'comment-start-skip "^#+[ \t]*")
27568 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27569 ;; The paragraph starter includes hand-formatted lists.
27570 (org-set-local 'paragraph-start
27571 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27572 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27573 ;; But only if the user has not turned off tables or fixed-width regions
27574 (org-set-local
27575 'auto-fill-inhibit-regexp
27576 (concat "\\*+ \\|#\\+"
27577 "\\|[ \t]*" org-keyword-time-regexp
27578 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27579 (concat
27580 "\\|[ \t]*["
27581 (if org-enable-table-editor "|" "")
27582 (if org-enable-fixed-width-editor ":" "")
27583 "]"))))
27584 ;; We use our own fill-paragraph function, to make sure that tables
27585 ;; and fixed-width regions are not wrapped. That function will pass
27586 ;; through to `fill-paragraph' when appropriate.
27587 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27588 ; Adaptive filling: To get full control, first make sure that
27589 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27590 (org-set-local 'adaptive-fill-regexp "\000")
27591 (org-set-local 'adaptive-fill-function
27592 'org-adaptive-fill-function)
27593 (org-set-local
27594 'align-mode-rules-list
27595 '((org-in-buffer-settings
27596 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
27597 (modes . '(org-mode))))))
27599 (defun org-fill-paragraph (&optional justify)
27600 "Re-align a table, pass through to fill-paragraph if no table."
27601 (let ((table-p (org-at-table-p))
27602 (table.el-p (org-at-table.el-p)))
27603 (cond ((and (equal (char-after (point-at-bol)) ?*)
27604 (save-excursion (goto-char (point-at-bol))
27605 (looking-at outline-regexp)))
27606 t) ; skip headlines
27607 (table.el-p t) ; skip table.el tables
27608 (table-p (org-table-align) t) ; align org-mode tables
27609 (t nil)))) ; call paragraph-fill
27611 ;; For reference, this is the default value of adaptive-fill-regexp
27612 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27614 (defun org-adaptive-fill-function ()
27615 "Return a fill prefix for org-mode files.
27616 In particular, this makes sure hanging paragraphs for hand-formatted lists
27617 work correctly."
27618 (cond ((looking-at "#[ \t]+")
27619 (match-string 0))
27620 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27621 (save-excursion
27622 (goto-char (match-end 0))
27623 (make-string (current-column) ?\ )))
27624 (t nil)))
27626 ;;;; Functions extending outline functionality
27628 (defun org-beginning-of-line (&optional arg)
27629 "Go to the beginning of the current line. If that is invisible, continue
27630 to a visible line beginning. This makes the function of C-a more intuitive.
27631 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27632 first attempt, and only move to after the tags when the cursor is already
27633 beyond the end of the headline."
27634 (interactive "P")
27635 (let ((pos (point)))
27636 (beginning-of-line 1)
27637 (if (bobp)
27639 (backward-char 1)
27640 (if (org-invisible-p)
27641 (while (and (not (bobp)) (org-invisible-p))
27642 (backward-char 1)
27643 (beginning-of-line 1))
27644 (forward-char 1)))
27645 (when org-special-ctrl-a/e
27646 (cond
27647 ((and (looking-at org-todo-line-regexp)
27648 (= (char-after (match-end 1)) ?\ ))
27649 (goto-char
27650 (if (eq org-special-ctrl-a/e t)
27651 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27652 ((= pos (point)) (match-beginning 3))
27653 (t (point)))
27654 (cond ((> pos (point)) (point))
27655 ((not (eq last-command this-command)) (point))
27656 (t (match-beginning 3))))))
27657 ((org-at-item-p)
27658 (goto-char
27659 (if (eq org-special-ctrl-a/e t)
27660 (cond ((> pos (match-end 4)) (match-end 4))
27661 ((= pos (point)) (match-end 4))
27662 (t (point)))
27663 (cond ((> pos (point)) (point))
27664 ((not (eq last-command this-command)) (point))
27665 (t (match-end 4))))))))))
27667 (defun org-end-of-line (&optional arg)
27668 "Go to the end of the line.
27669 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27670 first attempt, and only move to after the tags when the cursor is already
27671 beyond the end of the headline."
27672 (interactive "P")
27673 (if (or (not org-special-ctrl-a/e)
27674 (not (org-on-heading-p)))
27675 (end-of-line arg)
27676 (let ((pos (point)))
27677 (beginning-of-line 1)
27678 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27679 (if (eq org-special-ctrl-a/e t)
27680 (if (or (< pos (match-beginning 1))
27681 (= pos (match-end 0)))
27682 (goto-char (match-beginning 1))
27683 (goto-char (match-end 0)))
27684 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27685 (goto-char (match-end 0))
27686 (goto-char (match-beginning 1))))
27687 (end-of-line arg)))))
27689 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27690 (define-key org-mode-map "\C-e" 'org-end-of-line)
27692 (defun org-invisible-p ()
27693 "Check if point is at a character currently not visible."
27694 ;; Early versions of noutline don't have `outline-invisible-p'.
27695 (if (fboundp 'outline-invisible-p)
27696 (outline-invisible-p)
27697 (get-char-property (point) 'invisible)))
27699 (defun org-invisible-p2 ()
27700 "Check if point is at a character currently not visible."
27701 (save-excursion
27702 (if (and (eolp) (not (bobp))) (backward-char 1))
27703 ;; Early versions of noutline don't have `outline-invisible-p'.
27704 (if (fboundp 'outline-invisible-p)
27705 (outline-invisible-p)
27706 (get-char-property (point) 'invisible))))
27708 (defalias 'org-back-to-heading 'outline-back-to-heading)
27709 (defalias 'org-on-heading-p 'outline-on-heading-p)
27710 (defalias 'org-at-heading-p 'outline-on-heading-p)
27711 (defun org-at-heading-or-item-p ()
27712 (or (org-on-heading-p) (org-at-item-p)))
27714 (defun org-on-target-p ()
27715 (or (org-in-regexp org-radio-target-regexp)
27716 (org-in-regexp org-target-regexp)))
27718 (defun org-up-heading-all (arg)
27719 "Move to the heading line of which the present line is a subheading.
27720 This function considers both visible and invisible heading lines.
27721 With argument, move up ARG levels."
27722 (if (fboundp 'outline-up-heading-all)
27723 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27724 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27726 (defun org-up-heading-safe ()
27727 "Move to the heading line of which the present line is a subheading.
27728 This version will not throw an error. It will return the level of the
27729 headline found, or nil if no higher level is found."
27730 (let ((pos (point)) start-level level
27731 (re (concat "^" outline-regexp)))
27732 (catch 'exit
27733 (outline-back-to-heading t)
27734 (setq start-level (funcall outline-level))
27735 (if (equal start-level 1) (throw 'exit nil))
27736 (while (re-search-backward re nil t)
27737 (setq level (funcall outline-level))
27738 (if (< level start-level) (throw 'exit level)))
27739 nil)))
27741 (defun org-first-sibling-p ()
27742 "Is this heading the first child of its parents?"
27743 (interactive)
27744 (let ((re (concat "^" outline-regexp))
27745 level l)
27746 (unless (org-at-heading-p t)
27747 (error "Not at a heading"))
27748 (setq level (funcall outline-level))
27749 (save-excursion
27750 (if (not (re-search-backward re nil t))
27752 (setq l (funcall outline-level))
27753 (< l level)))))
27755 (defun org-goto-sibling (&optional previous)
27756 "Goto the next sibling, even if it is invisible.
27757 When PREVIOUS is set, go to the previous sibling instead. Returns t
27758 when a sibling was found. When none is found, return nil and don't
27759 move point."
27760 (let ((fun (if previous 're-search-backward 're-search-forward))
27761 (pos (point))
27762 (re (concat "^" outline-regexp))
27763 level l)
27764 (when (condition-case nil (org-back-to-heading t) (error nil))
27765 (setq level (funcall outline-level))
27766 (catch 'exit
27767 (or previous (forward-char 1))
27768 (while (funcall fun re nil t)
27769 (setq l (funcall outline-level))
27770 (when (< l level) (goto-char pos) (throw 'exit nil))
27771 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27772 (goto-char pos)
27773 nil))))
27775 (defun org-show-siblings ()
27776 "Show all siblings of the current headline."
27777 (save-excursion
27778 (while (org-goto-sibling) (org-flag-heading nil)))
27779 (save-excursion
27780 (while (org-goto-sibling 'previous)
27781 (org-flag-heading nil))))
27783 (defun org-show-hidden-entry ()
27784 "Show an entry where even the heading is hidden."
27785 (save-excursion
27786 (org-show-entry)))
27788 (defun org-flag-heading (flag &optional entry)
27789 "Flag the current heading. FLAG non-nil means make invisible.
27790 When ENTRY is non-nil, show the entire entry."
27791 (save-excursion
27792 (org-back-to-heading t)
27793 ;; Check if we should show the entire entry
27794 (if entry
27795 (progn
27796 (org-show-entry)
27797 (save-excursion
27798 (and (outline-next-heading)
27799 (org-flag-heading nil))))
27800 (outline-flag-region (max (point-min) (1- (point)))
27801 (save-excursion (outline-end-of-heading) (point))
27802 flag))))
27804 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27805 ;; This is an exact copy of the original function, but it uses
27806 ;; `org-back-to-heading', to make it work also in invisible
27807 ;; trees. And is uses an invisible-OK argument.
27808 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27809 (org-back-to-heading invisible-OK)
27810 (let ((first t)
27811 (level (funcall outline-level)))
27812 (while (and (not (eobp))
27813 (or first (> (funcall outline-level) level)))
27814 (setq first nil)
27815 (outline-next-heading))
27816 (unless to-heading
27817 (if (memq (preceding-char) '(?\n ?\^M))
27818 (progn
27819 ;; Go to end of line before heading
27820 (forward-char -1)
27821 (if (memq (preceding-char) '(?\n ?\^M))
27822 ;; leave blank line before heading
27823 (forward-char -1))))))
27824 (point))
27826 (defun org-show-subtree ()
27827 "Show everything after this heading at deeper levels."
27828 (outline-flag-region
27829 (point)
27830 (save-excursion
27831 (outline-end-of-subtree) (outline-next-heading) (point))
27832 nil))
27834 (defun org-show-entry ()
27835 "Show the body directly following this heading.
27836 Show the heading too, if it is currently invisible."
27837 (interactive)
27838 (save-excursion
27839 (condition-case nil
27840 (progn
27841 (org-back-to-heading t)
27842 (outline-flag-region
27843 (max (point-min) (1- (point)))
27844 (save-excursion
27845 (re-search-forward
27846 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27847 (or (match-beginning 1) (point-max)))
27848 nil))
27849 (error nil))))
27851 (defun org-make-options-regexp (kwds)
27852 "Make a regular expression for keyword lines."
27853 (concat
27855 "#?[ \t]*\\+\\("
27856 (mapconcat 'regexp-quote kwds "\\|")
27857 "\\):[ \t]*"
27858 "\\(.+\\)"))
27860 ;; Make isearch reveal the necessary context
27861 (defun org-isearch-end ()
27862 "Reveal context after isearch exits."
27863 (when isearch-success ; only if search was successful
27864 (if (featurep 'xemacs)
27865 ;; Under XEmacs, the hook is run in the correct place,
27866 ;; we directly show the context.
27867 (org-show-context 'isearch)
27868 ;; In Emacs the hook runs *before* restoring the overlays.
27869 ;; So we have to use a one-time post-command-hook to do this.
27870 ;; (Emacs 22 has a special variable, see function `org-mode')
27871 (unless (and (boundp 'isearch-mode-end-hook-quit)
27872 isearch-mode-end-hook-quit)
27873 ;; Only when the isearch was not quitted.
27874 (org-add-hook 'post-command-hook 'org-isearch-post-command
27875 'append 'local)))))
27877 (defun org-isearch-post-command ()
27878 "Remove self from hook, and show context."
27879 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27880 (org-show-context 'isearch))
27883 ;;;; Integration with and fixes for other packages
27885 ;;; Imenu support
27887 (defvar org-imenu-markers nil
27888 "All markers currently used by Imenu.")
27889 (make-variable-buffer-local 'org-imenu-markers)
27891 (defun org-imenu-new-marker (&optional pos)
27892 "Return a new marker for use by Imenu, and remember the marker."
27893 (let ((m (make-marker)))
27894 (move-marker m (or pos (point)))
27895 (push m org-imenu-markers)
27898 (defun org-imenu-get-tree ()
27899 "Produce the index for Imenu."
27900 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
27901 (setq org-imenu-markers nil)
27902 (let* ((n org-imenu-depth)
27903 (re (concat "^" outline-regexp))
27904 (subs (make-vector (1+ n) nil))
27905 (last-level 0)
27906 m tree level head)
27907 (save-excursion
27908 (save-restriction
27909 (widen)
27910 (goto-char (point-max))
27911 (while (re-search-backward re nil t)
27912 (setq level (org-reduced-level (funcall outline-level)))
27913 (when (<= level n)
27914 (looking-at org-complex-heading-regexp)
27915 (setq head (org-match-string-no-properties 4)
27916 m (org-imenu-new-marker))
27917 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
27918 (if (>= level last-level)
27919 (push (cons head m) (aref subs level))
27920 (push (cons head (aref subs (1+ level))) (aref subs level))
27921 (loop for i from (1+ level) to n do (aset subs i nil)))
27922 (setq last-level level)))))
27923 (aref subs 1)))
27925 (eval-after-load "imenu"
27926 '(progn
27927 (add-hook 'imenu-after-jump-hook
27928 (lambda () (org-show-context 'org-goto)))))
27930 ;; Speedbar support
27932 (defun org-speedbar-set-agenda-restriction ()
27933 "Restrict future agenda commands to the location at point in speedbar.
27934 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
27935 (interactive)
27936 (let (p m tp np dir txt w)
27937 (cond
27938 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27939 'org-imenu t))
27940 (setq m (get-text-property p 'org-imenu-marker))
27941 (save-excursion
27942 (save-restriction
27943 (set-buffer (marker-buffer m))
27944 (goto-char m)
27945 (org-agenda-set-restriction-lock 'subtree))))
27946 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27947 'speedbar-function 'speedbar-find-file))
27948 (setq tp (previous-single-property-change
27949 (1+ p) 'speedbar-function)
27950 np (next-single-property-change
27951 tp 'speedbar-function)
27952 dir (speedbar-line-directory)
27953 txt (buffer-substring-no-properties (or tp (point-min))
27954 (or np (point-max))))
27955 (save-excursion
27956 (save-restriction
27957 (set-buffer (find-file-noselect
27958 (let ((default-directory dir))
27959 (expand-file-name txt))))
27960 (unless (org-mode-p)
27961 (error "Cannot restrict to non-Org-mode file"))
27962 (org-agenda-set-restriction-lock 'file))))
27963 (t (error "Don't know how to restrict Org-mode's agenda")))
27964 (org-move-overlay org-speedbar-restriction-lock-overlay
27965 (point-at-bol) (point-at-eol))
27966 (setq current-prefix-arg nil)
27967 (org-agenda-maybe-redo)))
27969 (eval-after-load "speedbar"
27970 '(progn
27971 (speedbar-add-supported-extension ".org")
27972 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
27973 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
27974 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
27975 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27976 (add-hook 'speedbar-visiting-tag-hook
27977 (lambda () (org-show-context 'org-goto)))))
27980 ;;; Fixes and Hacks
27982 ;; Make flyspell not check words in links, to not mess up our keymap
27983 (defun org-mode-flyspell-verify ()
27984 "Don't let flyspell put overlays at active buttons."
27985 (not (get-text-property (point) 'keymap)))
27987 ;; Make `bookmark-jump' show the jump location if it was hidden.
27988 (eval-after-load "bookmark"
27989 '(if (boundp 'bookmark-after-jump-hook)
27990 ;; We can use the hook
27991 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
27992 ;; Hook not available, use advice
27993 (defadvice bookmark-jump (after org-make-visible activate)
27994 "Make the position visible."
27995 (org-bookmark-jump-unhide))))
27997 (defun org-bookmark-jump-unhide ()
27998 "Unhide the current position, to show the bookmark location."
27999 (and (org-mode-p)
28000 (or (org-invisible-p)
28001 (save-excursion (goto-char (max (point-min) (1- (point))))
28002 (org-invisible-p)))
28003 (org-show-context 'bookmark-jump)))
28005 ;; Fix a bug in htmlize where there are text properties (face nil)
28006 (eval-after-load "htmlize"
28007 '(progn
28008 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28009 "Make sure there are no nil faces"
28010 (setq ad-return-value (delq nil ad-return-value)))))
28012 ;; Make session.el ignore our circular variable
28013 (eval-after-load "session"
28014 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28016 ;;;; Experimental code
28018 (defun org-closed-in-range ()
28019 "Sparse tree of items closed in a certain time range.
28020 Still experimental, may disappear in the future."
28021 (interactive)
28022 ;; Get the time interval from the user.
28023 (let* ((time1 (time-to-seconds
28024 (org-read-date nil 'to-time nil "Starting date: ")))
28025 (time2 (time-to-seconds
28026 (org-read-date nil 'to-time nil "End date:")))
28027 ;; callback function
28028 (callback (lambda ()
28029 (let ((time
28030 (time-to-seconds
28031 (apply 'encode-time
28032 (org-parse-time-string
28033 (match-string 1))))))
28034 ;; check if time in interval
28035 (and (>= time time1) (<= time time2))))))
28036 ;; make tree, check each match with the callback
28037 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28041 ;(let ((org-refile-targets org-refile-targets)
28042 ; (org-refile-use-outline-path org-refile-use-outline-path))
28043 ; (when (equal just-goto '(16))
28044 ; (setq org-refile-targets '((nil . (:maxlevel . 10))))
28045 ; (setq org-refile-use-outline-path t))
28046 ; (setq org-refile-target-table (org-get-refile-targets default-buffer)))
28048 ;;;; Finish up
28050 (provide 'org)
28052 (run-hooks 'org-load-hook)
28054 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28055 ;;; org.el ends here