Release 5.15a
[org-mode/org-tableheadings.git] / org.el
blob13a775529690fe64158189359e34a4c6cae703e7
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 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.15a
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.15a"
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-unmodified (&rest body)
102 "Execute body without changing buffer-modified-p."
103 `(set-buffer-modified-p
104 (prog1 (buffer-modified-p) ,@body)))
106 (defmacro org-re (s)
107 "Replace posix classes in regular expression."
108 (if (featurep 'xemacs)
109 (let ((ss s))
110 (save-match-data
111 (while (string-match "\\[:alnum:\\]" ss)
112 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
113 (while (string-match "\\[:alpha:\\]" ss)
114 (setq ss (replace-match "a-zA-Z" t t ss)))
115 ss))
118 (defmacro org-preserve-lc (&rest body)
119 `(let ((_line (org-current-line))
120 (_col (current-column)))
121 (unwind-protect
122 (progn ,@body)
123 (goto-line _line)
124 (move-to-column _col))))
126 (defmacro org-without-partial-completion (&rest body)
127 `(let ((pc-mode (and (boundp 'partial-completion-mode)
128 partial-completion-mode)))
129 (unwind-protect
130 (progn
131 (if pc-mode (partial-completion-mode -1))
132 ,@body)
133 (if pc-mode (partial-completion-mode 1)))))
135 ;;; The custom variables
137 (defgroup org nil
138 "Outline-based notes management and organizer."
139 :tag "Org"
140 :group 'outlines
141 :group 'hypermedia
142 :group 'calendar)
144 ;; FIXME: Needs a separate group...
145 (defcustom org-completion-fallback-command 'hippie-expand
146 "The expansion command called by \\[org-complete] in normal context.
147 Normal means, no org-mode-specific context."
148 :group 'org
149 :type 'function)
151 (defgroup org-startup nil
152 "Options concerning startup of Org-mode."
153 :tag "Org Startup"
154 :group 'org)
156 (defcustom org-startup-folded t
157 "Non-nil means, entering Org-mode will switch to OVERVIEW.
158 This can also be configured on a per-file basis by adding one of
159 the following lines anywhere in the buffer:
161 #+STARTUP: fold
162 #+STARTUP: nofold
163 #+STARTUP: content"
164 :group 'org-startup
165 :type '(choice
166 (const :tag "nofold: show all" nil)
167 (const :tag "fold: overview" t)
168 (const :tag "content: all headlines" content)))
170 (defcustom org-startup-truncated t
171 "Non-nil means, entering Org-mode will set `truncate-lines'.
172 This is useful since some lines containing links can be very long and
173 uninteresting. Also tables look terrible when wrapped."
174 :group 'org-startup
175 :type 'boolean)
177 (defcustom org-startup-align-all-tables nil
178 "Non-nil means, align all tables when visiting a file.
179 This is useful when the column width in tables is forced with <N> cookies
180 in table fields. Such tables will look correct only after the first re-align.
181 This can also be configured on a per-file basis by adding one of
182 the following lines anywhere in the buffer:
183 #+STARTUP: align
184 #+STARTUP: noalign"
185 :group 'org-startup
186 :type 'boolean)
188 (defcustom org-insert-mode-line-in-empty-file nil
189 "Non-nil means insert the first line setting Org-mode in empty files.
190 When the function `org-mode' is called interactively in an empty file, this
191 normally means that the file name does not automatically trigger Org-mode.
192 To ensure that the file will always be in Org-mode in the future, a
193 line enforcing Org-mode will be inserted into the buffer, if this option
194 has been set."
195 :group 'org-startup
196 :type 'boolean)
198 (defcustom org-replace-disputed-keys nil
199 "Non-nil means use alternative key bindings for some keys.
200 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
201 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
202 If you want to use Org-mode together with one of these other modes,
203 or more generally if you would like to move some Org-mode commands to
204 other keys, set this variable and configure the keys with the variable
205 `org-disputed-keys'.
207 This option is only relevant at load-time of Org-mode, and must be set
208 *before* org.el is loaded. Changing it requires a restart of Emacs to
209 become effective."
210 :group 'org-startup
211 :type 'boolean)
213 (if (fboundp 'defvaralias)
214 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
216 (defcustom org-disputed-keys
217 '(([(shift up)] . [(meta p)])
218 ([(shift down)] . [(meta n)])
219 ([(shift left)] . [(meta -)])
220 ([(shift right)] . [(meta +)])
221 ([(control shift right)] . [(meta shift +)])
222 ([(control shift left)] . [(meta shift -)]))
223 "Keys for which Org-mode and other modes compete.
224 This is an alist, cars are the default keys, second element specifies
225 the alternative to use when `org-replace-disputed-keys' is t.
227 Keys can be specified in any syntax supported by `define-key'.
228 The value of this option takes effect only at Org-mode's startup,
229 therefore you'll have to restart Emacs to apply it after changing."
230 :group 'org-startup
231 :type 'alist)
233 (defun org-key (key)
234 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
235 Or return the original if not disputed."
236 (if org-replace-disputed-keys
237 (let* ((nkey (key-description key))
238 (x (org-find-if (lambda (x)
239 (equal (key-description (car x)) nkey))
240 org-disputed-keys)))
241 (if x (cdr x) key))
242 key))
244 (defun org-find-if (predicate seq)
245 (catch 'exit
246 (while seq
247 (if (funcall predicate (car seq))
248 (throw 'exit (car seq))
249 (pop seq)))))
251 (defun org-defkey (keymap key def)
252 "Define a key, possibly translated, as returned by `org-key'."
253 (define-key keymap (org-key key) def))
255 (defcustom org-ellipsis nil
256 "The ellipsis to use in the Org-mode outline.
257 When nil, just use the standard three dots. When a string, use that instead,
258 When a face, use the standart 3 dots, but with the specified face.
259 The change affects only Org-mode (which will then use its own display table).
260 Changing this requires executing `M-x org-mode' in a buffer to become
261 effective."
262 :group 'org-startup
263 :type '(choice (const :tag "Default" nil)
264 (face :tag "Face" :value org-warning)
265 (string :tag "String" :value "...#")))
267 (defvar org-display-table nil
268 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
270 (defgroup org-keywords nil
271 "Keywords in Org-mode."
272 :tag "Org Keywords"
273 :group 'org)
275 (defcustom org-deadline-string "DEADLINE:"
276 "String to mark deadline entries.
277 A deadline is this string, followed by a time stamp. Should be a word,
278 terminated by a colon. You can insert a schedule keyword and
279 a timestamp with \\[org-deadline].
280 Changes become only effective after restarting Emacs."
281 :group 'org-keywords
282 :type 'string)
284 (defcustom org-scheduled-string "SCHEDULED:"
285 "String to mark scheduled TODO entries.
286 A schedule is this string, followed by a time stamp. Should be a word,
287 terminated by a colon. You can insert a schedule keyword and
288 a timestamp with \\[org-schedule].
289 Changes become only effective after restarting Emacs."
290 :group 'org-keywords
291 :type 'string)
293 (defcustom org-closed-string "CLOSED:"
294 "String used as the prefix for timestamps logging closing a TODO entry."
295 :group 'org-keywords
296 :type 'string)
298 (defcustom org-clock-string "CLOCK:"
299 "String used as prefix for timestamps clocking work hours on an item."
300 :group 'org-keywords
301 :type 'string)
303 (defcustom org-comment-string "COMMENT"
304 "Entries starting with this keyword will never be exported.
305 An entry can be toggled between COMMENT and normal with
306 \\[org-toggle-comment].
307 Changes become only effective after restarting Emacs."
308 :group 'org-keywords
309 :type 'string)
311 (defcustom org-quote-string "QUOTE"
312 "Entries starting with this keyword will be exported in fixed-width font.
313 Quoting applies only to the text in the entry following the headline, and does
314 not extend beyond the next headline, even if that is lower level.
315 An entry can be toggled between QUOTE and normal with
316 \\[org-toggle-fixed-width-section]."
317 :group 'org-keywords
318 :type 'string)
320 (defconst org-repeat-re
321 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
322 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
323 "Regular expression for specifying repeated events.
324 After a match, group 1 contains the repeat expression.")
326 (defgroup org-structure nil
327 "Options concerning the general structure of Org-mode files."
328 :tag "Org Structure"
329 :group 'org)
331 (defgroup org-reveal-location nil
332 "Options about how to make context of a location visible."
333 :tag "Org Reveal Location"
334 :group 'org-structure)
336 (defcustom org-show-hierarchy-above '((default . t))
337 "Non-nil means, show full hierarchy when revealing a location.
338 Org-mode often shows locations in an org-mode file which might have
339 been invisible before. When this is set, the hierarchy of headings
340 above the exposed location is shown.
341 Turning this off for example for sparse trees makes them very compact.
342 Instead of t, this can also be an alist specifying this option for different
343 contexts. Valid contexts are
344 agenda when exposing an entry from the agenda
345 org-goto when using the command `org-goto' on key C-c C-j
346 occur-tree when using the command `org-occur' on key C-c /
347 tags-tree when constructing a sparse tree based on tags matches
348 link-search when exposing search matches associated with a link
349 mark-goto when exposing the jump goal of a mark
350 bookmark-jump when exposing a bookmark location
351 isearch when exiting from an incremental search
352 default default for all contexts not set explicitly"
353 :group 'org-reveal-location
354 :type '(choice
355 (const :tag "Always" t)
356 (const :tag "Never" nil)
357 (repeat :greedy t :tag "Individual contexts"
358 (cons
359 (choice :tag "Context"
360 (const agenda)
361 (const org-goto)
362 (const occur-tree)
363 (const tags-tree)
364 (const link-search)
365 (const mark-goto)
366 (const bookmark-jump)
367 (const isearch)
368 (const default))
369 (boolean)))))
371 (defcustom org-show-following-heading '((default . nil))
372 "Non-nil means, show following heading when revealing a location.
373 Org-mode often shows locations in an org-mode file which might have
374 been invisible before. When this is set, the heading following the
375 match is shown.
376 Turning this off for example for sparse trees makes them very compact,
377 but makes it harder to edit the location of the match. In such a case,
378 use the command \\[org-reveal] to show more context.
379 Instead of t, this can also be an alist specifying this option for different
380 contexts. See `org-show-hierarchy-above' for valid contexts."
381 :group 'org-reveal-location
382 :type '(choice
383 (const :tag "Always" t)
384 (const :tag "Never" nil)
385 (repeat :greedy t :tag "Individual contexts"
386 (cons
387 (choice :tag "Context"
388 (const agenda)
389 (const org-goto)
390 (const occur-tree)
391 (const tags-tree)
392 (const link-search)
393 (const mark-goto)
394 (const bookmark-jump)
395 (const isearch)
396 (const default))
397 (boolean)))))
399 (defcustom org-show-siblings '((default . nil) (isearch t))
400 "Non-nil means, show all sibling heading when revealing a location.
401 Org-mode often shows locations in an org-mode file which might have
402 been invisible before. When this is set, the sibling of the current entry
403 heading are all made visible. If `org-show-hierarchy-above' is t,
404 the same happens on each level of the hierarchy above the current entry.
406 By default this is on for the isearch context, off for all other contexts.
407 Turning this off for example for sparse trees makes them very compact,
408 but makes it harder to edit the location of the match. In such a case,
409 use the command \\[org-reveal] to show more context.
410 Instead of t, this can also be an alist specifying this option for different
411 contexts. See `org-show-hierarchy-above' for valid contexts."
412 :group 'org-reveal-location
413 :type '(choice
414 (const :tag "Always" t)
415 (const :tag "Never" nil)
416 (repeat :greedy t :tag "Individual contexts"
417 (cons
418 (choice :tag "Context"
419 (const agenda)
420 (const org-goto)
421 (const occur-tree)
422 (const tags-tree)
423 (const link-search)
424 (const mark-goto)
425 (const bookmark-jump)
426 (const isearch)
427 (const default))
428 (boolean)))))
430 (defcustom org-show-entry-below '((default . nil))
431 "Non-nil means, show the entry below a headline when revealing a location.
432 Org-mode often shows locations in an org-mode file which might have
433 been invisible before. When this is set, the text below the headline that is
434 exposed is also shown.
436 By default this is off for all contexts.
437 Instead of t, this can also be an alist specifying this option for different
438 contexts. See `org-show-hierarchy-above' for valid contexts."
439 :group 'org-reveal-location
440 :type '(choice
441 (const :tag "Always" t)
442 (const :tag "Never" nil)
443 (repeat :greedy t :tag "Individual contexts"
444 (cons
445 (choice :tag "Context"
446 (const agenda)
447 (const org-goto)
448 (const occur-tree)
449 (const tags-tree)
450 (const link-search)
451 (const mark-goto)
452 (const bookmark-jump)
453 (const isearch)
454 (const default))
455 (boolean)))))
457 (defgroup org-cycle nil
458 "Options concerning visibility cycling in Org-mode."
459 :tag "Org Cycle"
460 :group 'org-structure)
462 (defcustom org-drawers '("PROPERTIES" "CLOCK")
463 "Names of drawers. Drawers are not opened by cycling on the headline above.
464 Drawers only open with a TAB on the drawer line itself. A drawer looks like
465 this:
466 :DRAWERNAME:
467 .....
468 :END:
469 The drawer \"PROPERTIES\" is special for capturing properties through
470 the property API.
472 Drawers can be defined on the per-file basis with a line like:
474 #+DRAWERS: HIDDEN STATE PROPERTIES"
475 :group 'org-structure
476 :type '(repeat (string :tag "Drawer Name")))
478 (defcustom org-cycle-global-at-bob nil
479 "Cycle globally if cursor is at beginning of buffer and not at a headline.
480 This makes it possible to do global cycling without having to use S-TAB or
481 C-u TAB. For this special case to work, the first line of the buffer
482 must not be a headline - it may be empty ot some other text. When used in
483 this way, `org-cycle-hook' is disables temporarily, to make sure the
484 cursor stays at the beginning of the buffer.
485 When this option is nil, don't do anything special at the beginning
486 of the buffer."
487 :group 'org-cycle
488 :type 'boolean)
490 (defcustom org-cycle-emulate-tab t
491 "Where should `org-cycle' emulate TAB.
492 nil Never
493 white Only in completely white lines
494 whitestart Only at the beginning of lines, before the first non-white char.
495 t Everywhere except in headlines
496 exc-hl-bol Everywhere except at the start of a headline
497 If TAB is used in a place where it does not emulate TAB, the current subtree
498 visibility is cycled."
499 :group 'org-cycle
500 :type '(choice (const :tag "Never" nil)
501 (const :tag "Only in completely white lines" white)
502 (const :tag "Before first char in a line" whitestart)
503 (const :tag "Everywhere except in headlines" t)
504 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
507 (defcustom org-cycle-separator-lines 2
508 "Number of empty lines needed to keep an empty line between collapsed trees.
509 If you leave an empty line between the end of a subtree and the following
510 headline, this empty line is hidden when the subtree is folded.
511 Org-mode will leave (exactly) one empty line visible if the number of
512 empty lines is equal or larger to the number given in this variable.
513 So the default 2 means, at least 2 empty lines after the end of a subtree
514 are needed to produce free space between a collapsed subtree and the
515 following headline.
517 Special case: when 0, never leave empty lines in collapsed view."
518 :group 'org-cycle
519 :type 'integer)
521 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
522 org-cycle-hide-drawers
523 org-cycle-show-empty-lines
524 org-optimize-window-after-visibility-change)
525 "Hook that is run after `org-cycle' has changed the buffer visibility.
526 The function(s) in this hook must accept a single argument which indicates
527 the new state that was set by the most recent `org-cycle' command. The
528 argument is a symbol. After a global state change, it can have the values
529 `overview', `content', or `all'. After a local state change, it can have
530 the values `folded', `children', or `subtree'."
531 :group 'org-cycle
532 :type 'hook)
534 (defgroup org-edit-structure nil
535 "Options concerning structure editing in Org-mode."
536 :tag "Org Edit Structure"
537 :group 'org-structure)
539 (defcustom org-special-ctrl-a/e nil
540 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
541 When t, `C-a' will bring back the cursor to the beginning of the
542 headline text, i.e. after the stars and after a possible TODO keyword.
543 In an item, this will be the position after the bullet.
544 When the cursor is already at that position, another `C-a' will bring
545 it to the beginning of the line.
546 `C-e' will jump to the end of the headline, ignoring the presence of tags
547 in the headline. A second `C-e' will then jump to the true end of the
548 line, after any tags.
549 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
550 and only a directly following, identical keypress will bring the cursor
551 to the special positions."
552 :group 'org-edit-structure
553 :type '(choice
554 (const :tag "off" nil)
555 (const :tag "after bullet first" t)
556 (const :tag "border first" reversed)))
558 (if (fboundp 'defvaralias)
559 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
561 (defcustom org-odd-levels-only nil
562 "Non-nil means, skip even levels and only use odd levels for the outline.
563 This has the effect that two stars are being added/taken away in
564 promotion/demotion commands. It also influences how levels are
565 handled by the exporters.
566 Changing it requires restart of `font-lock-mode' to become effective
567 for fontification also in regions already fontified.
568 You may also set this on a per-file basis by adding one of the following
569 lines to the buffer:
571 #+STARTUP: odd
572 #+STARTUP: oddeven"
573 :group 'org-edit-structure
574 :group 'org-font-lock
575 :type 'boolean)
577 (defcustom org-adapt-indentation t
578 "Non-nil means, adapt indentation when promoting and demoting.
579 When this is set and the *entire* text in an entry is indented, the
580 indentation is increased by one space in a demotion command, and
581 decreased by one in a promotion command. If any line in the entry
582 body starts at column 0, indentation is not changed at all."
583 :group 'org-edit-structure
584 :type 'boolean)
586 (defcustom org-blank-before-new-entry '((heading . nil)
587 (plain-list-item . nil))
588 "Should `org-insert-heading' leave a blank line before new heading/item?
589 The value is an alist, with `heading' and `plain-list-item' as car,
590 and a boolean flag as cdr."
591 :group 'org-edit-structure
592 :type '(list
593 (cons (const heading) (boolean))
594 (cons (const plain-list-item) (boolean))))
596 (defcustom org-insert-heading-hook nil
597 "Hook being run after inserting a new heading."
598 :group 'org-edit-structure
599 :type 'hook)
601 (defcustom org-enable-fixed-width-editor t
602 "Non-nil means, lines starting with \":\" are treated as fixed-width.
603 This currently only means, they are never auto-wrapped.
604 When nil, such lines will be treated like ordinary lines.
605 See also the QUOTE keyword."
606 :group 'org-edit-structure
607 :type 'boolean)
609 (defgroup org-sparse-trees nil
610 "Options concerning sparse trees in Org-mode."
611 :tag "Org Sparse Trees"
612 :group 'org-structure)
614 (defcustom org-highlight-sparse-tree-matches t
615 "Non-nil means, highlight all matches that define a sparse tree.
616 The highlights will automatically disappear the next time the buffer is
617 changed by an edit command."
618 :group 'org-sparse-trees
619 :type 'boolean)
621 (defcustom org-remove-highlights-with-change t
622 "Non-nil means, any change to the buffer will remove temporary highlights.
623 Such highlights are created by `org-occur' and `org-clock-display'.
624 When nil, `C-c C-c needs to be used to get rid of the highlights.
625 The highlights created by `org-preview-latex-fragment' always need
626 `C-c C-c' to be removed."
627 :group 'org-sparse-trees
628 :group 'org-time
629 :type 'boolean)
632 (defcustom org-occur-hook '(org-first-headline-recenter)
633 "Hook that is run after `org-occur' has constructed a sparse tree.
634 This can be used to recenter the window to show as much of the structure
635 as possible."
636 :group 'org-sparse-trees
637 :type 'hook)
639 (defgroup org-plain-lists nil
640 "Options concerning plain lists in Org-mode."
641 :tag "Org Plain lists"
642 :group 'org-structure)
644 (defcustom org-cycle-include-plain-lists nil
645 "Non-nil means, include plain lists into visibility cycling.
646 This means that during cycling, plain list items will *temporarily* be
647 interpreted as outline headlines with a level given by 1000+i where i is the
648 indentation of the bullet. In all other operations, plain list items are
649 not seen as headlines. For example, you cannot assign a TODO keyword to
650 such an item."
651 :group 'org-plain-lists
652 :type 'boolean)
654 (defcustom org-plain-list-ordered-item-terminator t
655 "The character that makes a line with leading number an ordered list item.
656 Valid values are ?. and ?\). To get both terminators, use t. While
657 ?. may look nicer, it creates the danger that a line with leading
658 number may be incorrectly interpreted as an item. ?\) therefore is
659 the safe choice."
660 :group 'org-plain-lists
661 :type '(choice (const :tag "dot like in \"2.\"" ?.)
662 (const :tag "paren like in \"2)\"" ?\))
663 (const :tab "both" t)))
665 (defcustom org-auto-renumber-ordered-lists t
666 "Non-nil means, automatically renumber ordered plain lists.
667 Renumbering happens when the sequence have been changed with
668 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
669 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
670 :group 'org-plain-lists
671 :type 'boolean)
673 (defcustom org-provide-checkbox-statistics t
674 "Non-nil means, update checkbox statistics after insert and toggle.
675 When this is set, checkbox statistics is updated each time you either insert
676 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
677 with \\[org-ctrl-c-ctrl-c\\]."
678 :group 'org-plain-lists
679 :type 'boolean)
681 (defgroup org-archive nil
682 "Options concerning archiving in Org-mode."
683 :tag "Org Archive"
684 :group 'org-structure)
686 (defcustom org-archive-tag "ARCHIVE"
687 "The tag that marks a subtree as archived.
688 An archived subtree does not open during visibility cycling, and does
689 not contribute to the agenda listings.
690 After changing this, font-lock must be restarted in the relevant buffers to
691 get the proper fontification."
692 :group 'org-archive
693 :group 'org-keywords
694 :type 'string)
696 (defcustom org-agenda-skip-archived-trees t
697 "Non-nil means, the agenda will skip any items located in archived trees.
698 An archived tree is a tree marked with the tag ARCHIVE."
699 :group 'org-archive
700 :group 'org-agenda-skip
701 :type 'boolean)
703 (defcustom org-cycle-open-archived-trees nil
704 "Non-nil means, `org-cycle' will open archived trees.
705 An archived tree is a tree marked with the tag ARCHIVE.
706 When nil, archived trees will stay folded. You can still open them with
707 normal outline commands like `show-all', but not with the cycling commands."
708 :group 'org-archive
709 :group 'org-cycle
710 :type 'boolean)
712 (defcustom org-sparse-tree-open-archived-trees nil
713 "Non-nil means sparse tree construction shows matches in archived trees.
714 When nil, matches in these trees are highlighted, but the trees are kept in
715 collapsed state."
716 :group 'org-archive
717 :group 'org-sparse-trees
718 :type 'boolean)
720 (defcustom org-archive-location "%s_archive::"
721 "The location where subtrees should be archived.
722 This string consists of two parts, separated by a double-colon.
724 The first part is a file name - when omitted, archiving happens in the same
725 file. %s will be replaced by the current file name (without directory part).
726 Archiving to a different file is useful to keep archived entries from
727 contributing to the Org-mode Agenda.
729 The part after the double colon is a headline. The archived entries will be
730 filed under that headline. When omitted, the subtrees are simply filed away
731 at the end of the file, as top-level entries.
733 Here are a few examples:
734 \"%s_archive::\"
735 If the current file is Projects.org, archive in file
736 Projects.org_archive, as top-level trees. This is the default.
738 \"::* Archived Tasks\"
739 Archive in the current file, under the top-level headline
740 \"* Archived Tasks\".
742 \"~/org/archive.org::\"
743 Archive in file ~/org/archive.org (absolute path), as top-level trees.
745 \"basement::** Finished Tasks\"
746 Archive in file ./basement (relative path), as level 3 trees
747 below the level 2 heading \"** Finished Tasks\".
749 You may set this option on a per-file basis by adding to the buffer a
750 line like
752 #+ARCHIVE: basement::** Finished Tasks"
753 :group 'org-archive
754 :type 'string)
756 (defcustom org-archive-mark-done t
757 "Non-nil means, mark entries as DONE when they are moved to the archive file.
758 This can be a string to set the keyword to use. When t, Org-mode will
759 use the first keyword in its list that means done."
760 :group 'org-archive
761 :type '(choice
762 (const :tag "No" nil)
763 (const :tag "Yes" t)
764 (string :tag "Use this keyword")))
766 (defcustom org-archive-stamp-time t
767 "Non-nil means, add a time stamp to entries moved to an archive file.
768 This variable is obsolete and has no effect anymore, instead add ot remove
769 `time' from the variablle `org-archive-save-context-info'."
770 :group 'org-archive
771 :type 'boolean)
773 (defcustom org-archive-save-context-info '(time file category todo itags)
774 "Parts of context info that should be stored as properties when archiving.
775 When a subtree is moved to an archive file, it looses information given by
776 context, like inherited tags, the category, and possibly also the TODO
777 state (depending on the variable `org-archive-mark-done').
778 This variable can be a list of any of the following symbols:
780 time The time of archiving.
781 file The file where the entry originates.
782 itags The local tags, in the headline of the subtree.
783 ltags The tags the subtree inherits from further up the hierarchy.
784 todo The pre-archive TODO state.
785 category The category, taken from file name or #+CATEGORY lines.
787 For each symbol present in the list, a property will be created in
788 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
789 information."
790 :group 'org-archive
791 :type '(set :greedy t
792 (const :tag "Time" time)
793 (const :tag "File" file)
794 (const :tag "Category" category)
795 (const :tag "TODO state" todo)
796 (const :tag "TODO state" priority)
797 (const :tag "Inherited tags" itags)
798 (const :tag "Local tags" ltags)))
800 (defgroup org-table nil
801 "Options concerning tables in Org-mode."
802 :tag "Org Table"
803 :group 'org)
805 (defcustom org-enable-table-editor 'optimized
806 "Non-nil means, lines starting with \"|\" are handled by the table editor.
807 When nil, such lines will be treated like ordinary lines.
809 When equal to the symbol `optimized', the table editor will be optimized to
810 do the following:
811 - Automatic overwrite mode in front of whitespace in table fields.
812 This makes the structure of the table stay in tact as long as the edited
813 field does not exceed the column width.
814 - Minimize the number of realigns. Normally, the table is aligned each time
815 TAB or RET are pressed to move to another field. With optimization this
816 happens only if changes to a field might have changed the column width.
817 Optimization requires replacing the functions `self-insert-command',
818 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
819 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
820 very good at guessing when a re-align will be necessary, but you can always
821 force one with \\[org-ctrl-c-ctrl-c].
823 If you would like to use the optimized version in Org-mode, but the
824 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
826 This variable can be used to turn on and off the table editor during a session,
827 but in order to toggle optimization, a restart is required.
829 See also the variable `org-table-auto-blank-field'."
830 :group 'org-table
831 :type '(choice
832 (const :tag "off" nil)
833 (const :tag "on" t)
834 (const :tag "on, optimized" optimized)))
836 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
837 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
838 In the optimized version, the table editor takes over all simple keys that
839 normally just insert a character. In tables, the characters are inserted
840 in a way to minimize disturbing the table structure (i.e. in overwrite mode
841 for empty fields). Outside tables, the correct binding of the keys is
842 restored.
844 The default for this option is t if the optimized version is also used in
845 Org-mode. See the variable `org-enable-table-editor' for details. Changing
846 this variable requires a restart of Emacs to become effective."
847 :group 'org-table
848 :type 'boolean)
850 (defcustom orgtbl-radio-table-templates
851 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
852 % END RECEIVE ORGTBL %n
853 \\begin{comment}
854 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
855 | | |
856 \\end{comment}\n")
857 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
858 @c END RECEIVE ORGTBL %n
859 @ignore
860 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
861 | | |
862 @end ignore\n")
863 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
864 <!-- END RECEIVE ORGTBL %n -->
865 <!--
866 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
867 | | |
868 -->\n"))
869 "Templates for radio tables in different major modes.
870 All occurrences of %n in a template will be replaced with the name of the
871 table, obtained by prompting the user."
872 :group 'org-table
873 :type '(repeat
874 (list (symbol :tag "Major mode")
875 (string :tag "Format"))))
877 (defgroup org-table-settings nil
878 "Settings for tables in Org-mode."
879 :tag "Org Table Settings"
880 :group 'org-table)
882 (defcustom org-table-default-size "5x2"
883 "The default size for newly created tables, Columns x Rows."
884 :group 'org-table-settings
885 :type 'string)
887 (defcustom org-table-number-regexp
888 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
889 "Regular expression for recognizing numbers in table columns.
890 If a table column contains mostly numbers, it will be aligned to the
891 right. If not, it will be aligned to the left.
893 The default value of this option is a regular expression which allows
894 anything which looks remotely like a number as used in scientific
895 context. For example, all of the following will be considered a
896 number:
897 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
899 Other options offered by the customize interface are more restrictive."
900 :group 'org-table-settings
901 :type '(choice
902 (const :tag "Positive Integers"
903 "^[0-9]+$")
904 (const :tag "Integers"
905 "^[-+]?[0-9]+$")
906 (const :tag "Floating Point Numbers"
907 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
908 (const :tag "Floating Point Number or Integer"
909 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
910 (const :tag "Exponential, Floating point, Integer"
911 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
912 (const :tag "Very General Number-Like, including hex"
913 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
914 (string :tag "Regexp:")))
916 (defcustom org-table-number-fraction 0.5
917 "Fraction of numbers in a column required to make the column align right.
918 In a column all non-white fields are considered. If at least this
919 fraction of fields is matched by `org-table-number-fraction',
920 alignment to the right border applies."
921 :group 'org-table-settings
922 :type 'number)
924 (defgroup org-table-editing nil
925 "Behavior of tables during editing in Org-mode."
926 :tag "Org Table Editing"
927 :group 'org-table)
929 (defcustom org-table-automatic-realign t
930 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
931 When nil, aligning is only done with \\[org-table-align], or after column
932 removal/insertion."
933 :group 'org-table-editing
934 :type 'boolean)
936 (defcustom org-table-auto-blank-field t
937 "Non-nil means, automatically blank table field when starting to type into it.
938 This only happens when typing immediately after a field motion
939 command (TAB, S-TAB or RET).
940 Only relevant when `org-enable-table-editor' is equal to `optimized'."
941 :group 'org-table-editing
942 :type 'boolean)
944 (defcustom org-table-tab-jumps-over-hlines t
945 "Non-nil means, tab in the last column of a table with jump over a hline.
946 If a horizontal separator line is following the current line,
947 `org-table-next-field' can either create a new row before that line, or jump
948 over the line. When this option is nil, a new line will be created before
949 this line."
950 :group 'org-table-editing
951 :type 'boolean)
953 (defcustom org-table-tab-recognizes-table.el t
954 "Non-nil means, TAB will automatically notice a table.el table.
955 When it sees such a table, it moves point into it and - if necessary -
956 calls `table-recognize-table'."
957 :group 'org-table-editing
958 :type 'boolean)
960 (defgroup org-table-calculation nil
961 "Options concerning tables in Org-mode."
962 :tag "Org Table Calculation"
963 :group 'org-table)
965 (defcustom org-table-use-standard-references t
966 "Should org-mode work with table refrences like B3 instead of @3$2?
967 Possible values are:
968 nil never use them
969 from accept as input, do not present for editing
970 t: accept as input and present for editing"
971 :group 'org-table-calculation
972 :type '(choice
973 (const :tag "Never, don't even check unser input for them" nil)
974 (const :tag "Always, both as user input, and when editing" t)
975 (const :tag "Convert user input, don't offer during editing" 'from)))
977 (defcustom org-table-copy-increment t
978 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
979 :group 'org-table-calculation
980 :type 'boolean)
982 (defcustom org-calc-default-modes
983 '(calc-internal-prec 12
984 calc-float-format (float 5)
985 calc-angle-mode deg
986 calc-prefer-frac nil
987 calc-symbolic-mode nil
988 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
989 calc-display-working-message t
991 "List with Calc mode settings for use in calc-eval for table formulas.
992 The list must contain alternating symbols (Calc modes variables and values).
993 Don't remove any of the default settings, just change the values. Org-mode
994 relies on the variables to be present in the list."
995 :group 'org-table-calculation
996 :type 'plist)
998 (defcustom org-table-formula-evaluate-inline t
999 "Non-nil means, TAB and RET evaluate a formula in current table field.
1000 If the current field starts with an equal sign, it is assumed to be a formula
1001 which should be evaluated as described in the manual and in the documentation
1002 string of the command `org-table-eval-formula'. This feature requires the
1003 Emacs calc package.
1004 When this variable is nil, formula calculation is only available through
1005 the command \\[org-table-eval-formula]."
1006 :group 'org-table-calculation
1007 :type 'boolean)
1009 (defcustom org-table-formula-use-constants t
1010 "Non-nil means, interpret constants in formulas in tables.
1011 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1012 by the value given in `org-table-formula-constants', or by a value obtained
1013 from the `constants.el' package."
1014 :group 'org-table-calculation
1015 :type 'boolean)
1017 (defcustom org-table-formula-constants nil
1018 "Alist with constant names and values, for use in table formulas.
1019 The car of each element is a name of a constant, without the `$' before it.
1020 The cdr is the value as a string. For example, if you'd like to use the
1021 speed of light in a formula, you would configure
1023 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1025 and then use it in an equation like `$1*$c'.
1027 Constants can also be defined on a per-file basis using a line like
1029 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1030 :group 'org-table-calculation
1031 :type '(repeat
1032 (cons (string :tag "name")
1033 (string :tag "value"))))
1035 (defvar org-table-formula-constants-local nil
1036 "Local version of `org-table-formula-constants'.")
1037 (make-variable-buffer-local 'org-table-formula-constants-local)
1039 (defcustom org-table-allow-automatic-line-recalculation t
1040 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1041 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1042 :group 'org-table-calculation
1043 :type 'boolean)
1045 (defgroup org-link nil
1046 "Options concerning links in Org-mode."
1047 :tag "Org Link"
1048 :group 'org)
1050 (defvar org-link-abbrev-alist-local nil
1051 "Buffer-local version of `org-link-abbrev-alist', which see.
1052 The value of this is taken from the #+LINK lines.")
1053 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1055 (defcustom org-link-abbrev-alist nil
1056 "Alist of link abbreviations.
1057 The car of each element is a string, to be replaced at the start of a link.
1058 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1059 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1061 [[linkkey:tag][description]]
1063 If REPLACE is a string, the tag will simply be appended to create the link.
1064 If the string contains \"%s\", the tag will be inserted there. REPLACE may
1065 also be a function that will be called with the tag as the only argument to
1066 create the link. See the manual for examples."
1067 :group 'org-link
1068 :type 'alist)
1070 (defcustom org-descriptive-links t
1071 "Non-nil means, hide link part and only show description of bracket links.
1072 Bracket links are like [[link][descritpion]]. This variable sets the initial
1073 state in new org-mode buffers. The setting can then be toggled on a
1074 per-buffer basis from the Org->Hyperlinks menu."
1075 :group 'org-link
1076 :type 'boolean)
1078 (defcustom org-link-file-path-type 'adaptive
1079 "How the path name in file links should be stored.
1080 Valid values are:
1082 relative relative to the current directory, i.e. the directory of the file
1083 into which the link is being inserted.
1084 absolute absolute path, if possible with ~ for home directory.
1085 noabbrev absolute path, no abbreviation of home directory.
1086 adaptive Use relative path for files in the current directory and sub-
1087 directories of it. For other files, use an absolute path."
1088 :group 'org-link
1089 :type '(choice
1090 (const relative)
1091 (const absolute)
1092 (const noabbrev)
1093 (const adaptive)))
1095 (defcustom org-activate-links '(bracket angle plain radio tag date)
1096 "Types of links that should be activated in Org-mode files.
1097 This is a list of symbols, each leading to the activation of a certain link
1098 type. In principle, it does not hurt to turn on most link types - there may
1099 be a small gain when turning off unused link types. The types are:
1101 bracket The recommended [[link][description]] or [[link]] links with hiding.
1102 angular Links in angular brackes that may contain whitespace like
1103 <bbdb:Carsten Dominik>.
1104 plain Plain links in normal text, no whitespace, like http://google.com.
1105 radio Text that is matched by a radio target, see manual for details.
1106 tag Tag settings in a headline (link to tag search).
1107 date Time stamps (link to calendar).
1109 Changing this variable requires a restart of Emacs to become effective."
1110 :group 'org-link
1111 :type '(set (const :tag "Double bracket links (new style)" bracket)
1112 (const :tag "Angular bracket links (old style)" angular)
1113 (const :tag "plain text links" plain)
1114 (const :tag "Radio target matches" radio)
1115 (const :tag "Tags" tag)
1116 (const :tag "Tags" target)
1117 (const :tag "Timestamps" date)))
1119 (defgroup org-link-store nil
1120 "Options concerning storing links in Org-mode"
1121 :tag "Org Store Link"
1122 :group 'org-link)
1124 (defcustom org-email-link-description-format "Email %c: %.30s"
1125 "Format of the description part of a link to an email or usenet message.
1126 The following %-excapes will be replaced by corresponding information:
1128 %F full \"From\" field
1129 %f name, taken from \"From\" field, address if no name
1130 %T full \"To\" field
1131 %t first name in \"To\" field, address if no name
1132 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1133 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1134 %s subject
1135 %m message-id.
1137 You may use normal field width specification between the % and the letter.
1138 This is for example useful to limit the length of the subject.
1140 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1141 :group 'org-link-store
1142 :type 'string)
1144 (defcustom org-from-is-user-regexp
1145 (let (r1 r2)
1146 (when (and user-mail-address (not (string= user-mail-address "")))
1147 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1148 (when (and user-full-name (not (string= user-full-name "")))
1149 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1150 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1151 "Regexp mached against the \"From:\" header of an email or usenet message.
1152 It should match if the message is from the user him/herself."
1153 :group 'org-link-store
1154 :type 'regexp)
1156 (defcustom org-context-in-file-links t
1157 "Non-nil means, file links from `org-store-link' contain context.
1158 A search string will be added to the file name with :: as separator and
1159 used to find the context when the link is activated by the command
1160 `org-open-at-point'.
1161 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1162 negates this setting for the duration of the command."
1163 :group 'org-link-store
1164 :type 'boolean)
1166 (defcustom org-keep-stored-link-after-insertion nil
1167 "Non-nil means, keep link in list for entire session.
1169 The command `org-store-link' adds a link pointing to the current
1170 location to an internal list. These links accumulate during a session.
1171 The command `org-insert-link' can be used to insert links into any
1172 Org-mode file (offering completion for all stored links). When this
1173 option is nil, every link which has been inserted once using \\[org-insert-link]
1174 will be removed from the list, to make completing the unused links
1175 more efficient."
1176 :group 'org-link-store
1177 :type 'boolean)
1179 (defcustom org-usenet-links-prefer-google nil
1180 "Non-nil means, `org-store-link' will create web links to Google groups.
1181 When nil, Gnus will be used for such links.
1182 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1183 negates this setting for the duration of the command."
1184 :group 'org-link-store
1185 :type 'boolean)
1187 (defgroup org-link-follow nil
1188 "Options concerning following links in Org-mode"
1189 :tag "Org Follow Link"
1190 :group 'org-link)
1192 (defcustom org-tab-follows-link nil
1193 "Non-nil means, on links TAB will follow the link.
1194 Needs to be set before org.el is loaded."
1195 :group 'org-link-follow
1196 :type 'boolean)
1198 (defcustom org-return-follows-link nil
1199 "Non-nil means, on links RET will follow the link.
1200 Needs to be set before org.el is loaded."
1201 :group 'org-link-follow
1202 :type 'boolean)
1204 (defcustom org-mouse-1-follows-link t
1205 "Non-nil means, mouse-1 on a link will follow the link.
1206 A longer mouse click will still set point. Does not wortk on XEmacs.
1207 Needs to be set before org.el is loaded."
1208 :group 'org-link-follow
1209 :type 'boolean)
1211 (defcustom org-mark-ring-length 4
1212 "Number of different positions to be recorded in the ring
1213 Changing this requires a restart of Emacs to work correctly."
1214 :group 'org-link-follow
1215 :type 'interger)
1217 (defcustom org-link-frame-setup
1218 '((vm . vm-visit-folder-other-frame)
1219 (gnus . gnus-other-frame)
1220 (file . find-file-other-window))
1221 "Setup the frame configuration for following links.
1222 When following a link with Emacs, it may often be useful to display
1223 this link in another window or frame. This variable can be used to
1224 set this up for the different types of links.
1225 For VM, use any of
1226 `vm-visit-folder'
1227 `vm-visit-folder-other-frame'
1228 For Gnus, use any of
1229 `gnus'
1230 `gnus-other-frame'
1231 For FILE, use any of
1232 `find-file'
1233 `find-file-other-window'
1234 `find-file-other-frame'
1235 For the calendar, use the variable `calendar-setup'.
1236 For BBDB, it is currently only possible to display the matches in
1237 another window."
1238 :group 'org-link-follow
1239 :type '(list
1240 (cons (const vm)
1241 (choice
1242 (const vm-visit-folder)
1243 (const vm-visit-folder-other-window)
1244 (const vm-visit-folder-other-frame)))
1245 (cons (const gnus)
1246 (choice
1247 (const gnus)
1248 (const gnus-other-frame)))
1249 (cons (const file)
1250 (choice
1251 (const find-file)
1252 (const find-file-other-window)
1253 (const find-file-other-frame)))))
1255 (defcustom org-display-internal-link-with-indirect-buffer nil
1256 "Non-nil means, use indirect buffer to display infile links.
1257 Activating internal links (from one location in a file to another location
1258 in the same file) normally just jumps to the location. When the link is
1259 activated with a C-u prefix (or with mouse-3), the link is displayed in
1260 another window. When this option is set, the other window actually displays
1261 an indirect buffer clone of the current buffer, to avoid any visibility
1262 changes to the current buffer."
1263 :group 'org-link-follow
1264 :type 'boolean)
1266 (defcustom org-open-non-existing-files nil
1267 "Non-nil means, `org-open-file' will open non-existing files.
1268 When nil, an error will be generated."
1269 :group 'org-link-follow
1270 :type 'boolean)
1272 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1273 "Function and arguments to call for following mailto links.
1274 This is a list with the first element being a lisp function, and the
1275 remaining elements being arguments to the function. In string arguments,
1276 %a will be replaced by the address, and %s will be replaced by the subject
1277 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1278 :group 'org-link-follow
1279 :type '(choice
1280 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1281 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1282 (const :tag "message-mail" (message-mail "%a" "%s"))
1283 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1285 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1286 "Non-nil means, ask for confirmation before executing shell links.
1287 Shell links can be dangerous: just think about a link
1289 [[shell:rm -rf ~/*][Google Search]]
1291 This link would show up in your Org-mode document as \"Google Search\",
1292 but really it would remove your entire home directory.
1293 Therefore we advise against setting this variable to nil.
1294 Just change it to `y-or-n-p' of you want to confirm with a
1295 single keystroke rather than having to type \"yes\"."
1296 :group 'org-link-follow
1297 :type '(choice
1298 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1299 (const :tag "with y-or-n (faster)" y-or-n-p)
1300 (const :tag "no confirmation (dangerous)" nil)))
1302 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1303 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1304 Elisp links can be dangerous: just think about a link
1306 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1308 This link would show up in your Org-mode document as \"Google Search\",
1309 but really it would remove your entire home directory.
1310 Therefore we advise against setting this variable to nil.
1311 Just change it to `y-or-n-p' of you want to confirm with a
1312 single keystroke rather than having to type \"yes\"."
1313 :group 'org-link-follow
1314 :type '(choice
1315 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1316 (const :tag "with y-or-n (faster)" y-or-n-p)
1317 (const :tag "no confirmation (dangerous)" nil)))
1319 (defconst org-file-apps-defaults-gnu
1320 '((remote . emacs)
1321 (t . mailcap))
1322 "Default file applications on a UNIX or GNU/Linux system.
1323 See `org-file-apps'.")
1325 (defconst org-file-apps-defaults-macosx
1326 '((remote . emacs)
1327 (t . "open %s")
1328 ("ps" . "gv %s")
1329 ("ps.gz" . "gv %s")
1330 ("eps" . "gv %s")
1331 ("eps.gz" . "gv %s")
1332 ("dvi" . "xdvi %s")
1333 ("fig" . "xfig %s"))
1334 "Default file applications on a MacOS X system.
1335 The system \"open\" is known as a default, but we use X11 applications
1336 for some files for which the OS does not have a good default.
1337 See `org-file-apps'.")
1339 (defconst org-file-apps-defaults-windowsnt
1340 (list
1341 '(remote . emacs)
1342 (cons t
1343 (list (if (featurep 'xemacs)
1344 'mswindows-shell-execute
1345 'w32-shell-execute)
1346 "open" 'file)))
1347 "Default file applications on a Windows NT system.
1348 The system \"open\" is used for most files.
1349 See `org-file-apps'.")
1351 (defcustom org-file-apps
1353 ("txt" . emacs)
1354 ("tex" . emacs)
1355 ("ltx" . emacs)
1356 ("org" . emacs)
1357 ("el" . emacs)
1358 ("bib" . emacs)
1360 "External applications for opening `file:path' items in a document.
1361 Org-mode uses system defaults for different file types, but
1362 you can use this variable to set the application for a given file
1363 extension. The entries in this list are cons cells where the car identifies
1364 files and the cdr the corresponding command. Possible values for the
1365 file identifier are
1366 \"ext\" A string identifying an extension
1367 `directory' Matches a directory
1368 `remote' Matches a remote file, accessible through tramp or efs.
1369 Remote files most likely should be visited through Emacs
1370 because external applications cannot handle such paths.
1371 t Default for all remaining files
1373 Possible values for the command are:
1374 `emacs' The file will be visited by the current Emacs process.
1375 `default' Use the default application for this file type.
1376 string A command to be executed by a shell; %s will be replaced
1377 by the path to the file.
1378 sexp A Lisp form which will be evaluated. The file path will
1379 be available in the Lisp variable `file'.
1380 For more examples, see the system specific constants
1381 `org-file-apps-defaults-macosx'
1382 `org-file-apps-defaults-windowsnt'
1383 `org-file-apps-defaults-gnu'."
1384 :group 'org-link-follow
1385 :type '(repeat
1386 (cons (choice :value ""
1387 (string :tag "Extension")
1388 (const :tag "Default for unrecognized files" t)
1389 (const :tag "Remote file" remote)
1390 (const :tag "Links to a directory" directory))
1391 (choice :value ""
1392 (const :tag "Visit with Emacs" emacs)
1393 (const :tag "Use system default" default)
1394 (string :tag "Command")
1395 (sexp :tag "Lisp form")))))
1397 (defcustom org-mhe-search-all-folders nil
1398 "Non-nil means, that the search for the mh-message will be extended to
1399 all folders if the message cannot be found in the folder given in the link.
1400 Searching all folders is very efficient with one of the search engines
1401 supported by MH-E, but will be slow with pick."
1402 :group 'org-link-follow
1403 :type 'boolean)
1405 (defgroup org-remember nil
1406 "Options concerning interaction with remember.el."
1407 :tag "Org Remember"
1408 :group 'org)
1410 (defcustom org-directory "~/org"
1411 "Directory with org files.
1412 This directory will be used as default to prompt for org files.
1413 Used by the hooks for remember.el."
1414 :group 'org-remember
1415 :type 'directory)
1417 (defcustom org-default-notes-file "~/.notes"
1418 "Default target for storing notes.
1419 Used by the hooks for remember.el. This can be a string, or nil to mean
1420 the value of `remember-data-file'.
1421 You can set this on a per-template basis with the variable
1422 `org-remember-templates'."
1423 :group 'org-remember
1424 :type '(choice
1425 (const :tag "Default from remember-data-file" nil)
1426 file))
1428 (defcustom org-remember-store-without-prompt t
1429 "Non-nil means, `C-c C-c' stores remember note without further promts.
1430 In this case, you need `C-u C-c C-c' to get the prompts for
1431 note file and headline.
1432 When this variable is nil, `C-c C-c' give you the prompts, and
1433 `C-u C-c C-c' trigger the fasttrack."
1434 :group 'org-remember
1435 :type 'boolean)
1437 (defcustom org-remember-default-headline ""
1438 "The headline that should be the default location in the notes file.
1439 When filing remember notes, the cursor will start at that position.
1440 You can set this on a per-template basis with the variable
1441 `org-remember-templates'."
1442 :group 'org-remember
1443 :type 'string)
1445 (defcustom org-remember-templates nil
1446 "Templates for the creation of remember buffers.
1447 When nil, just let remember make the buffer.
1448 When not nil, this is a list of 5-element lists. In each entry, the first
1449 element is a the name of the template, It should be a single short word.
1450 The second element is a character, a unique key to select this template.
1451 The third element is the template. The forth element is optional and can
1452 specify a destination file for remember items created with this template.
1453 The default file is given by `org-default-notes-file'. An optional fifth
1454 element can specify the headline in that file that should be offered
1455 first when the user is asked to file the entry. The default headline is
1456 given in the variable `org-remember-default-headline'.
1458 The template specifies the structure of the remember buffer. It should have
1459 a first line starting with a star, to act as the org-mode headline.
1460 Furthermore, the following %-escapes will be replaced with content:
1462 %^{prompt} prompt the user for a string and replace this sequence with it.
1463 %t time stamp, date only
1464 %T time stamp with date and time
1465 %u, %U like the above, but inactive time stamps
1466 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1467 You may define a prompt like %^{Please specify birthday}t
1468 %n user name (taken from `user-full-name')
1469 %a annotation, normally the link created with org-store-link
1470 %i initial content, the region when remember is called with C-u.
1471 If %i is indented, the entire inserted text will be indented
1472 as well.
1474 %? After completing the template, position cursor here.
1476 Apart from these general escapes, you can access information specific to the
1477 link type that is created. For example, calling `remember' in emails or gnus
1478 will record the author and the subject of the message, which you can access
1479 with %:author and %:subject, respectively. Here is a complete list of what
1480 is recorded for each link type.
1482 Link type | Available information
1483 -------------------+------------------------------------------------------
1484 bbdb | %:type %:name %:company
1485 vm, wl, mh, rmail | %:type %:subject %:message-id
1486 | %:from %:fromname %:fromaddress
1487 | %:to %:toname %:toaddress
1488 | %:fromto (either \"to NAME\" or \"from NAME\")
1489 gnus | %:group, for messages also all email fields
1490 w3, w3m | %:type %:url
1491 info | %:type %:file %:node
1492 calendar | %:type %:date"
1493 :group 'org-remember
1494 :get (lambda (var) ; Make sure all entries have 5 elements
1495 (mapcar (lambda (x)
1496 (if (not (stringp (car x))) (setq x (cons "" x)))
1497 (cond ((= (length x) 4) (append x '("")))
1498 ((= (length x) 3) (append x '("" "")))
1499 (t x)))
1500 (default-value var)))
1501 :type '(repeat
1502 :tag "enabled"
1503 (list :value ("" ?a "\n" nil nil)
1504 (string :tag "Name")
1505 (character :tag "Selection Key")
1506 (string :tag "Template")
1507 (choice
1508 (file :tag "Destination file")
1509 (const :tag "Prompt for file" nil))
1510 (choice
1511 (string :tag "Destination headline")
1512 (const :tag "Selection interface for heading")))))
1514 (defcustom org-reverse-note-order nil
1515 "Non-nil means, store new notes at the beginning of a file or entry.
1516 When nil, new notes will be filed to the end of a file or entry.
1517 This can also be a list with cons cells of regular expressions that
1518 are matched against file names, and values."
1519 :group 'org-remember
1520 :type '(choice
1521 (const :tag "Reverse always" t)
1522 (const :tag "Reverse never" nil)
1523 (repeat :tag "By file name regexp"
1524 (cons regexp boolean))))
1526 (defgroup org-todo nil
1527 "Options concerning TODO items in Org-mode."
1528 :tag "Org TODO"
1529 :group 'org)
1531 (defgroup org-progress nil
1532 "Options concerning Progress logging in Org-mode."
1533 :tag "Org Progress"
1534 :group 'org-time)
1536 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1537 "List of TODO entry keyword sequences and their interpretation.
1538 \\<org-mode-map>This is a list of sequences.
1540 Each sequence starts with a symbol, either `sequence' or `type',
1541 indicating if the keywords should be interpreted as a sequence of
1542 action steps, or as different types of TODO items. The first
1543 keywords are states requiring action - these states will select a headline
1544 for inclusion into the global TODO list Org-mode produces. If one of
1545 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1546 signify that no further action is necessary. If \"|\" is not found,
1547 the last keyword is treated as the only DONE state of the sequence.
1549 The command \\[org-todo] cycles an entry through these states, and one
1550 additional state where no keyword is present. For details about this
1551 cycling, see the manual.
1553 TODO keywords and interpretation can also be set on a per-file basis with
1554 the special #+SEQ_TODO and #+TYP_TODO lines.
1556 For backward compatibility, this variable may also be just a list
1557 of keywords - in this case the interptetation (sequence or type) will be
1558 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1559 :group 'org-todo
1560 :group 'org-keywords
1561 :type '(choice
1562 (repeat :tag "Old syntax, just keywords"
1563 (string :tag "Keyword"))
1564 (repeat :tag "New syntax"
1565 (cons
1566 (choice
1567 :tag "Interpretation"
1568 (const :tag "Sequence (cycling hits every state)" sequence)
1569 (const :tag "Type (cycling directly to DONE)" type))
1570 (repeat
1571 (string :tag "Keyword"))))))
1573 (defvar org-todo-keywords-1 nil)
1574 (make-variable-buffer-local 'org-todo-keywords-1)
1575 (defvar org-todo-keywords-for-agenda nil)
1576 (defvar org-done-keywords-for-agenda nil)
1577 (defvar org-not-done-keywords nil)
1578 (make-variable-buffer-local 'org-not-done-keywords)
1579 (defvar org-done-keywords nil)
1580 (make-variable-buffer-local 'org-done-keywords)
1581 (defvar org-todo-heads nil)
1582 (make-variable-buffer-local 'org-todo-heads)
1583 (defvar org-todo-sets nil)
1584 (make-variable-buffer-local 'org-todo-sets)
1585 (defvar org-todo-log-states nil)
1586 (make-variable-buffer-local 'org-todo-log-states)
1587 (defvar org-todo-kwd-alist nil)
1588 (make-variable-buffer-local 'org-todo-kwd-alist)
1589 (defvar org-todo-key-alist nil)
1590 (make-variable-buffer-local 'org-todo-key-alist)
1591 (defvar org-todo-key-trigger nil)
1592 (make-variable-buffer-local 'org-todo-key-trigger)
1594 (defcustom org-todo-interpretation 'sequence
1595 "Controls how TODO keywords are interpreted.
1596 This variable is in principle obsolete and is only used for
1597 backward compatibility, if the interpretation of todo keywords is
1598 not given already in `org-todo-keywords'. See that variable for
1599 more information."
1600 :group 'org-todo
1601 :group 'org-keywords
1602 :type '(choice (const sequence)
1603 (const type)))
1605 (defcustom org-use-fast-todo-selection 'prefix
1606 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1607 This variable describes if and under what circumstances the cycling
1608 mechanism for TODO keywords will be replaced by a single-key, direct
1609 selection scheme.
1611 When nil, fast selection is never used.
1613 When the symbol `prefix', it will be used when `org-todo' is called with
1614 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1615 in an agenda buffer.
1617 When t, fast selection is used by default. In this case, the prefix
1618 argument forces cycling instead.
1620 In all cases, the special interface is only used if access keys have actually
1621 been assigned by the user, i.e. if keywords in the configuration are followed
1622 by a letter in parenthesis, like TODO(t)."
1623 :group 'org-todo
1624 :type '(choice
1625 (const :tag "Never" nil)
1626 (const :tag "By default" t)
1627 (const :tag "Only with C-u C-c C-t" prefix)))
1629 (defcustom org-after-todo-state-change-hook nil
1630 "Hook which is run after the state of a TODO item was changed.
1631 The new state (a string with a TODO keyword, or nil) is available in the
1632 Lisp variable `state'."
1633 :group 'org-todo
1634 :type 'hook)
1636 (defcustom org-log-done nil
1637 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1638 When the state of an entry is changed from nothing or a DONE state to
1639 a not-done TODO state, remove a previous closing date.
1641 This can also be a list of symbols indicating under which conditions
1642 the time stamp recording the action should be annotated with a short note.
1643 Valid members of this list are
1645 done Offer to record a note when marking entries done
1646 state Offer to record a note whenever changing the TODO state
1647 of an item. This is only relevant if TODO keywords are
1648 interpreted as sequence, see variable `org-todo-interpretation'.
1649 When `state' is set, this includes tracking `done'.
1650 clock-out Offer to record a note when clocking out of an item.
1652 A separate window will then pop up and allow you to type a note.
1653 After finishing with C-c C-c, the note will be added directly after the
1654 timestamp, as a plain list item. See also the variable
1655 `org-log-note-headings'.
1657 Logging can also be configured on a per-file basis by adding one of
1658 the following lines anywhere in the buffer:
1660 #+STARTUP: logdone
1661 #+STARTUP: nologging
1662 #+STARTUP: lognotedone
1663 #+STARTUP: lognotestate
1664 #+STARTUP: lognoteclock-out
1666 You can have local logging settings for a subtree by setting the LOGGING
1667 property to one or more of these keywords."
1668 :group 'org-todo
1669 :group 'org-progress
1670 :type '(choice
1671 (const :tag "off" nil)
1672 (const :tag "on" t)
1673 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1674 (const :tag "when item is marked DONE" done)
1675 (const :tag "when TODO state changes" state)
1676 (const :tag "when clocking out" clock-out))))
1678 (defcustom org-log-done-with-time t
1679 "Non-nil means, the CLOSED time stamp will contain date and time.
1680 When nil, only the date will be recorded."
1681 :group 'org-progress
1682 :type 'boolean)
1684 (defcustom org-log-note-headings
1685 '((done . "CLOSING NOTE %t")
1686 (state . "State %-12s %t")
1687 (clock-out . ""))
1688 "Headings for notes added when clocking out or closing TODO items.
1689 The value is an alist, with the car being a symbol indicating the note
1690 context, and the cdr is the heading to be used. The heading may also be the
1691 empty string.
1692 %t in the heading will be replaced by a time stamp.
1693 %s will be replaced by the new TODO state, in double quotes.
1694 %u will be replaced by the user name.
1695 %U will be replaced by the full user name."
1696 :group 'org-todo
1697 :group 'org-progress
1698 :type '(list :greedy t
1699 (cons (const :tag "Heading when closing an item" done) string)
1700 (cons (const :tag
1701 "Heading when changing todo state (todo sequence only)"
1702 state) string)
1703 (cons (const :tag "Heading when clocking out" clock-out) string)))
1705 (defcustom org-log-states-order-reversed t
1706 "Non-nil means, the latest state change note will be directly after heading.
1707 When nil, the notes will be orderer according to time."
1708 :group 'org-todo
1709 :group 'org-progress
1710 :type 'boolean)
1712 (defcustom org-log-repeat t
1713 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1714 When nil, no note will be taken.
1715 This option can also be set with on a per-file-basis with
1717 #+STARTUP: logrepeat
1718 #+STARTUP: nologrepeat
1720 You can have local logging settings for a subtree by setting the LOGGING
1721 property to one or more of these keywords."
1722 :group 'org-todo
1723 :group 'org-progress
1724 :type 'boolean)
1726 (defcustom org-clock-into-drawer 2
1727 "Should clocking info be wrapped into a drawer?
1728 When t, clocking info will always be inserted into a :CLOCK: drawer.
1729 If necessary, the drawer will be created.
1730 When nil, the drawer will not be created, but used when present.
1731 When an integer and the number of clocking entries in an item
1732 reaches or exceeds this number, a drawer will be created."
1733 :group 'org-todo
1734 :group 'org-progress
1735 :type '(choice
1736 (const :tag "Always" t)
1737 (const :tag "Only when drawer exists" nil)
1738 (integer :tag "When at least N clock entries")))
1740 (defcustom org-clock-out-when-done t
1741 "When t, the clock will be stopped when the relevant entry is marked DONE.
1742 Nil means, clock will keep running until stopped explicitly with
1743 `C-c C-x C-o', or until the clock is started in a different item."
1744 :group 'org-progress
1745 :type 'boolean)
1747 (defgroup org-priorities nil
1748 "Priorities in Org-mode."
1749 :tag "Org Priorities"
1750 :group 'org-todo)
1752 (defcustom org-highest-priority ?A
1753 "The highest priority of TODO items. A character like ?A, ?B etc.
1754 Must have a smaller ASCII number than `org-lowest-priority'."
1755 :group 'org-priorities
1756 :type 'character)
1758 (defcustom org-lowest-priority ?C
1759 "The lowest priority of TODO items. A character like ?A, ?B etc.
1760 Must have a larger ASCII number than `org-highest-priority'."
1761 :group 'org-priorities
1762 :type 'character)
1764 (defcustom org-default-priority ?B
1765 "The default priority of TODO items.
1766 This is the priority an item get if no explicit priority is given."
1767 :group 'org-priorities
1768 :type 'character)
1770 (defcustom org-priority-start-cycle-with-default t
1771 "Non-nil means, start with default priority when starting to cycle.
1772 When this is nil, the first step in the cycle will be (depending on the
1773 command used) one higher or lower that the default priority."
1774 :group 'org-priorities
1775 :type 'boolean)
1777 (defgroup org-time nil
1778 "Options concerning time stamps and deadlines in Org-mode."
1779 :tag "Org Time"
1780 :group 'org)
1782 (defcustom org-insert-labeled-timestamps-at-point nil
1783 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1784 When nil, these labeled time stamps are forces into the second line of an
1785 entry, just after the headline. When scheduling from the global TODO list,
1786 the time stamp will always be forced into the second line."
1787 :group 'org-time
1788 :type 'boolean)
1790 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1791 "Formats for `format-time-string' which are used for time stamps.
1792 It is not recommended to change this constant.")
1794 (defcustom org-time-stamp-rounding-minutes 0
1795 "Number of minutes to round time stamps to upon insertion.
1796 When zero, insert the time unmodified. Useful rounding numbers
1797 should be factors of 60, so for example 5, 10, 15.
1798 When this is not zero, you can still force an exact time-stamp by using
1799 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1800 :group 'org-time
1801 :type 'integer)
1803 (defcustom org-display-custom-times nil
1804 "Non-nil means, overlay custom formats over all time stamps.
1805 The formats are defined through the variable `org-time-stamp-custom-formats'.
1806 To turn this on on a per-file basis, insert anywhere in the file:
1807 #+STARTUP: customtime"
1808 :group 'org-time
1809 :set 'set-default
1810 :type 'sexp)
1811 (make-variable-buffer-local 'org-display-custom-times)
1813 (defcustom org-time-stamp-custom-formats
1814 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1815 "Custom formats for time stamps. See `format-time-string' for the syntax.
1816 These are overlayed over the default ISO format if the variable
1817 `org-display-custom-times' is set. Time like %H:%M should be at the
1818 end of the second format."
1819 :group 'org-time
1820 :type 'sexp)
1822 (defun org-time-stamp-format (&optional long inactive)
1823 "Get the right format for a time string."
1824 (let ((f (if long (cdr org-time-stamp-formats)
1825 (car org-time-stamp-formats))))
1826 (if inactive
1827 (concat "[" (substring f 1 -1) "]")
1828 f)))
1830 (defcustom org-read-date-prefer-future t
1831 "Non-nil means, assume future for incomplete date input from user.
1832 This affects the following situations:
1833 1. The user gives a day, but no month.
1834 For example, if today is the 15th, and you enter \"3\", Org-mode will
1835 read this as the third of *next* month. However, if you enter \"17\",
1836 it will be considered as *this* month.
1837 2. The user gives a month but not a year.
1838 For example, if it is april and you enter \"feb 2\", this will be read
1839 as feb 2, *next* year. \"May 5\", however, will be this year.
1841 When this option is nil, the current month and year will always be used
1842 as defaults."
1843 :group 'org-time
1844 :type 'boolean)
1846 (defcustom org-read-date-display-live t
1847 "Non-nil means, display current interpretation of date prompt live.
1848 This display will be in an overlay, in the minibuffer."
1849 :group 'org-time
1850 :type 'boolean)
1852 (defcustom org-read-date-popup-calendar t
1853 "Non-nil means, pop up a calendar when prompting for a date.
1854 In the calendar, the date can be selected with mouse-1. However, the
1855 minibuffer will also be active, and you can simply enter the date as well.
1856 When nil, only the minibuffer will be available."
1857 :group 'org-time
1858 :type 'boolean)
1859 (if (fboundp 'defvaralias)
1860 (defvaralias 'org-popup-calendar-for-date-prompt
1861 'org-read-date-popup-calendar))
1863 (defcustom org-extend-today-until 0
1864 "The hour when your day really ends.
1865 This has influence for the following applications:
1866 - When switching the agenda to \"today\". It it is still earlier than
1867 the time given here, the day recognized as TODAY is actually yesterday.
1868 - When a date is read from the user and it is still before the time given
1869 here, the current date and time will be assumed to be yesterday, 23:59.
1871 FIXME:
1872 IMPORTANT: This is still a very experimental feature, it may disappear
1873 again or it may be extended to mean more things."
1874 :group 'org-time
1875 :type 'number)
1877 (defcustom org-edit-timestamp-down-means-later nil
1878 "Non-nil means, S-down will increase the time in a time stamp.
1879 When nil, S-up will increase."
1880 :group 'org-time
1881 :type 'boolean)
1883 (defcustom org-calendar-follow-timestamp-change t
1884 "Non-nil means, make the calendar window follow timestamp changes.
1885 When a timestamp is modified and the calendar window is visible, it will be
1886 moved to the new date."
1887 :group 'org-time
1888 :type 'boolean)
1890 (defcustom org-clock-heading-function nil
1891 "When non-nil, should be a function to create `org-clock-heading'.
1892 This is the string shown in the mode line when a clock is running.
1893 The function is called with point at the beginning of the headline."
1894 :group 'org-time ; FIXME: Should we have a separate group????
1895 :type 'function)
1897 (defgroup org-tags nil
1898 "Options concerning tags in Org-mode."
1899 :tag "Org Tags"
1900 :group 'org)
1902 (defcustom org-tag-alist nil
1903 "List of tags allowed in Org-mode files.
1904 When this list is nil, Org-mode will base TAG input on what is already in the
1905 buffer.
1906 The value of this variable is an alist, the car of each entry must be a
1907 keyword as a string, the cdr may be a character that is used to select
1908 that tag through the fast-tag-selection interface.
1909 See the manual for details."
1910 :group 'org-tags
1911 :type '(repeat
1912 (choice
1913 (cons (string :tag "Tag name")
1914 (character :tag "Access char"))
1915 (const :tag "Start radio group" (:startgroup))
1916 (const :tag "End radio group" (:endgroup)))))
1918 (defcustom org-use-fast-tag-selection 'auto
1919 "Non-nil means, use fast tag selection scheme.
1920 This is a special interface to select and deselect tags with single keys.
1921 When nil, fast selection is never used.
1922 When the symbol `auto', fast selection is used if and only if selection
1923 characters for tags have been configured, either through the variable
1924 `org-tag-alist' or through a #+TAGS line in the buffer.
1925 When t, fast selection is always used and selection keys are assigned
1926 automatically if necessary."
1927 :group 'org-tags
1928 :type '(choice
1929 (const :tag "Always" t)
1930 (const :tag "Never" nil)
1931 (const :tag "When selection characters are configured" 'auto)))
1933 (defcustom org-fast-tag-selection-single-key nil
1934 "Non-nil means, fast tag selection exits after first change.
1935 When nil, you have to press RET to exit it.
1936 During fast tag selection, you can toggle this flag with `C-c'.
1937 This variable can also have the value `expert'. In this case, the window
1938 displaying the tags menu is not even shown, until you press C-c again."
1939 :group 'org-tags
1940 :type '(choice
1941 (const :tag "No" nil)
1942 (const :tag "Yes" t)
1943 (const :tag "Expert" expert)))
1945 (defvar org-fast-tag-selection-include-todo nil
1946 "Non-nil means, fast tags selection interface will also offer TODO states.
1947 This is an undocumented feature, you should not rely on it.")
1949 (defcustom org-tags-column -80
1950 "The column to which tags should be indented in a headline.
1951 If this number is positive, it specifies the column. If it is negative,
1952 it means that the tags should be flushright to that column. For example,
1953 -80 works well for a normal 80 character screen."
1954 :group 'org-tags
1955 :type 'integer)
1957 (defcustom org-auto-align-tags t
1958 "Non-nil means, realign tags after pro/demotion of TODO state change.
1959 These operations change the length of a headline and therefore shift
1960 the tags around. With this options turned on, after each such operation
1961 the tags are again aligned to `org-tags-column'."
1962 :group 'org-tags
1963 :type 'boolean)
1965 (defcustom org-use-tag-inheritance t
1966 "Non-nil means, tags in levels apply also for sublevels.
1967 When nil, only the tags directly given in a specific line apply there.
1968 If you turn off this option, you very likely want to turn on the
1969 companion option `org-tags-match-list-sublevels'."
1970 :group 'org-tags
1971 :type 'boolean)
1973 (defcustom org-tags-match-list-sublevels nil
1974 "Non-nil means list also sublevels of headlines matching tag search.
1975 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1976 the sublevels of a headline matching a tag search often also match
1977 the same search. Listing all of them can create very long lists.
1978 Setting this variable to nil causes subtrees of a match to be skipped.
1979 This option is off by default, because inheritance in on. If you turn
1980 inheritance off, you very likely want to turn this option on.
1982 As a special case, if the tag search is restricted to TODO items, the
1983 value of this variable is ignored and sublevels are always checked, to
1984 make sure all corresponding TODO items find their way into the list."
1985 :group 'org-tags
1986 :type 'boolean)
1988 (defvar org-tags-history nil
1989 "History of minibuffer reads for tags.")
1990 (defvar org-last-tags-completion-table nil
1991 "The last used completion table for tags.")
1992 (defvar org-after-tags-change-hook nil
1993 "Hook that is run after the tags in a line have changed.")
1995 (defgroup org-properties nil
1996 "Options concerning properties in Org-mode."
1997 :tag "Org Properties"
1998 :group 'org)
2000 (defcustom org-property-format "%-10s %s"
2001 "How property key/value pairs should be formatted by `indent-line'.
2002 When `indent-line' hits a property definition, it will format the line
2003 according to this format, mainly to make sure that the values are
2004 lined-up with respect to each other."
2005 :group 'org-properties
2006 :type 'string)
2008 (defcustom org-use-property-inheritance nil
2009 "Non-nil means, properties apply also for sublevels.
2010 This setting is only relevant during property searches, not when querying
2011 an entry with `org-entry-get'. To retrieve a property with inheritance,
2012 you need to call `org-entry-get' with the inheritance flag.
2013 Turning this on can cause significant overhead when doing a search, so
2014 this is turned off by default.
2015 When nil, only the properties directly given in the current entry count.
2016 The value may also be a list of properties that shouldhave inheritance.
2018 However, note that some special properties use inheritance under special
2019 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2020 and the properties ending in \"_ALL\" when they are used as descriptor
2021 for valid values of a property."
2022 :group 'org-properties
2023 :type '(choice
2024 (const :tag "Not" nil)
2025 (const :tag "Always" nil)
2026 (repeat :tag "Specific properties")))
2028 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2029 "The default column format, if no other format has been defined.
2030 This variable can be set on the per-file basis by inserting a line
2032 #+COLUMNS: %25ITEM ....."
2033 :group 'org-properties
2034 :type 'string)
2036 (defcustom org-global-properties nil
2037 "List of property/value pairs that can be inherited by any entry.
2038 You can set buffer-local values for this by adding lines like
2040 #+PROPERTY: NAME VALUE"
2041 :group 'org-properties
2042 :type '(repeat
2043 (cons (string :tag "Property")
2044 (string :tag "Value"))))
2046 (defvar org-local-properties nil
2047 "List of property/value pairs that can be inherited by any entry.
2048 Valid for the current buffer.
2049 This variable is populated from #+PROPERTY lines.")
2051 (defgroup org-agenda nil
2052 "Options concerning agenda views in Org-mode."
2053 :tag "Org Agenda"
2054 :group 'org)
2056 (defvar org-category nil
2057 "Variable used by org files to set a category for agenda display.
2058 Such files should use a file variable to set it, for example
2060 # -*- mode: org; org-category: \"ELisp\"
2062 or contain a special line
2064 #+CATEGORY: ELisp
2066 If the file does not specify a category, then file's base name
2067 is used instead.")
2068 (make-variable-buffer-local 'org-category)
2070 (defcustom org-agenda-files nil
2071 "The files to be used for agenda display.
2072 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2073 \\[org-remove-file]. You can also use customize to edit the list.
2075 If an entry is a directory, all files in that directory that are matched by
2076 `org-agenda-file-regexp' will be part of the file list.
2078 If the value of the variable is not a list but a single file name, then
2079 the list of agenda files is actually stored and maintained in that file, one
2080 agenda file per line."
2081 :group 'org-agenda
2082 :type '(choice
2083 (repeat :tag "List of files and directories" file)
2084 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2086 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2087 "Regular expression to match files for `org-agenda-files'.
2088 If any element in the list in that variable contains a directory instead
2089 of a normal file, all files in that directory that are matched by this
2090 regular expression will be included."
2091 :group 'org-agenda
2092 :type 'regexp)
2094 (defcustom org-agenda-skip-unavailable-files nil
2095 "t means to just skip non-reachable files in `org-agenda-files'.
2096 Nil means to remove them, after a query, from the list."
2097 :group 'org-agenda
2098 :type 'boolean)
2100 (defcustom org-agenda-multi-occur-extra-files nil
2101 "List of extra files to be searched by `org-occur-in-agenda-files'.
2102 The files in `org-agenda-files' are always searched."
2103 :group 'org-agenda
2104 :type '(repeat file))
2106 (defcustom org-agenda-confirm-kill 1
2107 "When set, remote killing from the agenda buffer needs confirmation.
2108 When t, a confirmation is always needed. When a number N, confirmation is
2109 only needed when the text to be killed contains more than N non-white lines."
2110 :group 'org-agenda
2111 :type '(choice
2112 (const :tag "Never" nil)
2113 (const :tag "Always" t)
2114 (number :tag "When more than N lines")))
2116 (defcustom org-calendar-to-agenda-key [?c]
2117 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2118 The command `org-calendar-goto-agenda' will be bound to this key. The
2119 default is the character `c' because then `c' can be used to switch back and
2120 forth between agenda and calendar."
2121 :group 'org-agenda
2122 :type 'sexp)
2124 (defcustom org-agenda-compact-blocks nil
2125 "Non-nil means, make the block agenda more compact.
2126 This is done by leaving out unnecessary lines."
2127 :group 'org-agenda
2128 :type nil)
2130 (defgroup org-agenda-export nil
2131 "Options concerning exporting agenda views in Org-mode."
2132 :tag "Org Agenda Export"
2133 :group 'org-agenda)
2135 (defcustom org-agenda-with-colors t
2136 "Non-nil means, use colors in agenda views."
2137 :group 'org-agenda-export
2138 :type 'boolean)
2140 (defcustom org-agenda-exporter-settings nil
2141 "Alist of variable/value pairs that should be active during agenda export.
2142 This is a good place to set uptions for ps-print and for htmlize."
2143 :group 'org-agenda-export
2144 :type '(repeat
2145 (list
2146 (variable)
2147 (sexp :tag "Value"))))
2149 (defcustom org-agenda-export-html-style ""
2150 "The style specification for exported HTML Agenda files.
2151 If this variable contains a string, it will replace the default <style>
2152 section as produced by `htmlize'.
2153 Since there are different ways of setting style information, this variable
2154 needs to contain the full HTML structure to provide a style, including the
2155 surrounding HTML tags. The style specifications should include definitions
2156 the fonts used by the agenda, here is an example:
2158 <style type=\"text/css\">
2159 p { font-weight: normal; color: gray; }
2160 .org-agenda-structure {
2161 font-size: 110%;
2162 color: #003399;
2163 font-weight: 600;
2165 .org-todo {
2166 color: #cc6666;Week-agenda:
2167 font-weight: bold;
2169 .org-done {
2170 color: #339933;
2172 .title { text-align: center; }
2173 .todo, .deadline { color: red; }
2174 .done { color: green; }
2175 </style>
2177 or, if you want to keep the style in a file,
2179 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2181 As the value of this option simply gets inserted into the HTML <head> header,
2182 you can \"misuse\" it to also add other text to the header. However,
2183 <style>...</style> is required, if not present the variable will be ignored."
2184 :group 'org-agenda-export
2185 :group 'org-export-html
2186 :type 'string)
2188 (defgroup org-agenda-custom-commands nil
2189 "Options concerning agenda views in Org-mode."
2190 :tag "Org Agenda Custom Commands"
2191 :group 'org-agenda)
2193 (defcustom org-agenda-custom-commands nil
2194 "Custom commands for the agenda.
2195 These commands will be offered on the splash screen displayed by the
2196 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2198 (key desc type match options files)
2200 key The key (one or more characters as a string) to be associated
2201 with the command.
2202 desc A description of the commend, when omitted or nil, a default
2203 description is built using MATCH.
2204 type The command type, any of the following symbols:
2205 todo Entries with a specific TODO keyword, in all agenda files.
2206 tags Tags match in all agenda files.
2207 tags-todo Tags match in all agenda files, TODO entries only.
2208 todo-tree Sparse tree of specific TODO keyword in *current* file.
2209 tags-tree Sparse tree with all tags matches in *current* file.
2210 occur-tree Occur sparse tree for *current* file.
2211 ... A user-defined function.
2212 match What to search for:
2213 - a single keyword for TODO keyword searches
2214 - a tags match expression for tags searches
2215 - a regular expression for occur searches
2216 options A list of option settings, similar to that in a let form, so like
2217 this: ((opt1 val1) (opt2 val2) ...)
2218 files A list of files file to write the produced agenda buffer to
2219 with the command `org-store-agenda-views'.
2220 If a file name ends in \".html\", an HTML version of the buffer
2221 is written out. If it ends in \".ps\", a postscript version is
2222 produced. Otherwide, only the plain text is written to the file.
2224 You can also define a set of commands, to create a composite agenda buffer.
2225 In this case, an entry looks like this:
2227 (key desc (cmd1 cmd2 ...) general-options file)
2229 where
2231 desc A description string to be displayed in the dispatcher menu.
2232 cmd An agenda command, similar to the above. However, tree commands
2233 are no allowed, but instead you can get agenda and global todo list.
2234 So valid commands for a set are:
2235 (agenda)
2236 (alltodo)
2237 (stuck)
2238 (todo \"match\" options files)
2239 (tags \"match\" options files)
2240 (tags-todo \"match\" options files)
2242 Each command can carry a list of options, and another set of options can be
2243 given for the whole set of commands. Individual command options take
2244 precedence over the general options.
2246 When using several characters as key to a command, the first characters
2247 are prefix commands. For the dispatcher to display useful information, you
2248 should provide a description for the prefix, like
2250 (setq org-agenda-custom-commands
2251 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2252 (\"hl\" tags \"+HOME+Lisa\")
2253 (\"hp\" tags \"+HOME+Peter\")
2254 (\"hk\" tags \"+HOME+Kim\")))"
2255 :group 'org-agenda-custom-commands
2256 :type '(repeat
2257 (choice :value ("a" "" tags "" nil)
2258 (list :tag "Single command"
2259 (string :tag "Access Key(s) ")
2260 (option (string :tag "Description"))
2261 (choice
2262 (const :tag "Agenda" agenda)
2263 (const :tag "TODO list" alltodo)
2264 (const :tag "Stuck projects" stuck)
2265 (const :tag "Tags search (all agenda files)" tags)
2266 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2267 (const :tag "TODO keyword search (all agenda files)" todo)
2268 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2269 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2270 (const :tag "Occur tree (current buffer)" occur-tree)
2271 (sexp :tag "Other, user-defined function"))
2272 (string :tag "Match")
2273 (repeat :tag "Local options"
2274 (list (variable :tag "Option") (sexp :tag "Value")))
2275 (option (repeat :tag "Export" (file :tag "Export to"))))
2276 (list :tag "Command series, all agenda files"
2277 (string :tag "Access Key(s)")
2278 (string :tag "Description ")
2279 (repeat
2280 (choice
2281 (const :tag "Agenda" (agenda))
2282 (const :tag "TODO list" (alltodo))
2283 (const :tag "Stuck projects" (stuck))
2284 (list :tag "Tags search"
2285 (const :format "" tags)
2286 (string :tag "Match")
2287 (repeat :tag "Local options"
2288 (list (variable :tag "Option")
2289 (sexp :tag "Value"))))
2291 (list :tag "Tags search, TODO entries only"
2292 (const :format "" tags-todo)
2293 (string :tag "Match")
2294 (repeat :tag "Local options"
2295 (list (variable :tag "Option")
2296 (sexp :tag "Value"))))
2298 (list :tag "TODO keyword search"
2299 (const :format "" todo)
2300 (string :tag "Match")
2301 (repeat :tag "Local options"
2302 (list (variable :tag "Option")
2303 (sexp :tag "Value"))))
2305 (list :tag "Other, user-defined function"
2306 (symbol :tag "function")
2307 (string :tag "Match")
2308 (repeat :tag "Local options"
2309 (list (variable :tag "Option")
2310 (sexp :tag "Value"))))))
2312 (repeat :tag "General options"
2313 (list (variable :tag "Option")
2314 (sexp :tag "Value")))
2315 (option (repeat :tag "Export" (file :tag "Export to"))))
2316 (cons :tag "Prefix key documentation"
2317 (string :tag "Access Key(s)")
2318 (string :tag "Description ")))))
2320 (defcustom org-stuck-projects
2321 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2322 "How to identify stuck projects.
2323 This is a list of four items:
2324 1. A tags/todo matcher string that is used to identify a project.
2325 The entire tree below a headline matched by this is considered one project.
2326 2. A list of TODO keywords identifying non-stuck projects.
2327 If the project subtree contains any headline with one of these todo
2328 keywords, the project is considered to be not stuck. If you specify
2329 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2330 3. A list of tags identifying non-stuck projects.
2331 If the project subtree contains any headline with one of these tags,
2332 the project is considered to be not stuck. If you specify \"*\" as
2333 a tag, any tag will mark the project unstuck.
2334 4. An arbitrary regular expression matching non-stuck projects.
2336 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2337 or `C-c a #' to produce the list."
2338 :group 'org-agenda-custom-commands
2339 :type '(list
2340 (string :tag "Tags/TODO match to identify a project")
2341 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2342 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2343 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2346 (defgroup org-agenda-skip nil
2347 "Options concerning skipping parts of agenda files."
2348 :tag "Org Agenda Skip"
2349 :group 'org-agenda)
2351 (defcustom org-agenda-todo-list-sublevels t
2352 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2353 When nil, the sublevels of a TODO entry are not checked, resulting in
2354 potentially much shorter TODO lists."
2355 :group 'org-agenda-skip
2356 :group 'org-todo
2357 :type 'boolean)
2359 (defcustom org-agenda-todo-ignore-with-date nil
2360 "Non-nil means, don't show entries with a date in the global todo list.
2361 You can use this if you prefer to mark mere appointments with a TODO keyword,
2362 but don't want them to show up in the TODO list.
2363 When this is set, it also covers deadlines and scheduled items, the settings
2364 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2365 will be ignored."
2366 :group 'org-agenda-skip
2367 :group 'org-todo
2368 :type 'boolean)
2370 (defcustom org-agenda-todo-ignore-scheduled nil
2371 "Non-nil means, don't show scheduled entries in the global todo list.
2372 The idea behind this is that by scheduling it, you have already taken care
2373 of this item.
2374 See also `org-agenda-todo-ignore-with-date'."
2375 :group 'org-agenda-skip
2376 :group 'org-todo
2377 :type 'boolean)
2379 (defcustom org-agenda-todo-ignore-deadlines nil
2380 "Non-nil means, don't show near deadline entries in the global todo list.
2381 Near means closer than `org-deadline-warning-days' days.
2382 The idea behind this is that such items will appear in the agenda anyway.
2383 See also `org-agenda-todo-ignore-with-date'."
2384 :group 'org-agenda-skip
2385 :group 'org-todo
2386 :type 'boolean)
2388 (defcustom org-agenda-skip-scheduled-if-done nil
2389 "Non-nil means don't show scheduled items in agenda when they are done.
2390 This is relevant for the daily/weekly agenda, not for the TODO list. And
2391 it applies only to the actual date of the scheduling. Warnings about
2392 an item with a past scheduling dates are always turned off when the item
2393 is DONE."
2394 :group 'org-agenda-skip
2395 :type 'boolean)
2397 (defcustom org-agenda-skip-deadline-if-done nil
2398 "Non-nil means don't show deadines when the corresponding item is done.
2399 When nil, the deadline is still shown and should give you a happy feeling.
2400 This is relevant for the daily/weekly agenda. And it applied only to the
2401 actualy date of the deadline. Warnings about approching and past-due
2402 deadlines are always turned off when the item is DONE."
2403 :group 'org-agenda-skip
2404 :type 'boolean)
2406 (defcustom org-agenda-skip-timestamp-if-done nil
2407 "Non-nil means don't don't select item by timestamp or -range if it is DONE."
2408 :group 'org-agenda-skip
2409 :type 'boolean)
2411 (defcustom org-timeline-show-empty-dates 3
2412 "Non-nil means, `org-timeline' also shows dates without an entry.
2413 When nil, only the days which actually have entries are shown.
2414 When t, all days between the first and the last date are shown.
2415 When an integer, show also empty dates, but if there is a gap of more than
2416 N days, just insert a special line indicating the size of the gap."
2417 :group 'org-agenda-skip
2418 :type '(choice
2419 (const :tag "None" nil)
2420 (const :tag "All" t)
2421 (number :tag "at most")))
2424 (defgroup org-agenda-startup nil
2425 "Options concerning initial settings in the Agenda in Org Mode."
2426 :tag "Org Agenda Startup"
2427 :group 'org-agenda)
2429 (defcustom org-finalize-agenda-hook nil
2430 "Hook run just before displaying an agenda buffer."
2431 :group 'org-agenda-startup
2432 :type 'hook)
2434 (defcustom org-agenda-mouse-1-follows-link nil
2435 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2436 A longer mouse click will still set point. Does not wortk on XEmacs.
2437 Needs to be set before org.el is loaded."
2438 :group 'org-agenda-startup
2439 :type 'boolean)
2441 (defcustom org-agenda-start-with-follow-mode nil
2442 "The initial value of follow-mode in a newly created agenda window."
2443 :group 'org-agenda-startup
2444 :type 'boolean)
2446 (defgroup org-agenda-windows nil
2447 "Options concerning the windows used by the Agenda in Org Mode."
2448 :tag "Org Agenda Windows"
2449 :group 'org-agenda)
2451 (defcustom org-agenda-window-setup 'reorganize-frame
2452 "How the agenda buffer should be displayed.
2453 Possible values for this option are:
2455 current-window Show agenda in the current window, keeping all other windows.
2456 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2457 other-window Use `switch-to-buffer-other-window' to display agenda.
2458 reorganize-frame Show only two windows on the current frame, the current
2459 window and the agenda.
2460 See also the variable `org-agenda-restore-windows-after-quit'."
2461 :group 'org-agenda-windows
2462 :type '(choice
2463 (const current-window)
2464 (const other-frame)
2465 (const other-window)
2466 (const reorganize-frame)))
2468 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2469 "The min and max height of the agenda window as a fraction of frame height.
2470 The value of the variable is a cons cell with two numbers between 0 and 1.
2471 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2472 :group 'org-agenda-windows
2473 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2475 (defcustom org-agenda-restore-windows-after-quit nil
2476 "Non-nil means, restore window configuration open exiting agenda.
2477 Before the window configuration is changed for displaying the agenda,
2478 the current status is recorded. When the agenda is exited with
2479 `q' or `x' and this option is set, the old state is restored. If
2480 `org-agenda-window-setup' is `other-frame', the value of this
2481 option will be ignored.."
2482 :group 'org-agenda-windows
2483 :type 'boolean)
2485 (defcustom org-indirect-buffer-display 'other-window
2486 "How should indirect tree buffers be displayed?
2487 This applies to indirect buffers created with the commands
2488 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2489 Valid values are:
2490 current-window Display in the current window
2491 other-window Just display in another window.
2492 dedicated-frame Create one new frame, and re-use it each time.
2493 new-frame Make a new frame each time. Note that in this case
2494 previously-made indirect buffers are kept, and you need to
2495 kill these buffers yourself."
2496 :group 'org-structure
2497 :group 'org-agenda-windows
2498 :type '(choice
2499 (const :tag "In current window" current-window)
2500 (const :tag "In current frame, other window" other-window)
2501 (const :tag "Each time a new frame" new-frame)
2502 (const :tag "One dedicated frame" dedicated-frame)))
2504 (defgroup org-agenda-daily/weekly nil
2505 "Options concerning the daily/weekly agenda."
2506 :tag "Org Agenda Daily/Weekly"
2507 :group 'org-agenda)
2509 (defcustom org-agenda-ndays 7
2510 "Number of days to include in overview display.
2511 Should be 1 or 7."
2512 :group 'org-agenda-daily/weekly
2513 :type 'number)
2515 (defcustom org-agenda-start-on-weekday 1
2516 "Non-nil means, start the overview always on the specified weekday.
2517 0 denotes Sunday, 1 denotes Monday etc.
2518 When nil, always start on the current day."
2519 :group 'org-agenda-daily/weekly
2520 :type '(choice (const :tag "Today" nil)
2521 (number :tag "Weekday No.")))
2523 (defcustom org-agenda-show-all-dates t
2524 "Non-nil means, `org-agenda' shows every day in the selected range.
2525 When nil, only the days which actually have entries are shown."
2526 :group 'org-agenda-daily/weekly
2527 :type 'boolean)
2529 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2530 "Format string for displaying dates in the agenda.
2531 Used by the daily/weekly agenda and by the timeline. This should be
2532 a format string understood by `format-time-string', or a function returning
2533 the formatted date as a string. The function must take a single argument,
2534 a calendar-style date list like (month day year)."
2535 :group 'org-agenda-daily/weekly
2536 :type '(choice
2537 (string :tag "Format string")
2538 (function :tag "Function")))
2540 (defun org-agenda-format-date-aligned (date)
2541 "Format a date string for display in the daily/weekly agenda, or timeline.
2542 This function makes sure that dates are aligned for easy reading."
2543 (format "%-9s %2d %s %4d"
2544 (calendar-day-name date)
2545 (extract-calendar-day date)
2546 (calendar-month-name (extract-calendar-month date))
2547 (extract-calendar-year date)))
2549 (defcustom org-agenda-include-diary nil
2550 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2551 :group 'org-agenda-daily/weekly
2552 :type 'boolean)
2554 (defcustom org-agenda-include-all-todo nil
2555 "Set means weekly/daily agenda will always contain all TODO entries.
2556 The TODO entries will be listed at the top of the agenda, before
2557 the entries for specific days."
2558 :group 'org-agenda-daily/weekly
2559 :type 'boolean)
2561 (defcustom org-agenda-repeating-timestamp-show-all t
2562 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2563 When nil, only one occurence is shown, either today or the
2564 nearest into the future."
2565 :group 'org-agenda-daily/weekly
2566 :type 'boolean)
2568 (defcustom org-deadline-warning-days 14
2569 "No. of days before expiration during which a deadline becomes active.
2570 This variable governs the display in sparse trees and in the agenda.
2571 When negative, it means use this number (the absolute value of it)
2572 even if a deadline has a different individual lead time specified."
2573 :group 'org-time
2574 :group 'org-agenda-daily/weekly
2575 :type 'number)
2577 (defcustom org-scheduled-past-days 10000
2578 "No. of days to continue listing scheduled items that are not marked DONE.
2579 When an item is scheduled on a date, it shows up in the agenda on this
2580 day and will be listed until it is marked done for the number of days
2581 given here."
2582 :group 'org-agenda-daily/weekly
2583 :type 'number)
2585 (defgroup org-agenda-time-grid nil
2586 "Options concerning the time grid in the Org-mode Agenda."
2587 :tag "Org Agenda Time Grid"
2588 :group 'org-agenda)
2590 (defcustom org-agenda-use-time-grid t
2591 "Non-nil means, show a time grid in the agenda schedule.
2592 A time grid is a set of lines for specific times (like every two hours between
2593 8:00 and 20:00). The items scheduled for a day at specific times are
2594 sorted in between these lines.
2595 For details about when the grid will be shown, and what it will look like, see
2596 the variable `org-agenda-time-grid'."
2597 :group 'org-agenda-time-grid
2598 :type 'boolean)
2600 (defcustom org-agenda-time-grid
2601 '((daily today require-timed)
2602 "----------------"
2603 (800 1000 1200 1400 1600 1800 2000))
2605 "The settings for time grid for agenda display.
2606 This is a list of three items. The first item is again a list. It contains
2607 symbols specifying conditions when the grid should be displayed:
2609 daily if the agenda shows a single day
2610 weekly if the agenda shows an entire week
2611 today show grid on current date, independent of daily/weekly display
2612 require-timed show grid only if at least one item has a time specification
2614 The second item is a string which will be places behing the grid time.
2616 The third item is a list of integers, indicating the times that should have
2617 a grid line."
2618 :group 'org-agenda-time-grid
2619 :type
2620 '(list
2621 (set :greedy t :tag "Grid Display Options"
2622 (const :tag "Show grid in single day agenda display" daily)
2623 (const :tag "Show grid in weekly agenda display" weekly)
2624 (const :tag "Always show grid for today" today)
2625 (const :tag "Show grid only if any timed entries are present"
2626 require-timed)
2627 (const :tag "Skip grid times already present in an entry"
2628 remove-match))
2629 (string :tag "Grid String")
2630 (repeat :tag "Grid Times" (integer :tag "Time"))))
2632 (defgroup org-agenda-sorting nil
2633 "Options concerning sorting in the Org-mode Agenda."
2634 :tag "Org Agenda Sorting"
2635 :group 'org-agenda)
2637 (let ((sorting-choice
2638 '(choice
2639 (const time-up) (const time-down)
2640 (const category-keep) (const category-up) (const category-down)
2641 (const tag-down) (const tag-up)
2642 (const priority-up) (const priority-down))))
2644 (defcustom org-agenda-sorting-strategy
2645 '((agenda time-up category-keep priority-down)
2646 (todo category-keep priority-down)
2647 (tags category-keep priority-down))
2648 "Sorting structure for the agenda items of a single day.
2649 This is a list of symbols which will be used in sequence to determine
2650 if an entry should be listed before another entry. The following
2651 symbols are recognized:
2653 time-up Put entries with time-of-day indications first, early first
2654 time-down Put entries with time-of-day indications first, late first
2655 category-keep Keep the default order of categories, corresponding to the
2656 sequence in `org-agenda-files'.
2657 category-up Sort alphabetically by category, A-Z.
2658 category-down Sort alphabetically by category, Z-A.
2659 tag-up Sort alphabetically by last tag, A-Z.
2660 tag-down Sort alphabetically by last tag, Z-A.
2661 priority-up Sort numerically by priority, high priority last.
2662 priority-down Sort numerically by priority, high priority first.
2664 The different possibilities will be tried in sequence, and testing stops
2665 if one comparison returns a \"not-equal\". For example, the default
2666 '(time-up category-keep priority-down)
2667 means: Pull out all entries having a specified time of day and sort them,
2668 in order to make a time schedule for the current day the first thing in the
2669 agenda listing for the day. Of the entries without a time indication, keep
2670 the grouped in categories, don't sort the categories, but keep them in
2671 the sequence given in `org-agenda-files'. Within each category sort by
2672 priority.
2674 Leaving out `category-keep' would mean that items will be sorted across
2675 categories by priority.
2677 Instead of a single list, this can also be a set of list for specific
2678 contents, with a context symbol in the car of the list, any of
2679 `agenda', `todo', `tags' for the corresponding agenda views."
2680 :group 'org-agenda-sorting
2681 :type `(choice
2682 (repeat :tag "General" ,sorting-choice)
2683 (list :tag "Individually"
2684 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2685 (repeat ,sorting-choice))
2686 (cons (const :tag "Strategy for TODO lists" todo)
2687 (repeat ,sorting-choice))
2688 (cons (const :tag "Strategy for Tags matches" tags)
2689 (repeat ,sorting-choice))))))
2691 (defcustom org-sort-agenda-notime-is-late t
2692 "Non-nil means, items without time are considered late.
2693 This is only relevant for sorting. When t, items which have no explicit
2694 time like 15:30 will be considered as 99:01, i.e. later than any items which
2695 do have a time. When nil, the default time is before 0:00. You can use this
2696 option to decide if the schedule for today should come before or after timeless
2697 agenda entries."
2698 :group 'org-agenda-sorting
2699 :type 'boolean)
2701 (defgroup org-agenda-line-format nil
2702 "Options concerning the entry prefix in the Org-mode agenda display."
2703 :tag "Org Agenda Line Format"
2704 :group 'org-agenda)
2706 (defcustom org-agenda-prefix-format
2707 '((agenda . " %-12:c%?-12t% s")
2708 (timeline . " % s")
2709 (todo . " %-12:c")
2710 (tags . " %-12:c"))
2711 "Format specifications for the prefix of items in the agenda views.
2712 An alist with four entries, for the different agenda types. The keys to the
2713 sublists are `agenda', `timeline', `todo', and `tags'. The values
2714 are format strings.
2715 This format works similar to a printf format, with the following meaning:
2717 %c the category of the item, \"Diary\" for entries from the diary, or
2718 as given by the CATEGORY keyword or derived from the file name.
2719 %T the *last* tag of the item. Last because inherited tags come
2720 first in the list.
2721 %t the time-of-day specification if one applies to the entry, in the
2722 format HH:MM
2723 %s Scheduling/Deadline information, a short string
2725 All specifiers work basically like the standard `%s' of printf, but may
2726 contain two additional characters: A question mark just after the `%' and
2727 a whitespace/punctuation character just before the final letter.
2729 If the first character after `%' is a question mark, the entire field
2730 will only be included if the corresponding value applies to the
2731 current entry. This is useful for fields which should have fixed
2732 width when present, but zero width when absent. For example,
2733 \"%?-12t\" will result in a 12 character time field if a time of the
2734 day is specified, but will completely disappear in entries which do
2735 not contain a time.
2737 If there is punctuation or whitespace character just before the final
2738 format letter, this character will be appended to the field value if
2739 the value is not empty. For example, the format \"%-12:c\" leads to
2740 \"Diary: \" if the category is \"Diary\". If the category were be
2741 empty, no additional colon would be interted.
2743 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2744 - Indent the line with two space characters
2745 - Give the category in a 12 chars wide field, padded with whitespace on
2746 the right (because of `-'). Append a colon if there is a category
2747 (because of `:').
2748 - If there is a time-of-day, put it into a 12 chars wide field. If no
2749 time, don't put in an empty field, just skip it (because of '?').
2750 - Finally, put the scheduling information and append a whitespace.
2752 As another example, if you don't want the time-of-day of entries in
2753 the prefix, you could use:
2755 (setq org-agenda-prefix-format \" %-11:c% s\")
2757 See also the variables `org-agenda-remove-times-when-in-prefix' and
2758 `org-agenda-remove-tags'."
2759 :type '(choice
2760 (string :tag "General format")
2761 (list :greedy t :tag "View dependent"
2762 (cons (const agenda) (string :tag "Format"))
2763 (cons (const timeline) (string :tag "Format"))
2764 (cons (const todo) (string :tag "Format"))
2765 (cons (const tags) (string :tag "Format"))))
2766 :group 'org-agenda-line-format)
2768 (defvar org-prefix-format-compiled nil
2769 "The compiled version of the most recently used prefix format.
2770 See the variable `org-agenda-prefix-format'.")
2772 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2773 "Text preceeding scheduled items in the agenda view.
2774 THis is a list with two strings. The first applies when the item is
2775 scheduled on the current day. The second applies when it has been scheduled
2776 previously, it may contain a %d to capture how many days ago the item was
2777 scheduled."
2778 :group 'org-agenda-line-format
2779 :type '(list
2780 (string :tag "Scheduled today ")
2781 (string :tag "Scheduled previously")))
2783 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2784 "Text preceeding deadline items in the agenda view.
2785 This is a list with two strings. The first applies when the item has its
2786 deadline on the current day. The second applies when it is in the past or
2787 in the future, it may contain %d to capture how many days away the deadline
2788 is (was)."
2789 :group 'org-agenda-line-format
2790 :type '(list
2791 (string :tag "Deadline today ")
2792 (string :tag "Deadline relative")))
2794 (defcustom org-agenda-remove-times-when-in-prefix t
2795 "Non-nil means, remove duplicate time specifications in agenda items.
2796 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2797 time-of-day specification in a headline or diary entry is extracted and
2798 placed into the prefix. If this option is non-nil, the original specification
2799 \(a timestamp or -range, or just a plain time(range) specification like
2800 11:30-4pm) will be removed for agenda display. This makes the agenda less
2801 cluttered.
2802 The option can be t or nil. It may also be the symbol `beg', indicating
2803 that the time should only be removed what it is located at the beginning of
2804 the headline/diary entry."
2805 :group 'org-agenda-line-format
2806 :type '(choice
2807 (const :tag "Always" t)
2808 (const :tag "Never" nil)
2809 (const :tag "When at beginning of entry" beg)))
2812 (defcustom org-agenda-default-appointment-duration nil
2813 "Default duration for appointments that only have a starting time.
2814 When nil, no duration is specified in such cases.
2815 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2816 :group 'org-agenda-line-format
2817 :type '(choice
2818 (integer :tag "Minutes")
2819 (const :tag "No default duration")))
2822 (defcustom org-agenda-remove-tags nil
2823 "Non-nil means, remove the tags from the headline copy in the agenda.
2824 When this is the symbol `prefix', only remove tags when
2825 `org-agenda-prefix-format' contains a `%T' specifier."
2826 :group 'org-agenda-line-format
2827 :type '(choice
2828 (const :tag "Always" t)
2829 (const :tag "Never" nil)
2830 (const :tag "When prefix format contains %T" prefix)))
2832 (if (fboundp 'defvaralias)
2833 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2834 'org-agenda-remove-tags))
2836 (defcustom org-agenda-tags-column -80
2837 "Shift tags in agenda items to this column.
2838 If this number is positive, it specifies the column. If it is negative,
2839 it means that the tags should be flushright to that column. For example,
2840 -80 works well for a normal 80 character screen."
2841 :group 'org-agenda-line-format
2842 :type 'integer)
2844 (if (fboundp 'defvaralias)
2845 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2847 (defcustom org-agenda-fontify-priorities t
2848 "Non-nil means, highlight low and high priorities in agenda.
2849 When t, the highest priority entries are bold, lowest priority italic.
2850 This may also be an association list of priority faces. The face may be
2851 a names face, or a list like `(:background \"Red\")'."
2852 :group 'org-agenda-line-format
2853 :type '(choice
2854 (const :tag "Never" nil)
2855 (const :tag "Defaults" t)
2856 (repeat :tag "Specify"
2857 (list (character :tag "Priority" :value ?A)
2858 (sexp :tag "face")))))
2860 (defgroup org-latex nil
2861 "Options for embedding LaTeX code into Org-mode"
2862 :tag "Org LaTeX"
2863 :group 'org)
2865 (defcustom org-format-latex-options
2866 '(:foreground default :background default :scale 1.0
2867 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2868 :matchers ("begin" "$" "$$" "\\(" "\\["))
2869 "Options for creating images from LaTeX fragments.
2870 This is a property list with the following properties:
2871 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2872 `default' means use the forground of the default face.
2873 :background the background color, or \"Transparent\".
2874 `default' means use the background of the default face.
2875 :scale a scaling factor for the size of the images
2876 :html-foreground, :html-background, :html-scale
2877 The same numbers for HTML export.
2878 :matchers a list indicating which matchers should be used to
2879 find LaTeX fragments. Valid members of this list are:
2880 \"begin\" find environments
2881 \"$\" find math expressions surrounded by $...$
2882 \"$$\" find math expressions surrounded by $$....$$
2883 \"\\(\" find math expressions surrounded by \\(...\\)
2884 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2885 :group 'org-latex
2886 :type 'plist)
2888 (defcustom org-format-latex-header "\\documentclass{article}
2889 \\usepackage{fullpage} % do not remove
2890 \\usepackage{amssymb}
2891 \\usepackage[usenames]{color}
2892 \\usepackage{amsmath}
2893 \\usepackage{latexsym}
2894 \\usepackage[mathscr]{eucal}
2895 \\pagestyle{empty} % do not remove"
2896 "The document header used for processing LaTeX fragments."
2897 :group 'org-latex
2898 :type 'string)
2900 (defgroup org-export nil
2901 "Options for exporting org-listings."
2902 :tag "Org Export"
2903 :group 'org)
2905 (defgroup org-export-general nil
2906 "General options for exporting Org-mode files."
2907 :tag "Org Export General"
2908 :group 'org-export)
2910 ;; FIXME
2911 (defvar org-export-publishing-directory nil)
2913 (defcustom org-export-with-special-strings t
2914 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
2915 When this option is turned on, these strings will be exported as:
2917 Org HTML LaTeX
2918 -----+----------+--------
2919 \\- &shy; \\-
2920 -- &ndash; --
2921 --- &mdash; ---
2922 ... &hellip; \ldots
2924 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
2925 :group 'org-export-translation
2926 :type 'boolean)
2928 (defcustom org-export-language-setup
2929 '(("en" "Author" "Date" "Table of Contents")
2930 ("cs" "Autor" "Datum" "Obsah")
2931 ("da" "Ophavsmand" "Dato" "Indhold")
2932 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2933 ("es" "Autor" "Fecha" "\xcdndice")
2934 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2935 ("it" "Autore" "Data" "Indice")
2936 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2937 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2938 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2939 "Terms used in export text, translated to different languages.
2940 Use the variable `org-export-default-language' to set the language,
2941 or use the +OPTION lines for a per-file setting."
2942 :group 'org-export-general
2943 :type '(repeat
2944 (list
2945 (string :tag "HTML language tag")
2946 (string :tag "Author")
2947 (string :tag "Date")
2948 (string :tag "Table of Contents"))))
2950 (defcustom org-export-default-language "en"
2951 "The default language of HTML export, as a string.
2952 This should have an association in `org-export-language-setup'."
2953 :group 'org-export-general
2954 :type 'string)
2956 (defcustom org-export-skip-text-before-1st-heading t
2957 "Non-nil means, skip all text before the first headline when exporting.
2958 When nil, that text is exported as well."
2959 :group 'org-export-general
2960 :type 'boolean)
2962 (defcustom org-export-headline-levels 3
2963 "The last level which is still exported as a headline.
2964 Inferior levels will produce itemize lists when exported.
2965 Note that a numeric prefix argument to an exporter function overrides
2966 this setting.
2968 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2969 :group 'org-export-general
2970 :type 'number)
2972 (defcustom org-export-with-section-numbers t
2973 "Non-nil means, add section numbers to headlines when exporting.
2975 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2976 :group 'org-export-general
2977 :type 'boolean)
2979 (defcustom org-export-with-toc t
2980 "Non-nil means, create a table of contents in exported files.
2981 The TOC contains headlines with levels up to`org-export-headline-levels'.
2982 When an integer, include levels up to N in the toc, this may then be
2983 different from `org-export-headline-levels', but it will not be allowed
2984 to be larger than the number of headline levels.
2985 When nil, no table of contents is made.
2987 Headlines which contain any TODO items will be marked with \"(*)\" in
2988 ASCII export, and with red color in HTML output, if the option
2989 `org-export-mark-todo-in-toc' is set.
2991 In HTML output, the TOC will be clickable.
2993 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2994 or \"toc:3\"."
2995 :group 'org-export-general
2996 :type '(choice
2997 (const :tag "No Table of Contents" nil)
2998 (const :tag "Full Table of Contents" t)
2999 (integer :tag "TOC to level")))
3001 (defcustom org-export-mark-todo-in-toc nil
3002 "Non-nil means, mark TOC lines that contain any open TODO items."
3003 :group 'org-export-general
3004 :type 'boolean)
3006 (defcustom org-export-preserve-breaks nil
3007 "Non-nil means, preserve all line breaks when exporting.
3008 Normally, in HTML output paragraphs will be reformatted. In ASCII
3009 export, line breaks will always be preserved, regardless of this variable.
3011 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3012 :group 'org-export-general
3013 :type 'boolean)
3015 (defcustom org-export-with-archived-trees 'headline
3016 "Whether subtrees with the ARCHIVE tag should be exported.
3017 This can have three different values
3018 nil Do not export, pretend this tree is not present
3019 t Do export the entire tree
3020 headline Only export the headline, but skip the tree below it."
3021 :group 'org-export-general
3022 :group 'org-archive
3023 :type '(choice
3024 (const :tag "not at all" nil)
3025 (const :tag "headline only" 'headline)
3026 (const :tag "entirely" t)))
3028 (defcustom org-export-author-info t
3029 "Non-nil means, insert author name and email into the exported file.
3031 This option can also be set with the +OPTIONS line,
3032 e.g. \"author-info:nil\"."
3033 :group 'org-export-general
3034 :type 'boolean)
3036 (defcustom org-export-time-stamp-file t
3037 "Non-nil means, insert a time stamp into the exported file.
3038 The time stamp shows when the file was created.
3040 This option can also be set with the +OPTIONS line,
3041 e.g. \"timestamp:nil\"."
3042 :group 'org-export-general
3043 :type 'boolean)
3045 (defcustom org-export-with-timestamps t
3046 "If nil, do not export time stamps and associated keywords."
3047 :group 'org-export-general
3048 :type 'boolean)
3050 (defcustom org-export-remove-timestamps-from-toc t
3051 "If nil, remove timestamps from the table of contents entries."
3052 :group 'org-export-general
3053 :type 'boolean)
3055 (defcustom org-export-with-tags 'not-in-toc
3056 "If nil, do not export tags, just remove them from headlines.
3057 If this is the symbol `not-in-toc', tags will be removed from table of
3058 contents entries, but still be shown in the headlines of the document.
3060 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3061 :group 'org-export-general
3062 :type '(choice
3063 (const :tag "Off" nil)
3064 (const :tag "Not in TOC" not-in-toc)
3065 (const :tag "On" t)))
3067 (defcustom org-export-with-drawers nil
3068 "Non-nil means, export with drawers like the property drawer.
3069 When t, all drawers are exported. This may also be a list of
3070 drawer names to export."
3071 :group 'org-export-general
3072 :type '(choice
3073 (const :tag "All drawers" t)
3074 (const :tag "None" nil)
3075 (repeat :tag "Selected drawers"
3076 (string :tag "Drawer name"))))
3078 (defgroup org-export-translation nil
3079 "Options for translating special ascii sequences for the export backends."
3080 :tag "Org Export Translation"
3081 :group 'org-export)
3083 (defcustom org-export-with-emphasize t
3084 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3085 If the export target supports emphasizing text, the word will be
3086 typeset in bold, italic, or underlined, respectively. Works only for
3087 single words, but you can say: I *really* *mean* *this*.
3088 Not all export backends support this.
3090 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3091 :group 'org-export-translation
3092 :type 'boolean)
3094 (defcustom org-export-with-footnotes t
3095 "If nil, export [1] as a footnote marker.
3096 Lines starting with [1] will be formatted as footnotes.
3098 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3099 :group 'org-export-translation
3100 :type 'boolean)
3102 (defcustom org-export-with-sub-superscripts t
3103 "Non-nil means, interpret \"_\" and \"^\" for export.
3104 When this option is turned on, you can use TeX-like syntax for sub- and
3105 superscripts. Several characters after \"_\" or \"^\" will be
3106 considered as a single item - so grouping with {} is normally not
3107 needed. For example, the following things will be parsed as single
3108 sub- or superscripts.
3110 10^24 or 10^tau several digits will be considered 1 item.
3111 10^-12 or 10^-tau a leading sign with digits or a word
3112 x^2-y^3 will be read as x^2 - y^3, because items are
3113 terminated by almost any nonword/nondigit char.
3114 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3116 Still, ambiguity is possible - so when in doubt use {} to enclose the
3117 sub/superscript. If you set this variable to the symbol `{}',
3118 the braces are *required* in order to trigger interpretations as
3119 sub/superscript. This can be helpful in documents that need \"_\"
3120 frequently in plain text.
3122 Not all export backends support this, but HTML does.
3124 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3125 :group 'org-export-translation
3126 :type '(choice
3127 (const :tag "Always interpret" t)
3128 (const :tag "Only with braces" {})
3129 (const :tag "Never interpret" nil)))
3131 (defcustom org-export-with-special-strings t
3132 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3133 When this option is turned on, these strings will be exported as:
3135 \\- : &shy;
3136 -- : &ndash;
3137 --- : &mdash;
3139 Not all export backends support this, but HTML does.
3141 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3142 :group 'org-export-translation
3143 :type 'boolean)
3145 (defcustom org-export-with-TeX-macros t
3146 "Non-nil means, interpret simple TeX-like macros when exporting.
3147 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3148 No only real TeX macros will work here, but the standard HTML entities
3149 for math can be used as macro names as well. For a list of supported
3150 names in HTML export, see the constant `org-html-entities'.
3151 Not all export backends support this.
3153 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3154 :group 'org-export-translation
3155 :group 'org-export-latex
3156 :type 'boolean)
3158 (defcustom org-export-with-LaTeX-fragments nil
3159 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3160 When set, the exporter will find LaTeX environments if the \\begin line is
3161 the first non-white thing on a line. It will also find the math delimiters
3162 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3163 display math.
3165 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3166 :group 'org-export-translation
3167 :group 'org-export-latex
3168 :type 'boolean)
3170 (defcustom org-export-with-fixed-width t
3171 "Non-nil means, lines starting with \":\" will be in fixed width font.
3172 This can be used to have pre-formatted text, fragments of code etc. For
3173 example:
3174 : ;; Some Lisp examples
3175 : (while (defc cnt)
3176 : (ding))
3177 will be looking just like this in also HTML. See also the QUOTE keyword.
3178 Not all export backends support this.
3180 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3181 :group 'org-export-translation
3182 :type 'boolean)
3184 (defcustom org-match-sexp-depth 3
3185 "Number of stacked braces for sub/superscript matching.
3186 This has to be set before loading org.el to be effective."
3187 :group 'org-export-translation
3188 :type 'integer)
3190 (defgroup org-export-tables nil
3191 "Options for exporting tables in Org-mode."
3192 :tag "Org Export Tables"
3193 :group 'org-export)
3195 (defcustom org-export-with-tables t
3196 "If non-nil, lines starting with \"|\" define a table.
3197 For example:
3199 | Name | Address | Birthday |
3200 |-------------+----------+-----------|
3201 | Arthur Dent | England | 29.2.2100 |
3203 Not all export backends support this.
3205 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3206 :group 'org-export-tables
3207 :type 'boolean)
3209 (defcustom org-export-highlight-first-table-line t
3210 "Non-nil means, highlight the first table line.
3211 In HTML export, this means use <th> instead of <td>.
3212 In tables created with table.el, this applies to the first table line.
3213 In Org-mode tables, all lines before the first horizontal separator
3214 line will be formatted with <th> tags."
3215 :group 'org-export-tables
3216 :type 'boolean)
3218 (defcustom org-export-table-remove-special-lines t
3219 "Remove special lines and marking characters in calculating tables.
3220 This removes the special marking character column from tables that are set
3221 up for spreadsheet calculations. It also removes the entire lines
3222 marked with `!', `_', or `^'. The lines with `$' are kept, because
3223 the values of constants may be useful to have."
3224 :group 'org-export-tables
3225 :type 'boolean)
3227 (defcustom org-export-prefer-native-exporter-for-tables nil
3228 "Non-nil means, always export tables created with table.el natively.
3229 Natively means, use the HTML code generator in table.el.
3230 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3231 the table does not use row- or column-spanning). This has the
3232 advantage, that the automatic HTML conversions for math symbols and
3233 sub/superscripts can be applied. Org-mode's HTML generator is also
3234 much faster."
3235 :group 'org-export-tables
3236 :type 'boolean)
3238 (defgroup org-export-ascii nil
3239 "Options specific for ASCII export of Org-mode files."
3240 :tag "Org Export ASCII"
3241 :group 'org-export)
3243 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3244 "Characters for underlining headings in ASCII export.
3245 In the given sequence, these characters will be used for level 1, 2, ..."
3246 :group 'org-export-ascii
3247 :type '(repeat character))
3249 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3250 "Bullet characters for headlines converted to lists in ASCII export.
3251 The first character is is used for the first lest level generated in this
3252 way, and so on. If there are more levels than characters given here,
3253 the list will be repeated.
3254 Note that plain lists will keep the same bullets as the have in the
3255 Org-mode file."
3256 :group 'org-export-ascii
3257 :type '(repeat character))
3259 (defgroup org-export-xml nil
3260 "Options specific for XML export of Org-mode files."
3261 :tag "Org Export XML"
3262 :group 'org-export)
3264 (defgroup org-export-html nil
3265 "Options specific for HTML export of Org-mode files."
3266 :tag "Org Export HTML"
3267 :group 'org-export)
3269 (defcustom org-export-html-coding-system nil
3271 :group 'org-export-html
3272 :type 'coding-system)
3274 (defcustom org-export-html-extension "html"
3275 "The extension for exported HTML files."
3276 :group 'org-export-html
3277 :type 'string)
3279 (defcustom org-export-html-style
3280 "<style type=\"text/css\">
3281 html {
3282 font-family: Times, serif;
3283 font-size: 12pt;
3285 .title { text-align: center; }
3286 .todo { color: red; }
3287 .done { color: green; }
3288 .timestamp { color: grey }
3289 .timestamp-kwd { color: CadetBlue }
3290 .tag { background-color:lightblue; font-weight:normal }
3291 .target { background-color: lavender; }
3292 pre {
3293 border: 1pt solid #AEBDCC;
3294 background-color: #F3F5F7;
3295 padding: 5pt;
3296 font-family: courier, monospace;
3298 table { border-collapse: collapse; }
3299 td, th {
3300 vertical-align: top;
3301 <!--border: 1pt solid #ADB9CC;-->
3303 </style>"
3304 "The default style specification for exported HTML files.
3305 Since there are different ways of setting style information, this variable
3306 needs to contain the full HTML structure to provide a style, including the
3307 surrounding HTML tags. The style specifications should include definitions
3308 for new classes todo, done, title, and deadline. For example, legal values
3309 would be:
3311 <style type=\"text/css\">
3312 p { font-weight: normal; color: gray; }
3313 h1 { color: black; }
3314 .title { text-align: center; }
3315 .todo, .deadline { color: red; }
3316 .done { color: green; }
3317 </style>
3319 or, if you want to keep the style in a file,
3321 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3323 As the value of this option simply gets inserted into the HTML <head> header,
3324 you can \"misuse\" it to add arbitrary text to the header."
3325 :group 'org-export-html
3326 :type 'string)
3329 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3330 "Format for typesetting the document title in HTML export."
3331 :group 'org-export-html
3332 :type 'string)
3334 (defcustom org-export-html-toplevel-hlevel 2
3335 "The <H> level for level 1 headings in HTML export."
3336 :group 'org-export-html
3337 :type 'string)
3339 (defcustom org-export-html-link-org-files-as-html t
3340 "Non-nil means, make file links to `file.org' point to `file.html'.
3341 When org-mode is exporting an org-mode file to HTML, links to
3342 non-html files are directly put into a href tag in HTML.
3343 However, links to other Org-mode files (recognized by the
3344 extension `.org.) should become links to the corresponding html
3345 file, assuming that the linked org-mode file will also be
3346 converted to HTML.
3347 When nil, the links still point to the plain `.org' file."
3348 :group 'org-export-html
3349 :type 'boolean)
3351 (defcustom org-export-html-inline-images 'maybe
3352 "Non-nil means, inline images into exported HTML pages.
3353 This is done using an <img> tag. When nil, an anchor with href is used to
3354 link to the image. If this option is `maybe', then images in links with
3355 an empty description will be inlined, while images with a description will
3356 be linked only."
3357 :group 'org-export-html
3358 :type '(choice (const :tag "Never" nil)
3359 (const :tag "Always" t)
3360 (const :tag "When there is no description" maybe)))
3362 ;; FIXME: rename
3363 (defcustom org-export-html-expand t
3364 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3365 When nil, these tags will be exported as plain text and therefore
3366 not be interpreted by a browser.
3368 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3369 :group 'org-export-html
3370 :type 'boolean)
3372 (defcustom org-export-html-table-tag
3373 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3374 "The HTML tag that is used to start a table.
3375 This must be a <table> tag, but you may change the options like
3376 borders and spacing."
3377 :group 'org-export-html
3378 :type 'string)
3380 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3381 "The opening tag for table header fields.
3382 This is customizable so that alignment options can be specified."
3383 :group 'org-export-tables
3384 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3386 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3387 "The opening tag for table data fields.
3388 This is customizable so that alignment options can be specified."
3389 :group 'org-export-tables
3390 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3392 (defcustom org-export-html-with-timestamp nil
3393 "If non-nil, write `org-export-html-html-helper-timestamp'
3394 into the exported HTML text. Otherwise, the buffer will just be saved
3395 to a file."
3396 :group 'org-export-html
3397 :type 'boolean)
3399 (defcustom org-export-html-html-helper-timestamp
3400 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3401 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3402 :group 'org-export-html
3403 :type 'string)
3405 (defgroup org-export-icalendar nil
3406 "Options specific for iCalendar export of Org-mode files."
3407 :tag "Org Export iCalendar"
3408 :group 'org-export)
3410 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3411 "The file name for the iCalendar file covering all agenda files.
3412 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3413 The file name should be absolute, the file will be overwritten without warning."
3414 :group 'org-export-icalendar
3415 :type 'file)
3417 (defcustom org-icalendar-include-todo nil
3418 "Non-nil means, export to iCalendar files should also cover TODO items."
3419 :group 'org-export-icalendar
3420 :type '(choice
3421 (const :tag "None" nil)
3422 (const :tag "Unfinished" t)
3423 (const :tag "All" all)))
3425 (defcustom org-icalendar-include-sexps t
3426 "Non-nil means, export to iCalendar files should also cover sexp entries.
3427 These are entries like in the diary, but directly in an Org-mode file."
3428 :group 'org-export-icalendar
3429 :type 'boolean)
3431 (defcustom org-icalendar-include-body 100
3432 "Amount of text below headline to be included in iCalendar export.
3433 This is a number of characters that should maximally be included.
3434 Properties, scheduling and clocking lines will always be removed.
3435 The text will be inserted into the DESCRIPTION field."
3436 :group 'org-export-icalendar
3437 :type '(choice
3438 (const :tag "Nothing" nil)
3439 (const :tag "Everything" t)
3440 (integer :tag "Max characters")))
3442 (defcustom org-icalendar-combined-name "OrgMode"
3443 "Calendar name for the combined iCalendar representing all agenda files."
3444 :group 'org-export-icalendar
3445 :type 'string)
3447 (defgroup org-font-lock nil
3448 "Font-lock settings for highlighting in Org-mode."
3449 :tag "Org Font Lock"
3450 :group 'org)
3452 (defcustom org-level-color-stars-only nil
3453 "Non-nil means fontify only the stars in each headline.
3454 When nil, the entire headline is fontified.
3455 Changing it requires restart of `font-lock-mode' to become effective
3456 also in regions already fontified."
3457 :group 'org-font-lock
3458 :type 'boolean)
3460 (defcustom org-hide-leading-stars nil
3461 "Non-nil means, hide the first N-1 stars in a headline.
3462 This works by using the face `org-hide' for these stars. This
3463 face is white for a light background, and black for a dark
3464 background. You may have to customize the face `org-hide' to
3465 make this work.
3466 Changing it requires restart of `font-lock-mode' to become effective
3467 also in regions already fontified.
3468 You may also set this on a per-file basis by adding one of the following
3469 lines to the buffer:
3471 #+STARTUP: hidestars
3472 #+STARTUP: showstars"
3473 :group 'org-font-lock
3474 :type 'boolean)
3476 (defcustom org-fontify-done-headline nil
3477 "Non-nil means, change the face of a headline if it is marked DONE.
3478 Normally, only the TODO/DONE keyword indicates the state of a headline.
3479 When this is non-nil, the headline after the keyword is set to the
3480 `org-headline-done' as an additional indication."
3481 :group 'org-font-lock
3482 :type 'boolean)
3484 (defcustom org-fontify-emphasized-text t
3485 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3486 Changing this variable requires a restart of Emacs to take effect."
3487 :group 'org-font-lock
3488 :type 'boolean)
3490 (defcustom org-hide-emphasis-markers nil
3491 "Non-nil mean font-lock should hide the emphasis marker characters."
3492 :group 'org-font-lock
3493 :type 'boolean)
3495 (defvar org-emph-re nil
3496 "Regular expression for matching emphasis.")
3497 (defvar org-verbatim-re nil
3498 "Regular expression for matching verbatim text.")
3499 (defvar org-emphasis-regexp-components) ; defined just below
3500 (defvar org-emphasis-alist) ; defined just below
3501 (defun org-set-emph-re (var val)
3502 "Set variable and compute the emphasis regular expression."
3503 (set var val)
3504 (when (and (boundp 'org-emphasis-alist)
3505 (boundp 'org-emphasis-regexp-components)
3506 org-emphasis-alist org-emphasis-regexp-components)
3507 (let* ((e org-emphasis-regexp-components)
3508 (pre (car e))
3509 (post (nth 1 e))
3510 (border (nth 2 e))
3511 (body (nth 3 e))
3512 (nl (nth 4 e))
3513 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3514 (body1 (concat body "*?"))
3515 (markers (mapconcat 'car org-emphasis-alist ""))
3516 (vmarkers (mapconcat
3517 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3518 org-emphasis-alist "")))
3519 ;; make sure special characters appear at the right position in the class
3520 (if (string-match "\\^" markers)
3521 (setq markers (concat (replace-match "" t t markers) "^")))
3522 (if (string-match "-" markers)
3523 (setq markers (concat (replace-match "" t t markers) "-")))
3524 (if (string-match "\\^" vmarkers)
3525 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3526 (if (string-match "-" vmarkers)
3527 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3528 (if (> nl 0)
3529 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3530 (int-to-string nl) "\\}")))
3531 ;; Make the regexp
3532 (setq org-emph-re
3533 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3534 "\\("
3535 "\\([" markers "]\\)"
3536 "\\("
3537 "[^" border "]\\|"
3538 "[^" border (if (and nil stacked) markers) "]"
3539 body1
3540 "[^" border (if (and nil stacked) markers) "]"
3541 "\\)"
3542 "\\3\\)"
3543 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3544 (setq org-verbatim-re
3545 (concat "\\([" pre "]\\|^\\)"
3546 "\\("
3547 "\\([" vmarkers "]\\)"
3548 "\\("
3549 "[^" border "]\\|"
3550 "[^" border "]"
3551 body1
3552 "[^" border "]"
3553 "\\)"
3554 "\\3\\)"
3555 "\\([" post "]\\|$\\)")))))
3557 (defcustom org-emphasis-regexp-components
3558 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3559 "Components used to build the regular expression for emphasis.
3560 This is a list with 6 entries. Terminology: In an emphasis string
3561 like \" *strong word* \", we call the initial space PREMATCH, the final
3562 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3563 and \"trong wor\" is the body. The different components in this variable
3564 specify what is allowed/forbidden in each part:
3566 pre Chars allowed as prematch. Beginning of line will be allowed too.
3567 post Chars allowed as postmatch. End of line will be allowed too.
3568 border The chars *forbidden* as border characters.
3569 body-regexp A regexp like \".\" to match a body character. Don't use
3570 non-shy groups here, and don't allow newline here.
3571 newline The maximum number of newlines allowed in an emphasis exp.
3573 Use customize to modify this, or restart Emacs after changing it."
3574 :group 'org-font-lock
3575 :set 'org-set-emph-re
3576 :type '(list
3577 (sexp :tag "Allowed chars in pre ")
3578 (sexp :tag "Allowed chars in post ")
3579 (sexp :tag "Forbidden chars in border ")
3580 (sexp :tag "Regexp for body ")
3581 (integer :tag "number of newlines allowed")
3582 (option (boolean :tag "Stacking (DISABLED) "))))
3584 (defcustom org-emphasis-alist
3585 '(("*" bold "<b>" "</b>")
3586 ("/" italic "<i>" "</i>")
3587 ("_" underline "<u>" "</u>")
3588 ("=" org-code "<code>" "</code>" verbatim)
3589 ("~" org-verbatim "" "" verbatim)
3590 ("+" (:strike-through t) "<del>" "</del>")
3592 "Special syntax for emphasized text.
3593 Text starting and ending with a special character will be emphasized, for
3594 example *bold*, _underlined_ and /italic/. This variable sets the marker
3595 characters, the face to be used by font-lock for highlighting in Org-mode
3596 Emacs buffers, and the HTML tags to be used for this.
3597 Use customize to modify this, or restart Emacs after changing it."
3598 :group 'org-font-lock
3599 :set 'org-set-emph-re
3600 :type '(repeat
3601 (list
3602 (string :tag "Marker character")
3603 (choice
3604 (face :tag "Font-lock-face")
3605 (plist :tag "Face property list"))
3606 (string :tag "HTML start tag")
3607 (string :tag "HTML end tag")
3608 (option (const verbatim)))))
3610 ;;; The faces
3612 (defgroup org-faces nil
3613 "Faces in Org-mode."
3614 :tag "Org Faces"
3615 :group 'org-font-lock)
3617 (defun org-compatible-face (inherits specs)
3618 "Make a compatible face specification.
3619 If INHERITS is an existing face and if the Emacs version supports it,
3620 just inherit the face. If not, use SPECS to define the face.
3621 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3622 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3623 to the top of the list. The `min-colors' attribute will be removed from
3624 any other entries, and any resulting duplicates will be removed entirely."
3625 (cond
3626 ((and inherits (facep inherits)
3627 (not (featurep 'xemacs)) (> emacs-major-version 22))
3628 ;; In Emacs 23, we use inheritance where possible.
3629 ;; We only do this in Emacs 23, because only there the outline
3630 ;; faces have been changed to the original org-mode-level-faces.
3631 (list (list t :inherit inherits)))
3632 ((or (featurep 'xemacs) (< emacs-major-version 22))
3633 ;; These do not understand the `min-colors' attribute.
3634 (let (r e a)
3635 (while (setq e (pop specs))
3636 (cond
3637 ((memq (car e) '(t default)) (push e r))
3638 ((setq a (member '(min-colors 8) (car e)))
3639 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3640 (cdr e)))))
3641 ((setq a (assq 'min-colors (car e)))
3642 (setq e (cons (delq a (car e)) (cdr e)))
3643 (or (assoc (car e) r) (push e r)))
3644 (t (or (assoc (car e) r) (push e r)))))
3645 (nreverse r)))
3646 (t specs)))
3648 (defface org-hide
3649 '((((background light)) (:foreground "white"))
3650 (((background dark)) (:foreground "black")))
3651 "Face used to hide leading stars in headlines.
3652 The forground color of this face should be equal to the background
3653 color of the frame."
3654 :group 'org-faces)
3656 (defface org-level-1 ;; font-lock-function-name-face
3657 (org-compatible-face
3658 'outline-1
3659 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3660 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3661 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3662 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3663 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3664 (t (:bold t))))
3665 "Face used for level 1 headlines."
3666 :group 'org-faces)
3668 (defface org-level-2 ;; font-lock-variable-name-face
3669 (org-compatible-face
3670 'outline-2
3671 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3672 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3673 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3674 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3675 (t (:bold t))))
3676 "Face used for level 2 headlines."
3677 :group 'org-faces)
3679 (defface org-level-3 ;; font-lock-keyword-face
3680 (org-compatible-face
3681 'outline-3
3682 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3683 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3684 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3685 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3686 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3687 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3688 (t (:bold t))))
3689 "Face used for level 3 headlines."
3690 :group 'org-faces)
3692 (defface org-level-4 ;; font-lock-comment-face
3693 (org-compatible-face
3694 'outline-4
3695 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3696 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3697 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3698 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3699 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3700 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3701 (t (:bold t))))
3702 "Face used for level 4 headlines."
3703 :group 'org-faces)
3705 (defface org-level-5 ;; font-lock-type-face
3706 (org-compatible-face
3707 'outline-5
3708 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3709 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3710 (((class color) (min-colors 8)) (:foreground "green"))))
3711 "Face used for level 5 headlines."
3712 :group 'org-faces)
3714 (defface org-level-6 ;; font-lock-constant-face
3715 (org-compatible-face
3716 'outline-6
3717 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3718 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3719 (((class color) (min-colors 8)) (:foreground "magenta"))))
3720 "Face used for level 6 headlines."
3721 :group 'org-faces)
3723 (defface org-level-7 ;; font-lock-builtin-face
3724 (org-compatible-face
3725 'outline-7
3726 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3727 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3728 (((class color) (min-colors 8)) (:foreground "blue"))))
3729 "Face used for level 7 headlines."
3730 :group 'org-faces)
3732 (defface org-level-8 ;; font-lock-string-face
3733 (org-compatible-face
3734 'outline-8
3735 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3736 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3737 (((class color) (min-colors 8)) (:foreground "green"))))
3738 "Face used for level 8 headlines."
3739 :group 'org-faces)
3741 (defface org-special-keyword ;; font-lock-string-face
3742 (org-compatible-face
3744 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3745 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3746 (t (:italic t))))
3747 "Face used for special keywords."
3748 :group 'org-faces)
3750 (defface org-drawer ;; font-lock-function-name-face
3751 (org-compatible-face
3753 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3754 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3755 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3756 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3757 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3758 (t (:bold t))))
3759 "Face used for drawers."
3760 :group 'org-faces)
3762 (defface org-property-value nil
3763 "Face used for the value of a property."
3764 :group 'org-faces)
3766 (defface org-column
3767 (org-compatible-face
3769 '((((class color) (min-colors 16) (background light))
3770 (:background "grey90"))
3771 (((class color) (min-colors 16) (background dark))
3772 (:background "grey30"))
3773 (((class color) (min-colors 8))
3774 (:background "cyan" :foreground "black"))
3775 (t (:inverse-video t))))
3776 "Face for column display of entry properties."
3777 :group 'org-faces)
3779 (when (fboundp 'set-face-attribute)
3780 ;; Make sure that a fixed-width face is used when we have a column table.
3781 (set-face-attribute 'org-column nil
3782 :height (face-attribute 'default :height)
3783 :family (face-attribute 'default :family)))
3785 (defface org-warning
3786 (org-compatible-face
3787 'font-lock-warning-face
3788 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3789 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3790 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3791 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3792 (t (:bold t))))
3793 "Face for deadlines and TODO keywords."
3794 :group 'org-faces)
3796 (defface org-archived ; similar to shadow
3797 (org-compatible-face
3798 'shadow
3799 '((((class color grayscale) (min-colors 88) (background light))
3800 (:foreground "grey50"))
3801 (((class color grayscale) (min-colors 88) (background dark))
3802 (:foreground "grey70"))
3803 (((class color) (min-colors 8) (background light))
3804 (:foreground "green"))
3805 (((class color) (min-colors 8) (background dark))
3806 (:foreground "yellow"))))
3807 "Face for headline with the ARCHIVE tag."
3808 :group 'org-faces)
3810 (defface org-link
3811 '((((class color) (background light)) (:foreground "Purple" :underline t))
3812 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3813 (t (:underline t)))
3814 "Face for links."
3815 :group 'org-faces)
3817 (defface org-ellipsis
3818 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3819 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3820 (t (:strike-through t)))
3821 "Face for the ellipsis in folded text."
3822 :group 'org-faces)
3824 (defface org-target
3825 '((((class color) (background light)) (:underline t))
3826 (((class color) (background dark)) (:underline t))
3827 (t (:underline t)))
3828 "Face for links."
3829 :group 'org-faces)
3831 (defface org-date
3832 '((((class color) (background light)) (:foreground "Purple" :underline t))
3833 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3834 (t (:underline t)))
3835 "Face for links."
3836 :group 'org-faces)
3838 (defface org-sexp-date
3839 '((((class color) (background light)) (:foreground "Purple"))
3840 (((class color) (background dark)) (:foreground "Cyan"))
3841 (t (:underline t)))
3842 "Face for links."
3843 :group 'org-faces)
3845 (defface org-tag
3846 '((t (:bold t)))
3847 "Face for tags."
3848 :group 'org-faces)
3850 (defface org-todo ; font-lock-warning-face
3851 (org-compatible-face
3853 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3854 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3855 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3856 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3857 (t (:inverse-video t :bold t))))
3858 "Face for TODO keywords."
3859 :group 'org-faces)
3861 (defface org-done ;; font-lock-type-face
3862 (org-compatible-face
3864 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3865 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3866 (((class color) (min-colors 8)) (:foreground "green"))
3867 (t (:bold t))))
3868 "Face used for todo keywords that indicate DONE items."
3869 :group 'org-faces)
3871 (defface org-headline-done ;; font-lock-string-face
3872 (org-compatible-face
3874 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3875 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3876 (((class color) (min-colors 8) (background light)) (:bold nil))))
3877 "Face used to indicate that a headline is DONE.
3878 This face is only used if `org-fontify-done-headline' is set. If applies
3879 to the part of the headline after the DONE keyword."
3880 :group 'org-faces)
3882 (defcustom org-todo-keyword-faces nil
3883 "Faces for specific TODO keywords.
3884 This is a list of cons cells, with TODO keywords in the car
3885 and faces in the cdr. The face can be a symbol, or a property
3886 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3887 :group 'org-faces
3888 :group 'org-todo
3889 :type '(repeat
3890 (cons
3891 (string :tag "keyword")
3892 (sexp :tag "face"))))
3894 (defface org-table ;; font-lock-function-name-face
3895 (org-compatible-face
3897 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3898 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3899 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3900 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3901 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3902 (((class color) (min-colors 8) (background dark)))))
3903 "Face used for tables."
3904 :group 'org-faces)
3906 (defface org-formula
3907 (org-compatible-face
3909 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3910 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3911 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3912 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3913 (t (:bold t :italic t))))
3914 "Face for formulas."
3915 :group 'org-faces)
3917 (defface org-code
3918 (org-compatible-face
3920 '((((class color grayscale) (min-colors 88) (background light))
3921 (:foreground "grey50"))
3922 (((class color grayscale) (min-colors 88) (background dark))
3923 (:foreground "grey70"))
3924 (((class color) (min-colors 8) (background light))
3925 (:foreground "green"))
3926 (((class color) (min-colors 8) (background dark))
3927 (:foreground "yellow"))))
3928 "Face for fixed-with text like code snippets."
3929 :group 'org-faces
3930 :version "22.1")
3932 (defface org-verbatim
3933 (org-compatible-face
3935 '((((class color grayscale) (min-colors 88) (background light))
3936 (:foreground "grey50" :underline t))
3937 (((class color grayscale) (min-colors 88) (background dark))
3938 (:foreground "grey70" :underline t))
3939 (((class color) (min-colors 8) (background light))
3940 (:foreground "green" :underline t))
3941 (((class color) (min-colors 8) (background dark))
3942 (:foreground "yellow" :underline t))))
3943 "Face for fixed-with text like code snippets."
3944 :group 'org-faces
3945 :version "22.1")
3947 (defface org-agenda-structure ;; font-lock-function-name-face
3948 (org-compatible-face
3950 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3951 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3952 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3953 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3954 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3955 (t (:bold t))))
3956 "Face used in agenda for captions and dates."
3957 :group 'org-faces)
3959 (defface org-scheduled-today
3960 (org-compatible-face
3962 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3963 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3964 (((class color) (min-colors 8)) (:foreground "green"))
3965 (t (:bold t :italic t))))
3966 "Face for items scheduled for a certain day."
3967 :group 'org-faces)
3969 (defface org-scheduled-previously
3970 (org-compatible-face
3972 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3973 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3974 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3975 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3976 (t (:bold t))))
3977 "Face for items scheduled previously, and not yet done."
3978 :group 'org-faces)
3980 (defface org-upcoming-deadline
3981 (org-compatible-face
3983 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3984 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3985 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3986 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3987 (t (:bold t))))
3988 "Face for items scheduled previously, and not yet done."
3989 :group 'org-faces)
3991 (defcustom org-agenda-deadline-faces
3992 '((1.0 . org-warning)
3993 (0.5 . org-upcoming-deadline)
3994 (0.0 . default))
3995 "Faces for showing deadlines in the agenda.
3996 This is a list of cons cells. The cdr of each cess is a face to be used,
3997 and it can also just be a like like '(:foreground \"yellow\").
3998 Each car is a fraction of the head-warning time that must have passed for
3999 this the face in the cdr to be used for display. The numbers must be
4000 given in descending order. The head-warning time is normally taken
4001 from `org-deadline-warning-days', but can also be specified in the deadline
4002 timestamp itself, like this:
4004 DEADLINE: <2007-08-13 Mon -8d>
4006 You may use d for days, w for weeks, m for months and y for years. Months
4007 and years will only be treated in an approximate fashion (30.4 days for a
4008 month and 365.24 days for a year)."
4009 :group 'org-faces
4010 :group 'org-agenda-daily/weekly
4011 :type '(repeat
4012 (cons
4013 (number :tag "Fraction of head-warning time passed")
4014 (sexp :tag "Face"))))
4016 (defface org-time-grid ;; font-lock-variable-name-face
4017 (org-compatible-face
4019 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4020 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4021 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4022 "Face used for time grids."
4023 :group 'org-faces)
4025 (defconst org-level-faces
4026 '(org-level-1 org-level-2 org-level-3 org-level-4
4027 org-level-5 org-level-6 org-level-7 org-level-8
4030 (defcustom org-n-level-faces (length org-level-faces)
4031 "The number different faces to be used for headlines.
4032 Org-mode defines 8 different headline faces, so this can be at most 8.
4033 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4034 :type 'number
4035 :group 'org-faces)
4037 ;;; Variables for pre-computed regular expressions, all buffer local
4039 (defvar org-drawer-regexp nil
4040 "Matches first line of a hidden block.")
4041 (make-variable-buffer-local 'org-drawer-regexp)
4042 (defvar org-todo-regexp nil
4043 "Matches any of the TODO state keywords.")
4044 (make-variable-buffer-local 'org-todo-regexp)
4045 (defvar org-not-done-regexp nil
4046 "Matches any of the TODO state keywords except the last one.")
4047 (make-variable-buffer-local 'org-not-done-regexp)
4048 (defvar org-todo-line-regexp nil
4049 "Matches a headline and puts TODO state into group 2 if present.")
4050 (make-variable-buffer-local 'org-todo-line-regexp)
4051 (defvar org-complex-heading-regexp nil
4052 "Matches a headline and puts everything into groups:
4053 group 1: the stars
4054 group 2: The todo keyword, maybe
4055 group 3: Priority cookie
4056 group 4: True headline
4057 group 5: Tags")
4058 (make-variable-buffer-local 'org-complex-heading-regexp)
4059 (defvar org-todo-line-tags-regexp nil
4060 "Matches a headline and puts TODO state into group 2 if present.
4061 Also put tags into group 4 if tags are present.")
4062 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4063 (defvar org-nl-done-regexp nil
4064 "Matches newline followed by a headline with the DONE keyword.")
4065 (make-variable-buffer-local 'org-nl-done-regexp)
4066 (defvar org-looking-at-done-regexp nil
4067 "Matches the DONE keyword a point.")
4068 (make-variable-buffer-local 'org-looking-at-done-regexp)
4069 (defvar org-ds-keyword-length 12
4070 "Maximum length of the Deadline and SCHEDULED keywords.")
4071 (make-variable-buffer-local 'org-ds-keyword-length)
4072 (defvar org-deadline-regexp nil
4073 "Matches the DEADLINE keyword.")
4074 (make-variable-buffer-local 'org-deadline-regexp)
4075 (defvar org-deadline-time-regexp nil
4076 "Matches the DEADLINE keyword together with a time stamp.")
4077 (make-variable-buffer-local 'org-deadline-time-regexp)
4078 (defvar org-deadline-line-regexp nil
4079 "Matches the DEADLINE keyword and the rest of the line.")
4080 (make-variable-buffer-local 'org-deadline-line-regexp)
4081 (defvar org-scheduled-regexp nil
4082 "Matches the SCHEDULED keyword.")
4083 (make-variable-buffer-local 'org-scheduled-regexp)
4084 (defvar org-scheduled-time-regexp nil
4085 "Matches the SCHEDULED keyword together with a time stamp.")
4086 (make-variable-buffer-local 'org-scheduled-time-regexp)
4087 (defvar org-closed-time-regexp nil
4088 "Matches the CLOSED keyword together with a time stamp.")
4089 (make-variable-buffer-local 'org-closed-time-regexp)
4091 (defvar org-keyword-time-regexp nil
4092 "Matches any of the 4 keywords, together with the time stamp.")
4093 (make-variable-buffer-local 'org-keyword-time-regexp)
4094 (defvar org-keyword-time-not-clock-regexp nil
4095 "Matches any of the 3 keywords, together with the time stamp.")
4096 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4097 (defvar org-maybe-keyword-time-regexp nil
4098 "Matches a timestamp, possibly preceeded by a keyword.")
4099 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4100 (defvar org-planning-or-clock-line-re nil
4101 "Matches a line with planning or clock info.")
4102 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4104 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4105 rear-nonsticky t mouse-map t fontified t)
4106 "Properties to remove when a string without properties is wanted.")
4108 (defsubst org-match-string-no-properties (num &optional string)
4109 (if (featurep 'xemacs)
4110 (let ((s (match-string num string)))
4111 (remove-text-properties 0 (length s) org-rm-props s)
4113 (match-string-no-properties num string)))
4115 (defsubst org-no-properties (s)
4116 (if (fboundp 'set-text-properties)
4117 (set-text-properties 0 (length s) nil s)
4118 (remove-text-properties 0 (length s) org-rm-props s))
4121 (defsubst org-get-alist-option (option key)
4122 (cond ((eq key t) t)
4123 ((eq option t) t)
4124 ((assoc key option) (cdr (assoc key option)))
4125 (t (cdr (assq 'default option)))))
4127 (defsubst org-inhibit-invisibility ()
4128 "Modified `buffer-invisibility-spec' for Emacs 21.
4129 Some ops with invisible text do not work correctly on Emacs 21. For these
4130 we turn off invisibility temporarily. Use this in a `let' form."
4131 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4133 (defsubst org-set-local (var value)
4134 "Make VAR local in current buffer and set it to VALUE."
4135 (set (make-variable-buffer-local var) value))
4137 (defsubst org-mode-p ()
4138 "Check if the current buffer is in Org-mode."
4139 (eq major-mode 'org-mode))
4141 (defsubst org-last (list)
4142 "Return the last element of LIST."
4143 (car (last list)))
4145 (defun org-let (list &rest body)
4146 (eval (cons 'let (cons list body))))
4147 (put 'org-let 'lisp-indent-function 1)
4149 (defun org-let2 (list1 list2 &rest body)
4150 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4151 (put 'org-let2 'lisp-indent-function 2)
4152 (defconst org-startup-options
4153 '(("fold" org-startup-folded t)
4154 ("overview" org-startup-folded t)
4155 ("nofold" org-startup-folded nil)
4156 ("showall" org-startup-folded nil)
4157 ("content" org-startup-folded content)
4158 ("hidestars" org-hide-leading-stars t)
4159 ("showstars" org-hide-leading-stars nil)
4160 ("odd" org-odd-levels-only t)
4161 ("oddeven" org-odd-levels-only nil)
4162 ("align" org-startup-align-all-tables t)
4163 ("noalign" org-startup-align-all-tables nil)
4164 ("customtime" org-display-custom-times t)
4165 ("logging" org-log-done t)
4166 ("logdone" org-log-done t)
4167 ("nologging" org-log-done nil)
4168 ("lognotedone" org-log-done done push)
4169 ("lognotestate" org-log-done state push)
4170 ("lognoteclock-out" org-log-done clock-out push)
4171 ("logrepeat" org-log-repeat t)
4172 ("nologrepeat" org-log-repeat nil)
4173 ("constcgs" constants-unit-system cgs)
4174 ("constSI" constants-unit-system SI))
4175 "Variable associated with STARTUP options for org-mode.
4176 Each element is a list of three items: The startup options as written
4177 in the #+STARTUP line, the corresponding variable, and the value to
4178 set this variable to if the option is found. An optional forth element PUSH
4179 means to push this value onto the list in the variable.")
4181 (defun org-set-regexps-and-options ()
4182 "Precompute regular expressions for current buffer."
4183 (when (org-mode-p)
4184 (org-set-local 'org-todo-kwd-alist nil)
4185 (org-set-local 'org-todo-key-alist nil)
4186 (org-set-local 'org-todo-key-trigger nil)
4187 (org-set-local 'org-todo-keywords-1 nil)
4188 (org-set-local 'org-done-keywords nil)
4189 (org-set-local 'org-todo-heads nil)
4190 (org-set-local 'org-todo-sets nil)
4191 (org-set-local 'org-todo-log-states nil)
4192 (let ((re (org-make-options-regexp
4193 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4194 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4195 "CONSTANTS" "PROPERTY" "DRAWERS")))
4196 (splitre "[ \t]+")
4197 kwds kws0 kwsa key value cat arch tags const links hw dws
4198 tail sep kws1 prio props drawers
4199 ex log)
4200 (save-excursion
4201 (save-restriction
4202 (widen)
4203 (goto-char (point-min))
4204 (while (re-search-forward re nil t)
4205 (setq key (match-string 1) value (org-match-string-no-properties 2))
4206 (cond
4207 ((equal key "CATEGORY")
4208 (if (string-match "[ \t]+$" value)
4209 (setq value (replace-match "" t t value)))
4210 (setq cat value))
4211 ((member key '("SEQ_TODO" "TODO"))
4212 (push (cons 'sequence (org-split-string value splitre)) kwds))
4213 ((equal key "TYP_TODO")
4214 (push (cons 'type (org-split-string value splitre)) kwds))
4215 ((equal key "TAGS")
4216 (setq tags (append tags (org-split-string value splitre))))
4217 ((equal key "COLUMNS")
4218 (org-set-local 'org-columns-default-format value))
4219 ((equal key "LINK")
4220 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4221 (push (cons (match-string 1 value)
4222 (org-trim (match-string 2 value)))
4223 links)))
4224 ((equal key "PRIORITIES")
4225 (setq prio (org-split-string value " +")))
4226 ((equal key "PROPERTY")
4227 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4228 (push (cons (match-string 1 value) (match-string 2 value))
4229 props)))
4230 ((equal key "DRAWERS")
4231 (setq drawers (org-split-string value splitre)))
4232 ((equal key "CONSTANTS")
4233 (setq const (append const (org-split-string value splitre))))
4234 ((equal key "STARTUP")
4235 (let ((opts (org-split-string value splitre))
4236 l var val)
4237 (while (setq l (pop opts))
4238 (when (setq l (assoc l org-startup-options))
4239 (setq var (nth 1 l) val (nth 2 l))
4240 (if (not (nth 3 l))
4241 (set (make-local-variable var) val)
4242 (if (not (listp (symbol-value var)))
4243 (set (make-local-variable var) nil))
4244 (set (make-local-variable var) (symbol-value var))
4245 (add-to-list var val))))))
4246 ((equal key "ARCHIVE")
4247 (string-match " *$" value)
4248 (setq arch (replace-match "" t t value))
4249 (remove-text-properties 0 (length arch)
4250 '(face t fontified t) arch)))
4252 (when cat
4253 (org-set-local 'org-category (intern cat))
4254 (push (cons "CATEGORY" cat) props))
4255 (when prio
4256 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4257 (setq prio (mapcar 'string-to-char prio))
4258 (org-set-local 'org-highest-priority (nth 0 prio))
4259 (org-set-local 'org-lowest-priority (nth 1 prio))
4260 (org-set-local 'org-default-priority (nth 2 prio)))
4261 (and props (org-set-local 'org-local-properties (nreverse props)))
4262 (and drawers (org-set-local 'org-drawers drawers))
4263 (and arch (org-set-local 'org-archive-location arch))
4264 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4265 ;; Process the TODO keywords
4266 (unless kwds
4267 ;; Use the global values as if they had been given locally.
4268 (setq kwds (default-value 'org-todo-keywords))
4269 (if (stringp (car kwds))
4270 (setq kwds (list (cons org-todo-interpretation
4271 (default-value 'org-todo-keywords)))))
4272 (setq kwds (reverse kwds)))
4273 (setq kwds (nreverse kwds))
4274 (let (inter kws kw)
4275 (while (setq kws (pop kwds))
4276 (setq inter (pop kws) sep (member "|" kws)
4277 kws0 (delete "|" (copy-sequence kws))
4278 kwsa nil
4279 kws1 (mapcar
4280 (lambda (x)
4281 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4282 (progn
4283 (setq kw (match-string 1 x)
4284 ex (and (match-end 2) (match-string 2 x))
4285 log (and ex (string-match "@" ex))
4286 key (and ex (substring ex 0 1)))
4287 (if (equal key "@") (setq key nil))
4288 (push (cons kw (and key (string-to-char key))) kwsa)
4289 (and log (push kw org-todo-log-states))
4291 (error "Invalid TODO keyword %s" x)))
4292 kws0)
4293 kwsa (if kwsa (append '((:startgroup))
4294 (nreverse kwsa)
4295 '((:endgroup))))
4296 hw (car kws1)
4297 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4298 tail (list inter hw (car dws) (org-last dws)))
4299 (add-to-list 'org-todo-heads hw 'append)
4300 ;????????????????? (setq org-todo-heads (append org-todo-heads (list hw)))
4301 (add-to-list 'org-todo-heads hw 'append)
4302 (push kws1 org-todo-sets)
4303 (setq org-done-keywords (append org-done-keywords dws nil))
4304 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4305 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4306 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4307 (setq org-todo-sets (nreverse org-todo-sets)
4308 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4309 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4310 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4311 ;; Process the constants
4312 (when const
4313 (let (e cst)
4314 (while (setq e (pop const))
4315 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4316 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4317 (setq org-table-formula-constants-local cst)))
4319 ;; Process the tags.
4320 (when tags
4321 (let (e tgs)
4322 (while (setq e (pop tags))
4323 (cond
4324 ((equal e "{") (push '(:startgroup) tgs))
4325 ((equal e "}") (push '(:endgroup) tgs))
4326 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4327 (push (cons (match-string 1 e)
4328 (string-to-char (match-string 2 e)))
4329 tgs))
4330 (t (push (list e) tgs))))
4331 (org-set-local 'org-tag-alist nil)
4332 (while (setq e (pop tgs))
4333 (or (and (stringp (car e))
4334 (assoc (car e) org-tag-alist))
4335 (push e org-tag-alist))))))
4337 ;; Compute the regular expressions and other local variables
4338 (if (not org-done-keywords)
4339 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4340 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4341 (length org-scheduled-string)))
4342 org-drawer-regexp
4343 (concat "^[ \t]*:\\("
4344 (mapconcat 'regexp-quote org-drawers "\\|")
4345 "\\):[ \t]*$")
4346 org-not-done-keywords
4347 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4348 org-todo-regexp
4349 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4350 "\\|") "\\)\\>")
4351 org-not-done-regexp
4352 (concat "\\<\\("
4353 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4354 "\\)\\>")
4355 org-todo-line-regexp
4356 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4357 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4358 "\\)\\>\\)?[ \t]*\\(.*\\)")
4359 org-complex-heading-regexp
4360 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4361 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4362 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4363 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4364 org-nl-done-regexp
4365 (concat "\n\\*+[ \t]+"
4366 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4367 "\\)" "\\>")
4368 org-todo-line-tags-regexp
4369 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4370 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4371 (org-re
4372 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4373 org-looking-at-done-regexp
4374 (concat "^" "\\(?:"
4375 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4376 "\\>")
4377 org-deadline-regexp (concat "\\<" org-deadline-string)
4378 org-deadline-time-regexp
4379 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4380 org-deadline-line-regexp
4381 (concat "\\<\\(" org-deadline-string "\\).*")
4382 org-scheduled-regexp
4383 (concat "\\<" org-scheduled-string)
4384 org-scheduled-time-regexp
4385 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4386 org-closed-time-regexp
4387 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4388 org-keyword-time-regexp
4389 (concat "\\<\\(" org-scheduled-string
4390 "\\|" org-deadline-string
4391 "\\|" org-closed-string
4392 "\\|" org-clock-string "\\)"
4393 " *[[<]\\([^]>]+\\)[]>]")
4394 org-keyword-time-not-clock-regexp
4395 (concat "\\<\\(" org-scheduled-string
4396 "\\|" org-deadline-string
4397 "\\|" org-closed-string
4398 "\\)"
4399 " *[[<]\\([^]>]+\\)[]>]")
4400 org-maybe-keyword-time-regexp
4401 (concat "\\(\\<\\(" org-scheduled-string
4402 "\\|" org-deadline-string
4403 "\\|" org-closed-string
4404 "\\|" org-clock-string "\\)\\)?"
4405 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4406 org-planning-or-clock-line-re
4407 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4408 "\\|" org-deadline-string
4409 "\\|" org-closed-string "\\|" org-clock-string
4410 "\\)\\>\\)")
4412 (org-compute-latex-and-specials-regexp)
4413 (org-set-font-lock-defaults)))
4415 (defun org-remove-keyword-keys (list)
4416 (mapcar (lambda (x)
4417 (if (string-match "(..?)$" x)
4418 (substring x 0 (match-beginning 0))
4420 list))
4422 ;;; Some variables ujsed in various places
4424 (defvar org-window-configuration nil
4425 "Used in various places to store a window configuration.")
4426 (defvar org-finish-function nil
4427 "Function to be called when `C-c C-c' is used.
4428 This is for getting out of special buffers like remember.")
4430 ;;; Foreign variables, to inform the compiler
4432 ;; XEmacs only
4433 (defvar outline-mode-menu-heading)
4434 (defvar outline-mode-menu-show)
4435 (defvar outline-mode-menu-hide)
4436 (defvar zmacs-regions) ; XEmacs regions
4437 ;; Emacs only
4438 (defvar mark-active)
4440 ;; Packages that org-mode interacts with
4441 (defvar calc-embedded-close-formula)
4442 (defvar calc-embedded-open-formula)
4443 (defvar font-lock-unfontify-region-function)
4444 (defvar org-goto-start-pos)
4445 (defvar vm-message-pointer)
4446 (defvar vm-folder-directory)
4447 (defvar wl-summary-buffer-elmo-folder)
4448 (defvar wl-summary-buffer-folder-name)
4449 (defvar gnus-other-frame-object)
4450 (defvar gnus-group-name)
4451 (defvar gnus-article-current)
4452 (defvar w3m-current-url)
4453 (defvar w3m-current-title)
4454 (defvar mh-progs)
4455 (defvar mh-current-folder)
4456 (defvar mh-show-folder-buffer)
4457 (defvar mh-index-folder)
4458 (defvar mh-searcher)
4459 (defvar calendar-mode-map)
4460 (defvar Info-current-file)
4461 (defvar Info-current-node)
4462 (defvar texmathp-why)
4463 (defvar remember-save-after-remembering)
4464 (defvar remember-data-file)
4465 (defvar remember-register)
4466 (defvar remember-buffer)
4467 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
4468 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
4469 (defvar org-latex-regexps)
4470 (defvar constants-unit-system)
4472 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4474 ;; FIXME: Occasionally check by commenting these, to make sure
4475 ;; no other functions uses these, forgetting to let-bind them.
4476 (defvar entry)
4477 (defvar state)
4478 (defvar last-state)
4479 (defvar date)
4480 (defvar description)
4482 ;; Defined somewhere in this file, but used before definition.
4483 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4484 (defvar org-agenda-buffer-name)
4485 (defvar org-agenda-undo-list)
4486 (defvar org-agenda-pending-undo-list)
4487 (defvar org-agenda-overriding-header)
4488 (defvar orgtbl-mode)
4489 (defvar org-html-entities)
4490 (defvar org-struct-menu)
4491 (defvar org-org-menu)
4492 (defvar org-tbl-menu)
4493 (defvar org-agenda-keymap)
4495 ;;;; Emacs/XEmacs compatibility
4497 ;; Overlay compatibility functions
4498 (defun org-make-overlay (beg end &optional buffer)
4499 (if (featurep 'xemacs)
4500 (make-extent beg end buffer)
4501 (make-overlay beg end buffer)))
4502 (defun org-delete-overlay (ovl)
4503 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4504 (defun org-detach-overlay (ovl)
4505 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4506 (defun org-move-overlay (ovl beg end &optional buffer)
4507 (if (featurep 'xemacs)
4508 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4509 (move-overlay ovl beg end buffer)))
4510 (defun org-overlay-put (ovl prop value)
4511 (if (featurep 'xemacs)
4512 (set-extent-property ovl prop value)
4513 (overlay-put ovl prop value)))
4514 (defun org-overlay-display (ovl text &optional face evap)
4515 "Make overlay OVL display TEXT with face FACE."
4516 (if (featurep 'xemacs)
4517 (let ((gl (make-glyph text)))
4518 (and face (set-glyph-face gl face))
4519 (set-extent-property ovl 'invisible t)
4520 (set-extent-property ovl 'end-glyph gl))
4521 (overlay-put ovl 'display text)
4522 (if face (overlay-put ovl 'face face))
4523 (if evap (overlay-put ovl 'evaporate t))))
4524 (defun org-overlay-before-string (ovl text &optional face evap)
4525 "Make overlay OVL display TEXT with face FACE."
4526 (if (featurep 'xemacs)
4527 (let ((gl (make-glyph text)))
4528 (and face (set-glyph-face gl face))
4529 (set-extent-property ovl 'begin-glyph gl))
4530 (if face (org-add-props text nil 'face face))
4531 (overlay-put ovl 'before-string text)
4532 (if evap (overlay-put ovl 'evaporate t))))
4533 (defun org-overlay-get (ovl prop)
4534 (if (featurep 'xemacs)
4535 (extent-property ovl prop)
4536 (overlay-get ovl prop)))
4537 (defun org-overlays-at (pos)
4538 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4539 (defun org-overlays-in (&optional start end)
4540 (if (featurep 'xemacs)
4541 (extent-list nil start end)
4542 (overlays-in start end)))
4543 (defun org-overlay-start (o)
4544 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4545 (defun org-overlay-end (o)
4546 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4547 (defun org-find-overlays (prop &optional pos delete)
4548 "Find all overlays specifying PROP at POS or point.
4549 If DELETE is non-nil, delete all those overlays."
4550 (let ((overlays (org-overlays-at (or pos (point))))
4551 ov found)
4552 (while (setq ov (pop overlays))
4553 (if (org-overlay-get ov prop)
4554 (if delete (org-delete-overlay ov) (push ov found))))
4555 found))
4557 ;; Region compatibility
4559 (defun org-add-hook (hook function &optional append local)
4560 "Add-hook, compatible with both Emacsen."
4561 (if (and local (featurep 'xemacs))
4562 (add-local-hook hook function append)
4563 (add-hook hook function append local)))
4565 (defvar org-ignore-region nil
4566 "To temporarily disable the active region.")
4568 (defun org-region-active-p ()
4569 "Is `transient-mark-mode' on and the region active?
4570 Works on both Emacs and XEmacs."
4571 (if org-ignore-region
4573 (if (featurep 'xemacs)
4574 (and zmacs-regions (region-active-p))
4575 (and transient-mark-mode mark-active))))
4577 ;; Invisibility compatibility
4579 (defun org-add-to-invisibility-spec (arg)
4580 "Add elements to `buffer-invisibility-spec'.
4581 See documentation for `buffer-invisibility-spec' for the kind of elements
4582 that can be added."
4583 (cond
4584 ((fboundp 'add-to-invisibility-spec)
4585 (add-to-invisibility-spec arg))
4586 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4587 (setq buffer-invisibility-spec (list arg)))
4589 (setq buffer-invisibility-spec
4590 (cons arg buffer-invisibility-spec)))))
4592 (defun org-remove-from-invisibility-spec (arg)
4593 "Remove elements from `buffer-invisibility-spec'."
4594 (if (fboundp 'remove-from-invisibility-spec)
4595 (remove-from-invisibility-spec arg)
4596 (if (consp buffer-invisibility-spec)
4597 (setq buffer-invisibility-spec
4598 (delete arg buffer-invisibility-spec)))))
4600 (defun org-in-invisibility-spec-p (arg)
4601 "Is ARG a member of `buffer-invisibility-spec'?"
4602 (if (consp buffer-invisibility-spec)
4603 (member arg buffer-invisibility-spec)
4604 nil))
4606 ;;;; Define the Org-mode
4608 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4609 (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."))
4612 ;; We use a before-change function to check if a table might need
4613 ;; an update.
4614 (defvar org-table-may-need-update t
4615 "Indicates that a table might need an update.
4616 This variable is set by `org-before-change-function'.
4617 `org-table-align' sets it back to nil.")
4618 (defvar org-mode-map)
4619 (defvar org-mode-hook nil)
4620 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4621 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4622 (defvar org-table-buffer-is-an nil)
4623 (defconst org-outline-regexp "\\*+ ")
4625 ;;;###autoload
4626 (define-derived-mode org-mode outline-mode "Org"
4627 "Outline-based notes management and organizer, alias
4628 \"Carsten's outline-mode for keeping track of everything.\"
4630 Org-mode develops organizational tasks around a NOTES file which
4631 contains information about projects as plain text. Org-mode is
4632 implemented on top of outline-mode, which is ideal to keep the content
4633 of large files well structured. It supports ToDo items, deadlines and
4634 time stamps, which magically appear in the diary listing of the Emacs
4635 calendar. Tables are easily created with a built-in table editor.
4636 Plain text URL-like links connect to websites, emails (VM), Usenet
4637 messages (Gnus), BBDB entries, and any files related to the project.
4638 For printing and sharing of notes, an Org-mode file (or a part of it)
4639 can be exported as a structured ASCII or HTML file.
4641 The following commands are available:
4643 \\{org-mode-map}"
4645 ;; Get rid of Outline menus, they are not needed
4646 ;; Need to do this here because define-derived-mode sets up
4647 ;; the keymap so late. Still, it is a waste to call this each time
4648 ;; we switch another buffer into org-mode.
4649 (if (featurep 'xemacs)
4650 (when (boundp 'outline-mode-menu-heading)
4651 ;; Assume this is Greg's port, it used easymenu
4652 (easy-menu-remove outline-mode-menu-heading)
4653 (easy-menu-remove outline-mode-menu-show)
4654 (easy-menu-remove outline-mode-menu-hide))
4655 (define-key org-mode-map [menu-bar headings] 'undefined)
4656 (define-key org-mode-map [menu-bar hide] 'undefined)
4657 (define-key org-mode-map [menu-bar show] 'undefined))
4659 (easy-menu-add org-org-menu)
4660 (easy-menu-add org-tbl-menu)
4661 (org-install-agenda-files-menu)
4662 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4663 (org-add-to-invisibility-spec '(org-cwidth))
4664 (when (featurep 'xemacs)
4665 (org-set-local 'line-move-ignore-invisible t))
4666 (org-set-local 'outline-regexp org-outline-regexp)
4667 (org-set-local 'outline-level 'org-outline-level)
4668 (when (and org-ellipsis
4669 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4670 (fboundp 'make-glyph-code))
4671 (unless org-display-table
4672 (setq org-display-table (make-display-table)))
4673 (set-display-table-slot
4674 org-display-table 4
4675 (vconcat (mapcar
4676 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4677 org-ellipsis)))
4678 (if (stringp org-ellipsis) org-ellipsis "..."))))
4679 (setq buffer-display-table org-display-table))
4680 (org-set-regexps-and-options)
4681 ;; Calc embedded
4682 (org-set-local 'calc-embedded-open-mode "# ")
4683 (modify-syntax-entry ?# "<")
4684 (modify-syntax-entry ?@ "w")
4685 (if org-startup-truncated (setq truncate-lines t))
4686 (org-set-local 'font-lock-unfontify-region-function
4687 'org-unfontify-region)
4688 ;; Activate before-change-function
4689 (org-set-local 'org-table-may-need-update t)
4690 (org-add-hook 'before-change-functions 'org-before-change-function nil
4691 'local)
4692 ;; Check for running clock before killing a buffer
4693 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4694 ;; Paragraphs and auto-filling
4695 (org-set-autofill-regexps)
4696 (setq indent-line-function 'org-indent-line-function)
4697 (org-update-radio-target-regexp)
4699 ;; Comment characters
4700 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4701 (org-set-local 'comment-padding " ")
4703 ;; Imenu
4704 (org-set-local 'imenu-create-index-function
4705 'org-imenu-get-tree)
4707 ;; Make isearch reveal context
4708 (if (or (featurep 'xemacs)
4709 (not (boundp 'outline-isearch-open-invisible-function)))
4710 ;; Emacs 21 and XEmacs make use of the hook
4711 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4712 ;; Emacs 22 deals with this through a special variable
4713 (org-set-local 'outline-isearch-open-invisible-function
4714 (lambda (&rest ignore) (org-show-context 'isearch))))
4716 ;; If empty file that did not turn on org-mode automatically, make it to.
4717 (if (and org-insert-mode-line-in-empty-file
4718 (interactive-p)
4719 (= (point-min) (point-max)))
4720 (insert "# -*- mode: org -*-\n\n"))
4722 (unless org-inhibit-startup
4723 (when org-startup-align-all-tables
4724 (let ((bmp (buffer-modified-p)))
4725 (org-table-map-tables 'org-table-align)
4726 (set-buffer-modified-p bmp)))
4727 (org-cycle-hide-drawers 'all)
4728 (cond
4729 ((eq org-startup-folded t)
4730 (org-cycle '(4)))
4731 ((eq org-startup-folded 'content)
4732 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4733 (org-cycle '(4)) (org-cycle '(4)))))))
4735 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4737 (defsubst org-call-with-arg (command arg)
4738 "Call COMMAND interactively, but pretend prefix are was ARG."
4739 (let ((current-prefix-arg arg)) (call-interactively command)))
4741 (defsubst org-current-line (&optional pos)
4742 (save-excursion
4743 (and pos (goto-char pos))
4744 ;; works also in narrowed buffer, because we start at 1, not point-min
4745 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4747 (defun org-current-time ()
4748 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4749 (if (> org-time-stamp-rounding-minutes 0)
4750 (let ((r org-time-stamp-rounding-minutes)
4751 (time (decode-time)))
4752 (apply 'encode-time
4753 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4754 (nthcdr 2 time))))
4755 (current-time)))
4757 (defun org-add-props (string plist &rest props)
4758 "Add text properties to entire string, from beginning to end.
4759 PLIST may be a list of properties, PROPS are individual properties and values
4760 that will be added to PLIST. Returns the string that was modified."
4761 (add-text-properties
4762 0 (length string) (if props (append plist props) plist) string)
4763 string)
4764 (put 'org-add-props 'lisp-indent-function 2)
4767 ;;;; Font-Lock stuff, including the activators
4769 (defvar org-mouse-map (make-sparse-keymap))
4770 (org-defkey org-mouse-map
4771 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4772 (org-defkey org-mouse-map
4773 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4774 (when org-mouse-1-follows-link
4775 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4776 (when org-tab-follows-link
4777 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4778 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4779 (when org-return-follows-link
4780 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4781 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4783 (require 'font-lock)
4785 (defconst org-non-link-chars "]\t\n\r<>")
4786 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4787 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4788 (defvar org-link-re-with-space nil
4789 "Matches a link with spaces, optional angular brackets around it.")
4790 (defvar org-link-re-with-space2 nil
4791 "Matches a link with spaces, optional angular brackets around it.")
4792 (defvar org-angle-link-re nil
4793 "Matches link with angular brackets, spaces are allowed.")
4794 (defvar org-plain-link-re nil
4795 "Matches plain link, without spaces.")
4796 (defvar org-bracket-link-regexp nil
4797 "Matches a link in double brackets.")
4798 (defvar org-bracket-link-analytic-regexp nil
4799 "Regular expression used to analyze links.
4800 Here is what the match groups contain after a match:
4801 1: http:
4802 2: http
4803 3: path
4804 4: [desc]
4805 5: desc")
4806 (defvar org-any-link-re nil
4807 "Regular expression matching any link.")
4809 (defun org-make-link-regexps ()
4810 "Update the link regular expressions.
4811 This should be called after the variable `org-link-types' has changed."
4812 (setq org-link-re-with-space
4813 (concat
4814 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4815 "\\([^" org-non-link-chars " ]"
4816 "[^" org-non-link-chars "]*"
4817 "[^" org-non-link-chars " ]\\)>?")
4818 org-link-re-with-space2
4819 (concat
4820 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4821 "\\([^" org-non-link-chars " ]"
4822 "[^]\t\n\r]*"
4823 "[^" org-non-link-chars " ]\\)>?")
4824 org-angle-link-re
4825 (concat
4826 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4827 "\\([^" org-non-link-chars " ]"
4828 "[^" org-non-link-chars "]*"
4829 "\\)>")
4830 org-plain-link-re
4831 (concat
4832 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4833 "\\([^]\t\n\r<>,;() ]+\\)")
4834 org-bracket-link-regexp
4835 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4836 org-bracket-link-analytic-regexp
4837 (concat
4838 "\\[\\["
4839 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4840 "\\([^]]+\\)"
4841 "\\]"
4842 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4843 "\\]")
4844 org-any-link-re
4845 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4846 org-angle-link-re "\\)\\|\\("
4847 org-plain-link-re "\\)")))
4849 (org-make-link-regexps)
4851 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4852 "Regular expression for fast time stamp matching.")
4853 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4854 "Regular expression for fast time stamp matching.")
4855 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4856 "Regular expression matching time strings for analysis.
4857 This one does not require the space after the date.")
4858 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4859 "Regular expression matching time strings for analysis.")
4860 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4861 "Regular expression matching time stamps, with groups.")
4862 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4863 "Regular expression matching time stamps (also [..]), with groups.")
4864 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4865 "Regular expression matching a time stamp range.")
4866 (defconst org-tr-regexp-both
4867 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4868 "Regular expression matching a time stamp range.")
4869 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4870 org-ts-regexp "\\)?")
4871 "Regular expression matching a time stamp or time stamp range.")
4872 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4873 org-ts-regexp-both "\\)?")
4874 "Regular expression matching a time stamp or time stamp range.
4875 The time stamps may be either active or inactive.")
4877 (defvar org-emph-face nil)
4879 (defun org-do-emphasis-faces (limit)
4880 "Run through the buffer and add overlays to links."
4881 (let (rtn)
4882 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4883 (if (not (= (char-after (match-beginning 3))
4884 (char-after (match-beginning 4))))
4885 (progn
4886 (setq rtn t)
4887 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4888 'face
4889 (nth 1 (assoc (match-string 3)
4890 org-emphasis-alist)))
4891 (add-text-properties (match-beginning 2) (match-end 2)
4892 '(font-lock-multiline t))
4893 (when org-hide-emphasis-markers
4894 (add-text-properties (match-end 4) (match-beginning 5)
4895 '(invisible org-link))
4896 (add-text-properties (match-beginning 3) (match-end 3)
4897 '(invisible org-link)))))
4898 (backward-char 1))
4899 rtn))
4901 (defun org-emphasize (&optional char)
4902 "Insert or change an emphasis, i.e. a font like bold or italic.
4903 If there is an active region, change that region to a new emphasis.
4904 If there is no region, just insert the marker characters and position
4905 the cursor between them.
4906 CHAR should be either the marker character, or the first character of the
4907 HTML tag associated with that emphasis. If CHAR is a space, the means
4908 to remove the emphasis of the selected region.
4909 If char is not given (for example in an interactive call) it
4910 will be prompted for."
4911 (interactive)
4912 (let ((eal org-emphasis-alist) e det
4913 (erc org-emphasis-regexp-components)
4914 (prompt "")
4915 (string "") beg end move tag c s)
4916 (if (org-region-active-p)
4917 (setq beg (region-beginning) end (region-end)
4918 string (buffer-substring beg end))
4919 (setq move t))
4921 (while (setq e (pop eal))
4922 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4923 c (aref tag 0))
4924 (push (cons c (string-to-char (car e))) det)
4925 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4926 (substring tag 1)))))
4927 (unless char
4928 (message "%s" (concat "Emphasis marker or tag:" prompt))
4929 (setq char (read-char-exclusive)))
4930 (setq char (or (cdr (assoc char det)) char))
4931 (if (equal char ?\ )
4932 (setq s "" move nil)
4933 (unless (assoc (char-to-string char) org-emphasis-alist)
4934 (error "No such emphasis marker: \"%c\"" char))
4935 (setq s (char-to-string char)))
4936 (while (and (> (length string) 1)
4937 (equal (substring string 0 1) (substring string -1))
4938 (assoc (substring string 0 1) org-emphasis-alist))
4939 (setq string (substring string 1 -1)))
4940 (setq string (concat s string s))
4941 (if beg (delete-region beg end))
4942 (unless (or (bolp)
4943 (string-match (concat "[" (nth 0 erc) "\n]")
4944 (char-to-string (char-before (point)))))
4945 (insert " "))
4946 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4947 (char-to-string (char-after (point))))
4948 (insert " ") (backward-char 1))
4949 (insert string)
4950 (and move (backward-char 1))))
4952 (defconst org-nonsticky-props
4953 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4956 (defun org-activate-plain-links (limit)
4957 "Run through the buffer and add overlays to links."
4958 (catch 'exit
4959 (let (f)
4960 (while (re-search-forward org-plain-link-re limit t)
4961 (setq f (get-text-property (match-beginning 0) 'face))
4962 (if (or (eq f 'org-tag)
4963 (and (listp f) (memq 'org-tag f)))
4965 (add-text-properties (match-beginning 0) (match-end 0)
4966 (list 'mouse-face 'highlight
4967 'rear-nonsticky org-nonsticky-props
4968 'keymap org-mouse-map
4970 (throw 'exit t))))))
4972 (defun org-activate-code (limit)
4973 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
4974 (unless (get-text-property (match-beginning 1) 'face)
4975 (remove-text-properties (match-beginning 0) (match-end 0)
4976 '(display t invisible t intangible t))
4977 t)))
4979 (defun org-activate-angle-links (limit)
4980 "Run through the buffer and add overlays to links."
4981 (if (re-search-forward org-angle-link-re limit t)
4982 (progn
4983 (add-text-properties (match-beginning 0) (match-end 0)
4984 (list 'mouse-face 'highlight
4985 'rear-nonsticky org-nonsticky-props
4986 'keymap org-mouse-map
4988 t)))
4990 (defmacro org-maybe-intangible (props)
4991 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4992 In emacs 21, invisible text is not avoided by the command loop, so the
4993 intangible property is needed to make sure point skips this text.
4994 In Emacs 22, this is not necessary. The intangible text property has
4995 led to problems with flyspell. These problems are fixed in flyspell.el,
4996 but we still avoid setting the property in Emacs 22 and later.
4997 We use a macro so that the test can happen at compilation time."
4998 (if (< emacs-major-version 22)
4999 `(append '(intangible t) ,props)
5000 props))
5002 (defun org-activate-bracket-links (limit)
5003 "Run through the buffer and add overlays to bracketed links."
5004 (if (re-search-forward org-bracket-link-regexp limit t)
5005 (let* ((help (concat "LINK: "
5006 (org-match-string-no-properties 1)))
5007 ;; FIXME: above we should remove the escapes.
5008 ;; but that requires another match, protecting match data,
5009 ;; a lot of overhead for font-lock.
5010 (ip (org-maybe-intangible
5011 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5012 'keymap org-mouse-map 'mouse-face 'highlight
5013 'font-lock-multiline t 'help-echo help)))
5014 (vp (list 'rear-nonsticky org-nonsticky-props
5015 'keymap org-mouse-map 'mouse-face 'highlight
5016 ' font-lock-multiline t 'help-echo help)))
5017 ;; We need to remove the invisible property here. Table narrowing
5018 ;; may have made some of this invisible.
5019 (remove-text-properties (match-beginning 0) (match-end 0)
5020 '(invisible nil))
5021 (if (match-end 3)
5022 (progn
5023 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5024 (add-text-properties (match-beginning 3) (match-end 3) vp)
5025 (add-text-properties (match-end 3) (match-end 0) ip))
5026 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5027 (add-text-properties (match-beginning 1) (match-end 1) vp)
5028 (add-text-properties (match-end 1) (match-end 0) ip))
5029 t)))
5031 (defun org-activate-dates (limit)
5032 "Run through the buffer and add overlays to dates."
5033 (if (re-search-forward org-tsr-regexp-both limit t)
5034 (progn
5035 (add-text-properties (match-beginning 0) (match-end 0)
5036 (list 'mouse-face 'highlight
5037 'rear-nonsticky org-nonsticky-props
5038 'keymap org-mouse-map))
5039 (when org-display-custom-times
5040 (if (match-end 3)
5041 (org-display-custom-time (match-beginning 3) (match-end 3)))
5042 (org-display-custom-time (match-beginning 1) (match-end 1)))
5043 t)))
5045 (defvar org-target-link-regexp nil
5046 "Regular expression matching radio targets in plain text.")
5047 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5048 "Regular expression matching a link target.")
5049 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5050 "Regular expression matching a radio target.")
5051 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5052 "Regular expression matching any target.")
5054 (defun org-activate-target-links (limit)
5055 "Run through the buffer and add overlays to target matches."
5056 (when org-target-link-regexp
5057 (let ((case-fold-search t))
5058 (if (re-search-forward org-target-link-regexp limit t)
5059 (progn
5060 (add-text-properties (match-beginning 0) (match-end 0)
5061 (list 'mouse-face 'highlight
5062 'rear-nonsticky org-nonsticky-props
5063 'keymap org-mouse-map
5064 'help-echo "Radio target link"
5065 'org-linked-text t))
5066 t)))))
5068 (defun org-update-radio-target-regexp ()
5069 "Find all radio targets in this file and update the regular expression."
5070 (interactive)
5071 (when (memq 'radio org-activate-links)
5072 (setq org-target-link-regexp
5073 (org-make-target-link-regexp (org-all-targets 'radio)))
5074 (org-restart-font-lock)))
5076 (defun org-hide-wide-columns (limit)
5077 (let (s e)
5078 (setq s (text-property-any (point) (or limit (point-max))
5079 'org-cwidth t))
5080 (when s
5081 (setq e (next-single-property-change s 'org-cwidth))
5082 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5083 (goto-char e)
5084 t)))
5086 (defun org-restart-font-lock ()
5087 "Restart font-lock-mode, to force refontification."
5088 (when (and (boundp 'font-lock-mode) font-lock-mode)
5089 (font-lock-mode -1)
5090 (font-lock-mode 1)))
5092 (defun org-all-targets (&optional radio)
5093 "Return a list of all targets in this file.
5094 With optional argument RADIO, only find radio targets."
5095 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5096 rtn)
5097 (save-excursion
5098 (goto-char (point-min))
5099 (while (re-search-forward re nil t)
5100 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5101 rtn)))
5103 (defun org-make-target-link-regexp (targets)
5104 "Make regular expression matching all strings in TARGETS.
5105 The regular expression finds the targets also if there is a line break
5106 between words."
5107 (and targets
5108 (concat
5109 "\\<\\("
5110 (mapconcat
5111 (lambda (x)
5112 (while (string-match " +" x)
5113 (setq x (replace-match "\\s-+" t t x)))
5115 targets
5116 "\\|")
5117 "\\)\\>")))
5119 (defun org-activate-tags (limit)
5120 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5121 (progn
5122 (add-text-properties (match-beginning 1) (match-end 1)
5123 (list 'mouse-face 'highlight
5124 'rear-nonsticky org-nonsticky-props
5125 'keymap org-mouse-map))
5126 t)))
5128 (defun org-outline-level ()
5129 (save-excursion
5130 (looking-at outline-regexp)
5131 (if (match-beginning 1)
5132 (+ (org-get-string-indentation (match-string 1)) 1000)
5133 (1- (- (match-end 0) (match-beginning 0))))))
5135 (defvar org-font-lock-keywords nil)
5137 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5138 "Regular expression matching a property line.")
5140 (defun org-set-font-lock-defaults ()
5141 (let* ((em org-fontify-emphasized-text)
5142 (lk org-activate-links)
5143 (org-font-lock-extra-keywords
5144 (list
5145 ;; Headlines
5146 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5147 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5148 ;; Table lines
5149 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5150 (1 'org-table t))
5151 ;; Table internals
5152 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5153 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5154 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5155 ;; Drawers
5156 (list org-drawer-regexp '(0 'org-special-keyword t))
5157 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5158 ;; Properties
5159 (list org-property-re
5160 '(1 'org-special-keyword t)
5161 '(3 'org-property-value t))
5162 (if org-format-transports-properties-p
5163 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5164 ;; Links
5165 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5166 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5167 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5168 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5169 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5170 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5171 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5172 '(org-hide-wide-columns (0 nil append))
5173 ;; TODO lines
5174 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5175 '(1 (org-get-todo-face 1) t))
5176 ;; DONE
5177 (if org-fontify-done-headline
5178 (list (concat "^[*]+ +\\<\\("
5179 (mapconcat 'regexp-quote org-done-keywords "\\|")
5180 "\\)\\(.*\\)")
5181 '(2 'org-headline-done t))
5182 nil)
5183 ;; Priorities
5184 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5185 ;; Special keywords
5186 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5187 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5188 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5189 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5190 ;; Emphasis
5191 (if em
5192 (if (featurep 'xemacs)
5193 '(org-do-emphasis-faces (0 nil append))
5194 '(org-do-emphasis-faces)))
5195 ;; Checkboxes
5196 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5197 2 'bold prepend)
5198 (if org-provide-checkbox-statistics
5199 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5200 (0 (org-get-checkbox-statistics-face) t)))
5201 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5202 '(1 'org-archived prepend))
5203 ;; Specials
5204 '(org-do-latex-and-special-faces)
5205 ;; Code
5206 '(org-activate-code (1 'org-code t))
5207 ;; COMMENT
5208 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5209 "\\|" org-quote-string "\\)\\>")
5210 '(1 'org-special-keyword t))
5211 '("^#.*" (0 'font-lock-comment-face t))
5213 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5214 ;; Now set the full font-lock-keywords
5215 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5216 (org-set-local 'font-lock-defaults
5217 '(org-font-lock-keywords t nil nil backward-paragraph))
5218 (kill-local-variable 'font-lock-keywords) nil))
5220 (defvar org-m nil)
5221 (defvar org-l nil)
5222 (defvar org-f nil)
5223 (defun org-get-level-face (n)
5224 "Get the right face for match N in font-lock matching of healdines."
5225 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5226 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5227 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5228 (cond
5229 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5230 ((eq n 2) org-f)
5231 (t (if org-level-color-stars-only nil org-f))))
5233 (defun org-get-todo-face (kwd)
5234 "Get the right face for a TODO keyword KWD.
5235 If KWD is a number, get the corresponding match group."
5236 (if (numberp kwd) (setq kwd (match-string kwd)))
5237 (or (cdr (assoc kwd org-todo-keyword-faces))
5238 (and (member kwd org-done-keywords) 'org-done)
5239 'org-todo))
5241 (defun org-unfontify-region (beg end &optional maybe_loudly)
5242 "Remove fontification and activation overlays from links."
5243 (font-lock-default-unfontify-region beg end)
5244 (let* ((buffer-undo-list t)
5245 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5246 (inhibit-modification-hooks t)
5247 deactivate-mark buffer-file-name buffer-file-truename)
5248 (remove-text-properties beg end
5249 '(mouse-face t keymap t org-linked-text t
5250 invisible t intangible t))))
5252 ;;;; Visibility cycling, including org-goto and indirect buffer
5254 ;;; Cycling
5256 (defvar org-cycle-global-status nil)
5257 (make-variable-buffer-local 'org-cycle-global-status)
5258 (defvar org-cycle-subtree-status nil)
5259 (make-variable-buffer-local 'org-cycle-subtree-status)
5261 ;;;###autoload
5262 (defun org-cycle (&optional arg)
5263 "Visibility cycling for Org-mode.
5265 - When this function is called with a prefix argument, rotate the entire
5266 buffer through 3 states (global cycling)
5267 1. OVERVIEW: Show only top-level headlines.
5268 2. CONTENTS: Show all headlines of all levels, but no body text.
5269 3. SHOW ALL: Show everything.
5271 - When point is at the beginning of a headline, rotate the subtree started
5272 by this line through 3 different states (local cycling)
5273 1. FOLDED: Only the main headline is shown.
5274 2. CHILDREN: The main headline and the direct children are shown.
5275 From this state, you can move to one of the children
5276 and zoom in further.
5277 3. SUBTREE: Show the entire subtree, including body text.
5279 - When there is a numeric prefix, go up to a heading with level ARG, do
5280 a `show-subtree' and return to the previous cursor position. If ARG
5281 is negative, go up that many levels.
5283 - When point is not at the beginning of a headline, execute
5284 `indent-relative', like TAB normally does. See the option
5285 `org-cycle-emulate-tab' for details.
5287 - Special case: if point is at the beginning of the buffer and there is
5288 no headline in line 1, this function will act as if called with prefix arg.
5289 But only if also the variable `org-cycle-global-at-bob' is t."
5290 (interactive "P")
5291 (let* ((outline-regexp
5292 (if (and (org-mode-p) org-cycle-include-plain-lists)
5293 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5294 outline-regexp))
5295 (bob-special (and org-cycle-global-at-bob (bobp)
5296 (not (looking-at outline-regexp))))
5297 (org-cycle-hook
5298 (if bob-special
5299 (delq 'org-optimize-window-after-visibility-change
5300 (copy-sequence org-cycle-hook))
5301 org-cycle-hook))
5302 (pos (point)))
5304 (if (or bob-special (equal arg '(4)))
5305 ;; special case: use global cycling
5306 (setq arg t))
5308 (cond
5310 ((org-at-table-p 'any)
5311 ;; Enter the table or move to the next field in the table
5312 (or (org-table-recognize-table.el)
5313 (progn
5314 (if arg (org-table-edit-field t)
5315 (org-table-justify-field-maybe)
5316 (call-interactively 'org-table-next-field)))))
5318 ((eq arg t) ;; Global cycling
5320 (cond
5321 ((and (eq last-command this-command)
5322 (eq org-cycle-global-status 'overview))
5323 ;; We just created the overview - now do table of contents
5324 ;; This can be slow in very large buffers, so indicate action
5325 (message "CONTENTS...")
5326 (org-content)
5327 (message "CONTENTS...done")
5328 (setq org-cycle-global-status 'contents)
5329 (run-hook-with-args 'org-cycle-hook 'contents))
5331 ((and (eq last-command this-command)
5332 (eq org-cycle-global-status 'contents))
5333 ;; We just showed the table of contents - now show everything
5334 (show-all)
5335 (message "SHOW ALL")
5336 (setq org-cycle-global-status 'all)
5337 (run-hook-with-args 'org-cycle-hook 'all))
5340 ;; Default action: go to overview
5341 (org-overview)
5342 (message "OVERVIEW")
5343 (setq org-cycle-global-status 'overview)
5344 (run-hook-with-args 'org-cycle-hook 'overview))))
5346 ((and org-drawers org-drawer-regexp
5347 (save-excursion
5348 (beginning-of-line 1)
5349 (looking-at org-drawer-regexp)))
5350 ;; Toggle block visibility
5351 (org-flag-drawer
5352 (not (get-char-property (match-end 0) 'invisible))))
5354 ((integerp arg)
5355 ;; Show-subtree, ARG levels up from here.
5356 (save-excursion
5357 (org-back-to-heading)
5358 (outline-up-heading (if (< arg 0) (- arg)
5359 (- (funcall outline-level) arg)))
5360 (org-show-subtree)))
5362 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5363 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5364 ;; At a heading: rotate between three different views
5365 (org-back-to-heading)
5366 (let ((goal-column 0) eoh eol eos)
5367 ;; First, some boundaries
5368 (save-excursion
5369 (org-back-to-heading)
5370 (save-excursion
5371 (beginning-of-line 2)
5372 (while (and (not (eobp)) ;; this is like `next-line'
5373 (get-char-property (1- (point)) 'invisible))
5374 (beginning-of-line 2)) (setq eol (point)))
5375 (outline-end-of-heading) (setq eoh (point))
5376 (org-end-of-subtree t)
5377 (unless (eobp)
5378 (skip-chars-forward " \t\n")
5379 (beginning-of-line 1) ; in case this is an item
5381 (setq eos (1- (point))))
5382 ;; Find out what to do next and set `this-command'
5383 (cond
5384 ((= eos eoh)
5385 ;; Nothing is hidden behind this heading
5386 (message "EMPTY ENTRY")
5387 (setq org-cycle-subtree-status nil)
5388 (save-excursion
5389 (goto-char eos)
5390 (outline-next-heading)
5391 (if (org-invisible-p) (org-flag-heading nil))))
5392 ((or (>= eol eos)
5393 (not (string-match "\\S-" (buffer-substring eol eos))))
5394 ;; Entire subtree is hidden in one line: open it
5395 (org-show-entry)
5396 (show-children)
5397 (message "CHILDREN")
5398 (save-excursion
5399 (goto-char eos)
5400 (outline-next-heading)
5401 (if (org-invisible-p) (org-flag-heading nil)))
5402 (setq org-cycle-subtree-status 'children)
5403 (run-hook-with-args 'org-cycle-hook 'children))
5404 ((and (eq last-command this-command)
5405 (eq org-cycle-subtree-status 'children))
5406 ;; We just showed the children, now show everything.
5407 (org-show-subtree)
5408 (message "SUBTREE")
5409 (setq org-cycle-subtree-status 'subtree)
5410 (run-hook-with-args 'org-cycle-hook 'subtree))
5412 ;; Default action: hide the subtree.
5413 (hide-subtree)
5414 (message "FOLDED")
5415 (setq org-cycle-subtree-status 'folded)
5416 (run-hook-with-args 'org-cycle-hook 'folded)))))
5418 ;; TAB emulation
5419 (buffer-read-only (org-back-to-heading))
5421 ((org-try-cdlatex-tab))
5423 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5424 (or (not (bolp))
5425 (not (looking-at outline-regexp))))
5426 (call-interactively (global-key-binding "\t")))
5428 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5429 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5430 (or (and (eq org-cycle-emulate-tab 'white)
5431 (= (match-end 0) (point-at-eol)))
5432 (and (eq org-cycle-emulate-tab 'whitestart)
5433 (>= (match-end 0) pos))))
5435 (eq org-cycle-emulate-tab t))
5436 ; (if (and (looking-at "[ \n\r\t]")
5437 ; (string-match "^[ \t]*$" (buffer-substring
5438 ; (point-at-bol) (point))))
5439 ; (progn
5440 ; (beginning-of-line 1)
5441 ; (and (looking-at "[ \t]+") (replace-match ""))))
5442 (call-interactively (global-key-binding "\t")))
5444 (t (save-excursion
5445 (org-back-to-heading)
5446 (org-cycle))))))
5448 ;;;###autoload
5449 (defun org-global-cycle (&optional arg)
5450 "Cycle the global visibility. For details see `org-cycle'."
5451 (interactive "P")
5452 (let ((org-cycle-include-plain-lists
5453 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5454 (if (integerp arg)
5455 (progn
5456 (show-all)
5457 (hide-sublevels arg)
5458 (setq org-cycle-global-status 'contents))
5459 (org-cycle '(4)))))
5461 (defun org-overview ()
5462 "Switch to overview mode, shoing only top-level headlines.
5463 Really, this shows all headlines with level equal or greater than the level
5464 of the first headline in the buffer. This is important, because if the
5465 first headline is not level one, then (hide-sublevels 1) gives confusing
5466 results."
5467 (interactive)
5468 (let ((level (save-excursion
5469 (goto-char (point-min))
5470 (if (re-search-forward (concat "^" outline-regexp) nil t)
5471 (progn
5472 (goto-char (match-beginning 0))
5473 (funcall outline-level))))))
5474 (and level (hide-sublevels level))))
5476 (defun org-content (&optional arg)
5477 "Show all headlines in the buffer, like a table of contents.
5478 With numerical argument N, show content up to level N."
5479 (interactive "P")
5480 (save-excursion
5481 ;; Visit all headings and show their offspring
5482 (and (integerp arg) (org-overview))
5483 (goto-char (point-max))
5484 (catch 'exit
5485 (while (and (progn (condition-case nil
5486 (outline-previous-visible-heading 1)
5487 (error (goto-char (point-min))))
5489 (looking-at outline-regexp))
5490 (if (integerp arg)
5491 (show-children (1- arg))
5492 (show-branches))
5493 (if (bobp) (throw 'exit nil))))))
5496 (defun org-optimize-window-after-visibility-change (state)
5497 "Adjust the window after a change in outline visibility.
5498 This function is the default value of the hook `org-cycle-hook'."
5499 (when (get-buffer-window (current-buffer))
5500 (cond
5501 ; ((eq state 'overview) (org-first-headline-recenter 1))
5502 ; ((eq state 'overview) (org-beginning-of-line))
5503 ((eq state 'content) nil)
5504 ((eq state 'all) nil)
5505 ((eq state 'folded) nil)
5506 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5507 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5510 (defun org-cycle-show-empty-lines (state)
5511 "Show empty lines above all visible headlines.
5512 The region to be covered depends on STATE when called through
5513 `org-cycle-hook'. Lisp program can use t for STATE to get the
5514 entire buffer covered. Note that an empty line is only shown if there
5515 are at least `org-cycle-separator-lines' empty lines before the headeline."
5516 (when (> org-cycle-separator-lines 0)
5517 (save-excursion
5518 (let* ((n org-cycle-separator-lines)
5519 (re (cond
5520 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5521 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5522 (t (let ((ns (number-to-string (- n 2))))
5523 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5524 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5525 beg end)
5526 (cond
5527 ((memq state '(overview contents t))
5528 (setq beg (point-min) end (point-max)))
5529 ((memq state '(children folded))
5530 (setq beg (point) end (progn (org-end-of-subtree t t)
5531 (beginning-of-line 2)
5532 (point)))))
5533 (when beg
5534 (goto-char beg)
5535 (while (re-search-forward re end t)
5536 (if (not (get-char-property (match-end 1) 'invisible))
5537 (outline-flag-region
5538 (match-beginning 1) (match-end 1) nil)))))))
5539 ;; Never hide empty lines at the end of the file.
5540 (save-excursion
5541 (goto-char (point-max))
5542 (outline-previous-heading)
5543 (outline-end-of-heading)
5544 (if (and (looking-at "[ \t\n]+")
5545 (= (match-end 0) (point-max)))
5546 (outline-flag-region (point) (match-end 0) nil))))
5548 (defun org-subtree-end-visible-p ()
5549 "Is the end of the current subtree visible?"
5550 (pos-visible-in-window-p
5551 (save-excursion (org-end-of-subtree t) (point))))
5553 (defun org-first-headline-recenter (&optional N)
5554 "Move cursor to the first headline and recenter the headline.
5555 Optional argument N means, put the headline into the Nth line of the window."
5556 (goto-char (point-min))
5557 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5558 (beginning-of-line)
5559 (recenter (prefix-numeric-value N))))
5561 ;;; Org-goto
5563 (defvar org-goto-window-configuration nil)
5564 (defvar org-goto-marker nil)
5565 (defvar org-goto-map
5566 (let ((map (make-sparse-keymap)))
5567 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5568 (while (setq cmd (pop cmds))
5569 (substitute-key-definition cmd cmd map global-map)))
5570 (suppress-keymap map)
5571 (org-defkey map "\C-m" 'org-goto-ret)
5572 (org-defkey map [(left)] 'org-goto-left)
5573 (org-defkey map [(right)] 'org-goto-right)
5574 (org-defkey map [(?q)] 'org-goto-quit)
5575 (org-defkey map [(control ?g)] 'org-goto-quit)
5576 (org-defkey map "\C-i" 'org-cycle)
5577 (org-defkey map [(tab)] 'org-cycle)
5578 (org-defkey map [(down)] 'outline-next-visible-heading)
5579 (org-defkey map [(up)] 'outline-previous-visible-heading)
5580 (org-defkey map "n" 'outline-next-visible-heading)
5581 (org-defkey map "p" 'outline-previous-visible-heading)
5582 (org-defkey map "f" 'outline-forward-same-level)
5583 (org-defkey map "b" 'outline-backward-same-level)
5584 (org-defkey map "u" 'outline-up-heading)
5585 (org-defkey map "/" 'org-occur)
5586 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5587 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5588 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5589 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5590 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5591 map))
5593 (defconst org-goto-help
5594 "Browse copy of buffer to find location or copy text.
5595 RET=jump to location [Q]uit and return to previous location
5596 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5599 (defun org-goto ()
5600 "Look up a different location in the current file, keeping current visibility.
5602 When you want look-up or go to a different location in a document, the
5603 fastest way is often to fold the entire buffer and then dive into the tree.
5604 This method has the disadvantage, that the previous location will be folded,
5605 which may not be what you want.
5607 This command works around this by showing a copy of the current buffer
5608 in an indirect buffer, in overview mode. You can dive into the tree in
5609 that copy, use org-occur and incremental search to find a location.
5610 When pressing RET or `Q', the command returns to the original buffer in
5611 which the visibility is still unchanged. After RET is will also jump to
5612 the location selected in the indirect buffer and expose the
5613 the headline hierarchy above."
5614 (interactive)
5615 (let* ((org-goto-start-pos (point))
5616 (selected-point
5617 (car (org-get-location (current-buffer) org-goto-help))))
5618 (if selected-point
5619 (progn
5620 (org-mark-ring-push org-goto-start-pos)
5621 (goto-char selected-point)
5622 (if (or (org-invisible-p) (org-invisible-p2))
5623 (org-show-context 'org-goto)))
5624 (message "Quit"))))
5626 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5627 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5629 (defun org-get-location (buf help)
5630 "Let the user select a location in the Org-mode buffer BUF.
5631 This function uses a recursive edit. It returns the selected position
5632 or nil."
5633 (let (org-goto-selected-point org-goto-exit-command)
5634 (save-excursion
5635 (save-window-excursion
5636 (delete-other-windows)
5637 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5638 (switch-to-buffer
5639 (condition-case nil
5640 (make-indirect-buffer (current-buffer) "*org-goto*")
5641 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5642 (with-output-to-temp-buffer "*Help*"
5643 (princ help))
5644 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5645 (setq buffer-read-only nil)
5646 (let ((org-startup-truncated t)
5647 (org-startup-folded nil)
5648 (org-startup-align-all-tables nil))
5649 (org-mode)
5650 (org-overview))
5651 (setq buffer-read-only t)
5652 (if (and (boundp 'org-goto-start-pos)
5653 (integer-or-marker-p org-goto-start-pos))
5654 (let ((org-show-hierarchy-above t)
5655 (org-show-siblings t)
5656 (org-show-following-heading t))
5657 (goto-char org-goto-start-pos)
5658 (and (org-invisible-p) (org-show-context)))
5659 (goto-char (point-min)))
5660 (org-beginning-of-line)
5661 (message "Select location and press RET")
5662 ;; now we make sure that during selection, ony very few keys work
5663 ;; and that it is impossible to switch to another window.
5664 ; (let ((gm (current-global-map))
5665 ; (overriding-local-map org-goto-map))
5666 ; (unwind-protect
5667 ; (progn
5668 ; (use-global-map org-goto-map)
5669 ; (recursive-edit))
5670 ; (use-global-map gm)))
5671 (use-local-map org-goto-map)
5672 (recursive-edit)
5674 (kill-buffer "*org-goto*")
5675 (cons org-goto-selected-point org-goto-exit-command)))
5677 (defun org-goto-ret (&optional arg)
5678 "Finish `org-goto' by going to the new location."
5679 (interactive "P")
5680 (setq org-goto-selected-point (point)
5681 org-goto-exit-command 'return)
5682 (throw 'exit nil))
5684 (defun org-goto-left ()
5685 "Finish `org-goto' by going to the new location."
5686 (interactive)
5687 (if (org-on-heading-p)
5688 (progn
5689 (beginning-of-line 1)
5690 (setq org-goto-selected-point (point)
5691 org-goto-exit-command 'left)
5692 (throw 'exit nil))
5693 (error "Not on a heading")))
5695 (defun org-goto-right ()
5696 "Finish `org-goto' by going to the new location."
5697 (interactive)
5698 (if (org-on-heading-p)
5699 (progn
5700 (setq org-goto-selected-point (point)
5701 org-goto-exit-command 'right)
5702 (throw 'exit nil))
5703 (error "Not on a heading")))
5705 (defun org-goto-quit ()
5706 "Finish `org-goto' without cursor motion."
5707 (interactive)
5708 (setq org-goto-selected-point nil)
5709 (setq org-goto-exit-command 'quit)
5710 (throw 'exit nil))
5712 ;;; Indirect buffer display of subtrees
5714 (defvar org-indirect-dedicated-frame nil
5715 "This is the frame being used for indirect tree display.")
5716 (defvar org-last-indirect-buffer nil)
5718 (defun org-tree-to-indirect-buffer (&optional arg)
5719 "Create indirect buffer and narrow it to current subtree.
5720 With numerical prefix ARG, go up to this level and then take that tree.
5721 If ARG is negative, go up that many levels.
5722 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5723 indirect buffer previously made with this command, to avoid proliferation of
5724 indirect buffers. However, when you call the command with a `C-u' prefix, or
5725 when `org-indirect-buffer-display' is `new-frame', the last buffer
5726 is kept so that you can work with several indirect buffers at the same time.
5727 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5728 requests that a new frame be made for the new buffer, so that the dedicated
5729 frame is not changed."
5730 (interactive "P")
5731 (let ((cbuf (current-buffer))
5732 (cwin (selected-window))
5733 (pos (point))
5734 beg end level heading ibuf)
5735 (save-excursion
5736 (org-back-to-heading t)
5737 (when (numberp arg)
5738 (setq level (org-outline-level))
5739 (if (< arg 0) (setq arg (+ level arg)))
5740 (while (> (setq level (org-outline-level)) arg)
5741 (outline-up-heading 1 t)))
5742 (setq beg (point)
5743 heading (org-get-heading))
5744 (org-end-of-subtree t) (setq end (point)))
5745 (if (and (buffer-live-p org-last-indirect-buffer)
5746 (not (eq org-indirect-buffer-display 'new-frame))
5747 (not arg))
5748 (kill-buffer org-last-indirect-buffer))
5749 (setq ibuf (org-get-indirect-buffer cbuf)
5750 org-last-indirect-buffer ibuf)
5751 (cond
5752 ((or (eq org-indirect-buffer-display 'new-frame)
5753 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5754 (select-frame (make-frame))
5755 (delete-other-windows)
5756 (switch-to-buffer ibuf)
5757 (org-set-frame-title heading))
5758 ((eq org-indirect-buffer-display 'dedicated-frame)
5759 (raise-frame
5760 (select-frame (or (and org-indirect-dedicated-frame
5761 (frame-live-p org-indirect-dedicated-frame)
5762 org-indirect-dedicated-frame)
5763 (setq org-indirect-dedicated-frame (make-frame)))))
5764 (delete-other-windows)
5765 (switch-to-buffer ibuf)
5766 (org-set-frame-title (concat "Indirect: " heading)))
5767 ((eq org-indirect-buffer-display 'current-window)
5768 (switch-to-buffer ibuf))
5769 ((eq org-indirect-buffer-display 'other-window)
5770 (pop-to-buffer ibuf))
5771 (t (error "Invalid value.")))
5772 (if (featurep 'xemacs)
5773 (save-excursion (org-mode) (turn-on-font-lock)))
5774 (narrow-to-region beg end)
5775 (show-all)
5776 (goto-char pos)
5777 (and (window-live-p cwin) (select-window cwin))))
5779 (defun org-get-indirect-buffer (&optional buffer)
5780 (setq buffer (or buffer (current-buffer)))
5781 (let ((n 1) (base (buffer-name buffer)) bname)
5782 (while (buffer-live-p
5783 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5784 (setq n (1+ n)))
5785 (condition-case nil
5786 (make-indirect-buffer buffer bname 'clone)
5787 (error (make-indirect-buffer buffer bname)))))
5789 (defun org-set-frame-title (title)
5790 "Set the title of the current frame to the string TITLE."
5791 ;; FIXME: how to name a single frame in XEmacs???
5792 (unless (featurep 'xemacs)
5793 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5795 ;;;; Structure editing
5797 ;;; Inserting headlines
5799 (defun org-insert-heading (&optional force-heading)
5800 "Insert a new heading or item with same depth at point.
5801 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5802 If point is at the beginning of a headline, insert a sibling before the
5803 current headline. If point is in the middle of a headline, split the headline
5804 at that position and make the rest of the headline part of the sibling below
5805 the current headline."
5806 (interactive "P")
5807 (if (= (buffer-size) 0)
5808 (insert "\n* ")
5809 (when (or force-heading (not (org-insert-item)))
5810 (let* ((head (save-excursion
5811 (condition-case nil
5812 (progn
5813 (org-back-to-heading)
5814 (match-string 0))
5815 (error "*"))))
5816 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5817 pos)
5818 (cond
5819 ((and (org-on-heading-p) (bolp)
5820 (or (bobp)
5821 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5822 (open-line (if blank 2 1)))
5823 ((and (bolp)
5824 (or (bobp)
5825 (save-excursion
5826 (backward-char 1) (not (org-invisible-p)))))
5827 nil)
5828 (t (newline (if blank 2 1))))
5829 (insert head) (just-one-space)
5830 (setq pos (point))
5831 (end-of-line 1)
5832 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5833 (run-hooks 'org-insert-heading-hook)))))
5835 (defun org-insert-heading-after-current ()
5836 "Insert a new heading with same level as current, after current subtree."
5837 (interactive)
5838 (org-back-to-heading)
5839 (org-insert-heading)
5840 (org-move-subtree-down)
5841 (end-of-line 1))
5843 (defun org-insert-todo-heading (arg)
5844 "Insert a new heading with the same level and TODO state as current heading.
5845 If the heading has no TODO state, or if the state is DONE, use the first
5846 state (TODO by default). Also with prefix arg, force first state."
5847 (interactive "P")
5848 (when (not (org-insert-item 'checkbox))
5849 (org-insert-heading)
5850 (save-excursion
5851 (org-back-to-heading)
5852 (outline-previous-heading)
5853 (looking-at org-todo-line-regexp))
5854 (if (or arg
5855 (not (match-beginning 2))
5856 (member (match-string 2) org-done-keywords))
5857 (insert (car org-todo-keywords-1) " ")
5858 (insert (match-string 2) " "))))
5860 (defun org-insert-subheading (arg)
5861 "Insert a new subheading and demote it.
5862 Works for outline headings and for plain lists alike."
5863 (interactive "P")
5864 (org-insert-heading arg)
5865 (cond
5866 ((org-on-heading-p) (org-do-demote))
5867 ((org-at-item-p) (org-indent-item 1))))
5869 (defun org-insert-todo-subheading (arg)
5870 "Insert a new subheading with TODO keyword or checkbox and demote it.
5871 Works for outline headings and for plain lists alike."
5872 (interactive "P")
5873 (org-insert-todo-heading arg)
5874 (cond
5875 ((org-on-heading-p) (org-do-demote))
5876 ((org-at-item-p) (org-indent-item 1))))
5878 ;;; Promotion and Demotion
5880 (defun org-promote-subtree ()
5881 "Promote the entire subtree.
5882 See also `org-promote'."
5883 (interactive)
5884 (save-excursion
5885 (org-map-tree 'org-promote))
5886 (org-fix-position-after-promote))
5888 (defun org-demote-subtree ()
5889 "Demote the entire subtree. See `org-demote'.
5890 See also `org-promote'."
5891 (interactive)
5892 (save-excursion
5893 (org-map-tree 'org-demote))
5894 (org-fix-position-after-promote))
5897 (defun org-do-promote ()
5898 "Promote the current heading higher up the tree.
5899 If the region is active in `transient-mark-mode', promote all headings
5900 in the region."
5901 (interactive)
5902 (save-excursion
5903 (if (org-region-active-p)
5904 (org-map-region 'org-promote (region-beginning) (region-end))
5905 (org-promote)))
5906 (org-fix-position-after-promote))
5908 (defun org-do-demote ()
5909 "Demote the current heading lower down the tree.
5910 If the region is active in `transient-mark-mode', demote all headings
5911 in the region."
5912 (interactive)
5913 (save-excursion
5914 (if (org-region-active-p)
5915 (org-map-region 'org-demote (region-beginning) (region-end))
5916 (org-demote)))
5917 (org-fix-position-after-promote))
5919 (defun org-fix-position-after-promote ()
5920 "Make sure that after pro/demotion cursor position is right."
5921 (let ((pos (point)))
5922 (when (save-excursion
5923 (beginning-of-line 1)
5924 (looking-at org-todo-line-regexp)
5925 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5926 (cond ((eobp) (insert " "))
5927 ((eolp) (insert " "))
5928 ((equal (char-after) ?\ ) (forward-char 1))))))
5930 (defun org-reduced-level (l)
5931 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5933 (defun org-get-legal-level (level &optional change)
5934 "Rectify a level change under the influence of `org-odd-levels-only'
5935 LEVEL is a current level, CHANGE is by how much the level should be
5936 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5937 even level numbers will become the next higher odd number."
5938 (if org-odd-levels-only
5939 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5940 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5941 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5942 (max 1 (+ level change))))
5944 (defun org-promote ()
5945 "Promote the current heading higher up the tree.
5946 If the region is active in `transient-mark-mode', promote all headings
5947 in the region."
5948 (org-back-to-heading t)
5949 (let* ((level (save-match-data (funcall outline-level)))
5950 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5951 (diff (abs (- level (length up-head) -1))))
5952 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5953 (replace-match up-head nil t)
5954 ;; Fixup tag positioning
5955 (and org-auto-align-tags (org-set-tags nil t))
5956 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5958 (defun org-demote ()
5959 "Demote the current heading lower down the tree.
5960 If the region is active in `transient-mark-mode', demote all headings
5961 in the region."
5962 (org-back-to-heading t)
5963 (let* ((level (save-match-data (funcall outline-level)))
5964 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5965 (diff (abs (- level (length down-head) -1))))
5966 (replace-match down-head nil t)
5967 ;; Fixup tag positioning
5968 (and org-auto-align-tags (org-set-tags nil t))
5969 (if org-adapt-indentation (org-fixup-indentation diff))))
5971 (defun org-map-tree (fun)
5972 "Call FUN for every heading underneath the current one."
5973 (org-back-to-heading)
5974 (let ((level (funcall outline-level)))
5975 (save-excursion
5976 (funcall fun)
5977 (while (and (progn
5978 (outline-next-heading)
5979 (> (funcall outline-level) level))
5980 (not (eobp)))
5981 (funcall fun)))))
5983 (defun org-map-region (fun beg end)
5984 "Call FUN for every heading between BEG and END."
5985 (let ((org-ignore-region t))
5986 (save-excursion
5987 (setq end (copy-marker end))
5988 (goto-char beg)
5989 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5990 (< (point) end))
5991 (funcall fun))
5992 (while (and (progn
5993 (outline-next-heading)
5994 (< (point) end))
5995 (not (eobp)))
5996 (funcall fun)))))
5998 (defun org-fixup-indentation (diff)
5999 "Change the indentation in the current entry by DIFF
6000 However, if any line in the current entry has no indentation, or if it
6001 would end up with no indentation after the change, nothing at all is done."
6002 (save-excursion
6003 (let ((end (save-excursion (outline-next-heading)
6004 (point-marker)))
6005 (prohibit (if (> diff 0)
6006 "^\\S-"
6007 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6008 col)
6009 (unless (save-excursion (end-of-line 1)
6010 (re-search-forward prohibit end t))
6011 (while (and (< (point) end)
6012 (re-search-forward "^[ \t]+" end t))
6013 (goto-char (match-end 0))
6014 (setq col (current-column))
6015 (if (< diff 0) (replace-match ""))
6016 (indent-to (+ diff col))))
6017 (move-marker end nil))))
6019 (defun org-convert-to-odd-levels ()
6020 "Convert an org-mode file with all levels allowed to one with odd levels.
6021 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6022 level 5 etc."
6023 (interactive)
6024 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6025 (let ((org-odd-levels-only nil) n)
6026 (save-excursion
6027 (goto-char (point-min))
6028 (while (re-search-forward "^\\*\\*+ " nil t)
6029 (setq n (- (length (match-string 0)) 2))
6030 (while (>= (setq n (1- n)) 0)
6031 (org-demote))
6032 (end-of-line 1))))))
6035 (defun org-convert-to-oddeven-levels ()
6036 "Convert an org-mode file with only odd levels to one with odd and even levels.
6037 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6038 section with an even level, conversion would destroy the structure of the file. An error
6039 is signaled in this case."
6040 (interactive)
6041 (goto-char (point-min))
6042 ;; First check if there are no even levels
6043 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6044 (org-show-context t)
6045 (error "Not all levels are odd in this file. Conversion not possible."))
6046 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6047 (let ((org-odd-levels-only nil) n)
6048 (save-excursion
6049 (goto-char (point-min))
6050 (while (re-search-forward "^\\*\\*+ " nil t)
6051 (setq n (/ (1- (length (match-string 0))) 2))
6052 (while (>= (setq n (1- n)) 0)
6053 (org-promote))
6054 (end-of-line 1))))))
6056 (defun org-tr-level (n)
6057 "Make N odd if required."
6058 (if org-odd-levels-only (1+ (/ n 2)) n))
6060 ;;; Vertical tree motion, cutting and pasting of subtrees
6062 (defun org-move-subtree-up (&optional arg)
6063 "Move the current subtree up past ARG headlines of the same level."
6064 (interactive "p")
6065 (org-move-subtree-down (- (prefix-numeric-value arg))))
6067 (defun org-move-subtree-down (&optional arg)
6068 "Move the current subtree down past ARG headlines of the same level."
6069 (interactive "p")
6070 (setq arg (prefix-numeric-value arg))
6071 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6072 'outline-get-last-sibling))
6073 (ins-point (make-marker))
6074 (cnt (abs arg))
6075 beg end txt folded)
6076 ;; Select the tree
6077 (org-back-to-heading)
6078 (setq beg (point))
6079 (save-match-data
6080 (save-excursion (outline-end-of-heading)
6081 (setq folded (org-invisible-p)))
6082 (outline-end-of-subtree))
6083 (outline-next-heading)
6084 (setq end (point))
6085 ;; Find insertion point, with error handling
6086 (goto-char beg)
6087 (while (> cnt 0)
6088 (or (and (funcall movfunc) (looking-at outline-regexp))
6089 (progn (goto-char beg)
6090 (error "Cannot move past superior level or buffer limit")))
6091 (setq cnt (1- cnt)))
6092 (if (> arg 0)
6093 ;; Moving forward - still need to move over subtree
6094 (progn (outline-end-of-subtree)
6095 (outline-next-heading)
6096 (if (not (or (looking-at (concat "^" outline-regexp))
6097 (bolp)))
6098 (newline))))
6099 (move-marker ins-point (point))
6100 (setq txt (buffer-substring beg end))
6101 (delete-region beg end)
6102 (insert txt)
6103 (or (bolp) (insert "\n"))
6104 (goto-char ins-point)
6105 (if folded (hide-subtree))
6106 (move-marker ins-point nil)))
6108 (defvar org-subtree-clip ""
6109 "Clipboard for cut and paste of subtrees.
6110 This is actually only a copy of the kill, because we use the normal kill
6111 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6113 (defvar org-subtree-clip-folded nil
6114 "Was the last copied subtree folded?
6115 This is used to fold the tree back after pasting.")
6117 (defun org-cut-subtree (&optional n)
6118 "Cut the current subtree into the clipboard.
6119 With prefix arg N, cut this many sequential subtrees.
6120 This is a short-hand for marking the subtree and then cutting it."
6121 (interactive "p")
6122 (org-copy-subtree n 'cut))
6124 (defun org-copy-subtree (&optional n cut)
6125 "Cut the current subtree into the clipboard.
6126 With prefix arg N, cut this many sequential subtrees.
6127 This is a short-hand for marking the subtree and then copying it.
6128 If CUT is non-nil, actually cut the subtree."
6129 (interactive "p")
6130 (let (beg end folded)
6131 (if (interactive-p)
6132 (org-back-to-heading nil) ; take what looks like a subtree
6133 (org-back-to-heading t)) ; take what is really there
6134 (setq beg (point))
6135 (save-match-data
6136 (save-excursion (outline-end-of-heading)
6137 (setq folded (org-invisible-p)))
6138 (condition-case nil
6139 (outline-forward-same-level (1- n))
6140 (error nil))
6141 (org-end-of-subtree t t))
6142 (setq end (point))
6143 (goto-char beg)
6144 (when (> end beg)
6145 (setq org-subtree-clip-folded folded)
6146 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6147 (setq org-subtree-clip (current-kill 0))
6148 (message "%s: Subtree(s) with %d characters"
6149 (if cut "Cut" "Copied")
6150 (length org-subtree-clip)))))
6152 (defun org-paste-subtree (&optional level tree)
6153 "Paste the clipboard as a subtree, with modification of headline level.
6154 The entire subtree is promoted or demoted in order to match a new headline
6155 level. By default, the new level is derived from the visible headings
6156 before and after the insertion point, and taken to be the inferior headline
6157 level of the two. So if the previous visible heading is level 3 and the
6158 next is level 4 (or vice versa), level 4 will be used for insertion.
6159 This makes sure that the subtree remains an independent subtree and does
6160 not swallow low level entries.
6162 You can also force a different level, either by using a numeric prefix
6163 argument, or by inserting the heading marker by hand. For example, if the
6164 cursor is after \"*****\", then the tree will be shifted to level 5.
6166 If you want to insert the tree as is, just use \\[yank].
6168 If optional TREE is given, use this text instead of the kill ring."
6169 (interactive "P")
6170 (unless (org-kill-is-subtree-p tree)
6171 (error
6172 (substitute-command-keys
6173 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6174 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6175 (^re (concat "^\\(" outline-regexp "\\)"))
6176 (re (concat "\\(" outline-regexp "\\)"))
6177 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6179 (old-level (if (string-match ^re txt)
6180 (- (match-end 0) (match-beginning 0) 1)
6181 -1))
6182 (force-level (cond (level (prefix-numeric-value level))
6183 ((string-match
6184 ^re_ (buffer-substring (point-at-bol) (point)))
6185 (- (match-end 1) (match-beginning 1)))
6186 (t nil)))
6187 (previous-level (save-excursion
6188 (condition-case nil
6189 (progn
6190 (outline-previous-visible-heading 1)
6191 (if (looking-at re)
6192 (- (match-end 0) (match-beginning 0) 1)
6194 (error 1))))
6195 (next-level (save-excursion
6196 (condition-case nil
6197 (progn
6198 (or (looking-at outline-regexp)
6199 (outline-next-visible-heading 1))
6200 (if (looking-at re)
6201 (- (match-end 0) (match-beginning 0) 1)
6203 (error 1))))
6204 (new-level (or force-level (max previous-level next-level)))
6205 (shift (if (or (= old-level -1)
6206 (= new-level -1)
6207 (= old-level new-level))
6209 (- new-level old-level)))
6210 (delta (if (> shift 0) -1 1))
6211 (func (if (> shift 0) 'org-demote 'org-promote))
6212 (org-odd-levels-only nil)
6213 beg end)
6214 ;; Remove the forced level indicator
6215 (if force-level
6216 (delete-region (point-at-bol) (point)))
6217 ;; Paste
6218 (beginning-of-line 1)
6219 (setq beg (point))
6220 (insert txt)
6221 (unless (string-match "\n\\'" txt) (insert "\n"))
6222 (setq end (point))
6223 (goto-char beg)
6224 ;; Shift if necessary
6225 (unless (= shift 0)
6226 (save-restriction
6227 (narrow-to-region beg end)
6228 (while (not (= shift 0))
6229 (org-map-region func (point-min) (point-max))
6230 (setq shift (+ delta shift)))
6231 (goto-char (point-min))))
6232 (when (interactive-p)
6233 (message "Clipboard pasted as level %d subtree" new-level))
6234 (if (and kill-ring
6235 (eq org-subtree-clip (current-kill 0))
6236 org-subtree-clip-folded)
6237 ;; The tree was folded before it was killed/copied
6238 (hide-subtree))))
6240 (defun org-kill-is-subtree-p (&optional txt)
6241 "Check if the current kill is an outline subtree, or a set of trees.
6242 Returns nil if kill does not start with a headline, or if the first
6243 headline level is not the largest headline level in the tree.
6244 So this will actually accept several entries of equal levels as well,
6245 which is OK for `org-paste-subtree'.
6246 If optional TXT is given, check this string instead of the current kill."
6247 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6248 (start-level (and kill
6249 (string-match (concat "\\`" org-outline-regexp) kill)
6250 (- (match-end 0) (match-beginning 0) 1)))
6251 (re (concat "^" org-outline-regexp))
6252 (start 1))
6253 (if (not start-level)
6254 (progn
6255 nil) ;; does not even start with a heading
6256 (catch 'exit
6257 (while (setq start (string-match re kill (1+ start)))
6258 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6259 (throw 'exit nil)))
6260 t))))
6262 (defun org-narrow-to-subtree ()
6263 "Narrow buffer to the current subtree."
6264 (interactive)
6265 (save-excursion
6266 (narrow-to-region
6267 (progn (org-back-to-heading) (point))
6268 (progn (org-end-of-subtree t t) (point)))))
6271 ;;; Outline Sorting
6273 (defun org-sort (with-case)
6274 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6275 Optional argument WITH-CASE means sort case-sensitively."
6276 (interactive "P")
6277 (if (org-at-table-p)
6278 (org-call-with-arg 'org-table-sort-lines with-case)
6279 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6281 (defvar org-priority-regexp) ; defined later in the file
6283 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6284 "Sort entries on a certain level of an outline tree.
6285 If there is an active region, the entries in the region are sorted.
6286 Else, if the cursor is before the first entry, sort the top-level items.
6287 Else, the children of the entry at point are sorted.
6289 Sorting can be alphabetically, numerically, and by date/time as given by
6290 the first time stamp in the entry. The command prompts for the sorting
6291 type unless it has been given to the function through the SORTING-TYPE
6292 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6293 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6294 called with point at the beginning of the record. It must return either
6295 a string or a number that should serve as the sorting key for that record.
6297 Comparing entries ignores case by default. However, with an optional argument
6298 WITH-CASE, the sorting considers case as well."
6299 (interactive "P")
6300 (let ((case-func (if with-case 'identity 'downcase))
6301 start beg end stars re re2
6302 txt what tmp plain-list-p)
6303 ;; Find beginning and end of region to sort
6304 (cond
6305 ((org-region-active-p)
6306 ;; we will sort the region
6307 (setq end (region-end)
6308 what "region")
6309 (goto-char (region-beginning))
6310 (if (not (org-on-heading-p)) (outline-next-heading))
6311 (setq start (point)))
6312 ((org-at-item-p)
6313 ;; we will sort this plain list
6314 (org-beginning-of-item-list) (setq start (point))
6315 (org-end-of-item-list) (setq end (point))
6316 (goto-char start)
6317 (setq plain-list-p t
6318 what "plain list"))
6319 ((or (org-on-heading-p)
6320 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6321 ;; we will sort the children of the current headline
6322 (org-back-to-heading)
6323 (setq start (point) end (org-end-of-subtree) what "children")
6324 (goto-char start)
6325 (show-subtree)
6326 (outline-next-heading))
6328 ;; we will sort the top-level entries in this file
6329 (goto-char (point-min))
6330 (or (org-on-heading-p) (outline-next-heading))
6331 (setq start (point) end (point-max) what "top-level")
6332 (goto-char start)
6333 (show-all)))
6335 (setq beg (point))
6336 (if (>= beg end) (error "Nothing to sort"))
6338 (unless plain-list-p
6339 (looking-at "\\(\\*+\\)")
6340 (setq stars (match-string 1)
6341 re (concat "^" (regexp-quote stars) " +")
6342 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6343 txt (buffer-substring beg end))
6344 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6345 (if (and (not (equal stars "*")) (string-match re2 txt))
6346 (error "Region to sort contains a level above the first entry")))
6348 (unless sorting-type
6349 (message
6350 (if plain-list-p
6351 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6352 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6353 what)
6354 (setq sorting-type (read-char-exclusive))
6356 (and (= (downcase sorting-type) ?f)
6357 (setq getkey-func
6358 (completing-read "Sort using function: "
6359 obarray 'fboundp t nil nil))
6360 (setq getkey-func (intern getkey-func)))
6362 (and (= (downcase sorting-type) ?r)
6363 (setq property
6364 (completing-read "Property: "
6365 (mapcar 'list (org-buffer-property-keys t))
6366 nil t))))
6368 (message "Sorting entries...")
6370 (save-restriction
6371 (narrow-to-region start end)
6373 (let ((dcst (downcase sorting-type))
6374 (now (current-time)))
6375 (sort-subr
6376 (/= dcst sorting-type)
6377 ;; This function moves to the beginning character of the "record" to
6378 ;; be sorted.
6379 (if plain-list-p
6380 (lambda nil
6381 (if (org-at-item-p) t (goto-char (point-max))))
6382 (lambda nil
6383 (if (re-search-forward re nil t)
6384 (goto-char (match-beginning 0))
6385 (goto-char (point-max)))))
6386 ;; This function moves to the last character of the "record" being
6387 ;; sorted.
6388 (if plain-list-p
6389 'org-end-of-item
6390 (lambda nil
6391 (save-match-data
6392 (condition-case nil
6393 (outline-forward-same-level 1)
6394 (error
6395 (goto-char (point-max)))))))
6397 ;; This function returns the value that gets sorted against.
6398 (if plain-list-p
6399 (lambda nil
6400 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6401 (cond
6402 ((= dcst ?n)
6403 (string-to-number (buffer-substring (match-end 0)
6404 (point-at-eol))))
6405 ((= dcst ?a)
6406 (buffer-substring (match-end 0) (point-at-eol)))
6407 ((= dcst ?t)
6408 (if (re-search-forward org-ts-regexp
6409 (point-at-eol) t)
6410 (org-time-string-to-time (match-string 0))
6411 now))
6412 ((= dcst ?f)
6413 (if getkey-func
6414 (progn
6415 (setq tmp (funcall getkey-func))
6416 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6417 tmp)
6418 (error "Invalid key function `%s'" getkey-func)))
6419 (t (error "Invalid sorting type `%c'" sorting-type)))))
6420 (lambda nil
6421 (cond
6422 ((= dcst ?n)
6423 (if (looking-at outline-regexp)
6424 (string-to-number (buffer-substring (match-end 0)
6425 (point-at-eol)))
6426 nil))
6427 ((= dcst ?a)
6428 (funcall case-func (buffer-substring (point-at-bol)
6429 (point-at-eol))))
6430 ((= dcst ?t)
6431 (if (re-search-forward org-ts-regexp
6432 (save-excursion
6433 (forward-line 2)
6434 (point)) t)
6435 (org-time-string-to-time (match-string 0))
6436 now))
6437 ((= dcst ?p)
6438 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6439 (string-to-char (match-string 2))
6440 org-default-priority))
6441 ((= dcst ?r)
6442 (or (org-entry-get nil property) ""))
6443 ((= dcst ?f)
6444 (if getkey-func
6445 (progn
6446 (setq tmp (funcall getkey-func))
6447 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6448 tmp)
6449 (error "Invalid key function `%s'" getkey-func)))
6450 (t (error "Invalid sorting type `%c'" sorting-type)))))
6452 (cond
6453 ((= dcst ?a) 'string<)
6454 ((= dcst ?t) 'time-less-p)
6455 (t nil)))))
6456 (message "Sorting entries...done")))
6458 (defun org-do-sort (table what &optional with-case sorting-type)
6459 "Sort TABLE of WHAT according to SORTING-TYPE.
6460 The user will be prompted for the SORTING-TYPE if the call to this
6461 function does not specify it. WHAT is only for the prompt, to indicate
6462 what is being sorted. The sorting key will be extracted from
6463 the car of the elements of the table.
6464 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6465 (unless sorting-type
6466 (message
6467 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6468 what)
6469 (setq sorting-type (read-char-exclusive)))
6470 (let ((dcst (downcase sorting-type))
6471 extractfun comparefun)
6472 ;; Define the appropriate functions
6473 (cond
6474 ((= dcst ?n)
6475 (setq extractfun 'string-to-number
6476 comparefun (if (= dcst sorting-type) '< '>)))
6477 ((= dcst ?a)
6478 (setq extractfun (if with-case 'identity 'downcase)
6479 comparefun (if (= dcst sorting-type)
6480 'string<
6481 (lambda (a b) (and (not (string< a b))
6482 (not (string= a b)))))))
6483 ((= dcst ?t)
6484 (setq extractfun
6485 (lambda (x)
6486 (if (string-match org-ts-regexp x)
6487 (time-to-seconds
6488 (org-time-string-to-time (match-string 0 x)))
6490 comparefun (if (= dcst sorting-type) '< '>)))
6491 (t (error "Invalid sorting type `%c'" sorting-type)))
6493 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6494 table)
6495 (lambda (a b) (funcall comparefun (car a) (car b))))))
6497 ;;;; Plain list items, including checkboxes
6499 ;;; Plain list items
6501 (defun org-at-item-p ()
6502 "Is point in a line starting a hand-formatted item?"
6503 (let ((llt org-plain-list-ordered-item-terminator))
6504 (save-excursion
6505 (goto-char (point-at-bol))
6506 (looking-at
6507 (cond
6508 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6509 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6510 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6511 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6513 (defun org-in-item-p ()
6514 "It the cursor inside a plain list item.
6515 Does not have to be the first line."
6516 (save-excursion
6517 (condition-case nil
6518 (progn
6519 (org-beginning-of-item)
6520 (org-at-item-p)
6522 (error nil))))
6524 (defun org-insert-item (&optional checkbox)
6525 "Insert a new item at the current level.
6526 Return t when things worked, nil when we are not in an item."
6527 (when (save-excursion
6528 (condition-case nil
6529 (progn
6530 (org-beginning-of-item)
6531 (org-at-item-p)
6532 (if (org-invisible-p) (error "Invisible item"))
6534 (error nil)))
6535 (let* ((bul (match-string 0))
6536 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6537 (match-end 0)))
6538 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6539 pos)
6540 (cond
6541 ((and (org-at-item-p) (<= (point) eow))
6542 ;; before the bullet
6543 (beginning-of-line 1)
6544 (open-line (if blank 2 1)))
6545 ((<= (point) eow)
6546 (beginning-of-line 1))
6547 (t (newline (if blank 2 1))))
6548 (insert bul (if checkbox "[ ]" ""))
6549 (just-one-space)
6550 (setq pos (point))
6551 (end-of-line 1)
6552 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6553 (org-maybe-renumber-ordered-list)
6554 (and checkbox (org-update-checkbox-count-maybe))
6557 ;;; Checkboxes
6559 (defun org-at-item-checkbox-p ()
6560 "Is point at a line starting a plain-list item with a checklet?"
6561 (and (org-at-item-p)
6562 (save-excursion
6563 (goto-char (match-end 0))
6564 (skip-chars-forward " \t")
6565 (looking-at "\\[[- X]\\]"))))
6567 (defun org-toggle-checkbox (&optional arg)
6568 "Toggle the checkbox in the current line."
6569 (interactive "P")
6570 (catch 'exit
6571 (let (beg end status (firstnew 'unknown))
6572 (cond
6573 ((org-region-active-p)
6574 (setq beg (region-beginning) end (region-end)))
6575 ((org-on-heading-p)
6576 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6577 ((org-at-item-checkbox-p)
6578 (let ((pos (point)))
6579 (replace-match
6580 (cond (arg "[-]")
6581 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6582 (t "[ ]"))
6583 t t)
6584 (goto-char pos))
6585 (throw 'exit t))
6586 (t (error "Not at a checkbox or heading, and no active region")))
6587 (save-excursion
6588 (goto-char beg)
6589 (while (< (point) end)
6590 (when (org-at-item-checkbox-p)
6591 (setq status (equal (match-string 0) "[X]"))
6592 (when (eq firstnew 'unknown)
6593 (setq firstnew (not status)))
6594 (replace-match
6595 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6596 (beginning-of-line 2)))))
6597 (org-update-checkbox-count-maybe))
6599 (defun org-update-checkbox-count-maybe ()
6600 "Update checkbox statistics unless turned off by user."
6601 (when org-provide-checkbox-statistics
6602 (org-update-checkbox-count)))
6604 (defun org-update-checkbox-count (&optional all)
6605 "Update the checkbox statistics in the current section.
6606 This will find all statistic cookies like [57%] and [6/12] and update them
6607 with the current numbers. With optional prefix argument ALL, do this for
6608 the whole buffer."
6609 (interactive "P")
6610 (save-excursion
6611 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6612 (beg (condition-case nil
6613 (progn (outline-back-to-heading) (point))
6614 (error (point-min))))
6615 (end (move-marker (make-marker)
6616 (progn (outline-next-heading) (point))))
6617 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6618 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6619 b1 e1 f1 c-on c-off lim (cstat 0))
6620 (when all
6621 (goto-char (point-min))
6622 (outline-next-heading)
6623 (setq beg (point) end (point-max)))
6624 (goto-char beg)
6625 (while (re-search-forward re end t)
6626 (setq cstat (1+ cstat)
6627 b1 (match-beginning 0)
6628 e1 (match-end 0)
6629 f1 (match-beginning 1)
6630 lim (cond
6631 ((org-on-heading-p) (outline-next-heading) (point))
6632 ((org-at-item-p) (org-end-of-item) (point))
6633 (t nil))
6634 c-on 0 c-off 0)
6635 (goto-char e1)
6636 (when lim
6637 (while (re-search-forward re-box lim t)
6638 (if (member (match-string 2) '("[ ]" "[-]"))
6639 (setq c-off (1+ c-off))
6640 (setq c-on (1+ c-on))))
6641 ; (delete-region b1 e1)
6642 (goto-char b1)
6643 (insert (if f1
6644 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6645 (format "[%d/%d]" c-on (+ c-on c-off))))
6646 (and (looking-at "\\[.*?\\]")
6647 (replace-match ""))))
6648 (when (interactive-p)
6649 (message "Checkbox satistics updated %s (%d places)"
6650 (if all "in entire file" "in current outline entry") cstat)))))
6652 (defun org-get-checkbox-statistics-face ()
6653 "Select the face for checkbox statistics.
6654 The face will be `org-done' when all relevant boxes are checked. Otherwise
6655 it will be `org-todo'."
6656 (if (match-end 1)
6657 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6658 (if (and (> (match-end 2) (match-beginning 2))
6659 (equal (match-string 2) (match-string 3)))
6660 'org-done
6661 'org-todo)))
6663 (defun org-get-indentation (&optional line)
6664 "Get the indentation of the current line, interpreting tabs.
6665 When LINE is given, assume it represents a line and compute its indentation."
6666 (if line
6667 (if (string-match "^ *" (org-remove-tabs line))
6668 (match-end 0))
6669 (save-excursion
6670 (beginning-of-line 1)
6671 (skip-chars-forward " \t")
6672 (current-column))))
6674 (defun org-remove-tabs (s &optional width)
6675 "Replace tabulators in S with spaces.
6676 Assumes that s is a single line, starting in column 0."
6677 (setq width (or width tab-width))
6678 (while (string-match "\t" s)
6679 (setq s (replace-match
6680 (make-string
6681 (- (* width (/ (+ (match-beginning 0) width) width))
6682 (match-beginning 0)) ?\ )
6683 t t s)))
6686 (defun org-fix-indentation (line ind)
6687 "Fix indentation in LINE.
6688 IND is a cons cell with target and minimum indentation.
6689 If the current indenation in LINE is smaller than the minimum,
6690 leave it alone. If it is larger than ind, set it to the target."
6691 (let* ((l (org-remove-tabs line))
6692 (i (org-get-indentation l))
6693 (i1 (car ind)) (i2 (cdr ind)))
6694 (if (>= i i2) (setq l (substring line i2)))
6695 (if (> i1 0)
6696 (concat (make-string i1 ?\ ) l)
6697 l)))
6699 (defcustom org-empty-line-terminates-plain-lists nil
6700 "Non-nil means, an empty line ends all plain list levels.
6701 When nil, empty lines are part of the preceeding item."
6702 :group 'org-plain-lists
6703 :type 'boolean)
6705 (defun org-beginning-of-item ()
6706 "Go to the beginning of the current hand-formatted item.
6707 If the cursor is not in an item, throw an error."
6708 (interactive)
6709 (let ((pos (point))
6710 (limit (save-excursion
6711 (condition-case nil
6712 (progn
6713 (org-back-to-heading)
6714 (beginning-of-line 2) (point))
6715 (error (point-min)))))
6716 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6717 ind ind1)
6718 (if (org-at-item-p)
6719 (beginning-of-line 1)
6720 (beginning-of-line 1)
6721 (skip-chars-forward " \t")
6722 (setq ind (current-column))
6723 (if (catch 'exit
6724 (while t
6725 (beginning-of-line 0)
6726 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6728 (if (looking-at "[ \t]*$")
6729 (setq ind1 ind-empty)
6730 (skip-chars-forward " \t")
6731 (setq ind1 (current-column)))
6732 (if (< ind1 ind)
6733 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6735 (goto-char pos)
6736 (error "Not in an item")))))
6738 (defun org-end-of-item ()
6739 "Go to the end of the current hand-formatted item.
6740 If the cursor is not in an item, throw an error."
6741 (interactive)
6742 (let* ((pos (point))
6743 ind1
6744 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6745 (limit (save-excursion (outline-next-heading) (point)))
6746 (ind (save-excursion
6747 (org-beginning-of-item)
6748 (skip-chars-forward " \t")
6749 (current-column)))
6750 (end (catch 'exit
6751 (while t
6752 (beginning-of-line 2)
6753 (if (eobp) (throw 'exit (point)))
6754 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6755 (if (looking-at "[ \t]*$")
6756 (setq ind1 ind-empty)
6757 (skip-chars-forward " \t")
6758 (setq ind1 (current-column)))
6759 (if (<= ind1 ind)
6760 (throw 'exit (point-at-bol)))))))
6761 (if end
6762 (goto-char end)
6763 (goto-char pos)
6764 (error "Not in an item"))))
6766 (defun org-next-item ()
6767 "Move to the beginning of the next item in the current plain list.
6768 Error if not at a plain list, or if this is the last item in the list."
6769 (interactive)
6770 (let (ind ind1 (pos (point)))
6771 (org-beginning-of-item)
6772 (setq ind (org-get-indentation))
6773 (org-end-of-item)
6774 (setq ind1 (org-get-indentation))
6775 (unless (and (org-at-item-p) (= ind ind1))
6776 (goto-char pos)
6777 (error "On last item"))))
6779 (defun org-previous-item ()
6780 "Move to the beginning of the previous item in the current plain list.
6781 Error if not at a plain list, or if this is the first item in the list."
6782 (interactive)
6783 (let (beg ind ind1 (pos (point)))
6784 (org-beginning-of-item)
6785 (setq beg (point))
6786 (setq ind (org-get-indentation))
6787 (goto-char beg)
6788 (catch 'exit
6789 (while t
6790 (beginning-of-line 0)
6791 (if (looking-at "[ \t]*$")
6793 (if (<= (setq ind1 (org-get-indentation)) ind)
6794 (throw 'exit t)))))
6795 (condition-case nil
6796 (if (or (not (org-at-item-p))
6797 (< ind1 (1- ind)))
6798 (error "")
6799 (org-beginning-of-item))
6800 (error (goto-char pos)
6801 (error "On first item")))))
6803 (defun org-move-item-down ()
6804 "Move the plain list item at point down, i.e. swap with following item.
6805 Subitems (items with larger indentation) are considered part of the item,
6806 so this really moves item trees."
6807 (interactive)
6808 (let (beg end ind ind1 (pos (point)) txt)
6809 (org-beginning-of-item)
6810 (setq beg (point))
6811 (setq ind (org-get-indentation))
6812 (org-end-of-item)
6813 (setq end (point))
6814 (setq ind1 (org-get-indentation))
6815 (if (and (org-at-item-p) (= ind ind1))
6816 (progn
6817 (org-end-of-item)
6818 (setq txt (buffer-substring beg end))
6819 (save-excursion
6820 (delete-region beg end))
6821 (setq pos (point))
6822 (insert txt)
6823 (goto-char pos)
6824 (org-maybe-renumber-ordered-list))
6825 (goto-char pos)
6826 (error "Cannot move this item further down"))))
6828 (defun org-move-item-up (arg)
6829 "Move the plain list item at point up, i.e. swap with previous item.
6830 Subitems (items with larger indentation) are considered part of the item,
6831 so this really moves item trees."
6832 (interactive "p")
6833 (let (beg end ind ind1 (pos (point)) txt)
6834 (org-beginning-of-item)
6835 (setq beg (point))
6836 (setq ind (org-get-indentation))
6837 (org-end-of-item)
6838 (setq end (point))
6839 (goto-char beg)
6840 (catch 'exit
6841 (while t
6842 (beginning-of-line 0)
6843 (if (looking-at "[ \t]*$")
6844 (if org-empty-line-terminates-plain-lists
6845 (progn
6846 (goto-char pos)
6847 (error "Cannot move this item further up"))
6848 nil)
6849 (if (<= (setq ind1 (org-get-indentation)) ind)
6850 (throw 'exit t)))))
6851 (condition-case nil
6852 (org-beginning-of-item)
6853 (error (goto-char beg)
6854 (error "Cannot move this item further up")))
6855 (setq ind1 (org-get-indentation))
6856 (if (and (org-at-item-p) (= ind ind1))
6857 (progn
6858 (setq txt (buffer-substring beg end))
6859 (save-excursion
6860 (delete-region beg end))
6861 (setq pos (point))
6862 (insert txt)
6863 (goto-char pos)
6864 (org-maybe-renumber-ordered-list))
6865 (goto-char pos)
6866 (error "Cannot move this item further up"))))
6868 (defun org-maybe-renumber-ordered-list ()
6869 "Renumber the ordered list at point if setup allows it.
6870 This tests the user option `org-auto-renumber-ordered-lists' before
6871 doing the renumbering."
6872 (interactive)
6873 (when (and org-auto-renumber-ordered-lists
6874 (org-at-item-p))
6875 (if (match-beginning 3)
6876 (org-renumber-ordered-list 1)
6877 (org-fix-bullet-type))))
6879 (defun org-maybe-renumber-ordered-list-safe ()
6880 (condition-case nil
6881 (save-excursion
6882 (org-maybe-renumber-ordered-list))
6883 (error nil)))
6885 (defun org-cycle-list-bullet (&optional which)
6886 "Cycle through the different itemize/enumerate bullets.
6887 This cycle the entire list level through the sequence:
6889 `-' -> `+' -> `*' -> `1.' -> `1)'
6891 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6892 0 meand `-', 1 means `+' etc."
6893 (interactive "P")
6894 (org-preserve-lc
6895 (org-beginning-of-item-list)
6896 (org-at-item-p)
6897 (beginning-of-line 1)
6898 (let ((current (match-string 0))
6899 (prevp (eq which 'previous))
6900 new)
6901 (setq new (cond
6902 ((and (numberp which)
6903 (nth (1- which) '("-" "+" "*" "1." "1)"))))
6904 ((string-match "-" current) (if prevp "1)" "+"))
6905 ((string-match "\\+" current)
6906 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
6907 ((string-match "\\*" current) (if prevp "+" "1."))
6908 ((string-match "\\." current) (if prevp "*" "1)"))
6909 ((string-match ")" current) (if prevp "1." "-"))
6910 (t (error "This should not happen"))))
6911 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6912 (org-fix-bullet-type)
6913 (org-maybe-renumber-ordered-list))))
6915 (defun org-get-string-indentation (s)
6916 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6917 (let ((n -1) (i 0) (w tab-width) c)
6918 (catch 'exit
6919 (while (< (setq n (1+ n)) (length s))
6920 (setq c (aref s n))
6921 (cond ((= c ?\ ) (setq i (1+ i)))
6922 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6923 (t (throw 'exit t)))))
6926 (defun org-renumber-ordered-list (arg)
6927 "Renumber an ordered plain list.
6928 Cursor needs to be in the first line of an item, the line that starts
6929 with something like \"1.\" or \"2)\"."
6930 (interactive "p")
6931 (unless (and (org-at-item-p)
6932 (match-beginning 3))
6933 (error "This is not an ordered list"))
6934 (let ((line (org-current-line))
6935 (col (current-column))
6936 (ind (org-get-string-indentation
6937 (buffer-substring (point-at-bol) (match-beginning 3))))
6938 ;; (term (substring (match-string 3) -1))
6939 ind1 (n (1- arg))
6940 fmt)
6941 ;; find where this list begins
6942 (org-beginning-of-item-list)
6943 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6944 (setq fmt (concat "%d" (match-string 1)))
6945 (beginning-of-line 0)
6946 ;; walk forward and replace these numbers
6947 (catch 'exit
6948 (while t
6949 (catch 'next
6950 (beginning-of-line 2)
6951 (if (eobp) (throw 'exit nil))
6952 (if (looking-at "[ \t]*$") (throw 'next nil))
6953 (skip-chars-forward " \t") (setq ind1 (current-column))
6954 (if (> ind1 ind) (throw 'next t))
6955 (if (< ind1 ind) (throw 'exit t))
6956 (if (not (org-at-item-p)) (throw 'exit nil))
6957 (delete-region (match-beginning 2) (match-end 2))
6958 (goto-char (match-beginning 2))
6959 (insert (format fmt (setq n (1+ n)))))))
6960 (goto-line line)
6961 (move-to-column col)))
6963 (defun org-fix-bullet-type ()
6964 "Make sure all items in this list have the same bullet as the firsst item."
6965 (interactive)
6966 (unless (org-at-item-p) (error "This is not a list"))
6967 (let ((line (org-current-line))
6968 (col (current-column))
6969 (ind (current-indentation))
6970 ind1 bullet)
6971 ;; find where this list begins
6972 (org-beginning-of-item-list)
6973 (beginning-of-line 1)
6974 ;; find out what the bullet type is
6975 (looking-at "[ \t]*\\(\\S-+\\)")
6976 (setq bullet (match-string 1))
6977 ;; walk forward and replace these numbers
6978 (beginning-of-line 0)
6979 (catch 'exit
6980 (while t
6981 (catch 'next
6982 (beginning-of-line 2)
6983 (if (eobp) (throw 'exit nil))
6984 (if (looking-at "[ \t]*$") (throw 'next nil))
6985 (skip-chars-forward " \t") (setq ind1 (current-column))
6986 (if (> ind1 ind) (throw 'next t))
6987 (if (< ind1 ind) (throw 'exit t))
6988 (if (not (org-at-item-p)) (throw 'exit nil))
6989 (skip-chars-forward " \t")
6990 (looking-at "\\S-+")
6991 (replace-match bullet))))
6992 (goto-line line)
6993 (move-to-column col)
6994 (if (string-match "[0-9]" bullet)
6995 (org-renumber-ordered-list 1))))
6997 (defun org-beginning-of-item-list ()
6998 "Go to the beginning of the current item list.
6999 I.e. to the first item in this list."
7000 (interactive)
7001 (org-beginning-of-item)
7002 (let ((pos (point-at-bol))
7003 (ind (org-get-indentation))
7004 ind1)
7005 ;; find where this list begins
7006 (catch 'exit
7007 (while t
7008 (catch 'next
7009 (beginning-of-line 0)
7010 (if (looking-at "[ \t]*$")
7011 (throw (if (bobp) 'exit 'next) t))
7012 (skip-chars-forward " \t") (setq ind1 (current-column))
7013 (if (or (< ind1 ind)
7014 (and (= ind1 ind)
7015 (not (org-at-item-p)))
7016 (bobp))
7017 (throw 'exit t)
7018 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7019 (goto-char pos)))
7022 (defun org-end-of-item-list ()
7023 "Go to the end of the current item list.
7024 I.e. to the text after the last item."
7025 (interactive)
7026 (org-beginning-of-item)
7027 (let ((pos (point-at-bol))
7028 (ind (org-get-indentation))
7029 ind1)
7030 ;; find where this list begins
7031 (catch 'exit
7032 (while t
7033 (catch 'next
7034 (beginning-of-line 2)
7035 (if (looking-at "[ \t]*$")
7036 (throw (if (eobp) 'exit 'next) t))
7037 (skip-chars-forward " \t") (setq ind1 (current-column))
7038 (if (or (< ind1 ind)
7039 (and (= ind1 ind)
7040 (not (org-at-item-p)))
7041 (eobp))
7042 (progn
7043 (setq pos (point-at-bol))
7044 (throw 'exit t))))))
7045 (goto-char pos)))
7048 (defvar org-last-indent-begin-marker (make-marker))
7049 (defvar org-last-indent-end-marker (make-marker))
7051 (defun org-outdent-item (arg)
7052 "Outdent a local list item."
7053 (interactive "p")
7054 (org-indent-item (- arg)))
7056 (defun org-indent-item (arg)
7057 "Indent a local list item."
7058 (interactive "p")
7059 (unless (org-at-item-p)
7060 (error "Not on an item"))
7061 (save-excursion
7062 (let (beg end ind ind1 tmp delta ind-down ind-up)
7063 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7064 (setq beg org-last-indent-begin-marker
7065 end org-last-indent-end-marker)
7066 (org-beginning-of-item)
7067 (setq beg (move-marker org-last-indent-begin-marker (point)))
7068 (org-end-of-item)
7069 (setq end (move-marker org-last-indent-end-marker (point))))
7070 (goto-char beg)
7071 (setq tmp (org-item-indent-positions)
7072 ind (car tmp)
7073 ind-down (nth 2 tmp)
7074 ind-up (nth 1 tmp)
7075 delta (if (> arg 0)
7076 (if ind-down (- ind-down ind) 2)
7077 (if ind-up (- ind-up ind) -2)))
7078 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7079 (while (< (point) end)
7080 (beginning-of-line 1)
7081 (skip-chars-forward " \t") (setq ind1 (current-column))
7082 (delete-region (point-at-bol) (point))
7083 (or (eolp) (indent-to-column (+ ind1 delta)))
7084 (beginning-of-line 2))))
7085 (org-fix-bullet-type)
7086 (org-maybe-renumber-ordered-list-safe)
7087 (save-excursion
7088 (beginning-of-line 0)
7089 (condition-case nil (org-beginning-of-item) (error nil))
7090 (org-maybe-renumber-ordered-list-safe)))
7092 (defun org-item-indent-positions ()
7093 "Return indentation for plain list items.
7094 This returns a list with three values: The current indentation, the
7095 parent indentation and the indentation a child should habe.
7096 Assumes cursor in item line."
7097 (let* ((bolpos (point-at-bol))
7098 (ind (org-get-indentation))
7099 ind-down ind-up pos)
7100 (save-excursion
7101 (org-beginning-of-item-list)
7102 (skip-chars-backward "\n\r \t")
7103 (when (org-in-item-p)
7104 (org-beginning-of-item)
7105 (setq ind-up (org-get-indentation))))
7106 (setq pos (point))
7107 (save-excursion
7108 (cond
7109 ((and (condition-case nil (progn (org-previous-item) t)
7110 (error nil))
7111 (or (forward-char 1) t)
7112 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7113 (setq ind-down (org-get-indentation)))
7114 ((and (goto-char pos)
7115 (org-at-item-p))
7116 (goto-char (match-end 0))
7117 (skip-chars-forward " \t")
7118 (setq ind-down (current-column)))))
7119 (list ind ind-up ind-down)))
7121 ;;; The orgstruct minor mode
7123 ;; Define a minor mode which can be used in other modes in order to
7124 ;; integrate the org-mode structure editing commands.
7126 ;; This is really a hack, because the org-mode structure commands use
7127 ;; keys which normally belong to the major mode. Here is how it
7128 ;; works: The minor mode defines all the keys necessary to operate the
7129 ;; structure commands, but wraps the commands into a function which
7130 ;; tests if the cursor is currently at a headline or a plain list
7131 ;; item. If that is the case, the structure command is used,
7132 ;; temporarily setting many Org-mode variables like regular
7133 ;; expressions for filling etc. However, when any of those keys is
7134 ;; used at a different location, function uses `key-binding' to look
7135 ;; up if the key has an associated command in another currently active
7136 ;; keymap (minor modes, major mode, global), and executes that
7137 ;; command. There might be problems if any of the keys is otherwise
7138 ;; used as a prefix key.
7140 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7141 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7142 ;; addresses this by checking explicitly for both bindings.
7144 (defvar orgstruct-mode-map (make-sparse-keymap)
7145 "Keymap for the minor `orgstruct-mode'.")
7147 (defvar org-local-vars nil
7148 "List of local variables, for use by `orgstruct-mode'")
7150 ;;;###autoload
7151 (define-minor-mode orgstruct-mode
7152 "Toggle the minor more `orgstruct-mode'.
7153 This mode is for using Org-mode structure commands in other modes.
7154 The following key behave as if Org-mode was active, if the cursor
7155 is on a headline, or on a plain list item (both in the definition
7156 of Org-mode).
7158 M-up Move entry/item up
7159 M-down Move entry/item down
7160 M-left Promote
7161 M-right Demote
7162 M-S-up Move entry/item up
7163 M-S-down Move entry/item down
7164 M-S-left Promote subtree
7165 M-S-right Demote subtree
7166 M-q Fill paragraph and items like in Org-mode
7167 C-c ^ Sort entries
7168 C-c - Cycle list bullet
7169 TAB Cycle item visibility
7170 M-RET Insert new heading/item
7171 S-M-RET Insert new TODO heading / Chekbox item
7172 C-c C-c Set tags / toggle checkbox"
7173 nil " OrgStruct" nil
7174 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7176 ;;;###autoload
7177 (defun turn-on-orgstruct ()
7178 "Unconditionally turn on `orgstruct-mode'."
7179 (orgstruct-mode 1))
7181 ;;;###autoload
7182 (defun turn-on-orgstruct++ ()
7183 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7184 In addition to setting orgstruct-mode, this also exports all indentation and
7185 autofilling variables from org-mode into the buffer. Note that turning
7186 off orgstruct-mode will *not* remove these additonal settings."
7187 (orgstruct-mode 1)
7188 (let (var val)
7189 (mapc
7190 (lambda (x)
7191 (when (string-match
7192 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7193 (symbol-name (car x)))
7194 (setq var (car x) val (nth 1 x))
7195 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7196 org-local-vars)))
7198 (defun orgstruct-error ()
7199 "Error when there is no default binding for a structure key."
7200 (interactive)
7201 (error "This key is has no function outside structure elements"))
7203 (defun orgstruct-setup ()
7204 "Setup orgstruct keymaps."
7205 (let ((nfunc 0)
7206 (bindings
7207 (list
7208 '([(meta up)] org-metaup)
7209 '([(meta down)] org-metadown)
7210 '([(meta left)] org-metaleft)
7211 '([(meta right)] org-metaright)
7212 '([(meta shift up)] org-shiftmetaup)
7213 '([(meta shift down)] org-shiftmetadown)
7214 '([(meta shift left)] org-shiftmetaleft)
7215 '([(meta shift right)] org-shiftmetaright)
7216 '([(shift up)] org-shiftup)
7217 '([(shift down)] org-shiftdown)
7218 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7219 '("\M-q" fill-paragraph)
7220 '("\C-c^" org-sort)
7221 '("\C-c-" org-cycle-list-bullet)))
7222 elt key fun cmd)
7223 (while (setq elt (pop bindings))
7224 (setq nfunc (1+ nfunc))
7225 (setq key (org-key (car elt))
7226 fun (nth 1 elt)
7227 cmd (orgstruct-make-binding fun nfunc key))
7228 (org-defkey orgstruct-mode-map key cmd))
7230 ;; Special treatment needed for TAB and RET
7231 (org-defkey orgstruct-mode-map [(tab)]
7232 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7233 (org-defkey orgstruct-mode-map "\C-i"
7234 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7236 (org-defkey orgstruct-mode-map "\M-\C-m"
7237 (orgstruct-make-binding 'org-insert-heading 105
7238 "\M-\C-m" [(meta return)]))
7239 (org-defkey orgstruct-mode-map [(meta return)]
7240 (orgstruct-make-binding 'org-insert-heading 106
7241 [(meta return)] "\M-\C-m"))
7243 (org-defkey orgstruct-mode-map [(shift meta return)]
7244 (orgstruct-make-binding 'org-insert-todo-heading 107
7245 [(meta return)] "\M-\C-m"))
7247 (unless org-local-vars
7248 (setq org-local-vars (org-get-local-variables)))
7252 (defun orgstruct-make-binding (fun n &rest keys)
7253 "Create a function for binding in the structure minor mode.
7254 FUN is the command to call inside a table. N is used to create a unique
7255 command name. KEYS are keys that should be checked in for a command
7256 to execute outside of tables."
7257 (eval
7258 (list 'defun
7259 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7260 '(arg)
7261 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7262 "Outside of structure, run the binding of `"
7263 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7264 "'.")
7265 '(interactive "p")
7266 (list 'if
7267 '(org-context-p 'headline 'item)
7268 (list 'org-run-like-in-org-mode (list 'quote fun))
7269 (list 'let '(orgstruct-mode)
7270 (list 'call-interactively
7271 (append '(or)
7272 (mapcar (lambda (k)
7273 (list 'key-binding k))
7274 keys)
7275 '('orgstruct-error))))))))
7277 (defun org-context-p (&rest contexts)
7278 "Check if local context is and of CONTEXTS.
7279 Possible values in the list of contexts are `table', `headline', and `item'."
7280 (let ((pos (point)))
7281 (goto-char (point-at-bol))
7282 (prog1 (or (and (memq 'table contexts)
7283 (looking-at "[ \t]*|"))
7284 (and (memq 'headline contexts)
7285 (looking-at "\\*+"))
7286 (and (memq 'item contexts)
7287 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7288 (goto-char pos))))
7290 (defun org-get-local-variables ()
7291 "Return a list of all local variables in an org-mode buffer."
7292 (let (varlist)
7293 (with-current-buffer (get-buffer-create "*Org tmp*")
7294 (erase-buffer)
7295 (org-mode)
7296 (setq varlist (buffer-local-variables)))
7297 (kill-buffer "*Org tmp*")
7298 (delq nil
7299 (mapcar
7300 (lambda (x)
7301 (setq x
7302 (if (symbolp x)
7303 (list x)
7304 (list (car x) (list 'quote (cdr x)))))
7305 (if (string-match
7306 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7307 (symbol-name (car x)))
7308 x nil))
7309 varlist))))
7311 ;;;###autoload
7312 (defun org-run-like-in-org-mode (cmd)
7313 (unless org-local-vars
7314 (setq org-local-vars (org-get-local-variables)))
7315 (eval (list 'let org-local-vars
7316 (list 'call-interactively (list 'quote cmd)))))
7318 ;;;; Archiving
7320 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7322 (defun org-archive-subtree (&optional find-done)
7323 "Move the current subtree to the archive.
7324 The archive can be a certain top-level heading in the current file, or in
7325 a different file. The tree will be moved to that location, the subtree
7326 heading be marked DONE, and the current time will be added.
7328 When called with prefix argument FIND-DONE, find whole trees without any
7329 open TODO items and archive them (after getting confirmation from the user).
7330 If the cursor is not at a headline when this comand is called, try all level
7331 1 trees. If the cursor is on a headline, only try the direct children of
7332 this heading."
7333 (interactive "P")
7334 (if find-done
7335 (org-archive-all-done)
7336 ;; Save all relevant TODO keyword-relatex variables
7338 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7339 (tr-org-todo-keywords-1 org-todo-keywords-1)
7340 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7341 (tr-org-done-keywords org-done-keywords)
7342 (tr-org-todo-regexp org-todo-regexp)
7343 (tr-org-todo-line-regexp org-todo-line-regexp)
7344 (tr-org-odd-levels-only org-odd-levels-only)
7345 (this-buffer (current-buffer))
7346 (org-archive-location org-archive-location)
7347 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7348 ;; start of variables that will be used for saving context
7349 ;; The compiler complains about them - keep them anyway!
7350 (file (abbreviate-file-name (buffer-file-name)))
7351 (time (format-time-string
7352 (substring (cdr org-time-stamp-formats) 1 -1)
7353 (current-time)))
7354 afile heading buffer level newfile-p
7355 category todo priority
7356 ;; start of variables that will be used for savind context
7357 ltags itags prop)
7359 ;; Try to find a local archive location
7360 (save-excursion
7361 (save-restriction
7362 (widen)
7363 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7364 (if (and prop (string-match "\\S-" prop))
7365 (setq org-archive-location prop)
7366 (if (or (re-search-backward re nil t)
7367 (re-search-forward re nil t))
7368 (setq org-archive-location (match-string 1))))))
7370 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7371 (progn
7372 (setq afile (format (match-string 1 org-archive-location)
7373 (file-name-nondirectory buffer-file-name))
7374 heading (match-string 2 org-archive-location)))
7375 (error "Invalid `org-archive-location'"))
7376 (if (> (length afile) 0)
7377 (setq newfile-p (not (file-exists-p afile))
7378 buffer (find-file-noselect afile))
7379 (setq buffer (current-buffer)))
7380 (unless buffer
7381 (error "Cannot access file \"%s\"" afile))
7382 (if (and (> (length heading) 0)
7383 (string-match "^\\*+" heading))
7384 (setq level (match-end 0))
7385 (setq heading nil level 0))
7386 (save-excursion
7387 (org-back-to-heading t)
7388 ;; Get context information that will be lost by moving the tree
7389 (org-refresh-category-properties)
7390 (setq category (org-get-category)
7391 todo (and (looking-at org-todo-line-regexp)
7392 (match-string 2))
7393 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7394 ltags (org-get-tags)
7395 itags (org-delete-all ltags (org-get-tags-at)))
7396 (setq ltags (mapconcat 'identity ltags " ")
7397 itags (mapconcat 'identity itags " "))
7398 ;; We first only copy, in case something goes wrong
7399 ;; we need to protect this-command, to avoid kill-region sets it,
7400 ;; which would lead to duplication of subtrees
7401 (let (this-command) (org-copy-subtree))
7402 (set-buffer buffer)
7403 ;; Enforce org-mode for the archive buffer
7404 (if (not (org-mode-p))
7405 ;; Force the mode for future visits.
7406 (let ((org-insert-mode-line-in-empty-file t)
7407 (org-inhibit-startup t))
7408 (call-interactively 'org-mode)))
7409 (when newfile-p
7410 (goto-char (point-max))
7411 (insert (format "\nArchived entries from file %s\n\n"
7412 (buffer-file-name this-buffer))))
7413 ;; Force the TODO keywords of the original buffer
7414 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7415 (org-todo-keywords-1 tr-org-todo-keywords-1)
7416 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7417 (org-done-keywords tr-org-done-keywords)
7418 (org-todo-regexp tr-org-todo-regexp)
7419 (org-todo-line-regexp tr-org-todo-line-regexp)
7420 (org-odd-levels-only
7421 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7422 org-odd-levels-only
7423 tr-org-odd-levels-only)))
7424 (goto-char (point-min))
7425 (if heading
7426 (progn
7427 (if (re-search-forward
7428 (concat "^" (regexp-quote heading)
7429 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7430 nil t)
7431 (goto-char (match-end 0))
7432 ;; Heading not found, just insert it at the end
7433 (goto-char (point-max))
7434 (or (bolp) (insert "\n"))
7435 (insert "\n" heading "\n")
7436 (end-of-line 0))
7437 ;; Make the subtree visible
7438 (show-subtree)
7439 (org-end-of-subtree t)
7440 (skip-chars-backward " \t\r\n")
7441 (and (looking-at "[ \t\r\n]*")
7442 (replace-match "\n\n")))
7443 ;; No specific heading, just go to end of file.
7444 (goto-char (point-max)) (insert "\n"))
7445 ;; Paste
7446 (org-paste-subtree (org-get-legal-level level 1))
7448 ;; Mark the entry as done
7449 (when (and org-archive-mark-done
7450 (looking-at org-todo-line-regexp)
7451 (or (not (match-end 2))
7452 (not (member (match-string 2) org-done-keywords))))
7453 (let (org-log-done)
7454 (org-todo
7455 (car (or (member org-archive-mark-done org-done-keywords)
7456 org-done-keywords)))))
7458 ;; Add the context info
7459 (when org-archive-save-context-info
7460 (let ((l org-archive-save-context-info) e n v)
7461 (while (setq e (pop l))
7462 (when (and (setq v (symbol-value e))
7463 (stringp v) (string-match "\\S-" v))
7464 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7465 (org-entry-put (point) n v)))))
7467 ;; Save the buffer, if it is not the same buffer.
7468 (if (not (eq this-buffer buffer)) (save-buffer))))
7469 ;; Here we are back in the original buffer. Everything seems to have
7470 ;; worked. So now cut the tree and finish up.
7471 (let (this-command) (org-cut-subtree))
7472 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7473 (message "Subtree archived %s"
7474 (if (eq this-buffer buffer)
7475 (concat "under heading: " heading)
7476 (concat "in file: " (abbreviate-file-name afile)))))))
7478 (defun org-refresh-category-properties ()
7479 "Refresh category text properties in teh buffer."
7480 (let ((def-cat (cond
7481 ((null org-category)
7482 (if buffer-file-name
7483 (file-name-sans-extension
7484 (file-name-nondirectory buffer-file-name))
7485 "???"))
7486 ((symbolp org-category) (symbol-name org-category))
7487 (t org-category)))
7488 beg end cat pos optionp)
7489 (org-unmodified
7490 (save-excursion
7491 (save-restriction
7492 (widen)
7493 (goto-char (point-min))
7494 (put-text-property (point) (point-max) 'org-category def-cat)
7495 (while (re-search-forward
7496 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7497 (setq pos (match-end 0)
7498 optionp (equal (char-after (match-beginning 0)) ?#)
7499 cat (org-trim (match-string 2)))
7500 (if optionp
7501 (setq beg (point-at-bol) end (point-max))
7502 (org-back-to-heading t)
7503 (setq beg (point) end (org-end-of-subtree t t)))
7504 (put-text-property beg end 'org-category cat)
7505 (goto-char pos)))))))
7507 (defun org-archive-all-done (&optional tag)
7508 "Archive sublevels of the current tree without open TODO items.
7509 If the cursor is not on a headline, try all level 1 trees. If
7510 it is on a headline, try all direct children.
7511 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7512 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7513 (rea (concat ".*:" org-archive-tag ":"))
7514 (begm (make-marker))
7515 (endm (make-marker))
7516 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7517 "Move subtree to archive (no open TODO items)? "))
7518 beg end (cntarch 0))
7519 (if (org-on-heading-p)
7520 (progn
7521 (setq re1 (concat "^" (regexp-quote
7522 (make-string
7523 (1+ (- (match-end 0) (match-beginning 0)))
7524 ?*))
7525 " "))
7526 (move-marker begm (point))
7527 (move-marker endm (org-end-of-subtree t)))
7528 (setq re1 "^* ")
7529 (move-marker begm (point-min))
7530 (move-marker endm (point-max)))
7531 (save-excursion
7532 (goto-char begm)
7533 (while (re-search-forward re1 endm t)
7534 (setq beg (match-beginning 0)
7535 end (save-excursion (org-end-of-subtree t) (point)))
7536 (goto-char beg)
7537 (if (re-search-forward re end t)
7538 (goto-char end)
7539 (goto-char beg)
7540 (if (and (or (not tag) (not (looking-at rea)))
7541 (y-or-n-p question))
7542 (progn
7543 (if tag
7544 (org-toggle-tag org-archive-tag 'on)
7545 (org-archive-subtree))
7546 (setq cntarch (1+ cntarch)))
7547 (goto-char end)))))
7548 (message "%d trees archived" cntarch)))
7550 (defun org-cycle-hide-drawers (state)
7551 "Re-hide all drawers after a visibility state change."
7552 (when (and (org-mode-p)
7553 (not (memq state '(overview folded))))
7554 (save-excursion
7555 (let* ((globalp (memq state '(contents all)))
7556 (beg (if globalp (point-min) (point)))
7557 (end (if globalp (point-max) (org-end-of-subtree t))))
7558 (goto-char beg)
7559 (while (re-search-forward org-drawer-regexp end t)
7560 (org-flag-drawer t))))))
7562 (defun org-flag-drawer (flag)
7563 (save-excursion
7564 (beginning-of-line 1)
7565 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7566 (let ((b (match-end 0)))
7567 (if (re-search-forward
7568 "^[ \t]*:END:"
7569 (save-excursion (outline-next-heading) (point)) t)
7570 (outline-flag-region b (point-at-eol) flag)
7571 (error ":END: line missing"))))))
7573 (defun org-cycle-hide-archived-subtrees (state)
7574 "Re-hide all archived subtrees after a visibility state change."
7575 (when (and (not org-cycle-open-archived-trees)
7576 (not (memq state '(overview folded))))
7577 (save-excursion
7578 (let* ((globalp (memq state '(contents all)))
7579 (beg (if globalp (point-min) (point)))
7580 (end (if globalp (point-max) (org-end-of-subtree t))))
7581 (org-hide-archived-subtrees beg end)
7582 (goto-char beg)
7583 (if (looking-at (concat ".*:" org-archive-tag ":"))
7584 (message (substitute-command-keys
7585 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7587 (defun org-force-cycle-archived ()
7588 "Cycle subtree even if it is archived."
7589 (interactive)
7590 (setq this-command 'org-cycle)
7591 (let ((org-cycle-open-archived-trees t))
7592 (call-interactively 'org-cycle)))
7594 (defun org-hide-archived-subtrees (beg end)
7595 "Re-hide all archived subtrees after a visibility state change."
7596 (save-excursion
7597 (let* ((re (concat ":" org-archive-tag ":")))
7598 (goto-char beg)
7599 (while (re-search-forward re end t)
7600 (and (org-on-heading-p) (hide-subtree))
7601 (org-end-of-subtree t)))))
7603 (defun org-toggle-tag (tag &optional onoff)
7604 "Toggle the tag TAG for the current line.
7605 If ONOFF is `on' or `off', don't toggle but set to this state."
7606 (unless (org-on-heading-p t) (error "Not on headling"))
7607 (let (res current)
7608 (save-excursion
7609 (beginning-of-line)
7610 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7611 (point-at-eol) t)
7612 (progn
7613 (setq current (match-string 1))
7614 (replace-match ""))
7615 (setq current ""))
7616 (setq current (nreverse (org-split-string current ":")))
7617 (cond
7618 ((eq onoff 'on)
7619 (setq res t)
7620 (or (member tag current) (push tag current)))
7621 ((eq onoff 'off)
7622 (or (not (member tag current)) (setq current (delete tag current))))
7623 (t (if (member tag current)
7624 (setq current (delete tag current))
7625 (setq res t)
7626 (push tag current))))
7627 (end-of-line 1)
7628 (if current
7629 (progn
7630 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7631 (org-set-tags nil t))
7632 (delete-horizontal-space))
7633 (run-hooks 'org-after-tags-change-hook))
7634 res))
7636 (defun org-toggle-archive-tag (&optional arg)
7637 "Toggle the archive tag for the current headline.
7638 With prefix ARG, check all children of current headline and offer tagging
7639 the children that do not contain any open TODO items."
7640 (interactive "P")
7641 (if arg
7642 (org-archive-all-done 'tag)
7643 (let (set)
7644 (save-excursion
7645 (org-back-to-heading t)
7646 (setq set (org-toggle-tag org-archive-tag))
7647 (when set (hide-subtree)))
7648 (and set (beginning-of-line 1))
7649 (message "Subtree %s" (if set "archived" "unarchived")))))
7652 ;;;; Tables
7654 ;;; The table editor
7656 ;; Watch out: Here we are talking about two different kind of tables.
7657 ;; Most of the code is for the tables created with the Org-mode table editor.
7658 ;; Sometimes, we talk about tables created and edited with the table.el
7659 ;; Emacs package. We call the former org-type tables, and the latter
7660 ;; table.el-type tables.
7662 (defun org-before-change-function (beg end)
7663 "Every change indicates that a table might need an update."
7664 (setq org-table-may-need-update t))
7666 (defconst org-table-line-regexp "^[ \t]*|"
7667 "Detects an org-type table line.")
7668 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7669 "Detects an org-type table line.")
7670 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7671 "Detects a table line marked for automatic recalculation.")
7672 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7673 "Detects a table line marked for automatic recalculation.")
7674 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7675 "Detects a table line marked for automatic recalculation.")
7676 (defconst org-table-hline-regexp "^[ \t]*|-"
7677 "Detects an org-type table hline.")
7678 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7679 "Detects a table-type table hline.")
7680 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7681 "Detects an org-type or table-type table.")
7682 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7683 "Searching from within a table (any type) this finds the first line
7684 outside the table.")
7685 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7686 "Searching from within a table (any type) this finds the first line
7687 outside the table.")
7689 (defvar org-table-last-highlighted-reference nil)
7690 (defvar org-table-formula-history nil)
7692 (defvar org-table-column-names nil
7693 "Alist with column names, derived from the `!' line.")
7694 (defvar org-table-column-name-regexp nil
7695 "Regular expression matching the current column names.")
7696 (defvar org-table-local-parameters nil
7697 "Alist with parameter names, derived from the `$' line.")
7698 (defvar org-table-named-field-locations nil
7699 "Alist with locations of named fields.")
7701 (defvar org-table-current-line-types nil
7702 "Table row types, non-nil only for the duration of a comand.")
7703 (defvar org-table-current-begin-line nil
7704 "Table begin line, non-nil only for the duration of a comand.")
7705 (defvar org-table-current-begin-pos nil
7706 "Table begin position, non-nil only for the duration of a comand.")
7707 (defvar org-table-dlines nil
7708 "Vector of data line line numbers in the current table.")
7709 (defvar org-table-hlines nil
7710 "Vector of hline line numbers in the current table.")
7712 (defconst org-table-range-regexp
7713 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7714 ;; 1 2 3 4 5
7715 "Regular expression for matching ranges in formulas.")
7717 (defconst org-table-range-regexp2
7718 (concat
7719 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7720 "\\.\\."
7721 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
7722 "Match a range for reference display.")
7724 (defconst org-table-translate-regexp
7725 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
7726 "Match a reference that needs translation, for reference display.")
7728 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
7730 (defun org-table-create-with-table.el ()
7731 "Use the table.el package to insert a new table.
7732 If there is already a table at point, convert between Org-mode tables
7733 and table.el tables."
7734 (interactive)
7735 (require 'table)
7736 (cond
7737 ((org-at-table.el-p)
7738 (if (y-or-n-p "Convert table to Org-mode table? ")
7739 (org-table-convert)))
7740 ((org-at-table-p)
7741 (if (y-or-n-p "Convert table to table.el table? ")
7742 (org-table-convert)))
7743 (t (call-interactively 'table-insert))))
7745 (defun org-table-create-or-convert-from-region (arg)
7746 "Convert region to table, or create an empty table.
7747 If there is an active region, convert it to a table, using the function
7748 `org-table-convert-region'. See the documentation of that function
7749 to learn how the prefix argument is interpreted to determine the field
7750 separator.
7751 If there is no such region, create an empty table with `org-table-create'."
7752 (interactive "P")
7753 (if (org-region-active-p)
7754 (org-table-convert-region (region-beginning) (region-end) arg)
7755 (org-table-create arg)))
7757 (defun org-table-create (&optional size)
7758 "Query for a size and insert a table skeleton.
7759 SIZE is a string Columns x Rows like for example \"3x2\"."
7760 (interactive "P")
7761 (unless size
7762 (setq size (read-string
7763 (concat "Table size Columns x Rows [e.g. "
7764 org-table-default-size "]: ")
7765 "" nil org-table-default-size)))
7767 (let* ((pos (point))
7768 (indent (make-string (current-column) ?\ ))
7769 (split (org-split-string size " *x *"))
7770 (rows (string-to-number (nth 1 split)))
7771 (columns (string-to-number (car split)))
7772 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7773 "\n")))
7774 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7775 (point-at-bol) (point)))
7776 (beginning-of-line 1)
7777 (newline))
7778 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7779 (dotimes (i rows) (insert line))
7780 (goto-char pos)
7781 (if (> rows 1)
7782 ;; Insert a hline after the first row.
7783 (progn
7784 (end-of-line 1)
7785 (insert "\n|-")
7786 (goto-char pos)))
7787 (org-table-align)))
7789 (defun org-table-convert-region (beg0 end0 &optional separator)
7790 "Convert region to a table.
7791 The region goes from BEG0 to END0, but these borders will be moved
7792 slightly, to make sure a beginning of line in the first line is included.
7794 SEPARATOR specifies the field separator in the lines. It can have the
7795 following values:
7797 '(4) Use the comma as a field separator
7798 '(16) Use a TAB as field separator
7799 integer When a number, use that many spaces as field separator
7800 nil When nil, the command tries to be smart and figure out the
7801 separator in the following way:
7802 - when each line contains a TAB, assume TAB-separated material
7803 - when each line contains a comme, assume CSV material
7804 - else, assume one or more SPACE charcters as separator."
7805 (interactive "rP")
7806 (let* ((beg (min beg0 end0))
7807 (end (max beg0 end0))
7809 (goto-char beg)
7810 (beginning-of-line 1)
7811 (setq beg (move-marker (make-marker) (point)))
7812 (goto-char end)
7813 (if (bolp) (backward-char 1) (end-of-line 1))
7814 (setq end (move-marker (make-marker) (point)))
7815 ;; Get the right field separator
7816 (unless separator
7817 (goto-char beg)
7818 (setq separator
7819 (cond
7820 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
7821 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
7822 (t 1))))
7823 (setq re (cond
7824 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
7825 ((equal separator '(16)) "^\\|\t")
7826 ((integerp separator)
7827 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
7828 (t (error "This should not happen"))))
7829 (goto-char beg)
7830 (while (re-search-forward re end t)
7831 (replace-match "| " t t))
7832 (goto-char beg)
7833 (insert " ")
7834 (org-table-align)))
7836 (defun org-table-import (file arg)
7837 "Import FILE as a table.
7838 The file is assumed to be tab-separated. Such files can be produced by most
7839 spreadsheet and database applications. If no tabs (at least one per line)
7840 are found, lines will be split on whitespace into fields."
7841 (interactive "f\nP")
7842 (or (bolp) (newline))
7843 (let ((beg (point))
7844 (pm (point-max)))
7845 (insert-file-contents file)
7846 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7848 (defun org-table-export ()
7849 "Export table as a tab-separated file.
7850 Such a file can be imported into a spreadsheet program like Excel."
7851 (interactive)
7852 (let* ((beg (org-table-begin))
7853 (end (org-table-end))
7854 (table (buffer-substring beg end))
7855 (file (read-file-name "Export table to: "))
7856 buf)
7857 (unless (or (not (file-exists-p file))
7858 (y-or-n-p (format "Overwrite file %s? " file)))
7859 (error "Abort"))
7860 (with-current-buffer (find-file-noselect file)
7861 (setq buf (current-buffer))
7862 (erase-buffer)
7863 (fundamental-mode)
7864 (insert table)
7865 (goto-char (point-min))
7866 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7867 (replace-match "" t t)
7868 (end-of-line 1))
7869 (goto-char (point-min))
7870 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7871 (replace-match "" t t)
7872 (goto-char (min (1+ (point)) (point-max))))
7873 (goto-char (point-min))
7874 (while (re-search-forward "^-[-+]*$" nil t)
7875 (replace-match "")
7876 (if (looking-at "\n")
7877 (delete-char 1)))
7878 (goto-char (point-min))
7879 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7880 (replace-match "\t" t t))
7881 (save-buffer))
7882 (kill-buffer buf)))
7884 (defvar org-table-aligned-begin-marker (make-marker)
7885 "Marker at the beginning of the table last aligned.
7886 Used to check if cursor still is in that table, to minimize realignment.")
7887 (defvar org-table-aligned-end-marker (make-marker)
7888 "Marker at the end of the table last aligned.
7889 Used to check if cursor still is in that table, to minimize realignment.")
7890 (defvar org-table-last-alignment nil
7891 "List of flags for flushright alignment, from the last re-alignment.
7892 This is being used to correctly align a single field after TAB or RET.")
7893 (defvar org-table-last-column-widths nil
7894 "List of max width of fields in each column.
7895 This is being used to correctly align a single field after TAB or RET.")
7896 (defvar org-table-overlay-coordinates nil
7897 "Overlay coordinates after each align of a table.")
7898 (make-variable-buffer-local 'org-table-overlay-coordinates)
7900 (defvar org-last-recalc-line nil)
7901 (defconst org-narrow-column-arrow "=>"
7902 "Used as display property in narrowed table columns.")
7904 (defun org-table-align ()
7905 "Align the table at point by aligning all vertical bars."
7906 (interactive)
7907 (let* (
7908 ;; Limits of table
7909 (beg (org-table-begin))
7910 (end (org-table-end))
7911 ;; Current cursor position
7912 (linepos (org-current-line))
7913 (colpos (org-table-current-column))
7914 (winstart (window-start))
7915 (winstartline (org-current-line (min winstart (1- (point-max)))))
7916 lines (new "") lengths l typenums ty fields maxfields i
7917 column
7918 (indent "") cnt frac
7919 rfmt hfmt
7920 (spaces '(1 . 1))
7921 (sp1 (car spaces))
7922 (sp2 (cdr spaces))
7923 (rfmt1 (concat
7924 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7925 (hfmt1 (concat
7926 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7927 emptystrings links dates emph narrow fmax f1 len c e)
7928 (untabify beg end)
7929 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7930 ;; Check if we have links or dates
7931 (goto-char beg)
7932 (setq links (re-search-forward org-bracket-link-regexp end t))
7933 (goto-char beg)
7934 (setq emph (and org-hide-emphasis-markers
7935 (re-search-forward org-emph-re end t)))
7936 (goto-char beg)
7937 (setq dates (and org-display-custom-times
7938 (re-search-forward org-ts-regexp-both end t)))
7939 ;; Make sure the link properties are right
7940 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7941 ;; Make sure the date properties are right
7942 (when dates (goto-char beg) (while (org-activate-dates end)))
7943 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
7945 ;; Check if we are narrowing any columns
7946 (goto-char beg)
7947 (setq narrow (and org-format-transports-properties-p
7948 (re-search-forward "<[0-9]+>" end t)))
7949 ;; Get the rows
7950 (setq lines (org-split-string
7951 (buffer-substring beg end) "\n"))
7952 ;; Store the indentation of the first line
7953 (if (string-match "^ *" (car lines))
7954 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7955 ;; Mark the hlines by setting the corresponding element to nil
7956 ;; At the same time, we remove trailing space.
7957 (setq lines (mapcar (lambda (l)
7958 (if (string-match "^ *|-" l)
7960 (if (string-match "[ \t]+$" l)
7961 (substring l 0 (match-beginning 0))
7962 l)))
7963 lines))
7964 ;; Get the data fields by splitting the lines.
7965 (setq fields (mapcar
7966 (lambda (l)
7967 (org-split-string l " *| *"))
7968 (delq nil (copy-sequence lines))))
7969 ;; How many fields in the longest line?
7970 (condition-case nil
7971 (setq maxfields (apply 'max (mapcar 'length fields)))
7972 (error
7973 (kill-region beg end)
7974 (org-table-create org-table-default-size)
7975 (error "Empty table - created default table")))
7976 ;; A list of empty strings to fill any short rows on output
7977 (setq emptystrings (make-list maxfields ""))
7978 ;; Check for special formatting.
7979 (setq i -1)
7980 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7981 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7982 ;; Check if there is an explicit width specified
7983 (when narrow
7984 (setq c column fmax nil)
7985 (while c
7986 (setq e (pop c))
7987 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7988 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7989 ;; Find fields that are wider than fmax, and shorten them
7990 (when fmax
7991 (loop for xx in column do
7992 (when (and (stringp xx)
7993 (> (org-string-width xx) fmax))
7994 (org-add-props xx nil
7995 'help-echo
7996 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7997 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7998 (unless (> f1 1)
7999 (error "Cannot narrow field starting with wide link \"%s\""
8000 (match-string 0 xx)))
8001 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8002 (add-text-properties (- f1 2) f1
8003 (list 'display org-narrow-column-arrow)
8004 xx)))))
8005 ;; Get the maximum width for each column
8006 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8007 ;; Get the fraction of numbers, to decide about alignment of the column
8008 (setq cnt 0 frac 0.0)
8009 (loop for x in column do
8010 (if (equal x "")
8012 (setq frac ( / (+ (* frac cnt)
8013 (if (string-match org-table-number-regexp x) 1 0))
8014 (setq cnt (1+ cnt))))))
8015 (push (>= frac org-table-number-fraction) typenums))
8016 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8018 ;; Store the alignment of this table, for later editing of single fields
8019 (setq org-table-last-alignment typenums
8020 org-table-last-column-widths lengths)
8022 ;; With invisible characters, `format' does not get the field width right
8023 ;; So we need to make these fields wide by hand.
8024 (when (or links emph)
8025 (loop for i from 0 upto (1- maxfields) do
8026 (setq len (nth i lengths))
8027 (loop for j from 0 upto (1- (length fields)) do
8028 (setq c (nthcdr i (car (nthcdr j fields))))
8029 (if (and (stringp (car c))
8030 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8031 ; (string-match org-bracket-link-regexp (car c))
8032 (< (org-string-width (car c)) len))
8033 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8035 ;; Compute the formats needed for output of the table
8036 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8037 (while (setq l (pop lengths))
8038 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8039 (setq rfmt (concat rfmt (format rfmt1 ty l))
8040 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8041 (setq rfmt (concat rfmt "\n")
8042 hfmt (concat (substring hfmt 0 -1) "|\n"))
8044 (setq new (mapconcat
8045 (lambda (l)
8046 (if l (apply 'format rfmt
8047 (append (pop fields) emptystrings))
8048 hfmt))
8049 lines ""))
8050 ;; Replace the old one
8051 (delete-region beg end)
8052 (move-marker end nil)
8053 (move-marker org-table-aligned-begin-marker (point))
8054 (insert new)
8055 (move-marker org-table-aligned-end-marker (point))
8056 (when (and orgtbl-mode (not (org-mode-p)))
8057 (goto-char org-table-aligned-begin-marker)
8058 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8059 ;; Try to move to the old location
8060 (goto-line winstartline)
8061 (setq winstart (point-at-bol))
8062 (goto-line linepos)
8063 (set-window-start (selected-window) winstart 'noforce)
8064 (org-table-goto-column colpos)
8065 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8066 (setq org-table-may-need-update nil)
8069 (defun org-string-width (s)
8070 "Compute width of string, ignoring invisible characters.
8071 This ignores character with invisibility property `org-link', and also
8072 characters with property `org-cwidth', because these will become invisible
8073 upon the next fontification round."
8074 (let (b l)
8075 (when (or (eq t buffer-invisibility-spec)
8076 (assq 'org-link buffer-invisibility-spec))
8077 (while (setq b (text-property-any 0 (length s)
8078 'invisible 'org-link s))
8079 (setq s (concat (substring s 0 b)
8080 (substring s (or (next-single-property-change
8081 b 'invisible s) (length s)))))))
8082 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8083 (setq s (concat (substring s 0 b)
8084 (substring s (or (next-single-property-change
8085 b 'org-cwidth s) (length s))))))
8086 (setq l (string-width s) b -1)
8087 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8088 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8091 (defun org-table-begin (&optional table-type)
8092 "Find the beginning of the table and return its position.
8093 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8094 (save-excursion
8095 (if (not (re-search-backward
8096 (if table-type org-table-any-border-regexp
8097 org-table-border-regexp)
8098 nil t))
8099 (progn (goto-char (point-min)) (point))
8100 (goto-char (match-beginning 0))
8101 (beginning-of-line 2)
8102 (point))))
8104 (defun org-table-end (&optional table-type)
8105 "Find the end of the table and return its position.
8106 With argument TABLE-TYPE, go to the end of a table.el-type table."
8107 (save-excursion
8108 (if (not (re-search-forward
8109 (if table-type org-table-any-border-regexp
8110 org-table-border-regexp)
8111 nil t))
8112 (goto-char (point-max))
8113 (goto-char (match-beginning 0)))
8114 (point-marker)))
8116 (defun org-table-justify-field-maybe (&optional new)
8117 "Justify the current field, text to left, number to right.
8118 Optional argument NEW may specify text to replace the current field content."
8119 (cond
8120 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8121 ((org-at-table-hline-p))
8122 ((and (not new)
8123 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8124 (current-buffer)))
8125 (< (point) org-table-aligned-begin-marker)
8126 (>= (point) org-table-aligned-end-marker)))
8127 ;; This is not the same table, force a full re-align
8128 (setq org-table-may-need-update t))
8129 (t ;; realign the current field, based on previous full realign
8130 (let* ((pos (point)) s
8131 (col (org-table-current-column))
8132 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8133 l f n o e)
8134 (when (> col 0)
8135 (skip-chars-backward "^|\n")
8136 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8137 (progn
8138 (setq s (match-string 1)
8139 o (match-string 0)
8140 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8141 e (not (= (match-beginning 2) (match-end 2))))
8142 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8143 l (if e "|" (setq org-table-may-need-update t) ""))
8144 n (format f s))
8145 (if new
8146 (if (<= (length new) l) ;; FIXME: length -> str-width?
8147 (setq n (format f new))
8148 (setq n (concat new "|") org-table-may-need-update t)))
8149 (or (equal n o)
8150 (let (org-table-may-need-update)
8151 (replace-match n t t))))
8152 (setq org-table-may-need-update t))
8153 (goto-char pos))))))
8155 (defun org-table-next-field ()
8156 "Go to the next field in the current table, creating new lines as needed.
8157 Before doing so, re-align the table if necessary."
8158 (interactive)
8159 (org-table-maybe-eval-formula)
8160 (org-table-maybe-recalculate-line)
8161 (if (and org-table-automatic-realign
8162 org-table-may-need-update)
8163 (org-table-align))
8164 (let ((end (org-table-end)))
8165 (if (org-at-table-hline-p)
8166 (end-of-line 1))
8167 (condition-case nil
8168 (progn
8169 (re-search-forward "|" end)
8170 (if (looking-at "[ \t]*$")
8171 (re-search-forward "|" end))
8172 (if (and (looking-at "-")
8173 org-table-tab-jumps-over-hlines
8174 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8175 (goto-char (match-beginning 1)))
8176 (if (looking-at "-")
8177 (progn
8178 (beginning-of-line 0)
8179 (org-table-insert-row 'below))
8180 (if (looking-at " ") (forward-char 1))))
8181 (error
8182 (org-table-insert-row 'below)))))
8184 (defun org-table-previous-field ()
8185 "Go to the previous field in the table.
8186 Before doing so, re-align the table if necessary."
8187 (interactive)
8188 (org-table-justify-field-maybe)
8189 (org-table-maybe-recalculate-line)
8190 (if (and org-table-automatic-realign
8191 org-table-may-need-update)
8192 (org-table-align))
8193 (if (org-at-table-hline-p)
8194 (end-of-line 1))
8195 (re-search-backward "|" (org-table-begin))
8196 (re-search-backward "|" (org-table-begin))
8197 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8198 (re-search-backward "|" (org-table-begin)))
8199 (if (looking-at "| ?")
8200 (goto-char (match-end 0))))
8202 (defun org-table-next-row ()
8203 "Go to the next row (same column) in the current table.
8204 Before doing so, re-align the table if necessary."
8205 (interactive)
8206 (org-table-maybe-eval-formula)
8207 (org-table-maybe-recalculate-line)
8208 (if (or (looking-at "[ \t]*$")
8209 (save-excursion (skip-chars-backward " \t") (bolp)))
8210 (newline)
8211 (if (and org-table-automatic-realign
8212 org-table-may-need-update)
8213 (org-table-align))
8214 (let ((col (org-table-current-column)))
8215 (beginning-of-line 2)
8216 (if (or (not (org-at-table-p))
8217 (org-at-table-hline-p))
8218 (progn
8219 (beginning-of-line 0)
8220 (org-table-insert-row 'below)))
8221 (org-table-goto-column col)
8222 (skip-chars-backward "^|\n\r")
8223 (if (looking-at " ") (forward-char 1)))))
8225 (defun org-table-copy-down (n)
8226 "Copy a field down in the current column.
8227 If the field at the cursor is empty, copy into it the content of the nearest
8228 non-empty field above. With argument N, use the Nth non-empty field.
8229 If the current field is not empty, it is copied down to the next row, and
8230 the cursor is moved with it. Therefore, repeating this command causes the
8231 column to be filled row-by-row.
8232 If the variable `org-table-copy-increment' is non-nil and the field is an
8233 integer or a timestamp, it will be incremented while copying. In the case of
8234 a timestamp, if the cursor is on the year, change the year. If it is on the
8235 month or the day, change that. Point will stay on the current date field
8236 in order to easily repeat the interval."
8237 (interactive "p")
8238 (let* ((colpos (org-table-current-column))
8239 (col (current-column))
8240 (field (org-table-get-field))
8241 (non-empty (string-match "[^ \t]" field))
8242 (beg (org-table-begin))
8243 txt)
8244 (org-table-check-inside-data-field)
8245 (if non-empty
8246 (progn
8247 (setq txt (org-trim field))
8248 (org-table-next-row)
8249 (org-table-blank-field))
8250 (save-excursion
8251 (setq txt
8252 (catch 'exit
8253 (while (progn (beginning-of-line 1)
8254 (re-search-backward org-table-dataline-regexp
8255 beg t))
8256 (org-table-goto-column colpos t)
8257 (if (and (looking-at
8258 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8259 (= (setq n (1- n)) 0))
8260 (throw 'exit (match-string 1))))))))
8261 (if txt
8262 (progn
8263 (if (and org-table-copy-increment
8264 (string-match "^[0-9]+$" txt))
8265 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8266 (insert txt)
8267 (move-to-column col)
8268 (if (and org-table-copy-increment (org-at-timestamp-p t))
8269 (org-timestamp-up 1)
8270 (org-table-maybe-recalculate-line))
8271 (org-table-align)
8272 (move-to-column col))
8273 (error "No non-empty field found"))))
8275 (defun org-table-check-inside-data-field ()
8276 "Is point inside a table data field?
8277 I.e. not on a hline or before the first or after the last column?
8278 This actually throws an error, so it aborts the current command."
8279 (if (or (not (org-at-table-p))
8280 (= (org-table-current-column) 0)
8281 (org-at-table-hline-p)
8282 (looking-at "[ \t]*$"))
8283 (error "Not in table data field")))
8285 (defvar org-table-clip nil
8286 "Clipboard for table regions.")
8288 (defun org-table-blank-field ()
8289 "Blank the current table field or active region."
8290 (interactive)
8291 (org-table-check-inside-data-field)
8292 (if (and (interactive-p) (org-region-active-p))
8293 (let (org-table-clip)
8294 (org-table-cut-region (region-beginning) (region-end)))
8295 (skip-chars-backward "^|")
8296 (backward-char 1)
8297 (if (looking-at "|[^|\n]+")
8298 (let* ((pos (match-beginning 0))
8299 (match (match-string 0))
8300 (len (org-string-width match)))
8301 (replace-match (concat "|" (make-string (1- len) ?\ )))
8302 (goto-char (+ 2 pos))
8303 (substring match 1)))))
8305 (defun org-table-get-field (&optional n replace)
8306 "Return the value of the field in column N of current row.
8307 N defaults to current field.
8308 If REPLACE is a string, replace field with this value. The return value
8309 is always the old value."
8310 (and n (org-table-goto-column n))
8311 (skip-chars-backward "^|\n")
8312 (backward-char 1)
8313 (if (looking-at "|[^|\r\n]*")
8314 (let* ((pos (match-beginning 0))
8315 (val (buffer-substring (1+ pos) (match-end 0))))
8316 (if replace
8317 (replace-match (concat "|" replace) t t))
8318 (goto-char (min (point-at-eol) (+ 2 pos)))
8319 val)
8320 (forward-char 1) ""))
8322 (defun org-table-field-info (arg)
8323 "Show info about the current field, and highlight any reference at point."
8324 (interactive "P")
8325 (org-table-get-specials)
8326 (save-excursion
8327 (let* ((pos (point))
8328 (col (org-table-current-column))
8329 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8330 (name (car (rassoc (list (org-current-line) col)
8331 org-table-named-field-locations)))
8332 (eql (org-table-get-stored-formulas))
8333 (dline (org-table-current-dline))
8334 (ref (format "@%d$%d" dline col))
8335 (ref1 (org-table-convert-refs-to-an ref))
8336 (fequation (or (assoc name eql) (assoc ref eql)))
8337 (cequation (assoc (int-to-string col) eql))
8338 (eqn (or fequation cequation)))
8339 (goto-char pos)
8340 (condition-case nil
8341 (org-table-show-reference 'local)
8342 (error nil))
8343 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8344 dline col
8345 (if cname (concat " or $" cname) "")
8346 dline col ref1
8347 (if name (concat " or $" name) "")
8348 ;; FIXME: formula info not correct if special table line
8349 (if eqn
8350 (concat ", formula: "
8351 (org-table-formula-to-user
8352 (concat
8353 (if (string-match "^[$@]"(car eqn)) "" "$")
8354 (car eqn) "=" (cdr eqn))))
8355 "")))))
8357 (defun org-table-current-column ()
8358 "Find out which column we are in.
8359 When called interactively, column is also displayed in echo area."
8360 (interactive)
8361 (if (interactive-p) (org-table-check-inside-data-field))
8362 (save-excursion
8363 (let ((cnt 0) (pos (point)))
8364 (beginning-of-line 1)
8365 (while (search-forward "|" pos t)
8366 (setq cnt (1+ cnt)))
8367 (if (interactive-p) (message "This is table column %d" cnt))
8368 cnt)))
8370 (defun org-table-current-dline ()
8371 "Find out what table data line we are in.
8372 Only datalins count for this."
8373 (interactive)
8374 (if (interactive-p) (org-table-check-inside-data-field))
8375 (save-excursion
8376 (let ((cnt 0) (pos (point)))
8377 (goto-char (org-table-begin))
8378 (while (<= (point) pos)
8379 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8380 (beginning-of-line 2))
8381 (if (interactive-p) (message "This is table line %d" cnt))
8382 cnt)))
8384 (defun org-table-goto-column (n &optional on-delim force)
8385 "Move the cursor to the Nth column in the current table line.
8386 With optional argument ON-DELIM, stop with point before the left delimiter
8387 of the field.
8388 If there are less than N fields, just go to after the last delimiter.
8389 However, when FORCE is non-nil, create new columns if necessary."
8390 (interactive "p")
8391 (let ((pos (point-at-eol)))
8392 (beginning-of-line 1)
8393 (when (> n 0)
8394 (while (and (> (setq n (1- n)) -1)
8395 (or (search-forward "|" pos t)
8396 (and force
8397 (progn (end-of-line 1)
8398 (skip-chars-backward "^|")
8399 (insert " | "))))))
8400 ; (backward-char 2) t)))))
8401 (when (and force (not (looking-at ".*|")))
8402 (save-excursion (end-of-line 1) (insert " | ")))
8403 (if on-delim
8404 (backward-char 1)
8405 (if (looking-at " ") (forward-char 1))))))
8407 (defun org-at-table-p (&optional table-type)
8408 "Return t if the cursor is inside an org-type table.
8409 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8410 (if org-enable-table-editor
8411 (save-excursion
8412 (beginning-of-line 1)
8413 (looking-at (if table-type org-table-any-line-regexp
8414 org-table-line-regexp)))
8415 nil))
8417 (defun org-at-table.el-p ()
8418 "Return t if and only if we are at a table.el table."
8419 (and (org-at-table-p 'any)
8420 (save-excursion
8421 (goto-char (org-table-begin 'any))
8422 (looking-at org-table1-hline-regexp))))
8424 (defun org-table-recognize-table.el ()
8425 "If there is a table.el table nearby, recognize it and move into it."
8426 (if org-table-tab-recognizes-table.el
8427 (if (org-at-table.el-p)
8428 (progn
8429 (beginning-of-line 1)
8430 (if (looking-at org-table-dataline-regexp)
8432 (if (looking-at org-table1-hline-regexp)
8433 (progn
8434 (beginning-of-line 2)
8435 (if (looking-at org-table-any-border-regexp)
8436 (beginning-of-line -1)))))
8437 (if (re-search-forward "|" (org-table-end t) t)
8438 (progn
8439 (require 'table)
8440 (if (table--at-cell-p (point))
8442 (message "recognizing table.el table...")
8443 (table-recognize-table)
8444 (message "recognizing table.el table...done")))
8445 (error "This should not happen..."))
8447 nil)
8448 nil))
8450 (defun org-at-table-hline-p ()
8451 "Return t if the cursor is inside a hline in a table."
8452 (if org-enable-table-editor
8453 (save-excursion
8454 (beginning-of-line 1)
8455 (looking-at org-table-hline-regexp))
8456 nil))
8458 (defun org-table-insert-column ()
8459 "Insert a new column into the table."
8460 (interactive)
8461 (if (not (org-at-table-p))
8462 (error "Not at a table"))
8463 (org-table-find-dataline)
8464 (let* ((col (max 1 (org-table-current-column)))
8465 (beg (org-table-begin))
8466 (end (org-table-end))
8467 ;; Current cursor position
8468 (linepos (org-current-line))
8469 (colpos col))
8470 (goto-char beg)
8471 (while (< (point) end)
8472 (if (org-at-table-hline-p)
8474 (org-table-goto-column col t)
8475 (insert "| "))
8476 (beginning-of-line 2))
8477 (move-marker end nil)
8478 (goto-line linepos)
8479 (org-table-goto-column colpos)
8480 (org-table-align)
8481 (org-table-fix-formulas "$" nil (1- col) 1)))
8483 (defun org-table-find-dataline ()
8484 "Find a dataline in the current table, which is needed for column commands."
8485 (if (and (org-at-table-p)
8486 (not (org-at-table-hline-p)))
8488 (let ((col (current-column))
8489 (end (org-table-end)))
8490 (move-to-column col)
8491 (while (and (< (point) end)
8492 (or (not (= (current-column) col))
8493 (org-at-table-hline-p)))
8494 (beginning-of-line 2)
8495 (move-to-column col))
8496 (if (and (org-at-table-p)
8497 (not (org-at-table-hline-p)))
8499 (error
8500 "Please position cursor in a data line for column operations")))))
8502 (defun org-table-delete-column ()
8503 "Delete a column from the table."
8504 (interactive)
8505 (if (not (org-at-table-p))
8506 (error "Not at a table"))
8507 (org-table-find-dataline)
8508 (org-table-check-inside-data-field)
8509 (let* ((col (org-table-current-column))
8510 (beg (org-table-begin))
8511 (end (org-table-end))
8512 ;; Current cursor position
8513 (linepos (org-current-line))
8514 (colpos col))
8515 (goto-char beg)
8516 (while (< (point) end)
8517 (if (org-at-table-hline-p)
8519 (org-table-goto-column col t)
8520 (and (looking-at "|[^|\n]+|")
8521 (replace-match "|")))
8522 (beginning-of-line 2))
8523 (move-marker end nil)
8524 (goto-line linepos)
8525 (org-table-goto-column colpos)
8526 (org-table-align)
8527 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8528 col -1 col)))
8530 (defun org-table-move-column-right ()
8531 "Move column to the right."
8532 (interactive)
8533 (org-table-move-column nil))
8534 (defun org-table-move-column-left ()
8535 "Move column to the left."
8536 (interactive)
8537 (org-table-move-column 'left))
8539 (defun org-table-move-column (&optional left)
8540 "Move the current column to the right. With arg LEFT, move to the left."
8541 (interactive "P")
8542 (if (not (org-at-table-p))
8543 (error "Not at a table"))
8544 (org-table-find-dataline)
8545 (org-table-check-inside-data-field)
8546 (let* ((col (org-table-current-column))
8547 (col1 (if left (1- col) col))
8548 (beg (org-table-begin))
8549 (end (org-table-end))
8550 ;; Current cursor position
8551 (linepos (org-current-line))
8552 (colpos (if left (1- col) (1+ col))))
8553 (if (and left (= col 1))
8554 (error "Cannot move column further left"))
8555 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8556 (error "Cannot move column further right"))
8557 (goto-char beg)
8558 (while (< (point) end)
8559 (if (org-at-table-hline-p)
8561 (org-table-goto-column col1 t)
8562 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8563 (replace-match "|\\2|\\1|")))
8564 (beginning-of-line 2))
8565 (move-marker end nil)
8566 (goto-line linepos)
8567 (org-table-goto-column colpos)
8568 (org-table-align)
8569 (org-table-fix-formulas
8570 "$" (list (cons (number-to-string col) (number-to-string colpos))
8571 (cons (number-to-string colpos) (number-to-string col))))))
8573 (defun org-table-move-row-down ()
8574 "Move table row down."
8575 (interactive)
8576 (org-table-move-row nil))
8577 (defun org-table-move-row-up ()
8578 "Move table row up."
8579 (interactive)
8580 (org-table-move-row 'up))
8582 (defun org-table-move-row (&optional up)
8583 "Move the current table line down. With arg UP, move it up."
8584 (interactive "P")
8585 (let* ((col (current-column))
8586 (pos (point))
8587 (hline1p (save-excursion (beginning-of-line 1)
8588 (looking-at org-table-hline-regexp)))
8589 (dline1 (org-table-current-dline))
8590 (dline2 (+ dline1 (if up -1 1)))
8591 (tonew (if up 0 2))
8592 txt hline2p)
8593 (beginning-of-line tonew)
8594 (unless (org-at-table-p)
8595 (goto-char pos)
8596 (error "Cannot move row further"))
8597 (setq hline2p (looking-at org-table-hline-regexp))
8598 (goto-char pos)
8599 (beginning-of-line 1)
8600 (setq pos (point))
8601 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8602 (delete-region (point) (1+ (point-at-eol)))
8603 (beginning-of-line tonew)
8604 (insert txt)
8605 (beginning-of-line 0)
8606 (move-to-column col)
8607 (unless (or hline1p hline2p)
8608 (org-table-fix-formulas
8609 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8610 (cons (number-to-string dline2) (number-to-string dline1)))))))
8612 (defun org-table-insert-row (&optional arg)
8613 "Insert a new row above the current line into the table.
8614 With prefix ARG, insert below the current line."
8615 (interactive "P")
8616 (if (not (org-at-table-p))
8617 (error "Not at a table"))
8618 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8619 (new (org-table-clean-line line)))
8620 ;; Fix the first field if necessary
8621 (if (string-match "^[ \t]*| *[#$] *|" line)
8622 (setq new (replace-match (match-string 0 line) t t new)))
8623 (beginning-of-line (if arg 2 1))
8624 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8625 (beginning-of-line 0)
8626 (re-search-forward "| ?" (point-at-eol) t)
8627 (and (or org-table-may-need-update org-table-overlay-coordinates)
8628 (org-table-align))
8629 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8631 (defun org-table-insert-hline (&optional above)
8632 "Insert a horizontal-line below the current line into the table.
8633 With prefix ABOVE, insert above the current line."
8634 (interactive "P")
8635 (if (not (org-at-table-p))
8636 (error "Not at a table"))
8637 (let ((line (org-table-clean-line
8638 (buffer-substring (point-at-bol) (point-at-eol))))
8639 (col (current-column)))
8640 (while (string-match "|\\( +\\)|" line)
8641 (setq line (replace-match
8642 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8643 ?-) "|") t t line)))
8644 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8645 (beginning-of-line (if above 1 2))
8646 (insert line "\n")
8647 (beginning-of-line (if above 1 -1))
8648 (move-to-column col)
8649 (and org-table-overlay-coordinates (org-table-align))))
8651 (defun org-table-hline-and-move (&optional same-column)
8652 "Insert a hline and move to the row below that line."
8653 (interactive "P")
8654 (let ((col (org-table-current-column)))
8655 (org-table-maybe-eval-formula)
8656 (org-table-maybe-recalculate-line)
8657 (org-table-insert-hline)
8658 (end-of-line 2)
8659 (if (looking-at "\n[ \t]*|-")
8660 (progn (insert "\n|") (org-table-align))
8661 (org-table-next-field))
8662 (if same-column (org-table-goto-column col))))
8664 (defun org-table-clean-line (s)
8665 "Convert a table line S into a string with only \"|\" and space.
8666 In particular, this does handle wide and invisible characters."
8667 (if (string-match "^[ \t]*|-" s)
8668 ;; It's a hline, just map the characters
8669 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8670 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8671 (setq s (replace-match
8672 (concat "|" (make-string (org-string-width (match-string 1 s))
8673 ?\ ) "|")
8674 t t s)))
8677 (defun org-table-kill-row ()
8678 "Delete the current row or horizontal line from the table."
8679 (interactive)
8680 (if (not (org-at-table-p))
8681 (error "Not at a table"))
8682 (let ((col (current-column))
8683 (dline (org-table-current-dline)))
8684 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8685 (if (not (org-at-table-p)) (beginning-of-line 0))
8686 (move-to-column col)
8687 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
8688 dline -1 dline)))
8690 (defun org-table-sort-lines (with-case &optional sorting-type)
8691 "Sort table lines according to the column at point.
8693 The position of point indicates the column to be used for
8694 sorting, and the range of lines is the range between the nearest
8695 horizontal separator lines, or the entire table of no such lines
8696 exist. If point is before the first column, you will be prompted
8697 for the sorting column. If there is an active region, the mark
8698 specifies the first line and the sorting column, while point
8699 should be in the last line to be included into the sorting.
8701 The command then prompts for the sorting type which can be
8702 alphabetically, numerically, or by time (as given in a time stamp
8703 in the field). Sorting in reverse order is also possible.
8705 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
8707 If SORTING-TYPE is specified when this function is called from a Lisp
8708 program, no prompting will take place. SORTING-TYPE must be a character,
8709 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8710 should be done in reverse order."
8711 (interactive "P")
8712 (let* ((thisline (org-current-line))
8713 (thiscol (org-table-current-column))
8714 beg end bcol ecol tend tbeg column lns pos)
8715 (when (equal thiscol 0)
8716 (if (interactive-p)
8717 (setq thiscol
8718 (string-to-number
8719 (read-string "Use column N for sorting: ")))
8720 (setq thiscol 1))
8721 (org-table-goto-column thiscol))
8722 (org-table-check-inside-data-field)
8723 (if (org-region-active-p)
8724 (progn
8725 (setq beg (region-beginning) end (region-end))
8726 (goto-char beg)
8727 (setq column (org-table-current-column)
8728 beg (point-at-bol))
8729 (goto-char end)
8730 (setq end (point-at-bol 2)))
8731 (setq column (org-table-current-column)
8732 pos (point)
8733 tbeg (org-table-begin)
8734 tend (org-table-end))
8735 (if (re-search-backward org-table-hline-regexp tbeg t)
8736 (setq beg (point-at-bol 2))
8737 (goto-char tbeg)
8738 (setq beg (point-at-bol 1)))
8739 (goto-char pos)
8740 (if (re-search-forward org-table-hline-regexp tend t)
8741 (setq end (point-at-bol 1))
8742 (goto-char tend)
8743 (setq end (point-at-bol))))
8744 (setq beg (move-marker (make-marker) beg)
8745 end (move-marker (make-marker) end))
8746 (untabify beg end)
8747 (goto-char beg)
8748 (org-table-goto-column column)
8749 (skip-chars-backward "^|")
8750 (setq bcol (current-column))
8751 (org-table-goto-column (1+ column))
8752 (skip-chars-backward "^|")
8753 (setq ecol (1- (current-column)))
8754 (org-table-goto-column column)
8755 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8756 (org-split-string (buffer-substring beg end) "\n")))
8757 (setq lns (org-do-sort lns "Table" with-case sorting-type))
8758 (delete-region beg end)
8759 (move-marker beg nil)
8760 (move-marker end nil)
8761 (insert (mapconcat 'cdr lns "\n") "\n")
8762 (goto-line thisline)
8763 (org-table-goto-column thiscol)
8764 (message "%d lines sorted, based on column %d" (length lns) column)))
8766 (defun org-table-cut-region (beg end)
8767 "Copy region in table to the clipboard and blank all relevant fields."
8768 (interactive "r")
8769 (org-table-copy-region beg end 'cut))
8771 (defun org-table-copy-region (beg end &optional cut)
8772 "Copy rectangular region in table to clipboard.
8773 A special clipboard is used which can only be accessed
8774 with `org-table-paste-rectangle'."
8775 (interactive "rP")
8776 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8777 region cols
8778 (rpl (if cut " " nil)))
8779 (goto-char beg)
8780 (org-table-check-inside-data-field)
8781 (setq l01 (org-current-line)
8782 c01 (org-table-current-column))
8783 (goto-char end)
8784 (org-table-check-inside-data-field)
8785 (setq l02 (org-current-line)
8786 c02 (org-table-current-column))
8787 (setq l1 (min l01 l02) l2 (max l01 l02)
8788 c1 (min c01 c02) c2 (max c01 c02))
8789 (catch 'exit
8790 (while t
8791 (catch 'nextline
8792 (if (> l1 l2) (throw 'exit t))
8793 (goto-line l1)
8794 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8795 (setq cols nil ic1 c1 ic2 c2)
8796 (while (< ic1 (1+ ic2))
8797 (push (org-table-get-field ic1 rpl) cols)
8798 (setq ic1 (1+ ic1)))
8799 (push (nreverse cols) region)
8800 (setq l1 (1+ l1)))))
8801 (setq org-table-clip (nreverse region))
8802 (if cut (org-table-align))
8803 org-table-clip))
8805 (defun org-table-paste-rectangle ()
8806 "Paste a rectangular region into a table.
8807 The upper right corner ends up in the current field. All involved fields
8808 will be overwritten. If the rectangle does not fit into the present table,
8809 the table is enlarged as needed. The process ignores horizontal separator
8810 lines."
8811 (interactive)
8812 (unless (and org-table-clip (listp org-table-clip))
8813 (error "First cut/copy a region to paste!"))
8814 (org-table-check-inside-data-field)
8815 (let* ((clip org-table-clip)
8816 (line (org-current-line))
8817 (col (org-table-current-column))
8818 (org-enable-table-editor t)
8819 (org-table-automatic-realign nil)
8820 c cols field)
8821 (while (setq cols (pop clip))
8822 (while (org-at-table-hline-p) (beginning-of-line 2))
8823 (if (not (org-at-table-p))
8824 (progn (end-of-line 0) (org-table-next-field)))
8825 (setq c col)
8826 (while (setq field (pop cols))
8827 (org-table-goto-column c nil 'force)
8828 (org-table-get-field nil field)
8829 (setq c (1+ c)))
8830 (beginning-of-line 2))
8831 (goto-line line)
8832 (org-table-goto-column col)
8833 (org-table-align)))
8835 (defun org-table-convert ()
8836 "Convert from `org-mode' table to table.el and back.
8837 Obviously, this only works within limits. When an Org-mode table is
8838 converted to table.el, all horizontal separator lines get lost, because
8839 table.el uses these as cell boundaries and has no notion of horizontal lines.
8840 A table.el table can be converted to an Org-mode table only if it does not
8841 do row or column spanning. Multiline cells will become multiple cells.
8842 Beware, Org-mode does not test if the table can be successfully converted - it
8843 blindly applies a recipe that works for simple tables."
8844 (interactive)
8845 (require 'table)
8846 (if (org-at-table.el-p)
8847 ;; convert to Org-mode table
8848 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8849 (end (move-marker (make-marker) (org-table-end t))))
8850 (table-unrecognize-region beg end)
8851 (goto-char beg)
8852 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8853 (replace-match ""))
8854 (goto-char beg))
8855 (if (org-at-table-p)
8856 ;; convert to table.el table
8857 (let ((beg (move-marker (make-marker) (org-table-begin)))
8858 (end (move-marker (make-marker) (org-table-end))))
8859 ;; first, get rid of all horizontal lines
8860 (goto-char beg)
8861 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8862 (replace-match ""))
8863 ;; insert a hline before first
8864 (goto-char beg)
8865 (org-table-insert-hline 'above)
8866 (beginning-of-line -1)
8867 ;; insert a hline after each line
8868 (while (progn (beginning-of-line 3) (< (point) end))
8869 (org-table-insert-hline))
8870 (goto-char beg)
8871 (setq end (move-marker end (org-table-end)))
8872 ;; replace "+" at beginning and ending of hlines
8873 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8874 (replace-match "\\1+-"))
8875 (goto-char beg)
8876 (while (re-search-forward "-|[ \t]*$" end t)
8877 (replace-match "-+"))
8878 (goto-char beg)))))
8880 (defun org-table-wrap-region (arg)
8881 "Wrap several fields in a column like a paragraph.
8882 This is useful if you'd like to spread the contents of a field over several
8883 lines, in order to keep the table compact.
8885 If there is an active region, and both point and mark are in the same column,
8886 the text in the column is wrapped to minimum width for the given number of
8887 lines. Generally, this makes the table more compact. A prefix ARG may be
8888 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8889 formats the selected text to two lines. If the region was longer than two
8890 lines, the remaining lines remain empty. A negative prefix argument reduces
8891 the current number of lines by that amount. The wrapped text is pasted back
8892 into the table. If you formatted it to more lines than it was before, fields
8893 further down in the table get overwritten - so you might need to make space in
8894 the table first.
8896 If there is no region, the current field is split at the cursor position and
8897 the text fragment to the right of the cursor is prepended to the field one
8898 line down.
8900 If there is no region, but you specify a prefix ARG, the current field gets
8901 blank, and the content is appended to the field above."
8902 (interactive "P")
8903 (org-table-check-inside-data-field)
8904 (if (org-region-active-p)
8905 ;; There is a region: fill as a paragraph
8906 (let* ((beg (region-beginning))
8907 (cline (save-excursion (goto-char beg) (org-current-line)))
8908 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8909 nlines)
8910 (org-table-cut-region (region-beginning) (region-end))
8911 (if (> (length (car org-table-clip)) 1)
8912 (error "Region must be limited to single column"))
8913 (setq nlines (if arg
8914 (if (< arg 1)
8915 (+ (length org-table-clip) arg)
8916 arg)
8917 (length org-table-clip)))
8918 (setq org-table-clip
8919 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8920 nil nlines)))
8921 (goto-line cline)
8922 (org-table-goto-column ccol)
8923 (org-table-paste-rectangle))
8924 ;; No region, split the current field at point
8925 (if arg
8926 ;; combine with field above
8927 (let ((s (org-table-blank-field))
8928 (col (org-table-current-column)))
8929 (beginning-of-line 0)
8930 (while (org-at-table-hline-p) (beginning-of-line 0))
8931 (org-table-goto-column col)
8932 (skip-chars-forward "^|")
8933 (skip-chars-backward " ")
8934 (insert " " (org-trim s))
8935 (org-table-align))
8936 ;; split field
8937 (when (looking-at "\\([^|]+\\)+|")
8938 (let ((s (match-string 1)))
8939 (replace-match " |")
8940 (goto-char (match-beginning 0))
8941 (org-table-next-row)
8942 (insert (org-trim s) " ")
8943 (org-table-align))))))
8945 (defvar org-field-marker nil)
8947 (defun org-table-edit-field (arg)
8948 "Edit table field in a different window.
8949 This is mainly useful for fields that contain hidden parts.
8950 When called with a \\[universal-argument] prefix, just make the full field visible so that
8951 it can be edited in place."
8952 (interactive "P")
8953 (if arg
8954 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8955 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8956 (remove-text-properties b e '(org-cwidth t invisible t
8957 display t intangible t))
8958 (if (and (boundp 'font-lock-mode) font-lock-mode)
8959 (font-lock-fontify-block)))
8960 (let ((pos (move-marker (make-marker) (point)))
8961 (field (org-table-get-field))
8962 (cw (current-window-configuration))
8964 (org-switch-to-buffer-other-window "*Org tmp*")
8965 (erase-buffer)
8966 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
8967 (let ((org-inhibit-startup t)) (org-mode))
8968 (goto-char (setq p (point-max)))
8969 (insert (org-trim field))
8970 (remove-text-properties p (point-max)
8971 '(invisible t org-cwidth t display t
8972 intangible t))
8973 (goto-char p)
8974 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
8975 (org-set-local 'org-window-configuration cw)
8976 (org-set-local 'org-field-marker pos)
8977 (message "Edit and finish with C-c C-c"))))
8979 (defun org-table-finish-edit-field ()
8980 "Finish editing a table data field.
8981 Remove all newline characters, insert the result into the table, realign
8982 the table and kill the editing buffer."
8983 (let ((pos org-field-marker)
8984 (cw org-window-configuration)
8985 (cb (current-buffer))
8986 text)
8987 (goto-char (point-min))
8988 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8989 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8990 (replace-match " "))
8991 (setq text (org-trim (buffer-string)))
8992 (set-window-configuration cw)
8993 (kill-buffer cb)
8994 (select-window (get-buffer-window (marker-buffer pos)))
8995 (goto-char pos)
8996 (move-marker pos nil)
8997 (org-table-check-inside-data-field)
8998 (org-table-get-field nil text)
8999 (org-table-align)
9000 (message "New field value inserted")))
9002 (defun org-trim (s)
9003 "Remove whitespace at beginning and end of string."
9004 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9005 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9008 (defun org-wrap (string &optional width lines)
9009 "Wrap string to either a number of lines, or a width in characters.
9010 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9011 that costs. If there is a word longer than WIDTH, the text is actually
9012 wrapped to the length of that word.
9013 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9014 many lines, whatever width that takes.
9015 The return value is a list of lines, without newlines at the end."
9016 (let* ((words (org-split-string string "[ \t\n]+"))
9017 (maxword (apply 'max (mapcar 'org-string-width words)))
9018 w ll)
9019 (cond (width
9020 (org-do-wrap words (max maxword width)))
9021 (lines
9022 (setq w maxword)
9023 (setq ll (org-do-wrap words maxword))
9024 (if (<= (length ll) lines)
9026 (setq ll words)
9027 (while (> (length ll) lines)
9028 (setq w (1+ w))
9029 (setq ll (org-do-wrap words w)))
9030 ll))
9031 (t (error "Cannot wrap this")))))
9034 (defun org-do-wrap (words width)
9035 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9036 (let (lines line)
9037 (while words
9038 (setq line (pop words))
9039 (while (and words (< (+ (length line) (length (car words))) width))
9040 (setq line (concat line " " (pop words))))
9041 (setq lines (push line lines)))
9042 (nreverse lines)))
9044 (defun org-split-string (string &optional separators)
9045 "Splits STRING into substrings at SEPARATORS.
9046 No empty strings are returned if there are matches at the beginning
9047 and end of string."
9048 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9049 (start 0)
9050 notfirst
9051 (list nil))
9052 (while (and (string-match rexp string
9053 (if (and notfirst
9054 (= start (match-beginning 0))
9055 (< start (length string)))
9056 (1+ start) start))
9057 (< (match-beginning 0) (length string)))
9058 (setq notfirst t)
9059 (or (eq (match-beginning 0) 0)
9060 (and (eq (match-beginning 0) (match-end 0))
9061 (eq (match-beginning 0) start))
9062 (setq list
9063 (cons (substring string start (match-beginning 0))
9064 list)))
9065 (setq start (match-end 0)))
9066 (or (eq start (length string))
9067 (setq list
9068 (cons (substring string start)
9069 list)))
9070 (nreverse list)))
9072 (defun org-table-map-tables (function)
9073 "Apply FUNCTION to the start of all tables in the buffer."
9074 (save-excursion
9075 (save-restriction
9076 (widen)
9077 (goto-char (point-min))
9078 (while (re-search-forward org-table-any-line-regexp nil t)
9079 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9080 (beginning-of-line 1)
9081 (if (looking-at org-table-line-regexp)
9082 (save-excursion (funcall function)))
9083 (re-search-forward org-table-any-border-regexp nil 1))))
9084 (message "Mapping tables: done"))
9086 (defvar org-timecnt) ; dynamically scoped parameter
9088 (defun org-table-sum (&optional beg end nlast)
9089 "Sum numbers in region of current table column.
9090 The result will be displayed in the echo area, and will be available
9091 as kill to be inserted with \\[yank].
9093 If there is an active region, it is interpreted as a rectangle and all
9094 numbers in that rectangle will be summed. If there is no active
9095 region and point is located in a table column, sum all numbers in that
9096 column.
9098 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9099 numbers are assumed to be times as well (in decimal hours) and the
9100 numbers are added as such.
9102 If NLAST is a number, only the NLAST fields will actually be summed."
9103 (interactive)
9104 (save-excursion
9105 (let (col (org-timecnt 0) diff h m s org-table-clip)
9106 (cond
9107 ((and beg end)) ; beg and end given explicitly
9108 ((org-region-active-p)
9109 (setq beg (region-beginning) end (region-end)))
9111 (setq col (org-table-current-column))
9112 (goto-char (org-table-begin))
9113 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9114 (error "No table data"))
9115 (org-table-goto-column col)
9116 (setq beg (point))
9117 (goto-char (org-table-end))
9118 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9119 (error "No table data"))
9120 (org-table-goto-column col)
9121 (setq end (point))))
9122 (let* ((items (apply 'append (org-table-copy-region beg end)))
9123 (items1 (cond ((not nlast) items)
9124 ((>= nlast (length items)) items)
9125 (t (setq items (reverse items))
9126 (setcdr (nthcdr (1- nlast) items) nil)
9127 (nreverse items))))
9128 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9129 items1)))
9130 (res (apply '+ numbers))
9131 (sres (if (= org-timecnt 0)
9132 (format "%g" res)
9133 (setq diff (* 3600 res)
9134 h (floor (/ diff 3600)) diff (mod diff 3600)
9135 m (floor (/ diff 60)) diff (mod diff 60)
9136 s diff)
9137 (format "%d:%02d:%02d" h m s))))
9138 (kill-new sres)
9139 (if (interactive-p)
9140 (message "%s"
9141 (substitute-command-keys
9142 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9143 (length numbers) sres))))
9144 sres))))
9146 (defun org-table-get-number-for-summing (s)
9147 (let (n)
9148 (if (string-match "^ *|? *" s)
9149 (setq s (replace-match "" nil nil s)))
9150 (if (string-match " *|? *$" s)
9151 (setq s (replace-match "" nil nil s)))
9152 (setq n (string-to-number s))
9153 (cond
9154 ((and (string-match "0" s)
9155 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9156 ((string-match "\\`[ \t]+\\'" s) nil)
9157 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9158 (let ((h (string-to-number (or (match-string 1 s) "0")))
9159 (m (string-to-number (or (match-string 2 s) "0")))
9160 (s (string-to-number (or (match-string 4 s) "0"))))
9161 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9162 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9163 ((equal n 0) nil)
9164 (t n))))
9166 (defun org-table-current-field-formula (&optional key noerror)
9167 "Return the formula active for the current field.
9168 Assumes that specials are in place.
9169 If KEY is given, return the key to this formula.
9170 Otherwise return the formula preceeded with \"=\" or \":=\"."
9171 (let* ((name (car (rassoc (list (org-current-line)
9172 (org-table-current-column))
9173 org-table-named-field-locations)))
9174 (col (org-table-current-column))
9175 (scol (int-to-string col))
9176 (ref (format "@%d$%d" (org-table-current-dline) col))
9177 (stored-list (org-table-get-stored-formulas noerror))
9178 (ass (or (assoc name stored-list)
9179 (assoc ref stored-list)
9180 (assoc scol stored-list))))
9181 (if key
9182 (car ass)
9183 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9184 (cdr ass))))))
9186 (defun org-table-get-formula (&optional equation named)
9187 "Read a formula from the minibuffer, offer stored formula as default.
9188 When NAMED is non-nil, look for a named equation."
9189 (let* ((stored-list (org-table-get-stored-formulas))
9190 (name (car (rassoc (list (org-current-line)
9191 (org-table-current-column))
9192 org-table-named-field-locations)))
9193 (ref (format "@%d$%d" (org-table-current-dline)
9194 (org-table-current-column)))
9195 (refass (assoc ref stored-list))
9196 (scol (if named
9197 (if name name ref)
9198 (int-to-string (org-table-current-column))))
9199 (dummy (and (or name refass) (not named)
9200 (not (y-or-n-p "Replace field formula with column formula? " ))
9201 (error "Abort")))
9202 (name (or name ref))
9203 (org-table-may-need-update nil)
9204 (stored (cdr (assoc scol stored-list)))
9205 (eq (cond
9206 ((and stored equation (string-match "^ *=? *$" equation))
9207 stored)
9208 ((stringp equation)
9209 equation)
9210 (t (org-table-formula-from-user
9211 (read-string
9212 (org-table-formula-to-user
9213 (format "%s formula %s%s="
9214 (if named "Field" "Column")
9215 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9216 scol))
9217 (if stored (org-table-formula-to-user stored) "")
9218 'org-table-formula-history
9219 )))))
9220 mustsave)
9221 (when (not (string-match "\\S-" eq))
9222 ;; remove formula
9223 (setq stored-list (delq (assoc scol stored-list) stored-list))
9224 (org-table-store-formulas stored-list)
9225 (error "Formula removed"))
9226 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9227 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9228 (if (and name (not named))
9229 ;; We set the column equation, delete the named one.
9230 (setq stored-list (delq (assoc name stored-list) stored-list)
9231 mustsave t))
9232 (if stored
9233 (setcdr (assoc scol stored-list) eq)
9234 (setq stored-list (cons (cons scol eq) stored-list)))
9235 (if (or mustsave (not (equal stored eq)))
9236 (org-table-store-formulas stored-list))
9237 eq))
9239 (defun org-table-store-formulas (alist)
9240 "Store the list of formulas below the current table."
9241 (setq alist (sort alist 'org-table-formula-less-p))
9242 (save-excursion
9243 (goto-char (org-table-end))
9244 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9245 (progn
9246 ;; don't overwrite TBLFM, we might use text properties to store stuff
9247 (goto-char (match-beginning 2))
9248 (delete-region (match-beginning 2) (match-end 0)))
9249 (insert "#+TBLFM:"))
9250 (insert " "
9251 (mapconcat (lambda (x)
9252 (concat
9253 (if (equal (string-to-char (car x)) ?@) "" "$")
9254 (car x) "=" (cdr x)))
9255 alist "::")
9256 "\n")))
9258 (defsubst org-table-formula-make-cmp-string (a)
9259 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9260 (concat
9261 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9262 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9263 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9265 (defun org-table-formula-less-p (a b)
9266 "Compare two formulas for sorting."
9267 (let ((as (org-table-formula-make-cmp-string (car a)))
9268 (bs (org-table-formula-make-cmp-string (car b))))
9269 (and as bs (string< as bs))))
9271 (defun org-table-get-stored-formulas (&optional noerror)
9272 "Return an alist with the stored formulas directly after current table."
9273 (interactive)
9274 (let (scol eq eq-alist strings string seen)
9275 (save-excursion
9276 (goto-char (org-table-end))
9277 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9278 (setq strings (org-split-string (match-string 2) " *:: *"))
9279 (while (setq string (pop strings))
9280 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9281 (setq scol (if (match-end 2)
9282 (match-string 2 string)
9283 (match-string 1 string))
9284 eq (match-string 3 string)
9285 eq-alist (cons (cons scol eq) eq-alist))
9286 (if (member scol seen)
9287 (if noerror
9288 (progn
9289 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9290 (ding)
9291 (sit-for 2))
9292 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9293 (push scol seen))))))
9294 (nreverse eq-alist)))
9296 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9297 "Modify the equations after the table structure has been edited.
9298 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9299 For all numbers larger than LIMIT, shift them by DELTA."
9300 (save-excursion
9301 (goto-char (org-table-end))
9302 (when (looking-at "#\\+TBLFM:")
9303 (let ((re (concat key "\\([0-9]+\\)"))
9304 (re2
9305 (when remove
9306 (if (equal key "$")
9307 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9308 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9309 s n a)
9310 (when remove
9311 (while (re-search-forward re2 (point-at-eol) t)
9312 (replace-match "")))
9313 (while (re-search-forward re (point-at-eol) t)
9314 (setq s (match-string 1) n (string-to-number s))
9315 (cond
9316 ((setq a (assoc s replace))
9317 (replace-match (concat key (cdr a)) t t))
9318 ((and limit (> n limit))
9319 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9321 (defun org-table-get-specials ()
9322 "Get the column names and local parameters for this table."
9323 (save-excursion
9324 (let ((beg (org-table-begin)) (end (org-table-end))
9325 names name fields fields1 field cnt
9326 c v l line col types dlines hlines)
9327 (setq org-table-column-names nil
9328 org-table-local-parameters nil
9329 org-table-named-field-locations nil
9330 org-table-current-begin-line nil
9331 org-table-current-begin-pos nil
9332 org-table-current-line-types nil)
9333 (goto-char beg)
9334 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9335 (setq names (org-split-string (match-string 1) " *| *")
9336 cnt 1)
9337 (while (setq name (pop names))
9338 (setq cnt (1+ cnt))
9339 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9340 (push (cons name (int-to-string cnt)) org-table-column-names))))
9341 (setq org-table-column-names (nreverse org-table-column-names))
9342 (setq org-table-column-name-regexp
9343 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9344 (goto-char beg)
9345 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9346 (setq fields (org-split-string (match-string 1) " *| *"))
9347 (while (setq field (pop fields))
9348 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9349 (push (cons (match-string 1 field) (match-string 2 field))
9350 org-table-local-parameters))))
9351 (goto-char beg)
9352 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9353 (setq c (match-string 1)
9354 fields (org-split-string (match-string 2) " *| *"))
9355 (save-excursion
9356 (beginning-of-line (if (equal c "_") 2 0))
9357 (setq line (org-current-line) col 1)
9358 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9359 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9360 (while (and fields1 (setq field (pop fields)))
9361 (setq v (pop fields1) col (1+ col))
9362 (when (and (stringp field) (stringp v)
9363 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9364 (push (cons field v) org-table-local-parameters)
9365 (push (list field line col) org-table-named-field-locations))))
9366 ;; Analyse the line types
9367 (goto-char beg)
9368 (setq org-table-current-begin-line (org-current-line)
9369 org-table-current-begin-pos (point)
9370 l org-table-current-begin-line)
9371 (while (looking-at "[ \t]*|\\(-\\)?")
9372 (push (if (match-end 1) 'hline 'dline) types)
9373 (if (match-end 1) (push l hlines) (push l dlines))
9374 (beginning-of-line 2)
9375 (setq l (1+ l)))
9376 (setq org-table-current-line-types (apply 'vector (nreverse types))
9377 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9378 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9380 (defun org-table-maybe-eval-formula ()
9381 "Check if the current field starts with \"=\" or \":=\".
9382 If yes, store the formula and apply it."
9383 ;; We already know we are in a table. Get field will only return a formula
9384 ;; when appropriate. It might return a separator line, but no problem.
9385 (when org-table-formula-evaluate-inline
9386 (let* ((field (org-trim (or (org-table-get-field) "")))
9387 named eq)
9388 (when (string-match "^:?=\\(.*\\)" field)
9389 (setq named (equal (string-to-char field) ?:)
9390 eq (match-string 1 field))
9391 (if (or (fboundp 'calc-eval)
9392 (equal (substring eq 0 (min 2 (length eq))) "'("))
9393 (org-table-eval-formula (if named '(4) nil)
9394 (org-table-formula-from-user eq))
9395 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9397 (defvar org-recalc-commands nil
9398 "List of commands triggering the recalculation of a line.
9399 Will be filled automatically during use.")
9401 (defvar org-recalc-marks
9402 '((" " . "Unmarked: no special line, no automatic recalculation")
9403 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9404 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9405 ("!" . "Column name definition line. Reference in formula as $name.")
9406 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9407 ("_" . "Names for values in row below this one.")
9408 ("^" . "Names for values in row above this one.")))
9410 (defun org-table-rotate-recalc-marks (&optional newchar)
9411 "Rotate the recalculation mark in the first column.
9412 If in any row, the first field is not consistent with a mark,
9413 insert a new column for the markers.
9414 When there is an active region, change all the lines in the region,
9415 after prompting for the marking character.
9416 After each change, a message will be displayed indicating the meaning
9417 of the new mark."
9418 (interactive)
9419 (unless (org-at-table-p) (error "Not at a table"))
9420 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9421 (beg (org-table-begin))
9422 (end (org-table-end))
9423 (l (org-current-line))
9424 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9425 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9426 (have-col
9427 (save-excursion
9428 (goto-char beg)
9429 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9430 (col (org-table-current-column))
9431 (forcenew (car (assoc newchar org-recalc-marks)))
9432 epos new)
9433 (when l1
9434 (message "Change region to what mark? Type # * ! $ or SPC: ")
9435 (setq newchar (char-to-string (read-char-exclusive))
9436 forcenew (car (assoc newchar org-recalc-marks))))
9437 (if (and newchar (not forcenew))
9438 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9439 newchar))
9440 (if l1 (goto-line l1))
9441 (save-excursion
9442 (beginning-of-line 1)
9443 (unless (looking-at org-table-dataline-regexp)
9444 (error "Not at a table data line")))
9445 (unless have-col
9446 (org-table-goto-column 1)
9447 (org-table-insert-column)
9448 (org-table-goto-column (1+ col)))
9449 (setq epos (point-at-eol))
9450 (save-excursion
9451 (beginning-of-line 1)
9452 (org-table-get-field
9453 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9454 (concat " "
9455 (setq new (or forcenew
9456 (cadr (member (match-string 1) marks))))
9457 " ")
9458 " # ")))
9459 (if (and l1 l2)
9460 (progn
9461 (goto-line l1)
9462 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9463 (and (looking-at org-table-dataline-regexp)
9464 (org-table-get-field 1 (concat " " new " "))))
9465 (goto-line l1)))
9466 (if (not (= epos (point-at-eol))) (org-table-align))
9467 (goto-line l)
9468 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9470 (defun org-table-maybe-recalculate-line ()
9471 "Recompute the current line if marked for it, and if we haven't just done it."
9472 (interactive)
9473 (and org-table-allow-automatic-line-recalculation
9474 (not (and (memq last-command org-recalc-commands)
9475 (equal org-last-recalc-line (org-current-line))))
9476 (save-excursion (beginning-of-line 1)
9477 (looking-at org-table-auto-recalculate-regexp))
9478 (org-table-recalculate) t))
9480 (defvar org-table-formula-debug nil
9481 "Non-nil means, debug table formulas.
9482 When nil, simply write \"#ERROR\" in corrupted fields.")
9483 (make-variable-buffer-local 'org-table-formula-debug)
9485 (defvar modes)
9486 (defsubst org-set-calc-mode (var &optional value)
9487 (if (stringp var)
9488 (setq var (assoc var '(("D" calc-angle-mode deg)
9489 ("R" calc-angle-mode rad)
9490 ("F" calc-prefer-frac t)
9491 ("S" calc-symbolic-mode t)))
9492 value (nth 2 var) var (nth 1 var)))
9493 (if (memq var modes)
9494 (setcar (cdr (memq var modes)) value)
9495 (cons var (cons value modes)))
9496 modes)
9498 (defun org-table-eval-formula (&optional arg equation
9499 suppress-align suppress-const
9500 suppress-store suppress-analysis)
9501 "Replace the table field value at the cursor by the result of a calculation.
9503 This function makes use of Dave Gillespie's Calc package, in my view the
9504 most exciting program ever written for GNU Emacs. So you need to have Calc
9505 installed in order to use this function.
9507 In a table, this command replaces the value in the current field with the
9508 result of a formula. It also installs the formula as the \"current\" column
9509 formula, by storing it in a special line below the table. When called
9510 with a `C-u' prefix, the current field must ba a named field, and the
9511 formula is installed as valid in only this specific field.
9513 When called with two `C-u' prefixes, insert the active equation
9514 for the field back into the current field, so that it can be
9515 edited there. This is useful in order to use \\[org-table-show-reference]
9516 to check the referenced fields.
9518 When called, the command first prompts for a formula, which is read in
9519 the minibuffer. Previously entered formulas are available through the
9520 history list, and the last used formula is offered as a default.
9521 These stored formulas are adapted correctly when moving, inserting, or
9522 deleting columns with the corresponding commands.
9524 The formula can be any algebraic expression understood by the Calc package.
9525 For details, see the Org-mode manual.
9527 This function can also be called from Lisp programs and offers
9528 additional arguments: EQUATION can be the formula to apply. If this
9529 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9530 used to speed-up recursive calls by by-passing unnecessary aligns.
9531 SUPPRESS-CONST suppresses the interpretation of constants in the
9532 formula, assuming that this has been done already outside the function.
9533 SUPPRESS-STORE means the formula should not be stored, either because
9534 it is already stored, or because it is a modified equation that should
9535 not overwrite the stored one."
9536 (interactive "P")
9537 (org-table-check-inside-data-field)
9538 (or suppress-analysis (org-table-get-specials))
9539 (if (equal arg '(16))
9540 (let ((eq (org-table-current-field-formula)))
9541 (or eq (error "No equation active for current field"))
9542 (org-table-get-field nil eq)
9543 (org-table-align)
9544 (setq org-table-may-need-update t))
9545 (let* (fields
9546 (ndown (if (integerp arg) arg 1))
9547 (org-table-automatic-realign nil)
9548 (case-fold-search nil)
9549 (down (> ndown 1))
9550 (formula (if (and equation suppress-store)
9551 equation
9552 (org-table-get-formula equation (equal arg '(4)))))
9553 (n0 (org-table-current-column))
9554 (modes (copy-sequence org-calc-default-modes))
9555 (numbers nil) ; was a variable, now fixed default
9556 (keep-empty nil)
9557 n form form0 bw fmt x ev orig c lispp literal)
9558 ;; Parse the format string. Since we have a lot of modes, this is
9559 ;; a lot of work. However, I think calc still uses most of the time.
9560 (if (string-match ";" formula)
9561 (let ((tmp (org-split-string formula ";")))
9562 (setq formula (car tmp)
9563 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9564 (nth 1 tmp)))
9565 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9566 (setq c (string-to-char (match-string 1 fmt))
9567 n (string-to-number (match-string 2 fmt)))
9568 (if (= c ?p)
9569 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9570 (setq modes (org-set-calc-mode
9571 'calc-float-format
9572 (list (cdr (assoc c '((?n . float) (?f . fix)
9573 (?s . sci) (?e . eng))))
9574 n))))
9575 (setq fmt (replace-match "" t t fmt)))
9576 (if (string-match "[NT]" fmt)
9577 (setq numbers (equal (match-string 0 fmt) "N")
9578 fmt (replace-match "" t t fmt)))
9579 (if (string-match "L" fmt)
9580 (setq literal t
9581 fmt (replace-match "" t t fmt)))
9582 (if (string-match "E" fmt)
9583 (setq keep-empty t
9584 fmt (replace-match "" t t fmt)))
9585 (while (string-match "[DRFS]" fmt)
9586 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9587 (setq fmt (replace-match "" t t fmt)))
9588 (unless (string-match "\\S-" fmt)
9589 (setq fmt nil))))
9590 (if (and (not suppress-const) org-table-formula-use-constants)
9591 (setq formula (org-table-formula-substitute-names formula)))
9592 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9593 (while (> ndown 0)
9594 (setq fields (org-split-string
9595 (org-no-properties
9596 (buffer-substring (point-at-bol) (point-at-eol)))
9597 " *| *"))
9598 (if (eq numbers t)
9599 (setq fields (mapcar
9600 (lambda (x) (number-to-string (string-to-number x)))
9601 fields)))
9602 (setq ndown (1- ndown))
9603 (setq form (copy-sequence formula)
9604 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9605 (if (and lispp literal) (setq lispp 'literal))
9606 ;; Check for old vertical references
9607 (setq form (org-rewrite-old-row-references form))
9608 ;; Insert complex ranges
9609 (while (string-match org-table-range-regexp form)
9610 (setq form
9611 (replace-match
9612 (save-match-data
9613 (org-table-make-reference
9614 (org-table-get-range (match-string 0 form) nil n0)
9615 keep-empty numbers lispp))
9616 t t form)))
9617 ;; Insert simple ranges
9618 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9619 (setq form
9620 (replace-match
9621 (save-match-data
9622 (org-table-make-reference
9623 (org-sublist
9624 fields (string-to-number (match-string 1 form))
9625 (string-to-number (match-string 2 form)))
9626 keep-empty numbers lispp))
9627 t t form)))
9628 (setq form0 form)
9629 ;; Insert the references to fields in same row
9630 (while (string-match "\\$\\([0-9]+\\)" form)
9631 (setq n (string-to-number (match-string 1 form))
9632 x (nth (1- (if (= n 0) n0 n)) fields))
9633 (unless x (error "Invalid field specifier \"%s\""
9634 (match-string 0 form)))
9635 (setq form (replace-match
9636 (save-match-data
9637 (org-table-make-reference x nil numbers lispp))
9638 t t form)))
9640 (if lispp
9641 (setq ev (condition-case nil
9642 (eval (eval (read form)))
9643 (error "#ERROR"))
9644 ev (if (numberp ev) (number-to-string ev) ev))
9645 (or (fboundp 'calc-eval)
9646 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9647 (setq ev (calc-eval (cons form modes)
9648 (if numbers 'num))))
9650 (when org-table-formula-debug
9651 (with-output-to-temp-buffer "*Substitution History*"
9652 (princ (format "Substitution history of formula
9653 Orig: %s
9654 $xyz-> %s
9655 @r$c-> %s
9656 $1-> %s\n" orig formula form0 form))
9657 (if (listp ev)
9658 (princ (format " %s^\nError: %s"
9659 (make-string (car ev) ?\-) (nth 1 ev)))
9660 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9661 ev (or fmt "NONE")
9662 (if fmt (format fmt (string-to-number ev)) ev)))))
9663 (setq bw (get-buffer-window "*Substitution History*"))
9664 (shrink-window-if-larger-than-buffer bw)
9665 (unless (and (interactive-p) (not ndown))
9666 (unless (let (inhibit-redisplay)
9667 (y-or-n-p "Debugging Formula. Continue to next? "))
9668 (org-table-align)
9669 (error "Abort"))
9670 (delete-window bw)
9671 (message "")))
9672 (if (listp ev) (setq fmt nil ev "#ERROR"))
9673 (org-table-justify-field-maybe
9674 (if fmt (format fmt (string-to-number ev)) ev))
9675 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9676 (call-interactively 'org-return)
9677 (setq ndown 0)))
9678 (and down (org-table-maybe-recalculate-line))
9679 (or suppress-align (and org-table-may-need-update
9680 (org-table-align))))))
9682 (defun org-table-put-field-property (prop value)
9683 (save-excursion
9684 (put-text-property (progn (skip-chars-backward "^|") (point))
9685 (progn (skip-chars-forward "^|") (point))
9686 prop value)))
9688 (defun org-table-get-range (desc &optional tbeg col highlight)
9689 "Get a calc vector from a column, accorting to descriptor DESC.
9690 Optional arguments TBEG and COL can give the beginning of the table and
9691 the current column, to avoid unnecessary parsing.
9692 HIGHLIGHT means, just highlight the range."
9693 (if (not (equal (string-to-char desc) ?@))
9694 (setq desc (concat "@" desc)))
9695 (save-excursion
9696 (or tbeg (setq tbeg (org-table-begin)))
9697 (or col (setq col (org-table-current-column)))
9698 (let ((thisline (org-current-line))
9699 beg end c1 c2 r1 r2 rangep tmp)
9700 (unless (string-match org-table-range-regexp desc)
9701 (error "Invalid table range specifier `%s'" desc))
9702 (setq rangep (match-end 3)
9703 r1 (and (match-end 1) (match-string 1 desc))
9704 r2 (and (match-end 4) (match-string 4 desc))
9705 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
9706 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
9708 (and c1 (setq c1 (+ (string-to-number c1)
9709 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9710 (and c2 (setq c2 (+ (string-to-number c2)
9711 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9712 (if (equal r1 "") (setq r1 nil))
9713 (if (equal r2 "") (setq r2 nil))
9714 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
9715 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
9716 ; (setq r2 (or r2 r1) c2 (or c2 c1))
9717 (if (not r1) (setq r1 thisline))
9718 (if (not r2) (setq r2 thisline))
9719 (if (not c1) (setq c1 col))
9720 (if (not c2) (setq c2 col))
9721 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
9722 ;; just one field
9723 (progn
9724 (goto-line r1)
9725 (while (not (looking-at org-table-dataline-regexp))
9726 (beginning-of-line 2))
9727 (prog1 (org-trim (org-table-get-field c1))
9728 (if highlight (org-table-highlight-rectangle (point) (point)))))
9729 ;; A range, return a vector
9730 ;; First sort the numbers to get a regular ractangle
9731 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
9732 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
9733 (goto-line r1)
9734 (while (not (looking-at org-table-dataline-regexp))
9735 (beginning-of-line 2))
9736 (org-table-goto-column c1)
9737 (setq beg (point))
9738 (goto-line r2)
9739 (while (not (looking-at org-table-dataline-regexp))
9740 (beginning-of-line 0))
9741 (org-table-goto-column c2)
9742 (setq end (point))
9743 (if highlight
9744 (org-table-highlight-rectangle
9745 beg (progn (skip-chars-forward "^|\n") (point))))
9746 ;; return string representation of calc vector
9747 (mapcar 'org-trim
9748 (apply 'append (org-table-copy-region beg end)))))))
9750 (defun org-table-get-descriptor-line (desc &optional cline bline table)
9751 "Analyze descriptor DESC and retrieve the corresponding line number.
9752 The cursor is currently in line CLINE, the table begins in line BLINE,
9753 and TABLE is a vector with line types."
9754 (if (string-match "^[0-9]+$" desc)
9755 (aref org-table-dlines (string-to-number desc))
9756 (setq cline (or cline (org-current-line))
9757 bline (or bline org-table-current-begin-line)
9758 table (or table org-table-current-line-types))
9759 (if (or
9760 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
9761 ;; 1 2 3 4 5 6
9762 (and (not (match-end 3)) (not (match-end 6)))
9763 (and (match-end 3) (match-end 6) (not (match-end 5))))
9764 (error "invalid row descriptor `%s'" desc))
9765 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
9766 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
9767 (odir (and (match-end 5) (match-string 5 desc)))
9768 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
9769 (i (- cline bline))
9770 (rel (and (match-end 6)
9771 (or (and (match-end 1) (not (match-end 3)))
9772 (match-end 5)))))
9773 (if (and hn (not hdir))
9774 (progn
9775 (setq i 0 hdir "+")
9776 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
9777 (if (and (not hn) on (not odir))
9778 (error "should never happen");;(aref org-table-dlines on)
9779 (if (and hn (> hn 0))
9780 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
9781 (if on
9782 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
9783 (+ bline i)))))
9785 (defun org-find-row-type (table i type backwards relative n)
9786 (let ((l (length table)))
9787 (while (> n 0)
9788 (while (and (setq i (+ i (if backwards -1 1)))
9789 (>= i 0) (< i l)
9790 (not (eq (aref table i) type))
9791 (if (and relative (eq (aref table i) 'hline))
9792 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
9793 t)))
9794 (setq n (1- n)))
9795 (if (or (< i 0) (>= i l))
9796 (error "Row descriptior leads outside table")
9797 i)))
9799 (defun org-rewrite-old-row-references (s)
9800 (if (string-match "&[-+0-9I]" s)
9801 (error "Formula contains old &row reference, please rewrite using @-syntax")
9804 (defun org-table-make-reference (elements keep-empty numbers lispp)
9805 "Convert list ELEMENTS to something appropriate to insert into formula.
9806 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
9807 NUMBERS indicates that everything should be converted to numbers.
9808 LISPP means to return something appropriate for a Lisp list."
9809 (if (stringp elements) ; just a single val
9810 (if lispp
9811 (if (eq lispp 'literal)
9812 elements
9813 (prin1-to-string (if numbers (string-to-number elements) elements)))
9814 (if (equal elements "") (setq elements "0"))
9815 (if numbers (number-to-string (string-to-number elements)) elements))
9816 (unless keep-empty
9817 (setq elements
9818 (delq nil
9819 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9820 elements))))
9821 (setq elements (or elements '("0")))
9822 (if lispp
9823 (mapconcat
9824 (lambda (x)
9825 (if (eq lispp 'literal)
9827 (prin1-to-string (if numbers (string-to-number x) x))))
9828 elements " ")
9829 (concat "[" (mapconcat
9830 (lambda (x)
9831 (if numbers (number-to-string (string-to-number x)) x))
9832 elements
9833 ",") "]"))))
9835 (defun org-table-recalculate (&optional all noalign)
9836 "Recalculate the current table line by applying all stored formulas.
9837 With prefix arg ALL, do this for all lines in the table."
9838 (interactive "P")
9839 (or (memq this-command org-recalc-commands)
9840 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9841 (unless (org-at-table-p) (error "Not at a table"))
9842 (if (equal all '(16))
9843 (org-table-iterate)
9844 (org-table-get-specials)
9845 (let* ((eqlist (sort (org-table-get-stored-formulas)
9846 (lambda (a b) (string< (car a) (car b)))))
9847 (inhibit-redisplay (not debug-on-error))
9848 (line-re org-table-dataline-regexp)
9849 (thisline (org-current-line))
9850 (thiscol (org-table-current-column))
9851 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9852 ;; Insert constants in all formulas
9853 (setq eqlist
9854 (mapcar (lambda (x)
9855 (setcdr x (org-table-formula-substitute-names (cdr x)))
9857 eqlist))
9858 ;; Split the equation list
9859 (while (setq eq (pop eqlist))
9860 (if (<= (string-to-char (car eq)) ?9)
9861 (push eq eqlnum)
9862 (push eq eqlname)))
9863 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9864 (if all
9865 (progn
9866 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9867 (goto-char (setq beg (org-table-begin)))
9868 (if (re-search-forward org-table-calculate-mark-regexp end t)
9869 ;; This is a table with marked lines, compute selected lines
9870 (setq line-re org-table-recalculate-regexp)
9871 ;; Move forward to the first non-header line
9872 (if (and (re-search-forward org-table-dataline-regexp end t)
9873 (re-search-forward org-table-hline-regexp end t)
9874 (re-search-forward org-table-dataline-regexp end t))
9875 (setq beg (match-beginning 0))
9876 nil))) ;; just leave beg where it is
9877 (setq beg (point-at-bol)
9878 end (move-marker (make-marker) (1+ (point-at-eol)))))
9879 (goto-char beg)
9880 (and all (message "Re-applying formulas to full table..."))
9882 ;; First find the named fields, and mark them untouchanble
9883 (remove-text-properties beg end '(org-untouchable t))
9884 (while (setq eq (pop eqlname))
9885 (setq name (car eq)
9886 a (assoc name org-table-named-field-locations))
9887 (and (not a)
9888 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9889 (setq a (list name
9890 (aref org-table-dlines
9891 (string-to-number (match-string 1 name)))
9892 (string-to-number (match-string 2 name)))))
9893 (when (and a (or all (equal (nth 1 a) thisline)))
9894 (message "Re-applying formula to field: %s" name)
9895 (goto-line (nth 1 a))
9896 (org-table-goto-column (nth 2 a))
9897 (push (append a (list (cdr eq))) eqlname1)
9898 (org-table-put-field-property :org-untouchable t)))
9900 ;; Now evauluate the column formulas, but skip fields covered by
9901 ;; field formulas
9902 (goto-char beg)
9903 (while (re-search-forward line-re end t)
9904 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9905 ;; Unprotected line, recalculate
9906 (and all (message "Re-applying formulas to full table...(line %d)"
9907 (setq cnt (1+ cnt))))
9908 (setq org-last-recalc-line (org-current-line))
9909 (setq eql eqlnum)
9910 (while (setq entry (pop eql))
9911 (goto-line org-last-recalc-line)
9912 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9913 (unless (get-text-property (point) :org-untouchable)
9914 (org-table-eval-formula nil (cdr entry)
9915 'noalign 'nocst 'nostore 'noanalysis)))))
9917 ;; Now evaluate the field formulas
9918 (while (setq eq (pop eqlname1))
9919 (message "Re-applying formula to field: %s" (car eq))
9920 (goto-line (nth 1 eq))
9921 (org-table-goto-column (nth 2 eq))
9922 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9923 'nostore 'noanalysis))
9925 (goto-line thisline)
9926 (org-table-goto-column thiscol)
9927 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9928 (or noalign (and org-table-may-need-update (org-table-align))
9929 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9931 ;; back to initial position
9932 (message "Re-applying formulas...done")
9933 (goto-line thisline)
9934 (org-table-goto-column thiscol)
9935 (or noalign (and org-table-may-need-update (org-table-align))
9936 (and all (message "Re-applying formulas...done"))))))
9938 (defun org-table-iterate (&optional arg)
9939 "Recalculate the table until it does not change anymore."
9940 (interactive "P")
9941 (let ((imax (if arg (prefix-numeric-value arg) 10))
9942 (i 0)
9943 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9944 thistbl)
9945 (catch 'exit
9946 (while (< i imax)
9947 (setq i (1+ i))
9948 (org-table-recalculate 'all)
9949 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9950 (if (not (string= lasttbl thistbl))
9951 (setq lasttbl thistbl)
9952 (if (> i 1)
9953 (message "Convergence after %d iterations" i)
9954 (message "Table was already stable"))
9955 (throw 'exit t)))
9956 (error "No convergence after %d iterations" i))))
9958 (defun org-table-formula-substitute-names (f)
9959 "Replace $const with values in string F."
9960 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
9961 ;; First, check for column names
9962 (while (setq start (string-match org-table-column-name-regexp f start))
9963 (setq start (1+ start))
9964 (setq a (assoc (match-string 1 f) org-table-column-names))
9965 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9966 ;; Parameters and constants
9967 (setq start 0)
9968 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
9969 (setq start (1+ start))
9970 (if (setq a (save-match-data
9971 (org-table-get-constant (match-string 1 f))))
9972 (setq f (replace-match
9973 (concat (if pp "(") a (if pp ")")) t t f))))
9974 (if org-table-formula-debug
9975 (put-text-property 0 (length f) :orig-formula f1 f))
9978 (defun org-table-get-constant (const)
9979 "Find the value for a parameter or constant in a formula.
9980 Parameters get priority."
9981 (or (cdr (assoc const org-table-local-parameters))
9982 (cdr (assoc const org-table-formula-constants-local))
9983 (cdr (assoc const org-table-formula-constants))
9984 (and (fboundp 'constants-get) (constants-get const))
9985 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9986 (org-entry-get nil (substring const 5) 'inherit))
9987 "#UNDEFINED_NAME"))
9989 (defvar org-table-fedit-map
9990 (let ((map (make-sparse-keymap)))
9991 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
9992 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
9993 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
9994 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
9995 (org-defkey map "\C-c?" 'org-table-show-reference)
9996 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
9997 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
9998 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
9999 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10000 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10001 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10002 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10003 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10004 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10005 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10006 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10007 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10008 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10009 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10010 map))
10012 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10013 '("Edit-Formulas"
10014 ["Finish and Install" org-table-fedit-finish t]
10015 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10016 ["Abort" org-table-fedit-abort t]
10017 "--"
10018 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10019 ["Complete Lisp Symbol" lisp-complete-symbol t]
10020 "--"
10021 "Shift Reference at Point"
10022 ["Up" org-table-fedit-ref-up t]
10023 ["Down" org-table-fedit-ref-down t]
10024 ["Left" org-table-fedit-ref-left t]
10025 ["Right" org-table-fedit-ref-right t]
10027 "Change Test Row for Column Formulas"
10028 ["Up" org-table-fedit-line-up t]
10029 ["Down" org-table-fedit-line-down t]
10030 "--"
10031 ["Scroll Table Window" org-table-fedit-scroll t]
10032 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10033 ["Show Table Grid" org-table-fedit-toggle-coordinates
10034 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10035 org-table-overlay-coordinates)]
10036 "--"
10037 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10038 :style toggle :selected org-table-buffer-is-an]))
10040 (defvar org-pos)
10042 (defun org-table-edit-formulas ()
10043 "Edit the formulas of the current table in a separate buffer."
10044 (interactive)
10045 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10046 (beginning-of-line 0))
10047 (unless (org-at-table-p) (error "Not at a table"))
10048 (org-table-get-specials)
10049 (let ((key (org-table-current-field-formula 'key 'noerror))
10050 (eql (sort (org-table-get-stored-formulas 'noerror)
10051 'org-table-formula-less-p))
10052 (pos (move-marker (make-marker) (point)))
10053 (startline 1)
10054 (wc (current-window-configuration))
10055 (titles '((column . "# Column Formulas\n")
10056 (field . "# Field Formulas\n")
10057 (named . "# Named Field Formulas\n")))
10058 entry s type title)
10059 (org-switch-to-buffer-other-window "*Edit Formulas*")
10060 (erase-buffer)
10061 ;; Keep global-font-lock-mode from turning on font-lock-mode
10062 (let ((font-lock-global-modes '(not fundamental-mode)))
10063 (fundamental-mode))
10064 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10065 (org-set-local 'org-pos pos)
10066 (org-set-local 'org-window-configuration wc)
10067 (use-local-map org-table-fedit-map)
10068 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10069 (easy-menu-add org-table-fedit-menu)
10070 (setq startline (org-current-line))
10071 (while (setq entry (pop eql))
10072 (setq type (cond
10073 ((equal (string-to-char (car entry)) ?@) 'field)
10074 ((string-match "^[0-9]" (car entry)) 'column)
10075 (t 'named)))
10076 (when (setq title (assq type titles))
10077 (or (bobp) (insert "\n"))
10078 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10079 (setq titles (delq title titles)))
10080 (if (equal key (car entry)) (setq startline (org-current-line)))
10081 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10082 (car entry) " = " (cdr entry) "\n"))
10083 (remove-text-properties 0 (length s) '(face nil) s)
10084 (insert s))
10085 (if (eq org-table-use-standard-references t)
10086 (org-table-fedit-toggle-ref-type))
10087 (goto-line startline)
10088 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10090 (defun org-table-fedit-post-command ()
10091 (when (not (memq this-command '(lisp-complete-symbol)))
10092 (let ((win (selected-window)))
10093 (save-excursion
10094 (condition-case nil
10095 (org-table-show-reference)
10096 (error nil))
10097 (select-window win)))))
10099 (defun org-table-formula-to-user (s)
10100 "Convert a formula from internal to user representation."
10101 (if (eq org-table-use-standard-references t)
10102 (org-table-convert-refs-to-an s)
10105 (defun org-table-formula-from-user (s)
10106 "Convert a formula from user to internal representation."
10107 (if org-table-use-standard-references
10108 (org-table-convert-refs-to-rc s)
10111 (defun org-table-convert-refs-to-rc (s)
10112 "Convert spreadsheet references from AB7 to @7$28.
10113 Works for single references, but also for entire formulas and even the
10114 full TBLFM line."
10115 (let ((start 0))
10116 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10117 (cond
10118 ((match-end 3)
10119 ;; format match, just advance
10120 (setq start (match-end 0)))
10121 ((and (> (match-beginning 0) 0)
10122 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10123 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10124 ;; 3.e5 or something like this.
10125 (setq start (match-end 0)))
10127 (setq start (match-beginning 0)
10128 s (replace-match
10129 (if (equal (match-string 2 s) "&")
10130 (format "$%d" (org-letters-to-number (match-string 1 s)))
10131 (format "@%d$%d"
10132 (string-to-number (match-string 2 s))
10133 (org-letters-to-number (match-string 1 s))))
10134 t t s)))))
10137 (defun org-table-convert-refs-to-an (s)
10138 "Convert spreadsheet references from to @7$28 to AB7.
10139 Works for single references, but also for entire formulas and even the
10140 full TBLFM line."
10141 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10142 (setq s (replace-match
10143 (format "%s%d"
10144 (org-number-to-letters
10145 (string-to-number (match-string 2 s)))
10146 (string-to-number (match-string 1 s)))
10147 t t s)))
10148 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10149 (setq s (replace-match (concat "\\1"
10150 (org-number-to-letters
10151 (string-to-number (match-string 2 s))) "&")
10152 t nil s)))
10155 (defun org-letters-to-number (s)
10156 "Convert a base 26 number represented by letters into an integer.
10157 For example: AB -> 28."
10158 (let ((n 0))
10159 (setq s (upcase s))
10160 (while (> (length s) 0)
10161 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10162 s (substring s 1)))
10165 (defun org-number-to-letters (n)
10166 "Convert an integer into a base 26 number represented by letters.
10167 For example: 28 -> AB."
10168 (let ((s ""))
10169 (while (> n 0)
10170 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10171 n (/ (1- n) 26)))
10174 (defun org-table-fedit-convert-buffer (function)
10175 "Convert all references in this buffer, using FUNTION."
10176 (let ((line (org-current-line)))
10177 (goto-char (point-min))
10178 (while (not (eobp))
10179 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10180 (delete-region (point) (point-at-eol))
10181 (or (eobp) (forward-char 1)))
10182 (goto-line line)))
10184 (defun org-table-fedit-toggle-ref-type ()
10185 "Convert all references in the buffer from B3 to @3$2 and back."
10186 (interactive)
10187 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10188 (org-table-fedit-convert-buffer
10189 (if org-table-buffer-is-an
10190 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10191 (message "Reference type switched to %s"
10192 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10194 (defun org-table-fedit-ref-up ()
10195 "Shift the reference at point one row/hline up."
10196 (interactive)
10197 (org-table-fedit-shift-reference 'up))
10198 (defun org-table-fedit-ref-down ()
10199 "Shift the reference at point one row/hline down."
10200 (interactive)
10201 (org-table-fedit-shift-reference 'down))
10202 (defun org-table-fedit-ref-left ()
10203 "Shift the reference at point one field to the left."
10204 (interactive)
10205 (org-table-fedit-shift-reference 'left))
10206 (defun org-table-fedit-ref-right ()
10207 "Shift the reference at point one field to the right."
10208 (interactive)
10209 (org-table-fedit-shift-reference 'right))
10211 (defun org-table-fedit-shift-reference (dir)
10212 (cond
10213 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10214 (if (memq dir '(left right))
10215 (org-rematch-and-replace 1 (eq dir 'left))
10216 (error "Cannot shift reference in this direction")))
10217 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10218 ;; A B3-like reference
10219 (if (memq dir '(up down))
10220 (org-rematch-and-replace 2 (eq dir 'up))
10221 (org-rematch-and-replace 1 (eq dir 'left))))
10222 ((org-at-regexp-p
10223 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10224 ;; An internal reference
10225 (if (memq dir '(up down))
10226 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10227 (org-rematch-and-replace 5 (eq dir 'left))))))
10229 (defun org-rematch-and-replace (n &optional decr hline)
10230 "Re-match the group N, and replace it with the shifted refrence."
10231 (or (match-end n) (error "Cannot shift reference in this direction"))
10232 (goto-char (match-beginning n))
10233 (and (looking-at (regexp-quote (match-string n)))
10234 (replace-match (org-shift-refpart (match-string 0) decr hline)
10235 t t)))
10237 (defun org-shift-refpart (ref &optional decr hline)
10238 "Shift a refrence part REF.
10239 If DECR is set, decrease the references row/column, else increase.
10240 If HLINE is set, this may be a hline reference, it certainly is not
10241 a translation reference."
10242 (save-match-data
10243 (let* ((sign (string-match "^[-+]" ref)) n)
10245 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10246 (cond
10247 ((and hline (string-match "^I+" ref))
10248 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10249 (setq n (+ n (if decr -1 1)))
10250 (if (= n 0) (setq n (+ n (if decr -1 1))))
10251 (if sign
10252 (setq sign (if (< n 0) "-" "+") n (abs n))
10253 (setq n (max 1 n)))
10254 (concat sign (make-string n ?I)))
10256 ((string-match "^[0-9]+" ref)
10257 (setq n (string-to-number (concat sign ref)))
10258 (setq n (+ n (if decr -1 1)))
10259 (if sign
10260 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10261 (number-to-string (max 1 n))))
10263 ((string-match "^[a-zA-Z]+" ref)
10264 (org-number-to-letters
10265 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10267 (t (error "Cannot shift reference"))))))
10269 (defun org-table-fedit-toggle-coordinates ()
10270 "Toggle the display of coordinates in the refrenced table."
10271 (interactive)
10272 (let ((pos (marker-position org-pos)))
10273 (with-current-buffer (marker-buffer org-pos)
10274 (save-excursion
10275 (goto-char pos)
10276 (org-table-toggle-coordinate-overlays)))))
10278 (defun org-table-fedit-finish (&optional arg)
10279 "Parse the buffer for formula definitions and install them.
10280 With prefix ARG, apply the new formulas to the table."
10281 (interactive "P")
10282 (org-table-remove-rectangle-highlight)
10283 (if org-table-use-standard-references
10284 (progn
10285 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10286 (setq org-table-buffer-is-an nil)))
10287 (let ((pos org-pos) eql var form)
10288 (goto-char (point-min))
10289 (while (re-search-forward
10290 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10291 nil t)
10292 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10293 form (match-string 3))
10294 (setq form (org-trim form))
10295 (when (not (equal form ""))
10296 (while (string-match "[ \t]*\n[ \t]*" form)
10297 (setq form (replace-match " " t t form)))
10298 (when (assoc var eql)
10299 (error "Double formulas for %s" var))
10300 (push (cons var form) eql)))
10301 (setq org-pos nil)
10302 (set-window-configuration org-window-configuration)
10303 (select-window (get-buffer-window (marker-buffer pos)))
10304 (goto-char pos)
10305 (unless (org-at-table-p)
10306 (error "Lost table position - cannot install formulae"))
10307 (org-table-store-formulas eql)
10308 (move-marker pos nil)
10309 (kill-buffer "*Edit Formulas*")
10310 (if arg
10311 (org-table-recalculate 'all)
10312 (message "New formulas installed - press C-u C-c C-c to apply."))))
10314 (defun org-table-fedit-abort ()
10315 "Abort editing formulas, without installing the changes."
10316 (interactive)
10317 (org-table-remove-rectangle-highlight)
10318 (let ((pos org-pos))
10319 (set-window-configuration org-window-configuration)
10320 (select-window (get-buffer-window (marker-buffer pos)))
10321 (goto-char pos)
10322 (move-marker pos nil)
10323 (message "Formula editing aborted without installing changes")))
10325 (defun org-table-fedit-lisp-indent ()
10326 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10327 (interactive)
10328 (let ((pos (point)) beg end ind)
10329 (beginning-of-line 1)
10330 (cond
10331 ((looking-at "[ \t]")
10332 (goto-char pos)
10333 (call-interactively 'lisp-indent-line))
10334 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10335 ((not (fboundp 'pp-buffer))
10336 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10337 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10338 (goto-char (- (match-end 0) 2))
10339 (setq beg (point))
10340 (setq ind (make-string (current-column) ?\ ))
10341 (condition-case nil (forward-sexp 1)
10342 (error
10343 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10344 (setq end (point))
10345 (save-restriction
10346 (narrow-to-region beg end)
10347 (if (eq last-command this-command)
10348 (progn
10349 (goto-char (point-min))
10350 (setq this-command nil)
10351 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10352 (replace-match " ")))
10353 (pp-buffer)
10354 (untabify (point-min) (point-max))
10355 (goto-char (1+ (point-min)))
10356 (while (re-search-forward "^." nil t)
10357 (beginning-of-line 1)
10358 (insert ind))
10359 (goto-char (point-max))
10360 (backward-delete-char 1)))
10361 (goto-char beg))
10362 (t nil))))
10364 (defvar org-show-positions nil)
10366 (defun org-table-show-reference (&optional local)
10367 "Show the location/value of the $ expression at point."
10368 (interactive)
10369 (org-table-remove-rectangle-highlight)
10370 (catch 'exit
10371 (let ((pos (if local (point) org-pos))
10372 (face2 'highlight)
10373 (org-inhibit-highlight-removal t)
10374 (win (selected-window))
10375 (org-show-positions nil)
10376 var name e what match dest)
10377 (if local (org-table-get-specials))
10378 (setq what (cond
10379 ((or (org-at-regexp-p org-table-range-regexp2)
10380 (org-at-regexp-p org-table-translate-regexp)
10381 (org-at-regexp-p org-table-range-regexp))
10382 (setq match
10383 (save-match-data
10384 (org-table-convert-refs-to-rc (match-string 0))))
10385 'range)
10386 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10387 ((org-at-regexp-p "\\$[0-9]+") 'column)
10388 ((not local) nil)
10389 (t (error "No reference at point")))
10390 match (and what (or match (match-string 0))))
10391 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10392 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10393 'secondary-selection))
10394 (org-add-hook 'before-change-functions
10395 'org-table-remove-rectangle-highlight)
10396 (if (eq what 'name) (setq var (substring match 1)))
10397 (when (eq what 'range)
10398 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10399 (setq match (org-table-formula-substitute-names match)))
10400 (unless local
10401 (save-excursion
10402 (end-of-line 1)
10403 (re-search-backward "^\\S-" nil t)
10404 (beginning-of-line 1)
10405 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10406 (setq dest
10407 (save-match-data
10408 (org-table-convert-refs-to-rc (match-string 1))))
10409 (org-table-add-rectangle-overlay
10410 (match-beginning 1) (match-end 1) face2))))
10411 (if (and (markerp pos) (marker-buffer pos))
10412 (if (get-buffer-window (marker-buffer pos))
10413 (select-window (get-buffer-window (marker-buffer pos)))
10414 (org-switch-to-buffer-other-window (get-buffer-window
10415 (marker-buffer pos)))))
10416 (goto-char pos)
10417 (org-table-force-dataline)
10418 (when dest
10419 (setq name (substring dest 1))
10420 (cond
10421 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10422 (setq e (assoc name org-table-named-field-locations))
10423 (goto-line (nth 1 e))
10424 (org-table-goto-column (nth 2 e)))
10425 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10426 (let ((l (string-to-number (match-string 1 dest)))
10427 (c (string-to-number (match-string 2 dest))))
10428 (goto-line (aref org-table-dlines l))
10429 (org-table-goto-column c)))
10430 (t (org-table-goto-column (string-to-number name))))
10431 (move-marker pos (point))
10432 (org-table-highlight-rectangle nil nil face2))
10433 (cond
10434 ((equal dest match))
10435 ((not match))
10436 ((eq what 'range)
10437 (condition-case nil
10438 (save-excursion
10439 (org-table-get-range match nil nil 'highlight))
10440 (error nil)))
10441 ((setq e (assoc var org-table-named-field-locations))
10442 (goto-line (nth 1 e))
10443 (org-table-goto-column (nth 2 e))
10444 (org-table-highlight-rectangle (point) (point))
10445 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10446 ((setq e (assoc var org-table-column-names))
10447 (org-table-goto-column (string-to-number (cdr e)))
10448 (org-table-highlight-rectangle (point) (point))
10449 (goto-char (org-table-begin))
10450 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10451 (org-table-end) t)
10452 (progn
10453 (goto-char (match-beginning 1))
10454 (org-table-highlight-rectangle)
10455 (message "Named column (column %s)" (cdr e)))
10456 (error "Column name not found")))
10457 ((eq what 'column)
10458 ;; column number
10459 (org-table-goto-column (string-to-number (substring match 1)))
10460 (org-table-highlight-rectangle (point) (point))
10461 (message "Column %s" (substring match 1)))
10462 ((setq e (assoc var org-table-local-parameters))
10463 (goto-char (org-table-begin))
10464 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10465 (progn
10466 (goto-char (match-beginning 1))
10467 (org-table-highlight-rectangle)
10468 (message "Local parameter."))
10469 (error "Parameter not found")))
10471 (cond
10472 ((not var) (error "No reference at point"))
10473 ((setq e (assoc var org-table-formula-constants-local))
10474 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10475 var (cdr e)))
10476 ((setq e (assoc var org-table-formula-constants))
10477 (message "Constant: $%s=%s in `org-table-formula-constants'."
10478 var (cdr e)))
10479 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10480 (message "Constant: $%s=%s, from `constants.el'%s."
10481 var e (format " (%s units)" constants-unit-system)))
10482 (t (error "Undefined name $%s" var)))))
10483 (goto-char pos)
10484 (when (and org-show-positions
10485 (not (memq this-command '(org-table-fedit-scroll
10486 org-table-fedit-scroll-down))))
10487 (push pos org-show-positions)
10488 (push org-table-current-begin-pos org-show-positions)
10489 (let ((min (apply 'min org-show-positions))
10490 (max (apply 'max org-show-positions)))
10491 (goto-char min) (recenter 0)
10492 (goto-char max)
10493 (or (pos-visible-in-window-p max) (recenter -1))))
10494 (select-window win))))
10496 (defun org-table-force-dataline ()
10497 "Make sure the cursor is in a dataline in a table."
10498 (unless (save-excursion
10499 (beginning-of-line 1)
10500 (looking-at org-table-dataline-regexp))
10501 (let* ((re org-table-dataline-regexp)
10502 (p1 (save-excursion (re-search-forward re nil 'move)))
10503 (p2 (save-excursion (re-search-backward re nil 'move))))
10504 (cond ((and p1 p2)
10505 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10506 p1 p2)))
10507 ((or p1 p2) (goto-char (or p1 p2)))
10508 (t (error "No table dataline around here"))))))
10510 (defun org-table-fedit-line-up ()
10511 "Move cursor one line up in the window showing the table."
10512 (interactive)
10513 (org-table-fedit-move 'previous-line))
10515 (defun org-table-fedit-line-down ()
10516 "Move cursor one line down in the window showing the table."
10517 (interactive)
10518 (org-table-fedit-move 'next-line))
10520 (defun org-table-fedit-move (command)
10521 "Move the cursor in the window shoinw the table.
10522 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10523 (let ((org-table-allow-automatic-line-recalculation nil)
10524 (pos org-pos) (win (selected-window)) p)
10525 (select-window (get-buffer-window (marker-buffer org-pos)))
10526 (setq p (point))
10527 (call-interactively command)
10528 (while (and (org-at-table-p)
10529 (org-at-table-hline-p))
10530 (call-interactively command))
10531 (or (org-at-table-p) (goto-char p))
10532 (move-marker pos (point))
10533 (select-window win)))
10535 (defun org-table-fedit-scroll (N)
10536 (interactive "p")
10537 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10538 (scroll-other-window N)))
10540 (defun org-table-fedit-scroll-down (N)
10541 (interactive "p")
10542 (org-table-fedit-scroll (- N)))
10544 (defvar org-table-rectangle-overlays nil)
10546 (defun org-table-add-rectangle-overlay (beg end &optional face)
10547 "Add a new overlay."
10548 (let ((ov (org-make-overlay beg end)))
10549 (org-overlay-put ov 'face (or face 'secondary-selection))
10550 (push ov org-table-rectangle-overlays)))
10552 (defun org-table-highlight-rectangle (&optional beg end face)
10553 "Highlight rectangular region in a table."
10554 (setq beg (or beg (point)) end (or end (point)))
10555 (let ((b (min beg end))
10556 (e (max beg end))
10557 l1 c1 l2 c2 tmp)
10558 (and (boundp 'org-show-positions)
10559 (setq org-show-positions (cons b (cons e org-show-positions))))
10560 (goto-char (min beg end))
10561 (setq l1 (org-current-line)
10562 c1 (org-table-current-column))
10563 (goto-char (max beg end))
10564 (setq l2 (org-current-line)
10565 c2 (org-table-current-column))
10566 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10567 (goto-line l1)
10568 (beginning-of-line 1)
10569 (loop for line from l1 to l2 do
10570 (when (looking-at org-table-dataline-regexp)
10571 (org-table-goto-column c1)
10572 (skip-chars-backward "^|\n") (setq beg (point))
10573 (org-table-goto-column c2)
10574 (skip-chars-forward "^|\n") (setq end (point))
10575 (org-table-add-rectangle-overlay beg end face))
10576 (beginning-of-line 2))
10577 (goto-char b))
10578 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10580 (defun org-table-remove-rectangle-highlight (&rest ignore)
10581 "Remove the rectangle overlays."
10582 (unless org-inhibit-highlight-removal
10583 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10584 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10585 (setq org-table-rectangle-overlays nil)))
10587 (defvar org-table-coordinate-overlays nil
10588 "Collects the cooordinate grid overlays, so that they can be removed.")
10589 (make-variable-buffer-local 'org-table-coordinate-overlays)
10591 (defun org-table-overlay-coordinates ()
10592 "Add overlays to the table at point, to show row/column coordinates."
10593 (interactive)
10594 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10595 (setq org-table-coordinate-overlays nil)
10596 (save-excursion
10597 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10598 (goto-char (org-table-begin))
10599 (while (org-at-table-p)
10600 (setq eol (point-at-eol))
10601 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10602 (push ov org-table-coordinate-overlays)
10603 (setq hline (looking-at org-table-hline-regexp))
10604 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10605 (format "%4d" (setq id (1+ id)))))
10606 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10607 (when hline
10608 (setq ic 0)
10609 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10610 (setq beg (1+ (match-beginning 0))
10611 ic (1+ ic)
10612 s1 (concat "$" (int-to-string ic))
10613 s2 (org-number-to-letters ic)
10614 str (if (eq org-table-use-standard-references t) s2 s1))
10615 (setq ov (org-make-overlay beg (+ beg (length str))))
10616 (push ov org-table-coordinate-overlays)
10617 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10618 (beginning-of-line 2)))))
10620 (defun org-table-toggle-coordinate-overlays ()
10621 "Toggle the display of Row/Column numbers in tables."
10622 (interactive)
10623 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10624 (message "Row/Column number display turned %s"
10625 (if org-table-overlay-coordinates "on" "off"))
10626 (if (and (org-at-table-p) org-table-overlay-coordinates)
10627 (org-table-align))
10628 (unless org-table-overlay-coordinates
10629 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10630 (setq org-table-coordinate-overlays nil)))
10632 (defun org-table-toggle-formula-debugger ()
10633 "Toggle the formula debugger in tables."
10634 (interactive)
10635 (setq org-table-formula-debug (not org-table-formula-debug))
10636 (message "Formula debugging has been turned %s"
10637 (if org-table-formula-debug "on" "off")))
10639 ;;; The orgtbl minor mode
10641 ;; Define a minor mode which can be used in other modes in order to
10642 ;; integrate the org-mode table editor.
10644 ;; This is really a hack, because the org-mode table editor uses several
10645 ;; keys which normally belong to the major mode, for example the TAB and
10646 ;; RET keys. Here is how it works: The minor mode defines all the keys
10647 ;; necessary to operate the table editor, but wraps the commands into a
10648 ;; function which tests if the cursor is currently inside a table. If that
10649 ;; is the case, the table editor command is executed. However, when any of
10650 ;; those keys is used outside a table, the function uses `key-binding' to
10651 ;; look up if the key has an associated command in another currently active
10652 ;; keymap (minor modes, major mode, global), and executes that command.
10653 ;; There might be problems if any of the keys used by the table editor is
10654 ;; otherwise used as a prefix key.
10656 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10657 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10658 ;; addresses this by checking explicitly for both bindings.
10660 ;; The optimized version (see variable `orgtbl-optimized') takes over
10661 ;; all keys which are bound to `self-insert-command' in the *global map*.
10662 ;; Some modes bind other commands to simple characters, for example
10663 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10664 ;; active, this binding is ignored inside tables and replaced with a
10665 ;; modified self-insert.
10667 (defvar orgtbl-mode nil
10668 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10669 table editor in arbitrary modes.")
10670 (make-variable-buffer-local 'orgtbl-mode)
10672 (defvar orgtbl-mode-map (make-keymap)
10673 "Keymap for `orgtbl-mode'.")
10675 ;;;###autoload
10676 (defun turn-on-orgtbl ()
10677 "Unconditionally turn on `orgtbl-mode'."
10678 (orgtbl-mode 1))
10680 (defvar org-old-auto-fill-inhibit-regexp nil
10681 "Local variable used by `orgtbl-mode'")
10683 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
10684 "Matches a line belonging to an orgtbl.")
10686 (defconst orgtbl-extra-font-lock-keywords
10687 (list (list (concat "^" orgtbl-line-start-regexp ".*")
10688 0 (quote 'org-table) 'prepend))
10689 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
10691 ;;;###autoload
10692 (defun orgtbl-mode (&optional arg)
10693 "The `org-mode' table editor as a minor mode for use in other modes."
10694 (interactive)
10695 (if (org-mode-p)
10696 ;; Exit without error, in case some hook functions calls this
10697 ;; by accident in org-mode.
10698 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10699 (setq orgtbl-mode
10700 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10701 (if orgtbl-mode
10702 (progn
10703 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10704 ;; Make sure we are first in minor-mode-map-alist
10705 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10706 (and c (setq minor-mode-map-alist
10707 (cons c (delq c minor-mode-map-alist)))))
10708 (org-set-local (quote org-table-may-need-update) t)
10709 (org-add-hook 'before-change-functions 'org-before-change-function
10710 nil 'local)
10711 (org-set-local 'org-old-auto-fill-inhibit-regexp
10712 auto-fill-inhibit-regexp)
10713 (org-set-local 'auto-fill-inhibit-regexp
10714 (if auto-fill-inhibit-regexp
10715 (concat orgtbl-line-start-regexp "\\|"
10716 auto-fill-inhibit-regexp)
10717 orgtbl-line-start-regexp))
10718 (org-add-to-invisibility-spec '(org-cwidth))
10719 (when (fboundp 'font-lock-add-keywords)
10720 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
10721 (org-restart-font-lock))
10722 (easy-menu-add orgtbl-mode-menu)
10723 (run-hooks 'orgtbl-mode-hook))
10724 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10725 (org-cleanup-narrow-column-properties)
10726 (org-remove-from-invisibility-spec '(org-cwidth))
10727 (remove-hook 'before-change-functions 'org-before-change-function t)
10728 (when (fboundp 'font-lock-remove-keywords)
10729 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
10730 (org-restart-font-lock))
10731 (easy-menu-remove orgtbl-mode-menu)
10732 (force-mode-line-update 'all))))
10734 (defun org-cleanup-narrow-column-properties ()
10735 "Remove all properties related to narrow-column invisibility."
10736 (let ((s 1))
10737 (while (setq s (text-property-any s (point-max)
10738 'display org-narrow-column-arrow))
10739 (remove-text-properties s (1+ s) '(display t)))
10740 (setq s 1)
10741 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10742 (remove-text-properties s (1+ s) '(org-cwidth t)))
10743 (setq s 1)
10744 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10745 (remove-text-properties s (1+ s) '(invisible t)))))
10747 ;; Install it as a minor mode.
10748 (put 'orgtbl-mode :included t)
10749 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10750 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10752 (defun orgtbl-make-binding (fun n &rest keys)
10753 "Create a function for binding in the table minor mode.
10754 FUN is the command to call inside a table. N is used to create a unique
10755 command name. KEYS are keys that should be checked in for a command
10756 to execute outside of tables."
10757 (eval
10758 (list 'defun
10759 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10760 '(arg)
10761 (concat "In tables, run `" (symbol-name fun) "'.\n"
10762 "Outside of tables, run the binding of `"
10763 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10764 "'.")
10765 '(interactive "p")
10766 (list 'if
10767 '(org-at-table-p)
10768 (list 'call-interactively (list 'quote fun))
10769 (list 'let '(orgtbl-mode)
10770 (list 'call-interactively
10771 (append '(or)
10772 (mapcar (lambda (k)
10773 (list 'key-binding k))
10774 keys)
10775 '('orgtbl-error))))))))
10777 (defun orgtbl-error ()
10778 "Error when there is no default binding for a table key."
10779 (interactive)
10780 (error "This key is has no function outside tables"))
10782 (defun orgtbl-setup ()
10783 "Setup orgtbl keymaps."
10784 (let ((nfunc 0)
10785 (bindings
10786 (list
10787 '([(meta shift left)] org-table-delete-column)
10788 '([(meta left)] org-table-move-column-left)
10789 '([(meta right)] org-table-move-column-right)
10790 '([(meta shift right)] org-table-insert-column)
10791 '([(meta shift up)] org-table-kill-row)
10792 '([(meta shift down)] org-table-insert-row)
10793 '([(meta up)] org-table-move-row-up)
10794 '([(meta down)] org-table-move-row-down)
10795 '("\C-c\C-w" org-table-cut-region)
10796 '("\C-c\M-w" org-table-copy-region)
10797 '("\C-c\C-y" org-table-paste-rectangle)
10798 '("\C-c-" org-table-insert-hline)
10799 '("\C-c}" org-table-toggle-coordinate-overlays)
10800 '("\C-c{" org-table-toggle-formula-debugger)
10801 '("\C-m" org-table-next-row)
10802 '([(shift return)] org-table-copy-down)
10803 '("\C-c\C-q" org-table-wrap-region)
10804 '("\C-c?" org-table-field-info)
10805 '("\C-c " org-table-blank-field)
10806 '("\C-c+" org-table-sum)
10807 '("\C-c=" org-table-eval-formula)
10808 '("\C-c'" org-table-edit-formulas)
10809 '("\C-c`" org-table-edit-field)
10810 '("\C-c*" org-table-recalculate)
10811 '("\C-c|" org-table-create-or-convert-from-region)
10812 '("\C-c^" org-table-sort-lines)
10813 '([(control ?#)] org-table-rotate-recalc-marks)))
10814 elt key fun cmd)
10815 (while (setq elt (pop bindings))
10816 (setq nfunc (1+ nfunc))
10817 (setq key (org-key (car elt))
10818 fun (nth 1 elt)
10819 cmd (orgtbl-make-binding fun nfunc key))
10820 (org-defkey orgtbl-mode-map key cmd))
10822 ;; Special treatment needed for TAB and RET
10823 (org-defkey orgtbl-mode-map [(return)]
10824 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10825 (org-defkey orgtbl-mode-map "\C-m"
10826 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10828 (org-defkey orgtbl-mode-map [(tab)]
10829 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10830 (org-defkey orgtbl-mode-map "\C-i"
10831 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10833 (org-defkey orgtbl-mode-map [(shift tab)]
10834 (orgtbl-make-binding 'org-table-previous-field 104
10835 [(shift tab)] [(tab)] "\C-i"))
10837 (org-defkey orgtbl-mode-map "\M-\C-m"
10838 (orgtbl-make-binding 'org-table-wrap-region 105
10839 "\M-\C-m" [(meta return)]))
10840 (org-defkey orgtbl-mode-map [(meta return)]
10841 (orgtbl-make-binding 'org-table-wrap-region 106
10842 [(meta return)] "\M-\C-m"))
10844 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10845 (when orgtbl-optimized
10846 ;; If the user wants maximum table support, we need to hijack
10847 ;; some standard editing functions
10848 (org-remap orgtbl-mode-map
10849 'self-insert-command 'orgtbl-self-insert-command
10850 'delete-char 'org-delete-char
10851 'delete-backward-char 'org-delete-backward-char)
10852 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10853 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10854 '("OrgTbl"
10855 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10856 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10857 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10858 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10859 "--"
10860 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10861 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10862 ["Copy Field from Above"
10863 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10864 "--"
10865 ("Column"
10866 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10867 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10868 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10869 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10870 ("Row"
10871 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10872 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10873 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10874 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10875 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10876 "--"
10877 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10878 ("Rectangle"
10879 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10880 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10881 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10882 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10883 "--"
10884 ("Radio tables"
10885 ["Insert table template" orgtbl-insert-radio-table
10886 (assq major-mode orgtbl-radio-table-templates)]
10887 ["Comment/uncomment table" orgtbl-toggle-comment t])
10888 "--"
10889 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10890 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10891 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10892 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10893 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10894 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10895 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10896 ["Sum Column/Rectangle" org-table-sum
10897 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10898 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10899 ["Debug Formulas"
10900 org-table-toggle-formula-debugger :active (org-at-table-p)
10901 :keys "C-c {"
10902 :style toggle :selected org-table-formula-debug]
10903 ["Show Col/Row Numbers"
10904 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10905 :keys "C-c }"
10906 :style toggle :selected org-table-overlay-coordinates]
10910 (defun orgtbl-ctrl-c-ctrl-c (arg)
10911 "If the cursor is inside a table, realign the table.
10912 It it is a table to be sent away to a receiver, do it.
10913 With prefix arg, also recompute table."
10914 (interactive "P")
10915 (let ((pos (point)) action)
10916 (save-excursion
10917 (beginning-of-line 1)
10918 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10919 ((looking-at "[ \t]*|") pos)
10920 ((looking-at "#\\+TBLFM:") 'recalc))))
10921 (cond
10922 ((integerp action)
10923 (goto-char action)
10924 (org-table-maybe-eval-formula)
10925 (if arg
10926 (call-interactively 'org-table-recalculate)
10927 (org-table-maybe-recalculate-line))
10928 (call-interactively 'org-table-align)
10929 (orgtbl-send-table 'maybe))
10930 ((eq action 'recalc)
10931 (save-excursion
10932 (beginning-of-line 1)
10933 (skip-chars-backward " \r\n\t")
10934 (if (org-at-table-p)
10935 (org-call-with-arg 'org-table-recalculate t))))
10936 (t (let (orgtbl-mode)
10937 (call-interactively (key-binding "\C-c\C-c")))))))
10939 (defun orgtbl-tab (arg)
10940 "Justification and field motion for `orgtbl-mode'."
10941 (interactive "P")
10942 (if arg (org-table-edit-field t)
10943 (org-table-justify-field-maybe)
10944 (org-table-next-field)))
10946 (defun orgtbl-ret ()
10947 "Justification and field motion for `orgtbl-mode'."
10948 (interactive)
10949 (org-table-justify-field-maybe)
10950 (org-table-next-row))
10952 (defun orgtbl-self-insert-command (N)
10953 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10954 If the cursor is in a table looking at whitespace, the whitespace is
10955 overwritten, and the table is not marked as requiring realignment."
10956 (interactive "p")
10957 (if (and (org-at-table-p)
10959 (and org-table-auto-blank-field
10960 (member last-command
10961 '(orgtbl-hijacker-command-100
10962 orgtbl-hijacker-command-101
10963 orgtbl-hijacker-command-102
10964 orgtbl-hijacker-command-103
10965 orgtbl-hijacker-command-104
10966 orgtbl-hijacker-command-105))
10967 (org-table-blank-field))
10969 (eq N 1)
10970 (looking-at "[^|\n]* +|"))
10971 (let (org-table-may-need-update)
10972 (goto-char (1- (match-end 0)))
10973 (delete-backward-char 1)
10974 (goto-char (match-beginning 0))
10975 (self-insert-command N))
10976 (setq org-table-may-need-update t)
10977 (let (orgtbl-mode)
10978 (call-interactively (key-binding (vector last-input-event))))))
10980 (defun org-force-self-insert (N)
10981 "Needed to enforce self-insert under remapping."
10982 (interactive "p")
10983 (self-insert-command N))
10985 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
10986 "Regula expression matching exponentials as produced by calc.")
10988 (defvar org-table-clean-did-remove-column nil)
10990 (defun orgtbl-export (table target)
10991 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10992 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10993 org-table-last-alignment org-table-last-column-widths
10994 maxcol column)
10995 (if (not (fboundp func))
10996 (error "Cannot export orgtbl table to %s" target))
10997 (setq lines (org-table-clean-before-export lines))
10998 (setq table
10999 (mapcar
11000 (lambda (x)
11001 (if (string-match org-table-hline-regexp x)
11002 'hline
11003 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11004 lines))
11005 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11006 table)))
11007 (loop for i from (1- maxcol) downto 0 do
11008 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11009 (setq column (delq nil column))
11010 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11011 (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))
11012 (funcall func table nil)))
11014 (defun orgtbl-send-table (&optional maybe)
11015 "Send a tranformed version of this table to the receiver position.
11016 With argument MAYBE, fail quietly if no transformation is defined for
11017 this table."
11018 (interactive)
11019 (catch 'exit
11020 (unless (org-at-table-p) (error "Not at a table"))
11021 ;; when non-interactive, we assume align has just happened.
11022 (when (interactive-p) (org-table-align))
11023 (save-excursion
11024 (goto-char (org-table-begin))
11025 (beginning-of-line 0)
11026 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11027 (if maybe
11028 (throw 'exit nil)
11029 (error "Don't know how to transform this table."))))
11030 (let* ((name (match-string 1))
11032 (transform (intern (match-string 2)))
11033 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11034 (skip (plist-get params :skip))
11035 (skipcols (plist-get params :skipcols))
11036 (txt (buffer-substring-no-properties
11037 (org-table-begin) (org-table-end)))
11038 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11039 (lines (org-table-clean-before-export lines))
11040 (i0 (if org-table-clean-did-remove-column 2 1))
11041 (table (mapcar
11042 (lambda (x)
11043 (if (string-match org-table-hline-regexp x)
11044 'hline
11045 (org-remove-by-index
11046 (org-split-string (org-trim x) "\\s-*|\\s-*")
11047 skipcols i0)))
11048 lines))
11049 (fun (if (= i0 2) 'cdr 'identity))
11050 (org-table-last-alignment
11051 (org-remove-by-index (funcall fun org-table-last-alignment)
11052 skipcols i0))
11053 (org-table-last-column-widths
11054 (org-remove-by-index (funcall fun org-table-last-column-widths)
11055 skipcols i0)))
11057 (unless (fboundp transform)
11058 (error "No such transformation function %s" transform))
11059 (setq txt (funcall transform table params))
11060 ;; Find the insertion place
11061 (save-excursion
11062 (goto-char (point-min))
11063 (unless (re-search-forward
11064 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11065 (error "Don't know where to insert translated table"))
11066 (goto-char (match-beginning 0))
11067 (beginning-of-line 2)
11068 (setq beg (point))
11069 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11070 (error "Cannot find end of insertion region"))
11071 (beginning-of-line 1)
11072 (delete-region beg (point))
11073 (goto-char beg)
11074 (insert txt "\n"))
11075 (message "Table converted and installed at receiver location"))))
11077 (defun org-remove-by-index (list indices &optional i0)
11078 "Remove the elements in LIST with indices in INDICES.
11079 First element has index 0, or I0 if given."
11080 (if (not indices)
11081 list
11082 (if (integerp indices) (setq indices (list indices)))
11083 (setq i0 (1- (or i0 0)))
11084 (delq :rm (mapcar (lambda (x)
11085 (setq i0 (1+ i0))
11086 (if (memq i0 indices) :rm x))
11087 list))))
11089 (defun orgtbl-toggle-comment ()
11090 "Comment or uncomment the orgtbl at point."
11091 (interactive)
11092 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11093 (re2 (concat "^" orgtbl-line-start-regexp))
11094 (commented (save-excursion (beginning-of-line 1)
11095 (cond ((looking-at re1) t)
11096 ((looking-at re2) nil)
11097 (t (error "Not at an org table")))))
11098 (re (if commented re1 re2))
11099 beg end)
11100 (save-excursion
11101 (beginning-of-line 1)
11102 (while (looking-at re) (beginning-of-line 0))
11103 (beginning-of-line 2)
11104 (setq beg (point))
11105 (while (looking-at re) (beginning-of-line 2))
11106 (setq end (point)))
11107 (comment-region beg end (if commented '(4) nil))))
11109 (defun orgtbl-insert-radio-table ()
11110 "Insert a radio table template appropriate for this major mode."
11111 (interactive)
11112 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11113 (txt (nth 1 e))
11114 name pos)
11115 (unless e (error "No radio table setup defined for %s" major-mode))
11116 (setq name (read-string "Table name: "))
11117 (while (string-match "%n" txt)
11118 (setq txt (replace-match name t t txt)))
11119 (or (bolp) (insert "\n"))
11120 (setq pos (point))
11121 (insert txt)
11122 (goto-char pos)))
11124 (defun org-get-param (params header i sym &optional hsym)
11125 "Get parameter value for symbol SYM.
11126 If this is a header line, actually get the value for the symbol with an
11127 additional \"h\" inserted after the colon.
11128 If the value is a protperty list, get the element for the current column.
11129 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11130 (let ((val (plist-get params sym)))
11131 (and hsym header (setq val (or (plist-get params hsym) val)))
11132 (if (consp val) (plist-get val i) val)))
11134 (defun orgtbl-to-generic (table params)
11135 "Convert the orgtbl-mode TABLE to some other format.
11136 This generic routine can be used for many standard cases.
11137 TABLE is a list, each entry either the symbol `hline' for a horizontal
11138 separator line, or a list of fields for that line.
11139 PARAMS is a property list of parameters that can influence the conversion.
11140 For the generic converter, some parameters are obligatory: You need to
11141 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11142 :splice, you must have :tstart and :tend.
11144 Valid parameters are
11146 :tstart String to start the table. Ignored when :splice is t.
11147 :tend String to end the table. Ignored when :splice is t.
11149 :splice When set to t, return only table body lines, don't wrap
11150 them into :tstart and :tend. Default is nil.
11152 :hline String to be inserted on horizontal separation lines.
11153 May be nil to ignore hlines.
11155 :lstart String to start a new table line.
11156 :lend String to end a table line
11157 :sep Separator between two fields
11158 :lfmt Format for entire line, with enough %s to capture all fields.
11159 If this is present, :lstart, :lend, and :sep are ignored.
11160 :fmt A format to be used to wrap the field, should contain
11161 %s for the original field value. For example, to wrap
11162 everything in dollars, you could use :fmt \"$%s$\".
11163 This may also be a property list with column numbers and
11164 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11166 :hlstart :hlend :hlsep :hlfmt :hfmt
11167 Same as above, specific for the header lines in the table.
11168 All lines before the first hline are treated as header.
11169 If any of these is not present, the data line value is used.
11171 :efmt Use this format to print numbers with exponentials.
11172 The format should have %s twice for inserting mantissa
11173 and exponent, for example \"%s\\\\times10^{%s}\". This
11174 may also be a property list with column numbers and
11175 formats. :fmt will still be applied after :efmt.
11177 In addition to this, the parameters :skip and :skipcols are always handled
11178 directly by `orgtbl-send-table'. See manual."
11179 (interactive)
11180 (let* ((p params)
11181 (splicep (plist-get p :splice))
11182 (hline (plist-get p :hline))
11183 rtn line i fm efm lfmt h)
11185 ;; Do we have a header?
11186 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11187 (setq h t))
11189 ;; Put header
11190 (unless splicep
11191 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11193 ;; Now loop over all lines
11194 (while (setq line (pop table))
11195 (if (eq line 'hline)
11196 ;; A horizontal separator line
11197 (progn (if hline (push hline rtn))
11198 (setq h nil)) ; no longer in header
11199 ;; A normal line. Convert the fields, push line onto the result list
11200 (setq i 0)
11201 (setq line
11202 (mapcar
11203 (lambda (f)
11204 (setq i (1+ i)
11205 fm (org-get-param p h i :fmt :hfmt)
11206 efm (org-get-param p h i :efmt))
11207 (if (and efm (string-match orgtbl-exp-regexp f))
11208 (setq f (format
11209 efm (match-string 1 f) (match-string 2 f))))
11210 (if fm (setq f (format fm f)))
11212 line))
11213 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11214 (push (apply 'format lfmt line) rtn)
11215 (push (concat
11216 (org-get-param p h i :lstart :hlstart)
11217 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11218 (org-get-param p h i :lend :hlend))
11219 rtn))))
11221 (unless splicep
11222 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11224 (mapconcat 'identity (nreverse rtn) "\n")))
11226 (defun orgtbl-to-latex (table params)
11227 "Convert the orgtbl-mode TABLE to LaTeX.
11228 TABLE is a list, each entry either the symbol `hline' for a horizontal
11229 separator line, or a list of fields for that line.
11230 PARAMS is a property list of parameters that can influence the conversion.
11231 Supports all parameters from `orgtbl-to-generic'. Most important for
11232 LaTeX are:
11234 :splice When set to t, return only table body lines, don't wrap
11235 them into a tabular environment. Default is nil.
11237 :fmt A format to be used to wrap the field, should contain %s for the
11238 original field value. For example, to wrap everything in dollars,
11239 use :fmt \"$%s$\". This may also be a property list with column
11240 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11242 :efmt Format for transforming numbers with exponentials. The format
11243 should have %s twice for inserting mantissa and exponent, for
11244 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11245 This may also be a property list with column numbers and formats.
11247 The general parameters :skip and :skipcols have already been applied when
11248 this function is called."
11249 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11250 org-table-last-alignment ""))
11251 (params2
11252 (list
11253 :tstart (concat "\\begin{tabular}{" alignment "}")
11254 :tend "\\end{tabular}"
11255 :lstart "" :lend " \\\\" :sep " & "
11256 :efmt "%s\\,(%s)" :hline "\\hline")))
11257 (orgtbl-to-generic table (org-combine-plists params2 params))))
11259 (defun orgtbl-to-html (table params)
11260 "Convert the orgtbl-mode TABLE to LaTeX.
11261 TABLE is a list, each entry either the symbol `hline' for a horizontal
11262 separator line, or a list of fields for that line.
11263 PARAMS is a property list of parameters that can influence the conversion.
11264 Currently this function recognizes the following parameters:
11266 :splice When set to t, return only table body lines, don't wrap
11267 them into a <table> environment. Default is nil.
11269 The general parameters :skip and :skipcols have already been applied when
11270 this function is called. The function does *not* use `orgtbl-to-generic',
11271 so you cannot specify parameters for it."
11272 (let* ((splicep (plist-get params :splice))
11273 html)
11274 ;; Just call the formatter we already have
11275 ;; We need to make text lines for it, so put the fields back together.
11276 (setq html (org-format-org-table-html
11277 (mapcar
11278 (lambda (x)
11279 (if (eq x 'hline)
11280 "|----+----|"
11281 (concat "| " (mapconcat 'identity x " | ") " |")))
11282 table)
11283 splicep))
11284 (if (string-match "\n+\\'" html)
11285 (setq html (replace-match "" t t html)))
11286 html))
11288 (defun orgtbl-to-texinfo (table params)
11289 "Convert the orgtbl-mode TABLE to TeXInfo.
11290 TABLE is a list, each entry either the symbol `hline' for a horizontal
11291 separator line, or a list of fields for that line.
11292 PARAMS is a property list of parameters that can influence the conversion.
11293 Supports all parameters from `orgtbl-to-generic'. Most important for
11294 TeXInfo are:
11296 :splice nil/t When set to t, return only table body lines, don't wrap
11297 them into a multitable environment. Default is nil.
11299 :fmt fmt A format to be used to wrap the field, should contain
11300 %s for the original field value. For example, to wrap
11301 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11302 This may also be a property list with column numbers and
11303 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11305 :cf \"f1 f2..\" The column fractions for the table. Bye default these
11306 are computed automatically from the width of the columns
11307 under org-mode.
11309 The general parameters :skip and :skipcols have already been applied when
11310 this function is called."
11311 (let* ((total (float (apply '+ org-table-last-column-widths)))
11312 (colfrac (or (plist-get params :cf)
11313 (mapconcat
11314 (lambda (x) (format "%.3f" (/ (float x) total)))
11315 org-table-last-column-widths " ")))
11316 (params2
11317 (list
11318 :tstart (concat "@multitable @columnfractions " colfrac)
11319 :tend "@end multitable"
11320 :lstart "@item " :lend "" :sep " @tab "
11321 :hlstart "@headitem ")))
11322 (orgtbl-to-generic table (org-combine-plists params2 params))))
11324 ;;;; Link Stuff
11326 ;;; Link abbreviations
11328 (defun org-link-expand-abbrev (link)
11329 "Apply replacements as defined in `org-link-abbrev-alist."
11330 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11331 (let* ((key (match-string 1 link))
11332 (as (or (assoc key org-link-abbrev-alist-local)
11333 (assoc key org-link-abbrev-alist)))
11334 (tag (and (match-end 2) (match-string 3 link)))
11335 rpl)
11336 (if (not as)
11337 link
11338 (setq rpl (cdr as))
11339 (cond
11340 ((symbolp rpl) (funcall rpl tag))
11341 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11342 (t (concat rpl tag)))))
11343 link))
11345 ;;; Storing and inserting links
11347 (defvar org-insert-link-history nil
11348 "Minibuffer history for links inserted with `org-insert-link'.")
11350 (defvar org-stored-links nil
11351 "Contains the links stored with `org-store-link'.")
11353 (defvar org-store-link-plist nil
11354 "Plist with info about the most recently link created with `org-store-link'.")
11356 (defvar org-link-protocols nil
11357 "Link protocols added to Org-mode using `org-add-link-type'.")
11359 (defvar org-store-link-functions nil
11360 "List of functions that are called to create and store a link.
11361 Each function will be called in turn until one returns a non-nil
11362 value. Each function should check if it is responsible for creating
11363 this link (for example by looking at the major mode).
11364 If not, it must exit and return nil.
11365 If yes, it should return a non-nil value after a calling
11366 `org-store-link-props' with a list of properties and values.
11367 Special properties are:
11369 :type The link prefix. like \"http\". This must be given.
11370 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11371 This is obligatory as well.
11372 :description Optional default description for the second pair
11373 of brackets in an Org-mode link. The user can still change
11374 this when inserting this link into an Org-mode buffer.
11376 In addition to these, any additional properties can be specified
11377 and then used in remember templates.")
11379 (defun org-add-link-type (type &optional follow publish)
11380 "Add TYPE to the list of `org-link-types'.
11381 Re-compute all regular expressions depending on `org-link-types'
11382 FOLLOW and PUBLISH are two functions. Both take the link path as
11383 an argument.
11384 FOLLOW should do whatever is necessary to follow the link, for example
11385 to find a file or display a mail message.
11386 PUBLISH takes the path and retuns the string that should be used when
11387 this document is published."
11388 (add-to-list 'org-link-types type t)
11389 (org-make-link-regexps)
11390 (add-to-list 'org-link-protocols
11391 (list type follow publish)))
11393 (defun org-add-agenda-custom-command (entry)
11394 "Replace or add a command in `org-agenda-custom-commands'.
11395 This is mostly for hacking and trying a new command - once the command
11396 works you probably want to add it to `org-agenda-custom-commands' for good."
11397 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11398 (if ass
11399 (setcdr ass (cdr entry))
11400 (push entry org-agenda-custom-commands))))
11402 ;;;###autoload
11403 (defun org-store-link (arg)
11404 "\\<org-mode-map>Store an org-link to the current location.
11405 This link can later be inserted into an org-buffer with
11406 \\[org-insert-link].
11407 For some link types, a prefix arg is interpreted:
11408 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11409 For file links, arg negates `org-context-in-file-links'."
11410 (interactive "P")
11411 (setq org-store-link-plist nil) ; reset
11412 (let (link cpltxt desc description search txt)
11413 (cond
11415 ((run-hook-with-args-until-success 'org-store-link-functions)
11416 (setq link (plist-get org-store-link-plist :link)
11417 desc (or (plist-get org-store-link-plist :description) link)))
11419 ((eq major-mode 'bbdb-mode)
11420 (let ((name (bbdb-record-name (bbdb-current-record)))
11421 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11422 (setq cpltxt (concat "bbdb:" (or name company))
11423 link (org-make-link cpltxt))
11424 (org-store-link-props :type "bbdb" :name name :company company)))
11426 ((eq major-mode 'Info-mode)
11427 (setq link (org-make-link "info:"
11428 (file-name-nondirectory Info-current-file)
11429 ":" Info-current-node))
11430 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11431 ":" Info-current-node))
11432 (org-store-link-props :type "info" :file Info-current-file
11433 :node Info-current-node))
11435 ((eq major-mode 'calendar-mode)
11436 (let ((cd (calendar-cursor-to-date)))
11437 (setq link
11438 (format-time-string
11439 (car org-time-stamp-formats)
11440 (apply 'encode-time
11441 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11442 nil nil nil))))
11443 (org-store-link-props :type "calendar" :date cd)))
11445 ((or (eq major-mode 'vm-summary-mode)
11446 (eq major-mode 'vm-presentation-mode))
11447 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11448 (vm-follow-summary-cursor)
11449 (save-excursion
11450 (vm-select-folder-buffer)
11451 (let* ((message (car vm-message-pointer))
11452 (folder buffer-file-name)
11453 (subject (vm-su-subject message))
11454 (to (vm-get-header-contents message "To"))
11455 (from (vm-get-header-contents message "From"))
11456 (message-id (vm-su-message-id message)))
11457 (org-store-link-props :type "vm" :from from :to to :subject subject
11458 :message-id message-id)
11459 (setq message-id (org-remove-angle-brackets message-id))
11460 (setq folder (abbreviate-file-name folder))
11461 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11462 folder)
11463 (setq folder (replace-match "" t t folder)))
11464 (setq cpltxt (org-email-link-description))
11465 (setq link (org-make-link "vm:" folder "#" message-id)))))
11467 ((eq major-mode 'wl-summary-mode)
11468 (let* ((msgnum (wl-summary-message-number))
11469 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11470 msgnum 'message-id))
11471 (wl-message-entity
11472 (if (fboundp 'elmo-message-entity)
11473 (elmo-message-entity
11474 wl-summary-buffer-elmo-folder msgnum)
11475 (elmo-msgdb-overview-get-entity
11476 msgnum (wl-summary-buffer-msgdb))))
11477 (from (wl-summary-line-from))
11478 (to (elmo-message-entity-field wl-message-entity 'to))
11479 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11480 (wl-summary-line-subject))))
11481 (org-store-link-props :type "wl" :from from :to to
11482 :subject subject :message-id message-id)
11483 (setq message-id (org-remove-angle-brackets message-id))
11484 (setq cpltxt (org-email-link-description))
11485 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11486 "#" message-id))))
11488 ((or (equal major-mode 'mh-folder-mode)
11489 (equal major-mode 'mh-show-mode))
11490 (let ((from (org-mhe-get-header "From:"))
11491 (to (org-mhe-get-header "To:"))
11492 (message-id (org-mhe-get-header "Message-Id:"))
11493 (subject (org-mhe-get-header "Subject:")))
11494 (org-store-link-props :type "mh" :from from :to to
11495 :subject subject :message-id message-id)
11496 (setq cpltxt (org-email-link-description))
11497 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11498 (org-remove-angle-brackets message-id)))))
11500 ((eq major-mode 'rmail-mode)
11501 (save-excursion
11502 (save-restriction
11503 (rmail-narrow-to-non-pruned-header)
11504 (let ((folder buffer-file-name)
11505 (message-id (mail-fetch-field "message-id"))
11506 (from (mail-fetch-field "from"))
11507 (to (mail-fetch-field "to"))
11508 (subject (mail-fetch-field "subject")))
11509 (org-store-link-props
11510 :type "rmail" :from from :to to
11511 :subject subject :message-id message-id)
11512 (setq message-id (org-remove-angle-brackets message-id))
11513 (setq cpltxt (org-email-link-description))
11514 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11516 ((eq major-mode 'gnus-group-mode)
11517 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11518 (gnus-group-group-name)) ; version
11519 ((fboundp 'gnus-group-name)
11520 (gnus-group-name))
11521 (t "???"))))
11522 (unless group (error "Not on a group"))
11523 (org-store-link-props :type "gnus" :group group)
11524 (setq cpltxt (concat
11525 (if (org-xor arg org-usenet-links-prefer-google)
11526 "http://groups.google.com/groups?group="
11527 "gnus:")
11528 group)
11529 link (org-make-link cpltxt))))
11531 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11532 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11533 (let* ((group gnus-newsgroup-name)
11534 (article (gnus-summary-article-number))
11535 (header (gnus-summary-article-header article))
11536 (from (mail-header-from header))
11537 (message-id (mail-header-id header))
11538 (date (mail-header-date header))
11539 (subject (gnus-summary-subject-string)))
11540 (org-store-link-props :type "gnus" :from from :subject subject
11541 :message-id message-id :group group)
11542 (setq cpltxt (org-email-link-description))
11543 (if (org-xor arg org-usenet-links-prefer-google)
11544 (setq link
11545 (concat
11546 cpltxt "\n "
11547 (format "http://groups.google.com/groups?as_umsgid=%s"
11548 (org-fixup-message-id-for-http message-id))))
11549 (setq link (org-make-link "gnus:" group
11550 "#" (number-to-string article))))))
11552 ((eq major-mode 'w3-mode)
11553 (setq cpltxt (url-view-url t)
11554 link (org-make-link cpltxt))
11555 (org-store-link-props :type "w3" :url (url-view-url t)))
11557 ((eq major-mode 'w3m-mode)
11558 (setq cpltxt (or w3m-current-title w3m-current-url)
11559 link (org-make-link w3m-current-url))
11560 (org-store-link-props :type "w3m" :url (url-view-url t)))
11562 ((setq search (run-hook-with-args-until-success
11563 'org-create-file-search-functions))
11564 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11565 "::" search))
11566 (setq cpltxt (or description link)))
11568 ((eq major-mode 'image-mode)
11569 (setq cpltxt (concat "file:"
11570 (abbreviate-file-name buffer-file-name))
11571 link (org-make-link cpltxt))
11572 (org-store-link-props :type "image" :file buffer-file-name))
11574 ((eq major-mode 'dired-mode)
11575 ;; link to the file in the current line
11576 (setq cpltxt (concat "file:"
11577 (abbreviate-file-name
11578 (expand-file-name
11579 (dired-get-filename nil t))))
11580 link (org-make-link cpltxt)))
11582 ((and buffer-file-name (org-mode-p))
11583 ;; Just link to current headline
11584 (setq cpltxt (concat "file:"
11585 (abbreviate-file-name buffer-file-name)))
11586 ;; Add a context search string
11587 (when (org-xor org-context-in-file-links arg)
11588 ;; Check if we are on a target
11589 (if (org-in-regexp "<<\\(.*?\\)>>")
11590 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11591 (setq txt (cond
11592 ((org-on-heading-p) nil)
11593 ((org-region-active-p)
11594 (buffer-substring (region-beginning) (region-end)))
11595 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11596 (when (or (null txt) (string-match "\\S-" txt))
11597 (setq cpltxt
11598 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11599 desc "NONE"))))
11600 (if (string-match "::\\'" cpltxt)
11601 (setq cpltxt (substring cpltxt 0 -2)))
11602 (setq link (org-make-link cpltxt)))
11604 ((buffer-file-name (buffer-base-buffer))
11605 ;; Just link to this file here.
11606 (setq cpltxt (concat "file:"
11607 (abbreviate-file-name
11608 (buffer-file-name (buffer-base-buffer)))))
11609 ;; Add a context string
11610 (when (org-xor org-context-in-file-links arg)
11611 (setq txt (if (org-region-active-p)
11612 (buffer-substring (region-beginning) (region-end))
11613 (buffer-substring (point-at-bol) (point-at-eol))))
11614 ;; Only use search option if there is some text.
11615 (when (string-match "\\S-" txt)
11616 (setq cpltxt
11617 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11618 desc "NONE")))
11619 (setq link (org-make-link cpltxt)))
11621 ((interactive-p)
11622 (error "Cannot link to a buffer which is not visiting a file"))
11624 (t (setq link nil)))
11626 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11627 (setq link (or link cpltxt)
11628 desc (or desc cpltxt))
11629 (if (equal desc "NONE") (setq desc nil))
11631 (if (and (interactive-p) link)
11632 (progn
11633 (setq org-stored-links
11634 (cons (list link desc) org-stored-links))
11635 (message "Stored: %s" (or desc link)))
11636 (and link (org-make-link-string link desc)))))
11638 (defun org-store-link-props (&rest plist)
11639 "Store link properties, extract names and addresses."
11640 (let (x adr)
11641 (when (setq x (plist-get plist :from))
11642 (setq adr (mail-extract-address-components x))
11643 (plist-put plist :fromname (car adr))
11644 (plist-put plist :fromaddress (nth 1 adr)))
11645 (when (setq x (plist-get plist :to))
11646 (setq adr (mail-extract-address-components x))
11647 (plist-put plist :toname (car adr))
11648 (plist-put plist :toaddress (nth 1 adr))))
11649 (let ((from (plist-get plist :from))
11650 (to (plist-get plist :to)))
11651 (when (and from to org-from-is-user-regexp)
11652 (plist-put plist :fromto
11653 (if (string-match org-from-is-user-regexp from)
11654 (concat "to %t")
11655 (concat "from %f")))))
11656 (setq org-store-link-plist plist))
11658 (defun org-email-link-description (&optional fmt)
11659 "Return the description part of an email link.
11660 This takes information from `org-store-link-plist' and formats it
11661 according to FMT (default from `org-email-link-description-format')."
11662 (setq fmt (or fmt org-email-link-description-format))
11663 (let* ((p org-store-link-plist)
11664 (to (plist-get p :toaddress))
11665 (from (plist-get p :fromaddress))
11666 (table
11667 (list
11668 (cons "%c" (plist-get p :fromto))
11669 (cons "%F" (plist-get p :from))
11670 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
11671 (cons "%T" (plist-get p :to))
11672 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
11673 (cons "%s" (plist-get p :subject))
11674 (cons "%m" (plist-get p :message-id)))))
11675 (when (string-match "%c" fmt)
11676 ;; Check if the user wrote this message
11677 (if (and org-from-is-user-regexp from to
11678 (save-match-data (string-match org-from-is-user-regexp from)))
11679 (setq fmt (replace-match "to %t" t t fmt))
11680 (setq fmt (replace-match "from %f" t t fmt))))
11681 (org-replace-escapes fmt table)))
11683 (defun org-make-org-heading-search-string (&optional string heading)
11684 "Make search string for STRING or current headline."
11685 (interactive)
11686 (let ((s (or string (org-get-heading))))
11687 (unless (and string (not heading))
11688 ;; We are using a headline, clean up garbage in there.
11689 (if (string-match org-todo-regexp s)
11690 (setq s (replace-match "" t t s)))
11691 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
11692 (setq s (replace-match "" t t s)))
11693 (setq s (org-trim s))
11694 (if (string-match (concat "^\\(" org-quote-string "\\|"
11695 org-comment-string "\\)") s)
11696 (setq s (replace-match "" t t s)))
11697 (while (string-match org-ts-regexp s)
11698 (setq s (replace-match "" t t s))))
11699 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11700 (setq s (replace-match " " t t s)))
11701 (or string (setq s (concat "*" s))) ; Add * for headlines
11702 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11704 (defun org-make-link (&rest strings)
11705 "Concatenate STRINGS."
11706 (apply 'concat strings))
11708 (defun org-make-link-string (link &optional description)
11709 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11710 (unless (string-match "\\S-" link)
11711 (error "Empty link"))
11712 (when (stringp description)
11713 ;; Remove brackets from the description, they are fatal.
11714 (while (string-match "\\[\\|\\]" description)
11715 (setq description (replace-match "" t t description))))
11716 (when (equal (org-link-escape link) description)
11717 ;; No description needed, it is identical
11718 (setq description nil))
11719 (when (and (not description)
11720 (not (equal link (org-link-escape link))))
11721 (setq description link))
11722 (concat "[[" (org-link-escape link) "]"
11723 (if description (concat "[" description "]") "")
11724 "]"))
11726 (defconst org-link-escape-chars
11727 '((?\ . "%20")
11728 (?\[ . "%5B")
11729 (?\] . "%5d")
11730 (?\340 . "%E0") ; `a
11731 (?\342 . "%E2") ; ^a
11732 (?\347 . "%E7") ; ,c
11733 (?\350 . "%E8") ; `e
11734 (?\351 . "%E9") ; 'e
11735 (?\352 . "%EA") ; ^e
11736 (?\356 . "%EE") ; ^i
11737 (?\364 . "%F4") ; ^o
11738 (?\371 . "%F9") ; `u
11739 (?\373 . "%FB") ; ^u
11740 (?\; . "%3B")
11741 (?? . "%3F")
11742 (?= . "%3D")
11743 (?+ . "%2B")
11745 "Association list of escapes for some characters problematic in links.
11746 This is the list that is used for internal purposes.")
11748 (defconst org-link-escape-chars-browser
11749 '((?\ . "%20")) ; 32 for the SPC char
11751 "Association list of escapes for some characters problematic in links.
11752 This is the list that is used before handing over to the browser.")
11754 (defun org-link-escape (text &optional table)
11755 "Escape charaters in TEXT that are problematic for links."
11756 (setq table (or table org-link-escape-chars))
11757 (when text
11758 (let ((re (mapconcat (lambda (x) (regexp-quote
11759 (char-to-string (car x))))
11760 table "\\|")))
11761 (while (string-match re text)
11762 (setq text
11763 (replace-match
11764 (cdr (assoc (string-to-char (match-string 0 text))
11765 table))
11766 t t text)))
11767 text)))
11769 (defun org-link-unescape (text &optional table)
11770 "Reverse the action of `org-link-escape'."
11771 (setq table (or table org-link-escape-chars))
11772 (when text
11773 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11774 table "\\|")))
11775 (while (string-match re text)
11776 (setq text
11777 (replace-match
11778 (char-to-string (car (rassoc (match-string 0 text) table)))
11779 t t text)))
11780 text)))
11782 (defun org-xor (a b)
11783 "Exclusive or."
11784 (if a (not b) b))
11786 (defun org-get-header (header)
11787 "Find a header field in the current buffer."
11788 (save-excursion
11789 (goto-char (point-min))
11790 (let ((case-fold-search t) s)
11791 (cond
11792 ((eq header 'from)
11793 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11794 (setq s (match-string 1)))
11795 (while (string-match "\"" s)
11796 (setq s (replace-match "" t t s)))
11797 (if (string-match "[<(].*" s)
11798 (setq s (replace-match "" t t s))))
11799 ((eq header 'message-id)
11800 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11801 (setq s (match-string 1))))
11802 ((eq header 'subject)
11803 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11804 (setq s (match-string 1)))))
11805 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11806 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11807 s)))
11810 (defun org-fixup-message-id-for-http (s)
11811 "Replace special characters in a message id, so it can be used in an http query."
11812 (while (string-match "<" s)
11813 (setq s (replace-match "%3C" t t s)))
11814 (while (string-match ">" s)
11815 (setq s (replace-match "%3E" t t s)))
11816 (while (string-match "@" s)
11817 (setq s (replace-match "%40" t t s)))
11820 ;;;###autoload
11821 (defun org-insert-link-global ()
11822 "Insert a link like Org-mode does.
11823 This command can be called in any mode to insert a link in Org-mode syntax."
11824 (interactive)
11825 (org-run-like-in-org-mode 'org-insert-link))
11827 (defun org-insert-link (&optional complete-file)
11828 "Insert a link. At the prompt, enter the link.
11830 Completion can be used to select a link previously stored with
11831 `org-store-link'. When the empty string is entered (i.e. if you just
11832 press RET at the prompt), the link defaults to the most recently
11833 stored link. As SPC triggers completion in the minibuffer, you need to
11834 use M-SPC or C-q SPC to force the insertion of a space character.
11836 You will also be prompted for a description, and if one is given, it will
11837 be displayed in the buffer instead of the link.
11839 If there is already a link at point, this command will allow you to edit link
11840 and description parts.
11842 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11843 selected using completion. The path to the file will be relative to
11844 the current directory if the file is in the current directory or a
11845 subdirectory. Otherwise, the link will be the absolute path as
11846 completed in the minibuffer (i.e. normally ~/path/to/file).
11848 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11849 is in the current directory or below.
11850 With three \\[universal-argument] prefixes, negate the meaning of
11851 `org-keep-stored-link-after-insertion'."
11852 (interactive "P")
11853 (let* ((wcf (current-window-configuration))
11854 (region (if (org-region-active-p)
11855 (buffer-substring (region-beginning) (region-end))))
11856 (remove (and region (list (region-beginning) (region-end))))
11857 (desc region)
11858 tmphist ; byte-compile incorrectly complains about this
11859 link entry file)
11860 (cond
11861 ((org-in-regexp org-bracket-link-regexp 1)
11862 ;; We do have a link at point, and we are going to edit it.
11863 (setq remove (list (match-beginning 0) (match-end 0)))
11864 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11865 (setq link (read-string "Link: "
11866 (org-link-unescape
11867 (org-match-string-no-properties 1)))))
11868 ((or (org-in-regexp org-angle-link-re)
11869 (org-in-regexp org-plain-link-re))
11870 ;; Convert to bracket link
11871 (setq remove (list (match-beginning 0) (match-end 0))
11872 link (read-string "Link: "
11873 (org-remove-angle-brackets (match-string 0)))))
11874 ((equal complete-file '(4))
11875 ;; Completing read for file names.
11876 (setq file (read-file-name "File: "))
11877 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11878 (pwd1 (file-name-as-directory (abbreviate-file-name
11879 (expand-file-name ".")))))
11880 (cond
11881 ((equal complete-file '(16))
11882 (setq link (org-make-link
11883 "file:"
11884 (abbreviate-file-name (expand-file-name file)))))
11885 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11886 (setq link (org-make-link "file:" (match-string 1 file))))
11887 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11888 (expand-file-name file))
11889 (setq link (org-make-link
11890 "file:" (match-string 1 (expand-file-name file)))))
11891 (t (setq link (org-make-link "file:" file))))))
11893 ;; Read link, with completion for stored links.
11894 (with-output-to-temp-buffer "*Org Links*"
11895 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11896 (when org-stored-links
11897 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
11898 (princ (mapconcat
11899 (lambda (x)
11900 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
11901 (reverse org-stored-links) "\n"))))
11902 (let ((cw (selected-window)))
11903 (select-window (get-buffer-window "*Org Links*"))
11904 (shrink-window-if-larger-than-buffer)
11905 (setq truncate-lines t)
11906 (select-window cw))
11907 ;; Fake a link history, containing the stored links.
11908 (setq tmphist (append (mapcar 'car org-stored-links)
11909 org-insert-link-history))
11910 (unwind-protect
11911 (setq link (org-completing-read
11912 "Link: "
11913 (append
11914 (mapcar (lambda (x) (list (concat (car x) ":")))
11915 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11916 (mapcar (lambda (x) (list (concat x ":")))
11917 org-link-types))
11918 nil nil nil
11919 'tmphist
11920 (or (car (car org-stored-links)))))
11921 (set-window-configuration wcf)
11922 (kill-buffer "*Org Links*"))
11923 (setq entry (assoc link org-stored-links))
11924 (or entry (push link org-insert-link-history))
11925 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11926 (not org-keep-stored-link-after-insertion))
11927 (setq org-stored-links (delq (assoc link org-stored-links)
11928 org-stored-links)))
11929 (setq desc (or desc (nth 1 entry)))))
11931 (if (string-match org-plain-link-re link)
11932 ;; URL-like link, normalize the use of angular brackets.
11933 (setq link (org-make-link (org-remove-angle-brackets link))))
11935 ;; Check if we are linking to the current file with a search option
11936 ;; If yes, simplify the link by using only the search option.
11937 (when (and buffer-file-name
11938 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11939 (let* ((path (match-string 1 link))
11940 (case-fold-search nil)
11941 (search (match-string 2 link)))
11942 (save-match-data
11943 (if (equal (file-truename buffer-file-name) (file-truename path))
11944 ;; We are linking to this same file, with a search option
11945 (setq link search)))))
11947 ;; Check if we can/should use a relative path. If yes, simplify the link
11948 (when (string-match "\\<file:\\(.*\\)" link)
11949 (let* ((path (match-string 1 link))
11950 (origpath path)
11951 (desc-is-link (equal link desc))
11952 (case-fold-search nil))
11953 (cond
11954 ((eq org-link-file-path-type 'absolute)
11955 (setq path (abbreviate-file-name (expand-file-name path))))
11956 ((eq org-link-file-path-type 'noabbrev)
11957 (setq path (expand-file-name path)))
11958 ((eq org-link-file-path-type 'relative)
11959 (setq path (file-relative-name path)))
11961 (save-match-data
11962 (if (string-match (concat "^" (regexp-quote
11963 (file-name-as-directory
11964 (expand-file-name "."))))
11965 (expand-file-name path))
11966 ;; We are linking a file with relative path name.
11967 (setq path (substring (expand-file-name path)
11968 (match-end 0)))))))
11969 (setq link (concat "file:" path))
11970 (if (equal desc origpath)
11971 (setq desc path))))
11973 (setq desc (read-string "Description: " desc))
11974 (unless (string-match "\\S-" desc) (setq desc nil))
11975 (if remove (apply 'delete-region remove))
11976 (insert (org-make-link-string link desc))))
11978 (defun org-completing-read (&rest args)
11979 (let ((minibuffer-local-completion-map
11980 (copy-keymap minibuffer-local-completion-map)))
11981 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
11982 (apply 'completing-read args)))
11984 ;;; Opening/following a link
11985 (defvar org-link-search-failed nil)
11987 (defun org-next-link ()
11988 "Move forward to the next link.
11989 If the link is in hidden text, expose it."
11990 (interactive)
11991 (when (and org-link-search-failed (eq this-command last-command))
11992 (goto-char (point-min))
11993 (message "Link search wrapped back to beginning of buffer"))
11994 (setq org-link-search-failed nil)
11995 (let* ((pos (point))
11996 (ct (org-context))
11997 (a (assoc :link ct)))
11998 (if a (goto-char (nth 2 a)))
11999 (if (re-search-forward org-any-link-re nil t)
12000 (progn
12001 (goto-char (match-beginning 0))
12002 (if (org-invisible-p) (org-show-context)))
12003 (goto-char pos)
12004 (setq org-link-search-failed t)
12005 (error "No further link found"))))
12007 (defun org-previous-link ()
12008 "Move backward to the previous link.
12009 If the link is in hidden text, expose it."
12010 (interactive)
12011 (when (and org-link-search-failed (eq this-command last-command))
12012 (goto-char (point-max))
12013 (message "Link search wrapped back to end of buffer"))
12014 (setq org-link-search-failed nil)
12015 (let* ((pos (point))
12016 (ct (org-context))
12017 (a (assoc :link ct)))
12018 (if a (goto-char (nth 1 a)))
12019 (if (re-search-backward org-any-link-re nil t)
12020 (progn
12021 (goto-char (match-beginning 0))
12022 (if (org-invisible-p) (org-show-context)))
12023 (goto-char pos)
12024 (setq org-link-search-failed t)
12025 (error "No further link found"))))
12027 (defun org-find-file-at-mouse (ev)
12028 "Open file link or URL at mouse."
12029 (interactive "e")
12030 (mouse-set-point ev)
12031 (org-open-at-point 'in-emacs))
12033 (defun org-open-at-mouse (ev)
12034 "Open file link or URL at mouse."
12035 (interactive "e")
12036 (mouse-set-point ev)
12037 (org-open-at-point))
12039 (defvar org-window-config-before-follow-link nil
12040 "The window configuration before following a link.
12041 This is saved in case the need arises to restore it.")
12043 (defvar org-open-link-marker (make-marker)
12044 "Marker pointing to the location where `org-open-at-point; was called.")
12046 ;;;###autoload
12047 (defun org-open-at-point-global ()
12048 "Follow a link like Org-mode does.
12049 This command can be called in any mode to follow a link that has
12050 Org-mode syntax."
12051 (interactive)
12052 (org-run-like-in-org-mode 'org-open-at-point))
12054 (defun org-open-at-point (&optional in-emacs)
12055 "Open link at or after point.
12056 If there is no link at point, this function will search forward up to
12057 the end of the current subtree.
12058 Normally, files will be opened by an appropriate application. If the
12059 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12060 (interactive "P")
12061 (move-marker org-open-link-marker (point))
12062 (setq org-window-config-before-follow-link (current-window-configuration))
12063 (org-remove-occur-highlights nil nil t)
12064 (if (org-at-timestamp-p t)
12065 (org-follow-timestamp-link)
12066 (let (type path link line search (pos (point)))
12067 (catch 'match
12068 (save-excursion
12069 (skip-chars-forward "^]\n\r")
12070 (when (org-in-regexp org-bracket-link-regexp)
12071 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12072 (while (string-match " *\n *" link)
12073 (setq link (replace-match " " t t link)))
12074 (setq link (org-link-expand-abbrev link))
12075 (if (string-match org-link-re-with-space2 link)
12076 (setq type (match-string 1 link) path (match-string 2 link))
12077 (setq type "thisfile" path link))
12078 (throw 'match t)))
12080 (when (get-text-property (point) 'org-linked-text)
12081 (setq type "thisfile"
12082 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12083 (1+ (point)) (point))
12084 path (buffer-substring
12085 (previous-single-property-change pos 'org-linked-text)
12086 (next-single-property-change pos 'org-linked-text)))
12087 (throw 'match t))
12089 (save-excursion
12090 (when (or (org-in-regexp org-angle-link-re)
12091 (org-in-regexp org-plain-link-re))
12092 (setq type (match-string 1) path (match-string 2))
12093 (throw 'match t)))
12094 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12095 (setq type "tree-match"
12096 path (match-string 1))
12097 (throw 'match t))
12098 (save-excursion
12099 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12100 (setq type "tags"
12101 path (match-string 1))
12102 (while (string-match ":" path)
12103 (setq path (replace-match "+" t t path)))
12104 (throw 'match t))))
12105 (unless path
12106 (error "No link found"))
12107 ;; Remove any trailing spaces in path
12108 (if (string-match " +\\'" path)
12109 (setq path (replace-match "" t t path)))
12111 (cond
12113 ((assoc type org-link-protocols)
12114 (funcall (nth 1 (assoc type org-link-protocols)) path))
12116 ((equal type "mailto")
12117 (let ((cmd (car org-link-mailto-program))
12118 (args (cdr org-link-mailto-program)) args1
12119 (address path) (subject "") a)
12120 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12121 (setq address (match-string 1 path)
12122 subject (org-link-escape (match-string 2 path))))
12123 (while args
12124 (cond
12125 ((not (stringp (car args))) (push (pop args) args1))
12126 (t (setq a (pop args))
12127 (if (string-match "%a" a)
12128 (setq a (replace-match address t t a)))
12129 (if (string-match "%s" a)
12130 (setq a (replace-match subject t t a)))
12131 (push a args1))))
12132 (apply cmd (nreverse args1))))
12134 ((member type '("http" "https" "ftp" "news"))
12135 (browse-url (concat type ":" (org-link-escape
12136 path org-link-escape-chars-browser))))
12138 ((string= type "tags")
12139 (org-tags-view in-emacs path))
12140 ((string= type "thisfile")
12141 (if in-emacs
12142 (switch-to-buffer-other-window
12143 (org-get-buffer-for-internal-link (current-buffer)))
12144 (org-mark-ring-push))
12145 (let ((cmd `(org-link-search
12146 ,path
12147 ,(cond ((equal in-emacs '(4)) 'occur)
12148 ((equal in-emacs '(16)) 'org-occur)
12149 (t nil))
12150 ,pos)))
12151 (condition-case nil (eval cmd)
12152 (error (progn (widen) (eval cmd))))))
12154 ((string= type "tree-match")
12155 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12157 ((string= type "file")
12158 (if (string-match "::\\([0-9]+\\)\\'" path)
12159 (setq line (string-to-number (match-string 1 path))
12160 path (substring path 0 (match-beginning 0)))
12161 (if (string-match "::\\(.+\\)\\'" path)
12162 (setq search (match-string 1 path)
12163 path (substring path 0 (match-beginning 0)))))
12164 (if (string-match "[*?{]" (file-name-nondirectory path))
12165 (dired path)
12166 (org-open-file path in-emacs line search)))
12168 ((string= type "news")
12169 (org-follow-gnus-link path))
12171 ((string= type "bbdb")
12172 (org-follow-bbdb-link path))
12174 ((string= type "info")
12175 (org-follow-info-link path))
12177 ((string= type "gnus")
12178 (let (group article)
12179 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12180 (error "Error in Gnus link"))
12181 (setq group (match-string 1 path)
12182 article (match-string 3 path))
12183 (org-follow-gnus-link group article)))
12185 ((string= type "vm")
12186 (let (folder article)
12187 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12188 (error "Error in VM link"))
12189 (setq folder (match-string 1 path)
12190 article (match-string 3 path))
12191 ;; in-emacs is the prefix arg, will be interpreted as read-only
12192 (org-follow-vm-link folder article in-emacs)))
12194 ((string= type "wl")
12195 (let (folder article)
12196 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12197 (error "Error in Wanderlust link"))
12198 (setq folder (match-string 1 path)
12199 article (match-string 3 path))
12200 (org-follow-wl-link folder article)))
12202 ((string= type "mhe")
12203 (let (folder article)
12204 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12205 (error "Error in MHE link"))
12206 (setq folder (match-string 1 path)
12207 article (match-string 3 path))
12208 (org-follow-mhe-link folder article)))
12210 ((string= type "rmail")
12211 (let (folder article)
12212 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12213 (error "Error in RMAIL link"))
12214 (setq folder (match-string 1 path)
12215 article (match-string 3 path))
12216 (org-follow-rmail-link folder article)))
12218 ((string= type "shell")
12219 (let ((cmd path))
12220 ;; The following is only for backward compatibility
12221 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
12222 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
12223 (if (or (not org-confirm-shell-link-function)
12224 (funcall org-confirm-shell-link-function
12225 (format "Execute \"%s\" in shell? "
12226 (org-add-props cmd nil
12227 'face 'org-warning))))
12228 (progn
12229 (message "Executing %s" cmd)
12230 (shell-command cmd))
12231 (error "Abort"))))
12233 ((string= type "elisp")
12234 (let ((cmd path))
12235 (if (or (not org-confirm-elisp-link-function)
12236 (funcall org-confirm-elisp-link-function
12237 (format "Execute \"%s\" as elisp? "
12238 (org-add-props cmd nil
12239 'face 'org-warning))))
12240 (message "%s => %s" cmd (eval (read cmd)))
12241 (error "Abort"))))
12244 (browse-url-at-point)))))
12245 (move-marker org-open-link-marker nil))
12247 ;;; File search
12249 (defvar org-create-file-search-functions nil
12250 "List of functions to construct the right search string for a file link.
12251 These functions are called in turn with point at the location to
12252 which the link should point.
12254 A function in the hook should first test if it would like to
12255 handle this file type, for example by checking the major-mode or
12256 the file extension. If it decides not to handle this file, it
12257 should just return nil to give other functions a chance. If it
12258 does handle the file, it must return the search string to be used
12259 when following the link. The search string will be part of the
12260 file link, given after a double colon, and `org-open-at-point'
12261 will automatically search for it. If special measures must be
12262 taken to make the search successful, another function should be
12263 added to the companion hook `org-execute-file-search-functions',
12264 which see.
12266 A function in this hook may also use `setq' to set the variable
12267 `description' to provide a suggestion for the descriptive text to
12268 be used for this link when it gets inserted into an Org-mode
12269 buffer with \\[org-insert-link].")
12271 (defvar org-execute-file-search-functions nil
12272 "List of functions to execute a file search triggered by a link.
12274 Functions added to this hook must accept a single argument, the
12275 search string that was part of the file link, the part after the
12276 double colon. The function must first check if it would like to
12277 handle this search, for example by checking the major-mode or the
12278 file extension. If it decides not to handle this search, it
12279 should just return nil to give other functions a chance. If it
12280 does handle the search, it must return a non-nil value to keep
12281 other functions from trying.
12283 Each function can access the current prefix argument through the
12284 variable `current-prefix-argument'. Note that a single prefix is
12285 used to force opening a link in Emacs, so it may be good to only
12286 use a numeric or double prefix to guide the search function.
12288 In case this is needed, a function in this hook can also restore
12289 the window configuration before `org-open-at-point' was called using:
12291 (set-window-configuration org-window-config-before-follow-link)")
12293 (defun org-link-search (s &optional type avoid-pos)
12294 "Search for a link search option.
12295 If S is surrounded by forward slashes, it is interpreted as a
12296 regular expression. In org-mode files, this will create an `org-occur'
12297 sparse tree. In ordinary files, `occur' will be used to list matches.
12298 If the current buffer is in `dired-mode', grep will be used to search
12299 in all files. If AVOID-POS is given, ignore matches near that position."
12300 (let ((case-fold-search t)
12301 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12302 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12303 (append '(("") (" ") ("\t") ("\n"))
12304 org-emphasis-alist)
12305 "\\|") "\\)"))
12306 (pos (point))
12307 (pre "") (post "")
12308 words re0 re1 re2 re3 re4 re5 re2a reall)
12309 (cond
12310 ;; First check if there are any special
12311 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12312 ;; Now try the builtin stuff
12313 ((save-excursion
12314 (goto-char (point-min))
12315 (and
12316 (re-search-forward
12317 (concat "<<" (regexp-quote s0) ">>") nil t)
12318 (setq pos (match-beginning 0))))
12319 ;; There is an exact target for this
12320 (goto-char pos))
12321 ((string-match "^/\\(.*\\)/$" s)
12322 ;; A regular expression
12323 (cond
12324 ((org-mode-p)
12325 (org-occur (match-string 1 s)))
12326 ;;((eq major-mode 'dired-mode)
12327 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12328 (t (org-do-occur (match-string 1 s)))))
12330 ;; A normal search strings
12331 (when (equal (string-to-char s) ?*)
12332 ;; Anchor on headlines, post may include tags.
12333 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12334 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12335 s (substring s 1)))
12336 (remove-text-properties
12337 0 (length s)
12338 '(face nil mouse-face nil keymap nil fontified nil) s)
12339 ;; Make a series of regular expressions to find a match
12340 (setq words (org-split-string s "[ \n\r\t]+")
12341 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12342 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12343 "\\)" markers)
12344 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12345 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12346 re1 (concat pre re2 post)
12347 re3 (concat pre re4 post)
12348 re5 (concat pre ".*" re4)
12349 re2 (concat pre re2)
12350 re2a (concat pre re2a)
12351 re4 (concat pre re4)
12352 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12353 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12354 re5 "\\)"
12356 (cond
12357 ((eq type 'org-occur) (org-occur reall))
12358 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12359 (t (goto-char (point-min))
12360 (if (or (org-search-not-self 1 re0 nil t)
12361 (org-search-not-self 1 re1 nil t)
12362 (org-search-not-self 1 re2 nil t)
12363 (org-search-not-self 1 re2a nil t)
12364 (org-search-not-self 1 re3 nil t)
12365 (org-search-not-self 1 re4 nil t)
12366 (org-search-not-self 1 re5 nil t)
12368 (goto-char (match-beginning 1))
12369 (goto-char pos)
12370 (error "No match")))))
12372 ;; Normal string-search
12373 (goto-char (point-min))
12374 (if (search-forward s nil t)
12375 (goto-char (match-beginning 0))
12376 (error "No match"))))
12377 (and (org-mode-p) (org-show-context 'link-search))))
12379 (defun org-search-not-self (group &rest args)
12380 "Execute `re-search-forward', but only accept matches that do not
12381 enclose the position of `org-open-link-marker'."
12382 (let ((m org-open-link-marker))
12383 (catch 'exit
12384 (while (apply 're-search-forward args)
12385 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12386 (goto-char (match-end group))
12387 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12388 (> (match-beginning 0) (marker-position m))
12389 (< (match-end 0) (marker-position m)))
12390 (save-match-data
12391 (or (not (org-in-regexp
12392 org-bracket-link-analytic-regexp 1))
12393 (not (match-end 4)) ; no description
12394 (and (<= (match-beginning 4) (point))
12395 (>= (match-end 4) (point))))))
12396 (throw 'exit (point))))))))
12398 (defun org-get-buffer-for-internal-link (buffer)
12399 "Return a buffer to be used for displaying the link target of internal links."
12400 (cond
12401 ((not org-display-internal-link-with-indirect-buffer)
12402 buffer)
12403 ((string-match "(Clone)$" (buffer-name buffer))
12404 (message "Buffer is already a clone, not making another one")
12405 ;; we also do not modify visibility in this case
12406 buffer)
12407 (t ; make a new indirect buffer for displaying the link
12408 (let* ((bn (buffer-name buffer))
12409 (ibn (concat bn "(Clone)"))
12410 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12411 (with-current-buffer ib (org-overview))
12412 ib))))
12414 (defun org-do-occur (regexp &optional cleanup)
12415 "Call the Emacs command `occur'.
12416 If CLEANUP is non-nil, remove the printout of the regular expression
12417 in the *Occur* buffer. This is useful if the regex is long and not useful
12418 to read."
12419 (occur regexp)
12420 (when cleanup
12421 (let ((cwin (selected-window)) win beg end)
12422 (when (setq win (get-buffer-window "*Occur*"))
12423 (select-window win))
12424 (goto-char (point-min))
12425 (when (re-search-forward "match[a-z]+" nil t)
12426 (setq beg (match-end 0))
12427 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12428 (setq end (1- (match-beginning 0)))))
12429 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12430 (goto-char (point-min))
12431 (select-window cwin))))
12433 ;;; The mark ring for links jumps
12435 (defvar org-mark-ring nil
12436 "Mark ring for positions before jumps in Org-mode.")
12437 (defvar org-mark-ring-last-goto nil
12438 "Last position in the mark ring used to go back.")
12439 ;; Fill and close the ring
12440 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12441 (loop for i from 1 to org-mark-ring-length do
12442 (push (make-marker) org-mark-ring))
12443 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12444 org-mark-ring)
12446 (defun org-mark-ring-push (&optional pos buffer)
12447 "Put the current position or POS into the mark ring and rotate it."
12448 (interactive)
12449 (setq pos (or pos (point)))
12450 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12451 (move-marker (car org-mark-ring)
12452 (or pos (point))
12453 (or buffer (current-buffer)))
12454 (message
12455 (substitute-command-keys
12456 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12458 (defun org-mark-ring-goto (&optional n)
12459 "Jump to the previous position in the mark ring.
12460 With prefix arg N, jump back that many stored positions. When
12461 called several times in succession, walk through the entire ring.
12462 Org-mode commands jumping to a different position in the current file,
12463 or to another Org-mode file, automatically push the old position
12464 onto the ring."
12465 (interactive "p")
12466 (let (p m)
12467 (if (eq last-command this-command)
12468 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12469 (setq p org-mark-ring))
12470 (setq org-mark-ring-last-goto p)
12471 (setq m (car p))
12472 (switch-to-buffer (marker-buffer m))
12473 (goto-char m)
12474 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12476 (defun org-remove-angle-brackets (s)
12477 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12478 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12480 (defun org-add-angle-brackets (s)
12481 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12482 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12485 ;;; Following specific links
12487 (defun org-follow-timestamp-link ()
12488 (cond
12489 ((org-at-date-range-p t)
12490 (let ((org-agenda-start-on-weekday)
12491 (t1 (match-string 1))
12492 (t2 (match-string 2)))
12493 (setq t1 (time-to-days (org-time-string-to-time t1))
12494 t2 (time-to-days (org-time-string-to-time t2)))
12495 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12496 ((org-at-timestamp-p t)
12497 (org-agenda-list nil (time-to-days (org-time-string-to-time
12498 (substring (match-string 1) 0 10)))
12500 (t (error "This should not happen"))))
12503 (defun org-follow-bbdb-link (name)
12504 "Follow a BBDB link to NAME."
12505 (require 'bbdb)
12506 (let ((inhibit-redisplay (not debug-on-error))
12507 (bbdb-electric-p nil))
12508 (catch 'exit
12509 ;; Exact match on name
12510 (bbdb-name (concat "\\`" name "\\'") nil)
12511 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12512 ;; Exact match on name
12513 (bbdb-company (concat "\\`" name "\\'") nil)
12514 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12515 ;; Partial match on name
12516 (bbdb-name name nil)
12517 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12518 ;; Partial match on company
12519 (bbdb-company name nil)
12520 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12521 ;; General match including network address and notes
12522 (bbdb name nil)
12523 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12524 (delete-window (get-buffer-window "*BBDB*"))
12525 (error "No matching BBDB record")))))
12527 (defun org-follow-info-link (name)
12528 "Follow an info file & node link to NAME."
12529 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12530 (string-match "\\(.*\\)" name))
12531 (progn
12532 (require 'info)
12533 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12534 (Info-find-node (match-string 1 name) (match-string 2 name))
12535 (Info-find-node (match-string 1 name) "Top")))
12536 (message (concat "Could not open: " name))))
12538 (defun org-follow-gnus-link (&optional group article)
12539 "Follow a Gnus link to GROUP and ARTICLE."
12540 (require 'gnus)
12541 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12542 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12543 (cond ((and group article)
12544 (gnus-group-read-group 1 nil group)
12545 (gnus-summary-goto-article (string-to-number article) nil t))
12546 (group (gnus-group-jump-to-group group))))
12548 (defun org-follow-vm-link (&optional folder article readonly)
12549 "Follow a VM link to FOLDER and ARTICLE."
12550 (require 'vm)
12551 (setq article (org-add-angle-brackets article))
12552 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12553 ;; ange-ftp or efs or tramp access
12554 (let ((user (or (match-string 1 folder) (user-login-name)))
12555 (host (match-string 2 folder))
12556 (file (match-string 3 folder)))
12557 (cond
12558 ((featurep 'tramp)
12559 ;; use tramp to access the file
12560 (if (featurep 'xemacs)
12561 (setq folder (format "[%s@%s]%s" user host file))
12562 (setq folder (format "/%s@%s:%s" user host file))))
12564 ;; use ange-ftp or efs
12565 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12566 (setq folder (format "/%s@%s:%s" user host file))))))
12567 (when folder
12568 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12569 (sit-for 0.1)
12570 (when article
12571 (vm-select-folder-buffer)
12572 (widen)
12573 (let ((case-fold-search t))
12574 (goto-char (point-min))
12575 (if (not (re-search-forward
12576 (concat "^" "message-id: *" (regexp-quote article))))
12577 (error "Could not find the specified message in this folder"))
12578 (vm-isearch-update)
12579 (vm-isearch-narrow)
12580 (vm-beginning-of-message)
12581 (vm-summarize)))))
12583 (defun org-follow-wl-link (folder article)
12584 "Follow a Wanderlust link to FOLDER and ARTICLE."
12585 (if (and (string= folder "%")
12586 article
12587 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12588 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12589 ;; Thus, we recompose folder and article ids.
12590 (setq folder (format "%s#%s" folder (match-string 1 article))
12591 article (match-string 3 article)))
12592 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12593 (error "No such folder: %s" folder))
12594 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12595 (and article
12596 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12597 (wl-summary-redisplay)))
12599 (defun org-follow-rmail-link (folder article)
12600 "Follow an RMAIL link to FOLDER and ARTICLE."
12601 (setq article (org-add-angle-brackets article))
12602 (let (message-number)
12603 (save-excursion
12604 (save-window-excursion
12605 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12606 (setq message-number
12607 (save-restriction
12608 (widen)
12609 (goto-char (point-max))
12610 (if (re-search-backward
12611 (concat "^Message-ID:\\s-+" (regexp-quote
12612 (or article "")))
12613 nil t)
12614 (rmail-what-message))))))
12615 (if message-number
12616 (progn
12617 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12618 (rmail-show-message message-number)
12619 message-number)
12620 (error "Message not found"))))
12622 ;;; mh-e integration based on planner-mode
12623 (defun org-mhe-get-message-real-folder ()
12624 "Return the name of the current message real folder, so if you use
12625 sequences, it will now work."
12626 (save-excursion
12627 (let* ((folder
12628 (if (equal major-mode 'mh-folder-mode)
12629 mh-current-folder
12630 ;; Refer to the show buffer
12631 mh-show-folder-buffer))
12632 (end-index
12633 (if (boundp 'mh-index-folder)
12634 (min (length mh-index-folder) (length folder))))
12636 ;; a simple test on mh-index-data does not work, because
12637 ;; mh-index-data is always nil in a show buffer.
12638 (if (and (boundp 'mh-index-folder)
12639 (string= mh-index-folder (substring folder 0 end-index)))
12640 (if (equal major-mode 'mh-show-mode)
12641 (save-window-excursion
12642 (let (pop-up-frames)
12643 (when (buffer-live-p (get-buffer folder))
12644 (progn
12645 (pop-to-buffer folder)
12646 (org-mhe-get-message-folder-from-index)
12649 (org-mhe-get-message-folder-from-index)
12651 folder
12655 (defun org-mhe-get-message-folder-from-index ()
12656 "Returns the name of the message folder in a index folder buffer."
12657 (save-excursion
12658 (mh-index-previous-folder)
12659 (re-search-forward "^\\(+.*\\)$" nil t)
12660 (message (match-string 1))))
12662 (defun org-mhe-get-message-folder ()
12663 "Return the name of the current message folder. Be careful if you
12664 use sequences."
12665 (save-excursion
12666 (if (equal major-mode 'mh-folder-mode)
12667 mh-current-folder
12668 ;; Refer to the show buffer
12669 mh-show-folder-buffer)))
12671 (defun org-mhe-get-message-num ()
12672 "Return the number of the current message. Be careful if you
12673 use sequences."
12674 (save-excursion
12675 (if (equal major-mode 'mh-folder-mode)
12676 (mh-get-msg-num nil)
12677 ;; Refer to the show buffer
12678 (mh-show-buffer-message-number))))
12680 (defun org-mhe-get-header (header)
12681 "Return a header of the message in folder mode. This will create a
12682 show buffer for the corresponding message. If you have a more clever
12683 idea..."
12684 (let* ((folder (org-mhe-get-message-folder))
12685 (num (org-mhe-get-message-num))
12686 (buffer (get-buffer-create (concat "show-" folder)))
12687 (header-field))
12688 (with-current-buffer buffer
12689 (mh-display-msg num folder)
12690 (if (equal major-mode 'mh-folder-mode)
12691 (mh-header-display)
12692 (mh-show-header-display))
12693 (set-buffer buffer)
12694 (setq header-field (mh-get-header-field header))
12695 (if (equal major-mode 'mh-folder-mode)
12696 (mh-show)
12697 (mh-show-show))
12698 header-field)))
12700 (defun org-follow-mhe-link (folder article)
12701 "Follow an MHE link to FOLDER and ARTICLE.
12702 If ARTICLE is nil FOLDER is shown. If the configuration variable
12703 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
12704 ARTICLE is searched in all folders. Indexed searches (swish++,
12705 namazu, and others supported by MH-E) will always search in all
12706 folders."
12707 (require 'mh-e)
12708 (require 'mh-search)
12709 (require 'mh-utils)
12710 (mh-find-path)
12711 (if (not article)
12712 (mh-visit-folder (mh-normalize-folder-name folder))
12713 (setq article (org-add-angle-brackets article))
12714 (mh-search-choose)
12715 (if (equal mh-searcher 'pick)
12716 (progn
12717 (mh-search folder (list "--message-id" article))
12718 (when (and org-mhe-search-all-folders
12719 (not (org-mhe-get-message-real-folder)))
12720 (kill-this-buffer)
12721 (mh-search "+" (list "--message-id" article))))
12722 (mh-search "+" article))
12723 (if (org-mhe-get-message-real-folder)
12724 (mh-show-msg 1)
12725 (kill-this-buffer)
12726 (error "Message not found"))))
12728 ;;; BibTeX links
12730 ;; Use the custom search meachnism to construct and use search strings for
12731 ;; file links to BibTeX database entries.
12733 (defun org-create-file-search-in-bibtex ()
12734 "Create the search string and description for a BibTeX database entry."
12735 (when (eq major-mode 'bibtex-mode)
12736 ;; yes, we want to construct this search string.
12737 ;; Make a good description for this entry, using names, year and the title
12738 ;; Put it into the `description' variable which is dynamically scoped.
12739 (let ((bibtex-autokey-names 1)
12740 (bibtex-autokey-names-stretch 1)
12741 (bibtex-autokey-name-case-convert-function 'identity)
12742 (bibtex-autokey-name-separator " & ")
12743 (bibtex-autokey-additional-names " et al.")
12744 (bibtex-autokey-year-length 4)
12745 (bibtex-autokey-name-year-separator " ")
12746 (bibtex-autokey-titlewords 3)
12747 (bibtex-autokey-titleword-separator " ")
12748 (bibtex-autokey-titleword-case-convert-function 'identity)
12749 (bibtex-autokey-titleword-length 'infty)
12750 (bibtex-autokey-year-title-separator ": "))
12751 (setq description (bibtex-generate-autokey)))
12752 ;; Now parse the entry, get the key and return it.
12753 (save-excursion
12754 (bibtex-beginning-of-entry)
12755 (cdr (assoc "=key=" (bibtex-parse-entry))))))
12757 (defun org-execute-file-search-in-bibtex (s)
12758 "Find the link search string S as a key for a database entry."
12759 (when (eq major-mode 'bibtex-mode)
12760 ;; Yes, we want to do the search in this file.
12761 ;; We construct a regexp that searches for "@entrytype{" followed by the key
12762 (goto-char (point-min))
12763 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
12764 (regexp-quote s) "[ \t\n]*,") nil t)
12765 (goto-char (match-beginning 0)))
12766 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
12767 ;; Use double prefix to indicate that any web link should be browsed
12768 (let ((b (current-buffer)) (p (point)))
12769 ;; Restore the window configuration because we just use the web link
12770 (set-window-configuration org-window-config-before-follow-link)
12771 (save-excursion (set-buffer b) (goto-char p)
12772 (bibtex-url)))
12773 (recenter 0)) ; Move entry start to beginning of window
12774 ;; return t to indicate that the search is done.
12777 ;; Finally add the functions to the right hooks.
12778 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
12779 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
12781 ;; end of Bibtex link setup
12783 ;;; Following file links
12785 (defun org-open-file (path &optional in-emacs line search)
12786 "Open the file at PATH.
12787 First, this expands any special file name abbreviations. Then the
12788 configuration variable `org-file-apps' is checked if it contains an
12789 entry for this file type, and if yes, the corresponding command is launched.
12790 If no application is found, Emacs simply visits the file.
12791 With optional argument IN-EMACS, Emacs will visit the file.
12792 Optional LINE specifies a line to go to, optional SEARCH a string to
12793 search for. If LINE or SEARCH is given, the file will always be
12794 opened in Emacs.
12795 If the file does not exist, an error is thrown."
12796 (setq in-emacs (or in-emacs line search))
12797 (let* ((file (if (equal path "")
12798 buffer-file-name
12799 (substitute-in-file-name (expand-file-name path))))
12800 (apps (append org-file-apps (org-default-apps)))
12801 (remp (and (assq 'remote apps) (org-file-remote-p file)))
12802 (dirp (if remp nil (file-directory-p file)))
12803 (dfile (downcase file))
12804 (old-buffer (current-buffer))
12805 (old-pos (point))
12806 (old-mode major-mode)
12807 ext cmd)
12808 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
12809 (setq ext (match-string 1 dfile))
12810 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
12811 (setq ext (match-string 1 dfile))))
12812 (if in-emacs
12813 (setq cmd 'emacs)
12814 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
12815 (and dirp (cdr (assoc 'directory apps)))
12816 (cdr (assoc ext apps))
12817 (cdr (assoc t apps)))))
12818 (when (eq cmd 'mailcap)
12819 (require 'mailcap)
12820 (mailcap-parse-mailcaps)
12821 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
12822 (command (mailcap-mime-info mime-type)))
12823 (if (stringp command)
12824 (setq cmd command)
12825 (setq cmd 'emacs))))
12826 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
12827 (not (file-exists-p file))
12828 (not org-open-non-existing-files))
12829 (error "No such file: %s" file))
12830 (cond
12831 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
12832 ;; Remove quotes around the file name - we'll use shell-quote-argument.
12833 (if (string-match "['\"]%s['\"]" cmd)
12834 (setq cmd (replace-match "%s" t t cmd)))
12835 (setq cmd (format cmd (shell-quote-argument file)))
12836 (save-window-excursion
12837 (start-process-shell-command cmd nil cmd)))
12838 ((or (stringp cmd)
12839 (eq cmd 'emacs))
12840 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12841 (widen)
12842 (if line (goto-line line)
12843 (if search (org-link-search search))))
12844 ((consp cmd)
12845 (eval cmd))
12846 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12847 (and (org-mode-p) (eq old-mode 'org-mode)
12848 (or (not (equal old-buffer (current-buffer)))
12849 (not (equal old-pos (point))))
12850 (org-mark-ring-push old-pos old-buffer))))
12852 (defun org-default-apps ()
12853 "Return the default applications for this operating system."
12854 (cond
12855 ((eq system-type 'darwin)
12856 org-file-apps-defaults-macosx)
12857 ((eq system-type 'windows-nt)
12858 org-file-apps-defaults-windowsnt)
12859 (t org-file-apps-defaults-gnu)))
12861 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12862 (defun org-file-remote-p (file)
12863 "Test whether FILE specifies a location on a remote system.
12864 Return non-nil if the location is indeed remote.
12866 For example, the filename \"/user@host:/foo\" specifies a location
12867 on the system \"/user@host:\"."
12868 (cond ((fboundp 'file-remote-p)
12869 (file-remote-p file))
12870 ((fboundp 'tramp-handle-file-remote-p)
12871 (tramp-handle-file-remote-p file))
12872 ((and (boundp 'ange-ftp-name-format)
12873 (string-match (car ange-ftp-name-format) file))
12875 (t nil)))
12878 ;;;; Hooks for remember.el
12880 ;;;###autoload
12881 (defun org-remember-insinuate ()
12882 "Setup remember.el for use wiht Org-mode."
12883 (require 'remember)
12884 (setq remember-annotation-functions '(org-remember-annotation))
12885 (setq remember-handler-functions '(org-remember-handler))
12886 (add-hook 'remember-mode-hook 'org-remember-apply-template))
12888 ;;;###autoload
12889 (defun org-remember-annotation ()
12890 "Return a link to the current location as an annotation for remember.el.
12891 If you are using Org-mode files as target for data storage with
12892 remember.el, then the annotations should include a link compatible with the
12893 conventions in Org-mode. This function returns such a link."
12894 (org-store-link nil))
12896 (defconst org-remember-help
12897 "Select a destination location for the note.
12898 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12899 RET on headline -> Store as sublevel entry to current headline
12900 RET at beg-of-buf -> Append to file as level 2 headline
12901 <left>/<right> -> before/after current headline, same headings level")
12903 (defvar org-remember-previous-location nil)
12904 (defvar org-force-remember-template-char) ;; dynamically scoped
12906 (defun org-select-remember-template (&optional use-char)
12907 (when org-remember-templates
12908 (let* ((templates (mapcar (lambda (x)
12909 (if (stringp (car x))
12910 (append (list (nth 1 x) (car x)) (cddr x))
12911 (append (list (car x) "") (cdr x))))
12912 org-remember-templates))
12913 (char (or use-char
12914 (cond
12915 ((= (length templates) 1)
12916 (caar templates))
12917 ((and (boundp 'org-force-remember-template-char)
12918 org-force-remember-template-char)
12919 (if (stringp org-force-remember-template-char)
12920 (string-to-char org-force-remember-template-char)
12921 org-force-remember-template-char))
12923 (message "Select template: %s"
12924 (mapconcat
12925 (lambda (x)
12926 (cond
12927 ((not (string-match "\\S-" (nth 1 x)))
12928 (format "[%c]" (car x)))
12929 ((equal (downcase (car x))
12930 (downcase (aref (nth 1 x) 0)))
12931 (format "[%c]%s" (car x)
12932 (substring (nth 1 x) 1)))
12933 (t (format "[%c]%s" (car x) (nth 1 x)))))
12934 templates " "))
12935 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
12936 (when (equal char0 ?\C-g)
12937 (jump-to-register remember-register)
12938 (kill-buffer remember-buffer))
12939 char0))))))
12940 (cddr (assoc char templates)))))
12942 ;;;###autoload
12943 (defun org-remember-apply-template (&optional use-char skip-interactive)
12944 "Initialize *remember* buffer with template, invoke `org-mode'.
12945 This function should be placed into `remember-mode-hook' and in fact requires
12946 to be run from that hook to function properly."
12947 (unless (fboundp 'remember-finalize)
12948 (defalias 'remember-finalize 'remember-buffer))
12949 (if org-remember-templates
12950 (let* ((entry (org-select-remember-template use-char))
12951 (tpl (car entry))
12952 (plist-p (if org-store-link-plist t nil))
12953 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12954 (string-match "\\S-" (nth 1 entry)))
12955 (nth 1 entry)
12956 org-default-notes-file))
12957 (headline (nth 2 entry))
12958 (v-c (if (or (and (eq window-system 'x)
12959 (x-cut-buffer-or-selection-value))
12960 (bound-and-true-p x-last-selected-text)
12961 (bound-and-true-p x-last-selected-text-primary))
12962 x-last-selected-text-primary
12963 (if (> (length kill-ring) 0)
12964 (current-kill 0)
12965 nil)))
12966 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12967 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
12968 (v-u (concat "[" (substring v-t 1 -1) "]"))
12969 (v-U (concat "[" (substring v-T 1 -1) "]"))
12970 ;; `initial' and `annotation' are bound in `remember'
12971 (v-i (if (boundp 'initial) initial))
12972 (v-a (if (and (boundp 'annotation) annotation)
12973 (if (equal annotation "[[]]") "" annotation)
12974 ""))
12975 (v-A (if (and v-a
12976 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
12977 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
12978 v-a))
12979 (v-n user-full-name)
12980 (org-startup-folded nil)
12981 org-time-was-given org-end-time-was-given x prompt char time pos)
12982 (setq org-store-link-plist
12983 (append (list :annotation v-a :initial v-i)
12984 org-store-link-plist))
12985 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
12986 (erase-buffer)
12987 (insert (substitute-command-keys
12988 (format
12989 "## Filing location: Select interactively, default, or last used:
12990 ## %s to select file and header location interactively.
12991 ## %s \"%s\" -> \"* %s\"
12992 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
12993 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
12994 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
12995 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
12996 (abbreviate-file-name (or file org-default-notes-file))
12997 (or headline "")
12998 (or (car org-remember-previous-location) "???")
12999 (or (cdr org-remember-previous-location) "???"))))
13000 (insert tpl) (goto-char (point-min))
13001 ;; Simple %-escapes
13002 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13003 (when (and initial (equal (match-string 0) "%i"))
13004 (save-match-data
13005 (let* ((lead (buffer-substring
13006 (point-at-bol) (match-beginning 0))))
13007 (setq v-i (mapconcat 'identity
13008 (org-split-string initial "\n")
13009 (concat "\n" lead))))))
13010 (replace-match
13011 (or (eval (intern (concat "v-" (match-string 1)))) "")
13012 t t))
13014 ;; %[] Insert contents of a file.
13015 (goto-char (point-min))
13016 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13017 (let ((start (match-beginning 0))
13018 (end (match-end 0))
13019 (filename (expand-file-name (match-string 1))))
13020 (goto-char start)
13021 (delete-region start end)
13022 (condition-case error
13023 (insert-file-contents filename)
13024 (error (insert (format "%%![Couldn't insert %s: %s]"
13025 filename error))))))
13026 ;; %() embedded elisp
13027 (goto-char (point-min))
13028 (while (re-search-forward "%\\((.+)\\)" nil t)
13029 (goto-char (match-beginning 0))
13030 (let ((template-start (point)))
13031 (forward-char 1)
13032 (let ((result
13033 (condition-case error
13034 (eval (read (current-buffer)))
13035 (error (format "%%![Error: %s]" error)))))
13036 (delete-region template-start (point))
13037 (insert result))))
13039 ;; From the property list
13040 (when plist-p
13041 (goto-char (point-min))
13042 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13043 (and (setq x (or (plist-get org-store-link-plist
13044 (intern (match-string 1))) ""))
13045 (replace-match x t t))))
13047 ;; Turn on org-mode in the remember buffer, set local variables
13048 (org-mode)
13049 (org-set-local 'org-finish-function 'remember-finalize)
13050 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13051 (org-set-local 'org-default-notes-file file))
13052 (if (and headline (stringp headline) (string-match "\\S-" headline))
13053 (org-set-local 'org-remember-default-headline headline))
13054 ;; Interactive template entries
13055 (goto-char (point-min))
13056 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
13057 (setq char (if (match-end 3) (match-string 3))
13058 prompt (if (match-end 2) (match-string 2)))
13059 (goto-char (match-beginning 0))
13060 (replace-match "")
13061 (cond
13062 ((member char '("G" "g"))
13063 (let* ((org-last-tags-completion-table
13064 (org-global-tags-completion-table
13065 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13066 (org-add-colon-after-tag-completion t)
13067 (ins (completing-read
13068 (if prompt (concat prompt ": ") "Tags: ")
13069 'org-tags-completion-function nil nil nil
13070 'org-tags-history)))
13071 (setq ins (mapconcat 'identity
13072 (org-split-string ins (org-re "[^[:alnum:]]+"))
13073 ":"))
13074 (when (string-match "\\S-" ins)
13075 (or (equal (char-before) ?:) (insert ":"))
13076 (insert ins)
13077 (or (equal (char-after) ?:) (insert ":")))))
13078 (char
13079 (setq org-time-was-given (equal (upcase char) char))
13080 (setq time (org-read-date (equal (upcase char) "U") t nil
13081 prompt))
13082 (org-insert-time-stamp time org-time-was-given
13083 (member char '("u" "U"))
13084 nil nil (list org-end-time-was-given)))
13086 (insert (read-string
13087 (if prompt (concat prompt ": ") "Enter string"))))))
13088 (goto-char (point-min))
13089 (if (re-search-forward "%\\?" nil t)
13090 (replace-match "")
13091 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13092 (org-mode)
13093 (org-set-local 'org-finish-function 'remember-finalize)))
13095 ;;;###autoload
13096 (defun org-remember (&optional goto org-force-remember-template-char)
13097 "Call `remember'. If this is already a remember buffer, re-apply template.
13098 If there is an active region, make sure remember uses it as initial content
13099 of the remember buffer.
13101 When called interactively with a `C-u' prefix argument GOTO, don't remember
13102 anything, just go to the file/headline where the selected templated usually
13103 stores its notes.
13105 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13106 associated with a template in `org-remember-tempates'."
13107 (interactive "P")
13108 (if (equal goto '(4))
13109 (org-go-to-remember-target)
13110 (if (eq org-finish-function 'remember-buffer)
13111 (progn
13112 (when (< (length org-remember-templates) 2)
13113 (error "No other template available"))
13114 (erase-buffer)
13115 (let ((annotation (plist-get org-store-link-plist :annotation))
13116 (initial (plist-get org-store-link-plist :initial)))
13117 (org-remember-apply-template))
13118 (message "Press C-c C-c to remember data"))
13119 (if (org-region-active-p)
13120 (remember (buffer-substring (point) (mark)))
13121 (call-interactively 'remember)))))
13123 (defun org-go-to-remember-target (&optional template-key)
13124 "Go to the target location of a remember template.
13125 The user is queried for the template."
13126 (interactive)
13127 (let* ((entry (org-select-remember-template template-key))
13128 (file (nth 1 entry))
13129 (heading (nth 2 entry))
13130 visiting)
13131 (unless (and file (stringp file) (string-match "\\S-" file))
13132 (setq file org-default-notes-file))
13133 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13134 (setq heading org-remember-default-headline))
13135 (setq visiting (org-find-base-buffer-visiting file))
13136 (if (not visiting) (find-file-noselect file))
13137 (switch-to-buffer (or visiting (get-file-buffer file)))
13138 (widen)
13139 (goto-char (point-min))
13140 (if (re-search-forward
13141 (concat "^\\*+[ \t]+" (regexp-quote heading)
13142 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13143 nil t)
13144 (goto-char (match-beginning 0))
13145 (error "Target headline not found: %s" heading))))
13147 (defvar org-note-abort nil) ; dynamically scoped
13149 ;;;###autoload
13150 (defun org-remember-handler ()
13151 "Store stuff from remember.el into an org file.
13152 First prompts for an org file. If the user just presses return, the value
13153 of `org-default-notes-file' is used.
13154 Then the command offers the headings tree of the selected file in order to
13155 file the text at a specific location.
13156 You can either immediately press RET to get the note appended to the
13157 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13158 find a better place. Then press RET or <left> or <right> in insert the note.
13160 Key Cursor position Note gets inserted
13161 -----------------------------------------------------------------------------
13162 RET buffer-start as level 1 heading at end of file
13163 RET on headline as sublevel of the heading at cursor
13164 RET no heading at cursor position, level taken from context.
13165 Or use prefix arg to specify level manually.
13166 <left> on headline as same level, before current heading
13167 <right> on headline as same level, after current heading
13169 So the fastest way to store the note is to press RET RET to append it to
13170 the default file. This way your current train of thought is not
13171 interrupted, in accordance with the principles of remember.el.
13172 You can also get the fast execution without prompting by using
13173 C-u C-c C-c to exit the remember buffer. See also the variable
13174 `org-remember-store-without-prompt'.
13176 Before being stored away, the function ensures that the text has a
13177 headline, i.e. a first line that starts with a \"*\". If not, a headline
13178 is constructed from the current date and some additional data.
13180 If the variable `org-adapt-indentation' is non-nil, the entire text is
13181 also indented so that it starts in the same column as the headline
13182 \(i.e. after the stars).
13184 See also the variable `org-reverse-note-order'."
13185 (goto-char (point-min))
13186 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13187 (replace-match ""))
13188 (goto-char (point-max))
13189 (catch 'quit
13190 (if org-note-abort (throw 'quit nil))
13191 (let* ((txt (buffer-substring (point-min) (point-max)))
13192 (fastp (org-xor (equal current-prefix-arg '(4))
13193 org-remember-store-without-prompt))
13194 (file (if fastp org-default-notes-file (org-get-org-file)))
13195 (heading org-remember-default-headline)
13196 (visiting (org-find-base-buffer-visiting file))
13197 (org-startup-folded nil)
13198 (org-startup-align-all-tables nil)
13199 (org-goto-start-pos 1)
13200 spos exitcmd level indent reversed)
13201 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13202 (setq file (car org-remember-previous-location)
13203 heading (cdr org-remember-previous-location)))
13204 (setq current-prefix-arg nil)
13205 ;; Modify text so that it becomes a nice subtree which can be inserted
13206 ;; into an org tree.
13207 (let* ((lines (split-string txt "\n"))
13208 first)
13209 (setq first (car lines) lines (cdr lines))
13210 (if (string-match "^\\*+ " first)
13211 ;; Is already a headline
13212 (setq indent nil)
13213 ;; We need to add a headline: Use time and first buffer line
13214 (setq lines (cons first lines)
13215 first (concat "* " (current-time-string)
13216 " (" (remember-buffer-desc) ")")
13217 indent " "))
13218 (if (and org-adapt-indentation indent)
13219 (setq lines (mapcar
13220 (lambda (x)
13221 (if (string-match "\\S-" x)
13222 (concat indent x) x))
13223 lines)))
13224 (setq txt (concat first "\n"
13225 (mapconcat 'identity lines "\n"))))
13226 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13227 (setq txt (replace-match "\n\n" t t txt))
13228 (if (string-match "[ \t\n]*\\'" txt)
13229 (setq txt (replace-match "\n" t t txt))))
13230 ;; Find the file
13231 (if (not visiting) (find-file-noselect file))
13232 (with-current-buffer (or visiting (get-file-buffer file))
13233 (unless (org-mode-p)
13234 (error "Target files for remember notes must be in Org-mode"))
13235 (save-excursion
13236 (save-restriction
13237 (widen)
13238 (and (goto-char (point-min))
13239 (not (re-search-forward "^\\* " nil t))
13240 (insert "\n* " (or heading "Notes") "\n"))
13241 (setq reversed (org-notes-order-reversed-p))
13243 ;; Find the default location
13244 (when (and heading (stringp heading) (string-match "\\S-" heading))
13245 (goto-char (point-min))
13246 (if (re-search-forward
13247 (concat "^\\*+[ \t]+" (regexp-quote heading)
13248 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13249 nil t)
13250 (setq org-goto-start-pos (match-beginning 0))
13251 (when fastp
13252 (goto-char (point-max))
13253 (unless (bolp) (newline))
13254 (insert "* " heading "\n")
13255 (setq org-goto-start-pos (point-at-bol 0)))))
13257 ;; Ask the User for a location
13258 (if fastp
13259 (setq spos org-goto-start-pos
13260 exitcmd 'return)
13261 (setq spos (org-get-location (current-buffer) org-remember-help)
13262 exitcmd (cdr spos)
13263 spos (car spos)))
13264 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13265 ; not handle this note
13266 (goto-char spos)
13267 (cond ((org-on-heading-p t)
13268 (org-back-to-heading t)
13269 (setq level (funcall outline-level))
13270 (cond
13271 ((eq exitcmd 'return)
13272 ;; sublevel of current
13273 (setq org-remember-previous-location
13274 (cons (abbreviate-file-name file)
13275 (org-get-heading 'notags)))
13276 (if reversed
13277 (outline-next-heading)
13278 (org-end-of-subtree)
13279 (if (not (bolp))
13280 (if (looking-at "[ \t]*\n")
13281 (beginning-of-line 2)
13282 (end-of-line 1)
13283 (insert "\n"))))
13284 (org-paste-subtree (org-get-legal-level level 1) txt))
13285 ((eq exitcmd 'left)
13286 ;; before current
13287 (org-paste-subtree level txt))
13288 ((eq exitcmd 'right)
13289 ;; after current
13290 (org-end-of-subtree t)
13291 (org-paste-subtree level txt))
13292 (t (error "This should not happen"))))
13294 ((and (bobp) (not reversed))
13295 ;; Put it at the end, one level below level 1
13296 (save-restriction
13297 (widen)
13298 (goto-char (point-max))
13299 (if (not (bolp)) (newline))
13300 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13302 ((and (bobp) reversed)
13303 ;; Put it at the start, as level 1
13304 (save-restriction
13305 (widen)
13306 (goto-char (point-min))
13307 (re-search-forward "^\\*+ " nil t)
13308 (beginning-of-line 1)
13309 (org-paste-subtree 1 txt)))
13311 ;; Put it right there, with automatic level determined by
13312 ;; org-paste-subtree or from prefix arg
13313 (org-paste-subtree
13314 (if (numberp current-prefix-arg) current-prefix-arg)
13315 txt)))
13316 (when remember-save-after-remembering
13317 (save-buffer)
13318 (if (not visiting) (kill-buffer (current-buffer)))))))))
13319 t) ;; return t to indicate that we took care of this note.
13321 (defun org-get-org-file ()
13322 "Read a filename, with default directory `org-directory'."
13323 (let ((default (or org-default-notes-file remember-data-file)))
13324 (read-file-name (format "File name [%s]: " default)
13325 (file-name-as-directory org-directory)
13326 default)))
13328 (defun org-notes-order-reversed-p ()
13329 "Check if the current file should receive notes in reversed order."
13330 (cond
13331 ((not org-reverse-note-order) nil)
13332 ((eq t org-reverse-note-order) t)
13333 ((not (listp org-reverse-note-order)) nil)
13334 (t (catch 'exit
13335 (let ((all org-reverse-note-order)
13336 entry)
13337 (while (setq entry (pop all))
13338 (if (string-match (car entry) buffer-file-name)
13339 (throw 'exit (cdr entry))))
13340 nil)))))
13342 ;;;; Dynamic blocks
13344 (defun org-find-dblock (name)
13345 "Find the first dynamic block with name NAME in the buffer.
13346 If not found, stay at current position and return nil."
13347 (let (pos)
13348 (save-excursion
13349 (goto-char (point-min))
13350 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13351 nil t)
13352 (match-beginning 0))))
13353 (if pos (goto-char pos))
13354 pos))
13356 (defconst org-dblock-start-re
13357 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13358 "Matches the startline of a dynamic block, with parameters.")
13360 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13361 "Matches the end of a dyhamic block.")
13363 (defun org-create-dblock (plist)
13364 "Create a dynamic block section, with parameters taken from PLIST.
13365 PLIST must containe a :name entry which is used as name of the block."
13366 (unless (bolp) (newline))
13367 (let ((name (plist-get plist :name)))
13368 (insert "#+BEGIN: " name)
13369 (while plist
13370 (if (eq (car plist) :name)
13371 (setq plist (cddr plist))
13372 (insert " " (prin1-to-string (pop plist)))))
13373 (insert "\n\n#+END:\n")
13374 (beginning-of-line -2)))
13376 (defun org-prepare-dblock ()
13377 "Prepare dynamic block for refresh.
13378 This empties the block, puts the cursor at the insert position and returns
13379 the property list including an extra property :name with the block name."
13380 (unless (looking-at org-dblock-start-re)
13381 (error "Not at a dynamic block"))
13382 (let* ((begdel (1+ (match-end 0)))
13383 (name (org-no-properties (match-string 1)))
13384 (params (append (list :name name)
13385 (read (concat "(" (match-string 3) ")")))))
13386 (unless (re-search-forward org-dblock-end-re nil t)
13387 (error "Dynamic block not terminated"))
13388 (delete-region begdel (match-beginning 0))
13389 (goto-char begdel)
13390 (open-line 1)
13391 params))
13393 (defun org-map-dblocks (&optional command)
13394 "Apply COMMAND to all dynamic blocks in the current buffer.
13395 If COMMAND is not given, use `org-update-dblock'."
13396 (let ((cmd (or command 'org-update-dblock))
13397 pos)
13398 (save-excursion
13399 (goto-char (point-min))
13400 (while (re-search-forward org-dblock-start-re nil t)
13401 (goto-char (setq pos (match-beginning 0)))
13402 (condition-case nil
13403 (funcall cmd)
13404 (error (message "Error during update of dynamic block")))
13405 (goto-char pos)
13406 (unless (re-search-forward org-dblock-end-re nil t)
13407 (error "Dynamic block not terminated"))))))
13409 (defun org-dblock-update (&optional arg)
13410 "User command for updating dynamic blocks.
13411 Update the dynamic block at point. With prefix ARG, update all dynamic
13412 blocks in the buffer."
13413 (interactive "P")
13414 (if arg
13415 (org-update-all-dblocks)
13416 (or (looking-at org-dblock-start-re)
13417 (org-beginning-of-dblock))
13418 (org-update-dblock)))
13420 (defun org-update-dblock ()
13421 "Update the dynamic block at point
13422 This means to empty the block, parse for parameters and then call
13423 the correct writing function."
13424 (save-window-excursion
13425 (let* ((pos (point))
13426 (line (org-current-line))
13427 (params (org-prepare-dblock))
13428 (name (plist-get params :name))
13429 (cmd (intern (concat "org-dblock-write:" name))))
13430 (message "Updating dynamic block `%s' at line %d..." name line)
13431 (funcall cmd params)
13432 (message "Updating dynamic block `%s' at line %d...done" name line)
13433 (goto-char pos))))
13435 (defun org-beginning-of-dblock ()
13436 "Find the beginning of the dynamic block at point.
13437 Error if there is no scuh block at point."
13438 (let ((pos (point))
13439 beg)
13440 (end-of-line 1)
13441 (if (and (re-search-backward org-dblock-start-re nil t)
13442 (setq beg (match-beginning 0))
13443 (re-search-forward org-dblock-end-re nil t)
13444 (> (match-end 0) pos))
13445 (goto-char beg)
13446 (goto-char pos)
13447 (error "Not in a dynamic block"))))
13449 (defun org-update-all-dblocks ()
13450 "Update all dynamic blocks in the buffer.
13451 This function can be used in a hook."
13452 (when (org-mode-p)
13453 (org-map-dblocks 'org-update-dblock)))
13456 ;;;; Completion
13458 (defconst org-additional-option-like-keywords
13459 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
13460 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
13461 "BEGIN_EXAMPLE" "END_EXAMPLE"))
13463 (defun org-complete (&optional arg)
13464 "Perform completion on word at point.
13465 At the beginning of a headline, this completes TODO keywords as given in
13466 `org-todo-keywords'.
13467 If the current word is preceded by a backslash, completes the TeX symbols
13468 that are supported for HTML support.
13469 If the current word is preceded by \"#+\", completes special words for
13470 setting file options.
13471 In the line after \"#+STARTUP:, complete valid keywords.\"
13472 At all other locations, this simply calls the value of
13473 `org-completion-fallback-command'."
13474 (interactive "P")
13475 (org-without-partial-completion
13476 (catch 'exit
13477 (let* ((end (point))
13478 (beg1 (save-excursion
13479 (skip-chars-backward (org-re "[:alnum:]_@"))
13480 (point)))
13481 (beg (save-excursion
13482 (skip-chars-backward "a-zA-Z0-9_:$")
13483 (point)))
13484 (confirm (lambda (x) (stringp (car x))))
13485 (searchhead (equal (char-before beg) ?*))
13486 (tag (and (equal (char-before beg1) ?:)
13487 (equal (char-after (point-at-bol)) ?*)))
13488 (prop (and (equal (char-before beg1) ?:)
13489 (not (equal (char-after (point-at-bol)) ?*))))
13490 (texp (equal (char-before beg) ?\\))
13491 (link (equal (char-before beg) ?\[))
13492 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
13493 beg)
13494 "#+"))
13495 (startup (string-match "^#\\+STARTUP:.*"
13496 (buffer-substring (point-at-bol) (point))))
13497 (completion-ignore-case opt)
13498 (type nil)
13499 (tbl nil)
13500 (table (cond
13501 (opt
13502 (setq type :opt)
13503 (append
13504 (mapcar
13505 (lambda (x)
13506 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
13507 (cons (match-string 2 x) (match-string 1 x)))
13508 (org-split-string (org-get-current-options) "\n"))
13509 (mapcar 'list org-additional-option-like-keywords)))
13510 (startup
13511 (setq type :startup)
13512 org-startup-options)
13513 (link (append org-link-abbrev-alist-local
13514 org-link-abbrev-alist))
13515 (texp
13516 (setq type :tex)
13517 org-html-entities)
13518 ((string-match "\\`\\*+[ \t]+\\'"
13519 (buffer-substring (point-at-bol) beg))
13520 (setq type :todo)
13521 (mapcar 'list org-todo-keywords-1))
13522 (searchhead
13523 (setq type :searchhead)
13524 (save-excursion
13525 (goto-char (point-min))
13526 (while (re-search-forward org-todo-line-regexp nil t)
13527 (push (list
13528 (org-make-org-heading-search-string
13529 (match-string 3) t))
13530 tbl)))
13531 tbl)
13532 (tag (setq type :tag beg beg1)
13533 (or org-tag-alist (org-get-buffer-tags)))
13534 (prop (setq type :prop beg beg1)
13535 (mapcar 'list (org-buffer-property-keys)))
13536 (t (progn
13537 (call-interactively org-completion-fallback-command)
13538 (throw 'exit nil)))))
13539 (pattern (buffer-substring-no-properties beg end))
13540 (completion (try-completion pattern table confirm)))
13541 (cond ((eq completion t)
13542 (if (not (assoc (upcase pattern) table))
13543 (message "Already complete")
13544 (if (equal type :opt)
13545 (insert (substring (cdr (assoc (upcase pattern) table))
13546 (length pattern)))
13547 (if (memq type '(:tag :prop)) (insert ":")))))
13548 ((null completion)
13549 (message "Can't find completion for \"%s\"" pattern)
13550 (ding))
13551 ((not (string= pattern completion))
13552 (delete-region beg end)
13553 (if (string-match " +$" completion)
13554 (setq completion (replace-match "" t t completion)))
13555 (insert completion)
13556 (if (get-buffer-window "*Completions*")
13557 (delete-window (get-buffer-window "*Completions*")))
13558 (if (assoc completion table)
13559 (if (eq type :todo) (insert " ")
13560 (if (memq type '(:tag :prop)) (insert ":"))))
13561 (if (and (equal type :opt) (assoc completion table))
13562 (message "%s" (substitute-command-keys
13563 "Press \\[org-complete] again to insert example settings"))))
13565 (message "Making completion list...")
13566 (let ((list (sort (all-completions pattern table confirm)
13567 'string<)))
13568 (with-output-to-temp-buffer "*Completions*"
13569 (condition-case nil
13570 ;; Protection needed for XEmacs and emacs 21
13571 (display-completion-list list pattern)
13572 (error (display-completion-list list)))))
13573 (message "Making completion list...%s" "done")))))))
13575 ;;;; TODO, DEADLINE, Comments
13577 (defun org-toggle-comment ()
13578 "Change the COMMENT state of an entry."
13579 (interactive)
13580 (save-excursion
13581 (org-back-to-heading)
13582 (let (case-fold-search)
13583 (if (looking-at (concat outline-regexp
13584 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
13585 (replace-match "" t t nil 1)
13586 (if (looking-at outline-regexp)
13587 (progn
13588 (goto-char (match-end 0))
13589 (insert org-comment-string " ")))))))
13591 (defvar org-last-todo-state-is-todo nil
13592 "This is non-nil when the last TODO state change led to a TODO state.
13593 If the last change removed the TODO tag or switched to DONE, then
13594 this is nil.")
13596 (defvar org-setting-tags nil) ; dynamically skiped
13598 ;; FIXME: better place
13599 (defun org-property-or-variable-value (var &optional inherit)
13600 "Check if there is a property fixing the value of VAR.
13601 If yes, return this value. If not, return the current value of the variable."
13602 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13603 (if (and prop (stringp prop) (string-match "\\S-" prop))
13604 (read prop)
13605 (symbol-value var))))
13607 (defun org-parse-local-options (string var)
13608 "Parse STRING for startup setting relevant for variable VAR."
13609 (let ((rtn (symbol-value var))
13610 e opts)
13611 (save-match-data
13612 (if (or (not string) (not (string-match "\\S-" string)))
13614 (setq opts (delq nil (mapcar (lambda (x)
13615 (setq e (assoc x org-startup-options))
13616 (if (eq (nth 1 e) var) e nil))
13617 (org-split-string string "[ \t]+"))))
13618 (if (not opts)
13620 (setq rtn nil)
13621 (while (setq e (pop opts))
13622 (if (not (nth 3 e))
13623 (setq rtn (nth 2 e))
13624 (if (not (listp rtn)) (setq rtn nil))
13625 (push (nth 2 e) rtn)))
13626 rtn)))))
13628 (defvar org-blocker-hook nil
13629 "Hook for functions that are allowed to block a state change.
13631 Each function gets as its single argument a property list, see
13632 `org-trigger-hook' for more information about this list.
13634 If any of the functions in this hook returns nil, the state change
13635 is blocked.")
13637 (defvar org-trigger-hook nil
13638 "Hook for functions that are triggered by a state change.
13640 Each function gets as its single argument a property list with at least
13641 the following elements:
13643 (:type type-of-change :position pos-at-entry-start
13644 :from old-state :to new-state)
13646 Depending on the type, more properties may be present.
13648 This mechanism is currently implemented for:
13650 TODO state changes
13651 ------------------
13652 :type todo-state-change
13653 :from previous state (keyword as a string), or nil
13654 :to new state (keyword as a string), or nil")
13657 (defun org-todo (&optional arg)
13658 "Change the TODO state of an item.
13659 The state of an item is given by a keyword at the start of the heading,
13660 like
13661 *** TODO Write paper
13662 *** DONE Call mom
13664 The different keywords are specified in the variable `org-todo-keywords'.
13665 By default the available states are \"TODO\" and \"DONE\".
13666 So for this example: when the item starts with TODO, it is changed to DONE.
13667 When it starts with DONE, the DONE is removed. And when neither TODO nor
13668 DONE are present, add TODO at the beginning of the heading.
13670 With C-u prefix arg, use completion to determine the new state.
13671 With numeric prefix arg, switch to that state.
13673 For calling through lisp, arg is also interpreted in the following way:
13674 'none -> empty state
13675 \"\"(empty string) -> switch to empty state
13676 'done -> switch to DONE
13677 'nextset -> switch to the next set of keywords
13678 'previousset -> switch to the previous set of keywords
13679 \"WAITING\" -> switch to the specified keyword, but only if it
13680 really is a member of `org-todo-keywords'."
13681 (interactive "P")
13682 (save-excursion
13683 (catch 'exit
13684 (org-back-to-heading)
13685 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
13686 (or (looking-at (concat " +" org-todo-regexp " *"))
13687 (looking-at " *"))
13688 (let* ((match-data (match-data))
13689 (startpos (point-at-bol))
13690 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
13691 (org-log-done (org-parse-local-options logging 'org-log-done))
13692 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
13693 (this (match-string 1))
13694 (hl-pos (match-beginning 0))
13695 (head (org-get-todo-sequence-head this))
13696 (ass (assoc head org-todo-kwd-alist))
13697 (interpret (nth 1 ass))
13698 (done-word (nth 3 ass))
13699 (final-done-word (nth 4 ass))
13700 (last-state (or this ""))
13701 (completion-ignore-case t)
13702 (member (member this org-todo-keywords-1))
13703 (tail (cdr member))
13704 (state (cond
13705 ((and org-todo-key-trigger
13706 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
13707 (and (not arg) org-use-fast-todo-selection
13708 (not (eq org-use-fast-todo-selection 'prefix)))))
13709 ;; Use fast selection
13710 (org-fast-todo-selection))
13711 ((and (equal arg '(4))
13712 (or (not org-use-fast-todo-selection)
13713 (not org-todo-key-trigger)))
13714 ;; Read a state with completion
13715 (completing-read "State: " (mapcar (lambda(x) (list x))
13716 org-todo-keywords-1)
13717 nil t))
13718 ((eq arg 'right)
13719 (if this
13720 (if tail (car tail) nil)
13721 (car org-todo-keywords-1)))
13722 ((eq arg 'left)
13723 (if (equal member org-todo-keywords-1)
13725 (if this
13726 (nth (- (length org-todo-keywords-1) (length tail) 2)
13727 org-todo-keywords-1)
13728 (org-last org-todo-keywords-1))))
13729 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
13730 (setq arg nil))) ; hack to fall back to cycling
13731 (arg
13732 ;; user or caller requests a specific state
13733 (cond
13734 ((equal arg "") nil)
13735 ((eq arg 'none) nil)
13736 ((eq arg 'done) (or done-word (car org-done-keywords)))
13737 ((eq arg 'nextset)
13738 (or (car (cdr (member head org-todo-heads)))
13739 (car org-todo-heads)))
13740 ((eq arg 'previousset)
13741 (let ((org-todo-heads (reverse org-todo-heads)))
13742 (or (car (cdr (member head org-todo-heads)))
13743 (car org-todo-heads))))
13744 ((car (member arg org-todo-keywords-1)))
13745 ((nth (1- (prefix-numeric-value arg))
13746 org-todo-keywords-1))))
13747 ((null member) (or head (car org-todo-keywords-1)))
13748 ((equal this final-done-word) nil) ;; -> make empty
13749 ((null tail) nil) ;; -> first entry
13750 ((eq interpret 'sequence)
13751 (car tail))
13752 ((memq interpret '(type priority))
13753 (if (eq this-command last-command)
13754 (car tail)
13755 (if (> (length tail) 0)
13756 (or done-word (car org-done-keywords))
13757 nil)))
13758 (t nil)))
13759 (next (if state (concat " " state " ") " "))
13760 (change-plist (list :type 'todo-state-change :from this :to state
13761 :position startpos))
13762 dostates)
13763 (when org-blocker-hook
13764 (unless (save-excursion
13765 (save-match-data
13766 (run-hook-with-args-until-failure
13767 'org-blocker-hook change-plist)))
13768 (if (interactive-p)
13769 (error "TODO state change from %s to %s blocked" this state)
13770 ;; fail silently
13771 (message "TODO state change from %s to %s blocked" this state)
13772 (throw 'exit nil))))
13773 (store-match-data match-data)
13774 (replace-match next t t)
13775 (unless (pos-visible-in-window-p hl-pos)
13776 (message "TODO state changed to %s" (org-trim next)))
13777 (unless head
13778 (setq head (org-get-todo-sequence-head state)
13779 ass (assoc head org-todo-kwd-alist)
13780 interpret (nth 1 ass)
13781 done-word (nth 3 ass)
13782 final-done-word (nth 4 ass)))
13783 (when (memq arg '(nextset previousset))
13784 (message "Keyword-Set %d/%d: %s"
13785 (- (length org-todo-sets) -1
13786 (length (memq (assoc state org-todo-sets) org-todo-sets)))
13787 (length org-todo-sets)
13788 (mapconcat 'identity (assoc state org-todo-sets) " ")))
13789 (setq org-last-todo-state-is-todo
13790 (not (member state org-done-keywords)))
13791 (when (and org-log-done (not (memq arg '(nextset previousset))))
13792 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
13793 (or (not org-todo-log-states)
13794 (member state org-todo-log-states))))
13796 (cond
13797 ((and state (member state org-not-done-keywords)
13798 (not (member this org-not-done-keywords)))
13799 ;; This is now a todo state and was not one before
13800 ;; Remove any CLOSED timestamp, and possibly log the state change
13801 (org-add-planning-info nil nil 'closed)
13802 (and dostates (org-add-log-maybe 'state state 'findpos)))
13803 ((and state dostates)
13804 ;; This is a non-nil state, and we need to log it
13805 (org-add-log-maybe 'state state 'findpos))
13806 ((and (member state org-done-keywords)
13807 (not (member this org-done-keywords)))
13808 ;; It is now done, and it was not done before
13809 (org-add-planning-info 'closed (org-current-time))
13810 (org-add-log-maybe 'done state 'findpos))))
13811 ;; Fixup tag positioning
13812 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
13813 (run-hooks 'org-after-todo-state-change-hook)
13814 (and (member state org-done-keywords) (org-auto-repeat-maybe))
13815 (if (and arg (not (member state org-done-keywords)))
13816 (setq head (org-get-todo-sequence-head state)))
13817 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
13818 ;; Fixup cursor location if close to the keyword
13819 (if (and (outline-on-heading-p)
13820 (not (bolp))
13821 (save-excursion (beginning-of-line 1)
13822 (looking-at org-todo-line-regexp))
13823 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
13824 (progn
13825 (goto-char (or (match-end 2) (match-end 1)))
13826 (just-one-space)))
13827 (when org-trigger-hook
13828 (save-excursion
13829 (run-hook-with-args 'org-trigger-hook change-plist)))))))
13831 (defun org-get-todo-sequence-head (kwd)
13832 "Return the head of the TODO sequence to which KWD belongs.
13833 If KWD is not set, check if there is a text property remembering the
13834 right sequence."
13835 (let (p)
13836 (cond
13837 ((not kwd)
13838 (or (get-text-property (point-at-bol) 'org-todo-head)
13839 (progn
13840 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13841 nil (point-at-eol)))
13842 (get-text-property p 'org-todo-head))))
13843 ((not (member kwd org-todo-keywords-1))
13844 (car org-todo-keywords-1))
13845 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13847 (defun org-fast-todo-selection ()
13848 "Fast TODO keyword selection with single keys.
13849 Returns the new TODO keyword, or nil if no state change should occur."
13850 (let* ((fulltable org-todo-key-alist)
13851 (done-keywords org-done-keywords) ;; needed for the faces.
13852 (maxlen (apply 'max (mapcar
13853 (lambda (x)
13854 (if (stringp (car x)) (string-width (car x)) 0))
13855 fulltable)))
13856 (expert nil)
13857 (fwidth (+ maxlen 3 1 3))
13858 (ncol (/ (- (window-width) 4) fwidth))
13859 tg cnt e c tbl
13860 groups ingroup)
13861 (save-window-excursion
13862 (if expert
13863 (set-buffer (get-buffer-create " *Org todo*"))
13864 ; (delete-other-windows)
13865 ; (split-window-vertically)
13866 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13867 (erase-buffer)
13868 (org-set-local 'org-done-keywords done-keywords)
13869 (setq tbl fulltable cnt 0)
13870 (while (setq e (pop tbl))
13871 (cond
13872 ((equal e '(:startgroup))
13873 (push '() groups) (setq ingroup t)
13874 (when (not (= cnt 0))
13875 (setq cnt 0)
13876 (insert "\n"))
13877 (insert "{ "))
13878 ((equal e '(:endgroup))
13879 (setq ingroup nil cnt 0)
13880 (insert "}\n"))
13882 (setq tg (car e) c (cdr e))
13883 (if ingroup (push tg (car groups)))
13884 (setq tg (org-add-props tg nil 'face
13885 (org-get-todo-face tg)))
13886 (if (and (= cnt 0) (not ingroup)) (insert " "))
13887 (insert "[" c "] " tg (make-string
13888 (- fwidth 4 (length tg)) ?\ ))
13889 (when (= (setq cnt (1+ cnt)) ncol)
13890 (insert "\n")
13891 (if ingroup (insert " "))
13892 (setq cnt 0)))))
13893 (insert "\n")
13894 (goto-char (point-min))
13895 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13896 (fit-window-to-buffer))
13897 (message "[a-z..]:Set [SPC]:clear")
13898 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13899 (cond
13900 ((or (= c ?\C-g)
13901 (and (= c ?q) (not (rassoc c fulltable))))
13902 (setq quit-flag t))
13903 ((= c ?\ ) nil)
13904 ((setq e (rassoc c fulltable) tg (car e))
13906 (t (setq quit-flag t))))))
13908 (defun org-get-repeat ()
13909 "Check if tere is a deadline/schedule with repeater in this entry."
13910 (save-match-data
13911 (save-excursion
13912 (org-back-to-heading t)
13913 (if (re-search-forward
13914 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
13915 (match-string 1)))))
13917 (defvar org-last-changed-timestamp)
13918 (defvar org-log-post-message)
13919 (defun org-auto-repeat-maybe ()
13920 "Check if the current headline contains a repeated deadline/schedule.
13921 If yes, set TODO state back to what it was and change the base date
13922 of repeating deadline/scheduled time stamps to new date.
13923 This function should be run in the `org-after-todo-state-change-hook'."
13924 ;; last-state is dynamically scoped into this function
13925 (let* ((repeat (org-get-repeat))
13926 (aa (assoc last-state org-todo-kwd-alist))
13927 (interpret (nth 1 aa))
13928 (head (nth 2 aa))
13929 (done-word (nth 3 aa))
13930 (whata '(("d" . day) ("m" . month) ("y" . year)))
13931 (msg "Entry repeats: ")
13932 (org-log-done)
13933 re type n what ts)
13934 (when repeat
13935 (org-todo (if (eq interpret 'type) last-state head))
13936 (when (and org-log-repeat
13937 (not (memq 'org-add-log-note
13938 (default-value 'post-command-hook))))
13939 ;; Make sure a note is taken
13940 (let ((org-log-done '(done)))
13941 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
13942 'findpos)))
13943 (org-back-to-heading t)
13944 (org-add-planning-info nil nil 'closed)
13945 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13946 org-deadline-time-regexp "\\)"))
13947 (while (re-search-forward
13948 re (save-excursion (outline-next-heading) (point)) t)
13949 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
13950 ts (match-string (if (match-end 2) 2 4)))
13951 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
13952 (setq n (string-to-number (match-string 1 ts))
13953 what (match-string 2 ts))
13954 (if (equal what "w") (setq n (* n 7) what "d"))
13955 (org-timestamp-change n (cdr (assoc what whata))))
13956 (setq msg (concat msg type org-last-changed-timestamp " ")))
13957 (setq org-log-post-message msg)
13958 (message msg))))
13960 (defun org-show-todo-tree (arg)
13961 "Make a compact tree which shows all headlines marked with TODO.
13962 The tree will show the lines where the regexp matches, and all higher
13963 headlines above the match.
13964 With \\[universal-argument] prefix, also show the DONE entries.
13965 With a numeric prefix N, construct a sparse tree for the Nth element
13966 of `org-todo-keywords-1'."
13967 (interactive "P")
13968 (let ((case-fold-search nil)
13969 (kwd-re
13970 (cond ((null arg) org-not-done-regexp)
13971 ((equal arg '(4))
13972 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
13973 (mapcar 'list org-todo-keywords-1))))
13974 (concat "\\("
13975 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13976 "\\)\\>")))
13977 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13978 (regexp-quote (nth (1- (prefix-numeric-value arg))
13979 org-todo-keywords-1)))
13980 (t (error "Invalid prefix argument: %s" arg)))))
13981 (message "%d TODO entries found"
13982 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
13984 (defun org-deadline (&optional remove)
13985 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13986 With argument REMOVE, remove any deadline from the item."
13987 (interactive "P")
13988 (if remove
13989 (progn
13990 (org-add-planning-info nil nil 'deadline)
13991 (message "Item no longer has a deadline."))
13992 (org-add-planning-info 'deadline nil 'closed)))
13994 (defun org-schedule (&optional remove)
13995 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13996 With argument REMOVE, remove any scheduling date from the item."
13997 (interactive "P")
13998 (if remove
13999 (progn
14000 (org-add-planning-info nil nil 'scheduled)
14001 (message "Item is no longer scheduled."))
14002 (org-add-planning-info 'scheduled nil 'closed)))
14004 (defun org-add-planning-info (what &optional time &rest remove)
14005 "Insert new timestamp with keyword in the line directly after the headline.
14006 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14007 If non is given, the user is prompted for a date.
14008 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14009 be removed."
14010 (interactive)
14011 (let (org-time-was-given org-end-time-was-given)
14012 (when what (setq time (or time (org-read-date nil 'to-time))))
14013 (when (and org-insert-labeled-timestamps-at-point
14014 (member what '(scheduled deadline)))
14015 (insert
14016 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14017 (org-insert-time-stamp time org-time-was-given
14018 nil nil nil (list org-end-time-was-given))
14019 (setq what nil))
14020 (save-excursion
14021 (save-restriction
14022 (let (col list elt ts buffer-invisibility-spec)
14023 (org-back-to-heading t)
14024 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14025 (goto-char (match-end 1))
14026 (setq col (current-column))
14027 (goto-char (match-end 0))
14028 (if (eobp) (insert "\n") (forward-char 1))
14029 (if (and (not (looking-at outline-regexp))
14030 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14031 "[^\r\n]*"))
14032 (not (equal (match-string 1) org-clock-string)))
14033 (narrow-to-region (match-beginning 0) (match-end 0))
14034 (insert-before-markers "\n")
14035 (backward-char 1)
14036 (narrow-to-region (point) (point))
14037 (indent-to-column col))
14038 ;; Check if we have to remove something.
14039 (setq list (cons what remove))
14040 (while list
14041 (setq elt (pop list))
14042 (goto-char (point-min))
14043 (when (or (and (eq elt 'scheduled)
14044 (re-search-forward org-scheduled-time-regexp nil t))
14045 (and (eq elt 'deadline)
14046 (re-search-forward org-deadline-time-regexp nil t))
14047 (and (eq elt 'closed)
14048 (re-search-forward org-closed-time-regexp nil t)))
14049 (replace-match "")
14050 (if (looking-at "--+<[^>]+>") (replace-match ""))
14051 (if (looking-at " +") (replace-match ""))))
14052 (goto-char (point-max))
14053 (when what
14054 (insert
14055 (if (not (equal (char-before) ?\ )) " " "")
14056 (cond ((eq what 'scheduled) org-scheduled-string)
14057 ((eq what 'deadline) org-deadline-string)
14058 ((eq what 'closed) org-closed-string))
14059 " ")
14060 (setq ts (org-insert-time-stamp
14061 time
14062 (or org-time-was-given
14063 (and (eq what 'closed) org-log-done-with-time))
14064 (eq what 'closed)
14065 nil nil (list org-end-time-was-given)))
14066 (end-of-line 1))
14067 (goto-char (point-min))
14068 (widen)
14069 (if (looking-at "[ \t]+\r?\n")
14070 (replace-match ""))
14071 ts)))))
14073 (defvar org-log-note-marker (make-marker))
14074 (defvar org-log-note-purpose nil)
14075 (defvar org-log-note-state nil)
14076 (defvar org-log-note-window-configuration nil)
14077 (defvar org-log-note-return-to (make-marker))
14078 (defvar org-log-post-message nil
14079 "Message to be displayed after a log note has been stored.
14080 The auto-repeater uses this.")
14082 (defun org-add-log-maybe (&optional purpose state findpos)
14083 "Set up the post command hook to take a note."
14084 (save-excursion
14085 (when (and (listp org-log-done)
14086 (memq purpose org-log-done))
14087 (when findpos
14088 (org-back-to-heading t)
14089 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14090 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14091 "[^\r\n]*\\)?"))
14092 (goto-char (match-end 0))
14093 (unless org-log-states-order-reversed
14094 (and (= (char-after) ?\n) (forward-char 1))
14095 (org-skip-over-state-notes)
14096 (skip-chars-backward " \t\n\r")))
14097 (move-marker org-log-note-marker (point))
14098 (setq org-log-note-purpose purpose)
14099 (setq org-log-note-state state)
14100 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14102 (defun org-skip-over-state-notes ()
14103 "Skip past the list of State notes in an entry."
14104 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14105 (while (looking-at "[ \t]*- State")
14106 (condition-case nil
14107 (org-next-item)
14108 (error (org-end-of-item)))))
14110 (defun org-add-log-note (&optional purpose)
14111 "Pop up a window for taking a note, and add this note later at point."
14112 (remove-hook 'post-command-hook 'org-add-log-note)
14113 (setq org-log-note-window-configuration (current-window-configuration))
14114 (delete-other-windows)
14115 (move-marker org-log-note-return-to (point))
14116 (switch-to-buffer (marker-buffer org-log-note-marker))
14117 (goto-char org-log-note-marker)
14118 (org-switch-to-buffer-other-window "*Org Note*")
14119 (erase-buffer)
14120 (let ((org-inhibit-startup t)) (org-mode))
14121 (insert (format "# Insert note for %s.
14122 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14123 (cond
14124 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14125 ((eq org-log-note-purpose 'done) "closed todo item")
14126 ((eq org-log-note-purpose 'state)
14127 (format "state change to \"%s\"" org-log-note-state))
14128 (t (error "This should not happen")))))
14129 (org-set-local 'org-finish-function 'org-store-log-note))
14131 (defun org-store-log-note ()
14132 "Finish taking a log note, and insert it to where it belongs."
14133 (let ((txt (buffer-string))
14134 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14135 lines ind)
14136 (kill-buffer (current-buffer))
14137 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14138 (setq txt (replace-match "" t t txt)))
14139 (if (string-match "\\s-+\\'" txt)
14140 (setq txt (replace-match "" t t txt)))
14141 (setq lines (org-split-string txt "\n"))
14142 (when (and note (string-match "\\S-" note))
14143 (setq note
14144 (org-replace-escapes
14145 note
14146 (list (cons "%u" (user-login-name))
14147 (cons "%U" user-full-name)
14148 (cons "%t" (format-time-string
14149 (org-time-stamp-format 'long 'inactive)
14150 (current-time)))
14151 (cons "%s" (if org-log-note-state
14152 (concat "\"" org-log-note-state "\"")
14153 "")))))
14154 (if lines (setq note (concat note " \\\\")))
14155 (push note lines))
14156 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14157 (when lines
14158 (save-excursion
14159 (set-buffer (marker-buffer org-log-note-marker))
14160 (save-excursion
14161 (goto-char org-log-note-marker)
14162 (move-marker org-log-note-marker nil)
14163 (end-of-line 1)
14164 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14165 (indent-relative nil)
14166 (insert "- " (pop lines))
14167 (org-indent-line-function)
14168 (beginning-of-line 1)
14169 (looking-at "[ \t]*")
14170 (setq ind (concat (match-string 0) " "))
14171 (end-of-line 1)
14172 (while lines (insert "\n" ind (pop lines)))))))
14173 (set-window-configuration org-log-note-window-configuration)
14174 (with-current-buffer (marker-buffer org-log-note-return-to)
14175 (goto-char org-log-note-return-to))
14176 (move-marker org-log-note-return-to nil)
14177 (and org-log-post-message (message org-log-post-message)))
14179 ;; FIXME: what else would be useful?
14180 ;; - priority
14181 ;; - date
14183 (defun org-sparse-tree (&optional arg)
14184 "Create a sparse tree, prompt for the details.
14185 This command can create sparse trees. You first need to select the type
14186 of match used to create the tree:
14188 t Show entries with a specific TODO keyword.
14189 T Show entries selected by a tags match.
14190 p Enter a property name and its value (both with completion on existing
14191 names/values) and show entries with that property.
14192 r Show entries matching a regular expression"
14193 (interactive "P")
14194 (let (ans kwd value)
14195 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines")
14196 (setq ans (read-char-exclusive))
14197 (cond
14198 ((equal ans ?d)
14199 (call-interactively 'org-check-deadlines))
14200 ((equal ans ?t)
14201 (org-show-todo-tree '(4)))
14202 ((equal ans ?T)
14203 (call-interactively 'org-tags-sparse-tree))
14204 ((member ans '(?p ?P))
14205 (setq kwd (completing-read "Property: "
14206 (mapcar 'list (org-buffer-property-keys))))
14207 (setq value (completing-read "Value: "
14208 (mapcar 'list (org-property-values kwd))))
14209 (unless (string-match "\\`{.*}\\'" value)
14210 (setq value (concat "\"" value "\"")))
14211 (org-tags-sparse-tree arg (concat kwd "=" value)))
14212 ((member ans '(?r ?R ?/))
14213 (call-interactively 'org-occur))
14214 (t (error "No such sparse tree command \"%c\"" ans)))))
14216 (defvar org-occur-highlights nil)
14217 (make-variable-buffer-local 'org-occur-highlights)
14219 (defun org-occur (regexp &optional keep-previous callback)
14220 "Make a compact tree which shows all matches of REGEXP.
14221 The tree will show the lines where the regexp matches, and all higher
14222 headlines above the match. It will also show the heading after the match,
14223 to make sure editing the matching entry is easy.
14224 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14225 call to `org-occur' will be kept, to allow stacking of calls to this
14226 command.
14227 If CALLBACK is non-nil, it is a function which is called to confirm
14228 that the match should indeed be shown."
14229 (interactive "sRegexp: \nP")
14230 (or keep-previous (org-remove-occur-highlights nil nil t))
14231 (let ((cnt 0))
14232 (save-excursion
14233 (goto-char (point-min))
14234 (if (or (not keep-previous) ; do not want to keep
14235 (not org-occur-highlights)) ; no previous matches
14236 ;; hide everything
14237 (org-overview))
14238 (while (re-search-forward regexp nil t)
14239 (when (or (not callback)
14240 (save-match-data (funcall callback)))
14241 (setq cnt (1+ cnt))
14242 (when org-highlight-sparse-tree-matches
14243 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14244 (org-show-context 'occur-tree))))
14245 (when org-remove-highlights-with-change
14246 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14247 nil 'local))
14248 (unless org-sparse-tree-open-archived-trees
14249 (org-hide-archived-subtrees (point-min) (point-max)))
14250 (run-hooks 'org-occur-hook)
14251 (if (interactive-p)
14252 (message "%d match(es) for regexp %s" cnt regexp))
14253 cnt))
14255 (defun org-show-context (&optional key)
14256 "Make sure point and context and visible.
14257 How much context is shown depends upon the variables
14258 `org-show-hierarchy-above', `org-show-following-heading'. and
14259 `org-show-siblings'."
14260 (let ((heading-p (org-on-heading-p t))
14261 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14262 (following-p (org-get-alist-option org-show-following-heading key))
14263 (entry-p (org-get-alist-option org-show-entry-below key))
14264 (siblings-p (org-get-alist-option org-show-siblings key)))
14265 (catch 'exit
14266 ;; Show heading or entry text
14267 (if (and heading-p (not entry-p))
14268 (org-flag-heading nil) ; only show the heading
14269 (and (or entry-p (org-invisible-p) (org-invisible-p2))
14270 (org-show-hidden-entry))) ; show entire entry
14271 (when following-p
14272 ;; Show next sibling, or heading below text
14273 (save-excursion
14274 (and (if heading-p (org-goto-sibling) (outline-next-heading))
14275 (org-flag-heading nil))))
14276 (when siblings-p (org-show-siblings))
14277 (when hierarchy-p
14278 ;; show all higher headings, possibly with siblings
14279 (save-excursion
14280 (while (and (condition-case nil
14281 (progn (org-up-heading-all 1) t)
14282 (error nil))
14283 (not (bobp)))
14284 (org-flag-heading nil)
14285 (when siblings-p (org-show-siblings))))))))
14287 (defun org-reveal (&optional siblings)
14288 "Show current entry, hierarchy above it, and the following headline.
14289 This can be used to show a consistent set of context around locations
14290 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14291 not t for the search context.
14293 With optional argument SIBLINGS, on each level of the hierarchy all
14294 siblings are shown. This repairs the tree structure to what it would
14295 look like when opened with hierarchical calls to `org-cycle'."
14296 (interactive "P")
14297 (let ((org-show-hierarchy-above t)
14298 (org-show-following-heading t)
14299 (org-show-siblings (if siblings t org-show-siblings)))
14300 (org-show-context nil)))
14302 (defun org-highlight-new-match (beg end)
14303 "Highlight from BEG to END and mark the highlight is an occur headline."
14304 (let ((ov (org-make-overlay beg end)))
14305 (org-overlay-put ov 'face 'secondary-selection)
14306 (push ov org-occur-highlights)))
14308 (defun org-remove-occur-highlights (&optional beg end noremove)
14309 "Remove the occur highlights from the buffer.
14310 BEG and END are ignored. If NOREMOVE is nil, remove this function
14311 from the `before-change-functions' in the current buffer."
14312 (interactive)
14313 (unless org-inhibit-highlight-removal
14314 (mapc 'org-delete-overlay org-occur-highlights)
14315 (setq org-occur-highlights nil)
14316 (unless noremove
14317 (remove-hook 'before-change-functions
14318 'org-remove-occur-highlights 'local))))
14320 ;;;; Priorities
14322 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14323 "Regular expression matching the priority indicator.")
14325 (defvar org-remove-priority-next-time nil)
14327 (defun org-priority-up ()
14328 "Increase the priority of the current item."
14329 (interactive)
14330 (org-priority 'up))
14332 (defun org-priority-down ()
14333 "Decrease the priority of the current item."
14334 (interactive)
14335 (org-priority 'down))
14337 (defun org-priority (&optional action)
14338 "Change the priority of an item by ARG.
14339 ACTION can be `set', `up', `down', or a character."
14340 (interactive)
14341 (setq action (or action 'set))
14342 (let (current new news have remove)
14343 (save-excursion
14344 (org-back-to-heading)
14345 (if (looking-at org-priority-regexp)
14346 (setq current (string-to-char (match-string 2))
14347 have t)
14348 (setq current org-default-priority))
14349 (cond
14350 ((or (eq action 'set) (integerp action))
14351 (if (integerp action)
14352 (setq new action)
14353 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14354 (setq new (read-char-exclusive)))
14355 (if (and (= (upcase org-highest-priority) org-highest-priority)
14356 (= (upcase org-lowest-priority) org-lowest-priority))
14357 (setq new (upcase new)))
14358 (cond ((equal new ?\ ) (setq remove t))
14359 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14360 (error "Priority must be between `%c' and `%c'"
14361 org-highest-priority org-lowest-priority))))
14362 ((eq action 'up)
14363 (if (and (not have) (eq last-command this-command))
14364 (setq new org-lowest-priority)
14365 (setq new (if (and org-priority-start-cycle-with-default (not have))
14366 org-default-priority (1- current)))))
14367 ((eq action 'down)
14368 (if (and (not have) (eq last-command this-command))
14369 (setq new org-highest-priority)
14370 (setq new (if (and org-priority-start-cycle-with-default (not have))
14371 org-default-priority (1+ current)))))
14372 (t (error "Invalid action")))
14373 (if (or (< (upcase new) org-highest-priority)
14374 (> (upcase new) org-lowest-priority))
14375 (setq remove t))
14376 (setq news (format "%c" new))
14377 (if have
14378 (if remove
14379 (replace-match "" t t nil 1)
14380 (replace-match news t t nil 2))
14381 (if remove
14382 (error "No priority cookie found in line")
14383 (looking-at org-todo-line-regexp)
14384 (if (match-end 2)
14385 (progn
14386 (goto-char (match-end 2))
14387 (insert " [#" news "]"))
14388 (goto-char (match-beginning 3))
14389 (insert "[#" news "] ")))))
14390 (org-preserve-lc (org-set-tags nil 'align))
14391 (if remove
14392 (message "Priority removed")
14393 (message "Priority of current item set to %s" news))))
14396 (defun org-get-priority (s)
14397 "Find priority cookie and return priority."
14398 (save-match-data
14399 (if (not (string-match org-priority-regexp s))
14400 (* 1000 (- org-lowest-priority org-default-priority))
14401 (* 1000 (- org-lowest-priority
14402 (string-to-char (match-string 2 s)))))))
14404 ;;;; Tags
14406 (defun org-scan-tags (action matcher &optional todo-only)
14407 "Scan headline tags with inheritance and produce output ACTION.
14408 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
14409 evaluated, testing if a given set of tags qualifies a headline for
14410 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
14411 are included in the output."
14412 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
14413 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14414 (org-re
14415 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
14416 (props (list 'face nil
14417 'done-face 'org-done
14418 'undone-face nil
14419 'mouse-face 'highlight
14420 'org-not-done-regexp org-not-done-regexp
14421 'org-todo-regexp org-todo-regexp
14422 'keymap org-agenda-keymap
14423 'help-echo
14424 (format "mouse-2 or RET jump to org file %s"
14425 (abbreviate-file-name
14426 (or (buffer-file-name (buffer-base-buffer))
14427 (buffer-name (buffer-base-buffer)))))))
14428 (case-fold-search nil)
14429 lspos
14430 tags tags-list tags-alist (llast 0) rtn level category i txt
14431 todo marker entry priority)
14432 (save-excursion
14433 (goto-char (point-min))
14434 (when (eq action 'sparse-tree)
14435 (org-overview)
14436 (org-remove-occur-highlights))
14437 (while (re-search-forward re nil t)
14438 (catch :skip
14439 (setq todo (if (match-end 1) (match-string 2))
14440 tags (if (match-end 4) (match-string 4)))
14441 (goto-char (setq lspos (1+ (match-beginning 0))))
14442 (setq level (org-reduced-level (funcall outline-level))
14443 category (org-get-category))
14444 (setq i llast llast level)
14445 ;; remove tag lists from same and sublevels
14446 (while (>= i level)
14447 (when (setq entry (assoc i tags-alist))
14448 (setq tags-alist (delete entry tags-alist)))
14449 (setq i (1- i)))
14450 ;; add the nex tags
14451 (when tags
14452 (setq tags (mapcar 'downcase (org-split-string tags ":"))
14453 tags-alist
14454 (cons (cons level tags) tags-alist)))
14455 ;; compile tags for current headline
14456 (setq tags-list
14457 (if org-use-tag-inheritance
14458 (apply 'append (mapcar 'cdr tags-alist))
14459 tags))
14460 (when (and (or (not todo-only) (member todo org-not-done-keywords))
14461 (eval matcher)
14462 (or (not org-agenda-skip-archived-trees)
14463 (not (member org-archive-tag tags-list))))
14464 (and (eq action 'agenda) (org-agenda-skip))
14465 ;; list this headline
14467 (if (eq action 'sparse-tree)
14468 (progn
14469 (and org-highlight-sparse-tree-matches
14470 (org-get-heading) (match-end 0)
14471 (org-highlight-new-match
14472 (match-beginning 0) (match-beginning 1)))
14473 (org-show-context 'tags-tree))
14474 (setq txt (org-format-agenda-item
14476 (concat
14477 (if org-tags-match-list-sublevels
14478 (make-string (1- level) ?.) "")
14479 (org-get-heading))
14480 category tags-list)
14481 priority (org-get-priority txt))
14482 (goto-char lspos)
14483 (setq marker (org-agenda-new-marker))
14484 (org-add-props txt props
14485 'org-marker marker 'org-hd-marker marker 'org-category category
14486 'priority priority 'type "tagsmatch")
14487 (push txt rtn))
14488 ;; if we are to skip sublevels, jump to end of subtree
14489 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
14490 (when (and (eq action 'sparse-tree)
14491 (not org-sparse-tree-open-archived-trees))
14492 (org-hide-archived-subtrees (point-min) (point-max)))
14493 (nreverse rtn)))
14495 (defvar todo-only) ;; dynamically scoped
14497 (defun org-tags-sparse-tree (&optional todo-only match)
14498 "Create a sparse tree according to tags string MATCH.
14499 MATCH can contain positive and negative selection of tags, like
14500 \"+WORK+URGENT-WITHBOSS\".
14501 If optional argument TODO_ONLY is non-nil, only select lines that are
14502 also TODO lines."
14503 (interactive "P")
14504 (org-prepare-agenda-buffers (list (current-buffer)))
14505 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14507 (defvar org-cached-props nil)
14508 (defun org-cached-entry-get (pom property)
14509 (if (or (eq t org-use-property-inheritance)
14510 (member property org-use-property-inheritance))
14511 ;; Caching is not possible, check it directly
14512 (org-entry-get pom property 'inherit)
14513 ;; Get all properties, so that we can do complicated checks easily
14514 (cdr (assoc property (or org-cached-props
14515 (setq org-cached-props
14516 (org-entry-properties pom)))))))
14518 (defun org-global-tags-completion-table (&optional files)
14519 "Return the list of all tags in all agenda buffer/files."
14520 (save-excursion
14521 (org-uniquify
14522 (apply 'append
14523 (mapcar
14524 (lambda (file)
14525 (set-buffer (find-file-noselect file))
14526 (org-get-buffer-tags))
14527 (if (and files (car files))
14528 files
14529 (org-agenda-files)))))))
14531 (defun org-make-tags-matcher (match)
14532 "Create the TAGS//TODO matcher form for the selection string MATCH."
14533 ;; todo-only is scoped dynamically into this function, and the function
14534 ;; may change it it the matcher asksk for it.
14535 (unless match
14536 ;; Get a new match request, with completion
14537 (let ((org-last-tags-completion-table
14538 (org-global-tags-completion-table)))
14539 (setq match (completing-read
14540 "Match: " 'org-tags-completion-function nil nil nil
14541 'org-tags-history))))
14543 ;; Parse the string and create a lisp form
14544 (let ((match0 match)
14545 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
14546 minus tag mm
14547 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14548 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
14549 (if (string-match "/+" match)
14550 ;; match contains also a todo-matching request
14551 (progn
14552 (setq tagsmatch (substring match 0 (match-beginning 0))
14553 todomatch (substring match (match-end 0)))
14554 (if (string-match "^!" todomatch)
14555 (setq todo-only t todomatch (substring todomatch 1)))
14556 (if (string-match "^\\s-*$" todomatch)
14557 (setq todomatch nil)))
14558 ;; only matching tags
14559 (setq tagsmatch match todomatch nil))
14561 ;; Make the tags matcher
14562 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14563 (setq tagsmatcher t)
14564 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14565 (while (setq term (pop orterms))
14566 (while (and (equal (substring term -1) "\\") orterms)
14567 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14568 (while (string-match re term)
14569 (setq minus (and (match-end 1)
14570 (equal (match-string 1 term) "-"))
14571 tag (match-string 2 term)
14572 re-p (equal (string-to-char tag) ?{)
14573 level-p (match-end 3)
14574 prop-p (match-end 4)
14575 mm (cond
14576 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14577 (level-p `(= level ,(string-to-number
14578 (match-string 3 term))))
14579 (prop-p
14580 (setq pn (match-string 4 term)
14581 pv (match-string 5 term)
14582 cat-p (equal pn "CATEGORY")
14583 re-p (equal (string-to-char pv) ?{)
14584 pv (substring pv 1 -1))
14585 (if (equal pn "CATEGORY")
14586 (setq gv '(get-text-property (point) 'org-category))
14587 (setq gv `(org-cached-entry-get nil ,pn)))
14588 (if re-p
14589 `(string-match ,pv (or ,gv ""))
14590 `(equal ,pv ,gv)))
14591 (t `(member ,(downcase tag) tags-list)))
14592 mm (if minus (list 'not mm) mm)
14593 term (substring term (match-end 0)))
14594 (push mm tagsmatcher))
14595 (push (if (> (length tagsmatcher) 1)
14596 (cons 'and tagsmatcher)
14597 (car tagsmatcher))
14598 orlist)
14599 (setq tagsmatcher nil))
14600 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14601 (setq tagsmatcher
14602 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14604 ;; Make the todo matcher
14605 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14606 (setq todomatcher t)
14607 (setq orterms (org-split-string todomatch "|") orlist nil)
14608 (while (setq term (pop orterms))
14609 (while (string-match re term)
14610 (setq minus (and (match-end 1)
14611 (equal (match-string 1 term) "-"))
14612 kwd (match-string 2 term)
14613 re-p (equal (string-to-char kwd) ?{)
14614 term (substring term (match-end 0))
14615 mm (if re-p
14616 `(string-match ,(substring kwd 1 -1) todo)
14617 (list 'equal 'todo kwd))
14618 mm (if minus (list 'not mm) mm))
14619 (push mm todomatcher))
14620 (push (if (> (length todomatcher) 1)
14621 (cons 'and todomatcher)
14622 (car todomatcher))
14623 orlist)
14624 (setq todomatcher nil))
14625 (setq todomatcher (if (> (length orlist) 1)
14626 (cons 'or orlist) (car orlist))))
14628 ;; Return the string and lisp forms of the matcher
14629 (setq matcher (if todomatcher
14630 (list 'and tagsmatcher todomatcher)
14631 tagsmatcher))
14632 (cons match0 matcher)))
14634 (defun org-match-any-p (re list)
14635 "Does re match any element of list?"
14636 (setq list (mapcar (lambda (x) (string-match re x)) list))
14637 (delq nil list))
14639 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
14640 (defvar org-tags-overlay (org-make-overlay 1 1))
14641 (org-detach-overlay org-tags-overlay)
14643 (defun org-align-tags-here (to-col)
14644 ;; Assumes that this is a headline
14645 (let ((pos (point)) (col (current-column)) tags)
14646 (beginning-of-line 1)
14647 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14648 (< pos (match-beginning 2)))
14649 (progn
14650 (setq tags (match-string 2))
14651 (goto-char (match-beginning 1))
14652 (insert " ")
14653 (delete-region (point) (1+ (match-end 0)))
14654 (backward-char 1)
14655 (move-to-column
14656 (max (1+ (current-column))
14657 (1+ col)
14658 (if (> to-col 0)
14659 to-col
14660 (- (abs to-col) (length tags))))
14662 (insert tags)
14663 (move-to-column (min (current-column) col) t))
14664 (goto-char pos))))
14666 (defun org-set-tags (&optional arg just-align)
14667 "Set the tags for the current headline.
14668 With prefix ARG, realign all tags in headings in the current buffer."
14669 (interactive "P")
14670 (let* ((re (concat "^" outline-regexp))
14671 (current (org-get-tags-string))
14672 (col (current-column))
14673 (org-setting-tags t)
14674 table current-tags inherited-tags ; computed below when needed
14675 tags p0 c0 c1 rpl)
14676 (if arg
14677 (save-excursion
14678 (goto-char (point-min))
14679 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14680 (while (re-search-forward re nil t)
14681 (org-set-tags nil t)
14682 (end-of-line 1)))
14683 (message "All tags realigned to column %d" org-tags-column))
14684 (if just-align
14685 (setq tags current)
14686 ;; Get a new set of tags from the user
14687 (save-excursion
14688 (setq table (or org-tag-alist (org-get-buffer-tags))
14689 org-last-tags-completion-table table
14690 current-tags (org-split-string current ":")
14691 inherited-tags (nreverse
14692 (nthcdr (length current-tags)
14693 (nreverse (org-get-tags-at))))
14694 tags
14695 (if (or (eq t org-use-fast-tag-selection)
14696 (and org-use-fast-tag-selection
14697 (delq nil (mapcar 'cdr table))))
14698 (org-fast-tag-selection
14699 current-tags inherited-tags table
14700 (if org-fast-tag-selection-include-todo org-todo-key-alist))
14701 (let ((org-add-colon-after-tag-completion t))
14702 (org-trim
14703 (org-without-partial-completion
14704 (completing-read "Tags: " 'org-tags-completion-function
14705 nil nil current 'org-tags-history)))))))
14706 (while (string-match "[-+&]+" tags)
14707 ;; No boolean logic, just a list
14708 (setq tags (replace-match ":" t t tags))))
14710 (if (string-match "\\`[\t ]*\\'" tags)
14711 (setq tags "")
14712 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14713 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14715 ;; Insert new tags at the correct column
14716 (beginning-of-line 1)
14717 (cond
14718 ((and (equal current "") (equal tags "")))
14719 ((re-search-forward
14720 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14721 (point-at-eol) t)
14722 (if (equal tags "")
14723 (setq rpl "")
14724 (goto-char (match-beginning 0))
14725 (setq c0 (current-column) p0 (point)
14726 c1 (max (1+ c0) (if (> org-tags-column 0)
14727 org-tags-column
14728 (- (- org-tags-column) (length tags))))
14729 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14730 (replace-match rpl t t)
14731 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
14732 tags)
14733 (t (error "Tags alignment failed")))
14734 (move-to-column col)
14735 (unless just-align
14736 (run-hooks 'org-after-tags-change-hook)))))
14738 (defun org-change-tag-in-region (beg end tag off)
14739 "Add or remove TAG for each entry in the region.
14740 This works in the agenda, and also in an org-mode buffer."
14741 (interactive
14742 (list (region-beginning) (region-end)
14743 (let ((org-last-tags-completion-table
14744 (if (org-mode-p)
14745 (org-get-buffer-tags)
14746 (org-global-tags-completion-table))))
14747 (completing-read
14748 "Tag: " 'org-tags-completion-function nil nil nil
14749 'org-tags-history))
14750 (progn
14751 (message "[s]et or [r]emove? ")
14752 (equal (read-char-exclusive) ?r))))
14753 (if (fboundp 'deactivate-mark) (deactivate-mark))
14754 (let ((agendap (equal major-mode 'org-agenda-mode))
14755 l1 l2 m buf pos newhead (cnt 0))
14756 (goto-char end)
14757 (setq l2 (1- (org-current-line)))
14758 (goto-char beg)
14759 (setq l1 (org-current-line))
14760 (loop for l from l1 to l2 do
14761 (goto-line l)
14762 (setq m (get-text-property (point) 'org-hd-marker))
14763 (when (or (and (org-mode-p) (org-on-heading-p))
14764 (and agendap m))
14765 (setq buf (if agendap (marker-buffer m) (current-buffer))
14766 pos (if agendap m (point)))
14767 (with-current-buffer buf
14768 (save-excursion
14769 (save-restriction
14770 (goto-char pos)
14771 (setq cnt (1+ cnt))
14772 (org-toggle-tag tag (if off 'off 'on))
14773 (setq newhead (org-get-heading)))))
14774 (and agendap (org-agenda-change-all-lines newhead m))))
14775 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14777 (defun org-tags-completion-function (string predicate &optional flag)
14778 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14779 (confirm (lambda (x) (stringp (car x)))))
14780 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
14781 (setq s1 (match-string 1 string)
14782 s2 (match-string 2 string))
14783 (setq s1 "" s2 string))
14784 (cond
14785 ((eq flag nil)
14786 ;; try completion
14787 (setq rtn (try-completion s2 ctable confirm))
14788 (if (stringp rtn)
14789 (setq rtn
14790 (concat s1 s2 (substring rtn (length s2))
14791 (if (and org-add-colon-after-tag-completion
14792 (assoc rtn ctable))
14793 ":" ""))))
14794 rtn)
14795 ((eq flag t)
14796 ;; all-completions
14797 (all-completions s2 ctable confirm)
14799 ((eq flag 'lambda)
14800 ;; exact match?
14801 (assoc s2 ctable)))
14804 (defun org-fast-tag-insert (kwd tags face &optional end)
14805 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
14806 (insert (format "%-12s" (concat kwd ":"))
14807 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14808 (or end "")))
14810 (defun org-fast-tag-show-exit (flag)
14811 (save-excursion
14812 (goto-line 3)
14813 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14814 (replace-match ""))
14815 (when flag
14816 (end-of-line 1)
14817 (move-to-column (- (window-width) 19) t)
14818 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14820 (defun org-set-current-tags-overlay (current prefix)
14821 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14822 (if (featurep 'xemacs)
14823 (org-overlay-display org-tags-overlay (concat prefix s)
14824 'secondary-selection)
14825 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14826 (org-overlay-display org-tags-overlay (concat prefix s)))))
14828 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14829 "Fast tag selection with single keys.
14830 CURRENT is the current list of tags in the headline, INHERITED is the
14831 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14832 possibly with grouping information. TODO-TABLE is a similar table with
14833 TODO keywords, should these have keys assigned to them.
14834 If the keys are nil, a-z are automatically assigned.
14835 Returns the new tags string, or nil to not change the current settings."
14836 (let* ((fulltable (append table todo-table))
14837 (maxlen (apply 'max (mapcar
14838 (lambda (x)
14839 (if (stringp (car x)) (string-width (car x)) 0))
14840 fulltable)))
14841 (buf (current-buffer))
14842 (expert (eq org-fast-tag-selection-single-key 'expert))
14843 (buffer-tags nil)
14844 (fwidth (+ maxlen 3 1 3))
14845 (ncol (/ (- (window-width) 4) fwidth))
14846 (i-face 'org-done)
14847 (c-face 'org-todo)
14848 tg cnt e c char c1 c2 ntable tbl rtn
14849 ov-start ov-end ov-prefix
14850 (exit-after-next org-fast-tag-selection-single-key)
14851 (done-keywords org-done-keywords)
14852 groups ingroup)
14853 (save-excursion
14854 (beginning-of-line 1)
14855 (if (looking-at
14856 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14857 (setq ov-start (match-beginning 1)
14858 ov-end (match-end 1)
14859 ov-prefix "")
14860 (setq ov-start (1- (point-at-eol))
14861 ov-end (1+ ov-start))
14862 (skip-chars-forward "^\n\r")
14863 (setq ov-prefix
14864 (concat
14865 (buffer-substring (1- (point)) (point))
14866 (if (> (current-column) org-tags-column)
14868 (make-string (- org-tags-column (current-column)) ?\ ))))))
14869 (org-move-overlay org-tags-overlay ov-start ov-end)
14870 (save-window-excursion
14871 (if expert
14872 (set-buffer (get-buffer-create " *Org tags*"))
14873 (delete-other-windows)
14874 (split-window-vertically)
14875 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14876 (erase-buffer)
14877 (org-set-local 'org-done-keywords done-keywords)
14878 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14879 (org-fast-tag-insert "Current" current c-face "\n\n")
14880 (org-fast-tag-show-exit exit-after-next)
14881 (org-set-current-tags-overlay current ov-prefix)
14882 (setq tbl fulltable char ?a cnt 0)
14883 (while (setq e (pop tbl))
14884 (cond
14885 ((equal e '(:startgroup))
14886 (push '() groups) (setq ingroup t)
14887 (when (not (= cnt 0))
14888 (setq cnt 0)
14889 (insert "\n"))
14890 (insert "{ "))
14891 ((equal e '(:endgroup))
14892 (setq ingroup nil cnt 0)
14893 (insert "}\n"))
14895 (setq tg (car e) c2 nil)
14896 (if (cdr e)
14897 (setq c (cdr e))
14898 ;; automatically assign a character.
14899 (setq c1 (string-to-char
14900 (downcase (substring
14901 tg (if (= (string-to-char tg) ?@) 1 0)))))
14902 (if (or (rassoc c1 ntable) (rassoc c1 table))
14903 (while (or (rassoc char ntable) (rassoc char table))
14904 (setq char (1+ char)))
14905 (setq c2 c1))
14906 (setq c (or c2 char)))
14907 (if ingroup (push tg (car groups)))
14908 (setq tg (org-add-props tg nil 'face
14909 (cond
14910 ((not (assoc tg table))
14911 (org-get-todo-face tg))
14912 ((member tg current) c-face)
14913 ((member tg inherited) i-face)
14914 (t nil))))
14915 (if (and (= cnt 0) (not ingroup)) (insert " "))
14916 (insert "[" c "] " tg (make-string
14917 (- fwidth 4 (length tg)) ?\ ))
14918 (push (cons tg c) ntable)
14919 (when (= (setq cnt (1+ cnt)) ncol)
14920 (insert "\n")
14921 (if ingroup (insert " "))
14922 (setq cnt 0)))))
14923 (setq ntable (nreverse ntable))
14924 (insert "\n")
14925 (goto-char (point-min))
14926 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14927 (fit-window-to-buffer))
14928 (setq rtn
14929 (catch 'exit
14930 (while t
14931 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
14932 (if groups " [!] no groups" " [!]groups")
14933 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14934 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14935 (cond
14936 ((= c ?\r) (throw 'exit t))
14937 ((= c ?!)
14938 (setq groups (not groups))
14939 (goto-char (point-min))
14940 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14941 ((= c ?\C-c)
14942 (if (not expert)
14943 (org-fast-tag-show-exit
14944 (setq exit-after-next (not exit-after-next)))
14945 (setq expert nil)
14946 (delete-other-windows)
14947 (split-window-vertically)
14948 (org-switch-to-buffer-other-window " *Org tags*")
14949 (and (fboundp 'fit-window-to-buffer)
14950 (fit-window-to-buffer))))
14951 ((or (= c ?\C-g)
14952 (and (= c ?q) (not (rassoc c ntable))))
14953 (org-detach-overlay org-tags-overlay)
14954 (setq quit-flag t))
14955 ((= c ?\ )
14956 (setq current nil)
14957 (if exit-after-next (setq exit-after-next 'now)))
14958 ((= c ?\t)
14959 (condition-case nil
14960 (setq tg (completing-read
14961 "Tag: "
14962 (or buffer-tags
14963 (with-current-buffer buf
14964 (org-get-buffer-tags)))))
14965 (quit (setq tg "")))
14966 (when (string-match "\\S-" tg)
14967 (add-to-list 'buffer-tags (list tg))
14968 (if (member tg current)
14969 (setq current (delete tg current))
14970 (push tg current)))
14971 (if exit-after-next (setq exit-after-next 'now)))
14972 ((setq e (rassoc c todo-table) tg (car e))
14973 (with-current-buffer buf
14974 (save-excursion (org-todo tg)))
14975 (if exit-after-next (setq exit-after-next 'now)))
14976 ((setq e (rassoc c ntable) tg (car e))
14977 (if (member tg current)
14978 (setq current (delete tg current))
14979 (loop for g in groups do
14980 (if (member tg g)
14981 (mapc (lambda (x)
14982 (setq current (delete x current)))
14983 g)))
14984 (push tg current))
14985 (if exit-after-next (setq exit-after-next 'now))))
14987 ;; Create a sorted list
14988 (setq current
14989 (sort current
14990 (lambda (a b)
14991 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14992 (if (eq exit-after-next 'now) (throw 'exit t))
14993 (goto-char (point-min))
14994 (beginning-of-line 2)
14995 (delete-region (point) (point-at-eol))
14996 (org-fast-tag-insert "Current" current c-face)
14997 (org-set-current-tags-overlay current ov-prefix)
14998 (while (re-search-forward
14999 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15000 (setq tg (match-string 1))
15001 (add-text-properties
15002 (match-beginning 1) (match-end 1)
15003 (list 'face
15004 (cond
15005 ((member tg current) c-face)
15006 ((member tg inherited) i-face)
15007 (t (get-text-property (match-beginning 1) 'face))))))
15008 (goto-char (point-min)))))
15009 (org-detach-overlay org-tags-overlay)
15010 (if rtn
15011 (mapconcat 'identity current ":")
15012 nil))))
15014 (defun org-get-tags-string ()
15015 "Get the TAGS string in the current headline."
15016 (unless (org-on-heading-p t)
15017 (error "Not on a heading"))
15018 (save-excursion
15019 (beginning-of-line 1)
15020 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15021 (org-match-string-no-properties 1)
15022 "")))
15024 (defun org-get-tags ()
15025 "Get the list of tags specified in the current headline."
15026 (org-split-string (org-get-tags-string) ":"))
15028 (defun org-get-buffer-tags ()
15029 "Get a table of all tags used in the buffer, for completion."
15030 (let (tags)
15031 (save-excursion
15032 (goto-char (point-min))
15033 (while (re-search-forward
15034 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15035 (when (equal (char-after (point-at-bol 0)) ?*)
15036 (mapc (lambda (x) (add-to-list 'tags x))
15037 (org-split-string (org-match-string-no-properties 1) ":")))))
15038 (mapcar 'list tags)))
15041 ;;;; Properties
15043 ;;; Setting and retrieving properties
15045 (defconst org-special-properties
15046 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15047 "TIMESTAMP" "TIMESTAMP_IA")
15048 "The special properties valid in Org-mode.
15050 These are properties that are not defined in the property drawer,
15051 but in some other way.")
15053 (defconst org-default-properties
15054 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15055 "LOCATION" "LOGGING" "COLUMNS")
15056 "Some properties that are used by Org-mode for various purposes.
15057 Being in this list makes sure that they are offered for completion.")
15059 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15060 "Regular expression matching the first line of a property drawer.")
15062 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15063 "Regular expression matching the first line of a property drawer.")
15065 (defun org-property-action ()
15066 "Do an action on properties."
15067 (interactive)
15068 (let (c)
15069 (org-at-property-p)
15070 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15071 (setq c (read-char-exclusive))
15072 (cond
15073 ((equal c ?s)
15074 (call-interactively 'org-set-property))
15075 ((equal c ?d)
15076 (call-interactively 'org-delete-property))
15077 ((equal c ?D)
15078 (call-interactively 'org-delete-property-globally))
15079 ((equal c ?c)
15080 (call-interactively 'org-compute-property-at-point))
15081 (t (error "No such property action %c" c)))))
15083 (defun org-at-property-p ()
15084 "Is the cursor in a property line?"
15085 ;; FIXME: Does not check if we are actually in the drawer.
15086 ;; FIXME: also returns true on any drawers.....
15087 ;; This is used by C-c C-c for property action.
15088 (save-excursion
15089 (beginning-of-line 1)
15090 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15092 (defmacro org-with-point-at (pom &rest body)
15093 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15094 (declare (indent 1) (debug t))
15095 `(save-excursion
15096 (if (markerp pom) (set-buffer (marker-buffer pom)))
15097 (save-excursion
15098 (goto-char (or pom (point)))
15099 ,@body)))
15101 (defun org-get-property-block (&optional beg end force)
15102 "Return the (beg . end) range of the body of the property drawer.
15103 BEG and END can be beginning and end of subtree, if not given
15104 they will be found.
15105 If the drawer does not exist and FORCE is non-nil, create the drawer."
15106 (catch 'exit
15107 (save-excursion
15108 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15109 (end (or end (progn (outline-next-heading) (point)))))
15110 (goto-char beg)
15111 (if (re-search-forward org-property-start-re end t)
15112 (setq beg (1+ (match-end 0)))
15113 (if force
15114 (save-excursion
15115 (org-insert-property-drawer)
15116 (setq end (progn (outline-next-heading) (point))))
15117 (throw 'exit nil))
15118 (goto-char beg)
15119 (if (re-search-forward org-property-start-re end t)
15120 (setq beg (1+ (match-end 0)))))
15121 (if (re-search-forward org-property-end-re end t)
15122 (setq end (match-beginning 0))
15123 (or force (throw 'exit nil))
15124 (goto-char beg)
15125 (setq end beg)
15126 (org-indent-line-function)
15127 (insert ":END:\n"))
15128 (cons beg end)))))
15130 (defun org-entry-properties (&optional pom which)
15131 "Get all properties of the entry at point-or-marker POM.
15132 This includes the TODO keyword, the tags, time strings for deadline,
15133 scheduled, and clocking, and any additional properties defined in the
15134 entry. The return value is an alist, keys may occur multiple times
15135 if the property key was used several times.
15136 POM may also be nil, in which case the current entry is used.
15137 If WHICH is nil or `all', get all properties. If WHICH is
15138 `special' or `standard', only get that subclass."
15139 (setq which (or which 'all))
15140 (org-with-point-at pom
15141 (let ((clockstr (substring org-clock-string 0 -1))
15142 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15143 beg end range props sum-props key value string)
15144 (save-excursion
15145 (when (condition-case nil (org-back-to-heading t) (error nil))
15146 (setq beg (point))
15147 (setq sum-props (get-text-property (point) 'org-summaries))
15148 (outline-next-heading)
15149 (setq end (point))
15150 (when (memq which '(all special))
15151 ;; Get the special properties, like TODO and tags
15152 (goto-char beg)
15153 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15154 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15155 (when (looking-at org-priority-regexp)
15156 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15157 (when (and (setq value (org-get-tags-string))
15158 (string-match "\\S-" value))
15159 (push (cons "TAGS" value) props))
15160 (when (setq value (org-get-tags-at))
15161 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15162 props))
15163 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15164 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15165 string (if (equal key clockstr)
15166 (org-no-properties
15167 (org-trim
15168 (buffer-substring
15169 (match-beginning 3) (goto-char (point-at-eol)))))
15170 (substring (org-match-string-no-properties 3) 1 -1)))
15171 (unless key
15172 (if (= (char-after (match-beginning 3)) ?\[)
15173 (setq key "TIMESTAMP_IA")
15174 (setq key "TIMESTAMP")))
15175 (when (or (equal key clockstr) (not (assoc key props)))
15176 (push (cons key string) props)))
15180 (when (memq which '(all standard))
15181 ;; Get the standard properties, like :PORP: ...
15182 (setq range (org-get-property-block beg end))
15183 (when range
15184 (goto-char (car range))
15185 (while (re-search-forward
15186 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15187 (cdr range) t)
15188 (setq key (org-match-string-no-properties 1)
15189 value (org-trim (or (org-match-string-no-properties 2) "")))
15190 (unless (member key excluded)
15191 (push (cons key (or value "")) props)))))
15192 (append sum-props (nreverse props)))))))
15194 (defun org-entry-get (pom property &optional inherit)
15195 "Get value of PROPERTY for entry at point-or-marker POM.
15196 If INHERIT is non-nil and the entry does not have the property,
15197 then also check higher levels of the hierarchy.
15198 If the property is present but empty, the return value is the empty string.
15199 If the property is not present at all, nil is returned."
15200 (org-with-point-at pom
15201 (if inherit
15202 (org-entry-get-with-inheritance property)
15203 (if (member property org-special-properties)
15204 ;; We need a special property. Use brute force, get all properties.
15205 (cdr (assoc property (org-entry-properties nil 'special)))
15206 (let ((range (org-get-property-block)))
15207 (if (and range
15208 (goto-char (car range))
15209 (re-search-forward
15210 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15211 (cdr range) t))
15212 ;; Found the property, return it.
15213 (if (match-end 1)
15214 (org-match-string-no-properties 1)
15215 "")))))))
15217 (defun org-entry-delete (pom property)
15218 "Delete the property PROPERTY from entry at point-or-marker POM."
15219 (org-with-point-at pom
15220 (if (member property org-special-properties)
15221 nil ; cannot delete these properties.
15222 (let ((range (org-get-property-block)))
15223 (if (and range
15224 (goto-char (car range))
15225 (re-search-forward
15226 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
15227 (cdr range) t))
15228 (progn
15229 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15231 nil)))))
15233 ;; Multi-values properties are properties that contain multiple values
15234 ;; These values are assumed to be single words, separated by whitespace.
15235 (defun org-entry-add-to-multivalued-property (pom property value)
15236 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15237 (let* ((old (org-entry-get pom property))
15238 (values (and old (org-split-string old "[ \t]"))))
15239 (unless (member value values)
15240 (setq values (cons value values))
15241 (org-entry-put pom property
15242 (mapconcat 'identity values " ")))))
15244 (defun org-entry-remove-from-multivalued-property (pom property value)
15245 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15246 (let* ((old (org-entry-get pom property))
15247 (values (and old (org-split-string old "[ \t]"))))
15248 (when (member value values)
15249 (setq values (delete value values))
15250 (org-entry-put pom property
15251 (mapconcat 'identity values " ")))))
15253 (defun org-entry-member-in-multivalued-property (pom property value)
15254 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15255 (let* ((old (org-entry-get pom property))
15256 (values (and old (org-split-string old "[ \t]"))))
15257 (member value values)))
15259 (defvar org-entry-property-inherited-from (make-marker))
15261 (defun org-entry-get-with-inheritance (property)
15262 "Get entry property, and search higher levels if not present."
15263 (let (tmp)
15264 (save-excursion
15265 (save-restriction
15266 (widen)
15267 (catch 'ex
15268 (while t
15269 (when (setq tmp (org-entry-get nil property))
15270 (org-back-to-heading t)
15271 (move-marker org-entry-property-inherited-from (point))
15272 (throw 'ex tmp))
15273 (or (org-up-heading-safe) (throw 'ex nil)))))
15274 (or tmp (cdr (assoc property org-local-properties))
15275 (cdr (assoc property org-global-properties))))))
15277 (defun org-entry-put (pom property value)
15278 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15279 (org-with-point-at pom
15280 (org-back-to-heading t)
15281 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15282 range)
15283 (cond
15284 ((equal property "TODO")
15285 (when (and (stringp value) (string-match "\\S-" value)
15286 (not (member value org-todo-keywords-1)))
15287 (error "\"%s\" is not a valid TODO state" value))
15288 (if (or (not value)
15289 (not (string-match "\\S-" value)))
15290 (setq value 'none))
15291 (org-todo value)
15292 (org-set-tags nil 'align))
15293 ((equal property "PRIORITY")
15294 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15295 (string-to-char value) ?\ ))
15296 (org-set-tags nil 'align))
15297 ((equal property "SCHEDULED")
15298 (if (re-search-forward org-scheduled-time-regexp end t)
15299 (cond
15300 ((eq value 'earlier) (org-timestamp-change -1 'day))
15301 ((eq value 'later) (org-timestamp-change 1 'day))
15302 (t (call-interactively 'org-schedule)))
15303 (call-interactively 'org-schedule)))
15304 ((equal property "DEADLINE")
15305 (if (re-search-forward org-deadline-time-regexp end t)
15306 (cond
15307 ((eq value 'earlier) (org-timestamp-change -1 'day))
15308 ((eq value 'later) (org-timestamp-change 1 'day))
15309 (t (call-interactively 'org-deadline)))
15310 (call-interactively 'org-deadline)))
15311 ((member property org-special-properties)
15312 (error "The %s property can not yet be set with `org-entry-put'"
15313 property))
15314 (t ; a non-special property
15315 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15316 (setq range (org-get-property-block beg end 'force))
15317 (goto-char (car range))
15318 (if (re-search-forward
15319 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15320 (progn
15321 (delete-region (match-beginning 1) (match-end 1))
15322 (goto-char (match-beginning 1)))
15323 (goto-char (cdr range))
15324 (insert "\n")
15325 (backward-char 1)
15326 (org-indent-line-function)
15327 (insert ":" property ":"))
15328 (and value (insert " " value))
15329 (org-indent-line-function)))))))
15331 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15332 "Get all property keys in the current buffer.
15333 With INCLUDE-SPECIALS, also list the special properties that relect things
15334 like tags and TODO state.
15335 With INCLUDE-DEFAULTS, also include properties that has special meaning
15336 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15337 (let (rtn range)
15338 (save-excursion
15339 (save-restriction
15340 (widen)
15341 (goto-char (point-min))
15342 (while (re-search-forward org-property-start-re nil t)
15343 (setq range (org-get-property-block))
15344 (goto-char (car range))
15345 (while (re-search-forward
15346 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15347 (cdr range) t)
15348 (add-to-list 'rtn (org-match-string-no-properties 1)))
15349 (outline-next-heading))))
15351 (when include-specials
15352 (setq rtn (append org-special-properties rtn)))
15354 (when include-defaults
15355 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15357 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15359 (defun org-property-values (key)
15360 "Return a list of all values of property KEY."
15361 (save-excursion
15362 (save-restriction
15363 (widen)
15364 (goto-char (point-min))
15365 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15366 values)
15367 (while (re-search-forward re nil t)
15368 (add-to-list 'values (org-trim (match-string 1))))
15369 (delete "" values)))))
15371 (defun org-insert-property-drawer ()
15372 "Insert a property drawer into the current entry."
15373 (interactive)
15374 (org-back-to-heading t)
15375 (looking-at outline-regexp)
15376 (let ((indent (- (match-end 0)(match-beginning 0)))
15377 (beg (point))
15378 (re (concat "^[ \t]*" org-keyword-time-regexp))
15379 end hiddenp)
15380 (outline-next-heading)
15381 (setq end (point))
15382 (goto-char beg)
15383 (while (re-search-forward re end t))
15384 (setq hiddenp (org-invisible-p))
15385 (end-of-line 1)
15386 (and (equal (char-after) ?\n) (forward-char 1))
15387 (org-skip-over-state-notes)
15388 (skip-chars-backward " \t\n\r")
15389 (if (eq (char-before) ?*) (forward-char 1))
15390 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15391 (beginning-of-line 0)
15392 (indent-to-column indent)
15393 (beginning-of-line 2)
15394 (indent-to-column indent)
15395 (beginning-of-line 0)
15396 (if hiddenp
15397 (save-excursion
15398 (org-back-to-heading t)
15399 (hide-entry))
15400 (org-flag-drawer t))))
15402 (defun org-set-property (property value)
15403 "In the current entry, set PROPERTY to VALUE.
15404 When called interactively, this will prompt for a property name, offering
15405 completion on existing and default properties. And then it will prompt
15406 for a value, offering competion either on allowed values (via an inherited
15407 xxx_ALL property) or on existing values in other instances of this property
15408 in the current file."
15409 (interactive
15410 (let* ((prop (completing-read
15411 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
15412 (cur (org-entry-get nil prop))
15413 (allowed (org-property-get-allowed-values nil prop 'table))
15414 (existing (mapcar 'list (org-property-values prop)))
15415 (val (if allowed
15416 (completing-read "Value: " allowed nil 'req-match)
15417 (completing-read
15418 (concat "Value" (if (and cur (string-match "\\S-" cur))
15419 (concat "[" cur "]") "")
15420 ": ")
15421 existing nil nil "" nil cur))))
15422 (list prop (if (equal val "") cur val))))
15423 (unless (equal (org-entry-get nil property) value)
15424 (org-entry-put nil property value)))
15426 (defun org-delete-property (property)
15427 "In the current entry, delete PROPERTY."
15428 (interactive
15429 (let* ((prop (completing-read
15430 "Property: " (org-entry-properties nil 'standard))))
15431 (list prop)))
15432 (message (concat "Property " property
15433 (if (org-entry-delete nil property)
15434 " deleted"
15435 " was not present in the entry"))))
15437 (defun org-delete-property-globally (property)
15438 "Remove PROPERTY globally, from all entries."
15439 (interactive
15440 (let* ((prop (completing-read
15441 "Globally remove property: "
15442 (mapcar 'list (org-buffer-property-keys)))))
15443 (list prop)))
15444 (save-excursion
15445 (save-restriction
15446 (widen)
15447 (goto-char (point-min))
15448 (let ((cnt 0))
15449 (while (re-search-forward
15450 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
15451 nil t)
15452 (setq cnt (1+ cnt))
15453 (replace-match ""))
15454 (message "Property \"%s\" removed from %d entries" property cnt)))))
15456 (defvar org-columns-current-fmt-compiled) ; defined below
15458 (defun org-compute-property-at-point ()
15459 "Compute the property at point.
15460 This looks for an enclosing column format, extracts the operator and
15461 then applies it to the proerty in the column format's scope."
15462 (interactive)
15463 (unless (org-at-property-p)
15464 (error "Not at a property"))
15465 (let ((prop (org-match-string-no-properties 2)))
15466 (org-columns-get-format-and-top-level)
15467 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15468 (error "No operator defined for property %s" prop))
15469 (org-columns-compute prop)))
15471 (defun org-property-get-allowed-values (pom property &optional table)
15472 "Get allowed values for the property PROPERTY.
15473 When TABLE is non-nil, return an alist that can directly be used for
15474 completion."
15475 (let (vals)
15476 (cond
15477 ((equal property "TODO")
15478 (setq vals (org-with-point-at pom
15479 (append org-todo-keywords-1 '("")))))
15480 ((equal property "PRIORITY")
15481 (let ((n org-lowest-priority))
15482 (while (>= n org-highest-priority)
15483 (push (char-to-string n) vals)
15484 (setq n (1- n)))))
15485 ((member property org-special-properties))
15487 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15489 (when (and vals (string-match "\\S-" vals))
15490 (setq vals (car (read-from-string (concat "(" vals ")"))))
15491 (setq vals (mapcar (lambda (x)
15492 (cond ((stringp x) x)
15493 ((numberp x) (number-to-string x))
15494 ((symbolp x) (symbol-name x))
15495 (t "???")))
15496 vals)))))
15497 (if table (mapcar 'list vals) vals)))
15499 (defun org-property-previous-allowed-value (&optional previous)
15500 "Switch to the next allowed value for this property."
15501 (interactive)
15502 (org-property-next-allowed-value t))
15504 (defun org-property-next-allowed-value (&optional previous)
15505 "Switch to the next allowed value for this property."
15506 (interactive)
15507 (unless (org-at-property-p)
15508 (error "Not at a property"))
15509 (let* ((key (match-string 2))
15510 (value (match-string 3))
15511 (allowed (or (org-property-get-allowed-values (point) key)
15512 (and (member value '("[ ]" "[-]" "[X]"))
15513 '("[ ]" "[X]"))))
15514 nval)
15515 (unless allowed
15516 (error "Allowed values for this property have not been defined"))
15517 (if previous (setq allowed (reverse allowed)))
15518 (if (member value allowed)
15519 (setq nval (car (cdr (member value allowed)))))
15520 (setq nval (or nval (car allowed)))
15521 (if (equal nval value)
15522 (error "Only one allowed value for this property"))
15523 (org-at-property-p)
15524 (replace-match (concat " :" key ": " nval) t t)
15525 (org-indent-line-function)
15526 (beginning-of-line 1)
15527 (skip-chars-forward " \t")))
15529 (defun org-find-entry-with-id (ident)
15530 "Locate the entry that contains the ID property with exact value IDENT.
15531 IDENT can be a string, a symbol or a number, this function will search for
15532 the string representation of it.
15533 Return the position where this entry starts, or nil if there is no such entry."
15534 (let ((id (cond
15535 ((stringp ident) ident)
15536 ((symbol-name ident) (symbol-name ident))
15537 ((numberp ident) (number-to-string ident))
15538 (t (error "IDENT %s must be a string, symbol or number" ident))))
15539 (case-fold-search nil))
15540 (save-excursion
15541 (save-restriction
15542 (goto-char (point-min))
15543 (when (re-search-forward
15544 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15545 nil t)
15546 (org-back-to-heading)
15547 (point))))))
15549 ;;; Column View
15551 (defvar org-columns-overlays nil
15552 "Holds the list of current column overlays.")
15554 (defvar org-columns-current-fmt nil
15555 "Local variable, holds the currently active column format.")
15556 (defvar org-columns-current-fmt-compiled nil
15557 "Local variable, holds the currently active column format.
15558 This is the compiled version of the format.")
15559 (defvar org-columns-current-widths nil
15560 "Loval variable, holds the currently widths of fields.")
15561 (defvar org-columns-current-maxwidths nil
15562 "Loval variable, holds the currently active maximum column widths.")
15563 (defvar org-columns-begin-marker (make-marker)
15564 "Points to the position where last a column creation command was called.")
15565 (defvar org-columns-top-level-marker (make-marker)
15566 "Points to the position where current columns region starts.")
15568 (defvar org-columns-map (make-sparse-keymap)
15569 "The keymap valid in column display.")
15571 (defun org-columns-content ()
15572 "Switch to contents view while in columns view."
15573 (interactive)
15574 (org-overview)
15575 (org-content))
15577 (org-defkey org-columns-map "c" 'org-columns-content)
15578 (org-defkey org-columns-map "o" 'org-overview)
15579 (org-defkey org-columns-map "e" 'org-columns-edit-value)
15580 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
15581 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
15582 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
15583 (org-defkey org-columns-map "v" 'org-columns-show-value)
15584 (org-defkey org-columns-map "q" 'org-columns-quit)
15585 (org-defkey org-columns-map "r" 'org-columns-redo)
15586 (org-defkey org-columns-map [left] 'backward-char)
15587 (org-defkey org-columns-map "\M-b" 'backward-char)
15588 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
15589 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
15590 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
15591 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
15592 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
15593 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
15594 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
15595 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
15596 (org-defkey org-columns-map "<" 'org-columns-narrow)
15597 (org-defkey org-columns-map ">" 'org-columns-widen)
15598 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
15599 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
15600 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
15601 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
15603 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
15604 '("Column"
15605 ["Edit property" org-columns-edit-value t]
15606 ["Next allowed value" org-columns-next-allowed-value t]
15607 ["Previous allowed value" org-columns-previous-allowed-value t]
15608 ["Show full value" org-columns-show-value t]
15609 ["Edit allowed values" org-columns-edit-allowed t]
15610 "--"
15611 ["Edit column attributes" org-columns-edit-attributes t]
15612 ["Increase column width" org-columns-widen t]
15613 ["Decrease column width" org-columns-narrow t]
15614 "--"
15615 ["Move column right" org-columns-move-right t]
15616 ["Move column left" org-columns-move-left t]
15617 ["Add column" org-columns-new t]
15618 ["Delete column" org-columns-delete t]
15619 "--"
15620 ["CONTENTS" org-columns-content t]
15621 ["OVERVIEW" org-overview t]
15622 ["Refresh columns display" org-columns-redo t]
15623 "--"
15624 ["Open link" org-columns-open-link t]
15625 "--"
15626 ["Quit" org-columns-quit t]))
15628 (defun org-columns-new-overlay (beg end &optional string face)
15629 "Create a new column overlay and add it to the list."
15630 (let ((ov (org-make-overlay beg end)))
15631 (org-overlay-put ov 'face (or face 'secondary-selection))
15632 (org-overlay-display ov string face)
15633 (push ov org-columns-overlays)
15634 ov))
15636 (defun org-columns-display-here (&optional props)
15637 "Overlay the current line with column display."
15638 (interactive)
15639 (let* ((fmt org-columns-current-fmt-compiled)
15640 (beg (point-at-bol))
15641 (level-face (save-excursion
15642 (beginning-of-line 1)
15643 (and (looking-at "\\(\\**\\)\\(\\* \\)")
15644 (org-get-level-face 2))))
15645 (color (list :foreground
15646 (face-attribute (or level-face 'default) :foreground)))
15647 props pom property ass width f string ov column val modval)
15648 ;; Check if the entry is in another buffer.
15649 (unless props
15650 (if (eq major-mode 'org-agenda-mode)
15651 (setq pom (or (get-text-property (point) 'org-hd-marker)
15652 (get-text-property (point) 'org-marker))
15653 props (if pom (org-entry-properties pom) nil))
15654 (setq props (org-entry-properties nil))))
15655 ;; Walk the format
15656 (while (setq column (pop fmt))
15657 (setq property (car column)
15658 ass (if (equal property "ITEM")
15659 (cons "ITEM"
15660 (save-match-data
15661 (org-no-properties
15662 (org-remove-tabs
15663 (buffer-substring-no-properties
15664 (point-at-bol) (point-at-eol))))))
15665 (assoc property props))
15666 width (or (cdr (assoc property org-columns-current-maxwidths))
15667 (nth 2 column)
15668 (length property))
15669 f (format "%%-%d.%ds | " width width)
15670 val (or (cdr ass) "")
15671 modval (if (equal property "ITEM")
15672 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
15673 string (format f (or modval val)))
15674 ;; Create the overlay
15675 (org-unmodified
15676 (setq ov (org-columns-new-overlay
15677 beg (setq beg (1+ beg)) string
15678 (list color 'org-column)))
15679 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
15680 (org-overlay-put ov 'keymap org-columns-map)
15681 (org-overlay-put ov 'org-columns-key property)
15682 (org-overlay-put ov 'org-columns-value (cdr ass))
15683 (org-overlay-put ov 'org-columns-value-modified modval)
15684 (org-overlay-put ov 'org-columns-pom pom)
15685 (org-overlay-put ov 'org-columns-format f))
15686 (if (or (not (char-after beg))
15687 (equal (char-after beg) ?\n))
15688 (let ((inhibit-read-only t))
15689 (save-excursion
15690 (goto-char beg)
15691 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
15692 ;; Make the rest of the line disappear.
15693 (org-unmodified
15694 (setq ov (org-columns-new-overlay beg (point-at-eol)))
15695 (org-overlay-put ov 'invisible t)
15696 (org-overlay-put ov 'keymap org-columns-map)
15697 (org-overlay-put ov 'intangible t)
15698 (push ov org-columns-overlays)
15699 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
15700 (org-overlay-put ov 'keymap org-columns-map)
15701 (push ov org-columns-overlays)
15702 (let ((inhibit-read-only t))
15703 (put-text-property (max (point-min) (1- (point-at-bol)))
15704 (min (point-max) (1+ (point-at-eol)))
15705 'read-only "Type `e' to edit property")))))
15707 (defvar org-previous-header-line-format nil
15708 "The header line format before column view was turned on.")
15709 (defvar org-columns-inhibit-recalculation nil
15710 "Inhibit recomputing of columns on column view startup.")
15713 (defvar header-line-format)
15714 (defun org-columns-display-here-title ()
15715 "Overlay the newline before the current line with the table title."
15716 (interactive)
15717 (let ((fmt org-columns-current-fmt-compiled)
15718 string (title "")
15719 property width f column str widths)
15720 (while (setq column (pop fmt))
15721 (setq property (car column)
15722 str (or (nth 1 column) property)
15723 width (or (cdr (assoc property org-columns-current-maxwidths))
15724 (nth 2 column)
15725 (length str))
15726 widths (push width widths)
15727 f (format "%%-%d.%ds | " width width)
15728 string (format f str)
15729 title (concat title string)))
15730 (setq title (concat
15731 (org-add-props " " nil 'display '(space :align-to 0))
15732 (org-add-props title nil 'face '(:weight bold :underline t))))
15733 (org-set-local 'org-previous-header-line-format header-line-format)
15734 (org-set-local 'org-columns-current-widths (nreverse widths))
15735 (setq header-line-format title)))
15737 (defun org-columns-remove-overlays ()
15738 "Remove all currently active column overlays."
15739 (interactive)
15740 (when (marker-buffer org-columns-begin-marker)
15741 (with-current-buffer (marker-buffer org-columns-begin-marker)
15742 (when (local-variable-p 'org-previous-header-line-format)
15743 (setq header-line-format org-previous-header-line-format)
15744 (kill-local-variable 'org-previous-header-line-format))
15745 (move-marker org-columns-begin-marker nil)
15746 (move-marker org-columns-top-level-marker nil)
15747 (org-unmodified
15748 (mapc 'org-delete-overlay org-columns-overlays)
15749 (setq org-columns-overlays nil)
15750 (let ((inhibit-read-only t))
15751 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
15753 (defun org-columns-cleanup-item (item fmt)
15754 "Remove from ITEM what is a column in the format FMT."
15755 (if (not org-complex-heading-regexp)
15756 item
15757 (when (string-match org-complex-heading-regexp item)
15758 (concat
15759 (org-add-props (concat (match-string 1 item) " ") nil
15760 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
15761 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
15762 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
15763 " " (match-string 4 item)
15764 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
15766 (defun org-columns-show-value ()
15767 "Show the full value of the property."
15768 (interactive)
15769 (let ((value (get-char-property (point) 'org-columns-value)))
15770 (message "Value is: %s" (or value ""))))
15772 (defun org-columns-quit ()
15773 "Remove the column overlays and in this way exit column editing."
15774 (interactive)
15775 (org-unmodified
15776 (org-columns-remove-overlays)
15777 (let ((inhibit-read-only t))
15778 (remove-text-properties (point-min) (point-max) '(read-only t))))
15779 (when (eq major-mode 'org-agenda-mode)
15780 (message
15781 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
15783 (defun org-columns-check-computed ()
15784 "Check if this column value is computed.
15785 If yes, throw an error indicating that changing it does not make sense."
15786 (let ((val (get-char-property (point) 'org-columns-value)))
15787 (when (and (stringp val)
15788 (get-char-property 0 'org-computed val))
15789 (error "This value is computed from the entry's children"))))
15791 (defun org-columns-todo (&optional arg)
15792 "Change the TODO state during column view."
15793 (interactive "P")
15794 (org-columns-edit-value "TODO"))
15796 (defun org-columns-set-tags-or-toggle (&optional arg)
15797 "Toggle checkbox at point, or set tags for current headline."
15798 (interactive "P")
15799 (if (string-match "\\`\\[[ xX-]\\]\\'"
15800 (get-char-property (point) 'org-columns-value))
15801 (org-columns-next-allowed-value)
15802 (org-columns-edit-value "TAGS")))
15804 (defun org-columns-edit-value (&optional key)
15805 "Edit the value of the property at point in column view.
15806 Where possible, use the standard interface for changing this line."
15807 (interactive)
15808 (org-columns-check-computed)
15809 (let* ((external-key key)
15810 (col (current-column))
15811 (key (or key (get-char-property (point) 'org-columns-key)))
15812 (value (get-char-property (point) 'org-columns-value))
15813 (bol (point-at-bol)) (eol (point-at-eol))
15814 (pom (or (get-text-property bol 'org-hd-marker)
15815 (point))) ; keep despite of compiler waring
15816 (line-overlays
15817 (delq nil (mapcar (lambda (x)
15818 (and (eq (overlay-buffer x) (current-buffer))
15819 (>= (overlay-start x) bol)
15820 (<= (overlay-start x) eol)
15822 org-columns-overlays)))
15823 nval eval allowed)
15824 (cond
15825 ((equal key "ITEM")
15826 (setq eval '(org-with-point-at pom
15827 (org-edit-headline))))
15828 ((equal key "TODO")
15829 (setq eval '(org-with-point-at pom
15830 (let ((current-prefix-arg
15831 (if external-key current-prefix-arg '(4))))
15832 (call-interactively 'org-todo)))))
15833 ((equal key "PRIORITY")
15834 (setq eval '(org-with-point-at pom
15835 (call-interactively 'org-priority))))
15836 ((equal key "TAGS")
15837 (setq eval '(org-with-point-at pom
15838 (let ((org-fast-tag-selection-single-key
15839 (if (eq org-fast-tag-selection-single-key 'expert)
15840 t org-fast-tag-selection-single-key)))
15841 (call-interactively 'org-set-tags)))))
15842 ((equal key "DEADLINE")
15843 (setq eval '(org-with-point-at pom
15844 (call-interactively 'org-deadline))))
15845 ((equal key "SCHEDULED")
15846 (setq eval '(org-with-point-at pom
15847 (call-interactively 'org-schedule))))
15849 (setq allowed (org-property-get-allowed-values pom key 'table))
15850 (if allowed
15851 (setq nval (completing-read "Value: " allowed nil t))
15852 (setq nval (read-string "Edit: " value)))
15853 (setq nval (org-trim nval))
15854 (when (not (equal nval value))
15855 (setq eval '(org-entry-put pom key nval)))))
15856 (when eval
15857 (let ((inhibit-read-only t))
15858 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
15859 (unwind-protect
15860 (progn
15861 (setq org-columns-overlays
15862 (org-delete-all line-overlays org-columns-overlays))
15863 (mapc 'org-delete-overlay line-overlays)
15864 (org-columns-eval eval))
15865 (org-columns-display-here))))
15866 (move-to-column col)
15867 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15868 (org-columns-update key))))
15870 (defun org-edit-headline () ; FIXME: this is not columns specific
15871 "Edit the current headline, the part without TODO keyword, TAGS."
15872 (org-back-to-heading)
15873 (when (looking-at org-todo-line-regexp)
15874 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
15875 (txt (match-string 3))
15876 (post "")
15877 txt2)
15878 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
15879 (setq post (match-string 0 txt)
15880 txt (substring txt 0 (match-beginning 0))))
15881 (setq txt2 (read-string "Edit: " txt))
15882 (when (not (equal txt txt2))
15883 (beginning-of-line 1)
15884 (insert pre txt2 post)
15885 (delete-region (point) (point-at-eol))
15886 (org-set-tags nil t)))))
15888 (defun org-columns-edit-allowed ()
15889 "Edit the list of allowed values for the current property."
15890 (interactive)
15891 (let* ((key (get-char-property (point) 'org-columns-key))
15892 (key1 (concat key "_ALL"))
15893 (allowed (org-entry-get (point) key1 t))
15894 nval)
15895 ;; FIXME: Cover editing TODO, TAGS etc inbiffer settings.????
15896 (setq nval (read-string "Allowed: " allowed))
15897 (org-entry-put
15898 (cond ((marker-position org-entry-property-inherited-from)
15899 org-entry-property-inherited-from)
15900 ((marker-position org-columns-top-level-marker)
15901 org-columns-top-level-marker))
15902 key1 nval)))
15904 (defmacro org-no-warnings (&rest body)
15905 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
15907 (defun org-columns-eval (form)
15908 (let (hidep)
15909 (save-excursion
15910 (beginning-of-line 1)
15911 ;; `next-line' is needed here, because it skips invisible line.
15912 ;; FIXME: RMS says this should be wrapped into `with-no-warnings'
15913 ;; but I don't know how to do this and keep the code XEmacs compatible.
15914 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
15915 (setq hidep (org-on-heading-p 1)))
15916 (eval form)
15917 (and hidep (hide-entry))))
15919 (defun org-columns-previous-allowed-value ()
15920 "Switch to the previous allowed value for this column."
15921 (interactive)
15922 (org-columns-next-allowed-value t))
15924 (defun org-columns-next-allowed-value (&optional previous)
15925 "Switch to the next allowed value for this column."
15926 (interactive)
15927 (org-columns-check-computed)
15928 (let* ((col (current-column))
15929 (key (get-char-property (point) 'org-columns-key))
15930 (value (get-char-property (point) 'org-columns-value))
15931 (bol (point-at-bol)) (eol (point-at-eol))
15932 (pom (or (get-text-property bol 'org-hd-marker)
15933 (point))) ; keep despite of compiler waring
15934 (line-overlays
15935 (delq nil (mapcar (lambda (x)
15936 (and (eq (overlay-buffer x) (current-buffer))
15937 (>= (overlay-start x) bol)
15938 (<= (overlay-start x) eol)
15940 org-columns-overlays)))
15941 (allowed (or (org-property-get-allowed-values pom key)
15942 (and (equal
15943 (nth 4 (assoc key org-columns-current-fmt-compiled))
15944 'checkbox) '("[ ]" "[X]"))))
15945 nval)
15946 (when (equal key "ITEM")
15947 (error "Cannot edit item headline from here"))
15948 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
15949 (error "Allowed values for this property have not been defined"))
15950 (if (member key '("SCHEDULED" "DEADLINE"))
15951 (setq nval (if previous 'earlier 'later))
15952 (if previous (setq allowed (reverse allowed)))
15953 (if (member value allowed)
15954 (setq nval (car (cdr (member value allowed)))))
15955 (setq nval (or nval (car allowed)))
15956 (if (equal nval value)
15957 (error "Only one allowed value for this property")))
15958 (let ((inhibit-read-only t))
15959 (remove-text-properties (1- bol) eol '(read-only t))
15960 (unwind-protect
15961 (progn
15962 (setq org-columns-overlays
15963 (org-delete-all line-overlays org-columns-overlays))
15964 (mapc 'org-delete-overlay line-overlays)
15965 (org-columns-eval '(org-entry-put pom key nval)))
15966 (org-columns-display-here)))
15967 (move-to-column col)
15968 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15969 (org-columns-update key))))
15971 (defun org-verify-version (task)
15972 (cond
15973 ((eq task 'columns)
15974 (if (or (featurep 'xemacs)
15975 (< emacs-major-version 22))
15976 (error "Emacs 22 is required for the columns feature")))))
15978 (defun org-columns-open-link (&optional arg)
15979 (interactive "P")
15980 (let ((key (get-char-property (point) 'org-columns-key))
15981 (value (get-char-property (point) 'org-columns-value)))
15982 (org-open-link-from-string arg)))
15984 (defun org-open-link-from-string (s &optional arg)
15985 "Open a link in the string S, as if it was in Org-mode."
15986 (interactive)
15987 (with-temp-buffer
15988 (let ((org-inhibit-startup t))
15989 (org-mode)
15990 (insert s)
15991 (goto-char (point-min))
15992 (org-open-at-point arg))))
15994 (defun org-columns-get-format-and-top-level ()
15995 (let (fmt)
15996 (when (condition-case nil (org-back-to-heading) (error nil))
15997 (move-marker org-entry-property-inherited-from nil)
15998 (setq fmt (org-entry-get nil "COLUMNS" t)))
15999 (setq fmt (or fmt org-columns-default-format))
16000 (org-set-local 'org-columns-current-fmt fmt)
16001 (org-columns-compile-format fmt)
16002 (if (marker-position org-entry-property-inherited-from)
16003 (move-marker org-columns-top-level-marker
16004 org-entry-property-inherited-from)
16005 (move-marker org-columns-top-level-marker (point)))
16006 fmt))
16008 (defun org-columns ()
16009 "Turn on column view on an org-mode file."
16010 (interactive)
16011 (org-verify-version 'columns)
16012 (org-columns-remove-overlays)
16013 (move-marker org-columns-begin-marker (point))
16014 (let (beg end fmt cache maxwidths)
16015 (setq fmt (org-columns-get-format-and-top-level))
16016 (save-excursion
16017 (goto-char org-columns-top-level-marker)
16018 (setq beg (point))
16019 (unless org-columns-inhibit-recalculation
16020 (org-columns-compute-all))
16021 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16022 (point-max)))
16023 (goto-char beg)
16024 ;; Get and cache the properties
16025 (while (re-search-forward (concat "^" outline-regexp) end t)
16026 (push (cons (org-current-line) (org-entry-properties)) cache))
16027 (when cache
16028 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16029 (org-set-local 'org-columns-current-maxwidths maxwidths)
16030 (org-columns-display-here-title)
16031 (mapc (lambda (x)
16032 (goto-line (car x))
16033 (org-columns-display-here (cdr x)))
16034 cache)))))
16036 (defun org-columns-new (&optional prop title width op fmt)
16037 "Insert a new column, to the leeft o the current column."
16038 (interactive)
16039 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16040 cell)
16041 (setq prop (completing-read
16042 "Property: " (mapcar 'list (org-buffer-property-keys t))
16043 nil nil prop))
16044 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16045 (setq width (read-string "Column width: " (if width (number-to-string width))))
16046 (if (string-match "\\S-" width)
16047 (setq width (string-to-number width))
16048 (setq width nil))
16049 (setq fmt (completing-read "Summary [none]: "
16050 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16051 nil t))
16052 (if (string-match "\\S-" fmt)
16053 (setq fmt (intern fmt))
16054 (setq fmt nil))
16055 (if (eq fmt 'none) (setq fmt nil))
16056 (if editp
16057 (progn
16058 (setcar editp prop)
16059 (setcdr editp (list title width nil fmt)))
16060 (setq cell (nthcdr (1- (current-column))
16061 org-columns-current-fmt-compiled))
16062 (setcdr cell (cons (list prop title width nil fmt)
16063 (cdr cell))))
16064 (org-columns-store-format)
16065 (org-columns-redo)))
16067 (defun org-columns-delete ()
16068 "Delete the column at point from columns view."
16069 (interactive)
16070 (let* ((n (current-column))
16071 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16072 (when (y-or-n-p
16073 (format "Are you sure you want to remove column \"%s\"? " title))
16074 (setq org-columns-current-fmt-compiled
16075 (delq (nth n org-columns-current-fmt-compiled)
16076 org-columns-current-fmt-compiled))
16077 (org-columns-store-format)
16078 (org-columns-redo)
16079 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16080 (backward-char 1)))))
16082 (defun org-columns-edit-attributes ()
16083 "Edit the attributes of the current column."
16084 (interactive)
16085 (let* ((n (current-column))
16086 (info (nth n org-columns-current-fmt-compiled)))
16087 (apply 'org-columns-new info)))
16089 (defun org-columns-widen (arg)
16090 "Make the column wider by ARG characters."
16091 (interactive "p")
16092 (let* ((n (current-column))
16093 (entry (nth n org-columns-current-fmt-compiled))
16094 (width (or (nth 2 entry)
16095 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16096 (setq width (max 1 (+ width arg)))
16097 (setcar (nthcdr 2 entry) width)
16098 (org-columns-store-format)
16099 (org-columns-redo)))
16101 (defun org-columns-narrow (arg)
16102 "Make the column nrrower by ARG characters."
16103 (interactive "p")
16104 (org-columns-widen (- arg)))
16106 (defun org-columns-move-right ()
16107 "Swap this column with the one to the right."
16108 (interactive)
16109 (let* ((n (current-column))
16110 (cell (nthcdr n org-columns-current-fmt-compiled))
16112 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16113 (error "Cannot shift this column further to the right"))
16114 (setq e (car cell))
16115 (setcar cell (car (cdr cell)))
16116 (setcdr cell (cons e (cdr (cdr cell))))
16117 (org-columns-store-format)
16118 (org-columns-redo)
16119 (forward-char 1)))
16121 (defun org-columns-move-left ()
16122 "Swap this column with the one to the left."
16123 (interactive)
16124 (let* ((n (current-column)))
16125 (when (= n 0)
16126 (error "Cannot shift this column further to the left"))
16127 (backward-char 1)
16128 (org-columns-move-right)
16129 (backward-char 1)))
16131 (defun org-columns-store-format ()
16132 "Store the text version of the current columns format in appropriate place.
16133 This is either in the COLUMNS property of the node starting the current column
16134 display, or in the #+COLUMNS line of the current buffer."
16135 (let (fmt (cnt 0))
16136 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16137 (org-set-local 'org-columns-current-fmt fmt)
16138 (if (marker-position org-columns-top-level-marker)
16139 (save-excursion
16140 (goto-char org-columns-top-level-marker)
16141 (if (and (org-at-heading-p)
16142 (org-entry-get nil "COLUMNS"))
16143 (org-entry-put nil "COLUMNS" fmt)
16144 (goto-char (point-min))
16145 ;; Overwrite all #+COLUMNS lines....
16146 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16147 (setq cnt (1+ cnt))
16148 (replace-match (concat "#+COLUMNS: " fmt) t t))
16149 (unless (> cnt 0)
16150 (goto-char (point-min))
16151 (or (org-on-heading-p t) (outline-next-heading))
16152 (let ((inhibit-read-only t))
16153 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16154 (org-set-local 'org-columns-default-format fmt))))))
16156 (defvar org-overriding-columns-format nil
16157 "When set, overrides any other definition.")
16158 (defvar org-agenda-view-columns-initially nil
16159 "When set, switch to columns view immediately after creating the agenda.")
16161 (defun org-agenda-columns ()
16162 "Turn on column view in the agenda."
16163 (interactive)
16164 (org-verify-version 'columns)
16165 (org-columns-remove-overlays)
16166 (move-marker org-columns-begin-marker (point))
16167 (let (fmt cache maxwidths m)
16168 (cond
16169 ((and (local-variable-p 'org-overriding-columns-format)
16170 org-overriding-columns-format)
16171 (setq fmt org-overriding-columns-format))
16172 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16173 (setq fmt (org-entry-get m "COLUMNS" t)))
16174 ((and (boundp 'org-columns-current-fmt)
16175 (local-variable-p 'org-columns-current-fmt)
16176 org-columns-current-fmt)
16177 (setq fmt org-columns-current-fmt))
16178 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16179 (setq m (get-text-property m 'org-hd-marker))
16180 (setq fmt (org-entry-get m "COLUMNS" t))))
16181 (setq fmt (or fmt org-columns-default-format))
16182 (org-set-local 'org-columns-current-fmt fmt)
16183 (org-columns-compile-format fmt)
16184 (save-excursion
16185 ;; Get and cache the properties
16186 (goto-char (point-min))
16187 (while (not (eobp))
16188 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16189 (get-text-property (point) 'org-marker)))
16190 (push (cons (org-current-line) (org-entry-properties m)) cache))
16191 (beginning-of-line 2))
16192 (when cache
16193 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16194 (org-set-local 'org-columns-current-maxwidths maxwidths)
16195 (org-columns-display-here-title)
16196 (mapc (lambda (x)
16197 (goto-line (car x))
16198 (org-columns-display-here (cdr x)))
16199 cache)))))
16201 (defun org-columns-get-autowidth-alist (s cache)
16202 "Derive the maximum column widths from the format and the cache."
16203 (let ((start 0) rtn)
16204 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
16205 (push (cons (match-string 1 s) 1) rtn)
16206 (setq start (match-end 0)))
16207 (mapc (lambda (x)
16208 (setcdr x (apply 'max
16209 (mapcar
16210 (lambda (y)
16211 (length (or (cdr (assoc (car x) (cdr y))) " ")))
16212 cache))))
16213 rtn)
16214 rtn))
16216 (defun org-columns-compute-all ()
16217 "Compute all columns that have operators defined."
16218 (org-unmodified
16219 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
16220 (let ((columns org-columns-current-fmt-compiled) col)
16221 (while (setq col (pop columns))
16222 (when (nth 3 col)
16223 (save-excursion
16224 (org-columns-compute (car col)))))))
16226 (defun org-columns-update (property)
16227 "Recompute PROPERTY, and update the columns display for it."
16228 (org-columns-compute property)
16229 (let (fmt val pos)
16230 (save-excursion
16231 (mapc (lambda (ov)
16232 (when (equal (org-overlay-get ov 'org-columns-key) property)
16233 (setq pos (org-overlay-start ov))
16234 (goto-char pos)
16235 (when (setq val (cdr (assoc property
16236 (get-text-property
16237 (point-at-bol) 'org-summaries))))
16238 (setq fmt (org-overlay-get ov 'org-columns-format))
16239 (org-overlay-put ov 'org-columns-value val)
16240 (org-overlay-put ov 'display (format fmt val)))))
16241 org-columns-overlays))))
16243 (defun org-columns-compute (property)
16244 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16245 (interactive)
16246 (let* ((re (concat "^" outline-regexp))
16247 (lmax 30) ; Does anyone use deeper levels???
16248 (lsum (make-vector lmax 0))
16249 (lflag (make-vector lmax nil))
16250 (level 0)
16251 (ass (assoc property org-columns-current-fmt-compiled))
16252 (format (nth 4 ass))
16253 (printf (nth 5 ass))
16254 (beg org-columns-top-level-marker)
16255 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
16256 (save-excursion
16257 ;; Find the region to compute
16258 (goto-char beg)
16259 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
16260 (goto-char end)
16261 ;; Walk the tree from the back and do the computations
16262 (while (re-search-backward re beg t)
16263 (setq sumpos (match-beginning 0)
16264 last-level level
16265 level (org-outline-level)
16266 val (org-entry-get nil property)
16267 valflag (and val (string-match "\\S-" val)))
16268 (cond
16269 ((< level last-level)
16270 ;; put the sum of lower levels here as a property
16271 (setq sum (aref lsum last-level) ; current sum
16272 flag (aref lflag last-level) ; any valid entries from children?
16273 str (org-column-number-to-string sum format printf)
16274 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
16275 useval (if flag str1 (if valflag val ""))
16276 sum-alist (get-text-property sumpos 'org-summaries))
16277 (if (assoc property sum-alist)
16278 (setcdr (assoc property sum-alist) useval)
16279 (push (cons property useval) sum-alist)
16280 (org-unmodified
16281 (add-text-properties sumpos (1+ sumpos)
16282 (list 'org-summaries sum-alist))))
16283 (when val
16284 (org-entry-put nil property (if flag str val)))
16285 ;; add current to current level accumulator
16286 (when (or flag valflag)
16287 ;; FIXME: is this ok?????????
16288 (aset lsum level (+ (aref lsum level)
16289 (if flag sum (org-column-string-to-number
16290 (if flag str val) format))))
16291 (aset lflag level t))
16292 ;; clear accumulators for deeper levels
16293 (loop for l from (1+ level) to (1- lmax) do
16294 (aset lsum l 0)
16295 (aset lflag l nil)))
16296 ((>= level last-level)
16297 ;; add what we have here to the accumulator for this level
16298 (aset lsum level (+ (aref lsum level)
16299 (org-column-string-to-number (or val "0") format)))
16300 (and valflag (aset lflag level t)))
16301 (t (error "This should not happen")))))))
16303 (defun org-columns-redo ()
16304 "Construct the column display again."
16305 (interactive)
16306 (message "Recomputing columns...")
16307 (save-excursion
16308 (if (marker-position org-columns-begin-marker)
16309 (goto-char org-columns-begin-marker))
16310 (org-columns-remove-overlays)
16311 (if (org-mode-p)
16312 (call-interactively 'org-columns)
16313 (call-interactively 'org-agenda-columns)))
16314 (message "Recomputing columns...done"))
16316 (defun org-columns-not-in-agenda ()
16317 (if (eq major-mode 'org-agenda-mode)
16318 (error "This command is only allowed in Org-mode buffers")))
16321 (defun org-string-to-number (s)
16322 "Convert string to number, and interpret hh:mm:ss."
16323 (if (not (string-match ":" s))
16324 (string-to-number s)
16325 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16326 (while l
16327 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16328 sum)))
16330 (defun org-column-number-to-string (n fmt printf)
16331 "Convert a computed column number to a string value, according to FMT."
16332 (cond
16333 ((eq fmt 'add_times)
16334 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16335 (format "%d:%02d" h m)))
16336 ((eq fmt 'checkbox)
16337 (cond ((= n (floor n)) "[X]")
16338 ((> n 1.) "[-]")
16339 (t "[ ]")))
16340 (printf (format printf n))
16341 ((eq fmt 'currency)
16342 (format "%.2f" n))
16343 (t (number-to-string n))))
16345 (defun org-column-string-to-number (s fmt)
16346 "Convert a column value to a number that can be used for column computing."
16347 (cond
16348 ((string-match ":" s)
16349 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16350 (while l
16351 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16352 sum))
16353 ((eq fmt 'checkbox)
16354 (if (equal s "[X]") 1. 0.000001))
16355 (t (string-to-number s))))
16357 (defun org-columns-uncompile-format (cfmt)
16358 "Turn the compiled columns format back into a string representation."
16359 (let ((rtn "") e s prop title op width fmt printf)
16360 (while (setq e (pop cfmt))
16361 (setq prop (car e)
16362 title (nth 1 e)
16363 width (nth 2 e)
16364 op (nth 3 e)
16365 fmt (nth 4 e)
16366 printf (nth 5 e))
16367 (cond
16368 ((eq fmt 'add_times) (setq op ":"))
16369 ((eq fmt 'checkbox) (setq op "X"))
16370 ((eq fmt 'add_numbers) (setq op "+"))
16371 ((eq fmt 'currency) (setq op "$")))
16372 (if (and op printf) (setq op (concat op ";" printf)))
16373 (if (equal title prop) (setq title nil))
16374 (setq s (concat "%" (if width (number-to-string width))
16375 prop
16376 (if title (concat "(" title ")"))
16377 (if op (concat "{" op "}"))))
16378 (setq rtn (concat rtn " " s)))
16379 (org-trim rtn)))
16381 (defun org-columns-compile-format (fmt)
16382 "Turn a column format string into an alist of specifications.
16383 The alist has one entry for each column in the format. The elements of
16384 that list are:
16385 property the property
16386 title the title field for the columns
16387 width the column width in characters, can be nil for automatic
16388 operator the operator if any
16389 format the output format for computed results, derived from operator
16390 printf a printf format for computed values"
16391 (let ((start 0) width prop title op f printf)
16392 (setq org-columns-current-fmt-compiled nil)
16393 (while (string-match
16394 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16395 fmt start)
16396 (setq start (match-end 0)
16397 width (match-string 1 fmt)
16398 prop (match-string 2 fmt)
16399 title (or (match-string 3 fmt) prop)
16400 op (match-string 4 fmt)
16401 f nil
16402 printf nil)
16403 (if width (setq width (string-to-number width)))
16404 (when (and op (string-match ";" op))
16405 (setq printf (substring op (match-end 0))
16406 op (substring op 0 (match-beginning 0))))
16407 (cond
16408 ((equal op "+") (setq f 'add_numbers))
16409 ((equal op "$") (setq f 'currency))
16410 ((equal op ":") (setq f 'add_times))
16411 ((equal op "X") (setq f 'checkbox)))
16412 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
16413 (setq org-columns-current-fmt-compiled
16414 (nreverse org-columns-current-fmt-compiled))))
16417 ;;; Dynamic block for Column view
16419 (defun org-columns-capture-view ()
16420 "Get the column view of the current buffer and return it as a list.
16421 The list will contains the title row and all other rows. Each row is
16422 a list of fields."
16423 (save-excursion
16424 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
16425 (n (length title)) row tbl)
16426 (goto-char (point-min))
16427 (while (re-search-forward "^\\*+ " nil t)
16428 (when (get-char-property (match-beginning 0) 'org-columns-key)
16429 (setq row nil)
16430 (loop for i from 0 to (1- n) do
16431 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
16432 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
16434 row))
16435 (setq row (nreverse row))
16436 (push row tbl)))
16437 (append (list title 'hline) (nreverse tbl)))))
16439 (defun org-dblock-write:columnview (params)
16440 "Write the column view table.
16441 PARAMS is a property list of parameters:
16443 :width enforce same column widths with <N> specifiers.
16444 :id the :ID: property of the entry where the columns view
16445 should be built, as a string. When `local', call locally.
16446 When `global' call column view with the cursor at the beginning
16447 of the buffer (usually this means that the whole buffer switches
16448 to column view).
16449 :hlines When t, insert a hline before each item. When a number, insert
16450 a hline before each level <= that number.
16451 :vlines When t, make each column a colgroup to enforce vertical lines."
16452 (let ((pos (move-marker (make-marker) (point)))
16453 (hlines (plist-get params :hlines))
16454 (vlines (plist-get params :vlines))
16455 tbl id idpos nfields tmp)
16456 (save-excursion
16457 (save-restriction
16458 (when (setq id (plist-get params :id))
16459 (cond ((not id) nil)
16460 ((eq id 'global) (goto-char (point-min)))
16461 ((eq id 'local) nil)
16462 ((setq idpos (org-find-entry-with-id id))
16463 (goto-char idpos))
16464 (t (error "Cannot find entry with :ID: %s" id))))
16465 (org-columns)
16466 (setq tbl (org-columns-capture-view))
16467 (setq nfields (length (car tbl)))
16468 (org-columns-quit)))
16469 (goto-char pos)
16470 (move-marker pos nil)
16471 (when tbl
16472 (when (plist-get params :hlines)
16473 (setq tmp nil)
16474 (while tbl
16475 (if (eq (car tbl) 'hline)
16476 (push (pop tbl) tmp)
16477 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
16478 (if (and (not (eq (car tmp) 'hline))
16479 (or (eq hlines t)
16480 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
16481 (push 'hline tmp)))
16482 (push (pop tbl) tmp)))
16483 (setq tbl (nreverse tmp)))
16484 (when vlines
16485 (setq tbl (mapcar (lambda (x)
16486 (if (eq 'hline x) x (cons "" x)))
16487 tbl))
16488 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
16489 (setq pos (point))
16490 (insert (org-listtable-to-string tbl))
16491 (when (plist-get params :width)
16492 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
16493 org-columns-current-widths "|")))
16494 (goto-char pos)
16495 (org-table-align))))
16497 (defun org-listtable-to-string (tbl)
16498 "Convert a listtable TBL to a string that contains the Org-mode table.
16499 The table still need to be alligned. The resulting string has no leading
16500 and tailing newline characters."
16501 (mapconcat
16502 (lambda (x)
16503 (cond
16504 ((listp x)
16505 (concat "|" (mapconcat 'identity x "|") "|"))
16506 ((eq x 'hline) "|-|")
16507 (t (error "Garbage in listtable: %s" x))))
16508 tbl "\n"))
16510 (defun org-insert-columns-dblock ()
16511 "Create a dynamic block capturing a column view table."
16512 (interactive)
16513 (let ((defaults '(:name "columnview" :hlines 1))
16514 (id (completing-read
16515 "Capture columns (local, global, entry with :ID: property) [local]: "
16516 (append '(("global") ("local"))
16517 (mapcar 'list (org-property-values "ID"))))))
16518 (if (equal id "") (setq id 'local))
16519 (if (equal id "global") (setq id 'global))
16520 (setq defaults (append defaults (list :id id)))
16521 (org-create-dblock defaults)
16522 (org-update-dblock)))
16524 ;;;; Timestamps
16526 (defvar org-last-changed-timestamp nil)
16527 (defvar org-time-was-given) ; dynamically scoped parameter
16528 (defvar org-end-time-was-given) ; dynamically scoped parameter
16529 (defvar org-ts-what) ; dynamically scoped parameter
16531 (defun org-time-stamp (arg)
16532 "Prompt for a date/time and insert a time stamp.
16533 If the user specifies a time like HH:MM, or if this command is called
16534 with a prefix argument, the time stamp will contain date and time.
16535 Otherwise, only the date will be included. All parts of a date not
16536 specified by the user will be filled in from the current date/time.
16537 So if you press just return without typing anything, the time stamp
16538 will represent the current date/time. If there is already a timestamp
16539 at the cursor, it will be modified."
16540 (interactive "P")
16541 (let* ((ts nil)
16542 (default-time
16543 ;; Default time is either today, or, when entering a range,
16544 ;; the range start.
16545 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16546 (save-excursion
16547 (re-search-backward
16548 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16549 (- (point) 20) t)))
16550 (apply 'encode-time (org-parse-time-string (match-string 1)))
16551 (current-time)))
16552 (default-input (and ts (org-get-compact-tod ts)))
16553 org-time-was-given org-end-time-was-given time)
16554 (cond
16555 ((and (org-at-timestamp-p)
16556 (eq last-command 'org-time-stamp)
16557 (eq this-command 'org-time-stamp))
16558 (insert "--")
16559 (setq time (let ((this-command this-command))
16560 (org-read-date arg 'totime nil nil default-time default-input)))
16561 (org-insert-time-stamp time (or org-time-was-given arg)))
16562 ((org-at-timestamp-p)
16563 (setq time (let ((this-command this-command))
16564 (org-read-date arg 'totime nil nil default-time default-input)))
16565 (when (org-at-timestamp-p) ; just to get the match data
16566 (replace-match "")
16567 (setq org-last-changed-timestamp
16568 (org-insert-time-stamp
16569 time (or org-time-was-given arg)
16570 nil nil nil (list org-end-time-was-given))))
16571 (message "Timestamp updated"))
16573 (setq time (let ((this-command this-command))
16574 (org-read-date arg 'totime nil nil default-time default-input)))
16575 (org-insert-time-stamp time (or org-time-was-given arg)
16576 nil nil nil (list org-end-time-was-given))))))
16578 ;; FIXME: can we use this for something else????
16579 ;; like computing time differences?????
16580 (defun org-get-compact-tod (s)
16581 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16582 (let* ((t1 (match-string 1 s))
16583 (h1 (string-to-number (match-string 2 s)))
16584 (m1 (string-to-number (match-string 3 s)))
16585 (t2 (and (match-end 4) (match-string 5 s)))
16586 (h2 (and t2 (string-to-number (match-string 6 s))))
16587 (m2 (and t2 (string-to-number (match-string 7 s))))
16588 dh dm)
16589 (if (not t2)
16591 (setq dh (- h2 h1) dm (- m2 m1))
16592 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16593 (concat t1 "+" (number-to-string dh)
16594 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16596 (defun org-time-stamp-inactive (&optional arg)
16597 "Insert an inactive time stamp.
16598 An inactive time stamp is enclosed in square brackets instead of angle
16599 brackets. It is inactive in the sense that it does not trigger agenda entries,
16600 does not link to the calendar and cannot be changed with the S-cursor keys.
16601 So these are more for recording a certain time/date."
16602 (interactive "P")
16603 (let (org-time-was-given org-end-time-was-given time)
16604 (setq time (org-read-date arg 'totime))
16605 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
16606 nil nil (list org-end-time-was-given))))
16608 (defvar org-date-ovl (org-make-overlay 1 1))
16609 (org-overlay-put org-date-ovl 'face 'org-warning)
16610 (org-detach-overlay org-date-ovl)
16612 (defvar org-ans1) ; dynamically scoped parameter
16613 (defvar org-ans2) ; dynamically scoped parameter
16615 (defvar org-plain-time-of-day-regexp) ; defined below
16617 (defvar org-read-date-overlay nil)
16618 (defvar org-dcst nil) ; dynamically scoped
16620 (defun org-read-date (&optional with-time to-time from-string prompt
16621 default-time default-input)
16622 "Read a date, possibly a time, and make things smooth for the user.
16623 The prompt will suggest to enter an ISO date, but you can also enter anything
16624 which will at least partially be understood by `parse-time-string'.
16625 Unrecognized parts of the date will default to the current day, month, year,
16626 hour and minute. If this command is called to replace a timestamp at point,
16627 of to enter the second timestamp of a range, the default time is taken from the
16628 existing stamp. For example,
16629 3-2-5 --> 2003-02-05
16630 feb 15 --> currentyear-02-15
16631 sep 12 9 --> 2009-09-12
16632 12:45 --> today 12:45
16633 22 sept 0:34 --> currentyear-09-22 0:34
16634 12 --> currentyear-currentmonth-12
16635 Fri --> nearest Friday (today or later)
16636 etc.
16638 Furthermore you can specify a relative date by giving, as the *first* thing
16639 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
16640 change in days weeks, months, years.
16641 With a single plus or minus, the date is relative to today. With a double
16642 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16643 +4d --> four days from today
16644 +4 --> same as above
16645 +2w --> two weeks from today
16646 ++5 --> five days from default date
16648 The function understands only English month and weekday abbreviations,
16649 but this can be configured with the variables `parse-time-months' and
16650 `parse-time-weekdays'.
16652 While prompting, a calendar is popped up - you can also select the
16653 date with the mouse (button 1). The calendar shows a period of three
16654 months. To scroll it to other months, use the keys `>' and `<'.
16655 If you don't like the calendar, turn it off with
16656 \(setq org-read-date-popup-calendar nil)
16658 With optional argument TO-TIME, the date will immediately be converted
16659 to an internal time.
16660 With an optional argument WITH-TIME, the prompt will suggest to also
16661 insert a time. Note that when WITH-TIME is not set, you can still
16662 enter a time, and this function will inform the calling routine about
16663 this change. The calling routine may then choose to change the format
16664 used to insert the time stamp into the buffer to include the time.
16665 With optional argument FROM-STRING, read from this string instead from
16666 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16667 the time/date that is used for everything that is not specified by the
16668 user."
16669 (require 'parse-time)
16670 (let* ((org-time-stamp-rounding-minutes
16671 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
16672 (org-dcst org-display-custom-times)
16673 (ct (org-current-time))
16674 (def (or default-time ct))
16675 (defdecode (decode-time def))
16676 (dummy (progn
16677 (when (< (nth 2 defdecode) org-extend-today-until)
16678 (setcar (nthcdr 2 defdecode) -1)
16679 (setcar (nthcdr 1 defdecode) 59)
16680 (setq def (apply 'encode-time defdecode)
16681 defdecode (decode-time def)))))
16682 (calendar-move-hook nil)
16683 (view-diary-entries-initially nil)
16684 (view-calendar-holidays-initially nil)
16685 (timestr (format-time-string
16686 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
16687 (prompt (concat (if prompt (concat prompt " ") "")
16688 (format "Date+time [%s]: " timestr)))
16689 ans (org-ans0 "") org-ans1 org-ans2 final)
16691 (cond
16692 (from-string (setq ans from-string))
16693 (org-read-date-popup-calendar
16694 (save-excursion
16695 (save-window-excursion
16696 (calendar)
16697 (calendar-forward-day (- (time-to-days def)
16698 (calendar-absolute-from-gregorian
16699 (calendar-current-date))))
16700 (org-eval-in-calendar nil t)
16701 (let* ((old-map (current-local-map))
16702 (map (copy-keymap calendar-mode-map))
16703 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
16704 (org-defkey map (kbd "RET") 'org-calendar-select)
16705 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
16706 'org-calendar-select-mouse)
16707 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
16708 'org-calendar-select-mouse)
16709 (org-defkey minibuffer-local-map [(meta shift left)]
16710 (lambda () (interactive)
16711 (org-eval-in-calendar '(calendar-backward-month 1))))
16712 (org-defkey minibuffer-local-map [(meta shift right)]
16713 (lambda () (interactive)
16714 (org-eval-in-calendar '(calendar-forward-month 1))))
16715 (org-defkey minibuffer-local-map [(meta shift up)]
16716 (lambda () (interactive)
16717 (org-eval-in-calendar '(calendar-backward-year 1))))
16718 (org-defkey minibuffer-local-map [(meta shift down)]
16719 (lambda () (interactive)
16720 (org-eval-in-calendar '(calendar-forward-year 1))))
16721 (org-defkey minibuffer-local-map [(shift up)]
16722 (lambda () (interactive)
16723 (org-eval-in-calendar '(calendar-backward-week 1))))
16724 (org-defkey minibuffer-local-map [(shift down)]
16725 (lambda () (interactive)
16726 (org-eval-in-calendar '(calendar-forward-week 1))))
16727 (org-defkey minibuffer-local-map [(shift left)]
16728 (lambda () (interactive)
16729 (org-eval-in-calendar '(calendar-backward-day 1))))
16730 (org-defkey minibuffer-local-map [(shift right)]
16731 (lambda () (interactive)
16732 (org-eval-in-calendar '(calendar-forward-day 1))))
16733 (org-defkey minibuffer-local-map ">"
16734 (lambda () (interactive)
16735 (org-eval-in-calendar '(scroll-calendar-left 1))))
16736 (org-defkey minibuffer-local-map "<"
16737 (lambda () (interactive)
16738 (org-eval-in-calendar '(scroll-calendar-right 1))))
16739 (unwind-protect
16740 (progn
16741 (use-local-map map)
16742 (add-hook 'post-command-hook 'org-read-date-display)
16743 (setq org-ans0 (read-string prompt default-input nil nil))
16744 ;; org-ans0: from prompt
16745 ;; org-ans1: from mouse click
16746 ;; org-ans2: from calendar motion
16747 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16748 (remove-hook 'post-command-hook 'org-read-date-display)
16749 (use-local-map old-map)
16750 (when org-read-date-overlay
16751 (org-delete-overlay org-read-date-overlay)
16752 (setq org-read-date-overlay nil)))))))
16754 (t ; Naked prompt only
16755 (unwind-protect
16756 (setq ans (read-string prompt default-input nil timestr))
16757 (when org-read-date-overlay
16758 (org-delete-overlay org-read-date-overlay)
16759 (setq org-read-date-overlay nil)))))
16761 (setq final (org-read-date-analyze ans def defdecode))
16763 (if to-time
16764 (apply 'encode-time final)
16765 (if (and (boundp 'org-time-was-given) org-time-was-given)
16766 (format "%04d-%02d-%02d %02d:%02d"
16767 (nth 5 final) (nth 4 final) (nth 3 final)
16768 (nth 2 final) (nth 1 final))
16769 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16770 (defvar def)
16771 (defvar defdecode)
16772 (defvar with-time)
16773 (defun org-read-date-display ()
16774 "Display the currrent date prompt interpretation in the minibuffer."
16775 (when org-read-date-display-live
16776 (when org-read-date-overlay
16777 (org-delete-overlay org-read-date-overlay))
16778 (let ((p (point)))
16779 (end-of-line 1)
16780 (while (not (equal (buffer-substring
16781 (max (point-min) (- (point) 4)) (point))
16782 " "))
16783 (insert " "))
16784 (goto-char p))
16785 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16786 " " (or org-ans1 org-ans2)))
16787 (org-end-time-was-given nil)
16788 (f (org-read-date-analyze ans def defdecode))
16789 (fmts (if org-dcst
16790 org-time-stamp-custom-formats
16791 org-time-stamp-formats))
16792 (fmt (if (or with-time
16793 (and (boundp 'org-time-was-given) org-time-was-given))
16794 (cdr fmts)
16795 (car fmts)))
16796 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
16797 (when (and org-end-time-was-given
16798 (string-match org-plain-time-of-day-regexp txt))
16799 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16800 org-end-time-was-given
16801 (substring txt (match-end 0)))))
16802 (setq org-read-date-overlay
16803 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16804 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
16806 (defun org-read-date-analyze (ans def defdecode)
16807 "Analyze the combined answer of the date prompt."
16808 ;; FIXME: cleanup and comment
16809 (let (delta deltan deltaw deltadef year month day
16810 hour minute second wday pm h2 m2 tl wday1)
16812 (when (setq delta (org-read-date-get-relative ans (current-time) def))
16813 (setq ans (replace-match "" t t ans)
16814 deltan (car delta)
16815 deltaw (nth 1 delta)
16816 deltadef (nth 2 delta)))
16818 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
16819 (when (string-match
16820 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16821 (setq year (if (match-end 2)
16822 (string-to-number (match-string 2 ans))
16823 (string-to-number (format-time-string "%Y")))
16824 month (string-to-number (match-string 3 ans))
16825 day (string-to-number (match-string 4 ans)))
16826 (if (< year 100) (setq year (+ 2000 year)))
16827 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16828 t nil ans)))
16829 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16830 ;; If there is a time with am/pm, and *no* time without it, we convert
16831 ;; so that matching will be successful.
16832 (loop for i from 1 to 2 do ; twice, for end time as well
16833 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16834 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16835 (setq hour (string-to-number (match-string 1 ans))
16836 minute (if (match-end 3)
16837 (string-to-number (match-string 3 ans))
16839 pm (equal ?p
16840 (string-to-char (downcase (match-string 4 ans)))))
16841 (if (and (= hour 12) (not pm))
16842 (setq hour 0)
16843 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16844 (setq ans (replace-match (format "%02d:%02d" hour minute)
16845 t t ans))))
16847 ;; Check if a time range is given as a duration
16848 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16849 (setq hour (string-to-number (match-string 1 ans))
16850 h2 (+ hour (string-to-number (match-string 3 ans)))
16851 minute (string-to-number (match-string 2 ans))
16852 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
16853 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16854 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
16856 ;; Check if there is a time range
16857 (when (boundp 'org-end-time-was-given)
16858 (setq org-time-was-given nil)
16859 (when (and (string-match org-plain-time-of-day-regexp ans)
16860 (match-end 8))
16861 (setq org-end-time-was-given (match-string 8 ans))
16862 (setq ans (concat (substring ans 0 (match-beginning 7))
16863 (substring ans (match-end 7))))))
16865 (setq tl (parse-time-string ans)
16866 day (or (nth 3 tl) (nth 3 defdecode))
16867 month (or (nth 4 tl)
16868 (if (and org-read-date-prefer-future
16869 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
16870 (1+ (nth 4 defdecode))
16871 (nth 4 defdecode)))
16872 year (or (nth 5 tl)
16873 (if (and org-read-date-prefer-future
16874 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
16875 (1+ (nth 5 defdecode))
16876 (nth 5 defdecode)))
16877 hour (or (nth 2 tl) (nth 2 defdecode))
16878 minute (or (nth 1 tl) (nth 1 defdecode))
16879 second (or (nth 0 tl) 0)
16880 wday (nth 6 tl))
16881 (when deltan
16882 (unless deltadef
16883 (let ((now (decode-time (current-time))))
16884 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16885 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16886 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16887 ((equal deltaw "m") (setq month (+ month deltan)))
16888 ((equal deltaw "y") (setq year (+ year deltan)))))
16889 (when (and wday (not (nth 3 tl)))
16890 ;; Weekday was given, but no day, so pick that day in the week
16891 ;; on or after the derived date.
16892 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16893 (unless (equal wday wday1)
16894 (setq day (+ day (% (- wday wday1 -7) 7)))))
16895 (if (and (boundp 'org-time-was-given)
16896 (nth 2 tl))
16897 (setq org-time-was-given t))
16898 (if (< year 100) (setq year (+ 2000 year)))
16899 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
16900 (list second minute hour day month year)))
16902 (defvar parse-time-weekdays)
16904 (defun org-read-date-get-relative (s today default)
16905 "Check string S for special relative date string.
16906 TODAY and DEFAULT are internal times, for today and for a default.
16907 Return shift list (N what def-flag)
16908 WHAT is \"d\", \"w\", \"m\", or \"y\" for day. week, month, year.
16909 N is the number if WHATs to shift
16910 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16911 the DEFAULT date rather than TODAY."
16912 (when (string-match
16913 (concat
16914 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
16915 "\\([0-9]+\\)?"
16916 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16917 "\\([ \t]\\|$\\)") s)
16918 (let* ((dir (if (match-end 1)
16919 (string-to-char (substring (match-string 1 s) -1))
16920 ?+))
16921 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16922 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16923 (what (if (match-end 3) (match-string 3 s) "d"))
16924 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16925 (date (if rel default today))
16926 (wday (nth 6 (decode-time date)))
16927 delta)
16928 (if wday1
16929 (progn
16930 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16931 (if (= dir ?-) (setq delta (- delta 7)))
16932 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16933 (list delta "d" rel))
16934 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16936 (defun org-eval-in-calendar (form &optional keepdate)
16937 "Eval FORM in the calendar window and return to current window.
16938 Also, store the cursor date in variable org-ans2."
16939 (let ((sw (selected-window)))
16940 (select-window (get-buffer-window "*Calendar*"))
16941 (eval form)
16942 (when (and (not keepdate) (calendar-cursor-to-date))
16943 (let* ((date (calendar-cursor-to-date))
16944 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16945 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16946 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16947 (select-window sw)))
16949 ; ;; Update the prompt to show new default date
16950 ; (save-excursion
16951 ; (goto-char (point-min))
16952 ; (when (and org-ans2
16953 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
16954 ; (get-text-property (match-end 0) 'field))
16955 ; (let ((inhibit-read-only t))
16956 ; (replace-match (concat "[" org-ans2 "]") t t)
16957 ; (add-text-properties (point-min) (1+ (match-end 0))
16958 ; (text-properties-at (1+ (point-min)))))))))
16960 (defun org-calendar-select ()
16961 "Return to `org-read-date' with the date currently selected.
16962 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16963 (interactive)
16964 (when (calendar-cursor-to-date)
16965 (let* ((date (calendar-cursor-to-date))
16966 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16967 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16968 (if (active-minibuffer-window) (exit-minibuffer))))
16970 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16971 "Insert a date stamp for the date given by the internal TIME.
16972 WITH-HM means, use the stamp format that includes the time of the day.
16973 INACTIVE means use square brackets instead of angular ones, so that the
16974 stamp will not contribute to the agenda.
16975 PRE and POST are optional strings to be inserted before and after the
16976 stamp.
16977 The command returns the inserted time stamp."
16978 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16979 stamp)
16980 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16981 (insert-before-markers (or pre ""))
16982 (insert-before-markers (setq stamp (format-time-string fmt time)))
16983 (when (listp extra)
16984 (setq extra (car extra))
16985 (if (and (stringp extra)
16986 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16987 (setq extra (format "-%02d:%02d"
16988 (string-to-number (match-string 1 extra))
16989 (string-to-number (match-string 2 extra))))
16990 (setq extra nil)))
16991 (when extra
16992 (backward-char 1)
16993 (insert-before-markers extra)
16994 (forward-char 1))
16995 (insert-before-markers (or post ""))
16996 stamp))
16998 (defun org-toggle-time-stamp-overlays ()
16999 "Toggle the use of custom time stamp formats."
17000 (interactive)
17001 (setq org-display-custom-times (not org-display-custom-times))
17002 (unless org-display-custom-times
17003 (let ((p (point-min)) (bmp (buffer-modified-p)))
17004 (while (setq p (next-single-property-change p 'display))
17005 (if (and (get-text-property p 'display)
17006 (eq (get-text-property p 'face) 'org-date))
17007 (remove-text-properties
17008 p (setq p (next-single-property-change p 'display))
17009 '(display t))))
17010 (set-buffer-modified-p bmp)))
17011 (if (featurep 'xemacs)
17012 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17013 (org-restart-font-lock)
17014 (setq org-table-may-need-update t)
17015 (if org-display-custom-times
17016 (message "Time stamps are overlayed with custom format")
17017 (message "Time stamp overlays removed")))
17019 (defun org-display-custom-time (beg end)
17020 "Overlay modified time stamp format over timestamp between BED and END."
17021 (let* ((ts (buffer-substring beg end))
17022 t1 w1 with-hm tf time str w2 (off 0))
17023 (save-match-data
17024 (setq t1 (org-parse-time-string ts t))
17025 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17026 (setq off (- (match-end 0) (match-beginning 0)))))
17027 (setq end (- end off))
17028 (setq w1 (- end beg)
17029 with-hm (and (nth 1 t1) (nth 2 t1))
17030 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17031 time (org-fix-decoded-time t1)
17032 str (org-add-props
17033 (format-time-string
17034 (substring tf 1 -1) (apply 'encode-time time))
17035 nil 'mouse-face 'highlight)
17036 w2 (length str))
17037 (if (not (= w2 w1))
17038 (add-text-properties (1+ beg) (+ 2 beg)
17039 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17040 (if (featurep 'xemacs)
17041 (progn
17042 (put-text-property beg end 'invisible t)
17043 (put-text-property beg end 'end-glyph (make-glyph str)))
17044 (put-text-property beg end 'display str))))
17046 (defun org-translate-time (string)
17047 "Translate all timestamps in STRING to custom format.
17048 But do this only if the variable `org-display-custom-times' is set."
17049 (when org-display-custom-times
17050 (save-match-data
17051 (let* ((start 0)
17052 (re org-ts-regexp-both)
17053 t1 with-hm inactive tf time str beg end)
17054 (while (setq start (string-match re string start))
17055 (setq beg (match-beginning 0)
17056 end (match-end 0)
17057 t1 (save-match-data
17058 (org-parse-time-string (substring string beg end) t))
17059 with-hm (and (nth 1 t1) (nth 2 t1))
17060 inactive (equal (substring string beg (1+ beg)) "[")
17061 tf (funcall (if with-hm 'cdr 'car)
17062 org-time-stamp-custom-formats)
17063 time (org-fix-decoded-time t1)
17064 str (format-time-string
17065 (concat
17066 (if inactive "[" "<") (substring tf 1 -1)
17067 (if inactive "]" ">"))
17068 (apply 'encode-time time))
17069 string (replace-match str t t string)
17070 start (+ start (length str)))))))
17071 string)
17073 (defun org-fix-decoded-time (time)
17074 "Set 0 instead of nil for the first 6 elements of time.
17075 Don't touch the rest."
17076 (let ((n 0))
17077 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17079 (defun org-days-to-time (timestamp-string)
17080 "Difference between TIMESTAMP-STRING and now in days."
17081 (- (time-to-days (org-time-string-to-time timestamp-string))
17082 (time-to-days (current-time))))
17084 (defun org-deadline-close (timestamp-string &optional ndays)
17085 "Is the time in TIMESTAMP-STRING close to the current date?"
17086 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17087 (and (< (org-days-to-time timestamp-string) ndays)
17088 (not (org-entry-is-done-p))))
17090 (defun org-get-wdays (ts)
17091 "Get the deadline lead time appropriate for timestring TS."
17092 (cond
17093 ((<= org-deadline-warning-days 0)
17094 ;; 0 or negative, enforce this value no matter what
17095 (- org-deadline-warning-days))
17096 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17097 ;; lead time is specified.
17098 (floor (* (string-to-number (match-string 1 ts))
17099 (cdr (assoc (match-string 2 ts)
17100 '(("d" . 1) ("w" . 7)
17101 ("m" . 30.4) ("y" . 365.25)))))))
17102 ;; go for the default.
17103 (t org-deadline-warning-days)))
17105 (defun org-calendar-select-mouse (ev)
17106 "Return to `org-read-date' with the date currently selected.
17107 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17108 (interactive "e")
17109 (mouse-set-point ev)
17110 (when (calendar-cursor-to-date)
17111 (let* ((date (calendar-cursor-to-date))
17112 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17113 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17114 (if (active-minibuffer-window) (exit-minibuffer))))
17116 (defun org-check-deadlines (ndays)
17117 "Check if there are any deadlines due or past due.
17118 A deadline is considered due if it happens within `org-deadline-warning-days'
17119 days from today's date. If the deadline appears in an entry marked DONE,
17120 it is not shown. The prefix arg NDAYS can be used to test that many
17121 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17122 (interactive "P")
17123 (let* ((org-warn-days
17124 (cond
17125 ((equal ndays '(4)) 100000)
17126 (ndays (prefix-numeric-value ndays))
17127 (t (abs org-deadline-warning-days))))
17128 (case-fold-search nil)
17129 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17130 (callback
17131 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17133 (message "%d deadlines past-due or due within %d days"
17134 (org-occur regexp nil callback)
17135 org-warn-days)))
17137 (defun org-evaluate-time-range (&optional to-buffer)
17138 "Evaluate a time range by computing the difference between start and end.
17139 Normally the result is just printed in the echo area, but with prefix arg
17140 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17141 If the time range is actually in a table, the result is inserted into the
17142 next column.
17143 For time difference computation, a year is assumed to be exactly 365
17144 days in order to avoid rounding problems."
17145 (interactive "P")
17147 (org-clock-update-time-maybe)
17148 (save-excursion
17149 (unless (org-at-date-range-p t)
17150 (goto-char (point-at-bol))
17151 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17152 (if (not (org-at-date-range-p t))
17153 (error "Not at a time-stamp range, and none found in current line")))
17154 (let* ((ts1 (match-string 1))
17155 (ts2 (match-string 2))
17156 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17157 (match-end (match-end 0))
17158 (time1 (org-time-string-to-time ts1))
17159 (time2 (org-time-string-to-time ts2))
17160 (t1 (time-to-seconds time1))
17161 (t2 (time-to-seconds time2))
17162 (diff (abs (- t2 t1)))
17163 (negative (< (- t2 t1) 0))
17164 ;; (ys (floor (* 365 24 60 60)))
17165 (ds (* 24 60 60))
17166 (hs (* 60 60))
17167 (fy "%dy %dd %02d:%02d")
17168 (fy1 "%dy %dd")
17169 (fd "%dd %02d:%02d")
17170 (fd1 "%dd")
17171 (fh "%02d:%02d")
17172 y d h m align)
17173 (if havetime
17174 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17176 d (floor (/ diff ds)) diff (mod diff ds)
17177 h (floor (/ diff hs)) diff (mod diff hs)
17178 m (floor (/ diff 60)))
17179 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17181 d (floor (+ (/ diff ds) 0.5))
17182 h 0 m 0))
17183 (if (not to-buffer)
17184 (message (org-make-tdiff-string y d h m))
17185 (if (org-at-table-p)
17186 (progn
17187 (goto-char match-end)
17188 (setq align t)
17189 (and (looking-at " *|") (goto-char (match-end 0))))
17190 (goto-char match-end))
17191 (if (looking-at
17192 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17193 (replace-match ""))
17194 (if negative (insert " -"))
17195 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17196 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17197 (insert " " (format fh h m))))
17198 (if align (org-table-align))
17199 (message "Time difference inserted")))))
17201 (defun org-make-tdiff-string (y d h m)
17202 (let ((fmt "")
17203 (l nil))
17204 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17205 l (push y l)))
17206 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17207 l (push d l)))
17208 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17209 l (push h l)))
17210 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17211 l (push m l)))
17212 (apply 'format fmt (nreverse l))))
17214 (defun org-time-string-to-time (s)
17215 (apply 'encode-time (org-parse-time-string s)))
17217 (defun org-time-string-to-absolute (s &optional daynr)
17218 "Convert a time stamp to an absolute day number.
17219 If there is a specifyer for a cyclic time stamp, get the closest date to
17220 DAYNR."
17221 (cond
17222 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17223 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17224 daynr
17225 (+ daynr 1000)))
17226 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
17227 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17228 (time-to-days (current-time))) (match-string 0 s)))
17229 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
17231 (defun org-time-from-absolute (d)
17232 "Return the time corresponding to date D.
17233 D may be an absolute day number, or a calendar-type list (month day year)."
17234 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17235 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17237 (defun org-calendar-holiday ()
17238 "List of holidays, for Diary display in Org-mode."
17239 (require 'holidays)
17240 (let ((hl (funcall
17241 (if (fboundp 'calendar-check-holidays)
17242 'calendar-check-holidays 'check-calendar-holidays) date)))
17243 (if hl (mapconcat 'identity hl "; "))))
17245 (defun org-diary-sexp-entry (sexp entry date)
17246 "Process a SEXP diary ENTRY for DATE."
17247 (require 'diary-lib)
17248 (let ((result (if calendar-debug-sexp
17249 (let ((stack-trace-on-error t))
17250 (eval (car (read-from-string sexp))))
17251 (condition-case nil
17252 (eval (car (read-from-string sexp)))
17253 (error
17254 (beep)
17255 (message "Bad sexp at line %d in %s: %s"
17256 (org-current-line)
17257 (buffer-file-name) sexp)
17258 (sleep-for 2))))))
17259 (cond ((stringp result) result)
17260 ((and (consp result)
17261 (stringp (cdr result))) (cdr result))
17262 (result entry)
17263 (t nil))))
17265 (defun org-diary-to-ical-string (frombuf)
17266 "Get iCalendar entries from diary entries in buffer FROMBUF.
17267 This uses the icalendar.el library."
17268 (let* ((tmpdir (if (featurep 'xemacs)
17269 (temp-directory)
17270 temporary-file-directory))
17271 (tmpfile (make-temp-name
17272 (expand-file-name "orgics" tmpdir)))
17273 buf rtn b e)
17274 (save-excursion
17275 (set-buffer frombuf)
17276 (icalendar-export-region (point-min) (point-max) tmpfile)
17277 (setq buf (find-buffer-visiting tmpfile))
17278 (set-buffer buf)
17279 (goto-char (point-min))
17280 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17281 (setq b (match-beginning 0)))
17282 (goto-char (point-max))
17283 (if (re-search-backward "^END:VEVENT" nil t)
17284 (setq e (match-end 0)))
17285 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17286 (kill-buffer buf)
17287 (kill-buffer frombuf)
17288 (delete-file tmpfile)
17289 rtn))
17291 (defun org-closest-date (start current change)
17292 "Find the date closest to CURRENT that is consistent with START and CHANGE."
17293 ;; Make the proper lists from the dates
17294 (catch 'exit
17295 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
17296 dn dw sday cday n1 n2
17297 d m y y1 y2 date1 date2 nmonths nm ny m2)
17299 (setq start (org-date-to-gregorian start)
17300 current (org-date-to-gregorian
17301 (if org-agenda-repeating-timestamp-show-all
17302 current
17303 (time-to-days (current-time))))
17304 sday (calendar-absolute-from-gregorian start)
17305 cday (calendar-absolute-from-gregorian current))
17307 (if (<= cday sday) (throw 'exit sday))
17309 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
17310 (setq dn (string-to-number (match-string 1 change))
17311 dw (cdr (assoc (match-string 2 change) a1)))
17312 (error "Invalid change specifyer: %s" change))
17313 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17314 (cond
17315 ((eq dw 'day)
17316 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17317 n2 (+ n1 dn)))
17318 ((eq dw 'year)
17319 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17320 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17321 (setq date1 (list m d y1)
17322 n1 (calendar-absolute-from-gregorian date1)
17323 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17324 n2 (calendar-absolute-from-gregorian date2)))
17325 ((eq dw 'month)
17326 ;; approx number of month between the tow dates
17327 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17328 ;; How often does dn fit in there?
17329 (setq d (nth 1 start) m (car start) y (nth 2 start)
17330 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17331 m (+ m nm)
17332 ny (floor (/ m 12))
17333 y (+ y ny)
17334 m (- m (* ny 12)))
17335 (while (> m 12) (setq m (- m 12) y (1+ y)))
17336 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17337 (setq m2 (+ m dn) y2 y)
17338 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17339 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17340 (while (< n2 cday)
17341 (setq n1 n2 m m2 y y2)
17342 (setq m2 (+ m dn) y2 y)
17343 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17344 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17346 (if org-agenda-repeating-timestamp-show-all
17347 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
17348 (if (= cday n1) n1 n2)))))
17350 (defun org-date-to-gregorian (date)
17351 "Turn any specification of DATE into a gregorian date for the calendar."
17352 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17353 ((and (listp date) (= (length date) 3)) date)
17354 ((stringp date)
17355 (setq date (org-parse-time-string date))
17356 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17357 ((listp date)
17358 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17360 (defun org-parse-time-string (s &optional nodefault)
17361 "Parse the standard Org-mode time string.
17362 This should be a lot faster than the normal `parse-time-string'.
17363 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17364 hour and minute fields will be nil if not given."
17365 (if (string-match org-ts-regexp0 s)
17366 (list 0
17367 (if (or (match-beginning 8) (not nodefault))
17368 (string-to-number (or (match-string 8 s) "0")))
17369 (if (or (match-beginning 7) (not nodefault))
17370 (string-to-number (or (match-string 7 s) "0")))
17371 (string-to-number (match-string 4 s))
17372 (string-to-number (match-string 3 s))
17373 (string-to-number (match-string 2 s))
17374 nil nil nil)
17375 (make-list 9 0)))
17377 (defun org-timestamp-up (&optional arg)
17378 "Increase the date item at the cursor by one.
17379 If the cursor is on the year, change the year. If it is on the month or
17380 the day, change that.
17381 With prefix ARG, change by that many units."
17382 (interactive "p")
17383 (org-timestamp-change (prefix-numeric-value arg)))
17385 (defun org-timestamp-down (&optional arg)
17386 "Decrease the date item at the cursor by one.
17387 If the cursor is on the year, change the year. If it is on the month or
17388 the day, change that.
17389 With prefix ARG, change by that many units."
17390 (interactive "p")
17391 (org-timestamp-change (- (prefix-numeric-value arg))))
17393 (defun org-timestamp-up-day (&optional arg)
17394 "Increase the date in the time stamp by one day.
17395 With prefix ARG, change that many days."
17396 (interactive "p")
17397 (if (and (not (org-at-timestamp-p t))
17398 (org-on-heading-p))
17399 (org-todo 'up)
17400 (org-timestamp-change (prefix-numeric-value arg) 'day)))
17402 (defun org-timestamp-down-day (&optional arg)
17403 "Decrease the date in the time stamp by one day.
17404 With prefix ARG, change that many days."
17405 (interactive "p")
17406 (if (and (not (org-at-timestamp-p t))
17407 (org-on-heading-p))
17408 (org-todo 'down)
17409 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
17411 (defsubst org-pos-in-match-range (pos n)
17412 (and (match-beginning n)
17413 (<= (match-beginning n) pos)
17414 (>= (match-end n) pos)))
17416 (defun org-at-timestamp-p (&optional inactive-ok)
17417 "Determine if the cursor is in or at a timestamp."
17418 (interactive)
17419 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17420 (pos (point))
17421 (ans (or (looking-at tsr)
17422 (save-excursion
17423 (skip-chars-backward "^[<\n\r\t")
17424 (if (> (point) (point-min)) (backward-char 1))
17425 (and (looking-at tsr)
17426 (> (- (match-end 0) pos) -1))))))
17427 (and ans
17428 (boundp 'org-ts-what)
17429 (setq org-ts-what
17430 (cond
17431 ((= pos (match-beginning 0)) 'bracket)
17432 ((= pos (1- (match-end 0))) 'bracket)
17433 ((org-pos-in-match-range pos 2) 'year)
17434 ((org-pos-in-match-range pos 3) 'month)
17435 ((org-pos-in-match-range pos 7) 'hour)
17436 ((org-pos-in-match-range pos 8) 'minute)
17437 ((or (org-pos-in-match-range pos 4)
17438 (org-pos-in-match-range pos 5)) 'day)
17439 ((and (> pos (or (match-end 8) (match-end 5)))
17440 (< pos (match-end 0)))
17441 (- pos (or (match-end 8) (match-end 5))))
17442 (t 'day))))
17443 ans))
17445 (defun org-toggle-timestamp-type ()
17447 (interactive)
17448 (when (org-at-timestamp-p t)
17449 (save-excursion
17450 (goto-char (match-beginning 0))
17451 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
17452 (goto-char (1- (match-end 0)))
17453 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
17454 (message "Timestamp is now %sactive"
17455 (if (equal (char-before) ?>) "in" ""))))
17457 (defun org-timestamp-change (n &optional what)
17458 "Change the date in the time stamp at point.
17459 The date will be changed by N times WHAT. WHAT can be `day', `month',
17460 `year', `minute', `second'. If WHAT is not given, the cursor position
17461 in the timestamp determines what will be changed."
17462 (let ((pos (point))
17463 with-hm inactive
17464 org-ts-what
17465 extra
17466 ts time time0)
17467 (if (not (org-at-timestamp-p t))
17468 (error "Not at a timestamp"))
17469 (if (and (not what) (eq org-ts-what 'bracket))
17470 (org-toggle-timestamp-type)
17471 (if (and (not what) (not (eq org-ts-what 'day))
17472 org-display-custom-times
17473 (get-text-property (point) 'display)
17474 (not (get-text-property (1- (point)) 'display)))
17475 (setq org-ts-what 'day))
17476 (setq org-ts-what (or what org-ts-what)
17477 inactive (= (char-after (match-beginning 0)) ?\[)
17478 ts (match-string 0))
17479 (replace-match "")
17480 (if (string-match
17481 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
17483 (setq extra (match-string 1 ts)))
17484 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17485 (setq with-hm t))
17486 (setq time0 (org-parse-time-string ts))
17487 (setq time
17488 (encode-time (or (car time0) 0)
17489 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17490 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17491 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17492 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17493 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17494 (nthcdr 6 time0)))
17495 (when (integerp org-ts-what)
17496 (setq extra (org-modify-ts-extra extra org-ts-what n)))
17497 (if (eq what 'calendar)
17498 (let ((cal-date (org-get-date-from-calendar)))
17499 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17500 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17501 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17502 (setcar time0 (or (car time0) 0))
17503 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17504 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17505 (setq time (apply 'encode-time time0))))
17506 (setq org-last-changed-timestamp
17507 (org-insert-time-stamp time with-hm inactive nil nil extra))
17508 (org-clock-update-time-maybe)
17509 (goto-char pos)
17510 ;; Try to recenter the calendar window, if any
17511 (if (and org-calendar-follow-timestamp-change
17512 (get-buffer-window "*Calendar*" t)
17513 (memq org-ts-what '(day month year)))
17514 (org-recenter-calendar (time-to-days time))))))
17516 ;; FIXME: does not yet work for lead times
17517 (defun org-modify-ts-extra (s pos n)
17518 "Change the different parts of the lead-time and repeat fields in timestamp."
17519 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17520 ng h m new)
17521 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17522 (cond
17523 ((or (org-pos-in-match-range pos 2)
17524 (org-pos-in-match-range pos 3))
17525 (setq m (string-to-number (match-string 3 s))
17526 h (string-to-number (match-string 2 s)))
17527 (if (org-pos-in-match-range pos 2)
17528 (setq h (+ h n))
17529 (setq m (+ m n)))
17530 (if (< m 0) (setq m (+ m 60) h (1- h)))
17531 (if (> m 59) (setq m (- m 60) h (1+ h)))
17532 (setq h (min 24 (max 0 h)))
17533 (setq ng 1 new (format "-%02d:%02d" h m)))
17534 ((org-pos-in-match-range pos 6)
17535 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17536 ((org-pos-in-match-range pos 5)
17537 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
17539 (when ng
17540 (setq s (concat
17541 (substring s 0 (match-beginning ng))
17543 (substring s (match-end ng))))))
17546 (defun org-recenter-calendar (date)
17547 "If the calendar is visible, recenter it to DATE."
17548 (let* ((win (selected-window))
17549 (cwin (get-buffer-window "*Calendar*" t))
17550 (calendar-move-hook nil))
17551 (when cwin
17552 (select-window cwin)
17553 (calendar-goto-date (if (listp date) date
17554 (calendar-gregorian-from-absolute date)))
17555 (select-window win))))
17557 (defun org-goto-calendar (&optional arg)
17558 "Go to the Emacs calendar at the current date.
17559 If there is a time stamp in the current line, go to that date.
17560 A prefix ARG can be used to force the current date."
17561 (interactive "P")
17562 (let ((tsr org-ts-regexp) diff
17563 (calendar-move-hook nil)
17564 (view-calendar-holidays-initially nil)
17565 (view-diary-entries-initially nil))
17566 (if (or (org-at-timestamp-p)
17567 (save-excursion
17568 (beginning-of-line 1)
17569 (looking-at (concat ".*" tsr))))
17570 (let ((d1 (time-to-days (current-time)))
17571 (d2 (time-to-days
17572 (org-time-string-to-time (match-string 1)))))
17573 (setq diff (- d2 d1))))
17574 (calendar)
17575 (calendar-goto-today)
17576 (if (and diff (not arg)) (calendar-forward-day diff))))
17578 (defun org-get-date-from-calendar ()
17579 "Return a list (month day year) of date at point in calendar."
17580 (with-current-buffer "*Calendar*"
17581 (save-match-data
17582 (calendar-cursor-to-date))))
17584 (defun org-date-from-calendar ()
17585 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17586 If there is already a time stamp at the cursor position, update it."
17587 (interactive)
17588 (if (org-at-timestamp-p t)
17589 (org-timestamp-change 0 'calendar)
17590 (let ((cal-date (org-get-date-from-calendar)))
17591 (org-insert-time-stamp
17592 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17594 ;; Make appt aware of appointments from the agenda
17595 ;;;###autoload
17596 (defun org-agenda-to-appt (&optional filter)
17597 "Activate appointments found in `org-agenda-files'.
17598 When prefixed, prompt for a regular expression and use it as a
17599 filter: only add entries if they match this regular expression.
17601 FILTER can be a string. In this case, use this string as a
17602 regular expression to filter results.
17604 FILTER can also be an alist, with the car of each cell being
17605 either 'headline or 'category. For example:
17607 '((headline \"IMPORTANT\")
17608 (category \"Work\"))
17610 will only add headlines containing IMPORTANT or headlines
17611 belonging to the category \"Work\"."
17612 (interactive "P")
17613 (require 'calendar)
17614 (if (equal filter '(4))
17615 (setq filter (read-from-minibuffer "Regexp filter: ")))
17616 (let* ((cnt 0) ; count added events
17617 (today (org-date-to-gregorian
17618 (time-to-days (current-time))))
17619 (files (org-agenda-files)) entries file)
17620 ;; Get all entries which may contain an appt
17621 (while (setq file (pop files))
17622 (setq entries
17623 (append entries
17624 (org-agenda-get-day-entries
17625 file today
17626 :timestamp :scheduled :deadline))))
17627 (setq entries (delq nil entries))
17628 ;; Map thru entries and find if they pass thru the filter
17629 (mapc
17630 (lambda(x)
17631 (let* ((evt (org-trim (get-text-property 1 'txt x)))
17632 (cat (get-text-property 1 'org-category x))
17633 (tod (get-text-property 1 'time-of-day x))
17634 (ok (or (null filter)
17635 (and (stringp filter) (string-match filter evt))
17636 (and (listp filter)
17637 (or (string-match
17638 (cadr (assoc 'category filter)) cat)
17639 (string-match
17640 (cadr (assoc 'headline filter)) evt))))))
17641 ;; FIXME Shall we remove text-properties for the appt text?
17642 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
17643 (when (and ok tod)
17644 (setq tod (number-to-string tod)
17645 tod (when (string-match
17646 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
17647 (concat (match-string 1 tod) ":"
17648 (match-string 2 tod))))
17649 (appt-add tod evt)
17650 (setq cnt (1+ cnt))))) entries)
17651 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
17653 ;;; The clock for measuring work time.
17655 (defvar org-mode-line-string "")
17656 (put 'org-mode-line-string 'risky-local-variable t)
17658 (defvar org-mode-line-timer nil)
17659 (defvar org-clock-heading "")
17660 (defvar org-clock-start-time "")
17662 (defun org-update-mode-line ()
17663 (let* ((delta (- (time-to-seconds (current-time))
17664 (time-to-seconds org-clock-start-time)))
17665 (h (floor delta 3600))
17666 (m (floor (- delta (* 3600 h)) 60)))
17667 (setq org-mode-line-string
17668 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
17669 'help-echo "Org-mode clock is running"))
17670 (force-mode-line-update)))
17672 (defvar org-clock-marker (make-marker)
17673 "Marker recording the last clock-in.")
17674 (defvar org-clock-mode-line-entry nil
17675 "Information for the modeline about the running clock.")
17677 (defun org-clock-in ()
17678 "Start the clock on the current item.
17679 If necessary, clock-out of the currently active clock."
17680 (interactive)
17681 (org-clock-out t)
17682 (let (ts)
17683 (save-excursion
17684 (org-back-to-heading t)
17685 (if (and org-clock-heading-function
17686 (functionp org-clock-heading-function))
17687 (setq org-clock-heading (funcall org-clock-heading-function))
17688 (if (looking-at org-complex-heading-regexp)
17689 (setq org-clock-heading (match-string 4))
17690 (setq org-clock-heading "???")))
17691 (setq org-clock-heading (propertize org-clock-heading 'face nil))
17692 (org-clock-find-position)
17694 (insert "\n") (backward-char 1)
17695 (indent-relative)
17696 (insert org-clock-string " ")
17697 (setq org-clock-start-time (current-time))
17698 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17699 (move-marker org-clock-marker (point) (buffer-base-buffer))
17700 (or global-mode-string (setq global-mode-string '("")))
17701 (or (memq 'org-mode-line-string global-mode-string)
17702 (setq global-mode-string
17703 (append global-mode-string '(org-mode-line-string))))
17704 (org-update-mode-line)
17705 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
17706 (message "Clock started at %s" ts))))
17708 (defun org-clock-find-position ()
17709 "Find the location where the next clock line should be inserted."
17710 (org-back-to-heading t)
17711 (catch 'exit
17712 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
17713 (re (concat "^[ \t]*" org-clock-string))
17714 (cnt 0)
17715 first last)
17716 (goto-char beg)
17717 (when (eobp) (newline) (setq end (max (point) end)))
17718 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
17719 ;; we seem to have a CLOCK drawer, so go there.
17720 (beginning-of-line 2)
17721 (throw 'exit t))
17722 ;; Lets count the CLOCK lines
17723 (goto-char beg)
17724 (while (re-search-forward re end t)
17725 (setq first (or first (match-beginning 0))
17726 last (match-beginning 0)
17727 cnt (1+ cnt)))
17728 (when (and (integerp org-clock-into-drawer)
17729 (>= (1+ cnt) org-clock-into-drawer))
17730 ;; Wrap current entries into a new drawer
17731 (goto-char last)
17732 (beginning-of-line 2)
17733 (if (org-at-item-p) (org-end-of-item))
17734 (insert ":END:\n")
17735 (beginning-of-line 0)
17736 (org-indent-line-function)
17737 (goto-char first)
17738 (insert ":CLOCK:\n")
17739 (beginning-of-line 0)
17740 (org-indent-line-function)
17741 (org-flag-drawer t)
17742 (beginning-of-line 2)
17743 (throw 'exit nil))
17745 (goto-char beg)
17746 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17747 (not (equal (match-string 1) org-clock-string)))
17748 ;; Planning info, skip to after it
17749 (beginning-of-line 2)
17750 (or (bolp) (newline)))
17751 (when (eq t org-clock-into-drawer)
17752 (insert ":CLOCK:\n:END:\n")
17753 (beginning-of-line -1)
17754 (org-indent-line-function)
17755 (org-flag-drawer t)
17756 (beginning-of-line 2)
17757 (org-indent-line-function)))))
17759 (defun org-clock-out (&optional fail-quietly)
17760 "Stop the currently running clock.
17761 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
17762 (interactive)
17763 (catch 'exit
17764 (if (not (marker-buffer org-clock-marker))
17765 (if fail-quietly (throw 'exit t) (error "No active clock")))
17766 (let (ts te s h m)
17767 (save-excursion
17768 (set-buffer (marker-buffer org-clock-marker))
17769 (goto-char org-clock-marker)
17770 (beginning-of-line 1)
17771 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17772 (equal (match-string 1) org-clock-string))
17773 (setq ts (match-string 2))
17774 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
17775 (goto-char (match-end 0))
17776 (delete-region (point) (point-at-eol))
17777 (insert "--")
17778 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17779 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
17780 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
17781 h (floor (/ s 3600))
17782 s (- s (* 3600 h))
17783 m (floor (/ s 60))
17784 s (- s (* 60 s)))
17785 (insert " => " (format "%2d:%02d" h m))
17786 (move-marker org-clock-marker nil)
17787 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
17788 (org-log-done (org-parse-local-options logging 'org-log-done))
17789 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
17790 (org-add-log-maybe 'clock-out))
17791 (when org-mode-line-timer
17792 (cancel-timer org-mode-line-timer)
17793 (setq org-mode-line-timer nil))
17794 (setq global-mode-string
17795 (delq 'org-mode-line-string global-mode-string))
17796 (force-mode-line-update)
17797 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
17799 (defun org-clock-cancel ()
17800 "Cancel the running clock be removing the start timestamp."
17801 (interactive)
17802 (if (not (marker-buffer org-clock-marker))
17803 (error "No active clock"))
17804 (save-excursion
17805 (set-buffer (marker-buffer org-clock-marker))
17806 (goto-char org-clock-marker)
17807 (delete-region (1- (point-at-bol)) (point-at-eol)))
17808 (setq global-mode-string
17809 (delq 'org-mode-line-string global-mode-string))
17810 (force-mode-line-update)
17811 (message "Clock canceled"))
17813 (defun org-clock-goto (&optional delete-windows)
17814 "Go to the currently clocked-in entry."
17815 (interactive "P")
17816 (if (not (marker-buffer org-clock-marker))
17817 (error "No active clock"))
17818 (switch-to-buffer-other-window
17819 (marker-buffer org-clock-marker))
17820 (if delete-windows (delete-other-windows))
17821 (goto-char org-clock-marker)
17822 (org-show-entry)
17823 (org-back-to-heading)
17824 (recenter))
17826 (defvar org-clock-file-total-minutes nil
17827 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
17828 (make-variable-buffer-local 'org-clock-file-total-minutes)
17830 (defun org-clock-sum (&optional tstart tend)
17831 "Sum the times for each subtree.
17832 Puts the resulting times in minutes as a text property on each headline."
17833 (interactive)
17834 (let* ((bmp (buffer-modified-p))
17835 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
17836 org-clock-string
17837 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
17838 (lmax 30)
17839 (ltimes (make-vector lmax 0))
17840 (t1 0)
17841 (level 0)
17842 ts te dt
17843 time)
17844 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
17845 (save-excursion
17846 (goto-char (point-max))
17847 (while (re-search-backward re nil t)
17848 (cond
17849 ((match-end 2)
17850 ;; Two time stamps
17851 (setq ts (match-string 2)
17852 te (match-string 3)
17853 ts (time-to-seconds
17854 (apply 'encode-time (org-parse-time-string ts)))
17855 te (time-to-seconds
17856 (apply 'encode-time (org-parse-time-string te)))
17857 ts (if tstart (max ts tstart) ts)
17858 te (if tend (min te tend) te)
17859 dt (- te ts)
17860 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
17861 ((match-end 4)
17862 ;; A naket time
17863 (setq t1 (+ t1 (string-to-number (match-string 5))
17864 (* 60 (string-to-number (match-string 4))))))
17865 (t ;; A headline
17866 (setq level (- (match-end 1) (match-beginning 1)))
17867 (when (or (> t1 0) (> (aref ltimes level) 0))
17868 (loop for l from 0 to level do
17869 (aset ltimes l (+ (aref ltimes l) t1)))
17870 (setq t1 0 time (aref ltimes level))
17871 (loop for l from level to (1- lmax) do
17872 (aset ltimes l 0))
17873 (goto-char (match-beginning 0))
17874 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
17875 (setq org-clock-file-total-minutes (aref ltimes 0)))
17876 (set-buffer-modified-p bmp)))
17878 (defun org-clock-display (&optional total-only)
17879 "Show subtree times in the entire buffer.
17880 If TOTAL-ONLY is non-nil, only show the total time for the entire file
17881 in the echo area."
17882 (interactive)
17883 (org-remove-clock-overlays)
17884 (let (time h m p)
17885 (org-clock-sum)
17886 (unless total-only
17887 (save-excursion
17888 (goto-char (point-min))
17889 (while (or (and (equal (setq p (point)) (point-min))
17890 (get-text-property p :org-clock-minutes))
17891 (setq p (next-single-property-change
17892 (point) :org-clock-minutes)))
17893 (goto-char p)
17894 (when (setq time (get-text-property p :org-clock-minutes))
17895 (org-put-clock-overlay time (funcall outline-level))))
17896 (setq h (/ org-clock-file-total-minutes 60)
17897 m (- org-clock-file-total-minutes (* 60 h)))
17898 ;; Arrange to remove the overlays upon next change.
17899 (when org-remove-highlights-with-change
17900 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
17901 nil 'local))))
17902 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
17904 (defvar org-clock-overlays nil)
17905 (make-variable-buffer-local 'org-clock-overlays)
17907 (defun org-put-clock-overlay (time &optional level)
17908 "Put an overlays on the current line, displaying TIME.
17909 If LEVEL is given, prefix time with a corresponding number of stars.
17910 This creates a new overlay and stores it in `org-clock-overlays', so that it
17911 will be easy to remove."
17912 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
17913 (l (if level (org-get-legal-level level 0) 0))
17914 (off 0)
17915 ov tx)
17916 (move-to-column c)
17917 (unless (eolp) (skip-chars-backward "^ \t"))
17918 (skip-chars-backward " \t")
17919 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
17920 tx (concat (buffer-substring (1- (point)) (point))
17921 (make-string (+ off (max 0 (- c (current-column)))) ?.)
17922 (org-add-props (format "%s %2d:%02d%s"
17923 (make-string l ?*) h m
17924 (make-string (- 10 l) ?\ ))
17925 '(face secondary-selection))
17926 ""))
17927 (if (not (featurep 'xemacs))
17928 (org-overlay-put ov 'display tx)
17929 (org-overlay-put ov 'invisible t)
17930 (org-overlay-put ov 'end-glyph (make-glyph tx)))
17931 (push ov org-clock-overlays)))
17933 (defun org-remove-clock-overlays (&optional beg end noremove)
17934 "Remove the occur highlights from the buffer.
17935 BEG and END are ignored. If NOREMOVE is nil, remove this function
17936 from the `before-change-functions' in the current buffer."
17937 (interactive)
17938 (unless org-inhibit-highlight-removal
17939 (mapc 'org-delete-overlay org-clock-overlays)
17940 (setq org-clock-overlays nil)
17941 (unless noremove
17942 (remove-hook 'before-change-functions
17943 'org-remove-clock-overlays 'local))))
17945 (defun org-clock-out-if-current ()
17946 "Clock out if the current entry contains the running clock.
17947 This is used to stop the clock after a TODO entry is marked DONE,
17948 and is only done if the variable `org-clock-out-when-done' is not nil."
17949 (when (and org-clock-out-when-done
17950 (member state org-done-keywords)
17951 (equal (marker-buffer org-clock-marker) (current-buffer))
17952 (< (point) org-clock-marker)
17953 (> (save-excursion (outline-next-heading) (point))
17954 org-clock-marker))
17955 ;; Clock out, but don't accept a logging message for this.
17956 (let ((org-log-done (if (and (listp org-log-done)
17957 (member 'clock-out org-log-done))
17958 '(done)
17959 org-log-done)))
17960 (org-clock-out))))
17962 (add-hook 'org-after-todo-state-change-hook
17963 'org-clock-out-if-current)
17965 (defun org-check-running-clock ()
17966 "Check if the current buffer contains the running clock.
17967 If yes, offer to stop it and to save the buffer with the changes."
17968 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
17969 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
17970 (buffer-name))))
17971 (org-clock-out)
17972 (when (y-or-n-p "Save changed buffer?")
17973 (save-buffer))))
17975 (defun org-clock-report (&optional arg)
17976 "Create a table containing a report about clocked time.
17977 If the cursor is inside an existing clocktable block, then the table
17978 will be updated. If not, a new clocktable will be inserted.
17979 When called with a prefix argument, move to the first clock table in the
17980 buffer and update it."
17981 (interactive "P")
17982 (org-remove-clock-overlays)
17983 (when arg (org-find-dblock "clocktable"))
17984 (if (org-in-clocktable-p)
17985 (goto-char (org-in-clocktable-p))
17986 (org-create-dblock (list :name "clocktable"
17987 :maxlevel 2 :scope 'file)))
17988 (org-update-dblock))
17990 (defun org-in-clocktable-p ()
17991 "Check if the cursor is in a clocktable."
17992 (let ((pos (point)) start)
17993 (save-excursion
17994 (end-of-line 1)
17995 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
17996 (setq start (match-beginning 0))
17997 (re-search-forward "^#\\+END:.*" nil t)
17998 (>= (match-end 0) pos)
17999 start))))
18001 (defun org-clock-update-time-maybe ()
18002 "If this is a CLOCK line, update it and return t.
18003 Otherwise, return nil."
18004 (interactive)
18005 (save-excursion
18006 (beginning-of-line 1)
18007 (skip-chars-forward " \t")
18008 (when (looking-at org-clock-string)
18009 (let ((re (concat "[ \t]*" org-clock-string
18010 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18011 "\\([ \t]*=>.*\\)?"))
18012 ts te h m s)
18013 (if (not (looking-at re))
18015 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18016 (end-of-line 1)
18017 (setq ts (match-string 1)
18018 te (match-string 2))
18019 (setq s (- (time-to-seconds
18020 (apply 'encode-time (org-parse-time-string te)))
18021 (time-to-seconds
18022 (apply 'encode-time (org-parse-time-string ts))))
18023 h (floor (/ s 3600))
18024 s (- s (* 3600 h))
18025 m (floor (/ s 60))
18026 s (- s (* 60 s)))
18027 (insert " => " (format "%2d:%02d" h m))
18028 t)))))
18030 (defun org-clock-special-range (key &optional time as-strings)
18031 "Return two times bordering a special time range.
18032 Key is a symbol specifying the range and can be one of `today', `yesterday',
18033 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18034 A week starts Monday 0:00 and ends Sunday 24:00.
18035 The range is determined relative to TIME. TIME defaults to the current time.
18036 The return value is a cons cell with two internal times like the ones
18037 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18038 the returned times will be formatted strings."
18039 (let* ((tm (decode-time (or time (current-time))))
18040 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18041 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18042 (dow (nth 6 tm))
18043 s1 m1 h1 d1 month1 y1 diff ts te fm)
18044 (cond
18045 ((eq key 'today)
18046 (setq h 0 m 0 h1 24 m1 0))
18047 ((eq key 'yesterday)
18048 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18049 ((eq key 'thisweek)
18050 (setq diff (if (= dow 0) 6 (1- dow))
18051 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18052 ((eq key 'lastweek)
18053 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18054 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18055 ((eq key 'thismonth)
18056 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18057 ((eq key 'lastmonth)
18058 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18059 ((eq key 'thisyear)
18060 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18061 ((eq key 'lastyear)
18062 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18063 (t (error "No such time block %s" key)))
18064 (setq ts (encode-time s m h d month y)
18065 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18066 (or d1 d) (or month1 month) (or y1 y)))
18067 (setq fm (cdr org-time-stamp-formats))
18068 (if as-strings
18069 (cons (format-time-string fm ts) (format-time-string fm te))
18070 (cons ts te))))
18072 (defun org-dblock-write:clocktable (params)
18073 "Write the standard clocktable."
18074 (let ((hlchars '((1 . "*") (2 . "/")))
18075 (emph nil)
18076 (ins (make-marker))
18077 (total-time nil)
18078 ipos time h m p level hlc hdl maxlevel
18079 ts te cc block beg end pos scope tbl tostring multifile)
18080 (setq scope (plist-get params :scope)
18081 tostring (plist-get params :tostring)
18082 multifile (plist-get params :multifile)
18083 maxlevel (or (plist-get params :maxlevel) 3)
18084 emph (plist-get params :emphasize)
18085 ts (plist-get params :tstart)
18086 te (plist-get params :tend)
18087 block (plist-get params :block))
18088 (when block
18089 (setq cc (org-clock-special-range block nil t)
18090 ts (car cc) te (cdr cc)))
18091 (if ts (setq ts (time-to-seconds
18092 (apply 'encode-time (org-parse-time-string ts)))))
18093 (if te (setq te (time-to-seconds
18094 (apply 'encode-time (org-parse-time-string te)))))
18095 (move-marker ins (point))
18096 (setq ipos (point))
18098 ;; Get the right scope
18099 (setq pos (point))
18100 (save-restriction
18101 (cond
18102 ((not scope))
18103 ((eq scope 'file) (widen))
18104 ((eq scope 'subtree) (org-narrow-to-subtree))
18105 ((eq scope 'tree)
18106 (while (org-up-heading-safe))
18107 (org-narrow-to-subtree))
18108 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18109 (symbol-name scope)))
18110 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18111 (catch 'exit
18112 (while (org-up-heading-safe)
18113 (looking-at outline-regexp)
18114 (if (<= (org-reduced-level (funcall outline-level)) level)
18115 (throw 'exit nil))))
18116 (org-narrow-to-subtree))
18117 ((or (listp scope) (eq scope 'agenda))
18118 (let* ((files (if (listp scope) scope (org-agenda-files)))
18119 (scope 'agenda)
18120 (p1 (copy-sequence params))
18121 file)
18122 (plist-put p1 :tostring t)
18123 (plist-put p1 :multifile t)
18124 (plist-put p1 :scope 'file)
18125 (org-prepare-agenda-buffers files)
18126 (while (setq file (pop files))
18127 (with-current-buffer (find-buffer-visiting file)
18128 (push (org-clocktable-add-file
18129 file (org-dblock-write:clocktable p1)) tbl)
18130 (setq total-time (+ (or total-time 0)
18131 org-clock-file-total-minutes)))))))
18132 (goto-char pos)
18134 (unless (eq scope 'agenda)
18135 (org-clock-sum ts te)
18136 (goto-char (point-min))
18137 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18138 (goto-char p)
18139 (when (setq time (get-text-property p :org-clock-minutes))
18140 (save-excursion
18141 (beginning-of-line 1)
18142 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18143 (setq level (org-reduced-level
18144 (- (match-end 1) (match-beginning 1))))
18145 (<= level maxlevel))
18146 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18147 hdl (match-string 2)
18148 h (/ time 60)
18149 m (- time (* 60 h)))
18150 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18151 (push (concat
18152 "| " (int-to-string level) "|" hlc hdl hlc " |"
18153 (make-string (1- level) ?|)
18154 hlc (format "%d:%02d" h m) hlc
18155 " |") tbl))))))
18156 (setq tbl (nreverse tbl))
18157 (if tostring
18158 (if tbl (mapconcat 'identity tbl "\n") nil)
18159 (goto-char ins)
18160 (insert-before-markers
18161 "Clock summary at ["
18162 (substring
18163 (format-time-string (cdr org-time-stamp-formats))
18164 1 -1)
18165 "]."
18166 (if block
18167 (format " Considered range is /%s/." block)
18169 "\n\n"
18170 (if (eq scope 'agenda) "|File" "")
18171 "|L|Headline|Time|\n")
18172 (setq total-time (or total-time org-clock-file-total-minutes)
18173 h (/ total-time 60)
18174 m (- total-time (* 60 h)))
18175 (insert-before-markers
18176 "|-\n|"
18177 (if (eq scope 'agenda) "|" "")
18179 "*Total time*| "
18180 (format "*%d:%02d*" h m)
18181 "|\n|-\n")
18182 (setq tbl (delq nil tbl))
18183 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
18184 (equal (substring (car tbl) 0 2) "|-"))
18185 (pop tbl))
18186 (insert-before-markers (mapconcat
18187 'identity (delq nil tbl)
18188 (if (eq scope 'agenda) "\n|-\n" "\n")))
18189 (backward-delete-char 1)
18190 (goto-char ipos)
18191 (skip-chars-forward "^|")
18192 (org-table-align)))))
18194 (defun org-clocktable-add-file (file table)
18195 (if table
18196 (let ((lines (org-split-string table "\n"))
18197 (ff (file-name-nondirectory file)))
18198 (mapconcat 'identity
18199 (mapcar (lambda (x)
18200 (if (string-match org-table-dataline-regexp x)
18201 (concat "|" ff x)
18203 lines)
18204 "\n"))))
18206 ;; FIXME: I don't think anybody uses this, ask David
18207 (defun org-collect-clock-time-entries ()
18208 "Return an internal list with clocking information.
18209 This list has one entry for each CLOCK interval.
18210 FIXME: describe the elements."
18211 (interactive)
18212 (let ((re (concat "^[ \t]*" org-clock-string
18213 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
18214 rtn beg end next cont level title total closedp leafp
18215 clockpos titlepos h m donep)
18216 (save-excursion
18217 (org-clock-sum)
18218 (goto-char (point-min))
18219 (while (re-search-forward re nil t)
18220 (setq clockpos (match-beginning 0)
18221 beg (match-string 1) end (match-string 2)
18222 cont (match-end 0))
18223 (setq beg (apply 'encode-time (org-parse-time-string beg))
18224 end (apply 'encode-time (org-parse-time-string end)))
18225 (org-back-to-heading t)
18226 (setq donep (org-entry-is-done-p))
18227 (setq titlepos (point)
18228 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
18229 h (/ total 60) m (- total (* 60 h))
18230 total (cons h m))
18231 (looking-at "\\(\\*+\\) +\\(.*\\)")
18232 (setq level (- (match-end 1) (match-beginning 1))
18233 title (org-match-string-no-properties 2))
18234 (save-excursion (outline-next-heading) (setq next (point)))
18235 (setq closedp (re-search-forward org-closed-time-regexp next t))
18236 (goto-char next)
18237 (setq leafp (and (looking-at "^\\*+ ")
18238 (<= (- (match-end 0) (point)) level)))
18239 (push (list beg end clockpos closedp donep
18240 total title titlepos level leafp)
18241 rtn)
18242 (goto-char cont)))
18243 (nreverse rtn)))
18245 ;;;; Agenda, and Diary Integration
18247 ;;; Define the Org-agenda-mode
18249 (defvar org-agenda-mode-map (make-sparse-keymap)
18250 "Keymap for `org-agenda-mode'.")
18252 (defvar org-agenda-menu) ; defined later in this file.
18253 (defvar org-agenda-follow-mode nil)
18254 (defvar org-agenda-show-log nil)
18255 (defvar org-agenda-redo-command nil)
18256 (defvar org-agenda-mode-hook nil)
18257 (defvar org-agenda-type nil)
18258 (defvar org-agenda-force-single-file nil)
18260 (defun org-agenda-mode ()
18261 "Mode for time-sorted view on action items in Org-mode files.
18263 The following commands are available:
18265 \\{org-agenda-mode-map}"
18266 (interactive)
18267 (kill-all-local-variables)
18268 (setq org-agenda-undo-list nil
18269 org-agenda-pending-undo-list nil)
18270 (setq major-mode 'org-agenda-mode)
18271 ;; Keep global-font-lock-mode from turning on font-lock-mode
18272 (org-set-local 'font-lock-global-modes (list 'not major-mode))
18273 (setq mode-name "Org-Agenda")
18274 (use-local-map org-agenda-mode-map)
18275 (easy-menu-add org-agenda-menu)
18276 (if org-startup-truncated (setq truncate-lines t))
18277 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
18278 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
18279 ;; Make sure properties are removed when copying text
18280 (when (boundp 'buffer-substring-filters)
18281 (org-set-local 'buffer-substring-filters
18282 (cons (lambda (x)
18283 (set-text-properties 0 (length x) nil x) x)
18284 buffer-substring-filters)))
18285 (unless org-agenda-keep-modes
18286 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
18287 org-agenda-show-log nil))
18288 (easy-menu-change
18289 '("Agenda") "Agenda Files"
18290 (append
18291 (list
18292 (vector
18293 (if (get 'org-agenda-files 'org-restrict)
18294 "Restricted to single file"
18295 "Edit File List")
18296 '(org-edit-agenda-file-list)
18297 (not (get 'org-agenda-files 'org-restrict)))
18298 "--")
18299 (mapcar 'org-file-menu-entry (org-agenda-files))))
18300 (org-agenda-set-mode-name)
18301 (apply
18302 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
18303 (list 'org-agenda-mode-hook)))
18305 (substitute-key-definition 'undo 'org-agenda-undo
18306 org-agenda-mode-map global-map)
18307 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
18308 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
18309 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
18310 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
18311 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
18312 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
18313 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
18314 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
18315 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
18316 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
18317 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
18318 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
18319 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
18320 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
18321 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
18322 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
18323 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
18324 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
18325 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
18326 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
18327 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
18328 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
18329 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
18330 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
18331 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
18332 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
18333 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
18334 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
18335 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
18337 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
18338 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
18339 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
18340 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
18341 (while l (org-defkey org-agenda-mode-map
18342 (int-to-string (pop l)) 'digit-argument)))
18344 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
18345 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
18346 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
18347 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
18348 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
18349 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
18350 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
18351 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
18352 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
18353 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
18354 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
18355 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
18356 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
18357 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
18358 (org-defkey org-agenda-mode-map "n" 'next-line)
18359 (org-defkey org-agenda-mode-map "p" 'previous-line)
18360 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
18361 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
18362 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
18363 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
18364 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
18365 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
18366 (eval-after-load "calendar"
18367 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
18368 'org-calendar-goto-agenda))
18369 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
18370 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
18371 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
18372 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
18373 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
18374 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
18375 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
18376 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
18377 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
18378 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
18379 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
18380 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18381 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
18382 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
18383 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
18384 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
18385 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
18386 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
18387 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
18388 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
18389 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
18390 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
18392 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
18393 "Local keymap for agenda entries from Org-mode.")
18395 (org-defkey org-agenda-keymap
18396 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
18397 (org-defkey org-agenda-keymap
18398 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
18399 (when org-agenda-mouse-1-follows-link
18400 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
18401 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
18402 '("Agenda"
18403 ("Agenda Files")
18404 "--"
18405 ["Show" org-agenda-show t]
18406 ["Go To (other window)" org-agenda-goto t]
18407 ["Go To (this window)" org-agenda-switch-to t]
18408 ["Follow Mode" org-agenda-follow-mode
18409 :style toggle :selected org-agenda-follow-mode :active t]
18410 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
18411 "--"
18412 ["Cycle TODO" org-agenda-todo t]
18413 ["Archive subtree" org-agenda-archive t]
18414 ["Delete subtree" org-agenda-kill t]
18415 "--"
18416 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
18417 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
18418 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
18419 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
18420 "--"
18421 ("Tags and Properties"
18422 ["Show all Tags" org-agenda-show-tags t]
18423 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
18424 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
18425 "--"
18426 ["Column View" org-columns t])
18427 ("Date/Schedule"
18428 ["Schedule" org-agenda-schedule t]
18429 ["Set Deadline" org-agenda-deadline t]
18430 "--"
18431 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
18432 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
18433 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
18434 ("Clock"
18435 ["Clock in" org-agenda-clock-in t]
18436 ["Clock out" org-agenda-clock-out t]
18437 ["Clock cancel" org-agenda-clock-cancel t]
18438 ["Goto running clock" org-clock-goto t])
18439 ("Priority"
18440 ["Set Priority" org-agenda-priority t]
18441 ["Increase Priority" org-agenda-priority-up t]
18442 ["Decrease Priority" org-agenda-priority-down t]
18443 ["Show Priority" org-agenda-show-priority t])
18444 ("Calendar/Diary"
18445 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
18446 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
18447 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
18448 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
18449 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
18450 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
18451 "--"
18452 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
18453 "--"
18454 ("View"
18455 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
18456 :style radio :selected (equal org-agenda-ndays 1)]
18457 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
18458 :style radio :selected (equal org-agenda-ndays 7)]
18459 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
18460 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
18461 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
18462 :style radio :selected (member org-agenda-ndays '(365 366))]
18463 "--"
18464 ["Show Logbook entries" org-agenda-log-mode
18465 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
18466 ["Include Diary" org-agenda-toggle-diary
18467 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
18468 ["Use Time Grid" org-agenda-toggle-time-grid
18469 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
18470 ["Write view to file" org-write-agenda t]
18471 ["Rebuild buffer" org-agenda-redo t]
18472 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
18473 "--"
18474 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
18475 "--"
18476 ["Quit" org-agenda-quit t]
18477 ["Exit and Release Buffers" org-agenda-exit t]
18480 ;;; Agenda undo
18482 (defvar org-agenda-allow-remote-undo t
18483 "Non-nil means, allow remote undo from the agenda buffer.")
18484 (defvar org-agenda-undo-list nil
18485 "List of undoable operations in the agenda since last refresh.")
18486 (defvar org-agenda-undo-has-started-in nil
18487 "Buffers that have already seen `undo-start' in the current undo sequence.")
18488 (defvar org-agenda-pending-undo-list nil
18489 "In a series of undo commands, this is the list of remaning undo items.")
18491 (defmacro org-if-unprotected (&rest body)
18492 "Execute BODY if there is no `org-protected' text property at point."
18493 (declare (debug t))
18494 `(unless (get-text-property (point) 'org-protected)
18495 ,@body))
18497 (defmacro org-with-remote-undo (_buffer &rest _body)
18498 "Execute BODY while recording undo information in two buffers."
18499 (declare (indent 1) (debug t))
18500 `(let ((_cline (org-current-line))
18501 (_cmd this-command)
18502 (_buf1 (current-buffer))
18503 (_buf2 ,_buffer)
18504 (_undo1 buffer-undo-list)
18505 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
18506 _c1 _c2)
18507 ,@_body
18508 (when org-agenda-allow-remote-undo
18509 (setq _c1 (org-verify-change-for-undo
18510 _undo1 (with-current-buffer _buf1 buffer-undo-list))
18511 _c2 (org-verify-change-for-undo
18512 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
18513 (when (or _c1 _c2)
18514 ;; make sure there are undo boundaries
18515 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
18516 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
18517 ;; remember which buffer to undo
18518 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
18519 org-agenda-undo-list)))))
18521 (defun org-agenda-undo ()
18522 "Undo a remote editing step in the agenda.
18523 This undoes changes both in the agenda buffer and in the remote buffer
18524 that have been changed along."
18525 (interactive)
18526 (or org-agenda-allow-remote-undo
18527 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
18528 (if (not (eq this-command last-command))
18529 (setq org-agenda-undo-has-started-in nil
18530 org-agenda-pending-undo-list org-agenda-undo-list))
18531 (if (not org-agenda-pending-undo-list)
18532 (error "No further undo information"))
18533 (let* ((entry (pop org-agenda-pending-undo-list))
18534 buf line cmd rembuf)
18535 (setq cmd (pop entry) line (pop entry))
18536 (setq rembuf (nth 2 entry))
18537 (org-with-remote-undo rembuf
18538 (while (bufferp (setq buf (pop entry)))
18539 (if (pop entry)
18540 (with-current-buffer buf
18541 (let ((last-undo-buffer buf)
18542 (inhibit-read-only t))
18543 (unless (memq buf org-agenda-undo-has-started-in)
18544 (push buf org-agenda-undo-has-started-in)
18545 (make-local-variable 'pending-undo-list)
18546 (undo-start))
18547 (while (and pending-undo-list
18548 (listp pending-undo-list)
18549 (not (car pending-undo-list)))
18550 (pop pending-undo-list))
18551 (undo-more 1))))))
18552 (goto-line line)
18553 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
18555 (defun org-verify-change-for-undo (l1 l2)
18556 "Verify that a real change occurred between the undo lists L1 and L2."
18557 (while (and l1 (listp l1) (null (car l1))) (pop l1))
18558 (while (and l2 (listp l2) (null (car l2))) (pop l2))
18559 (not (eq l1 l2)))
18561 ;;; Agenda dispatch
18563 (defvar org-agenda-restrict nil)
18564 (defvar org-agenda-restrict-begin (make-marker))
18565 (defvar org-agenda-restrict-end (make-marker))
18566 (defvar org-agenda-last-dispatch-buffer nil)
18567 (defvar org-agenda-overriding-restriction nil)
18569 ;;;###autoload
18570 (defun org-agenda (arg &optional keys restriction)
18571 "Dispatch agenda commands to collect entries to the agenda buffer.
18572 Prompts for a command to execute. Any prefix arg will be passed
18573 on to the selected command. The default selections are:
18575 a Call `org-agenda-list' to display the agenda for current day or week.
18576 t Call `org-todo-list' to display the global todo list.
18577 T Call `org-todo-list' to display the global todo list, select only
18578 entries with a specific TODO keyword (the user gets a prompt).
18579 m Call `org-tags-view' to display headlines with tags matching
18580 a condition (the user is prompted for the condition).
18581 M Like `m', but select only TODO entries, no ordinary headlines.
18582 L Create a timeline for the current buffer.
18583 e Export views to associated files.
18585 More commands can be added by configuring the variable
18586 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
18587 searches can be pre-defined in this way.
18589 If the current buffer is in Org-mode and visiting a file, you can also
18590 first press `<' once to indicate that the agenda should be temporarily
18591 \(until the next use of \\[org-agenda]) restricted to the current file.
18592 Pressing `<' twice means to restrict to the current subtree or region
18593 \(if active)."
18594 (interactive "P")
18595 (catch 'exit
18596 (let* ((prefix-descriptions nil)
18597 (org-agenda-custom-commands
18598 ;; normalize different versions
18599 (delq nil
18600 (mapcar
18601 (lambda (x)
18602 (cond ((stringp (cdr x))
18603 (push x prefix-descriptions)
18604 nil)
18605 ((stringp (nth 1 x)) x)
18606 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
18607 (t (cons (car x) (cons "" (cdr x))))))
18608 org-agenda-custom-commands)))
18609 (buf (current-buffer))
18610 (bfn (buffer-file-name (buffer-base-buffer)))
18611 entry key type match lprops ans)
18612 ;; Turn off restriction unless there is an overriding one
18613 (unless org-agenda-overriding-restriction
18614 (put 'org-agenda-files 'org-restrict nil)
18615 (setq org-agenda-restrict nil)
18616 (move-marker org-agenda-restrict-begin nil)
18617 (move-marker org-agenda-restrict-end nil))
18618 ;; Delete old local properties
18619 (put 'org-agenda-redo-command 'org-lprops nil)
18620 ;; Remember where this call originated
18621 (setq org-agenda-last-dispatch-buffer (current-buffer))
18622 (unless keys
18623 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
18624 keys (car ans)
18625 restriction (cdr ans)))
18626 ;; Estabish the restriction, if any
18627 (when (and (not org-agenda-overriding-restriction) restriction)
18628 (put 'org-agenda-files 'org-restrict (list bfn))
18629 (cond
18630 ((eq restriction 'region)
18631 (setq org-agenda-restrict t)
18632 (move-marker org-agenda-restrict-begin (region-beginning))
18633 (move-marker org-agenda-restrict-end (region-end)))
18634 ((eq restriction 'subtree)
18635 (save-excursion
18636 (setq org-agenda-restrict t)
18637 (org-back-to-heading t)
18638 (move-marker org-agenda-restrict-begin (point))
18639 (move-marker org-agenda-restrict-end
18640 (progn (org-end-of-subtree t)))))))
18642 (require 'calendar) ; FIXME: can we avoid this for some commands?
18643 ;; For example the todo list should not need it (but does...)
18644 (cond
18645 ((setq entry (assoc keys org-agenda-custom-commands))
18646 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
18647 (progn
18648 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
18649 (put 'org-agenda-redo-command 'org-lprops lprops)
18650 (cond
18651 ((eq type 'agenda)
18652 (org-let lprops '(org-agenda-list current-prefix-arg)))
18653 ((eq type 'alltodo)
18654 (org-let lprops '(org-todo-list current-prefix-arg)))
18655 ((eq type 'stuck)
18656 (org-let lprops '(org-agenda-list-stuck-projects
18657 current-prefix-arg)))
18658 ((eq type 'tags)
18659 (org-let lprops '(org-tags-view current-prefix-arg match)))
18660 ((eq type 'tags-todo)
18661 (org-let lprops '(org-tags-view '(4) match)))
18662 ((eq type 'todo)
18663 (org-let lprops '(org-todo-list match)))
18664 ((eq type 'tags-tree)
18665 (org-check-for-org-mode)
18666 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
18667 ((eq type 'todo-tree)
18668 (org-check-for-org-mode)
18669 (org-let lprops
18670 '(org-occur (concat "^" outline-regexp "[ \t]*"
18671 (regexp-quote match) "\\>"))))
18672 ((eq type 'occur-tree)
18673 (org-check-for-org-mode)
18674 (org-let lprops '(org-occur match)))
18675 ((functionp type)
18676 (org-let lprops '(funcall type match)))
18677 ((fboundp type)
18678 (org-let lprops '(funcall type match)))
18679 (t (error "Invalid custom agenda command type %s" type))))
18680 (org-run-agenda-series (nth 1 entry) (cddr entry))))
18681 ((equal keys "C") (customize-variable 'org-agenda-custom-commands))
18682 ((equal keys "a") (call-interactively 'org-agenda-list))
18683 ((equal keys "t") (call-interactively 'org-todo-list))
18684 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
18685 ((equal keys "m") (call-interactively 'org-tags-view))
18686 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
18687 ((equal keys "e") (call-interactively 'org-store-agenda-views))
18688 ((equal keys "L")
18689 (unless (org-mode-p)
18690 (error "This is not an Org-mode file"))
18691 (unless restriction
18692 (put 'org-agenda-files 'org-restrict (list bfn))
18693 (org-call-with-arg 'org-timeline arg)))
18694 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
18695 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
18696 ((equal keys "!") (customize-variable 'org-stuck-projects))
18697 (t (error "Invalid agenda key"))))))
18699 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
18700 "The user interface for selecting an agenda command."
18701 (catch 'exit
18702 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
18703 (restrict-ok (and bfn (org-mode-p)))
18704 (region-p (org-region-active-p))
18705 (custom org-agenda-custom-commands)
18706 (selstring "")
18707 restriction second-time
18708 c entry key type match prefixes rmheader header-end custom1 desc)
18709 (save-window-excursion
18710 (delete-other-windows)
18711 (org-switch-to-buffer-other-window " *Agenda Commands*")
18712 (erase-buffer)
18713 (insert (eval-when-compile
18714 (let ((header
18716 Press key for an agenda command: < Buffer,subtree/region restriction
18717 -------------------------------- > Remove restriction
18718 a Agenda for current week or day e Export agenda views
18719 t List of all TODO entries T Entries with special TODO kwd
18720 m Match a TAGS query M Like m, but only TODO entries
18721 L Timeline for current buffer # List stuck projects (!=configure)
18722 / Multi-occur C Configure custom agenda commands
18724 (start 0))
18725 (while (string-match
18726 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
18727 header start)
18728 (setq start (match-end 0))
18729 (add-text-properties (match-beginning 2) (match-end 2)
18730 '(face bold) header))
18731 header)))
18732 (setq header-end (move-marker (make-marker) (point)))
18733 (while t
18734 (setq custom1 custom)
18735 (when (eq rmheader t)
18736 (goto-line 1)
18737 (re-search-forward ":" nil t)
18738 (delete-region (match-end 0) (point-at-eol))
18739 (forward-char 1)
18740 (looking-at "-+")
18741 (delete-region (match-end 0) (point-at-eol))
18742 (move-marker header-end (match-end 0)))
18743 (goto-char header-end)
18744 (delete-region (point) (point-max))
18745 (while (setq entry (pop custom1))
18746 (setq key (car entry) desc (nth 1 entry)
18747 type (nth 2 entry) match (nth 3 entry))
18748 (if (> (length key) 1)
18749 (add-to-list 'prefixes (string-to-char key))
18750 (insert
18751 (format
18752 "\n%-4s%-14s: %s"
18753 (org-add-props (copy-sequence key)
18754 '(face bold))
18755 (cond
18756 ((string-match "\\S-" desc) desc)
18757 ((eq type 'agenda) "Agenda for current week or day")
18758 ((eq type 'alltodo) "List of all TODO entries")
18759 ((eq type 'stuck) "List of stuck projects")
18760 ((eq type 'todo) "TODO keyword")
18761 ((eq type 'tags) "Tags query")
18762 ((eq type 'tags-todo) "Tags (TODO)")
18763 ((eq type 'tags-tree) "Tags tree")
18764 ((eq type 'todo-tree) "TODO kwd tree")
18765 ((eq type 'occur-tree) "Occur tree")
18766 ((functionp type) (if (symbolp type)
18767 (symbol-name type)
18768 "Lambda expression"))
18769 (t "???"))
18770 (cond
18771 ((stringp match)
18772 (org-add-props match nil 'face 'org-warning))
18773 (match
18774 (format "set of %d commands" (length match)))
18775 (t ""))))))
18776 (when prefixes
18777 (mapc (lambda (x)
18778 (insert
18779 (format "\n%s %s"
18780 (org-add-props (char-to-string x)
18781 nil 'face 'bold)
18782 (or (cdr (assoc (concat selstring (char-to-string x))
18783 prefix-descriptions))
18784 "Prefix key"))))
18785 prefixes))
18786 (goto-char (point-min))
18787 (when (fboundp 'fit-window-to-buffer)
18788 (if second-time
18789 (if (not (pos-visible-in-window-p (point-max)))
18790 (fit-window-to-buffer))
18791 (setq second-time t)
18792 (fit-window-to-buffer)))
18793 (message "Press key for agenda command%s:"
18794 (if (or restrict-ok org-agenda-overriding-restriction)
18795 (if org-agenda-overriding-restriction
18796 " (restriction lock active)"
18797 (if restriction
18798 (format " (restricted to %s)" restriction)
18799 " (unrestricted)"))
18800 ""))
18801 (setq c (read-char-exclusive))
18802 (message "")
18803 (cond
18804 ((assoc (char-to-string c) custom)
18805 (setq selstring (concat selstring (char-to-string c)))
18806 (throw 'exit (cons selstring restriction)))
18807 ((memq c prefixes)
18808 (setq selstring (concat selstring (char-to-string c))
18809 prefixes nil
18810 rmheader (or rmheader t)
18811 custom (delq nil (mapcar
18812 (lambda (x)
18813 (if (or (= (length (car x)) 1)
18814 (/= (string-to-char (car x)) c))
18816 (cons (substring (car x) 1) (cdr x))))
18817 custom))))
18818 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
18819 (message "Restriction is only possible in Org-mode buffers")
18820 (ding) (sit-for 1))
18821 ((eq c ?1)
18822 (org-agenda-remove-restriction-lock 'noupdate)
18823 (setq restriction 'buffer))
18824 ((eq c ?0)
18825 (org-agenda-remove-restriction-lock 'noupdate)
18826 (setq restriction (if region-p 'region 'subtree)))
18827 ((eq c ?<)
18828 (org-agenda-remove-restriction-lock 'noupdate)
18829 (setq restriction
18830 (cond
18831 ((eq restriction 'buffer)
18832 (if region-p 'region 'subtree))
18833 ((memq restriction '(subtree region))
18834 nil)
18835 (t 'buffer))))
18836 ((eq c ?>)
18837 (org-agenda-remove-restriction-lock 'noupdate)
18838 (setq restriction nil))
18839 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?/)))
18840 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
18841 ((equal c ?q) (error "Abort"))
18842 (t (error "Invalid key %c" c))))))))
18844 (defun org-run-agenda-series (name series)
18845 (org-prepare-agenda name)
18846 (let* ((org-agenda-multi t)
18847 (redo (list 'org-run-agenda-series name (list 'quote series)))
18848 (cmds (car series))
18849 (gprops (nth 1 series))
18850 match ;; The byte compiler incorrectly complains about this. Keep it!
18851 cmd type lprops)
18852 (while (setq cmd (pop cmds))
18853 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
18854 (cond
18855 ((eq type 'agenda)
18856 (org-let2 gprops lprops
18857 '(call-interactively 'org-agenda-list)))
18858 ((eq type 'alltodo)
18859 (org-let2 gprops lprops
18860 '(call-interactively 'org-todo-list)))
18861 ((eq type 'stuck)
18862 (org-let2 gprops lprops
18863 '(call-interactively 'org-agenda-list-stuck-projects)))
18864 ((eq type 'tags)
18865 (org-let2 gprops lprops
18866 '(org-tags-view current-prefix-arg match)))
18867 ((eq type 'tags-todo)
18868 (org-let2 gprops lprops
18869 '(org-tags-view '(4) match)))
18870 ((eq type 'todo)
18871 (org-let2 gprops lprops
18872 '(org-todo-list match)))
18873 ((fboundp type)
18874 (org-let2 gprops lprops
18875 '(funcall type match)))
18876 (t (error "Invalid type in command series"))))
18877 (widen)
18878 (setq org-agenda-redo-command redo)
18879 (goto-char (point-min)))
18880 (org-finalize-agenda))
18882 ;;;###autoload
18883 (defmacro org-batch-agenda (cmd-key &rest parameters)
18884 "Run an agenda command in batch mode and send the result to STDOUT.
18885 If CMD-KEY is a string of length 1, it is used as a key in
18886 `org-agenda-custom-commands' and triggers this command. If it is a
18887 longer string is is used as a tags/todo match string.
18888 Paramters are alternating variable names and values that will be bound
18889 before running the agenda command."
18890 (let (pars)
18891 (while parameters
18892 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18893 (if (> (length cmd-key) 2)
18894 (eval (list 'let (nreverse pars)
18895 (list 'org-tags-view nil cmd-key)))
18896 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
18897 (set-buffer org-agenda-buffer-name)
18898 (princ (org-encode-for-stdout (buffer-string)))))
18900 (defun org-encode-for-stdout (string)
18901 (if (fboundp 'encode-coding-string)
18902 (encode-coding-string string buffer-file-coding-system)
18903 string))
18905 (defvar org-agenda-info nil)
18907 ;;;###autoload
18908 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
18909 "Run an agenda command in batch mode and send the result to STDOUT.
18910 If CMD-KEY is a string of length 1, it is used as a key in
18911 `org-agenda-custom-commands' and triggers this command. If it is a
18912 longer string is is used as a tags/todo match string.
18913 Paramters are alternating variable names and values that will be bound
18914 before running the agenda command.
18916 The output gives a line for each selected agenda item. Each
18917 item is a list of comma-separated values, like this:
18919 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
18921 category The category of the item
18922 head The headline, without TODO kwd, TAGS and PRIORITY
18923 type The type of the agenda entry, can be
18924 todo selected in TODO match
18925 tagsmatch selected in tags match
18926 diary imported from diary
18927 deadline a deadline on given date
18928 scheduled scheduled on given date
18929 timestamp entry has timestamp on given date
18930 closed entry was closed on given date
18931 upcoming-deadline warning about deadline
18932 past-scheduled forwarded scheduled item
18933 block entry has date block including g. date
18934 todo The todo keyword, if any
18935 tags All tags including inherited ones, separated by colons
18936 date The relevant date, like 2007-2-14
18937 time The time, like 15:00-16:50
18938 extra Sting with extra planning info
18939 priority-l The priority letter if any was given
18940 priority-n The computed numerical priority
18941 agenda-day The day in the agenda where this is listed"
18943 (let (pars)
18944 (while parameters
18945 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18946 (push (list 'org-agenda-remove-tags t) pars)
18947 (if (> (length cmd-key) 2)
18948 (eval (list 'let (nreverse pars)
18949 (list 'org-tags-view nil cmd-key)))
18950 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
18951 (set-buffer org-agenda-buffer-name)
18952 (let* ((lines (org-split-string (buffer-string) "\n"))
18953 line)
18954 (while (setq line (pop lines))
18955 (catch 'next
18956 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
18957 (setq org-agenda-info
18958 (org-fix-agenda-info (text-properties-at 0 line)))
18959 (princ
18960 (org-encode-for-stdout
18961 (mapconcat 'org-agenda-export-csv-mapper
18962 '(org-category txt type todo tags date time-of-day extra
18963 priority-letter priority agenda-day)
18964 ",")))
18965 (princ "\n"))))))
18967 (defun org-fix-agenda-info (props)
18968 "Make sure all properties on an agenda item have a canonical form,
18969 so the the export commands caneasily use it."
18970 (let (tmp re)
18971 (when (setq tmp (plist-get props 'tags))
18972 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
18973 (when (setq tmp (plist-get props 'date))
18974 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
18975 (let ((calendar-date-display-form '(year "-" month "-" day)))
18976 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
18978 (setq tmp (calendar-date-string tmp)))
18979 (setq props (plist-put props 'date tmp)))
18980 (when (setq tmp (plist-get props 'day))
18981 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
18982 (let ((calendar-date-display-form '(year "-" month "-" day)))
18983 (setq tmp (calendar-date-string tmp)))
18984 (setq props (plist-put props 'day tmp))
18985 (setq props (plist-put props 'agenda-day tmp)))
18986 (when (setq tmp (plist-get props 'txt))
18987 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
18988 (plist-put props 'priority-letter (match-string 1 tmp))
18989 (setq tmp (replace-match "" t t tmp)))
18990 (when (and (setq re (plist-get props 'org-todo-regexp))
18991 (setq re (concat "\\`\\.*" re " ?"))
18992 (string-match re tmp))
18993 (plist-put props 'todo (match-string 1 tmp))
18994 (setq tmp (replace-match "" t t tmp)))
18995 (plist-put props 'txt tmp)))
18996 props)
18998 (defun org-agenda-export-csv-mapper (prop)
18999 (let ((res (plist-get org-agenda-info prop)))
19000 (setq res
19001 (cond
19002 ((not res) "")
19003 ((stringp res) res)
19004 (t (prin1-to-string res))))
19005 (while (string-match "," res)
19006 (setq res (replace-match ";" t t res)))
19007 (org-trim res)))
19010 ;;;###autoload
19011 (defun org-store-agenda-views (&rest parameters)
19012 (interactive)
19013 (eval (list 'org-batch-store-agenda-views)))
19015 ;; FIXME, why is this a macro?????
19016 ;;;###autoload
19017 (defmacro org-batch-store-agenda-views (&rest parameters)
19018 "Run all custom agenda commands that have a file argument."
19019 (let ((cmds org-agenda-custom-commands)
19020 (pop-up-frames nil)
19021 (dir default-directory)
19022 pars cmd thiscmdkey files opts)
19023 (while parameters
19024 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19025 (setq pars (reverse pars))
19026 (save-window-excursion
19027 (while cmds
19028 (setq cmd (pop cmds)
19029 thiscmdkey (car cmd)
19030 opts (nth 3 cmd)
19031 files (nth 4 cmd))
19032 (if (stringp files) (setq files (list files)))
19033 (when files
19034 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19035 (list 'org-agenda nil thiscmdkey)))
19036 (set-buffer org-agenda-buffer-name)
19037 (while files
19038 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19039 (list 'org-write-agenda
19040 (expand-file-name (pop files) dir) t))))
19041 (and (get-buffer org-agenda-buffer-name)
19042 (kill-buffer org-agenda-buffer-name)))))))
19044 (defun org-write-agenda (file &optional nosettings)
19045 "Write the current buffer (an agenda view) as a file.
19046 Depending on the extension of the file name, plain text (.txt),
19047 HTML (.html or .htm) or Postscript (.ps) is produced.
19048 If NOSETTINGS is given, do not scope the settings of
19049 `org-agenda-exporter-settings' into the export commands. This is used when
19050 the settings have already been scoped and we do not wish to overrule other,
19051 higher priority settings."
19052 (interactive "FWrite agenda to file: ")
19053 (if (not (file-writable-p file))
19054 (error "Cannot write agenda to file %s" file))
19055 (cond
19056 ((string-match "\\.html?\\'" file) (require 'htmlize))
19057 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19058 (org-let (if nosettings nil org-agenda-exporter-settings)
19059 '(save-excursion
19060 (save-window-excursion
19061 (cond
19062 ((string-match "\\.html?\\'" file)
19063 (set-buffer (htmlize-buffer (current-buffer)))
19065 (when (and org-agenda-export-html-style
19066 (string-match "<style>" org-agenda-export-html-style))
19067 ;; replace <style> section with org-agenda-export-html-style
19068 (goto-char (point-min))
19069 (kill-region (- (search-forward "<style") 6)
19070 (search-forward "</style>"))
19071 (insert org-agenda-export-html-style))
19072 (write-file file)
19073 (kill-buffer (current-buffer))
19074 (message "HTML written to %s" file))
19075 ((string-match "\\.ps\\'" file)
19076 (ps-print-buffer-with-faces file)
19077 (message "Postscript written to %s" file))
19079 (let ((bs (buffer-string)))
19080 (find-file file)
19081 (insert bs)
19082 (save-buffer 0)
19083 (kill-buffer (current-buffer))
19084 (message "Plain text written to %s" file))))))
19085 (set-buffer org-agenda-buffer-name)))
19087 (defmacro org-no-read-only (&rest body)
19088 "Inhibit read-only for BODY."
19089 `(let ((inhibit-read-only t)) ,@body))
19091 (defun org-check-for-org-mode ()
19092 "Make sure current buffer is in org-mode. Error if not."
19093 (or (org-mode-p)
19094 (error "Cannot execute org-mode agenda command on buffer in %s."
19095 major-mode)))
19097 (defun org-fit-agenda-window ()
19098 "Fit the window to the buffer size."
19099 (and (memq org-agenda-window-setup '(reorganize-frame))
19100 (fboundp 'fit-window-to-buffer)
19101 (fit-window-to-buffer
19103 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19104 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19106 ;;; Agenda file list
19108 (defun org-agenda-files (&optional unrestricted)
19109 "Get the list of agenda files.
19110 Optional UNRESTRICTED means return the full list even if a restriction
19111 is currently in place."
19112 (let ((files
19113 (cond
19114 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19115 ((stringp org-agenda-files) (org-read-agenda-file-list))
19116 ((listp org-agenda-files) org-agenda-files)
19117 (t (error "Invalid value of `org-agenda-files'")))))
19118 (setq files (apply 'append
19119 (mapcar (lambda (f)
19120 (if (file-directory-p f)
19121 (directory-files f t "\\.org\\'")
19122 (list f)))
19123 files)))
19124 (if org-agenda-skip-unavailable-files
19125 (delq nil
19126 (mapcar (function
19127 (lambda (file)
19128 (and (file-readable-p file) file)))
19129 files))
19130 files))) ; `org-check-agenda-file' will remove them from the list
19132 (defun org-edit-agenda-file-list ()
19133 "Edit the list of agenda files.
19134 Depending on setup, this either uses customize to edit the variable
19135 `org-agenda-files', or it visits the file that is holding the list. In the
19136 latter case, the buffer is set up in a way that saving it automatically kills
19137 the buffer and restores the previous window configuration."
19138 (interactive)
19139 (if (stringp org-agenda-files)
19140 (let ((cw (current-window-configuration)))
19141 (find-file org-agenda-files)
19142 (org-set-local 'org-window-configuration cw)
19143 (org-add-hook 'after-save-hook
19144 (lambda ()
19145 (set-window-configuration
19146 (prog1 org-window-configuration
19147 (kill-buffer (current-buffer))))
19148 (org-install-agenda-files-menu)
19149 (message "New agenda file list installed"))
19150 nil 'local)
19151 (message (substitute-command-keys
19152 "Edit list and finish with \\[save-buffer]")))
19153 (customize-variable 'org-agenda-files)))
19155 (defun org-store-new-agenda-file-list (list)
19156 "Set new value for the agenda file list and save it correcly."
19157 (if (stringp org-agenda-files)
19158 (let ((f org-agenda-files) b)
19159 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
19160 (with-temp-file f
19161 (insert (mapconcat 'identity list "\n") "\n")))
19162 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
19163 (setq org-agenda-files list)
19164 (customize-save-variable 'org-agenda-files org-agenda-files))))
19166 (defun org-read-agenda-file-list ()
19167 "Read the list of agenda files from a file."
19168 (when (stringp org-agenda-files)
19169 (with-temp-buffer
19170 (insert-file-contents org-agenda-files)
19171 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
19174 ;;;###autoload
19175 (defun org-cycle-agenda-files ()
19176 "Cycle through the files in `org-agenda-files'.
19177 If the current buffer visits an agenda file, find the next one in the list.
19178 If the current buffer does not, find the first agenda file."
19179 (interactive)
19180 (let* ((fs (org-agenda-files t))
19181 (files (append fs (list (car fs))))
19182 (tcf (if buffer-file-name (file-truename buffer-file-name)))
19183 file)
19184 (unless files (error "No agenda files"))
19185 (catch 'exit
19186 (while (setq file (pop files))
19187 (if (equal (file-truename file) tcf)
19188 (when (car files)
19189 (find-file (car files))
19190 (throw 'exit t))))
19191 (find-file (car fs)))
19192 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
19194 (defun org-agenda-file-to-front (&optional to-end)
19195 "Move/add the current file to the top of the agenda file list.
19196 If the file is not present in the list, it is added to the front. If it is
19197 present, it is moved there. With optional argument TO-END, add/move to the
19198 end of the list."
19199 (interactive "P")
19200 (let ((org-agenda-skip-unavailable-files nil)
19201 (file-alist (mapcar (lambda (x)
19202 (cons (file-truename x) x))
19203 (org-agenda-files t)))
19204 (ctf (file-truename buffer-file-name))
19205 x had)
19206 (setq x (assoc ctf file-alist) had x)
19208 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
19209 (if to-end
19210 (setq file-alist (append (delq x file-alist) (list x)))
19211 (setq file-alist (cons x (delq x file-alist))))
19212 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
19213 (org-install-agenda-files-menu)
19214 (message "File %s to %s of agenda file list"
19215 (if had "moved" "added") (if to-end "end" "front"))))
19217 (defun org-remove-file (&optional file)
19218 "Remove current file from the list of files in variable `org-agenda-files'.
19219 These are the files which are being checked for agenda entries.
19220 Optional argument FILE means, use this file instead of the current."
19221 (interactive)
19222 (let* ((org-agenda-skip-unavailable-files nil)
19223 (file (or file buffer-file-name))
19224 (true-file (file-truename file))
19225 (afile (abbreviate-file-name file))
19226 (files (delq nil (mapcar
19227 (lambda (x)
19228 (if (equal true-file
19229 (file-truename x))
19230 nil x))
19231 (org-agenda-files t)))))
19232 (if (not (= (length files) (length (org-agenda-files t))))
19233 (progn
19234 (org-store-new-agenda-file-list files)
19235 (org-install-agenda-files-menu)
19236 (message "Removed file: %s" afile))
19237 (message "File was not in list: %s" afile))))
19239 (defun org-file-menu-entry (file)
19240 (vector file (list 'find-file file) t))
19242 (defun org-check-agenda-file (file)
19243 "Make sure FILE exists. If not, ask user what to do."
19244 (when (not (file-exists-p file))
19245 (message "non-existent file %s. [R]emove from list or [A]bort?"
19246 (abbreviate-file-name file))
19247 (let ((r (downcase (read-char-exclusive))))
19248 (cond
19249 ((equal r ?r)
19250 (org-remove-file file)
19251 (throw 'nextfile t))
19252 (t (error "Abort"))))))
19254 ;;; Agenda prepare and finalize
19256 (defvar org-agenda-multi nil) ; dynammically scoped
19257 (defvar org-agenda-buffer-name "*Org Agenda*")
19258 (defvar org-pre-agenda-window-conf nil)
19259 (defvar org-agenda-name nil)
19260 (defun org-prepare-agenda (&optional name)
19261 (setq org-todo-keywords-for-agenda nil)
19262 (setq org-done-keywords-for-agenda nil)
19263 (if org-agenda-multi
19264 (progn
19265 (setq buffer-read-only nil)
19266 (goto-char (point-max))
19267 (unless (or (bobp) org-agenda-compact-blocks)
19268 (insert "\n" (make-string (window-width) ?=) "\n"))
19269 (narrow-to-region (point) (point-max)))
19270 (org-agenda-maybe-reset-markers 'force)
19271 (org-prepare-agenda-buffers (org-agenda-files))
19272 (setq org-todo-keywords-for-agenda
19273 (org-uniquify org-todo-keywords-for-agenda))
19274 (setq org-done-keywords-for-agenda
19275 (org-uniquify org-done-keywords-for-agenda))
19276 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
19277 (awin (get-buffer-window abuf)))
19278 (cond
19279 ((equal (current-buffer) abuf) nil)
19280 (awin (select-window awin))
19281 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
19282 ((equal org-agenda-window-setup 'current-window)
19283 (switch-to-buffer abuf))
19284 ((equal org-agenda-window-setup 'other-window)
19285 (org-switch-to-buffer-other-window abuf))
19286 ((equal org-agenda-window-setup 'other-frame)
19287 (switch-to-buffer-other-frame abuf))
19288 ((equal org-agenda-window-setup 'reorganize-frame)
19289 (delete-other-windows)
19290 (org-switch-to-buffer-other-window abuf))))
19291 (setq buffer-read-only nil)
19292 (erase-buffer)
19293 (org-agenda-mode)
19294 (and name (not org-agenda-name)
19295 (org-set-local 'org-agenda-name name)))
19296 (setq buffer-read-only nil))
19298 (defun org-finalize-agenda ()
19299 "Finishing touch for the agenda buffer, called just before displaying it."
19300 (unless org-agenda-multi
19301 (save-excursion
19302 (let ((inhibit-read-only t))
19303 (goto-char (point-min))
19304 (while (org-activate-bracket-links (point-max))
19305 (add-text-properties (match-beginning 0) (match-end 0)
19306 '(face org-link)))
19307 (org-agenda-align-tags)
19308 (unless org-agenda-with-colors
19309 (remove-text-properties (point-min) (point-max) '(face nil))))
19310 (if (and (boundp 'org-overriding-columns-format)
19311 org-overriding-columns-format)
19312 (org-set-local 'org-overriding-columns-format
19313 org-overriding-columns-format))
19314 (if (and (boundp 'org-agenda-view-columns-initially)
19315 org-agenda-view-columns-initially)
19316 (org-agenda-columns))
19317 (when org-agenda-fontify-priorities
19318 (org-fontify-priorities))
19319 (run-hooks 'org-finalize-agenda-hook))))
19321 (defun org-fontify-priorities ()
19322 "Make highest priority lines bold, and lowest italic."
19323 (interactive)
19324 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
19325 (org-delete-overlay o)))
19326 (org-overlays-in (point-min) (point-max)))
19327 (save-excursion
19328 (let ((inhibit-read-only t)
19329 b e p ov h l)
19330 (goto-char (point-min))
19331 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
19332 (setq h (or (get-char-property (point) 'org-highest-priority)
19333 org-highest-priority)
19334 l (or (get-char-property (point) 'org-lowest-priority)
19335 org-lowest-priority)
19336 p (string-to-char (match-string 1))
19337 b (match-beginning 0) e (point-at-eol)
19338 ov (org-make-overlay b e))
19339 (org-overlay-put
19340 ov 'face
19341 (cond ((listp org-agenda-fontify-priorities)
19342 (cdr (assoc p org-agenda-fontify-priorities)))
19343 ((equal p l) 'italic)
19344 ((equal p h) 'bold)))
19345 (org-overlay-put ov 'org-type 'org-priority)))))
19347 (defun org-prepare-agenda-buffers (files)
19348 "Create buffers for all agenda files, protect archived trees and comments."
19349 (interactive)
19350 (let ((pa '(:org-archived t))
19351 (pc '(:org-comment t))
19352 (pall '(:org-archived t :org-comment t))
19353 (inhibit-read-only t)
19354 (rea (concat ":" org-archive-tag ":"))
19355 bmp file re)
19356 (save-excursion
19357 (save-restriction
19358 (while (setq file (pop files))
19359 (if (bufferp file)
19360 (set-buffer file)
19361 (org-check-agenda-file file)
19362 (set-buffer (org-get-agenda-file-buffer file)))
19363 (widen)
19364 (setq bmp (buffer-modified-p))
19365 (org-refresh-category-properties)
19366 (setq org-todo-keywords-for-agenda
19367 (append org-todo-keywords-for-agenda org-todo-keywords-1))
19368 (setq org-done-keywords-for-agenda
19369 (append org-done-keywords-for-agenda org-done-keywords))
19370 (save-excursion
19371 (remove-text-properties (point-min) (point-max) pall)
19372 (when org-agenda-skip-archived-trees
19373 (goto-char (point-min))
19374 (while (re-search-forward rea nil t)
19375 (if (org-on-heading-p t)
19376 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
19377 (goto-char (point-min))
19378 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
19379 (while (re-search-forward re nil t)
19380 (add-text-properties
19381 (match-beginning 0) (org-end-of-subtree t) pc)))
19382 (set-buffer-modified-p bmp))))))
19384 (defvar org-agenda-skip-function nil
19385 "Function to be called at each match during agenda construction.
19386 If this function returns nil, the current match should not be skipped.
19387 Otherwise, the function must return a position from where the search
19388 should be continued.
19389 This may also be a Lisp form, it will be evaluated.
19390 Never set this variable using `setq' or so, because then it will apply
19391 to all future agenda commands. Instead, bind it with `let' to scope
19392 it dynamically into the agenda-constructing command. A good way to set
19393 it is through options in org-agenda-custom-commands.")
19395 (defun org-agenda-skip ()
19396 "Throw to `:skip' in places that should be skipped.
19397 Also moves point to the end of the skipped region, so that search can
19398 continue from there."
19399 (let ((p (point-at-bol)) to fp)
19400 (and org-agenda-skip-archived-trees
19401 (get-text-property p :org-archived)
19402 (org-end-of-subtree t)
19403 (throw :skip t))
19404 (and (get-text-property p :org-comment)
19405 (org-end-of-subtree t)
19406 (throw :skip t))
19407 (if (equal (char-after p) ?#) (throw :skip t))
19408 (when (and (or (setq fp (functionp org-agenda-skip-function))
19409 (consp org-agenda-skip-function))
19410 (setq to (save-excursion
19411 (save-match-data
19412 (if fp
19413 (funcall org-agenda-skip-function)
19414 (eval org-agenda-skip-function))))))
19415 (goto-char to)
19416 (throw :skip t))))
19418 (defvar org-agenda-markers nil
19419 "List of all currently active markers created by `org-agenda'.")
19420 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
19421 "Creation time of the last agenda marker.")
19423 (defun org-agenda-new-marker (&optional pos)
19424 "Return a new agenda marker.
19425 Org-mode keeps a list of these markers and resets them when they are
19426 no longer in use."
19427 (let ((m (copy-marker (or pos (point)))))
19428 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
19429 (push m org-agenda-markers)
19432 (defun org-agenda-maybe-reset-markers (&optional force)
19433 "Reset markers created by `org-agenda'. But only if they are old enough."
19434 (if (or (and force (not org-agenda-multi))
19435 (> (- (time-to-seconds (current-time))
19436 org-agenda-last-marker-time)
19438 (while org-agenda-markers
19439 (move-marker (pop org-agenda-markers) nil))))
19441 (defvar org-agenda-new-buffers nil
19442 "Buffers created to visit agenda files.")
19444 (defun org-get-agenda-file-buffer (file)
19445 "Get a buffer visiting FILE. If the buffer needs to be created, add
19446 it to the list of buffers which might be released later."
19447 (let ((buf (org-find-base-buffer-visiting file)))
19448 (if buf
19449 buf ; just return it
19450 ;; Make a new buffer and remember it
19451 (setq buf (find-file-noselect file))
19452 (if buf (push buf org-agenda-new-buffers))
19453 buf)))
19455 (defun org-release-buffers (blist)
19456 "Release all buffers in list, asking the user for confirmation when needed.
19457 When a buffer is unmodified, it is just killed. When modified, it is saved
19458 \(if the user agrees) and then killed."
19459 (let (buf file)
19460 (while (setq buf (pop blist))
19461 (setq file (buffer-file-name buf))
19462 (when (and (buffer-modified-p buf)
19463 file
19464 (y-or-n-p (format "Save file %s? " file)))
19465 (with-current-buffer buf (save-buffer)))
19466 (kill-buffer buf))))
19468 (defun org-get-category (&optional pos)
19469 "Get the category applying to position POS."
19470 (get-text-property (or pos (point)) 'org-category))
19472 ;;; Agenda timeline
19474 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
19476 (defun org-timeline (&optional include-all)
19477 "Show a time-sorted view of the entries in the current org file.
19478 Only entries with a time stamp of today or later will be listed. With
19479 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
19480 under the current date.
19481 If the buffer contains an active region, only check the region for
19482 dates."
19483 (interactive "P")
19484 (require 'calendar)
19485 (org-compile-prefix-format 'timeline)
19486 (org-set-sorting-strategy 'timeline)
19487 (let* ((dopast t)
19488 (dotodo include-all)
19489 (doclosed org-agenda-show-log)
19490 (entry buffer-file-name)
19491 (date (calendar-current-date))
19492 (beg (if (org-region-active-p) (region-beginning) (point-min)))
19493 (end (if (org-region-active-p) (region-end) (point-max)))
19494 (day-numbers (org-get-all-dates beg end 'no-ranges
19495 t doclosed ; always include today
19496 org-timeline-show-empty-dates))
19497 (org-deadline-warning-days 0)
19498 (org-agenda-only-exact-dates t)
19499 (today (time-to-days (current-time)))
19500 (past t)
19501 args
19502 s e rtn d emptyp)
19503 (setq org-agenda-redo-command
19504 (list 'progn
19505 (list 'org-switch-to-buffer-other-window (current-buffer))
19506 (list 'org-timeline (list 'quote include-all))))
19507 (if (not dopast)
19508 ;; Remove past dates from the list of dates.
19509 (setq day-numbers (delq nil (mapcar (lambda(x)
19510 (if (>= x today) x nil))
19511 day-numbers))))
19512 (org-prepare-agenda (concat "Timeline "
19513 (file-name-nondirectory buffer-file-name)))
19514 (if doclosed (push :closed args))
19515 (push :timestamp args)
19516 (push :deadline args)
19517 (push :scheduled args)
19518 (push :sexp args)
19519 (if dotodo (push :todo args))
19520 (while (setq d (pop day-numbers))
19521 (if (and (listp d) (eq (car d) :omitted))
19522 (progn
19523 (setq s (point))
19524 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
19525 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
19526 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
19527 (if (and (>= d today)
19528 dopast
19529 past)
19530 (progn
19531 (setq past nil)
19532 (insert (make-string 79 ?-) "\n")))
19533 (setq date (calendar-gregorian-from-absolute d))
19534 (setq s (point))
19535 (setq rtn (and (not emptyp)
19536 (apply 'org-agenda-get-day-entries entry
19537 date args)))
19538 (if (or rtn (equal d today) org-timeline-show-empty-dates)
19539 (progn
19540 (insert
19541 (if (stringp org-agenda-format-date)
19542 (format-time-string org-agenda-format-date
19543 (org-time-from-absolute date))
19544 (funcall org-agenda-format-date date))
19545 "\n")
19546 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19547 (put-text-property s (1- (point)) 'org-date-line t)
19548 (if (equal d today)
19549 (put-text-property s (1- (point)) 'org-today t))
19550 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
19551 (put-text-property s (1- (point)) 'day d)))))
19552 (goto-char (point-min))
19553 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
19554 (point-min)))
19555 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
19556 (org-finalize-agenda)
19557 (setq buffer-read-only t)))
19559 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
19560 "Return a list of all relevant day numbers from BEG to END buffer positions.
19561 If NO-RANGES is non-nil, include only the start and end dates of a range,
19562 not every single day in the range. If FORCE-TODAY is non-nil, make
19563 sure that TODAY is included in the list. If INACTIVE is non-nil, also
19564 inactive time stamps (those in square brackets) are included.
19565 When EMPTY is non-nil, also include days without any entries."
19566 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
19567 dates dates1 date day day1 day2 ts1 ts2)
19568 (if force-today
19569 (setq dates (list (time-to-days (current-time)))))
19570 (save-excursion
19571 (goto-char beg)
19572 (while (re-search-forward re end t)
19573 (setq day (time-to-days (org-time-string-to-time
19574 (substring (match-string 1) 0 10))))
19575 (or (memq day dates) (push day dates)))
19576 (unless no-ranges
19577 (goto-char beg)
19578 (while (re-search-forward org-tr-regexp end t)
19579 (setq ts1 (substring (match-string 1) 0 10)
19580 ts2 (substring (match-string 2) 0 10)
19581 day1 (time-to-days (org-time-string-to-time ts1))
19582 day2 (time-to-days (org-time-string-to-time ts2)))
19583 (while (< (setq day1 (1+ day1)) day2)
19584 (or (memq day1 dates) (push day1 dates)))))
19585 (setq dates (sort dates '<))
19586 (when empty
19587 (while (setq day (pop dates))
19588 (setq day2 (car dates))
19589 (push day dates1)
19590 (when (and day2 empty)
19591 (if (or (eq empty t)
19592 (and (numberp empty) (<= (- day2 day) empty)))
19593 (while (< (setq day (1+ day)) day2)
19594 (push (list day) dates1))
19595 (push (cons :omitted (- day2 day)) dates1))))
19596 (setq dates (nreverse dates1)))
19597 dates)))
19599 ;;; Agenda Daily/Weekly
19601 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
19602 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
19603 (defvar org-agenda-last-arguments nil
19604 "The arguments of the previous call to org-agenda")
19605 (defvar org-starting-day nil) ; local variable in the agenda buffer
19606 (defvar org-agenda-span nil) ; local variable in the agenda buffer
19607 (defvar org-include-all-loc nil) ; local variable
19608 (defvar org-agenda-remove-date nil) ; dynamically scoped
19610 ;;;###autoload
19611 (defun org-agenda-list (&optional include-all start-day ndays)
19612 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
19613 The view will be for the current day or week, but from the overview buffer
19614 you will be able to go to other days/weeks.
19616 With one \\[universal-argument] prefix argument INCLUDE-ALL,
19617 all unfinished TODO items will also be shown, before the agenda.
19618 This feature is considered obsolete, please use the TODO list or a block
19619 agenda instead.
19621 With a numeric prefix argument in an interactive call, the agenda will
19622 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
19623 the number of days. NDAYS defaults to `org-agenda-ndays'.
19625 START-DAY defaults to TODAY, or to the most recent match for the weekday
19626 given in `org-agenda-start-on-weekday'."
19627 (interactive "P")
19628 (if (and (integerp include-all) (> include-all 0))
19629 (setq ndays include-all include-all nil))
19630 (setq ndays (or ndays org-agenda-ndays)
19631 start-day (or start-day org-agenda-start-day))
19632 (if org-agenda-overriding-arguments
19633 (setq include-all (car org-agenda-overriding-arguments)
19634 start-day (nth 1 org-agenda-overriding-arguments)
19635 ndays (nth 2 org-agenda-overriding-arguments)))
19636 (if (stringp start-day)
19637 ;; Convert to an absolute day number
19638 (setq start-day (time-to-days (org-read-date nil t start-day))))
19639 (setq org-agenda-last-arguments (list include-all start-day ndays))
19640 (org-compile-prefix-format 'agenda)
19641 (org-set-sorting-strategy 'agenda)
19642 (require 'calendar)
19643 (let* ((org-agenda-start-on-weekday
19644 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
19645 org-agenda-start-on-weekday nil))
19646 (thefiles (org-agenda-files))
19647 (files thefiles)
19648 (today (time-to-days
19649 (time-subtract (current-time)
19650 (list 0 (* 3600 org-extend-today-until) 0))))
19651 (sd (or start-day today))
19652 (start (if (or (null org-agenda-start-on-weekday)
19653 (< org-agenda-ndays 7))
19655 (let* ((nt (calendar-day-of-week
19656 (calendar-gregorian-from-absolute sd)))
19657 (n1 org-agenda-start-on-weekday)
19658 (d (- nt n1)))
19659 (- sd (+ (if (< d 0) 7 0) d)))))
19660 (day-numbers (list start))
19661 (day-cnt 0)
19662 (inhibit-redisplay (not debug-on-error))
19663 s e rtn rtnall file date d start-pos end-pos todayp nd)
19664 (setq org-agenda-redo-command
19665 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
19666 ;; Make the list of days
19667 (setq ndays (or ndays org-agenda-ndays)
19668 nd ndays)
19669 (while (> ndays 1)
19670 (push (1+ (car day-numbers)) day-numbers)
19671 (setq ndays (1- ndays)))
19672 (setq day-numbers (nreverse day-numbers))
19673 (org-prepare-agenda "Day/Week")
19674 (org-set-local 'org-starting-day (car day-numbers))
19675 (org-set-local 'org-include-all-loc include-all)
19676 (org-set-local 'org-agenda-span
19677 (org-agenda-ndays-to-span nd))
19678 (when (and (or include-all org-agenda-include-all-todo)
19679 (member today day-numbers))
19680 (setq files thefiles
19681 rtnall nil)
19682 (while (setq file (pop files))
19683 (catch 'nextfile
19684 (org-check-agenda-file file)
19685 (setq date (calendar-gregorian-from-absolute today)
19686 rtn (org-agenda-get-day-entries
19687 file date :todo))
19688 (setq rtnall (append rtnall rtn))))
19689 (when rtnall
19690 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
19691 (add-text-properties (point-min) (1- (point))
19692 (list 'face 'org-agenda-structure))
19693 (insert (org-finalize-agenda-entries rtnall) "\n")))
19694 (unless org-agenda-compact-blocks
19695 (setq s (point))
19696 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
19697 "-agenda:\n")
19698 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
19699 'org-date-line t)))
19700 (while (setq d (pop day-numbers))
19701 (setq date (calendar-gregorian-from-absolute d)
19702 s (point))
19703 (if (or (setq todayp (= d today))
19704 (and (not start-pos) (= d sd)))
19705 (setq start-pos (point))
19706 (if (and start-pos (not end-pos))
19707 (setq end-pos (point))))
19708 (setq files thefiles
19709 rtnall nil)
19710 (while (setq file (pop files))
19711 (catch 'nextfile
19712 (org-check-agenda-file file)
19713 (if org-agenda-show-log
19714 (setq rtn (org-agenda-get-day-entries
19715 file date
19716 :deadline :scheduled :timestamp :sexp :closed))
19717 (setq rtn (org-agenda-get-day-entries
19718 file date
19719 :deadline :scheduled :sexp :timestamp)))
19720 (setq rtnall (append rtnall rtn))))
19721 (if org-agenda-include-diary
19722 (progn
19723 (require 'diary-lib)
19724 (setq rtn (org-get-entries-from-diary date))
19725 (setq rtnall (append rtnall rtn))))
19726 (if (or rtnall org-agenda-show-all-dates)
19727 (progn
19728 (setq day-cnt (1+ day-cnt))
19729 (insert
19730 (if (stringp org-agenda-format-date)
19731 (format-time-string org-agenda-format-date
19732 (org-time-from-absolute date))
19733 (funcall org-agenda-format-date date))
19734 "\n")
19735 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19736 (put-text-property s (1- (point)) 'org-date-line t)
19737 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
19738 (if todayp (put-text-property s (1- (point)) 'org-today t))
19739 (if rtnall (insert
19740 (org-finalize-agenda-entries
19741 (org-agenda-add-time-grid-maybe
19742 rtnall nd todayp))
19743 "\n"))
19744 (put-text-property s (1- (point)) 'day d)
19745 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
19746 (goto-char (point-min))
19747 (org-fit-agenda-window)
19748 (unless (and (pos-visible-in-window-p (point-min))
19749 (pos-visible-in-window-p (point-max)))
19750 (goto-char (1- (point-max)))
19751 (recenter -1)
19752 (if (not (pos-visible-in-window-p (or start-pos 1)))
19753 (progn
19754 (goto-char (or start-pos 1))
19755 (recenter 1))))
19756 (goto-char (or start-pos 1))
19757 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
19758 (org-finalize-agenda)
19759 (setq buffer-read-only t)
19760 (message "")))
19762 (defun org-agenda-ndays-to-span (n)
19763 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
19765 ;;; Agenda TODO list
19767 (defvar org-select-this-todo-keyword nil)
19768 (defvar org-last-arg nil)
19770 ;;;###autoload
19771 (defun org-todo-list (arg)
19772 "Show all TODO entries from all agenda file in a single list.
19773 The prefix arg can be used to select a specific TODO keyword and limit
19774 the list to these. When using \\[universal-argument], you will be prompted
19775 for a keyword. A numeric prefix directly selects the Nth keyword in
19776 `org-todo-keywords-1'."
19777 (interactive "P")
19778 (require 'calendar)
19779 (org-compile-prefix-format 'todo)
19780 (org-set-sorting-strategy 'todo)
19781 (org-prepare-agenda "TODO")
19782 (let* ((today (time-to-days (current-time)))
19783 (date (calendar-gregorian-from-absolute today))
19784 (kwds org-todo-keywords-for-agenda)
19785 (completion-ignore-case t)
19786 (org-select-this-todo-keyword
19787 (if (stringp arg) arg
19788 (and arg (integerp arg) (> arg 0)
19789 (nth (1- arg) kwds))))
19790 rtn rtnall files file pos)
19791 (when (equal arg '(4))
19792 (setq org-select-this-todo-keyword
19793 (completing-read "Keyword (or KWD1|K2D2|...): "
19794 (mapcar 'list kwds) nil nil)))
19795 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
19796 (org-set-local 'org-last-arg arg)
19797 (setq org-agenda-redo-command
19798 '(org-todo-list (or current-prefix-arg org-last-arg)))
19799 (setq files (org-agenda-files)
19800 rtnall nil)
19801 (while (setq file (pop files))
19802 (catch 'nextfile
19803 (org-check-agenda-file file)
19804 (setq rtn (org-agenda-get-day-entries file date :todo))
19805 (setq rtnall (append rtnall rtn))))
19806 (if org-agenda-overriding-header
19807 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
19808 nil 'face 'org-agenda-structure) "\n")
19809 (insert "Global list of TODO items of type: ")
19810 (add-text-properties (point-min) (1- (point))
19811 (list 'face 'org-agenda-structure))
19812 (setq pos (point))
19813 (insert (or org-select-this-todo-keyword "ALL") "\n")
19814 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
19815 (setq pos (point))
19816 (unless org-agenda-multi
19817 (insert "Available with `N r': (0)ALL")
19818 (let ((n 0) s)
19819 (mapc (lambda (x)
19820 (setq s (format "(%d)%s" (setq n (1+ n)) x))
19821 (if (> (+ (current-column) (string-width s) 1) (frame-width))
19822 (insert "\n "))
19823 (insert " " s))
19824 kwds))
19825 (insert "\n"))
19826 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
19827 (when rtnall
19828 (insert (org-finalize-agenda-entries rtnall) "\n"))
19829 (goto-char (point-min))
19830 (org-fit-agenda-window)
19831 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
19832 (org-finalize-agenda)
19833 (setq buffer-read-only t)))
19835 ;;; Agenda tags match
19837 ;;;###autoload
19838 (defun org-tags-view (&optional todo-only match)
19839 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
19840 The prefix arg TODO-ONLY limits the search to TODO entries."
19841 (interactive "P")
19842 (org-compile-prefix-format 'tags)
19843 (org-set-sorting-strategy 'tags)
19844 (let* ((org-tags-match-list-sublevels
19845 (if todo-only t org-tags-match-list-sublevels))
19846 (completion-ignore-case t)
19847 rtn rtnall files file pos matcher
19848 buffer)
19849 (setq matcher (org-make-tags-matcher match)
19850 match (car matcher) matcher (cdr matcher))
19851 (org-prepare-agenda (concat "TAGS " match))
19852 (setq org-agenda-redo-command
19853 (list 'org-tags-view (list 'quote todo-only)
19854 (list 'if 'current-prefix-arg nil match)))
19855 (setq files (org-agenda-files)
19856 rtnall nil)
19857 (while (setq file (pop files))
19858 (catch 'nextfile
19859 (org-check-agenda-file file)
19860 (setq buffer (if (file-exists-p file)
19861 (org-get-agenda-file-buffer file)
19862 (error "No such file %s" file)))
19863 (if (not buffer)
19864 ;; If file does not exist, merror message to agenda
19865 (setq rtn (list
19866 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
19867 rtnall (append rtnall rtn))
19868 (with-current-buffer buffer
19869 (unless (org-mode-p)
19870 (error "Agenda file %s is not in `org-mode'" file))
19871 (save-excursion
19872 (save-restriction
19873 (if org-agenda-restrict
19874 (narrow-to-region org-agenda-restrict-begin
19875 org-agenda-restrict-end)
19876 (widen))
19877 (setq rtn (org-scan-tags 'agenda matcher todo-only))
19878 (setq rtnall (append rtnall rtn))))))))
19879 (if org-agenda-overriding-header
19880 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
19881 nil 'face 'org-agenda-structure) "\n")
19882 (insert "Headlines with TAGS match: ")
19883 (add-text-properties (point-min) (1- (point))
19884 (list 'face 'org-agenda-structure))
19885 (setq pos (point))
19886 (insert match "\n")
19887 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
19888 (setq pos (point))
19889 (unless org-agenda-multi
19890 (insert "Press `C-u r' to search again with new search string\n"))
19891 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
19892 (when rtnall
19893 (insert (org-finalize-agenda-entries rtnall) "\n"))
19894 (goto-char (point-min))
19895 (org-fit-agenda-window)
19896 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
19897 (org-finalize-agenda)
19898 (setq buffer-read-only t)))
19900 ;;; Agenda Finding stuck projects
19902 (defvar org-agenda-skip-regexp nil
19903 "Regular expression used in skipping subtrees for the agenda.
19904 This is basically a temporary global variable that can be set and then
19905 used by user-defined selections using `org-agenda-skip-function'.")
19907 (defvar org-agenda-overriding-header nil
19908 "When this is set during todo and tags searches, will replace header.")
19910 (defun org-agenda-skip-subtree-when-regexp-matches ()
19911 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
19912 If yes, it returns the end position of this tree, causing agenda commands
19913 to skip this subtree. This is a function that can be put into
19914 `org-agenda-skip-function' for the duration of a command."
19915 (let ((end (save-excursion (org-end-of-subtree t)))
19916 skip)
19917 (save-excursion
19918 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
19919 (and skip end)))
19921 (defun org-agenda-skip-entry-if (&rest conditions)
19922 "Skip entry if any of CONDITIONS is true.
19923 See `org-agenda-skip-if for details."
19924 (org-agenda-skip-if nil conditions))
19926 (defun org-agenda-skip-subtree-if (&rest conditions)
19927 "Skip entry if any of CONDITIONS is true.
19928 See `org-agenda-skip-if for details."
19929 (org-agenda-skip-if t conditions))
19931 (defun org-agenda-skip-if (subtree conditions)
19932 "Checks current entity for CONDITIONS.
19933 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
19934 the entry, i.e. the text before the next heading is checked.
19936 CONDITIONS is a list of symbols, boolean OR is used to combine the results
19937 from different tests. Valid conditions are:
19939 scheduled Check if there is a scheduled cookie
19940 notscheduled Check if there is no scheduled cookie
19941 deadline Check if there is a deadline
19942 notdeadline Check if there is no deadline
19943 regexp Check if regexp matches
19944 notregexp Check if regexp does not match.
19946 The regexp is taken from the conditions list, it must com right after the
19947 `regexp' of `notregexp' element.
19949 If any of these conditions is met, this function returns the end point of
19950 the entity, causing the search to continue from there. This is a function
19951 that can be put into `org-agenda-skip-function' for the duration of a command."
19952 (let (beg end m)
19953 (org-back-to-heading t)
19954 (setq beg (point)
19955 end (if subtree
19956 (progn (org-end-of-subtree t) (point))
19957 (progn (outline-next-heading) (1- (point)))))
19958 (goto-char beg)
19959 (and
19961 (and (memq 'scheduled conditions)
19962 (re-search-forward org-scheduled-time-regexp end t))
19963 (and (memq 'notscheduled conditions)
19964 (not (re-search-forward org-scheduled-time-regexp end t)))
19965 (and (memq 'deadline conditions)
19966 (re-search-forward org-deadline-time-regexp end t))
19967 (and (memq 'notdeadline conditions)
19968 (not (re-search-forward org-deadline-time-regexp end t)))
19969 (and (setq m (memq 'regexp conditions))
19970 (stringp (nth 1 m))
19971 (re-search-forward (nth 1 m) end t))
19972 (and (setq m (memq 'notregexp conditions))
19973 (stringp (nth 1 m))
19974 (not (re-search-forward (nth 1 m) end t))))
19975 end)))
19977 ;;;###autoload
19978 (defun org-agenda-list-stuck-projects (&rest ignore)
19979 "Create agenda view for projects that are stuck.
19980 Stuck projects are project that have no next actions. For the definitions
19981 of what a project is and how to check if it stuck, customize the variable
19982 `org-stuck-projects'.
19983 MATCH is being ignored."
19984 (interactive)
19985 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
19986 ;; FIXME: we could have used org-agenda-skip-if here.
19987 (org-agenda-overriding-header "List of stuck projects: ")
19988 (matcher (nth 0 org-stuck-projects))
19989 (todo (nth 1 org-stuck-projects))
19990 (todo-wds (if (member "*" todo)
19991 (progn
19992 (org-prepare-agenda-buffers (org-agenda-files))
19993 (org-delete-all
19994 org-done-keywords-for-agenda
19995 (copy-sequence org-todo-keywords-for-agenda)))
19996 todo))
19997 (todo-re (concat "^\\*+[ \t]+\\("
19998 (mapconcat 'identity todo-wds "\\|")
19999 "\\)\\>"))
20000 (tags (nth 2 org-stuck-projects))
20001 (tags-re (if (member "*" tags)
20002 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20003 (concat "^\\*+ .*:\\("
20004 (mapconcat 'identity tags "\\|")
20005 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20006 (gen-re (nth 3 org-stuck-projects))
20007 (re-list
20008 (delq nil
20009 (list
20010 (if todo todo-re)
20011 (if tags tags-re)
20012 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20013 gen-re)))))
20014 (setq org-agenda-skip-regexp
20015 (if re-list
20016 (mapconcat 'identity re-list "\\|")
20017 (error "No information how to identify unstuck projects")))
20018 (org-tags-view nil matcher)
20019 (with-current-buffer org-agenda-buffer-name
20020 (setq org-agenda-redo-command
20021 '(org-agenda-list-stuck-projects
20022 (or current-prefix-arg org-last-arg))))))
20024 ;;; Diary integration
20026 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20028 (defun org-get-entries-from-diary (date)
20029 "Get the (Emacs Calendar) diary entries for DATE."
20030 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20031 (diary-display-hook '(fancy-diary-display))
20032 (pop-up-frames nil)
20033 (list-diary-entries-hook
20034 (cons 'org-diary-default-entry list-diary-entries-hook))
20035 (diary-file-name-prefix-function nil) ; turn this feature off
20036 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20037 entries
20038 (org-disable-agenda-to-diary t))
20039 (save-excursion
20040 (save-window-excursion
20041 (funcall (if (fboundp 'diary-list-entries)
20042 'diary-list-entries 'list-diary-entries)
20043 date 1)))
20044 (if (not (get-buffer fancy-diary-buffer))
20045 (setq entries nil)
20046 (with-current-buffer fancy-diary-buffer
20047 (setq buffer-read-only nil)
20048 (if (zerop (buffer-size))
20049 ;; No entries
20050 (setq entries nil)
20051 ;; Omit the date and other unnecessary stuff
20052 (org-agenda-cleanup-fancy-diary)
20053 ;; Add prefix to each line and extend the text properties
20054 (if (zerop (buffer-size))
20055 (setq entries nil)
20056 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20057 (set-buffer-modified-p nil)
20058 (kill-buffer fancy-diary-buffer)))
20059 (when entries
20060 (setq entries (org-split-string entries "\n"))
20061 (setq entries
20062 (mapcar
20063 (lambda (x)
20064 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20065 ;; Extend the text properties to the beginning of the line
20066 (org-add-props x (text-properties-at (1- (length x)) x)
20067 'type "diary" 'date date))
20068 entries)))))
20070 (defun org-agenda-cleanup-fancy-diary ()
20071 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20072 This gets rid of the date, the underline under the date, and
20073 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20074 date. It also removes lines that contain only whitespace."
20075 (goto-char (point-min))
20076 (if (looking-at ".*?:[ \t]*")
20077 (progn
20078 (replace-match "")
20079 (re-search-forward "\n=+$" nil t)
20080 (replace-match "")
20081 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20082 (re-search-forward "\n=+$" nil t)
20083 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20084 (goto-char (point-min))
20085 (while (re-search-forward "^ +\n" nil t)
20086 (replace-match ""))
20087 (goto-char (point-min))
20088 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20089 (replace-match "")))
20091 ;; Make sure entries from the diary have the right text properties.
20092 (eval-after-load "diary-lib"
20093 '(if (boundp 'diary-modify-entry-list-string-function)
20094 ;; We can rely on the hook, nothing to do
20096 ;; Hook not avaiable, must use advice to make this work
20097 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20098 "Make the position visible."
20099 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20100 (stringp string)
20101 buffer-file-name)
20102 (setq string (org-modify-diary-entry-string string))))))
20104 (defun org-modify-diary-entry-string (string)
20105 "Add text properties to string, allowing org-mode to act on it."
20106 (org-add-props string nil
20107 'mouse-face 'highlight
20108 'keymap org-agenda-keymap
20109 'help-echo (if buffer-file-name
20110 (format "mouse-2 or RET jump to diary file %s"
20111 (abbreviate-file-name buffer-file-name))
20113 'org-agenda-diary-link t
20114 'org-marker (org-agenda-new-marker (point-at-bol))))
20116 (defun org-diary-default-entry ()
20117 "Add a dummy entry to the diary.
20118 Needed to avoid empty dates which mess up holiday display."
20119 ;; Catch the error if dealing with the new add-to-diary-alist
20120 (when org-disable-agenda-to-diary
20121 (condition-case nil
20122 (add-to-diary-list original-date "Org-mode dummy" "")
20123 (error
20124 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
20126 ;;;###autoload
20127 (defun org-diary (&rest args)
20128 "Return diary information from org-files.
20129 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
20130 It accesses org files and extracts information from those files to be
20131 listed in the diary. The function accepts arguments specifying what
20132 items should be listed. The following arguments are allowed:
20134 :timestamp List the headlines of items containing a date stamp or
20135 date range matching the selected date. Deadlines will
20136 also be listed, on the expiration day.
20138 :sexp List entries resulting from diary-like sexps.
20140 :deadline List any deadlines past due, or due within
20141 `org-deadline-warning-days'. The listing occurs only
20142 in the diary for *today*, not at any other date. If
20143 an entry is marked DONE, it is no longer listed.
20145 :scheduled List all items which are scheduled for the given date.
20146 The diary for *today* also contains items which were
20147 scheduled earlier and are not yet marked DONE.
20149 :todo List all TODO items from the org-file. This may be a
20150 long list - so this is not turned on by default.
20151 Like deadlines, these entries only show up in the
20152 diary for *today*, not at any other date.
20154 The call in the diary file should look like this:
20156 &%%(org-diary) ~/path/to/some/orgfile.org
20158 Use a separate line for each org file to check. Or, if you omit the file name,
20159 all files listed in `org-agenda-files' will be checked automatically:
20161 &%%(org-diary)
20163 If you don't give any arguments (as in the example above), the default
20164 arguments (:deadline :scheduled :timestamp :sexp) are used.
20165 So the example above may also be written as
20167 &%%(org-diary :deadline :timestamp :sexp :scheduled)
20169 The function expects the lisp variables `entry' and `date' to be provided
20170 by the caller, because this is how the calendar works. Don't use this
20171 function from a program - use `org-agenda-get-day-entries' instead."
20172 (org-agenda-maybe-reset-markers)
20173 (org-compile-prefix-format 'agenda)
20174 (org-set-sorting-strategy 'agenda)
20175 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20176 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
20177 (list entry)
20178 (org-agenda-files t)))
20179 file rtn results)
20180 (org-prepare-agenda-buffers files)
20181 ;; If this is called during org-agenda, don't return any entries to
20182 ;; the calendar. Org Agenda will list these entries itself.
20183 (if org-disable-agenda-to-diary (setq files nil))
20184 (while (setq file (pop files))
20185 (setq rtn (apply 'org-agenda-get-day-entries file date args))
20186 (setq results (append results rtn)))
20187 (if results
20188 (concat (org-finalize-agenda-entries results) "\n"))))
20190 ;;; Agenda entry finders
20192 (defun org-agenda-get-day-entries (file date &rest args)
20193 "Does the work for `org-diary' and `org-agenda'.
20194 FILE is the path to a file to be checked for entries. DATE is date like
20195 the one returned by `calendar-current-date'. ARGS are symbols indicating
20196 which kind of entries should be extracted. For details about these, see
20197 the documentation of `org-diary'."
20198 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20199 (let* ((org-startup-folded nil)
20200 (org-startup-align-all-tables nil)
20201 (buffer (if (file-exists-p file)
20202 (org-get-agenda-file-buffer file)
20203 (error "No such file %s" file)))
20204 arg results rtn)
20205 (if (not buffer)
20206 ;; If file does not exist, make sure an error message ends up in diary
20207 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20208 (with-current-buffer buffer
20209 (unless (org-mode-p)
20210 (error "Agenda file %s is not in `org-mode'" file))
20211 (let ((case-fold-search nil))
20212 (save-excursion
20213 (save-restriction
20214 (if org-agenda-restrict
20215 (narrow-to-region org-agenda-restrict-begin
20216 org-agenda-restrict-end)
20217 (widen))
20218 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
20219 (while (setq arg (pop args))
20220 (cond
20221 ((and (eq arg :todo)
20222 (equal date (calendar-current-date)))
20223 (setq rtn (org-agenda-get-todos))
20224 (setq results (append results rtn)))
20225 ((eq arg :timestamp)
20226 (setq rtn (org-agenda-get-blocks))
20227 (setq results (append results rtn))
20228 (setq rtn (org-agenda-get-timestamps))
20229 (setq results (append results rtn)))
20230 ((eq arg :sexp)
20231 (setq rtn (org-agenda-get-sexps))
20232 (setq results (append results rtn)))
20233 ((eq arg :scheduled)
20234 (setq rtn (org-agenda-get-scheduled))
20235 (setq results (append results rtn)))
20236 ((eq arg :closed)
20237 (setq rtn (org-agenda-get-closed))
20238 (setq results (append results rtn)))
20239 ((eq arg :deadline)
20240 (setq rtn (org-agenda-get-deadlines))
20241 (setq results (append results rtn))))))))
20242 results))))
20244 ;; FIXME: this works only if the cursor is *not* at the
20245 ;; beginning of the entry
20246 ;(defun org-entry-is-done-p ()
20247 ; "Is the current entry marked DONE?"
20248 ; (save-excursion
20249 ; (and (re-search-backward "[\r\n]\\*+ " nil t)
20250 ; (looking-at org-nl-done-regexp))))
20252 (defun org-entry-is-todo-p ()
20253 (member (org-get-todo-state) org-not-done-keywords))
20255 (defun org-entry-is-done-p ()
20256 (member (org-get-todo-state) org-done-keywords))
20258 (defun org-get-todo-state ()
20259 (save-excursion
20260 (org-back-to-heading t)
20261 (and (looking-at org-todo-line-regexp)
20262 (match-end 2)
20263 (match-string 2))))
20265 (defun org-at-date-range-p (&optional inactive-ok)
20266 "Is the cursor inside a date range?"
20267 (interactive)
20268 (save-excursion
20269 (catch 'exit
20270 (let ((pos (point)))
20271 (skip-chars-backward "^[<\r\n")
20272 (skip-chars-backward "<[")
20273 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20274 (>= (match-end 0) pos)
20275 (throw 'exit t))
20276 (skip-chars-backward "^<[\r\n")
20277 (skip-chars-backward "<[")
20278 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20279 (>= (match-end 0) pos)
20280 (throw 'exit t)))
20281 nil)))
20283 (defun org-agenda-get-todos ()
20284 "Return the TODO information for agenda display."
20285 (let* ((props (list 'face nil
20286 'done-face 'org-done
20287 'org-not-done-regexp org-not-done-regexp
20288 'org-todo-regexp org-todo-regexp
20289 'mouse-face 'highlight
20290 'keymap org-agenda-keymap
20291 'help-echo
20292 (format "mouse-2 or RET jump to org file %s"
20293 (abbreviate-file-name buffer-file-name))))
20294 ;; FIXME: get rid of the \n at some point but watch out
20295 (regexp (concat "^\\*+[ \t]+\\("
20296 (if org-select-this-todo-keyword
20297 (if (equal org-select-this-todo-keyword "*")
20298 org-todo-regexp
20299 (concat "\\<\\("
20300 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
20301 "\\)\\>"))
20302 org-not-done-regexp)
20303 "[^\n\r]*\\)"))
20304 marker priority category tags
20305 ee txt beg end)
20306 (goto-char (point-min))
20307 (while (re-search-forward regexp nil t)
20308 (catch :skip
20309 (save-match-data
20310 (beginning-of-line)
20311 (setq beg (point) end (progn (outline-next-heading) (point)))
20312 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
20313 (re-search-forward org-ts-regexp end t))
20314 (and org-agenda-todo-ignore-scheduled (goto-char beg)
20315 (re-search-forward org-scheduled-time-regexp end t))
20316 (and org-agenda-todo-ignore-deadlines (goto-char beg)
20317 (re-search-forward org-deadline-time-regexp end t)
20318 (org-deadline-close (match-string 1))))
20319 (goto-char (1+ beg))
20320 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
20321 (throw :skip nil)))
20322 (goto-char beg)
20323 (org-agenda-skip)
20324 (goto-char (match-beginning 1))
20325 (setq marker (org-agenda-new-marker (match-beginning 0))
20326 category (org-get-category)
20327 tags (org-get-tags-at (point))
20328 txt (org-format-agenda-item "" (match-string 1) category tags)
20329 priority (1+ (org-get-priority txt)))
20330 (org-add-props txt props
20331 'org-marker marker 'org-hd-marker marker
20332 'priority priority 'org-category category
20333 'type "todo")
20334 (push txt ee)
20335 (if org-agenda-todo-list-sublevels
20336 (goto-char (match-end 1))
20337 (org-end-of-subtree 'invisible))))
20338 (nreverse ee)))
20340 (defconst org-agenda-no-heading-message
20341 "No heading for this item in buffer or region.")
20343 (defun org-agenda-get-timestamps ()
20344 "Return the date stamp information for agenda display."
20345 (let* ((props (list 'face nil
20346 'org-not-done-regexp org-not-done-regexp
20347 'org-todo-regexp org-todo-regexp
20348 'mouse-face 'highlight
20349 'keymap org-agenda-keymap
20350 'help-echo
20351 (format "mouse-2 or RET jump to org file %s"
20352 (abbreviate-file-name buffer-file-name))))
20353 (d1 (calendar-absolute-from-gregorian date))
20354 (remove-re
20355 (concat
20356 (regexp-quote
20357 (format-time-string
20358 "<%Y-%m-%d"
20359 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20360 ".*?>"))
20361 (regexp
20362 (concat
20363 (regexp-quote
20364 (substring
20365 (format-time-string
20366 (car org-time-stamp-formats)
20367 (apply 'encode-time ; DATE bound by calendar
20368 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20369 0 11))
20370 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
20371 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
20372 marker hdmarker deadlinep scheduledp donep tmp priority category
20373 ee txt timestr tags b0 b3 e3 head)
20374 (goto-char (point-min))
20375 (while (re-search-forward regexp nil t)
20376 (setq b0 (match-beginning 0)
20377 b3 (match-beginning 3) e3 (match-end 3))
20378 (catch :skip
20379 (and (org-at-date-range-p) (throw :skip nil))
20380 (org-agenda-skip)
20381 (if (and (match-end 1)
20382 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
20383 (throw :skip nil))
20384 (if (and e3
20385 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
20386 (throw :skip nil))
20387 (setq marker (org-agenda-new-marker b0)
20388 category (org-get-category b0)
20389 tmp (buffer-substring (max (point-min)
20390 (- b0 org-ds-keyword-length))
20392 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
20393 deadlinep (string-match org-deadline-regexp tmp)
20394 scheduledp (string-match org-scheduled-regexp tmp)
20395 donep (org-entry-is-done-p))
20396 (if (or scheduledp deadlinep) (throw :skip t))
20397 (if (string-match ">" timestr)
20398 ;; substring should only run to end of time stamp
20399 (setq timestr (substring timestr 0 (match-end 0))))
20400 (save-excursion
20401 (if (re-search-backward "^\\*+ " nil t)
20402 (progn
20403 (goto-char (match-beginning 0))
20404 (setq hdmarker (org-agenda-new-marker)
20405 tags (org-get-tags-at))
20406 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20407 (setq head (match-string 1))
20408 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
20409 (setq txt (org-format-agenda-item
20410 nil head category tags timestr nil
20411 remove-re)))
20412 (setq txt org-agenda-no-heading-message))
20413 (setq priority (org-get-priority txt))
20414 (org-add-props txt props
20415 'org-marker marker 'org-hd-marker hdmarker)
20416 (org-add-props txt nil 'priority priority
20417 'org-category category 'date date
20418 'type "timestamp")
20419 (push txt ee))
20420 (outline-next-heading)))
20421 (nreverse ee)))
20423 (defun org-agenda-get-sexps ()
20424 "Return the sexp information for agenda display."
20425 (require 'diary-lib)
20426 (let* ((props (list 'face nil
20427 'mouse-face 'highlight
20428 'keymap org-agenda-keymap
20429 'help-echo
20430 (format "mouse-2 or RET jump to org file %s"
20431 (abbreviate-file-name buffer-file-name))))
20432 (regexp "^&?%%(")
20433 marker category ee txt tags entry result beg b sexp sexp-entry)
20434 (goto-char (point-min))
20435 (while (re-search-forward regexp nil t)
20436 (catch :skip
20437 (org-agenda-skip)
20438 (setq beg (match-beginning 0))
20439 (goto-char (1- (match-end 0)))
20440 (setq b (point))
20441 (forward-sexp 1)
20442 (setq sexp (buffer-substring b (point)))
20443 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
20444 (org-trim (match-string 1))
20445 ""))
20446 (setq result (org-diary-sexp-entry sexp sexp-entry date))
20447 (when result
20448 (setq marker (org-agenda-new-marker beg)
20449 category (org-get-category beg))
20451 (if (string-match "\\S-" result)
20452 (setq txt result)
20453 (setq txt "SEXP entry returned empty string"))
20455 (setq txt (org-format-agenda-item
20456 "" txt category tags 'time))
20457 (org-add-props txt props 'org-marker marker)
20458 (org-add-props txt nil
20459 'org-category category 'date date
20460 'type "sexp")
20461 (push txt ee))))
20462 (nreverse ee)))
20464 (defun org-agenda-get-closed ()
20465 "Return the logged TODO entries for agenda display."
20466 (let* ((props (list 'mouse-face 'highlight
20467 'org-not-done-regexp org-not-done-regexp
20468 'org-todo-regexp org-todo-regexp
20469 'keymap org-agenda-keymap
20470 'help-echo
20471 (format "mouse-2 or RET jump to org file %s"
20472 (abbreviate-file-name buffer-file-name))))
20473 (regexp (concat
20474 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
20475 (regexp-quote
20476 (substring
20477 (format-time-string
20478 (car org-time-stamp-formats)
20479 (apply 'encode-time ; DATE bound by calendar
20480 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20481 1 11))))
20482 marker hdmarker priority category tags closedp
20483 ee txt timestr)
20484 (goto-char (point-min))
20485 (while (re-search-forward regexp nil t)
20486 (catch :skip
20487 (org-agenda-skip)
20488 (setq marker (org-agenda-new-marker (match-beginning 0))
20489 closedp (equal (match-string 1) org-closed-string)
20490 category (org-get-category (match-beginning 0))
20491 timestr (buffer-substring (match-beginning 0) (point-at-eol))
20492 ;; donep (org-entry-is-done-p)
20494 (if (string-match "\\]" timestr)
20495 ;; substring should only run to end of time stamp
20496 (setq timestr (substring timestr 0 (match-end 0))))
20497 (save-excursion
20498 (if (re-search-backward "^\\*+ " nil t)
20499 (progn
20500 (goto-char (match-beginning 0))
20501 (setq hdmarker (org-agenda-new-marker)
20502 tags (org-get-tags-at))
20503 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20504 (setq txt (org-format-agenda-item
20505 (if closedp "Closed: " "Clocked: ")
20506 (match-string 1) category tags timestr)))
20507 (setq txt org-agenda-no-heading-message))
20508 (setq priority 100000)
20509 (org-add-props txt props
20510 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
20511 'priority priority 'org-category category
20512 'type "closed" 'date date
20513 'undone-face 'org-warning 'done-face 'org-done)
20514 (push txt ee))
20515 (outline-next-heading)))
20516 (nreverse ee)))
20518 (defun org-agenda-get-deadlines ()
20519 "Return the deadline information for agenda display."
20520 (let* ((props (list 'mouse-face 'highlight
20521 'org-not-done-regexp org-not-done-regexp
20522 'org-todo-regexp org-todo-regexp
20523 'keymap org-agenda-keymap
20524 'help-echo
20525 (format "mouse-2 or RET jump to org file %s"
20526 (abbreviate-file-name buffer-file-name))))
20527 (regexp org-deadline-time-regexp)
20528 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20529 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20530 d2 diff dfrac wdays pos pos1 category tags
20531 ee txt head face s upcomingp donep timestr)
20532 (goto-char (point-min))
20533 (while (re-search-forward regexp nil t)
20534 (catch :skip
20535 (org-agenda-skip)
20536 (setq s (match-string 1)
20537 pos (1- (match-beginning 1))
20538 d2 (org-time-string-to-absolute (match-string 1) d1)
20539 diff (- d2 d1)
20540 wdays (org-get-wdays s)
20541 dfrac (/ (* 1.0 (- wdays diff)) wdays)
20542 upcomingp (and todayp (> diff 0)))
20543 ;; When to show a deadline in the calendar:
20544 ;; If the expiration is within wdays warning time.
20545 ;; Past-due deadlines are only shown on the current date
20546 (if (or (and (<= diff wdays)
20547 (and todayp (not org-agenda-only-exact-dates)))
20548 (= diff 0))
20549 (save-excursion
20550 (setq category (org-get-category))
20551 (if (re-search-backward "^\\*+[ \t]+" nil t)
20552 (progn
20553 (goto-char (match-end 0))
20554 (setq pos1 (match-beginning 0))
20555 (setq tags (org-get-tags-at pos1))
20556 (setq head (buffer-substring-no-properties
20557 (point)
20558 (progn (skip-chars-forward "^\r\n")
20559 (point))))
20560 (setq donep (string-match org-looking-at-done-regexp head))
20561 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20562 (setq timestr
20563 (concat (substring s (match-beginning 1)) " "))
20564 (setq timestr 'time))
20565 (if (and donep
20566 (or org-agenda-skip-deadline-if-done
20567 (not (= diff 0))))
20568 (setq txt nil)
20569 (setq txt (org-format-agenda-item
20570 (if (= diff 0)
20571 (car org-agenda-deadline-leaders)
20572 (format (nth 1 org-agenda-deadline-leaders)
20573 diff))
20574 head category tags timestr))))
20575 (setq txt org-agenda-no-heading-message))
20576 (when txt
20577 (setq face (org-agenda-deadline-face dfrac))
20578 (org-add-props txt props
20579 'org-marker (org-agenda-new-marker pos)
20580 'org-hd-marker (org-agenda-new-marker pos1)
20581 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
20582 (org-get-priority txt))
20583 'org-category category
20584 'type (if upcomingp "upcoming-deadline" "deadline")
20585 'date (if upcomingp date d2)
20586 'face (if donep 'org-done face)
20587 'undone-face face 'done-face 'org-done)
20588 (push txt ee))))))
20589 (nreverse ee)))
20591 (defun org-agenda-deadline-face (fraction)
20592 "Return the face to displaying a deadline item.
20593 FRACTION is what fraction of the head-warning time has passed."
20594 (let ((faces org-agenda-deadline-faces) f)
20595 (catch 'exit
20596 (while (setq f (pop faces))
20597 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
20599 (defun org-agenda-get-scheduled ()
20600 "Return the scheduled information for agenda display."
20601 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
20602 'org-todo-regexp org-todo-regexp
20603 'done-face 'org-done
20604 'mouse-face 'highlight
20605 'keymap org-agenda-keymap
20606 'help-echo
20607 (format "mouse-2 or RET jump to org file %s"
20608 (abbreviate-file-name buffer-file-name))))
20609 (regexp org-scheduled-time-regexp)
20610 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20611 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20612 d2 diff pos pos1 category tags
20613 ee txt head pastschedp donep face timestr s)
20614 (goto-char (point-min))
20615 (while (re-search-forward regexp nil t)
20616 (catch :skip
20617 (org-agenda-skip)
20618 (setq s (match-string 1)
20619 pos (1- (match-beginning 1))
20620 d2 (org-time-string-to-absolute (match-string 1) d1)
20621 diff (- d2 d1))
20622 (setq pastschedp (and todayp (< diff 0)))
20623 ;; When to show a scheduled item in the calendar:
20624 ;; If it is on or past the date.
20625 (if (or (and (< diff 0)
20626 (and todayp (not org-agenda-only-exact-dates)))
20627 (= diff 0))
20628 (save-excursion
20629 (setq category (org-get-category))
20630 (if (re-search-backward "^\\*+[ \t]+" nil t)
20631 (progn
20632 (goto-char (match-end 0))
20633 (setq pos1 (match-beginning 0))
20634 (setq tags (org-get-tags-at))
20635 (setq head (buffer-substring-no-properties
20636 (point)
20637 (progn (skip-chars-forward "^\r\n") (point))))
20638 (setq donep (string-match org-looking-at-done-regexp head))
20639 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20640 (setq timestr
20641 (concat (substring s (match-beginning 1)) " "))
20642 (setq timestr 'time))
20643 (if (and donep
20644 (or org-agenda-skip-scheduled-if-done
20645 (not (= diff 0))))
20646 (setq txt nil)
20647 (setq txt (org-format-agenda-item
20648 (if (= diff 0)
20649 (car org-agenda-scheduled-leaders)
20650 (format (nth 1 org-agenda-scheduled-leaders)
20651 (- 1 diff)))
20652 head category tags timestr))))
20653 (setq txt org-agenda-no-heading-message))
20654 (when txt
20655 (setq face (if pastschedp
20656 'org-scheduled-previously
20657 'org-scheduled-today))
20658 (org-add-props txt props
20659 'undone-face face
20660 'face (if donep 'org-done face)
20661 'org-marker (org-agenda-new-marker pos)
20662 'org-hd-marker (org-agenda-new-marker pos1)
20663 'type (if pastschedp "past-scheduled" "scheduled")
20664 'date (if pastschedp d2 date)
20665 'priority (+ 94 (- 5 diff) (org-get-priority txt))
20666 'org-category category)
20667 (push txt ee))))))
20668 (nreverse ee)))
20670 (defun org-agenda-get-blocks ()
20671 "Return the date-range information for agenda display."
20672 (let* ((props (list 'face nil
20673 'org-not-done-regexp org-not-done-regexp
20674 'org-todo-regexp org-todo-regexp
20675 'mouse-face 'highlight
20676 'keymap org-agenda-keymap
20677 'help-echo
20678 (format "mouse-2 or RET jump to org file %s"
20679 (abbreviate-file-name buffer-file-name))))
20680 (regexp org-tr-regexp)
20681 (d0 (calendar-absolute-from-gregorian date))
20682 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
20683 donep head)
20684 (goto-char (point-min))
20685 (while (re-search-forward regexp nil t)
20686 (catch :skip
20687 (org-agenda-skip)
20688 (setq pos (point))
20689 (setq timestr (match-string 0)
20690 s1 (match-string 1)
20691 s2 (match-string 2)
20692 d1 (time-to-days (org-time-string-to-time s1))
20693 d2 (time-to-days (org-time-string-to-time s2)))
20694 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
20695 ;; Only allow days between the limits, because the normal
20696 ;; date stamps will catch the limits.
20697 (save-excursion
20698 (setq marker (org-agenda-new-marker (point)))
20699 (setq category (org-get-category))
20700 (if (re-search-backward "^\\*+ " nil t)
20701 (progn
20702 (goto-char (match-beginning 0))
20703 (setq hdmarker (org-agenda-new-marker (point)))
20704 (setq tags (org-get-tags-at))
20705 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20706 (setq head (match-string 1))
20707 (and org-agenda-skip-timestamp-if-done
20708 (org-entry-is-done-p)
20709 (throw :skip t))
20710 (setq txt (org-format-agenda-item
20711 (format (if (= d1 d2) "" "(%d/%d): ")
20712 (1+ (- d0 d1)) (1+ (- d2 d1)))
20713 head category tags
20714 (if (= d0 d1) timestr))))
20715 (setq txt org-agenda-no-heading-message))
20716 (org-add-props txt props
20717 'org-marker marker 'org-hd-marker hdmarker
20718 'type "block" 'date date
20719 'priority (org-get-priority txt) 'org-category category)
20720 (push txt ee)))
20721 (goto-char pos)))
20722 ;; Sort the entries by expiration date.
20723 (nreverse ee)))
20725 ;;; Agenda presentation and sorting
20727 (defconst org-plain-time-of-day-regexp
20728 (concat
20729 "\\(\\<[012]?[0-9]"
20730 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20731 "\\(--?"
20732 "\\(\\<[012]?[0-9]"
20733 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20734 "\\)?")
20735 "Regular expression to match a plain time or time range.
20736 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20737 groups carry important information:
20738 0 the full match
20739 1 the first time, range or not
20740 8 the second time, if it is a range.")
20742 (defconst org-plain-time-extension-regexp
20743 (concat
20744 "\\(\\<[012]?[0-9]"
20745 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20746 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
20747 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
20748 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20749 groups carry important information:
20750 0 the full match
20751 7 hours of duration
20752 9 minutes of duration")
20754 (defconst org-stamp-time-of-day-regexp
20755 (concat
20756 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
20757 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
20758 "\\(--?"
20759 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
20760 "Regular expression to match a timestamp time or time range.
20761 After a match, the following groups carry important information:
20762 0 the full match
20763 1 date plus weekday, for backreferencing to make sure both times on same day
20764 2 the first time, range or not
20765 4 the second time, if it is a range.")
20767 (defvar org-prefix-has-time nil
20768 "A flag, set by `org-compile-prefix-format'.
20769 The flag is set if the currently compiled format contains a `%t'.")
20770 (defvar org-prefix-has-tag nil
20771 "A flag, set by `org-compile-prefix-format'.
20772 The flag is set if the currently compiled format contains a `%T'.")
20774 (defun org-format-agenda-item (extra txt &optional category tags dotime
20775 noprefix remove-re)
20776 "Format TXT to be inserted into the agenda buffer.
20777 In particular, it adds the prefix and corresponding text properties. EXTRA
20778 must be a string and replaces the `%s' specifier in the prefix format.
20779 CATEGORY (string, symbol or nil) may be used to overrule the default
20780 category taken from local variable or file name. It will replace the `%c'
20781 specifier in the format. DOTIME, when non-nil, indicates that a
20782 time-of-day should be extracted from TXT for sorting of this entry, and for
20783 the `%t' specifier in the format. When DOTIME is a string, this string is
20784 searched for a time before TXT is. NOPREFIX is a flag and indicates that
20785 only the correctly processes TXT should be returned - this is used by
20786 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
20787 Any match of REMOVE-RE will be removed from TXT."
20788 (save-match-data
20789 ;; Diary entries sometimes have extra whitespace at the beginning
20790 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
20791 (let* ((category (or category
20792 org-category
20793 (if buffer-file-name
20794 (file-name-sans-extension
20795 (file-name-nondirectory buffer-file-name))
20796 "")))
20797 (tag (if tags (nth (1- (length tags)) tags) ""))
20798 time ; time and tag are needed for the eval of the prefix format
20799 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
20800 (time-of-day (and dotime (org-get-time-of-day ts)))
20801 stamp plain s0 s1 s2 rtn srp)
20802 (when (and dotime time-of-day org-prefix-has-time)
20803 ;; Extract starting and ending time and move them to prefix
20804 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
20805 (setq plain (string-match org-plain-time-of-day-regexp ts)))
20806 (setq s0 (match-string 0 ts)
20807 srp (and stamp (match-end 3))
20808 s1 (match-string (if plain 1 2) ts)
20809 s2 (match-string (if plain 8 (if srp 4 6)) ts))
20811 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
20812 ;; them, we might want to remove them there to avoid duplication.
20813 ;; The user can turn this off with a variable.
20814 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
20815 (string-match (concat (regexp-quote s0) " *") txt)
20816 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
20817 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
20818 (= (match-beginning 0) 0)
20820 (setq txt (replace-match "" nil nil txt))))
20821 ;; Normalize the time(s) to 24 hour
20822 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
20823 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
20825 (when (and s1 (not s2) org-agenda-default-appointment-duration
20826 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
20827 (let ((m (+ (string-to-number (match-string 2 s1))
20828 (* 60 (string-to-number (match-string 1 s1)))
20829 org-agenda-default-appointment-duration))
20831 (setq h (/ m 60) m (- m (* h 60)))
20832 (setq s2 (format "%02d:%02d" h m))))
20834 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
20835 txt)
20836 ;; Tags are in the string
20837 (if (or (eq org-agenda-remove-tags t)
20838 (and org-agenda-remove-tags
20839 org-prefix-has-tag))
20840 (setq txt (replace-match "" t t txt))
20841 (setq txt (replace-match
20842 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
20843 (match-string 2 txt))
20844 t t txt))))
20846 (when remove-re
20847 (while (string-match remove-re txt)
20848 (setq txt (replace-match "" t t txt))))
20850 ;; Create the final string
20851 (if noprefix
20852 (setq rtn txt)
20853 ;; Prepare the variables needed in the eval of the compiled format
20854 (setq time (cond (s2 (concat s1 "-" s2))
20855 (s1 (concat s1 "......"))
20856 (t ""))
20857 extra (or extra "")
20858 category (if (symbolp category) (symbol-name category) category))
20859 ;; Evaluate the compiled format
20860 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
20862 ;; And finally add the text properties
20863 (org-add-props rtn nil
20864 'org-category (downcase category) 'tags tags
20865 'org-highest-priority org-highest-priority
20866 'org-lowest-priority org-lowest-priority
20867 'prefix-length (- (length rtn) (length txt))
20868 'time-of-day time-of-day
20869 'txt txt
20870 'time time
20871 'extra extra
20872 'dotime dotime))))
20874 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
20875 (defvar org-agenda-sorting-strategy-selected nil)
20877 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
20878 (catch 'exit
20879 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
20880 ((and todayp (member 'today (car org-agenda-time-grid))))
20881 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
20882 ((member 'weekly (car org-agenda-time-grid)))
20883 (t (throw 'exit list)))
20884 (let* ((have (delq nil (mapcar
20885 (lambda (x) (get-text-property 1 'time-of-day x))
20886 list)))
20887 (string (nth 1 org-agenda-time-grid))
20888 (gridtimes (nth 2 org-agenda-time-grid))
20889 (req (car org-agenda-time-grid))
20890 (remove (member 'remove-match req))
20891 new time)
20892 (if (and (member 'require-timed req) (not have))
20893 ;; don't show empty grid
20894 (throw 'exit list))
20895 (while (setq time (pop gridtimes))
20896 (unless (and remove (member time have))
20897 (setq time (int-to-string time))
20898 (push (org-format-agenda-item
20899 nil string "" nil
20900 (concat (substring time 0 -2) ":" (substring time -2)))
20901 new)
20902 (put-text-property
20903 1 (length (car new)) 'face 'org-time-grid (car new))))
20904 (if (member 'time-up org-agenda-sorting-strategy-selected)
20905 (append new list)
20906 (append list new)))))
20908 (defun org-compile-prefix-format (key)
20909 "Compile the prefix format into a Lisp form that can be evaluated.
20910 The resulting form is returned and stored in the variable
20911 `org-prefix-format-compiled'."
20912 (setq org-prefix-has-time nil org-prefix-has-tag nil)
20913 (let ((s (cond
20914 ((stringp org-agenda-prefix-format)
20915 org-agenda-prefix-format)
20916 ((assq key org-agenda-prefix-format)
20917 (cdr (assq key org-agenda-prefix-format)))
20918 (t " %-12:c%?-12t% s")))
20919 (start 0)
20920 varform vars var e c f opt)
20921 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
20922 s start)
20923 (setq var (cdr (assoc (match-string 4 s)
20924 '(("c" . category) ("t" . time) ("s" . extra)
20925 ("T" . tag))))
20926 c (or (match-string 3 s) "")
20927 opt (match-beginning 1)
20928 start (1+ (match-beginning 0)))
20929 (if (equal var 'time) (setq org-prefix-has-time t))
20930 (if (equal var 'tag) (setq org-prefix-has-tag t))
20931 (setq f (concat "%" (match-string 2 s) "s"))
20932 (if opt
20933 (setq varform
20934 `(if (equal "" ,var)
20936 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
20937 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
20938 (setq s (replace-match "%s" t nil s))
20939 (push varform vars))
20940 (setq vars (nreverse vars))
20941 (setq org-prefix-format-compiled `(format ,s ,@vars))))
20943 (defun org-set-sorting-strategy (key)
20944 (if (symbolp (car org-agenda-sorting-strategy))
20945 ;; the old format
20946 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
20947 (setq org-agenda-sorting-strategy-selected
20948 (or (cdr (assq key org-agenda-sorting-strategy))
20949 (cdr (assq 'agenda org-agenda-sorting-strategy))
20950 '(time-up category-keep priority-down)))))
20952 (defun org-get-time-of-day (s &optional string mod24)
20953 "Check string S for a time of day.
20954 If found, return it as a military time number between 0 and 2400.
20955 If not found, return nil.
20956 The optional STRING argument forces conversion into a 5 character wide string
20957 HH:MM."
20958 (save-match-data
20959 (when
20960 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
20961 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
20962 (let* ((h (string-to-number (match-string 1 s)))
20963 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
20964 (ampm (if (match-end 4) (downcase (match-string 4 s))))
20965 (am-p (equal ampm "am"))
20966 (h1 (cond ((not ampm) h)
20967 ((= h 12) (if am-p 0 12))
20968 (t (+ h (if am-p 0 12)))))
20969 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
20970 (mod h1 24) h1))
20971 (t0 (+ (* 100 h2) m))
20972 (t1 (concat (if (>= h1 24) "+" " ")
20973 (if (< t0 100) "0" "")
20974 (if (< t0 10) "0" "")
20975 (int-to-string t0))))
20976 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
20978 (defun org-finalize-agenda-entries (list &optional nosort)
20979 "Sort and concatenate the agenda items."
20980 (setq list (mapcar 'org-agenda-highlight-todo list))
20981 (if nosort
20982 list
20983 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
20985 (defun org-agenda-highlight-todo (x)
20986 (let (re pl)
20987 (if (eq x 'line)
20988 (save-excursion
20989 (beginning-of-line 1)
20990 (setq re (get-text-property (point) 'org-todo-regexp))
20991 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
20992 (and (looking-at (concat "[ \t]*\\.*" re))
20993 (add-text-properties (match-beginning 0) (match-end 0)
20994 (list 'face (org-get-todo-face 0)))))
20995 (setq re (concat (get-text-property 0 'org-todo-regexp x))
20996 pl (get-text-property 0 'prefix-length x))
20997 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
20998 (add-text-properties
20999 (or (match-end 1) (match-end 0)) (match-end 0)
21000 (list 'face (org-get-todo-face (match-string 2 x)))
21002 x)))
21004 (defsubst org-cmp-priority (a b)
21005 "Compare the priorities of string A and B."
21006 (let ((pa (or (get-text-property 1 'priority a) 0))
21007 (pb (or (get-text-property 1 'priority b) 0)))
21008 (cond ((> pa pb) +1)
21009 ((< pa pb) -1)
21010 (t nil))))
21012 (defsubst org-cmp-category (a b)
21013 "Compare the string values of categories of strings A and B."
21014 (let ((ca (or (get-text-property 1 'org-category a) ""))
21015 (cb (or (get-text-property 1 'org-category b) "")))
21016 (cond ((string-lessp ca cb) -1)
21017 ((string-lessp cb ca) +1)
21018 (t nil))))
21020 (defsubst org-cmp-tag (a b)
21021 "Compare the string values of categories of strings A and B."
21022 (let ((ta (car (last (get-text-property 1 'tags a))))
21023 (tb (car (last (get-text-property 1 'tags b)))))
21024 (cond ((not ta) +1)
21025 ((not tb) -1)
21026 ((string-lessp ta tb) -1)
21027 ((string-lessp tb ta) +1)
21028 (t nil))))
21030 (defsubst org-cmp-time (a b)
21031 "Compare the time-of-day values of strings A and B."
21032 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21033 (ta (or (get-text-property 1 'time-of-day a) def))
21034 (tb (or (get-text-property 1 'time-of-day b) def)))
21035 (cond ((< ta tb) -1)
21036 ((< tb ta) +1)
21037 (t nil))))
21039 (defun org-entries-lessp (a b)
21040 "Predicate for sorting agenda entries."
21041 ;; The following variables will be used when the form is evaluated.
21042 ;; So even though the compiler complains, keep them.
21043 (let* ((time-up (org-cmp-time a b))
21044 (time-down (if time-up (- time-up) nil))
21045 (priority-up (org-cmp-priority a b))
21046 (priority-down (if priority-up (- priority-up) nil))
21047 (category-up (org-cmp-category a b))
21048 (category-down (if category-up (- category-up) nil))
21049 (category-keep (if category-up +1 nil))
21050 (tag-up (org-cmp-tag a b))
21051 (tag-down (if tag-up (- tag-up) nil)))
21052 (cdr (assoc
21053 (eval (cons 'or org-agenda-sorting-strategy-selected))
21054 '((-1 . t) (1 . nil) (nil . nil))))))
21056 ;;; Agenda commands
21058 (defun org-agenda-check-type (error &rest types)
21059 "Check if agenda buffer is of allowed type.
21060 If ERROR is non-nil, throw an error, otherwise just return nil."
21061 (if (memq org-agenda-type types)
21063 (if error
21064 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
21065 nil)))
21067 (defun org-agenda-quit ()
21068 "Exit agenda by removing the window or the buffer."
21069 (interactive)
21070 (let ((buf (current-buffer)))
21071 (if (not (one-window-p)) (delete-window))
21072 (kill-buffer buf)
21073 (org-agenda-maybe-reset-markers 'force)
21074 (org-columns-remove-overlays))
21075 ;; Maybe restore the pre-agenda window configuration.
21076 (and org-agenda-restore-windows-after-quit
21077 (not (eq org-agenda-window-setup 'other-frame))
21078 org-pre-agenda-window-conf
21079 (set-window-configuration org-pre-agenda-window-conf)))
21081 (defun org-agenda-exit ()
21082 "Exit agenda by removing the window or the buffer.
21083 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
21084 Org-mode buffers visited directly by the user will not be touched."
21085 (interactive)
21086 (org-release-buffers org-agenda-new-buffers)
21087 (setq org-agenda-new-buffers nil)
21088 (org-agenda-quit))
21090 (defun org-agenda-execute (arg)
21091 "Execute another agenda command, keeping same window.\\<global-map>
21092 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
21093 (interactive "P")
21094 (let ((org-agenda-window-setup 'current-window))
21095 (org-agenda arg)))
21097 (defun org-save-all-org-buffers ()
21098 "Save all Org-mode buffers without user confirmation."
21099 (interactive)
21100 (message "Saving all Org-mode buffers...")
21101 (save-some-buffers t 'org-mode-p)
21102 (message "Saving all Org-mode buffers... done"))
21104 (defun org-agenda-redo ()
21105 "Rebuild Agenda.
21106 When this is the global TODO list, a prefix argument will be interpreted."
21107 (interactive)
21108 (let* ((org-agenda-keep-modes t)
21109 (line (org-current-line))
21110 (window-line (- line (org-current-line (window-start))))
21111 (lprops (get 'org-agenda-redo-command 'org-lprops)))
21112 (message "Rebuilding agenda buffer...")
21113 (org-let lprops '(eval org-agenda-redo-command))
21114 (setq org-agenda-undo-list nil
21115 org-agenda-pending-undo-list nil)
21116 (message "Rebuilding agenda buffer...done")
21117 (goto-line line)
21118 (recenter window-line)))
21120 (defun org-agenda-goto-date (date)
21121 "Jump to DATE in agenda."
21122 (interactive (list (org-read-date)))
21123 (org-agenda-list nil date))
21125 (defun org-agenda-goto-today ()
21126 "Go to today."
21127 (interactive)
21128 (org-agenda-check-type t 'timeline 'agenda)
21129 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
21130 (cond
21131 (tdpos (goto-char tdpos))
21132 ((eq org-agenda-type 'agenda)
21133 (let* ((sd (time-to-days
21134 (time-subtract (current-time)
21135 (list 0 (* 3600 org-extend-today-until) 0))))
21136 (comp (org-agenda-compute-time-span sd org-agenda-span))
21137 (org-agenda-overriding-arguments org-agenda-last-arguments))
21138 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
21139 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
21140 (org-agenda-redo)
21141 (org-agenda-find-same-or-today-or-agenda)))
21142 (t (error "Cannot find today")))))
21144 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
21145 (goto-char
21146 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
21147 (text-property-any (point-min) (point-max) 'org-today t)
21148 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
21149 (point-min))))
21151 (defun org-agenda-later (arg)
21152 "Go forward in time by thee current span.
21153 With prefix ARG, go forward that many times the current span."
21154 (interactive "p")
21155 (org-agenda-check-type t 'agenda)
21156 (let* ((span org-agenda-span)
21157 (sd org-starting-day)
21158 (greg (calendar-gregorian-from-absolute sd))
21159 (cnt (get-text-property (point) 'org-day-cnt))
21160 greg2 nd)
21161 (cond
21162 ((eq span 'day)
21163 (setq sd (+ arg sd) nd 1))
21164 ((eq span 'week)
21165 (setq sd (+ (* 7 arg) sd) nd 7))
21166 ((eq span 'month)
21167 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
21168 sd (calendar-absolute-from-gregorian greg2))
21169 (setcar greg2 (1+ (car greg2)))
21170 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
21171 ((eq span 'year)
21172 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
21173 sd (calendar-absolute-from-gregorian greg2))
21174 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
21175 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
21176 (let ((org-agenda-overriding-arguments
21177 (list (car org-agenda-last-arguments) sd nd t)))
21178 (org-agenda-redo)
21179 (org-agenda-find-same-or-today-or-agenda cnt))))
21181 (defun org-agenda-earlier (arg)
21182 "Go backward in time by the current span.
21183 With prefix ARG, go backward that many times the current span."
21184 (interactive "p")
21185 (org-agenda-later (- arg)))
21187 (defun org-agenda-day-view ()
21188 "Switch to daily view for agenda."
21189 (interactive)
21190 (setq org-agenda-ndays 1)
21191 (org-agenda-change-time-span 'day))
21192 (defun org-agenda-week-view ()
21193 "Switch to daily view for agenda."
21194 (interactive)
21195 (setq org-agenda-ndays 7)
21196 (org-agenda-change-time-span 'week))
21197 (defun org-agenda-month-view ()
21198 "Switch to daily view for agenda."
21199 (interactive)
21200 (org-agenda-change-time-span 'month))
21201 (defun org-agenda-year-view ()
21202 "Switch to daily view for agenda."
21203 (interactive)
21204 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
21205 (org-agenda-change-time-span 'year)
21206 (error "Abort")))
21208 (defun org-agenda-change-time-span (span)
21209 "Change the agenda view to SPAN.
21210 SPAN may be `day', `week', `month', `year'."
21211 (org-agenda-check-type t 'agenda)
21212 (if (equal org-agenda-span span)
21213 (error "Viewing span is already \"%s\"" span))
21214 (let* ((sd (or (get-text-property (point) 'day)
21215 org-starting-day))
21216 (computed (org-agenda-compute-time-span sd span))
21217 (org-agenda-overriding-arguments
21218 (list (car org-agenda-last-arguments)
21219 (car computed) (cdr computed) t)))
21220 (org-agenda-redo)
21221 (org-agenda-find-same-or-today-or-agenda))
21222 (org-agenda-set-mode-name)
21223 (message "Switched to %s view" span))
21225 (defun org-agenda-compute-time-span (sd span)
21226 "Compute starting date and number of days for agenda.
21227 SPAN may be `day', `week', `month', `year'. The return value
21228 is a cons cell with the starting date and the number of days,
21229 so that the date SD will be in that range."
21230 (let* ((greg (calendar-gregorian-from-absolute sd))
21232 (cond
21233 ((eq span 'day)
21234 (setq nd 1))
21235 ((eq span 'week)
21236 (let* ((nt (calendar-day-of-week
21237 (calendar-gregorian-from-absolute sd)))
21238 (d (if org-agenda-start-on-weekday
21239 (- nt org-agenda-start-on-weekday)
21240 0)))
21241 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
21242 (setq nd 7)))
21243 ((eq span 'month)
21244 (setq sd (calendar-absolute-from-gregorian
21245 (list (car greg) 1 (nth 2 greg)))
21246 nd (- (calendar-absolute-from-gregorian
21247 (list (1+ (car greg)) 1 (nth 2 greg)))
21248 sd)))
21249 ((eq span 'year)
21250 (setq sd (calendar-absolute-from-gregorian
21251 (list 1 1 (nth 2 greg)))
21252 nd (- (calendar-absolute-from-gregorian
21253 (list 1 1 (1+ (nth 2 greg))))
21254 sd))))
21255 (cons sd nd)))
21257 ;; FIXME: does not work if user makes date format that starts with a blank
21258 (defun org-agenda-next-date-line (&optional arg)
21259 "Jump to the next line indicating a date in agenda buffer."
21260 (interactive "p")
21261 (org-agenda-check-type t 'agenda 'timeline)
21262 (beginning-of-line 1)
21263 (if (looking-at "^\\S-") (forward-char 1))
21264 (if (not (re-search-forward "^\\S-" nil t arg))
21265 (progn
21266 (backward-char 1)
21267 (error "No next date after this line in this buffer")))
21268 (goto-char (match-beginning 0)))
21270 (defun org-agenda-previous-date-line (&optional arg)
21271 "Jump to the previous line indicating a date in agenda buffer."
21272 (interactive "p")
21273 (org-agenda-check-type t 'agenda 'timeline)
21274 (beginning-of-line 1)
21275 (if (not (re-search-backward "^\\S-" nil t arg))
21276 (error "No previous date before this line in this buffer")))
21278 ;; Initialize the highlight
21279 (defvar org-hl (org-make-overlay 1 1))
21280 (org-overlay-put org-hl 'face 'highlight)
21282 (defun org-highlight (begin end &optional buffer)
21283 "Highlight a region with overlay."
21284 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
21285 org-hl begin end (or buffer (current-buffer))))
21287 (defun org-unhighlight ()
21288 "Detach overlay INDEX."
21289 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
21291 ;; FIXME this is currently not used.
21292 (defun org-highlight-until-next-command (beg end &optional buffer)
21293 (org-highlight beg end buffer)
21294 (add-hook 'pre-command-hook 'org-unhighlight-once))
21295 (defun org-unhighlight-once ()
21296 (remove-hook 'pre-command-hook 'org-unhighlight-once)
21297 (org-unhighlight))
21299 (defun org-agenda-follow-mode ()
21300 "Toggle follow mode in an agenda buffer."
21301 (interactive)
21302 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
21303 (org-agenda-set-mode-name)
21304 (message "Follow mode is %s"
21305 (if org-agenda-follow-mode "on" "off")))
21307 (defun org-agenda-log-mode ()
21308 "Toggle log mode in an agenda buffer."
21309 (interactive)
21310 (org-agenda-check-type t 'agenda 'timeline)
21311 (setq org-agenda-show-log (not org-agenda-show-log))
21312 (org-agenda-set-mode-name)
21313 (org-agenda-redo)
21314 (message "Log mode is %s"
21315 (if org-agenda-show-log "on" "off")))
21317 (defun org-agenda-toggle-diary ()
21318 "Toggle diary inclusion in an agenda buffer."
21319 (interactive)
21320 (org-agenda-check-type t 'agenda)
21321 (setq org-agenda-include-diary (not org-agenda-include-diary))
21322 (org-agenda-redo)
21323 (org-agenda-set-mode-name)
21324 (message "Diary inclusion turned %s"
21325 (if org-agenda-include-diary "on" "off")))
21327 (defun org-agenda-toggle-time-grid ()
21328 "Toggle time grid in an agenda buffer."
21329 (interactive)
21330 (org-agenda-check-type t 'agenda)
21331 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
21332 (org-agenda-redo)
21333 (org-agenda-set-mode-name)
21334 (message "Time-grid turned %s"
21335 (if org-agenda-use-time-grid "on" "off")))
21337 (defun org-agenda-set-mode-name ()
21338 "Set the mode name to indicate all the small mode settings."
21339 (setq mode-name
21340 (concat "Org-Agenda"
21341 (if (equal org-agenda-ndays 1) " Day" "")
21342 (if (equal org-agenda-ndays 7) " Week" "")
21343 (if org-agenda-follow-mode " Follow" "")
21344 (if org-agenda-include-diary " Diary" "")
21345 (if org-agenda-use-time-grid " Grid" "")
21346 (if org-agenda-show-log " Log" "")))
21347 (force-mode-line-update))
21349 (defun org-agenda-post-command-hook ()
21350 (and (eolp) (not (bolp)) (backward-char 1))
21351 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
21352 (if (and org-agenda-follow-mode
21353 (get-text-property (point) 'org-marker))
21354 (org-agenda-show)))
21356 (defun org-agenda-show-priority ()
21357 "Show the priority of the current item.
21358 This priority is composed of the main priority given with the [#A] cookies,
21359 and by additional input from the age of a schedules or deadline entry."
21360 (interactive)
21361 (let* ((pri (get-text-property (point-at-bol) 'priority)))
21362 (message "Priority is %d" (if pri pri -1000))))
21364 (defun org-agenda-show-tags ()
21365 "Show the tags applicable to the current item."
21366 (interactive)
21367 (let* ((tags (get-text-property (point-at-bol) 'tags)))
21368 (if tags
21369 (message "Tags are :%s:"
21370 (org-no-properties (mapconcat 'identity tags ":")))
21371 (message "No tags associated with this line"))))
21373 (defun org-agenda-goto (&optional highlight)
21374 "Go to the Org-mode file which contains the item at point."
21375 (interactive)
21376 (let* ((marker (or (get-text-property (point) 'org-marker)
21377 (org-agenda-error)))
21378 (buffer (marker-buffer marker))
21379 (pos (marker-position marker)))
21380 (switch-to-buffer-other-window buffer)
21381 (widen)
21382 (goto-char pos)
21383 (when (org-mode-p)
21384 (org-show-context 'agenda)
21385 (save-excursion
21386 (and (outline-next-heading)
21387 (org-flag-heading nil)))) ; show the next heading
21388 (run-hooks 'org-agenda-after-show-hook)
21389 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
21391 (defvar org-agenda-after-show-hook nil
21392 "Normal hook run after an item has been shown from the agenda.
21393 Point is in the buffer where the item originated.")
21395 (defun org-agenda-kill ()
21396 "Kill the entry or subtree belonging to the current agenda entry."
21397 (interactive)
21398 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
21399 (let* ((marker (or (get-text-property (point) 'org-marker)
21400 (org-agenda-error)))
21401 (buffer (marker-buffer marker))
21402 (pos (marker-position marker))
21403 (type (get-text-property (point) 'type))
21404 dbeg dend (n 0) conf)
21405 (org-with-remote-undo buffer
21406 (with-current-buffer buffer
21407 (save-excursion
21408 (goto-char pos)
21409 (if (and (org-mode-p) (not (member type '("sexp"))))
21410 (setq dbeg (progn (org-back-to-heading t) (point))
21411 dend (org-end-of-subtree t t))
21412 (setq dbeg (point-at-bol)
21413 dend (min (point-max) (1+ (point-at-eol)))))
21414 (goto-char dbeg)
21415 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
21416 (setq conf (or (eq t org-agenda-confirm-kill)
21417 (and (numberp org-agenda-confirm-kill)
21418 (> n org-agenda-confirm-kill))))
21419 (and conf
21420 (not (y-or-n-p
21421 (format "Delete entry with %d lines in buffer \"%s\"? "
21422 n (buffer-name buffer))))
21423 (error "Abort"))
21424 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
21425 (with-current-buffer buffer (delete-region dbeg dend))
21426 (message "Agenda item and source killed"))))
21428 (defun org-agenda-archive ()
21429 "Kill the entry or subtree belonging to the current agenda entry."
21430 (interactive)
21431 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
21432 (let* ((marker (or (get-text-property (point) 'org-marker)
21433 (org-agenda-error)))
21434 (buffer (marker-buffer marker))
21435 (pos (marker-position marker)))
21436 (org-with-remote-undo buffer
21437 (with-current-buffer buffer
21438 (if (org-mode-p)
21439 (save-excursion
21440 (goto-char pos)
21441 (org-remove-subtree-entries-from-agenda)
21442 (org-back-to-heading t)
21443 (org-archive-subtree))
21444 (error "Archiving works only in Org-mode files"))))))
21446 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
21447 "Remove all lines in the agenda that correspond to a given subtree.
21448 The subtree is the one in buffer BUF, starting at BEG and ending at END.
21449 If this information is not given, the function uses the tree at point."
21450 (let ((buf (or buf (current-buffer))) m p)
21451 (save-excursion
21452 (unless (and beg end)
21453 (org-back-to-heading t)
21454 (setq beg (point))
21455 (org-end-of-subtree t)
21456 (setq end (point)))
21457 (set-buffer (get-buffer org-agenda-buffer-name))
21458 (save-excursion
21459 (goto-char (point-max))
21460 (beginning-of-line 1)
21461 (while (not (bobp))
21462 (when (and (setq m (get-text-property (point) 'org-marker))
21463 (equal buf (marker-buffer m))
21464 (setq p (marker-position m))
21465 (>= p beg)
21466 (<= p end))
21467 (let ((inhibit-read-only t))
21468 (delete-region (point-at-bol) (1+ (point-at-eol)))))
21469 (beginning-of-line 0))))))
21471 (defun org-agenda-open-link ()
21472 "Follow the link in the current line, if any."
21473 (interactive)
21474 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
21475 (save-excursion
21476 (save-restriction
21477 (narrow-to-region (point-at-bol) (point-at-eol))
21478 (org-open-at-point))))
21480 (defun org-agenda-copy-local-variable (var)
21481 "Get a variable from a referenced buffer and install it here."
21482 (let ((m (get-text-property (point) 'org-marker)))
21483 (when (and m (buffer-live-p (marker-buffer m)))
21484 (org-set-local var (with-current-buffer (marker-buffer m)
21485 (symbol-value var))))))
21487 (defun org-agenda-switch-to (&optional delete-other-windows)
21488 "Go to the Org-mode file which contains the item at point."
21489 (interactive)
21490 (let* ((marker (or (get-text-property (point) 'org-marker)
21491 (org-agenda-error)))
21492 (buffer (marker-buffer marker))
21493 (pos (marker-position marker)))
21494 (switch-to-buffer buffer)
21495 (and delete-other-windows (delete-other-windows))
21496 (widen)
21497 (goto-char pos)
21498 (when (org-mode-p)
21499 (org-show-context 'agenda)
21500 (save-excursion
21501 (and (outline-next-heading)
21502 (org-flag-heading nil)))))) ; show the next heading
21504 (defun org-agenda-goto-mouse (ev)
21505 "Go to the Org-mode file which contains the item at the mouse click."
21506 (interactive "e")
21507 (mouse-set-point ev)
21508 (org-agenda-goto))
21510 (defun org-agenda-show ()
21511 "Display the Org-mode file which contains the item at point."
21512 (interactive)
21513 (let ((win (selected-window)))
21514 (org-agenda-goto t)
21515 (select-window win)))
21517 (defun org-agenda-recenter (arg)
21518 "Display the Org-mode file which contains the item at point and recenter."
21519 (interactive "P")
21520 (let ((win (selected-window)))
21521 (org-agenda-goto t)
21522 (recenter arg)
21523 (select-window win)))
21525 (defun org-agenda-show-mouse (ev)
21526 "Display the Org-mode file which contains the item at the mouse click."
21527 (interactive "e")
21528 (mouse-set-point ev)
21529 (org-agenda-show))
21531 (defun org-agenda-check-no-diary ()
21532 "Check if the entry is a diary link and abort if yes."
21533 (if (get-text-property (point) 'org-agenda-diary-link)
21534 (org-agenda-error)))
21536 (defun org-agenda-error ()
21537 (error "Command not allowed in this line"))
21539 (defun org-agenda-tree-to-indirect-buffer ()
21540 "Show the subtree corresponding to the current entry in an indirect buffer.
21541 This calls the command `org-tree-to-indirect-buffer' from the original
21542 Org-mode buffer.
21543 With numerical prefix arg ARG, go up to this level and then take that tree.
21544 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
21545 dedicated frame)."
21546 (interactive)
21547 (org-agenda-check-no-diary)
21548 (let* ((marker (or (get-text-property (point) 'org-marker)
21549 (org-agenda-error)))
21550 (buffer (marker-buffer marker))
21551 (pos (marker-position marker)))
21552 (with-current-buffer buffer
21553 (save-excursion
21554 (goto-char pos)
21555 (call-interactively 'org-tree-to-indirect-buffer)))))
21557 (defvar org-last-heading-marker (make-marker)
21558 "Marker pointing to the headline that last changed its TODO state
21559 by a remote command from the agenda.")
21561 (defun org-agenda-todo-nextset ()
21562 "Switch TODO entry to next sequence."
21563 (interactive)
21564 (org-agenda-todo 'nextset))
21566 (defun org-agenda-todo-previousset ()
21567 "Switch TODO entry to previous sequence."
21568 (interactive)
21569 (org-agenda-todo 'previousset))
21571 (defun org-agenda-todo (&optional arg)
21572 "Cycle TODO state of line at point, also in Org-mode file.
21573 This changes the line at point, all other lines in the agenda referring to
21574 the same tree node, and the headline of the tree node in the Org-mode file."
21575 (interactive "P")
21576 (org-agenda-check-no-diary)
21577 (let* ((col (current-column))
21578 (marker (or (get-text-property (point) 'org-marker)
21579 (org-agenda-error)))
21580 (buffer (marker-buffer marker))
21581 (pos (marker-position marker))
21582 (hdmarker (get-text-property (point) 'org-hd-marker))
21583 (inhibit-read-only t)
21584 newhead)
21585 (org-with-remote-undo buffer
21586 (with-current-buffer buffer
21587 (widen)
21588 (goto-char pos)
21589 (org-show-context 'agenda)
21590 (save-excursion
21591 (and (outline-next-heading)
21592 (org-flag-heading nil))) ; show the next heading
21593 (org-todo arg)
21594 (and (bolp) (forward-char 1))
21595 (setq newhead (org-get-heading))
21596 (save-excursion
21597 (org-back-to-heading)
21598 (move-marker org-last-heading-marker (point))))
21599 (beginning-of-line 1)
21600 (save-excursion
21601 (org-agenda-change-all-lines newhead hdmarker 'fixface))
21602 (move-to-column col))))
21604 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
21605 "Change all lines in the agenda buffer which match HDMARKER.
21606 The new content of the line will be NEWHEAD (as modified by
21607 `org-format-agenda-item'). HDMARKER is checked with
21608 `equal' against all `org-hd-marker' text properties in the file.
21609 If FIXFACE is non-nil, the face of each item is modified acording to
21610 the new TODO state."
21611 (let* ((inhibit-read-only t)
21612 props m pl undone-face done-face finish new dotime cat tags)
21613 (save-excursion
21614 (goto-char (point-max))
21615 (beginning-of-line 1)
21616 (while (not finish)
21617 (setq finish (bobp))
21618 (when (and (setq m (get-text-property (point) 'org-hd-marker))
21619 (equal m hdmarker))
21620 (setq props (text-properties-at (point))
21621 dotime (get-text-property (point) 'dotime)
21622 cat (get-text-property (point) 'org-category)
21623 tags (get-text-property (point) 'tags)
21624 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
21625 pl (get-text-property (point) 'prefix-length)
21626 undone-face (get-text-property (point) 'undone-face)
21627 done-face (get-text-property (point) 'done-face))
21628 (move-to-column pl)
21629 (cond
21630 ((equal new "")
21631 (beginning-of-line 1)
21632 (and (looking-at ".*\n?") (replace-match "")))
21633 ((looking-at ".*")
21634 (replace-match new t t)
21635 (beginning-of-line 1)
21636 (add-text-properties (point-at-bol) (point-at-eol) props)
21637 (when fixface
21638 (add-text-properties
21639 (point-at-bol) (point-at-eol)
21640 (list 'face
21641 (if org-last-todo-state-is-todo
21642 undone-face done-face))))
21643 (org-agenda-highlight-todo 'line)
21644 (beginning-of-line 1))
21645 (t (error "Line update did not work"))))
21646 (beginning-of-line 0)))
21647 (org-finalize-agenda)))
21649 (defun org-agenda-align-tags (&optional line)
21650 "Align all tags in agenda items to `org-agenda-tags-column'."
21651 (let ((inhibit-read-only t) l c)
21652 (save-excursion
21653 (goto-char (if line (point-at-bol) (point-min)))
21654 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21655 (if line (point-at-eol) nil) t)
21656 (add-text-properties
21657 (match-beginning 2) (match-end 2)
21658 (list 'face (list 'org-tag (get-text-property
21659 (match-beginning 2) 'face))))
21660 (setq l (- (match-end 2) (match-beginning 2))
21661 c (if (< org-agenda-tags-column 0)
21662 (- (abs org-agenda-tags-column) l)
21663 org-agenda-tags-column))
21664 (delete-region (match-beginning 1) (match-end 1))
21665 (goto-char (match-beginning 1))
21666 (insert (org-add-props
21667 (make-string (max 1 (- c (current-column))) ?\ )
21668 (text-properties-at (point))))))))
21670 (defun org-agenda-priority-up ()
21671 "Increase the priority of line at point, also in Org-mode file."
21672 (interactive)
21673 (org-agenda-priority 'up))
21675 (defun org-agenda-priority-down ()
21676 "Decrease the priority of line at point, also in Org-mode file."
21677 (interactive)
21678 (org-agenda-priority 'down))
21680 (defun org-agenda-priority (&optional force-direction)
21681 "Set the priority of line at point, also in Org-mode file.
21682 This changes the line at point, all other lines in the agenda referring to
21683 the same tree node, and the headline of the tree node in the Org-mode file."
21684 (interactive)
21685 (org-agenda-check-no-diary)
21686 (let* ((marker (or (get-text-property (point) 'org-marker)
21687 (org-agenda-error)))
21688 (hdmarker (get-text-property (point) 'org-hd-marker))
21689 (buffer (marker-buffer hdmarker))
21690 (pos (marker-position hdmarker))
21691 (inhibit-read-only t)
21692 newhead)
21693 (org-with-remote-undo buffer
21694 (with-current-buffer buffer
21695 (widen)
21696 (goto-char pos)
21697 (org-show-context 'agenda)
21698 (save-excursion
21699 (and (outline-next-heading)
21700 (org-flag-heading nil))) ; show the next heading
21701 (funcall 'org-priority force-direction)
21702 (end-of-line 1)
21703 (setq newhead (org-get-heading)))
21704 (org-agenda-change-all-lines newhead hdmarker)
21705 (beginning-of-line 1))))
21707 (defun org-get-tags-at (&optional pos)
21708 "Get a list of all headline tags applicable at POS.
21709 POS defaults to point. If tags are inherited, the list contains
21710 the targets in the same sequence as the headlines appear, i.e.
21711 the tags of the current headline come last."
21712 (interactive)
21713 (let (tags lastpos)
21714 (save-excursion
21715 (save-restriction
21716 (widen)
21717 (goto-char (or pos (point)))
21718 (save-match-data
21719 (org-back-to-heading t)
21720 (condition-case nil
21721 (while (not (equal lastpos (point)))
21722 (setq lastpos (point))
21723 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
21724 (setq tags (append (org-split-string
21725 (org-match-string-no-properties 1) ":")
21726 tags)))
21727 (or org-use-tag-inheritance (error ""))
21728 (org-up-heading-all 1))
21729 (error nil))))
21730 tags)))
21732 ;; FIXME: should fix the tags property of the agenda line.
21733 (defun org-agenda-set-tags ()
21734 "Set tags for the current headline."
21735 (interactive)
21736 (org-agenda-check-no-diary)
21737 (if (and (org-region-active-p) (interactive-p))
21738 (call-interactively 'org-change-tag-in-region)
21739 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
21740 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
21741 (org-agenda-error)))
21742 (buffer (marker-buffer hdmarker))
21743 (pos (marker-position hdmarker))
21744 (inhibit-read-only t)
21745 newhead)
21746 (org-with-remote-undo buffer
21747 (with-current-buffer buffer
21748 (widen)
21749 (goto-char pos)
21750 (save-excursion
21751 (org-show-context 'agenda))
21752 (save-excursion
21753 (and (outline-next-heading)
21754 (org-flag-heading nil))) ; show the next heading
21755 (goto-char pos)
21756 (call-interactively 'org-set-tags)
21757 (end-of-line 1)
21758 (setq newhead (org-get-heading)))
21759 (org-agenda-change-all-lines newhead hdmarker)
21760 (beginning-of-line 1)))))
21762 (defun org-agenda-toggle-archive-tag ()
21763 "Toggle the archive tag for the current entry."
21764 (interactive)
21765 (org-agenda-check-no-diary)
21766 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
21767 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
21768 (org-agenda-error)))
21769 (buffer (marker-buffer hdmarker))
21770 (pos (marker-position hdmarker))
21771 (inhibit-read-only t)
21772 newhead)
21773 (org-with-remote-undo buffer
21774 (with-current-buffer buffer
21775 (widen)
21776 (goto-char pos)
21777 (org-show-context 'agenda)
21778 (save-excursion
21779 (and (outline-next-heading)
21780 (org-flag-heading nil))) ; show the next heading
21781 (call-interactively 'org-toggle-archive-tag)
21782 (end-of-line 1)
21783 (setq newhead (org-get-heading)))
21784 (org-agenda-change-all-lines newhead hdmarker)
21785 (beginning-of-line 1))))
21787 (defun org-agenda-date-later (arg &optional what)
21788 "Change the date of this item to one day later."
21789 (interactive "p")
21790 (org-agenda-check-type t 'agenda 'timeline)
21791 (org-agenda-check-no-diary)
21792 (let* ((marker (or (get-text-property (point) 'org-marker)
21793 (org-agenda-error)))
21794 (buffer (marker-buffer marker))
21795 (pos (marker-position marker)))
21796 (org-with-remote-undo buffer
21797 (with-current-buffer buffer
21798 (widen)
21799 (goto-char pos)
21800 (if (not (org-at-timestamp-p))
21801 (error "Cannot find time stamp"))
21802 (org-timestamp-change arg (or what 'day)))
21803 (org-agenda-show-new-time marker org-last-changed-timestamp))
21804 (message "Time stamp changed to %s" org-last-changed-timestamp)))
21806 (defun org-agenda-date-earlier (arg &optional what)
21807 "Change the date of this item to one day earlier."
21808 (interactive "p")
21809 (org-agenda-date-later (- arg) what))
21811 (defun org-agenda-show-new-time (marker stamp &optional prefix)
21812 "Show new date stamp via text properties."
21813 ;; We use text properties to make this undoable
21814 (let ((inhibit-read-only t))
21815 (setq stamp (concat " " prefix " => " stamp))
21816 (save-excursion
21817 (goto-char (point-max))
21818 (while (not (bobp))
21819 (when (equal marker (get-text-property (point) 'org-marker))
21820 (move-to-column (- (window-width) (length stamp)) t)
21821 (if (featurep 'xemacs)
21822 ;; Use `duplicable' property to trigger undo recording
21823 (let ((ex (make-extent nil nil))
21824 (gl (make-glyph stamp)))
21825 (set-glyph-face gl 'secondary-selection)
21826 (set-extent-properties
21827 ex (list 'invisible t 'end-glyph gl 'duplicable t))
21828 (insert-extent ex (1- (point)) (point-at-eol)))
21829 (add-text-properties
21830 (1- (point)) (point-at-eol)
21831 (list 'display (org-add-props stamp nil
21832 'face 'secondary-selection))))
21833 (beginning-of-line 1))
21834 (beginning-of-line 0)))))
21836 (defun org-agenda-date-prompt (arg)
21837 "Change the date of this item. Date is prompted for, with default today.
21838 The prefix ARG is passed to the `org-time-stamp' command and can therefore
21839 be used to request time specification in the time stamp."
21840 (interactive "P")
21841 (org-agenda-check-type t 'agenda 'timeline)
21842 (org-agenda-check-no-diary)
21843 (let* ((marker (or (get-text-property (point) 'org-marker)
21844 (org-agenda-error)))
21845 (buffer (marker-buffer marker))
21846 (pos (marker-position marker)))
21847 (org-with-remote-undo buffer
21848 (with-current-buffer buffer
21849 (widen)
21850 (goto-char pos)
21851 (if (not (org-at-timestamp-p))
21852 (error "Cannot find time stamp"))
21853 (org-time-stamp arg)
21854 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
21856 (defun org-agenda-schedule (arg)
21857 "Schedule the item at point."
21858 (interactive "P")
21859 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
21860 (org-agenda-check-no-diary)
21861 (let* ((marker (or (get-text-property (point) 'org-marker)
21862 (org-agenda-error)))
21863 (buffer (marker-buffer marker))
21864 (pos (marker-position marker))
21865 (org-insert-labeled-timestamps-at-point nil)
21867 (org-with-remote-undo buffer
21868 (with-current-buffer buffer
21869 (widen)
21870 (goto-char pos)
21871 (setq ts (org-schedule arg)))
21872 (org-agenda-show-new-time marker ts "S"))
21873 (message "Item scheduled for %s" ts)))
21875 (defun org-agenda-deadline (arg)
21876 "Schedule the item at point."
21877 (interactive "P")
21878 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
21879 (org-agenda-check-no-diary)
21880 (let* ((marker (or (get-text-property (point) 'org-marker)
21881 (org-agenda-error)))
21882 (buffer (marker-buffer marker))
21883 (pos (marker-position marker))
21884 (org-insert-labeled-timestamps-at-point nil)
21886 (org-with-remote-undo buffer
21887 (with-current-buffer buffer
21888 (widen)
21889 (goto-char pos)
21890 (setq ts (org-deadline arg)))
21891 (org-agenda-show-new-time marker ts "S"))
21892 (message "Deadline for this item set to %s" ts)))
21894 (defun org-get-heading (&optional no-tags)
21895 "Return the heading of the current entry, without the stars."
21896 (save-excursion
21897 (org-back-to-heading t)
21898 (if (looking-at
21899 (if no-tags
21900 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
21901 "\\*+[ \t]+\\([^\r\n]*\\)"))
21902 (match-string 1) "")))
21904 (defun org-agenda-clock-in (&optional arg)
21905 "Start the clock on the currently selected item."
21906 (interactive "P")
21907 (org-agenda-check-no-diary)
21908 (let* ((marker (or (get-text-property (point) 'org-marker)
21909 (org-agenda-error)))
21910 (pos (marker-position marker)))
21911 (org-with-remote-undo (marker-buffer marker)
21912 (with-current-buffer (marker-buffer marker)
21913 (widen)
21914 (goto-char pos)
21915 (org-clock-in)))))
21917 (defun org-agenda-clock-out (&optional arg)
21918 "Stop the currently running clock."
21919 (interactive "P")
21920 (unless (marker-buffer org-clock-marker)
21921 (error "No running clock"))
21922 (org-with-remote-undo (marker-buffer org-clock-marker)
21923 (org-clock-out)))
21925 (defun org-agenda-clock-cancel (&optional arg)
21926 "Cancel the currently running clock."
21927 (interactive "P")
21928 (unless (marker-buffer org-clock-marker)
21929 (error "No running clock"))
21930 (org-with-remote-undo (marker-buffer org-clock-marker)
21931 (org-clock-cancel)))
21933 (defun org-agenda-diary-entry ()
21934 "Make a diary entry, like the `i' command from the calendar.
21935 All the standard commands work: block, weekly etc."
21936 (interactive)
21937 (org-agenda-check-type t 'agenda 'timeline)
21938 (require 'diary-lib)
21939 (let* ((char (progn
21940 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
21941 (read-char-exclusive)))
21942 (cmd (cdr (assoc char
21943 '((?d . insert-diary-entry)
21944 (?w . insert-weekly-diary-entry)
21945 (?m . insert-monthly-diary-entry)
21946 (?y . insert-yearly-diary-entry)
21947 (?a . insert-anniversary-diary-entry)
21948 (?b . insert-block-diary-entry)
21949 (?c . insert-cyclic-diary-entry)))))
21950 (oldf (symbol-function 'calendar-cursor-to-date))
21951 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
21952 (point (point))
21953 (mark (or (mark t) (point))))
21954 (unless cmd
21955 (error "No command associated with <%c>" char))
21956 (unless (and (get-text-property point 'day)
21957 (or (not (equal ?b char))
21958 (get-text-property mark 'day)))
21959 (error "Don't know which date to use for diary entry"))
21960 ;; We implement this by hacking the `calendar-cursor-to-date' function
21961 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
21962 (let ((calendar-mark-ring
21963 (list (calendar-gregorian-from-absolute
21964 (or (get-text-property mark 'day)
21965 (get-text-property point 'day))))))
21966 (unwind-protect
21967 (progn
21968 (fset 'calendar-cursor-to-date
21969 (lambda (&optional error)
21970 (calendar-gregorian-from-absolute
21971 (get-text-property point 'day))))
21972 (call-interactively cmd))
21973 (fset 'calendar-cursor-to-date oldf)))))
21976 (defun org-agenda-execute-calendar-command (cmd)
21977 "Execute a calendar command from the agenda, with the date associated to
21978 the cursor position."
21979 (org-agenda-check-type t 'agenda 'timeline)
21980 (require 'diary-lib)
21981 (unless (get-text-property (point) 'day)
21982 (error "Don't know which date to use for calendar command"))
21983 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
21984 (point (point))
21985 (date (calendar-gregorian-from-absolute
21986 (get-text-property point 'day)))
21987 ;; the following 3 vars are needed in the calendar
21988 (displayed-day (extract-calendar-day date))
21989 (displayed-month (extract-calendar-month date))
21990 (displayed-year (extract-calendar-year date)))
21991 (unwind-protect
21992 (progn
21993 (fset 'calendar-cursor-to-date
21994 (lambda (&optional error)
21995 (calendar-gregorian-from-absolute
21996 (get-text-property point 'day))))
21997 (call-interactively cmd))
21998 (fset 'calendar-cursor-to-date oldf))))
22000 (defun org-agenda-phases-of-moon ()
22001 "Display the phases of the moon for the 3 months around the cursor date."
22002 (interactive)
22003 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22005 (defun org-agenda-holidays ()
22006 "Display the holidays for the 3 months around the cursor date."
22007 (interactive)
22008 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22010 (defun org-agenda-sunrise-sunset (arg)
22011 "Display sunrise and sunset for the cursor date.
22012 Latitude and longitude can be specified with the variables
22013 `calendar-latitude' and `calendar-longitude'. When called with prefix
22014 argument, latitude and longitude will be prompted for."
22015 (interactive "P")
22016 (let ((calendar-longitude (if arg nil calendar-longitude))
22017 (calendar-latitude (if arg nil calendar-latitude))
22018 (calendar-location-name
22019 (if arg "the given coordinates" calendar-location-name)))
22020 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22022 (defun org-agenda-goto-calendar ()
22023 "Open the Emacs calendar with the date at the cursor."
22024 (interactive)
22025 (org-agenda-check-type t 'agenda 'timeline)
22026 (let* ((day (or (get-text-property (point) 'day)
22027 (error "Don't know which date to open in calendar")))
22028 (date (calendar-gregorian-from-absolute day))
22029 (calendar-move-hook nil)
22030 (view-calendar-holidays-initially nil)
22031 (view-diary-entries-initially nil))
22032 (calendar)
22033 (calendar-goto-date date)))
22035 (defun org-calendar-goto-agenda ()
22036 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
22037 This is a command that has to be installed in `calendar-mode-map'."
22038 (interactive)
22039 (org-agenda-list nil (calendar-absolute-from-gregorian
22040 (calendar-cursor-to-date))
22041 nil))
22043 (defun org-agenda-convert-date ()
22044 (interactive)
22045 (org-agenda-check-type t 'agenda 'timeline)
22046 (let ((day (get-text-property (point) 'day))
22047 date s)
22048 (unless day
22049 (error "Don't know which date to convert"))
22050 (setq date (calendar-gregorian-from-absolute day))
22051 (setq s (concat
22052 "Gregorian: " (calendar-date-string date) "\n"
22053 "ISO: " (calendar-iso-date-string date) "\n"
22054 "Day of Yr: " (calendar-day-of-year-string date) "\n"
22055 "Julian: " (calendar-julian-date-string date) "\n"
22056 "Astron. JD: " (calendar-astro-date-string date)
22057 " (Julian date number at noon UTC)\n"
22058 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
22059 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
22060 "French: " (calendar-french-date-string date) "\n"
22061 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
22062 "Mayan: " (calendar-mayan-date-string date) "\n"
22063 "Coptic: " (calendar-coptic-date-string date) "\n"
22064 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
22065 "Persian: " (calendar-persian-date-string date) "\n"
22066 "Chinese: " (calendar-chinese-date-string date) "\n"))
22067 (with-output-to-temp-buffer "*Dates*"
22068 (princ s))
22069 (if (fboundp 'fit-window-to-buffer)
22070 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
22073 ;;;; Embedded LaTeX
22075 (defvar org-cdlatex-mode-map (make-sparse-keymap)
22076 "Keymap for the minor `org-cdlatex-mode'.")
22078 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
22079 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
22080 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
22081 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
22082 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
22084 (defvar org-cdlatex-texmathp-advice-is-done nil
22085 "Flag remembering if we have applied the advice to texmathp already.")
22087 (define-minor-mode org-cdlatex-mode
22088 "Toggle the minor `org-cdlatex-mode'.
22089 This mode supports entering LaTeX environment and math in LaTeX fragments
22090 in Org-mode.
22091 \\{org-cdlatex-mode-map}"
22092 nil " OCDL" nil
22093 (when org-cdlatex-mode (require 'cdlatex))
22094 (unless org-cdlatex-texmathp-advice-is-done
22095 (setq org-cdlatex-texmathp-advice-is-done t)
22096 (defadvice texmathp (around org-math-always-on activate)
22097 "Always return t in org-mode buffers.
22098 This is because we want to insert math symbols without dollars even outside
22099 the LaTeX math segments. If Orgmode thinks that point is actually inside
22100 en embedded LaTeX fragement, let texmathp do its job.
22101 \\[org-cdlatex-mode-map]"
22102 (interactive)
22103 (let (p)
22104 (cond
22105 ((not (org-mode-p)) ad-do-it)
22106 ((eq this-command 'cdlatex-math-symbol)
22107 (setq ad-return-value t
22108 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
22110 (let ((p (org-inside-LaTeX-fragment-p)))
22111 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
22112 (setq ad-return-value t
22113 texmathp-why '("Org-mode embedded math" . 0))
22114 (if p ad-do-it)))))))))
22116 (defun turn-on-org-cdlatex ()
22117 "Unconditionally turn on `org-cdlatex-mode'."
22118 (org-cdlatex-mode 1))
22120 (defun org-inside-LaTeX-fragment-p ()
22121 "Test if point is inside a LaTeX fragment.
22122 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
22123 sequence appearing also before point.
22124 Even though the matchers for math are configurable, this function assumes
22125 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
22126 delimiters are skipped when they have been removed by customization.
22127 The return value is nil, or a cons cell with the delimiter and
22128 and the position of this delimiter.
22130 This function does a reasonably good job, but can locally be fooled by
22131 for example currency specifications. For example it will assume being in
22132 inline math after \"$22.34\". The LaTeX fragment formatter will only format
22133 fragments that are properly closed, but during editing, we have to live
22134 with the uncertainty caused by missing closing delimiters. This function
22135 looks only before point, not after."
22136 (catch 'exit
22137 (let ((pos (point))
22138 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
22139 (lim (progn
22140 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
22141 (point)))
22142 dd-on str (start 0) m re)
22143 (goto-char pos)
22144 (when dodollar
22145 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
22146 re (nth 1 (assoc "$" org-latex-regexps)))
22147 (while (string-match re str start)
22148 (cond
22149 ((= (match-end 0) (length str))
22150 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
22151 ((= (match-end 0) (- (length str) 5))
22152 (throw 'exit nil))
22153 (t (setq start (match-end 0))))))
22154 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
22155 (goto-char pos)
22156 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
22157 (and (match-beginning 2) (throw 'exit nil))
22158 ;; count $$
22159 (while (re-search-backward "\\$\\$" lim t)
22160 (setq dd-on (not dd-on)))
22161 (goto-char pos)
22162 (if dd-on (cons "$$" m))))))
22165 (defun org-try-cdlatex-tab ()
22166 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
22167 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
22168 - inside a LaTeX fragment, or
22169 - after the first word in a line, where an abbreviation expansion could
22170 insert a LaTeX environment."
22171 (when org-cdlatex-mode
22172 (cond
22173 ((save-excursion
22174 (skip-chars-backward "a-zA-Z0-9*")
22175 (skip-chars-backward " \t")
22176 (bolp))
22177 (cdlatex-tab) t)
22178 ((org-inside-LaTeX-fragment-p)
22179 (cdlatex-tab) t)
22180 (t nil))))
22182 (defun org-cdlatex-underscore-caret (&optional arg)
22183 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
22184 Revert to the normal definition outside of these fragments."
22185 (interactive "P")
22186 (if (org-inside-LaTeX-fragment-p)
22187 (call-interactively 'cdlatex-sub-superscript)
22188 (let (org-cdlatex-mode)
22189 (call-interactively (key-binding (vector last-input-event))))))
22191 (defun org-cdlatex-math-modify (&optional arg)
22192 "Execute `cdlatex-math-modify' in LaTeX fragments.
22193 Revert to the normal definition outside of these fragments."
22194 (interactive "P")
22195 (if (org-inside-LaTeX-fragment-p)
22196 (call-interactively 'cdlatex-math-modify)
22197 (let (org-cdlatex-mode)
22198 (call-interactively (key-binding (vector last-input-event))))))
22200 (defvar org-latex-fragment-image-overlays nil
22201 "List of overlays carrying the images of latex fragments.")
22202 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
22204 (defun org-remove-latex-fragment-image-overlays ()
22205 "Remove all overlays with LaTeX fragment images in current buffer."
22206 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
22207 (setq org-latex-fragment-image-overlays nil))
22209 (defun org-preview-latex-fragment (&optional subtree)
22210 "Preview the LaTeX fragment at point, or all locally or globally.
22211 If the cursor is in a LaTeX fragment, create the image and overlay
22212 it over the source code. If there is no fragment at point, display
22213 all fragments in the current text, from one headline to the next. With
22214 prefix SUBTREE, display all fragments in the current subtree. With a
22215 double prefix `C-u C-u', or when the cursor is before the first headline,
22216 display all fragments in the buffer.
22217 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
22218 (interactive "P")
22219 (org-remove-latex-fragment-image-overlays)
22220 (save-excursion
22221 (save-restriction
22222 (let (beg end at msg)
22223 (cond
22224 ((or (equal subtree '(16))
22225 (not (save-excursion
22226 (re-search-backward (concat "^" outline-regexp) nil t))))
22227 (setq beg (point-min) end (point-max)
22228 msg "Creating images for buffer...%s"))
22229 ((equal subtree '(4))
22230 (org-back-to-heading)
22231 (setq beg (point) end (org-end-of-subtree t)
22232 msg "Creating images for subtree...%s"))
22234 (if (setq at (org-inside-LaTeX-fragment-p))
22235 (goto-char (max (point-min) (- (cdr at) 2)))
22236 (org-back-to-heading))
22237 (setq beg (point) end (progn (outline-next-heading) (point))
22238 msg (if at "Creating image...%s"
22239 "Creating images for entry...%s"))))
22240 (message msg "")
22241 (narrow-to-region beg end)
22242 (goto-char beg)
22243 (org-format-latex
22244 (concat "ltxpng/" (file-name-sans-extension
22245 (file-name-nondirectory
22246 buffer-file-name)))
22247 default-directory 'overlays msg at 'forbuffer)
22248 (message msg "done. Use `C-c C-c' to remove images.")))))
22250 (defvar org-latex-regexps
22251 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
22252 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
22253 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
22254 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
22255 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
22256 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
22257 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
22258 "Regular expressions for matching embedded LaTeX.")
22260 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
22261 "Replace LaTeX fragments with links to an image, and produce images."
22262 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
22263 (let* ((prefixnodir (file-name-nondirectory prefix))
22264 (absprefix (expand-file-name prefix dir))
22265 (todir (file-name-directory absprefix))
22266 (opt org-format-latex-options)
22267 (matchers (plist-get opt :matchers))
22268 (re-list org-latex-regexps)
22269 (cnt 0) txt link beg end re e checkdir
22270 m n block linkfile movefile ov)
22271 ;; Check if there are old images files with this prefix, and remove them
22272 (when (file-directory-p todir)
22273 (mapc 'delete-file
22274 (directory-files
22275 todir 'full
22276 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
22277 ;; Check the different regular expressions
22278 (while (setq e (pop re-list))
22279 (setq m (car e) re (nth 1 e) n (nth 2 e)
22280 block (if (nth 3 e) "\n\n" ""))
22281 (when (member m matchers)
22282 (goto-char (point-min))
22283 (while (re-search-forward re nil t)
22284 (when (or (not at) (equal (cdr at) (match-beginning n)))
22285 (setq txt (match-string n)
22286 beg (match-beginning n) end (match-end n)
22287 cnt (1+ cnt)
22288 linkfile (format "%s_%04d.png" prefix cnt)
22289 movefile (format "%s_%04d.png" absprefix cnt)
22290 link (concat block "[[file:" linkfile "]]" block))
22291 (if msg (message msg cnt))
22292 (goto-char beg)
22293 (unless checkdir ; make sure the directory exists
22294 (setq checkdir t)
22295 (or (file-directory-p todir) (make-directory todir)))
22296 (org-create-formula-image
22297 txt movefile opt forbuffer)
22298 (if overlays
22299 (progn
22300 (setq ov (org-make-overlay beg end))
22301 (if (featurep 'xemacs)
22302 (progn
22303 (org-overlay-put ov 'invisible t)
22304 (org-overlay-put
22305 ov 'end-glyph
22306 (make-glyph (vector 'png :file movefile))))
22307 (org-overlay-put
22308 ov 'display
22309 (list 'image :type 'png :file movefile :ascent 'center)))
22310 (push ov org-latex-fragment-image-overlays)
22311 (goto-char end))
22312 (delete-region beg end)
22313 (insert link))))))))
22315 ;; This function borrows from Ganesh Swami's latex2png.el
22316 (defun org-create-formula-image (string tofile options buffer)
22317 (let* ((tmpdir (if (featurep 'xemacs)
22318 (temp-directory)
22319 temporary-file-directory))
22320 (texfilebase (make-temp-name
22321 (expand-file-name "orgtex" tmpdir)))
22322 (texfile (concat texfilebase ".tex"))
22323 (dvifile (concat texfilebase ".dvi"))
22324 (pngfile (concat texfilebase ".png"))
22325 (fnh (face-attribute 'default :height nil))
22326 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
22327 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
22328 (fg (or (plist-get options (if buffer :foreground :html-foreground))
22329 "Black"))
22330 (bg (or (plist-get options (if buffer :background :html-background))
22331 "Transparent")))
22332 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
22333 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
22334 (with-temp-file texfile
22335 (insert org-format-latex-header
22336 "\n\\begin{document}\n" string "\n\\end{document}\n"))
22337 (let ((dir default-directory))
22338 (condition-case nil
22339 (progn
22340 (cd tmpdir)
22341 (call-process "latex" nil nil nil texfile))
22342 (error nil))
22343 (cd dir))
22344 (if (not (file-exists-p dvifile))
22345 (progn (message "Failed to create dvi file from %s" texfile) nil)
22346 (call-process "dvipng" nil nil nil
22347 "-E" "-fg" fg "-bg" bg
22348 "-D" dpi
22349 ;;"-x" scale "-y" scale
22350 "-T" "tight"
22351 "-o" pngfile
22352 dvifile)
22353 (if (not (file-exists-p pngfile))
22354 (progn (message "Failed to create png file from %s" texfile) nil)
22355 ;; Use the requested file name and clean up
22356 (copy-file pngfile tofile 'replace)
22357 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
22358 (delete-file (concat texfilebase e)))
22359 pngfile))))
22361 (defun org-dvipng-color (attr)
22362 "Return an rgb color specification for dvipng."
22363 (apply 'format "rgb %s %s %s"
22364 (mapcar 'org-normalize-color
22365 (color-values (face-attribute 'default attr nil)))))
22367 (defun org-normalize-color (value)
22368 "Return string to be used as color value for an RGB component."
22369 (format "%g" (/ value 65535.0)))
22371 ;;;; Exporting
22373 ;;; Variables, constants, and parameter plists
22375 (defconst org-level-max 20)
22377 (defvar org-export-html-preamble nil
22378 "Preamble, to be inserted just after <body>. Set by publishing functions.")
22379 (defvar org-export-html-postamble nil
22380 "Preamble, to be inserted just before </body>. Set by publishing functions.")
22381 (defvar org-export-html-auto-preamble t
22382 "Should default preamble be inserted? Set by publishing functions.")
22383 (defvar org-export-html-auto-postamble t
22384 "Should default postamble be inserted? Set by publishing functions.")
22385 (defvar org-current-export-file nil) ; dynamically scoped parameter
22386 (defvar org-current-export-dir nil) ; dynamically scoped parameter
22389 (defconst org-export-plist-vars
22390 '((:language . org-export-default-language)
22391 (:customtime . org-display-custom-times)
22392 (:headline-levels . org-export-headline-levels)
22393 (:section-numbers . org-export-with-section-numbers)
22394 (:table-of-contents . org-export-with-toc)
22395 (:preserve-breaks . org-export-preserve-breaks)
22396 (:archived-trees . org-export-with-archived-trees)
22397 (:emphasize . org-export-with-emphasize)
22398 (:sub-superscript . org-export-with-sub-superscripts)
22399 (:special-strings . org-export-with-special-strings)
22400 (:footnotes . org-export-with-footnotes)
22401 (:drawers . org-export-with-drawers)
22402 (:tags . org-export-with-tags)
22403 (:TeX-macros . org-export-with-TeX-macros)
22404 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
22405 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
22406 (:fixed-width . org-export-with-fixed-width)
22407 (:timestamps . org-export-with-timestamps)
22408 (:author-info . org-export-author-info)
22409 (:time-stamp-file . org-export-time-stamp-file)
22410 (:tables . org-export-with-tables)
22411 (:table-auto-headline . org-export-highlight-first-table-line)
22412 (:style . org-export-html-style)
22413 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
22414 (:convert-org-links . org-export-html-link-org-files-as-html)
22415 (:inline-images . org-export-html-inline-images)
22416 (:html-extension . org-export-html-extension)
22417 (:html-table-tag . org-export-html-table-tag)
22418 (:expand-quoted-html . org-export-html-expand)
22419 (:timestamp . org-export-html-with-timestamp)
22420 (:publishing-directory . org-export-publishing-directory)
22421 (:preamble . org-export-html-preamble)
22422 (:postamble . org-export-html-postamble)
22423 (:auto-preamble . org-export-html-auto-preamble)
22424 (:auto-postamble . org-export-html-auto-postamble)
22425 (:author . user-full-name)
22426 (:email . user-mail-address)))
22428 (defun org-default-export-plist ()
22429 "Return the property list with default settings for the export variables."
22430 (let ((l org-export-plist-vars) rtn e)
22431 (while (setq e (pop l))
22432 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
22433 rtn))
22435 (defun org-infile-export-plist ()
22436 "Return the property list with file-local settings for export."
22437 (save-excursion
22438 (goto-char 0)
22439 (let ((re (org-make-options-regexp
22440 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
22441 p key val text options)
22442 (while (re-search-forward re nil t)
22443 (setq key (org-match-string-no-properties 1)
22444 val (org-match-string-no-properties 2))
22445 (cond
22446 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
22447 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
22448 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
22449 ((string-equal key "DATE") (setq p (plist-put p :date val)))
22450 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
22451 ((string-equal key "TEXT")
22452 (setq text (if text (concat text "\n" val) val)))
22453 ((string-equal key "OPTIONS") (setq options val))))
22454 (setq p (plist-put p :text text))
22455 (when options
22456 (let ((op '(("H" . :headline-levels)
22457 ("num" . :section-numbers)
22458 ("toc" . :table-of-contents)
22459 ("\\n" . :preserve-breaks)
22460 ("@" . :expand-quoted-html)
22461 (":" . :fixed-width)
22462 ("|" . :tables)
22463 ("^" . :sub-superscript)
22464 ("-" . :special-strings)
22465 ("f" . :footnotes)
22466 ("d" . :drawers)
22467 ("tags" . :tags)
22468 ("*" . :emphasize)
22469 ("TeX" . :TeX-macros)
22470 ("LaTeX" . :LaTeX-fragments)
22471 ("skip" . :skip-before-1st-heading)
22472 ("author" . :author-info)
22473 ("timestamp" . :time-stamp-file)))
22475 (while (setq o (pop op))
22476 (if (string-match (concat (regexp-quote (car o))
22477 ":\\([^ \t\n\r;,.]*\\)")
22478 options)
22479 (setq p (plist-put p (cdr o)
22480 (car (read-from-string
22481 (match-string 1 options)))))))))
22482 p)))
22484 (defun org-export-directory (type plist)
22485 (let* ((val (plist-get plist :publishing-directory))
22486 (dir (if (listp val)
22487 (or (cdr (assoc type val)) ".")
22488 val)))
22489 dir))
22491 (defun org-skip-comments (lines)
22492 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
22493 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
22494 (re2 "^\\(\\*+\\)[ \t\n\r]")
22495 (case-fold-search nil)
22496 rtn line level)
22497 (while (setq line (pop lines))
22498 (cond
22499 ((and (string-match re1 line)
22500 (setq level (- (match-end 1) (match-beginning 1))))
22501 ;; Beginning of a COMMENT subtree. Skip it.
22502 (while (and (setq line (pop lines))
22503 (or (not (string-match re2 line))
22504 (> (- (match-end 1) (match-beginning 1)) level))))
22505 (setq lines (cons line lines)))
22506 ((string-match "^#" line)
22507 ;; an ordinary comment line
22509 ((and org-export-table-remove-special-lines
22510 (string-match "^[ \t]*|" line)
22511 (or (string-match "^[ \t]*| *[!_^] *|" line)
22512 (and (string-match "| *<[0-9]+> *|" line)
22513 (not (string-match "| *[^ <|]" line)))))
22514 ;; a special table line that should be removed
22516 (t (setq rtn (cons line rtn)))))
22517 (nreverse rtn)))
22519 (defun org-export (&optional arg)
22520 (interactive)
22521 (let ((help "[t] insert the export option template
22522 \[v] limit export to visible part of outline tree
22524 \[a] export as ASCII
22526 \[h] export as HTML
22527 \[H] export as HTML to temporary buffer
22528 \[R] export region as HTML
22529 \[b] export as HTML and browse immediately
22530 \[x] export as XOXO
22532 \[l] export as LaTeX
22533 \[L] export as LaTeX to temporary buffer
22535 \[i] export current file as iCalendar file
22536 \[I] export all agenda files as iCalendar files
22537 \[c] export agenda files into combined iCalendar file
22539 \[F] publish current file
22540 \[P] publish current project
22541 \[X] publish... (project will be prompted for)
22542 \[A] publish all projects")
22543 (cmds
22544 '((?t . org-insert-export-options-template)
22545 (?v . org-export-visible)
22546 (?a . org-export-as-ascii)
22547 (?h . org-export-as-html)
22548 (?b . org-export-as-html-and-open)
22549 (?H . org-export-as-html-to-buffer)
22550 (?R . org-export-region-as-html)
22551 (?x . org-export-as-xoxo)
22552 (?l . org-export-as-latex)
22553 (?L . org-export-as-latex-to-buffer)
22554 (?i . org-export-icalendar-this-file)
22555 (?I . org-export-icalendar-all-agenda-files)
22556 (?c . org-export-icalendar-combine-agenda-files)
22557 (?F . org-publish-current-file)
22558 (?P . org-publish-current-project)
22559 (?X . org-publish)
22560 (?A . org-publish-all)))
22561 r1 r2 ass)
22562 (save-window-excursion
22563 (delete-other-windows)
22564 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
22565 (princ help))
22566 (message "Select command: ")
22567 (setq r1 (read-char-exclusive)))
22568 (setq r2 (if (< r1 27) (+ r1 96) r1))
22569 (if (setq ass (assq r2 cmds))
22570 (call-interactively (cdr ass))
22571 (error "No command associated with key %c" r1))))
22573 (defconst org-html-entities
22574 '(("nbsp")
22575 ("iexcl")
22576 ("cent")
22577 ("pound")
22578 ("curren")
22579 ("yen")
22580 ("brvbar")
22581 ("vert" . "&#124;")
22582 ("sect")
22583 ("uml")
22584 ("copy")
22585 ("ordf")
22586 ("laquo")
22587 ("not")
22588 ("shy")
22589 ("reg")
22590 ("macr")
22591 ("deg")
22592 ("plusmn")
22593 ("sup2")
22594 ("sup3")
22595 ("acute")
22596 ("micro")
22597 ("para")
22598 ("middot")
22599 ("odot"."o")
22600 ("star"."*")
22601 ("cedil")
22602 ("sup1")
22603 ("ordm")
22604 ("raquo")
22605 ("frac14")
22606 ("frac12")
22607 ("frac34")
22608 ("iquest")
22609 ("Agrave")
22610 ("Aacute")
22611 ("Acirc")
22612 ("Atilde")
22613 ("Auml")
22614 ("Aring") ("AA"."&Aring;")
22615 ("AElig")
22616 ("Ccedil")
22617 ("Egrave")
22618 ("Eacute")
22619 ("Ecirc")
22620 ("Euml")
22621 ("Igrave")
22622 ("Iacute")
22623 ("Icirc")
22624 ("Iuml")
22625 ("ETH")
22626 ("Ntilde")
22627 ("Ograve")
22628 ("Oacute")
22629 ("Ocirc")
22630 ("Otilde")
22631 ("Ouml")
22632 ("times")
22633 ("Oslash")
22634 ("Ugrave")
22635 ("Uacute")
22636 ("Ucirc")
22637 ("Uuml")
22638 ("Yacute")
22639 ("THORN")
22640 ("szlig")
22641 ("agrave")
22642 ("aacute")
22643 ("acirc")
22644 ("atilde")
22645 ("auml")
22646 ("aring")
22647 ("aelig")
22648 ("ccedil")
22649 ("egrave")
22650 ("eacute")
22651 ("ecirc")
22652 ("euml")
22653 ("igrave")
22654 ("iacute")
22655 ("icirc")
22656 ("iuml")
22657 ("eth")
22658 ("ntilde")
22659 ("ograve")
22660 ("oacute")
22661 ("ocirc")
22662 ("otilde")
22663 ("ouml")
22664 ("divide")
22665 ("oslash")
22666 ("ugrave")
22667 ("uacute")
22668 ("ucirc")
22669 ("uuml")
22670 ("yacute")
22671 ("thorn")
22672 ("yuml")
22673 ("fnof")
22674 ("Alpha")
22675 ("Beta")
22676 ("Gamma")
22677 ("Delta")
22678 ("Epsilon")
22679 ("Zeta")
22680 ("Eta")
22681 ("Theta")
22682 ("Iota")
22683 ("Kappa")
22684 ("Lambda")
22685 ("Mu")
22686 ("Nu")
22687 ("Xi")
22688 ("Omicron")
22689 ("Pi")
22690 ("Rho")
22691 ("Sigma")
22692 ("Tau")
22693 ("Upsilon")
22694 ("Phi")
22695 ("Chi")
22696 ("Psi")
22697 ("Omega")
22698 ("alpha")
22699 ("beta")
22700 ("gamma")
22701 ("delta")
22702 ("epsilon")
22703 ("varepsilon"."&epsilon;")
22704 ("zeta")
22705 ("eta")
22706 ("theta")
22707 ("iota")
22708 ("kappa")
22709 ("lambda")
22710 ("mu")
22711 ("nu")
22712 ("xi")
22713 ("omicron")
22714 ("pi")
22715 ("rho")
22716 ("sigmaf") ("varsigma"."&sigmaf;")
22717 ("sigma")
22718 ("tau")
22719 ("upsilon")
22720 ("phi")
22721 ("chi")
22722 ("psi")
22723 ("omega")
22724 ("thetasym") ("vartheta"."&thetasym;")
22725 ("upsih")
22726 ("piv")
22727 ("bull") ("bullet"."&bull;")
22728 ("hellip") ("dots"."&hellip;")
22729 ("prime")
22730 ("Prime")
22731 ("oline")
22732 ("frasl")
22733 ("weierp")
22734 ("image")
22735 ("real")
22736 ("trade")
22737 ("alefsym")
22738 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
22739 ("uarr") ("uparrow"."&uarr;")
22740 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
22741 ("darr")("downarrow"."&darr;")
22742 ("harr") ("leftrightarrow"."&harr;")
22743 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
22744 ("lArr") ("Leftarrow"."&lArr;")
22745 ("uArr") ("Uparrow"."&uArr;")
22746 ("rArr") ("Rightarrow"."&rArr;")
22747 ("dArr") ("Downarrow"."&dArr;")
22748 ("hArr") ("Leftrightarrow"."&hArr;")
22749 ("forall")
22750 ("part") ("partial"."&part;")
22751 ("exist") ("exists"."&exist;")
22752 ("empty") ("emptyset"."&empty;")
22753 ("nabla")
22754 ("isin") ("in"."&isin;")
22755 ("notin")
22756 ("ni")
22757 ("prod")
22758 ("sum")
22759 ("minus")
22760 ("lowast") ("ast"."&lowast;")
22761 ("radic")
22762 ("prop") ("proptp"."&prop;")
22763 ("infin") ("infty"."&infin;")
22764 ("ang") ("angle"."&ang;")
22765 ("and") ("wedge"."&and;")
22766 ("or") ("vee"."&or;")
22767 ("cap")
22768 ("cup")
22769 ("int")
22770 ("there4")
22771 ("sim")
22772 ("cong") ("simeq"."&cong;")
22773 ("asymp")("approx"."&asymp;")
22774 ("ne") ("neq"."&ne;")
22775 ("equiv")
22776 ("le")
22777 ("ge")
22778 ("sub") ("subset"."&sub;")
22779 ("sup") ("supset"."&sup;")
22780 ("nsub")
22781 ("sube")
22782 ("supe")
22783 ("oplus")
22784 ("otimes")
22785 ("perp")
22786 ("sdot") ("cdot"."&sdot;")
22787 ("lceil")
22788 ("rceil")
22789 ("lfloor")
22790 ("rfloor")
22791 ("lang")
22792 ("rang")
22793 ("loz") ("Diamond"."&loz;")
22794 ("spades") ("spadesuit"."&spades;")
22795 ("clubs") ("clubsuit"."&clubs;")
22796 ("hearts") ("diamondsuit"."&hearts;")
22797 ("diams") ("diamondsuit"."&diams;")
22798 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
22799 ("quot")
22800 ("amp")
22801 ("lt")
22802 ("gt")
22803 ("OElig")
22804 ("oelig")
22805 ("Scaron")
22806 ("scaron")
22807 ("Yuml")
22808 ("circ")
22809 ("tilde")
22810 ("ensp")
22811 ("emsp")
22812 ("thinsp")
22813 ("zwnj")
22814 ("zwj")
22815 ("lrm")
22816 ("rlm")
22817 ("ndash")
22818 ("mdash")
22819 ("lsquo")
22820 ("rsquo")
22821 ("sbquo")
22822 ("ldquo")
22823 ("rdquo")
22824 ("bdquo")
22825 ("dagger")
22826 ("Dagger")
22827 ("permil")
22828 ("lsaquo")
22829 ("rsaquo")
22830 ("euro")
22832 ("arccos"."arccos")
22833 ("arcsin"."arcsin")
22834 ("arctan"."arctan")
22835 ("arg"."arg")
22836 ("cos"."cos")
22837 ("cosh"."cosh")
22838 ("cot"."cot")
22839 ("coth"."coth")
22840 ("csc"."csc")
22841 ("deg"."deg")
22842 ("det"."det")
22843 ("dim"."dim")
22844 ("exp"."exp")
22845 ("gcd"."gcd")
22846 ("hom"."hom")
22847 ("inf"."inf")
22848 ("ker"."ker")
22849 ("lg"."lg")
22850 ("lim"."lim")
22851 ("liminf"."liminf")
22852 ("limsup"."limsup")
22853 ("ln"."ln")
22854 ("log"."log")
22855 ("max"."max")
22856 ("min"."min")
22857 ("Pr"."Pr")
22858 ("sec"."sec")
22859 ("sin"."sin")
22860 ("sinh"."sinh")
22861 ("sup"."sup")
22862 ("tan"."tan")
22863 ("tanh"."tanh")
22865 "Entities for TeX->HTML translation.
22866 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
22867 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
22868 In that case, \"\\ent\" will be translated to \"&other;\".
22869 The list contains HTML entities for Latin-1, Greek and other symbols.
22870 It is supplemented by a number of commonly used TeX macros with appropriate
22871 translations. There is currently no way for users to extend this.")
22873 ;;; General functions for all backends
22875 (defun org-cleaned-string-for-export (string &rest parameters)
22876 "Cleanup a buffer STRING so that links can be created safely."
22877 (interactive)
22878 (let* ((re-radio (and org-target-link-regexp
22879 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
22880 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
22881 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
22882 (re-archive (concat ":" org-archive-tag ":"))
22883 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
22884 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
22885 (htmlp (plist-get parameters :for-html))
22886 (asciip (plist-get parameters :for-ascii))
22887 (latexp (plist-get parameters :for-LaTeX))
22888 (commentsp (plist-get parameters :comments))
22889 (archived-trees (plist-get parameters :archived-trees))
22890 (inhibit-read-only t)
22891 (drawers org-drawers)
22892 (exp-drawers (plist-get parameters :drawers))
22893 (outline-regexp "\\*+ ")
22894 a b xx
22895 rtn p)
22896 (with-current-buffer (get-buffer-create " org-mode-tmp")
22897 (erase-buffer)
22898 (insert string)
22899 ;; Remove license-to-kill stuff
22900 (while (setq p (text-property-any (point-min) (point-max)
22901 :org-license-to-kill t))
22902 (delete-region p (next-single-property-change p :org-license-to-kill)))
22904 (let ((org-inhibit-startup t)) (org-mode))
22905 (untabify (point-min) (point-max))
22907 ;; Get the correct stuff before the first headline
22908 (when (plist-get parameters :skip-before-1st-heading)
22909 (goto-char (point-min))
22910 (when (re-search-forward "^\\*+[ \t]" nil t)
22911 (delete-region (point-min) (match-beginning 0))
22912 (goto-char (point-min))
22913 (insert "\n")))
22914 (when (plist-get parameters :add-text)
22915 (goto-char (point-min))
22916 (insert (plist-get parameters :add-text) "\n"))
22918 ;; Get rid of archived trees
22919 (when (not (eq archived-trees t))
22920 (goto-char (point-min))
22921 (while (re-search-forward re-archive nil t)
22922 (if (not (org-on-heading-p t))
22923 (org-end-of-subtree t)
22924 (beginning-of-line 1)
22925 (setq a (if archived-trees
22926 (1+ (point-at-eol)) (point))
22927 b (org-end-of-subtree t))
22928 (if (> b a) (delete-region a b)))))
22930 ;; Get rid of drawers
22931 (unless (eq t exp-drawers)
22932 (goto-char (point-min))
22933 (let ((re (concat "^[ \t]*:\\("
22934 (mapconcat
22935 'identity
22936 (org-delete-all exp-drawers
22937 (copy-sequence drawers))
22938 "\\|")
22939 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
22940 (while (re-search-forward re nil t)
22941 (replace-match ""))))
22943 ;; Find targets in comments and move them out of comments,
22944 ;; but mark them as targets that should be invisible
22945 (goto-char (point-min))
22946 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
22947 (replace-match "\\1(INVISIBLE)"))
22949 ;; Protect backend specific stuff, throw away the others.
22950 (let ((formatters
22951 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
22952 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
22953 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
22954 fmt)
22955 (goto-char (point-min))
22956 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
22957 (goto-char (match-end 0))
22958 (while (not (looking-at "#\\+END_EXAMPLE"))
22959 (insert ": ")
22960 (beginning-of-line 2)))
22961 (goto-char (point-min))
22962 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
22963 (add-text-properties (match-beginning 0) (match-end 0)
22964 '(org-protected t)))
22965 (while formatters
22966 (setq fmt (pop formatters))
22967 (when (car fmt)
22968 (goto-char (point-min))
22969 (while (re-search-forward (concat "^#\\+" (cadr fmt)
22970 ":[ \t]*\\(.*\\)") nil t)
22971 (replace-match "\\1" t)
22972 (add-text-properties
22973 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
22974 '(org-protected t))))
22975 (goto-char (point-min))
22976 (while (re-search-forward
22977 (concat "^#\\+"
22978 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
22979 (cadddr fmt) "\\>.*\n?") nil t)
22980 (if (car fmt)
22981 (add-text-properties (match-beginning 1) (1+ (match-end 1))
22982 '(org-protected t))
22983 (delete-region (match-beginning 0) (match-end 0))))))
22985 ;; Protect quoted subtrees
22986 (goto-char (point-min))
22987 (while (re-search-forward re-quote nil t)
22988 (goto-char (match-beginning 0))
22989 (end-of-line 1)
22990 (add-text-properties (point) (org-end-of-subtree t)
22991 '(org-protected t)))
22993 ;; Protect verbatim elements
22994 (goto-char (point-min))
22995 (while (re-search-forward org-verbatim-re nil t)
22996 (add-text-properties (match-beginning 4) (match-end 4)
22997 '(org-protected t))
22998 (goto-char (1+ (match-end 4))))
23000 ;; Remove subtrees that are commented
23001 (goto-char (point-min))
23002 (while (re-search-forward re-commented nil t)
23003 (goto-char (match-beginning 0))
23004 (delete-region (point) (org-end-of-subtree t)))
23006 ;; Remove special table lines
23007 (when org-export-table-remove-special-lines
23008 (goto-char (point-min))
23009 (while (re-search-forward "^[ \t]*|" nil t)
23010 (beginning-of-line 1)
23011 (if (or (looking-at "[ \t]*| *[!_^] *|")
23012 (and (looking-at ".*?| *<[0-9]+> *|")
23013 (not (looking-at ".*?| *[^ <|]"))))
23014 (delete-region (max (point-min) (1- (point-at-bol)))
23015 (point-at-eol))
23016 (end-of-line 1))))
23018 ;; Specific LaTeX stuff
23019 (when latexp
23020 (require 'org-export-latex nil)
23021 (org-export-latex-cleaned-string))
23023 (when asciip
23024 (org-export-ascii-clean-string))
23026 ;; Specific HTML stuff
23027 (when htmlp
23028 ;; Convert LaTeX fragments to images
23029 (when (plist-get parameters :LaTeX-fragments)
23030 (org-format-latex
23031 (concat "ltxpng/" (file-name-sans-extension
23032 (file-name-nondirectory
23033 org-current-export-file)))
23034 org-current-export-dir nil "Creating LaTeX image %s"))
23035 (message "Exporting..."))
23037 ;; Remove or replace comments
23038 (goto-char (point-min))
23039 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
23040 (if commentsp
23041 (progn (add-text-properties
23042 (match-beginning 0) (match-end 0) '(org-protected t))
23043 (replace-match (format commentsp (match-string 1)) t t))
23044 (replace-match "")))
23046 ;; Find matches for radio targets and turn them into internal links
23047 (goto-char (point-min))
23048 (when re-radio
23049 (while (re-search-forward re-radio nil t)
23050 (org-if-unprotected
23051 (replace-match "\\1[[\\2]]"))))
23053 ;; Find all links that contain a newline and put them into a single line
23054 (goto-char (point-min))
23055 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
23056 (org-if-unprotected
23057 (replace-match "\\1 \\3")
23058 (goto-char (match-beginning 0))))
23061 ;; Normalize links: Convert angle and plain links into bracket links
23062 ;; Expand link abbreviations
23063 (goto-char (point-min))
23064 (while (re-search-forward re-plain-link nil t)
23065 (goto-char (1- (match-end 0)))
23066 (org-if-unprotected
23067 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23068 ":" (match-string 3) "]]")))
23069 ;; added 'org-link face to links
23070 (put-text-property 0 (length s) 'face 'org-link s)
23071 (replace-match s t t))))
23072 (goto-char (point-min))
23073 (while (re-search-forward re-angle-link nil t)
23074 (goto-char (1- (match-end 0)))
23075 (org-if-unprotected
23076 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23077 ":" (match-string 3) "]]")))
23078 (put-text-property 0 (length s) 'face 'org-link s)
23079 (replace-match s t t))))
23080 (goto-char (point-min))
23081 (while (re-search-forward org-bracket-link-regexp nil t)
23082 (org-if-unprotected
23083 (let* ((s (concat "[[" (setq xx (save-match-data
23084 (org-link-expand-abbrev (match-string 1))))
23086 (if (match-end 3)
23087 (match-string 2)
23088 (concat "[" xx "]"))
23089 "]")))
23090 (put-text-property 0 (length s) 'face 'org-link s)
23091 (replace-match s t t))))
23093 ;; Find multiline emphasis and put them into single line
23094 (when (plist-get parameters :emph-multiline)
23095 (goto-char (point-min))
23096 (while (re-search-forward org-emph-re nil t)
23097 (if (not (= (char-after (match-beginning 3))
23098 (char-after (match-beginning 4))))
23099 (org-if-unprotected
23100 (subst-char-in-region (match-beginning 0) (match-end 0)
23101 ?\n ?\ t)
23102 (goto-char (1- (match-end 0))))
23103 (goto-char (1+ (match-beginning 0))))))
23105 (setq rtn (buffer-string)))
23106 (kill-buffer " org-mode-tmp")
23107 rtn))
23109 (defun org-export-grab-title-from-buffer ()
23110 "Get a title for the current document, from looking at the buffer."
23111 (let ((inhibit-read-only t))
23112 (save-excursion
23113 (goto-char (point-min))
23114 (let ((end (save-excursion (outline-next-heading) (point))))
23115 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
23116 ;; Mark the line so that it will not be exported as normal text.
23117 (org-unmodified
23118 (add-text-properties (match-beginning 0) (match-end 0)
23119 (list :org-license-to-kill t)))
23120 ;; Return the title string
23121 (org-trim (match-string 0)))))))
23123 (defun org-export-get-title-from-subtree ()
23124 "Return subtree title and exclude it from export."
23125 (let (title (m (mark)))
23126 (save-excursion
23127 (goto-char (region-beginning))
23128 (when (and (org-at-heading-p)
23129 (>= (org-end-of-subtree t t) (region-end)))
23130 ;; This is a subtree, we take the title from the first heading
23131 (goto-char (region-beginning))
23132 (looking-at org-todo-line-regexp)
23133 (setq title (match-string 3))
23134 (org-unmodified
23135 (add-text-properties (point) (1+ (point-at-eol))
23136 (list :org-license-to-kill t)))))
23137 title))
23139 (defun org-solidify-link-text (s &optional alist)
23140 "Take link text and make a safe target out of it."
23141 (save-match-data
23142 (let* ((rtn
23143 (mapconcat
23144 'identity
23145 (org-split-string s "[ \t\r\n]+") "--"))
23146 (a (assoc rtn alist)))
23147 (or (cdr a) rtn))))
23149 (defun org-get-min-level (lines)
23150 "Get the minimum level in LINES."
23151 (let ((re "^\\(\\*+\\) ") l min)
23152 (catch 'exit
23153 (while (setq l (pop lines))
23154 (if (string-match re l)
23155 (throw 'exit (org-tr-level (length (match-string 1 l))))))
23156 1)))
23158 ;; Variable holding the vector with section numbers
23159 (defvar org-section-numbers (make-vector org-level-max 0))
23161 (defun org-init-section-numbers ()
23162 "Initialize the vector for the section numbers."
23163 (let* ((level -1)
23164 (numbers (nreverse (org-split-string "" "\\.")))
23165 (depth (1- (length org-section-numbers)))
23166 (i depth) number-string)
23167 (while (>= i 0)
23168 (if (> i level)
23169 (aset org-section-numbers i 0)
23170 (setq number-string (or (car numbers) "0"))
23171 (if (string-match "\\`[A-Z]\\'" number-string)
23172 (aset org-section-numbers i
23173 (- (string-to-char number-string) ?A -1))
23174 (aset org-section-numbers i (string-to-number number-string)))
23175 (pop numbers))
23176 (setq i (1- i)))))
23178 (defun org-section-number (&optional level)
23179 "Return a string with the current section number.
23180 When LEVEL is non-nil, increase section numbers on that level."
23181 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
23182 (when level
23183 (when (> level -1)
23184 (aset org-section-numbers
23185 level (1+ (aref org-section-numbers level))))
23186 (setq idx (1+ level))
23187 (while (<= idx depth)
23188 (if (not (= idx 1))
23189 (aset org-section-numbers idx 0))
23190 (setq idx (1+ idx))))
23191 (setq idx 0)
23192 (while (<= idx depth)
23193 (setq n (aref org-section-numbers idx))
23194 (setq string (concat string (if (not (string= string "")) "." "")
23195 (int-to-string n)))
23196 (setq idx (1+ idx)))
23197 (save-match-data
23198 (if (string-match "\\`\\([@0]\\.\\)+" string)
23199 (setq string (replace-match "" t nil string)))
23200 (if (string-match "\\(\\.0\\)+\\'" string)
23201 (setq string (replace-match "" t nil string))))
23202 string))
23204 ;;; ASCII export
23206 (defvar org-last-level nil) ; dynamically scoped variable
23207 (defvar org-min-level nil) ; dynamically scoped variable
23208 (defvar org-levels-open nil) ; dynamically scoped parameter
23209 (defvar org-ascii-current-indentation nil) ; For communication
23211 (defun org-export-as-ascii (arg)
23212 "Export the outline as a pretty ASCII file.
23213 If there is an active region, export only the region.
23214 The prefix ARG specifies how many levels of the outline should become
23215 underlined headlines. The default is 3."
23216 (interactive "P")
23217 (setq-default org-todo-line-regexp org-todo-line-regexp)
23218 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23219 (org-infile-export-plist)))
23220 (region-p (org-region-active-p))
23221 (subtree-p
23222 (when region-p
23223 (save-excursion
23224 (goto-char (region-beginning))
23225 (and (org-at-heading-p)
23226 (>= (org-end-of-subtree t t) (region-end))))))
23227 (custom-times org-display-custom-times)
23228 (org-ascii-current-indentation '(0 . 0))
23229 (level 0) line txt
23230 (umax nil)
23231 (umax-toc nil)
23232 (case-fold-search nil)
23233 (filename (concat (file-name-as-directory
23234 (org-export-directory :ascii opt-plist))
23235 (file-name-sans-extension
23236 (or (and subtree-p
23237 (org-entry-get (region-beginning)
23238 "EXPORT_FILE_NAME" t))
23239 (file-name-nondirectory buffer-file-name)))
23240 ".txt"))
23241 (filename (if (equal (file-truename filename)
23242 (file-truename buffer-file-name))
23243 (concat filename ".txt")
23244 filename))
23245 (buffer (find-file-noselect filename))
23246 (org-levels-open (make-vector org-level-max nil))
23247 (odd org-odd-levels-only)
23248 (date (plist-get opt-plist :date))
23249 (author (plist-get opt-plist :author))
23250 (title (or (and subtree-p (org-export-get-title-from-subtree))
23251 (plist-get opt-plist :title)
23252 (and (not
23253 (plist-get opt-plist :skip-before-1st-heading))
23254 (org-export-grab-title-from-buffer))
23255 (file-name-sans-extension
23256 (file-name-nondirectory buffer-file-name))))
23257 (email (plist-get opt-plist :email))
23258 (language (plist-get opt-plist :language))
23259 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23260 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
23261 (todo nil)
23262 (lang-words nil)
23263 (region
23264 (buffer-substring
23265 (if (org-region-active-p) (region-beginning) (point-min))
23266 (if (org-region-active-p) (region-end) (point-max))))
23267 (lines (org-split-string
23268 (org-cleaned-string-for-export
23269 region
23270 :for-ascii t
23271 :skip-before-1st-heading
23272 (plist-get opt-plist :skip-before-1st-heading)
23273 :drawers (plist-get opt-plist :drawers)
23274 :verbatim-multiline t
23275 :archived-trees
23276 (plist-get opt-plist :archived-trees)
23277 :add-text (plist-get opt-plist :text))
23278 "\n"))
23279 thetoc have-headings first-heading-pos
23280 table-open table-buffer)
23282 (let ((inhibit-read-only t))
23283 (org-unmodified
23284 (remove-text-properties (point-min) (point-max)
23285 '(:org-license-to-kill t))))
23287 (setq org-min-level (org-get-min-level lines))
23288 (setq org-last-level org-min-level)
23289 (org-init-section-numbers)
23291 (find-file-noselect filename)
23293 (setq lang-words (or (assoc language org-export-language-setup)
23294 (assoc "en" org-export-language-setup)))
23295 (switch-to-buffer-other-window buffer)
23296 (erase-buffer)
23297 (fundamental-mode)
23298 ;; create local variables for all options, to make sure all called
23299 ;; functions get the correct information
23300 (mapc (lambda (x)
23301 (set (make-local-variable (cdr x))
23302 (plist-get opt-plist (car x))))
23303 org-export-plist-vars)
23304 (org-set-local 'org-odd-levels-only odd)
23305 (setq umax (if arg (prefix-numeric-value arg)
23306 org-export-headline-levels))
23307 (setq umax-toc (if (integerp org-export-with-toc)
23308 (min org-export-with-toc umax)
23309 umax))
23311 ;; File header
23312 (if title (org-insert-centered title ?=))
23313 (insert "\n")
23314 (if (and (or author email)
23315 org-export-author-info)
23316 (insert (concat (nth 1 lang-words) ": " (or author "")
23317 (if email (concat " <" email ">") "")
23318 "\n")))
23320 (cond
23321 ((and date (string-match "%" date))
23322 (setq date (format-time-string date (current-time))))
23323 (date)
23324 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
23326 (if (and date org-export-time-stamp-file)
23327 (insert (concat (nth 2 lang-words) ": " date"\n")))
23329 (insert "\n\n")
23331 (if org-export-with-toc
23332 (progn
23333 (push (concat (nth 3 lang-words) "\n") thetoc)
23334 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
23335 (mapc '(lambda (line)
23336 (if (string-match org-todo-line-regexp
23337 line)
23338 ;; This is a headline
23339 (progn
23340 (setq have-headings t)
23341 (setq level (- (match-end 1) (match-beginning 1))
23342 level (org-tr-level level)
23343 txt (match-string 3 line)
23344 todo
23345 (or (and org-export-mark-todo-in-toc
23346 (match-beginning 2)
23347 (not (member (match-string 2 line)
23348 org-done-keywords)))
23349 ; TODO, not DONE
23350 (and org-export-mark-todo-in-toc
23351 (= level umax-toc)
23352 (org-search-todo-below
23353 line lines level))))
23354 (setq txt (org-html-expand-for-ascii txt))
23356 (while (string-match org-bracket-link-regexp txt)
23357 (setq txt
23358 (replace-match
23359 (match-string (if (match-end 2) 3 1) txt)
23360 t t txt)))
23362 (if (and (memq org-export-with-tags '(not-in-toc nil))
23363 (string-match
23364 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
23365 txt))
23366 (setq txt (replace-match "" t t txt)))
23367 (if (string-match quote-re0 txt)
23368 (setq txt (replace-match "" t t txt)))
23370 (if org-export-with-section-numbers
23371 (setq txt (concat (org-section-number level)
23372 " " txt)))
23373 (if (<= level umax-toc)
23374 (progn
23375 (push
23376 (concat
23377 (make-string
23378 (* (max 0 (- level org-min-level)) 4) ?\ )
23379 (format (if todo "%s (*)\n" "%s\n") txt))
23380 thetoc)
23381 (setq org-last-level level))
23382 ))))
23383 lines)
23384 (setq thetoc (if have-headings (nreverse thetoc) nil))))
23386 (org-init-section-numbers)
23387 (while (setq line (pop lines))
23388 ;; Remove the quoted HTML tags.
23389 (setq line (org-html-expand-for-ascii line))
23390 ;; Remove targets
23391 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
23392 (setq line (replace-match "" t t line)))
23393 ;; Replace internal links
23394 (while (string-match org-bracket-link-regexp line)
23395 (setq line (replace-match
23396 (if (match-end 3) "[\\3]" "[\\1]")
23397 t nil line)))
23398 (when custom-times
23399 (setq line (org-translate-time line)))
23400 (cond
23401 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
23402 ;; a Headline
23403 (setq first-heading-pos (or first-heading-pos (point)))
23404 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
23405 txt (match-string 2 line))
23406 (org-ascii-level-start level txt umax lines))
23408 ((and org-export-with-tables
23409 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
23410 (if (not table-open)
23411 ;; New table starts
23412 (setq table-open t table-buffer nil))
23413 ;; Accumulate lines
23414 (setq table-buffer (cons line table-buffer))
23415 (when (or (not lines)
23416 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
23417 (car lines))))
23418 (setq table-open nil
23419 table-buffer (nreverse table-buffer))
23420 (insert (mapconcat
23421 (lambda (x)
23422 (org-fix-indentation x org-ascii-current-indentation))
23423 (org-format-table-ascii table-buffer)
23424 "\n") "\n")))
23426 (setq line (org-fix-indentation line org-ascii-current-indentation))
23427 (if (and org-export-with-fixed-width
23428 (string-match "^\\([ \t]*\\)\\(:\\)" line))
23429 (setq line (replace-match "\\1" nil nil line)))
23430 (insert line "\n"))))
23432 (normal-mode)
23434 ;; insert the table of contents
23435 (when thetoc
23436 (goto-char (point-min))
23437 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
23438 (progn
23439 (goto-char (match-beginning 0))
23440 (replace-match ""))
23441 (goto-char first-heading-pos))
23442 (mapc 'insert thetoc)
23443 (or (looking-at "[ \t]*\n[ \t]*\n")
23444 (insert "\n\n")))
23446 ;; Convert whitespace place holders
23447 (goto-char (point-min))
23448 (let (beg end)
23449 (while (setq beg (next-single-property-change (point) 'org-whitespace))
23450 (setq end (next-single-property-change beg 'org-whitespace))
23451 (goto-char beg)
23452 (delete-region beg end)
23453 (insert (make-string (- end beg) ?\ ))))
23455 (save-buffer)
23456 ;; remove display and invisible chars
23457 (let (beg end)
23458 (goto-char (point-min))
23459 (while (setq beg (next-single-property-change (point) 'display))
23460 (setq end (next-single-property-change beg 'display))
23461 (delete-region beg end)
23462 (goto-char beg)
23463 (insert "=>"))
23464 (goto-char (point-min))
23465 (while (setq beg (next-single-property-change (point) 'org-cwidth))
23466 (setq end (next-single-property-change beg 'org-cwidth))
23467 (delete-region beg end)
23468 (goto-char beg)))
23469 (goto-char (point-min))))
23471 (defun org-export-ascii-clean-string ()
23472 "Do extra work for ASCII export"
23473 (goto-char (point-min))
23474 (while (re-search-forward org-verbatim-re nil t)
23475 (goto-char (match-end 2))
23476 (backward-delete-char 1) (insert "'")
23477 (goto-char (match-beginning 2))
23478 (delete-char 1) (insert "`")
23479 (goto-char (match-end 2))))
23481 (defun org-search-todo-below (line lines level)
23482 "Search the subtree below LINE for any TODO entries."
23483 (let ((rest (cdr (memq line lines)))
23484 (re org-todo-line-regexp)
23485 line lv todo)
23486 (catch 'exit
23487 (while (setq line (pop rest))
23488 (if (string-match re line)
23489 (progn
23490 (setq lv (- (match-end 1) (match-beginning 1))
23491 todo (and (match-beginning 2)
23492 (not (member (match-string 2 line)
23493 org-done-keywords))))
23494 ; TODO, not DONE
23495 (if (<= lv level) (throw 'exit nil))
23496 (if todo (throw 'exit t))))))))
23498 (defun org-html-expand-for-ascii (line)
23499 "Handle quoted HTML for ASCII export."
23500 (if org-export-html-expand
23501 (while (string-match "@<[^<>\n]*>" line)
23502 ;; We just remove the tags for now.
23503 (setq line (replace-match "" nil nil line))))
23504 line)
23506 (defun org-insert-centered (s &optional underline)
23507 "Insert the string S centered and underline it with character UNDERLINE."
23508 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
23509 (insert (make-string ind ?\ ) s "\n")
23510 (if underline
23511 (insert (make-string ind ?\ )
23512 (make-string (string-width s) underline)
23513 "\n"))))
23515 (defun org-ascii-level-start (level title umax &optional lines)
23516 "Insert a new level in ASCII export."
23517 (let (char (n (- level umax 1)) (ind 0))
23518 (if (> level umax)
23519 (progn
23520 (insert (make-string (* 2 n) ?\ )
23521 (char-to-string (nth (% n (length org-export-ascii-bullets))
23522 org-export-ascii-bullets))
23523 " " title "\n")
23524 ;; find the indentation of the next non-empty line
23525 (catch 'stop
23526 (while lines
23527 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
23528 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
23529 (throw 'stop (setq ind (org-get-indentation (car lines)))))
23530 (pop lines)))
23531 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
23532 (if (or (not (equal (char-before) ?\n))
23533 (not (equal (char-before (1- (point))) ?\n)))
23534 (insert "\n"))
23535 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
23536 (unless org-export-with-tags
23537 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
23538 (setq title (replace-match "" t t title))))
23539 (if org-export-with-section-numbers
23540 (setq title (concat (org-section-number level) " " title)))
23541 (insert title "\n" (make-string (string-width title) char) "\n")
23542 (setq org-ascii-current-indentation '(0 . 0)))))
23544 (defun org-export-visible (type arg)
23545 "Create a copy of the visible part of the current buffer, and export it.
23546 The copy is created in a temporary buffer and removed after use.
23547 TYPE is the final key (as a string) that also select the export command in
23548 the `C-c C-e' export dispatcher.
23549 As a special case, if the you type SPC at the prompt, the temporary
23550 org-mode file will not be removed but presented to you so that you can
23551 continue to use it. The prefix arg ARG is passed through to the exporting
23552 command."
23553 (interactive
23554 (list (progn
23555 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
23556 (read-char-exclusive))
23557 current-prefix-arg))
23558 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
23559 (error "Invalid export key"))
23560 (let* ((binding (cdr (assoc type
23561 '((?a . org-export-as-ascii)
23562 (?\C-a . org-export-as-ascii)
23563 (?b . org-export-as-html-and-open)
23564 (?\C-b . org-export-as-html-and-open)
23565 (?h . org-export-as-html)
23566 (?H . org-export-as-html-to-buffer)
23567 (?R . org-export-region-as-html)
23568 (?x . org-export-as-xoxo)))))
23569 (keepp (equal type ?\ ))
23570 (file buffer-file-name)
23571 (buffer (get-buffer-create "*Org Export Visible*"))
23572 s e)
23573 ;; Need to hack the drawers here.
23574 (save-excursion
23575 (goto-char (point-min))
23576 (while (re-search-forward org-drawer-regexp nil t)
23577 (goto-char (match-beginning 1))
23578 (or (org-invisible-p) (org-flag-drawer nil))))
23579 (with-current-buffer buffer (erase-buffer))
23580 (save-excursion
23581 (setq s (goto-char (point-min)))
23582 (while (not (= (point) (point-max)))
23583 (goto-char (org-find-invisible))
23584 (append-to-buffer buffer s (point))
23585 (setq s (goto-char (org-find-visible))))
23586 (org-cycle-hide-drawers 'all)
23587 (goto-char (point-min))
23588 (unless keepp
23589 ;; Copy all comment lines to the end, to make sure #+ settings are
23590 ;; still available for the second export step. Kind of a hack, but
23591 ;; does do the trick.
23592 (if (looking-at "#[^\r\n]*")
23593 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
23594 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
23595 (append-to-buffer buffer (1+ (match-beginning 0))
23596 (min (point-max) (1+ (match-end 0))))))
23597 (set-buffer buffer)
23598 (let ((buffer-file-name file)
23599 (org-inhibit-startup t))
23600 (org-mode)
23601 (show-all)
23602 (unless keepp (funcall binding arg))))
23603 (if (not keepp)
23604 (kill-buffer buffer)
23605 (switch-to-buffer-other-window buffer)
23606 (goto-char (point-min)))))
23608 (defun org-find-visible ()
23609 (let ((s (point)))
23610 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23611 (get-char-property s 'invisible)))
23613 (defun org-find-invisible ()
23614 (let ((s (point)))
23615 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23616 (not (get-char-property s 'invisible))))
23619 ;;; HTML export
23621 (defun org-get-current-options ()
23622 "Return a string with current options as keyword options.
23623 Does include HTML export options as well as TODO and CATEGORY stuff."
23624 (format
23625 "#+TITLE: %s
23626 #+AUTHOR: %s
23627 #+EMAIL: %s
23628 #+LANGUAGE: %s
23629 #+TEXT: Some descriptive text to be emitted. Several lines OK.
23630 #+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
23631 #+CATEGORY: %s
23632 #+SEQ_TODO: %s
23633 #+TYP_TODO: %s
23634 #+PRIORITIES: %c %c %c
23635 #+DRAWERS: %s
23636 #+STARTUP: %s %s %s %s %s
23637 #+TAGS: %s
23638 #+ARCHIVE: %s
23639 #+LINK: %s
23641 (buffer-name) (user-full-name) user-mail-address org-export-default-language
23642 org-export-headline-levels
23643 org-export-with-section-numbers
23644 org-export-with-toc
23645 org-export-preserve-breaks
23646 org-export-html-expand
23647 org-export-with-fixed-width
23648 org-export-with-tables
23649 org-export-with-sub-superscripts
23650 org-export-with-special-strings
23651 org-export-with-footnotes
23652 org-export-with-emphasize
23653 org-export-with-TeX-macros
23654 org-export-with-LaTeX-fragments
23655 org-export-skip-text-before-1st-heading
23656 org-export-with-drawers
23657 org-export-with-tags
23658 (file-name-nondirectory buffer-file-name)
23659 "TODO FEEDBACK VERIFY DONE"
23660 "Me Jason Marie DONE"
23661 org-highest-priority org-lowest-priority org-default-priority
23662 (mapconcat 'identity org-drawers " ")
23663 (cdr (assoc org-startup-folded
23664 '((nil . "showall") (t . "overview") (content . "content"))))
23665 (if org-odd-levels-only "odd" "oddeven")
23666 (if org-hide-leading-stars "hidestars" "showstars")
23667 (if org-startup-align-all-tables "align" "noalign")
23668 (cond ((eq t org-log-done) "logdone")
23669 ((not org-log-done) "nologging")
23670 ((listp org-log-done)
23671 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
23672 org-log-done " ")))
23673 (or (mapconcat (lambda (x)
23674 (cond
23675 ((equal '(:startgroup) x) "{")
23676 ((equal '(:endgroup) x) "}")
23677 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
23678 (t (car x))))
23679 (or org-tag-alist (org-get-buffer-tags)) " ") "")
23680 org-archive-location
23681 "org file:~/org/%s.org"
23684 (defun org-insert-export-options-template ()
23685 "Insert into the buffer a template with information for exporting."
23686 (interactive)
23687 (if (not (bolp)) (newline))
23688 (let ((s (org-get-current-options)))
23689 (and (string-match "#\\+CATEGORY" s)
23690 (setq s (substring s 0 (match-beginning 0))))
23691 (insert s)))
23693 (defun org-toggle-fixed-width-section (arg)
23694 "Toggle the fixed-width export.
23695 If there is no active region, the QUOTE keyword at the current headline is
23696 inserted or removed. When present, it causes the text between this headline
23697 and the next to be exported as fixed-width text, and unmodified.
23698 If there is an active region, this command adds or removes a colon as the
23699 first character of this line. If the first character of a line is a colon,
23700 this line is also exported in fixed-width font."
23701 (interactive "P")
23702 (let* ((cc 0)
23703 (regionp (org-region-active-p))
23704 (beg (if regionp (region-beginning) (point)))
23705 (end (if regionp (region-end)))
23706 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
23707 (case-fold-search nil)
23708 (re "[ \t]*\\(:\\)")
23709 off)
23710 (if regionp
23711 (save-excursion
23712 (goto-char beg)
23713 (setq cc (current-column))
23714 (beginning-of-line 1)
23715 (setq off (looking-at re))
23716 (while (> nlines 0)
23717 (setq nlines (1- nlines))
23718 (beginning-of-line 1)
23719 (cond
23720 (arg
23721 (move-to-column cc t)
23722 (insert ":\n")
23723 (forward-line -1))
23724 ((and off (looking-at re))
23725 (replace-match "" t t nil 1))
23726 ((not off) (move-to-column cc t) (insert ":")))
23727 (forward-line 1)))
23728 (save-excursion
23729 (org-back-to-heading)
23730 (if (looking-at (concat outline-regexp
23731 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
23732 (replace-match "" t t nil 1)
23733 (if (looking-at outline-regexp)
23734 (progn
23735 (goto-char (match-end 0))
23736 (insert org-quote-string " "))))))))
23738 (defun org-export-as-html-and-open (arg)
23739 "Export the outline as HTML and immediately open it with a browser.
23740 If there is an active region, export only the region.
23741 The prefix ARG specifies how many levels of the outline should become
23742 headlines. The default is 3. Lower levels will become bulleted lists."
23743 (interactive "P")
23744 (org-export-as-html arg 'hidden)
23745 (org-open-file buffer-file-name))
23747 (defun org-export-as-html-batch ()
23748 "Call `org-export-as-html', may be used in batch processing as
23749 emacs --batch
23750 --load=$HOME/lib/emacs/org.el
23751 --eval \"(setq org-export-headline-levels 2)\"
23752 --visit=MyFile --funcall org-export-as-html-batch"
23753 (org-export-as-html org-export-headline-levels 'hidden))
23755 (defun org-export-as-html-to-buffer (arg)
23756 "Call `org-exort-as-html` with output to a temporary buffer.
23757 No file is created. The prefix ARG is passed through to `org-export-as-html'."
23758 (interactive "P")
23759 (org-export-as-html arg nil nil "*Org HTML Export*")
23760 (switch-to-buffer-other-window "*Org HTML Export*"))
23762 (defun org-replace-region-by-html (beg end)
23763 "Assume the current region has org-mode syntax, and convert it to HTML.
23764 This can be used in any buffer. For example, you could write an
23765 itemized list in org-mode syntax in an HTML buffer and then use this
23766 command to convert it."
23767 (interactive "r")
23768 (let (reg html buf pop-up-frames)
23769 (save-window-excursion
23770 (if (org-mode-p)
23771 (setq html (org-export-region-as-html
23772 beg end t 'string))
23773 (setq reg (buffer-substring beg end)
23774 buf (get-buffer-create "*Org tmp*"))
23775 (with-current-buffer buf
23776 (erase-buffer)
23777 (insert reg)
23778 (org-mode)
23779 (setq html (org-export-region-as-html
23780 (point-min) (point-max) t 'string)))
23781 (kill-buffer buf)))
23782 (delete-region beg end)
23783 (insert html)))
23785 (defun org-export-region-as-html (beg end &optional body-only buffer)
23786 "Convert region from BEG to END in org-mode buffer to HTML.
23787 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
23788 contents, and only produce the region of converted text, useful for
23789 cut-and-paste operations.
23790 If BUFFER is a buffer or a string, use/create that buffer as a target
23791 of the converted HTML. If BUFFER is the symbol `string', return the
23792 produced HTML as a string and leave not buffer behind. For example,
23793 a Lisp program could call this function in the following way:
23795 (setq html (org-export-region-as-html beg end t 'string))
23797 When called interactively, the output buffer is selected, and shown
23798 in a window. A non-interactive call will only retunr the buffer."
23799 (interactive "r\nP")
23800 (when (interactive-p)
23801 (setq buffer "*Org HTML Export*"))
23802 (let ((transient-mark-mode t) (zmacs-regions t)
23803 rtn)
23804 (goto-char end)
23805 (set-mark (point)) ;; to activate the region
23806 (goto-char beg)
23807 (setq rtn (org-export-as-html
23808 nil nil nil
23809 buffer body-only))
23810 (if (fboundp 'deactivate-mark) (deactivate-mark))
23811 (if (and (interactive-p) (bufferp rtn))
23812 (switch-to-buffer-other-window rtn)
23813 rtn)))
23815 (defvar html-table-tag nil) ; dynamically scoped into this.
23816 (defun org-export-as-html (arg &optional hidden ext-plist
23817 to-buffer body-only)
23818 "Export the outline as a pretty HTML file.
23819 If there is an active region, export only the region. The prefix
23820 ARG specifies how many levels of the outline should become
23821 headlines. The default is 3. Lower levels will become bulleted
23822 lists. When HIDDEN is non-nil, don't display the HTML buffer.
23823 EXT-PLIST is a property list with external parameters overriding
23824 org-mode's default settings, but still inferior to file-local
23825 settings. When TO-BUFFER is non-nil, create a buffer with that
23826 name and export to that buffer. If TO-BUFFER is the symbol `string',
23827 don't leave any buffer behind but just return the resulting HTML as
23828 a string. When BODY-ONLY is set, don't produce the file header and footer,
23829 simply return the content of <body>...</body>, without even
23830 the body tags themselves."
23831 (interactive "P")
23833 ;; Make sure we have a file name when we need it.
23834 (when (and (not (or to-buffer body-only))
23835 (not buffer-file-name))
23836 (if (buffer-base-buffer)
23837 (org-set-local 'buffer-file-name
23838 (with-current-buffer (buffer-base-buffer)
23839 buffer-file-name))
23840 (error "Need a file name to be able to export.")))
23842 (message "Exporting...")
23843 (setq-default org-todo-line-regexp org-todo-line-regexp)
23844 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
23845 (setq-default org-done-keywords org-done-keywords)
23846 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
23847 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23848 ext-plist
23849 (org-infile-export-plist)))
23851 (style (plist-get opt-plist :style))
23852 (link-validate (plist-get opt-plist :link-validation-function))
23853 valid thetoc have-headings first-heading-pos
23854 (odd org-odd-levels-only)
23855 (region-p (org-region-active-p))
23856 (subtree-p
23857 (when region-p
23858 (save-excursion
23859 (goto-char (region-beginning))
23860 (and (org-at-heading-p)
23861 (>= (org-end-of-subtree t t) (region-end))))))
23862 ;; The following two are dynamically scoped into other
23863 ;; routines below.
23864 (org-current-export-dir (org-export-directory :html opt-plist))
23865 (org-current-export-file buffer-file-name)
23866 (level 0) (line "") (origline "") txt todo
23867 (umax nil)
23868 (umax-toc nil)
23869 (filename (if to-buffer nil
23870 (concat (file-name-as-directory
23871 (org-export-directory :html opt-plist))
23872 (file-name-sans-extension
23873 (or (and subtree-p
23874 (org-entry-get (region-beginning)
23875 "EXPORT_FILE_NAME" t))
23876 (file-name-nondirectory buffer-file-name)))
23877 "." org-export-html-extension)))
23878 (current-dir (if buffer-file-name
23879 (file-name-directory buffer-file-name)
23880 default-directory))
23881 (buffer (if to-buffer
23882 (cond
23883 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
23884 (t (get-buffer-create to-buffer)))
23885 (find-file-noselect filename)))
23886 (org-levels-open (make-vector org-level-max nil))
23887 (date (plist-get opt-plist :date))
23888 (author (plist-get opt-plist :author))
23889 (title (or (and subtree-p (org-export-get-title-from-subtree))
23890 (plist-get opt-plist :title)
23891 (and (not
23892 (plist-get opt-plist :skip-before-1st-heading))
23893 (org-export-grab-title-from-buffer))
23894 (and buffer-file-name
23895 (file-name-sans-extension
23896 (file-name-nondirectory buffer-file-name)))
23897 "UNTITLED"))
23898 (html-table-tag (plist-get opt-plist :html-table-tag))
23899 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23900 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
23901 (inquote nil)
23902 (infixed nil)
23903 (in-local-list nil)
23904 (local-list-num nil)
23905 (local-list-indent nil)
23906 (llt org-plain-list-ordered-item-terminator)
23907 (email (plist-get opt-plist :email))
23908 (language (plist-get opt-plist :language))
23909 (lang-words nil)
23910 (target-alist nil) tg
23911 (head-count 0) cnt
23912 (start 0)
23913 (coding-system (and (boundp 'buffer-file-coding-system)
23914 buffer-file-coding-system))
23915 (coding-system-for-write (or org-export-html-coding-system
23916 coding-system))
23917 (save-buffer-coding-system (or org-export-html-coding-system
23918 coding-system))
23919 (charset (and coding-system-for-write
23920 (fboundp 'coding-system-get)
23921 (coding-system-get coding-system-for-write
23922 'mime-charset)))
23923 (region
23924 (buffer-substring
23925 (if region-p (region-beginning) (point-min))
23926 (if region-p (region-end) (point-max))))
23927 (lines
23928 (org-split-string
23929 (org-cleaned-string-for-export
23930 region
23931 :emph-multiline t
23932 :for-html t
23933 :skip-before-1st-heading
23934 (plist-get opt-plist :skip-before-1st-heading)
23935 :drawers (plist-get opt-plist :drawers)
23936 :archived-trees
23937 (plist-get opt-plist :archived-trees)
23938 :add-text
23939 (plist-get opt-plist :text)
23940 :LaTeX-fragments
23941 (plist-get opt-plist :LaTeX-fragments))
23942 "[\r\n]"))
23943 table-open type
23944 table-buffer table-orig-buffer
23945 ind start-is-num starter didclose
23946 rpl path desc descp desc1 desc2 link
23949 (let ((inhibit-read-only t))
23950 (org-unmodified
23951 (remove-text-properties (point-min) (point-max)
23952 '(:org-license-to-kill t))))
23954 (message "Exporting...")
23956 (setq org-min-level (org-get-min-level lines))
23957 (setq org-last-level org-min-level)
23958 (org-init-section-numbers)
23960 (cond
23961 ((and date (string-match "%" date))
23962 (setq date (format-time-string date (current-time))))
23963 (date)
23964 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
23966 ;; Get the language-dependent settings
23967 (setq lang-words (or (assoc language org-export-language-setup)
23968 (assoc "en" org-export-language-setup)))
23970 ;; Switch to the output buffer
23971 (set-buffer buffer)
23972 (erase-buffer)
23973 (fundamental-mode)
23975 (and (fboundp 'set-buffer-file-coding-system)
23976 (set-buffer-file-coding-system coding-system-for-write))
23978 (let ((case-fold-search nil)
23979 (org-odd-levels-only odd))
23980 ;; create local variables for all options, to make sure all called
23981 ;; functions get the correct information
23982 (mapc (lambda (x)
23983 (set (make-local-variable (cdr x))
23984 (plist-get opt-plist (car x))))
23985 org-export-plist-vars)
23986 (setq umax (if arg (prefix-numeric-value arg)
23987 org-export-headline-levels))
23988 (setq umax-toc (if (integerp org-export-with-toc)
23989 (min org-export-with-toc umax)
23990 umax))
23991 (unless body-only
23992 ;; File header
23993 (insert (format
23994 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
23995 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
23996 <html xmlns=\"http://www.w3.org/1999/xhtml\"
23997 lang=\"%s\" xml:lang=\"%s\">
23998 <head>
23999 <title>%s</title>
24000 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24001 <meta name=\"generator\" content=\"Org-mode\"/>
24002 <meta name=\"generated\" content=\"%s\"/>
24003 <meta name=\"author\" content=\"%s\"/>
24005 </head><body>
24007 language language (org-html-expand title)
24008 (or charset "iso-8859-1") date author style))
24010 (insert (or (plist-get opt-plist :preamble) ""))
24012 (when (plist-get opt-plist :auto-preamble)
24013 (if title (insert (format org-export-html-title-format
24014 (org-html-expand title))))))
24016 (if (and org-export-with-toc (not body-only))
24017 (progn
24018 (push (format "<h%d>%s</h%d>\n"
24019 org-export-html-toplevel-hlevel
24020 (nth 3 lang-words)
24021 org-export-html-toplevel-hlevel)
24022 thetoc)
24023 (push "<ul>\n<li>" thetoc)
24024 (setq lines
24025 (mapcar '(lambda (line)
24026 (if (string-match org-todo-line-regexp line)
24027 ;; This is a headline
24028 (progn
24029 (setq have-headings t)
24030 (setq level (- (match-end 1) (match-beginning 1))
24031 level (org-tr-level level)
24032 txt (save-match-data
24033 (org-html-expand
24034 (org-export-cleanup-toc-line
24035 (match-string 3 line))))
24036 todo
24037 (or (and org-export-mark-todo-in-toc
24038 (match-beginning 2)
24039 (not (member (match-string 2 line)
24040 org-done-keywords)))
24041 ; TODO, not DONE
24042 (and org-export-mark-todo-in-toc
24043 (= level umax-toc)
24044 (org-search-todo-below
24045 line lines level))))
24046 (if (string-match
24047 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
24048 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
24049 (if (string-match quote-re0 txt)
24050 (setq txt (replace-match "" t t txt)))
24051 (if org-export-with-section-numbers
24052 (setq txt (concat (org-section-number level)
24053 " " txt)))
24054 (if (<= level (max umax umax-toc))
24055 (setq head-count (+ head-count 1)))
24056 (if (<= level umax-toc)
24057 (progn
24058 (if (> level org-last-level)
24059 (progn
24060 (setq cnt (- level org-last-level))
24061 (while (>= (setq cnt (1- cnt)) 0)
24062 (push "\n<ul>\n<li>" thetoc))
24063 (push "\n" thetoc)))
24064 (if (< level org-last-level)
24065 (progn
24066 (setq cnt (- org-last-level level))
24067 (while (>= (setq cnt (1- cnt)) 0)
24068 (push "</li>\n</ul>" thetoc))
24069 (push "\n" thetoc)))
24070 ;; Check for targets
24071 (while (string-match org-target-regexp line)
24072 (setq tg (match-string 1 line)
24073 line (replace-match
24074 (concat "@<span class=\"target\">" tg "@</span> ")
24075 t t line))
24076 (push (cons (org-solidify-link-text tg)
24077 (format "sec-%d" head-count))
24078 target-alist))
24079 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
24080 (setq txt (replace-match "" t t txt)))
24081 (push
24082 (format
24083 (if todo
24084 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
24085 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
24086 head-count txt) thetoc)
24088 (setq org-last-level level))
24090 line)
24091 lines))
24092 (while (> org-last-level (1- org-min-level))
24093 (setq org-last-level (1- org-last-level))
24094 (push "</li>\n</ul>\n" thetoc))
24095 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24097 (setq head-count 0)
24098 (org-init-section-numbers)
24100 (while (setq line (pop lines) origline line)
24101 (catch 'nextline
24103 ;; end of quote section?
24104 (when (and inquote (string-match "^\\*+ " line))
24105 (insert "</pre>\n")
24106 (setq inquote nil))
24107 ;; inside a quote section?
24108 (when inquote
24109 (insert (org-html-protect line) "\n")
24110 (throw 'nextline nil))
24112 ;; verbatim lines
24113 (when (and org-export-with-fixed-width
24114 (string-match "^[ \t]*:\\(.*\\)" line))
24115 (when (not infixed)
24116 (setq infixed t)
24117 (insert "<pre>\n"))
24118 (insert (org-html-protect (match-string 1 line)) "\n")
24119 (when (and lines
24120 (not (string-match "^[ \t]*\\(:.*\\)"
24121 (car lines))))
24122 (setq infixed nil)
24123 (insert "</pre>\n"))
24124 (throw 'nextline nil))
24126 ;; Protected HTML
24127 (when (get-text-property 0 'org-protected line)
24128 (let (par)
24129 (when (re-search-backward
24130 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
24131 (setq par (match-string 1))
24132 (replace-match "\\2\n"))
24133 (insert line "\n")
24134 (while (and lines
24135 (get-text-property 0 'org-protected (car lines)))
24136 (insert (pop lines) "\n"))
24137 (and par (insert "<p>\n")))
24138 (throw 'nextline nil))
24140 ;; Horizontal line
24141 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
24142 (insert "\n<hr/>\n")
24143 (throw 'nextline nil))
24145 ;; make targets to anchors
24146 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
24147 (cond
24148 ((match-end 2)
24149 (setq line (replace-match
24150 (concat "@<a name=\""
24151 (org-solidify-link-text (match-string 1 line))
24152 "\">\\nbsp@</a>")
24153 t t line)))
24154 ((and org-export-with-toc (equal (string-to-char line) ?*))
24155 (setq line (replace-match
24156 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
24157 ; (concat "@<i>" (match-string 1 line) "@</i> ")
24158 t t line)))
24160 (setq line (replace-match
24161 (concat "@<a name=\""
24162 (org-solidify-link-text (match-string 1 line))
24163 "\" class=\"target\">" (match-string 1 line) "@</a> ")
24164 t t line)))))
24166 (setq line (org-html-handle-time-stamps line))
24168 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
24169 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
24170 ;; Also handle sub_superscripts and checkboxes
24171 (or (string-match org-table-hline-regexp line)
24172 (setq line (org-html-expand line)))
24174 ;; Format the links
24175 (setq start 0)
24176 (while (string-match org-bracket-link-analytic-regexp line start)
24177 (setq start (match-beginning 0))
24178 (setq type (if (match-end 2) (match-string 2 line) "internal"))
24179 (setq path (match-string 3 line))
24180 (setq desc1 (if (match-end 5) (match-string 5 line))
24181 desc2 (if (match-end 2) (concat type ":" path) path)
24182 descp (and desc1 (not (equal desc1 desc2)))
24183 desc (or desc1 desc2))
24184 ;; Make an image out of the description if that is so wanted
24185 (when (and descp (org-file-image-p desc))
24186 (save-match-data
24187 (if (string-match "^file:" desc)
24188 (setq desc (substring desc (match-end 0)))))
24189 (setq desc (concat "<img src=\"" desc "\"/>")))
24190 ;; FIXME: do we need to unescape here somewhere?
24191 (cond
24192 ((equal type "internal")
24193 (setq rpl
24194 (concat
24195 "<a href=\"#"
24196 (org-solidify-link-text
24197 (save-match-data (org-link-unescape path)) target-alist)
24198 "\">" desc "</a>")))
24199 ((member type '("http" "https"))
24200 ;; standard URL, just check if we need to inline an image
24201 (if (and (or (eq t org-export-html-inline-images)
24202 (and org-export-html-inline-images (not descp)))
24203 (org-file-image-p path))
24204 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
24205 (setq link (concat type ":" path))
24206 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
24207 ((member type '("ftp" "mailto" "news"))
24208 ;; standard URL
24209 (setq link (concat type ":" path))
24210 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
24211 ((string= type "file")
24212 ;; FILE link
24213 (let* ((filename path)
24214 (abs-p (file-name-absolute-p filename))
24215 thefile file-is-image-p search)
24216 (save-match-data
24217 (if (string-match "::\\(.*\\)" filename)
24218 (setq search (match-string 1 filename)
24219 filename (replace-match "" t nil filename)))
24220 (setq valid
24221 (if (functionp link-validate)
24222 (funcall link-validate filename current-dir)
24224 (setq file-is-image-p (org-file-image-p filename))
24225 (setq thefile (if abs-p (expand-file-name filename) filename))
24226 (when (and org-export-html-link-org-files-as-html
24227 (string-match "\\.org$" thefile))
24228 (setq thefile (concat (substring thefile 0
24229 (match-beginning 0))
24230 "." org-export-html-extension))
24231 (if (and search
24232 ;; make sure this is can be used as target search
24233 (not (string-match "^[0-9]*$" search))
24234 (not (string-match "^\\*" search))
24235 (not (string-match "^/.*/$" search)))
24236 (setq thefile (concat thefile "#"
24237 (org-solidify-link-text
24238 (org-link-unescape search)))))
24239 (when (string-match "^file:" desc)
24240 (setq desc (replace-match "" t t desc))
24241 (if (string-match "\\.org$" desc)
24242 (setq desc (replace-match "" t t desc))))))
24243 (setq rpl (if (and file-is-image-p
24244 (or (eq t org-export-html-inline-images)
24245 (and org-export-html-inline-images
24246 (not descp))))
24247 (concat "<img src=\"" thefile "\"/>")
24248 (concat "<a href=\"" thefile "\">" desc "</a>")))
24249 (if (not valid) (setq rpl desc))))
24250 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
24251 (setq rpl (concat "<i>&lt;" type ":"
24252 (save-match-data (org-link-unescape path))
24253 "&gt;</i>"))))
24254 (setq line (replace-match rpl t t line)
24255 start (+ start (length rpl))))
24257 ;; TODO items
24258 (if (and (string-match org-todo-line-regexp line)
24259 (match-beginning 2))
24261 (setq line
24262 (concat (substring line 0 (match-beginning 2))
24263 "<span class=\""
24264 (if (member (match-string 2 line)
24265 org-done-keywords)
24266 "done" "todo")
24267 "\">" (match-string 2 line)
24268 "</span>" (substring line (match-end 2)))))
24270 ;; Does this contain a reference to a footnote?
24271 (when org-export-with-footnotes
24272 (setq start 0)
24273 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
24274 (if (get-text-property (match-beginning 2) 'org-protected line)
24275 (setq start (match-end 2))
24276 (let ((n (match-string 2 line)))
24277 (setq line
24278 (replace-match
24279 (format
24280 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
24281 (match-string 1 line) n n n)
24282 t t line))))))
24284 (cond
24285 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24286 ;; This is a headline
24287 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24288 txt (match-string 2 line))
24289 (if (string-match quote-re0 txt)
24290 (setq txt (replace-match "" t t txt)))
24291 (if (<= level (max umax umax-toc))
24292 (setq head-count (+ head-count 1)))
24293 (when in-local-list
24294 ;; Close any local lists before inserting a new header line
24295 (while local-list-num
24296 (org-close-li)
24297 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
24298 (pop local-list-num))
24299 (setq local-list-indent nil
24300 in-local-list nil))
24301 (setq first-heading-pos (or first-heading-pos (point)))
24302 (org-html-level-start level txt umax
24303 (and org-export-with-toc (<= level umax))
24304 head-count)
24305 ;; QUOTES
24306 (when (string-match quote-re line)
24307 (insert "<pre>")
24308 (setq inquote t)))
24310 ((and org-export-with-tables
24311 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24312 (if (not table-open)
24313 ;; New table starts
24314 (setq table-open t table-buffer nil table-orig-buffer nil))
24315 ;; Accumulate lines
24316 (setq table-buffer (cons line table-buffer)
24317 table-orig-buffer (cons origline table-orig-buffer))
24318 (when (or (not lines)
24319 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24320 (car lines))))
24321 (setq table-open nil
24322 table-buffer (nreverse table-buffer)
24323 table-orig-buffer (nreverse table-orig-buffer))
24324 (org-close-par-maybe)
24325 (insert (org-format-table-html table-buffer table-orig-buffer))))
24327 ;; Normal lines
24328 (when (string-match
24329 (cond
24330 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24331 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24332 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24333 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
24334 line)
24335 (setq ind (org-get-string-indentation line)
24336 start-is-num (match-beginning 4)
24337 starter (if (match-beginning 2)
24338 (substring (match-string 2 line) 0 -1))
24339 line (substring line (match-beginning 5)))
24340 (unless (string-match "[^ \t]" line)
24341 ;; empty line. Pretend indentation is large.
24342 (setq ind (if org-empty-line-terminates-plain-lists
24344 (1+ (or (car local-list-indent) 1)))))
24345 (setq didclose nil)
24346 (while (and in-local-list
24347 (or (and (= ind (car local-list-indent))
24348 (not starter))
24349 (< ind (car local-list-indent))))
24350 (setq didclose t)
24351 (org-close-li)
24352 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
24353 (pop local-list-num) (pop local-list-indent)
24354 (setq in-local-list local-list-indent))
24355 (cond
24356 ((and starter
24357 (or (not in-local-list)
24358 (> ind (car local-list-indent))))
24359 ;; Start new (level of) list
24360 (org-close-par-maybe)
24361 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
24362 (push start-is-num local-list-num)
24363 (push ind local-list-indent)
24364 (setq in-local-list t))
24365 (starter
24366 ;; continue current list
24367 (org-close-li)
24368 (insert "<li>\n"))
24369 (didclose
24370 ;; we did close a list, normal text follows: need <p>
24371 (org-open-par)))
24372 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
24373 (setq line
24374 (replace-match
24375 (if (equal (match-string 1 line) "X")
24376 "<b>[X]</b>"
24377 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
24378 t t line))))
24380 ;; Empty lines start a new paragraph. If hand-formatted lists
24381 ;; are not fully interpreted, lines starting with "-", "+", "*"
24382 ;; also start a new paragraph.
24383 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
24385 ;; Is this the start of a footnote?
24386 (when org-export-with-footnotes
24387 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
24388 (org-close-par-maybe)
24389 (let ((n (match-string 1 line)))
24390 (setq line (replace-match
24391 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
24393 ;; Check if the line break needs to be conserved
24394 (cond
24395 ((string-match "\\\\\\\\[ \t]*$" line)
24396 (setq line (replace-match "<br/>" t t line)))
24397 (org-export-preserve-breaks
24398 (setq line (concat line "<br/>"))))
24400 (insert line "\n")))))
24402 ;; Properly close all local lists and other lists
24403 (when inquote (insert "</pre>\n"))
24404 (when in-local-list
24405 ;; Close any local lists before inserting a new header line
24406 (while local-list-num
24407 (org-close-li)
24408 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
24409 (pop local-list-num))
24410 (setq local-list-indent nil
24411 in-local-list nil))
24412 (org-html-level-start 1 nil umax
24413 (and org-export-with-toc (<= level umax))
24414 head-count)
24416 (unless body-only
24417 (when (plist-get opt-plist :auto-postamble)
24418 (insert "<div id=\"postamble\">")
24419 (when (and org-export-author-info author)
24420 (insert "<p class=\"author\"> "
24421 (nth 1 lang-words) ": " author "\n")
24422 (when email
24423 (if (listp (split-string email ",+ *"))
24424 (mapc (lambda(e)
24425 (insert "<a href=\"mailto:" e "\">&lt;"
24426 e "&gt;</a>\n"))
24427 (split-string email ",+ *"))
24428 (insert "<a href=\"mailto:" email "\">&lt;"
24429 email "&gt;</a>\n")))
24430 (insert "</p>\n"))
24431 (when (and date org-export-time-stamp-file)
24432 (insert "<p class=\"date\"> "
24433 (nth 2 lang-words) ": "
24434 date "</p>\n"))
24435 (insert "</div>"))
24437 (if org-export-html-with-timestamp
24438 (insert org-export-html-html-helper-timestamp))
24439 (insert (or (plist-get opt-plist :postamble) ""))
24440 (insert "</body>\n</html>\n"))
24442 (normal-mode)
24443 (if (eq major-mode default-major-mode) (html-mode))
24445 ;; insert the table of contents
24446 (goto-char (point-min))
24447 (when thetoc
24448 (if (or (re-search-forward
24449 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
24450 (re-search-forward
24451 "\\[TABLE-OF-CONTENTS\\]" nil t))
24452 (progn
24453 (goto-char (match-beginning 0))
24454 (replace-match ""))
24455 (goto-char first-heading-pos)
24456 (when (looking-at "\\s-*</p>")
24457 (goto-char (match-end 0))
24458 (insert "\n")))
24459 (insert "<div id=\"table-of-contents\">\n")
24460 (mapc 'insert thetoc)
24461 (insert "</div>\n"))
24462 ;; remove empty paragraphs and lists
24463 (goto-char (point-min))
24464 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
24465 (replace-match ""))
24466 (goto-char (point-min))
24467 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
24468 (replace-match ""))
24469 ;; Convert whitespace place holders
24470 (goto-char (point-min))
24471 (let (beg end n)
24472 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24473 (setq n (get-text-property beg 'org-whitespace)
24474 end (next-single-property-change beg 'org-whitespace))
24475 (goto-char beg)
24476 (delete-region beg end)
24477 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
24478 (make-string n ?x)))))
24480 (or to-buffer (save-buffer))
24481 (goto-char (point-min))
24482 (message "Exporting... done")
24483 (if (eq to-buffer 'string)
24484 (prog1 (buffer-substring (point-min) (point-max))
24485 (kill-buffer (current-buffer)))
24486 (current-buffer)))))
24488 (defvar org-table-colgroup-info nil)
24489 (defun org-format-table-ascii (lines)
24490 "Format a table for ascii export."
24491 (if (stringp lines)
24492 (setq lines (org-split-string lines "\n")))
24493 (if (not (string-match "^[ \t]*|" (car lines)))
24494 ;; Table made by table.el - test for spanning
24495 lines
24497 ;; A normal org table
24498 ;; Get rid of hlines at beginning and end
24499 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24500 (setq lines (nreverse lines))
24501 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24502 (setq lines (nreverse lines))
24503 (when org-export-table-remove-special-lines
24504 ;; Check if the table has a marking column. If yes remove the
24505 ;; column and the special lines
24506 (setq lines (org-table-clean-before-export lines)))
24507 ;; Get rid of the vertical lines except for grouping
24508 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
24509 rtn line vl1 start)
24510 (while (setq line (pop lines))
24511 (if (string-match org-table-hline-regexp line)
24512 (and (string-match "|\\(.*\\)|" line)
24513 (setq line (replace-match " \\1" t nil line)))
24514 (setq start 0 vl1 vl)
24515 (while (string-match "|" line start)
24516 (setq start (match-end 0))
24517 (or (pop vl1) (setq line (replace-match " " t t line)))))
24518 (push line rtn))
24519 (nreverse rtn))))
24521 (defun org-colgroup-info-to-vline-list (info)
24522 (let (vl new last)
24523 (while info
24524 (setq last new new (pop info))
24525 (if (or (memq last '(:end :startend))
24526 (memq new '(:start :startend)))
24527 (push t vl)
24528 (push nil vl)))
24529 (setq vl (nreverse vl))
24530 (and vl (setcar vl nil))
24531 vl))
24533 (defun org-format-table-html (lines olines)
24534 "Find out which HTML converter to use and return the HTML code."
24535 (if (stringp lines)
24536 (setq lines (org-split-string lines "\n")))
24537 (if (string-match "^[ \t]*|" (car lines))
24538 ;; A normal org table
24539 (org-format-org-table-html lines)
24540 ;; Table made by table.el - test for spanning
24541 (let* ((hlines (delq nil (mapcar
24542 (lambda (x)
24543 (if (string-match "^[ \t]*\\+-" x) x
24544 nil))
24545 lines)))
24546 (first (car hlines))
24547 (ll (and (string-match "\\S-+" first)
24548 (match-string 0 first)))
24549 (re (concat "^[ \t]*" (regexp-quote ll)))
24550 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
24551 hlines))))
24552 (if (and (not spanning)
24553 (not org-export-prefer-native-exporter-for-tables))
24554 ;; We can use my own converter with HTML conversions
24555 (org-format-table-table-html lines)
24556 ;; Need to use the code generator in table.el, with the original text.
24557 (org-format-table-table-html-using-table-generate-source olines)))))
24559 (defun org-format-org-table-html (lines &optional splice)
24560 "Format a table into HTML."
24561 ;; Get rid of hlines at beginning and end
24562 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24563 (setq lines (nreverse lines))
24564 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24565 (setq lines (nreverse lines))
24566 (when org-export-table-remove-special-lines
24567 ;; Check if the table has a marking column. If yes remove the
24568 ;; column and the special lines
24569 (setq lines (org-table-clean-before-export lines)))
24571 (let ((head (and org-export-highlight-first-table-line
24572 (delq nil (mapcar
24573 (lambda (x) (string-match "^[ \t]*|-" x))
24574 (cdr lines)))))
24575 (nlines 0) fnum i
24576 tbopen line fields html gr colgropen)
24577 (if splice (setq head nil))
24578 (unless splice (push (if head "<thead>" "<tbody>") html))
24579 (setq tbopen t)
24580 (while (setq line (pop lines))
24581 (catch 'next-line
24582 (if (string-match "^[ \t]*|-" line)
24583 (progn
24584 (unless splice
24585 (push (if head "</thead>" "</tbody>") html)
24586 (if lines (push "<tbody>" html) (setq tbopen nil)))
24587 (setq head nil) ;; head ends here, first time around
24588 ;; ignore this line
24589 (throw 'next-line t)))
24590 ;; Break the line into fields
24591 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24592 (unless fnum (setq fnum (make-vector (length fields) 0)))
24593 (setq nlines (1+ nlines) i -1)
24594 (push (concat "<tr>"
24595 (mapconcat
24596 (lambda (x)
24597 (setq i (1+ i))
24598 (if (and (< i nlines)
24599 (string-match org-table-number-regexp x))
24600 (incf (aref fnum i)))
24601 (if head
24602 (concat (car org-export-table-header-tags) x
24603 (cdr org-export-table-header-tags))
24604 (concat (car org-export-table-data-tags) x
24605 (cdr org-export-table-data-tags))))
24606 fields "")
24607 "</tr>")
24608 html)))
24609 (unless splice (if tbopen (push "</tbody>" html)))
24610 (unless splice (push "</table>\n" html))
24611 (setq html (nreverse html))
24612 (unless splice
24613 ;; Put in col tags with the alignment (unfortuntely often ignored...)
24614 (push (mapconcat
24615 (lambda (x)
24616 (setq gr (pop org-table-colgroup-info))
24617 (format "%s<col align=\"%s\"></col>%s"
24618 (if (memq gr '(:start :startend))
24619 (prog1
24620 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
24621 (setq colgropen t))
24623 (if (> (/ (float x) nlines) org-table-number-fraction)
24624 "right" "left")
24625 (if (memq gr '(:end :startend))
24626 (progn (setq colgropen nil) "</colgroup>")
24627 "")))
24628 fnum "")
24629 html)
24630 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
24631 (push html-table-tag html))
24632 (concat (mapconcat 'identity html "\n") "\n")))
24634 (defun org-table-clean-before-export (lines)
24635 "Check if the table has a marking column.
24636 If yes remove the column and the special lines."
24637 (setq org-table-colgroup-info nil)
24638 (if (memq nil
24639 (mapcar
24640 (lambda (x) (or (string-match "^[ \t]*|-" x)
24641 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
24642 lines))
24643 (progn
24644 (setq org-table-clean-did-remove-column nil)
24645 (delq nil
24646 (mapcar
24647 (lambda (x)
24648 (cond
24649 ((string-match "^[ \t]*| */ *|" x)
24650 (setq org-table-colgroup-info
24651 (mapcar (lambda (x)
24652 (cond ((member x '("<" "&lt;")) :start)
24653 ((member x '(">" "&gt;")) :end)
24654 ((member x '("<>" "&lt;&gt;")) :startend)
24655 (t nil)))
24656 (org-split-string x "[ \t]*|[ \t]*")))
24657 nil)
24658 (t x)))
24659 lines)))
24660 (setq org-table-clean-did-remove-column t)
24661 (delq nil
24662 (mapcar
24663 (lambda (x)
24664 (cond
24665 ((string-match "^[ \t]*| */ *|" x)
24666 (setq org-table-colgroup-info
24667 (mapcar (lambda (x)
24668 (cond ((member x '("<" "&lt;")) :start)
24669 ((member x '(">" "&gt;")) :end)
24670 ((member x '("<>" "&lt;&gt;")) :startend)
24671 (t nil)))
24672 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
24673 nil)
24674 ((string-match "^[ \t]*| *[!_^/] *|" x)
24675 nil) ; ignore this line
24676 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
24677 (string-match "^\\([ \t]*\\)|[^|]*|" x))
24678 ;; remove the first column
24679 (replace-match "\\1|" t nil x))))
24680 lines))))
24682 (defun org-format-table-table-html (lines)
24683 "Format a table generated by table.el into HTML.
24684 This conversion does *not* use `table-generate-source' from table.el.
24685 This has the advantage that Org-mode's HTML conversions can be used.
24686 But it has the disadvantage, that no cell- or row-spanning is allowed."
24687 (let (line field-buffer
24688 (head org-export-highlight-first-table-line)
24689 fields html empty)
24690 (setq html (concat html-table-tag "\n"))
24691 (while (setq line (pop lines))
24692 (setq empty "&nbsp;")
24693 (catch 'next-line
24694 (if (string-match "^[ \t]*\\+-" line)
24695 (progn
24696 (if field-buffer
24697 (progn
24698 (setq
24699 html
24700 (concat
24701 html
24702 "<tr>"
24703 (mapconcat
24704 (lambda (x)
24705 (if (equal x "") (setq x empty))
24706 (if head
24707 (concat (car org-export-table-header-tags) x
24708 (cdr org-export-table-header-tags))
24709 (concat (car org-export-table-data-tags) x
24710 (cdr org-export-table-data-tags))))
24711 field-buffer "\n")
24712 "</tr>\n"))
24713 (setq head nil)
24714 (setq field-buffer nil)))
24715 ;; Ignore this line
24716 (throw 'next-line t)))
24717 ;; Break the line into fields and store the fields
24718 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24719 (if field-buffer
24720 (setq field-buffer (mapcar
24721 (lambda (x)
24722 (concat x "<br/>" (pop fields)))
24723 field-buffer))
24724 (setq field-buffer fields))))
24725 (setq html (concat html "</table>\n"))
24726 html))
24728 (defun org-format-table-table-html-using-table-generate-source (lines)
24729 "Format a table into html, using `table-generate-source' from table.el.
24730 This has the advantage that cell- or row-spanning is allowed.
24731 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
24732 (require 'table)
24733 (with-current-buffer (get-buffer-create " org-tmp1 ")
24734 (erase-buffer)
24735 (insert (mapconcat 'identity lines "\n"))
24736 (goto-char (point-min))
24737 (if (not (re-search-forward "|[^+]" nil t))
24738 (error "Error processing table"))
24739 (table-recognize-table)
24740 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
24741 (table-generate-source 'html " org-tmp2 ")
24742 (set-buffer " org-tmp2 ")
24743 (buffer-substring (point-min) (point-max))))
24745 (defun org-html-handle-time-stamps (s)
24746 "Format time stamps in string S, or remove them."
24747 (catch 'exit
24748 (let (r b)
24749 (while (string-match org-maybe-keyword-time-regexp s)
24750 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
24751 ;; never export CLOCK
24752 (throw 'exit ""))
24753 (or b (setq b (substring s 0 (match-beginning 0))))
24754 (if (not org-export-with-timestamps)
24755 (setq r (concat r (substring s 0 (match-beginning 0)))
24756 s (substring s (match-end 0)))
24757 (setq r (concat
24758 r (substring s 0 (match-beginning 0))
24759 (if (match-end 1)
24760 (format "@<span class=\"timestamp-kwd\">%s @</span>"
24761 (match-string 1 s)))
24762 (format " @<span class=\"timestamp\">%s@</span>"
24763 (substring
24764 (org-translate-time (match-string 3 s)) 1 -1)))
24765 s (substring s (match-end 0)))))
24766 ;; Line break if line started and ended with time stamp stuff
24767 (if (not r)
24769 (setq r (concat r s))
24770 (unless (string-match "\\S-" (concat b s))
24771 (setq r (concat r "@<br/>")))
24772 r))))
24774 (defun org-html-protect (s)
24775 ;; convert & to &amp;, < to &lt; and > to &gt;
24776 (let ((start 0))
24777 (while (string-match "&" s start)
24778 (setq s (replace-match "&amp;" t t s)
24779 start (1+ (match-beginning 0))))
24780 (while (string-match "<" s)
24781 (setq s (replace-match "&lt;" t t s)))
24782 (while (string-match ">" s)
24783 (setq s (replace-match "&gt;" t t s))))
24786 (defun org-export-cleanup-toc-line (s)
24787 "Remove tags and time staps from lines going into the toc."
24788 (when (memq org-export-with-tags '(not-in-toc nil))
24789 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
24790 (setq s (replace-match "" t t s))))
24791 (when org-export-remove-timestamps-from-toc
24792 (while (string-match org-maybe-keyword-time-regexp s)
24793 (setq s (replace-match "" t t s))))
24794 (while (string-match org-bracket-link-regexp s)
24795 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
24796 t t s)))
24799 (defun org-html-expand (string)
24800 "Prepare STRING for HTML export. Applies all active conversions.
24801 If there are links in the string, don't modify these."
24802 (let* ((re (concat org-bracket-link-regexp "\\|"
24803 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
24804 m s l res)
24805 (while (setq m (string-match re string))
24806 (setq s (substring string 0 m)
24807 l (match-string 0 string)
24808 string (substring string (match-end 0)))
24809 (push (org-html-do-expand s) res)
24810 (push l res))
24811 (push (org-html-do-expand string) res)
24812 (apply 'concat (nreverse res))))
24814 (defun org-html-do-expand (s)
24815 "Apply all active conversions to translate special ASCII to HTML."
24816 (setq s (org-html-protect s))
24817 (if org-export-html-expand
24818 (let ((start 0))
24819 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
24820 (setq s (replace-match "<\\1>" t nil s)))))
24821 (if org-export-with-emphasize
24822 (setq s (org-export-html-convert-emphasize s)))
24823 (if org-export-with-special-strings
24824 (setq s (org-export-html-convert-special-strings s)))
24825 (if org-export-with-sub-superscripts
24826 (setq s (org-export-html-convert-sub-super s)))
24827 (if org-export-with-TeX-macros
24828 (let ((start 0) wd ass)
24829 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
24830 (if (get-text-property (match-beginning 0) 'org-protected s)
24831 (setq start (match-end 0))
24832 (setq wd (match-string 1 s))
24833 (if (setq ass (assoc wd org-html-entities))
24834 (setq s (replace-match (or (cdr ass)
24835 (concat "&" (car ass) ";"))
24836 t t s))
24837 (setq start (+ start (length wd))))))))
24840 (defun org-create-multibrace-regexp (left right n)
24841 "Create a regular expression which will match a balanced sexp.
24842 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
24843 as single character strings.
24844 The regexp returned will match the entire expression including the
24845 delimiters. It will also define a single group which contains the
24846 match except for the outermost delimiters. The maximum depth of
24847 stacked delimiters is N. Escaping delimiters is not possible."
24848 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
24849 (or "\\|")
24850 (re nothing)
24851 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
24852 (while (> n 1)
24853 (setq n (1- n)
24854 re (concat re or next)
24855 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
24856 (concat left "\\(" re "\\)" right)))
24858 (defvar org-match-substring-regexp
24859 (concat
24860 "\\([^\\]\\)\\([_^]\\)\\("
24861 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
24862 "\\|"
24863 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
24864 "\\|"
24865 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
24866 "The regular expression matching a sub- or superscript.")
24868 (defvar org-match-substring-with-braces-regexp
24869 (concat
24870 "\\([^\\]\\)\\([_^]\\)\\("
24871 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
24872 "\\)")
24873 "The regular expression matching a sub- or superscript, forcing braces.")
24875 (defconst org-export-html-special-string-regexps
24876 '(("\\\\-" . "&shy;")
24877 ("---\\([^-]\\)" . "&mdash;\\1")
24878 ("--\\([^-]\\)" . "&ndash;\\1")
24879 ("\\.\\.\\." . "&hellip;"))
24880 "Regular expressions for special string conversion.")
24882 (defun org-export-html-convert-special-strings (string)
24883 "Convert special characters in STRING to HTML."
24884 (let ((all org-export-html-special-string-regexps)
24885 e a re rpl start)
24886 (while (setq a (pop all))
24887 (setq re (car a) rpl (cdr a) start 0)
24888 (while (string-match re string start)
24889 (if (get-text-property (match-beginning 0) 'org-protected string)
24890 (setq start (match-end 0))
24891 (setq string (replace-match rpl t nil string)))))
24892 string))
24894 (defun org-export-html-convert-sub-super (string)
24895 "Convert sub- and superscripts in STRING to HTML."
24896 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
24897 (while (string-match org-match-substring-regexp string s)
24898 (cond
24899 ((and requireb (match-end 8)) (setq s (match-end 2)))
24900 ((get-text-property (match-beginning 2) 'org-protected string)
24901 (setq s (match-end 2)))
24903 (setq s (match-end 1)
24904 key (if (string= (match-string 2 string) "_") "sub" "sup")
24905 c (or (match-string 8 string)
24906 (match-string 6 string)
24907 (match-string 5 string))
24908 string (replace-match
24909 (concat (match-string 1 string)
24910 "<" key ">" c "</" key ">")
24911 t t string)))))
24912 (while (string-match "\\\\\\([_^]\\)" string)
24913 (setq string (replace-match (match-string 1 string) t t string)))
24914 string))
24916 (defun org-export-html-convert-emphasize (string)
24917 "Apply emphasis."
24918 (let ((s 0) rpl)
24919 (while (string-match org-emph-re string s)
24920 (if (not (equal
24921 (substring string (match-beginning 3) (1+ (match-beginning 3)))
24922 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
24923 (setq s (match-beginning 0)
24925 (concat
24926 (match-string 1 string)
24927 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
24928 (match-string 4 string)
24929 (nth 3 (assoc (match-string 3 string)
24930 org-emphasis-alist))
24931 (match-string 5 string))
24932 string (replace-match rpl t t string)
24933 s (+ s (- (length rpl) 2)))
24934 (setq s (1+ s))))
24935 string))
24937 (defvar org-par-open nil)
24938 (defun org-open-par ()
24939 "Insert <p>, but first close previous paragraph if any."
24940 (org-close-par-maybe)
24941 (insert "\n<p>")
24942 (setq org-par-open t))
24943 (defun org-close-par-maybe ()
24944 "Close paragraph if there is one open."
24945 (when org-par-open
24946 (insert "</p>")
24947 (setq org-par-open nil)))
24948 (defun org-close-li ()
24949 "Close <li> if necessary."
24950 (org-close-par-maybe)
24951 (insert "</li>\n"))
24953 (defvar body-only) ; dynamically scoped into this.
24954 (defun org-html-level-start (level title umax with-toc head-count)
24955 "Insert a new level in HTML export.
24956 When TITLE is nil, just close all open levels."
24957 (org-close-par-maybe)
24958 (let ((l org-level-max))
24959 (while (>= l level)
24960 (if (aref org-levels-open (1- l))
24961 (progn
24962 (org-html-level-close l umax)
24963 (aset org-levels-open (1- l) nil)))
24964 (setq l (1- l)))
24965 (when title
24966 ;; If title is nil, this means this function is called to close
24967 ;; all levels, so the rest is done only if title is given
24968 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24969 (setq title (replace-match
24970 (if org-export-with-tags
24971 (save-match-data
24972 (concat
24973 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
24974 (mapconcat 'identity (org-split-string
24975 (match-string 1 title) ":")
24976 "&nbsp;")
24977 "</span>"))
24979 t t title)))
24980 (if (> level umax)
24981 (progn
24982 (if (aref org-levels-open (1- level))
24983 (progn
24984 (org-close-li)
24985 (insert "<li>" title "<br/>\n"))
24986 (aset org-levels-open (1- level) t)
24987 (org-close-par-maybe)
24988 (insert "<ul>\n<li>" title "<br/>\n")))
24989 (aset org-levels-open (1- level) t)
24990 (if (and org-export-with-section-numbers (not body-only))
24991 (setq title (concat (org-section-number level) " " title)))
24992 (setq level (+ level org-export-html-toplevel-hlevel -1))
24993 (if with-toc
24994 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
24995 level level head-count title level))
24996 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
24997 (org-open-par)))))
24999 (defun org-html-level-close (level max-outline-level)
25000 "Terminate one level in HTML export."
25001 (if (<= level max-outline-level)
25002 (insert "</div>\n")
25003 (org-close-li)
25004 (insert "</ul>\n")))
25006 ;;; iCalendar export
25008 ;;;###autoload
25009 (defun org-export-icalendar-this-file ()
25010 "Export current file as an iCalendar file.
25011 The iCalendar file will be located in the same directory as the Org-mode
25012 file, but with extension `.ics'."
25013 (interactive)
25014 (org-export-icalendar nil buffer-file-name))
25016 ;;;###autoload
25017 (defun org-export-icalendar-all-agenda-files ()
25018 "Export all files in `org-agenda-files' to iCalendar .ics files.
25019 Each iCalendar file will be located in the same directory as the Org-mode
25020 file, but with extension `.ics'."
25021 (interactive)
25022 (apply 'org-export-icalendar nil (org-agenda-files t)))
25024 ;;;###autoload
25025 (defun org-export-icalendar-combine-agenda-files ()
25026 "Export all files in `org-agenda-files' to a single combined iCalendar file.
25027 The file is stored under the name `org-combined-agenda-icalendar-file'."
25028 (interactive)
25029 (apply 'org-export-icalendar t (org-agenda-files t)))
25031 (defun org-export-icalendar (combine &rest files)
25032 "Create iCalendar files for all elements of FILES.
25033 If COMBINE is non-nil, combine all calendar entries into a single large
25034 file and store it under the name `org-combined-agenda-icalendar-file'."
25035 (save-excursion
25036 (org-prepare-agenda-buffers files)
25037 (let* ((dir (org-export-directory
25038 :ical (list :publishing-directory
25039 org-export-publishing-directory)))
25040 file ical-file ical-buffer category started org-agenda-new-buffers)
25042 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
25043 (when combine
25044 (setq ical-file
25045 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
25046 org-combined-agenda-icalendar-file
25047 (expand-file-name org-combined-agenda-icalendar-file dir))
25048 ical-buffer (org-get-agenda-file-buffer ical-file))
25049 (set-buffer ical-buffer) (erase-buffer))
25050 (while (setq file (pop files))
25051 (catch 'nextfile
25052 (org-check-agenda-file file)
25053 (set-buffer (org-get-agenda-file-buffer file))
25054 (unless combine
25055 (setq ical-file (concat (file-name-as-directory dir)
25056 (file-name-sans-extension
25057 (file-name-nondirectory buffer-file-name))
25058 ".ics"))
25059 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
25060 (with-current-buffer ical-buffer (erase-buffer)))
25061 (setq category (or org-category
25062 (file-name-sans-extension
25063 (file-name-nondirectory buffer-file-name))))
25064 (if (symbolp category) (setq category (symbol-name category)))
25065 (let ((standard-output ical-buffer))
25066 (if combine
25067 (and (not started) (setq started t)
25068 (org-start-icalendar-file org-icalendar-combined-name))
25069 (org-start-icalendar-file category))
25070 (org-print-icalendar-entries combine)
25071 (when (or (and combine (not files)) (not combine))
25072 (org-finish-icalendar-file)
25073 (set-buffer ical-buffer)
25074 (save-buffer)
25075 (run-hooks 'org-after-save-iCalendar-file-hook)))))
25076 (org-release-buffers org-agenda-new-buffers))))
25078 (defvar org-after-save-iCalendar-file-hook nil
25079 "Hook run after an iCalendar file has been saved.
25080 The iCalendar buffer is still current when this hook is run.
25081 A good way to use this is to tell a desktop calenndar application to re-read
25082 the iCalendar file.")
25084 (defun org-print-icalendar-entries (&optional combine)
25085 "Print iCalendar entries for the current Org-mode file to `standard-output'.
25086 When COMBINE is non nil, add the category to each line."
25087 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
25088 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
25089 (dts (org-ical-ts-to-string
25090 (format-time-string (cdr org-time-stamp-formats) (current-time))
25091 "DTSTART"))
25092 hd ts ts2 state status (inc t) pos b sexp rrule
25093 scheduledp deadlinep tmp pri category entry location summary desc
25094 (sexp-buffer (get-buffer-create "*ical-tmp*")))
25095 (org-refresh-category-properties)
25096 (save-excursion
25097 (goto-char (point-min))
25098 (while (re-search-forward re1 nil t)
25099 (catch :skip
25100 (org-agenda-skip)
25101 (setq pos (match-beginning 0)
25102 ts (match-string 0)
25103 inc t
25104 hd (org-get-heading)
25105 summary (org-icalendar-cleanup-string
25106 (org-entry-get nil "SUMMARY"))
25107 desc (org-icalendar-cleanup-string
25108 (or (org-entry-get nil "DESCRIPTION")
25109 (and org-icalendar-include-body (org-get-entry)))
25110 t org-icalendar-include-body)
25111 location (org-icalendar-cleanup-string
25112 (org-entry-get nil "LOCATION"))
25113 category (org-get-category))
25114 (if (looking-at re2)
25115 (progn
25116 (goto-char (match-end 0))
25117 (setq ts2 (match-string 1) inc nil))
25118 (setq tmp (buffer-substring (max (point-min)
25119 (- pos org-ds-keyword-length))
25120 pos)
25121 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
25122 (progn
25123 (setq inc nil)
25124 (replace-match "\\1" t nil ts))
25126 deadlinep (string-match org-deadline-regexp tmp)
25127 scheduledp (string-match org-scheduled-regexp tmp)
25128 ;; donep (org-entry-is-done-p)
25130 (if (or (string-match org-tr-regexp hd)
25131 (string-match org-ts-regexp hd))
25132 (setq hd (replace-match "" t t hd)))
25133 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
25134 (setq rrule
25135 (concat "\nRRULE:FREQ="
25136 (cdr (assoc
25137 (match-string 2 ts)
25138 '(("d" . "DAILY")("w" . "WEEKLY")
25139 ("m" . "MONTHLY")("y" . "YEARLY"))))
25140 ";INTERVAL=" (match-string 1 ts)))
25141 (setq rrule ""))
25142 (setq summary (or summary hd))
25143 (if (string-match org-bracket-link-regexp summary)
25144 (setq summary
25145 (replace-match (if (match-end 3)
25146 (match-string 3 summary)
25147 (match-string 1 summary))
25148 t t summary)))
25149 (if deadlinep (setq summary (concat "DL: " summary)))
25150 (if scheduledp (setq summary (concat "S: " summary)))
25151 (if (string-match "\\`<%%" ts)
25152 (with-current-buffer sexp-buffer
25153 (insert (substring ts 1 -1) " " summary "\n"))
25154 (princ (format "BEGIN:VEVENT
25156 %s%s
25157 SUMMARY:%s%s%s
25158 CATEGORIES:%s
25159 END:VEVENT\n"
25160 (org-ical-ts-to-string ts "DTSTART")
25161 (org-ical-ts-to-string ts2 "DTEND" inc)
25162 rrule summary
25163 (if (and desc (string-match "\\S-" desc))
25164 (concat "\nDESCRIPTION: " desc) "")
25165 (if (and location (string-match "\\S-" location))
25166 (concat "\nLOCATION: " location) "")
25167 category)))))
25169 (when (and org-icalendar-include-sexps
25170 (condition-case nil (require 'icalendar) (error nil))
25171 (fboundp 'icalendar-export-region))
25172 ;; Get all the literal sexps
25173 (goto-char (point-min))
25174 (while (re-search-forward "^&?%%(" nil t)
25175 (catch :skip
25176 (org-agenda-skip)
25177 (setq b (match-beginning 0))
25178 (goto-char (1- (match-end 0)))
25179 (forward-sexp 1)
25180 (end-of-line 1)
25181 (setq sexp (buffer-substring b (point)))
25182 (with-current-buffer sexp-buffer
25183 (insert sexp "\n"))
25184 (princ (org-diary-to-ical-string sexp-buffer)))))
25186 (when org-icalendar-include-todo
25187 (goto-char (point-min))
25188 (while (re-search-forward org-todo-line-regexp nil t)
25189 (catch :skip
25190 (org-agenda-skip)
25191 (setq state (match-string 2))
25192 (setq status (if (member state org-done-keywords)
25193 "COMPLETED" "NEEDS-ACTION"))
25194 (when (and state
25195 (or (not (member state org-done-keywords))
25196 (eq org-icalendar-include-todo 'all))
25197 (not (member org-archive-tag (org-get-tags-at)))
25199 (setq hd (match-string 3)
25200 summary (org-icalendar-cleanup-string
25201 (org-entry-get nil "SUMMARY"))
25202 desc (org-icalendar-cleanup-string
25203 (or (org-entry-get nil "DESCRIPTION")
25204 (and org-icalendar-include-body (org-get-entry)))
25205 t org-icalendar-include-body)
25206 location (org-icalendar-cleanup-string
25207 (org-entry-get nil "LOCATION")))
25208 (if (string-match org-bracket-link-regexp hd)
25209 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
25210 (match-string 1 hd))
25211 t t hd)))
25212 (if (string-match org-priority-regexp hd)
25213 (setq pri (string-to-char (match-string 2 hd))
25214 hd (concat (substring hd 0 (match-beginning 1))
25215 (substring hd (match-end 1))))
25216 (setq pri org-default-priority))
25217 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
25218 (- org-lowest-priority org-highest-priority))))))
25220 (princ (format "BEGIN:VTODO
25222 SUMMARY:%s%s%s
25223 CATEGORIES:%s
25224 SEQUENCE:1
25225 PRIORITY:%d
25226 STATUS:%s
25227 END:VTODO\n"
25229 (or summary hd)
25230 (if (and location (string-match "\\S-" location))
25231 (concat "\nLOCATION: " location) "")
25232 (if (and desc (string-match "\\S-" desc))
25233 (concat "\nDESCRIPTION: " desc) "")
25234 category pri status)))))))))
25236 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
25237 "Take out stuff and quote what needs to be quoted.
25238 When IS-BODY is non-nil, assume that this is the body of an item, clean up
25239 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
25240 characters."
25241 (if (not s)
25243 (when is-body
25244 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
25245 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
25246 (while (string-match re s) (setq s (replace-match "" t t s)))
25247 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
25248 (let ((start 0))
25249 (while (string-match "\\([,;\\]\\)" s start)
25250 (setq start (+ (match-beginning 0) 2)
25251 s (replace-match "\\\\\\1" nil nil s))))
25252 (when is-body
25253 (while (string-match "[ \t]*\n[ \t]*" s)
25254 (setq s (replace-match "\\n" t t s))))
25255 (setq s (org-trim s))
25256 (if is-body
25257 (if maxlength
25258 (if (and (numberp maxlength)
25259 (> (length s) maxlength))
25260 (setq s (substring s 0 maxlength)))))
25263 (defun org-get-entry ()
25264 "Clean-up description string."
25265 (save-excursion
25266 (org-back-to-heading t)
25267 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
25269 (defun org-start-icalendar-file (name)
25270 "Start an iCalendar file by inserting the header."
25271 (let ((user user-full-name)
25272 (name (or name "unknown"))
25273 (timezone (cadr (current-time-zone))))
25274 (princ
25275 (format "BEGIN:VCALENDAR
25276 VERSION:2.0
25277 X-WR-CALNAME:%s
25278 PRODID:-//%s//Emacs with Org-mode//EN
25279 X-WR-TIMEZONE:%s
25280 CALSCALE:GREGORIAN\n" name user timezone))))
25282 (defun org-finish-icalendar-file ()
25283 "Finish an iCalendar file by inserting the END statement."
25284 (princ "END:VCALENDAR\n"))
25286 (defun org-ical-ts-to-string (s keyword &optional inc)
25287 "Take a time string S and convert it to iCalendar format.
25288 KEYWORD is added in front, to make a complete line like DTSTART....
25289 When INC is non-nil, increase the hour by two (if time string contains
25290 a time), or the day by one (if it does not contain a time)."
25291 (let ((t1 (org-parse-time-string s 'nodefault))
25292 t2 fmt have-time time)
25293 (if (and (car t1) (nth 1 t1) (nth 2 t1))
25294 (setq t2 t1 have-time t)
25295 (setq t2 (org-parse-time-string s)))
25296 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
25297 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
25298 (when inc
25299 (if have-time
25300 (if org-agenda-default-appointment-duration
25301 (setq mi (+ org-agenda-default-appointment-duration mi))
25302 (setq h (+ 2 h)))
25303 (setq d (1+ d))))
25304 (setq time (encode-time s mi h d m y)))
25305 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
25306 (concat keyword (format-time-string fmt time))))
25308 ;;; XOXO export
25310 (defun org-export-as-xoxo-insert-into (buffer &rest output)
25311 (with-current-buffer buffer
25312 (apply 'insert output)))
25313 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
25315 (defun org-export-as-xoxo (&optional buffer)
25316 "Export the org buffer as XOXO.
25317 The XOXO buffer is named *xoxo-<source buffer name>*"
25318 (interactive (list (current-buffer)))
25319 ;; A quickie abstraction
25321 ;; Output everything as XOXO
25322 (with-current-buffer (get-buffer buffer)
25323 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
25324 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25325 (org-infile-export-plist)))
25326 (filename (concat (file-name-as-directory
25327 (org-export-directory :xoxo opt-plist))
25328 (file-name-sans-extension
25329 (file-name-nondirectory buffer-file-name))
25330 ".html"))
25331 (out (find-file-noselect filename))
25332 (last-level 1)
25333 (hanging-li nil))
25334 ;; Check the output buffer is empty.
25335 (with-current-buffer out (erase-buffer))
25336 ;; Kick off the output
25337 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
25338 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
25339 (let* ((hd (match-string-no-properties 1))
25340 (level (length hd))
25341 (text (concat
25342 (match-string-no-properties 2)
25343 (save-excursion
25344 (goto-char (match-end 0))
25345 (let ((str ""))
25346 (catch 'loop
25347 (while 't
25348 (forward-line)
25349 (if (looking-at "^[ \t]\\(.*\\)")
25350 (setq str (concat str (match-string-no-properties 1)))
25351 (throw 'loop str)))))))))
25353 ;; Handle level rendering
25354 (cond
25355 ((> level last-level)
25356 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
25358 ((< level last-level)
25359 (dotimes (- (- last-level level) 1)
25360 (if hanging-li
25361 (org-export-as-xoxo-insert-into out "</li>\n"))
25362 (org-export-as-xoxo-insert-into out "</ol>\n"))
25363 (when hanging-li
25364 (org-export-as-xoxo-insert-into out "</li>\n")
25365 (setq hanging-li nil)))
25367 ((equal level last-level)
25368 (if hanging-li
25369 (org-export-as-xoxo-insert-into out "</li>\n")))
25372 (setq last-level level)
25374 ;; And output the new li
25375 (setq hanging-li 't)
25376 (if (equal ?+ (elt text 0))
25377 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
25378 (org-export-as-xoxo-insert-into out "<li>" text))))
25380 ;; Finally finish off the ol
25381 (dotimes (- last-level 1)
25382 (if hanging-li
25383 (org-export-as-xoxo-insert-into out "</li>\n"))
25384 (org-export-as-xoxo-insert-into out "</ol>\n"))
25386 ;; Finish the buffer off and clean it up.
25387 (switch-to-buffer-other-window out)
25388 (indent-region (point-min) (point-max) nil)
25389 (save-buffer)
25390 (goto-char (point-min))
25394 ;;;; Key bindings
25396 ;; Make `C-c C-x' a prefix key
25397 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
25399 ;; TAB key with modifiers
25400 (org-defkey org-mode-map "\C-i" 'org-cycle)
25401 (org-defkey org-mode-map [(tab)] 'org-cycle)
25402 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
25403 (org-defkey org-mode-map [(meta tab)] 'org-complete)
25404 (org-defkey org-mode-map "\M-\t" 'org-complete)
25405 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
25406 ;; The following line is necessary under Suse GNU/Linux
25407 (unless (featurep 'xemacs)
25408 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
25409 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
25410 (define-key org-mode-map [backtab] 'org-shifttab)
25412 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
25413 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
25414 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
25416 ;; Cursor keys with modifiers
25417 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
25418 (org-defkey org-mode-map [(meta right)] 'org-metaright)
25419 (org-defkey org-mode-map [(meta up)] 'org-metaup)
25420 (org-defkey org-mode-map [(meta down)] 'org-metadown)
25422 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
25423 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
25424 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
25425 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
25427 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
25428 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
25429 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
25430 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
25432 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
25433 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
25435 ;;; Extra keys for tty access.
25436 ;; We only set them when really needed because otherwise the
25437 ;; menus don't show the simple keys
25439 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
25440 (not window-system))
25441 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
25442 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
25443 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
25444 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
25445 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
25446 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
25447 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
25448 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
25449 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
25450 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
25451 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
25452 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
25453 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
25454 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
25455 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
25456 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
25457 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
25458 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
25459 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
25460 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
25461 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
25462 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
25464 ;; All the other keys
25466 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
25467 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
25468 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
25469 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
25470 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
25471 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
25472 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
25473 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
25474 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
25475 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
25476 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
25477 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
25478 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
25479 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
25480 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
25481 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
25482 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
25483 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
25484 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
25485 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
25486 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
25487 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
25488 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
25489 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
25490 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
25491 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
25492 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
25493 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
25494 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
25495 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
25496 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
25497 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
25498 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
25499 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
25500 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
25501 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
25502 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
25503 (org-defkey org-mode-map "\C-c^" 'org-sort)
25504 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
25505 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
25506 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
25507 (org-defkey org-mode-map "\C-m" 'org-return)
25508 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
25509 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
25510 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
25511 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
25512 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
25513 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
25514 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
25515 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
25516 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
25517 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
25518 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
25519 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
25520 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
25521 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
25522 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
25523 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
25525 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
25526 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
25527 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
25528 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
25530 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
25531 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
25532 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
25533 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
25534 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
25535 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
25536 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
25537 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
25538 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
25539 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
25540 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
25541 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
25543 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
25545 (when (featurep 'xemacs)
25546 (org-defkey org-mode-map 'button3 'popup-mode-menu))
25548 (defsubst org-table-p () (org-at-table-p))
25550 (defun org-self-insert-command (N)
25551 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
25552 If the cursor is in a table looking at whitespace, the whitespace is
25553 overwritten, and the table is not marked as requiring realignment."
25554 (interactive "p")
25555 (if (and (org-table-p)
25556 (progn
25557 ;; check if we blank the field, and if that triggers align
25558 (and org-table-auto-blank-field
25559 (member last-command
25560 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
25561 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
25562 ;; got extra space, this field does not determine column width
25563 (let (org-table-may-need-update) (org-table-blank-field))
25564 ;; no extra space, this field may determine column width
25565 (org-table-blank-field)))
25567 (eq N 1)
25568 (looking-at "[^|\n]* |"))
25569 (let (org-table-may-need-update)
25570 (goto-char (1- (match-end 0)))
25571 (delete-backward-char 1)
25572 (goto-char (match-beginning 0))
25573 (self-insert-command N))
25574 (setq org-table-may-need-update t)
25575 (self-insert-command N)
25576 (org-fix-tags-on-the-fly)))
25578 (defun org-fix-tags-on-the-fly ()
25579 (when (and (equal (char-after (point-at-bol)) ?*)
25580 (org-on-heading-p))
25581 (org-align-tags-here org-tags-column)))
25583 (defun org-delete-backward-char (N)
25584 "Like `delete-backward-char', insert whitespace at field end in tables.
25585 When deleting backwards, in tables this function will insert whitespace in
25586 front of the next \"|\" separator, to keep the table aligned. The table will
25587 still be marked for re-alignment if the field did fill the entire column,
25588 because, in this case the deletion might narrow the column."
25589 (interactive "p")
25590 (if (and (org-table-p)
25591 (eq N 1)
25592 (string-match "|" (buffer-substring (point-at-bol) (point)))
25593 (looking-at ".*?|"))
25594 (let ((pos (point))
25595 (noalign (looking-at "[^|\n\r]* |"))
25596 (c org-table-may-need-update))
25597 (backward-delete-char N)
25598 (skip-chars-forward "^|")
25599 (insert " ")
25600 (goto-char (1- pos))
25601 ;; noalign: if there were two spaces at the end, this field
25602 ;; does not determine the width of the column.
25603 (if noalign (setq org-table-may-need-update c)))
25604 (backward-delete-char N)
25605 (org-fix-tags-on-the-fly)))
25607 (defun org-delete-char (N)
25608 "Like `delete-char', but insert whitespace at field end in tables.
25609 When deleting characters, in tables this function will insert whitespace in
25610 front of the next \"|\" separator, to keep the table aligned. The table will
25611 still be marked for re-alignment if the field did fill the entire column,
25612 because, in this case the deletion might narrow the column."
25613 (interactive "p")
25614 (if (and (org-table-p)
25615 (not (bolp))
25616 (not (= (char-after) ?|))
25617 (eq N 1))
25618 (if (looking-at ".*?|")
25619 (let ((pos (point))
25620 (noalign (looking-at "[^|\n\r]* |"))
25621 (c org-table-may-need-update))
25622 (replace-match (concat
25623 (substring (match-string 0) 1 -1)
25624 " |"))
25625 (goto-char pos)
25626 ;; noalign: if there were two spaces at the end, this field
25627 ;; does not determine the width of the column.
25628 (if noalign (setq org-table-may-need-update c)))
25629 (delete-char N))
25630 (delete-char N)
25631 (org-fix-tags-on-the-fly)))
25633 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
25634 (put 'org-self-insert-command 'delete-selection t)
25635 (put 'orgtbl-self-insert-command 'delete-selection t)
25636 (put 'org-delete-char 'delete-selection 'supersede)
25637 (put 'org-delete-backward-char 'delete-selection 'supersede)
25639 ;; Make `flyspell-mode' delay after some commands
25640 (put 'org-self-insert-command 'flyspell-delayed t)
25641 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
25642 (put 'org-delete-char 'flyspell-delayed t)
25643 (put 'org-delete-backward-char 'flyspell-delayed t)
25645 ;; Make pabbrev-mode expand after org-mode commands
25646 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
25647 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
25649 ;; How to do this: Measure non-white length of current string
25650 ;; If equal to column width, we should realign.
25652 (defun org-remap (map &rest commands)
25653 "In MAP, remap the functions given in COMMANDS.
25654 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
25655 (let (new old)
25656 (while commands
25657 (setq old (pop commands) new (pop commands))
25658 (if (fboundp 'command-remapping)
25659 (org-defkey map (vector 'remap old) new)
25660 (substitute-key-definition old new map global-map)))))
25662 (when (eq org-enable-table-editor 'optimized)
25663 ;; If the user wants maximum table support, we need to hijack
25664 ;; some standard editing functions
25665 (org-remap org-mode-map
25666 'self-insert-command 'org-self-insert-command
25667 'delete-char 'org-delete-char
25668 'delete-backward-char 'org-delete-backward-char)
25669 (org-defkey org-mode-map "|" 'org-force-self-insert))
25671 (defun org-shiftcursor-error ()
25672 "Throw an error because Shift-Cursor command was applied in wrong context."
25673 (error "This command is active in special context like tables, headlines or timestamps"))
25675 (defun org-shifttab (&optional arg)
25676 "Global visibility cycling or move to previous table field.
25677 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
25678 on context.
25679 See the individual commands for more information."
25680 (interactive "P")
25681 (cond
25682 ((org-at-table-p) (call-interactively 'org-table-previous-field))
25683 (arg (message "Content view to level: ")
25684 (org-content (prefix-numeric-value arg))
25685 (setq org-cycle-global-status 'overview))
25686 (t (call-interactively 'org-global-cycle))))
25688 (defun org-shiftmetaleft ()
25689 "Promote subtree or delete table column.
25690 Calls `org-promote-subtree', `org-outdent-item',
25691 or `org-table-delete-column', depending on context.
25692 See the individual commands for more information."
25693 (interactive)
25694 (cond
25695 ((org-at-table-p) (call-interactively 'org-table-delete-column))
25696 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
25697 ((org-at-item-p) (call-interactively 'org-outdent-item))
25698 (t (org-shiftcursor-error))))
25700 (defun org-shiftmetaright ()
25701 "Demote subtree or insert table column.
25702 Calls `org-demote-subtree', `org-indent-item',
25703 or `org-table-insert-column', depending on context.
25704 See the individual commands for more information."
25705 (interactive)
25706 (cond
25707 ((org-at-table-p) (call-interactively 'org-table-insert-column))
25708 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
25709 ((org-at-item-p) (call-interactively 'org-indent-item))
25710 (t (org-shiftcursor-error))))
25712 (defun org-shiftmetaup (&optional arg)
25713 "Move subtree up or kill table row.
25714 Calls `org-move-subtree-up' or `org-table-kill-row' or
25715 `org-move-item-up' depending on context. See the individual commands
25716 for more information."
25717 (interactive "P")
25718 (cond
25719 ((org-at-table-p) (call-interactively 'org-table-kill-row))
25720 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
25721 ((org-at-item-p) (call-interactively 'org-move-item-up))
25722 (t (org-shiftcursor-error))))
25723 (defun org-shiftmetadown (&optional arg)
25724 "Move subtree down or insert table row.
25725 Calls `org-move-subtree-down' or `org-table-insert-row' or
25726 `org-move-item-down', depending on context. See the individual
25727 commands for more information."
25728 (interactive "P")
25729 (cond
25730 ((org-at-table-p) (call-interactively 'org-table-insert-row))
25731 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
25732 ((org-at-item-p) (call-interactively 'org-move-item-down))
25733 (t (org-shiftcursor-error))))
25735 (defun org-metaleft (&optional arg)
25736 "Promote heading or move table column to left.
25737 Calls `org-do-promote' or `org-table-move-column', depending on context.
25738 With no specific context, calls the Emacs default `backward-word'.
25739 See the individual commands for more information."
25740 (interactive "P")
25741 (cond
25742 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
25743 ((or (org-on-heading-p) (org-region-active-p))
25744 (call-interactively 'org-do-promote))
25745 ((org-at-item-p) (call-interactively 'org-outdent-item))
25746 (t (call-interactively 'backward-word))))
25748 (defun org-metaright (&optional arg)
25749 "Demote subtree or move table column to right.
25750 Calls `org-do-demote' or `org-table-move-column', depending on context.
25751 With no specific context, calls the Emacs default `forward-word'.
25752 See the individual commands for more information."
25753 (interactive "P")
25754 (cond
25755 ((org-at-table-p) (call-interactively 'org-table-move-column))
25756 ((or (org-on-heading-p) (org-region-active-p))
25757 (call-interactively 'org-do-demote))
25758 ((org-at-item-p) (call-interactively 'org-indent-item))
25759 (t (call-interactively 'forward-word))))
25761 (defun org-metaup (&optional arg)
25762 "Move subtree up or move table row up.
25763 Calls `org-move-subtree-up' or `org-table-move-row' or
25764 `org-move-item-up', depending on context. See the individual commands
25765 for more information."
25766 (interactive "P")
25767 (cond
25768 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
25769 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
25770 ((org-at-item-p) (call-interactively 'org-move-item-up))
25771 (t (transpose-lines 1) (beginning-of-line -1))))
25773 (defun org-metadown (&optional arg)
25774 "Move subtree down or move table row down.
25775 Calls `org-move-subtree-down' or `org-table-move-row' or
25776 `org-move-item-down', depending on context. See the individual
25777 commands for more information."
25778 (interactive "P")
25779 (cond
25780 ((org-at-table-p) (call-interactively 'org-table-move-row))
25781 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
25782 ((org-at-item-p) (call-interactively 'org-move-item-down))
25783 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
25785 (defun org-shiftup (&optional arg)
25786 "Increase item in timestamp or increase priority of current headline.
25787 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
25788 depending on context. See the individual commands for more information."
25789 (interactive "P")
25790 (cond
25791 ((org-at-timestamp-p t)
25792 (call-interactively (if org-edit-timestamp-down-means-later
25793 'org-timestamp-down 'org-timestamp-up)))
25794 ((org-on-heading-p) (call-interactively 'org-priority-up))
25795 ((org-at-item-p) (call-interactively 'org-previous-item))
25796 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
25798 (defun org-shiftdown (&optional arg)
25799 "Decrease item in timestamp or decrease priority of current headline.
25800 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
25801 depending on context. See the individual commands for more information."
25802 (interactive "P")
25803 (cond
25804 ((org-at-timestamp-p t)
25805 (call-interactively (if org-edit-timestamp-down-means-later
25806 'org-timestamp-up 'org-timestamp-down)))
25807 ((org-on-heading-p) (call-interactively 'org-priority-down))
25808 (t (call-interactively 'org-next-item))))
25810 (defun org-shiftright ()
25811 "Next TODO keyword or timestamp one day later, depending on context."
25812 (interactive)
25813 (cond
25814 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
25815 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
25816 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
25817 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
25818 (t (org-shiftcursor-error))))
25820 (defun org-shiftleft ()
25821 "Previous TODO keyword or timestamp one day earlier, depending on context."
25822 (interactive)
25823 (cond
25824 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
25825 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
25826 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
25827 ((org-at-property-p)
25828 (call-interactively 'org-property-previous-allowed-value))
25829 (t (org-shiftcursor-error))))
25831 (defun org-shiftcontrolright ()
25832 "Switch to next TODO set."
25833 (interactive)
25834 (cond
25835 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
25836 (t (org-shiftcursor-error))))
25838 (defun org-shiftcontrolleft ()
25839 "Switch to previous TODO set."
25840 (interactive)
25841 (cond
25842 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
25843 (t (org-shiftcursor-error))))
25845 (defun org-ctrl-c-ret ()
25846 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
25847 (interactive)
25848 (cond
25849 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
25850 (t (call-interactively 'org-insert-heading))))
25852 (defun org-copy-special ()
25853 "Copy region in table or copy current subtree.
25854 Calls `org-table-copy' or `org-copy-subtree', depending on context.
25855 See the individual commands for more information."
25856 (interactive)
25857 (call-interactively
25858 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
25860 (defun org-cut-special ()
25861 "Cut region in table or cut current subtree.
25862 Calls `org-table-copy' or `org-cut-subtree', depending on context.
25863 See the individual commands for more information."
25864 (interactive)
25865 (call-interactively
25866 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
25868 (defun org-paste-special (arg)
25869 "Paste rectangular region into table, or past subtree relative to level.
25870 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
25871 See the individual commands for more information."
25872 (interactive "P")
25873 (if (org-at-table-p)
25874 (org-table-paste-rectangle)
25875 (org-paste-subtree arg)))
25877 (defun org-ctrl-c-ctrl-c (&optional arg)
25878 "Set tags in headline, or update according to changed information at point.
25880 This command does many different things, depending on context:
25882 - If the cursor is in a headline, prompt for tags and insert them
25883 into the current line, aligned to `org-tags-column'. When called
25884 with prefix arg, realign all tags in the current buffer.
25886 - If the cursor is in one of the special #+KEYWORD lines, this
25887 triggers scanning the buffer for these lines and updating the
25888 information.
25890 - If the cursor is inside a table, realign the table. This command
25891 works even if the automatic table editor has been turned off.
25893 - If the cursor is on a #+TBLFM line, re-apply the formulas to
25894 the entire table.
25896 - If the cursor is a the beginning of a dynamic block, update it.
25898 - If the cursor is inside a table created by the table.el package,
25899 activate that table.
25901 - If the current buffer is a remember buffer, close note and file it.
25902 with a prefix argument, file it without further interaction to the default
25903 location.
25905 - If the cursor is on a <<<target>>>, update radio targets and corresponding
25906 links in this buffer.
25908 - If the cursor is on a numbered item in a plain list, renumber the
25909 ordered list.
25911 - If the cursor is on a checkbox, toggle it."
25912 (interactive "P")
25913 (let ((org-enable-table-editor t))
25914 (cond
25915 ((or org-clock-overlays
25916 org-occur-highlights
25917 org-latex-fragment-image-overlays)
25918 (org-remove-clock-overlays)
25919 (org-remove-occur-highlights)
25920 (org-remove-latex-fragment-image-overlays)
25921 (message "Temporary highlights/overlays removed from current buffer"))
25922 ((and (local-variable-p 'org-finish-function (current-buffer))
25923 (fboundp org-finish-function))
25924 (funcall org-finish-function))
25925 ((org-at-property-p)
25926 (call-interactively 'org-property-action))
25927 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
25928 ((org-on-heading-p) (call-interactively 'org-set-tags))
25929 ((org-at-table.el-p)
25930 (require 'table)
25931 (beginning-of-line 1)
25932 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
25933 (call-interactively 'table-recognize-table))
25934 ((org-at-table-p)
25935 (org-table-maybe-eval-formula)
25936 (if arg
25937 (call-interactively 'org-table-recalculate)
25938 (org-table-maybe-recalculate-line))
25939 (call-interactively 'org-table-align))
25940 ((org-at-item-checkbox-p)
25941 (call-interactively 'org-toggle-checkbox))
25942 ((org-at-item-p)
25943 (call-interactively 'org-maybe-renumber-ordered-list))
25944 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
25945 ;; Dynamic block
25946 (beginning-of-line 1)
25947 (org-update-dblock))
25948 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
25949 (cond
25950 ((equal (match-string 1) "TBLFM")
25951 ;; Recalculate the table before this line
25952 (save-excursion
25953 (beginning-of-line 1)
25954 (skip-chars-backward " \r\n\t")
25955 (if (org-at-table-p)
25956 (org-call-with-arg 'org-table-recalculate t))))
25958 (call-interactively 'org-mode-restart))))
25959 (t (error "C-c C-c can do nothing useful at this location.")))))
25961 (defun org-mode-restart ()
25962 "Restart Org-mode, to scan again for special lines.
25963 Also updates the keyword regular expressions."
25964 (interactive)
25965 (let ((org-inhibit-startup t)) (org-mode))
25966 (message "Org-mode restarted to refresh keyword and special line setup"))
25968 (defun org-kill-note-or-show-branches ()
25969 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
25970 (interactive)
25971 (if (not org-finish-function)
25972 (call-interactively 'show-branches)
25973 (let ((org-note-abort t))
25974 (funcall org-finish-function))))
25976 (defun org-return ()
25977 "Goto next table row or insert a newline.
25978 Calls `org-table-next-row' or `newline', depending on context.
25979 See the individual commands for more information."
25980 (interactive)
25981 (cond
25982 ((bobp) (newline))
25983 ((org-at-table-p)
25984 (org-table-justify-field-maybe)
25985 (call-interactively 'org-table-next-row))
25986 (t (newline))))
25989 (defun org-ctrl-c-minus ()
25990 "Insert separator line in table or modify bullet type in list.
25991 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
25992 depending on context."
25993 (interactive)
25994 (cond
25995 ((org-at-table-p)
25996 (call-interactively 'org-table-insert-hline))
25997 ((org-on-heading-p)
25998 ;; Convert to item
25999 (save-excursion
26000 (beginning-of-line 1)
26001 (if (looking-at "\\*+ ")
26002 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26003 ((org-in-item-p)
26004 (call-interactively 'org-cycle-list-bullet))
26005 (t (error "`C-c -' does have no function here."))))
26007 (defun org-meta-return (&optional arg)
26008 "Insert a new heading or wrap a region in a table.
26009 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
26010 See the individual commands for more information."
26011 (interactive "P")
26012 (cond
26013 ((org-at-table-p)
26014 (call-interactively 'org-table-wrap-region))
26015 (t (call-interactively 'org-insert-heading))))
26017 ;;; Menu entries
26019 ;; Define the Org-mode menus
26020 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
26021 '("Tbl"
26022 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
26023 ["Next Field" org-cycle (org-at-table-p)]
26024 ["Previous Field" org-shifttab (org-at-table-p)]
26025 ["Next Row" org-return (org-at-table-p)]
26026 "--"
26027 ["Blank Field" org-table-blank-field (org-at-table-p)]
26028 ["Edit Field" org-table-edit-field (org-at-table-p)]
26029 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
26030 "--"
26031 ("Column"
26032 ["Move Column Left" org-metaleft (org-at-table-p)]
26033 ["Move Column Right" org-metaright (org-at-table-p)]
26034 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
26035 ["Insert Column" org-shiftmetaright (org-at-table-p)])
26036 ("Row"
26037 ["Move Row Up" org-metaup (org-at-table-p)]
26038 ["Move Row Down" org-metadown (org-at-table-p)]
26039 ["Delete Row" org-shiftmetaup (org-at-table-p)]
26040 ["Insert Row" org-shiftmetadown (org-at-table-p)]
26041 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
26042 "--"
26043 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
26044 ("Rectangle"
26045 ["Copy Rectangle" org-copy-special (org-at-table-p)]
26046 ["Cut Rectangle" org-cut-special (org-at-table-p)]
26047 ["Paste Rectangle" org-paste-special (org-at-table-p)]
26048 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
26049 "--"
26050 ("Calculate"
26051 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
26052 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
26053 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
26054 "--"
26055 ["Recalculate line" org-table-recalculate (org-at-table-p)]
26056 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
26057 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
26058 "--"
26059 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
26060 "--"
26061 ["Sum Column/Rectangle" org-table-sum
26062 (or (org-at-table-p) (org-region-active-p))]
26063 ["Which Column?" org-table-current-column (org-at-table-p)])
26064 ["Debug Formulas"
26065 org-table-toggle-formula-debugger
26066 :style toggle :selected org-table-formula-debug]
26067 ["Show Col/Row Numbers"
26068 org-table-toggle-coordinate-overlays
26069 :style toggle :selected org-table-overlay-coordinates]
26070 "--"
26071 ["Create" org-table-create (and (not (org-at-table-p))
26072 org-enable-table-editor)]
26073 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
26074 ["Import from File" org-table-import (not (org-at-table-p))]
26075 ["Export to File" org-table-export (org-at-table-p)]
26076 "--"
26077 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
26079 (easy-menu-define org-org-menu org-mode-map "Org menu"
26080 '("Org"
26081 ("Show/Hide"
26082 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
26083 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
26084 ["Sparse Tree" org-occur t]
26085 ["Reveal Context" org-reveal t]
26086 ["Show All" show-all t]
26087 "--"
26088 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
26089 "--"
26090 ["New Heading" org-insert-heading t]
26091 ("Navigate Headings"
26092 ["Up" outline-up-heading t]
26093 ["Next" outline-next-visible-heading t]
26094 ["Previous" outline-previous-visible-heading t]
26095 ["Next Same Level" outline-forward-same-level t]
26096 ["Previous Same Level" outline-backward-same-level t]
26097 "--"
26098 ["Jump" org-goto t])
26099 ("Edit Structure"
26100 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
26101 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
26102 "--"
26103 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
26104 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
26105 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
26106 "--"
26107 ["Promote Heading" org-metaleft (not (org-at-table-p))]
26108 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
26109 ["Demote Heading" org-metaright (not (org-at-table-p))]
26110 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
26111 "--"
26112 ["Sort Region/Children" org-sort (not (org-at-table-p))]
26113 "--"
26114 ["Convert to odd levels" org-convert-to-odd-levels t]
26115 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
26116 ("Editing"
26117 ["Emphasis..." org-emphasize t])
26118 ("Archive"
26119 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
26120 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
26121 ; :active t :keys "C-u C-c C-x C-a"]
26122 ["Sparse trees open ARCHIVE trees"
26123 (setq org-sparse-tree-open-archived-trees
26124 (not org-sparse-tree-open-archived-trees))
26125 :style toggle :selected org-sparse-tree-open-archived-trees]
26126 ["Cycling opens ARCHIVE trees"
26127 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
26128 :style toggle :selected org-cycle-open-archived-trees]
26129 ["Agenda includes ARCHIVE trees"
26130 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
26131 :style toggle :selected (not org-agenda-skip-archived-trees)]
26132 "--"
26133 ["Move Subtree to Archive" org-advertized-archive-subtree t]
26134 ; ["Check and Move Children" (org-archive-subtree '(4))
26135 ; :active t :keys "C-u C-c C-x C-s"]
26137 "--"
26138 ("TODO Lists"
26139 ["TODO/DONE/-" org-todo t]
26140 ("Select keyword"
26141 ["Next keyword" org-shiftright (org-on-heading-p)]
26142 ["Previous keyword" org-shiftleft (org-on-heading-p)]
26143 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
26144 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
26145 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
26146 ["Show TODO Tree" org-show-todo-tree t]
26147 ["Global TODO list" org-todo-list t]
26148 "--"
26149 ["Set Priority" org-priority t]
26150 ["Priority Up" org-shiftup t]
26151 ["Priority Down" org-shiftdown t])
26152 ("TAGS and Properties"
26153 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
26154 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
26155 "--"
26156 ["Set property" 'org-set-property t]
26157 ["Column view of properties" org-columns t]
26158 ["Insert Column View DBlock" org-insert-columns-dblock t])
26159 ("Dates and Scheduling"
26160 ["Timestamp" org-time-stamp t]
26161 ["Timestamp (inactive)" org-time-stamp-inactive t]
26162 ("Change Date"
26163 ["1 Day Later" org-shiftright t]
26164 ["1 Day Earlier" org-shiftleft t]
26165 ["1 ... Later" org-shiftup t]
26166 ["1 ... Earlier" org-shiftdown t])
26167 ["Compute Time Range" org-evaluate-time-range t]
26168 ["Schedule Item" org-schedule t]
26169 ["Deadline" org-deadline t]
26170 "--"
26171 ["Custom time format" org-toggle-time-stamp-overlays
26172 :style radio :selected org-display-custom-times]
26173 "--"
26174 ["Goto Calendar" org-goto-calendar t]
26175 ["Date from Calendar" org-date-from-calendar t])
26176 ("Logging work"
26177 ["Clock in" org-clock-in t]
26178 ["Clock out" org-clock-out t]
26179 ["Clock cancel" org-clock-cancel t]
26180 ["Goto running clock" org-clock-goto t]
26181 ["Display times" org-clock-display t]
26182 ["Create clock table" org-clock-report t]
26183 "--"
26184 ["Record DONE time"
26185 (progn (setq org-log-done (not org-log-done))
26186 (message "Switching to %s will %s record a timestamp"
26187 (car org-done-keywords)
26188 (if org-log-done "automatically" "not")))
26189 :style toggle :selected org-log-done])
26190 "--"
26191 ["Agenda Command..." org-agenda t]
26192 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
26193 ("File List for Agenda")
26194 ("Special views current file"
26195 ["TODO Tree" org-show-todo-tree t]
26196 ["Check Deadlines" org-check-deadlines t]
26197 ["Timeline" org-timeline t]
26198 ["Tags Tree" org-tags-sparse-tree t])
26199 "--"
26200 ("Hyperlinks"
26201 ["Store Link (Global)" org-store-link t]
26202 ["Insert Link" org-insert-link t]
26203 ["Follow Link" org-open-at-point t]
26204 "--"
26205 ["Next link" org-next-link t]
26206 ["Previous link" org-previous-link t]
26207 "--"
26208 ["Descriptive Links"
26209 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
26210 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
26211 ["Literal Links"
26212 (progn
26213 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
26214 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
26215 "--"
26216 ["Export/Publish..." org-export t]
26217 ("LaTeX"
26218 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
26219 :selected org-cdlatex-mode]
26220 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
26221 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
26222 ["Modify math symbol" org-cdlatex-math-modify
26223 (org-inside-LaTeX-fragment-p)]
26224 ["Export LaTeX fragments as images"
26225 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
26226 :style toggle :selected org-export-with-LaTeX-fragments])
26227 "--"
26228 ("Documentation"
26229 ["Show Version" org-version t]
26230 ["Info Documentation" org-info t])
26231 ("Customize"
26232 ["Browse Org Group" org-customize t]
26233 "--"
26234 ["Expand This Menu" org-create-customize-menu
26235 (fboundp 'customize-menu-create)])
26236 "--"
26237 ["Refresh setup" org-mode-restart t]
26240 (defun org-info (&optional node)
26241 "Read documentation for Org-mode in the info system.
26242 With optional NODE, go directly to that node."
26243 (interactive)
26244 (require 'info)
26245 (Info-goto-node (format "(org)%s" (or node ""))))
26247 (defun org-install-agenda-files-menu ()
26248 (let ((bl (buffer-list)))
26249 (save-excursion
26250 (while bl
26251 (set-buffer (pop bl))
26252 (if (org-mode-p) (setq bl nil)))
26253 (when (org-mode-p)
26254 (easy-menu-change
26255 '("Org") "File List for Agenda"
26256 (append
26257 (list
26258 ["Edit File List" (org-edit-agenda-file-list) t]
26259 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
26260 ["Remove Current File from List" org-remove-file t]
26261 ["Cycle through agenda files" org-cycle-agenda-files t]
26262 ["Occur in all agenda files" org-occur-in-agenda-files t]
26263 "--")
26264 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
26266 ;;;; Documentation
26268 (defun org-customize ()
26269 "Call the customize function with org as argument."
26270 (interactive)
26271 (customize-browse 'org))
26273 (defun org-create-customize-menu ()
26274 "Create a full customization menu for Org-mode, insert it into the menu."
26275 (interactive)
26276 (if (fboundp 'customize-menu-create)
26277 (progn
26278 (easy-menu-change
26279 '("Org") "Customize"
26280 `(["Browse Org group" org-customize t]
26281 "--"
26282 ,(customize-menu-create 'org)
26283 ["Set" Custom-set t]
26284 ["Save" Custom-save t]
26285 ["Reset to Current" Custom-reset-current t]
26286 ["Reset to Saved" Custom-reset-saved t]
26287 ["Reset to Standard Settings" Custom-reset-standard t]))
26288 (message "\"Org\"-menu now contains full customization menu"))
26289 (error "Cannot expand menu (outdated version of cus-edit.el)")))
26291 ;;;; Miscellaneous stuff
26294 ;;; Generally useful functions
26296 (defun org-context ()
26297 "Return a list of contexts of the current cursor position.
26298 If several contexts apply, all are returned.
26299 Each context entry is a list with a symbol naming the context, and
26300 two positions indicating start and end of the context. Possible
26301 contexts are:
26303 :headline anywhere in a headline
26304 :headline-stars on the leading stars in a headline
26305 :todo-keyword on a TODO keyword (including DONE) in a headline
26306 :tags on the TAGS in a headline
26307 :priority on the priority cookie in a headline
26308 :item on the first line of a plain list item
26309 :item-bullet on the bullet/number of a plain list item
26310 :checkbox on the checkbox in a plain list item
26311 :table in an org-mode table
26312 :table-special on a special filed in a table
26313 :table-table in a table.el table
26314 :link on a hyperlink
26315 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
26316 :target on a <<target>>
26317 :radio-target on a <<<radio-target>>>
26318 :latex-fragment on a LaTeX fragment
26319 :latex-preview on a LaTeX fragment with overlayed preview image
26321 This function expects the position to be visible because it uses font-lock
26322 faces as a help to recognize the following contexts: :table-special, :link,
26323 and :keyword."
26324 (let* ((f (get-text-property (point) 'face))
26325 (faces (if (listp f) f (list f)))
26326 (p (point)) clist o)
26327 ;; First the large context
26328 (cond
26329 ((org-on-heading-p t)
26330 (push (list :headline (point-at-bol) (point-at-eol)) clist)
26331 (when (progn
26332 (beginning-of-line 1)
26333 (looking-at org-todo-line-tags-regexp))
26334 (push (org-point-in-group p 1 :headline-stars) clist)
26335 (push (org-point-in-group p 2 :todo-keyword) clist)
26336 (push (org-point-in-group p 4 :tags) clist))
26337 (goto-char p)
26338 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
26339 (if (looking-at "\\[#[A-Z0-9]\\]")
26340 (push (org-point-in-group p 0 :priority) clist)))
26342 ((org-at-item-p)
26343 (push (org-point-in-group p 2 :item-bullet) clist)
26344 (push (list :item (point-at-bol)
26345 (save-excursion (org-end-of-item) (point)))
26346 clist)
26347 (and (org-at-item-checkbox-p)
26348 (push (org-point-in-group p 0 :checkbox) clist)))
26350 ((org-at-table-p)
26351 (push (list :table (org-table-begin) (org-table-end)) clist)
26352 (if (memq 'org-formula faces)
26353 (push (list :table-special
26354 (previous-single-property-change p 'face)
26355 (next-single-property-change p 'face)) clist)))
26356 ((org-at-table-p 'any)
26357 (push (list :table-table) clist)))
26358 (goto-char p)
26360 ;; Now the small context
26361 (cond
26362 ((org-at-timestamp-p)
26363 (push (org-point-in-group p 0 :timestamp) clist))
26364 ((memq 'org-link faces)
26365 (push (list :link
26366 (previous-single-property-change p 'face)
26367 (next-single-property-change p 'face)) clist))
26368 ((memq 'org-special-keyword faces)
26369 (push (list :keyword
26370 (previous-single-property-change p 'face)
26371 (next-single-property-change p 'face)) clist))
26372 ((org-on-target-p)
26373 (push (org-point-in-group p 0 :target) clist)
26374 (goto-char (1- (match-beginning 0)))
26375 (if (looking-at org-radio-target-regexp)
26376 (push (org-point-in-group p 0 :radio-target) clist))
26377 (goto-char p))
26378 ((setq o (car (delq nil
26379 (mapcar
26380 (lambda (x)
26381 (if (memq x org-latex-fragment-image-overlays) x))
26382 (org-overlays-at (point))))))
26383 (push (list :latex-fragment
26384 (org-overlay-start o) (org-overlay-end o)) clist)
26385 (push (list :latex-preview
26386 (org-overlay-start o) (org-overlay-end o)) clist))
26387 ((org-inside-LaTeX-fragment-p)
26388 ;; FIXME: positions wrong.
26389 (push (list :latex-fragment (point) (point)) clist)))
26391 (setq clist (nreverse (delq nil clist)))
26392 clist))
26394 ;; FIXME: Compare with at-regexp-p Do we need both?
26395 (defun org-in-regexp (re &optional nlines visually)
26396 "Check if point is inside a match of regexp.
26397 Normally only the current line is checked, but you can include NLINES extra
26398 lines both before and after point into the search.
26399 If VISUALLY is set, require that the cursor is not after the match but
26400 really on, so that the block visually is on the match."
26401 (catch 'exit
26402 (let ((pos (point))
26403 (eol (point-at-eol (+ 1 (or nlines 0))))
26404 (inc (if visually 1 0)))
26405 (save-excursion
26406 (beginning-of-line (- 1 (or nlines 0)))
26407 (while (re-search-forward re eol t)
26408 (if (and (<= (match-beginning 0) pos)
26409 (>= (+ inc (match-end 0)) pos))
26410 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
26412 (defun org-at-regexp-p (regexp)
26413 "Is point inside a match of REGEXP in the current line?"
26414 (catch 'exit
26415 (save-excursion
26416 (let ((pos (point)) (end (point-at-eol)))
26417 (beginning-of-line 1)
26418 (while (re-search-forward regexp end t)
26419 (if (and (<= (match-beginning 0) pos)
26420 (>= (match-end 0) pos))
26421 (throw 'exit t)))
26422 nil))))
26424 (defun org-occur-in-agenda-files (regexp &optional nlines)
26425 "Call `multi-occur' with buffers for all agenda files."
26426 (interactive "sOrg-files matching: \np")
26427 (let* ((files (org-agenda-files))
26428 (tnames (mapcar 'file-truename files))
26429 (extra org-agenda-multi-occur-extra-files)
26431 (while (setq f (pop extra))
26432 (unless (member (file-truename f) tnames)
26433 (add-to-list 'files f 'append)
26434 (add-to-list 'tnames (file-truename f) 'append)))
26435 (multi-occur
26436 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
26437 regexp)))
26439 (defun org-uniquify (list)
26440 "Remove duplicate elements from LIST."
26441 (let (res)
26442 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
26443 res))
26445 (defun org-delete-all (elts list)
26446 "Remove all elements in ELTS from LIST."
26447 (while elts
26448 (setq list (delete (pop elts) list)))
26449 list)
26451 (defun org-point-in-group (point group &optional context)
26452 "Check if POINT is in match-group GROUP.
26453 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
26454 match. If the match group does ot exist or point is not inside it,
26455 return nil."
26456 (and (match-beginning group)
26457 (>= point (match-beginning group))
26458 (<= point (match-end group))
26459 (if context
26460 (list context (match-beginning group) (match-end group))
26461 t)))
26463 (defun org-switch-to-buffer-other-window (&rest args)
26464 "Switch to buffer in a second window on the current frame.
26465 In particular, do not allow pop-up frames."
26466 (let (pop-up-frames special-display-buffer-names special-display-regexps
26467 special-display-function)
26468 (apply 'switch-to-buffer-other-window args)))
26470 (defun org-combine-plists (&rest plists)
26471 "Create a single property list from all plists in PLISTS.
26472 The process starts by copying the first list, and then setting properties
26473 from the other lists. Settings in the last list are the most significant
26474 ones and overrule settings in the other lists."
26475 (let ((rtn (copy-sequence (pop plists)))
26476 p v ls)
26477 (while plists
26478 (setq ls (pop plists))
26479 (while ls
26480 (setq p (pop ls) v (pop ls))
26481 (setq rtn (plist-put rtn p v))))
26482 rtn))
26484 (defun org-move-line-down (arg)
26485 "Move the current line down. With prefix argument, move it past ARG lines."
26486 (interactive "p")
26487 (let ((col (current-column))
26488 beg end pos)
26489 (beginning-of-line 1) (setq beg (point))
26490 (beginning-of-line 2) (setq end (point))
26491 (beginning-of-line (+ 1 arg))
26492 (setq pos (move-marker (make-marker) (point)))
26493 (insert (delete-and-extract-region beg end))
26494 (goto-char pos)
26495 (move-to-column col)))
26497 (defun org-move-line-up (arg)
26498 "Move the current line up. With prefix argument, move it past ARG lines."
26499 (interactive "p")
26500 (let ((col (current-column))
26501 beg end pos)
26502 (beginning-of-line 1) (setq beg (point))
26503 (beginning-of-line 2) (setq end (point))
26504 (beginning-of-line (- arg))
26505 (setq pos (move-marker (make-marker) (point)))
26506 (insert (delete-and-extract-region beg end))
26507 (goto-char pos)
26508 (move-to-column col)))
26510 (defun org-replace-escapes (string table)
26511 "Replace %-escapes in STRING with values in TABLE.
26512 TABLE is an association list with keys like \"%a\" and string values.
26513 The sequences in STRING may contain normal field width and padding information,
26514 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
26515 so values can contain further %-escapes if they are define later in TABLE."
26516 (let ((case-fold-search nil)
26517 e re rpl)
26518 (while (setq e (pop table))
26519 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
26520 (while (string-match re string)
26521 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
26522 (cdr e)))
26523 (setq string (replace-match rpl t t string))))
26524 string))
26527 (defun org-sublist (list start end)
26528 "Return a section of LIST, from START to END.
26529 Counting starts at 1."
26530 (let (rtn (c start))
26531 (setq list (nthcdr (1- start) list))
26532 (while (and list (<= c end))
26533 (push (pop list) rtn)
26534 (setq c (1+ c)))
26535 (nreverse rtn)))
26537 (defun org-find-base-buffer-visiting (file)
26538 "Like `find-buffer-visiting' but alway return the base buffer and
26539 not an indirect buffer"
26540 (let ((buf (find-buffer-visiting file)))
26541 (if buf
26542 (or (buffer-base-buffer buf) buf)
26543 nil)))
26545 (defun org-image-file-name-regexp ()
26546 "Return regexp matching the file names of images."
26547 (if (fboundp 'image-file-name-regexp)
26548 (image-file-name-regexp)
26549 (let ((image-file-name-extensions
26550 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
26551 "xbm" "xpm" "pbm" "pgm" "ppm")))
26552 (concat "\\."
26553 (regexp-opt (nconc (mapcar 'upcase
26554 image-file-name-extensions)
26555 image-file-name-extensions)
26557 "\\'"))))
26559 (defun org-file-image-p (file)
26560 "Return non-nil if FILE is an image."
26561 (save-match-data
26562 (string-match (org-image-file-name-regexp) file)))
26564 ;;; Paragraph filling stuff.
26565 ;; We want this to be just right, so use the full arsenal.
26567 (defun org-indent-line-function ()
26568 "Indent line like previous, but further if previous was headline or item."
26569 (interactive)
26570 (let* ((pos (point))
26571 (itemp (org-at-item-p))
26572 column bpos bcol tpos tcol bullet btype bullet-type)
26573 ;; Find the previous relevant line
26574 (beginning-of-line 1)
26575 (cond
26576 ((looking-at "#") (setq column 0))
26577 ((looking-at "\\*+ ") (setq column 0))
26579 (beginning-of-line 0)
26580 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
26581 (beginning-of-line 0))
26582 (cond
26583 ((looking-at "\\*+[ \t]+")
26584 (goto-char (match-end 0))
26585 (setq column (current-column)))
26586 ((org-in-item-p)
26587 (org-beginning-of-item)
26588 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26589 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
26590 (setq bpos (match-beginning 1) tpos (match-end 0)
26591 bcol (progn (goto-char bpos) (current-column))
26592 tcol (progn (goto-char tpos) (current-column))
26593 bullet (match-string 1)
26594 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
26595 (if (not itemp)
26596 (setq column tcol)
26597 (goto-char pos)
26598 (beginning-of-line 1)
26599 (if (looking-at "\\S-")
26600 (progn
26601 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26602 (setq bullet (match-string 1)
26603 btype (if (string-match "[0-9]" bullet) "n" bullet))
26604 (setq column (if (equal btype bullet-type) bcol tcol)))
26605 (setq column (org-get-indentation)))))
26606 (t (setq column (org-get-indentation))))))
26607 (goto-char pos)
26608 (if (<= (current-column) (current-indentation))
26609 (indent-line-to column)
26610 (save-excursion (indent-line-to column)))
26611 (setq column (current-column))
26612 (beginning-of-line 1)
26613 (if (looking-at
26614 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
26615 (replace-match (concat "\\1" (format org-property-format
26616 (match-string 2) (match-string 3)))
26617 t nil))
26618 (move-to-column column)))
26620 (defun org-set-autofill-regexps ()
26621 (interactive)
26622 ;; In the paragraph separator we include headlines, because filling
26623 ;; text in a line directly attached to a headline would otherwise
26624 ;; fill the headline as well.
26625 (org-set-local 'comment-start-skip "^#+[ \t]*")
26626 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
26627 ;; The paragraph starter includes hand-formatted lists.
26628 (org-set-local 'paragraph-start
26629 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
26630 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
26631 ;; But only if the user has not turned off tables or fixed-width regions
26632 (org-set-local
26633 'auto-fill-inhibit-regexp
26634 (concat "\\*+ \\|#\\+"
26635 "\\|[ \t]*" org-keyword-time-regexp
26636 (if (or org-enable-table-editor org-enable-fixed-width-editor)
26637 (concat
26638 "\\|[ \t]*["
26639 (if org-enable-table-editor "|" "")
26640 (if org-enable-fixed-width-editor ":" "")
26641 "]"))))
26642 ;; We use our own fill-paragraph function, to make sure that tables
26643 ;; and fixed-width regions are not wrapped. That function will pass
26644 ;; through to `fill-paragraph' when appropriate.
26645 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
26646 ; Adaptive filling: To get full control, first make sure that
26647 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
26648 (org-set-local 'adaptive-fill-regexp "\000")
26649 (org-set-local 'adaptive-fill-function
26650 'org-adaptive-fill-function))
26652 (defun org-fill-paragraph (&optional justify)
26653 "Re-align a table, pass through to fill-paragraph if no table."
26654 (let ((table-p (org-at-table-p))
26655 (table.el-p (org-at-table.el-p)))
26656 (cond ((and (equal (char-after (point-at-bol)) ?*)
26657 (save-excursion (goto-char (point-at-bol))
26658 (looking-at outline-regexp)))
26659 t) ; skip headlines
26660 (table.el-p t) ; skip table.el tables
26661 (table-p (org-table-align) t) ; align org-mode tables
26662 (t nil)))) ; call paragraph-fill
26664 ;; For reference, this is the default value of adaptive-fill-regexp
26665 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
26667 (defun org-adaptive-fill-function ()
26668 "Return a fill prefix for org-mode files.
26669 In particular, this makes sure hanging paragraphs for hand-formatted lists
26670 work correctly."
26671 (cond ((looking-at "#[ \t]+")
26672 (match-string 0))
26673 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
26674 (save-excursion
26675 (goto-char (match-end 0))
26676 (make-string (current-column) ?\ )))
26677 (t nil)))
26679 ;;;; Functions extending outline functionality
26681 (defun org-beginning-of-line (&optional arg)
26682 "Go to the beginning of the current line. If that is invisible, continue
26683 to a visible line beginning. This makes the function of C-a more intuitive.
26684 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26685 first attempt, and only move to after the tags when the cursor is already
26686 beyond the end of the headline."
26687 (interactive "P")
26688 (let ((pos (point)))
26689 (beginning-of-line 1)
26690 (if (bobp)
26692 (backward-char 1)
26693 (if (org-invisible-p)
26694 (while (and (not (bobp)) (org-invisible-p))
26695 (backward-char 1)
26696 (beginning-of-line 1))
26697 (forward-char 1)))
26698 (when org-special-ctrl-a/e
26699 (cond
26700 ((and (looking-at org-todo-line-regexp)
26701 (= (char-after (match-end 1)) ?\ ))
26702 (goto-char
26703 (if (eq org-special-ctrl-a/e t)
26704 (cond ((> pos (match-beginning 3)) (match-beginning 3))
26705 ((= pos (point)) (match-beginning 3))
26706 (t (point)))
26707 (cond ((> pos (point)) (point))
26708 ((not (eq last-command this-command)) (point))
26709 (t (match-beginning 3))))))
26710 ((org-at-item-p)
26711 (goto-char
26712 (if (eq org-special-ctrl-a/e t)
26713 (cond ((> pos (match-end 4)) (match-end 4))
26714 ((= pos (point)) (match-end 4))
26715 (t (point)))
26716 (cond ((> pos (point)) (point))
26717 ((not (eq last-command this-command)) (point))
26718 (t (match-end 4))))))))))
26720 (defun org-end-of-line (&optional arg)
26721 "Go to the end of the line.
26722 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26723 first attempt, and only move to after the tags when the cursor is already
26724 beyond the end of the headline."
26725 (interactive "P")
26726 (if (or (not org-special-ctrl-a/e)
26727 (not (org-on-heading-p)))
26728 (end-of-line arg)
26729 (let ((pos (point)))
26730 (beginning-of-line 1)
26731 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
26732 (if (eq org-special-ctrl-a/e t)
26733 (if (or (< pos (match-beginning 1))
26734 (= pos (match-end 0)))
26735 (goto-char (match-beginning 1))
26736 (goto-char (match-end 0)))
26737 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
26738 (goto-char (match-end 0))
26739 (goto-char (match-beginning 1))))
26740 (end-of-line arg)))))
26742 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
26743 (define-key org-mode-map "\C-e" 'org-end-of-line)
26745 (defun org-invisible-p ()
26746 "Check if point is at a character currently not visible."
26747 ;; Early versions of noutline don't have `outline-invisible-p'.
26748 (if (fboundp 'outline-invisible-p)
26749 (outline-invisible-p)
26750 (get-char-property (point) 'invisible)))
26752 (defun org-invisible-p2 ()
26753 "Check if point is at a character currently not visible."
26754 (save-excursion
26755 (if (and (eolp) (not (bobp))) (backward-char 1))
26756 ;; Early versions of noutline don't have `outline-invisible-p'.
26757 (if (fboundp 'outline-invisible-p)
26758 (outline-invisible-p)
26759 (get-char-property (point) 'invisible))))
26761 (defalias 'org-back-to-heading 'outline-back-to-heading)
26762 (defalias 'org-on-heading-p 'outline-on-heading-p)
26763 (defalias 'org-at-heading-p 'outline-on-heading-p)
26764 (defun org-at-heading-or-item-p ()
26765 (or (org-on-heading-p) (org-at-item-p)))
26767 (defun org-on-target-p ()
26768 (or (org-in-regexp org-radio-target-regexp)
26769 (org-in-regexp org-target-regexp)))
26771 (defun org-up-heading-all (arg)
26772 "Move to the heading line of which the present line is a subheading.
26773 This function considers both visible and invisible heading lines.
26774 With argument, move up ARG levels."
26775 (if (fboundp 'outline-up-heading-all)
26776 (outline-up-heading-all arg) ; emacs 21 version of outline.el
26777 (outline-up-heading arg t))) ; emacs 22 version of outline.el
26779 (defun org-up-heading-safe ()
26780 "Move to the heading line of which the present line is a subheading.
26781 This version will not throw an error. It will return the level of the
26782 headline found, or nil if no higher level is found."
26783 (let ((pos (point)) start-level level
26784 (re (concat "^" outline-regexp)))
26785 (catch 'exit
26786 (outline-back-to-heading t)
26787 (setq start-level (funcall outline-level))
26788 (if (equal start-level 1) (throw 'exit nil))
26789 (while (re-search-backward re nil t)
26790 (setq level (funcall outline-level))
26791 (if (< level start-level) (throw 'exit level)))
26792 nil)))
26794 (defun org-goto-sibling (&optional previous)
26795 "Goto the next sibling, even if it is invisible.
26796 When PREVIOUS is set, go to the previous sibling instead. Returns t
26797 when a sibling was found. When none is found, return nil and don't
26798 move point."
26799 (let ((fun (if previous 're-search-backward 're-search-forward))
26800 (pos (point))
26801 (re (concat "^" outline-regexp))
26802 level l)
26803 (when (condition-case nil (org-back-to-heading t) (error nil))
26804 (setq level (funcall outline-level))
26805 (catch 'exit
26806 (or previous (forward-char 1))
26807 (while (funcall fun re nil t)
26808 (setq l (funcall outline-level))
26809 (when (< l level) (goto-char pos) (throw 'exit nil))
26810 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
26811 (goto-char pos)
26812 nil))))
26814 (defun org-show-siblings ()
26815 "Show all siblings of the current headline."
26816 (save-excursion
26817 (while (org-goto-sibling) (org-flag-heading nil)))
26818 (save-excursion
26819 (while (org-goto-sibling 'previous)
26820 (org-flag-heading nil))))
26822 (defun org-show-hidden-entry ()
26823 "Show an entry where even the heading is hidden."
26824 (save-excursion
26825 (org-show-entry)))
26827 (defun org-flag-heading (flag &optional entry)
26828 "Flag the current heading. FLAG non-nil means make invisible.
26829 When ENTRY is non-nil, show the entire entry."
26830 (save-excursion
26831 (org-back-to-heading t)
26832 ;; Check if we should show the entire entry
26833 (if entry
26834 (progn
26835 (org-show-entry)
26836 (save-excursion
26837 (and (outline-next-heading)
26838 (org-flag-heading nil))))
26839 (outline-flag-region (max (point-min) (1- (point)))
26840 (save-excursion (outline-end-of-heading) (point))
26841 flag))))
26843 (defun org-end-of-subtree (&optional invisible-OK to-heading)
26844 ;; This is an exact copy of the original function, but it uses
26845 ;; `org-back-to-heading', to make it work also in invisible
26846 ;; trees. And is uses an invisible-OK argument.
26847 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
26848 (org-back-to-heading invisible-OK)
26849 (let ((first t)
26850 (level (funcall outline-level)))
26851 (while (and (not (eobp))
26852 (or first (> (funcall outline-level) level)))
26853 (setq first nil)
26854 (outline-next-heading))
26855 (unless to-heading
26856 (if (memq (preceding-char) '(?\n ?\^M))
26857 (progn
26858 ;; Go to end of line before heading
26859 (forward-char -1)
26860 (if (memq (preceding-char) '(?\n ?\^M))
26861 ;; leave blank line before heading
26862 (forward-char -1))))))
26863 (point))
26865 (defun org-show-subtree ()
26866 "Show everything after this heading at deeper levels."
26867 (outline-flag-region
26868 (point)
26869 (save-excursion
26870 (outline-end-of-subtree) (outline-next-heading) (point))
26871 nil))
26873 (defun org-show-entry ()
26874 "Show the body directly following this heading.
26875 Show the heading too, if it is currently invisible."
26876 (interactive)
26877 (save-excursion
26878 (condition-case nil
26879 (progn
26880 (org-back-to-heading t)
26881 (outline-flag-region
26882 (max (point-min) (1- (point)))
26883 (save-excursion
26884 (re-search-forward
26885 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
26886 (or (match-beginning 1) (point-max)))
26887 nil))
26888 (error nil))))
26890 (defun org-make-options-regexp (kwds)
26891 "Make a regular expression for keyword lines."
26892 (concat
26894 "#?[ \t]*\\+\\("
26895 (mapconcat 'regexp-quote kwds "\\|")
26896 "\\):[ \t]*"
26897 "\\(.+\\)"))
26899 ;; Make isearch reveal the necessary context
26900 (defun org-isearch-end ()
26901 "Reveal context after isearch exits."
26902 (when isearch-success ; only if search was successful
26903 (if (featurep 'xemacs)
26904 ;; Under XEmacs, the hook is run in the correct place,
26905 ;; we directly show the context.
26906 (org-show-context 'isearch)
26907 ;; In Emacs the hook runs *before* restoring the overlays.
26908 ;; So we have to use a one-time post-command-hook to do this.
26909 ;; (Emacs 22 has a special variable, see function `org-mode')
26910 (unless (and (boundp 'isearch-mode-end-hook-quit)
26911 isearch-mode-end-hook-quit)
26912 ;; Only when the isearch was not quitted.
26913 (org-add-hook 'post-command-hook 'org-isearch-post-command
26914 'append 'local)))))
26916 (defun org-isearch-post-command ()
26917 "Remove self from hook, and show context."
26918 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
26919 (org-show-context 'isearch))
26922 ;;;; Address problems with some other packages
26924 ;; Make flyspell not check words in links, to not mess up our keymap
26925 (defun org-mode-flyspell-verify ()
26926 "Don't let flyspell put overlays at active buttons."
26927 (not (get-text-property (point) 'keymap)))
26929 ;; Make `bookmark-jump' show the jump location if it was hidden.
26930 (eval-after-load "bookmark"
26931 '(if (boundp 'bookmark-after-jump-hook)
26932 ;; We can use the hook
26933 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
26934 ;; Hook not available, use advice
26935 (defadvice bookmark-jump (after org-make-visible activate)
26936 "Make the position visible."
26937 (org-bookmark-jump-unhide))))
26939 (defun org-bookmark-jump-unhide ()
26940 "Unhide the current position, to show the bookmark location."
26941 (and (org-mode-p)
26942 (or (org-invisible-p)
26943 (save-excursion (goto-char (max (point-min) (1- (point))))
26944 (org-invisible-p)))
26945 (org-show-context 'bookmark-jump)))
26947 ;; Fix a bug in htmlize where there are text properties (face nil)
26948 (eval-after-load "htmlize"
26949 '(progn
26950 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
26951 "Make sure there are no nil faces"
26952 (setq ad-return-value (delq nil ad-return-value)))))
26954 ;; Make session.el ignore our circular variable
26955 (eval-after-load "session"
26956 '(add-to-list 'session-globals-exclude 'org-mark-ring))
26958 ;;;; Experimental code
26960 (defun org-closed-in-range ()
26961 "Sparse tree of items closed in a certain time range.
26962 Still experimental, may disappear in the future."
26963 (interactive)
26964 ;; Get the time interval from the user.
26965 (let* ((time1 (time-to-seconds
26966 (org-read-date nil 'to-time nil "Starting date: ")))
26967 (time2 (time-to-seconds
26968 (org-read-date nil 'to-time nil "End date:")))
26969 ;; callback function
26970 (callback (lambda ()
26971 (let ((time
26972 (time-to-seconds
26973 (apply 'encode-time
26974 (org-parse-time-string
26975 (match-string 1))))))
26976 ;; check if time in interval
26977 (and (>= time time1) (<= time time2))))))
26978 ;; make tree, check each match with the callback
26979 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
26981 (defun org-fill-paragraph-experimental (&optional justify)
26982 "Re-align a table, pass through to fill-paragraph if no table."
26983 (let ((table-p (org-at-table-p))
26984 (table.el-p (org-at-table.el-p)))
26985 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
26986 (table.el-p t) ; skip table.el tables
26987 (table-p (org-table-align) t) ; align org-mode tables
26988 ((save-excursion
26989 (let ((pos (1+ (point-at-eol))))
26990 (backward-paragraph 1)
26991 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
26992 (save-excursion
26993 (save-restriction
26994 (narrow-to-region (1+ (match-end 0)) (point-max))
26995 (fill-paragraph nil)
26996 t)))
26997 (t nil)))) ; call paragraph-fill
26999 ;; FIXME: this needs a much better algorithm
27000 (defun org-assign-fast-keys (alist)
27001 "Assign fast keys to a keyword-key alist.
27002 Respect keys that are already there."
27003 (let (new e k c c1 c2 (char ?a))
27004 (while (setq e (pop alist))
27005 (cond
27006 ((equal e '(:startgroup)) (push e new))
27007 ((equal e '(:endgroup)) (push e new))
27009 (setq k (car e) c2 nil)
27010 (if (cdr e)
27011 (setq c (cdr e))
27012 ;; automatically assign a character.
27013 (setq c1 (string-to-char
27014 (downcase (substring
27015 k (if (= (string-to-char k) ?@) 1 0)))))
27016 (if (or (rassoc c1 new) (rassoc c1 alist))
27017 (while (or (rassoc char new) (rassoc char alist))
27018 (setq char (1+ char)))
27019 (setq c2 c1))
27020 (setq c (or c2 char)))
27021 (push (cons k c) new))))
27022 (nreverse new)))
27024 (defcustom org-refile-targets '((nil . (:level . 1)))
27025 "Targets for refiling entries with \\[org-refile].
27026 This is list of cons cells. Each cell contains:
27027 - a specification of the files to be considered, either a list of files,
27028 or a symbol whose function or value fields will be used to retrieve
27029 a file name or a list of file names. Nil means, refile to a different
27030 heading in the current buffer.
27031 - A specification of how to find candidate refile targets. This may be
27032 any of
27033 - a cons cell (:tag . \"TAG\") to identify refile targes by a tag.
27034 This tag has to be present in all target headlines, inheritance will
27035 not be considered.
27036 - a cons cell (:todo . \"KEYWORD\" to identify refile targets by
27037 todo keyword.
27038 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
27039 headlines that are refiling targets.
27040 - a cons cell (:level . N). Any headline of level N is considered a target."
27041 ;; FIXME: what if there are a var and func with same name???
27042 :group 'org
27043 :type '(repeat
27044 (cons
27045 (choice :value org-agenda-files
27046 (const :tag "All agenda files" org-agenda-files)
27047 (const :tag "Current buffer" nil)
27048 (function) (variable) (file))
27049 (choice :tag "Identify target headline by"
27050 (cons :tag "Specific tag" (const :tag) (string))
27051 (cons :tag "TODO keyword" (const :todo) (string))
27052 (cons :tag "Regular expression" (const :regexp) (regexp))
27053 (cons :tag "Level number" (const :level) (integer))))))
27055 (defvar org-refile-target-table nil
27056 "The list of refile targets, created by `org-refile'.")
27058 (defun org-get-refile-targets ()
27059 "Produce a table with refile targets."
27060 ;; FIXME: interpret the different specs for refile targets.
27061 (put 'org-agenda-files 'org-restrict nil)
27062 (let ((entries org-refile-targets)
27063 org-agenda-new-files targets txt re files f desc descre)
27064 (while (setq entry (pop entries))
27065 (setq files (car entry) desc (cdr entry))
27066 (cond
27067 ((null files) (setq files (list (current-buffer))))
27068 ((and (symbolp files) (fboundp files))
27069 (setq files (funcall files)))
27070 ((and (symbolp files) (boundp files))
27071 (setq files (symbol-value files))))
27072 (if (stringp files) (setq files (list files)))
27073 (cond
27074 ((eq (car desc) :tag)
27075 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
27076 ((eq (car desc) :todo)
27077 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
27078 ((eq (car desc) :regexp)
27079 (setq descre (cdr desc)))
27080 ((eq (car desc) :level)
27081 (setq descre (concat "^\\*\\{" (number-to-string
27082 (if org-odd-levels-only
27083 (1- (* 2 (cdr desc)))
27084 (cdr desc)))
27085 "\\}[ \t]")))
27086 (t (error "Bad refiling target description %s" desc)))
27087 (while (setq f (pop files))
27088 (save-excursion
27089 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
27090 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
27091 (save-excursion
27092 (save-restriction
27093 (widen)
27094 (goto-char (point-min))
27095 (while (re-search-forward descre nil t)
27096 (goto-char (point-at-bol))
27097 (when (looking-at org-complex-heading-regexp)
27098 (setq txt (match-string 4)
27099 re (concat "^" (regexp-quote
27100 (buffer-substring (match-beginning 1)
27101 (match-end 4)))))
27102 (if (match-end 5) (setq re (concat re "[ \t]+"
27103 (regexp-quote
27104 (match-string 5)))))
27105 (setq re (concat re "[ \t]*$"))
27106 (push (list txt f re (point)) targets))
27107 (goto-char (point-at-eol))))))))
27108 (org-release-buffers org-agenda-new-buffers)
27109 (nreverse targets)))
27111 (defun org-refile (&optional reversed-or-update)
27112 "Move the entry at point to another heading.
27113 The list of target headings is compiled using the information in
27114 `org-refile-targets', which see. This list is created upon first use, and
27115 you can update it by calling this command with a double prefix (`C-u C-u').
27117 At the target location, the entry is filed as a subitem of the target heading.
27118 Depending on `org-reverse-note-order', the new subitem will either be the
27119 first of the last subitem. A single C-u prefix will toggle the value of this
27120 variable for the duration of the command."
27121 (interactive "P")
27122 (if (equal reversed-or-update '(16))
27123 (progn
27124 (setq org-refile-target-table (org-get-refile-targets))
27125 (message "Refile targets updated (%d targets)"
27126 (length org-refile-target-table)))
27127 (when (or (not org-refile-target-table)
27128 (and (= (length org-refile-targets) 1)
27129 (not (caar org-refile-targets))))
27130 (setq org-refile-target-table (org-get-refile-targets)))
27131 (unless org-refile-target-table
27132 (error "No refile targets"))
27133 (let* ((cbuf (current-buffer))
27134 (filename (buffer-file-name (buffer-base-buffer cbuf)))
27135 (fname (and filename (file-truename filename)))
27136 (tbl (mapcar
27137 (lambda (x)
27138 (if (not (equal fname (file-truename (nth 1 x))))
27139 (cons (concat (car x) " (" (file-name-nondirectory
27140 (nth 1 x)) ")")
27141 (cdr x))
27143 org-refile-target-table))
27144 (completion-ignore-case t)
27145 pos it nbuf file re level reversed)
27146 (when (setq it (completing-read "Refile to: " tbl
27147 nil t nil 'org-refile-history))
27148 (setq it (assoc it tbl)
27149 file (nth 1 it)
27150 re (nth 2 it))
27151 (org-copy-special)
27152 (save-excursion
27153 (set-buffer (setq nbuf (or (find-buffer-visiting file)
27154 (find-file-noselect file))))
27155 (setq reversed (org-notes-order-reversed-p))
27156 (if (equal reversed-or-update '(16)) (setq reversed (not reversed)))
27157 (save-excursion
27158 (save-restriction
27159 (widen)
27160 (goto-char (point-min))
27161 (unless (re-search-forward re nil t)
27162 (error "Cannot find target location - try again with `C-u' prefix."))
27163 (goto-char (match-beginning 0))
27164 (looking-at outline-regexp)
27165 (setq level (org-get-legal-level (funcall outline-level) 1))
27166 (goto-char (or (save-excursion
27167 (if reversed
27168 (outline-next-heading)
27169 (outline-get-next-sibling)))
27170 (point-max)))
27171 (org-paste-subtree level))))
27172 (org-cut-special)
27173 (message "Entry refiled to \"%s\"" (car it))))))
27175 (defcustom org-highlight-latex-fragments-and-specials nil
27176 "Non-nil means, fontify what is treated specially by the exporters."
27177 :group 'org-font-lock
27178 :type 'boolean)
27180 (defvar org-latex-and-specials-regexp nil
27181 "Regular expression for highlighting export special stuff.")
27183 (defun org-compute-latex-and-specials-regexp ()
27184 "Compute regular expression for stuff treated specially by exporters."
27185 (if (not org-highlight-latex-fragments-and-specials)
27186 (org-set-local 'org-latex-and-specials-regexp nil)
27187 (let*
27188 ((matchers (plist-get org-format-latex-options :matchers))
27189 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
27190 org-latex-regexps)))
27191 (options (org-combine-plists (org-default-export-plist)
27192 (org-infile-export-plist)))
27193 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
27194 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
27195 (org-export-with-TeX-macros (plist-get options :TeX-macros))
27196 (org-export-html-expand (plist-get options :expand-quoted-html))
27197 (org-export-with-special-strings (plist-get options :special-strings))
27198 (re-sub
27199 (cond
27200 ((equal org-export-with-sub-superscripts '{})
27201 (list org-match-substring-with-braces-regexp))
27202 (org-export-with-sub-superscripts
27203 (list org-match-substring-regexp))
27204 (t nil)))
27205 (re-latex
27206 (if org-export-with-LaTeX-fragments
27207 (mapcar (lambda (x) (nth 1 x)) latexs)))
27208 (re-macros
27209 (if org-export-with-TeX-macros
27210 (list (concat "\\\\"
27211 (regexp-opt
27212 (append (mapcar 'car org-html-entities)
27213 (if (boundp 'org-latex-entities)
27214 org-latex-entities nil))
27215 'words))) ; FIXME
27217 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
27218 (re-special (if org-export-with-special-strings
27219 (mapcar (lambda (x) (car x))
27220 org-export-html-special-string-regexps)))
27221 (re-rest
27222 (delq nil
27223 (list
27224 (if org-export-html-expand "@<[^>\n]+>")
27225 ))))
27226 (org-set-local
27227 'org-latex-and-specials-regexp
27228 (mapconcat 'identity (append re-latex re-sub re-macros re-special re-rest) "\\|")))))
27230 (defface org-latex-and-export-specials
27231 (let ((font (cond ((assq :inherit custom-face-attributes)
27232 '(:inherit underline))
27233 (t '(:underline t)))))
27234 `((((class grayscale) (background light))
27235 (:foreground "DimGray" ,@font))
27236 (((class grayscale) (background dark))
27237 (:foreground "LightGray" ,@font))
27238 (((class color) (background light))
27239 (:foreground "SaddleBrown"))
27240 (((class color) (background dark))
27241 (:foreground "burlywood"))
27242 (t (,@font))))
27243 "Face used to highlight math latex and other special exporter stuff."
27244 :group 'org-faces)
27246 (defun org-do-latex-and-special-faces (limit)
27247 "Run through the buffer and add overlays to links."
27248 (when org-latex-and-specials-regexp
27249 (let (rtn d)
27250 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
27251 limit t))
27252 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0)) 'face))
27253 '(org-code org-verbatim underline)))
27254 (progn
27255 (setq rtn t
27256 d (cond ((member (char-after (1+ (match-beginning 0))) '(?_ ?^)) 1)
27257 (t 0)))
27258 (font-lock-prepend-text-property
27259 (+ d (match-beginning 0)) (match-end 0)
27260 'face 'org-latex-and-export-specials)
27261 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
27262 '(font-lock-multiline t)))))
27263 rtn)))
27265 (defun org-agenda-remove-restriction-lock (&optional noupdate)
27266 (setq org-agenda-restrict nil)
27267 (put 'org-agenda-files 'org-restrict nil)
27268 (move-marker org-agenda-restrict-begin nil)
27269 (move-marker org-agenda-restrict-end nil))
27272 ;;;; Finish up
27274 (provide 'org)
27276 (run-hooks 'org-load-hook)
27278 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
27279 ;;; org.el ends here