Fix `org-load-default-extensions': don't throw an error.
[org-mode.git] / org.el
blobaf6632dcfb92a37fc3b90334770968a6f4384cf2
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.22a+
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.22a+"
88 "The version number of the file org.el.")
90 (defun org-version (&optional here)
91 "Show the org-mode version in the echo area.
92 With prefix arg HERE, insert it at point."
93 (interactive "P")
94 (let ((version (format "Org-mode version %s" org-version)))
95 (message version)
96 (if here
97 (insert version))))
99 ;;; Compatibility constants
100 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
101 (defconst org-format-transports-properties-p
102 (let ((x "a"))
103 (add-text-properties 0 1 '(test t) x)
104 (get-text-property 0 'test (format "%s" x)))
105 "Does format transport text properties?")
107 (defmacro org-bound-and-true-p (var)
108 "Return the value of symbol VAR if it is bound, else nil."
109 `(and (boundp (quote ,var)) ,var))
111 (defmacro org-unmodified (&rest body)
112 "Execute body without changing `buffer-modified-p'."
113 `(set-buffer-modified-p
114 (prog1 (buffer-modified-p) ,@body)))
116 (defmacro org-re (s)
117 "Replace posix classes in regular expression."
118 (if (featurep 'xemacs)
119 (let ((ss s))
120 (save-match-data
121 (while (string-match "\\[:alnum:\\]" ss)
122 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
123 (while (string-match "\\[:alpha:\\]" ss)
124 (setq ss (replace-match "a-zA-Z" t t ss)))
125 ss))
128 (defmacro org-preserve-lc (&rest body)
129 `(let ((_line (org-current-line))
130 (_col (current-column)))
131 (unwind-protect
132 (progn ,@body)
133 (goto-line _line)
134 (move-to-column _col))))
136 (defmacro org-without-partial-completion (&rest body)
137 `(let ((pc-mode (and (boundp 'partial-completion-mode)
138 partial-completion-mode)))
139 (unwind-protect
140 (progn
141 (if pc-mode (partial-completion-mode -1))
142 ,@body)
143 (if pc-mode (partial-completion-mode 1)))))
145 ;;; The custom variables
147 (defgroup org nil
148 "Outline-based notes management and organizer."
149 :tag "Org"
150 :group 'outlines
151 :group 'hypermedia
152 :group 'calendar)
154 (defcustom org-load-hook '(org-load-default-extensions)
155 "Hook that is run after org.el has been loaded.
156 This happens also after `org' has been provided, so
157 requiring something in this hook that does a (require 'org) is ok."
158 :group 'org
159 :type 'hook)
161 (defcustom org-default-extensions '(org-irc)
162 "Extensions that should always be loaded together with org.el.
163 If the description starts with <A>, this means the extension
164 will be autoloaded when needed, preloading is not necessary."
165 :group 'org
166 :type
167 '(set :greedy t
168 (const :tag " Mouse support (org-mouse.el)" org-mouse)
169 (const :tag "<A> Publishing (org-publish.el)" org-publish)
170 (const :tag "<A> LaTeX export (org-export-latex.el)" org-export-latex)
171 (const :tag " IRC/ERC links (org-irc.el)" org-irc)
172 (const :tag " Apple Mail message links under OS X (org-mac-message.el)" org-mac-message)))
174 (defun org-load-default-extensions ()
175 "Load all extensions listed in `org-default-extensions'."
176 (mapc (lambda (ext)
177 (condition-case nil (require ext)
178 (error (message "Feature `%s' is not known" ext))))
179 org-default-extensions))
181 ;; FIXME: Needs a separate group...
182 (defcustom org-completion-fallback-command 'hippie-expand
183 "The expansion command called by \\[org-complete] in normal context.
184 Normal means, no org-mode-specific context."
185 :group 'org
186 :type 'function)
188 (defgroup org-startup nil
189 "Options concerning startup of Org-mode."
190 :tag "Org Startup"
191 :group 'org)
193 (defcustom org-startup-folded t
194 "Non-nil means, entering Org-mode will switch to OVERVIEW.
195 This can also be configured on a per-file basis by adding one of
196 the following lines anywhere in the buffer:
198 #+STARTUP: fold
199 #+STARTUP: nofold
200 #+STARTUP: content"
201 :group 'org-startup
202 :type '(choice
203 (const :tag "nofold: show all" nil)
204 (const :tag "fold: overview" t)
205 (const :tag "content: all headlines" content)))
207 (defcustom org-startup-truncated t
208 "Non-nil means, entering Org-mode will set `truncate-lines'.
209 This is useful since some lines containing links can be very long and
210 uninteresting. Also tables look terrible when wrapped."
211 :group 'org-startup
212 :type 'boolean)
214 (defcustom org-startup-align-all-tables nil
215 "Non-nil means, align all tables when visiting a file.
216 This is useful when the column width in tables is forced with <N> cookies
217 in table fields. Such tables will look correct only after the first re-align.
218 This can also be configured on a per-file basis by adding one of
219 the following lines anywhere in the buffer:
220 #+STARTUP: align
221 #+STARTUP: noalign"
222 :group 'org-startup
223 :type 'boolean)
225 (defcustom org-insert-mode-line-in-empty-file nil
226 "Non-nil means insert the first line setting Org-mode in empty files.
227 When the function `org-mode' is called interactively in an empty file, this
228 normally means that the file name does not automatically trigger Org-mode.
229 To ensure that the file will always be in Org-mode in the future, a
230 line enforcing Org-mode will be inserted into the buffer, if this option
231 has been set."
232 :group 'org-startup
233 :type 'boolean)
235 (defcustom org-replace-disputed-keys nil
236 "Non-nil means use alternative key bindings for some keys.
237 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
238 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
239 If you want to use Org-mode together with one of these other modes,
240 or more generally if you would like to move some Org-mode commands to
241 other keys, set this variable and configure the keys with the variable
242 `org-disputed-keys'.
244 This option is only relevant at load-time of Org-mode, and must be set
245 *before* org.el is loaded. Changing it requires a restart of Emacs to
246 become effective."
247 :group 'org-startup
248 :type 'boolean)
250 (if (fboundp 'defvaralias)
251 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
253 (defcustom org-disputed-keys
254 '(([(shift up)] . [(meta p)])
255 ([(shift down)] . [(meta n)])
256 ([(shift left)] . [(meta -)])
257 ([(shift right)] . [(meta +)])
258 ([(control shift right)] . [(meta shift +)])
259 ([(control shift left)] . [(meta shift -)]))
260 "Keys for which Org-mode and other modes compete.
261 This is an alist, cars are the default keys, second element specifies
262 the alternative to use when `org-replace-disputed-keys' is t.
264 Keys can be specified in any syntax supported by `define-key'.
265 The value of this option takes effect only at Org-mode's startup,
266 therefore you'll have to restart Emacs to apply it after changing."
267 :group 'org-startup
268 :type 'alist)
270 (defun org-key (key)
271 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
272 Or return the original if not disputed."
273 (if org-replace-disputed-keys
274 (let* ((nkey (key-description key))
275 (x (org-find-if (lambda (x)
276 (equal (key-description (car x)) nkey))
277 org-disputed-keys)))
278 (if x (cdr x) key))
279 key))
281 (defun org-find-if (predicate seq)
282 (catch 'exit
283 (while seq
284 (if (funcall predicate (car seq))
285 (throw 'exit (car seq))
286 (pop seq)))))
288 (defun org-defkey (keymap key def)
289 "Define a key, possibly translated, as returned by `org-key'."
290 (define-key keymap (org-key key) def))
292 (defcustom org-ellipsis nil
293 "The ellipsis to use in the Org-mode outline.
294 When nil, just use the standard three dots. When a string, use that instead,
295 When a face, use the standart 3 dots, but with the specified face.
296 The change affects only Org-mode (which will then use its own display table).
297 Changing this requires executing `M-x org-mode' in a buffer to become
298 effective."
299 :group 'org-startup
300 :type '(choice (const :tag "Default" nil)
301 (face :tag "Face" :value org-warning)
302 (string :tag "String" :value "...#")))
304 (defvar org-display-table nil
305 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
307 (defgroup org-keywords nil
308 "Keywords in Org-mode."
309 :tag "Org Keywords"
310 :group 'org)
312 (defcustom org-deadline-string "DEADLINE:"
313 "String to mark deadline entries.
314 A deadline is this string, followed by a time stamp. Should be a word,
315 terminated by a colon. You can insert a schedule keyword and
316 a timestamp with \\[org-deadline].
317 Changes become only effective after restarting Emacs."
318 :group 'org-keywords
319 :type 'string)
321 (defcustom org-scheduled-string "SCHEDULED:"
322 "String to mark scheduled TODO entries.
323 A schedule is this string, followed by a time stamp. Should be a word,
324 terminated by a colon. You can insert a schedule keyword and
325 a timestamp with \\[org-schedule].
326 Changes become only effective after restarting Emacs."
327 :group 'org-keywords
328 :type 'string)
330 (defcustom org-closed-string "CLOSED:"
331 "String used as the prefix for timestamps logging closing a TODO entry."
332 :group 'org-keywords
333 :type 'string)
335 (defcustom org-clock-string "CLOCK:"
336 "String used as prefix for timestamps clocking work hours on an item."
337 :group 'org-keywords
338 :type 'string)
340 (defcustom org-comment-string "COMMENT"
341 "Entries starting with this keyword will never be exported.
342 An entry can be toggled between COMMENT and normal with
343 \\[org-toggle-comment].
344 Changes become only effective after restarting Emacs."
345 :group 'org-keywords
346 :type 'string)
348 (defcustom org-quote-string "QUOTE"
349 "Entries starting with this keyword will be exported in fixed-width font.
350 Quoting applies only to the text in the entry following the headline, and does
351 not extend beyond the next headline, even if that is lower level.
352 An entry can be toggled between QUOTE and normal with
353 \\[org-toggle-fixed-width-section]."
354 :group 'org-keywords
355 :type 'string)
357 (defconst org-repeat-re
358 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
359 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
360 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
361 "Regular expression for specifying repeated events.
362 After a match, group 1 contains the repeat expression.")
364 (defgroup org-structure nil
365 "Options concerning the general structure of Org-mode files."
366 :tag "Org Structure"
367 :group 'org)
369 (defgroup org-reveal-location nil
370 "Options about how to make context of a location visible."
371 :tag "Org Reveal Location"
372 :group 'org-structure)
374 (defconst org-context-choice
375 '(choice
376 (const :tag "Always" t)
377 (const :tag "Never" nil)
378 (repeat :greedy t :tag "Individual contexts"
379 (cons
380 (choice :tag "Context"
381 (const agenda)
382 (const org-goto)
383 (const occur-tree)
384 (const tags-tree)
385 (const link-search)
386 (const mark-goto)
387 (const bookmark-jump)
388 (const isearch)
389 (const default))
390 (boolean))))
391 "Contexts for the reveal options.")
393 (defcustom org-show-hierarchy-above '((default . t))
394 "Non-nil means, show full hierarchy when revealing a location.
395 Org-mode often shows locations in an org-mode file which might have
396 been invisible before. When this is set, the hierarchy of headings
397 above the exposed location is shown.
398 Turning this off for example for sparse trees makes them very compact.
399 Instead of t, this can also be an alist specifying this option for different
400 contexts. Valid contexts are
401 agenda when exposing an entry from the agenda
402 org-goto when using the command `org-goto' on key C-c C-j
403 occur-tree when using the command `org-occur' on key C-c /
404 tags-tree when constructing a sparse tree based on tags matches
405 link-search when exposing search matches associated with a link
406 mark-goto when exposing the jump goal of a mark
407 bookmark-jump when exposing a bookmark location
408 isearch when exiting from an incremental search
409 default default for all contexts not set explicitly"
410 :group 'org-reveal-location
411 :type org-context-choice)
413 (defcustom org-show-following-heading '((default . nil))
414 "Non-nil means, show following heading when revealing a location.
415 Org-mode often shows locations in an org-mode file which might have
416 been invisible before. When this is set, the heading following the
417 match is shown.
418 Turning this off for example for sparse trees makes them very compact,
419 but makes it harder to edit the location of the match. In such a case,
420 use the command \\[org-reveal] to show more context.
421 Instead of t, this can also be an alist specifying this option for different
422 contexts. See `org-show-hierarchy-above' for valid contexts."
423 :group 'org-reveal-location
424 :type org-context-choice)
426 (defcustom org-show-siblings '((default . nil) (isearch t))
427 "Non-nil means, show all sibling heading when revealing a location.
428 Org-mode often shows locations in an org-mode file which might have
429 been invisible before. When this is set, the sibling of the current entry
430 heading are all made visible. If `org-show-hierarchy-above' is t,
431 the same happens on each level of the hierarchy above the current entry.
433 By default this is on for the isearch context, off for all other contexts.
434 Turning this off for example for sparse trees makes them very compact,
435 but makes it harder to edit the location of the match. In such a case,
436 use the command \\[org-reveal] to show more context.
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 org-context-choice)
442 (defcustom org-show-entry-below '((default . nil))
443 "Non-nil means, show the entry below a headline when revealing a location.
444 Org-mode often shows locations in an org-mode file which might have
445 been invisible before. When this is set, the text below the headline that is
446 exposed is also shown.
448 By default this is off for all contexts.
449 Instead of t, this can also be an alist specifying this option for different
450 contexts. See `org-show-hierarchy-above' for valid contexts."
451 :group 'org-reveal-location
452 :type org-context-choice)
454 (defgroup org-cycle nil
455 "Options concerning visibility cycling in Org-mode."
456 :tag "Org Cycle"
457 :group 'org-structure)
459 (defcustom org-drawers '("PROPERTIES" "CLOCK")
460 "Names of drawers. Drawers are not opened by cycling on the headline above.
461 Drawers only open with a TAB on the drawer line itself. A drawer looks like
462 this:
463 :DRAWERNAME:
464 .....
465 :END:
466 The drawer \"PROPERTIES\" is special for capturing properties through
467 the property API.
469 Drawers can be defined on the per-file basis with a line like:
471 #+DRAWERS: HIDDEN STATE PROPERTIES"
472 :group 'org-structure
473 :type '(repeat (string :tag "Drawer Name")))
475 (defcustom org-cycle-global-at-bob nil
476 "Cycle globally if cursor is at beginning of buffer and not at a headline.
477 This makes it possible to do global cycling without having to use S-TAB or
478 C-u TAB. For this special case to work, the first line of the buffer
479 must not be a headline - it may be empty ot some other text. When used in
480 this way, `org-cycle-hook' is disables temporarily, to make sure the
481 cursor stays at the beginning of the buffer.
482 When this option is nil, don't do anything special at the beginning
483 of the buffer."
484 :group 'org-cycle
485 :type 'boolean)
487 (defcustom org-cycle-emulate-tab t
488 "Where should `org-cycle' emulate TAB.
489 nil Never
490 white Only in completely white lines
491 whitestart Only at the beginning of lines, before the first non-white char
492 t Everywhere except in headlines
493 exc-hl-bol Everywhere except at the start of a headline
494 If TAB is used in a place where it does not emulate TAB, the current subtree
495 visibility is cycled."
496 :group 'org-cycle
497 :type '(choice (const :tag "Never" nil)
498 (const :tag "Only in completely white lines" white)
499 (const :tag "Before first char in a line" whitestart)
500 (const :tag "Everywhere except in headlines" t)
501 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
504 (defcustom org-cycle-separator-lines 2
505 "Number of empty lines needed to keep an empty line between collapsed trees.
506 If you leave an empty line between the end of a subtree and the following
507 headline, this empty line is hidden when the subtree is folded.
508 Org-mode will leave (exactly) one empty line visible if the number of
509 empty lines is equal or larger to the number given in this variable.
510 So the default 2 means, at least 2 empty lines after the end of a subtree
511 are needed to produce free space between a collapsed subtree and the
512 following headline.
514 Special case: when 0, never leave empty lines in collapsed view."
515 :group 'org-cycle
516 :type 'integer)
518 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
519 org-cycle-hide-drawers
520 org-cycle-show-empty-lines
521 org-optimize-window-after-visibility-change)
522 "Hook that is run after `org-cycle' has changed the buffer visibility.
523 The function(s) in this hook must accept a single argument which indicates
524 the new state that was set by the most recent `org-cycle' command. The
525 argument is a symbol. After a global state change, it can have the values
526 `overview', `content', or `all'. After a local state change, it can have
527 the values `folded', `children', or `subtree'."
528 :group 'org-cycle
529 :type 'hook)
531 (defgroup org-edit-structure nil
532 "Options concerning structure editing in Org-mode."
533 :tag "Org Edit Structure"
534 :group 'org-structure)
536 (defcustom org-odd-levels-only nil
537 "Non-nil means, skip even levels and only use odd levels for the outline.
538 This has the effect that two stars are being added/taken away in
539 promotion/demotion commands. It also influences how levels are
540 handled by the exporters.
541 Changing it requires restart of `font-lock-mode' to become effective
542 for fontification also in regions already fontified.
543 You may also set this on a per-file basis by adding one of the following
544 lines to the buffer:
546 #+STARTUP: odd
547 #+STARTUP: oddeven"
548 :group 'org-edit-structure
549 :group 'org-font-lock
550 :type 'boolean)
552 (defcustom org-adapt-indentation t
553 "Non-nil means, adapt indentation when promoting and demoting.
554 When this is set and the *entire* text in an entry is indented, the
555 indentation is increased by one space in a demotion command, and
556 decreased by one in a promotion command. If any line in the entry
557 body starts at column 0, indentation is not changed at all."
558 :group 'org-edit-structure
559 :type 'boolean)
561 (defcustom org-special-ctrl-a/e nil
562 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
563 When t, `C-a' will bring back the cursor to the beginning of the
564 headline text, i.e. after the stars and after a possible TODO keyword.
565 In an item, this will be the position after the bullet.
566 When the cursor is already at that position, another `C-a' will bring
567 it to the beginning of the line.
568 `C-e' will jump to the end of the headline, ignoring the presence of tags
569 in the headline. A second `C-e' will then jump to the true end of the
570 line, after any tags.
571 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
572 and only a directly following, identical keypress will bring the cursor
573 to the special positions."
574 :group 'org-edit-structure
575 :type '(choice
576 (const :tag "off" nil)
577 (const :tag "after bullet first" t)
578 (const :tag "border first" reversed)))
580 (if (fboundp 'defvaralias)
581 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
583 (defcustom org-special-ctrl-k nil
584 "Non-nil means `C-k' will behave specially in headlines.
585 When nil, `C-k' will call the default `kill-line' command.
586 When t, the following will happen while the cursor is in the headline:
588 - When the cursor is at the beginning of a headline, kill the entire
589 line and possible the folded subtree below the line.
590 - When in the middle of the headline text, kill the headline up to the tags.
591 - When after the headline text, kill the tags."
592 :group 'org-edit-structure
593 :type 'boolean)
595 (defcustom org-M-RET-may-split-line '((default . t))
596 "Non-nil means, M-RET will split the line at the cursor position.
597 When nil, it will go to the end of the line before making a
598 new line.
599 You may also set this option in a different way for different
600 contexts. Valid contexts are:
602 headline when creating a new headline
603 item when creating a new item
604 table in a table field
605 default the value to be used for all contexts not explicitly
606 customized"
607 :group 'org-structure
608 :group 'org-table
609 :type '(choice
610 (const :tag "Always" t)
611 (const :tag "Never" nil)
612 (repeat :greedy t :tag "Individual contexts"
613 (cons
614 (choice :tag "Context"
615 (const headline)
616 (const item)
617 (const table)
618 (const default))
619 (boolean)))))
622 (defcustom org-blank-before-new-entry '((heading . nil)
623 (plain-list-item . nil))
624 "Should `org-insert-heading' leave a blank line before new heading/item?
625 The value is an alist, with `heading' and `plain-list-item' as car,
626 and a boolean flag as cdr."
627 :group 'org-edit-structure
628 :type '(list
629 (cons (const heading) (boolean))
630 (cons (const plain-list-item) (boolean))))
632 (defcustom org-insert-heading-hook nil
633 "Hook being run after inserting a new heading."
634 :group 'org-edit-structure
635 :type 'hook)
637 (defcustom org-enable-fixed-width-editor t
638 "Non-nil means, lines starting with \":\" are treated as fixed-width.
639 This currently only means, they are never auto-wrapped.
640 When nil, such lines will be treated like ordinary lines.
641 See also the QUOTE keyword."
642 :group 'org-edit-structure
643 :type 'boolean)
645 (defcustom org-goto-auto-isearch t
646 "Non-nil means, typing characters in org-goto starts incremental search."
647 :group 'org-edit-structure
648 :type 'boolean)
650 (defgroup org-sparse-trees nil
651 "Options concerning sparse trees in Org-mode."
652 :tag "Org Sparse Trees"
653 :group 'org-structure)
655 (defcustom org-highlight-sparse-tree-matches t
656 "Non-nil means, highlight all matches that define a sparse tree.
657 The highlights will automatically disappear the next time the buffer is
658 changed by an edit command."
659 :group 'org-sparse-trees
660 :type 'boolean)
662 (defcustom org-remove-highlights-with-change t
663 "Non-nil means, any change to the buffer will remove temporary highlights.
664 Such highlights are created by `org-occur' and `org-clock-display'.
665 When nil, `C-c C-c needs to be used to get rid of the highlights.
666 The highlights created by `org-preview-latex-fragment' always need
667 `C-c C-c' to be removed."
668 :group 'org-sparse-trees
669 :group 'org-time
670 :type 'boolean)
673 (defcustom org-occur-hook '(org-first-headline-recenter)
674 "Hook that is run after `org-occur' has constructed a sparse tree.
675 This can be used to recenter the window to show as much of the structure
676 as possible."
677 :group 'org-sparse-trees
678 :type 'hook)
680 (defgroup org-plain-lists nil
681 "Options concerning plain lists in Org-mode."
682 :tag "Org Plain lists"
683 :group 'org-structure)
685 (defcustom org-cycle-include-plain-lists nil
686 "Non-nil means, include plain lists into visibility cycling.
687 This means that during cycling, plain list items will *temporarily* be
688 interpreted as outline headlines with a level given by 1000+i where i is the
689 indentation of the bullet. In all other operations, plain list items are
690 not seen as headlines. For example, you cannot assign a TODO keyword to
691 such an item."
692 :group 'org-plain-lists
693 :type 'boolean)
695 (defcustom org-plain-list-ordered-item-terminator t
696 "The character that makes a line with leading number an ordered list item.
697 Valid values are ?. and ?\). To get both terminators, use t. While
698 ?. may look nicer, it creates the danger that a line with leading
699 number may be incorrectly interpreted as an item. ?\) therefore is
700 the safe choice."
701 :group 'org-plain-lists
702 :type '(choice (const :tag "dot like in \"2.\"" ?.)
703 (const :tag "paren like in \"2)\"" ?\))
704 (const :tab "both" t)))
706 (defcustom org-auto-renumber-ordered-lists t
707 "Non-nil means, automatically renumber ordered plain lists.
708 Renumbering happens when the sequence have been changed with
709 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
710 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
711 :group 'org-plain-lists
712 :type 'boolean)
714 (defcustom org-provide-checkbox-statistics t
715 "Non-nil means, update checkbox statistics after insert and toggle.
716 When this is set, checkbox statistics is updated each time you either insert
717 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
718 with \\[org-ctrl-c-ctrl-c\\]."
719 :group 'org-plain-lists
720 :type 'boolean)
722 (defgroup org-archive nil
723 "Options concerning archiving in Org-mode."
724 :tag "Org Archive"
725 :group 'org-structure)
727 (defcustom org-archive-tag "ARCHIVE"
728 "The tag that marks a subtree as archived.
729 An archived subtree does not open during visibility cycling, and does
730 not contribute to the agenda listings.
731 After changing this, font-lock must be restarted in the relevant buffers to
732 get the proper fontification."
733 :group 'org-archive
734 :group 'org-keywords
735 :type 'string)
737 (defcustom org-agenda-skip-archived-trees t
738 "Non-nil means, the agenda will skip any items located in archived trees.
739 An archived tree is a tree marked with the tag ARCHIVE."
740 :group 'org-archive
741 :group 'org-agenda-skip
742 :type 'boolean)
744 (defcustom org-cycle-open-archived-trees nil
745 "Non-nil means, `org-cycle' will open archived trees.
746 An archived tree is a tree marked with the tag ARCHIVE.
747 When nil, archived trees will stay folded. You can still open them with
748 normal outline commands like `show-all', but not with the cycling commands."
749 :group 'org-archive
750 :group 'org-cycle
751 :type 'boolean)
753 (defcustom org-sparse-tree-open-archived-trees nil
754 "Non-nil means sparse tree construction shows matches in archived trees.
755 When nil, matches in these trees are highlighted, but the trees are kept in
756 collapsed state."
757 :group 'org-archive
758 :group 'org-sparse-trees
759 :type 'boolean)
761 (defcustom org-archive-location "%s_archive::"
762 "The location where subtrees should be archived.
763 This string consists of two parts, separated by a double-colon.
765 The first part is a file name - when omitted, archiving happens in the same
766 file. %s will be replaced by the current file name (without directory part).
767 Archiving to a different file is useful to keep archived entries from
768 contributing to the Org-mode Agenda.
770 The part after the double colon is a headline. The archived entries will be
771 filed under that headline. When omitted, the subtrees are simply filed away
772 at the end of the file, as top-level entries.
774 Here are a few examples:
775 \"%s_archive::\"
776 If the current file is Projects.org, archive in file
777 Projects.org_archive, as top-level trees. This is the default.
779 \"::* Archived Tasks\"
780 Archive in the current file, under the top-level headline
781 \"* Archived Tasks\".
783 \"~/org/archive.org::\"
784 Archive in file ~/org/archive.org (absolute path), as top-level trees.
786 \"basement::** Finished Tasks\"
787 Archive in file ./basement (relative path), as level 3 trees
788 below the level 2 heading \"** Finished Tasks\".
790 You may set this option on a per-file basis by adding to the buffer a
791 line like
793 #+ARCHIVE: basement::** Finished Tasks"
794 :group 'org-archive
795 :type 'string)
797 (defcustom org-archive-mark-done t
798 "Non-nil means, mark entries as DONE when they are moved to the archive file.
799 This can be a string to set the keyword to use. When t, Org-mode will
800 use the first keyword in its list that means done."
801 :group 'org-archive
802 :type '(choice
803 (const :tag "No" nil)
804 (const :tag "Yes" t)
805 (string :tag "Use this keyword")))
807 (defcustom org-archive-stamp-time t
808 "Non-nil means, add a time stamp to entries moved to an archive file.
809 This variable is obsolete and has no effect anymore, instead add ot remove
810 `time' from the variablle `org-archive-save-context-info'."
811 :group 'org-archive
812 :type 'boolean)
814 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
815 "Parts of context info that should be stored as properties when archiving.
816 When a subtree is moved to an archive file, it looses information given by
817 context, like inherited tags, the category, and possibly also the TODO
818 state (depending on the variable `org-archive-mark-done').
819 This variable can be a list of any of the following symbols:
821 time The time of archiving.
822 file The file where the entry originates.
823 itags The local tags, in the headline of the subtree.
824 ltags The tags the subtree inherits from further up the hierarchy.
825 todo The pre-archive TODO state.
826 category The category, taken from file name or #+CATEGORY lines.
827 olpath The outline path to the item. These are all headlines above
828 the current item, separated by /, like a file path.
830 For each symbol present in the list, a property will be created in
831 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
832 information."
833 :group 'org-archive
834 :type '(set :greedy t
835 (const :tag "Time" time)
836 (const :tag "File" file)
837 (const :tag "Category" category)
838 (const :tag "TODO state" todo)
839 (const :tag "TODO state" priority)
840 (const :tag "Inherited tags" itags)
841 (const :tag "Outline path" olpath)
842 (const :tag "Local tags" ltags)))
844 (defgroup org-imenu-and-speedbar nil
845 "Options concerning imenu and speedbar in Org-mode."
846 :tag "Org Imenu and Speedbar"
847 :group 'org-structure)
849 (defcustom org-imenu-depth 2
850 "The maximum level for Imenu access to Org-mode headlines.
851 This also applied for speedbar access."
852 :group 'org-imenu-and-speedbar
853 :type 'number)
855 (defgroup org-table nil
856 "Options concerning tables in Org-mode."
857 :tag "Org Table"
858 :group 'org)
860 (defcustom org-enable-table-editor 'optimized
861 "Non-nil means, lines starting with \"|\" are handled by the table editor.
862 When nil, such lines will be treated like ordinary lines.
864 When equal to the symbol `optimized', the table editor will be optimized to
865 do the following:
866 - Automatic overwrite mode in front of whitespace in table fields.
867 This makes the structure of the table stay in tact as long as the edited
868 field does not exceed the column width.
869 - Minimize the number of realigns. Normally, the table is aligned each time
870 TAB or RET are pressed to move to another field. With optimization this
871 happens only if changes to a field might have changed the column width.
872 Optimization requires replacing the functions `self-insert-command',
873 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
874 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
875 very good at guessing when a re-align will be necessary, but you can always
876 force one with \\[org-ctrl-c-ctrl-c].
878 If you would like to use the optimized version in Org-mode, but the
879 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
881 This variable can be used to turn on and off the table editor during a session,
882 but in order to toggle optimization, a restart is required.
884 See also the variable `org-table-auto-blank-field'."
885 :group 'org-table
886 :type '(choice
887 (const :tag "off" nil)
888 (const :tag "on" t)
889 (const :tag "on, optimized" optimized)))
891 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
892 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
893 In the optimized version, the table editor takes over all simple keys that
894 normally just insert a character. In tables, the characters are inserted
895 in a way to minimize disturbing the table structure (i.e. in overwrite mode
896 for empty fields). Outside tables, the correct binding of the keys is
897 restored.
899 The default for this option is t if the optimized version is also used in
900 Org-mode. See the variable `org-enable-table-editor' for details. Changing
901 this variable requires a restart of Emacs to become effective."
902 :group 'org-table
903 :type 'boolean)
905 (defcustom orgtbl-radio-table-templates
906 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
907 % END RECEIVE ORGTBL %n
908 \\begin{comment}
909 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
910 | | |
911 \\end{comment}\n")
912 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
913 @c END RECEIVE ORGTBL %n
914 @ignore
915 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
916 | | |
917 @end ignore\n")
918 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
919 <!-- END RECEIVE ORGTBL %n -->
920 <!--
921 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
922 | | |
923 -->\n"))
924 "Templates for radio tables in different major modes.
925 All occurrences of %n in a template will be replaced with the name of the
926 table, obtained by prompting the user."
927 :group 'org-table
928 :type '(repeat
929 (list (symbol :tag "Major mode")
930 (string :tag "Format"))))
932 (defgroup org-table-settings nil
933 "Settings for tables in Org-mode."
934 :tag "Org Table Settings"
935 :group 'org-table)
937 (defcustom org-table-default-size "5x2"
938 "The default size for newly created tables, Columns x Rows."
939 :group 'org-table-settings
940 :type 'string)
942 (defcustom org-table-number-regexp
943 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
944 "Regular expression for recognizing numbers in table columns.
945 If a table column contains mostly numbers, it will be aligned to the
946 right. If not, it will be aligned to the left.
948 The default value of this option is a regular expression which allows
949 anything which looks remotely like a number as used in scientific
950 context. For example, all of the following will be considered a
951 number:
952 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
954 Other options offered by the customize interface are more restrictive."
955 :group 'org-table-settings
956 :type '(choice
957 (const :tag "Positive Integers"
958 "^[0-9]+$")
959 (const :tag "Integers"
960 "^[-+]?[0-9]+$")
961 (const :tag "Floating Point Numbers"
962 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
963 (const :tag "Floating Point Number or Integer"
964 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
965 (const :tag "Exponential, Floating point, Integer"
966 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
967 (const :tag "Very General Number-Like, including hex"
968 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
969 (string :tag "Regexp:")))
971 (defcustom org-table-number-fraction 0.5
972 "Fraction of numbers in a column required to make the column align right.
973 In a column all non-white fields are considered. If at least this
974 fraction of fields is matched by `org-table-number-fraction',
975 alignment to the right border applies."
976 :group 'org-table-settings
977 :type 'number)
979 (defgroup org-table-editing nil
980 "Behavior of tables during editing in Org-mode."
981 :tag "Org Table Editing"
982 :group 'org-table)
984 (defcustom org-table-automatic-realign t
985 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
986 When nil, aligning is only done with \\[org-table-align], or after column
987 removal/insertion."
988 :group 'org-table-editing
989 :type 'boolean)
991 (defcustom org-table-auto-blank-field t
992 "Non-nil means, automatically blank table field when starting to type into it.
993 This only happens when typing immediately after a field motion
994 command (TAB, S-TAB or RET).
995 Only relevant when `org-enable-table-editor' is equal to `optimized'."
996 :group 'org-table-editing
997 :type 'boolean)
999 (defcustom org-table-tab-jumps-over-hlines t
1000 "Non-nil means, tab in the last column of a table with jump over a hline.
1001 If a horizontal separator line is following the current line,
1002 `org-table-next-field' can either create a new row before that line, or jump
1003 over the line. When this option is nil, a new line will be created before
1004 this line."
1005 :group 'org-table-editing
1006 :type 'boolean)
1008 (defcustom org-table-tab-recognizes-table.el t
1009 "Non-nil means, TAB will automatically notice a table.el table.
1010 When it sees such a table, it moves point into it and - if necessary -
1011 calls `table-recognize-table'."
1012 :group 'org-table-editing
1013 :type 'boolean)
1015 (defgroup org-table-calculation nil
1016 "Options concerning tables in Org-mode."
1017 :tag "Org Table Calculation"
1018 :group 'org-table)
1020 (defcustom org-table-use-standard-references t
1021 "Should org-mode work with table refrences like B3 instead of @3$2?
1022 Possible values are:
1023 nil never use them
1024 from accept as input, do not present for editing
1025 t: accept as input and present for editing"
1026 :group 'org-table-calculation
1027 :type '(choice
1028 (const :tag "Never, don't even check unser input for them" nil)
1029 (const :tag "Always, both as user input, and when editing" t)
1030 (const :tag "Convert user input, don't offer during editing" 'from)))
1032 (defcustom org-table-copy-increment t
1033 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1034 :group 'org-table-calculation
1035 :type 'boolean)
1037 (defcustom org-calc-default-modes
1038 '(calc-internal-prec 12
1039 calc-float-format (float 5)
1040 calc-angle-mode deg
1041 calc-prefer-frac nil
1042 calc-symbolic-mode nil
1043 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1044 calc-display-working-message t
1046 "List with Calc mode settings for use in calc-eval for table formulas.
1047 The list must contain alternating symbols (Calc modes variables and values).
1048 Don't remove any of the default settings, just change the values. Org-mode
1049 relies on the variables to be present in the list."
1050 :group 'org-table-calculation
1051 :type 'plist)
1053 (defcustom org-table-formula-evaluate-inline t
1054 "Non-nil means, TAB and RET evaluate a formula in current table field.
1055 If the current field starts with an equal sign, it is assumed to be a formula
1056 which should be evaluated as described in the manual and in the documentation
1057 string of the command `org-table-eval-formula'. This feature requires the
1058 Emacs calc package.
1059 When this variable is nil, formula calculation is only available through
1060 the command \\[org-table-eval-formula]."
1061 :group 'org-table-calculation
1062 :type 'boolean)
1064 (defcustom org-table-formula-use-constants t
1065 "Non-nil means, interpret constants in formulas in tables.
1066 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1067 by the value given in `org-table-formula-constants', or by a value obtained
1068 from the `constants.el' package."
1069 :group 'org-table-calculation
1070 :type 'boolean)
1072 (defcustom org-table-formula-constants nil
1073 "Alist with constant names and values, for use in table formulas.
1074 The car of each element is a name of a constant, without the `$' before it.
1075 The cdr is the value as a string. For example, if you'd like to use the
1076 speed of light in a formula, you would configure
1078 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1080 and then use it in an equation like `$1*$c'.
1082 Constants can also be defined on a per-file basis using a line like
1084 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1085 :group 'org-table-calculation
1086 :type '(repeat
1087 (cons (string :tag "name")
1088 (string :tag "value"))))
1090 (defvar org-table-formula-constants-local nil
1091 "Local version of `org-table-formula-constants'.")
1092 (make-variable-buffer-local 'org-table-formula-constants-local)
1094 (defcustom org-table-allow-automatic-line-recalculation t
1095 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1096 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1097 :group 'org-table-calculation
1098 :type 'boolean)
1100 (defgroup org-link nil
1101 "Options concerning links in Org-mode."
1102 :tag "Org Link"
1103 :group 'org)
1105 (defvar org-link-abbrev-alist-local nil
1106 "Buffer-local version of `org-link-abbrev-alist', which see.
1107 The value of this is taken from the #+LINK lines.")
1108 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1110 (defcustom org-link-abbrev-alist nil
1111 "Alist of link abbreviations.
1112 The car of each element is a string, to be replaced at the start of a link.
1113 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1114 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1116 [[linkkey:tag][description]]
1118 If REPLACE is a string, the tag will simply be appended to create the link.
1119 If the string contains \"%s\", the tag will be inserted there.
1121 REPLACE may also be a function that will be called with the tag as the
1122 only argument to create the link, which should be returned as a string.
1124 See the manual for examples."
1125 :group 'org-link
1126 :type 'alist)
1128 (defcustom org-descriptive-links t
1129 "Non-nil means, hide link part and only show description of bracket links.
1130 Bracket links are like [[link][descritpion]]. This variable sets the initial
1131 state in new org-mode buffers. The setting can then be toggled on a
1132 per-buffer basis from the Org->Hyperlinks menu."
1133 :group 'org-link
1134 :type 'boolean)
1136 (defcustom org-link-file-path-type 'adaptive
1137 "How the path name in file links should be stored.
1138 Valid values are:
1140 relative Relative to the current directory, i.e. the directory of the file
1141 into which the link is being inserted.
1142 absolute Absolute path, if possible with ~ for home directory.
1143 noabbrev Absolute path, no abbreviation of home directory.
1144 adaptive Use relative path for files in the current directory and sub-
1145 directories of it. For other files, use an absolute path."
1146 :group 'org-link
1147 :type '(choice
1148 (const relative)
1149 (const absolute)
1150 (const noabbrev)
1151 (const adaptive)))
1153 (defcustom org-activate-links '(bracket angle plain radio tag date)
1154 "Types of links that should be activated in Org-mode files.
1155 This is a list of symbols, each leading to the activation of a certain link
1156 type. In principle, it does not hurt to turn on most link types - there may
1157 be a small gain when turning off unused link types. The types are:
1159 bracket The recommended [[link][description]] or [[link]] links with hiding.
1160 angular Links in angular brackes that may contain whitespace like
1161 <bbdb:Carsten Dominik>.
1162 plain Plain links in normal text, no whitespace, like http://google.com.
1163 radio Text that is matched by a radio target, see manual for details.
1164 tag Tag settings in a headline (link to tag search).
1165 date Time stamps (link to calendar).
1167 Changing this variable requires a restart of Emacs to become effective."
1168 :group 'org-link
1169 :type '(set (const :tag "Double bracket links (new style)" bracket)
1170 (const :tag "Angular bracket links (old style)" angular)
1171 (const :tag "Plain text links" plain)
1172 (const :tag "Radio target matches" radio)
1173 (const :tag "Tags" tag)
1174 (const :tag "Timestamps" date)))
1176 (defgroup org-link-store nil
1177 "Options concerning storing links in Org-mode"
1178 :tag "Org Store Link"
1179 :group 'org-link)
1181 (defcustom org-email-link-description-format "Email %c: %.30s"
1182 "Format of the description part of a link to an email or usenet message.
1183 The following %-excapes will be replaced by corresponding information:
1185 %F full \"From\" field
1186 %f name, taken from \"From\" field, address if no name
1187 %T full \"To\" field
1188 %t first name in \"To\" field, address if no name
1189 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1190 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1191 %s subject
1192 %m message-id.
1194 You may use normal field width specification between the % and the letter.
1195 This is for example useful to limit the length of the subject.
1197 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1198 :group 'org-link-store
1199 :type 'string)
1201 (defcustom org-from-is-user-regexp
1202 (let (r1 r2)
1203 (when (and user-mail-address (not (string= user-mail-address "")))
1204 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1205 (when (and user-full-name (not (string= user-full-name "")))
1206 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1207 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1208 "Regexp mached against the \"From:\" header of an email or usenet message.
1209 It should match if the message is from the user him/herself."
1210 :group 'org-link-store
1211 :type 'regexp)
1213 (defcustom org-context-in-file-links t
1214 "Non-nil means, file links from `org-store-link' contain context.
1215 A search string will be added to the file name with :: as separator and
1216 used to find the context when the link is activated by the command
1217 `org-open-at-point'.
1218 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1219 negates this setting for the duration of the command."
1220 :group 'org-link-store
1221 :type 'boolean)
1223 (defcustom org-keep-stored-link-after-insertion nil
1224 "Non-nil means, keep link in list for entire session.
1226 The command `org-store-link' adds a link pointing to the current
1227 location to an internal list. These links accumulate during a session.
1228 The command `org-insert-link' can be used to insert links into any
1229 Org-mode file (offering completion for all stored links). When this
1230 option is nil, every link which has been inserted once using \\[org-insert-link]
1231 will be removed from the list, to make completing the unused links
1232 more efficient."
1233 :group 'org-link-store
1234 :type 'boolean)
1236 (defcustom org-usenet-links-prefer-google nil
1237 "Non-nil means, `org-store-link' will create web links to Google groups.
1238 When nil, Gnus will be used for such links.
1239 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1240 negates this setting for the duration of the command."
1241 :group 'org-link-store
1242 :type 'boolean)
1244 (defgroup org-link-follow nil
1245 "Options concerning following links in Org-mode"
1246 :tag "Org Follow Link"
1247 :group 'org-link)
1249 (defcustom org-tab-follows-link nil
1250 "Non-nil means, on links TAB will follow the link.
1251 Needs to be set before org.el is loaded."
1252 :group 'org-link-follow
1253 :type 'boolean)
1255 (defcustom org-return-follows-link nil
1256 "Non-nil means, on links RET will follow the link.
1257 Needs to be set before org.el is loaded."
1258 :group 'org-link-follow
1259 :type 'boolean)
1261 (defcustom org-mouse-1-follows-link
1262 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1263 "Non-nil means, mouse-1 on a link will follow the link.
1264 A longer mouse click will still set point. Does not work on XEmacs.
1265 Needs to be set before org.el is loaded."
1266 :group 'org-link-follow
1267 :type 'boolean)
1269 (defcustom org-mark-ring-length 4
1270 "Number of different positions to be recorded in the ring
1271 Changing this requires a restart of Emacs to work correctly."
1272 :group 'org-link-follow
1273 :type 'interger)
1275 (defcustom org-link-frame-setup
1276 '((vm . vm-visit-folder-other-frame)
1277 (gnus . gnus-other-frame)
1278 (file . find-file-other-window))
1279 "Setup the frame configuration for following links.
1280 When following a link with Emacs, it may often be useful to display
1281 this link in another window or frame. This variable can be used to
1282 set this up for the different types of links.
1283 For VM, use any of
1284 `vm-visit-folder'
1285 `vm-visit-folder-other-frame'
1286 For Gnus, use any of
1287 `gnus'
1288 `gnus-other-frame'
1289 For FILE, use any of
1290 `find-file'
1291 `find-file-other-window'
1292 `find-file-other-frame'
1293 For the calendar, use the variable `calendar-setup'.
1294 For BBDB, it is currently only possible to display the matches in
1295 another window."
1296 :group 'org-link-follow
1297 :type '(list
1298 (cons (const vm)
1299 (choice
1300 (const vm-visit-folder)
1301 (const vm-visit-folder-other-window)
1302 (const vm-visit-folder-other-frame)))
1303 (cons (const gnus)
1304 (choice
1305 (const gnus)
1306 (const gnus-other-frame)))
1307 (cons (const file)
1308 (choice
1309 (const find-file)
1310 (const find-file-other-window)
1311 (const find-file-other-frame)))))
1313 (defcustom org-display-internal-link-with-indirect-buffer nil
1314 "Non-nil means, use indirect buffer to display infile links.
1315 Activating internal links (from one location in a file to another location
1316 in the same file) normally just jumps to the location. When the link is
1317 activated with a C-u prefix (or with mouse-3), the link is displayed in
1318 another window. When this option is set, the other window actually displays
1319 an indirect buffer clone of the current buffer, to avoid any visibility
1320 changes to the current buffer."
1321 :group 'org-link-follow
1322 :type 'boolean)
1324 (defcustom org-open-non-existing-files nil
1325 "Non-nil means, `org-open-file' will open non-existing files.
1326 When nil, an error will be generated."
1327 :group 'org-link-follow
1328 :type 'boolean)
1330 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1331 "Function and arguments to call for following mailto links.
1332 This is a list with the first element being a lisp function, and the
1333 remaining elements being arguments to the function. In string arguments,
1334 %a will be replaced by the address, and %s will be replaced by the subject
1335 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1336 :group 'org-link-follow
1337 :type '(choice
1338 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1339 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1340 (const :tag "message-mail" (message-mail "%a" "%s"))
1341 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1343 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1344 "Non-nil means, ask for confirmation before executing shell links.
1345 Shell links can be dangerous: just think about a link
1347 [[shell:rm -rf ~/*][Google Search]]
1349 This link would show up in your Org-mode document as \"Google Search\",
1350 but really it would remove your entire home directory.
1351 Therefore we advise against setting this variable to nil.
1352 Just change it to `y-or-n-p' of you want to confirm with a
1353 single keystroke rather than having to type \"yes\"."
1354 :group 'org-link-follow
1355 :type '(choice
1356 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1357 (const :tag "with y-or-n (faster)" y-or-n-p)
1358 (const :tag "no confirmation (dangerous)" nil)))
1360 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1361 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1362 Elisp links can be dangerous: just think about a link
1364 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1366 This link would show up in your Org-mode document as \"Google Search\",
1367 but really it would remove your entire home directory.
1368 Therefore we advise against setting this variable to nil.
1369 Just change it to `y-or-n-p' of you want to confirm with a
1370 single keystroke rather than having to type \"yes\"."
1371 :group 'org-link-follow
1372 :type '(choice
1373 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1374 (const :tag "with y-or-n (faster)" y-or-n-p)
1375 (const :tag "no confirmation (dangerous)" nil)))
1377 (defconst org-file-apps-defaults-gnu
1378 '((remote . emacs)
1379 (t . mailcap))
1380 "Default file applications on a UNIX or GNU/Linux system.
1381 See `org-file-apps'.")
1383 (defconst org-file-apps-defaults-macosx
1384 '((remote . emacs)
1385 (t . "open %s")
1386 ("ps" . "gv %s")
1387 ("ps.gz" . "gv %s")
1388 ("eps" . "gv %s")
1389 ("eps.gz" . "gv %s")
1390 ("dvi" . "xdvi %s")
1391 ("fig" . "xfig %s"))
1392 "Default file applications on a MacOS X system.
1393 The system \"open\" is known as a default, but we use X11 applications
1394 for some files for which the OS does not have a good default.
1395 See `org-file-apps'.")
1397 (defconst org-file-apps-defaults-windowsnt
1398 (list
1399 '(remote . emacs)
1400 (cons t
1401 (list (if (featurep 'xemacs)
1402 'mswindows-shell-execute
1403 'w32-shell-execute)
1404 "open" 'file)))
1405 "Default file applications on a Windows NT system.
1406 The system \"open\" is used for most files.
1407 See `org-file-apps'.")
1409 (defcustom org-file-apps
1411 ("txt" . emacs)
1412 ("tex" . emacs)
1413 ("ltx" . emacs)
1414 ("org" . emacs)
1415 ("el" . emacs)
1416 ("bib" . emacs)
1418 "External applications for opening `file:path' items in a document.
1419 Org-mode uses system defaults for different file types, but
1420 you can use this variable to set the application for a given file
1421 extension. The entries in this list are cons cells where the car identifies
1422 files and the cdr the corresponding command. Possible values for the
1423 file identifier are
1424 \"ext\" A string identifying an extension
1425 `directory' Matches a directory
1426 `remote' Matches a remote file, accessible through tramp or efs.
1427 Remote files most likely should be visited through Emacs
1428 because external applications cannot handle such paths.
1429 t Default for all remaining files
1431 Possible values for the command are:
1432 `emacs' The file will be visited by the current Emacs process.
1433 `default' Use the default application for this file type.
1434 string A command to be executed by a shell; %s will be replaced
1435 by the path to the file.
1436 sexp A Lisp form which will be evaluated. The file path will
1437 be available in the Lisp variable `file'.
1438 For more examples, see the system specific constants
1439 `org-file-apps-defaults-macosx'
1440 `org-file-apps-defaults-windowsnt'
1441 `org-file-apps-defaults-gnu'."
1442 :group 'org-link-follow
1443 :type '(repeat
1444 (cons (choice :value ""
1445 (string :tag "Extension")
1446 (const :tag "Default for unrecognized files" t)
1447 (const :tag "Remote file" remote)
1448 (const :tag "Links to a directory" directory))
1449 (choice :value ""
1450 (const :tag "Visit with Emacs" emacs)
1451 (const :tag "Use system default" default)
1452 (string :tag "Command")
1453 (sexp :tag "Lisp form")))))
1455 (defcustom org-mhe-search-all-folders nil
1456 "Non-nil means, that the search for the mh-message will be extended to
1457 all folders if the message cannot be found in the folder given in the link.
1458 Searching all folders is very efficient with one of the search engines
1459 supported by MH-E, but will be slow with pick."
1460 :group 'org-link-follow
1461 :type 'boolean)
1463 (defgroup org-remember nil
1464 "Options concerning interaction with remember.el."
1465 :tag "Org Remember"
1466 :group 'org)
1468 (defcustom org-directory "~/org"
1469 "Directory with org files.
1470 This directory will be used as default to prompt for org files.
1471 Used by the hooks for remember.el."
1472 :group 'org-remember
1473 :type 'directory)
1475 (defcustom org-default-notes-file "~/.notes"
1476 "Default target for storing notes.
1477 Used by the hooks for remember.el. This can be a string, or nil to mean
1478 the value of `remember-data-file'.
1479 You can set this on a per-template basis with the variable
1480 `org-remember-templates'."
1481 :group 'org-remember
1482 :type '(choice
1483 (const :tag "Default from remember-data-file" nil)
1484 file))
1486 (defcustom org-remember-store-without-prompt t
1487 "Non-nil means, `C-c C-c' stores remember note without further promts.
1488 In this case, you need `C-u C-c C-c' to get the prompts for
1489 note file and headline.
1490 When this variable is nil, `C-c C-c' give you the prompts, and
1491 `C-u C-c C-c' trigger the fasttrack."
1492 :group 'org-remember
1493 :type 'boolean)
1495 (defcustom org-remember-interactive-interface 'refile
1496 "The interface to be used for interactive filing of remember notes.
1497 This is only used when the interactive mode for selecting a filing
1498 location is used (see the variable `org-remember-store-without-prompt').
1499 Allowed vaues are:
1500 outline The interface shows an outline of the relevant file
1501 and the correct heading is found by moving through
1502 the outline or by searching with incremental search.
1503 outline-path-completion Headlines in the current buffer are offered via
1504 completion.
1505 refile Use the refile interface, and offer headlines,
1506 possibly from different buffers."
1507 :group 'org-remember
1508 :type '(choice
1509 (const :tag "Refile" refile)
1510 (const :tag "Outline" outline)
1511 (const :tag "Outline-path-completion" outline-path-completion)))
1513 (defcustom org-goto-interface 'outline
1514 "The default interface to be used for `org-goto'.
1515 Allowed vaues are:
1516 outline The interface shows an outline of the relevant file
1517 and the correct heading is found by moving through
1518 the outline or by searching with incremental search.
1519 outline-path-completion Headlines in the current buffer are offered via
1520 completion."
1521 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1522 :type '(choice
1523 (const :tag "Outline" outline)
1524 (const :tag "Outline-path-completion" outline-path-completion)))
1526 (defcustom org-remember-default-headline ""
1527 "The headline that should be the default location in the notes file.
1528 When filing remember notes, the cursor will start at that position.
1529 You can set this on a per-template basis with the variable
1530 `org-remember-templates'."
1531 :group 'org-remember
1532 :type 'string)
1534 (defcustom org-remember-templates nil
1535 "Templates for the creation of remember buffers.
1536 When nil, just let remember make the buffer.
1537 When not nil, this is a list of 5-element lists. In each entry, the first
1538 element is the name of the template, which should be a single short word.
1539 The second element is a character, a unique key to select this template.
1540 The third element is the template. The fourth element is optional and can
1541 specify a destination file for remember items created with this template.
1542 The default file is given by `org-default-notes-file'. An optional fifth
1543 element can specify the headline in that file that should be offered
1544 first when the user is asked to file the entry. The default headline is
1545 given in the variable `org-remember-default-headline'.
1547 The template specifies the structure of the remember buffer. It should have
1548 a first line starting with a star, to act as the org-mode headline.
1549 Furthermore, the following %-escapes will be replaced with content:
1551 %^{prompt} Prompt the user for a string and replace this sequence with it.
1552 A default value and a completion table ca be specified like this:
1553 %^{prompt|default|completion2|completion3|...}
1554 %t time stamp, date only
1555 %T time stamp with date and time
1556 %u, %U like the above, but inactive time stamps
1557 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1558 You may define a prompt like %^{Please specify birthday}t
1559 %n user name (taken from `user-full-name')
1560 %a annotation, normally the link created with org-store-link
1561 %i initial content, the region active. If %i is indented,
1562 the entire inserted text will be indented as well.
1563 %c content of the clipboard, or current kill ring head
1564 %^g prompt for tags, with completion on tags in target file
1565 %^G prompt for tags, with completion all tags in all agenda files
1566 %:keyword specific information for certain link types, see below
1567 %[pathname] insert the contents of the file given by `pathname'
1568 %(sexp) evaluate elisp `(sexp)' and replace with the result
1569 %! Store this note immediately after filling the template
1571 %? After completing the template, position cursor here.
1573 Apart from these general escapes, you can access information specific to the
1574 link type that is created. For example, calling `remember' in emails or gnus
1575 will record the author and the subject of the message, which you can access
1576 with %:author and %:subject, respectively. Here is a complete list of what
1577 is recorded for each link type.
1579 Link type | Available information
1580 -------------------+------------------------------------------------------
1581 bbdb | %:type %:name %:company
1582 vm, wl, mh, rmail | %:type %:subject %:message-id
1583 | %:from %:fromname %:fromaddress
1584 | %:to %:toname %:toaddress
1585 | %:fromto (either \"to NAME\" or \"from NAME\")
1586 gnus | %:group, for messages also all email fields
1587 w3, w3m | %:type %:url
1588 info | %:type %:file %:node
1589 calendar | %:type %:date"
1590 :group 'org-remember
1591 :get (lambda (var) ; Make sure all entries have 5 elements
1592 (mapcar (lambda (x)
1593 (if (not (stringp (car x))) (setq x (cons "" x)))
1594 (cond ((= (length x) 4) (append x '("")))
1595 ((= (length x) 3) (append x '("" "")))
1596 (t x)))
1597 (default-value var)))
1598 :type '(repeat
1599 :tag "enabled"
1600 (list :value ("" ?a "\n" nil nil)
1601 (string :tag "Name")
1602 (character :tag "Selection Key")
1603 (string :tag "Template")
1604 (choice
1605 (file :tag "Destination file")
1606 (const :tag "Prompt for file" nil))
1607 (choice
1608 (string :tag "Destination headline")
1609 (const :tag "Selection interface for heading")))))
1611 (defcustom org-reverse-note-order nil
1612 "Non-nil means, store new notes at the beginning of a file or entry.
1613 When nil, new notes will be filed to the end of a file or entry.
1614 This can also be a list with cons cells of regular expressions that
1615 are matched against file names, and values."
1616 :group 'org-remember
1617 :type '(choice
1618 (const :tag "Reverse always" t)
1619 (const :tag "Reverse never" nil)
1620 (repeat :tag "By file name regexp"
1621 (cons regexp boolean))))
1623 (defcustom org-refile-targets nil
1624 "Targets for refiling entries with \\[org-refile].
1625 This is list of cons cells. Each cell contains:
1626 - a specification of the files to be considered, either a list of files,
1627 or a symbol whose function or value fields will be used to retrieve
1628 a file name or a list of file names. Nil means, refile to a different
1629 heading in the current buffer.
1630 - A specification of how to find candidate refile targets. This may be
1631 any of
1632 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1633 This tag has to be present in all target headlines, inheritance will
1634 not be considered.
1635 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1636 todo keyword.
1637 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1638 headlines that are refiling targets.
1639 - a cons cell (:level . N). Any headline of level N is considered a target.
1640 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1641 ;; FIXME: what if there are a var and func with same name???
1642 :group 'org-remember
1643 :type '(repeat
1644 (cons
1645 (choice :value org-agenda-files
1646 (const :tag "All agenda files" org-agenda-files)
1647 (const :tag "Current buffer" nil)
1648 (function) (variable) (file))
1649 (choice :tag "Identify target headline by"
1650 (cons :tag "Specific tag" (const :tag) (string))
1651 (cons :tag "TODO keyword" (const :todo) (string))
1652 (cons :tag "Regular expression" (const :regexp) (regexp))
1653 (cons :tag "Level number" (const :level) (integer))
1654 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1656 (defcustom org-refile-use-outline-path nil
1657 "Non-nil means, provide refile targets as paths.
1658 So a level 3 headline will be available as level1/level2/level3.
1659 When the value is `file', also include the file name (without directory)
1660 into the path. When `full-file-path', include the full file path."
1661 :group 'org-remember
1662 :type '(choice
1663 (const :tag "Not" nil)
1664 (const :tag "Yes" t)
1665 (const :tag "Start with file name" file)
1666 (const :tag "Start with full file path" full-file-path)))
1668 (defgroup org-todo nil
1669 "Options concerning TODO items in Org-mode."
1670 :tag "Org TODO"
1671 :group 'org)
1673 (defgroup org-progress nil
1674 "Options concerning Progress logging in Org-mode."
1675 :tag "Org Progress"
1676 :group 'org-time)
1678 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1679 "List of TODO entry keyword sequences and their interpretation.
1680 \\<org-mode-map>This is a list of sequences.
1682 Each sequence starts with a symbol, either `sequence' or `type',
1683 indicating if the keywords should be interpreted as a sequence of
1684 action steps, or as different types of TODO items. The first
1685 keywords are states requiring action - these states will select a headline
1686 for inclusion into the global TODO list Org-mode produces. If one of
1687 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1688 signify that no further action is necessary. If \"|\" is not found,
1689 the last keyword is treated as the only DONE state of the sequence.
1691 The command \\[org-todo] cycles an entry through these states, and one
1692 additional state where no keyword is present. For details about this
1693 cycling, see the manual.
1695 TODO keywords and interpretation can also be set on a per-file basis with
1696 the special #+SEQ_TODO and #+TYP_TODO lines.
1698 Each keyword can optionally specify a character for fast state selection
1699 \(in combination with the variable `org-use-fast-todo-selection')
1700 and specifiers for state change logging, using the same syntax
1701 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1702 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1703 indicates to record a time stamp each time this state is selected.
1704 \"WAIT(w@)\" says that the user should in addition be prompted for a
1705 note, and \"WAIT(w@/@)\" says that a note should be taken both when
1706 entering and when leaving this state.
1708 For backward compatibility, this variable may also be just a list
1709 of keywords - in this case the interptetation (sequence or type) will be
1710 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1711 :group 'org-todo
1712 :group 'org-keywords
1713 :type '(choice
1714 (repeat :tag "Old syntax, just keywords"
1715 (string :tag "Keyword"))
1716 (repeat :tag "New syntax"
1717 (cons
1718 (choice
1719 :tag "Interpretation"
1720 (const :tag "Sequence (cycling hits every state)" sequence)
1721 (const :tag "Type (cycling directly to DONE)" type))
1722 (repeat
1723 (string :tag "Keyword"))))))
1725 (defvar org-todo-keywords-1 nil
1726 "All TODO and DONE keywords active in a buffer.")
1727 (make-variable-buffer-local 'org-todo-keywords-1)
1728 (defvar org-todo-keywords-for-agenda nil)
1729 (defvar org-done-keywords-for-agenda nil)
1730 (defvar org-not-done-keywords nil)
1731 (make-variable-buffer-local 'org-not-done-keywords)
1732 (defvar org-done-keywords nil)
1733 (make-variable-buffer-local 'org-done-keywords)
1734 (defvar org-todo-heads nil)
1735 (make-variable-buffer-local 'org-todo-heads)
1736 (defvar org-todo-sets nil)
1737 (make-variable-buffer-local 'org-todo-sets)
1738 (defvar org-todo-log-states nil)
1739 (make-variable-buffer-local 'org-todo-log-states)
1740 (defvar org-todo-kwd-alist nil)
1741 (make-variable-buffer-local 'org-todo-kwd-alist)
1742 (defvar org-todo-key-alist nil)
1743 (make-variable-buffer-local 'org-todo-key-alist)
1744 (defvar org-todo-key-trigger nil)
1745 (make-variable-buffer-local 'org-todo-key-trigger)
1747 (defcustom org-todo-interpretation 'sequence
1748 "Controls how TODO keywords are interpreted.
1749 This variable is in principle obsolete and is only used for
1750 backward compatibility, if the interpretation of todo keywords is
1751 not given already in `org-todo-keywords'. See that variable for
1752 more information."
1753 :group 'org-todo
1754 :group 'org-keywords
1755 :type '(choice (const sequence)
1756 (const type)))
1758 (defcustom org-use-fast-todo-selection 'prefix
1759 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1760 This variable describes if and under what circumstances the cycling
1761 mechanism for TODO keywords will be replaced by a single-key, direct
1762 selection scheme.
1764 When nil, fast selection is never used.
1766 When the symbol `prefix', it will be used when `org-todo' is called with
1767 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1768 in an agenda buffer.
1770 When t, fast selection is used by default. In this case, the prefix
1771 argument forces cycling instead.
1773 In all cases, the special interface is only used if access keys have actually
1774 been assigned by the user, i.e. if keywords in the configuration are followed
1775 by a letter in parenthesis, like TODO(t)."
1776 :group 'org-todo
1777 :type '(choice
1778 (const :tag "Never" nil)
1779 (const :tag "By default" t)
1780 (const :tag "Only with C-u C-c C-t" prefix)))
1782 (defcustom org-after-todo-state-change-hook nil
1783 "Hook which is run after the state of a TODO item was changed.
1784 The new state (a string with a TODO keyword, or nil) is available in the
1785 Lisp variable `state'."
1786 :group 'org-todo
1787 :type 'hook)
1789 (defcustom org-log-done nil
1790 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1791 When equal to the list (done), also prompt for a closing note.
1792 This can also be configured on a per-file basis by adding one of
1793 the following lines anywhere in the buffer:
1795 #+STARTUP: logdone
1796 #+STARTUP: lognotedone
1797 #+STARTUP: nologdone"
1798 :group 'org-todo
1799 :group 'org-progress
1800 :type '(choice
1801 (const :tag "No logging" nil)
1802 (const :tag "Record CLOSED timestamp" time)
1803 (const :tag "Record CLOSED timestamp with closing note." note)))
1805 ;; Normalize old uses of org-log-done.
1806 (cond
1807 ((eq org-log-done t) (setq org-log-done 'time))
1808 ((and (listp org-log-done) (memq 'done org-log-done))
1809 (setq org-log-done 'note)))
1811 ;; FIXME: document
1812 (defcustom org-log-note-clock-out nil
1813 "Non-nil means, recored a note when clocking out of an item.
1814 This can also be configured on a per-file basis by adding one of
1815 the following lines anywhere in the buffer:
1817 #+STARTUP: lognoteclock-out
1818 #+STARTUP: nolognoteclock-out"
1819 :group 'org-todo
1820 :group 'org-progress
1821 :type 'boolean)
1823 (defcustom org-log-done-with-time t
1824 "Non-nil means, the CLOSED time stamp will contain date and time.
1825 When nil, only the date will be recorded."
1826 :group 'org-progress
1827 :type 'boolean)
1829 (defcustom org-log-note-headings
1830 '((done . "CLOSING NOTE %t")
1831 (state . "State %-12s %t")
1832 (clock-out . ""))
1833 "Headings for notes added when clocking out or closing TODO items.
1834 The value is an alist, with the car being a symbol indicating the note
1835 context, and the cdr is the heading to be used. The heading may also be the
1836 empty string.
1837 %t in the heading will be replaced by a time stamp.
1838 %s will be replaced by the new TODO state, in double quotes.
1839 %u will be replaced by the user name.
1840 %U will be replaced by the full user name."
1841 :group 'org-todo
1842 :group 'org-progress
1843 :type '(list :greedy t
1844 (cons (const :tag "Heading when closing an item" done) string)
1845 (cons (const :tag
1846 "Heading when changing todo state (todo sequence only)"
1847 state) string)
1848 (cons (const :tag "Heading when clocking out" clock-out) string)))
1850 (defcustom org-log-states-order-reversed t
1851 "Non-nil means, the latest state change note will be directly after heading.
1852 When nil, the notes will be orderer according to time."
1853 :group 'org-todo
1854 :group 'org-progress
1855 :type 'boolean)
1857 (defcustom org-log-repeat 'time
1858 "Non-nil means, record moving through the DONE state when triggering repeat.
1859 An auto-repeating tasks is immediately switched back to TODO when marked
1860 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1861 the TODO keyword definition, or recording a cloing note by setting
1862 `org-log-done', there will be no record of the task moving trhough DONE.
1863 This variable forces taking a note anyway. Possible values are:
1865 nil Don't force a record
1866 time Record a time stamp
1867 note Record a note
1869 This option can also be set with on a per-file-basis with
1871 #+STARTUP: logrepeat
1872 #+STARTUP: lognoterepeat
1873 #+STARTUP: nologrepeat
1875 You can have local logging settings for a subtree by setting the LOGGING
1876 property to one or more of these keywords."
1877 :group 'org-todo
1878 :group 'org-progress
1879 :type '(choice
1880 (const :tag "Don't force a record" nil)
1881 (const :tag "Force recording the DONE state" time)
1882 (const :tag "Force recording a note with the DONE state" note)))
1884 (defcustom org-clock-into-drawer 2
1885 "Should clocking info be wrapped into a drawer?
1886 When t, clocking info will always be inserted into a :CLOCK: drawer.
1887 If necessary, the drawer will be created.
1888 When nil, the drawer will not be created, but used when present.
1889 When an integer and the number of clocking entries in an item
1890 reaches or exceeds this number, a drawer will be created."
1891 :group 'org-todo
1892 :group 'org-progress
1893 :type '(choice
1894 (const :tag "Always" t)
1895 (const :tag "Only when drawer exists" nil)
1896 (integer :tag "When at least N clock entries")))
1898 (defcustom org-clock-out-when-done t
1899 "When t, the clock will be stopped when the relevant entry is marked DONE.
1900 Nil means, clock will keep running until stopped explicitly with
1901 `C-c C-x C-o', or until the clock is started in a different item."
1902 :group 'org-progress
1903 :type 'boolean)
1905 (defcustom org-clock-in-switch-to-state nil
1906 "Set task to a special todo state while clocking it.
1907 The value should be the state to which the entry should be switched."
1908 :group 'org-progress
1909 :group 'org-todo
1910 :type '(choice
1911 (const :tag "Don't force a state" nil)
1912 (string :tag "State")))
1914 (defgroup org-priorities nil
1915 "Priorities in Org-mode."
1916 :tag "Org Priorities"
1917 :group 'org-todo)
1919 (defcustom org-highest-priority ?A
1920 "The highest priority of TODO items. A character like ?A, ?B etc.
1921 Must have a smaller ASCII number than `org-lowest-priority'."
1922 :group 'org-priorities
1923 :type 'character)
1925 (defcustom org-lowest-priority ?C
1926 "The lowest priority of TODO items. A character like ?A, ?B etc.
1927 Must have a larger ASCII number than `org-highest-priority'."
1928 :group 'org-priorities
1929 :type 'character)
1931 (defcustom org-default-priority ?B
1932 "The default priority of TODO items.
1933 This is the priority an item get if no explicit priority is given."
1934 :group 'org-priorities
1935 :type 'character)
1937 (defcustom org-priority-start-cycle-with-default t
1938 "Non-nil means, start with default priority when starting to cycle.
1939 When this is nil, the first step in the cycle will be (depending on the
1940 command used) one higher or lower that the default priority."
1941 :group 'org-priorities
1942 :type 'boolean)
1944 (defgroup org-time nil
1945 "Options concerning time stamps and deadlines in Org-mode."
1946 :tag "Org Time"
1947 :group 'org)
1949 (defcustom org-insert-labeled-timestamps-at-point nil
1950 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1951 When nil, these labeled time stamps are forces into the second line of an
1952 entry, just after the headline. When scheduling from the global TODO list,
1953 the time stamp will always be forced into the second line."
1954 :group 'org-time
1955 :type 'boolean)
1957 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1958 "Formats for `format-time-string' which are used for time stamps.
1959 It is not recommended to change this constant.")
1961 (defcustom org-time-stamp-rounding-minutes 0
1962 "Number of minutes to round time stamps to upon insertion.
1963 When zero, insert the time unmodified. Useful rounding numbers
1964 should be factors of 60, so for example 5, 10, 15.
1965 When this is not zero, you can still force an exact time-stamp by using
1966 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1967 :group 'org-time
1968 :type 'integer)
1970 (defcustom org-display-custom-times nil
1971 "Non-nil means, overlay custom formats over all time stamps.
1972 The formats are defined through the variable `org-time-stamp-custom-formats'.
1973 To turn this on on a per-file basis, insert anywhere in the file:
1974 #+STARTUP: customtime"
1975 :group 'org-time
1976 :set 'set-default
1977 :type 'sexp)
1978 (make-variable-buffer-local 'org-display-custom-times)
1980 (defcustom org-time-stamp-custom-formats
1981 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1982 "Custom formats for time stamps. See `format-time-string' for the syntax.
1983 These are overlayed over the default ISO format if the variable
1984 `org-display-custom-times' is set. Time like %H:%M should be at the
1985 end of the second format."
1986 :group 'org-time
1987 :type 'sexp)
1989 (defun org-time-stamp-format (&optional long inactive)
1990 "Get the right format for a time string."
1991 (let ((f (if long (cdr org-time-stamp-formats)
1992 (car org-time-stamp-formats))))
1993 (if inactive
1994 (concat "[" (substring f 1 -1) "]")
1995 f)))
1997 (defcustom org-read-date-prefer-future t
1998 "Non-nil means, assume future for incomplete date input from user.
1999 This affects the following situations:
2000 1. The user gives a day, but no month.
2001 For example, if today is the 15th, and you enter \"3\", Org-mode will
2002 read this as the third of *next* month. However, if you enter \"17\",
2003 it will be considered as *this* month.
2004 2. The user gives a month but not a year.
2005 For example, if it is april and you enter \"feb 2\", this will be read
2006 as feb 2, *next* year. \"May 5\", however, will be this year.
2008 When this option is nil, the current month and year will always be used
2009 as defaults."
2010 :group 'org-time
2011 :type 'boolean)
2013 (defcustom org-read-date-display-live t
2014 "Non-nil means, display current interpretation of date prompt live.
2015 This display will be in an overlay, in the minibuffer."
2016 :group 'org-time
2017 :type 'boolean)
2019 (defcustom org-read-date-popup-calendar t
2020 "Non-nil means, pop up a calendar when prompting for a date.
2021 In the calendar, the date can be selected with mouse-1. However, the
2022 minibuffer will also be active, and you can simply enter the date as well.
2023 When nil, only the minibuffer will be available."
2024 :group 'org-time
2025 :type 'boolean)
2026 (if (fboundp 'defvaralias)
2027 (defvaralias 'org-popup-calendar-for-date-prompt
2028 'org-read-date-popup-calendar))
2030 (defcustom org-extend-today-until 0
2031 "The hour when your day really ends.
2032 This has influence for the following applications:
2033 - When switching the agenda to \"today\". It it is still earlier than
2034 the time given here, the day recognized as TODAY is actually yesterday.
2035 - When a date is read from the user and it is still before the time given
2036 here, the current date and time will be assumed to be yesterday, 23:59.
2038 FIXME:
2039 IMPORTANT: This is still a very experimental feature, it may disappear
2040 again or it may be extended to mean more things."
2041 :group 'org-time
2042 :type 'number)
2044 (defcustom org-edit-timestamp-down-means-later nil
2045 "Non-nil means, S-down will increase the time in a time stamp.
2046 When nil, S-up will increase."
2047 :group 'org-time
2048 :type 'boolean)
2050 (defcustom org-calendar-follow-timestamp-change t
2051 "Non-nil means, make the calendar window follow timestamp changes.
2052 When a timestamp is modified and the calendar window is visible, it will be
2053 moved to the new date."
2054 :group 'org-time
2055 :type 'boolean)
2057 (defcustom org-clock-heading-function nil
2058 "When non-nil, should be a function to create `org-clock-heading'.
2059 This is the string shown in the mode line when a clock is running.
2060 The function is called with point at the beginning of the headline."
2061 :group 'org-time ; FIXME: Should we have a separate group????
2062 :type 'function)
2064 (defgroup org-tags nil
2065 "Options concerning tags in Org-mode."
2066 :tag "Org Tags"
2067 :group 'org)
2069 (defcustom org-tag-alist nil
2070 "List of tags allowed in Org-mode files.
2071 When this list is nil, Org-mode will base TAG input on what is already in the
2072 buffer.
2073 The value of this variable is an alist, the car of each entry must be a
2074 keyword as a string, the cdr may be a character that is used to select
2075 that tag through the fast-tag-selection interface.
2076 See the manual for details."
2077 :group 'org-tags
2078 :type '(repeat
2079 (choice
2080 (cons (string :tag "Tag name")
2081 (character :tag "Access char"))
2082 (const :tag "Start radio group" (:startgroup))
2083 (const :tag "End radio group" (:endgroup)))))
2085 (defcustom org-use-fast-tag-selection 'auto
2086 "Non-nil means, use fast tag selection scheme.
2087 This is a special interface to select and deselect tags with single keys.
2088 When nil, fast selection is never used.
2089 When the symbol `auto', fast selection is used if and only if selection
2090 characters for tags have been configured, either through the variable
2091 `org-tag-alist' or through a #+TAGS line in the buffer.
2092 When t, fast selection is always used and selection keys are assigned
2093 automatically if necessary."
2094 :group 'org-tags
2095 :type '(choice
2096 (const :tag "Always" t)
2097 (const :tag "Never" nil)
2098 (const :tag "When selection characters are configured" 'auto)))
2100 (defcustom org-fast-tag-selection-single-key nil
2101 "Non-nil means, fast tag selection exits after first change.
2102 When nil, you have to press RET to exit it.
2103 During fast tag selection, you can toggle this flag with `C-c'.
2104 This variable can also have the value `expert'. In this case, the window
2105 displaying the tags menu is not even shown, until you press C-c again."
2106 :group 'org-tags
2107 :type '(choice
2108 (const :tag "No" nil)
2109 (const :tag "Yes" t)
2110 (const :tag "Expert" expert)))
2112 (defvar org-fast-tag-selection-include-todo nil
2113 "Non-nil means, fast tags selection interface will also offer TODO states.
2114 This is an undocumented feature, you should not rely on it.")
2116 (defcustom org-tags-column -80
2117 "The column to which tags should be indented in a headline.
2118 If this number is positive, it specifies the column. If it is negative,
2119 it means that the tags should be flushright to that column. For example,
2120 -80 works well for a normal 80 character screen."
2121 :group 'org-tags
2122 :type 'integer)
2124 (defcustom org-auto-align-tags t
2125 "Non-nil means, realign tags after pro/demotion of TODO state change.
2126 These operations change the length of a headline and therefore shift
2127 the tags around. With this options turned on, after each such operation
2128 the tags are again aligned to `org-tags-column'."
2129 :group 'org-tags
2130 :type 'boolean)
2132 (defcustom org-use-tag-inheritance t
2133 "Non-nil means, tags in levels apply also for sublevels.
2134 When nil, only the tags directly given in a specific line apply there.
2135 If you turn off this option, you very likely want to turn on the
2136 companion option `org-tags-match-list-sublevels'."
2137 :group 'org-tags
2138 :type 'boolean)
2140 (defcustom org-tags-match-list-sublevels nil
2141 "Non-nil means list also sublevels of headlines matching tag search.
2142 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2143 the sublevels of a headline matching a tag search often also match
2144 the same search. Listing all of them can create very long lists.
2145 Setting this variable to nil causes subtrees of a match to be skipped.
2146 This option is off by default, because inheritance in on. If you turn
2147 inheritance off, you very likely want to turn this option on.
2149 As a special case, if the tag search is restricted to TODO items, the
2150 value of this variable is ignored and sublevels are always checked, to
2151 make sure all corresponding TODO items find their way into the list."
2152 :group 'org-tags
2153 :type 'boolean)
2155 (defvar org-tags-history nil
2156 "History of minibuffer reads for tags.")
2157 (defvar org-last-tags-completion-table nil
2158 "The last used completion table for tags.")
2159 (defvar org-after-tags-change-hook nil
2160 "Hook that is run after the tags in a line have changed.")
2162 (defgroup org-properties nil
2163 "Options concerning properties in Org-mode."
2164 :tag "Org Properties"
2165 :group 'org)
2167 (defcustom org-property-format "%-10s %s"
2168 "How property key/value pairs should be formatted by `indent-line'.
2169 When `indent-line' hits a property definition, it will format the line
2170 according to this format, mainly to make sure that the values are
2171 lined-up with respect to each other."
2172 :group 'org-properties
2173 :type 'string)
2175 (defcustom org-use-property-inheritance nil
2176 "Non-nil means, properties apply also for sublevels.
2177 This setting is only relevant during property searches, not when querying
2178 an entry with `org-entry-get'. To retrieve a property with inheritance,
2179 you need to call `org-entry-get' with the inheritance flag.
2180 Turning this on can cause significant overhead when doing a search, so
2181 this is turned off by default.
2182 When nil, only the properties directly given in the current entry count.
2183 The value may also be a list of properties that shouldhave inheritance.
2185 However, note that some special properties use inheritance under special
2186 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2187 and the properties ending in \"_ALL\" when they are used as descriptor
2188 for valid values of a property."
2189 :group 'org-properties
2190 :type '(choice
2191 (const :tag "Not" nil)
2192 (const :tag "Always" nil)
2193 (repeat :tag "Specific properties" (string :tag "Property"))))
2195 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2196 "The default column format, if no other format has been defined.
2197 This variable can be set on the per-file basis by inserting a line
2199 #+COLUMNS: %25ITEM ....."
2200 :group 'org-properties
2201 :type 'string)
2203 (defcustom org-global-properties nil
2204 "List of property/value pairs that can be inherited by any entry.
2205 You can set buffer-local values for this by adding lines like
2207 #+PROPERTY: NAME VALUE"
2208 :group 'org-properties
2209 :type '(repeat
2210 (cons (string :tag "Property")
2211 (string :tag "Value"))))
2213 (defvar org-local-properties nil
2214 "List of property/value pairs that can be inherited by any entry.
2215 Valid for the current buffer.
2216 This variable is populated from #+PROPERTY lines.")
2218 (defgroup org-agenda nil
2219 "Options concerning agenda views in Org-mode."
2220 :tag "Org Agenda"
2221 :group 'org)
2223 (defvar org-category nil
2224 "Variable used by org files to set a category for agenda display.
2225 Such files should use a file variable to set it, for example
2227 # -*- mode: org; org-category: \"ELisp\"
2229 or contain a special line
2231 #+CATEGORY: ELisp
2233 If the file does not specify a category, then file's base name
2234 is used instead.")
2235 (make-variable-buffer-local 'org-category)
2237 (defcustom org-agenda-files nil
2238 "The files to be used for agenda display.
2239 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2240 \\[org-remove-file]. You can also use customize to edit the list.
2242 If an entry is a directory, all files in that directory that are matched by
2243 `org-agenda-file-regexp' will be part of the file list.
2245 If the value of the variable is not a list but a single file name, then
2246 the list of agenda files is actually stored and maintained in that file, one
2247 agenda file per line."
2248 :group 'org-agenda
2249 :type '(choice
2250 (repeat :tag "List of files and directories" file)
2251 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2253 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2254 "Regular expression to match files for `org-agenda-files'.
2255 If any element in the list in that variable contains a directory instead
2256 of a normal file, all files in that directory that are matched by this
2257 regular expression will be included."
2258 :group 'org-agenda
2259 :type 'regexp)
2261 (defcustom org-agenda-skip-unavailable-files nil
2262 "t means to just skip non-reachable files in `org-agenda-files'.
2263 Nil means to remove them, after a query, from the list."
2264 :group 'org-agenda
2265 :type 'boolean)
2267 (defcustom org-agenda-text-search-extra-files nil
2268 "List of extra files to be searched by text search commands.
2269 These files will be search in addition to the agenda files bu the
2270 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2271 Note that these files will only be searched for text search commands,
2272 not for the other agenda views like todo lists, tag earches or the weekly
2273 agenda. This variable is intended to list notes and possibly archive files
2274 that should also be searched by these two commands."
2275 :group 'org-agenda
2276 :type '(repeat file))
2278 (if (fboundp 'defvaralias)
2279 (defvaralias 'org-agenda-multi-occur-extra-files
2280 'org-agenda-text-search-extra-files))
2282 (defcustom org-agenda-confirm-kill 1
2283 "When set, remote killing from the agenda buffer needs confirmation.
2284 When t, a confirmation is always needed. When a number N, confirmation is
2285 only needed when the text to be killed contains more than N non-white lines."
2286 :group 'org-agenda
2287 :type '(choice
2288 (const :tag "Never" nil)
2289 (const :tag "Always" t)
2290 (number :tag "When more than N lines")))
2292 (defcustom org-calendar-to-agenda-key [?c]
2293 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2294 The command `org-calendar-goto-agenda' will be bound to this key. The
2295 default is the character `c' because then `c' can be used to switch back and
2296 forth between agenda and calendar."
2297 :group 'org-agenda
2298 :type 'sexp)
2300 (defcustom org-agenda-compact-blocks nil
2301 "Non-nil means, make the block agenda more compact.
2302 This is done by leaving out unnecessary lines."
2303 :group 'org-agenda
2304 :type nil)
2306 (defgroup org-agenda-export nil
2307 "Options concerning exporting agenda views in Org-mode."
2308 :tag "Org Agenda Export"
2309 :group 'org-agenda)
2311 (defcustom org-agenda-with-colors t
2312 "Non-nil means, use colors in agenda views."
2313 :group 'org-agenda-export
2314 :type 'boolean)
2316 (defcustom org-agenda-exporter-settings nil
2317 "Alist of variable/value pairs that should be active during agenda export.
2318 This is a good place to set uptions for ps-print and for htmlize."
2319 :group 'org-agenda-export
2320 :type '(repeat
2321 (list
2322 (variable)
2323 (sexp :tag "Value"))))
2325 (defcustom org-agenda-export-html-style ""
2326 "The style specification for exported HTML Agenda files.
2327 If this variable contains a string, it will replace the default <style>
2328 section as produced by `htmlize'.
2329 Since there are different ways of setting style information, this variable
2330 needs to contain the full HTML structure to provide a style, including the
2331 surrounding HTML tags. The style specifications should include definitions
2332 the fonts used by the agenda, here is an example:
2334 <style type=\"text/css\">
2335 p { font-weight: normal; color: gray; }
2336 .org-agenda-structure {
2337 font-size: 110%;
2338 color: #003399;
2339 font-weight: 600;
2341 .org-todo {
2342 color: #cc6666;Week-agenda:
2343 font-weight: bold;
2345 .org-done {
2346 color: #339933;
2348 .title { text-align: center; }
2349 .todo, .deadline { color: red; }
2350 .done { color: green; }
2351 </style>
2353 or, if you want to keep the style in a file,
2355 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2357 As the value of this option simply gets inserted into the HTML <head> header,
2358 you can \"misuse\" it to also add other text to the header. However,
2359 <style>...</style> is required, if not present the variable will be ignored."
2360 :group 'org-agenda-export
2361 :group 'org-export-html
2362 :type 'string)
2364 (defgroup org-agenda-custom-commands nil
2365 "Options concerning agenda views in Org-mode."
2366 :tag "Org Agenda Custom Commands"
2367 :group 'org-agenda)
2369 (defcustom org-agenda-custom-commands nil
2370 "Custom commands for the agenda.
2371 These commands will be offered on the splash screen displayed by the
2372 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2374 (key desc type match options files)
2376 key The key (one or more characters as a string) to be associated
2377 with the command.
2378 desc A description of the commend, when omitted or nil, a default
2379 description is built using MATCH.
2380 type The command type, any of the following symbols:
2381 agenda The daily/weekly agenda.
2382 todo Entries with a specific TODO keyword, in all agenda files.
2383 search Entries containing search words entry or headline.
2384 tags Tags/Property/TODO match in all agenda files.
2385 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2386 todo-tree Sparse tree of specific TODO keyword in *current* file.
2387 tags-tree Sparse tree with all tags matches in *current* file.
2388 occur-tree Occur sparse tree for *current* file.
2389 ... A user-defined function.
2390 match What to search for:
2391 - a single keyword for TODO keyword searches
2392 - a tags match expression for tags searches
2393 - a regular expression for occur searches
2394 options A list of option settings, similar to that in a let form, so like
2395 this: ((opt1 val1) (opt2 val2) ...)
2396 files A list of files file to write the produced agenda buffer to
2397 with the command `org-store-agenda-views'.
2398 If a file name ends in \".html\", an HTML version of the buffer
2399 is written out. If it ends in \".ps\", a postscript version is
2400 produced. Otherwide, only the plain text is written to the file.
2402 You can also define a set of commands, to create a composite agenda buffer.
2403 In this case, an entry looks like this:
2405 (key desc (cmd1 cmd2 ...) general-options file)
2407 where
2409 desc A description string to be displayed in the dispatcher menu.
2410 cmd An agenda command, similar to the above. However, tree commands
2411 are no allowed, but instead you can get agenda and global todo list.
2412 So valid commands for a set are:
2413 (agenda)
2414 (alltodo)
2415 (stuck)
2416 (todo \"match\" options files)
2417 (search \"match\" options files)
2418 (tags \"match\" options files)
2419 (tags-todo \"match\" options files)
2421 Each command can carry a list of options, and another set of options can be
2422 given for the whole set of commands. Individual command options take
2423 precedence over the general options.
2425 When using several characters as key to a command, the first characters
2426 are prefix commands. For the dispatcher to display useful information, you
2427 should provide a description for the prefix, like
2429 (setq org-agenda-custom-commands
2430 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2431 (\"hl\" tags \"+HOME+Lisa\")
2432 (\"hp\" tags \"+HOME+Peter\")
2433 (\"hk\" tags \"+HOME+Kim\")))"
2434 :group 'org-agenda-custom-commands
2435 :type '(repeat
2436 (choice :value ("a" "" tags "" nil)
2437 (list :tag "Single command"
2438 (string :tag "Access Key(s) ")
2439 (option (string :tag "Description"))
2440 (choice
2441 (const :tag "Agenda" agenda)
2442 (const :tag "TODO list" alltodo)
2443 (const :tag "Search words" search)
2444 (const :tag "Stuck projects" stuck)
2445 (const :tag "Tags search (all agenda files)" tags)
2446 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2447 (const :tag "TODO keyword search (all agenda files)" todo)
2448 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2449 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2450 (const :tag "Occur tree (current buffer)" occur-tree)
2451 (sexp :tag "Other, user-defined function"))
2452 (string :tag "Match")
2453 (repeat :tag "Local options"
2454 (list (variable :tag "Option") (sexp :tag "Value")))
2455 (option (repeat :tag "Export" (file :tag "Export to"))))
2456 (list :tag "Command series, all agenda files"
2457 (string :tag "Access Key(s)")
2458 (string :tag "Description ")
2459 (repeat
2460 (choice
2461 (const :tag "Agenda" (agenda))
2462 (const :tag "TODO list" (alltodo))
2463 (list :tag "Search words"
2464 (const :format "" search)
2465 (string :tag "Match")
2466 (repeat :tag "Local options"
2467 (list (variable :tag "Option")
2468 (sexp :tag "Value"))))
2469 (const :tag "Stuck projects" (stuck))
2470 (list :tag "Tags search"
2471 (const :format "" tags)
2472 (string :tag "Match")
2473 (repeat :tag "Local options"
2474 (list (variable :tag "Option")
2475 (sexp :tag "Value"))))
2477 (list :tag "Tags search, TODO entries only"
2478 (const :format "" tags-todo)
2479 (string :tag "Match")
2480 (repeat :tag "Local options"
2481 (list (variable :tag "Option")
2482 (sexp :tag "Value"))))
2484 (list :tag "TODO keyword search"
2485 (const :format "" todo)
2486 (string :tag "Match")
2487 (repeat :tag "Local options"
2488 (list (variable :tag "Option")
2489 (sexp :tag "Value"))))
2491 (list :tag "Other, user-defined function"
2492 (symbol :tag "function")
2493 (string :tag "Match")
2494 (repeat :tag "Local options"
2495 (list (variable :tag "Option")
2496 (sexp :tag "Value"))))))
2498 (repeat :tag "General options"
2499 (list (variable :tag "Option")
2500 (sexp :tag "Value")))
2501 (option (repeat :tag "Export" (file :tag "Export to"))))
2502 (cons :tag "Prefix key documentation"
2503 (string :tag "Access Key(s)")
2504 (string :tag "Description ")))))
2506 (defcustom org-agenda-query-register ?o
2507 "The register holding the current query string.
2508 The prupose of this is that if you construct a query string interactively,
2509 you can then use it to define a custom command."
2510 :group 'org-agenda-custom-commands
2511 :type 'character)
2513 (defcustom org-stuck-projects
2514 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2515 "How to identify stuck projects.
2516 This is a list of four items:
2517 1. A tags/todo matcher string that is used to identify a project.
2518 The entire tree below a headline matched by this is considered one project.
2519 2. A list of TODO keywords identifying non-stuck projects.
2520 If the project subtree contains any headline with one of these todo
2521 keywords, the project is considered to be not stuck. If you specify
2522 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2523 3. A list of tags identifying non-stuck projects.
2524 If the project subtree contains any headline with one of these tags,
2525 the project is considered to be not stuck. If you specify \"*\" as
2526 a tag, any tag will mark the project unstuck.
2527 4. An arbitrary regular expression matching non-stuck projects.
2529 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2530 or `C-c a #' to produce the list."
2531 :group 'org-agenda-custom-commands
2532 :type '(list
2533 (string :tag "Tags/TODO match to identify a project")
2534 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2535 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2536 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2539 (defgroup org-agenda-skip nil
2540 "Options concerning skipping parts of agenda files."
2541 :tag "Org Agenda Skip"
2542 :group 'org-agenda)
2544 (defcustom org-agenda-todo-list-sublevels t
2545 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2546 When nil, the sublevels of a TODO entry are not checked, resulting in
2547 potentially much shorter TODO lists."
2548 :group 'org-agenda-skip
2549 :group 'org-todo
2550 :type 'boolean)
2552 (defcustom org-agenda-todo-ignore-with-date nil
2553 "Non-nil means, don't show entries with a date in the global todo list.
2554 You can use this if you prefer to mark mere appointments with a TODO keyword,
2555 but don't want them to show up in the TODO list.
2556 When this is set, it also covers deadlines and scheduled items, the settings
2557 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2558 will be ignored."
2559 :group 'org-agenda-skip
2560 :group 'org-todo
2561 :type 'boolean)
2563 (defcustom org-agenda-todo-ignore-scheduled nil
2564 "Non-nil means, don't show scheduled entries in the global todo list.
2565 The idea behind this is that by scheduling it, you have already taken care
2566 of this item.
2567 See also `org-agenda-todo-ignore-with-date'."
2568 :group 'org-agenda-skip
2569 :group 'org-todo
2570 :type 'boolean)
2572 (defcustom org-agenda-todo-ignore-deadlines nil
2573 "Non-nil means, don't show near deadline entries in the global todo list.
2574 Near means closer than `org-deadline-warning-days' days.
2575 The idea behind this is that such items will appear in the agenda anyway.
2576 See also `org-agenda-todo-ignore-with-date'."
2577 :group 'org-agenda-skip
2578 :group 'org-todo
2579 :type 'boolean)
2581 (defcustom org-agenda-skip-scheduled-if-done nil
2582 "Non-nil means don't show scheduled items in agenda when they are done.
2583 This is relevant for the daily/weekly agenda, not for the TODO list. And
2584 it applies only to the actual date of the scheduling. Warnings about
2585 an item with a past scheduling dates are always turned off when the item
2586 is DONE."
2587 :group 'org-agenda-skip
2588 :type 'boolean)
2590 (defcustom org-agenda-skip-deadline-if-done nil
2591 "Non-nil means don't show deadines when the corresponding item is done.
2592 When nil, the deadline is still shown and should give you a happy feeling.
2593 This is relevant for the daily/weekly agenda. And it applied only to the
2594 actualy date of the deadline. Warnings about approching and past-due
2595 deadlines are always turned off when the item is DONE."
2596 :group 'org-agenda-skip
2597 :type 'boolean)
2599 (defcustom org-agenda-skip-timestamp-if-done nil
2600 "Non-nil means don't select item by timestamp or -range if it is DONE."
2601 :group 'org-agenda-skip
2602 :type 'boolean)
2604 (defcustom org-timeline-show-empty-dates 3
2605 "Non-nil means, `org-timeline' also shows dates without an entry.
2606 When nil, only the days which actually have entries are shown.
2607 When t, all days between the first and the last date are shown.
2608 When an integer, show also empty dates, but if there is a gap of more than
2609 N days, just insert a special line indicating the size of the gap."
2610 :group 'org-agenda-skip
2611 :type '(choice
2612 (const :tag "None" nil)
2613 (const :tag "All" t)
2614 (number :tag "at most")))
2617 (defgroup org-agenda-startup nil
2618 "Options concerning initial settings in the Agenda in Org Mode."
2619 :tag "Org Agenda Startup"
2620 :group 'org-agenda)
2622 (defcustom org-finalize-agenda-hook nil
2623 "Hook run just before displaying an agenda buffer."
2624 :group 'org-agenda-startup
2625 :type 'hook)
2627 (defcustom org-agenda-mouse-1-follows-link nil
2628 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2629 A longer mouse click will still set point. Does not work on XEmacs.
2630 Needs to be set before org.el is loaded."
2631 :group 'org-agenda-startup
2632 :type 'boolean)
2634 (defcustom org-agenda-start-with-follow-mode nil
2635 "The initial value of follow-mode in a newly created agenda window."
2636 :group 'org-agenda-startup
2637 :type 'boolean)
2639 (defgroup org-agenda-windows nil
2640 "Options concerning the windows used by the Agenda in Org Mode."
2641 :tag "Org Agenda Windows"
2642 :group 'org-agenda)
2644 (defcustom org-agenda-window-setup 'reorganize-frame
2645 "How the agenda buffer should be displayed.
2646 Possible values for this option are:
2648 current-window Show agenda in the current window, keeping all other windows.
2649 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2650 other-window Use `switch-to-buffer-other-window' to display agenda.
2651 reorganize-frame Show only two windows on the current frame, the current
2652 window and the agenda.
2653 See also the variable `org-agenda-restore-windows-after-quit'."
2654 :group 'org-agenda-windows
2655 :type '(choice
2656 (const current-window)
2657 (const other-frame)
2658 (const other-window)
2659 (const reorganize-frame)))
2661 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2662 "The min and max height of the agenda window as a fraction of frame height.
2663 The value of the variable is a cons cell with two numbers between 0 and 1.
2664 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2665 :group 'org-agenda-windows
2666 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2668 (defcustom org-agenda-restore-windows-after-quit nil
2669 "Non-nil means, restore window configuration open exiting agenda.
2670 Before the window configuration is changed for displaying the agenda,
2671 the current status is recorded. When the agenda is exited with
2672 `q' or `x' and this option is set, the old state is restored. If
2673 `org-agenda-window-setup' is `other-frame', the value of this
2674 option will be ignored.."
2675 :group 'org-agenda-windows
2676 :type 'boolean)
2678 (defcustom org-indirect-buffer-display 'other-window
2679 "How should indirect tree buffers be displayed?
2680 This applies to indirect buffers created with the commands
2681 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2682 Valid values are:
2683 current-window Display in the current window
2684 other-window Just display in another window.
2685 dedicated-frame Create one new frame, and re-use it each time.
2686 new-frame Make a new frame each time. Note that in this case
2687 previously-made indirect buffers are kept, and you need to
2688 kill these buffers yourself."
2689 :group 'org-structure
2690 :group 'org-agenda-windows
2691 :type '(choice
2692 (const :tag "In current window" current-window)
2693 (const :tag "In current frame, other window" other-window)
2694 (const :tag "Each time a new frame" new-frame)
2695 (const :tag "One dedicated frame" dedicated-frame)))
2697 (defgroup org-agenda-daily/weekly nil
2698 "Options concerning the daily/weekly agenda."
2699 :tag "Org Agenda Daily/Weekly"
2700 :group 'org-agenda)
2702 (defcustom org-agenda-ndays 7
2703 "Number of days to include in overview display.
2704 Should be 1 or 7."
2705 :group 'org-agenda-daily/weekly
2706 :type 'number)
2708 (defcustom org-agenda-start-on-weekday 1
2709 "Non-nil means, start the overview always on the specified weekday.
2710 0 denotes Sunday, 1 denotes Monday etc.
2711 When nil, always start on the current day."
2712 :group 'org-agenda-daily/weekly
2713 :type '(choice (const :tag "Today" nil)
2714 (number :tag "Weekday No.")))
2716 (defcustom org-agenda-show-all-dates t
2717 "Non-nil means, `org-agenda' shows every day in the selected range.
2718 When nil, only the days which actually have entries are shown."
2719 :group 'org-agenda-daily/weekly
2720 :type 'boolean)
2722 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2723 "Format string for displaying dates in the agenda.
2724 Used by the daily/weekly agenda and by the timeline. This should be
2725 a format string understood by `format-time-string', or a function returning
2726 the formatted date as a string. The function must take a single argument,
2727 a calendar-style date list like (month day year)."
2728 :group 'org-agenda-daily/weekly
2729 :type '(choice
2730 (string :tag "Format string")
2731 (function :tag "Function")))
2733 (defun org-agenda-format-date-aligned (date)
2734 "Format a date string for display in the daily/weekly agenda, or timeline.
2735 This function makes sure that dates are aligned for easy reading."
2736 (format "%-9s %2d %s %4d"
2737 (calendar-day-name date)
2738 (extract-calendar-day date)
2739 (calendar-month-name (extract-calendar-month date))
2740 (extract-calendar-year date)))
2742 (defcustom org-agenda-include-diary nil
2743 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2744 :group 'org-agenda-daily/weekly
2745 :type 'boolean)
2747 (defcustom org-agenda-include-all-todo nil
2748 "Set means weekly/daily agenda will always contain all TODO entries.
2749 The TODO entries will be listed at the top of the agenda, before
2750 the entries for specific days."
2751 :group 'org-agenda-daily/weekly
2752 :type 'boolean)
2754 (defcustom org-agenda-repeating-timestamp-show-all t
2755 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2756 When nil, only one occurence is shown, either today or the
2757 nearest into the future."
2758 :group 'org-agenda-daily/weekly
2759 :type 'boolean)
2761 (defcustom org-deadline-warning-days 14
2762 "No. of days before expiration during which a deadline becomes active.
2763 This variable governs the display in sparse trees and in the agenda.
2764 When 0 or negative, it means use this number (the absolute value of it)
2765 even if a deadline has a different individual lead time specified."
2766 :group 'org-time
2767 :group 'org-agenda-daily/weekly
2768 :type 'number)
2770 (defcustom org-scheduled-past-days 10000
2771 "No. of days to continue listing scheduled items that are not marked DONE.
2772 When an item is scheduled on a date, it shows up in the agenda on this
2773 day and will be listed until it is marked done for the number of days
2774 given here."
2775 :group 'org-agenda-daily/weekly
2776 :type 'number)
2778 (defgroup org-agenda-time-grid nil
2779 "Options concerning the time grid in the Org-mode Agenda."
2780 :tag "Org Agenda Time Grid"
2781 :group 'org-agenda)
2783 (defcustom org-agenda-use-time-grid t
2784 "Non-nil means, show a time grid in the agenda schedule.
2785 A time grid is a set of lines for specific times (like every two hours between
2786 8:00 and 20:00). The items scheduled for a day at specific times are
2787 sorted in between these lines.
2788 For details about when the grid will be shown, and what it will look like, see
2789 the variable `org-agenda-time-grid'."
2790 :group 'org-agenda-time-grid
2791 :type 'boolean)
2793 (defcustom org-agenda-time-grid
2794 '((daily today require-timed)
2795 "----------------"
2796 (800 1000 1200 1400 1600 1800 2000))
2798 "The settings for time grid for agenda display.
2799 This is a list of three items. The first item is again a list. It contains
2800 symbols specifying conditions when the grid should be displayed:
2802 daily if the agenda shows a single day
2803 weekly if the agenda shows an entire week
2804 today show grid on current date, independent of daily/weekly display
2805 require-timed show grid only if at least one item has a time specification
2807 The second item is a string which will be places behing the grid time.
2809 The third item is a list of integers, indicating the times that should have
2810 a grid line."
2811 :group 'org-agenda-time-grid
2812 :type
2813 '(list
2814 (set :greedy t :tag "Grid Display Options"
2815 (const :tag "Show grid in single day agenda display" daily)
2816 (const :tag "Show grid in weekly agenda display" weekly)
2817 (const :tag "Always show grid for today" today)
2818 (const :tag "Show grid only if any timed entries are present"
2819 require-timed)
2820 (const :tag "Skip grid times already present in an entry"
2821 remove-match))
2822 (string :tag "Grid String")
2823 (repeat :tag "Grid Times" (integer :tag "Time"))))
2825 (defgroup org-agenda-sorting nil
2826 "Options concerning sorting in the Org-mode Agenda."
2827 :tag "Org Agenda Sorting"
2828 :group 'org-agenda)
2830 (defconst org-sorting-choice
2831 '(choice
2832 (const time-up) (const time-down)
2833 (const category-keep) (const category-up) (const category-down)
2834 (const tag-down) (const tag-up)
2835 (const priority-up) (const priority-down))
2836 "Sorting choices.")
2838 (defcustom org-agenda-sorting-strategy
2839 '((agenda time-up category-keep priority-down)
2840 (todo category-keep priority-down)
2841 (tags category-keep priority-down)
2842 (search category-keep))
2843 "Sorting structure for the agenda items of a single day.
2844 This is a list of symbols which will be used in sequence to determine
2845 if an entry should be listed before another entry. The following
2846 symbols are recognized:
2848 time-up Put entries with time-of-day indications first, early first
2849 time-down Put entries with time-of-day indications first, late first
2850 category-keep Keep the default order of categories, corresponding to the
2851 sequence in `org-agenda-files'.
2852 category-up Sort alphabetically by category, A-Z.
2853 category-down Sort alphabetically by category, Z-A.
2854 tag-up Sort alphabetically by last tag, A-Z.
2855 tag-down Sort alphabetically by last tag, Z-A.
2856 priority-up Sort numerically by priority, high priority last.
2857 priority-down Sort numerically by priority, high priority first.
2859 The different possibilities will be tried in sequence, and testing stops
2860 if one comparison returns a \"not-equal\". For example, the default
2861 '(time-up category-keep priority-down)
2862 means: Pull out all entries having a specified time of day and sort them,
2863 in order to make a time schedule for the current day the first thing in the
2864 agenda listing for the day. Of the entries without a time indication, keep
2865 the grouped in categories, don't sort the categories, but keep them in
2866 the sequence given in `org-agenda-files'. Within each category sort by
2867 priority.
2869 Leaving out `category-keep' would mean that items will be sorted across
2870 categories by priority.
2872 Instead of a single list, this can also be a set of list for specific
2873 contents, with a context symbol in the car of the list, any of
2874 `agenda', `todo', `tags' for the corresponding agenda views."
2875 :group 'org-agenda-sorting
2876 :type `(choice
2877 (repeat :tag "General" ,org-sorting-choice)
2878 (list :tag "Individually"
2879 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2880 (repeat ,org-sorting-choice))
2881 (cons (const :tag "Strategy for TODO lists" todo)
2882 (repeat ,org-sorting-choice))
2883 (cons (const :tag "Strategy for Tags matches" tags)
2884 (repeat ,org-sorting-choice)))))
2886 (defcustom org-sort-agenda-notime-is-late t
2887 "Non-nil means, items without time are considered late.
2888 This is only relevant for sorting. When t, items which have no explicit
2889 time like 15:30 will be considered as 99:01, i.e. later than any items which
2890 do have a time. When nil, the default time is before 0:00. You can use this
2891 option to decide if the schedule for today should come before or after timeless
2892 agenda entries."
2893 :group 'org-agenda-sorting
2894 :type 'boolean)
2896 (defgroup org-agenda-line-format nil
2897 "Options concerning the entry prefix in the Org-mode agenda display."
2898 :tag "Org Agenda Line Format"
2899 :group 'org-agenda)
2901 (defcustom org-agenda-prefix-format
2902 '((agenda . " %-12:c%?-12t% s")
2903 (timeline . " % s")
2904 (todo . " %-12:c")
2905 (tags . " %-12:c")
2906 (search . " %-12:c"))
2907 "Format specifications for the prefix of items in the agenda views.
2908 An alist with four entries, for the different agenda types. The keys to the
2909 sublists are `agenda', `timeline', `todo', and `tags'. The values
2910 are format strings.
2911 This format works similar to a printf format, with the following meaning:
2913 %c the category of the item, \"Diary\" for entries from the diary, or
2914 as given by the CATEGORY keyword or derived from the file name.
2915 %T the *last* tag of the item. Last because inherited tags come
2916 first in the list.
2917 %t the time-of-day specification if one applies to the entry, in the
2918 format HH:MM
2919 %s Scheduling/Deadline information, a short string
2921 All specifiers work basically like the standard `%s' of printf, but may
2922 contain two additional characters: A question mark just after the `%' and
2923 a whitespace/punctuation character just before the final letter.
2925 If the first character after `%' is a question mark, the entire field
2926 will only be included if the corresponding value applies to the
2927 current entry. This is useful for fields which should have fixed
2928 width when present, but zero width when absent. For example,
2929 \"%?-12t\" will result in a 12 character time field if a time of the
2930 day is specified, but will completely disappear in entries which do
2931 not contain a time.
2933 If there is punctuation or whitespace character just before the final
2934 format letter, this character will be appended to the field value if
2935 the value is not empty. For example, the format \"%-12:c\" leads to
2936 \"Diary: \" if the category is \"Diary\". If the category were be
2937 empty, no additional colon would be interted.
2939 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2940 - Indent the line with two space characters
2941 - Give the category in a 12 chars wide field, padded with whitespace on
2942 the right (because of `-'). Append a colon if there is a category
2943 (because of `:').
2944 - If there is a time-of-day, put it into a 12 chars wide field. If no
2945 time, don't put in an empty field, just skip it (because of '?').
2946 - Finally, put the scheduling information and append a whitespace.
2948 As another example, if you don't want the time-of-day of entries in
2949 the prefix, you could use:
2951 (setq org-agenda-prefix-format \" %-11:c% s\")
2953 See also the variables `org-agenda-remove-times-when-in-prefix' and
2954 `org-agenda-remove-tags'."
2955 :type '(choice
2956 (string :tag "General format")
2957 (list :greedy t :tag "View dependent"
2958 (cons (const agenda) (string :tag "Format"))
2959 (cons (const timeline) (string :tag "Format"))
2960 (cons (const todo) (string :tag "Format"))
2961 (cons (const tags) (string :tag "Format"))
2962 (cons (const search) (string :tag "Format"))))
2963 :group 'org-agenda-line-format)
2965 (defvar org-prefix-format-compiled nil
2966 "The compiled version of the most recently used prefix format.
2967 See the variable `org-agenda-prefix-format'.")
2969 (defcustom org-agenda-todo-keyword-format "%-1s"
2970 "Format for the TODO keyword in agenda lines.
2971 Set this to something like \"%-12s\" if you want all TODO keywords
2972 to occupy a fixed space in the agenda display."
2973 :group 'org-agenda-line-format
2974 :type 'string)
2976 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2977 "Text preceeding scheduled items in the agenda view.
2978 This is a list with two strings. The first applies when the item is
2979 scheduled on the current day. The second applies when it has been scheduled
2980 previously, it may contain a %d to capture how many days ago the item was
2981 scheduled."
2982 :group 'org-agenda-line-format
2983 :type '(list
2984 (string :tag "Scheduled today ")
2985 (string :tag "Scheduled previously")))
2987 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2988 "Text preceeding deadline items in the agenda view.
2989 This is a list with two strings. The first applies when the item has its
2990 deadline on the current day. The second applies when it is in the past or
2991 in the future, it may contain %d to capture how many days away the deadline
2992 is (was)."
2993 :group 'org-agenda-line-format
2994 :type '(list
2995 (string :tag "Deadline today ")
2996 (string :tag "Deadline relative")))
2998 (defcustom org-agenda-remove-times-when-in-prefix t
2999 "Non-nil means, remove duplicate time specifications in agenda items.
3000 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3001 time-of-day specification in a headline or diary entry is extracted and
3002 placed into the prefix. If this option is non-nil, the original specification
3003 \(a timestamp or -range, or just a plain time(range) specification like
3004 11:30-4pm) will be removed for agenda display. This makes the agenda less
3005 cluttered.
3006 The option can be t or nil. It may also be the symbol `beg', indicating
3007 that the time should only be removed what it is located at the beginning of
3008 the headline/diary entry."
3009 :group 'org-agenda-line-format
3010 :type '(choice
3011 (const :tag "Always" t)
3012 (const :tag "Never" nil)
3013 (const :tag "When at beginning of entry" beg)))
3016 (defcustom org-agenda-default-appointment-duration nil
3017 "Default duration for appointments that only have a starting time.
3018 When nil, no duration is specified in such cases.
3019 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3020 :group 'org-agenda-line-format
3021 :type '(choice
3022 (integer :tag "Minutes")
3023 (const :tag "No default duration")))
3026 (defcustom org-agenda-remove-tags nil
3027 "Non-nil means, remove the tags from the headline copy in the agenda.
3028 When this is the symbol `prefix', only remove tags when
3029 `org-agenda-prefix-format' contains a `%T' specifier."
3030 :group 'org-agenda-line-format
3031 :type '(choice
3032 (const :tag "Always" t)
3033 (const :tag "Never" nil)
3034 (const :tag "When prefix format contains %T" prefix)))
3036 (if (fboundp 'defvaralias)
3037 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3038 'org-agenda-remove-tags))
3040 (defcustom org-agenda-tags-column -80
3041 "Shift tags in agenda items to this column.
3042 If this number is positive, it specifies the column. If it is negative,
3043 it means that the tags should be flushright to that column. For example,
3044 -80 works well for a normal 80 character screen."
3045 :group 'org-agenda-line-format
3046 :type 'integer)
3048 (if (fboundp 'defvaralias)
3049 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3051 (defcustom org-agenda-fontify-priorities t
3052 "Non-nil means, highlight low and high priorities in agenda.
3053 When t, the highest priority entries are bold, lowest priority italic.
3054 This may also be an association list of priority faces. The face may be
3055 a names face, or a list like `(:background \"Red\")'."
3056 :group 'org-agenda-line-format
3057 :type '(choice
3058 (const :tag "Never" nil)
3059 (const :tag "Defaults" t)
3060 (repeat :tag "Specify"
3061 (list (character :tag "Priority" :value ?A)
3062 (sexp :tag "face")))))
3064 (defgroup org-latex nil
3065 "Options for embedding LaTeX code into Org-mode"
3066 :tag "Org LaTeX"
3067 :group 'org)
3069 (defcustom org-format-latex-options
3070 '(:foreground default :background default :scale 1.0
3071 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3072 :matchers ("begin" "$" "$$" "\\(" "\\["))
3073 "Options for creating images from LaTeX fragments.
3074 This is a property list with the following properties:
3075 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3076 `default' means use the forground of the default face.
3077 :background the background color, or \"Transparent\".
3078 `default' means use the background of the default face.
3079 :scale a scaling factor for the size of the images
3080 :html-foreground, :html-background, :html-scale
3081 The same numbers for HTML export.
3082 :matchers a list indicating which matchers should be used to
3083 find LaTeX fragments. Valid members of this list are:
3084 \"begin\" find environments
3085 \"$\" find math expressions surrounded by $...$
3086 \"$$\" find math expressions surrounded by $$....$$
3087 \"\\(\" find math expressions surrounded by \\(...\\)
3088 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3089 :group 'org-latex
3090 :type 'plist)
3092 (defcustom org-format-latex-header "\\documentclass{article}
3093 \\usepackage{fullpage} % do not remove
3094 \\usepackage{amssymb}
3095 \\usepackage[usenames]{color}
3096 \\usepackage{amsmath}
3097 \\usepackage{latexsym}
3098 \\usepackage[mathscr]{eucal}
3099 \\pagestyle{empty} % do not remove"
3100 "The document header used for processing LaTeX fragments."
3101 :group 'org-latex
3102 :type 'string)
3104 (defgroup org-export nil
3105 "Options for exporting org-listings."
3106 :tag "Org Export"
3107 :group 'org)
3109 (defgroup org-export-general nil
3110 "General options for exporting Org-mode files."
3111 :tag "Org Export General"
3112 :group 'org-export)
3114 ;; FIXME
3115 (defvar org-export-publishing-directory nil)
3117 (defcustom org-export-with-special-strings t
3118 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3119 When this option is turned on, these strings will be exported as:
3121 Org HTML LaTeX
3122 -----+----------+--------
3123 \\- &shy; \\-
3124 -- &ndash; --
3125 --- &mdash; ---
3126 ... &hellip; \ldots
3128 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3129 :group 'org-export-translation
3130 :type 'boolean)
3132 (defcustom org-export-language-setup
3133 '(("en" "Author" "Date" "Table of Contents")
3134 ("cs" "Autor" "Datum" "Obsah")
3135 ("da" "Ophavsmand" "Dato" "Indhold")
3136 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3137 ("es" "Autor" "Fecha" "\xcdndice")
3138 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3139 ("it" "Autore" "Data" "Indice")
3140 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3141 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3142 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3143 "Terms used in export text, translated to different languages.
3144 Use the variable `org-export-default-language' to set the language,
3145 or use the +OPTION lines for a per-file setting."
3146 :group 'org-export-general
3147 :type '(repeat
3148 (list
3149 (string :tag "HTML language tag")
3150 (string :tag "Author")
3151 (string :tag "Date")
3152 (string :tag "Table of Contents"))))
3154 (defcustom org-export-default-language "en"
3155 "The default language of HTML export, as a string.
3156 This should have an association in `org-export-language-setup'."
3157 :group 'org-export-general
3158 :type 'string)
3160 (defcustom org-export-skip-text-before-1st-heading t
3161 "Non-nil means, skip all text before the first headline when exporting.
3162 When nil, that text is exported as well."
3163 :group 'org-export-general
3164 :type 'boolean)
3166 (defcustom org-export-headline-levels 3
3167 "The last level which is still exported as a headline.
3168 Inferior levels will produce itemize lists when exported.
3169 Note that a numeric prefix argument to an exporter function overrides
3170 this setting.
3172 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3173 :group 'org-export-general
3174 :type 'number)
3176 (defcustom org-export-with-section-numbers t
3177 "Non-nil means, add section numbers to headlines when exporting.
3179 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3180 :group 'org-export-general
3181 :type 'boolean)
3183 (defcustom org-export-with-toc t
3184 "Non-nil means, create a table of contents in exported files.
3185 The TOC contains headlines with levels up to`org-export-headline-levels'.
3186 When an integer, include levels up to N in the toc, this may then be
3187 different from `org-export-headline-levels', but it will not be allowed
3188 to be larger than the number of headline levels.
3189 When nil, no table of contents is made.
3191 Headlines which contain any TODO items will be marked with \"(*)\" in
3192 ASCII export, and with red color in HTML output, if the option
3193 `org-export-mark-todo-in-toc' is set.
3195 In HTML output, the TOC will be clickable.
3197 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3198 or \"toc:3\"."
3199 :group 'org-export-general
3200 :type '(choice
3201 (const :tag "No Table of Contents" nil)
3202 (const :tag "Full Table of Contents" t)
3203 (integer :tag "TOC to level")))
3205 (defcustom org-export-mark-todo-in-toc nil
3206 "Non-nil means, mark TOC lines that contain any open TODO items."
3207 :group 'org-export-general
3208 :type 'boolean)
3210 (defcustom org-export-preserve-breaks nil
3211 "Non-nil means, preserve all line breaks when exporting.
3212 Normally, in HTML output paragraphs will be reformatted. In ASCII
3213 export, line breaks will always be preserved, regardless of this variable.
3215 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3216 :group 'org-export-general
3217 :type 'boolean)
3219 (defcustom org-export-with-archived-trees 'headline
3220 "Whether subtrees with the ARCHIVE tag should be exported.
3221 This can have three different values
3222 nil Do not export, pretend this tree is not present
3223 t Do export the entire tree
3224 headline Only export the headline, but skip the tree below it."
3225 :group 'org-export-general
3226 :group 'org-archive
3227 :type '(choice
3228 (const :tag "not at all" nil)
3229 (const :tag "headline only" 'headline)
3230 (const :tag "entirely" t)))
3232 (defcustom org-export-author-info t
3233 "Non-nil means, insert author name and email into the exported file.
3235 This option can also be set with the +OPTIONS line,
3236 e.g. \"author-info:nil\"."
3237 :group 'org-export-general
3238 :type 'boolean)
3240 (defcustom org-export-time-stamp-file t
3241 "Non-nil means, insert a time stamp into the exported file.
3242 The time stamp shows when the file was created.
3244 This option can also be set with the +OPTIONS line,
3245 e.g. \"timestamp:nil\"."
3246 :group 'org-export-general
3247 :type 'boolean)
3249 (defcustom org-export-with-timestamps t
3250 "If nil, do not export time stamps and associated keywords."
3251 :group 'org-export-general
3252 :type 'boolean)
3254 (defcustom org-export-remove-timestamps-from-toc t
3255 "If nil, remove timestamps from the table of contents entries."
3256 :group 'org-export-general
3257 :type 'boolean)
3259 (defcustom org-export-with-tags 'not-in-toc
3260 "If nil, do not export tags, just remove them from headlines.
3261 If this is the symbol `not-in-toc', tags will be removed from table of
3262 contents entries, but still be shown in the headlines of the document.
3264 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3265 :group 'org-export-general
3266 :type '(choice
3267 (const :tag "Off" nil)
3268 (const :tag "Not in TOC" not-in-toc)
3269 (const :tag "On" t)))
3271 (defcustom org-export-with-drawers nil
3272 "Non-nil means, export with drawers like the property drawer.
3273 When t, all drawers are exported. This may also be a list of
3274 drawer names to export."
3275 :group 'org-export-general
3276 :type '(choice
3277 (const :tag "All drawers" t)
3278 (const :tag "None" nil)
3279 (repeat :tag "Selected drawers"
3280 (string :tag "Drawer name"))))
3282 (defgroup org-export-translation nil
3283 "Options for translating special ascii sequences for the export backends."
3284 :tag "Org Export Translation"
3285 :group 'org-export)
3287 (defcustom org-export-with-emphasize t
3288 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3289 If the export target supports emphasizing text, the word will be
3290 typeset in bold, italic, or underlined, respectively. Works only for
3291 single words, but you can say: I *really* *mean* *this*.
3292 Not all export backends support this.
3294 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3295 :group 'org-export-translation
3296 :type 'boolean)
3298 (defcustom org-export-with-footnotes t
3299 "If nil, export [1] as a footnote marker.
3300 Lines starting with [1] will be formatted as footnotes.
3302 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3303 :group 'org-export-translation
3304 :type 'boolean)
3306 (defcustom org-export-with-sub-superscripts t
3307 "Non-nil means, interpret \"_\" and \"^\" for export.
3308 When this option is turned on, you can use TeX-like syntax for sub- and
3309 superscripts. Several characters after \"_\" or \"^\" will be
3310 considered as a single item - so grouping with {} is normally not
3311 needed. For example, the following things will be parsed as single
3312 sub- or superscripts.
3314 10^24 or 10^tau several digits will be considered 1 item.
3315 10^-12 or 10^-tau a leading sign with digits or a word
3316 x^2-y^3 will be read as x^2 - y^3, because items are
3317 terminated by almost any nonword/nondigit char.
3318 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3320 Still, ambiguity is possible - so when in doubt use {} to enclose the
3321 sub/superscript. If you set this variable to the symbol `{}',
3322 the braces are *required* in order to trigger interpretations as
3323 sub/superscript. This can be helpful in documents that need \"_\"
3324 frequently in plain text.
3326 Not all export backends support this, but HTML does.
3328 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3329 :group 'org-export-translation
3330 :type '(choice
3331 (const :tag "Always interpret" t)
3332 (const :tag "Only with braces" {})
3333 (const :tag "Never interpret" nil)))
3335 (defcustom org-export-with-special-strings t
3336 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3337 When this option is turned on, these strings will be exported as:
3339 \\- : &shy;
3340 -- : &ndash;
3341 --- : &mdash;
3343 Not all export backends support this, but HTML does.
3345 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3346 :group 'org-export-translation
3347 :type 'boolean)
3349 (defcustom org-export-with-TeX-macros t
3350 "Non-nil means, interpret simple TeX-like macros when exporting.
3351 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3352 No only real TeX macros will work here, but the standard HTML entities
3353 for math can be used as macro names as well. For a list of supported
3354 names in HTML export, see the constant `org-html-entities'.
3355 Not all export backends support this.
3357 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3358 :group 'org-export-translation
3359 :group 'org-export-latex
3360 :type 'boolean)
3362 (defcustom org-export-with-LaTeX-fragments nil
3363 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3364 When set, the exporter will find LaTeX environments if the \\begin line is
3365 the first non-white thing on a line. It will also find the math delimiters
3366 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3367 display math.
3369 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3370 :group 'org-export-translation
3371 :group 'org-export-latex
3372 :type 'boolean)
3374 (defcustom org-export-with-fixed-width t
3375 "Non-nil means, lines starting with \":\" will be in fixed width font.
3376 This can be used to have pre-formatted text, fragments of code etc. For
3377 example:
3378 : ;; Some Lisp examples
3379 : (while (defc cnt)
3380 : (ding))
3381 will be looking just like this in also HTML. See also the QUOTE keyword.
3382 Not all export backends support this.
3384 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3385 :group 'org-export-translation
3386 :type 'boolean)
3388 (defcustom org-match-sexp-depth 3
3389 "Number of stacked braces for sub/superscript matching.
3390 This has to be set before loading org.el to be effective."
3391 :group 'org-export-translation
3392 :type 'integer)
3394 (defgroup org-export-tables nil
3395 "Options for exporting tables in Org-mode."
3396 :tag "Org Export Tables"
3397 :group 'org-export)
3399 (defcustom org-export-with-tables t
3400 "If non-nil, lines starting with \"|\" define a table.
3401 For example:
3403 | Name | Address | Birthday |
3404 |-------------+----------+-----------|
3405 | Arthur Dent | England | 29.2.2100 |
3407 Not all export backends support this.
3409 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3410 :group 'org-export-tables
3411 :type 'boolean)
3413 (defcustom org-export-highlight-first-table-line t
3414 "Non-nil means, highlight the first table line.
3415 In HTML export, this means use <th> instead of <td>.
3416 In tables created with table.el, this applies to the first table line.
3417 In Org-mode tables, all lines before the first horizontal separator
3418 line will be formatted with <th> tags."
3419 :group 'org-export-tables
3420 :type 'boolean)
3422 (defcustom org-export-table-remove-special-lines t
3423 "Remove special lines and marking characters in calculating tables.
3424 This removes the special marking character column from tables that are set
3425 up for spreadsheet calculations. It also removes the entire lines
3426 marked with `!', `_', or `^'. The lines with `$' are kept, because
3427 the values of constants may be useful to have."
3428 :group 'org-export-tables
3429 :type 'boolean)
3431 (defcustom org-export-prefer-native-exporter-for-tables nil
3432 "Non-nil means, always export tables created with table.el natively.
3433 Natively means, use the HTML code generator in table.el.
3434 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3435 the table does not use row- or column-spanning). This has the
3436 advantage, that the automatic HTML conversions for math symbols and
3437 sub/superscripts can be applied. Org-mode's HTML generator is also
3438 much faster."
3439 :group 'org-export-tables
3440 :type 'boolean)
3442 (defgroup org-export-ascii nil
3443 "Options specific for ASCII export of Org-mode files."
3444 :tag "Org Export ASCII"
3445 :group 'org-export)
3447 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3448 "Characters for underlining headings in ASCII export.
3449 In the given sequence, these characters will be used for level 1, 2, ..."
3450 :group 'org-export-ascii
3451 :type '(repeat character))
3453 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3454 "Bullet characters for headlines converted to lists in ASCII export.
3455 The first character is used for the first lest level generated in this
3456 way, and so on. If there are more levels than characters given here,
3457 the list will be repeated.
3458 Note that plain lists will keep the same bullets as the have in the
3459 Org-mode file."
3460 :group 'org-export-ascii
3461 :type '(repeat character))
3463 (defgroup org-export-xml nil
3464 "Options specific for XML export of Org-mode files."
3465 :tag "Org Export XML"
3466 :group 'org-export)
3468 (defgroup org-export-html nil
3469 "Options specific for HTML export of Org-mode files."
3470 :tag "Org Export HTML"
3471 :group 'org-export)
3473 (defcustom org-export-html-coding-system nil
3475 :group 'org-export-html
3476 :type 'coding-system)
3478 (defcustom org-export-html-extension "html"
3479 "The extension for exported HTML files."
3480 :group 'org-export-html
3481 :type 'string)
3483 (defcustom org-export-html-style
3484 "<style type=\"text/css\">
3485 html {
3486 font-family: Times, serif;
3487 font-size: 12pt;
3489 .title { text-align: center; }
3490 .todo { color: red; }
3491 .done { color: green; }
3492 .timestamp { color: grey }
3493 .timestamp-kwd { color: CadetBlue }
3494 .tag { background-color:lightblue; font-weight:normal }
3495 .target { background-color: lavender; }
3496 pre {
3497 border: 1pt solid #AEBDCC;
3498 background-color: #F3F5F7;
3499 padding: 5pt;
3500 font-family: courier, monospace;
3502 table { border-collapse: collapse; }
3503 td, th {
3504 vertical-align: top;
3505 <!--border: 1pt solid #ADB9CC;-->
3507 </style>"
3508 "The default style specification for exported HTML files.
3509 Since there are different ways of setting style information, this variable
3510 needs to contain the full HTML structure to provide a style, including the
3511 surrounding HTML tags. The style specifications should include definitions
3512 for new classes todo, done, title, and deadline. For example, legal values
3513 would be:
3515 <style type=\"text/css\">
3516 p { font-weight: normal; color: gray; }
3517 h1 { color: black; }
3518 .title { text-align: center; }
3519 .todo, .deadline { color: red; }
3520 .done { color: green; }
3521 </style>
3523 or, if you want to keep the style in a file,
3525 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3527 As the value of this option simply gets inserted into the HTML <head> header,
3528 you can \"misuse\" it to add arbitrary text to the header."
3529 :group 'org-export-html
3530 :type 'string)
3533 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3534 "Format for typesetting the document title in HTML export."
3535 :group 'org-export-html
3536 :type 'string)
3538 (defcustom org-export-html-toplevel-hlevel 2
3539 "The <H> level for level 1 headings in HTML export."
3540 :group 'org-export-html
3541 :type 'string)
3543 (defcustom org-export-html-link-org-files-as-html t
3544 "Non-nil means, make file links to `file.org' point to `file.html'.
3545 When org-mode is exporting an org-mode file to HTML, links to
3546 non-html files are directly put into a href tag in HTML.
3547 However, links to other Org-mode files (recognized by the
3548 extension `.org.) should become links to the corresponding html
3549 file, assuming that the linked org-mode file will also be
3550 converted to HTML.
3551 When nil, the links still point to the plain `.org' file."
3552 :group 'org-export-html
3553 :type 'boolean)
3555 (defcustom org-export-html-inline-images 'maybe
3556 "Non-nil means, inline images into exported HTML pages.
3557 This is done using an <img> tag. When nil, an anchor with href is used to
3558 link to the image. If this option is `maybe', then images in links with
3559 an empty description will be inlined, while images with a description will
3560 be linked only."
3561 :group 'org-export-html
3562 :type '(choice (const :tag "Never" nil)
3563 (const :tag "Always" t)
3564 (const :tag "When there is no description" maybe)))
3566 ;; FIXME: rename
3567 (defcustom org-export-html-expand t
3568 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3569 When nil, these tags will be exported as plain text and therefore
3570 not be interpreted by a browser.
3572 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3573 :group 'org-export-html
3574 :type 'boolean)
3576 (defcustom org-export-html-table-tag
3577 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3578 "The HTML tag that is used to start a table.
3579 This must be a <table> tag, but you may change the options like
3580 borders and spacing."
3581 :group 'org-export-html
3582 :type 'string)
3584 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3585 "The opening tag for table header fields.
3586 This is customizable so that alignment options can be specified."
3587 :group 'org-export-tables
3588 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3590 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3591 "The opening tag for table data fields.
3592 This is customizable so that alignment options can be specified."
3593 :group 'org-export-tables
3594 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3596 (defcustom org-export-html-with-timestamp nil
3597 "If non-nil, write `org-export-html-html-helper-timestamp'
3598 into the exported HTML text. Otherwise, the buffer will just be saved
3599 to a file."
3600 :group 'org-export-html
3601 :type 'boolean)
3603 (defcustom org-export-html-html-helper-timestamp
3604 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3605 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3606 :group 'org-export-html
3607 :type 'string)
3609 (defgroup org-export-icalendar nil
3610 "Options specific for iCalendar export of Org-mode files."
3611 :tag "Org Export iCalendar"
3612 :group 'org-export)
3614 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3615 "The file name for the iCalendar file covering all agenda files.
3616 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3617 The file name should be absolute, the file will be overwritten without warning."
3618 :group 'org-export-icalendar
3619 :type 'file)
3621 (defcustom org-icalendar-include-todo nil
3622 "Non-nil means, export to iCalendar files should also cover TODO items."
3623 :group 'org-export-icalendar
3624 :type '(choice
3625 (const :tag "None" nil)
3626 (const :tag "Unfinished" t)
3627 (const :tag "All" all)))
3629 (defcustom org-icalendar-include-sexps t
3630 "Non-nil means, export to iCalendar files should also cover sexp entries.
3631 These are entries like in the diary, but directly in an Org-mode file."
3632 :group 'org-export-icalendar
3633 :type 'boolean)
3635 (defcustom org-icalendar-include-body 100
3636 "Amount of text below headline to be included in iCalendar export.
3637 This is a number of characters that should maximally be included.
3638 Properties, scheduling and clocking lines will always be removed.
3639 The text will be inserted into the DESCRIPTION field."
3640 :group 'org-export-icalendar
3641 :type '(choice
3642 (const :tag "Nothing" nil)
3643 (const :tag "Everything" t)
3644 (integer :tag "Max characters")))
3646 (defcustom org-icalendar-combined-name "OrgMode"
3647 "Calendar name for the combined iCalendar representing all agenda files."
3648 :group 'org-export-icalendar
3649 :type 'string)
3651 (defgroup org-font-lock nil
3652 "Font-lock settings for highlighting in Org-mode."
3653 :tag "Org Font Lock"
3654 :group 'org)
3656 (defcustom org-level-color-stars-only nil
3657 "Non-nil means fontify only the stars in each headline.
3658 When nil, the entire headline is fontified.
3659 Changing it requires restart of `font-lock-mode' to become effective
3660 also in regions already fontified."
3661 :group 'org-font-lock
3662 :type 'boolean)
3664 (defcustom org-hide-leading-stars nil
3665 "Non-nil means, hide the first N-1 stars in a headline.
3666 This works by using the face `org-hide' for these stars. This
3667 face is white for a light background, and black for a dark
3668 background. You may have to customize the face `org-hide' to
3669 make this work.
3670 Changing it requires restart of `font-lock-mode' to become effective
3671 also in regions already fontified.
3672 You may also set this on a per-file basis by adding one of the following
3673 lines to the buffer:
3675 #+STARTUP: hidestars
3676 #+STARTUP: showstars"
3677 :group 'org-font-lock
3678 :type 'boolean)
3680 (defcustom org-fontify-done-headline nil
3681 "Non-nil means, change the face of a headline if it is marked DONE.
3682 Normally, only the TODO/DONE keyword indicates the state of a headline.
3683 When this is non-nil, the headline after the keyword is set to the
3684 `org-headline-done' as an additional indication."
3685 :group 'org-font-lock
3686 :type 'boolean)
3688 (defcustom org-fontify-emphasized-text t
3689 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3690 Changing this variable requires a restart of Emacs to take effect."
3691 :group 'org-font-lock
3692 :type 'boolean)
3694 (defcustom org-highlight-latex-fragments-and-specials nil
3695 "Non-nil means, fontify what is treated specially by the exporters."
3696 :group 'org-font-lock
3697 :type 'boolean)
3699 (defcustom org-hide-emphasis-markers nil
3700 "Non-nil mean font-lock should hide the emphasis marker characters."
3701 :group 'org-font-lock
3702 :type 'boolean)
3704 (defvar org-emph-re nil
3705 "Regular expression for matching emphasis.")
3706 (defvar org-verbatim-re nil
3707 "Regular expression for matching verbatim text.")
3708 (defvar org-emphasis-regexp-components) ; defined just below
3709 (defvar org-emphasis-alist) ; defined just below
3710 (defun org-set-emph-re (var val)
3711 "Set variable and compute the emphasis regular expression."
3712 (set var val)
3713 (when (and (boundp 'org-emphasis-alist)
3714 (boundp 'org-emphasis-regexp-components)
3715 org-emphasis-alist org-emphasis-regexp-components)
3716 (let* ((e org-emphasis-regexp-components)
3717 (pre (car e))
3718 (post (nth 1 e))
3719 (border (nth 2 e))
3720 (body (nth 3 e))
3721 (nl (nth 4 e))
3722 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3723 (body1 (concat body "*?"))
3724 (markers (mapconcat 'car org-emphasis-alist ""))
3725 (vmarkers (mapconcat
3726 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3727 org-emphasis-alist "")))
3728 ;; make sure special characters appear at the right position in the class
3729 (if (string-match "\\^" markers)
3730 (setq markers (concat (replace-match "" t t markers) "^")))
3731 (if (string-match "-" markers)
3732 (setq markers (concat (replace-match "" t t markers) "-")))
3733 (if (string-match "\\^" vmarkers)
3734 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3735 (if (string-match "-" vmarkers)
3736 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3737 (if (> nl 0)
3738 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3739 (int-to-string nl) "\\}")))
3740 ;; Make the regexp
3741 (setq org-emph-re
3742 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3743 "\\("
3744 "\\([" markers "]\\)"
3745 "\\("
3746 "[^" border "]\\|"
3747 "[^" border (if (and nil stacked) markers) "]"
3748 body1
3749 "[^" border (if (and nil stacked) markers) "]"
3750 "\\)"
3751 "\\3\\)"
3752 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3753 (setq org-verbatim-re
3754 (concat "\\([" pre "]\\|^\\)"
3755 "\\("
3756 "\\([" vmarkers "]\\)"
3757 "\\("
3758 "[^" border "]\\|"
3759 "[^" border "]"
3760 body1
3761 "[^" border "]"
3762 "\\)"
3763 "\\3\\)"
3764 "\\([" post "]\\|$\\)")))))
3766 (defcustom org-emphasis-regexp-components
3767 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3768 "Components used to build the regular expression for emphasis.
3769 This is a list with 6 entries. Terminology: In an emphasis string
3770 like \" *strong word* \", we call the initial space PREMATCH, the final
3771 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3772 and \"trong wor\" is the body. The different components in this variable
3773 specify what is allowed/forbidden in each part:
3775 pre Chars allowed as prematch. Beginning of line will be allowed too.
3776 post Chars allowed as postmatch. End of line will be allowed too.
3777 border The chars *forbidden* as border characters.
3778 body-regexp A regexp like \".\" to match a body character. Don't use
3779 non-shy groups here, and don't allow newline here.
3780 newline The maximum number of newlines allowed in an emphasis exp.
3782 Use customize to modify this, or restart Emacs after changing it."
3783 :group 'org-font-lock
3784 :set 'org-set-emph-re
3785 :type '(list
3786 (sexp :tag "Allowed chars in pre ")
3787 (sexp :tag "Allowed chars in post ")
3788 (sexp :tag "Forbidden chars in border ")
3789 (sexp :tag "Regexp for body ")
3790 (integer :tag "number of newlines allowed")
3791 (option (boolean :tag "Stacking (DISABLED) "))))
3793 (defcustom org-emphasis-alist
3794 '(("*" bold "<b>" "</b>")
3795 ("/" italic "<i>" "</i>")
3796 ("_" underline "<u>" "</u>")
3797 ("=" org-code "<code>" "</code>" verbatim)
3798 ("~" org-verbatim "" "" verbatim)
3799 ("+" (:strike-through t) "<del>" "</del>")
3801 "Special syntax for emphasized text.
3802 Text starting and ending with a special character will be emphasized, for
3803 example *bold*, _underlined_ and /italic/. This variable sets the marker
3804 characters, the face to be used by font-lock for highlighting in Org-mode
3805 Emacs buffers, and the HTML tags to be used for this.
3806 Use customize to modify this, or restart Emacs after changing it."
3807 :group 'org-font-lock
3808 :set 'org-set-emph-re
3809 :type '(repeat
3810 (list
3811 (string :tag "Marker character")
3812 (choice
3813 (face :tag "Font-lock-face")
3814 (plist :tag "Face property list"))
3815 (string :tag "HTML start tag")
3816 (string :tag "HTML end tag")
3817 (option (const verbatim)))))
3819 ;;; The faces
3821 (defgroup org-faces nil
3822 "Faces in Org-mode."
3823 :tag "Org Faces"
3824 :group 'org-font-lock)
3826 (defun org-compatible-face (inherits specs)
3827 "Make a compatible face specification.
3828 If INHERITS is an existing face and if the Emacs version supports it,
3829 just inherit the face. If not, use SPECS to define the face.
3830 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3831 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3832 to the top of the list. The `min-colors' attribute will be removed from
3833 any other entries, and any resulting duplicates will be removed entirely."
3834 (cond
3835 ((and inherits (facep inherits)
3836 (not (featurep 'xemacs)) (> emacs-major-version 22))
3837 ;; In Emacs 23, we use inheritance where possible.
3838 ;; We only do this in Emacs 23, because only there the outline
3839 ;; faces have been changed to the original org-mode-level-faces.
3840 (list (list t :inherit inherits)))
3841 ((or (featurep 'xemacs) (< emacs-major-version 22))
3842 ;; These do not understand the `min-colors' attribute.
3843 (let (r e a)
3844 (while (setq e (pop specs))
3845 (cond
3846 ((memq (car e) '(t default)) (push e r))
3847 ((setq a (member '(min-colors 8) (car e)))
3848 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3849 (cdr e)))))
3850 ((setq a (assq 'min-colors (car e)))
3851 (setq e (cons (delq a (car e)) (cdr e)))
3852 (or (assoc (car e) r) (push e r)))
3853 (t (or (assoc (car e) r) (push e r)))))
3854 (nreverse r)))
3855 (t specs)))
3856 (put 'org-compatible-face 'lisp-indent-function 1)
3858 (defface org-hide
3859 '((((background light)) (:foreground "white"))
3860 (((background dark)) (:foreground "black")))
3861 "Face used to hide leading stars in headlines.
3862 The forground color of this face should be equal to the background
3863 color of the frame."
3864 :group 'org-faces)
3866 (defface org-level-1 ;; font-lock-function-name-face
3867 (org-compatible-face 'outline-1
3868 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3869 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3870 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3871 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3872 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3873 (t (:bold t))))
3874 "Face used for level 1 headlines."
3875 :group 'org-faces)
3877 (defface org-level-2 ;; font-lock-variable-name-face
3878 (org-compatible-face 'outline-2
3879 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3880 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3881 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3882 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3883 (t (:bold t))))
3884 "Face used for level 2 headlines."
3885 :group 'org-faces)
3887 (defface org-level-3 ;; font-lock-keyword-face
3888 (org-compatible-face 'outline-3
3889 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3890 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3891 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3892 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3893 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3894 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3895 (t (:bold t))))
3896 "Face used for level 3 headlines."
3897 :group 'org-faces)
3899 (defface org-level-4 ;; font-lock-comment-face
3900 (org-compatible-face 'outline-4
3901 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3902 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3903 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3904 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3905 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3906 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3907 (t (:bold t))))
3908 "Face used for level 4 headlines."
3909 :group 'org-faces)
3911 (defface org-level-5 ;; font-lock-type-face
3912 (org-compatible-face 'outline-5
3913 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3914 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3915 (((class color) (min-colors 8)) (:foreground "green"))))
3916 "Face used for level 5 headlines."
3917 :group 'org-faces)
3919 (defface org-level-6 ;; font-lock-constant-face
3920 (org-compatible-face 'outline-6
3921 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3922 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3923 (((class color) (min-colors 8)) (:foreground "magenta"))))
3924 "Face used for level 6 headlines."
3925 :group 'org-faces)
3927 (defface org-level-7 ;; font-lock-builtin-face
3928 (org-compatible-face 'outline-7
3929 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3930 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3931 (((class color) (min-colors 8)) (:foreground "blue"))))
3932 "Face used for level 7 headlines."
3933 :group 'org-faces)
3935 (defface org-level-8 ;; font-lock-string-face
3936 (org-compatible-face 'outline-8
3937 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3938 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3939 (((class color) (min-colors 8)) (:foreground "green"))))
3940 "Face used for level 8 headlines."
3941 :group 'org-faces)
3943 (defface org-special-keyword ;; font-lock-string-face
3944 (org-compatible-face nil
3945 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3946 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3947 (t (:italic t))))
3948 "Face used for special keywords."
3949 :group 'org-faces)
3951 (defface org-drawer ;; font-lock-function-name-face
3952 (org-compatible-face nil
3953 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3954 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3955 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3956 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3957 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3958 (t (:bold t))))
3959 "Face used for drawers."
3960 :group 'org-faces)
3962 (defface org-property-value nil
3963 "Face used for the value of a property."
3964 :group 'org-faces)
3966 (defface org-column
3967 (org-compatible-face nil
3968 '((((class color) (min-colors 16) (background light))
3969 (:background "grey90"))
3970 (((class color) (min-colors 16) (background dark))
3971 (:background "grey30"))
3972 (((class color) (min-colors 8))
3973 (:background "cyan" :foreground "black"))
3974 (t (:inverse-video t))))
3975 "Face for column display of entry properties."
3976 :group 'org-faces)
3978 (when (fboundp 'set-face-attribute)
3979 ;; Make sure that a fixed-width face is used when we have a column table.
3980 (set-face-attribute 'org-column nil
3981 :height (face-attribute 'default :height)
3982 :family (face-attribute 'default :family)))
3984 (defface org-warning
3985 (org-compatible-face 'font-lock-warning-face
3986 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3987 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3988 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3989 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3990 (t (:bold t))))
3991 "Face for deadlines and TODO keywords."
3992 :group 'org-faces)
3994 (defface org-archived ; similar to shadow
3995 (org-compatible-face 'shadow
3996 '((((class color grayscale) (min-colors 88) (background light))
3997 (:foreground "grey50"))
3998 (((class color grayscale) (min-colors 88) (background dark))
3999 (:foreground "grey70"))
4000 (((class color) (min-colors 8) (background light))
4001 (:foreground "green"))
4002 (((class color) (min-colors 8) (background dark))
4003 (:foreground "yellow"))))
4004 "Face for headline with the ARCHIVE tag."
4005 :group 'org-faces)
4007 (defface org-link
4008 '((((class color) (background light)) (:foreground "Purple" :underline t))
4009 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4010 (t (:underline t)))
4011 "Face for links."
4012 :group 'org-faces)
4014 (defface org-ellipsis
4015 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4016 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4017 (t (:strike-through t)))
4018 "Face for the ellipsis in folded text."
4019 :group 'org-faces)
4021 (defface org-target
4022 '((((class color) (background light)) (:underline t))
4023 (((class color) (background dark)) (:underline t))
4024 (t (:underline t)))
4025 "Face for links."
4026 :group 'org-faces)
4028 (defface org-date
4029 '((((class color) (background light)) (:foreground "Purple" :underline t))
4030 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4031 (t (:underline t)))
4032 "Face for links."
4033 :group 'org-faces)
4035 (defface org-sexp-date
4036 '((((class color) (background light)) (:foreground "Purple"))
4037 (((class color) (background dark)) (:foreground "Cyan"))
4038 (t (:underline t)))
4039 "Face for links."
4040 :group 'org-faces)
4042 (defface org-tag
4043 '((t (:bold t)))
4044 "Face for tags."
4045 :group 'org-faces)
4047 (defface org-todo ; font-lock-warning-face
4048 (org-compatible-face nil
4049 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4050 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4051 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4052 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4053 (t (:inverse-video t :bold t))))
4054 "Face for TODO keywords."
4055 :group 'org-faces)
4057 (defface org-done ;; font-lock-type-face
4058 (org-compatible-face nil
4059 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4060 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4061 (((class color) (min-colors 8)) (:foreground "green"))
4062 (t (:bold t))))
4063 "Face used for todo keywords that indicate DONE items."
4064 :group 'org-faces)
4066 (defface org-headline-done ;; font-lock-string-face
4067 (org-compatible-face nil
4068 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4069 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4070 (((class color) (min-colors 8) (background light)) (:bold nil))))
4071 "Face used to indicate that a headline is DONE.
4072 This face is only used if `org-fontify-done-headline' is set. If applies
4073 to the part of the headline after the DONE keyword."
4074 :group 'org-faces)
4076 (defcustom org-todo-keyword-faces nil
4077 "Faces for specific TODO keywords.
4078 This is a list of cons cells, with TODO keywords in the car
4079 and faces in the cdr. The face can be a symbol, or a property
4080 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4081 :group 'org-faces
4082 :group 'org-todo
4083 :type '(repeat
4084 (cons
4085 (string :tag "keyword")
4086 (sexp :tag "face"))))
4088 (defface org-table ;; font-lock-function-name-face
4089 (org-compatible-face nil
4090 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4091 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4092 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4093 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4094 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4095 (((class color) (min-colors 8) (background dark)))))
4096 "Face used for tables."
4097 :group 'org-faces)
4099 (defface org-formula
4100 (org-compatible-face nil
4101 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4102 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4103 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4104 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4105 (t (:bold t :italic t))))
4106 "Face for formulas."
4107 :group 'org-faces)
4109 (defface org-code
4110 (org-compatible-face nil
4111 '((((class color grayscale) (min-colors 88) (background light))
4112 (:foreground "grey50"))
4113 (((class color grayscale) (min-colors 88) (background dark))
4114 (:foreground "grey70"))
4115 (((class color) (min-colors 8) (background light))
4116 (:foreground "green"))
4117 (((class color) (min-colors 8) (background dark))
4118 (:foreground "yellow"))))
4119 "Face for fixed-with text like code snippets."
4120 :group 'org-faces
4121 :version "22.1")
4123 (defface org-verbatim
4124 (org-compatible-face nil
4125 '((((class color grayscale) (min-colors 88) (background light))
4126 (:foreground "grey50" :underline t))
4127 (((class color grayscale) (min-colors 88) (background dark))
4128 (:foreground "grey70" :underline t))
4129 (((class color) (min-colors 8) (background light))
4130 (:foreground "green" :underline t))
4131 (((class color) (min-colors 8) (background dark))
4132 (:foreground "yellow" :underline t))))
4133 "Face for fixed-with text like code snippets."
4134 :group 'org-faces
4135 :version "22.1")
4137 (defface org-agenda-structure ;; font-lock-function-name-face
4138 (org-compatible-face nil
4139 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4140 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4141 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4142 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4143 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4144 (t (:bold t))))
4145 "Face used in agenda for captions and dates."
4146 :group 'org-faces)
4148 (defface org-scheduled-today
4149 (org-compatible-face nil
4150 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4151 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4152 (((class color) (min-colors 8)) (:foreground "green"))
4153 (t (:bold t :italic t))))
4154 "Face for items scheduled for a certain day."
4155 :group 'org-faces)
4157 (defface org-scheduled-previously
4158 (org-compatible-face nil
4159 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4160 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4161 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4162 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4163 (t (:bold t))))
4164 "Face for items scheduled previously, and not yet done."
4165 :group 'org-faces)
4167 (defface org-upcoming-deadline
4168 (org-compatible-face nil
4169 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4170 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4171 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4172 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4173 (t (:bold t))))
4174 "Face for items scheduled previously, and not yet done."
4175 :group 'org-faces)
4177 (defcustom org-agenda-deadline-faces
4178 '((1.0 . org-warning)
4179 (0.5 . org-upcoming-deadline)
4180 (0.0 . default))
4181 "Faces for showing deadlines in the agenda.
4182 This is a list of cons cells. The cdr of each cell is a face to be used,
4183 and it can also just be like '(:foreground \"yellow\").
4184 Each car is a fraction of the head-warning time that must have passed for
4185 this the face in the cdr to be used for display. The numbers must be
4186 given in descending order. The head-warning time is normally taken
4187 from `org-deadline-warning-days', but can also be specified in the deadline
4188 timestamp itself, like this:
4190 DEADLINE: <2007-08-13 Mon -8d>
4192 You may use d for days, w for weeks, m for months and y for years. Months
4193 and years will only be treated in an approximate fashion (30.4 days for a
4194 month and 365.24 days for a year)."
4195 :group 'org-faces
4196 :group 'org-agenda-daily/weekly
4197 :type '(repeat
4198 (cons
4199 (number :tag "Fraction of head-warning time passed")
4200 (sexp :tag "Face"))))
4202 ;; FIXME: this is not a good face yet.
4203 (defface org-agenda-restriction-lock
4204 (org-compatible-face nil
4205 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4206 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4207 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4208 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4209 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4210 (t (:inverse-video t))))
4211 "Face for showing the agenda restriction lock."
4212 :group 'org-faces)
4214 (defface org-time-grid ;; font-lock-variable-name-face
4215 (org-compatible-face nil
4216 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4217 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4218 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4219 "Face used for time grids."
4220 :group 'org-faces)
4222 (defconst org-level-faces
4223 '(org-level-1 org-level-2 org-level-3 org-level-4
4224 org-level-5 org-level-6 org-level-7 org-level-8
4227 (defcustom org-n-level-faces (length org-level-faces)
4228 "The number of different faces to be used for headlines.
4229 Org-mode defines 8 different headline faces, so this can be at most 8.
4230 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4231 :type 'number
4232 :group 'org-faces)
4234 ;;; Functions and variables from ther packages
4235 ;; Declared here to avoid compiler warnings
4237 (eval-and-compile
4238 (unless (fboundp 'declare-function)
4239 (defmacro declare-function (fn file &optional arglist fileonly))))
4241 ;; XEmacs only
4242 (defvar outline-mode-menu-heading)
4243 (defvar outline-mode-menu-show)
4244 (defvar outline-mode-menu-hide)
4245 (defvar zmacs-regions) ; XEmacs regions
4247 ;; Emacs only
4248 (defvar mark-active)
4250 ;; Various packages
4251 ;; FIXME: get the argument lists for the UNKNOWN stuff
4252 (declare-function add-to-diary-list "diary-lib"
4253 (date string specifier &optional marker globcolor literal))
4254 (declare-function table--at-cell-p "table" (position &optional object at-column))
4255 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4256 (declare-function bbdb "ext:bbdb-com" (string elidep))
4257 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4258 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4259 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4260 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4261 (declare-function bbdb-record-name "ext:bbdb" (record))
4262 (declare-function bibtex-beginning-of-entry "bibtex" ())
4263 (declare-function bibtex-generate-autokey "bibtex" ())
4264 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4265 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4266 (defvar calc-embedded-close-formula)
4267 (defvar calc-embedded-open-formula)
4268 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4269 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4270 (declare-function calendar-check-holidays "holidays" (date))
4271 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4272 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4273 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4274 (declare-function calendar-forward-day "cal-move" (arg))
4275 (declare-function calendar-french-date-string "cal-french" (&optional date))
4276 (declare-function calendar-goto-date "cal-move" (date))
4277 (declare-function calendar-goto-today "cal-move" ())
4278 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4279 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4280 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4281 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4282 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4283 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4284 (defvar calendar-mode-map)
4285 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4286 (declare-function cdlatex-tab "ext:cdlatex" ())
4287 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4288 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4289 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4290 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4291 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4292 (defvar font-lock-unfontify-region-function)
4293 (declare-function gnus-article-show-summary "gnus-art" ())
4294 (declare-function gnus-summary-last-subject "gnus-sum" ())
4295 (defvar gnus-other-frame-object)
4296 (defvar gnus-group-name)
4297 (defvar gnus-article-current)
4298 (defvar Info-current-file)
4299 (defvar Info-current-node)
4300 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4301 (declare-function mh-find-path "mh-utils" ())
4302 (declare-function mh-get-header-field "mh-utils" (field))
4303 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4304 (declare-function mh-header-display "mh-show" ())
4305 (declare-function mh-index-previous-folder "mh-search" ())
4306 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4307 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4308 (declare-function mh-search-choose "mh-search" (&optional searcher))
4309 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4310 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4311 (declare-function mh-show-header-display "mh-show" t t)
4312 (declare-function mh-show-msg "mh-show" (msg))
4313 (declare-function mh-show-show "mh-show" t t)
4314 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4315 (defvar mh-progs)
4316 (defvar mh-current-folder)
4317 (defvar mh-show-folder-buffer)
4318 (defvar mh-index-folder)
4319 (defvar mh-searcher)
4320 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4321 (declare-function parse-time-string "parse-time" (string))
4322 (declare-function remember "remember" (&optional initial))
4323 (declare-function remember-buffer-desc "remember" ())
4324 (declare-function remember-finalize "remember" ())
4325 (defvar remember-save-after-remembering)
4326 (defvar remember-data-file)
4327 (defvar remember-register)
4328 (defvar remember-buffer)
4329 (defvar remember-handler-functions)
4330 (defvar remember-annotation-functions)
4331 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4332 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4333 (declare-function rmail-what-message "rmail" ())
4334 (defvar rmail-current-message)
4335 (defvar texmathp-why)
4336 (declare-function vm-beginning-of-message "ext:vm-page" ())
4337 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4338 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4339 (declare-function vm-isearch-narrow "ext:vm-search" ())
4340 (declare-function vm-isearch-update "ext:vm-search" ())
4341 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4342 (declare-function vm-su-message-id "ext:vm-summary" (m))
4343 (declare-function vm-su-subject "ext:vm-summary" (m))
4344 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4345 (defvar vm-message-pointer)
4346 (defvar vm-folder-directory)
4347 (defvar w3m-current-url)
4348 (defvar w3m-current-title)
4349 ;; backward compatibility to old version of wl
4350 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4351 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4352 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4353 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4354 (declare-function wl-summary-line-from "ext:wl-summary" ())
4355 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4356 (declare-function wl-summary-message-number "ext:wl-summary" ())
4357 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4358 (defvar wl-summary-buffer-elmo-folder)
4359 (defvar wl-summary-buffer-folder-name)
4360 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4362 (defvar org-latex-regexps)
4363 (defvar constants-unit-system)
4365 ;;; Variables for pre-computed regular expressions, all buffer local
4367 (defvar org-drawer-regexp nil
4368 "Matches first line of a hidden block.")
4369 (make-variable-buffer-local 'org-drawer-regexp)
4370 (defvar org-todo-regexp nil
4371 "Matches any of the TODO state keywords.")
4372 (make-variable-buffer-local 'org-todo-regexp)
4373 (defvar org-not-done-regexp nil
4374 "Matches any of the TODO state keywords except the last one.")
4375 (make-variable-buffer-local 'org-not-done-regexp)
4376 (defvar org-todo-line-regexp nil
4377 "Matches a headline and puts TODO state into group 2 if present.")
4378 (make-variable-buffer-local 'org-todo-line-regexp)
4379 (defvar org-complex-heading-regexp nil
4380 "Matches a headline and puts everything into groups:
4381 group 1: the stars
4382 group 2: The todo keyword, maybe
4383 group 3: Priority cookie
4384 group 4: True headline
4385 group 5: Tags")
4386 (make-variable-buffer-local 'org-complex-heading-regexp)
4387 (defvar org-todo-line-tags-regexp nil
4388 "Matches a headline and puts TODO state into group 2 if present.
4389 Also put tags into group 4 if tags are present.")
4390 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4391 (defvar org-nl-done-regexp nil
4392 "Matches newline followed by a headline with the DONE keyword.")
4393 (make-variable-buffer-local 'org-nl-done-regexp)
4394 (defvar org-looking-at-done-regexp nil
4395 "Matches the DONE keyword a point.")
4396 (make-variable-buffer-local 'org-looking-at-done-regexp)
4397 (defvar org-ds-keyword-length 12
4398 "Maximum length of the Deadline and SCHEDULED keywords.")
4399 (make-variable-buffer-local 'org-ds-keyword-length)
4400 (defvar org-deadline-regexp nil
4401 "Matches the DEADLINE keyword.")
4402 (make-variable-buffer-local 'org-deadline-regexp)
4403 (defvar org-deadline-time-regexp nil
4404 "Matches the DEADLINE keyword together with a time stamp.")
4405 (make-variable-buffer-local 'org-deadline-time-regexp)
4406 (defvar org-deadline-line-regexp nil
4407 "Matches the DEADLINE keyword and the rest of the line.")
4408 (make-variable-buffer-local 'org-deadline-line-regexp)
4409 (defvar org-scheduled-regexp nil
4410 "Matches the SCHEDULED keyword.")
4411 (make-variable-buffer-local 'org-scheduled-regexp)
4412 (defvar org-scheduled-time-regexp nil
4413 "Matches the SCHEDULED keyword together with a time stamp.")
4414 (make-variable-buffer-local 'org-scheduled-time-regexp)
4415 (defvar org-closed-time-regexp nil
4416 "Matches the CLOSED keyword together with a time stamp.")
4417 (make-variable-buffer-local 'org-closed-time-regexp)
4419 (defvar org-keyword-time-regexp nil
4420 "Matches any of the 4 keywords, together with the time stamp.")
4421 (make-variable-buffer-local 'org-keyword-time-regexp)
4422 (defvar org-keyword-time-not-clock-regexp nil
4423 "Matches any of the 3 keywords, together with the time stamp.")
4424 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4425 (defvar org-maybe-keyword-time-regexp nil
4426 "Matches a timestamp, possibly preceeded by a keyword.")
4427 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4428 (defvar org-planning-or-clock-line-re nil
4429 "Matches a line with planning or clock info.")
4430 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4432 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4433 rear-nonsticky t mouse-map t fontified t)
4434 "Properties to remove when a string without properties is wanted.")
4436 (defsubst org-match-string-no-properties (num &optional string)
4437 (if (featurep 'xemacs)
4438 (let ((s (match-string num string)))
4439 (remove-text-properties 0 (length s) org-rm-props s)
4441 (match-string-no-properties num string)))
4443 (defsubst org-no-properties (s)
4444 (if (fboundp 'set-text-properties)
4445 (set-text-properties 0 (length s) nil s)
4446 (remove-text-properties 0 (length s) org-rm-props s))
4449 (defsubst org-get-alist-option (option key)
4450 (cond ((eq key t) t)
4451 ((eq option t) t)
4452 ((assoc key option) (cdr (assoc key option)))
4453 (t (cdr (assq 'default option)))))
4455 (defsubst org-inhibit-invisibility ()
4456 "Modified `buffer-invisibility-spec' for Emacs 21.
4457 Some ops with invisible text do not work correctly on Emacs 21. For these
4458 we turn off invisibility temporarily. Use this in a `let' form."
4459 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4461 (defsubst org-set-local (var value)
4462 "Make VAR local in current buffer and set it to VALUE."
4463 (set (make-variable-buffer-local var) value))
4465 (defsubst org-mode-p ()
4466 "Check if the current buffer is in Org-mode."
4467 (eq major-mode 'org-mode))
4469 (defsubst org-last (list)
4470 "Return the last element of LIST."
4471 (car (last list)))
4473 (defun org-let (list &rest body)
4474 (eval (cons 'let (cons list body))))
4475 (put 'org-let 'lisp-indent-function 1)
4477 (defun org-let2 (list1 list2 &rest body)
4478 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4479 (put 'org-let2 'lisp-indent-function 2)
4480 (defconst org-startup-options
4481 '(("fold" org-startup-folded t)
4482 ("overview" org-startup-folded t)
4483 ("nofold" org-startup-folded nil)
4484 ("showall" org-startup-folded nil)
4485 ("content" org-startup-folded content)
4486 ("hidestars" org-hide-leading-stars t)
4487 ("showstars" org-hide-leading-stars nil)
4488 ("odd" org-odd-levels-only t)
4489 ("oddeven" org-odd-levels-only nil)
4490 ("align" org-startup-align-all-tables t)
4491 ("noalign" org-startup-align-all-tables nil)
4492 ("customtime" org-display-custom-times t)
4493 ("logdone" org-log-done time)
4494 ("lognotedone" org-log-done note)
4495 ("nologdone" org-log-done nil)
4496 ("lognoteclock-out" org-log-note-clock-out t)
4497 ("nolognoteclock-out" org-log-note-clock-out nil)
4498 ("logrepeat" org-log-repeat state)
4499 ("lognoterepeat" org-log-repeat note)
4500 ("nologrepeat" org-log-repeat nil)
4501 ("constcgs" constants-unit-system cgs)
4502 ("constSI" constants-unit-system SI))
4503 "Variable associated with STARTUP options for org-mode.
4504 Each element is a list of three items: The startup options as written
4505 in the #+STARTUP line, the corresponding variable, and the value to
4506 set this variable to if the option is found. An optional forth element PUSH
4507 means to push this value onto the list in the variable.")
4509 (defun org-set-regexps-and-options ()
4510 "Precompute regular expressions for current buffer."
4511 (when (org-mode-p)
4512 (org-set-local 'org-todo-kwd-alist nil)
4513 (org-set-local 'org-todo-key-alist nil)
4514 (org-set-local 'org-todo-key-trigger nil)
4515 (org-set-local 'org-todo-keywords-1 nil)
4516 (org-set-local 'org-done-keywords nil)
4517 (org-set-local 'org-todo-heads nil)
4518 (org-set-local 'org-todo-sets nil)
4519 (org-set-local 'org-todo-log-states nil)
4520 (let ((re (org-make-options-regexp
4521 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4522 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4523 "CONSTANTS" "PROPERTY" "DRAWERS")))
4524 (splitre "[ \t]+")
4525 kwds kws0 kwsa key log value cat arch tags const links hw dws
4526 tail sep kws1 prio props drawers)
4527 (save-excursion
4528 (save-restriction
4529 (widen)
4530 (goto-char (point-min))
4531 (while (re-search-forward re nil t)
4532 (setq key (match-string 1) value (org-match-string-no-properties 2))
4533 (cond
4534 ((equal key "CATEGORY")
4535 (if (string-match "[ \t]+$" value)
4536 (setq value (replace-match "" t t value)))
4537 (setq cat value))
4538 ((member key '("SEQ_TODO" "TODO"))
4539 (push (cons 'sequence (org-split-string value splitre)) kwds))
4540 ((equal key "TYP_TODO")
4541 (push (cons 'type (org-split-string value splitre)) kwds))
4542 ((equal key "TAGS")
4543 (setq tags (append tags (org-split-string value splitre))))
4544 ((equal key "COLUMNS")
4545 (org-set-local 'org-columns-default-format value))
4546 ((equal key "LINK")
4547 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4548 (push (cons (match-string 1 value)
4549 (org-trim (match-string 2 value)))
4550 links)))
4551 ((equal key "PRIORITIES")
4552 (setq prio (org-split-string value " +")))
4553 ((equal key "PROPERTY")
4554 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4555 (push (cons (match-string 1 value) (match-string 2 value))
4556 props)))
4557 ((equal key "DRAWERS")
4558 (setq drawers (org-split-string value splitre)))
4559 ((equal key "CONSTANTS")
4560 (setq const (append const (org-split-string value splitre))))
4561 ((equal key "STARTUP")
4562 (let ((opts (org-split-string value splitre))
4563 l var val)
4564 (while (setq l (pop opts))
4565 (when (setq l (assoc l org-startup-options))
4566 (setq var (nth 1 l) val (nth 2 l))
4567 (if (not (nth 3 l))
4568 (set (make-local-variable var) val)
4569 (if (not (listp (symbol-value var)))
4570 (set (make-local-variable var) nil))
4571 (set (make-local-variable var) (symbol-value var))
4572 (add-to-list var val))))))
4573 ((equal key "ARCHIVE")
4574 (string-match " *$" value)
4575 (setq arch (replace-match "" t t value))
4576 (remove-text-properties 0 (length arch)
4577 '(face t fontified t) arch)))
4579 (when cat
4580 (org-set-local 'org-category (intern cat))
4581 (push (cons "CATEGORY" cat) props))
4582 (when prio
4583 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4584 (setq prio (mapcar 'string-to-char prio))
4585 (org-set-local 'org-highest-priority (nth 0 prio))
4586 (org-set-local 'org-lowest-priority (nth 1 prio))
4587 (org-set-local 'org-default-priority (nth 2 prio)))
4588 (and props (org-set-local 'org-local-properties (nreverse props)))
4589 (and drawers (org-set-local 'org-drawers drawers))
4590 (and arch (org-set-local 'org-archive-location arch))
4591 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4592 ;; Process the TODO keywords
4593 (unless kwds
4594 ;; Use the global values as if they had been given locally.
4595 (setq kwds (default-value 'org-todo-keywords))
4596 (if (stringp (car kwds))
4597 (setq kwds (list (cons org-todo-interpretation
4598 (default-value 'org-todo-keywords)))))
4599 (setq kwds (reverse kwds)))
4600 (setq kwds (nreverse kwds))
4601 (let (inter kws kw)
4602 (while (setq kws (pop kwds))
4603 (setq inter (pop kws) sep (member "|" kws)
4604 kws0 (delete "|" (copy-sequence kws))
4605 kwsa nil
4606 kws1 (mapcar
4607 (lambda (x)
4608 ;; 1 2
4609 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4610 (progn
4611 (setq kw (match-string 1 x)
4612 key (and (match-end 2) (match-string 2 x))
4613 log (org-extract-log-state-settings x))
4614 (push (cons kw (and key (string-to-char key))) kwsa)
4615 (and log (push log org-todo-log-states))
4617 (error "Invalid TODO keyword %s" x)))
4618 kws0)
4619 kwsa (if kwsa (append '((:startgroup))
4620 (nreverse kwsa)
4621 '((:endgroup))))
4622 hw (car kws1)
4623 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4624 tail (list inter hw (car dws) (org-last dws)))
4625 (add-to-list 'org-todo-heads hw 'append)
4626 (push kws1 org-todo-sets)
4627 (setq org-done-keywords (append org-done-keywords dws nil))
4628 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4629 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4630 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4631 (setq org-todo-sets (nreverse org-todo-sets)
4632 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4633 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4634 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4635 ;; Process the constants
4636 (when const
4637 (let (e cst)
4638 (while (setq e (pop const))
4639 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4640 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4641 (setq org-table-formula-constants-local cst)))
4643 ;; Process the tags.
4644 (when tags
4645 (let (e tgs)
4646 (while (setq e (pop tags))
4647 (cond
4648 ((equal e "{") (push '(:startgroup) tgs))
4649 ((equal e "}") (push '(:endgroup) tgs))
4650 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4651 (push (cons (match-string 1 e)
4652 (string-to-char (match-string 2 e)))
4653 tgs))
4654 (t (push (list e) tgs))))
4655 (org-set-local 'org-tag-alist nil)
4656 (while (setq e (pop tgs))
4657 (or (and (stringp (car e))
4658 (assoc (car e) org-tag-alist))
4659 (push e org-tag-alist))))))
4661 ;; Compute the regular expressions and other local variables
4662 (if (not org-done-keywords)
4663 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4664 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4665 (length org-scheduled-string)))
4666 org-drawer-regexp
4667 (concat "^[ \t]*:\\("
4668 (mapconcat 'regexp-quote org-drawers "\\|")
4669 "\\):[ \t]*$")
4670 org-not-done-keywords
4671 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4672 org-todo-regexp
4673 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4674 "\\|") "\\)\\>")
4675 org-not-done-regexp
4676 (concat "\\<\\("
4677 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4678 "\\)\\>")
4679 org-todo-line-regexp
4680 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4681 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4682 "\\)\\>\\)?[ \t]*\\(.*\\)")
4683 org-complex-heading-regexp
4684 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4685 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4686 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4687 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4688 org-nl-done-regexp
4689 (concat "\n\\*+[ \t]+"
4690 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4691 "\\)" "\\>")
4692 org-todo-line-tags-regexp
4693 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4694 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4695 (org-re
4696 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4697 org-looking-at-done-regexp
4698 (concat "^" "\\(?:"
4699 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4700 "\\>")
4701 org-deadline-regexp (concat "\\<" org-deadline-string)
4702 org-deadline-time-regexp
4703 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4704 org-deadline-line-regexp
4705 (concat "\\<\\(" org-deadline-string "\\).*")
4706 org-scheduled-regexp
4707 (concat "\\<" org-scheduled-string)
4708 org-scheduled-time-regexp
4709 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4710 org-closed-time-regexp
4711 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4712 org-keyword-time-regexp
4713 (concat "\\<\\(" org-scheduled-string
4714 "\\|" org-deadline-string
4715 "\\|" org-closed-string
4716 "\\|" org-clock-string "\\)"
4717 " *[[<]\\([^]>]+\\)[]>]")
4718 org-keyword-time-not-clock-regexp
4719 (concat "\\<\\(" org-scheduled-string
4720 "\\|" org-deadline-string
4721 "\\|" org-closed-string
4722 "\\)"
4723 " *[[<]\\([^]>]+\\)[]>]")
4724 org-maybe-keyword-time-regexp
4725 (concat "\\(\\<\\(" org-scheduled-string
4726 "\\|" org-deadline-string
4727 "\\|" org-closed-string
4728 "\\|" org-clock-string "\\)\\)?"
4729 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4730 org-planning-or-clock-line-re
4731 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4732 "\\|" org-deadline-string
4733 "\\|" org-closed-string "\\|" org-clock-string
4734 "\\)\\>\\)")
4736 (org-compute-latex-and-specials-regexp)
4737 (org-set-font-lock-defaults)))
4739 (defun org-extract-log-state-settings (x)
4740 "Extract the log state setting from a TODO keyword string.
4741 This will extract info from a string like \"WAIT(w@/!)\"."
4742 (let (kw key log1 log2)
4743 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4744 (setq kw (match-string 1 x)
4745 key (and (match-end 2) (match-string 2 x))
4746 log1 (and (match-end 3) (match-string 3 x))
4747 log2 (and (match-end 4) (match-string 4 x)))
4748 (and (or log1 log2)
4749 (list kw
4750 (and log1 (if (equal log1 "!") 'time 'note))
4751 (and log2 (if (equal log2 "!") 'time 'note)))))))
4753 (defun org-remove-keyword-keys (list)
4754 "Remove a pair of parenthesis at the end of each string in LIST."
4755 (mapcar (lambda (x)
4756 (if (string-match "(.*)$" x)
4757 (substring x 0 (match-beginning 0))
4759 list))
4761 ;; FIXME: this could be done much better, using second characters etc.
4762 (defun org-assign-fast-keys (alist)
4763 "Assign fast keys to a keyword-key alist.
4764 Respect keys that are already there."
4765 (let (new e k c c1 c2 (char ?a))
4766 (while (setq e (pop alist))
4767 (cond
4768 ((equal e '(:startgroup)) (push e new))
4769 ((equal e '(:endgroup)) (push e new))
4771 (setq k (car e) c2 nil)
4772 (if (cdr e)
4773 (setq c (cdr e))
4774 ;; automatically assign a character.
4775 (setq c1 (string-to-char
4776 (downcase (substring
4777 k (if (= (string-to-char k) ?@) 1 0)))))
4778 (if (or (rassoc c1 new) (rassoc c1 alist))
4779 (while (or (rassoc char new) (rassoc char alist))
4780 (setq char (1+ char)))
4781 (setq c2 c1))
4782 (setq c (or c2 char)))
4783 (push (cons k c) new))))
4784 (nreverse new)))
4786 ;;; Some variables ujsed in various places
4788 (defvar org-window-configuration nil
4789 "Used in various places to store a window configuration.")
4790 (defvar org-finish-function nil
4791 "Function to be called when `C-c C-c' is used.
4792 This is for getting out of special buffers like remember.")
4795 ;; FIXME: Occasionally check by commenting these, to make sure
4796 ;; no other functions uses these, forgetting to let-bind them.
4797 (defvar entry)
4798 (defvar state)
4799 (defvar last-state)
4800 (defvar date)
4801 (defvar description)
4803 ;; Defined somewhere in this file, but used before definition.
4804 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4805 (defvar org-agenda-buffer-name)
4806 (defvar org-agenda-undo-list)
4807 (defvar org-agenda-pending-undo-list)
4808 (defvar org-agenda-overriding-header)
4809 (defvar orgtbl-mode)
4810 (defvar org-html-entities)
4811 (defvar org-struct-menu)
4812 (defvar org-org-menu)
4813 (defvar org-tbl-menu)
4814 (defvar org-agenda-keymap)
4816 ;;;; Emacs/XEmacs compatibility
4818 ;; Overlay compatibility functions
4819 (defun org-make-overlay (beg end &optional buffer)
4820 (if (featurep 'xemacs)
4821 (make-extent beg end buffer)
4822 (make-overlay beg end buffer)))
4823 (defun org-delete-overlay (ovl)
4824 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4825 (defun org-detach-overlay (ovl)
4826 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4827 (defun org-move-overlay (ovl beg end &optional buffer)
4828 (if (featurep 'xemacs)
4829 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4830 (move-overlay ovl beg end buffer)))
4831 (defun org-overlay-put (ovl prop value)
4832 (if (featurep 'xemacs)
4833 (set-extent-property ovl prop value)
4834 (overlay-put ovl prop value)))
4835 (defun org-overlay-display (ovl text &optional face evap)
4836 "Make overlay OVL display TEXT with face FACE."
4837 (if (featurep 'xemacs)
4838 (let ((gl (make-glyph text)))
4839 (and face (set-glyph-face gl face))
4840 (set-extent-property ovl 'invisible t)
4841 (set-extent-property ovl 'end-glyph gl))
4842 (overlay-put ovl 'display text)
4843 (if face (overlay-put ovl 'face face))
4844 (if evap (overlay-put ovl 'evaporate t))))
4845 (defun org-overlay-before-string (ovl text &optional face evap)
4846 "Make overlay OVL display TEXT with face FACE."
4847 (if (featurep 'xemacs)
4848 (let ((gl (make-glyph text)))
4849 (and face (set-glyph-face gl face))
4850 (set-extent-property ovl 'begin-glyph gl))
4851 (if face (org-add-props text nil 'face face))
4852 (overlay-put ovl 'before-string text)
4853 (if evap (overlay-put ovl 'evaporate t))))
4854 (defun org-overlay-get (ovl prop)
4855 (if (featurep 'xemacs)
4856 (extent-property ovl prop)
4857 (overlay-get ovl prop)))
4858 (defun org-overlays-at (pos)
4859 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4860 (defun org-overlays-in (&optional start end)
4861 (if (featurep 'xemacs)
4862 (extent-list nil start end)
4863 (overlays-in start end)))
4864 (defun org-overlay-start (o)
4865 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4866 (defun org-overlay-end (o)
4867 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4868 (defun org-find-overlays (prop &optional pos delete)
4869 "Find all overlays specifying PROP at POS or point.
4870 If DELETE is non-nil, delete all those overlays."
4871 (let ((overlays (org-overlays-at (or pos (point))))
4872 ov found)
4873 (while (setq ov (pop overlays))
4874 (if (org-overlay-get ov prop)
4875 (if delete (org-delete-overlay ov) (push ov found))))
4876 found))
4878 ;; Region compatibility
4880 (defun org-add-hook (hook function &optional append local)
4881 "Add-hook, compatible with both Emacsen."
4882 (if (and local (featurep 'xemacs))
4883 (add-local-hook hook function append)
4884 (add-hook hook function append local)))
4886 (defvar org-ignore-region nil
4887 "To temporarily disable the active region.")
4889 (defun org-region-active-p ()
4890 "Is `transient-mark-mode' on and the region active?
4891 Works on both Emacs and XEmacs."
4892 (if org-ignore-region
4894 (if (featurep 'xemacs)
4895 (and zmacs-regions (region-active-p))
4896 (if (fboundp 'use-region-p)
4897 (use-region-p)
4898 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4900 ;; Invisibility compatibility
4902 (defun org-add-to-invisibility-spec (arg)
4903 "Add elements to `buffer-invisibility-spec'.
4904 See documentation for `buffer-invisibility-spec' for the kind of elements
4905 that can be added."
4906 (cond
4907 ((fboundp 'add-to-invisibility-spec)
4908 (add-to-invisibility-spec arg))
4909 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4910 (setq buffer-invisibility-spec (list arg)))
4912 (setq buffer-invisibility-spec
4913 (cons arg buffer-invisibility-spec)))))
4915 (defun org-remove-from-invisibility-spec (arg)
4916 "Remove elements from `buffer-invisibility-spec'."
4917 (if (fboundp 'remove-from-invisibility-spec)
4918 (remove-from-invisibility-spec arg)
4919 (if (consp buffer-invisibility-spec)
4920 (setq buffer-invisibility-spec
4921 (delete arg buffer-invisibility-spec)))))
4923 (defun org-in-invisibility-spec-p (arg)
4924 "Is ARG a member of `buffer-invisibility-spec'?"
4925 (if (consp buffer-invisibility-spec)
4926 (member arg buffer-invisibility-spec)
4927 nil))
4929 ;;;; Define the Org-mode
4931 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4932 (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."))
4935 ;; We use a before-change function to check if a table might need
4936 ;; an update.
4937 (defvar org-table-may-need-update t
4938 "Indicates that a table might need an update.
4939 This variable is set by `org-before-change-function'.
4940 `org-table-align' sets it back to nil.")
4941 (defvar org-mode-map)
4942 (defvar org-mode-hook nil)
4943 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4944 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4945 (defvar org-table-buffer-is-an nil)
4946 (defconst org-outline-regexp "\\*+ ")
4948 ;;;###autoload
4949 (define-derived-mode org-mode outline-mode "Org"
4950 "Outline-based notes management and organizer, alias
4951 \"Carsten's outline-mode for keeping track of everything.\"
4953 Org-mode develops organizational tasks around a NOTES file which
4954 contains information about projects as plain text. Org-mode is
4955 implemented on top of outline-mode, which is ideal to keep the content
4956 of large files well structured. It supports ToDo items, deadlines and
4957 time stamps, which magically appear in the diary listing of the Emacs
4958 calendar. Tables are easily created with a built-in table editor.
4959 Plain text URL-like links connect to websites, emails (VM), Usenet
4960 messages (Gnus), BBDB entries, and any files related to the project.
4961 For printing and sharing of notes, an Org-mode file (or a part of it)
4962 can be exported as a structured ASCII or HTML file.
4964 The following commands are available:
4966 \\{org-mode-map}"
4968 ;; Get rid of Outline menus, they are not needed
4969 ;; Need to do this here because define-derived-mode sets up
4970 ;; the keymap so late. Still, it is a waste to call this each time
4971 ;; we switch another buffer into org-mode.
4972 (if (featurep 'xemacs)
4973 (when (boundp 'outline-mode-menu-heading)
4974 ;; Assume this is Greg's port, it used easymenu
4975 (easy-menu-remove outline-mode-menu-heading)
4976 (easy-menu-remove outline-mode-menu-show)
4977 (easy-menu-remove outline-mode-menu-hide))
4978 (define-key org-mode-map [menu-bar headings] 'undefined)
4979 (define-key org-mode-map [menu-bar hide] 'undefined)
4980 (define-key org-mode-map [menu-bar show] 'undefined))
4982 (easy-menu-add org-org-menu)
4983 (easy-menu-add org-tbl-menu)
4984 (org-install-agenda-files-menu)
4985 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4986 (org-add-to-invisibility-spec '(org-cwidth))
4987 (when (featurep 'xemacs)
4988 (org-set-local 'line-move-ignore-invisible t))
4989 (org-set-local 'outline-regexp org-outline-regexp)
4990 (org-set-local 'outline-level 'org-outline-level)
4991 (when (and org-ellipsis
4992 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4993 (fboundp 'make-glyph-code))
4994 (unless org-display-table
4995 (setq org-display-table (make-display-table)))
4996 (set-display-table-slot
4997 org-display-table 4
4998 (vconcat (mapcar
4999 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5000 org-ellipsis)))
5001 (if (stringp org-ellipsis) org-ellipsis "..."))))
5002 (setq buffer-display-table org-display-table))
5003 (org-set-regexps-and-options)
5004 ;; Calc embedded
5005 (org-set-local 'calc-embedded-open-mode "# ")
5006 (modify-syntax-entry ?# "<")
5007 (modify-syntax-entry ?@ "w")
5008 (if org-startup-truncated (setq truncate-lines t))
5009 (org-set-local 'font-lock-unfontify-region-function
5010 'org-unfontify-region)
5011 ;; Activate before-change-function
5012 (org-set-local 'org-table-may-need-update t)
5013 (org-add-hook 'before-change-functions 'org-before-change-function nil
5014 'local)
5015 ;; Check for running clock before killing a buffer
5016 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5017 ;; Paragraphs and auto-filling
5018 (org-set-autofill-regexps)
5019 (setq indent-line-function 'org-indent-line-function)
5020 (org-update-radio-target-regexp)
5022 ;; Comment characters
5023 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5024 (org-set-local 'comment-padding " ")
5026 ;; Align options lines
5027 (org-set-local
5028 'align-mode-rules-list
5029 '((org-in-buffer-settings
5030 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5031 (modes . '(org-mode)))))
5033 ;; Imenu
5034 (org-set-local 'imenu-create-index-function
5035 'org-imenu-get-tree)
5037 ;; Make isearch reveal context
5038 (if (or (featurep 'xemacs)
5039 (not (boundp 'outline-isearch-open-invisible-function)))
5040 ;; Emacs 21 and XEmacs make use of the hook
5041 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5042 ;; Emacs 22 deals with this through a special variable
5043 (org-set-local 'outline-isearch-open-invisible-function
5044 (lambda (&rest ignore) (org-show-context 'isearch))))
5046 ;; If empty file that did not turn on org-mode automatically, make it to.
5047 (if (and org-insert-mode-line-in-empty-file
5048 (interactive-p)
5049 (= (point-min) (point-max)))
5050 (insert "# -*- mode: org -*-\n\n"))
5052 (unless org-inhibit-startup
5053 (when org-startup-align-all-tables
5054 (let ((bmp (buffer-modified-p)))
5055 (org-table-map-tables 'org-table-align)
5056 (set-buffer-modified-p bmp)))
5057 (org-cycle-hide-drawers 'all)
5058 (cond
5059 ((eq org-startup-folded t)
5060 (org-cycle '(4)))
5061 ((eq org-startup-folded 'content)
5062 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5063 (org-cycle '(4)) (org-cycle '(4)))))))
5065 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5067 (defsubst org-call-with-arg (command arg)
5068 "Call COMMAND interactively, but pretend prefix are was ARG."
5069 (let ((current-prefix-arg arg)) (call-interactively command)))
5071 (defsubst org-current-line (&optional pos)
5072 (save-excursion
5073 (and pos (goto-char pos))
5074 ;; works also in narrowed buffer, because we start at 1, not point-min
5075 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5077 (defun org-current-time ()
5078 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5079 (if (> org-time-stamp-rounding-minutes 0)
5080 (let ((r org-time-stamp-rounding-minutes)
5081 (time (decode-time)))
5082 (apply 'encode-time
5083 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5084 (nthcdr 2 time))))
5085 (current-time)))
5087 (defun org-add-props (string plist &rest props)
5088 "Add text properties to entire string, from beginning to end.
5089 PLIST may be a list of properties, PROPS are individual properties and values
5090 that will be added to PLIST. Returns the string that was modified."
5091 (add-text-properties
5092 0 (length string) (if props (append plist props) plist) string)
5093 string)
5094 (put 'org-add-props 'lisp-indent-function 2)
5097 ;;;; Font-Lock stuff, including the activators
5099 (defvar org-mouse-map (make-sparse-keymap))
5100 (org-defkey org-mouse-map
5101 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5102 (org-defkey org-mouse-map
5103 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5104 (when org-mouse-1-follows-link
5105 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5106 (when org-tab-follows-link
5107 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5108 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5109 (when org-return-follows-link
5110 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5111 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5113 (require 'font-lock)
5115 (defconst org-non-link-chars "]\t\n\r<>")
5116 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5117 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5118 (defvar org-link-re-with-space nil
5119 "Matches a link with spaces, optional angular brackets around it.")
5120 (defvar org-link-re-with-space2 nil
5121 "Matches a link with spaces, optional angular brackets around it.")
5122 (defvar org-angle-link-re nil
5123 "Matches link with angular brackets, spaces are allowed.")
5124 (defvar org-plain-link-re nil
5125 "Matches plain link, without spaces.")
5126 (defvar org-bracket-link-regexp nil
5127 "Matches a link in double brackets.")
5128 (defvar org-bracket-link-analytic-regexp nil
5129 "Regular expression used to analyze links.
5130 Here is what the match groups contain after a match:
5131 1: http:
5132 2: http
5133 3: path
5134 4: [desc]
5135 5: desc")
5136 (defvar org-any-link-re nil
5137 "Regular expression matching any link.")
5139 (defun org-make-link-regexps ()
5140 "Update the link regular expressions.
5141 This should be called after the variable `org-link-types' has changed."
5142 (setq org-link-re-with-space
5143 (concat
5144 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5145 "\\([^" org-non-link-chars " ]"
5146 "[^" org-non-link-chars "]*"
5147 "[^" org-non-link-chars " ]\\)>?")
5148 org-link-re-with-space2
5149 (concat
5150 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5151 "\\([^" org-non-link-chars " ]"
5152 "[^]\t\n\r]*"
5153 "[^" org-non-link-chars " ]\\)>?")
5154 org-angle-link-re
5155 (concat
5156 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5157 "\\([^" org-non-link-chars " ]"
5158 "[^" org-non-link-chars "]*"
5159 "\\)>")
5160 org-plain-link-re
5161 (concat
5162 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5163 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5164 org-bracket-link-regexp
5165 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5166 org-bracket-link-analytic-regexp
5167 (concat
5168 "\\[\\["
5169 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5170 "\\([^]]+\\)"
5171 "\\]"
5172 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5173 "\\]")
5174 org-any-link-re
5175 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5176 org-angle-link-re "\\)\\|\\("
5177 org-plain-link-re "\\)")))
5179 (org-make-link-regexps)
5181 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5182 "Regular expression for fast time stamp matching.")
5183 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5184 "Regular expression for fast time stamp matching.")
5185 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5186 "Regular expression matching time strings for analysis.
5187 This one does not require the space after the date.")
5188 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5189 "Regular expression matching time strings for analysis.")
5190 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5191 "Regular expression matching time stamps, with groups.")
5192 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5193 "Regular expression matching time stamps (also [..]), with groups.")
5194 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5195 "Regular expression matching a time stamp range.")
5196 (defconst org-tr-regexp-both
5197 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5198 "Regular expression matching a time stamp range.")
5199 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5200 org-ts-regexp "\\)?")
5201 "Regular expression matching a time stamp or time stamp range.")
5202 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5203 org-ts-regexp-both "\\)?")
5204 "Regular expression matching a time stamp or time stamp range.
5205 The time stamps may be either active or inactive.")
5207 (defvar org-emph-face nil)
5209 (defun org-do-emphasis-faces (limit)
5210 "Run through the buffer and add overlays to links."
5211 (let (rtn)
5212 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5213 (if (not (= (char-after (match-beginning 3))
5214 (char-after (match-beginning 4))))
5215 (progn
5216 (setq rtn t)
5217 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5218 'face
5219 (nth 1 (assoc (match-string 3)
5220 org-emphasis-alist)))
5221 (add-text-properties (match-beginning 2) (match-end 2)
5222 '(font-lock-multiline t))
5223 (when org-hide-emphasis-markers
5224 (add-text-properties (match-end 4) (match-beginning 5)
5225 '(invisible org-link))
5226 (add-text-properties (match-beginning 3) (match-end 3)
5227 '(invisible org-link)))))
5228 (backward-char 1))
5229 rtn))
5231 (defun org-emphasize (&optional char)
5232 "Insert or change an emphasis, i.e. a font like bold or italic.
5233 If there is an active region, change that region to a new emphasis.
5234 If there is no region, just insert the marker characters and position
5235 the cursor between them.
5236 CHAR should be either the marker character, or the first character of the
5237 HTML tag associated with that emphasis. If CHAR is a space, the means
5238 to remove the emphasis of the selected region.
5239 If char is not given (for example in an interactive call) it
5240 will be prompted for."
5241 (interactive)
5242 (let ((eal org-emphasis-alist) e det
5243 (erc org-emphasis-regexp-components)
5244 (prompt "")
5245 (string "") beg end move tag c s)
5246 (if (org-region-active-p)
5247 (setq beg (region-beginning) end (region-end)
5248 string (buffer-substring beg end))
5249 (setq move t))
5251 (while (setq e (pop eal))
5252 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5253 c (aref tag 0))
5254 (push (cons c (string-to-char (car e))) det)
5255 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5256 (substring tag 1)))))
5257 (unless char
5258 (message "%s" (concat "Emphasis marker or tag:" prompt))
5259 (setq char (read-char-exclusive)))
5260 (setq char (or (cdr (assoc char det)) char))
5261 (if (equal char ?\ )
5262 (setq s "" move nil)
5263 (unless (assoc (char-to-string char) org-emphasis-alist)
5264 (error "No such emphasis marker: \"%c\"" char))
5265 (setq s (char-to-string char)))
5266 (while (and (> (length string) 1)
5267 (equal (substring string 0 1) (substring string -1))
5268 (assoc (substring string 0 1) org-emphasis-alist))
5269 (setq string (substring string 1 -1)))
5270 (setq string (concat s string s))
5271 (if beg (delete-region beg end))
5272 (unless (or (bolp)
5273 (string-match (concat "[" (nth 0 erc) "\n]")
5274 (char-to-string (char-before (point)))))
5275 (insert " "))
5276 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5277 (char-to-string (char-after (point))))
5278 (insert " ") (backward-char 1))
5279 (insert string)
5280 (and move (backward-char 1))))
5282 (defconst org-nonsticky-props
5283 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5286 (defun org-activate-plain-links (limit)
5287 "Run through the buffer and add overlays to links."
5288 (catch 'exit
5289 (let (f)
5290 (while (re-search-forward org-plain-link-re limit t)
5291 (setq f (get-text-property (match-beginning 0) 'face))
5292 (if (or (eq f 'org-tag)
5293 (and (listp f) (memq 'org-tag f)))
5295 (add-text-properties (match-beginning 0) (match-end 0)
5296 (list 'mouse-face 'highlight
5297 'rear-nonsticky org-nonsticky-props
5298 'keymap org-mouse-map
5300 (throw 'exit t))))))
5302 (defun org-activate-code (limit)
5303 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5304 (unless (get-text-property (match-beginning 1) 'face)
5305 (remove-text-properties (match-beginning 0) (match-end 0)
5306 '(display t invisible t intangible t))
5307 t)))
5309 (defun org-activate-angle-links (limit)
5310 "Run through the buffer and add overlays to links."
5311 (if (re-search-forward org-angle-link-re limit t)
5312 (progn
5313 (add-text-properties (match-beginning 0) (match-end 0)
5314 (list 'mouse-face 'highlight
5315 'rear-nonsticky org-nonsticky-props
5316 'keymap org-mouse-map
5318 t)))
5320 (defmacro org-maybe-intangible (props)
5321 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5322 In emacs 21, invisible text is not avoided by the command loop, so the
5323 intangible property is needed to make sure point skips this text.
5324 In Emacs 22, this is not necessary. The intangible text property has
5325 led to problems with flyspell. These problems are fixed in flyspell.el,
5326 but we still avoid setting the property in Emacs 22 and later.
5327 We use a macro so that the test can happen at compilation time."
5328 (if (< emacs-major-version 22)
5329 `(append '(intangible t) ,props)
5330 props))
5332 (defun org-activate-bracket-links (limit)
5333 "Run through the buffer and add overlays to bracketed links."
5334 (if (re-search-forward org-bracket-link-regexp limit t)
5335 (let* ((help (concat "LINK: "
5336 (org-match-string-no-properties 1)))
5337 ;; FIXME: above we should remove the escapes.
5338 ;; but that requires another match, protecting match data,
5339 ;; a lot of overhead for font-lock.
5340 (ip (org-maybe-intangible
5341 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5342 'keymap org-mouse-map 'mouse-face 'highlight
5343 'font-lock-multiline t 'help-echo help)))
5344 (vp (list 'rear-nonsticky org-nonsticky-props
5345 'keymap org-mouse-map 'mouse-face 'highlight
5346 ' font-lock-multiline t 'help-echo help)))
5347 ;; We need to remove the invisible property here. Table narrowing
5348 ;; may have made some of this invisible.
5349 (remove-text-properties (match-beginning 0) (match-end 0)
5350 '(invisible nil))
5351 (if (match-end 3)
5352 (progn
5353 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5354 (add-text-properties (match-beginning 3) (match-end 3) vp)
5355 (add-text-properties (match-end 3) (match-end 0) ip))
5356 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5357 (add-text-properties (match-beginning 1) (match-end 1) vp)
5358 (add-text-properties (match-end 1) (match-end 0) ip))
5359 t)))
5361 (defun org-activate-dates (limit)
5362 "Run through the buffer and add overlays to dates."
5363 (if (re-search-forward org-tsr-regexp-both limit t)
5364 (progn
5365 (add-text-properties (match-beginning 0) (match-end 0)
5366 (list 'mouse-face 'highlight
5367 'rear-nonsticky org-nonsticky-props
5368 'keymap org-mouse-map))
5369 (when org-display-custom-times
5370 (if (match-end 3)
5371 (org-display-custom-time (match-beginning 3) (match-end 3)))
5372 (org-display-custom-time (match-beginning 1) (match-end 1)))
5373 t)))
5375 (defvar org-target-link-regexp nil
5376 "Regular expression matching radio targets in plain text.")
5377 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5378 "Regular expression matching a link target.")
5379 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5380 "Regular expression matching a radio target.")
5381 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5382 "Regular expression matching any target.")
5384 (defun org-activate-target-links (limit)
5385 "Run through the buffer and add overlays to target matches."
5386 (when org-target-link-regexp
5387 (let ((case-fold-search t))
5388 (if (re-search-forward org-target-link-regexp limit t)
5389 (progn
5390 (add-text-properties (match-beginning 0) (match-end 0)
5391 (list 'mouse-face 'highlight
5392 'rear-nonsticky org-nonsticky-props
5393 'keymap org-mouse-map
5394 'help-echo "Radio target link"
5395 'org-linked-text t))
5396 t)))))
5398 (defun org-update-radio-target-regexp ()
5399 "Find all radio targets in this file and update the regular expression."
5400 (interactive)
5401 (when (memq 'radio org-activate-links)
5402 (setq org-target-link-regexp
5403 (org-make-target-link-regexp (org-all-targets 'radio)))
5404 (org-restart-font-lock)))
5406 (defun org-hide-wide-columns (limit)
5407 (let (s e)
5408 (setq s (text-property-any (point) (or limit (point-max))
5409 'org-cwidth t))
5410 (when s
5411 (setq e (next-single-property-change s 'org-cwidth))
5412 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5413 (goto-char e)
5414 t)))
5416 (defvar org-latex-and-specials-regexp nil
5417 "Regular expression for highlighting export special stuff.")
5418 (defvar org-match-substring-regexp)
5419 (defvar org-match-substring-with-braces-regexp)
5420 (defvar org-export-html-special-string-regexps)
5422 (defun org-compute-latex-and-specials-regexp ()
5423 "Compute regular expression for stuff treated specially by exporters."
5424 (if (not org-highlight-latex-fragments-and-specials)
5425 (org-set-local 'org-latex-and-specials-regexp nil)
5426 (let*
5427 ((matchers (plist-get org-format-latex-options :matchers))
5428 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5429 org-latex-regexps)))
5430 (options (org-combine-plists (org-default-export-plist)
5431 (org-infile-export-plist)))
5432 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5433 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5434 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5435 (org-export-html-expand (plist-get options :expand-quoted-html))
5436 (org-export-with-special-strings (plist-get options :special-strings))
5437 (re-sub
5438 (cond
5439 ((equal org-export-with-sub-superscripts '{})
5440 (list org-match-substring-with-braces-regexp))
5441 (org-export-with-sub-superscripts
5442 (list org-match-substring-regexp))
5443 (t nil)))
5444 (re-latex
5445 (if org-export-with-LaTeX-fragments
5446 (mapcar (lambda (x) (nth 1 x)) latexs)))
5447 (re-macros
5448 (if org-export-with-TeX-macros
5449 (list (concat "\\\\"
5450 (regexp-opt
5451 (append (mapcar 'car org-html-entities)
5452 (if (boundp 'org-latex-entities)
5453 org-latex-entities nil))
5454 'words))) ; FIXME
5456 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5457 (re-special (if org-export-with-special-strings
5458 (mapcar (lambda (x) (car x))
5459 org-export-html-special-string-regexps)))
5460 (re-rest
5461 (delq nil
5462 (list
5463 (if org-export-html-expand "@<[^>\n]+>")
5464 ))))
5465 (org-set-local
5466 'org-latex-and-specials-regexp
5467 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5468 re-rest) "\\|")))))
5470 (defface org-latex-and-export-specials
5471 (let ((font (cond ((assq :inherit custom-face-attributes)
5472 '(:inherit underline))
5473 (t '(:underline t)))))
5474 `((((class grayscale) (background light))
5475 (:foreground "DimGray" ,@font))
5476 (((class grayscale) (background dark))
5477 (:foreground "LightGray" ,@font))
5478 (((class color) (background light))
5479 (:foreground "SaddleBrown"))
5480 (((class color) (background dark))
5481 (:foreground "burlywood"))
5482 (t (,@font))))
5483 "Face used to highlight math latex and other special exporter stuff."
5484 :group 'org-faces)
5486 (defun org-do-latex-and-special-faces (limit)
5487 "Run through the buffer and add overlays to links."
5488 (when org-latex-and-specials-regexp
5489 (let (rtn d)
5490 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5491 limit t))
5492 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5493 'face))
5494 '(org-code org-verbatim underline)))
5495 (progn
5496 (setq rtn t
5497 d (cond ((member (char-after (1+ (match-beginning 0)))
5498 '(?_ ?^)) 1)
5499 (t 0)))
5500 (font-lock-prepend-text-property
5501 (+ d (match-beginning 0)) (match-end 0)
5502 'face 'org-latex-and-export-specials)
5503 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5504 '(font-lock-multiline t)))))
5505 rtn)))
5507 (defun org-restart-font-lock ()
5508 "Restart font-lock-mode, to force refontification."
5509 (when (and (boundp 'font-lock-mode) font-lock-mode)
5510 (font-lock-mode -1)
5511 (font-lock-mode 1)))
5513 (defun org-all-targets (&optional radio)
5514 "Return a list of all targets in this file.
5515 With optional argument RADIO, only find radio targets."
5516 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5517 rtn)
5518 (save-excursion
5519 (goto-char (point-min))
5520 (while (re-search-forward re nil t)
5521 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5522 rtn)))
5524 (defun org-make-target-link-regexp (targets)
5525 "Make regular expression matching all strings in TARGETS.
5526 The regular expression finds the targets also if there is a line break
5527 between words."
5528 (and targets
5529 (concat
5530 "\\<\\("
5531 (mapconcat
5532 (lambda (x)
5533 (while (string-match " +" x)
5534 (setq x (replace-match "\\s-+" t t x)))
5536 targets
5537 "\\|")
5538 "\\)\\>")))
5540 (defun org-activate-tags (limit)
5541 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5542 (progn
5543 (add-text-properties (match-beginning 1) (match-end 1)
5544 (list 'mouse-face 'highlight
5545 'rear-nonsticky org-nonsticky-props
5546 'keymap org-mouse-map))
5547 t)))
5549 (defun org-outline-level ()
5550 (save-excursion
5551 (looking-at outline-regexp)
5552 (if (match-beginning 1)
5553 (+ (org-get-string-indentation (match-string 1)) 1000)
5554 (1- (- (match-end 0) (match-beginning 0))))))
5556 (defvar org-font-lock-keywords nil)
5558 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5559 "Regular expression matching a property line.")
5561 (defun org-set-font-lock-defaults ()
5562 (let* ((em org-fontify-emphasized-text)
5563 (lk org-activate-links)
5564 (org-font-lock-extra-keywords
5565 (list
5566 ;; Headlines
5567 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5568 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5569 ;; Table lines
5570 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5571 (1 'org-table t))
5572 ;; Table internals
5573 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5574 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5575 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5576 ;; Drawers
5577 (list org-drawer-regexp '(0 'org-special-keyword t))
5578 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5579 ;; Properties
5580 (list org-property-re
5581 '(1 'org-special-keyword t)
5582 '(3 'org-property-value t))
5583 (if org-format-transports-properties-p
5584 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5585 ;; Links
5586 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5587 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5588 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5589 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5590 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5591 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5592 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5593 '(org-hide-wide-columns (0 nil append))
5594 ;; TODO lines
5595 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5596 '(1 (org-get-todo-face 1) t))
5597 ;; DONE
5598 (if org-fontify-done-headline
5599 (list (concat "^[*]+ +\\<\\("
5600 (mapconcat 'regexp-quote org-done-keywords "\\|")
5601 "\\)\\(.*\\)")
5602 '(2 'org-headline-done t))
5603 nil)
5604 ;; Priorities
5605 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5606 ;; Special keywords
5607 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5608 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5609 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5610 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5611 ;; Emphasis
5612 (if em
5613 (if (featurep 'xemacs)
5614 '(org-do-emphasis-faces (0 nil append))
5615 '(org-do-emphasis-faces)))
5616 ;; Checkboxes
5617 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5618 2 'bold prepend)
5619 (if org-provide-checkbox-statistics
5620 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5621 (0 (org-get-checkbox-statistics-face) t)))
5622 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5623 '(1 'org-archived prepend))
5624 ;; Specials
5625 '(org-do-latex-and-special-faces)
5626 ;; Code
5627 '(org-activate-code (1 'org-code t))
5628 ;; COMMENT
5629 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5630 "\\|" org-quote-string "\\)\\>")
5631 '(1 'org-special-keyword t))
5632 '("^#.*" (0 'font-lock-comment-face t))
5634 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5635 ;; Now set the full font-lock-keywords
5636 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5637 (org-set-local 'font-lock-defaults
5638 '(org-font-lock-keywords t nil nil backward-paragraph))
5639 (kill-local-variable 'font-lock-keywords) nil))
5641 (defvar org-m nil)
5642 (defvar org-l nil)
5643 (defvar org-f nil)
5644 (defun org-get-level-face (n)
5645 "Get the right face for match N in font-lock matching of healdines."
5646 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5647 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5648 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5649 (cond
5650 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5651 ((eq n 2) org-f)
5652 (t (if org-level-color-stars-only nil org-f))))
5654 (defun org-get-todo-face (kwd)
5655 "Get the right face for a TODO keyword KWD.
5656 If KWD is a number, get the corresponding match group."
5657 (if (numberp kwd) (setq kwd (match-string kwd)))
5658 (or (cdr (assoc kwd org-todo-keyword-faces))
5659 (and (member kwd org-done-keywords) 'org-done)
5660 'org-todo))
5662 (defun org-unfontify-region (beg end &optional maybe_loudly)
5663 "Remove fontification and activation overlays from links."
5664 (font-lock-default-unfontify-region beg end)
5665 (let* ((buffer-undo-list t)
5666 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5667 (inhibit-modification-hooks t)
5668 deactivate-mark buffer-file-name buffer-file-truename)
5669 (remove-text-properties beg end
5670 '(mouse-face t keymap t org-linked-text t
5671 invisible t intangible t))))
5673 ;;;; Visibility cycling, including org-goto and indirect buffer
5675 ;;; Cycling
5677 (defvar org-cycle-global-status nil)
5678 (make-variable-buffer-local 'org-cycle-global-status)
5679 (defvar org-cycle-subtree-status nil)
5680 (make-variable-buffer-local 'org-cycle-subtree-status)
5682 ;;;###autoload
5683 (defun org-cycle (&optional arg)
5684 "Visibility cycling for Org-mode.
5686 - When this function is called with a prefix argument, rotate the entire
5687 buffer through 3 states (global cycling)
5688 1. OVERVIEW: Show only top-level headlines.
5689 2. CONTENTS: Show all headlines of all levels, but no body text.
5690 3. SHOW ALL: Show everything.
5692 - When point is at the beginning of a headline, rotate the subtree started
5693 by this line through 3 different states (local cycling)
5694 1. FOLDED: Only the main headline is shown.
5695 2. CHILDREN: The main headline and the direct children are shown.
5696 From this state, you can move to one of the children
5697 and zoom in further.
5698 3. SUBTREE: Show the entire subtree, including body text.
5700 - When there is a numeric prefix, go up to a heading with level ARG, do
5701 a `show-subtree' and return to the previous cursor position. If ARG
5702 is negative, go up that many levels.
5704 - When point is not at the beginning of a headline, execute
5705 `indent-relative', like TAB normally does. See the option
5706 `org-cycle-emulate-tab' for details.
5708 - Special case: if point is at the beginning of the buffer and there is
5709 no headline in line 1, this function will act as if called with prefix arg.
5710 But only if also the variable `org-cycle-global-at-bob' is t."
5711 (interactive "P")
5712 (let* ((outline-regexp
5713 (if (and (org-mode-p) org-cycle-include-plain-lists)
5714 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5715 outline-regexp))
5716 (bob-special (and org-cycle-global-at-bob (bobp)
5717 (not (looking-at outline-regexp))))
5718 (org-cycle-hook
5719 (if bob-special
5720 (delq 'org-optimize-window-after-visibility-change
5721 (copy-sequence org-cycle-hook))
5722 org-cycle-hook))
5723 (pos (point)))
5725 (if (or bob-special (equal arg '(4)))
5726 ;; special case: use global cycling
5727 (setq arg t))
5729 (cond
5731 ((org-at-table-p 'any)
5732 ;; Enter the table or move to the next field in the table
5733 (or (org-table-recognize-table.el)
5734 (progn
5735 (if arg (org-table-edit-field t)
5736 (org-table-justify-field-maybe)
5737 (call-interactively 'org-table-next-field)))))
5739 ((eq arg t) ;; Global cycling
5741 (cond
5742 ((and (eq last-command this-command)
5743 (eq org-cycle-global-status 'overview))
5744 ;; We just created the overview - now do table of contents
5745 ;; This can be slow in very large buffers, so indicate action
5746 (message "CONTENTS...")
5747 (org-content)
5748 (message "CONTENTS...done")
5749 (setq org-cycle-global-status 'contents)
5750 (run-hook-with-args 'org-cycle-hook 'contents))
5752 ((and (eq last-command this-command)
5753 (eq org-cycle-global-status 'contents))
5754 ;; We just showed the table of contents - now show everything
5755 (show-all)
5756 (message "SHOW ALL")
5757 (setq org-cycle-global-status 'all)
5758 (run-hook-with-args 'org-cycle-hook 'all))
5761 ;; Default action: go to overview
5762 (org-overview)
5763 (message "OVERVIEW")
5764 (setq org-cycle-global-status 'overview)
5765 (run-hook-with-args 'org-cycle-hook 'overview))))
5767 ((and org-drawers org-drawer-regexp
5768 (save-excursion
5769 (beginning-of-line 1)
5770 (looking-at org-drawer-regexp)))
5771 ;; Toggle block visibility
5772 (org-flag-drawer
5773 (not (get-char-property (match-end 0) 'invisible))))
5775 ((integerp arg)
5776 ;; Show-subtree, ARG levels up from here.
5777 (save-excursion
5778 (org-back-to-heading)
5779 (outline-up-heading (if (< arg 0) (- arg)
5780 (- (funcall outline-level) arg)))
5781 (org-show-subtree)))
5783 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5784 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5785 ;; At a heading: rotate between three different views
5786 (org-back-to-heading)
5787 (let ((goal-column 0) eoh eol eos)
5788 ;; First, some boundaries
5789 (save-excursion
5790 (org-back-to-heading)
5791 (save-excursion
5792 (beginning-of-line 2)
5793 (while (and (not (eobp)) ;; this is like `next-line'
5794 (get-char-property (1- (point)) 'invisible))
5795 (beginning-of-line 2)) (setq eol (point)))
5796 (outline-end-of-heading) (setq eoh (point))
5797 (org-end-of-subtree t)
5798 (unless (eobp)
5799 (skip-chars-forward " \t\n")
5800 (beginning-of-line 1) ; in case this is an item
5802 (setq eos (1- (point))))
5803 ;; Find out what to do next and set `this-command'
5804 (cond
5805 ((= eos eoh)
5806 ;; Nothing is hidden behind this heading
5807 (message "EMPTY ENTRY")
5808 (setq org-cycle-subtree-status nil)
5809 (save-excursion
5810 (goto-char eos)
5811 (outline-next-heading)
5812 (if (org-invisible-p) (org-flag-heading nil))))
5813 ((or (>= eol eos)
5814 (not (string-match "\\S-" (buffer-substring eol eos))))
5815 ;; Entire subtree is hidden in one line: open it
5816 (org-show-entry)
5817 (show-children)
5818 (message "CHILDREN")
5819 (save-excursion
5820 (goto-char eos)
5821 (outline-next-heading)
5822 (if (org-invisible-p) (org-flag-heading nil)))
5823 (setq org-cycle-subtree-status 'children)
5824 (run-hook-with-args 'org-cycle-hook 'children))
5825 ((and (eq last-command this-command)
5826 (eq org-cycle-subtree-status 'children))
5827 ;; We just showed the children, now show everything.
5828 (org-show-subtree)
5829 (message "SUBTREE")
5830 (setq org-cycle-subtree-status 'subtree)
5831 (run-hook-with-args 'org-cycle-hook 'subtree))
5833 ;; Default action: hide the subtree.
5834 (hide-subtree)
5835 (message "FOLDED")
5836 (setq org-cycle-subtree-status 'folded)
5837 (run-hook-with-args 'org-cycle-hook 'folded)))))
5839 ;; TAB emulation
5840 (buffer-read-only (org-back-to-heading))
5842 ((org-try-cdlatex-tab))
5844 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5845 (or (not (bolp))
5846 (not (looking-at outline-regexp))))
5847 (call-interactively (global-key-binding "\t")))
5849 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5850 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5851 (or (and (eq org-cycle-emulate-tab 'white)
5852 (= (match-end 0) (point-at-eol)))
5853 (and (eq org-cycle-emulate-tab 'whitestart)
5854 (>= (match-end 0) pos))))
5856 (eq org-cycle-emulate-tab t))
5857 ; (if (and (looking-at "[ \n\r\t]")
5858 ; (string-match "^[ \t]*$" (buffer-substring
5859 ; (point-at-bol) (point))))
5860 ; (progn
5861 ; (beginning-of-line 1)
5862 ; (and (looking-at "[ \t]+") (replace-match ""))))
5863 (call-interactively (global-key-binding "\t")))
5865 (t (save-excursion
5866 (org-back-to-heading)
5867 (org-cycle))))))
5869 ;;;###autoload
5870 (defun org-global-cycle (&optional arg)
5871 "Cycle the global visibility. For details see `org-cycle'."
5872 (interactive "P")
5873 (let ((org-cycle-include-plain-lists
5874 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5875 (if (integerp arg)
5876 (progn
5877 (show-all)
5878 (hide-sublevels arg)
5879 (setq org-cycle-global-status 'contents))
5880 (org-cycle '(4)))))
5882 (defun org-overview ()
5883 "Switch to overview mode, shoing only top-level headlines.
5884 Really, this shows all headlines with level equal or greater than the level
5885 of the first headline in the buffer. This is important, because if the
5886 first headline is not level one, then (hide-sublevels 1) gives confusing
5887 results."
5888 (interactive)
5889 (let ((level (save-excursion
5890 (goto-char (point-min))
5891 (if (re-search-forward (concat "^" outline-regexp) nil t)
5892 (progn
5893 (goto-char (match-beginning 0))
5894 (funcall outline-level))))))
5895 (and level (hide-sublevels level))))
5897 (defun org-content (&optional arg)
5898 "Show all headlines in the buffer, like a table of contents.
5899 With numerical argument N, show content up to level N."
5900 (interactive "P")
5901 (save-excursion
5902 ;; Visit all headings and show their offspring
5903 (and (integerp arg) (org-overview))
5904 (goto-char (point-max))
5905 (catch 'exit
5906 (while (and (progn (condition-case nil
5907 (outline-previous-visible-heading 1)
5908 (error (goto-char (point-min))))
5910 (looking-at outline-regexp))
5911 (if (integerp arg)
5912 (show-children (1- arg))
5913 (show-branches))
5914 (if (bobp) (throw 'exit nil))))))
5917 (defun org-optimize-window-after-visibility-change (state)
5918 "Adjust the window after a change in outline visibility.
5919 This function is the default value of the hook `org-cycle-hook'."
5920 (when (get-buffer-window (current-buffer))
5921 (cond
5922 ; ((eq state 'overview) (org-first-headline-recenter 1))
5923 ; ((eq state 'overview) (org-beginning-of-line))
5924 ((eq state 'content) nil)
5925 ((eq state 'all) nil)
5926 ((eq state 'folded) nil)
5927 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5928 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5930 (defun org-compact-display-after-subtree-move ()
5931 (let (beg end)
5932 (save-excursion
5933 (if (org-up-heading-safe)
5934 (progn
5935 (hide-subtree)
5936 (show-entry)
5937 (show-children)
5938 (org-cycle-show-empty-lines 'children)
5939 (org-cycle-hide-drawers 'children))
5940 (org-overview)))))
5942 (defun org-cycle-show-empty-lines (state)
5943 "Show empty lines above all visible headlines.
5944 The region to be covered depends on STATE when called through
5945 `org-cycle-hook'. Lisp program can use t for STATE to get the
5946 entire buffer covered. Note that an empty line is only shown if there
5947 are at least `org-cycle-separator-lines' empty lines before the headeline."
5948 (when (> org-cycle-separator-lines 0)
5949 (save-excursion
5950 (let* ((n org-cycle-separator-lines)
5951 (re (cond
5952 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5953 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5954 (t (let ((ns (number-to-string (- n 2))))
5955 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5956 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5957 beg end)
5958 (cond
5959 ((memq state '(overview contents t))
5960 (setq beg (point-min) end (point-max)))
5961 ((memq state '(children folded))
5962 (setq beg (point) end (progn (org-end-of-subtree t t)
5963 (beginning-of-line 2)
5964 (point)))))
5965 (when beg
5966 (goto-char beg)
5967 (while (re-search-forward re end t)
5968 (if (not (get-char-property (match-end 1) 'invisible))
5969 (outline-flag-region
5970 (match-beginning 1) (match-end 1) nil)))))))
5971 ;; Never hide empty lines at the end of the file.
5972 (save-excursion
5973 (goto-char (point-max))
5974 (outline-previous-heading)
5975 (outline-end-of-heading)
5976 (if (and (looking-at "[ \t\n]+")
5977 (= (match-end 0) (point-max)))
5978 (outline-flag-region (point) (match-end 0) nil))))
5980 (defun org-subtree-end-visible-p ()
5981 "Is the end of the current subtree visible?"
5982 (pos-visible-in-window-p
5983 (save-excursion (org-end-of-subtree t) (point))))
5985 (defun org-first-headline-recenter (&optional N)
5986 "Move cursor to the first headline and recenter the headline.
5987 Optional argument N means, put the headline into the Nth line of the window."
5988 (goto-char (point-min))
5989 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5990 (beginning-of-line)
5991 (recenter (prefix-numeric-value N))))
5993 ;;; Org-goto
5995 (defvar org-goto-window-configuration nil)
5996 (defvar org-goto-marker nil)
5997 (defvar org-goto-map
5998 (let ((map (make-sparse-keymap)))
5999 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6000 (while (setq cmd (pop cmds))
6001 (substitute-key-definition cmd cmd map global-map)))
6002 (suppress-keymap map)
6003 (org-defkey map "\C-m" 'org-goto-ret)
6004 (org-defkey map [(return)] 'org-goto-ret)
6005 (org-defkey map [(left)] 'org-goto-left)
6006 (org-defkey map [(right)] 'org-goto-right)
6007 (org-defkey map [(control ?g)] 'org-goto-quit)
6008 (org-defkey map "\C-i" 'org-cycle)
6009 (org-defkey map [(tab)] 'org-cycle)
6010 (org-defkey map [(down)] 'outline-next-visible-heading)
6011 (org-defkey map [(up)] 'outline-previous-visible-heading)
6012 (if org-goto-auto-isearch
6013 (if (fboundp 'define-key-after)
6014 (define-key-after map [t] 'org-goto-local-auto-isearch)
6015 nil)
6016 (org-defkey map "q" 'org-goto-quit)
6017 (org-defkey map "n" 'outline-next-visible-heading)
6018 (org-defkey map "p" 'outline-previous-visible-heading)
6019 (org-defkey map "f" 'outline-forward-same-level)
6020 (org-defkey map "b" 'outline-backward-same-level)
6021 (org-defkey map "u" 'outline-up-heading))
6022 (org-defkey map "/" 'org-occur)
6023 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6024 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6025 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6026 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6027 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6028 map))
6030 (defconst org-goto-help
6031 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6032 RET=jump to location [Q]uit and return to previous location
6033 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6035 (defvar org-goto-start-pos) ; dynamically scoped parameter
6037 (defun org-goto (&optional alternative-interface)
6038 "Look up a different location in the current file, keeping current visibility.
6040 When you want look-up or go to a different location in a document, the
6041 fastest way is often to fold the entire buffer and then dive into the tree.
6042 This method has the disadvantage, that the previous location will be folded,
6043 which may not be what you want.
6045 This command works around this by showing a copy of the current buffer
6046 in an indirect buffer, in overview mode. You can dive into the tree in
6047 that copy, use org-occur and incremental search to find a location.
6048 When pressing RET or `Q', the command returns to the original buffer in
6049 which the visibility is still unchanged. After RET is will also jump to
6050 the location selected in the indirect buffer and expose the
6051 the headline hierarchy above."
6052 (interactive "P")
6053 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6054 (org-refile-use-outline-path t)
6055 (interface
6056 (if (not alternative-interface)
6057 org-goto-interface
6058 (if (eq org-goto-interface 'outline)
6059 'outline-path-completion
6060 'outline)))
6061 (org-goto-start-pos (point))
6062 (selected-point
6063 (if (eq interface 'outline)
6064 (car (org-get-location (current-buffer) org-goto-help))
6065 (nth 3 (org-refile-get-location "Goto: ")))))
6066 (if selected-point
6067 (progn
6068 (org-mark-ring-push org-goto-start-pos)
6069 (goto-char selected-point)
6070 (if (or (org-invisible-p) (org-invisible-p2))
6071 (org-show-context 'org-goto)))
6072 (message "Quit"))))
6074 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6075 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6076 (defvar org-goto-local-auto-isearch-map) ; defined below
6078 (defun org-get-location (buf help)
6079 "Let the user select a location in the Org-mode buffer BUF.
6080 This function uses a recursive edit. It returns the selected position
6081 or nil."
6082 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6083 (isearch-hide-immediately nil)
6084 (isearch-search-fun-function
6085 (lambda () 'org-goto-local-search-forward-headings))
6086 (org-goto-selected-point org-goto-exit-command))
6087 (save-excursion
6088 (save-window-excursion
6089 (delete-other-windows)
6090 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6091 (switch-to-buffer
6092 (condition-case nil
6093 (make-indirect-buffer (current-buffer) "*org-goto*")
6094 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6095 (with-output-to-temp-buffer "*Help*"
6096 (princ help))
6097 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6098 (setq buffer-read-only nil)
6099 (let ((org-startup-truncated t)
6100 (org-startup-folded nil)
6101 (org-startup-align-all-tables nil))
6102 (org-mode)
6103 (org-overview))
6104 (setq buffer-read-only t)
6105 (if (and (boundp 'org-goto-start-pos)
6106 (integer-or-marker-p org-goto-start-pos))
6107 (let ((org-show-hierarchy-above t)
6108 (org-show-siblings t)
6109 (org-show-following-heading t))
6110 (goto-char org-goto-start-pos)
6111 (and (org-invisible-p) (org-show-context)))
6112 (goto-char (point-min)))
6113 (org-beginning-of-line)
6114 (message "Select location and press RET")
6115 (use-local-map org-goto-map)
6116 (recursive-edit)
6118 (kill-buffer "*org-goto*")
6119 (cons org-goto-selected-point org-goto-exit-command)))
6121 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6122 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6123 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6124 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6126 (defun org-goto-local-search-forward-headings (string bound noerror)
6127 "Search and make sure that anu matches are in headlines."
6128 (catch 'return
6129 (while (search-forward string bound noerror)
6130 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6131 (and (member :headline context)
6132 (not (member :tags context))))
6133 (throw 'return (point))))))
6135 (defun org-goto-local-auto-isearch ()
6136 "Start isearch."
6137 (interactive)
6138 (goto-char (point-min))
6139 (let ((keys (this-command-keys)))
6140 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6141 (isearch-mode t)
6142 (isearch-process-search-char (string-to-char keys)))))
6144 (defun org-goto-ret (&optional arg)
6145 "Finish `org-goto' by going to the new location."
6146 (interactive "P")
6147 (setq org-goto-selected-point (point)
6148 org-goto-exit-command 'return)
6149 (throw 'exit nil))
6151 (defun org-goto-left ()
6152 "Finish `org-goto' by going to the new location."
6153 (interactive)
6154 (if (org-on-heading-p)
6155 (progn
6156 (beginning-of-line 1)
6157 (setq org-goto-selected-point (point)
6158 org-goto-exit-command 'left)
6159 (throw 'exit nil))
6160 (error "Not on a heading")))
6162 (defun org-goto-right ()
6163 "Finish `org-goto' by going to the new location."
6164 (interactive)
6165 (if (org-on-heading-p)
6166 (progn
6167 (setq org-goto-selected-point (point)
6168 org-goto-exit-command 'right)
6169 (throw 'exit nil))
6170 (error "Not on a heading")))
6172 (defun org-goto-quit ()
6173 "Finish `org-goto' without cursor motion."
6174 (interactive)
6175 (setq org-goto-selected-point nil)
6176 (setq org-goto-exit-command 'quit)
6177 (throw 'exit nil))
6179 ;;; Indirect buffer display of subtrees
6181 (defvar org-indirect-dedicated-frame nil
6182 "This is the frame being used for indirect tree display.")
6183 (defvar org-last-indirect-buffer nil)
6185 (defun org-tree-to-indirect-buffer (&optional arg)
6186 "Create indirect buffer and narrow it to current subtree.
6187 With numerical prefix ARG, go up to this level and then take that tree.
6188 If ARG is negative, go up that many levels.
6189 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6190 indirect buffer previously made with this command, to avoid proliferation of
6191 indirect buffers. However, when you call the command with a `C-u' prefix, or
6192 when `org-indirect-buffer-display' is `new-frame', the last buffer
6193 is kept so that you can work with several indirect buffers at the same time.
6194 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6195 requests that a new frame be made for the new buffer, so that the dedicated
6196 frame is not changed."
6197 (interactive "P")
6198 (let ((cbuf (current-buffer))
6199 (cwin (selected-window))
6200 (pos (point))
6201 beg end level heading ibuf)
6202 (save-excursion
6203 (org-back-to-heading t)
6204 (when (numberp arg)
6205 (setq level (org-outline-level))
6206 (if (< arg 0) (setq arg (+ level arg)))
6207 (while (> (setq level (org-outline-level)) arg)
6208 (outline-up-heading 1 t)))
6209 (setq beg (point)
6210 heading (org-get-heading))
6211 (org-end-of-subtree t) (setq end (point)))
6212 (if (and (buffer-live-p org-last-indirect-buffer)
6213 (not (eq org-indirect-buffer-display 'new-frame))
6214 (not arg))
6215 (kill-buffer org-last-indirect-buffer))
6216 (setq ibuf (org-get-indirect-buffer cbuf)
6217 org-last-indirect-buffer ibuf)
6218 (cond
6219 ((or (eq org-indirect-buffer-display 'new-frame)
6220 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6221 (select-frame (make-frame))
6222 (delete-other-windows)
6223 (switch-to-buffer ibuf)
6224 (org-set-frame-title heading))
6225 ((eq org-indirect-buffer-display 'dedicated-frame)
6226 (raise-frame
6227 (select-frame (or (and org-indirect-dedicated-frame
6228 (frame-live-p org-indirect-dedicated-frame)
6229 org-indirect-dedicated-frame)
6230 (setq org-indirect-dedicated-frame (make-frame)))))
6231 (delete-other-windows)
6232 (switch-to-buffer ibuf)
6233 (org-set-frame-title (concat "Indirect: " heading)))
6234 ((eq org-indirect-buffer-display 'current-window)
6235 (switch-to-buffer ibuf))
6236 ((eq org-indirect-buffer-display 'other-window)
6237 (pop-to-buffer ibuf))
6238 (t (error "Invalid value.")))
6239 (if (featurep 'xemacs)
6240 (save-excursion (org-mode) (turn-on-font-lock)))
6241 (narrow-to-region beg end)
6242 (show-all)
6243 (goto-char pos)
6244 (and (window-live-p cwin) (select-window cwin))))
6246 (defun org-get-indirect-buffer (&optional buffer)
6247 (setq buffer (or buffer (current-buffer)))
6248 (let ((n 1) (base (buffer-name buffer)) bname)
6249 (while (buffer-live-p
6250 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6251 (setq n (1+ n)))
6252 (condition-case nil
6253 (make-indirect-buffer buffer bname 'clone)
6254 (error (make-indirect-buffer buffer bname)))))
6256 (defun org-set-frame-title (title)
6257 "Set the title of the current frame to the string TITLE."
6258 ;; FIXME: how to name a single frame in XEmacs???
6259 (unless (featurep 'xemacs)
6260 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6262 ;;;; Structure editing
6264 ;;; Inserting headlines
6266 (defun org-insert-heading (&optional force-heading)
6267 "Insert a new heading or item with same depth at point.
6268 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6269 If point is at the beginning of a headline, insert a sibling before the
6270 current headline. If point is not at the beginning, do not split the line,
6271 but create the new hedline after the current line."
6272 (interactive "P")
6273 (if (= (buffer-size) 0)
6274 (insert "\n* ")
6275 (when (or force-heading (not (org-insert-item)))
6276 (let* ((head (save-excursion
6277 (condition-case nil
6278 (progn
6279 (org-back-to-heading)
6280 (match-string 0))
6281 (error "*"))))
6282 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6283 pos)
6284 (cond
6285 ((and (org-on-heading-p) (bolp)
6286 (or (bobp)
6287 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6288 ;; insert before the current line
6289 (open-line (if blank 2 1)))
6290 ((and (bolp)
6291 (or (bobp)
6292 (save-excursion
6293 (backward-char 1) (not (org-invisible-p)))))
6294 ;; insert right here
6295 nil)
6297 ; ;; in the middle of the line
6298 ; (org-show-entry)
6299 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6300 ; (if (and
6301 ; (org-on-heading-p)
6302 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6303 ; ;; protect the tags
6304 ;; (let ((tags (match-string 2)) pos)
6305 ; (delete-region (match-beginning 1) (match-end 1))
6306 ; (setq pos (point-at-bol))
6307 ; (newline (if blank 2 1))
6308 ; (save-excursion
6309 ; (goto-char pos)
6310 ; (end-of-line 1)
6311 ; (insert " " tags)
6312 ; (org-set-tags nil 'align)))
6313 ; (newline (if blank 2 1)))
6314 ; (newline (if blank 2 1))))
6317 ;; in the middle of the line
6318 (org-show-entry)
6319 (let ((split
6320 (org-get-alist-option org-M-RET-may-split-line 'headline))
6321 tags pos)
6322 (if (org-on-heading-p)
6323 (progn
6324 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6325 (setq tags (and (match-end 2) (match-string 2)))
6326 (and (match-end 1)
6327 (delete-region (match-beginning 1) (match-end 1)))
6328 (setq pos (point-at-bol))
6329 (or split (end-of-line 1))
6330 (delete-horizontal-space)
6331 (newline (if blank 2 1))
6332 (when tags
6333 (save-excursion
6334 (goto-char pos)
6335 (end-of-line 1)
6336 (insert " " tags)
6337 (org-set-tags nil 'align))))
6338 (or split (end-of-line 1))
6339 (newline (if blank 2 1))))))
6340 (insert head) (just-one-space)
6341 (setq pos (point))
6342 (end-of-line 1)
6343 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6344 (run-hooks 'org-insert-heading-hook)))))
6346 (defun org-insert-heading-after-current ()
6347 "Insert a new heading with same level as current, after current subtree."
6348 (interactive)
6349 (org-back-to-heading)
6350 (org-insert-heading)
6351 (org-move-subtree-down)
6352 (end-of-line 1))
6354 (defun org-insert-todo-heading (arg)
6355 "Insert a new heading with the same level and TODO state as current heading.
6356 If the heading has no TODO state, or if the state is DONE, use the first
6357 state (TODO by default). Also with prefix arg, force first state."
6358 (interactive "P")
6359 (when (not (org-insert-item 'checkbox))
6360 (org-insert-heading)
6361 (save-excursion
6362 (org-back-to-heading)
6363 (outline-previous-heading)
6364 (looking-at org-todo-line-regexp))
6365 (if (or arg
6366 (not (match-beginning 2))
6367 (member (match-string 2) org-done-keywords))
6368 (insert (car org-todo-keywords-1) " ")
6369 (insert (match-string 2) " "))))
6371 (defun org-insert-subheading (arg)
6372 "Insert a new subheading and demote it.
6373 Works for outline headings and for plain lists alike."
6374 (interactive "P")
6375 (org-insert-heading arg)
6376 (cond
6377 ((org-on-heading-p) (org-do-demote))
6378 ((org-at-item-p) (org-indent-item 1))))
6380 (defun org-insert-todo-subheading (arg)
6381 "Insert a new subheading with TODO keyword or checkbox and demote it.
6382 Works for outline headings and for plain lists alike."
6383 (interactive "P")
6384 (org-insert-todo-heading arg)
6385 (cond
6386 ((org-on-heading-p) (org-do-demote))
6387 ((org-at-item-p) (org-indent-item 1))))
6389 ;;; Promotion and Demotion
6391 (defun org-promote-subtree ()
6392 "Promote the entire subtree.
6393 See also `org-promote'."
6394 (interactive)
6395 (save-excursion
6396 (org-map-tree 'org-promote))
6397 (org-fix-position-after-promote))
6399 (defun org-demote-subtree ()
6400 "Demote the entire subtree. See `org-demote'.
6401 See also `org-promote'."
6402 (interactive)
6403 (save-excursion
6404 (org-map-tree 'org-demote))
6405 (org-fix-position-after-promote))
6408 (defun org-do-promote ()
6409 "Promote the current heading higher up the tree.
6410 If the region is active in `transient-mark-mode', promote all headings
6411 in the region."
6412 (interactive)
6413 (save-excursion
6414 (if (org-region-active-p)
6415 (org-map-region 'org-promote (region-beginning) (region-end))
6416 (org-promote)))
6417 (org-fix-position-after-promote))
6419 (defun org-do-demote ()
6420 "Demote the current heading lower down the tree.
6421 If the region is active in `transient-mark-mode', demote all headings
6422 in the region."
6423 (interactive)
6424 (save-excursion
6425 (if (org-region-active-p)
6426 (org-map-region 'org-demote (region-beginning) (region-end))
6427 (org-demote)))
6428 (org-fix-position-after-promote))
6430 (defun org-fix-position-after-promote ()
6431 "Make sure that after pro/demotion cursor position is right."
6432 (let ((pos (point)))
6433 (when (save-excursion
6434 (beginning-of-line 1)
6435 (looking-at org-todo-line-regexp)
6436 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6437 (cond ((eobp) (insert " "))
6438 ((eolp) (insert " "))
6439 ((equal (char-after) ?\ ) (forward-char 1))))))
6441 (defun org-reduced-level (l)
6442 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6444 (defun org-get-legal-level (level &optional change)
6445 "Rectify a level change under the influence of `org-odd-levels-only'
6446 LEVEL is a current level, CHANGE is by how much the level should be
6447 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6448 even level numbers will become the next higher odd number."
6449 (if org-odd-levels-only
6450 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6451 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6452 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6453 (max 1 (+ level change))))
6455 (defun org-promote ()
6456 "Promote the current heading higher up the tree.
6457 If the region is active in `transient-mark-mode', promote all headings
6458 in the region."
6459 (org-back-to-heading t)
6460 (let* ((level (save-match-data (funcall outline-level)))
6461 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6462 (diff (abs (- level (length up-head) -1))))
6463 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6464 (replace-match up-head nil t)
6465 ;; Fixup tag positioning
6466 (and org-auto-align-tags (org-set-tags nil t))
6467 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6469 (defun org-demote ()
6470 "Demote the current heading lower down the tree.
6471 If the region is active in `transient-mark-mode', demote all headings
6472 in the region."
6473 (org-back-to-heading t)
6474 (let* ((level (save-match-data (funcall outline-level)))
6475 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6476 (diff (abs (- level (length down-head) -1))))
6477 (replace-match down-head nil t)
6478 ;; Fixup tag positioning
6479 (and org-auto-align-tags (org-set-tags nil t))
6480 (if org-adapt-indentation (org-fixup-indentation diff))))
6482 (defun org-map-tree (fun)
6483 "Call FUN for every heading underneath the current one."
6484 (org-back-to-heading)
6485 (let ((level (funcall outline-level)))
6486 (save-excursion
6487 (funcall fun)
6488 (while (and (progn
6489 (outline-next-heading)
6490 (> (funcall outline-level) level))
6491 (not (eobp)))
6492 (funcall fun)))))
6494 (defun org-map-region (fun beg end)
6495 "Call FUN for every heading between BEG and END."
6496 (let ((org-ignore-region t))
6497 (save-excursion
6498 (setq end (copy-marker end))
6499 (goto-char beg)
6500 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6501 (< (point) end))
6502 (funcall fun))
6503 (while (and (progn
6504 (outline-next-heading)
6505 (< (point) end))
6506 (not (eobp)))
6507 (funcall fun)))))
6509 (defun org-fixup-indentation (diff)
6510 "Change the indentation in the current entry by DIFF
6511 However, if any line in the current entry has no indentation, or if it
6512 would end up with no indentation after the change, nothing at all is done."
6513 (save-excursion
6514 (let ((end (save-excursion (outline-next-heading)
6515 (point-marker)))
6516 (prohibit (if (> diff 0)
6517 "^\\S-"
6518 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6519 col)
6520 (unless (save-excursion (end-of-line 1)
6521 (re-search-forward prohibit end t))
6522 (while (and (< (point) end)
6523 (re-search-forward "^[ \t]+" end t))
6524 (goto-char (match-end 0))
6525 (setq col (current-column))
6526 (if (< diff 0) (replace-match ""))
6527 (indent-to (+ diff col))))
6528 (move-marker end nil))))
6530 (defun org-convert-to-odd-levels ()
6531 "Convert an org-mode file with all levels allowed to one with odd levels.
6532 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6533 level 5 etc."
6534 (interactive)
6535 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6536 (let ((org-odd-levels-only nil) n)
6537 (save-excursion
6538 (goto-char (point-min))
6539 (while (re-search-forward "^\\*\\*+ " nil t)
6540 (setq n (- (length (match-string 0)) 2))
6541 (while (>= (setq n (1- n)) 0)
6542 (org-demote))
6543 (end-of-line 1))))))
6546 (defun org-convert-to-oddeven-levels ()
6547 "Convert an org-mode file with only odd levels to one with odd and even levels.
6548 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6549 section with an even level, conversion would destroy the structure of the file. An error
6550 is signaled in this case."
6551 (interactive)
6552 (goto-char (point-min))
6553 ;; First check if there are no even levels
6554 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6555 (org-show-context t)
6556 (error "Not all levels are odd in this file. Conversion not possible."))
6557 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6558 (let ((org-odd-levels-only nil) n)
6559 (save-excursion
6560 (goto-char (point-min))
6561 (while (re-search-forward "^\\*\\*+ " nil t)
6562 (setq n (/ (1- (length (match-string 0))) 2))
6563 (while (>= (setq n (1- n)) 0)
6564 (org-promote))
6565 (end-of-line 1))))))
6567 (defun org-tr-level (n)
6568 "Make N odd if required."
6569 (if org-odd-levels-only (1+ (/ n 2)) n))
6571 ;;; Vertical tree motion, cutting and pasting of subtrees
6573 (defun org-move-subtree-up (&optional arg)
6574 "Move the current subtree up past ARG headlines of the same level."
6575 (interactive "p")
6576 (org-move-subtree-down (- (prefix-numeric-value arg))))
6578 (defun org-move-subtree-down (&optional arg)
6579 "Move the current subtree down past ARG headlines of the same level."
6580 (interactive "p")
6581 (setq arg (prefix-numeric-value arg))
6582 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6583 'outline-get-last-sibling))
6584 (ins-point (make-marker))
6585 (cnt (abs arg))
6586 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6587 ;; Select the tree
6588 (org-back-to-heading)
6589 (setq beg0 (point))
6590 (save-excursion
6591 (setq ne-beg (org-back-over-empty-lines))
6592 (setq beg (point)))
6593 (save-match-data
6594 (save-excursion (outline-end-of-heading)
6595 (setq folded (org-invisible-p)))
6596 (outline-end-of-subtree))
6597 (outline-next-heading)
6598 (setq ne-end (org-back-over-empty-lines))
6599 (setq end (point))
6600 (goto-char beg0)
6601 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6602 ;; include less whitespace
6603 (save-excursion
6604 (goto-char beg)
6605 (forward-line (- ne-beg ne-end))
6606 (setq beg (point))))
6607 ;; Find insertion point, with error handling
6608 (while (> cnt 0)
6609 (or (and (funcall movfunc) (looking-at outline-regexp))
6610 (progn (goto-char beg0)
6611 (error "Cannot move past superior level or buffer limit")))
6612 (setq cnt (1- cnt)))
6613 (if (> arg 0)
6614 ;; Moving forward - still need to move over subtree
6615 (progn (org-end-of-subtree t t)
6616 (save-excursion
6617 (org-back-over-empty-lines)
6618 (or (bolp) (newline)))))
6619 (setq ne-ins (org-back-over-empty-lines))
6620 (move-marker ins-point (point))
6621 (setq txt (buffer-substring beg end))
6622 (delete-region beg end)
6623 (outline-flag-region (1- beg) beg nil)
6624 (outline-flag-region (1- (point)) (point) nil)
6625 (insert txt)
6626 (or (bolp) (insert "\n"))
6627 (setq ins-end (point))
6628 (goto-char ins-point)
6629 (org-skip-whitespace)
6630 (when (and (< arg 0)
6631 (org-first-sibling-p)
6632 (> ne-ins ne-beg))
6633 ;; Move whitespace back to beginning
6634 (save-excursion
6635 (goto-char ins-end)
6636 (let ((kill-whole-line t))
6637 (kill-line (- ne-ins ne-beg)) (point)))
6638 (insert (make-string (- ne-ins ne-beg) ?\n)))
6639 (move-marker ins-point nil)
6640 (org-compact-display-after-subtree-move)
6641 (unless folded
6642 (org-show-entry)
6643 (show-children)
6644 (org-cycle-hide-drawers 'children))))
6646 (defvar org-subtree-clip ""
6647 "Clipboard for cut and paste of subtrees.
6648 This is actually only a copy of the kill, because we use the normal kill
6649 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6651 (defvar org-subtree-clip-folded nil
6652 "Was the last copied subtree folded?
6653 This is used to fold the tree back after pasting.")
6655 (defun org-cut-subtree (&optional n)
6656 "Cut the current subtree into the clipboard.
6657 With prefix arg N, cut this many sequential subtrees.
6658 This is a short-hand for marking the subtree and then cutting it."
6659 (interactive "p")
6660 (org-copy-subtree n 'cut))
6662 (defun org-copy-subtree (&optional n cut)
6663 "Cut the current subtree into the clipboard.
6664 With prefix arg N, cut this many sequential subtrees.
6665 This is a short-hand for marking the subtree and then copying it.
6666 If CUT is non-nil, actually cut the subtree."
6667 (interactive "p")
6668 (let (beg end folded (beg0 (point)))
6669 (if (interactive-p)
6670 (org-back-to-heading nil) ; take what looks like a subtree
6671 (org-back-to-heading t)) ; take what is really there
6672 (org-back-over-empty-lines)
6673 (setq beg (point))
6674 (skip-chars-forward " \t\r\n")
6675 (save-match-data
6676 (save-excursion (outline-end-of-heading)
6677 (setq folded (org-invisible-p)))
6678 (condition-case nil
6679 (outline-forward-same-level (1- n))
6680 (error nil))
6681 (org-end-of-subtree t t))
6682 (org-back-over-empty-lines)
6683 (setq end (point))
6684 (goto-char beg0)
6685 (when (> end beg)
6686 (setq org-subtree-clip-folded folded)
6687 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6688 (setq org-subtree-clip (current-kill 0))
6689 (message "%s: Subtree(s) with %d characters"
6690 (if cut "Cut" "Copied")
6691 (length org-subtree-clip)))))
6693 (defun org-paste-subtree (&optional level tree)
6694 "Paste the clipboard as a subtree, with modification of headline level.
6695 The entire subtree is promoted or demoted in order to match a new headline
6696 level. By default, the new level is derived from the visible headings
6697 before and after the insertion point, and taken to be the inferior headline
6698 level of the two. So if the previous visible heading is level 3 and the
6699 next is level 4 (or vice versa), level 4 will be used for insertion.
6700 This makes sure that the subtree remains an independent subtree and does
6701 not swallow low level entries.
6703 You can also force a different level, either by using a numeric prefix
6704 argument, or by inserting the heading marker by hand. For example, if the
6705 cursor is after \"*****\", then the tree will be shifted to level 5.
6707 If you want to insert the tree as is, just use \\[yank].
6709 If optional TREE is given, use this text instead of the kill ring."
6710 (interactive "P")
6711 (unless (org-kill-is-subtree-p tree)
6712 (error "%s"
6713 (substitute-command-keys
6714 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6715 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6716 (^re (concat "^\\(" outline-regexp "\\)"))
6717 (re (concat "\\(" outline-regexp "\\)"))
6718 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6720 (old-level (if (string-match ^re txt)
6721 (- (match-end 0) (match-beginning 0) 1)
6722 -1))
6723 (force-level (cond (level (prefix-numeric-value level))
6724 ((string-match
6725 ^re_ (buffer-substring (point-at-bol) (point)))
6726 (- (match-end 1) (match-beginning 1)))
6727 (t nil)))
6728 (previous-level (save-excursion
6729 (condition-case nil
6730 (progn
6731 (outline-previous-visible-heading 1)
6732 (if (looking-at re)
6733 (- (match-end 0) (match-beginning 0) 1)
6735 (error 1))))
6736 (next-level (save-excursion
6737 (condition-case nil
6738 (progn
6739 (or (looking-at outline-regexp)
6740 (outline-next-visible-heading 1))
6741 (if (looking-at re)
6742 (- (match-end 0) (match-beginning 0) 1)
6744 (error 1))))
6745 (new-level (or force-level (max previous-level next-level)))
6746 (shift (if (or (= old-level -1)
6747 (= new-level -1)
6748 (= old-level new-level))
6750 (- new-level old-level)))
6751 (delta (if (> shift 0) -1 1))
6752 (func (if (> shift 0) 'org-demote 'org-promote))
6753 (org-odd-levels-only nil)
6754 beg end)
6755 ;; Remove the forced level indicator
6756 (if force-level
6757 (delete-region (point-at-bol) (point)))
6758 ;; Paste
6759 (beginning-of-line 1)
6760 (org-back-over-empty-lines) ;; FIXME: correct fix????
6761 (setq beg (point))
6762 (insert-before-markers txt) ;; FIXME: correct fix????
6763 (unless (string-match "\n\\'" txt) (insert "\n"))
6764 (setq end (point))
6765 (goto-char beg)
6766 (skip-chars-forward " \t\n\r")
6767 (setq beg (point))
6768 ;; Shift if necessary
6769 (unless (= shift 0)
6770 (save-restriction
6771 (narrow-to-region beg end)
6772 (while (not (= shift 0))
6773 (org-map-region func (point-min) (point-max))
6774 (setq shift (+ delta shift)))
6775 (goto-char (point-min))))
6776 (when (interactive-p)
6777 (message "Clipboard pasted as level %d subtree" new-level))
6778 (if (and kill-ring
6779 (eq org-subtree-clip (current-kill 0))
6780 org-subtree-clip-folded)
6781 ;; The tree was folded before it was killed/copied
6782 (hide-subtree))))
6784 (defun org-kill-is-subtree-p (&optional txt)
6785 "Check if the current kill is an outline subtree, or a set of trees.
6786 Returns nil if kill does not start with a headline, or if the first
6787 headline level is not the largest headline level in the tree.
6788 So this will actually accept several entries of equal levels as well,
6789 which is OK for `org-paste-subtree'.
6790 If optional TXT is given, check this string instead of the current kill."
6791 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6792 (start-level (and kill
6793 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6794 org-outline-regexp "\\)")
6795 kill)
6796 (- (match-end 2) (match-beginning 2) 1)))
6797 (re (concat "^" org-outline-regexp))
6798 (start (1+ (match-beginning 2))))
6799 (if (not start-level)
6800 (progn
6801 nil) ;; does not even start with a heading
6802 (catch 'exit
6803 (while (setq start (string-match re kill (1+ start)))
6804 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6805 (throw 'exit nil)))
6806 t))))
6808 (defun org-narrow-to-subtree ()
6809 "Narrow buffer to the current subtree."
6810 (interactive)
6811 (save-excursion
6812 (save-match-data
6813 (narrow-to-region
6814 (progn (org-back-to-heading) (point))
6815 (progn (org-end-of-subtree t t) (point))))))
6818 ;;; Outline Sorting
6820 (defun org-sort (with-case)
6821 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6822 Optional argument WITH-CASE means sort case-sensitively."
6823 (interactive "P")
6824 (if (org-at-table-p)
6825 (org-call-with-arg 'org-table-sort-lines with-case)
6826 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6828 (defvar org-priority-regexp) ; defined later in the file
6830 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6831 "Sort entries on a certain level of an outline tree.
6832 If there is an active region, the entries in the region are sorted.
6833 Else, if the cursor is before the first entry, sort the top-level items.
6834 Else, the children of the entry at point are sorted.
6836 Sorting can be alphabetically, numerically, and by date/time as given by
6837 the first time stamp in the entry. The command prompts for the sorting
6838 type unless it has been given to the function through the SORTING-TYPE
6839 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6840 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6841 called with point at the beginning of the record. It must return either
6842 a string or a number that should serve as the sorting key for that record.
6844 Comparing entries ignores case by default. However, with an optional argument
6845 WITH-CASE, the sorting considers case as well."
6846 (interactive "P")
6847 (let ((case-func (if with-case 'identity 'downcase))
6848 start beg end stars re re2
6849 txt what tmp plain-list-p)
6850 ;; Find beginning and end of region to sort
6851 (cond
6852 ((org-region-active-p)
6853 ;; we will sort the region
6854 (setq end (region-end)
6855 what "region")
6856 (goto-char (region-beginning))
6857 (if (not (org-on-heading-p)) (outline-next-heading))
6858 (setq start (point)))
6859 ((org-at-item-p)
6860 ;; we will sort this plain list
6861 (org-beginning-of-item-list) (setq start (point))
6862 (org-end-of-item-list) (setq end (point))
6863 (goto-char start)
6864 (setq plain-list-p t
6865 what "plain list"))
6866 ((or (org-on-heading-p)
6867 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6868 ;; we will sort the children of the current headline
6869 (org-back-to-heading)
6870 (setq start (point)
6871 end (progn (org-end-of-subtree t t)
6872 (org-back-over-empty-lines)
6873 (point))
6874 what "children")
6875 (goto-char start)
6876 (show-subtree)
6877 (outline-next-heading))
6879 ;; we will sort the top-level entries in this file
6880 (goto-char (point-min))
6881 (or (org-on-heading-p) (outline-next-heading))
6882 (setq start (point) end (point-max) what "top-level")
6883 (goto-char start)
6884 (show-all)))
6886 (setq beg (point))
6887 (if (>= beg end) (error "Nothing to sort"))
6889 (unless plain-list-p
6890 (looking-at "\\(\\*+\\)")
6891 (setq stars (match-string 1)
6892 re (concat "^" (regexp-quote stars) " +")
6893 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6894 txt (buffer-substring beg end))
6895 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6896 (if (and (not (equal stars "*")) (string-match re2 txt))
6897 (error "Region to sort contains a level above the first entry")))
6899 (unless sorting-type
6900 (message
6901 (if plain-list-p
6902 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6903 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6904 what)
6905 (setq sorting-type (read-char-exclusive))
6907 (and (= (downcase sorting-type) ?f)
6908 (setq getkey-func
6909 (completing-read "Sort using function: "
6910 obarray 'fboundp t nil nil))
6911 (setq getkey-func (intern getkey-func)))
6913 (and (= (downcase sorting-type) ?r)
6914 (setq property
6915 (completing-read "Property: "
6916 (mapcar 'list (org-buffer-property-keys t))
6917 nil t))))
6919 (message "Sorting entries...")
6921 (save-restriction
6922 (narrow-to-region start end)
6924 (let ((dcst (downcase sorting-type))
6925 (now (current-time)))
6926 (sort-subr
6927 (/= dcst sorting-type)
6928 ;; This function moves to the beginning character of the "record" to
6929 ;; be sorted.
6930 (if plain-list-p
6931 (lambda nil
6932 (if (org-at-item-p) t (goto-char (point-max))))
6933 (lambda nil
6934 (if (re-search-forward re nil t)
6935 (goto-char (match-beginning 0))
6936 (goto-char (point-max)))))
6937 ;; This function moves to the last character of the "record" being
6938 ;; sorted.
6939 (if plain-list-p
6940 'org-end-of-item
6941 (lambda nil
6942 (save-match-data
6943 (condition-case nil
6944 (outline-forward-same-level 1)
6945 (error
6946 (goto-char (point-max)))))))
6948 ;; This function returns the value that gets sorted against.
6949 (if plain-list-p
6950 (lambda nil
6951 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6952 (cond
6953 ((= dcst ?n)
6954 (string-to-number (buffer-substring (match-end 0)
6955 (point-at-eol))))
6956 ((= dcst ?a)
6957 (buffer-substring (match-end 0) (point-at-eol)))
6958 ((= dcst ?t)
6959 (if (re-search-forward org-ts-regexp
6960 (point-at-eol) t)
6961 (org-time-string-to-time (match-string 0))
6962 now))
6963 ((= dcst ?f)
6964 (if getkey-func
6965 (progn
6966 (setq tmp (funcall getkey-func))
6967 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6968 tmp)
6969 (error "Invalid key function `%s'" getkey-func)))
6970 (t (error "Invalid sorting type `%c'" sorting-type)))))
6971 (lambda nil
6972 (cond
6973 ((= dcst ?n)
6974 (if (looking-at outline-regexp)
6975 (string-to-number (buffer-substring (match-end 0)
6976 (point-at-eol)))
6977 nil))
6978 ((= dcst ?a)
6979 (funcall case-func (buffer-substring (point-at-bol)
6980 (point-at-eol))))
6981 ((= dcst ?t)
6982 (if (re-search-forward org-ts-regexp
6983 (save-excursion
6984 (forward-line 2)
6985 (point)) t)
6986 (org-time-string-to-time (match-string 0))
6987 now))
6988 ((= dcst ?p)
6989 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6990 (string-to-char (match-string 2))
6991 org-default-priority))
6992 ((= dcst ?r)
6993 (or (org-entry-get nil property) ""))
6994 ((= dcst ?f)
6995 (if getkey-func
6996 (progn
6997 (setq tmp (funcall getkey-func))
6998 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6999 tmp)
7000 (error "Invalid key function `%s'" getkey-func)))
7001 (t (error "Invalid sorting type `%c'" sorting-type)))))
7003 (cond
7004 ((= dcst ?a) 'string<)
7005 ((= dcst ?t) 'time-less-p)
7006 (t nil)))))
7007 (message "Sorting entries...done")))
7009 (defun org-do-sort (table what &optional with-case sorting-type)
7010 "Sort TABLE of WHAT according to SORTING-TYPE.
7011 The user will be prompted for the SORTING-TYPE if the call to this
7012 function does not specify it. WHAT is only for the prompt, to indicate
7013 what is being sorted. The sorting key will be extracted from
7014 the car of the elements of the table.
7015 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7016 (unless sorting-type
7017 (message
7018 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7019 what)
7020 (setq sorting-type (read-char-exclusive)))
7021 (let ((dcst (downcase sorting-type))
7022 extractfun comparefun)
7023 ;; Define the appropriate functions
7024 (cond
7025 ((= dcst ?n)
7026 (setq extractfun 'string-to-number
7027 comparefun (if (= dcst sorting-type) '< '>)))
7028 ((= dcst ?a)
7029 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7030 (lambda(x) (downcase (org-sort-remove-invisible x))))
7031 comparefun (if (= dcst sorting-type)
7032 'string<
7033 (lambda (a b) (and (not (string< a b))
7034 (not (string= a b)))))))
7035 ((= dcst ?t)
7036 (setq extractfun
7037 (lambda (x)
7038 (if (string-match org-ts-regexp x)
7039 (time-to-seconds
7040 (org-time-string-to-time (match-string 0 x)))
7042 comparefun (if (= dcst sorting-type) '< '>)))
7043 (t (error "Invalid sorting type `%c'" sorting-type)))
7045 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7046 table)
7047 (lambda (a b) (funcall comparefun (car a) (car b))))))
7049 ;;;; Plain list items, including checkboxes
7051 ;;; Plain list items
7053 (defun org-at-item-p ()
7054 "Is point in a line starting a hand-formatted item?"
7055 (let ((llt org-plain-list-ordered-item-terminator))
7056 (save-excursion
7057 (goto-char (point-at-bol))
7058 (looking-at
7059 (cond
7060 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7061 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7062 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7063 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7065 (defun org-in-item-p ()
7066 "It the cursor inside a plain list item.
7067 Does not have to be the first line."
7068 (save-excursion
7069 (condition-case nil
7070 (progn
7071 (org-beginning-of-item)
7072 (org-at-item-p)
7074 (error nil))))
7076 (defun org-insert-item (&optional checkbox)
7077 "Insert a new item at the current level.
7078 Return t when things worked, nil when we are not in an item."
7079 (when (save-excursion
7080 (condition-case nil
7081 (progn
7082 (org-beginning-of-item)
7083 (org-at-item-p)
7084 (if (org-invisible-p) (error "Invisible item"))
7086 (error nil)))
7087 (let* ((bul (match-string 0))
7088 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7089 (match-end 0)))
7090 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7091 pos)
7092 (cond
7093 ((and (org-at-item-p) (<= (point) eow))
7094 ;; before the bullet
7095 (beginning-of-line 1)
7096 (open-line (if blank 2 1)))
7097 ((<= (point) eow)
7098 (beginning-of-line 1))
7100 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7101 (end-of-line 1)
7102 (delete-horizontal-space))
7103 (newline (if blank 2 1))))
7104 (insert bul (if checkbox "[ ]" ""))
7105 (just-one-space)
7106 (setq pos (point))
7107 (end-of-line 1)
7108 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7109 (org-maybe-renumber-ordered-list)
7110 (and checkbox (org-update-checkbox-count-maybe))
7113 ;;; Checkboxes
7115 (defun org-at-item-checkbox-p ()
7116 "Is point at a line starting a plain-list item with a checklet?"
7117 (and (org-at-item-p)
7118 (save-excursion
7119 (goto-char (match-end 0))
7120 (skip-chars-forward " \t")
7121 (looking-at "\\[[- X]\\]"))))
7123 (defun org-toggle-checkbox (&optional arg)
7124 "Toggle the checkbox in the current line."
7125 (interactive "P")
7126 (catch 'exit
7127 (let (beg end status (firstnew 'unknown))
7128 (cond
7129 ((org-region-active-p)
7130 (setq beg (region-beginning) end (region-end)))
7131 ((org-on-heading-p)
7132 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7133 ((org-at-item-checkbox-p)
7134 (let ((pos (point)))
7135 (replace-match
7136 (cond (arg "[-]")
7137 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7138 (t "[ ]"))
7139 t t)
7140 (goto-char pos))
7141 (throw 'exit t))
7142 (t (error "Not at a checkbox or heading, and no active region")))
7143 (save-excursion
7144 (goto-char beg)
7145 (while (< (point) end)
7146 (when (org-at-item-checkbox-p)
7147 (setq status (equal (match-string 0) "[X]"))
7148 (when (eq firstnew 'unknown)
7149 (setq firstnew (not status)))
7150 (replace-match
7151 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7152 (beginning-of-line 2)))))
7153 (org-update-checkbox-count-maybe))
7155 (defun org-update-checkbox-count-maybe ()
7156 "Update checkbox statistics unless turned off by user."
7157 (when org-provide-checkbox-statistics
7158 (org-update-checkbox-count)))
7160 (defun org-update-checkbox-count (&optional all)
7161 "Update the checkbox statistics in the current section.
7162 This will find all statistic cookies like [57%] and [6/12] and update them
7163 with the current numbers. With optional prefix argument ALL, do this for
7164 the whole buffer."
7165 (interactive "P")
7166 (save-excursion
7167 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7168 (beg (condition-case nil
7169 (progn (outline-back-to-heading) (point))
7170 (error (point-min))))
7171 (end (move-marker (make-marker)
7172 (progn (outline-next-heading) (point))))
7173 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7174 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7175 (re-find (concat re "\\|" re-box))
7176 beg-cookie end-cookie is-percent c-on c-off lim
7177 eline curr-ind next-ind continue-from startsearch
7178 (cstat 0)
7180 (when all
7181 (goto-char (point-min))
7182 (outline-next-heading)
7183 (setq beg (point) end (point-max)))
7184 (goto-char end)
7185 ;; find each statistic cookie
7186 (while (re-search-backward re-find beg t)
7187 (setq beg-cookie (match-beginning 1)
7188 end-cookie (match-end 1)
7189 cstat (+ cstat (if end-cookie 1 0))
7190 startsearch (point-at-eol)
7191 continue-from (point-at-bol)
7192 is-percent (match-beginning 2)
7193 lim (cond
7194 ((org-on-heading-p) (outline-next-heading) (point))
7195 ((org-at-item-p) (org-end-of-item) (point))
7196 (t nil))
7197 c-on 0
7198 c-off 0)
7199 (when lim
7200 ;; find first checkbox for this cookie and gather
7201 ;; statistics from all that are at this indentation level
7202 (goto-char startsearch)
7203 (if (re-search-forward re-box lim t)
7204 (progn
7205 (org-beginning-of-item)
7206 (setq curr-ind (org-get-indentation))
7207 (setq next-ind curr-ind)
7208 (while (= curr-ind next-ind)
7209 (save-excursion (end-of-line) (setq eline (point)))
7210 (if (re-search-forward re-box eline t)
7211 (if (member (match-string 2) '("[ ]" "[-]"))
7212 (setq c-off (1+ c-off))
7213 (setq c-on (1+ c-on))
7216 (org-end-of-item)
7217 (setq next-ind (org-get-indentation))
7219 (goto-char continue-from)
7220 ;; update cookie
7221 (when end-cookie
7222 (delete-region beg-cookie end-cookie)
7223 (goto-char beg-cookie)
7224 (insert
7225 (if is-percent
7226 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7227 (format "[%d/%d]" c-on (+ c-on c-off)))))
7228 ;; update items checkbox if it has one
7229 (when (org-at-item-p)
7230 (org-beginning-of-item)
7231 (when (and (> (+ c-on c-off) 0)
7232 (re-search-forward re-box (point-at-eol) t))
7233 (setq beg-cookie (match-beginning 2)
7234 end-cookie (match-end 2))
7235 (delete-region beg-cookie end-cookie)
7236 (goto-char beg-cookie)
7237 (cond ((= c-off 0) (insert "[X]"))
7238 ((= c-on 0) (insert "[ ]"))
7239 (t (insert "[-]")))
7241 (goto-char continue-from))
7242 (when (interactive-p)
7243 (message "Checkbox satistics updated %s (%d places)"
7244 (if all "in entire file" "in current outline entry") cstat)))))
7246 (defun org-get-checkbox-statistics-face ()
7247 "Select the face for checkbox statistics.
7248 The face will be `org-done' when all relevant boxes are checked. Otherwise
7249 it will be `org-todo'."
7250 (if (match-end 1)
7251 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7252 (if (and (> (match-end 2) (match-beginning 2))
7253 (equal (match-string 2) (match-string 3)))
7254 'org-done
7255 'org-todo)))
7257 (defun org-get-indentation (&optional line)
7258 "Get the indentation of the current line, interpreting tabs.
7259 When LINE is given, assume it represents a line and compute its indentation."
7260 (if line
7261 (if (string-match "^ *" (org-remove-tabs line))
7262 (match-end 0))
7263 (save-excursion
7264 (beginning-of-line 1)
7265 (skip-chars-forward " \t")
7266 (current-column))))
7268 (defun org-remove-tabs (s &optional width)
7269 "Replace tabulators in S with spaces.
7270 Assumes that s is a single line, starting in column 0."
7271 (setq width (or width tab-width))
7272 (while (string-match "\t" s)
7273 (setq s (replace-match
7274 (make-string
7275 (- (* width (/ (+ (match-beginning 0) width) width))
7276 (match-beginning 0)) ?\ )
7277 t t s)))
7280 (defun org-fix-indentation (line ind)
7281 "Fix indentation in LINE.
7282 IND is a cons cell with target and minimum indentation.
7283 If the current indenation in LINE is smaller than the minimum,
7284 leave it alone. If it is larger than ind, set it to the target."
7285 (let* ((l (org-remove-tabs line))
7286 (i (org-get-indentation l))
7287 (i1 (car ind)) (i2 (cdr ind)))
7288 (if (>= i i2) (setq l (substring line i2)))
7289 (if (> i1 0)
7290 (concat (make-string i1 ?\ ) l)
7291 l)))
7293 (defcustom org-empty-line-terminates-plain-lists nil
7294 "Non-nil means, an empty line ends all plain list levels.
7295 When nil, empty lines are part of the preceeding item."
7296 :group 'org-plain-lists
7297 :type 'boolean)
7299 (defun org-beginning-of-item ()
7300 "Go to the beginning of the current hand-formatted item.
7301 If the cursor is not in an item, throw an error."
7302 (interactive)
7303 (let ((pos (point))
7304 (limit (save-excursion
7305 (condition-case nil
7306 (progn
7307 (org-back-to-heading)
7308 (beginning-of-line 2) (point))
7309 (error (point-min)))))
7310 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7311 ind ind1)
7312 (if (org-at-item-p)
7313 (beginning-of-line 1)
7314 (beginning-of-line 1)
7315 (skip-chars-forward " \t")
7316 (setq ind (current-column))
7317 (if (catch 'exit
7318 (while t
7319 (beginning-of-line 0)
7320 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7322 (if (looking-at "[ \t]*$")
7323 (setq ind1 ind-empty)
7324 (skip-chars-forward " \t")
7325 (setq ind1 (current-column)))
7326 (if (< ind1 ind)
7327 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7329 (goto-char pos)
7330 (error "Not in an item")))))
7332 (defun org-end-of-item ()
7333 "Go to the end of the current hand-formatted item.
7334 If the cursor is not in an item, throw an error."
7335 (interactive)
7336 (let* ((pos (point))
7337 ind1
7338 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7339 (limit (save-excursion (outline-next-heading) (point)))
7340 (ind (save-excursion
7341 (org-beginning-of-item)
7342 (skip-chars-forward " \t")
7343 (current-column)))
7344 (end (catch 'exit
7345 (while t
7346 (beginning-of-line 2)
7347 (if (eobp) (throw 'exit (point)))
7348 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7349 (if (looking-at "[ \t]*$")
7350 (setq ind1 ind-empty)
7351 (skip-chars-forward " \t")
7352 (setq ind1 (current-column)))
7353 (if (<= ind1 ind)
7354 (throw 'exit (point-at-bol)))))))
7355 (if end
7356 (goto-char end)
7357 (goto-char pos)
7358 (error "Not in an item"))))
7360 (defun org-next-item ()
7361 "Move to the beginning of the next item in the current plain list.
7362 Error if not at a plain list, or if this is the last item in the list."
7363 (interactive)
7364 (let (ind ind1 (pos (point)))
7365 (org-beginning-of-item)
7366 (setq ind (org-get-indentation))
7367 (org-end-of-item)
7368 (setq ind1 (org-get-indentation))
7369 (unless (and (org-at-item-p) (= ind ind1))
7370 (goto-char pos)
7371 (error "On last item"))))
7373 (defun org-previous-item ()
7374 "Move to the beginning of the previous item in the current plain list.
7375 Error if not at a plain list, or if this is the first item in the list."
7376 (interactive)
7377 (let (beg ind ind1 (pos (point)))
7378 (org-beginning-of-item)
7379 (setq beg (point))
7380 (setq ind (org-get-indentation))
7381 (goto-char beg)
7382 (catch 'exit
7383 (while t
7384 (beginning-of-line 0)
7385 (if (looking-at "[ \t]*$")
7387 (if (<= (setq ind1 (org-get-indentation)) ind)
7388 (throw 'exit t)))))
7389 (condition-case nil
7390 (if (or (not (org-at-item-p))
7391 (< ind1 (1- ind)))
7392 (error "")
7393 (org-beginning-of-item))
7394 (error (goto-char pos)
7395 (error "On first item")))))
7397 (defun org-first-list-item-p ()
7398 "Is this heading the item in a plain list?"
7399 (unless (org-at-item-p)
7400 (error "Not at a plain list item"))
7401 (org-beginning-of-item)
7402 (= (point) (save-excursion (org-beginning-of-item-list))))
7404 (defun org-move-item-down ()
7405 "Move the plain list item at point down, i.e. swap with following item.
7406 Subitems (items with larger indentation) are considered part of the item,
7407 so this really moves item trees."
7408 (interactive)
7409 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7410 (org-beginning-of-item)
7411 (setq beg0 (point))
7412 (save-excursion
7413 (setq ne-beg (org-back-over-empty-lines))
7414 (setq beg (point)))
7415 (goto-char beg0)
7416 (setq ind (org-get-indentation))
7417 (org-end-of-item)
7418 (setq end0 (point))
7419 (setq ind1 (org-get-indentation))
7420 (setq ne-end (org-back-over-empty-lines))
7421 (setq end (point))
7422 (goto-char beg0)
7423 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7424 ;; include less whitespace
7425 (save-excursion
7426 (goto-char beg)
7427 (forward-line (- ne-beg ne-end))
7428 (setq beg (point))))
7429 (goto-char end0)
7430 (if (and (org-at-item-p) (= ind ind1))
7431 (progn
7432 (org-end-of-item)
7433 (org-back-over-empty-lines)
7434 (setq txt (buffer-substring beg end))
7435 (save-excursion
7436 (delete-region beg end))
7437 (setq pos (point))
7438 (insert txt)
7439 (goto-char pos) (org-skip-whitespace)
7440 (org-maybe-renumber-ordered-list))
7441 (goto-char pos)
7442 (error "Cannot move this item further down"))))
7444 (defun org-move-item-up (arg)
7445 "Move the plain list item at point up, i.e. swap with previous item.
7446 Subitems (items with larger indentation) are considered part of the item,
7447 so this really moves item trees."
7448 (interactive "p")
7449 (let (beg beg0 end ind ind1 (pos (point)) txt
7450 ne-beg ne-ins ins-end)
7451 (org-beginning-of-item)
7452 (setq beg0 (point))
7453 (setq ind (org-get-indentation))
7454 (save-excursion
7455 (setq ne-beg (org-back-over-empty-lines))
7456 (setq beg (point)))
7457 (goto-char beg0)
7458 (org-end-of-item)
7459 (setq end (point))
7460 (goto-char beg0)
7461 (catch 'exit
7462 (while t
7463 (beginning-of-line 0)
7464 (if (looking-at "[ \t]*$")
7465 (if org-empty-line-terminates-plain-lists
7466 (progn
7467 (goto-char pos)
7468 (error "Cannot move this item further up"))
7469 nil)
7470 (if (<= (setq ind1 (org-get-indentation)) ind)
7471 (throw 'exit t)))))
7472 (condition-case nil
7473 (org-beginning-of-item)
7474 (error (goto-char beg)
7475 (error "Cannot move this item further up")))
7476 (setq ind1 (org-get-indentation))
7477 (if (and (org-at-item-p) (= ind ind1))
7478 (progn
7479 (setq ne-ins (org-back-over-empty-lines))
7480 (setq txt (buffer-substring beg end))
7481 (save-excursion
7482 (delete-region beg end))
7483 (setq pos (point))
7484 (insert txt)
7485 (setq ins-end (point))
7486 (goto-char pos) (org-skip-whitespace)
7488 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7489 ;; Move whitespace back to beginning
7490 (save-excursion
7491 (goto-char ins-end)
7492 (let ((kill-whole-line t))
7493 (kill-line (- ne-ins ne-beg)) (point)))
7494 (insert (make-string (- ne-ins ne-beg) ?\n)))
7496 (org-maybe-renumber-ordered-list))
7497 (goto-char pos)
7498 (error "Cannot move this item further up"))))
7500 (defun org-maybe-renumber-ordered-list ()
7501 "Renumber the ordered list at point if setup allows it.
7502 This tests the user option `org-auto-renumber-ordered-lists' before
7503 doing the renumbering."
7504 (interactive)
7505 (when (and org-auto-renumber-ordered-lists
7506 (org-at-item-p))
7507 (if (match-beginning 3)
7508 (org-renumber-ordered-list 1)
7509 (org-fix-bullet-type))))
7511 (defun org-maybe-renumber-ordered-list-safe ()
7512 (condition-case nil
7513 (save-excursion
7514 (org-maybe-renumber-ordered-list))
7515 (error nil)))
7517 (defun org-cycle-list-bullet (&optional which)
7518 "Cycle through the different itemize/enumerate bullets.
7519 This cycle the entire list level through the sequence:
7521 `-' -> `+' -> `*' -> `1.' -> `1)'
7523 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7524 0 meand `-', 1 means `+' etc."
7525 (interactive "P")
7526 (org-preserve-lc
7527 (org-beginning-of-item-list)
7528 (org-at-item-p)
7529 (beginning-of-line 1)
7530 (let ((current (match-string 0))
7531 (prevp (eq which 'previous))
7532 new)
7533 (setq new (cond
7534 ((and (numberp which)
7535 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7536 ((string-match "-" current) (if prevp "1)" "+"))
7537 ((string-match "\\+" current)
7538 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7539 ((string-match "\\*" current) (if prevp "+" "1."))
7540 ((string-match "\\." current) (if prevp "*" "1)"))
7541 ((string-match ")" current) (if prevp "1." "-"))
7542 (t (error "This should not happen"))))
7543 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7544 (org-fix-bullet-type)
7545 (org-maybe-renumber-ordered-list))))
7547 (defun org-get-string-indentation (s)
7548 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7549 (let ((n -1) (i 0) (w tab-width) c)
7550 (catch 'exit
7551 (while (< (setq n (1+ n)) (length s))
7552 (setq c (aref s n))
7553 (cond ((= c ?\ ) (setq i (1+ i)))
7554 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7555 (t (throw 'exit t)))))
7558 (defun org-renumber-ordered-list (arg)
7559 "Renumber an ordered plain list.
7560 Cursor needs to be in the first line of an item, the line that starts
7561 with something like \"1.\" or \"2)\"."
7562 (interactive "p")
7563 (unless (and (org-at-item-p)
7564 (match-beginning 3))
7565 (error "This is not an ordered list"))
7566 (let ((line (org-current-line))
7567 (col (current-column))
7568 (ind (org-get-string-indentation
7569 (buffer-substring (point-at-bol) (match-beginning 3))))
7570 ;; (term (substring (match-string 3) -1))
7571 ind1 (n (1- arg))
7572 fmt)
7573 ;; find where this list begins
7574 (org-beginning-of-item-list)
7575 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7576 (setq fmt (concat "%d" (match-string 1)))
7577 (beginning-of-line 0)
7578 ;; walk forward and replace these numbers
7579 (catch 'exit
7580 (while t
7581 (catch 'next
7582 (beginning-of-line 2)
7583 (if (eobp) (throw 'exit nil))
7584 (if (looking-at "[ \t]*$") (throw 'next nil))
7585 (skip-chars-forward " \t") (setq ind1 (current-column))
7586 (if (> ind1 ind) (throw 'next t))
7587 (if (< ind1 ind) (throw 'exit t))
7588 (if (not (org-at-item-p)) (throw 'exit nil))
7589 (delete-region (match-beginning 2) (match-end 2))
7590 (goto-char (match-beginning 2))
7591 (insert (format fmt (setq n (1+ n)))))))
7592 (goto-line line)
7593 (move-to-column col)))
7595 (defun org-fix-bullet-type ()
7596 "Make sure all items in this list have the same bullet as the firsst item."
7597 (interactive)
7598 (unless (org-at-item-p) (error "This is not a list"))
7599 (let ((line (org-current-line))
7600 (col (current-column))
7601 (ind (current-indentation))
7602 ind1 bullet)
7603 ;; find where this list begins
7604 (org-beginning-of-item-list)
7605 (beginning-of-line 1)
7606 ;; find out what the bullet type is
7607 (looking-at "[ \t]*\\(\\S-+\\)")
7608 (setq bullet (match-string 1))
7609 ;; walk forward and replace these numbers
7610 (beginning-of-line 0)
7611 (catch 'exit
7612 (while t
7613 (catch 'next
7614 (beginning-of-line 2)
7615 (if (eobp) (throw 'exit nil))
7616 (if (looking-at "[ \t]*$") (throw 'next nil))
7617 (skip-chars-forward " \t") (setq ind1 (current-column))
7618 (if (> ind1 ind) (throw 'next t))
7619 (if (< ind1 ind) (throw 'exit t))
7620 (if (not (org-at-item-p)) (throw 'exit nil))
7621 (skip-chars-forward " \t")
7622 (looking-at "\\S-+")
7623 (replace-match bullet))))
7624 (goto-line line)
7625 (move-to-column col)
7626 (if (string-match "[0-9]" bullet)
7627 (org-renumber-ordered-list 1))))
7629 (defun org-beginning-of-item-list ()
7630 "Go to the beginning of the current item list.
7631 I.e. to the first item in this list."
7632 (interactive)
7633 (org-beginning-of-item)
7634 (let ((pos (point-at-bol))
7635 (ind (org-get-indentation))
7636 ind1)
7637 ;; find where this list begins
7638 (catch 'exit
7639 (while t
7640 (catch 'next
7641 (beginning-of-line 0)
7642 (if (looking-at "[ \t]*$")
7643 (throw (if (bobp) 'exit 'next) t))
7644 (skip-chars-forward " \t") (setq ind1 (current-column))
7645 (if (or (< ind1 ind)
7646 (and (= ind1 ind)
7647 (not (org-at-item-p)))
7648 (bobp))
7649 (throw 'exit t)
7650 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7651 (goto-char pos)))
7654 (defun org-end-of-item-list ()
7655 "Go to the end of the current item list.
7656 I.e. to the text after the last item."
7657 (interactive)
7658 (org-beginning-of-item)
7659 (let ((pos (point-at-bol))
7660 (ind (org-get-indentation))
7661 ind1)
7662 ;; find where this list begins
7663 (catch 'exit
7664 (while t
7665 (catch 'next
7666 (beginning-of-line 2)
7667 (if (looking-at "[ \t]*$")
7668 (throw (if (eobp) 'exit 'next) t))
7669 (skip-chars-forward " \t") (setq ind1 (current-column))
7670 (if (or (< ind1 ind)
7671 (and (= ind1 ind)
7672 (not (org-at-item-p)))
7673 (eobp))
7674 (progn
7675 (setq pos (point-at-bol))
7676 (throw 'exit t))))))
7677 (goto-char pos)))
7680 (defvar org-last-indent-begin-marker (make-marker))
7681 (defvar org-last-indent-end-marker (make-marker))
7683 (defun org-outdent-item (arg)
7684 "Outdent a local list item."
7685 (interactive "p")
7686 (org-indent-item (- arg)))
7688 (defun org-indent-item (arg)
7689 "Indent a local list item."
7690 (interactive "p")
7691 (unless (org-at-item-p)
7692 (error "Not on an item"))
7693 (save-excursion
7694 (let (beg end ind ind1 tmp delta ind-down ind-up)
7695 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7696 (setq beg org-last-indent-begin-marker
7697 end org-last-indent-end-marker)
7698 (org-beginning-of-item)
7699 (setq beg (move-marker org-last-indent-begin-marker (point)))
7700 (org-end-of-item)
7701 (setq end (move-marker org-last-indent-end-marker (point))))
7702 (goto-char beg)
7703 (setq tmp (org-item-indent-positions)
7704 ind (car tmp)
7705 ind-down (nth 2 tmp)
7706 ind-up (nth 1 tmp)
7707 delta (if (> arg 0)
7708 (if ind-down (- ind-down ind) 2)
7709 (if ind-up (- ind-up ind) -2)))
7710 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7711 (while (< (point) end)
7712 (beginning-of-line 1)
7713 (skip-chars-forward " \t") (setq ind1 (current-column))
7714 (delete-region (point-at-bol) (point))
7715 (or (eolp) (indent-to-column (+ ind1 delta)))
7716 (beginning-of-line 2))))
7717 (org-fix-bullet-type)
7718 (org-maybe-renumber-ordered-list-safe)
7719 (save-excursion
7720 (beginning-of-line 0)
7721 (condition-case nil (org-beginning-of-item) (error nil))
7722 (org-maybe-renumber-ordered-list-safe)))
7724 (defun org-item-indent-positions ()
7725 "Return indentation for plain list items.
7726 This returns a list with three values: The current indentation, the
7727 parent indentation and the indentation a child should habe.
7728 Assumes cursor in item line."
7729 (let* ((bolpos (point-at-bol))
7730 (ind (org-get-indentation))
7731 ind-down ind-up pos)
7732 (save-excursion
7733 (org-beginning-of-item-list)
7734 (skip-chars-backward "\n\r \t")
7735 (when (org-in-item-p)
7736 (org-beginning-of-item)
7737 (setq ind-up (org-get-indentation))))
7738 (setq pos (point))
7739 (save-excursion
7740 (cond
7741 ((and (condition-case nil (progn (org-previous-item) t)
7742 (error nil))
7743 (or (forward-char 1) t)
7744 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7745 (setq ind-down (org-get-indentation)))
7746 ((and (goto-char pos)
7747 (org-at-item-p))
7748 (goto-char (match-end 0))
7749 (skip-chars-forward " \t")
7750 (setq ind-down (current-column)))))
7751 (list ind ind-up ind-down)))
7753 ;;; The orgstruct minor mode
7755 ;; Define a minor mode which can be used in other modes in order to
7756 ;; integrate the org-mode structure editing commands.
7758 ;; This is really a hack, because the org-mode structure commands use
7759 ;; keys which normally belong to the major mode. Here is how it
7760 ;; works: The minor mode defines all the keys necessary to operate the
7761 ;; structure commands, but wraps the commands into a function which
7762 ;; tests if the cursor is currently at a headline or a plain list
7763 ;; item. If that is the case, the structure command is used,
7764 ;; temporarily setting many Org-mode variables like regular
7765 ;; expressions for filling etc. However, when any of those keys is
7766 ;; used at a different location, function uses `key-binding' to look
7767 ;; up if the key has an associated command in another currently active
7768 ;; keymap (minor modes, major mode, global), and executes that
7769 ;; command. There might be problems if any of the keys is otherwise
7770 ;; used as a prefix key.
7772 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7773 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7774 ;; addresses this by checking explicitly for both bindings.
7776 (defvar orgstruct-mode-map (make-sparse-keymap)
7777 "Keymap for the minor `orgstruct-mode'.")
7779 (defvar org-local-vars nil
7780 "List of local variables, for use by `orgstruct-mode'")
7782 ;;;###autoload
7783 (define-minor-mode orgstruct-mode
7784 "Toggle the minor more `orgstruct-mode'.
7785 This mode is for using Org-mode structure commands in other modes.
7786 The following key behave as if Org-mode was active, if the cursor
7787 is on a headline, or on a plain list item (both in the definition
7788 of Org-mode).
7790 M-up Move entry/item up
7791 M-down Move entry/item down
7792 M-left Promote
7793 M-right Demote
7794 M-S-up Move entry/item up
7795 M-S-down Move entry/item down
7796 M-S-left Promote subtree
7797 M-S-right Demote subtree
7798 M-q Fill paragraph and items like in Org-mode
7799 C-c ^ Sort entries
7800 C-c - Cycle list bullet
7801 TAB Cycle item visibility
7802 M-RET Insert new heading/item
7803 S-M-RET Insert new TODO heading / Chekbox item
7804 C-c C-c Set tags / toggle checkbox"
7805 nil " OrgStruct" nil
7806 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7808 ;;;###autoload
7809 (defun turn-on-orgstruct ()
7810 "Unconditionally turn on `orgstruct-mode'."
7811 (orgstruct-mode 1))
7813 ;;;###autoload
7814 (defun turn-on-orgstruct++ ()
7815 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7816 In addition to setting orgstruct-mode, this also exports all indentation and
7817 autofilling variables from org-mode into the buffer. Note that turning
7818 off orgstruct-mode will *not* remove these additional settings."
7819 (orgstruct-mode 1)
7820 (let (var val)
7821 (mapc
7822 (lambda (x)
7823 (when (string-match
7824 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7825 (symbol-name (car x)))
7826 (setq var (car x) val (nth 1 x))
7827 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7828 org-local-vars)))
7830 (defun orgstruct-error ()
7831 "Error when there is no default binding for a structure key."
7832 (interactive)
7833 (error "This key has no function outside structure elements"))
7835 (defun orgstruct-setup ()
7836 "Setup orgstruct keymaps."
7837 (let ((nfunc 0)
7838 (bindings
7839 (list
7840 '([(meta up)] org-metaup)
7841 '([(meta down)] org-metadown)
7842 '([(meta left)] org-metaleft)
7843 '([(meta right)] org-metaright)
7844 '([(meta shift up)] org-shiftmetaup)
7845 '([(meta shift down)] org-shiftmetadown)
7846 '([(meta shift left)] org-shiftmetaleft)
7847 '([(meta shift right)] org-shiftmetaright)
7848 '([(shift up)] org-shiftup)
7849 '([(shift down)] org-shiftdown)
7850 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7851 '("\M-q" fill-paragraph)
7852 '("\C-c^" org-sort)
7853 '("\C-c-" org-cycle-list-bullet)))
7854 elt key fun cmd)
7855 (while (setq elt (pop bindings))
7856 (setq nfunc (1+ nfunc))
7857 (setq key (org-key (car elt))
7858 fun (nth 1 elt)
7859 cmd (orgstruct-make-binding fun nfunc key))
7860 (org-defkey orgstruct-mode-map key cmd))
7862 ;; Special treatment needed for TAB and RET
7863 (org-defkey orgstruct-mode-map [(tab)]
7864 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7865 (org-defkey orgstruct-mode-map "\C-i"
7866 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7868 (org-defkey orgstruct-mode-map "\M-\C-m"
7869 (orgstruct-make-binding 'org-insert-heading 105
7870 "\M-\C-m" [(meta return)]))
7871 (org-defkey orgstruct-mode-map [(meta return)]
7872 (orgstruct-make-binding 'org-insert-heading 106
7873 [(meta return)] "\M-\C-m"))
7875 (org-defkey orgstruct-mode-map [(shift meta return)]
7876 (orgstruct-make-binding 'org-insert-todo-heading 107
7877 [(meta return)] "\M-\C-m"))
7879 (unless org-local-vars
7880 (setq org-local-vars (org-get-local-variables)))
7884 (defun orgstruct-make-binding (fun n &rest keys)
7885 "Create a function for binding in the structure minor mode.
7886 FUN is the command to call inside a table. N is used to create a unique
7887 command name. KEYS are keys that should be checked in for a command
7888 to execute outside of tables."
7889 (eval
7890 (list 'defun
7891 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7892 '(arg)
7893 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7894 "Outside of structure, run the binding of `"
7895 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7896 "'.")
7897 '(interactive "p")
7898 (list 'if
7899 '(org-context-p 'headline 'item)
7900 (list 'org-run-like-in-org-mode (list 'quote fun))
7901 (list 'let '(orgstruct-mode)
7902 (list 'call-interactively
7903 (append '(or)
7904 (mapcar (lambda (k)
7905 (list 'key-binding k))
7906 keys)
7907 '('orgstruct-error))))))))
7909 (defun org-context-p (&rest contexts)
7910 "Check if local context is and of CONTEXTS.
7911 Possible values in the list of contexts are `table', `headline', and `item'."
7912 (let ((pos (point)))
7913 (goto-char (point-at-bol))
7914 (prog1 (or (and (memq 'table contexts)
7915 (looking-at "[ \t]*|"))
7916 (and (memq 'headline contexts)
7917 (looking-at "\\*+"))
7918 (and (memq 'item contexts)
7919 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7920 (goto-char pos))))
7922 (defun org-get-local-variables ()
7923 "Return a list of all local variables in an org-mode buffer."
7924 (let (varlist)
7925 (with-current-buffer (get-buffer-create "*Org tmp*")
7926 (erase-buffer)
7927 (org-mode)
7928 (setq varlist (buffer-local-variables)))
7929 (kill-buffer "*Org tmp*")
7930 (delq nil
7931 (mapcar
7932 (lambda (x)
7933 (setq x
7934 (if (symbolp x)
7935 (list x)
7936 (list (car x) (list 'quote (cdr x)))))
7937 (if (string-match
7938 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7939 (symbol-name (car x)))
7940 x nil))
7941 varlist))))
7943 ;;;###autoload
7944 (defun org-run-like-in-org-mode (cmd)
7945 (unless org-local-vars
7946 (setq org-local-vars (org-get-local-variables)))
7947 (eval (list 'let org-local-vars
7948 (list 'call-interactively (list 'quote cmd)))))
7950 ;;;; Archiving
7952 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7954 (defun org-archive-subtree (&optional find-done)
7955 "Move the current subtree to the archive.
7956 The archive can be a certain top-level heading in the current file, or in
7957 a different file. The tree will be moved to that location, the subtree
7958 heading be marked DONE, and the current time will be added.
7960 When called with prefix argument FIND-DONE, find whole trees without any
7961 open TODO items and archive them (after getting confirmation from the user).
7962 If the cursor is not at a headline when this comand is called, try all level
7963 1 trees. If the cursor is on a headline, only try the direct children of
7964 this heading."
7965 (interactive "P")
7966 (if find-done
7967 (org-archive-all-done)
7968 ;; Save all relevant TODO keyword-relatex variables
7970 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7971 (tr-org-todo-keywords-1 org-todo-keywords-1)
7972 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7973 (tr-org-done-keywords org-done-keywords)
7974 (tr-org-todo-regexp org-todo-regexp)
7975 (tr-org-todo-line-regexp org-todo-line-regexp)
7976 (tr-org-odd-levels-only org-odd-levels-only)
7977 (this-buffer (current-buffer))
7978 (org-archive-location org-archive-location)
7979 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7980 ;; start of variables that will be used for saving context
7981 ;; The compiler complains about them - keep them anyway!
7982 (file (abbreviate-file-name (buffer-file-name)))
7983 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7984 (time (format-time-string
7985 (substring (cdr org-time-stamp-formats) 1 -1)
7986 (current-time)))
7987 afile heading buffer level newfile-p
7988 category todo priority
7989 ;; start of variables that will be used for savind context
7990 ltags itags prop)
7992 ;; Try to find a local archive location
7993 (save-excursion
7994 (save-restriction
7995 (widen)
7996 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7997 (if (and prop (string-match "\\S-" prop))
7998 (setq org-archive-location prop)
7999 (if (or (re-search-backward re nil t)
8000 (re-search-forward re nil t))
8001 (setq org-archive-location (match-string 1))))))
8003 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8004 (progn
8005 (setq afile (format (match-string 1 org-archive-location)
8006 (file-name-nondirectory buffer-file-name))
8007 heading (match-string 2 org-archive-location)))
8008 (error "Invalid `org-archive-location'"))
8009 (if (> (length afile) 0)
8010 (setq newfile-p (not (file-exists-p afile))
8011 buffer (find-file-noselect afile))
8012 (setq buffer (current-buffer)))
8013 (unless buffer
8014 (error "Cannot access file \"%s\"" afile))
8015 (if (and (> (length heading) 0)
8016 (string-match "^\\*+" heading))
8017 (setq level (match-end 0))
8018 (setq heading nil level 0))
8019 (save-excursion
8020 (org-back-to-heading t)
8021 ;; Get context information that will be lost by moving the tree
8022 (org-refresh-category-properties)
8023 (setq category (org-get-category)
8024 todo (and (looking-at org-todo-line-regexp)
8025 (match-string 2))
8026 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8027 ltags (org-get-tags)
8028 itags (org-delete-all ltags (org-get-tags-at)))
8029 (setq ltags (mapconcat 'identity ltags " ")
8030 itags (mapconcat 'identity itags " "))
8031 ;; We first only copy, in case something goes wrong
8032 ;; we need to protect this-command, to avoid kill-region sets it,
8033 ;; which would lead to duplication of subtrees
8034 (let (this-command) (org-copy-subtree))
8035 (set-buffer buffer)
8036 ;; Enforce org-mode for the archive buffer
8037 (if (not (org-mode-p))
8038 ;; Force the mode for future visits.
8039 (let ((org-insert-mode-line-in-empty-file t)
8040 (org-inhibit-startup t))
8041 (call-interactively 'org-mode)))
8042 (when newfile-p
8043 (goto-char (point-max))
8044 (insert (format "\nArchived entries from file %s\n\n"
8045 (buffer-file-name this-buffer))))
8046 ;; Force the TODO keywords of the original buffer
8047 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8048 (org-todo-keywords-1 tr-org-todo-keywords-1)
8049 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8050 (org-done-keywords tr-org-done-keywords)
8051 (org-todo-regexp tr-org-todo-regexp)
8052 (org-todo-line-regexp tr-org-todo-line-regexp)
8053 (org-odd-levels-only
8054 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8055 org-odd-levels-only
8056 tr-org-odd-levels-only)))
8057 (goto-char (point-min))
8058 (show-all)
8059 (if heading
8060 (progn
8061 (if (re-search-forward
8062 (concat "^" (regexp-quote heading)
8063 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8064 nil t)
8065 (goto-char (match-end 0))
8066 ;; Heading not found, just insert it at the end
8067 (goto-char (point-max))
8068 (or (bolp) (insert "\n"))
8069 (insert "\n" heading "\n")
8070 (end-of-line 0))
8071 ;; Make the subtree visible
8072 (show-subtree)
8073 (org-end-of-subtree t)
8074 (skip-chars-backward " \t\r\n")
8075 (and (looking-at "[ \t\r\n]*")
8076 (replace-match "\n\n")))
8077 ;; No specific heading, just go to end of file.
8078 (goto-char (point-max)) (insert "\n"))
8079 ;; Paste
8080 (org-paste-subtree (org-get-legal-level level 1))
8082 ;; Mark the entry as done
8083 (when (and org-archive-mark-done
8084 (looking-at org-todo-line-regexp)
8085 (or (not (match-end 2))
8086 (not (member (match-string 2) org-done-keywords))))
8087 (let (org-log-done org-todo-log-states)
8088 (org-todo
8089 (car (or (member org-archive-mark-done org-done-keywords)
8090 org-done-keywords)))))
8092 ;; Add the context info
8093 (when org-archive-save-context-info
8094 (let ((l org-archive-save-context-info) e n v)
8095 (while (setq e (pop l))
8096 (when (and (setq v (symbol-value e))
8097 (stringp v) (string-match "\\S-" v))
8098 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8099 (org-entry-put (point) n v)))))
8101 ;; Save and kill the buffer, if it is not the same buffer.
8102 (if (not (eq this-buffer buffer))
8103 (progn (save-buffer) (kill-buffer buffer)))))
8104 ;; Here we are back in the original buffer. Everything seems to have
8105 ;; worked. So now cut the tree and finish up.
8106 (let (this-command) (org-cut-subtree))
8107 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8108 (message "Subtree archived %s"
8109 (if (eq this-buffer buffer)
8110 (concat "under heading: " heading)
8111 (concat "in file: " (abbreviate-file-name afile)))))))
8113 (defun org-refresh-category-properties ()
8114 "Refresh category text properties in teh buffer."
8115 (let ((def-cat (cond
8116 ((null org-category)
8117 (if buffer-file-name
8118 (file-name-sans-extension
8119 (file-name-nondirectory buffer-file-name))
8120 "???"))
8121 ((symbolp org-category) (symbol-name org-category))
8122 (t org-category)))
8123 beg end cat pos optionp)
8124 (org-unmodified
8125 (save-excursion
8126 (save-restriction
8127 (widen)
8128 (goto-char (point-min))
8129 (put-text-property (point) (point-max) 'org-category def-cat)
8130 (while (re-search-forward
8131 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8132 (setq pos (match-end 0)
8133 optionp (equal (char-after (match-beginning 0)) ?#)
8134 cat (org-trim (match-string 2)))
8135 (if optionp
8136 (setq beg (point-at-bol) end (point-max))
8137 (org-back-to-heading t)
8138 (setq beg (point) end (org-end-of-subtree t t)))
8139 (put-text-property beg end 'org-category cat)
8140 (goto-char pos)))))))
8142 (defun org-archive-all-done (&optional tag)
8143 "Archive sublevels of the current tree without open TODO items.
8144 If the cursor is not on a headline, try all level 1 trees. If
8145 it is on a headline, try all direct children.
8146 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8147 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8148 (rea (concat ".*:" org-archive-tag ":"))
8149 (begm (make-marker))
8150 (endm (make-marker))
8151 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8152 "Move subtree to archive (no open TODO items)? "))
8153 beg end (cntarch 0))
8154 (if (org-on-heading-p)
8155 (progn
8156 (setq re1 (concat "^" (regexp-quote
8157 (make-string
8158 (1+ (- (match-end 0) (match-beginning 0) 1))
8159 ?*))
8160 " "))
8161 (move-marker begm (point))
8162 (move-marker endm (org-end-of-subtree t)))
8163 (setq re1 "^* ")
8164 (move-marker begm (point-min))
8165 (move-marker endm (point-max)))
8166 (save-excursion
8167 (goto-char begm)
8168 (while (re-search-forward re1 endm t)
8169 (setq beg (match-beginning 0)
8170 end (save-excursion (org-end-of-subtree t) (point)))
8171 (goto-char beg)
8172 (if (re-search-forward re end t)
8173 (goto-char end)
8174 (goto-char beg)
8175 (if (and (or (not tag) (not (looking-at rea)))
8176 (y-or-n-p question))
8177 (progn
8178 (if tag
8179 (org-toggle-tag org-archive-tag 'on)
8180 (org-archive-subtree))
8181 (setq cntarch (1+ cntarch)))
8182 (goto-char end)))))
8183 (message "%d trees archived" cntarch)))
8185 (defun org-cycle-hide-drawers (state)
8186 "Re-hide all drawers after a visibility state change."
8187 (when (and (org-mode-p)
8188 (not (memq state '(overview folded))))
8189 (save-excursion
8190 (let* ((globalp (memq state '(contents all)))
8191 (beg (if globalp (point-min) (point)))
8192 (end (if globalp (point-max) (org-end-of-subtree t))))
8193 (goto-char beg)
8194 (while (re-search-forward org-drawer-regexp end t)
8195 (org-flag-drawer t))))))
8197 (defun org-flag-drawer (flag)
8198 (save-excursion
8199 (beginning-of-line 1)
8200 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8201 (let ((b (match-end 0))
8202 (outline-regexp org-outline-regexp))
8203 (if (re-search-forward
8204 "^[ \t]*:END:"
8205 (save-excursion (outline-next-heading) (point)) t)
8206 (outline-flag-region b (point-at-eol) flag)
8207 (error ":END: line missing"))))))
8209 (defun org-cycle-hide-archived-subtrees (state)
8210 "Re-hide all archived subtrees after a visibility state change."
8211 (when (and (not org-cycle-open-archived-trees)
8212 (not (memq state '(overview folded))))
8213 (save-excursion
8214 (let* ((globalp (memq state '(contents all)))
8215 (beg (if globalp (point-min) (point)))
8216 (end (if globalp (point-max) (org-end-of-subtree t))))
8217 (org-hide-archived-subtrees beg end)
8218 (goto-char beg)
8219 (if (looking-at (concat ".*:" org-archive-tag ":"))
8220 (message "%s" (substitute-command-keys
8221 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8223 (defun org-force-cycle-archived ()
8224 "Cycle subtree even if it is archived."
8225 (interactive)
8226 (setq this-command 'org-cycle)
8227 (let ((org-cycle-open-archived-trees t))
8228 (call-interactively 'org-cycle)))
8230 (defun org-hide-archived-subtrees (beg end)
8231 "Re-hide all archived subtrees after a visibility state change."
8232 (save-excursion
8233 (let* ((re (concat ":" org-archive-tag ":")))
8234 (goto-char beg)
8235 (while (re-search-forward re end t)
8236 (and (org-on-heading-p) (hide-subtree))
8237 (org-end-of-subtree t)))))
8239 (defun org-toggle-tag (tag &optional onoff)
8240 "Toggle the tag TAG for the current line.
8241 If ONOFF is `on' or `off', don't toggle but set to this state."
8242 (unless (org-on-heading-p t) (error "Not on headling"))
8243 (let (res current)
8244 (save-excursion
8245 (beginning-of-line)
8246 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8247 (point-at-eol) t)
8248 (progn
8249 (setq current (match-string 1))
8250 (replace-match ""))
8251 (setq current ""))
8252 (setq current (nreverse (org-split-string current ":")))
8253 (cond
8254 ((eq onoff 'on)
8255 (setq res t)
8256 (or (member tag current) (push tag current)))
8257 ((eq onoff 'off)
8258 (or (not (member tag current)) (setq current (delete tag current))))
8259 (t (if (member tag current)
8260 (setq current (delete tag current))
8261 (setq res t)
8262 (push tag current))))
8263 (end-of-line 1)
8264 (if current
8265 (progn
8266 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8267 (org-set-tags nil t))
8268 (delete-horizontal-space))
8269 (run-hooks 'org-after-tags-change-hook))
8270 res))
8272 (defun org-toggle-archive-tag (&optional arg)
8273 "Toggle the archive tag for the current headline.
8274 With prefix ARG, check all children of current headline and offer tagging
8275 the children that do not contain any open TODO items."
8276 (interactive "P")
8277 (if arg
8278 (org-archive-all-done 'tag)
8279 (let (set)
8280 (save-excursion
8281 (org-back-to-heading t)
8282 (setq set (org-toggle-tag org-archive-tag))
8283 (when set (hide-subtree)))
8284 (and set (beginning-of-line 1))
8285 (message "Subtree %s" (if set "archived" "unarchived")))))
8288 ;;;; Tables
8290 ;;; The table editor
8292 ;; Watch out: Here we are talking about two different kind of tables.
8293 ;; Most of the code is for the tables created with the Org-mode table editor.
8294 ;; Sometimes, we talk about tables created and edited with the table.el
8295 ;; Emacs package. We call the former org-type tables, and the latter
8296 ;; table.el-type tables.
8298 (defun org-before-change-function (beg end)
8299 "Every change indicates that a table might need an update."
8300 (setq org-table-may-need-update t))
8302 (defconst org-table-line-regexp "^[ \t]*|"
8303 "Detects an org-type table line.")
8304 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8305 "Detects an org-type table line.")
8306 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8307 "Detects a table line marked for automatic recalculation.")
8308 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8309 "Detects a table line marked for automatic recalculation.")
8310 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8311 "Detects a table line marked for automatic recalculation.")
8312 (defconst org-table-hline-regexp "^[ \t]*|-"
8313 "Detects an org-type table hline.")
8314 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8315 "Detects a table-type table hline.")
8316 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8317 "Detects an org-type or table-type table.")
8318 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8319 "Searching from within a table (any type) this finds the first line
8320 outside the table.")
8321 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8322 "Searching from within a table (any type) this finds the first line
8323 outside the table.")
8325 (defvar org-table-last-highlighted-reference nil)
8326 (defvar org-table-formula-history nil)
8328 (defvar org-table-column-names nil
8329 "Alist with column names, derived from the `!' line.")
8330 (defvar org-table-column-name-regexp nil
8331 "Regular expression matching the current column names.")
8332 (defvar org-table-local-parameters nil
8333 "Alist with parameter names, derived from the `$' line.")
8334 (defvar org-table-named-field-locations nil
8335 "Alist with locations of named fields.")
8337 (defvar org-table-current-line-types nil
8338 "Table row types, non-nil only for the duration of a comand.")
8339 (defvar org-table-current-begin-line nil
8340 "Table begin line, non-nil only for the duration of a comand.")
8341 (defvar org-table-current-begin-pos nil
8342 "Table begin position, non-nil only for the duration of a comand.")
8343 (defvar org-table-dlines nil
8344 "Vector of data line line numbers in the current table.")
8345 (defvar org-table-hlines nil
8346 "Vector of hline line numbers in the current table.")
8348 (defconst org-table-range-regexp
8349 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8350 ;; 1 2 3 4 5
8351 "Regular expression for matching ranges in formulas.")
8353 (defconst org-table-range-regexp2
8354 (concat
8355 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8356 "\\.\\."
8357 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8358 "Match a range for reference display.")
8360 (defconst org-table-translate-regexp
8361 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8362 "Match a reference that needs translation, for reference display.")
8364 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8366 (defun org-table-create-with-table.el ()
8367 "Use the table.el package to insert a new table.
8368 If there is already a table at point, convert between Org-mode tables
8369 and table.el tables."
8370 (interactive)
8371 (require 'table)
8372 (cond
8373 ((org-at-table.el-p)
8374 (if (y-or-n-p "Convert table to Org-mode table? ")
8375 (org-table-convert)))
8376 ((org-at-table-p)
8377 (if (y-or-n-p "Convert table to table.el table? ")
8378 (org-table-convert)))
8379 (t (call-interactively 'table-insert))))
8381 (defun org-table-create-or-convert-from-region (arg)
8382 "Convert region to table, or create an empty table.
8383 If there is an active region, convert it to a table, using the function
8384 `org-table-convert-region'. See the documentation of that function
8385 to learn how the prefix argument is interpreted to determine the field
8386 separator.
8387 If there is no such region, create an empty table with `org-table-create'."
8388 (interactive "P")
8389 (if (org-region-active-p)
8390 (org-table-convert-region (region-beginning) (region-end) arg)
8391 (org-table-create arg)))
8393 (defun org-table-create (&optional size)
8394 "Query for a size and insert a table skeleton.
8395 SIZE is a string Columns x Rows like for example \"3x2\"."
8396 (interactive "P")
8397 (unless size
8398 (setq size (read-string
8399 (concat "Table size Columns x Rows [e.g. "
8400 org-table-default-size "]: ")
8401 "" nil org-table-default-size)))
8403 (let* ((pos (point))
8404 (indent (make-string (current-column) ?\ ))
8405 (split (org-split-string size " *x *"))
8406 (rows (string-to-number (nth 1 split)))
8407 (columns (string-to-number (car split)))
8408 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8409 "\n")))
8410 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8411 (point-at-bol) (point)))
8412 (beginning-of-line 1)
8413 (newline))
8414 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8415 (dotimes (i rows) (insert line))
8416 (goto-char pos)
8417 (if (> rows 1)
8418 ;; Insert a hline after the first row.
8419 (progn
8420 (end-of-line 1)
8421 (insert "\n|-")
8422 (goto-char pos)))
8423 (org-table-align)))
8425 (defun org-table-convert-region (beg0 end0 &optional separator)
8426 "Convert region to a table.
8427 The region goes from BEG0 to END0, but these borders will be moved
8428 slightly, to make sure a beginning of line in the first line is included.
8430 SEPARATOR specifies the field separator in the lines. It can have the
8431 following values:
8433 '(4) Use the comma as a field separator
8434 '(16) Use a TAB as field separator
8435 integer When a number, use that many spaces as field separator
8436 nil When nil, the command tries to be smart and figure out the
8437 separator in the following way:
8438 - when each line contains a TAB, assume TAB-separated material
8439 - when each line contains a comme, assume CSV material
8440 - else, assume one or more SPACE charcters as separator."
8441 (interactive "rP")
8442 (let* ((beg (min beg0 end0))
8443 (end (max beg0 end0))
8445 (goto-char beg)
8446 (beginning-of-line 1)
8447 (setq beg (move-marker (make-marker) (point)))
8448 (goto-char end)
8449 (if (bolp) (backward-char 1) (end-of-line 1))
8450 (setq end (move-marker (make-marker) (point)))
8451 ;; Get the right field separator
8452 (unless separator
8453 (goto-char beg)
8454 (setq separator
8455 (cond
8456 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8457 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8458 (t 1))))
8459 (setq re (cond
8460 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8461 ((equal separator '(16)) "^\\|\t")
8462 ((integerp separator)
8463 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8464 (t (error "This should not happen"))))
8465 (goto-char beg)
8466 (while (re-search-forward re end t)
8467 (replace-match "| " t t))
8468 (goto-char beg)
8469 (insert " ")
8470 (org-table-align)))
8472 (defun org-table-import (file arg)
8473 "Import FILE as a table.
8474 The file is assumed to be tab-separated. Such files can be produced by most
8475 spreadsheet and database applications. If no tabs (at least one per line)
8476 are found, lines will be split on whitespace into fields."
8477 (interactive "f\nP")
8478 (or (bolp) (newline))
8479 (let ((beg (point))
8480 (pm (point-max)))
8481 (insert-file-contents file)
8482 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8484 (defun org-table-export ()
8485 "Export table as a tab-separated file.
8486 Such a file can be imported into a spreadsheet program like Excel."
8487 (interactive)
8488 (let* ((beg (org-table-begin))
8489 (end (org-table-end))
8490 (table (buffer-substring beg end))
8491 (file (read-file-name "Export table to: "))
8492 buf)
8493 (unless (or (not (file-exists-p file))
8494 (y-or-n-p (format "Overwrite file %s? " file)))
8495 (error "Abort"))
8496 (with-current-buffer (find-file-noselect file)
8497 (setq buf (current-buffer))
8498 (erase-buffer)
8499 (fundamental-mode)
8500 (insert table)
8501 (goto-char (point-min))
8502 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8503 (replace-match "" t t)
8504 (end-of-line 1))
8505 (goto-char (point-min))
8506 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8507 (replace-match "" t t)
8508 (goto-char (min (1+ (point)) (point-max))))
8509 (goto-char (point-min))
8510 (while (re-search-forward "^-[-+]*$" nil t)
8511 (replace-match "")
8512 (if (looking-at "\n")
8513 (delete-char 1)))
8514 (goto-char (point-min))
8515 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8516 (replace-match "\t" t t))
8517 (save-buffer))
8518 (kill-buffer buf)))
8520 (defvar org-table-aligned-begin-marker (make-marker)
8521 "Marker at the beginning of the table last aligned.
8522 Used to check if cursor still is in that table, to minimize realignment.")
8523 (defvar org-table-aligned-end-marker (make-marker)
8524 "Marker at the end of the table last aligned.
8525 Used to check if cursor still is in that table, to minimize realignment.")
8526 (defvar org-table-last-alignment nil
8527 "List of flags for flushright alignment, from the last re-alignment.
8528 This is being used to correctly align a single field after TAB or RET.")
8529 (defvar org-table-last-column-widths nil
8530 "List of max width of fields in each column.
8531 This is being used to correctly align a single field after TAB or RET.")
8532 (defvar org-table-overlay-coordinates nil
8533 "Overlay coordinates after each align of a table.")
8534 (make-variable-buffer-local 'org-table-overlay-coordinates)
8536 (defvar org-last-recalc-line nil)
8537 (defconst org-narrow-column-arrow "=>"
8538 "Used as display property in narrowed table columns.")
8540 (defun org-table-align ()
8541 "Align the table at point by aligning all vertical bars."
8542 (interactive)
8543 (let* (
8544 ;; Limits of table
8545 (beg (org-table-begin))
8546 (end (org-table-end))
8547 ;; Current cursor position
8548 (linepos (org-current-line))
8549 (colpos (org-table-current-column))
8550 (winstart (window-start))
8551 (winstartline (org-current-line (min winstart (1- (point-max)))))
8552 lines (new "") lengths l typenums ty fields maxfields i
8553 column
8554 (indent "") cnt frac
8555 rfmt hfmt
8556 (spaces '(1 . 1))
8557 (sp1 (car spaces))
8558 (sp2 (cdr spaces))
8559 (rfmt1 (concat
8560 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8561 (hfmt1 (concat
8562 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8563 emptystrings links dates emph narrow fmax f1 len c e)
8564 (untabify beg end)
8565 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8566 ;; Check if we have links or dates
8567 (goto-char beg)
8568 (setq links (re-search-forward org-bracket-link-regexp end t))
8569 (goto-char beg)
8570 (setq emph (and org-hide-emphasis-markers
8571 (re-search-forward org-emph-re end t)))
8572 (goto-char beg)
8573 (setq dates (and org-display-custom-times
8574 (re-search-forward org-ts-regexp-both end t)))
8575 ;; Make sure the link properties are right
8576 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8577 ;; Make sure the date properties are right
8578 (when dates (goto-char beg) (while (org-activate-dates end)))
8579 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8581 ;; Check if we are narrowing any columns
8582 (goto-char beg)
8583 (setq narrow (and org-format-transports-properties-p
8584 (re-search-forward "<[0-9]+>" end t)))
8585 ;; Get the rows
8586 (setq lines (org-split-string
8587 (buffer-substring beg end) "\n"))
8588 ;; Store the indentation of the first line
8589 (if (string-match "^ *" (car lines))
8590 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8591 ;; Mark the hlines by setting the corresponding element to nil
8592 ;; At the same time, we remove trailing space.
8593 (setq lines (mapcar (lambda (l)
8594 (if (string-match "^ *|-" l)
8596 (if (string-match "[ \t]+$" l)
8597 (substring l 0 (match-beginning 0))
8598 l)))
8599 lines))
8600 ;; Get the data fields by splitting the lines.
8601 (setq fields (mapcar
8602 (lambda (l)
8603 (org-split-string l " *| *"))
8604 (delq nil (copy-sequence lines))))
8605 ;; How many fields in the longest line?
8606 (condition-case nil
8607 (setq maxfields (apply 'max (mapcar 'length fields)))
8608 (error
8609 (kill-region beg end)
8610 (org-table-create org-table-default-size)
8611 (error "Empty table - created default table")))
8612 ;; A list of empty strings to fill any short rows on output
8613 (setq emptystrings (make-list maxfields ""))
8614 ;; Check for special formatting.
8615 (setq i -1)
8616 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8617 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8618 ;; Check if there is an explicit width specified
8619 (when narrow
8620 (setq c column fmax nil)
8621 (while c
8622 (setq e (pop c))
8623 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8624 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8625 ;; Find fields that are wider than fmax, and shorten them
8626 (when fmax
8627 (loop for xx in column do
8628 (when (and (stringp xx)
8629 (> (org-string-width xx) fmax))
8630 (org-add-props xx nil
8631 'help-echo
8632 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8633 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8634 (unless (> f1 1)
8635 (error "Cannot narrow field starting with wide link \"%s\""
8636 (match-string 0 xx)))
8637 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8638 (add-text-properties (- f1 2) f1
8639 (list 'display org-narrow-column-arrow)
8640 xx)))))
8641 ;; Get the maximum width for each column
8642 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8643 ;; Get the fraction of numbers, to decide about alignment of the column
8644 (setq cnt 0 frac 0.0)
8645 (loop for x in column do
8646 (if (equal x "")
8648 (setq frac ( / (+ (* frac cnt)
8649 (if (string-match org-table-number-regexp x) 1 0))
8650 (setq cnt (1+ cnt))))))
8651 (push (>= frac org-table-number-fraction) typenums))
8652 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8654 ;; Store the alignment of this table, for later editing of single fields
8655 (setq org-table-last-alignment typenums
8656 org-table-last-column-widths lengths)
8658 ;; With invisible characters, `format' does not get the field width right
8659 ;; So we need to make these fields wide by hand.
8660 (when (or links emph)
8661 (loop for i from 0 upto (1- maxfields) do
8662 (setq len (nth i lengths))
8663 (loop for j from 0 upto (1- (length fields)) do
8664 (setq c (nthcdr i (car (nthcdr j fields))))
8665 (if (and (stringp (car c))
8666 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8667 ; (string-match org-bracket-link-regexp (car c))
8668 (< (org-string-width (car c)) len))
8669 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8671 ;; Compute the formats needed for output of the table
8672 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8673 (while (setq l (pop lengths))
8674 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8675 (setq rfmt (concat rfmt (format rfmt1 ty l))
8676 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8677 (setq rfmt (concat rfmt "\n")
8678 hfmt (concat (substring hfmt 0 -1) "|\n"))
8680 (setq new (mapconcat
8681 (lambda (l)
8682 (if l (apply 'format rfmt
8683 (append (pop fields) emptystrings))
8684 hfmt))
8685 lines ""))
8686 ;; Replace the old one
8687 (delete-region beg end)
8688 (move-marker end nil)
8689 (move-marker org-table-aligned-begin-marker (point))
8690 (insert new)
8691 (move-marker org-table-aligned-end-marker (point))
8692 (when (and orgtbl-mode (not (org-mode-p)))
8693 (goto-char org-table-aligned-begin-marker)
8694 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8695 ;; Try to move to the old location
8696 (goto-line winstartline)
8697 (setq winstart (point-at-bol))
8698 (goto-line linepos)
8699 (set-window-start (selected-window) winstart 'noforce)
8700 (org-table-goto-column colpos)
8701 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8702 (setq org-table-may-need-update nil)
8705 (defun org-string-width (s)
8706 "Compute width of string, ignoring invisible characters.
8707 This ignores character with invisibility property `org-link', and also
8708 characters with property `org-cwidth', because these will become invisible
8709 upon the next fontification round."
8710 (let (b l)
8711 (when (or (eq t buffer-invisibility-spec)
8712 (assq 'org-link buffer-invisibility-spec))
8713 (while (setq b (text-property-any 0 (length s)
8714 'invisible 'org-link s))
8715 (setq s (concat (substring s 0 b)
8716 (substring s (or (next-single-property-change
8717 b 'invisible s) (length s)))))))
8718 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8719 (setq s (concat (substring s 0 b)
8720 (substring s (or (next-single-property-change
8721 b 'org-cwidth s) (length s))))))
8722 (setq l (string-width s) b -1)
8723 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8724 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8727 (defun org-table-begin (&optional table-type)
8728 "Find the beginning of the table and return its position.
8729 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8730 (save-excursion
8731 (if (not (re-search-backward
8732 (if table-type org-table-any-border-regexp
8733 org-table-border-regexp)
8734 nil t))
8735 (progn (goto-char (point-min)) (point))
8736 (goto-char (match-beginning 0))
8737 (beginning-of-line 2)
8738 (point))))
8740 (defun org-table-end (&optional table-type)
8741 "Find the end of the table and return its position.
8742 With argument TABLE-TYPE, go to the end of a table.el-type table."
8743 (save-excursion
8744 (if (not (re-search-forward
8745 (if table-type org-table-any-border-regexp
8746 org-table-border-regexp)
8747 nil t))
8748 (goto-char (point-max))
8749 (goto-char (match-beginning 0)))
8750 (point-marker)))
8752 (defun org-table-justify-field-maybe (&optional new)
8753 "Justify the current field, text to left, number to right.
8754 Optional argument NEW may specify text to replace the current field content."
8755 (cond
8756 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8757 ((org-at-table-hline-p))
8758 ((and (not new)
8759 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8760 (current-buffer)))
8761 (< (point) org-table-aligned-begin-marker)
8762 (>= (point) org-table-aligned-end-marker)))
8763 ;; This is not the same table, force a full re-align
8764 (setq org-table-may-need-update t))
8765 (t ;; realign the current field, based on previous full realign
8766 (let* ((pos (point)) s
8767 (col (org-table-current-column))
8768 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8769 l f n o e)
8770 (when (> col 0)
8771 (skip-chars-backward "^|\n")
8772 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8773 (progn
8774 (setq s (match-string 1)
8775 o (match-string 0)
8776 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8777 e (not (= (match-beginning 2) (match-end 2))))
8778 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8779 l (if e "|" (setq org-table-may-need-update t) ""))
8780 n (format f s))
8781 (if new
8782 (if (<= (length new) l) ;; FIXME: length -> str-width?
8783 (setq n (format f new))
8784 (setq n (concat new "|") org-table-may-need-update t)))
8785 (or (equal n o)
8786 (let (org-table-may-need-update)
8787 (replace-match n t t))))
8788 (setq org-table-may-need-update t))
8789 (goto-char pos))))))
8791 (defun org-table-next-field ()
8792 "Go to the next field in the current table, creating new lines as needed.
8793 Before doing so, re-align the table if necessary."
8794 (interactive)
8795 (org-table-maybe-eval-formula)
8796 (org-table-maybe-recalculate-line)
8797 (if (and org-table-automatic-realign
8798 org-table-may-need-update)
8799 (org-table-align))
8800 (let ((end (org-table-end)))
8801 (if (org-at-table-hline-p)
8802 (end-of-line 1))
8803 (condition-case nil
8804 (progn
8805 (re-search-forward "|" end)
8806 (if (looking-at "[ \t]*$")
8807 (re-search-forward "|" end))
8808 (if (and (looking-at "-")
8809 org-table-tab-jumps-over-hlines
8810 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8811 (goto-char (match-beginning 1)))
8812 (if (looking-at "-")
8813 (progn
8814 (beginning-of-line 0)
8815 (org-table-insert-row 'below))
8816 (if (looking-at " ") (forward-char 1))))
8817 (error
8818 (org-table-insert-row 'below)))))
8820 (defun org-table-previous-field ()
8821 "Go to the previous field in the table.
8822 Before doing so, re-align the table if necessary."
8823 (interactive)
8824 (org-table-justify-field-maybe)
8825 (org-table-maybe-recalculate-line)
8826 (if (and org-table-automatic-realign
8827 org-table-may-need-update)
8828 (org-table-align))
8829 (if (org-at-table-hline-p)
8830 (end-of-line 1))
8831 (re-search-backward "|" (org-table-begin))
8832 (re-search-backward "|" (org-table-begin))
8833 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8834 (re-search-backward "|" (org-table-begin)))
8835 (if (looking-at "| ?")
8836 (goto-char (match-end 0))))
8838 (defun org-table-next-row ()
8839 "Go to the next row (same column) in the current table.
8840 Before doing so, re-align the table if necessary."
8841 (interactive)
8842 (org-table-maybe-eval-formula)
8843 (org-table-maybe-recalculate-line)
8844 (if (or (looking-at "[ \t]*$")
8845 (save-excursion (skip-chars-backward " \t") (bolp)))
8846 (newline)
8847 (if (and org-table-automatic-realign
8848 org-table-may-need-update)
8849 (org-table-align))
8850 (let ((col (org-table-current-column)))
8851 (beginning-of-line 2)
8852 (if (or (not (org-at-table-p))
8853 (org-at-table-hline-p))
8854 (progn
8855 (beginning-of-line 0)
8856 (org-table-insert-row 'below)))
8857 (org-table-goto-column col)
8858 (skip-chars-backward "^|\n\r")
8859 (if (looking-at " ") (forward-char 1)))))
8861 (defun org-table-copy-down (n)
8862 "Copy a field down in the current column.
8863 If the field at the cursor is empty, copy into it the content of the nearest
8864 non-empty field above. With argument N, use the Nth non-empty field.
8865 If the current field is not empty, it is copied down to the next row, and
8866 the cursor is moved with it. Therefore, repeating this command causes the
8867 column to be filled row-by-row.
8868 If the variable `org-table-copy-increment' is non-nil and the field is an
8869 integer or a timestamp, it will be incremented while copying. In the case of
8870 a timestamp, if the cursor is on the year, change the year. If it is on the
8871 month or the day, change that. Point will stay on the current date field
8872 in order to easily repeat the interval."
8873 (interactive "p")
8874 (let* ((colpos (org-table-current-column))
8875 (col (current-column))
8876 (field (org-table-get-field))
8877 (non-empty (string-match "[^ \t]" field))
8878 (beg (org-table-begin))
8879 txt)
8880 (org-table-check-inside-data-field)
8881 (if non-empty
8882 (progn
8883 (setq txt (org-trim field))
8884 (org-table-next-row)
8885 (org-table-blank-field))
8886 (save-excursion
8887 (setq txt
8888 (catch 'exit
8889 (while (progn (beginning-of-line 1)
8890 (re-search-backward org-table-dataline-regexp
8891 beg t))
8892 (org-table-goto-column colpos t)
8893 (if (and (looking-at
8894 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8895 (= (setq n (1- n)) 0))
8896 (throw 'exit (match-string 1))))))))
8897 (if txt
8898 (progn
8899 (if (and org-table-copy-increment
8900 (string-match "^[0-9]+$" txt))
8901 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8902 (insert txt)
8903 (move-to-column col)
8904 (if (and org-table-copy-increment (org-at-timestamp-p t))
8905 (org-timestamp-up 1)
8906 (org-table-maybe-recalculate-line))
8907 (org-table-align)
8908 (move-to-column col))
8909 (error "No non-empty field found"))))
8911 (defun org-table-check-inside-data-field ()
8912 "Is point inside a table data field?
8913 I.e. not on a hline or before the first or after the last column?
8914 This actually throws an error, so it aborts the current command."
8915 (if (or (not (org-at-table-p))
8916 (= (org-table-current-column) 0)
8917 (org-at-table-hline-p)
8918 (looking-at "[ \t]*$"))
8919 (error "Not in table data field")))
8921 (defvar org-table-clip nil
8922 "Clipboard for table regions.")
8924 (defun org-table-blank-field ()
8925 "Blank the current table field or active region."
8926 (interactive)
8927 (org-table-check-inside-data-field)
8928 (if (and (interactive-p) (org-region-active-p))
8929 (let (org-table-clip)
8930 (org-table-cut-region (region-beginning) (region-end)))
8931 (skip-chars-backward "^|")
8932 (backward-char 1)
8933 (if (looking-at "|[^|\n]+")
8934 (let* ((pos (match-beginning 0))
8935 (match (match-string 0))
8936 (len (org-string-width match)))
8937 (replace-match (concat "|" (make-string (1- len) ?\ )))
8938 (goto-char (+ 2 pos))
8939 (substring match 1)))))
8941 (defun org-table-get-field (&optional n replace)
8942 "Return the value of the field in column N of current row.
8943 N defaults to current field.
8944 If REPLACE is a string, replace field with this value. The return value
8945 is always the old value."
8946 (and n (org-table-goto-column n))
8947 (skip-chars-backward "^|\n")
8948 (backward-char 1)
8949 (if (looking-at "|[^|\r\n]*")
8950 (let* ((pos (match-beginning 0))
8951 (val (buffer-substring (1+ pos) (match-end 0))))
8952 (if replace
8953 (replace-match (concat "|" replace) t t))
8954 (goto-char (min (point-at-eol) (+ 2 pos)))
8955 val)
8956 (forward-char 1) ""))
8958 (defun org-table-field-info (arg)
8959 "Show info about the current field, and highlight any reference at point."
8960 (interactive "P")
8961 (org-table-get-specials)
8962 (save-excursion
8963 (let* ((pos (point))
8964 (col (org-table-current-column))
8965 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8966 (name (car (rassoc (list (org-current-line) col)
8967 org-table-named-field-locations)))
8968 (eql (org-table-get-stored-formulas))
8969 (dline (org-table-current-dline))
8970 (ref (format "@%d$%d" dline col))
8971 (ref1 (org-table-convert-refs-to-an ref))
8972 (fequation (or (assoc name eql) (assoc ref eql)))
8973 (cequation (assoc (int-to-string col) eql))
8974 (eqn (or fequation cequation)))
8975 (goto-char pos)
8976 (condition-case nil
8977 (org-table-show-reference 'local)
8978 (error nil))
8979 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8980 dline col
8981 (if cname (concat " or $" cname) "")
8982 dline col ref1
8983 (if name (concat " or $" name) "")
8984 ;; FIXME: formula info not correct if special table line
8985 (if eqn
8986 (concat ", formula: "
8987 (org-table-formula-to-user
8988 (concat
8989 (if (string-match "^[$@]"(car eqn)) "" "$")
8990 (car eqn) "=" (cdr eqn))))
8991 "")))))
8993 (defun org-table-current-column ()
8994 "Find out which column we are in.
8995 When called interactively, column is also displayed in echo area."
8996 (interactive)
8997 (if (interactive-p) (org-table-check-inside-data-field))
8998 (save-excursion
8999 (let ((cnt 0) (pos (point)))
9000 (beginning-of-line 1)
9001 (while (search-forward "|" pos t)
9002 (setq cnt (1+ cnt)))
9003 (if (interactive-p) (message "This is table column %d" cnt))
9004 cnt)))
9006 (defun org-table-current-dline ()
9007 "Find out what table data line we are in.
9008 Only datalins count for this."
9009 (interactive)
9010 (if (interactive-p) (org-table-check-inside-data-field))
9011 (save-excursion
9012 (let ((cnt 0) (pos (point)))
9013 (goto-char (org-table-begin))
9014 (while (<= (point) pos)
9015 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9016 (beginning-of-line 2))
9017 (if (interactive-p) (message "This is table line %d" cnt))
9018 cnt)))
9020 (defun org-table-goto-column (n &optional on-delim force)
9021 "Move the cursor to the Nth column in the current table line.
9022 With optional argument ON-DELIM, stop with point before the left delimiter
9023 of the field.
9024 If there are less than N fields, just go to after the last delimiter.
9025 However, when FORCE is non-nil, create new columns if necessary."
9026 (interactive "p")
9027 (let ((pos (point-at-eol)))
9028 (beginning-of-line 1)
9029 (when (> n 0)
9030 (while (and (> (setq n (1- n)) -1)
9031 (or (search-forward "|" pos t)
9032 (and force
9033 (progn (end-of-line 1)
9034 (skip-chars-backward "^|")
9035 (insert " | "))))))
9036 ; (backward-char 2) t)))))
9037 (when (and force (not (looking-at ".*|")))
9038 (save-excursion (end-of-line 1) (insert " | ")))
9039 (if on-delim
9040 (backward-char 1)
9041 (if (looking-at " ") (forward-char 1))))))
9043 (defun org-at-table-p (&optional table-type)
9044 "Return t if the cursor is inside an org-type table.
9045 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9046 (if org-enable-table-editor
9047 (save-excursion
9048 (beginning-of-line 1)
9049 (looking-at (if table-type org-table-any-line-regexp
9050 org-table-line-regexp)))
9051 nil))
9053 (defun org-at-table.el-p ()
9054 "Return t if and only if we are at a table.el table."
9055 (and (org-at-table-p 'any)
9056 (save-excursion
9057 (goto-char (org-table-begin 'any))
9058 (looking-at org-table1-hline-regexp))))
9060 (defun org-table-recognize-table.el ()
9061 "If there is a table.el table nearby, recognize it and move into it."
9062 (if org-table-tab-recognizes-table.el
9063 (if (org-at-table.el-p)
9064 (progn
9065 (beginning-of-line 1)
9066 (if (looking-at org-table-dataline-regexp)
9068 (if (looking-at org-table1-hline-regexp)
9069 (progn
9070 (beginning-of-line 2)
9071 (if (looking-at org-table-any-border-regexp)
9072 (beginning-of-line -1)))))
9073 (if (re-search-forward "|" (org-table-end t) t)
9074 (progn
9075 (require 'table)
9076 (if (table--at-cell-p (point))
9078 (message "recognizing table.el table...")
9079 (table-recognize-table)
9080 (message "recognizing table.el table...done")))
9081 (error "This should not happen..."))
9083 nil)
9084 nil))
9086 (defun org-at-table-hline-p ()
9087 "Return t if the cursor is inside a hline in a table."
9088 (if org-enable-table-editor
9089 (save-excursion
9090 (beginning-of-line 1)
9091 (looking-at org-table-hline-regexp))
9092 nil))
9094 (defun org-table-insert-column ()
9095 "Insert a new column into the table."
9096 (interactive)
9097 (if (not (org-at-table-p))
9098 (error "Not at a table"))
9099 (org-table-find-dataline)
9100 (let* ((col (max 1 (org-table-current-column)))
9101 (beg (org-table-begin))
9102 (end (org-table-end))
9103 ;; Current cursor position
9104 (linepos (org-current-line))
9105 (colpos col))
9106 (goto-char beg)
9107 (while (< (point) end)
9108 (if (org-at-table-hline-p)
9110 (org-table-goto-column col t)
9111 (insert "| "))
9112 (beginning-of-line 2))
9113 (move-marker end nil)
9114 (goto-line linepos)
9115 (org-table-goto-column colpos)
9116 (org-table-align)
9117 (org-table-fix-formulas "$" nil (1- col) 1)))
9119 (defun org-table-find-dataline ()
9120 "Find a dataline in the current table, which is needed for column commands."
9121 (if (and (org-at-table-p)
9122 (not (org-at-table-hline-p)))
9124 (let ((col (current-column))
9125 (end (org-table-end)))
9126 (move-to-column col)
9127 (while (and (< (point) end)
9128 (or (not (= (current-column) col))
9129 (org-at-table-hline-p)))
9130 (beginning-of-line 2)
9131 (move-to-column col))
9132 (if (and (org-at-table-p)
9133 (not (org-at-table-hline-p)))
9135 (error
9136 "Please position cursor in a data line for column operations")))))
9138 (defun org-table-delete-column ()
9139 "Delete a column from the table."
9140 (interactive)
9141 (if (not (org-at-table-p))
9142 (error "Not at a table"))
9143 (org-table-find-dataline)
9144 (org-table-check-inside-data-field)
9145 (let* ((col (org-table-current-column))
9146 (beg (org-table-begin))
9147 (end (org-table-end))
9148 ;; Current cursor position
9149 (linepos (org-current-line))
9150 (colpos col))
9151 (goto-char beg)
9152 (while (< (point) end)
9153 (if (org-at-table-hline-p)
9155 (org-table-goto-column col t)
9156 (and (looking-at "|[^|\n]+|")
9157 (replace-match "|")))
9158 (beginning-of-line 2))
9159 (move-marker end nil)
9160 (goto-line linepos)
9161 (org-table-goto-column colpos)
9162 (org-table-align)
9163 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9164 col -1 col)))
9166 (defun org-table-move-column-right ()
9167 "Move column to the right."
9168 (interactive)
9169 (org-table-move-column nil))
9170 (defun org-table-move-column-left ()
9171 "Move column to the left."
9172 (interactive)
9173 (org-table-move-column 'left))
9175 (defun org-table-move-column (&optional left)
9176 "Move the current column to the right. With arg LEFT, move to the left."
9177 (interactive "P")
9178 (if (not (org-at-table-p))
9179 (error "Not at a table"))
9180 (org-table-find-dataline)
9181 (org-table-check-inside-data-field)
9182 (let* ((col (org-table-current-column))
9183 (col1 (if left (1- col) col))
9184 (beg (org-table-begin))
9185 (end (org-table-end))
9186 ;; Current cursor position
9187 (linepos (org-current-line))
9188 (colpos (if left (1- col) (1+ col))))
9189 (if (and left (= col 1))
9190 (error "Cannot move column further left"))
9191 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9192 (error "Cannot move column further right"))
9193 (goto-char beg)
9194 (while (< (point) end)
9195 (if (org-at-table-hline-p)
9197 (org-table-goto-column col1 t)
9198 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9199 (replace-match "|\\2|\\1|")))
9200 (beginning-of-line 2))
9201 (move-marker end nil)
9202 (goto-line linepos)
9203 (org-table-goto-column colpos)
9204 (org-table-align)
9205 (org-table-fix-formulas
9206 "$" (list (cons (number-to-string col) (number-to-string colpos))
9207 (cons (number-to-string colpos) (number-to-string col))))))
9209 (defun org-table-move-row-down ()
9210 "Move table row down."
9211 (interactive)
9212 (org-table-move-row nil))
9213 (defun org-table-move-row-up ()
9214 "Move table row up."
9215 (interactive)
9216 (org-table-move-row 'up))
9218 (defun org-table-move-row (&optional up)
9219 "Move the current table line down. With arg UP, move it up."
9220 (interactive "P")
9221 (let* ((col (current-column))
9222 (pos (point))
9223 (hline1p (save-excursion (beginning-of-line 1)
9224 (looking-at org-table-hline-regexp)))
9225 (dline1 (org-table-current-dline))
9226 (dline2 (+ dline1 (if up -1 1)))
9227 (tonew (if up 0 2))
9228 txt hline2p)
9229 (beginning-of-line tonew)
9230 (unless (org-at-table-p)
9231 (goto-char pos)
9232 (error "Cannot move row further"))
9233 (setq hline2p (looking-at org-table-hline-regexp))
9234 (goto-char pos)
9235 (beginning-of-line 1)
9236 (setq pos (point))
9237 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9238 (delete-region (point) (1+ (point-at-eol)))
9239 (beginning-of-line tonew)
9240 (insert txt)
9241 (beginning-of-line 0)
9242 (move-to-column col)
9243 (unless (or hline1p hline2p)
9244 (org-table-fix-formulas
9245 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9246 (cons (number-to-string dline2) (number-to-string dline1)))))))
9248 (defun org-table-insert-row (&optional arg)
9249 "Insert a new row above the current line into the table.
9250 With prefix ARG, insert below the current line."
9251 (interactive "P")
9252 (if (not (org-at-table-p))
9253 (error "Not at a table"))
9254 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9255 (new (org-table-clean-line line)))
9256 ;; Fix the first field if necessary
9257 (if (string-match "^[ \t]*| *[#$] *|" line)
9258 (setq new (replace-match (match-string 0 line) t t new)))
9259 (beginning-of-line (if arg 2 1))
9260 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9261 (beginning-of-line 0)
9262 (re-search-forward "| ?" (point-at-eol) t)
9263 (and (or org-table-may-need-update org-table-overlay-coordinates)
9264 (org-table-align))
9265 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9267 (defun org-table-insert-hline (&optional above)
9268 "Insert a horizontal-line below the current line into the table.
9269 With prefix ABOVE, insert above the current line."
9270 (interactive "P")
9271 (if (not (org-at-table-p))
9272 (error "Not at a table"))
9273 (let ((line (org-table-clean-line
9274 (buffer-substring (point-at-bol) (point-at-eol))))
9275 (col (current-column)))
9276 (while (string-match "|\\( +\\)|" line)
9277 (setq line (replace-match
9278 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9279 ?-) "|") t t line)))
9280 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9281 (beginning-of-line (if above 1 2))
9282 (insert line "\n")
9283 (beginning-of-line (if above 1 -1))
9284 (move-to-column col)
9285 (and org-table-overlay-coordinates (org-table-align))))
9287 (defun org-table-hline-and-move (&optional same-column)
9288 "Insert a hline and move to the row below that line."
9289 (interactive "P")
9290 (let ((col (org-table-current-column)))
9291 (org-table-maybe-eval-formula)
9292 (org-table-maybe-recalculate-line)
9293 (org-table-insert-hline)
9294 (end-of-line 2)
9295 (if (looking-at "\n[ \t]*|-")
9296 (progn (insert "\n|") (org-table-align))
9297 (org-table-next-field))
9298 (if same-column (org-table-goto-column col))))
9300 (defun org-table-clean-line (s)
9301 "Convert a table line S into a string with only \"|\" and space.
9302 In particular, this does handle wide and invisible characters."
9303 (if (string-match "^[ \t]*|-" s)
9304 ;; It's a hline, just map the characters
9305 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9306 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9307 (setq s (replace-match
9308 (concat "|" (make-string (org-string-width (match-string 1 s))
9309 ?\ ) "|")
9310 t t s)))
9313 (defun org-table-kill-row ()
9314 "Delete the current row or horizontal line from the table."
9315 (interactive)
9316 (if (not (org-at-table-p))
9317 (error "Not at a table"))
9318 (let ((col (current-column))
9319 (dline (org-table-current-dline)))
9320 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9321 (if (not (org-at-table-p)) (beginning-of-line 0))
9322 (move-to-column col)
9323 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9324 dline -1 dline)))
9326 (defun org-table-sort-lines (with-case &optional sorting-type)
9327 "Sort table lines according to the column at point.
9329 The position of point indicates the column to be used for
9330 sorting, and the range of lines is the range between the nearest
9331 horizontal separator lines, or the entire table of no such lines
9332 exist. If point is before the first column, you will be prompted
9333 for the sorting column. If there is an active region, the mark
9334 specifies the first line and the sorting column, while point
9335 should be in the last line to be included into the sorting.
9337 The command then prompts for the sorting type which can be
9338 alphabetically, numerically, or by time (as given in a time stamp
9339 in the field). Sorting in reverse order is also possible.
9341 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9343 If SORTING-TYPE is specified when this function is called from a Lisp
9344 program, no prompting will take place. SORTING-TYPE must be a character,
9345 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9346 should be done in reverse order."
9347 (interactive "P")
9348 (let* ((thisline (org-current-line))
9349 (thiscol (org-table-current-column))
9350 beg end bcol ecol tend tbeg column lns pos)
9351 (when (equal thiscol 0)
9352 (if (interactive-p)
9353 (setq thiscol
9354 (string-to-number
9355 (read-string "Use column N for sorting: ")))
9356 (setq thiscol 1))
9357 (org-table-goto-column thiscol))
9358 (org-table-check-inside-data-field)
9359 (if (org-region-active-p)
9360 (progn
9361 (setq beg (region-beginning) end (region-end))
9362 (goto-char beg)
9363 (setq column (org-table-current-column)
9364 beg (point-at-bol))
9365 (goto-char end)
9366 (setq end (point-at-bol 2)))
9367 (setq column (org-table-current-column)
9368 pos (point)
9369 tbeg (org-table-begin)
9370 tend (org-table-end))
9371 (if (re-search-backward org-table-hline-regexp tbeg t)
9372 (setq beg (point-at-bol 2))
9373 (goto-char tbeg)
9374 (setq beg (point-at-bol 1)))
9375 (goto-char pos)
9376 (if (re-search-forward org-table-hline-regexp tend t)
9377 (setq end (point-at-bol 1))
9378 (goto-char tend)
9379 (setq end (point-at-bol))))
9380 (setq beg (move-marker (make-marker) beg)
9381 end (move-marker (make-marker) end))
9382 (untabify beg end)
9383 (goto-char beg)
9384 (org-table-goto-column column)
9385 (skip-chars-backward "^|")
9386 (setq bcol (current-column))
9387 (org-table-goto-column (1+ column))
9388 (skip-chars-backward "^|")
9389 (setq ecol (1- (current-column)))
9390 (org-table-goto-column column)
9391 (setq lns (mapcar (lambda(x) (cons
9392 (org-sort-remove-invisible
9393 (nth (1- column)
9394 (org-split-string x "[ \t]*|[ \t]*")))
9396 (org-split-string (buffer-substring beg end) "\n")))
9397 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9398 (delete-region beg end)
9399 (move-marker beg nil)
9400 (move-marker end nil)
9401 (insert (mapconcat 'cdr lns "\n") "\n")
9402 (goto-line thisline)
9403 (org-table-goto-column thiscol)
9404 (message "%d lines sorted, based on column %d" (length lns) column)))
9406 ;; FIXME: maybe we will not need this? Table sorting is broken....
9407 (defun org-sort-remove-invisible (s)
9408 (remove-text-properties 0 (length s) org-rm-props s)
9409 (while (string-match org-bracket-link-regexp s)
9410 (setq s (replace-match (if (match-end 2)
9411 (match-string 3 s)
9412 (match-string 1 s)) t t s)))
9415 (defun org-table-cut-region (beg end)
9416 "Copy region in table to the clipboard and blank all relevant fields."
9417 (interactive "r")
9418 (org-table-copy-region beg end 'cut))
9420 (defun org-table-copy-region (beg end &optional cut)
9421 "Copy rectangular region in table to clipboard.
9422 A special clipboard is used which can only be accessed
9423 with `org-table-paste-rectangle'."
9424 (interactive "rP")
9425 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9426 region cols
9427 (rpl (if cut " " nil)))
9428 (goto-char beg)
9429 (org-table-check-inside-data-field)
9430 (setq l01 (org-current-line)
9431 c01 (org-table-current-column))
9432 (goto-char end)
9433 (org-table-check-inside-data-field)
9434 (setq l02 (org-current-line)
9435 c02 (org-table-current-column))
9436 (setq l1 (min l01 l02) l2 (max l01 l02)
9437 c1 (min c01 c02) c2 (max c01 c02))
9438 (catch 'exit
9439 (while t
9440 (catch 'nextline
9441 (if (> l1 l2) (throw 'exit t))
9442 (goto-line l1)
9443 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9444 (setq cols nil ic1 c1 ic2 c2)
9445 (while (< ic1 (1+ ic2))
9446 (push (org-table-get-field ic1 rpl) cols)
9447 (setq ic1 (1+ ic1)))
9448 (push (nreverse cols) region)
9449 (setq l1 (1+ l1)))))
9450 (setq org-table-clip (nreverse region))
9451 (if cut (org-table-align))
9452 org-table-clip))
9454 (defun org-table-paste-rectangle ()
9455 "Paste a rectangular region into a table.
9456 The upper right corner ends up in the current field. All involved fields
9457 will be overwritten. If the rectangle does not fit into the present table,
9458 the table is enlarged as needed. The process ignores horizontal separator
9459 lines."
9460 (interactive)
9461 (unless (and org-table-clip (listp org-table-clip))
9462 (error "First cut/copy a region to paste!"))
9463 (org-table-check-inside-data-field)
9464 (let* ((clip org-table-clip)
9465 (line (org-current-line))
9466 (col (org-table-current-column))
9467 (org-enable-table-editor t)
9468 (org-table-automatic-realign nil)
9469 c cols field)
9470 (while (setq cols (pop clip))
9471 (while (org-at-table-hline-p) (beginning-of-line 2))
9472 (if (not (org-at-table-p))
9473 (progn (end-of-line 0) (org-table-next-field)))
9474 (setq c col)
9475 (while (setq field (pop cols))
9476 (org-table-goto-column c nil 'force)
9477 (org-table-get-field nil field)
9478 (setq c (1+ c)))
9479 (beginning-of-line 2))
9480 (goto-line line)
9481 (org-table-goto-column col)
9482 (org-table-align)))
9484 (defun org-table-convert ()
9485 "Convert from `org-mode' table to table.el and back.
9486 Obviously, this only works within limits. When an Org-mode table is
9487 converted to table.el, all horizontal separator lines get lost, because
9488 table.el uses these as cell boundaries and has no notion of horizontal lines.
9489 A table.el table can be converted to an Org-mode table only if it does not
9490 do row or column spanning. Multiline cells will become multiple cells.
9491 Beware, Org-mode does not test if the table can be successfully converted - it
9492 blindly applies a recipe that works for simple tables."
9493 (interactive)
9494 (require 'table)
9495 (if (org-at-table.el-p)
9496 ;; convert to Org-mode table
9497 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9498 (end (move-marker (make-marker) (org-table-end t))))
9499 (table-unrecognize-region beg end)
9500 (goto-char beg)
9501 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9502 (replace-match ""))
9503 (goto-char beg))
9504 (if (org-at-table-p)
9505 ;; convert to table.el table
9506 (let ((beg (move-marker (make-marker) (org-table-begin)))
9507 (end (move-marker (make-marker) (org-table-end))))
9508 ;; first, get rid of all horizontal lines
9509 (goto-char beg)
9510 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9511 (replace-match ""))
9512 ;; insert a hline before first
9513 (goto-char beg)
9514 (org-table-insert-hline 'above)
9515 (beginning-of-line -1)
9516 ;; insert a hline after each line
9517 (while (progn (beginning-of-line 3) (< (point) end))
9518 (org-table-insert-hline))
9519 (goto-char beg)
9520 (setq end (move-marker end (org-table-end)))
9521 ;; replace "+" at beginning and ending of hlines
9522 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9523 (replace-match "\\1+-"))
9524 (goto-char beg)
9525 (while (re-search-forward "-|[ \t]*$" end t)
9526 (replace-match "-+"))
9527 (goto-char beg)))))
9529 (defun org-table-wrap-region (arg)
9530 "Wrap several fields in a column like a paragraph.
9531 This is useful if you'd like to spread the contents of a field over several
9532 lines, in order to keep the table compact.
9534 If there is an active region, and both point and mark are in the same column,
9535 the text in the column is wrapped to minimum width for the given number of
9536 lines. Generally, this makes the table more compact. A prefix ARG may be
9537 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9538 formats the selected text to two lines. If the region was longer than two
9539 lines, the remaining lines remain empty. A negative prefix argument reduces
9540 the current number of lines by that amount. The wrapped text is pasted back
9541 into the table. If you formatted it to more lines than it was before, fields
9542 further down in the table get overwritten - so you might need to make space in
9543 the table first.
9545 If there is no region, the current field is split at the cursor position and
9546 the text fragment to the right of the cursor is prepended to the field one
9547 line down.
9549 If there is no region, but you specify a prefix ARG, the current field gets
9550 blank, and the content is appended to the field above."
9551 (interactive "P")
9552 (org-table-check-inside-data-field)
9553 (if (org-region-active-p)
9554 ;; There is a region: fill as a paragraph
9555 (let* ((beg (region-beginning))
9556 (cline (save-excursion (goto-char beg) (org-current-line)))
9557 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9558 nlines)
9559 (org-table-cut-region (region-beginning) (region-end))
9560 (if (> (length (car org-table-clip)) 1)
9561 (error "Region must be limited to single column"))
9562 (setq nlines (if arg
9563 (if (< arg 1)
9564 (+ (length org-table-clip) arg)
9565 arg)
9566 (length org-table-clip)))
9567 (setq org-table-clip
9568 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9569 nil nlines)))
9570 (goto-line cline)
9571 (org-table-goto-column ccol)
9572 (org-table-paste-rectangle))
9573 ;; No region, split the current field at point
9574 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9575 (skip-chars-forward "^\r\n|"))
9576 (if arg
9577 ;; combine with field above
9578 (let ((s (org-table-blank-field))
9579 (col (org-table-current-column)))
9580 (beginning-of-line 0)
9581 (while (org-at-table-hline-p) (beginning-of-line 0))
9582 (org-table-goto-column col)
9583 (skip-chars-forward "^|")
9584 (skip-chars-backward " ")
9585 (insert " " (org-trim s))
9586 (org-table-align))
9587 ;; split field
9588 (if (looking-at "\\([^|]+\\)+|")
9589 (let ((s (match-string 1)))
9590 (replace-match " |")
9591 (goto-char (match-beginning 0))
9592 (org-table-next-row)
9593 (insert (org-trim s) " ")
9594 (org-table-align))
9595 (org-table-next-row)))))
9597 (defvar org-field-marker nil)
9599 (defun org-table-edit-field (arg)
9600 "Edit table field in a different window.
9601 This is mainly useful for fields that contain hidden parts.
9602 When called with a \\[universal-argument] prefix, just make the full field visible so that
9603 it can be edited in place."
9604 (interactive "P")
9605 (if arg
9606 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9607 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9608 (remove-text-properties b e '(org-cwidth t invisible t
9609 display t intangible t))
9610 (if (and (boundp 'font-lock-mode) font-lock-mode)
9611 (font-lock-fontify-block)))
9612 (let ((pos (move-marker (make-marker) (point)))
9613 (field (org-table-get-field))
9614 (cw (current-window-configuration))
9616 (org-switch-to-buffer-other-window "*Org tmp*")
9617 (erase-buffer)
9618 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9619 (let ((org-inhibit-startup t)) (org-mode))
9620 (goto-char (setq p (point-max)))
9621 (insert (org-trim field))
9622 (remove-text-properties p (point-max)
9623 '(invisible t org-cwidth t display t
9624 intangible t))
9625 (goto-char p)
9626 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9627 (org-set-local 'org-window-configuration cw)
9628 (org-set-local 'org-field-marker pos)
9629 (message "Edit and finish with C-c C-c"))))
9631 (defun org-table-finish-edit-field ()
9632 "Finish editing a table data field.
9633 Remove all newline characters, insert the result into the table, realign
9634 the table and kill the editing buffer."
9635 (let ((pos org-field-marker)
9636 (cw org-window-configuration)
9637 (cb (current-buffer))
9638 text)
9639 (goto-char (point-min))
9640 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9641 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9642 (replace-match " "))
9643 (setq text (org-trim (buffer-string)))
9644 (set-window-configuration cw)
9645 (kill-buffer cb)
9646 (select-window (get-buffer-window (marker-buffer pos)))
9647 (goto-char pos)
9648 (move-marker pos nil)
9649 (org-table-check-inside-data-field)
9650 (org-table-get-field nil text)
9651 (org-table-align)
9652 (message "New field value inserted")))
9654 (defun org-trim (s)
9655 "Remove whitespace at beginning and end of string."
9656 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9657 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9660 (defun org-wrap (string &optional width lines)
9661 "Wrap string to either a number of lines, or a width in characters.
9662 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9663 that costs. If there is a word longer than WIDTH, the text is actually
9664 wrapped to the length of that word.
9665 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9666 many lines, whatever width that takes.
9667 The return value is a list of lines, without newlines at the end."
9668 (let* ((words (org-split-string string "[ \t\n]+"))
9669 (maxword (apply 'max (mapcar 'org-string-width words)))
9670 w ll)
9671 (cond (width
9672 (org-do-wrap words (max maxword width)))
9673 (lines
9674 (setq w maxword)
9675 (setq ll (org-do-wrap words maxword))
9676 (if (<= (length ll) lines)
9678 (setq ll words)
9679 (while (> (length ll) lines)
9680 (setq w (1+ w))
9681 (setq ll (org-do-wrap words w)))
9682 ll))
9683 (t (error "Cannot wrap this")))))
9686 (defun org-do-wrap (words width)
9687 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9688 (let (lines line)
9689 (while words
9690 (setq line (pop words))
9691 (while (and words (< (+ (length line) (length (car words))) width))
9692 (setq line (concat line " " (pop words))))
9693 (setq lines (push line lines)))
9694 (nreverse lines)))
9696 (defun org-split-string (string &optional separators)
9697 "Splits STRING into substrings at SEPARATORS.
9698 No empty strings are returned if there are matches at the beginning
9699 and end of string."
9700 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9701 (start 0)
9702 notfirst
9703 (list nil))
9704 (while (and (string-match rexp string
9705 (if (and notfirst
9706 (= start (match-beginning 0))
9707 (< start (length string)))
9708 (1+ start) start))
9709 (< (match-beginning 0) (length string)))
9710 (setq notfirst t)
9711 (or (eq (match-beginning 0) 0)
9712 (and (eq (match-beginning 0) (match-end 0))
9713 (eq (match-beginning 0) start))
9714 (setq list
9715 (cons (substring string start (match-beginning 0))
9716 list)))
9717 (setq start (match-end 0)))
9718 (or (eq start (length string))
9719 (setq list
9720 (cons (substring string start)
9721 list)))
9722 (nreverse list)))
9724 (defun org-table-map-tables (function)
9725 "Apply FUNCTION to the start of all tables in the buffer."
9726 (save-excursion
9727 (save-restriction
9728 (widen)
9729 (goto-char (point-min))
9730 (while (re-search-forward org-table-any-line-regexp nil t)
9731 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9732 (beginning-of-line 1)
9733 (if (looking-at org-table-line-regexp)
9734 (save-excursion (funcall function)))
9735 (re-search-forward org-table-any-border-regexp nil 1))))
9736 (message "Mapping tables: done"))
9738 (defvar org-timecnt) ; dynamically scoped parameter
9740 (defun org-table-sum (&optional beg end nlast)
9741 "Sum numbers in region of current table column.
9742 The result will be displayed in the echo area, and will be available
9743 as kill to be inserted with \\[yank].
9745 If there is an active region, it is interpreted as a rectangle and all
9746 numbers in that rectangle will be summed. If there is no active
9747 region and point is located in a table column, sum all numbers in that
9748 column.
9750 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9751 numbers are assumed to be times as well (in decimal hours) and the
9752 numbers are added as such.
9754 If NLAST is a number, only the NLAST fields will actually be summed."
9755 (interactive)
9756 (save-excursion
9757 (let (col (org-timecnt 0) diff h m s org-table-clip)
9758 (cond
9759 ((and beg end)) ; beg and end given explicitly
9760 ((org-region-active-p)
9761 (setq beg (region-beginning) end (region-end)))
9763 (setq col (org-table-current-column))
9764 (goto-char (org-table-begin))
9765 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9766 (error "No table data"))
9767 (org-table-goto-column col)
9768 (setq beg (point))
9769 (goto-char (org-table-end))
9770 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9771 (error "No table data"))
9772 (org-table-goto-column col)
9773 (setq end (point))))
9774 (let* ((items (apply 'append (org-table-copy-region beg end)))
9775 (items1 (cond ((not nlast) items)
9776 ((>= nlast (length items)) items)
9777 (t (setq items (reverse items))
9778 (setcdr (nthcdr (1- nlast) items) nil)
9779 (nreverse items))))
9780 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9781 items1)))
9782 (res (apply '+ numbers))
9783 (sres (if (= org-timecnt 0)
9784 (format "%g" res)
9785 (setq diff (* 3600 res)
9786 h (floor (/ diff 3600)) diff (mod diff 3600)
9787 m (floor (/ diff 60)) diff (mod diff 60)
9788 s diff)
9789 (format "%d:%02d:%02d" h m s))))
9790 (kill-new sres)
9791 (if (interactive-p)
9792 (message "%s"
9793 (substitute-command-keys
9794 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9795 (length numbers) sres))))
9796 sres))))
9798 (defun org-table-get-number-for-summing (s)
9799 (let (n)
9800 (if (string-match "^ *|? *" s)
9801 (setq s (replace-match "" nil nil s)))
9802 (if (string-match " *|? *$" s)
9803 (setq s (replace-match "" nil nil s)))
9804 (setq n (string-to-number s))
9805 (cond
9806 ((and (string-match "0" s)
9807 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9808 ((string-match "\\`[ \t]+\\'" s) nil)
9809 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9810 (let ((h (string-to-number (or (match-string 1 s) "0")))
9811 (m (string-to-number (or (match-string 2 s) "0")))
9812 (s (string-to-number (or (match-string 4 s) "0"))))
9813 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9814 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9815 ((equal n 0) nil)
9816 (t n))))
9818 (defun org-table-current-field-formula (&optional key noerror)
9819 "Return the formula active for the current field.
9820 Assumes that specials are in place.
9821 If KEY is given, return the key to this formula.
9822 Otherwise return the formula preceeded with \"=\" or \":=\"."
9823 (let* ((name (car (rassoc (list (org-current-line)
9824 (org-table-current-column))
9825 org-table-named-field-locations)))
9826 (col (org-table-current-column))
9827 (scol (int-to-string col))
9828 (ref (format "@%d$%d" (org-table-current-dline) col))
9829 (stored-list (org-table-get-stored-formulas noerror))
9830 (ass (or (assoc name stored-list)
9831 (assoc ref stored-list)
9832 (assoc scol stored-list))))
9833 (if key
9834 (car ass)
9835 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9836 (cdr ass))))))
9838 (defun org-table-get-formula (&optional equation named)
9839 "Read a formula from the minibuffer, offer stored formula as default.
9840 When NAMED is non-nil, look for a named equation."
9841 (let* ((stored-list (org-table-get-stored-formulas))
9842 (name (car (rassoc (list (org-current-line)
9843 (org-table-current-column))
9844 org-table-named-field-locations)))
9845 (ref (format "@%d$%d" (org-table-current-dline)
9846 (org-table-current-column)))
9847 (refass (assoc ref stored-list))
9848 (scol (if named
9849 (if name name ref)
9850 (int-to-string (org-table-current-column))))
9851 (dummy (and (or name refass) (not named)
9852 (not (y-or-n-p "Replace field formula with column formula? " ))
9853 (error "Abort")))
9854 (name (or name ref))
9855 (org-table-may-need-update nil)
9856 (stored (cdr (assoc scol stored-list)))
9857 (eq (cond
9858 ((and stored equation (string-match "^ *=? *$" equation))
9859 stored)
9860 ((stringp equation)
9861 equation)
9862 (t (org-table-formula-from-user
9863 (read-string
9864 (org-table-formula-to-user
9865 (format "%s formula %s%s="
9866 (if named "Field" "Column")
9867 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9868 scol))
9869 (if stored (org-table-formula-to-user stored) "")
9870 'org-table-formula-history
9871 )))))
9872 mustsave)
9873 (when (not (string-match "\\S-" eq))
9874 ;; remove formula
9875 (setq stored-list (delq (assoc scol stored-list) stored-list))
9876 (org-table-store-formulas stored-list)
9877 (error "Formula removed"))
9878 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9879 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9880 (if (and name (not named))
9881 ;; We set the column equation, delete the named one.
9882 (setq stored-list (delq (assoc name stored-list) stored-list)
9883 mustsave t))
9884 (if stored
9885 (setcdr (assoc scol stored-list) eq)
9886 (setq stored-list (cons (cons scol eq) stored-list)))
9887 (if (or mustsave (not (equal stored eq)))
9888 (org-table-store-formulas stored-list))
9889 eq))
9891 (defun org-table-store-formulas (alist)
9892 "Store the list of formulas below the current table."
9893 (setq alist (sort alist 'org-table-formula-less-p))
9894 (save-excursion
9895 (goto-char (org-table-end))
9896 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9897 (progn
9898 ;; don't overwrite TBLFM, we might use text properties to store stuff
9899 (goto-char (match-beginning 2))
9900 (delete-region (match-beginning 2) (match-end 0)))
9901 (insert "#+TBLFM:"))
9902 (insert " "
9903 (mapconcat (lambda (x)
9904 (concat
9905 (if (equal (string-to-char (car x)) ?@) "" "$")
9906 (car x) "=" (cdr x)))
9907 alist "::")
9908 "\n")))
9910 (defsubst org-table-formula-make-cmp-string (a)
9911 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9912 (concat
9913 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9914 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9915 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9917 (defun org-table-formula-less-p (a b)
9918 "Compare two formulas for sorting."
9919 (let ((as (org-table-formula-make-cmp-string (car a)))
9920 (bs (org-table-formula-make-cmp-string (car b))))
9921 (and as bs (string< as bs))))
9923 (defun org-table-get-stored-formulas (&optional noerror)
9924 "Return an alist with the stored formulas directly after current table."
9925 (interactive)
9926 (let (scol eq eq-alist strings string seen)
9927 (save-excursion
9928 (goto-char (org-table-end))
9929 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9930 (setq strings (org-split-string (match-string 2) " *:: *"))
9931 (while (setq string (pop strings))
9932 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9933 (setq scol (if (match-end 2)
9934 (match-string 2 string)
9935 (match-string 1 string))
9936 eq (match-string 3 string)
9937 eq-alist (cons (cons scol eq) eq-alist))
9938 (if (member scol seen)
9939 (if noerror
9940 (progn
9941 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9942 (ding)
9943 (sit-for 2))
9944 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9945 (push scol seen))))))
9946 (nreverse eq-alist)))
9948 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9949 "Modify the equations after the table structure has been edited.
9950 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9951 For all numbers larger than LIMIT, shift them by DELTA."
9952 (save-excursion
9953 (goto-char (org-table-end))
9954 (when (looking-at "#\\+TBLFM:")
9955 (let ((re (concat key "\\([0-9]+\\)"))
9956 (re2
9957 (when remove
9958 (if (equal key "$")
9959 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9960 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9961 s n a)
9962 (when remove
9963 (while (re-search-forward re2 (point-at-eol) t)
9964 (replace-match "")))
9965 (while (re-search-forward re (point-at-eol) t)
9966 (setq s (match-string 1) n (string-to-number s))
9967 (cond
9968 ((setq a (assoc s replace))
9969 (replace-match (concat key (cdr a)) t t))
9970 ((and limit (> n limit))
9971 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9973 (defun org-table-get-specials ()
9974 "Get the column names and local parameters for this table."
9975 (save-excursion
9976 (let ((beg (org-table-begin)) (end (org-table-end))
9977 names name fields fields1 field cnt
9978 c v l line col types dlines hlines)
9979 (setq org-table-column-names nil
9980 org-table-local-parameters nil
9981 org-table-named-field-locations nil
9982 org-table-current-begin-line nil
9983 org-table-current-begin-pos nil
9984 org-table-current-line-types nil)
9985 (goto-char beg)
9986 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9987 (setq names (org-split-string (match-string 1) " *| *")
9988 cnt 1)
9989 (while (setq name (pop names))
9990 (setq cnt (1+ cnt))
9991 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9992 (push (cons name (int-to-string cnt)) org-table-column-names))))
9993 (setq org-table-column-names (nreverse org-table-column-names))
9994 (setq org-table-column-name-regexp
9995 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9996 (goto-char beg)
9997 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9998 (setq fields (org-split-string (match-string 1) " *| *"))
9999 (while (setq field (pop fields))
10000 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10001 (push (cons (match-string 1 field) (match-string 2 field))
10002 org-table-local-parameters))))
10003 (goto-char beg)
10004 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10005 (setq c (match-string 1)
10006 fields (org-split-string (match-string 2) " *| *"))
10007 (save-excursion
10008 (beginning-of-line (if (equal c "_") 2 0))
10009 (setq line (org-current-line) col 1)
10010 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10011 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10012 (while (and fields1 (setq field (pop fields)))
10013 (setq v (pop fields1) col (1+ col))
10014 (when (and (stringp field) (stringp v)
10015 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10016 (push (cons field v) org-table-local-parameters)
10017 (push (list field line col) org-table-named-field-locations))))
10018 ;; Analyse the line types
10019 (goto-char beg)
10020 (setq org-table-current-begin-line (org-current-line)
10021 org-table-current-begin-pos (point)
10022 l org-table-current-begin-line)
10023 (while (looking-at "[ \t]*|\\(-\\)?")
10024 (push (if (match-end 1) 'hline 'dline) types)
10025 (if (match-end 1) (push l hlines) (push l dlines))
10026 (beginning-of-line 2)
10027 (setq l (1+ l)))
10028 (setq org-table-current-line-types (apply 'vector (nreverse types))
10029 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10030 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10032 (defun org-table-maybe-eval-formula ()
10033 "Check if the current field starts with \"=\" or \":=\".
10034 If yes, store the formula and apply it."
10035 ;; We already know we are in a table. Get field will only return a formula
10036 ;; when appropriate. It might return a separator line, but no problem.
10037 (when org-table-formula-evaluate-inline
10038 (let* ((field (org-trim (or (org-table-get-field) "")))
10039 named eq)
10040 (when (string-match "^:?=\\(.*\\)" field)
10041 (setq named (equal (string-to-char field) ?:)
10042 eq (match-string 1 field))
10043 (if (or (fboundp 'calc-eval)
10044 (equal (substring eq 0 (min 2 (length eq))) "'("))
10045 (org-table-eval-formula (if named '(4) nil)
10046 (org-table-formula-from-user eq))
10047 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10049 (defvar org-recalc-commands nil
10050 "List of commands triggering the recalculation of a line.
10051 Will be filled automatically during use.")
10053 (defvar org-recalc-marks
10054 '((" " . "Unmarked: no special line, no automatic recalculation")
10055 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10056 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10057 ("!" . "Column name definition line. Reference in formula as $name.")
10058 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10059 ("_" . "Names for values in row below this one.")
10060 ("^" . "Names for values in row above this one.")))
10062 (defun org-table-rotate-recalc-marks (&optional newchar)
10063 "Rotate the recalculation mark in the first column.
10064 If in any row, the first field is not consistent with a mark,
10065 insert a new column for the markers.
10066 When there is an active region, change all the lines in the region,
10067 after prompting for the marking character.
10068 After each change, a message will be displayed indicating the meaning
10069 of the new mark."
10070 (interactive)
10071 (unless (org-at-table-p) (error "Not at a table"))
10072 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10073 (beg (org-table-begin))
10074 (end (org-table-end))
10075 (l (org-current-line))
10076 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10077 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10078 (have-col
10079 (save-excursion
10080 (goto-char beg)
10081 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10082 (col (org-table-current-column))
10083 (forcenew (car (assoc newchar org-recalc-marks)))
10084 epos new)
10085 (when l1
10086 (message "Change region to what mark? Type # * ! $ or SPC: ")
10087 (setq newchar (char-to-string (read-char-exclusive))
10088 forcenew (car (assoc newchar org-recalc-marks))))
10089 (if (and newchar (not forcenew))
10090 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10091 newchar))
10092 (if l1 (goto-line l1))
10093 (save-excursion
10094 (beginning-of-line 1)
10095 (unless (looking-at org-table-dataline-regexp)
10096 (error "Not at a table data line")))
10097 (unless have-col
10098 (org-table-goto-column 1)
10099 (org-table-insert-column)
10100 (org-table-goto-column (1+ col)))
10101 (setq epos (point-at-eol))
10102 (save-excursion
10103 (beginning-of-line 1)
10104 (org-table-get-field
10105 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10106 (concat " "
10107 (setq new (or forcenew
10108 (cadr (member (match-string 1) marks))))
10109 " ")
10110 " # ")))
10111 (if (and l1 l2)
10112 (progn
10113 (goto-line l1)
10114 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10115 (and (looking-at org-table-dataline-regexp)
10116 (org-table-get-field 1 (concat " " new " "))))
10117 (goto-line l1)))
10118 (if (not (= epos (point-at-eol))) (org-table-align))
10119 (goto-line l)
10120 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10122 (defun org-table-maybe-recalculate-line ()
10123 "Recompute the current line if marked for it, and if we haven't just done it."
10124 (interactive)
10125 (and org-table-allow-automatic-line-recalculation
10126 (not (and (memq last-command org-recalc-commands)
10127 (equal org-last-recalc-line (org-current-line))))
10128 (save-excursion (beginning-of-line 1)
10129 (looking-at org-table-auto-recalculate-regexp))
10130 (org-table-recalculate) t))
10132 (defvar org-table-formula-debug nil
10133 "Non-nil means, debug table formulas.
10134 When nil, simply write \"#ERROR\" in corrupted fields.")
10135 (make-variable-buffer-local 'org-table-formula-debug)
10137 (defvar modes)
10138 (defsubst org-set-calc-mode (var &optional value)
10139 (if (stringp var)
10140 (setq var (assoc var '(("D" calc-angle-mode deg)
10141 ("R" calc-angle-mode rad)
10142 ("F" calc-prefer-frac t)
10143 ("S" calc-symbolic-mode t)))
10144 value (nth 2 var) var (nth 1 var)))
10145 (if (memq var modes)
10146 (setcar (cdr (memq var modes)) value)
10147 (cons var (cons value modes)))
10148 modes)
10150 (defun org-table-eval-formula (&optional arg equation
10151 suppress-align suppress-const
10152 suppress-store suppress-analysis)
10153 "Replace the table field value at the cursor by the result of a calculation.
10155 This function makes use of Dave Gillespie's Calc package, in my view the
10156 most exciting program ever written for GNU Emacs. So you need to have Calc
10157 installed in order to use this function.
10159 In a table, this command replaces the value in the current field with the
10160 result of a formula. It also installs the formula as the \"current\" column
10161 formula, by storing it in a special line below the table. When called
10162 with a `C-u' prefix, the current field must ba a named field, and the
10163 formula is installed as valid in only this specific field.
10165 When called with two `C-u' prefixes, insert the active equation
10166 for the field back into the current field, so that it can be
10167 edited there. This is useful in order to use \\[org-table-show-reference]
10168 to check the referenced fields.
10170 When called, the command first prompts for a formula, which is read in
10171 the minibuffer. Previously entered formulas are available through the
10172 history list, and the last used formula is offered as a default.
10173 These stored formulas are adapted correctly when moving, inserting, or
10174 deleting columns with the corresponding commands.
10176 The formula can be any algebraic expression understood by the Calc package.
10177 For details, see the Org-mode manual.
10179 This function can also be called from Lisp programs and offers
10180 additional arguments: EQUATION can be the formula to apply. If this
10181 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10182 used to speed-up recursive calls by by-passing unnecessary aligns.
10183 SUPPRESS-CONST suppresses the interpretation of constants in the
10184 formula, assuming that this has been done already outside the function.
10185 SUPPRESS-STORE means the formula should not be stored, either because
10186 it is already stored, or because it is a modified equation that should
10187 not overwrite the stored one."
10188 (interactive "P")
10189 (org-table-check-inside-data-field)
10190 (or suppress-analysis (org-table-get-specials))
10191 (if (equal arg '(16))
10192 (let ((eq (org-table-current-field-formula)))
10193 (or eq (error "No equation active for current field"))
10194 (org-table-get-field nil eq)
10195 (org-table-align)
10196 (setq org-table-may-need-update t))
10197 (let* (fields
10198 (ndown (if (integerp arg) arg 1))
10199 (org-table-automatic-realign nil)
10200 (case-fold-search nil)
10201 (down (> ndown 1))
10202 (formula (if (and equation suppress-store)
10203 equation
10204 (org-table-get-formula equation (equal arg '(4)))))
10205 (n0 (org-table-current-column))
10206 (modes (copy-sequence org-calc-default-modes))
10207 (numbers nil) ; was a variable, now fixed default
10208 (keep-empty nil)
10209 n form form0 bw fmt x ev orig c lispp literal)
10210 ;; Parse the format string. Since we have a lot of modes, this is
10211 ;; a lot of work. However, I think calc still uses most of the time.
10212 (if (string-match ";" formula)
10213 (let ((tmp (org-split-string formula ";")))
10214 (setq formula (car tmp)
10215 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10216 (nth 1 tmp)))
10217 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10218 (setq c (string-to-char (match-string 1 fmt))
10219 n (string-to-number (match-string 2 fmt)))
10220 (if (= c ?p)
10221 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10222 (setq modes (org-set-calc-mode
10223 'calc-float-format
10224 (list (cdr (assoc c '((?n . float) (?f . fix)
10225 (?s . sci) (?e . eng))))
10226 n))))
10227 (setq fmt (replace-match "" t t fmt)))
10228 (if (string-match "[NT]" fmt)
10229 (setq numbers (equal (match-string 0 fmt) "N")
10230 fmt (replace-match "" t t fmt)))
10231 (if (string-match "L" fmt)
10232 (setq literal t
10233 fmt (replace-match "" t t fmt)))
10234 (if (string-match "E" fmt)
10235 (setq keep-empty t
10236 fmt (replace-match "" t t fmt)))
10237 (while (string-match "[DRFS]" fmt)
10238 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10239 (setq fmt (replace-match "" t t fmt)))
10240 (unless (string-match "\\S-" fmt)
10241 (setq fmt nil))))
10242 (if (and (not suppress-const) org-table-formula-use-constants)
10243 (setq formula (org-table-formula-substitute-names formula)))
10244 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10245 (while (> ndown 0)
10246 (setq fields (org-split-string
10247 (org-no-properties
10248 (buffer-substring (point-at-bol) (point-at-eol)))
10249 " *| *"))
10250 (if (eq numbers t)
10251 (setq fields (mapcar
10252 (lambda (x) (number-to-string (string-to-number x)))
10253 fields)))
10254 (setq ndown (1- ndown))
10255 (setq form (copy-sequence formula)
10256 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10257 (if (and lispp literal) (setq lispp 'literal))
10258 ;; Check for old vertical references
10259 (setq form (org-rewrite-old-row-references form))
10260 ;; Insert complex ranges
10261 (while (string-match org-table-range-regexp form)
10262 (setq form
10263 (replace-match
10264 (save-match-data
10265 (org-table-make-reference
10266 (org-table-get-range (match-string 0 form) nil n0)
10267 keep-empty numbers lispp))
10268 t t form)))
10269 ;; Insert simple ranges
10270 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10271 (setq form
10272 (replace-match
10273 (save-match-data
10274 (org-table-make-reference
10275 (org-sublist
10276 fields (string-to-number (match-string 1 form))
10277 (string-to-number (match-string 2 form)))
10278 keep-empty numbers lispp))
10279 t t form)))
10280 (setq form0 form)
10281 ;; Insert the references to fields in same row
10282 (while (string-match "\\$\\([0-9]+\\)" form)
10283 (setq n (string-to-number (match-string 1 form))
10284 x (nth (1- (if (= n 0) n0 n)) fields))
10285 (unless x (error "Invalid field specifier \"%s\""
10286 (match-string 0 form)))
10287 (setq form (replace-match
10288 (save-match-data
10289 (org-table-make-reference x nil numbers lispp))
10290 t t form)))
10292 (if lispp
10293 (setq ev (condition-case nil
10294 (eval (eval (read form)))
10295 (error "#ERROR"))
10296 ev (if (numberp ev) (number-to-string ev) ev))
10297 (or (fboundp 'calc-eval)
10298 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10299 (setq ev (calc-eval (cons form modes)
10300 (if numbers 'num))))
10302 (when org-table-formula-debug
10303 (with-output-to-temp-buffer "*Substitution History*"
10304 (princ (format "Substitution history of formula
10305 Orig: %s
10306 $xyz-> %s
10307 @r$c-> %s
10308 $1-> %s\n" orig formula form0 form))
10309 (if (listp ev)
10310 (princ (format " %s^\nError: %s"
10311 (make-string (car ev) ?\-) (nth 1 ev)))
10312 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10313 ev (or fmt "NONE")
10314 (if fmt (format fmt (string-to-number ev)) ev)))))
10315 (setq bw (get-buffer-window "*Substitution History*"))
10316 (shrink-window-if-larger-than-buffer bw)
10317 (unless (and (interactive-p) (not ndown))
10318 (unless (let (inhibit-redisplay)
10319 (y-or-n-p "Debugging Formula. Continue to next? "))
10320 (org-table-align)
10321 (error "Abort"))
10322 (delete-window bw)
10323 (message "")))
10324 (if (listp ev) (setq fmt nil ev "#ERROR"))
10325 (org-table-justify-field-maybe
10326 (if fmt (format fmt (string-to-number ev)) ev))
10327 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10328 (call-interactively 'org-return)
10329 (setq ndown 0)))
10330 (and down (org-table-maybe-recalculate-line))
10331 (or suppress-align (and org-table-may-need-update
10332 (org-table-align))))))
10334 (defun org-table-put-field-property (prop value)
10335 (save-excursion
10336 (put-text-property (progn (skip-chars-backward "^|") (point))
10337 (progn (skip-chars-forward "^|") (point))
10338 prop value)))
10340 (defun org-table-get-range (desc &optional tbeg col highlight)
10341 "Get a calc vector from a column, accorting to descriptor DESC.
10342 Optional arguments TBEG and COL can give the beginning of the table and
10343 the current column, to avoid unnecessary parsing.
10344 HIGHLIGHT means, just highlight the range."
10345 (if (not (equal (string-to-char desc) ?@))
10346 (setq desc (concat "@" desc)))
10347 (save-excursion
10348 (or tbeg (setq tbeg (org-table-begin)))
10349 (or col (setq col (org-table-current-column)))
10350 (let ((thisline (org-current-line))
10351 beg end c1 c2 r1 r2 rangep tmp)
10352 (unless (string-match org-table-range-regexp desc)
10353 (error "Invalid table range specifier `%s'" desc))
10354 (setq rangep (match-end 3)
10355 r1 (and (match-end 1) (match-string 1 desc))
10356 r2 (and (match-end 4) (match-string 4 desc))
10357 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10358 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10360 (and c1 (setq c1 (+ (string-to-number c1)
10361 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10362 (and c2 (setq c2 (+ (string-to-number c2)
10363 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10364 (if (equal r1 "") (setq r1 nil))
10365 (if (equal r2 "") (setq r2 nil))
10366 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10367 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10368 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10369 (if (not r1) (setq r1 thisline))
10370 (if (not r2) (setq r2 thisline))
10371 (if (not c1) (setq c1 col))
10372 (if (not c2) (setq c2 col))
10373 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10374 ;; just one field
10375 (progn
10376 (goto-line r1)
10377 (while (not (looking-at org-table-dataline-regexp))
10378 (beginning-of-line 2))
10379 (prog1 (org-trim (org-table-get-field c1))
10380 (if highlight (org-table-highlight-rectangle (point) (point)))))
10381 ;; A range, return a vector
10382 ;; First sort the numbers to get a regular ractangle
10383 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10384 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10385 (goto-line r1)
10386 (while (not (looking-at org-table-dataline-regexp))
10387 (beginning-of-line 2))
10388 (org-table-goto-column c1)
10389 (setq beg (point))
10390 (goto-line r2)
10391 (while (not (looking-at org-table-dataline-regexp))
10392 (beginning-of-line 0))
10393 (org-table-goto-column c2)
10394 (setq end (point))
10395 (if highlight
10396 (org-table-highlight-rectangle
10397 beg (progn (skip-chars-forward "^|\n") (point))))
10398 ;; return string representation of calc vector
10399 (mapcar 'org-trim
10400 (apply 'append (org-table-copy-region beg end)))))))
10402 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10403 "Analyze descriptor DESC and retrieve the corresponding line number.
10404 The cursor is currently in line CLINE, the table begins in line BLINE,
10405 and TABLE is a vector with line types."
10406 (if (string-match "^[0-9]+$" desc)
10407 (aref org-table-dlines (string-to-number desc))
10408 (setq cline (or cline (org-current-line))
10409 bline (or bline org-table-current-begin-line)
10410 table (or table org-table-current-line-types))
10411 (if (or
10412 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10413 ;; 1 2 3 4 5 6
10414 (and (not (match-end 3)) (not (match-end 6)))
10415 (and (match-end 3) (match-end 6) (not (match-end 5))))
10416 (error "invalid row descriptor `%s'" desc))
10417 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10418 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10419 (odir (and (match-end 5) (match-string 5 desc)))
10420 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10421 (i (- cline bline))
10422 (rel (and (match-end 6)
10423 (or (and (match-end 1) (not (match-end 3)))
10424 (match-end 5)))))
10425 (if (and hn (not hdir))
10426 (progn
10427 (setq i 0 hdir "+")
10428 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10429 (if (and (not hn) on (not odir))
10430 (error "should never happen");;(aref org-table-dlines on)
10431 (if (and hn (> hn 0))
10432 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10433 (if on
10434 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10435 (+ bline i)))))
10437 (defun org-find-row-type (table i type backwards relative n)
10438 (let ((l (length table)))
10439 (while (> n 0)
10440 (while (and (setq i (+ i (if backwards -1 1)))
10441 (>= i 0) (< i l)
10442 (not (eq (aref table i) type))
10443 (if (and relative (eq (aref table i) 'hline))
10444 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10445 t)))
10446 (setq n (1- n)))
10447 (if (or (< i 0) (>= i l))
10448 (error "Row descriptior leads outside table")
10449 i)))
10451 (defun org-rewrite-old-row-references (s)
10452 (if (string-match "&[-+0-9I]" s)
10453 (error "Formula contains old &row reference, please rewrite using @-syntax")
10456 (defun org-table-make-reference (elements keep-empty numbers lispp)
10457 "Convert list ELEMENTS to something appropriate to insert into formula.
10458 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10459 NUMBERS indicates that everything should be converted to numbers.
10460 LISPP means to return something appropriate for a Lisp list."
10461 (if (stringp elements) ; just a single val
10462 (if lispp
10463 (if (eq lispp 'literal)
10464 elements
10465 (prin1-to-string (if numbers (string-to-number elements) elements)))
10466 (if (equal elements "") (setq elements "0"))
10467 (if numbers (number-to-string (string-to-number elements)) elements))
10468 (unless keep-empty
10469 (setq elements
10470 (delq nil
10471 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10472 elements))))
10473 (setq elements (or elements '("0")))
10474 (if lispp
10475 (mapconcat
10476 (lambda (x)
10477 (if (eq lispp 'literal)
10479 (prin1-to-string (if numbers (string-to-number x) x))))
10480 elements " ")
10481 (concat "[" (mapconcat
10482 (lambda (x)
10483 (if numbers (number-to-string (string-to-number x)) x))
10484 elements
10485 ",") "]"))))
10487 (defun org-table-recalculate (&optional all noalign)
10488 "Recalculate the current table line by applying all stored formulas.
10489 With prefix arg ALL, do this for all lines in the table."
10490 (interactive "P")
10491 (or (memq this-command org-recalc-commands)
10492 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10493 (unless (org-at-table-p) (error "Not at a table"))
10494 (if (equal all '(16))
10495 (org-table-iterate)
10496 (org-table-get-specials)
10497 (let* ((eqlist (sort (org-table-get-stored-formulas)
10498 (lambda (a b) (string< (car a) (car b)))))
10499 (inhibit-redisplay (not debug-on-error))
10500 (line-re org-table-dataline-regexp)
10501 (thisline (org-current-line))
10502 (thiscol (org-table-current-column))
10503 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10504 ;; Insert constants in all formulas
10505 (setq eqlist
10506 (mapcar (lambda (x)
10507 (setcdr x (org-table-formula-substitute-names (cdr x)))
10509 eqlist))
10510 ;; Split the equation list
10511 (while (setq eq (pop eqlist))
10512 (if (<= (string-to-char (car eq)) ?9)
10513 (push eq eqlnum)
10514 (push eq eqlname)))
10515 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10516 (if all
10517 (progn
10518 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10519 (goto-char (setq beg (org-table-begin)))
10520 (if (re-search-forward org-table-calculate-mark-regexp end t)
10521 ;; This is a table with marked lines, compute selected lines
10522 (setq line-re org-table-recalculate-regexp)
10523 ;; Move forward to the first non-header line
10524 (if (and (re-search-forward org-table-dataline-regexp end t)
10525 (re-search-forward org-table-hline-regexp end t)
10526 (re-search-forward org-table-dataline-regexp end t))
10527 (setq beg (match-beginning 0))
10528 nil))) ;; just leave beg where it is
10529 (setq beg (point-at-bol)
10530 end (move-marker (make-marker) (1+ (point-at-eol)))))
10531 (goto-char beg)
10532 (and all (message "Re-applying formulas to full table..."))
10534 ;; First find the named fields, and mark them untouchanble
10535 (remove-text-properties beg end '(org-untouchable t))
10536 (while (setq eq (pop eqlname))
10537 (setq name (car eq)
10538 a (assoc name org-table-named-field-locations))
10539 (and (not a)
10540 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10541 (setq a (list name
10542 (aref org-table-dlines
10543 (string-to-number (match-string 1 name)))
10544 (string-to-number (match-string 2 name)))))
10545 (when (and a (or all (equal (nth 1 a) thisline)))
10546 (message "Re-applying formula to field: %s" name)
10547 (goto-line (nth 1 a))
10548 (org-table-goto-column (nth 2 a))
10549 (push (append a (list (cdr eq))) eqlname1)
10550 (org-table-put-field-property :org-untouchable t)))
10552 ;; Now evauluate the column formulas, but skip fields covered by
10553 ;; field formulas
10554 (goto-char beg)
10555 (while (re-search-forward line-re end t)
10556 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10557 ;; Unprotected line, recalculate
10558 (and all (message "Re-applying formulas to full table...(line %d)"
10559 (setq cnt (1+ cnt))))
10560 (setq org-last-recalc-line (org-current-line))
10561 (setq eql eqlnum)
10562 (while (setq entry (pop eql))
10563 (goto-line org-last-recalc-line)
10564 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10565 (unless (get-text-property (point) :org-untouchable)
10566 (org-table-eval-formula nil (cdr entry)
10567 'noalign 'nocst 'nostore 'noanalysis)))))
10569 ;; Now evaluate the field formulas
10570 (while (setq eq (pop eqlname1))
10571 (message "Re-applying formula to field: %s" (car eq))
10572 (goto-line (nth 1 eq))
10573 (org-table-goto-column (nth 2 eq))
10574 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10575 'nostore 'noanalysis))
10577 (goto-line thisline)
10578 (org-table-goto-column thiscol)
10579 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10580 (or noalign (and org-table-may-need-update (org-table-align))
10581 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10583 ;; back to initial position
10584 (message "Re-applying formulas...done")
10585 (goto-line thisline)
10586 (org-table-goto-column thiscol)
10587 (or noalign (and org-table-may-need-update (org-table-align))
10588 (and all (message "Re-applying formulas...done"))))))
10590 (defun org-table-iterate (&optional arg)
10591 "Recalculate the table until it does not change anymore."
10592 (interactive "P")
10593 (let ((imax (if arg (prefix-numeric-value arg) 10))
10594 (i 0)
10595 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10596 thistbl)
10597 (catch 'exit
10598 (while (< i imax)
10599 (setq i (1+ i))
10600 (org-table-recalculate 'all)
10601 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10602 (if (not (string= lasttbl thistbl))
10603 (setq lasttbl thistbl)
10604 (if (> i 1)
10605 (message "Convergence after %d iterations" i)
10606 (message "Table was already stable"))
10607 (throw 'exit t)))
10608 (error "No convergence after %d iterations" i))))
10610 (defun org-table-formula-substitute-names (f)
10611 "Replace $const with values in string F."
10612 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10613 ;; First, check for column names
10614 (while (setq start (string-match org-table-column-name-regexp f start))
10615 (setq start (1+ start))
10616 (setq a (assoc (match-string 1 f) org-table-column-names))
10617 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10618 ;; Parameters and constants
10619 (setq start 0)
10620 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10621 (setq start (1+ start))
10622 (if (setq a (save-match-data
10623 (org-table-get-constant (match-string 1 f))))
10624 (setq f (replace-match
10625 (concat (if pp "(") a (if pp ")")) t t f))))
10626 (if org-table-formula-debug
10627 (put-text-property 0 (length f) :orig-formula f1 f))
10630 (defun org-table-get-constant (const)
10631 "Find the value for a parameter or constant in a formula.
10632 Parameters get priority."
10633 (or (cdr (assoc const org-table-local-parameters))
10634 (cdr (assoc const org-table-formula-constants-local))
10635 (cdr (assoc const org-table-formula-constants))
10636 (and (fboundp 'constants-get) (constants-get const))
10637 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10638 (org-entry-get nil (substring const 5) 'inherit))
10639 "#UNDEFINED_NAME"))
10641 (defvar org-table-fedit-map
10642 (let ((map (make-sparse-keymap)))
10643 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10644 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10645 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10646 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10647 (org-defkey map "\C-c?" 'org-table-show-reference)
10648 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10649 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10650 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10651 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10652 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10653 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10654 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10655 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10656 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10657 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10658 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10659 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10660 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10661 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10662 map))
10664 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10665 '("Edit-Formulas"
10666 ["Finish and Install" org-table-fedit-finish t]
10667 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10668 ["Abort" org-table-fedit-abort t]
10669 "--"
10670 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10671 ["Complete Lisp Symbol" lisp-complete-symbol t]
10672 "--"
10673 "Shift Reference at Point"
10674 ["Up" org-table-fedit-ref-up t]
10675 ["Down" org-table-fedit-ref-down t]
10676 ["Left" org-table-fedit-ref-left t]
10677 ["Right" org-table-fedit-ref-right t]
10679 "Change Test Row for Column Formulas"
10680 ["Up" org-table-fedit-line-up t]
10681 ["Down" org-table-fedit-line-down t]
10682 "--"
10683 ["Scroll Table Window" org-table-fedit-scroll t]
10684 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10685 ["Show Table Grid" org-table-fedit-toggle-coordinates
10686 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10687 org-table-overlay-coordinates)]
10688 "--"
10689 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10690 :style toggle :selected org-table-buffer-is-an]))
10692 (defvar org-pos)
10694 (defun org-table-edit-formulas ()
10695 "Edit the formulas of the current table in a separate buffer."
10696 (interactive)
10697 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10698 (beginning-of-line 0))
10699 (unless (org-at-table-p) (error "Not at a table"))
10700 (org-table-get-specials)
10701 (let ((key (org-table-current-field-formula 'key 'noerror))
10702 (eql (sort (org-table-get-stored-formulas 'noerror)
10703 'org-table-formula-less-p))
10704 (pos (move-marker (make-marker) (point)))
10705 (startline 1)
10706 (wc (current-window-configuration))
10707 (titles '((column . "# Column Formulas\n")
10708 (field . "# Field Formulas\n")
10709 (named . "# Named Field Formulas\n")))
10710 entry s type title)
10711 (org-switch-to-buffer-other-window "*Edit Formulas*")
10712 (erase-buffer)
10713 ;; Keep global-font-lock-mode from turning on font-lock-mode
10714 (let ((font-lock-global-modes '(not fundamental-mode)))
10715 (fundamental-mode))
10716 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10717 (org-set-local 'org-pos pos)
10718 (org-set-local 'org-window-configuration wc)
10719 (use-local-map org-table-fedit-map)
10720 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10721 (easy-menu-add org-table-fedit-menu)
10722 (setq startline (org-current-line))
10723 (while (setq entry (pop eql))
10724 (setq type (cond
10725 ((equal (string-to-char (car entry)) ?@) 'field)
10726 ((string-match "^[0-9]" (car entry)) 'column)
10727 (t 'named)))
10728 (when (setq title (assq type titles))
10729 (or (bobp) (insert "\n"))
10730 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10731 (setq titles (delq title titles)))
10732 (if (equal key (car entry)) (setq startline (org-current-line)))
10733 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10734 (car entry) " = " (cdr entry) "\n"))
10735 (remove-text-properties 0 (length s) '(face nil) s)
10736 (insert s))
10737 (if (eq org-table-use-standard-references t)
10738 (org-table-fedit-toggle-ref-type))
10739 (goto-line startline)
10740 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10742 (defun org-table-fedit-post-command ()
10743 (when (not (memq this-command '(lisp-complete-symbol)))
10744 (let ((win (selected-window)))
10745 (save-excursion
10746 (condition-case nil
10747 (org-table-show-reference)
10748 (error nil))
10749 (select-window win)))))
10751 (defun org-table-formula-to-user (s)
10752 "Convert a formula from internal to user representation."
10753 (if (eq org-table-use-standard-references t)
10754 (org-table-convert-refs-to-an s)
10757 (defun org-table-formula-from-user (s)
10758 "Convert a formula from user to internal representation."
10759 (if org-table-use-standard-references
10760 (org-table-convert-refs-to-rc s)
10763 (defun org-table-convert-refs-to-rc (s)
10764 "Convert spreadsheet references from AB7 to @7$28.
10765 Works for single references, but also for entire formulas and even the
10766 full TBLFM line."
10767 (let ((start 0))
10768 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10769 (cond
10770 ((match-end 3)
10771 ;; format match, just advance
10772 (setq start (match-end 0)))
10773 ((and (> (match-beginning 0) 0)
10774 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10775 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10776 ;; 3.e5 or something like this.
10777 (setq start (match-end 0)))
10779 (setq start (match-beginning 0)
10780 s (replace-match
10781 (if (equal (match-string 2 s) "&")
10782 (format "$%d" (org-letters-to-number (match-string 1 s)))
10783 (format "@%d$%d"
10784 (string-to-number (match-string 2 s))
10785 (org-letters-to-number (match-string 1 s))))
10786 t t s)))))
10789 (defun org-table-convert-refs-to-an (s)
10790 "Convert spreadsheet references from to @7$28 to AB7.
10791 Works for single references, but also for entire formulas and even the
10792 full TBLFM line."
10793 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10794 (setq s (replace-match
10795 (format "%s%d"
10796 (org-number-to-letters
10797 (string-to-number (match-string 2 s)))
10798 (string-to-number (match-string 1 s)))
10799 t t s)))
10800 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10801 (setq s (replace-match (concat "\\1"
10802 (org-number-to-letters
10803 (string-to-number (match-string 2 s))) "&")
10804 t nil s)))
10807 (defun org-letters-to-number (s)
10808 "Convert a base 26 number represented by letters into an integer.
10809 For example: AB -> 28."
10810 (let ((n 0))
10811 (setq s (upcase s))
10812 (while (> (length s) 0)
10813 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10814 s (substring s 1)))
10817 (defun org-number-to-letters (n)
10818 "Convert an integer into a base 26 number represented by letters.
10819 For example: 28 -> AB."
10820 (let ((s ""))
10821 (while (> n 0)
10822 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10823 n (/ (1- n) 26)))
10826 (defun org-table-fedit-convert-buffer (function)
10827 "Convert all references in this buffer, using FUNTION."
10828 (let ((line (org-current-line)))
10829 (goto-char (point-min))
10830 (while (not (eobp))
10831 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10832 (delete-region (point) (point-at-eol))
10833 (or (eobp) (forward-char 1)))
10834 (goto-line line)))
10836 (defun org-table-fedit-toggle-ref-type ()
10837 "Convert all references in the buffer from B3 to @3$2 and back."
10838 (interactive)
10839 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10840 (org-table-fedit-convert-buffer
10841 (if org-table-buffer-is-an
10842 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10843 (message "Reference type switched to %s"
10844 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10846 (defun org-table-fedit-ref-up ()
10847 "Shift the reference at point one row/hline up."
10848 (interactive)
10849 (org-table-fedit-shift-reference 'up))
10850 (defun org-table-fedit-ref-down ()
10851 "Shift the reference at point one row/hline down."
10852 (interactive)
10853 (org-table-fedit-shift-reference 'down))
10854 (defun org-table-fedit-ref-left ()
10855 "Shift the reference at point one field to the left."
10856 (interactive)
10857 (org-table-fedit-shift-reference 'left))
10858 (defun org-table-fedit-ref-right ()
10859 "Shift the reference at point one field to the right."
10860 (interactive)
10861 (org-table-fedit-shift-reference 'right))
10863 (defun org-table-fedit-shift-reference (dir)
10864 (cond
10865 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10866 (if (memq dir '(left right))
10867 (org-rematch-and-replace 1 (eq dir 'left))
10868 (error "Cannot shift reference in this direction")))
10869 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10870 ;; A B3-like reference
10871 (if (memq dir '(up down))
10872 (org-rematch-and-replace 2 (eq dir 'up))
10873 (org-rematch-and-replace 1 (eq dir 'left))))
10874 ((org-at-regexp-p
10875 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10876 ;; An internal reference
10877 (if (memq dir '(up down))
10878 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10879 (org-rematch-and-replace 5 (eq dir 'left))))))
10881 (defun org-rematch-and-replace (n &optional decr hline)
10882 "Re-match the group N, and replace it with the shifted refrence."
10883 (or (match-end n) (error "Cannot shift reference in this direction"))
10884 (goto-char (match-beginning n))
10885 (and (looking-at (regexp-quote (match-string n)))
10886 (replace-match (org-shift-refpart (match-string 0) decr hline)
10887 t t)))
10889 (defun org-shift-refpart (ref &optional decr hline)
10890 "Shift a refrence part REF.
10891 If DECR is set, decrease the references row/column, else increase.
10892 If HLINE is set, this may be a hline reference, it certainly is not
10893 a translation reference."
10894 (save-match-data
10895 (let* ((sign (string-match "^[-+]" ref)) n)
10897 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10898 (cond
10899 ((and hline (string-match "^I+" ref))
10900 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10901 (setq n (+ n (if decr -1 1)))
10902 (if (= n 0) (setq n (+ n (if decr -1 1))))
10903 (if sign
10904 (setq sign (if (< n 0) "-" "+") n (abs n))
10905 (setq n (max 1 n)))
10906 (concat sign (make-string n ?I)))
10908 ((string-match "^[0-9]+" ref)
10909 (setq n (string-to-number (concat sign ref)))
10910 (setq n (+ n (if decr -1 1)))
10911 (if sign
10912 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10913 (number-to-string (max 1 n))))
10915 ((string-match "^[a-zA-Z]+" ref)
10916 (org-number-to-letters
10917 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10919 (t (error "Cannot shift reference"))))))
10921 (defun org-table-fedit-toggle-coordinates ()
10922 "Toggle the display of coordinates in the refrenced table."
10923 (interactive)
10924 (let ((pos (marker-position org-pos)))
10925 (with-current-buffer (marker-buffer org-pos)
10926 (save-excursion
10927 (goto-char pos)
10928 (org-table-toggle-coordinate-overlays)))))
10930 (defun org-table-fedit-finish (&optional arg)
10931 "Parse the buffer for formula definitions and install them.
10932 With prefix ARG, apply the new formulas to the table."
10933 (interactive "P")
10934 (org-table-remove-rectangle-highlight)
10935 (if org-table-use-standard-references
10936 (progn
10937 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10938 (setq org-table-buffer-is-an nil)))
10939 (let ((pos org-pos) eql var form)
10940 (goto-char (point-min))
10941 (while (re-search-forward
10942 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10943 nil t)
10944 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10945 form (match-string 3))
10946 (setq form (org-trim form))
10947 (when (not (equal form ""))
10948 (while (string-match "[ \t]*\n[ \t]*" form)
10949 (setq form (replace-match " " t t form)))
10950 (when (assoc var eql)
10951 (error "Double formulas for %s" var))
10952 (push (cons var form) eql)))
10953 (setq org-pos nil)
10954 (set-window-configuration org-window-configuration)
10955 (select-window (get-buffer-window (marker-buffer pos)))
10956 (goto-char pos)
10957 (unless (org-at-table-p)
10958 (error "Lost table position - cannot install formulae"))
10959 (org-table-store-formulas eql)
10960 (move-marker pos nil)
10961 (kill-buffer "*Edit Formulas*")
10962 (if arg
10963 (org-table-recalculate 'all)
10964 (message "New formulas installed - press C-u C-c C-c to apply."))))
10966 (defun org-table-fedit-abort ()
10967 "Abort editing formulas, without installing the changes."
10968 (interactive)
10969 (org-table-remove-rectangle-highlight)
10970 (let ((pos org-pos))
10971 (set-window-configuration org-window-configuration)
10972 (select-window (get-buffer-window (marker-buffer pos)))
10973 (goto-char pos)
10974 (move-marker pos nil)
10975 (message "Formula editing aborted without installing changes")))
10977 (defun org-table-fedit-lisp-indent ()
10978 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10979 (interactive)
10980 (let ((pos (point)) beg end ind)
10981 (beginning-of-line 1)
10982 (cond
10983 ((looking-at "[ \t]")
10984 (goto-char pos)
10985 (call-interactively 'lisp-indent-line))
10986 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10987 ((not (fboundp 'pp-buffer))
10988 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10989 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10990 (goto-char (- (match-end 0) 2))
10991 (setq beg (point))
10992 (setq ind (make-string (current-column) ?\ ))
10993 (condition-case nil (forward-sexp 1)
10994 (error
10995 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10996 (setq end (point))
10997 (save-restriction
10998 (narrow-to-region beg end)
10999 (if (eq last-command this-command)
11000 (progn
11001 (goto-char (point-min))
11002 (setq this-command nil)
11003 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11004 (replace-match " ")))
11005 (pp-buffer)
11006 (untabify (point-min) (point-max))
11007 (goto-char (1+ (point-min)))
11008 (while (re-search-forward "^." nil t)
11009 (beginning-of-line 1)
11010 (insert ind))
11011 (goto-char (point-max))
11012 (backward-delete-char 1)))
11013 (goto-char beg))
11014 (t nil))))
11016 (defvar org-show-positions nil)
11018 (defun org-table-show-reference (&optional local)
11019 "Show the location/value of the $ expression at point."
11020 (interactive)
11021 (org-table-remove-rectangle-highlight)
11022 (catch 'exit
11023 (let ((pos (if local (point) org-pos))
11024 (face2 'highlight)
11025 (org-inhibit-highlight-removal t)
11026 (win (selected-window))
11027 (org-show-positions nil)
11028 var name e what match dest)
11029 (if local (org-table-get-specials))
11030 (setq what (cond
11031 ((or (org-at-regexp-p org-table-range-regexp2)
11032 (org-at-regexp-p org-table-translate-regexp)
11033 (org-at-regexp-p org-table-range-regexp))
11034 (setq match
11035 (save-match-data
11036 (org-table-convert-refs-to-rc (match-string 0))))
11037 'range)
11038 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11039 ((org-at-regexp-p "\\$[0-9]+") 'column)
11040 ((not local) nil)
11041 (t (error "No reference at point")))
11042 match (and what (or match (match-string 0))))
11043 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11044 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11045 'secondary-selection))
11046 (org-add-hook 'before-change-functions
11047 'org-table-remove-rectangle-highlight)
11048 (if (eq what 'name) (setq var (substring match 1)))
11049 (when (eq what 'range)
11050 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11051 (setq match (org-table-formula-substitute-names match)))
11052 (unless local
11053 (save-excursion
11054 (end-of-line 1)
11055 (re-search-backward "^\\S-" nil t)
11056 (beginning-of-line 1)
11057 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11058 (setq dest
11059 (save-match-data
11060 (org-table-convert-refs-to-rc (match-string 1))))
11061 (org-table-add-rectangle-overlay
11062 (match-beginning 1) (match-end 1) face2))))
11063 (if (and (markerp pos) (marker-buffer pos))
11064 (if (get-buffer-window (marker-buffer pos))
11065 (select-window (get-buffer-window (marker-buffer pos)))
11066 (org-switch-to-buffer-other-window (get-buffer-window
11067 (marker-buffer pos)))))
11068 (goto-char pos)
11069 (org-table-force-dataline)
11070 (when dest
11071 (setq name (substring dest 1))
11072 (cond
11073 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11074 (setq e (assoc name org-table-named-field-locations))
11075 (goto-line (nth 1 e))
11076 (org-table-goto-column (nth 2 e)))
11077 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11078 (let ((l (string-to-number (match-string 1 dest)))
11079 (c (string-to-number (match-string 2 dest))))
11080 (goto-line (aref org-table-dlines l))
11081 (org-table-goto-column c)))
11082 (t (org-table-goto-column (string-to-number name))))
11083 (move-marker pos (point))
11084 (org-table-highlight-rectangle nil nil face2))
11085 (cond
11086 ((equal dest match))
11087 ((not match))
11088 ((eq what 'range)
11089 (condition-case nil
11090 (save-excursion
11091 (org-table-get-range match nil nil 'highlight))
11092 (error nil)))
11093 ((setq e (assoc var org-table-named-field-locations))
11094 (goto-line (nth 1 e))
11095 (org-table-goto-column (nth 2 e))
11096 (org-table-highlight-rectangle (point) (point))
11097 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11098 ((setq e (assoc var org-table-column-names))
11099 (org-table-goto-column (string-to-number (cdr e)))
11100 (org-table-highlight-rectangle (point) (point))
11101 (goto-char (org-table-begin))
11102 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11103 (org-table-end) t)
11104 (progn
11105 (goto-char (match-beginning 1))
11106 (org-table-highlight-rectangle)
11107 (message "Named column (column %s)" (cdr e)))
11108 (error "Column name not found")))
11109 ((eq what 'column)
11110 ;; column number
11111 (org-table-goto-column (string-to-number (substring match 1)))
11112 (org-table-highlight-rectangle (point) (point))
11113 (message "Column %s" (substring match 1)))
11114 ((setq e (assoc var org-table-local-parameters))
11115 (goto-char (org-table-begin))
11116 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11117 (progn
11118 (goto-char (match-beginning 1))
11119 (org-table-highlight-rectangle)
11120 (message "Local parameter."))
11121 (error "Parameter not found")))
11123 (cond
11124 ((not var) (error "No reference at point"))
11125 ((setq e (assoc var org-table-formula-constants-local))
11126 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11127 var (cdr e)))
11128 ((setq e (assoc var org-table-formula-constants))
11129 (message "Constant: $%s=%s in `org-table-formula-constants'."
11130 var (cdr e)))
11131 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11132 (message "Constant: $%s=%s, from `constants.el'%s."
11133 var e (format " (%s units)" constants-unit-system)))
11134 (t (error "Undefined name $%s" var)))))
11135 (goto-char pos)
11136 (when (and org-show-positions
11137 (not (memq this-command '(org-table-fedit-scroll
11138 org-table-fedit-scroll-down))))
11139 (push pos org-show-positions)
11140 (push org-table-current-begin-pos org-show-positions)
11141 (let ((min (apply 'min org-show-positions))
11142 (max (apply 'max org-show-positions)))
11143 (goto-char min) (recenter 0)
11144 (goto-char max)
11145 (or (pos-visible-in-window-p max) (recenter -1))))
11146 (select-window win))))
11148 (defun org-table-force-dataline ()
11149 "Make sure the cursor is in a dataline in a table."
11150 (unless (save-excursion
11151 (beginning-of-line 1)
11152 (looking-at org-table-dataline-regexp))
11153 (let* ((re org-table-dataline-regexp)
11154 (p1 (save-excursion (re-search-forward re nil 'move)))
11155 (p2 (save-excursion (re-search-backward re nil 'move))))
11156 (cond ((and p1 p2)
11157 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11158 p1 p2)))
11159 ((or p1 p2) (goto-char (or p1 p2)))
11160 (t (error "No table dataline around here"))))))
11162 (defun org-table-fedit-line-up ()
11163 "Move cursor one line up in the window showing the table."
11164 (interactive)
11165 (org-table-fedit-move 'previous-line))
11167 (defun org-table-fedit-line-down ()
11168 "Move cursor one line down in the window showing the table."
11169 (interactive)
11170 (org-table-fedit-move 'next-line))
11172 (defun org-table-fedit-move (command)
11173 "Move the cursor in the window shoinw the table.
11174 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11175 (let ((org-table-allow-automatic-line-recalculation nil)
11176 (pos org-pos) (win (selected-window)) p)
11177 (select-window (get-buffer-window (marker-buffer org-pos)))
11178 (setq p (point))
11179 (call-interactively command)
11180 (while (and (org-at-table-p)
11181 (org-at-table-hline-p))
11182 (call-interactively command))
11183 (or (org-at-table-p) (goto-char p))
11184 (move-marker pos (point))
11185 (select-window win)))
11187 (defun org-table-fedit-scroll (N)
11188 (interactive "p")
11189 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11190 (scroll-other-window N)))
11192 (defun org-table-fedit-scroll-down (N)
11193 (interactive "p")
11194 (org-table-fedit-scroll (- N)))
11196 (defvar org-table-rectangle-overlays nil)
11198 (defun org-table-add-rectangle-overlay (beg end &optional face)
11199 "Add a new overlay."
11200 (let ((ov (org-make-overlay beg end)))
11201 (org-overlay-put ov 'face (or face 'secondary-selection))
11202 (push ov org-table-rectangle-overlays)))
11204 (defun org-table-highlight-rectangle (&optional beg end face)
11205 "Highlight rectangular region in a table."
11206 (setq beg (or beg (point)) end (or end (point)))
11207 (let ((b (min beg end))
11208 (e (max beg end))
11209 l1 c1 l2 c2 tmp)
11210 (and (boundp 'org-show-positions)
11211 (setq org-show-positions (cons b (cons e org-show-positions))))
11212 (goto-char (min beg end))
11213 (setq l1 (org-current-line)
11214 c1 (org-table-current-column))
11215 (goto-char (max beg end))
11216 (setq l2 (org-current-line)
11217 c2 (org-table-current-column))
11218 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11219 (goto-line l1)
11220 (beginning-of-line 1)
11221 (loop for line from l1 to l2 do
11222 (when (looking-at org-table-dataline-regexp)
11223 (org-table-goto-column c1)
11224 (skip-chars-backward "^|\n") (setq beg (point))
11225 (org-table-goto-column c2)
11226 (skip-chars-forward "^|\n") (setq end (point))
11227 (org-table-add-rectangle-overlay beg end face))
11228 (beginning-of-line 2))
11229 (goto-char b))
11230 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11232 (defun org-table-remove-rectangle-highlight (&rest ignore)
11233 "Remove the rectangle overlays."
11234 (unless org-inhibit-highlight-removal
11235 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11236 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11237 (setq org-table-rectangle-overlays nil)))
11239 (defvar org-table-coordinate-overlays nil
11240 "Collects the cooordinate grid overlays, so that they can be removed.")
11241 (make-variable-buffer-local 'org-table-coordinate-overlays)
11243 (defun org-table-overlay-coordinates ()
11244 "Add overlays to the table at point, to show row/column coordinates."
11245 (interactive)
11246 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11247 (setq org-table-coordinate-overlays nil)
11248 (save-excursion
11249 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11250 (goto-char (org-table-begin))
11251 (while (org-at-table-p)
11252 (setq eol (point-at-eol))
11253 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11254 (push ov org-table-coordinate-overlays)
11255 (setq hline (looking-at org-table-hline-regexp))
11256 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11257 (format "%4d" (setq id (1+ id)))))
11258 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11259 (when hline
11260 (setq ic 0)
11261 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11262 (setq beg (1+ (match-beginning 0))
11263 ic (1+ ic)
11264 s1 (concat "$" (int-to-string ic))
11265 s2 (org-number-to-letters ic)
11266 str (if (eq org-table-use-standard-references t) s2 s1))
11267 (setq ov (org-make-overlay beg (+ beg (length str))))
11268 (push ov org-table-coordinate-overlays)
11269 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11270 (beginning-of-line 2)))))
11272 (defun org-table-toggle-coordinate-overlays ()
11273 "Toggle the display of Row/Column numbers in tables."
11274 (interactive)
11275 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11276 (message "Row/Column number display turned %s"
11277 (if org-table-overlay-coordinates "on" "off"))
11278 (if (and (org-at-table-p) org-table-overlay-coordinates)
11279 (org-table-align))
11280 (unless org-table-overlay-coordinates
11281 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11282 (setq org-table-coordinate-overlays nil)))
11284 (defun org-table-toggle-formula-debugger ()
11285 "Toggle the formula debugger in tables."
11286 (interactive)
11287 (setq org-table-formula-debug (not org-table-formula-debug))
11288 (message "Formula debugging has been turned %s"
11289 (if org-table-formula-debug "on" "off")))
11291 ;;; The orgtbl minor mode
11293 ;; Define a minor mode which can be used in other modes in order to
11294 ;; integrate the org-mode table editor.
11296 ;; This is really a hack, because the org-mode table editor uses several
11297 ;; keys which normally belong to the major mode, for example the TAB and
11298 ;; RET keys. Here is how it works: The minor mode defines all the keys
11299 ;; necessary to operate the table editor, but wraps the commands into a
11300 ;; function which tests if the cursor is currently inside a table. If that
11301 ;; is the case, the table editor command is executed. However, when any of
11302 ;; those keys is used outside a table, the function uses `key-binding' to
11303 ;; look up if the key has an associated command in another currently active
11304 ;; keymap (minor modes, major mode, global), and executes that command.
11305 ;; There might be problems if any of the keys used by the table editor is
11306 ;; otherwise used as a prefix key.
11308 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11309 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11310 ;; addresses this by checking explicitly for both bindings.
11312 ;; The optimized version (see variable `orgtbl-optimized') takes over
11313 ;; all keys which are bound to `self-insert-command' in the *global map*.
11314 ;; Some modes bind other commands to simple characters, for example
11315 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11316 ;; active, this binding is ignored inside tables and replaced with a
11317 ;; modified self-insert.
11319 (defvar orgtbl-mode nil
11320 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11321 table editor in arbitrary modes.")
11322 (make-variable-buffer-local 'orgtbl-mode)
11324 (defvar orgtbl-mode-map (make-keymap)
11325 "Keymap for `orgtbl-mode'.")
11327 ;;;###autoload
11328 (defun turn-on-orgtbl ()
11329 "Unconditionally turn on `orgtbl-mode'."
11330 (orgtbl-mode 1))
11332 (defvar org-old-auto-fill-inhibit-regexp nil
11333 "Local variable used by `orgtbl-mode'")
11335 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11336 "Matches a line belonging to an orgtbl.")
11338 (defconst orgtbl-extra-font-lock-keywords
11339 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11340 0 (quote 'org-table) 'prepend))
11341 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11343 ;;;###autoload
11344 (defun orgtbl-mode (&optional arg)
11345 "The `org-mode' table editor as a minor mode for use in other modes."
11346 (interactive)
11347 (if (org-mode-p)
11348 ;; Exit without error, in case some hook functions calls this
11349 ;; by accident in org-mode.
11350 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11351 (setq orgtbl-mode
11352 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11353 (if orgtbl-mode
11354 (progn
11355 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11356 ;; Make sure we are first in minor-mode-map-alist
11357 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11358 (and c (setq minor-mode-map-alist
11359 (cons c (delq c minor-mode-map-alist)))))
11360 (org-set-local (quote org-table-may-need-update) t)
11361 (org-add-hook 'before-change-functions 'org-before-change-function
11362 nil 'local)
11363 (org-set-local 'org-old-auto-fill-inhibit-regexp
11364 auto-fill-inhibit-regexp)
11365 (org-set-local 'auto-fill-inhibit-regexp
11366 (if auto-fill-inhibit-regexp
11367 (concat orgtbl-line-start-regexp "\\|"
11368 auto-fill-inhibit-regexp)
11369 orgtbl-line-start-regexp))
11370 (org-add-to-invisibility-spec '(org-cwidth))
11371 (when (fboundp 'font-lock-add-keywords)
11372 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11373 (org-restart-font-lock))
11374 (easy-menu-add orgtbl-mode-menu)
11375 (run-hooks 'orgtbl-mode-hook))
11376 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11377 (org-cleanup-narrow-column-properties)
11378 (org-remove-from-invisibility-spec '(org-cwidth))
11379 (remove-hook 'before-change-functions 'org-before-change-function t)
11380 (when (fboundp 'font-lock-remove-keywords)
11381 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11382 (org-restart-font-lock))
11383 (easy-menu-remove orgtbl-mode-menu)
11384 (force-mode-line-update 'all))))
11386 (defun org-cleanup-narrow-column-properties ()
11387 "Remove all properties related to narrow-column invisibility."
11388 (let ((s 1))
11389 (while (setq s (text-property-any s (point-max)
11390 'display org-narrow-column-arrow))
11391 (remove-text-properties s (1+ s) '(display t)))
11392 (setq s 1)
11393 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11394 (remove-text-properties s (1+ s) '(org-cwidth t)))
11395 (setq s 1)
11396 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11397 (remove-text-properties s (1+ s) '(invisible t)))))
11399 ;; Install it as a minor mode.
11400 (put 'orgtbl-mode :included t)
11401 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11402 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11404 (defun orgtbl-make-binding (fun n &rest keys)
11405 "Create a function for binding in the table minor mode.
11406 FUN is the command to call inside a table. N is used to create a unique
11407 command name. KEYS are keys that should be checked in for a command
11408 to execute outside of tables."
11409 (eval
11410 (list 'defun
11411 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11412 '(arg)
11413 (concat "In tables, run `" (symbol-name fun) "'.\n"
11414 "Outside of tables, run the binding of `"
11415 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11416 "'.")
11417 '(interactive "p")
11418 (list 'if
11419 '(org-at-table-p)
11420 (list 'call-interactively (list 'quote fun))
11421 (list 'let '(orgtbl-mode)
11422 (list 'call-interactively
11423 (append '(or)
11424 (mapcar (lambda (k)
11425 (list 'key-binding k))
11426 keys)
11427 '('orgtbl-error))))))))
11429 (defun orgtbl-error ()
11430 "Error when there is no default binding for a table key."
11431 (interactive)
11432 (error "This key has no function outside tables"))
11434 (defun orgtbl-setup ()
11435 "Setup orgtbl keymaps."
11436 (let ((nfunc 0)
11437 (bindings
11438 (list
11439 '([(meta shift left)] org-table-delete-column)
11440 '([(meta left)] org-table-move-column-left)
11441 '([(meta right)] org-table-move-column-right)
11442 '([(meta shift right)] org-table-insert-column)
11443 '([(meta shift up)] org-table-kill-row)
11444 '([(meta shift down)] org-table-insert-row)
11445 '([(meta up)] org-table-move-row-up)
11446 '([(meta down)] org-table-move-row-down)
11447 '("\C-c\C-w" org-table-cut-region)
11448 '("\C-c\M-w" org-table-copy-region)
11449 '("\C-c\C-y" org-table-paste-rectangle)
11450 '("\C-c-" org-table-insert-hline)
11451 '("\C-c}" org-table-toggle-coordinate-overlays)
11452 '("\C-c{" org-table-toggle-formula-debugger)
11453 '("\C-m" org-table-next-row)
11454 '([(shift return)] org-table-copy-down)
11455 '("\C-c\C-q" org-table-wrap-region)
11456 '("\C-c?" org-table-field-info)
11457 '("\C-c " org-table-blank-field)
11458 '("\C-c+" org-table-sum)
11459 '("\C-c=" org-table-eval-formula)
11460 '("\C-c'" org-table-edit-formulas)
11461 '("\C-c`" org-table-edit-field)
11462 '("\C-c*" org-table-recalculate)
11463 '("\C-c|" org-table-create-or-convert-from-region)
11464 '("\C-c^" org-table-sort-lines)
11465 '([(control ?#)] org-table-rotate-recalc-marks)))
11466 elt key fun cmd)
11467 (while (setq elt (pop bindings))
11468 (setq nfunc (1+ nfunc))
11469 (setq key (org-key (car elt))
11470 fun (nth 1 elt)
11471 cmd (orgtbl-make-binding fun nfunc key))
11472 (org-defkey orgtbl-mode-map key cmd))
11474 ;; Special treatment needed for TAB and RET
11475 (org-defkey orgtbl-mode-map [(return)]
11476 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11477 (org-defkey orgtbl-mode-map "\C-m"
11478 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11480 (org-defkey orgtbl-mode-map [(tab)]
11481 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11482 (org-defkey orgtbl-mode-map "\C-i"
11483 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11485 (org-defkey orgtbl-mode-map [(shift tab)]
11486 (orgtbl-make-binding 'org-table-previous-field 104
11487 [(shift tab)] [(tab)] "\C-i"))
11489 (org-defkey orgtbl-mode-map "\M-\C-m"
11490 (orgtbl-make-binding 'org-table-wrap-region 105
11491 "\M-\C-m" [(meta return)]))
11492 (org-defkey orgtbl-mode-map [(meta return)]
11493 (orgtbl-make-binding 'org-table-wrap-region 106
11494 [(meta return)] "\M-\C-m"))
11496 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11497 (when orgtbl-optimized
11498 ;; If the user wants maximum table support, we need to hijack
11499 ;; some standard editing functions
11500 (org-remap orgtbl-mode-map
11501 'self-insert-command 'orgtbl-self-insert-command
11502 'delete-char 'org-delete-char
11503 'delete-backward-char 'org-delete-backward-char)
11504 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11505 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11506 '("OrgTbl"
11507 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11508 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11509 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11510 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11511 "--"
11512 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11513 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11514 ["Copy Field from Above"
11515 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11516 "--"
11517 ("Column"
11518 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11519 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11520 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11521 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11522 ("Row"
11523 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11524 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11525 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11526 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11527 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11528 "--"
11529 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11530 ("Rectangle"
11531 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11532 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11533 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11534 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11535 "--"
11536 ("Radio tables"
11537 ["Insert table template" orgtbl-insert-radio-table
11538 (assq major-mode orgtbl-radio-table-templates)]
11539 ["Comment/uncomment table" orgtbl-toggle-comment t])
11540 "--"
11541 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11542 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11543 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11544 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11545 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11546 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11547 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11548 ["Sum Column/Rectangle" org-table-sum
11549 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11550 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11551 ["Debug Formulas"
11552 org-table-toggle-formula-debugger :active (org-at-table-p)
11553 :keys "C-c {"
11554 :style toggle :selected org-table-formula-debug]
11555 ["Show Col/Row Numbers"
11556 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11557 :keys "C-c }"
11558 :style toggle :selected org-table-overlay-coordinates]
11562 (defun orgtbl-ctrl-c-ctrl-c (arg)
11563 "If the cursor is inside a table, realign the table.
11564 It it is a table to be sent away to a receiver, do it.
11565 With prefix arg, also recompute table."
11566 (interactive "P")
11567 (let ((pos (point)) action)
11568 (save-excursion
11569 (beginning-of-line 1)
11570 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11571 ((looking-at "[ \t]*|") pos)
11572 ((looking-at "#\\+TBLFM:") 'recalc))))
11573 (cond
11574 ((integerp action)
11575 (goto-char action)
11576 (org-table-maybe-eval-formula)
11577 (if arg
11578 (call-interactively 'org-table-recalculate)
11579 (org-table-maybe-recalculate-line))
11580 (call-interactively 'org-table-align)
11581 (orgtbl-send-table 'maybe))
11582 ((eq action 'recalc)
11583 (save-excursion
11584 (beginning-of-line 1)
11585 (skip-chars-backward " \r\n\t")
11586 (if (org-at-table-p)
11587 (org-call-with-arg 'org-table-recalculate t))))
11588 (t (let (orgtbl-mode)
11589 (call-interactively (key-binding "\C-c\C-c")))))))
11591 (defun orgtbl-tab (arg)
11592 "Justification and field motion for `orgtbl-mode'."
11593 (interactive "P")
11594 (if arg (org-table-edit-field t)
11595 (org-table-justify-field-maybe)
11596 (org-table-next-field)))
11598 (defun orgtbl-ret ()
11599 "Justification and field motion for `orgtbl-mode'."
11600 (interactive)
11601 (org-table-justify-field-maybe)
11602 (org-table-next-row))
11604 (defun orgtbl-self-insert-command (N)
11605 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11606 If the cursor is in a table looking at whitespace, the whitespace is
11607 overwritten, and the table is not marked as requiring realignment."
11608 (interactive "p")
11609 (if (and (org-at-table-p)
11611 (and org-table-auto-blank-field
11612 (member last-command
11613 '(orgtbl-hijacker-command-100
11614 orgtbl-hijacker-command-101
11615 orgtbl-hijacker-command-102
11616 orgtbl-hijacker-command-103
11617 orgtbl-hijacker-command-104
11618 orgtbl-hijacker-command-105))
11619 (org-table-blank-field))
11621 (eq N 1)
11622 (looking-at "[^|\n]* +|"))
11623 (let (org-table-may-need-update)
11624 (goto-char (1- (match-end 0)))
11625 (delete-backward-char 1)
11626 (goto-char (match-beginning 0))
11627 (self-insert-command N))
11628 (setq org-table-may-need-update t)
11629 (let (orgtbl-mode)
11630 (call-interactively (key-binding (vector last-input-event))))))
11632 (defun org-force-self-insert (N)
11633 "Needed to enforce self-insert under remapping."
11634 (interactive "p")
11635 (self-insert-command N))
11637 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11638 "Regula expression matching exponentials as produced by calc.")
11640 (defvar org-table-clean-did-remove-column nil)
11642 (defun orgtbl-export (table target)
11643 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11644 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11645 org-table-last-alignment org-table-last-column-widths
11646 maxcol column)
11647 (if (not (fboundp func))
11648 (error "Cannot export orgtbl table to %s" target))
11649 (setq lines (org-table-clean-before-export lines))
11650 (setq table
11651 (mapcar
11652 (lambda (x)
11653 (if (string-match org-table-hline-regexp x)
11654 'hline
11655 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11656 lines))
11657 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11658 table)))
11659 (loop for i from (1- maxcol) downto 0 do
11660 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11661 (setq column (delq nil column))
11662 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11663 (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))
11664 (funcall func table nil)))
11666 (defun orgtbl-send-table (&optional maybe)
11667 "Send a tranformed version of this table to the receiver position.
11668 With argument MAYBE, fail quietly if no transformation is defined for
11669 this table."
11670 (interactive)
11671 (catch 'exit
11672 (unless (org-at-table-p) (error "Not at a table"))
11673 ;; when non-interactive, we assume align has just happened.
11674 (when (interactive-p) (org-table-align))
11675 (save-excursion
11676 (goto-char (org-table-begin))
11677 (beginning-of-line 0)
11678 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11679 (if maybe
11680 (throw 'exit nil)
11681 (error "Don't know how to transform this table."))))
11682 (let* ((name (match-string 1))
11684 (transform (intern (match-string 2)))
11685 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11686 (skip (plist-get params :skip))
11687 (skipcols (plist-get params :skipcols))
11688 (txt (buffer-substring-no-properties
11689 (org-table-begin) (org-table-end)))
11690 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11691 (lines (org-table-clean-before-export lines))
11692 (i0 (if org-table-clean-did-remove-column 2 1))
11693 (table (mapcar
11694 (lambda (x)
11695 (if (string-match org-table-hline-regexp x)
11696 'hline
11697 (org-remove-by-index
11698 (org-split-string (org-trim x) "\\s-*|\\s-*")
11699 skipcols i0)))
11700 lines))
11701 (fun (if (= i0 2) 'cdr 'identity))
11702 (org-table-last-alignment
11703 (org-remove-by-index (funcall fun org-table-last-alignment)
11704 skipcols i0))
11705 (org-table-last-column-widths
11706 (org-remove-by-index (funcall fun org-table-last-column-widths)
11707 skipcols i0)))
11709 (unless (fboundp transform)
11710 (error "No such transformation function %s" transform))
11711 (setq txt (funcall transform table params))
11712 ;; Find the insertion place
11713 (save-excursion
11714 (goto-char (point-min))
11715 (unless (re-search-forward
11716 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11717 (error "Don't know where to insert translated table"))
11718 (goto-char (match-beginning 0))
11719 (beginning-of-line 2)
11720 (setq beg (point))
11721 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11722 (error "Cannot find end of insertion region"))
11723 (beginning-of-line 1)
11724 (delete-region beg (point))
11725 (goto-char beg)
11726 (insert txt "\n"))
11727 (message "Table converted and installed at receiver location"))))
11729 (defun org-remove-by-index (list indices &optional i0)
11730 "Remove the elements in LIST with indices in INDICES.
11731 First element has index 0, or I0 if given."
11732 (if (not indices)
11733 list
11734 (if (integerp indices) (setq indices (list indices)))
11735 (setq i0 (1- (or i0 0)))
11736 (delq :rm (mapcar (lambda (x)
11737 (setq i0 (1+ i0))
11738 (if (memq i0 indices) :rm x))
11739 list))))
11741 (defun orgtbl-toggle-comment ()
11742 "Comment or uncomment the orgtbl at point."
11743 (interactive)
11744 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11745 (re2 (concat "^" orgtbl-line-start-regexp))
11746 (commented (save-excursion (beginning-of-line 1)
11747 (cond ((looking-at re1) t)
11748 ((looking-at re2) nil)
11749 (t (error "Not at an org table")))))
11750 (re (if commented re1 re2))
11751 beg end)
11752 (save-excursion
11753 (beginning-of-line 1)
11754 (while (looking-at re) (beginning-of-line 0))
11755 (beginning-of-line 2)
11756 (setq beg (point))
11757 (while (looking-at re) (beginning-of-line 2))
11758 (setq end (point)))
11759 (comment-region beg end (if commented '(4) nil))))
11761 (defun orgtbl-insert-radio-table ()
11762 "Insert a radio table template appropriate for this major mode."
11763 (interactive)
11764 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11765 (txt (nth 1 e))
11766 name pos)
11767 (unless e (error "No radio table setup defined for %s" major-mode))
11768 (setq name (read-string "Table name: "))
11769 (while (string-match "%n" txt)
11770 (setq txt (replace-match name t t txt)))
11771 (or (bolp) (insert "\n"))
11772 (setq pos (point))
11773 (insert txt)
11774 (goto-char pos)))
11776 (defun org-get-param (params header i sym &optional hsym)
11777 "Get parameter value for symbol SYM.
11778 If this is a header line, actually get the value for the symbol with an
11779 additional \"h\" inserted after the colon.
11780 If the value is a protperty list, get the element for the current column.
11781 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11782 (let ((val (plist-get params sym)))
11783 (and hsym header (setq val (or (plist-get params hsym) val)))
11784 (if (consp val) (plist-get val i) val)))
11786 (defun orgtbl-to-generic (table params)
11787 "Convert the orgtbl-mode TABLE to some other format.
11788 This generic routine can be used for many standard cases.
11789 TABLE is a list, each entry either the symbol `hline' for a horizontal
11790 separator line, or a list of fields for that line.
11791 PARAMS is a property list of parameters that can influence the conversion.
11792 For the generic converter, some parameters are obligatory: You need to
11793 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11794 :splice, you must have :tstart and :tend.
11796 Valid parameters are
11798 :tstart String to start the table. Ignored when :splice is t.
11799 :tend String to end the table. Ignored when :splice is t.
11801 :splice When set to t, return only table body lines, don't wrap
11802 them into :tstart and :tend. Default is nil.
11804 :hline String to be inserted on horizontal separation lines.
11805 May be nil to ignore hlines.
11807 :lstart String to start a new table line.
11808 :lend String to end a table line
11809 :sep Separator between two fields
11810 :lfmt Format for entire line, with enough %s to capture all fields.
11811 If this is present, :lstart, :lend, and :sep are ignored.
11812 :fmt A format to be used to wrap the field, should contain
11813 %s for the original field value. For example, to wrap
11814 everything in dollars, you could use :fmt \"$%s$\".
11815 This may also be a property list with column numbers and
11816 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11818 :hlstart :hlend :hlsep :hlfmt :hfmt
11819 Same as above, specific for the header lines in the table.
11820 All lines before the first hline are treated as header.
11821 If any of these is not present, the data line value is used.
11823 :efmt Use this format to print numbers with exponentials.
11824 The format should have %s twice for inserting mantissa
11825 and exponent, for example \"%s\\\\times10^{%s}\". This
11826 may also be a property list with column numbers and
11827 formats. :fmt will still be applied after :efmt.
11829 In addition to this, the parameters :skip and :skipcols are always handled
11830 directly by `orgtbl-send-table'. See manual."
11831 (interactive)
11832 (let* ((p params)
11833 (splicep (plist-get p :splice))
11834 (hline (plist-get p :hline))
11835 rtn line i fm efm lfmt h)
11837 ;; Do we have a header?
11838 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11839 (setq h t))
11841 ;; Put header
11842 (unless splicep
11843 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11845 ;; Now loop over all lines
11846 (while (setq line (pop table))
11847 (if (eq line 'hline)
11848 ;; A horizontal separator line
11849 (progn (if hline (push hline rtn))
11850 (setq h nil)) ; no longer in header
11851 ;; A normal line. Convert the fields, push line onto the result list
11852 (setq i 0)
11853 (setq line
11854 (mapcar
11855 (lambda (f)
11856 (setq i (1+ i)
11857 fm (org-get-param p h i :fmt :hfmt)
11858 efm (org-get-param p h i :efmt))
11859 (if (and efm (string-match orgtbl-exp-regexp f))
11860 (setq f (format
11861 efm (match-string 1 f) (match-string 2 f))))
11862 (if fm (setq f (format fm f)))
11864 line))
11865 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11866 (push (apply 'format lfmt line) rtn)
11867 (push (concat
11868 (org-get-param p h i :lstart :hlstart)
11869 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11870 (org-get-param p h i :lend :hlend))
11871 rtn))))
11873 (unless splicep
11874 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11876 (mapconcat 'identity (nreverse rtn) "\n")))
11878 (defun orgtbl-to-latex (table params)
11879 "Convert the orgtbl-mode TABLE to LaTeX.
11880 TABLE is a list, each entry either the symbol `hline' for a horizontal
11881 separator line, or a list of fields for that line.
11882 PARAMS is a property list of parameters that can influence the conversion.
11883 Supports all parameters from `orgtbl-to-generic'. Most important for
11884 LaTeX are:
11886 :splice When set to t, return only table body lines, don't wrap
11887 them into a tabular environment. Default is nil.
11889 :fmt A format to be used to wrap the field, should contain %s for the
11890 original field value. For example, to wrap everything in dollars,
11891 use :fmt \"$%s$\". This may also be a property list with column
11892 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11894 :efmt Format for transforming numbers with exponentials. The format
11895 should have %s twice for inserting mantissa and exponent, for
11896 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11897 This may also be a property list with column numbers and formats.
11899 The general parameters :skip and :skipcols have already been applied when
11900 this function is called."
11901 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11902 org-table-last-alignment ""))
11903 (params2
11904 (list
11905 :tstart (concat "\\begin{tabular}{" alignment "}")
11906 :tend "\\end{tabular}"
11907 :lstart "" :lend " \\\\" :sep " & "
11908 :efmt "%s\\,(%s)" :hline "\\hline")))
11909 (orgtbl-to-generic table (org-combine-plists params2 params))))
11911 (defun orgtbl-to-html (table params)
11912 "Convert the orgtbl-mode TABLE to LaTeX.
11913 TABLE is a list, each entry either the symbol `hline' for a horizontal
11914 separator line, or a list of fields for that line.
11915 PARAMS is a property list of parameters that can influence the conversion.
11916 Currently this function recognizes the following parameters:
11918 :splice When set to t, return only table body lines, don't wrap
11919 them into a <table> environment. Default is nil.
11921 The general parameters :skip and :skipcols have already been applied when
11922 this function is called. The function does *not* use `orgtbl-to-generic',
11923 so you cannot specify parameters for it."
11924 (let* ((splicep (plist-get params :splice))
11925 html)
11926 ;; Just call the formatter we already have
11927 ;; We need to make text lines for it, so put the fields back together.
11928 (setq html (org-format-org-table-html
11929 (mapcar
11930 (lambda (x)
11931 (if (eq x 'hline)
11932 "|----+----|"
11933 (concat "| " (mapconcat 'identity x " | ") " |")))
11934 table)
11935 splicep))
11936 (if (string-match "\n+\\'" html)
11937 (setq html (replace-match "" t t html)))
11938 html))
11940 (defun orgtbl-to-texinfo (table params)
11941 "Convert the orgtbl-mode TABLE to TeXInfo.
11942 TABLE is a list, each entry either the symbol `hline' for a horizontal
11943 separator line, or a list of fields for that line.
11944 PARAMS is a property list of parameters that can influence the conversion.
11945 Supports all parameters from `orgtbl-to-generic'. Most important for
11946 TeXInfo are:
11948 :splice nil/t When set to t, return only table body lines, don't wrap
11949 them into a multitable environment. Default is nil.
11951 :fmt fmt A format to be used to wrap the field, should contain
11952 %s for the original field value. For example, to wrap
11953 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11954 This may also be a property list with column numbers and
11955 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11957 :cf \"f1 f2..\" The column fractions for the table. By default these
11958 are computed automatically from the width of the columns
11959 under org-mode.
11961 The general parameters :skip and :skipcols have already been applied when
11962 this function is called."
11963 (let* ((total (float (apply '+ org-table-last-column-widths)))
11964 (colfrac (or (plist-get params :cf)
11965 (mapconcat
11966 (lambda (x) (format "%.3f" (/ (float x) total)))
11967 org-table-last-column-widths " ")))
11968 (params2
11969 (list
11970 :tstart (concat "@multitable @columnfractions " colfrac)
11971 :tend "@end multitable"
11972 :lstart "@item " :lend "" :sep " @tab "
11973 :hlstart "@headitem ")))
11974 (orgtbl-to-generic table (org-combine-plists params2 params))))
11976 ;;;; Link Stuff
11978 ;;; Link abbreviations
11980 (defun org-link-expand-abbrev (link)
11981 "Apply replacements as defined in `org-link-abbrev-alist."
11982 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11983 (let* ((key (match-string 1 link))
11984 (as (or (assoc key org-link-abbrev-alist-local)
11985 (assoc key org-link-abbrev-alist)))
11986 (tag (and (match-end 2) (match-string 3 link)))
11987 rpl)
11988 (if (not as)
11989 link
11990 (setq rpl (cdr as))
11991 (cond
11992 ((symbolp rpl) (funcall rpl tag))
11993 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11994 (t (concat rpl tag)))))
11995 link))
11997 ;;; Storing and inserting links
11999 (defvar org-insert-link-history nil
12000 "Minibuffer history for links inserted with `org-insert-link'.")
12002 (defvar org-stored-links nil
12003 "Contains the links stored with `org-store-link'.")
12005 (defvar org-store-link-plist nil
12006 "Plist with info about the most recently link created with `org-store-link'.")
12008 (defvar org-link-protocols nil
12009 "Link protocols added to Org-mode using `org-add-link-type'.")
12011 (defvar org-store-link-functions nil
12012 "List of functions that are called to create and store a link.
12013 Each function will be called in turn until one returns a non-nil
12014 value. Each function should check if it is responsible for creating
12015 this link (for example by looking at the major mode).
12016 If not, it must exit and return nil.
12017 If yes, it should return a non-nil value after a calling
12018 `org-store-link-props' with a list of properties and values.
12019 Special properties are:
12021 :type The link prefix. like \"http\". This must be given.
12022 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12023 This is obligatory as well.
12024 :description Optional default description for the second pair
12025 of brackets in an Org-mode link. The user can still change
12026 this when inserting this link into an Org-mode buffer.
12028 In addition to these, any additional properties can be specified
12029 and then used in remember templates.")
12031 (defun org-add-link-type (type &optional follow publish)
12032 "Add TYPE to the list of `org-link-types'.
12033 Re-compute all regular expressions depending on `org-link-types'
12034 FOLLOW and PUBLISH are two functions. Both take the link path as
12035 an argument.
12036 FOLLOW should do whatever is necessary to follow the link, for example
12037 to find a file or display a mail message.
12039 PUBLISH takes the path and retuns the string that should be used when
12040 this document is published. FIMXE: This is actually not yet implemented."
12041 (add-to-list 'org-link-types type t)
12042 (org-make-link-regexps)
12043 (add-to-list 'org-link-protocols
12044 (list type follow publish)))
12046 (defun org-add-agenda-custom-command (entry)
12047 "Replace or add a command in `org-agenda-custom-commands'.
12048 This is mostly for hacking and trying a new command - once the command
12049 works you probably want to add it to `org-agenda-custom-commands' for good."
12050 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12051 (if ass
12052 (setcdr ass (cdr entry))
12053 (push entry org-agenda-custom-commands))))
12055 ;;;###autoload
12056 (defun org-store-link (arg)
12057 "\\<org-mode-map>Store an org-link to the current location.
12058 This link is added to `org-stored-links' and can later be inserted
12059 into an org-buffer with \\[org-insert-link].
12061 For some link types, a prefix arg is interpreted:
12062 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12063 For file links, arg negates `org-context-in-file-links'."
12064 (interactive "P")
12065 (setq org-store-link-plist nil) ; reset
12066 (let (link cpltxt desc description search txt)
12067 (cond
12069 ((run-hook-with-args-until-success 'org-store-link-functions)
12070 (setq link (plist-get org-store-link-plist :link)
12071 desc (or (plist-get org-store-link-plist :description) link)))
12073 ((eq major-mode 'bbdb-mode)
12074 (let ((name (bbdb-record-name (bbdb-current-record)))
12075 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12076 (setq cpltxt (concat "bbdb:" (or name company))
12077 link (org-make-link cpltxt))
12078 (org-store-link-props :type "bbdb" :name name :company company)))
12080 ((eq major-mode 'Info-mode)
12081 (setq link (org-make-link "info:"
12082 (file-name-nondirectory Info-current-file)
12083 ":" Info-current-node))
12084 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12085 ":" Info-current-node))
12086 (org-store-link-props :type "info" :file Info-current-file
12087 :node Info-current-node))
12089 ((eq major-mode 'calendar-mode)
12090 (let ((cd (calendar-cursor-to-date)))
12091 (setq link
12092 (format-time-string
12093 (car org-time-stamp-formats)
12094 (apply 'encode-time
12095 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12096 nil nil nil))))
12097 (org-store-link-props :type "calendar" :date cd)))
12099 ((or (eq major-mode 'vm-summary-mode)
12100 (eq major-mode 'vm-presentation-mode))
12101 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12102 (vm-follow-summary-cursor)
12103 (save-excursion
12104 (vm-select-folder-buffer)
12105 (let* ((message (car vm-message-pointer))
12106 (folder buffer-file-name)
12107 (subject (vm-su-subject message))
12108 (to (vm-get-header-contents message "To"))
12109 (from (vm-get-header-contents message "From"))
12110 (message-id (vm-su-message-id message)))
12111 (org-store-link-props :type "vm" :from from :to to :subject subject
12112 :message-id message-id)
12113 (setq message-id (org-remove-angle-brackets message-id))
12114 (setq folder (abbreviate-file-name folder))
12115 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12116 folder)
12117 (setq folder (replace-match "" t t folder)))
12118 (setq cpltxt (org-email-link-description))
12119 (setq link (org-make-link "vm:" folder "#" message-id)))))
12121 ((eq major-mode 'wl-summary-mode)
12122 (let* ((msgnum (wl-summary-message-number))
12123 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12124 msgnum 'message-id))
12125 (wl-message-entity
12126 (if (fboundp 'elmo-message-entity)
12127 (elmo-message-entity
12128 wl-summary-buffer-elmo-folder msgnum)
12129 (elmo-msgdb-overview-get-entity
12130 msgnum (wl-summary-buffer-msgdb))))
12131 (from (wl-summary-line-from))
12132 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12133 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12134 (wl-summary-line-subject))))
12135 (org-store-link-props :type "wl" :from from :to to
12136 :subject subject :message-id message-id)
12137 (setq message-id (org-remove-angle-brackets message-id))
12138 (setq cpltxt (org-email-link-description))
12139 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12140 "#" message-id))))
12142 ((or (equal major-mode 'mh-folder-mode)
12143 (equal major-mode 'mh-show-mode))
12144 (let ((from (org-mhe-get-header "From:"))
12145 (to (org-mhe-get-header "To:"))
12146 (message-id (org-mhe-get-header "Message-Id:"))
12147 (subject (org-mhe-get-header "Subject:")))
12148 (org-store-link-props :type "mh" :from from :to to
12149 :subject subject :message-id message-id)
12150 (setq cpltxt (org-email-link-description))
12151 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12152 (org-remove-angle-brackets message-id)))))
12154 ((or (eq major-mode 'rmail-mode)
12155 (eq major-mode 'rmail-summary-mode))
12156 (save-window-excursion
12157 (save-restriction
12158 (when (eq major-mode 'rmail-summary-mode)
12159 (rmail-show-message rmail-current-message))
12160 (rmail-narrow-to-non-pruned-header)
12161 (let ((folder buffer-file-name)
12162 (message-id (mail-fetch-field "message-id"))
12163 (from (mail-fetch-field "from"))
12164 (to (mail-fetch-field "to"))
12165 (subject (mail-fetch-field "subject")))
12166 (org-store-link-props
12167 :type "rmail" :from from :to to
12168 :subject subject :message-id message-id)
12169 (setq message-id (org-remove-angle-brackets message-id))
12170 (setq cpltxt (org-email-link-description))
12171 (setq link (org-make-link "rmail:" folder "#" message-id)))
12172 (rmail-show-message rmail-current-message))))
12174 ((eq major-mode 'gnus-group-mode)
12175 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12176 (gnus-group-group-name)) ; version
12177 ((fboundp 'gnus-group-name)
12178 (gnus-group-name))
12179 (t "???"))))
12180 (unless group (error "Not on a group"))
12181 (org-store-link-props :type "gnus" :group group)
12182 (setq cpltxt (concat
12183 (if (org-xor arg org-usenet-links-prefer-google)
12184 "http://groups.google.com/groups?group="
12185 "gnus:")
12186 group)
12187 link (org-make-link cpltxt))))
12189 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12190 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12191 (let* ((group gnus-newsgroup-name)
12192 (article (gnus-summary-article-number))
12193 (header (gnus-summary-article-header article))
12194 (from (mail-header-from header))
12195 (message-id (mail-header-id header))
12196 (date (mail-header-date header))
12197 (subject (gnus-summary-subject-string)))
12198 (org-store-link-props :type "gnus" :from from :subject subject
12199 :message-id message-id :group group)
12200 (setq cpltxt (org-email-link-description))
12201 (if (org-xor arg org-usenet-links-prefer-google)
12202 (setq link
12203 (concat
12204 cpltxt "\n "
12205 (format "http://groups.google.com/groups?as_umsgid=%s"
12206 (org-fixup-message-id-for-http message-id))))
12207 (setq link (org-make-link "gnus:" group
12208 "#" (number-to-string article))))))
12210 ((eq major-mode 'w3-mode)
12211 (setq cpltxt (url-view-url t)
12212 link (org-make-link cpltxt))
12213 (org-store-link-props :type "w3" :url (url-view-url t)))
12215 ((eq major-mode 'w3m-mode)
12216 (setq cpltxt (or w3m-current-title w3m-current-url)
12217 link (org-make-link w3m-current-url))
12218 (org-store-link-props :type "w3m" :url (url-view-url t)))
12220 ((setq search (run-hook-with-args-until-success
12221 'org-create-file-search-functions))
12222 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12223 "::" search))
12224 (setq cpltxt (or description link)))
12226 ((eq major-mode 'image-mode)
12227 (setq cpltxt (concat "file:"
12228 (abbreviate-file-name buffer-file-name))
12229 link (org-make-link cpltxt))
12230 (org-store-link-props :type "image" :file buffer-file-name))
12232 ((eq major-mode 'dired-mode)
12233 ;; link to the file in the current line
12234 (setq cpltxt (concat "file:"
12235 (abbreviate-file-name
12236 (expand-file-name
12237 (dired-get-filename nil t))))
12238 link (org-make-link cpltxt)))
12240 ((and buffer-file-name (org-mode-p))
12241 ;; Just link to current headline
12242 (setq cpltxt (concat "file:"
12243 (abbreviate-file-name buffer-file-name)))
12244 ;; Add a context search string
12245 (when (org-xor org-context-in-file-links arg)
12246 ;; Check if we are on a target
12247 (if (org-in-regexp "<<\\(.*?\\)>>")
12248 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12249 (setq txt (cond
12250 ((org-on-heading-p) nil)
12251 ((org-region-active-p)
12252 (buffer-substring (region-beginning) (region-end)))
12253 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12254 (when (or (null txt) (string-match "\\S-" txt))
12255 (setq cpltxt
12256 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12257 desc "NONE"))))
12258 (if (string-match "::\\'" cpltxt)
12259 (setq cpltxt (substring cpltxt 0 -2)))
12260 (setq link (org-make-link cpltxt)))
12262 ((buffer-file-name (buffer-base-buffer))
12263 ;; Just link to this file here.
12264 (setq cpltxt (concat "file:"
12265 (abbreviate-file-name
12266 (buffer-file-name (buffer-base-buffer)))))
12267 ;; Add a context string
12268 (when (org-xor org-context-in-file-links arg)
12269 (setq txt (if (org-region-active-p)
12270 (buffer-substring (region-beginning) (region-end))
12271 (buffer-substring (point-at-bol) (point-at-eol))))
12272 ;; Only use search option if there is some text.
12273 (when (string-match "\\S-" txt)
12274 (setq cpltxt
12275 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12276 desc "NONE")))
12277 (setq link (org-make-link cpltxt)))
12279 ((interactive-p)
12280 (error "Cannot link to a buffer which is not visiting a file"))
12282 (t (setq link nil)))
12284 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12285 (setq link (or link cpltxt)
12286 desc (or desc cpltxt))
12287 (if (equal desc "NONE") (setq desc nil))
12289 (if (and (interactive-p) link)
12290 (progn
12291 (setq org-stored-links
12292 (cons (list link desc) org-stored-links))
12293 (message "Stored: %s" (or desc link)))
12294 (and link (org-make-link-string link desc)))))
12296 (defun org-store-link-props (&rest plist)
12297 "Store link properties, extract names and addresses."
12298 (let (x adr)
12299 (when (setq x (plist-get plist :from))
12300 (setq adr (mail-extract-address-components x))
12301 (plist-put plist :fromname (car adr))
12302 (plist-put plist :fromaddress (nth 1 adr)))
12303 (when (setq x (plist-get plist :to))
12304 (setq adr (mail-extract-address-components x))
12305 (plist-put plist :toname (car adr))
12306 (plist-put plist :toaddress (nth 1 adr))))
12307 (let ((from (plist-get plist :from))
12308 (to (plist-get plist :to)))
12309 (when (and from to org-from-is-user-regexp)
12310 (plist-put plist :fromto
12311 (if (string-match org-from-is-user-regexp from)
12312 (concat "to %t")
12313 (concat "from %f")))))
12314 (setq org-store-link-plist plist))
12316 (defun org-email-link-description (&optional fmt)
12317 "Return the description part of an email link.
12318 This takes information from `org-store-link-plist' and formats it
12319 according to FMT (default from `org-email-link-description-format')."
12320 (setq fmt (or fmt org-email-link-description-format))
12321 (let* ((p org-store-link-plist)
12322 (to (plist-get p :toaddress))
12323 (from (plist-get p :fromaddress))
12324 (table
12325 (list
12326 (cons "%c" (plist-get p :fromto))
12327 (cons "%F" (plist-get p :from))
12328 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12329 (cons "%T" (plist-get p :to))
12330 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12331 (cons "%s" (plist-get p :subject))
12332 (cons "%m" (plist-get p :message-id)))))
12333 (when (string-match "%c" fmt)
12334 ;; Check if the user wrote this message
12335 (if (and org-from-is-user-regexp from to
12336 (save-match-data (string-match org-from-is-user-regexp from)))
12337 (setq fmt (replace-match "to %t" t t fmt))
12338 (setq fmt (replace-match "from %f" t t fmt))))
12339 (org-replace-escapes fmt table)))
12341 (defun org-make-org-heading-search-string (&optional string heading)
12342 "Make search string for STRING or current headline."
12343 (interactive)
12344 (let ((s (or string (org-get-heading))))
12345 (unless (and string (not heading))
12346 ;; We are using a headline, clean up garbage in there.
12347 (if (string-match org-todo-regexp s)
12348 (setq s (replace-match "" t t s)))
12349 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12350 (setq s (replace-match "" t t s)))
12351 (setq s (org-trim s))
12352 (if (string-match (concat "^\\(" org-quote-string "\\|"
12353 org-comment-string "\\)") s)
12354 (setq s (replace-match "" t t s)))
12355 (while (string-match org-ts-regexp s)
12356 (setq s (replace-match "" t t s))))
12357 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12358 (setq s (replace-match " " t t s)))
12359 (or string (setq s (concat "*" s))) ; Add * for headlines
12360 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12362 (defun org-make-link (&rest strings)
12363 "Concatenate STRINGS."
12364 (apply 'concat strings))
12366 (defun org-make-link-string (link &optional description)
12367 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12368 (unless (string-match "\\S-" link)
12369 (error "Empty link"))
12370 (when (stringp description)
12371 ;; Remove brackets from the description, they are fatal.
12372 (while (string-match "\\[" description)
12373 (setq description (replace-match "{" t t description)))
12374 (while (string-match "\\]" description)
12375 (setq description (replace-match "}" t t description))))
12376 (when (equal (org-link-escape link) description)
12377 ;; No description needed, it is identical
12378 (setq description nil))
12379 (when (and (not description)
12380 (not (equal link (org-link-escape link))))
12381 (setq description link))
12382 (concat "[[" (org-link-escape link) "]"
12383 (if description (concat "[" description "]") "")
12384 "]"))
12386 (defconst org-link-escape-chars
12387 '((?\ . "%20")
12388 (?\[ . "%5B")
12389 (?\] . "%5D")
12390 (?\340 . "%E0") ; `a
12391 (?\342 . "%E2") ; ^a
12392 (?\347 . "%E7") ; ,c
12393 (?\350 . "%E8") ; `e
12394 (?\351 . "%E9") ; 'e
12395 (?\352 . "%EA") ; ^e
12396 (?\356 . "%EE") ; ^i
12397 (?\364 . "%F4") ; ^o
12398 (?\371 . "%F9") ; `u
12399 (?\373 . "%FB") ; ^u
12400 (?\; . "%3B")
12401 (?? . "%3F")
12402 (?= . "%3D")
12403 (?+ . "%2B")
12405 "Association list of escapes for some characters problematic in links.
12406 This is the list that is used for internal purposes.")
12408 (defconst org-link-escape-chars-browser
12409 '((?\ . "%20")) ; 32 for the SPC char
12410 "Association list of escapes for some characters problematic in links.
12411 This is the list that is used before handing over to the browser.")
12413 (defun org-link-escape (text &optional table)
12414 "Escape charaters in TEXT that are problematic for links."
12415 (setq table (or table org-link-escape-chars))
12416 (when text
12417 (let ((re (mapconcat (lambda (x) (regexp-quote
12418 (char-to-string (car x))))
12419 table "\\|")))
12420 (while (string-match re text)
12421 (setq text
12422 (replace-match
12423 (cdr (assoc (string-to-char (match-string 0 text))
12424 table))
12425 t t text)))
12426 text)))
12428 (defun org-link-unescape (text &optional table)
12429 "Reverse the action of `org-link-escape'."
12430 (setq table (or table org-link-escape-chars))
12431 (when text
12432 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12433 table "\\|")))
12434 (while (string-match re text)
12435 (setq text
12436 (replace-match
12437 (char-to-string (car (rassoc (match-string 0 text) table)))
12438 t t text)))
12439 text)))
12441 (defun org-xor (a b)
12442 "Exclusive or."
12443 (if a (not b) b))
12445 (defun org-get-header (header)
12446 "Find a header field in the current buffer."
12447 (save-excursion
12448 (goto-char (point-min))
12449 (let ((case-fold-search t) s)
12450 (cond
12451 ((eq header 'from)
12452 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12453 (setq s (match-string 1)))
12454 (while (string-match "\"" s)
12455 (setq s (replace-match "" t t s)))
12456 (if (string-match "[<(].*" s)
12457 (setq s (replace-match "" t t s))))
12458 ((eq header 'message-id)
12459 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12460 (setq s (match-string 1))))
12461 ((eq header 'subject)
12462 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12463 (setq s (match-string 1)))))
12464 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12465 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12466 s)))
12469 (defun org-fixup-message-id-for-http (s)
12470 "Replace special characters in a message id, so it can be used in an http query."
12471 (while (string-match "<" s)
12472 (setq s (replace-match "%3C" t t s)))
12473 (while (string-match ">" s)
12474 (setq s (replace-match "%3E" t t s)))
12475 (while (string-match "@" s)
12476 (setq s (replace-match "%40" t t s)))
12479 ;;;###autoload
12480 (defun org-insert-link-global ()
12481 "Insert a link like Org-mode does.
12482 This command can be called in any mode to insert a link in Org-mode syntax."
12483 (interactive)
12484 (org-run-like-in-org-mode 'org-insert-link))
12486 (defun org-insert-link (&optional complete-file)
12487 "Insert a link. At the prompt, enter the link.
12489 Completion can be used to select a link previously stored with
12490 `org-store-link'. When the empty string is entered (i.e. if you just
12491 press RET at the prompt), the link defaults to the most recently
12492 stored link. As SPC triggers completion in the minibuffer, you need to
12493 use M-SPC or C-q SPC to force the insertion of a space character.
12495 You will also be prompted for a description, and if one is given, it will
12496 be displayed in the buffer instead of the link.
12498 If there is already a link at point, this command will allow you to edit link
12499 and description parts.
12501 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12502 selected using completion. The path to the file will be relative to
12503 the current directory if the file is in the current directory or a
12504 subdirectory. Otherwise, the link will be the absolute path as
12505 completed in the minibuffer (i.e. normally ~/path/to/file).
12507 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12508 is in the current directory or below.
12509 With three \\[universal-argument] prefixes, negate the meaning of
12510 `org-keep-stored-link-after-insertion'."
12511 (interactive "P")
12512 (let* ((wcf (current-window-configuration))
12513 (region (if (org-region-active-p)
12514 (buffer-substring (region-beginning) (region-end))))
12515 (remove (and region (list (region-beginning) (region-end))))
12516 (desc region)
12517 tmphist ; byte-compile incorrectly complains about this
12518 link entry file)
12519 (cond
12520 ((org-in-regexp org-bracket-link-regexp 1)
12521 ;; We do have a link at point, and we are going to edit it.
12522 (setq remove (list (match-beginning 0) (match-end 0)))
12523 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12524 (setq link (read-string "Link: "
12525 (org-link-unescape
12526 (org-match-string-no-properties 1)))))
12527 ((or (org-in-regexp org-angle-link-re)
12528 (org-in-regexp org-plain-link-re))
12529 ;; Convert to bracket link
12530 (setq remove (list (match-beginning 0) (match-end 0))
12531 link (read-string "Link: "
12532 (org-remove-angle-brackets (match-string 0)))))
12533 ((equal complete-file '(4))
12534 ;; Completing read for file names.
12535 (setq file (read-file-name "File: "))
12536 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12537 (pwd1 (file-name-as-directory (abbreviate-file-name
12538 (expand-file-name ".")))))
12539 (cond
12540 ((equal complete-file '(16))
12541 (setq link (org-make-link
12542 "file:"
12543 (abbreviate-file-name (expand-file-name file)))))
12544 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12545 (setq link (org-make-link "file:" (match-string 1 file))))
12546 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12547 (expand-file-name file))
12548 (setq link (org-make-link
12549 "file:" (match-string 1 (expand-file-name file)))))
12550 (t (setq link (org-make-link "file:" file))))))
12552 ;; Read link, with completion for stored links.
12553 (with-output-to-temp-buffer "*Org Links*"
12554 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12555 (when org-stored-links
12556 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12557 (princ (mapconcat
12558 (lambda (x)
12559 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12560 (reverse org-stored-links) "\n"))))
12561 (let ((cw (selected-window)))
12562 (select-window (get-buffer-window "*Org Links*"))
12563 (shrink-window-if-larger-than-buffer)
12564 (setq truncate-lines t)
12565 (select-window cw))
12566 ;; Fake a link history, containing the stored links.
12567 (setq tmphist (append (mapcar 'car org-stored-links)
12568 org-insert-link-history))
12569 (unwind-protect
12570 (setq link (org-completing-read
12571 "Link: "
12572 (append
12573 (mapcar (lambda (x) (list (concat (car x) ":")))
12574 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12575 (mapcar (lambda (x) (list (concat x ":")))
12576 org-link-types))
12577 nil nil nil
12578 'tmphist
12579 (or (car (car org-stored-links)))))
12580 (set-window-configuration wcf)
12581 (kill-buffer "*Org Links*"))
12582 (setq entry (assoc link org-stored-links))
12583 (or entry (push link org-insert-link-history))
12584 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12585 (not org-keep-stored-link-after-insertion))
12586 (setq org-stored-links (delq (assoc link org-stored-links)
12587 org-stored-links)))
12588 (setq desc (or desc (nth 1 entry)))))
12590 (if (string-match org-plain-link-re link)
12591 ;; URL-like link, normalize the use of angular brackets.
12592 (setq link (org-make-link (org-remove-angle-brackets link))))
12594 ;; Check if we are linking to the current file with a search option
12595 ;; If yes, simplify the link by using only the search option.
12596 (when (and buffer-file-name
12597 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12598 (let* ((path (match-string 1 link))
12599 (case-fold-search nil)
12600 (search (match-string 2 link)))
12601 (save-match-data
12602 (if (equal (file-truename buffer-file-name) (file-truename path))
12603 ;; We are linking to this same file, with a search option
12604 (setq link search)))))
12606 ;; Check if we can/should use a relative path. If yes, simplify the link
12607 (when (string-match "\\<file:\\(.*\\)" link)
12608 (let* ((path (match-string 1 link))
12609 (origpath path)
12610 (case-fold-search nil))
12611 (cond
12612 ((eq org-link-file-path-type 'absolute)
12613 (setq path (abbreviate-file-name (expand-file-name path))))
12614 ((eq org-link-file-path-type 'noabbrev)
12615 (setq path (expand-file-name path)))
12616 ((eq org-link-file-path-type 'relative)
12617 (setq path (file-relative-name path)))
12619 (save-match-data
12620 (if (string-match (concat "^" (regexp-quote
12621 (file-name-as-directory
12622 (expand-file-name "."))))
12623 (expand-file-name path))
12624 ;; We are linking a file with relative path name.
12625 (setq path (substring (expand-file-name path)
12626 (match-end 0)))))))
12627 (setq link (concat "file:" path))
12628 (if (equal desc origpath)
12629 (setq desc path))))
12631 (setq desc (read-string "Description: " desc))
12632 (unless (string-match "\\S-" desc) (setq desc nil))
12633 (if remove (apply 'delete-region remove))
12634 (insert (org-make-link-string link desc))))
12636 (defun org-completing-read (&rest args)
12637 (let ((minibuffer-local-completion-map
12638 (copy-keymap minibuffer-local-completion-map)))
12639 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12640 (apply 'completing-read args)))
12642 ;;; Opening/following a link
12643 (defvar org-link-search-failed nil)
12645 (defun org-next-link ()
12646 "Move forward to the next link.
12647 If the link is in hidden text, expose it."
12648 (interactive)
12649 (when (and org-link-search-failed (eq this-command last-command))
12650 (goto-char (point-min))
12651 (message "Link search wrapped back to beginning of buffer"))
12652 (setq org-link-search-failed nil)
12653 (let* ((pos (point))
12654 (ct (org-context))
12655 (a (assoc :link ct)))
12656 (if a (goto-char (nth 2 a)))
12657 (if (re-search-forward org-any-link-re nil t)
12658 (progn
12659 (goto-char (match-beginning 0))
12660 (if (org-invisible-p) (org-show-context)))
12661 (goto-char pos)
12662 (setq org-link-search-failed t)
12663 (error "No further link found"))))
12665 (defun org-previous-link ()
12666 "Move backward to the previous link.
12667 If the link is in hidden text, expose it."
12668 (interactive)
12669 (when (and org-link-search-failed (eq this-command last-command))
12670 (goto-char (point-max))
12671 (message "Link search wrapped back to end of buffer"))
12672 (setq org-link-search-failed nil)
12673 (let* ((pos (point))
12674 (ct (org-context))
12675 (a (assoc :link ct)))
12676 (if a (goto-char (nth 1 a)))
12677 (if (re-search-backward org-any-link-re nil t)
12678 (progn
12679 (goto-char (match-beginning 0))
12680 (if (org-invisible-p) (org-show-context)))
12681 (goto-char pos)
12682 (setq org-link-search-failed t)
12683 (error "No further link found"))))
12685 (defun org-find-file-at-mouse (ev)
12686 "Open file link or URL at mouse."
12687 (interactive "e")
12688 (mouse-set-point ev)
12689 (org-open-at-point 'in-emacs))
12691 (defun org-open-at-mouse (ev)
12692 "Open file link or URL at mouse."
12693 (interactive "e")
12694 (mouse-set-point ev)
12695 (org-open-at-point))
12697 (defvar org-window-config-before-follow-link nil
12698 "The window configuration before following a link.
12699 This is saved in case the need arises to restore it.")
12701 (defvar org-open-link-marker (make-marker)
12702 "Marker pointing to the location where `org-open-at-point; was called.")
12704 ;;;###autoload
12705 (defun org-open-at-point-global ()
12706 "Follow a link like Org-mode does.
12707 This command can be called in any mode to follow a link that has
12708 Org-mode syntax."
12709 (interactive)
12710 (org-run-like-in-org-mode 'org-open-at-point))
12712 (defun org-open-at-point (&optional in-emacs)
12713 "Open link at or after point.
12714 If there is no link at point, this function will search forward up to
12715 the end of the current subtree.
12716 Normally, files will be opened by an appropriate application. If the
12717 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12718 (interactive "P")
12719 (move-marker org-open-link-marker (point))
12720 (setq org-window-config-before-follow-link (current-window-configuration))
12721 (org-remove-occur-highlights nil nil t)
12722 (if (org-at-timestamp-p t)
12723 (org-follow-timestamp-link)
12724 (let (type path link line search (pos (point)))
12725 (catch 'match
12726 (save-excursion
12727 (skip-chars-forward "^]\n\r")
12728 (when (org-in-regexp org-bracket-link-regexp)
12729 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12730 (while (string-match " *\n *" link)
12731 (setq link (replace-match " " t t link)))
12732 (setq link (org-link-expand-abbrev link))
12733 (if (string-match org-link-re-with-space2 link)
12734 (setq type (match-string 1 link) path (match-string 2 link))
12735 (setq type "thisfile" path link))
12736 (throw 'match t)))
12738 (when (get-text-property (point) 'org-linked-text)
12739 (setq type "thisfile"
12740 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12741 (1+ (point)) (point))
12742 path (buffer-substring
12743 (previous-single-property-change pos 'org-linked-text)
12744 (next-single-property-change pos 'org-linked-text)))
12745 (throw 'match t))
12747 (save-excursion
12748 (when (or (org-in-regexp org-angle-link-re)
12749 (org-in-regexp org-plain-link-re))
12750 (setq type (match-string 1) path (match-string 2))
12751 (throw 'match t)))
12752 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12753 (setq type "tree-match"
12754 path (match-string 1))
12755 (throw 'match t))
12756 (save-excursion
12757 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12758 (setq type "tags"
12759 path (match-string 1))
12760 (while (string-match ":" path)
12761 (setq path (replace-match "+" t t path)))
12762 (throw 'match t))))
12763 (unless path
12764 (error "No link found"))
12765 ;; Remove any trailing spaces in path
12766 (if (string-match " +\\'" path)
12767 (setq path (replace-match "" t t path)))
12769 (cond
12771 ((assoc type org-link-protocols)
12772 (funcall (nth 1 (assoc type org-link-protocols)) path))
12774 ((equal type "mailto")
12775 (let ((cmd (car org-link-mailto-program))
12776 (args (cdr org-link-mailto-program)) args1
12777 (address path) (subject "") a)
12778 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12779 (setq address (match-string 1 path)
12780 subject (org-link-escape (match-string 2 path))))
12781 (while args
12782 (cond
12783 ((not (stringp (car args))) (push (pop args) args1))
12784 (t (setq a (pop args))
12785 (if (string-match "%a" a)
12786 (setq a (replace-match address t t a)))
12787 (if (string-match "%s" a)
12788 (setq a (replace-match subject t t a)))
12789 (push a args1))))
12790 (apply cmd (nreverse args1))))
12792 ((member type '("http" "https" "ftp" "news"))
12793 (browse-url (concat type ":" (org-link-escape
12794 path org-link-escape-chars-browser))))
12796 ((member type '("message"))
12797 (browse-url (concat type ":" path)))
12799 ((string= type "tags")
12800 (org-tags-view in-emacs path))
12801 ((string= type "thisfile")
12802 (if in-emacs
12803 (switch-to-buffer-other-window
12804 (org-get-buffer-for-internal-link (current-buffer)))
12805 (org-mark-ring-push))
12806 (let ((cmd `(org-link-search
12807 ,path
12808 ,(cond ((equal in-emacs '(4)) 'occur)
12809 ((equal in-emacs '(16)) 'org-occur)
12810 (t nil))
12811 ,pos)))
12812 (condition-case nil (eval cmd)
12813 (error (progn (widen) (eval cmd))))))
12815 ((string= type "tree-match")
12816 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12818 ((string= type "file")
12819 (if (string-match "::\\([0-9]+\\)\\'" path)
12820 (setq line (string-to-number (match-string 1 path))
12821 path (substring path 0 (match-beginning 0)))
12822 (if (string-match "::\\(.+\\)\\'" path)
12823 (setq search (match-string 1 path)
12824 path (substring path 0 (match-beginning 0)))))
12825 (if (string-match "[*?{]" (file-name-nondirectory path))
12826 (dired path)
12827 (org-open-file path in-emacs line search)))
12829 ((string= type "news")
12830 (org-follow-gnus-link path))
12832 ((string= type "bbdb")
12833 (org-follow-bbdb-link path))
12835 ((string= type "info")
12836 (org-follow-info-link path))
12838 ((string= type "gnus")
12839 (let (group article)
12840 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12841 (error "Error in Gnus link"))
12842 (setq group (match-string 1 path)
12843 article (match-string 3 path))
12844 (org-follow-gnus-link group article)))
12846 ((string= type "vm")
12847 (let (folder article)
12848 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12849 (error "Error in VM link"))
12850 (setq folder (match-string 1 path)
12851 article (match-string 3 path))
12852 ;; in-emacs is the prefix arg, will be interpreted as read-only
12853 (org-follow-vm-link folder article in-emacs)))
12855 ((string= type "wl")
12856 (let (folder article)
12857 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12858 (error "Error in Wanderlust link"))
12859 (setq folder (match-string 1 path)
12860 article (match-string 3 path))
12861 (org-follow-wl-link folder article)))
12863 ((string= type "mhe")
12864 (let (folder article)
12865 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12866 (error "Error in MHE link"))
12867 (setq folder (match-string 1 path)
12868 article (match-string 3 path))
12869 (org-follow-mhe-link folder article)))
12871 ((string= type "rmail")
12872 (let (folder article)
12873 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12874 (error "Error in RMAIL link"))
12875 (setq folder (match-string 1 path)
12876 article (match-string 3 path))
12877 (org-follow-rmail-link folder article)))
12879 ((string= type "shell")
12880 (let ((cmd path))
12881 (if (or (not org-confirm-shell-link-function)
12882 (funcall org-confirm-shell-link-function
12883 (format "Execute \"%s\" in shell? "
12884 (org-add-props cmd nil
12885 'face 'org-warning))))
12886 (progn
12887 (message "Executing %s" cmd)
12888 (shell-command cmd))
12889 (error "Abort"))))
12891 ((string= type "elisp")
12892 (let ((cmd path))
12893 (if (or (not org-confirm-elisp-link-function)
12894 (funcall org-confirm-elisp-link-function
12895 (format "Execute \"%s\" as elisp? "
12896 (org-add-props cmd nil
12897 'face 'org-warning))))
12898 (message "%s => %s" cmd (eval (read cmd)))
12899 (error "Abort"))))
12902 (browse-url-at-point)))))
12903 (move-marker org-open-link-marker nil))
12905 ;;; File search
12907 (defvar org-create-file-search-functions nil
12908 "List of functions to construct the right search string for a file link.
12909 These functions are called in turn with point at the location to
12910 which the link should point.
12912 A function in the hook should first test if it would like to
12913 handle this file type, for example by checking the major-mode or
12914 the file extension. If it decides not to handle this file, it
12915 should just return nil to give other functions a chance. If it
12916 does handle the file, it must return the search string to be used
12917 when following the link. The search string will be part of the
12918 file link, given after a double colon, and `org-open-at-point'
12919 will automatically search for it. If special measures must be
12920 taken to make the search successful, another function should be
12921 added to the companion hook `org-execute-file-search-functions',
12922 which see.
12924 A function in this hook may also use `setq' to set the variable
12925 `description' to provide a suggestion for the descriptive text to
12926 be used for this link when it gets inserted into an Org-mode
12927 buffer with \\[org-insert-link].")
12929 (defvar org-execute-file-search-functions nil
12930 "List of functions to execute a file search triggered by a link.
12932 Functions added to this hook must accept a single argument, the
12933 search string that was part of the file link, the part after the
12934 double colon. The function must first check if it would like to
12935 handle this search, for example by checking the major-mode or the
12936 file extension. If it decides not to handle this search, it
12937 should just return nil to give other functions a chance. If it
12938 does handle the search, it must return a non-nil value to keep
12939 other functions from trying.
12941 Each function can access the current prefix argument through the
12942 variable `current-prefix-argument'. Note that a single prefix is
12943 used to force opening a link in Emacs, so it may be good to only
12944 use a numeric or double prefix to guide the search function.
12946 In case this is needed, a function in this hook can also restore
12947 the window configuration before `org-open-at-point' was called using:
12949 (set-window-configuration org-window-config-before-follow-link)")
12951 (defun org-link-search (s &optional type avoid-pos)
12952 "Search for a link search option.
12953 If S is surrounded by forward slashes, it is interpreted as a
12954 regular expression. In org-mode files, this will create an `org-occur'
12955 sparse tree. In ordinary files, `occur' will be used to list matches.
12956 If the current buffer is in `dired-mode', grep will be used to search
12957 in all files. If AVOID-POS is given, ignore matches near that position."
12958 (let ((case-fold-search t)
12959 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12960 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12961 (append '(("") (" ") ("\t") ("\n"))
12962 org-emphasis-alist)
12963 "\\|") "\\)"))
12964 (pos (point))
12965 (pre "") (post "")
12966 words re0 re1 re2 re3 re4 re5 re2a reall)
12967 (cond
12968 ;; First check if there are any special
12969 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12970 ;; Now try the builtin stuff
12971 ((save-excursion
12972 (goto-char (point-min))
12973 (and
12974 (re-search-forward
12975 (concat "<<" (regexp-quote s0) ">>") nil t)
12976 (setq pos (match-beginning 0))))
12977 ;; There is an exact target for this
12978 (goto-char pos))
12979 ((string-match "^/\\(.*\\)/$" s)
12980 ;; A regular expression
12981 (cond
12982 ((org-mode-p)
12983 (org-occur (match-string 1 s)))
12984 ;;((eq major-mode 'dired-mode)
12985 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12986 (t (org-do-occur (match-string 1 s)))))
12988 ;; A normal search strings
12989 (when (equal (string-to-char s) ?*)
12990 ;; Anchor on headlines, post may include tags.
12991 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12992 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12993 s (substring s 1)))
12994 (remove-text-properties
12995 0 (length s)
12996 '(face nil mouse-face nil keymap nil fontified nil) s)
12997 ;; Make a series of regular expressions to find a match
12998 (setq words (org-split-string s "[ \n\r\t]+")
12999 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
13000 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
13001 "\\)" markers)
13002 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13003 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13004 re1 (concat pre re2 post)
13005 re3 (concat pre re4 post)
13006 re5 (concat pre ".*" re4)
13007 re2 (concat pre re2)
13008 re2a (concat pre re2a)
13009 re4 (concat pre re4)
13010 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13011 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13012 re5 "\\)"
13014 (cond
13015 ((eq type 'org-occur) (org-occur reall))
13016 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13017 (t (goto-char (point-min))
13018 (if (or (org-search-not-self 1 re0 nil t)
13019 (org-search-not-self 1 re1 nil t)
13020 (org-search-not-self 1 re2 nil t)
13021 (org-search-not-self 1 re2a nil t)
13022 (org-search-not-self 1 re3 nil t)
13023 (org-search-not-self 1 re4 nil t)
13024 (org-search-not-self 1 re5 nil t)
13026 (goto-char (match-beginning 1))
13027 (goto-char pos)
13028 (error "No match")))))
13030 ;; Normal string-search
13031 (goto-char (point-min))
13032 (if (search-forward s nil t)
13033 (goto-char (match-beginning 0))
13034 (error "No match"))))
13035 (and (org-mode-p) (org-show-context 'link-search))))
13037 (defun org-search-not-self (group &rest args)
13038 "Execute `re-search-forward', but only accept matches that do not
13039 enclose the position of `org-open-link-marker'."
13040 (let ((m org-open-link-marker))
13041 (catch 'exit
13042 (while (apply 're-search-forward args)
13043 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13044 (goto-char (match-end group))
13045 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13046 (> (match-beginning 0) (marker-position m))
13047 (< (match-end 0) (marker-position m)))
13048 (save-match-data
13049 (or (not (org-in-regexp
13050 org-bracket-link-analytic-regexp 1))
13051 (not (match-end 4)) ; no description
13052 (and (<= (match-beginning 4) (point))
13053 (>= (match-end 4) (point))))))
13054 (throw 'exit (point))))))))
13056 (defun org-get-buffer-for-internal-link (buffer)
13057 "Return a buffer to be used for displaying the link target of internal links."
13058 (cond
13059 ((not org-display-internal-link-with-indirect-buffer)
13060 buffer)
13061 ((string-match "(Clone)$" (buffer-name buffer))
13062 (message "Buffer is already a clone, not making another one")
13063 ;; we also do not modify visibility in this case
13064 buffer)
13065 (t ; make a new indirect buffer for displaying the link
13066 (let* ((bn (buffer-name buffer))
13067 (ibn (concat bn "(Clone)"))
13068 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13069 (with-current-buffer ib (org-overview))
13070 ib))))
13072 (defun org-do-occur (regexp &optional cleanup)
13073 "Call the Emacs command `occur'.
13074 If CLEANUP is non-nil, remove the printout of the regular expression
13075 in the *Occur* buffer. This is useful if the regex is long and not useful
13076 to read."
13077 (occur regexp)
13078 (when cleanup
13079 (let ((cwin (selected-window)) win beg end)
13080 (when (setq win (get-buffer-window "*Occur*"))
13081 (select-window win))
13082 (goto-char (point-min))
13083 (when (re-search-forward "match[a-z]+" nil t)
13084 (setq beg (match-end 0))
13085 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13086 (setq end (1- (match-beginning 0)))))
13087 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13088 (goto-char (point-min))
13089 (select-window cwin))))
13091 ;;; The mark ring for links jumps
13093 (defvar org-mark-ring nil
13094 "Mark ring for positions before jumps in Org-mode.")
13095 (defvar org-mark-ring-last-goto nil
13096 "Last position in the mark ring used to go back.")
13097 ;; Fill and close the ring
13098 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13099 (loop for i from 1 to org-mark-ring-length do
13100 (push (make-marker) org-mark-ring))
13101 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13102 org-mark-ring)
13104 (defun org-mark-ring-push (&optional pos buffer)
13105 "Put the current position or POS into the mark ring and rotate it."
13106 (interactive)
13107 (setq pos (or pos (point)))
13108 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13109 (move-marker (car org-mark-ring)
13110 (or pos (point))
13111 (or buffer (current-buffer)))
13112 (message "%s"
13113 (substitute-command-keys
13114 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13116 (defun org-mark-ring-goto (&optional n)
13117 "Jump to the previous position in the mark ring.
13118 With prefix arg N, jump back that many stored positions. When
13119 called several times in succession, walk through the entire ring.
13120 Org-mode commands jumping to a different position in the current file,
13121 or to another Org-mode file, automatically push the old position
13122 onto the ring."
13123 (interactive "p")
13124 (let (p m)
13125 (if (eq last-command this-command)
13126 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13127 (setq p org-mark-ring))
13128 (setq org-mark-ring-last-goto p)
13129 (setq m (car p))
13130 (switch-to-buffer (marker-buffer m))
13131 (goto-char m)
13132 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13134 (defun org-remove-angle-brackets (s)
13135 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13136 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13138 (defun org-add-angle-brackets (s)
13139 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13140 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13143 ;;; Following specific links
13145 (defun org-follow-timestamp-link ()
13146 (cond
13147 ((org-at-date-range-p t)
13148 (let ((org-agenda-start-on-weekday)
13149 (t1 (match-string 1))
13150 (t2 (match-string 2)))
13151 (setq t1 (time-to-days (org-time-string-to-time t1))
13152 t2 (time-to-days (org-time-string-to-time t2)))
13153 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13154 ((org-at-timestamp-p t)
13155 (org-agenda-list nil (time-to-days (org-time-string-to-time
13156 (substring (match-string 1) 0 10)))
13158 (t (error "This should not happen"))))
13161 (defun org-follow-bbdb-link (name)
13162 "Follow a BBDB link to NAME."
13163 (require 'bbdb)
13164 (let ((inhibit-redisplay (not debug-on-error))
13165 (bbdb-electric-p nil))
13166 (catch 'exit
13167 ;; Exact match on name
13168 (bbdb-name (concat "\\`" name "\\'") nil)
13169 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13170 ;; Exact match on name
13171 (bbdb-company (concat "\\`" name "\\'") nil)
13172 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13173 ;; Partial match on name
13174 (bbdb-name name nil)
13175 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13176 ;; Partial match on company
13177 (bbdb-company name nil)
13178 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13179 ;; General match including network address and notes
13180 (bbdb name nil)
13181 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13182 (delete-window (get-buffer-window "*BBDB*"))
13183 (error "No matching BBDB record")))))
13185 (defun org-follow-info-link (name)
13186 "Follow an info file & node link to NAME."
13187 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13188 (string-match "\\(.*\\)" name))
13189 (progn
13190 (require 'info)
13191 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13192 (Info-find-node (match-string 1 name) (match-string 2 name))
13193 (Info-find-node (match-string 1 name) "Top")))
13194 (message "Could not open: %s" name)))
13196 (defun org-follow-gnus-link (&optional group article)
13197 "Follow a Gnus link to GROUP and ARTICLE."
13198 (require 'gnus)
13199 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13200 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13201 (cond ((and group article)
13202 (gnus-group-read-group 1 nil group)
13203 (gnus-summary-goto-article (string-to-number article) nil t))
13204 (group (gnus-group-jump-to-group group))))
13206 (defun org-follow-vm-link (&optional folder article readonly)
13207 "Follow a VM link to FOLDER and ARTICLE."
13208 (require 'vm)
13209 (setq article (org-add-angle-brackets article))
13210 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13211 ;; ange-ftp or efs or tramp access
13212 (let ((user (or (match-string 1 folder) (user-login-name)))
13213 (host (match-string 2 folder))
13214 (file (match-string 3 folder)))
13215 (cond
13216 ((featurep 'tramp)
13217 ;; use tramp to access the file
13218 (if (featurep 'xemacs)
13219 (setq folder (format "[%s@%s]%s" user host file))
13220 (setq folder (format "/%s@%s:%s" user host file))))
13222 ;; use ange-ftp or efs
13223 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13224 (setq folder (format "/%s@%s:%s" user host file))))))
13225 (when folder
13226 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13227 (sit-for 0.1)
13228 (when article
13229 (vm-select-folder-buffer)
13230 (widen)
13231 (let ((case-fold-search t))
13232 (goto-char (point-min))
13233 (if (not (re-search-forward
13234 (concat "^" "message-id: *" (regexp-quote article))))
13235 (error "Could not find the specified message in this folder"))
13236 (vm-isearch-update)
13237 (vm-isearch-narrow)
13238 (vm-beginning-of-message)
13239 (vm-summarize)))))
13241 (defun org-follow-wl-link (folder article)
13242 "Follow a Wanderlust link to FOLDER and ARTICLE."
13243 (if (and (string= folder "%")
13244 article
13245 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13246 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13247 ;; Thus, we recompose folder and article ids.
13248 (setq folder (format "%s#%s" folder (match-string 1 article))
13249 article (match-string 3 article)))
13250 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13251 (error "No such folder: %s" folder))
13252 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13253 (and article
13254 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13255 (wl-summary-redisplay)))
13257 (defun org-follow-rmail-link (folder article)
13258 "Follow an RMAIL link to FOLDER and ARTICLE."
13259 (setq article (org-add-angle-brackets article))
13260 (let (message-number)
13261 (save-excursion
13262 (save-window-excursion
13263 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13264 (setq message-number
13265 (save-restriction
13266 (widen)
13267 (goto-char (point-max))
13268 (if (re-search-backward
13269 (concat "^Message-ID:\\s-+" (regexp-quote
13270 (or article "")))
13271 nil t)
13272 (rmail-what-message))))))
13273 (if message-number
13274 (progn
13275 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13276 (rmail-show-message message-number)
13277 message-number)
13278 (error "Message not found"))))
13280 ;;; mh-e integration based on planner-mode
13281 (defun org-mhe-get-message-real-folder ()
13282 "Return the name of the current message real folder, so if you use
13283 sequences, it will now work."
13284 (save-excursion
13285 (let* ((folder
13286 (if (equal major-mode 'mh-folder-mode)
13287 mh-current-folder
13288 ;; Refer to the show buffer
13289 mh-show-folder-buffer))
13290 (end-index
13291 (if (boundp 'mh-index-folder)
13292 (min (length mh-index-folder) (length folder))))
13294 ;; a simple test on mh-index-data does not work, because
13295 ;; mh-index-data is always nil in a show buffer.
13296 (if (and (boundp 'mh-index-folder)
13297 (string= mh-index-folder (substring folder 0 end-index)))
13298 (if (equal major-mode 'mh-show-mode)
13299 (save-window-excursion
13300 (let (pop-up-frames)
13301 (when (buffer-live-p (get-buffer folder))
13302 (progn
13303 (pop-to-buffer folder)
13304 (org-mhe-get-message-folder-from-index)
13307 (org-mhe-get-message-folder-from-index)
13309 folder
13313 (defun org-mhe-get-message-folder-from-index ()
13314 "Returns the name of the message folder in a index folder buffer."
13315 (save-excursion
13316 (mh-index-previous-folder)
13317 (re-search-forward "^\\(+.*\\)$" nil t)
13318 (message "%s" (match-string 1))))
13320 (defun org-mhe-get-message-folder ()
13321 "Return the name of the current message folder. Be careful if you
13322 use sequences."
13323 (save-excursion
13324 (if (equal major-mode 'mh-folder-mode)
13325 mh-current-folder
13326 ;; Refer to the show buffer
13327 mh-show-folder-buffer)))
13329 (defun org-mhe-get-message-num ()
13330 "Return the number of the current message. Be careful if you
13331 use sequences."
13332 (save-excursion
13333 (if (equal major-mode 'mh-folder-mode)
13334 (mh-get-msg-num nil)
13335 ;; Refer to the show buffer
13336 (mh-show-buffer-message-number))))
13338 (defun org-mhe-get-header (header)
13339 "Return a header of the message in folder mode. This will create a
13340 show buffer for the corresponding message. If you have a more clever
13341 idea..."
13342 (let* ((folder (org-mhe-get-message-folder))
13343 (num (org-mhe-get-message-num))
13344 (buffer (get-buffer-create (concat "show-" folder)))
13345 (header-field))
13346 (with-current-buffer buffer
13347 (mh-display-msg num folder)
13348 (if (equal major-mode 'mh-folder-mode)
13349 (mh-header-display)
13350 (mh-show-header-display))
13351 (set-buffer buffer)
13352 (setq header-field (mh-get-header-field header))
13353 (if (equal major-mode 'mh-folder-mode)
13354 (mh-show)
13355 (mh-show-show))
13356 header-field)))
13358 (defun org-follow-mhe-link (folder article)
13359 "Follow an MHE link to FOLDER and ARTICLE.
13360 If ARTICLE is nil FOLDER is shown. If the configuration variable
13361 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13362 ARTICLE is searched in all folders. Indexed searches (swish++,
13363 namazu, and others supported by MH-E) will always search in all
13364 folders."
13365 (require 'mh-e)
13366 (require 'mh-search)
13367 (require 'mh-utils)
13368 (mh-find-path)
13369 (if (not article)
13370 (mh-visit-folder (mh-normalize-folder-name folder))
13371 (setq article (org-add-angle-brackets article))
13372 (mh-search-choose)
13373 (if (equal mh-searcher 'pick)
13374 (progn
13375 (mh-search folder (list "--message-id" article))
13376 (when (and org-mhe-search-all-folders
13377 (not (org-mhe-get-message-real-folder)))
13378 (kill-this-buffer)
13379 (mh-search "+" (list "--message-id" article))))
13380 (mh-search "+" article))
13381 (if (org-mhe-get-message-real-folder)
13382 (mh-show-msg 1)
13383 (kill-this-buffer)
13384 (error "Message not found"))))
13386 ;;; BibTeX links
13388 ;; Use the custom search meachnism to construct and use search strings for
13389 ;; file links to BibTeX database entries.
13391 (defun org-create-file-search-in-bibtex ()
13392 "Create the search string and description for a BibTeX database entry."
13393 (when (eq major-mode 'bibtex-mode)
13394 ;; yes, we want to construct this search string.
13395 ;; Make a good description for this entry, using names, year and the title
13396 ;; Put it into the `description' variable which is dynamically scoped.
13397 (let ((bibtex-autokey-names 1)
13398 (bibtex-autokey-names-stretch 1)
13399 (bibtex-autokey-name-case-convert-function 'identity)
13400 (bibtex-autokey-name-separator " & ")
13401 (bibtex-autokey-additional-names " et al.")
13402 (bibtex-autokey-year-length 4)
13403 (bibtex-autokey-name-year-separator " ")
13404 (bibtex-autokey-titlewords 3)
13405 (bibtex-autokey-titleword-separator " ")
13406 (bibtex-autokey-titleword-case-convert-function 'identity)
13407 (bibtex-autokey-titleword-length 'infty)
13408 (bibtex-autokey-year-title-separator ": "))
13409 (setq description (bibtex-generate-autokey)))
13410 ;; Now parse the entry, get the key and return it.
13411 (save-excursion
13412 (bibtex-beginning-of-entry)
13413 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13415 (defun org-execute-file-search-in-bibtex (s)
13416 "Find the link search string S as a key for a database entry."
13417 (when (eq major-mode 'bibtex-mode)
13418 ;; Yes, we want to do the search in this file.
13419 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13420 (goto-char (point-min))
13421 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13422 (regexp-quote s) "[ \t\n]*,") nil t)
13423 (goto-char (match-beginning 0)))
13424 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13425 ;; Use double prefix to indicate that any web link should be browsed
13426 (let ((b (current-buffer)) (p (point)))
13427 ;; Restore the window configuration because we just use the web link
13428 (set-window-configuration org-window-config-before-follow-link)
13429 (save-excursion (set-buffer b) (goto-char p)
13430 (bibtex-url)))
13431 (recenter 0)) ; Move entry start to beginning of window
13432 ;; return t to indicate that the search is done.
13435 ;; Finally add the functions to the right hooks.
13436 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13437 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13439 ;; end of Bibtex link setup
13441 ;;; Following file links
13443 (defun org-open-file (path &optional in-emacs line search)
13444 "Open the file at PATH.
13445 First, this expands any special file name abbreviations. Then the
13446 configuration variable `org-file-apps' is checked if it contains an
13447 entry for this file type, and if yes, the corresponding command is launched.
13448 If no application is found, Emacs simply visits the file.
13449 With optional argument IN-EMACS, Emacs will visit the file.
13450 Optional LINE specifies a line to go to, optional SEARCH a string to
13451 search for. If LINE or SEARCH is given, the file will always be
13452 opened in Emacs.
13453 If the file does not exist, an error is thrown."
13454 (setq in-emacs (or in-emacs line search))
13455 (let* ((file (if (equal path "")
13456 buffer-file-name
13457 (substitute-in-file-name (expand-file-name path))))
13458 (apps (append org-file-apps (org-default-apps)))
13459 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13460 (dirp (if remp nil (file-directory-p file)))
13461 (dfile (downcase file))
13462 (old-buffer (current-buffer))
13463 (old-pos (point))
13464 (old-mode major-mode)
13465 ext cmd)
13466 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13467 (setq ext (match-string 1 dfile))
13468 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13469 (setq ext (match-string 1 dfile))))
13470 (if in-emacs
13471 (setq cmd 'emacs)
13472 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13473 (and dirp (cdr (assoc 'directory apps)))
13474 (cdr (assoc ext apps))
13475 (cdr (assoc t apps)))))
13476 (when (eq cmd 'mailcap)
13477 (require 'mailcap)
13478 (mailcap-parse-mailcaps)
13479 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13480 (command (mailcap-mime-info mime-type)))
13481 (if (stringp command)
13482 (setq cmd command)
13483 (setq cmd 'emacs))))
13484 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13485 (not (file-exists-p file))
13486 (not org-open-non-existing-files))
13487 (error "No such file: %s" file))
13488 (cond
13489 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13490 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13491 (while (string-match "['\"]%s['\"]" cmd)
13492 (setq cmd (replace-match "%s" t t cmd)))
13493 (while (string-match "%s" cmd)
13494 (setq cmd (replace-match
13495 (save-match-data (shell-quote-argument file))
13496 t t cmd)))
13497 (save-window-excursion
13498 (start-process-shell-command cmd nil cmd)))
13499 ((or (stringp cmd)
13500 (eq cmd 'emacs))
13501 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13502 (widen)
13503 (if line (goto-line line)
13504 (if search (org-link-search search))))
13505 ((consp cmd)
13506 (eval cmd))
13507 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13508 (and (org-mode-p) (eq old-mode 'org-mode)
13509 (or (not (equal old-buffer (current-buffer)))
13510 (not (equal old-pos (point))))
13511 (org-mark-ring-push old-pos old-buffer))))
13513 (defun org-default-apps ()
13514 "Return the default applications for this operating system."
13515 (cond
13516 ((eq system-type 'darwin)
13517 org-file-apps-defaults-macosx)
13518 ((eq system-type 'windows-nt)
13519 org-file-apps-defaults-windowsnt)
13520 (t org-file-apps-defaults-gnu)))
13522 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13523 (defun org-file-remote-p (file)
13524 "Test whether FILE specifies a location on a remote system.
13525 Return non-nil if the location is indeed remote.
13527 For example, the filename \"/user@host:/foo\" specifies a location
13528 on the system \"/user@host:\"."
13529 (cond ((fboundp 'file-remote-p)
13530 (file-remote-p file))
13531 ((fboundp 'tramp-handle-file-remote-p)
13532 (tramp-handle-file-remote-p file))
13533 ((and (boundp 'ange-ftp-name-format)
13534 (string-match (car ange-ftp-name-format) file))
13536 (t nil)))
13539 ;;;; Hooks for remember.el, and refiling
13541 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13542 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13544 ;;;###autoload
13545 (defun org-remember-insinuate ()
13546 "Setup remember.el for use wiht Org-mode."
13547 (require 'remember)
13548 (setq remember-annotation-functions '(org-remember-annotation))
13549 (setq remember-handler-functions '(org-remember-handler))
13550 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13552 ;;;###autoload
13553 (defun org-remember-annotation ()
13554 "Return a link to the current location as an annotation for remember.el.
13555 If you are using Org-mode files as target for data storage with
13556 remember.el, then the annotations should include a link compatible with the
13557 conventions in Org-mode. This function returns such a link."
13558 (org-store-link nil))
13560 (defconst org-remember-help
13561 "Select a destination location for the note.
13562 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13563 RET on headline -> Store as sublevel entry to current headline
13564 RET at beg-of-buf -> Append to file as level 2 headline
13565 <left>/<right> -> before/after current headline, same headings level")
13567 (defvar org-remember-previous-location nil)
13568 (defvar org-force-remember-template-char) ;; dynamically scoped
13570 (defun org-select-remember-template (&optional use-char)
13571 (when org-remember-templates
13572 (let* ((templates (mapcar (lambda (x)
13573 (if (stringp (car x))
13574 (append (list (nth 1 x) (car x)) (cddr x))
13575 (append (list (car x) "") (cdr x))))
13576 org-remember-templates))
13577 (char (or use-char
13578 (cond
13579 ((= (length templates) 1)
13580 (caar templates))
13581 ((and (boundp 'org-force-remember-template-char)
13582 org-force-remember-template-char)
13583 (if (stringp org-force-remember-template-char)
13584 (string-to-char org-force-remember-template-char)
13585 org-force-remember-template-char))
13587 (message "Select template: %s"
13588 (mapconcat
13589 (lambda (x)
13590 (cond
13591 ((not (string-match "\\S-" (nth 1 x)))
13592 (format "[%c]" (car x)))
13593 ((equal (downcase (car x))
13594 (downcase (aref (nth 1 x) 0)))
13595 (format "[%c]%s" (car x)
13596 (substring (nth 1 x) 1)))
13597 (t (format "[%c]%s" (car x) (nth 1 x)))))
13598 templates " "))
13599 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13600 (when (equal char0 ?\C-g)
13601 (jump-to-register remember-register)
13602 (kill-buffer remember-buffer))
13603 char0))))))
13604 (cddr (assoc char templates)))))
13606 (defvar x-last-selected-text)
13607 (defvar x-last-selected-text-primary)
13609 ;;;###autoload
13610 (defun org-remember-apply-template (&optional use-char skip-interactive)
13611 "Initialize *remember* buffer with template, invoke `org-mode'.
13612 This function should be placed into `remember-mode-hook' and in fact requires
13613 to be run from that hook to function properly."
13614 (if org-remember-templates
13615 (let* ((entry (org-select-remember-template use-char))
13616 (tpl (car entry))
13617 (plist-p (if org-store-link-plist t nil))
13618 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13619 (string-match "\\S-" (nth 1 entry)))
13620 (nth 1 entry)
13621 org-default-notes-file))
13622 (headline (nth 2 entry))
13623 (v-c (or (and (eq window-system 'x)
13624 (fboundp 'x-cut-buffer-or-selection-value)
13625 (x-cut-buffer-or-selection-value))
13626 (org-bound-and-true-p x-last-selected-text)
13627 (org-bound-and-true-p x-last-selected-text-primary)
13628 (and (> (length kill-ring) 0) (current-kill 0))))
13629 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13630 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13631 (v-u (concat "[" (substring v-t 1 -1) "]"))
13632 (v-U (concat "[" (substring v-T 1 -1) "]"))
13633 ;; `initial' and `annotation' are bound in `remember'
13634 (v-i (if (boundp 'initial) initial))
13635 (v-a (if (and (boundp 'annotation) annotation)
13636 (if (equal annotation "[[]]") "" annotation)
13637 ""))
13638 (v-A (if (and v-a
13639 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13640 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13641 v-a))
13642 (v-n user-full-name)
13643 (org-startup-folded nil)
13644 org-time-was-given org-end-time-was-given x
13645 prompt completions char time pos default histvar)
13646 (setq org-store-link-plist
13647 (append (list :annotation v-a :initial v-i)
13648 org-store-link-plist))
13649 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13650 (erase-buffer)
13651 (insert (substitute-command-keys
13652 (format
13653 "## Filing location: Select interactively, default, or last used:
13654 ## %s to select file and header location interactively.
13655 ## %s \"%s\" -> \"* %s\"
13656 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13657 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13658 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13659 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13660 (abbreviate-file-name (or file org-default-notes-file))
13661 (or headline "")
13662 (or (car org-remember-previous-location) "???")
13663 (or (cdr org-remember-previous-location) "???"))))
13664 (insert tpl) (goto-char (point-min))
13665 ;; Simple %-escapes
13666 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13667 (when (and initial (equal (match-string 0) "%i"))
13668 (save-match-data
13669 (let* ((lead (buffer-substring
13670 (point-at-bol) (match-beginning 0))))
13671 (setq v-i (mapconcat 'identity
13672 (org-split-string initial "\n")
13673 (concat "\n" lead))))))
13674 (replace-match
13675 (or (eval (intern (concat "v-" (match-string 1)))) "")
13676 t t))
13678 ;; %[] Insert contents of a file.
13679 (goto-char (point-min))
13680 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13681 (let ((start (match-beginning 0))
13682 (end (match-end 0))
13683 (filename (expand-file-name (match-string 1))))
13684 (goto-char start)
13685 (delete-region start end)
13686 (condition-case error
13687 (insert-file-contents filename)
13688 (error (insert (format "%%![Couldn't insert %s: %s]"
13689 filename error))))))
13690 ;; %() embedded elisp
13691 (goto-char (point-min))
13692 (while (re-search-forward "%\\((.+)\\)" nil t)
13693 (goto-char (match-beginning 0))
13694 (let ((template-start (point)))
13695 (forward-char 1)
13696 (let ((result
13697 (condition-case error
13698 (eval (read (current-buffer)))
13699 (error (format "%%![Error: %s]" error)))))
13700 (delete-region template-start (point))
13701 (insert result))))
13703 ;; From the property list
13704 (when plist-p
13705 (goto-char (point-min))
13706 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13707 (and (setq x (or (plist-get org-store-link-plist
13708 (intern (match-string 1))) ""))
13709 (replace-match x t t))))
13711 ;; Turn on org-mode in the remember buffer, set local variables
13712 (org-mode)
13713 (org-set-local 'org-finish-function 'org-remember-finalize)
13714 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13715 (org-set-local 'org-default-notes-file file))
13716 (if (and headline (stringp headline) (string-match "\\S-" headline))
13717 (org-set-local 'org-remember-default-headline headline))
13718 ;; Interactive template entries
13719 (goto-char (point-min))
13720 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13721 (setq char (if (match-end 3) (match-string 3))
13722 prompt (if (match-end 2) (match-string 2)))
13723 (goto-char (match-beginning 0))
13724 (replace-match "")
13725 (setq completions nil default nil)
13726 (when prompt
13727 (setq completions (org-split-string prompt "|")
13728 prompt (pop completions)
13729 default (car completions)
13730 histvar (intern (concat
13731 "org-remember-template-prompt-history::"
13732 (or prompt "")))
13733 completions (mapcar 'list completions)))
13734 (cond
13735 ((member char '("G" "g"))
13736 (let* ((org-last-tags-completion-table
13737 (org-global-tags-completion-table
13738 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13739 (org-add-colon-after-tag-completion t)
13740 (ins (completing-read
13741 (if prompt (concat prompt ": ") "Tags: ")
13742 'org-tags-completion-function nil nil nil
13743 'org-tags-history)))
13744 (setq ins (mapconcat 'identity
13745 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13746 ":"))
13747 (when (string-match "\\S-" ins)
13748 (or (equal (char-before) ?:) (insert ":"))
13749 (insert ins)
13750 (or (equal (char-after) ?:) (insert ":")))))
13751 (char
13752 (setq org-time-was-given (equal (upcase char) char))
13753 (setq time (org-read-date (equal (upcase char) "U") t nil
13754 prompt))
13755 (org-insert-time-stamp time org-time-was-given
13756 (member char '("u" "U"))
13757 nil nil (list org-end-time-was-given)))
13759 (insert (org-completing-read
13760 (concat (if prompt prompt "Enter string")
13761 (if default (concat " [" default "]"))
13762 ": ")
13763 completions nil nil nil histvar default)))))
13764 (goto-char (point-min))
13765 (if (re-search-forward "%\\?" nil t)
13766 (replace-match "")
13767 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13768 (org-mode)
13769 (org-set-local 'org-finish-function 'org-remember-finalize))
13770 (when (save-excursion
13771 (goto-char (point-min))
13772 (re-search-forward "%!" nil t))
13773 (replace-match "")
13774 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13776 (defun org-remember-finish-immediately ()
13777 "File remember note immediately.
13778 This should be run in `post-command-hook' and will remove itself
13779 from that hook."
13780 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13781 (when org-finish-function
13782 (funcall org-finish-function)))
13784 (defvar org-clock-marker) ; Defined below
13785 (defun org-remember-finalize ()
13786 "Finalize the remember process."
13787 (unless (fboundp 'remember-finalize)
13788 (defalias 'remember-finalize 'remember-buffer))
13789 (when (and org-clock-marker
13790 (equal (marker-buffer org-clock-marker) (current-buffer)))
13791 ;; FIXME: test this, this is w/o notetaking!
13792 (let (org-log-note-clock-out) (org-clock-out)))
13793 (when buffer-file-name
13794 (save-buffer)
13795 (setq buffer-file-name nil))
13796 (remember-finalize))
13798 ;;;###autoload
13799 (defun org-remember (&optional goto org-force-remember-template-char)
13800 "Call `remember'. If this is already a remember buffer, re-apply template.
13801 If there is an active region, make sure remember uses it as initial content
13802 of the remember buffer.
13804 When called interactively with a `C-u' prefix argument GOTO, don't remember
13805 anything, just go to the file/headline where the selected template usually
13806 stores its notes. With a double prefix arg `C-u C-u', go to the last
13807 note stored by remember.
13809 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13810 associated with a template in `org-remember-templates'."
13811 (interactive "P")
13812 (cond
13813 ((equal goto '(4)) (org-go-to-remember-target))
13814 ((equal goto '(16)) (org-remember-goto-last-stored))
13816 (if (memq org-finish-function '(remember-buffer remember-finalize))
13817 (progn
13818 (when (< (length org-remember-templates) 2)
13819 (error "No other template available"))
13820 (erase-buffer)
13821 (let ((annotation (plist-get org-store-link-plist :annotation))
13822 (initial (plist-get org-store-link-plist :initial)))
13823 (org-remember-apply-template))
13824 (message "Press C-c C-c to remember data"))
13825 (if (org-region-active-p)
13826 (remember (buffer-substring (point) (mark)))
13827 (call-interactively 'remember))))))
13829 (defun org-remember-goto-last-stored ()
13830 "Go to the location where the last remember note was stored."
13831 (interactive)
13832 (bookmark-jump "org-remember-last-stored")
13833 (message "This is the last note stored by remember"))
13835 (defun org-go-to-remember-target (&optional template-key)
13836 "Go to the target location of a remember template.
13837 The user is queried for the template."
13838 (interactive)
13839 (let* ((entry (org-select-remember-template template-key))
13840 (file (nth 1 entry))
13841 (heading (nth 2 entry))
13842 visiting)
13843 (unless (and file (stringp file) (string-match "\\S-" file))
13844 (setq file org-default-notes-file))
13845 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13846 (setq heading org-remember-default-headline))
13847 (setq visiting (org-find-base-buffer-visiting file))
13848 (if (not visiting) (find-file-noselect file))
13849 (switch-to-buffer (or visiting (get-file-buffer file)))
13850 (widen)
13851 (goto-char (point-min))
13852 (if (re-search-forward
13853 (concat "^\\*+[ \t]+" (regexp-quote heading)
13854 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13855 nil t)
13856 (goto-char (match-beginning 0))
13857 (error "Target headline not found: %s" heading))))
13859 (defvar org-note-abort nil) ; dynamically scoped
13861 ;;;###autoload
13862 (defun org-remember-handler ()
13863 "Store stuff from remember.el into an org file.
13864 First prompts for an org file. If the user just presses return, the value
13865 of `org-default-notes-file' is used.
13866 Then the command offers the headings tree of the selected file in order to
13867 file the text at a specific location.
13868 You can either immediately press RET to get the note appended to the
13869 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13870 find a better place. Then press RET or <left> or <right> in insert the note.
13872 Key Cursor position Note gets inserted
13873 -----------------------------------------------------------------------------
13874 RET buffer-start as level 1 heading at end of file
13875 RET on headline as sublevel of the heading at cursor
13876 RET no heading at cursor position, level taken from context.
13877 Or use prefix arg to specify level manually.
13878 <left> on headline as same level, before current heading
13879 <right> on headline as same level, after current heading
13881 So the fastest way to store the note is to press RET RET to append it to
13882 the default file. This way your current train of thought is not
13883 interrupted, in accordance with the principles of remember.el.
13884 You can also get the fast execution without prompting by using
13885 C-u C-c C-c to exit the remember buffer. See also the variable
13886 `org-remember-store-without-prompt'.
13888 Before being stored away, the function ensures that the text has a
13889 headline, i.e. a first line that starts with a \"*\". If not, a headline
13890 is constructed from the current date and some additional data.
13892 If the variable `org-adapt-indentation' is non-nil, the entire text is
13893 also indented so that it starts in the same column as the headline
13894 \(i.e. after the stars).
13896 See also the variable `org-reverse-note-order'."
13897 (goto-char (point-min))
13898 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13899 (replace-match ""))
13900 (goto-char (point-max))
13901 (beginning-of-line 1)
13902 (while (looking-at "[ \t]*$\\|##.*")
13903 (delete-region (1- (point)) (point-max))
13904 (beginning-of-line 1))
13905 (catch 'quit
13906 (if org-note-abort (throw 'quit nil))
13907 (let* ((txt (buffer-substring (point-min) (point-max)))
13908 (fastp (org-xor (equal current-prefix-arg '(4))
13909 org-remember-store-without-prompt))
13910 (file (cond
13911 (fastp org-default-notes-file)
13912 ((and (eq org-remember-interactive-interface 'refile)
13913 org-refile-targets)
13914 org-default-notes-file)
13915 ((not (and (equal current-prefix-arg '(16))
13916 org-remember-previous-location))
13917 (org-get-org-file))))
13918 (heading org-remember-default-headline)
13919 (visiting (and file (org-find-base-buffer-visiting file)))
13920 (org-startup-folded nil)
13921 (org-startup-align-all-tables nil)
13922 (org-goto-start-pos 1)
13923 spos exitcmd level indent reversed)
13924 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13925 (setq file (car org-remember-previous-location)
13926 heading (cdr org-remember-previous-location)
13927 fastp t))
13928 (setq current-prefix-arg nil)
13929 (if (string-match "[ \t\n]+\\'" txt)
13930 (setq txt (replace-match "" t t txt)))
13931 ;; Modify text so that it becomes a nice subtree which can be inserted
13932 ;; into an org tree.
13933 (let* ((lines (split-string txt "\n"))
13934 first)
13935 (setq first (car lines) lines (cdr lines))
13936 (if (string-match "^\\*+ " first)
13937 ;; Is already a headline
13938 (setq indent nil)
13939 ;; We need to add a headline: Use time and first buffer line
13940 (setq lines (cons first lines)
13941 first (concat "* " (current-time-string)
13942 " (" (remember-buffer-desc) ")")
13943 indent " "))
13944 (if (and org-adapt-indentation indent)
13945 (setq lines (mapcar
13946 (lambda (x)
13947 (if (string-match "\\S-" x)
13948 (concat indent x) x))
13949 lines)))
13950 (setq txt (concat first "\n"
13951 (mapconcat 'identity lines "\n"))))
13952 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13953 (setq txt (replace-match "\n\n" t t txt))
13954 (if (string-match "[ \t\n]*\\'" txt)
13955 (setq txt (replace-match "\n" t t txt))))
13956 ;; Put the modified text back into the remember buffer, for refile.
13957 (erase-buffer)
13958 (insert txt)
13959 (goto-char (point-min))
13960 (when (and (eq org-remember-interactive-interface 'refile)
13961 (not fastp))
13962 (org-refile nil (or visiting (find-file-noselect file)))
13963 (throw 'quit t))
13964 ;; Find the file
13965 (if (not visiting) (find-file-noselect file))
13966 (with-current-buffer (or visiting (get-file-buffer file))
13967 (unless (org-mode-p)
13968 (error "Target files for remember notes must be in Org-mode"))
13969 (save-excursion
13970 (save-restriction
13971 (widen)
13972 (and (goto-char (point-min))
13973 (not (re-search-forward "^\\* " nil t))
13974 (insert "\n* " (or heading "Notes") "\n"))
13975 (setq reversed (org-notes-order-reversed-p))
13977 ;; Find the default location
13978 (when (and heading (stringp heading) (string-match "\\S-" heading))
13979 (goto-char (point-min))
13980 (if (re-search-forward
13981 (concat "^\\*+[ \t]+" (regexp-quote heading)
13982 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13983 nil t)
13984 (setq org-goto-start-pos (match-beginning 0))
13985 (when fastp
13986 (goto-char (point-max))
13987 (unless (bolp) (newline))
13988 (insert "* " heading "\n")
13989 (setq org-goto-start-pos (point-at-bol 0)))))
13991 ;; Ask the User for a location, using the appropriate interface
13992 (cond
13993 (fastp (setq spos org-goto-start-pos
13994 exitcmd 'return))
13995 ((eq org-remember-interactive-interface 'outline)
13996 (setq spos (org-get-location (current-buffer)
13997 org-remember-help)
13998 exitcmd (cdr spos)
13999 spos (car spos)))
14000 ((eq org-remember-interactive-interface 'outline-path-completion)
14001 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
14002 (org-refile-use-outline-path t))
14003 (setq spos (org-refile-get-location "Heading: ")
14004 exitcmd 'return
14005 spos (nth 3 spos))))
14006 (t (error "this should not hapen")))
14007 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14008 ; not handle this note
14009 (goto-char spos)
14010 (cond ((org-on-heading-p t)
14011 (org-back-to-heading t)
14012 (setq level (funcall outline-level))
14013 (cond
14014 ((eq exitcmd 'return)
14015 ;; sublevel of current
14016 (setq org-remember-previous-location
14017 (cons (abbreviate-file-name file)
14018 (org-get-heading 'notags)))
14019 (if reversed
14020 (outline-next-heading)
14021 (org-end-of-subtree t)
14022 (if (not (bolp))
14023 (if (looking-at "[ \t]*\n")
14024 (beginning-of-line 2)
14025 (end-of-line 1)
14026 (insert "\n"))))
14027 (bookmark-set "org-remember-last-stored")
14028 (org-paste-subtree (org-get-legal-level level 1) txt))
14029 ((eq exitcmd 'left)
14030 ;; before current
14031 (bookmark-set "org-remember-last-stored")
14032 (org-paste-subtree level txt))
14033 ((eq exitcmd 'right)
14034 ;; after current
14035 (org-end-of-subtree t)
14036 (bookmark-set "org-remember-last-stored")
14037 (org-paste-subtree level txt))
14038 (t (error "This should not happen"))))
14040 ((and (bobp) (not reversed))
14041 ;; Put it at the end, one level below level 1
14042 (save-restriction
14043 (widen)
14044 (goto-char (point-max))
14045 (if (not (bolp)) (newline))
14046 (bookmark-set "org-remember-last-stored")
14047 (org-paste-subtree (org-get-legal-level 1 1) txt)))
14049 ((and (bobp) reversed)
14050 ;; Put it at the start, as level 1
14051 (save-restriction
14052 (widen)
14053 (goto-char (point-min))
14054 (re-search-forward "^\\*+ " nil t)
14055 (beginning-of-line 1)
14056 (bookmark-set "org-remember-last-stored")
14057 (org-paste-subtree 1 txt)))
14059 ;; Put it right there, with automatic level determined by
14060 ;; org-paste-subtree or from prefix arg
14061 (bookmark-set "org-remember-last-stored")
14062 (org-paste-subtree
14063 (if (numberp current-prefix-arg) current-prefix-arg)
14064 txt)))
14065 (when remember-save-after-remembering
14066 (save-buffer)
14067 (if (not visiting) (kill-buffer (current-buffer)))))))))
14069 t) ;; return t to indicate that we took care of this note.
14071 (defun org-get-org-file ()
14072 "Read a filename, with default directory `org-directory'."
14073 (let ((default (or org-default-notes-file remember-data-file)))
14074 (read-file-name (format "File name [%s]: " default)
14075 (file-name-as-directory org-directory)
14076 default)))
14078 (defun org-notes-order-reversed-p ()
14079 "Check if the current file should receive notes in reversed order."
14080 (cond
14081 ((not org-reverse-note-order) nil)
14082 ((eq t org-reverse-note-order) t)
14083 ((not (listp org-reverse-note-order)) nil)
14084 (t (catch 'exit
14085 (let ((all org-reverse-note-order)
14086 entry)
14087 (while (setq entry (pop all))
14088 (if (string-match (car entry) buffer-file-name)
14089 (throw 'exit (cdr entry))))
14090 nil)))))
14092 ;;; Refiling
14094 (defvar org-refile-target-table nil
14095 "The list of refile targets, created by `org-refile'.")
14097 (defvar org-agenda-new-buffers nil
14098 "Buffers created to visit agenda files.")
14100 (defun org-get-refile-targets (&optional default-buffer)
14101 "Produce a table with refile targets."
14102 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14103 targets txt re files f desc descre)
14104 (with-current-buffer (or default-buffer (current-buffer))
14105 (while (setq entry (pop entries))
14106 (setq files (car entry) desc (cdr entry))
14107 (cond
14108 ((null files) (setq files (list (current-buffer))))
14109 ((eq files 'org-agenda-files)
14110 (setq files (org-agenda-files 'unrestricted)))
14111 ((and (symbolp files) (fboundp files))
14112 (setq files (funcall files)))
14113 ((and (symbolp files) (boundp files))
14114 (setq files (symbol-value files))))
14115 (if (stringp files) (setq files (list files)))
14116 (cond
14117 ((eq (car desc) :tag)
14118 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14119 ((eq (car desc) :todo)
14120 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14121 ((eq (car desc) :regexp)
14122 (setq descre (cdr desc)))
14123 ((eq (car desc) :level)
14124 (setq descre (concat "^\\*\\{" (number-to-string
14125 (if org-odd-levels-only
14126 (1- (* 2 (cdr desc)))
14127 (cdr desc)))
14128 "\\}[ \t]")))
14129 ((eq (car desc) :maxlevel)
14130 (setq descre (concat "^\\*\\{1," (number-to-string
14131 (if org-odd-levels-only
14132 (1- (* 2 (cdr desc)))
14133 (cdr desc)))
14134 "\\}[ \t]")))
14135 (t (error "Bad refiling target description %s" desc)))
14136 (while (setq f (pop files))
14137 (save-excursion
14138 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14139 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14140 (save-excursion
14141 (save-restriction
14142 (widen)
14143 (goto-char (point-min))
14144 (while (re-search-forward descre nil t)
14145 (goto-char (point-at-bol))
14146 (when (looking-at org-complex-heading-regexp)
14147 (setq txt (match-string 4)
14148 re (concat "^" (regexp-quote
14149 (buffer-substring (match-beginning 1)
14150 (match-end 4)))))
14151 (if (match-end 5) (setq re (concat re "[ \t]+"
14152 (regexp-quote
14153 (match-string 5)))))
14154 (setq re (concat re "[ \t]*$"))
14155 (when org-refile-use-outline-path
14156 (setq txt (mapconcat 'identity
14157 (append
14158 (if (eq org-refile-use-outline-path 'file)
14159 (list (file-name-nondirectory
14160 (buffer-file-name (buffer-base-buffer))))
14161 (if (eq org-refile-use-outline-path 'full-file-path)
14162 (list (buffer-file-name (buffer-base-buffer)))))
14163 (org-get-outline-path)
14164 (list txt))
14165 "/")))
14166 (push (list txt f re (point)) targets))
14167 (goto-char (point-at-eol))))))))
14168 (nreverse targets))))
14170 (defun org-get-outline-path ()
14171 "Return the outline path to the current entry, as a list."
14172 (let (rtn)
14173 (save-excursion
14174 (while (org-up-heading-safe)
14175 (when (looking-at org-complex-heading-regexp)
14176 (push (org-match-string-no-properties 4) rtn)))
14177 rtn)))
14179 (defvar org-refile-history nil
14180 "History for refiling operations.")
14182 (defun org-refile (&optional goto default-buffer)
14183 "Move the entry at point to another heading.
14184 The list of target headings is compiled using the information in
14185 `org-refile-targets', which see. This list is created upon first use, and
14186 you can update it by calling this command with a double prefix (`C-u C-u').
14187 FIXME: Can we find a better way of updating?
14189 At the target location, the entry is filed as a subitem of the target heading.
14190 Depending on `org-reverse-note-order', the new subitem will either be the
14191 first of the last subitem.
14193 With prefix arg GOTO, the command will only visit the target location,
14194 not actually move anything.
14195 With a double prefix `C-c C-c', go to the location where the last refiling
14196 operation has put the subtree.
14198 With a double prefix argument, the command can be used to jump to any
14199 heading in the current buffer."
14200 (interactive "P")
14201 (let* ((cbuf (current-buffer))
14202 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14203 pos it nbuf file re level reversed)
14204 (if (equal goto '(16))
14205 (org-refile-goto-last-stored)
14206 (when (setq it (org-refile-get-location
14207 (if goto "Goto: " "Refile to: ") default-buffer))
14208 (setq file (nth 1 it)
14209 re (nth 2 it)
14210 pos (nth 3 it))
14211 (setq nbuf (or (find-buffer-visiting file)
14212 (find-file-noselect file)))
14213 (if goto
14214 (progn
14215 (switch-to-buffer nbuf)
14216 (goto-char pos)
14217 (org-show-context 'org-goto))
14218 (org-copy-special)
14219 (save-excursion
14220 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14221 (find-file-noselect file))))
14222 (setq reversed (org-notes-order-reversed-p))
14223 (save-excursion
14224 (save-restriction
14225 (widen)
14226 (goto-char pos)
14227 (looking-at outline-regexp)
14228 (setq level (org-get-legal-level (funcall outline-level) 1))
14229 (goto-char
14230 (if reversed
14231 (outline-next-heading)
14232 (or (save-excursion (outline-get-next-sibling))
14233 (org-end-of-subtree t t)
14234 (point-max))))
14235 (bookmark-set "org-refile-last-stored")
14236 (org-paste-subtree level))))
14237 (org-cut-special)
14238 (message "Entry refiled to \"%s\"" (car it)))))))
14240 (defun org-refile-goto-last-stored ()
14241 "Go to the location where the last refile was stored."
14242 (interactive)
14243 (bookmark-jump "org-refile-last-stored")
14244 (message "This is the location of the last refile"))
14246 (defun org-refile-get-location (&optional prompt default-buffer)
14247 "Prompt the user for a refile location, using PROMPT."
14248 (let ((org-refile-targets org-refile-targets)
14249 (org-refile-use-outline-path org-refile-use-outline-path))
14250 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14251 (unless org-refile-target-table
14252 (error "No refile targets"))
14253 (let* ((cbuf (current-buffer))
14254 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14255 (fname (and filename (file-truename filename)))
14256 (tbl (mapcar
14257 (lambda (x)
14258 (if (not (equal fname (file-truename (nth 1 x))))
14259 (cons (concat (car x) " (" (file-name-nondirectory
14260 (nth 1 x)) ")")
14261 (cdr x))
14263 org-refile-target-table))
14264 (completion-ignore-case t))
14265 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14266 tbl)))
14268 ;;;; Dynamic blocks
14270 (defun org-find-dblock (name)
14271 "Find the first dynamic block with name NAME in the buffer.
14272 If not found, stay at current position and return nil."
14273 (let (pos)
14274 (save-excursion
14275 (goto-char (point-min))
14276 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14277 nil t)
14278 (match-beginning 0))))
14279 (if pos (goto-char pos))
14280 pos))
14282 (defconst org-dblock-start-re
14283 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14284 "Matches the startline of a dynamic block, with parameters.")
14286 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14287 "Matches the end of a dyhamic block.")
14289 (defun org-create-dblock (plist)
14290 "Create a dynamic block section, with parameters taken from PLIST.
14291 PLIST must containe a :name entry which is used as name of the block."
14292 (unless (bolp) (newline))
14293 (let ((name (plist-get plist :name)))
14294 (insert "#+BEGIN: " name)
14295 (while plist
14296 (if (eq (car plist) :name)
14297 (setq plist (cddr plist))
14298 (insert " " (prin1-to-string (pop plist)))))
14299 (insert "\n\n#+END:\n")
14300 (beginning-of-line -2)))
14302 (defun org-prepare-dblock ()
14303 "Prepare dynamic block for refresh.
14304 This empties the block, puts the cursor at the insert position and returns
14305 the property list including an extra property :name with the block name."
14306 (unless (looking-at org-dblock-start-re)
14307 (error "Not at a dynamic block"))
14308 (let* ((begdel (1+ (match-end 0)))
14309 (name (org-no-properties (match-string 1)))
14310 (params (append (list :name name)
14311 (read (concat "(" (match-string 3) ")")))))
14312 (unless (re-search-forward org-dblock-end-re nil t)
14313 (error "Dynamic block not terminated"))
14314 (delete-region begdel (match-beginning 0))
14315 (goto-char begdel)
14316 (open-line 1)
14317 params))
14319 (defun org-map-dblocks (&optional command)
14320 "Apply COMMAND to all dynamic blocks in the current buffer.
14321 If COMMAND is not given, use `org-update-dblock'."
14322 (let ((cmd (or command 'org-update-dblock))
14323 pos)
14324 (save-excursion
14325 (goto-char (point-min))
14326 (while (re-search-forward org-dblock-start-re nil t)
14327 (goto-char (setq pos (match-beginning 0)))
14328 (condition-case nil
14329 (funcall cmd)
14330 (error (message "Error during update of dynamic block")))
14331 (goto-char pos)
14332 (unless (re-search-forward org-dblock-end-re nil t)
14333 (error "Dynamic block not terminated"))))))
14335 (defun org-dblock-update (&optional arg)
14336 "User command for updating dynamic blocks.
14337 Update the dynamic block at point. With prefix ARG, update all dynamic
14338 blocks in the buffer."
14339 (interactive "P")
14340 (if arg
14341 (org-update-all-dblocks)
14342 (or (looking-at org-dblock-start-re)
14343 (org-beginning-of-dblock))
14344 (org-update-dblock)))
14346 (defun org-update-dblock ()
14347 "Update the dynamic block at point
14348 This means to empty the block, parse for parameters and then call
14349 the correct writing function."
14350 (save-window-excursion
14351 (let* ((pos (point))
14352 (line (org-current-line))
14353 (params (org-prepare-dblock))
14354 (name (plist-get params :name))
14355 (cmd (intern (concat "org-dblock-write:" name))))
14356 (message "Updating dynamic block `%s' at line %d..." name line)
14357 (funcall cmd params)
14358 (message "Updating dynamic block `%s' at line %d...done" name line)
14359 (goto-char pos))))
14361 (defun org-beginning-of-dblock ()
14362 "Find the beginning of the dynamic block at point.
14363 Error if there is no scuh block at point."
14364 (let ((pos (point))
14365 beg)
14366 (end-of-line 1)
14367 (if (and (re-search-backward org-dblock-start-re nil t)
14368 (setq beg (match-beginning 0))
14369 (re-search-forward org-dblock-end-re nil t)
14370 (> (match-end 0) pos))
14371 (goto-char beg)
14372 (goto-char pos)
14373 (error "Not in a dynamic block"))))
14375 (defun org-update-all-dblocks ()
14376 "Update all dynamic blocks in the buffer.
14377 This function can be used in a hook."
14378 (when (org-mode-p)
14379 (org-map-dblocks 'org-update-dblock)))
14382 ;;;; Completion
14384 (defconst org-additional-option-like-keywords
14385 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14386 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14387 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14389 (defun org-complete (&optional arg)
14390 "Perform completion on word at point.
14391 At the beginning of a headline, this completes TODO keywords as given in
14392 `org-todo-keywords'.
14393 If the current word is preceded by a backslash, completes the TeX symbols
14394 that are supported for HTML support.
14395 If the current word is preceded by \"#+\", completes special words for
14396 setting file options.
14397 In the line after \"#+STARTUP:, complete valid keywords.\"
14398 At all other locations, this simply calls the value of
14399 `org-completion-fallback-command'."
14400 (interactive "P")
14401 (org-without-partial-completion
14402 (catch 'exit
14403 (let* ((end (point))
14404 (beg1 (save-excursion
14405 (skip-chars-backward (org-re "[:alnum:]_@"))
14406 (point)))
14407 (beg (save-excursion
14408 (skip-chars-backward "a-zA-Z0-9_:$")
14409 (point)))
14410 (confirm (lambda (x) (stringp (car x))))
14411 (searchhead (equal (char-before beg) ?*))
14412 (tag (and (equal (char-before beg1) ?:)
14413 (equal (char-after (point-at-bol)) ?*)))
14414 (prop (and (equal (char-before beg1) ?:)
14415 (not (equal (char-after (point-at-bol)) ?*))))
14416 (texp (equal (char-before beg) ?\\))
14417 (link (equal (char-before beg) ?\[))
14418 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14419 beg)
14420 "#+"))
14421 (startup (string-match "^#\\+STARTUP:.*"
14422 (buffer-substring (point-at-bol) (point))))
14423 (completion-ignore-case opt)
14424 (type nil)
14425 (tbl nil)
14426 (table (cond
14427 (opt
14428 (setq type :opt)
14429 (append
14430 (mapcar
14431 (lambda (x)
14432 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14433 (cons (match-string 2 x) (match-string 1 x)))
14434 (org-split-string (org-get-current-options) "\n"))
14435 (mapcar 'list org-additional-option-like-keywords)))
14436 (startup
14437 (setq type :startup)
14438 org-startup-options)
14439 (link (append org-link-abbrev-alist-local
14440 org-link-abbrev-alist))
14441 (texp
14442 (setq type :tex)
14443 org-html-entities)
14444 ((string-match "\\`\\*+[ \t]+\\'"
14445 (buffer-substring (point-at-bol) beg))
14446 (setq type :todo)
14447 (mapcar 'list org-todo-keywords-1))
14448 (searchhead
14449 (setq type :searchhead)
14450 (save-excursion
14451 (goto-char (point-min))
14452 (while (re-search-forward org-todo-line-regexp nil t)
14453 (push (list
14454 (org-make-org-heading-search-string
14455 (match-string 3) t))
14456 tbl)))
14457 tbl)
14458 (tag (setq type :tag beg beg1)
14459 (or org-tag-alist (org-get-buffer-tags)))
14460 (prop (setq type :prop beg beg1)
14461 (mapcar 'list (org-buffer-property-keys nil t t)))
14462 (t (progn
14463 (call-interactively org-completion-fallback-command)
14464 (throw 'exit nil)))))
14465 (pattern (buffer-substring-no-properties beg end))
14466 (completion (try-completion pattern table confirm)))
14467 (cond ((eq completion t)
14468 (if (not (assoc (upcase pattern) table))
14469 (message "Already complete")
14470 (if (equal type :opt)
14471 (insert (substring (cdr (assoc (upcase pattern) table))
14472 (length pattern)))
14473 (if (memq type '(:tag :prop)) (insert ":")))))
14474 ((null completion)
14475 (message "Can't find completion for \"%s\"" pattern)
14476 (ding))
14477 ((not (string= pattern completion))
14478 (delete-region beg end)
14479 (if (string-match " +$" completion)
14480 (setq completion (replace-match "" t t completion)))
14481 (insert completion)
14482 (if (get-buffer-window "*Completions*")
14483 (delete-window (get-buffer-window "*Completions*")))
14484 (if (assoc completion table)
14485 (if (eq type :todo) (insert " ")
14486 (if (memq type '(:tag :prop)) (insert ":"))))
14487 (if (and (equal type :opt) (assoc completion table))
14488 (message "%s" (substitute-command-keys
14489 "Press \\[org-complete] again to insert example settings"))))
14491 (message "Making completion list...")
14492 (let ((list (sort (all-completions pattern table confirm)
14493 'string<)))
14494 (with-output-to-temp-buffer "*Completions*"
14495 (condition-case nil
14496 ;; Protection needed for XEmacs and emacs 21
14497 (display-completion-list list pattern)
14498 (error (display-completion-list list)))))
14499 (message "Making completion list...%s" "done")))))))
14501 ;;;; TODO, DEADLINE, Comments
14503 (defun org-toggle-comment ()
14504 "Change the COMMENT state of an entry."
14505 (interactive)
14506 (save-excursion
14507 (org-back-to-heading)
14508 (let (case-fold-search)
14509 (if (looking-at (concat outline-regexp
14510 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14511 (replace-match "" t t nil 1)
14512 (if (looking-at outline-regexp)
14513 (progn
14514 (goto-char (match-end 0))
14515 (insert org-comment-string " ")))))))
14517 (defvar org-last-todo-state-is-todo nil
14518 "This is non-nil when the last TODO state change led to a TODO state.
14519 If the last change removed the TODO tag or switched to DONE, then
14520 this is nil.")
14522 (defvar org-setting-tags nil) ; dynamically skiped
14524 ;; FIXME: better place
14525 (defun org-property-or-variable-value (var &optional inherit)
14526 "Check if there is a property fixing the value of VAR.
14527 If yes, return this value. If not, return the current value of the variable."
14528 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14529 (if (and prop (stringp prop) (string-match "\\S-" prop))
14530 (read prop)
14531 (symbol-value var))))
14533 (defun org-parse-local-options (string var)
14534 "Parse STRING for startup setting relevant for variable VAR."
14535 (let ((rtn (symbol-value var))
14536 e opts)
14537 (save-match-data
14538 (if (or (not string) (not (string-match "\\S-" string)))
14540 (setq opts (delq nil (mapcar (lambda (x)
14541 (setq e (assoc x org-startup-options))
14542 (if (eq (nth 1 e) var) e nil))
14543 (org-split-string string "[ \t]+"))))
14544 (if (not opts)
14546 (setq rtn nil)
14547 (while (setq e (pop opts))
14548 (if (not (nth 3 e))
14549 (setq rtn (nth 2 e))
14550 (if (not (listp rtn)) (setq rtn nil))
14551 (push (nth 2 e) rtn)))
14552 rtn)))))
14554 (defvar org-blocker-hook nil
14555 "Hook for functions that are allowed to block a state change.
14557 Each function gets as its single argument a property list, see
14558 `org-trigger-hook' for more information about this list.
14560 If any of the functions in this hook returns nil, the state change
14561 is blocked.")
14563 (defvar org-trigger-hook nil
14564 "Hook for functions that are triggered by a state change.
14566 Each function gets as its single argument a property list with at least
14567 the following elements:
14569 (:type type-of-change :position pos-at-entry-start
14570 :from old-state :to new-state)
14572 Depending on the type, more properties may be present.
14574 This mechanism is currently implemented for:
14576 TODO state changes
14577 ------------------
14578 :type todo-state-change
14579 :from previous state (keyword as a string), or nil
14580 :to new state (keyword as a string), or nil")
14583 (defun org-todo (&optional arg)
14584 "Change the TODO state of an item.
14585 The state of an item is given by a keyword at the start of the heading,
14586 like
14587 *** TODO Write paper
14588 *** DONE Call mom
14590 The different keywords are specified in the variable `org-todo-keywords'.
14591 By default the available states are \"TODO\" and \"DONE\".
14592 So for this example: when the item starts with TODO, it is changed to DONE.
14593 When it starts with DONE, the DONE is removed. And when neither TODO nor
14594 DONE are present, add TODO at the beginning of the heading.
14596 With C-u prefix arg, use completion to determine the new state.
14597 With numeric prefix arg, switch to that state.
14599 For calling through lisp, arg is also interpreted in the following way:
14600 'none -> empty state
14601 \"\"(empty string) -> switch to empty state
14602 'done -> switch to DONE
14603 'nextset -> switch to the next set of keywords
14604 'previousset -> switch to the previous set of keywords
14605 \"WAITING\" -> switch to the specified keyword, but only if it
14606 really is a member of `org-todo-keywords'."
14607 (interactive "P")
14608 (save-excursion
14609 (catch 'exit
14610 (org-back-to-heading)
14611 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14612 (or (looking-at (concat " +" org-todo-regexp " *"))
14613 (looking-at " *"))
14614 (let* ((match-data (match-data))
14615 (startpos (point-at-bol))
14616 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14617 (org-log-done org-log-done)
14618 (org-log-repeat org-log-repeat)
14619 (org-todo-log-states org-todo-log-states)
14620 (this (match-string 1))
14621 (hl-pos (match-beginning 0))
14622 (head (org-get-todo-sequence-head this))
14623 (ass (assoc head org-todo-kwd-alist))
14624 (interpret (nth 1 ass))
14625 (done-word (nth 3 ass))
14626 (final-done-word (nth 4 ass))
14627 (last-state (or this ""))
14628 (completion-ignore-case t)
14629 (member (member this org-todo-keywords-1))
14630 (tail (cdr member))
14631 (state (cond
14632 ((and org-todo-key-trigger
14633 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14634 (and (not arg) org-use-fast-todo-selection
14635 (not (eq org-use-fast-todo-selection 'prefix)))))
14636 ;; Use fast selection
14637 (org-fast-todo-selection))
14638 ((and (equal arg '(4))
14639 (or (not org-use-fast-todo-selection)
14640 (not org-todo-key-trigger)))
14641 ;; Read a state with completion
14642 (completing-read "State: " (mapcar (lambda(x) (list x))
14643 org-todo-keywords-1)
14644 nil t))
14645 ((eq arg 'right)
14646 (if this
14647 (if tail (car tail) nil)
14648 (car org-todo-keywords-1)))
14649 ((eq arg 'left)
14650 (if (equal member org-todo-keywords-1)
14652 (if this
14653 (nth (- (length org-todo-keywords-1) (length tail) 2)
14654 org-todo-keywords-1)
14655 (org-last org-todo-keywords-1))))
14656 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14657 (setq arg nil))) ; hack to fall back to cycling
14658 (arg
14659 ;; user or caller requests a specific state
14660 (cond
14661 ((equal arg "") nil)
14662 ((eq arg 'none) nil)
14663 ((eq arg 'done) (or done-word (car org-done-keywords)))
14664 ((eq arg 'nextset)
14665 (or (car (cdr (member head org-todo-heads)))
14666 (car org-todo-heads)))
14667 ((eq arg 'previousset)
14668 (let ((org-todo-heads (reverse org-todo-heads)))
14669 (or (car (cdr (member head org-todo-heads)))
14670 (car org-todo-heads))))
14671 ((car (member arg org-todo-keywords-1)))
14672 ((nth (1- (prefix-numeric-value arg))
14673 org-todo-keywords-1))))
14674 ((null member) (or head (car org-todo-keywords-1)))
14675 ((equal this final-done-word) nil) ;; -> make empty
14676 ((null tail) nil) ;; -> first entry
14677 ((eq interpret 'sequence)
14678 (car tail))
14679 ((memq interpret '(type priority))
14680 (if (eq this-command last-command)
14681 (car tail)
14682 (if (> (length tail) 0)
14683 (or done-word (car org-done-keywords))
14684 nil)))
14685 (t nil)))
14686 (next (if state (concat " " state " ") " "))
14687 (change-plist (list :type 'todo-state-change :from this :to state
14688 :position startpos))
14689 dolog now-done-p)
14690 (when org-blocker-hook
14691 (unless (save-excursion
14692 (save-match-data
14693 (run-hook-with-args-until-failure
14694 'org-blocker-hook change-plist)))
14695 (if (interactive-p)
14696 (error "TODO state change from %s to %s blocked" this state)
14697 ;; fail silently
14698 (message "TODO state change from %s to %s blocked" this state)
14699 (throw 'exit nil))))
14700 (store-match-data match-data)
14701 (replace-match next t t)
14702 (unless (pos-visible-in-window-p hl-pos)
14703 (message "TODO state changed to %s" (org-trim next)))
14704 (unless head
14705 (setq head (org-get-todo-sequence-head state)
14706 ass (assoc head org-todo-kwd-alist)
14707 interpret (nth 1 ass)
14708 done-word (nth 3 ass)
14709 final-done-word (nth 4 ass)))
14710 (when (memq arg '(nextset previousset))
14711 (message "Keyword-Set %d/%d: %s"
14712 (- (length org-todo-sets) -1
14713 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14714 (length org-todo-sets)
14715 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14716 (setq org-last-todo-state-is-todo
14717 (not (member state org-done-keywords)))
14718 (setq now-done-p (and (member state org-done-keywords)
14719 (not (member this org-done-keywords))))
14720 (and logging (org-local-logging logging))
14721 (when (and (or org-todo-log-states org-log-done)
14722 (not (memq arg '(nextset previousset))))
14723 ;; we need to look at recording a time and note
14724 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14725 (nth 2 (assoc this org-todo-log-states))))
14726 (when (and state
14727 (member state org-not-done-keywords)
14728 (not (member this org-not-done-keywords)))
14729 ;; This is now a todo state and was not one before
14730 ;; If there was a CLOSED time stamp, get rid of it.
14731 (org-add-planning-info nil nil 'closed))
14732 (when (and now-done-p org-log-done)
14733 ;; It is now done, and it was not done before
14734 (org-add-planning-info 'closed (org-current-time))
14735 (if (and (not dolog) (eq 'note org-log-done))
14736 (org-add-log-maybe 'done state 'findpos 'note)))
14737 (when (and state dolog)
14738 ;; This is a non-nil state, and we need to log it
14739 (org-add-log-maybe 'state state 'findpos dolog)))
14740 ;; Fixup tag positioning
14741 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14742 (run-hooks 'org-after-todo-state-change-hook)
14743 (if (and arg (not (member state org-done-keywords)))
14744 (setq head (org-get-todo-sequence-head state)))
14745 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14746 ;; Do we need to trigger a repeat?
14747 (when now-done-p (org-auto-repeat-maybe state))
14748 ;; Fixup cursor location if close to the keyword
14749 (if (and (outline-on-heading-p)
14750 (not (bolp))
14751 (save-excursion (beginning-of-line 1)
14752 (looking-at org-todo-line-regexp))
14753 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14754 (progn
14755 (goto-char (or (match-end 2) (match-end 1)))
14756 (just-one-space)))
14757 (when org-trigger-hook
14758 (save-excursion
14759 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14761 (defun org-local-logging (value)
14762 "Get logging settings from a property VALUE."
14763 (let* (words w a)
14764 ;; directly set the variables, they are already local.
14765 (setq org-log-done nil
14766 org-log-repeat nil
14767 org-todo-log-states nil)
14768 (setq words (org-split-string value))
14769 (while (setq w (pop words))
14770 (cond
14771 ((setq a (assoc w org-startup-options))
14772 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14773 (set (nth 1 a) (nth 2 a))))
14774 ((setq a (org-extract-log-state-settings w))
14775 (and (member (car a) org-todo-keywords-1)
14776 (push a org-todo-log-states)))))))
14778 (defun org-get-todo-sequence-head (kwd)
14779 "Return the head of the TODO sequence to which KWD belongs.
14780 If KWD is not set, check if there is a text property remembering the
14781 right sequence."
14782 (let (p)
14783 (cond
14784 ((not kwd)
14785 (or (get-text-property (point-at-bol) 'org-todo-head)
14786 (progn
14787 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14788 nil (point-at-eol)))
14789 (get-text-property p 'org-todo-head))))
14790 ((not (member kwd org-todo-keywords-1))
14791 (car org-todo-keywords-1))
14792 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14794 (defun org-fast-todo-selection ()
14795 "Fast TODO keyword selection with single keys.
14796 Returns the new TODO keyword, or nil if no state change should occur."
14797 (let* ((fulltable org-todo-key-alist)
14798 (done-keywords org-done-keywords) ;; needed for the faces.
14799 (maxlen (apply 'max (mapcar
14800 (lambda (x)
14801 (if (stringp (car x)) (string-width (car x)) 0))
14802 fulltable)))
14803 (expert nil)
14804 (fwidth (+ maxlen 3 1 3))
14805 (ncol (/ (- (window-width) 4) fwidth))
14806 tg cnt e c tbl
14807 groups ingroup)
14808 (save-window-excursion
14809 (if expert
14810 (set-buffer (get-buffer-create " *Org todo*"))
14811 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14812 (erase-buffer)
14813 (org-set-local 'org-done-keywords done-keywords)
14814 (setq tbl fulltable cnt 0)
14815 (while (setq e (pop tbl))
14816 (cond
14817 ((equal e '(:startgroup))
14818 (push '() groups) (setq ingroup t)
14819 (when (not (= cnt 0))
14820 (setq cnt 0)
14821 (insert "\n"))
14822 (insert "{ "))
14823 ((equal e '(:endgroup))
14824 (setq ingroup nil cnt 0)
14825 (insert "}\n"))
14827 (setq tg (car e) c (cdr e))
14828 (if ingroup (push tg (car groups)))
14829 (setq tg (org-add-props tg nil 'face
14830 (org-get-todo-face tg)))
14831 (if (and (= cnt 0) (not ingroup)) (insert " "))
14832 (insert "[" c "] " tg (make-string
14833 (- fwidth 4 (length tg)) ?\ ))
14834 (when (= (setq cnt (1+ cnt)) ncol)
14835 (insert "\n")
14836 (if ingroup (insert " "))
14837 (setq cnt 0)))))
14838 (insert "\n")
14839 (goto-char (point-min))
14840 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14841 (fit-window-to-buffer))
14842 (message "[a-z..]:Set [SPC]:clear")
14843 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14844 (cond
14845 ((or (= c ?\C-g)
14846 (and (= c ?q) (not (rassoc c fulltable))))
14847 (setq quit-flag t))
14848 ((= c ?\ ) nil)
14849 ((setq e (rassoc c fulltable) tg (car e))
14851 (t (setq quit-flag t))))))
14853 (defun org-get-repeat ()
14854 "Check if tere is a deadline/schedule with repeater in this entry."
14855 (save-match-data
14856 (save-excursion
14857 (org-back-to-heading t)
14858 (if (re-search-forward
14859 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14860 (match-string 1)))))
14862 (defvar org-last-changed-timestamp)
14863 (defvar org-log-post-message)
14864 (defvar org-log-note-purpose)
14865 (defun org-auto-repeat-maybe (done-word)
14866 "Check if the current headline contains a repeated deadline/schedule.
14867 If yes, set TODO state back to what it was and change the base date
14868 of repeating deadline/scheduled time stamps to new date.
14869 This function is run automatically after each state change to a DONE state."
14870 ;; last-state is dynamically scoped into this function
14871 (let* ((repeat (org-get-repeat))
14872 (aa (assoc last-state org-todo-kwd-alist))
14873 (interpret (nth 1 aa))
14874 (head (nth 2 aa))
14875 (whata '(("d" . day) ("m" . month) ("y" . year)))
14876 (msg "Entry repeats: ")
14877 (org-log-done nil)
14878 (org-todo-log-states nil)
14879 re type n what ts)
14880 (when repeat
14881 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14882 (org-todo (if (eq interpret 'type) last-state head))
14883 (when (and org-log-repeat
14884 (or (not (memq 'org-add-log-note
14885 (default-value 'post-command-hook)))
14886 (eq org-log-note-purpose 'done)))
14887 ;; Make sure a note is taken;
14888 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14889 'findpos org-log-repeat))
14890 (org-back-to-heading t)
14891 (org-add-planning-info nil nil 'closed)
14892 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14893 org-deadline-time-regexp "\\)\\|\\("
14894 org-ts-regexp "\\)"))
14895 (while (re-search-forward
14896 re (save-excursion (outline-next-heading) (point)) t)
14897 (setq type (if (match-end 1) org-scheduled-string
14898 (if (match-end 3) org-deadline-string "Plain:"))
14899 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14900 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14901 (setq n (string-to-number (match-string 1 ts))
14902 what (match-string 2 ts))
14903 (if (equal what "w") (setq n (* n 7) what "d"))
14904 (org-timestamp-change n (cdr (assoc what whata)))
14905 (setq msg (concat msg type org-last-changed-timestamp " "))))
14906 (setq org-log-post-message msg)
14907 (message "%s" msg))))
14909 (defun org-show-todo-tree (arg)
14910 "Make a compact tree which shows all headlines marked with TODO.
14911 The tree will show the lines where the regexp matches, and all higher
14912 headlines above the match.
14913 With a \\[universal-argument] prefix, also show the DONE entries.
14914 With a numeric prefix N, construct a sparse tree for the Nth element
14915 of `org-todo-keywords-1'."
14916 (interactive "P")
14917 (let ((case-fold-search nil)
14918 (kwd-re
14919 (cond ((null arg) org-not-done-regexp)
14920 ((equal arg '(4))
14921 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14922 (mapcar 'list org-todo-keywords-1))))
14923 (concat "\\("
14924 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14925 "\\)\\>")))
14926 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14927 (regexp-quote (nth (1- (prefix-numeric-value arg))
14928 org-todo-keywords-1)))
14929 (t (error "Invalid prefix argument: %s" arg)))))
14930 (message "%d TODO entries found"
14931 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14933 (defun org-deadline (&optional remove)
14934 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14935 With argument REMOVE, remove any deadline from the item."
14936 (interactive "P")
14937 (if remove
14938 (progn
14939 (org-remove-timestamp-with-keyword org-deadline-string)
14940 (message "Item no longer has a deadline."))
14941 (org-add-planning-info 'deadline nil 'closed)))
14943 (defun org-schedule (&optional remove)
14944 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14945 With argument REMOVE, remove any scheduling date from the item."
14946 (interactive "P")
14947 (if remove
14948 (progn
14949 (org-remove-timestamp-with-keyword org-scheduled-string)
14950 (message "Item is no longer scheduled."))
14951 (org-add-planning-info 'scheduled nil 'closed)))
14953 (defun org-remove-timestamp-with-keyword (keyword)
14954 "Remove all time stamps with KEYWORD in the current entry."
14955 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14956 beg)
14957 (save-excursion
14958 (org-back-to-heading t)
14959 (setq beg (point))
14960 (org-end-of-subtree t t)
14961 (while (re-search-backward re beg t)
14962 (replace-match "")
14963 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14964 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14966 (defun org-add-planning-info (what &optional time &rest remove)
14967 "Insert new timestamp with keyword in the line directly after the headline.
14968 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14969 If non is given, the user is prompted for a date.
14970 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14971 be removed."
14972 (interactive)
14973 (let (org-time-was-given org-end-time-was-given)
14974 (when what (setq time (or time (org-read-date nil 'to-time))))
14975 (when (and org-insert-labeled-timestamps-at-point
14976 (member what '(scheduled deadline)))
14977 (insert
14978 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14979 (org-insert-time-stamp time org-time-was-given
14980 nil nil nil (list org-end-time-was-given))
14981 (setq what nil))
14982 (save-excursion
14983 (save-restriction
14984 (let (col list elt ts buffer-invisibility-spec)
14985 (org-back-to-heading t)
14986 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14987 (goto-char (match-end 1))
14988 (setq col (current-column))
14989 (goto-char (match-end 0))
14990 (if (eobp) (insert "\n") (forward-char 1))
14991 (if (and (not (looking-at outline-regexp))
14992 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14993 "[^\r\n]*"))
14994 (not (equal (match-string 1) org-clock-string)))
14995 (narrow-to-region (match-beginning 0) (match-end 0))
14996 (insert-before-markers "\n")
14997 (backward-char 1)
14998 (narrow-to-region (point) (point))
14999 (indent-to-column col))
15000 ;; Check if we have to remove something.
15001 (setq list (cons what remove))
15002 (while list
15003 (setq elt (pop list))
15004 (goto-char (point-min))
15005 (when (or (and (eq elt 'scheduled)
15006 (re-search-forward org-scheduled-time-regexp nil t))
15007 (and (eq elt 'deadline)
15008 (re-search-forward org-deadline-time-regexp nil t))
15009 (and (eq elt 'closed)
15010 (re-search-forward org-closed-time-regexp nil t)))
15011 (replace-match "")
15012 (if (looking-at "--+<[^>]+>") (replace-match ""))
15013 (if (looking-at " +") (replace-match ""))))
15014 (goto-char (point-max))
15015 (when what
15016 (insert
15017 (if (not (equal (char-before) ?\ )) " " "")
15018 (cond ((eq what 'scheduled) org-scheduled-string)
15019 ((eq what 'deadline) org-deadline-string)
15020 ((eq what 'closed) org-closed-string))
15021 " ")
15022 (setq ts (org-insert-time-stamp
15023 time
15024 (or org-time-was-given
15025 (and (eq what 'closed) org-log-done-with-time))
15026 (eq what 'closed)
15027 nil nil (list org-end-time-was-given)))
15028 (end-of-line 1))
15029 (goto-char (point-min))
15030 (widen)
15031 (if (looking-at "[ \t]+\r?\n")
15032 (replace-match ""))
15033 ts)))))
15035 (defvar org-log-note-marker (make-marker))
15036 (defvar org-log-note-purpose nil)
15037 (defvar org-log-note-state nil)
15038 (defvar org-log-note-how nil)
15039 (defvar org-log-note-window-configuration nil)
15040 (defvar org-log-note-return-to (make-marker))
15041 (defvar org-log-post-message nil
15042 "Message to be displayed after a log note has been stored.
15043 The auto-repeater uses this.")
15045 (defun org-add-log-maybe (&optional purpose state findpos how)
15046 "Set up the post command hook to take a note.
15047 If this is about to TODO state change, the new state is expected in STATE.
15048 When FINDPOS is non-nil, find the correct position for the note in
15049 the current entry. If not, assume that it can be inserted at point."
15050 (save-excursion
15051 (when findpos
15052 (org-back-to-heading t)
15053 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15054 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15055 "[^\r\n]*\\)?"))
15056 (goto-char (match-end 0))
15057 (unless org-log-states-order-reversed
15058 (and (= (char-after) ?\n) (forward-char 1))
15059 (org-skip-over-state-notes)
15060 (skip-chars-backward " \t\n\r")))
15061 (move-marker org-log-note-marker (point))
15062 (setq org-log-note-purpose purpose
15063 org-log-note-state state
15064 org-log-note-how how)
15065 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15067 (defun org-skip-over-state-notes ()
15068 "Skip past the list of State notes in an entry."
15069 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15070 (while (looking-at "[ \t]*- State")
15071 (condition-case nil
15072 (org-next-item)
15073 (error (org-end-of-item)))))
15075 (defun org-add-log-note (&optional purpose)
15076 "Pop up a window for taking a note, and add this note later at point."
15077 (remove-hook 'post-command-hook 'org-add-log-note)
15078 (setq org-log-note-window-configuration (current-window-configuration))
15079 (delete-other-windows)
15080 (move-marker org-log-note-return-to (point))
15081 (switch-to-buffer (marker-buffer org-log-note-marker))
15082 (goto-char org-log-note-marker)
15083 (org-switch-to-buffer-other-window "*Org Note*")
15084 (erase-buffer)
15085 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15086 (org-store-log-note)
15087 (let ((org-inhibit-startup t)) (org-mode))
15088 (insert (format "# Insert note for %s.
15089 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15090 (cond
15091 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15092 ((eq org-log-note-purpose 'done) "closed todo item")
15093 ((eq org-log-note-purpose 'state)
15094 (format "state change to \"%s\"" org-log-note-state))
15095 (t (error "This should not happen")))))
15096 (org-set-local 'org-finish-function 'org-store-log-note)))
15098 (defun org-store-log-note ()
15099 "Finish taking a log note, and insert it to where it belongs."
15100 (let ((txt (buffer-string))
15101 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15102 lines ind)
15103 (kill-buffer (current-buffer))
15104 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15105 (setq txt (replace-match "" t t txt)))
15106 (if (string-match "\\s-+\\'" txt)
15107 (setq txt (replace-match "" t t txt)))
15108 (setq lines (org-split-string txt "\n"))
15109 (when (and note (string-match "\\S-" note))
15110 (setq note
15111 (org-replace-escapes
15112 note
15113 (list (cons "%u" (user-login-name))
15114 (cons "%U" user-full-name)
15115 (cons "%t" (format-time-string
15116 (org-time-stamp-format 'long 'inactive)
15117 (current-time)))
15118 (cons "%s" (if org-log-note-state
15119 (concat "\"" org-log-note-state "\"")
15120 "")))))
15121 (if lines (setq note (concat note " \\\\")))
15122 (push note lines))
15123 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15124 (when lines
15125 (save-excursion
15126 (set-buffer (marker-buffer org-log-note-marker))
15127 (save-excursion
15128 (goto-char org-log-note-marker)
15129 (move-marker org-log-note-marker nil)
15130 (end-of-line 1)
15131 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15132 (indent-relative nil)
15133 (insert "- " (pop lines))
15134 (org-indent-line-function)
15135 (beginning-of-line 1)
15136 (looking-at "[ \t]*")
15137 (setq ind (concat (match-string 0) " "))
15138 (end-of-line 1)
15139 (while lines (insert "\n" ind (pop lines)))))))
15140 (set-window-configuration org-log-note-window-configuration)
15141 (with-current-buffer (marker-buffer org-log-note-return-to)
15142 (goto-char org-log-note-return-to))
15143 (move-marker org-log-note-return-to nil)
15144 (and org-log-post-message (message "%s" org-log-post-message)))
15146 ;; FIXME: what else would be useful?
15147 ;; - priority
15148 ;; - date
15150 (defun org-sparse-tree (&optional arg)
15151 "Create a sparse tree, prompt for the details.
15152 This command can create sparse trees. You first need to select the type
15153 of match used to create the tree:
15155 t Show entries with a specific TODO keyword.
15156 T Show entries selected by a tags match.
15157 p Enter a property name and its value (both with completion on existing
15158 names/values) and show entries with that property.
15159 r Show entries matching a regular expression
15160 d Show deadlines due within `org-deadline-warning-days'."
15161 (interactive "P")
15162 (let (ans kwd value)
15163 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15164 (setq ans (read-char-exclusive))
15165 (cond
15166 ((equal ans ?d)
15167 (call-interactively 'org-check-deadlines))
15168 ((equal ans ?b)
15169 (call-interactively 'org-check-before-date))
15170 ((equal ans ?t)
15171 (org-show-todo-tree '(4)))
15172 ((equal ans ?T)
15173 (call-interactively 'org-tags-sparse-tree))
15174 ((member ans '(?p ?P))
15175 (setq kwd (completing-read "Property: "
15176 (mapcar 'list (org-buffer-property-keys))))
15177 (setq value (completing-read "Value: "
15178 (mapcar 'list (org-property-values kwd))))
15179 (unless (string-match "\\`{.*}\\'" value)
15180 (setq value (concat "\"" value "\"")))
15181 (org-tags-sparse-tree arg (concat kwd "=" value)))
15182 ((member ans '(?r ?R ?/))
15183 (call-interactively 'org-occur))
15184 (t (error "No such sparse tree command \"%c\"" ans)))))
15186 (defvar org-occur-highlights nil)
15187 (make-variable-buffer-local 'org-occur-highlights)
15189 (defun org-occur (regexp &optional keep-previous callback)
15190 "Make a compact tree which shows all matches of REGEXP.
15191 The tree will show the lines where the regexp matches, and all higher
15192 headlines above the match. It will also show the heading after the match,
15193 to make sure editing the matching entry is easy.
15194 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15195 call to `org-occur' will be kept, to allow stacking of calls to this
15196 command.
15197 If CALLBACK is non-nil, it is a function which is called to confirm
15198 that the match should indeed be shown."
15199 (interactive "sRegexp: \nP")
15200 (or keep-previous (org-remove-occur-highlights nil nil t))
15201 (let ((cnt 0))
15202 (save-excursion
15203 (goto-char (point-min))
15204 (if (or (not keep-previous) ; do not want to keep
15205 (not org-occur-highlights)) ; no previous matches
15206 ;; hide everything
15207 (org-overview))
15208 (while (re-search-forward regexp nil t)
15209 (when (or (not callback)
15210 (save-match-data (funcall callback)))
15211 (setq cnt (1+ cnt))
15212 (when org-highlight-sparse-tree-matches
15213 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15214 (org-show-context 'occur-tree))))
15215 (when org-remove-highlights-with-change
15216 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15217 nil 'local))
15218 (unless org-sparse-tree-open-archived-trees
15219 (org-hide-archived-subtrees (point-min) (point-max)))
15220 (run-hooks 'org-occur-hook)
15221 (if (interactive-p)
15222 (message "%d match(es) for regexp %s" cnt regexp))
15223 cnt))
15225 (defun org-show-context (&optional key)
15226 "Make sure point and context and visible.
15227 How much context is shown depends upon the variables
15228 `org-show-hierarchy-above', `org-show-following-heading'. and
15229 `org-show-siblings'."
15230 (let ((heading-p (org-on-heading-p t))
15231 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15232 (following-p (org-get-alist-option org-show-following-heading key))
15233 (entry-p (org-get-alist-option org-show-entry-below key))
15234 (siblings-p (org-get-alist-option org-show-siblings key)))
15235 (catch 'exit
15236 ;; Show heading or entry text
15237 (if (and heading-p (not entry-p))
15238 (org-flag-heading nil) ; only show the heading
15239 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15240 (org-show-hidden-entry))) ; show entire entry
15241 (when following-p
15242 ;; Show next sibling, or heading below text
15243 (save-excursion
15244 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15245 (org-flag-heading nil))))
15246 (when siblings-p (org-show-siblings))
15247 (when hierarchy-p
15248 ;; show all higher headings, possibly with siblings
15249 (save-excursion
15250 (while (and (condition-case nil
15251 (progn (org-up-heading-all 1) t)
15252 (error nil))
15253 (not (bobp)))
15254 (org-flag-heading nil)
15255 (when siblings-p (org-show-siblings))))))))
15257 (defun org-reveal (&optional siblings)
15258 "Show current entry, hierarchy above it, and the following headline.
15259 This can be used to show a consistent set of context around locations
15260 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15261 not t for the search context.
15263 With optional argument SIBLINGS, on each level of the hierarchy all
15264 siblings are shown. This repairs the tree structure to what it would
15265 look like when opened with hierarchical calls to `org-cycle'."
15266 (interactive "P")
15267 (let ((org-show-hierarchy-above t)
15268 (org-show-following-heading t)
15269 (org-show-siblings (if siblings t org-show-siblings)))
15270 (org-show-context nil)))
15272 (defun org-highlight-new-match (beg end)
15273 "Highlight from BEG to END and mark the highlight is an occur headline."
15274 (let ((ov (org-make-overlay beg end)))
15275 (org-overlay-put ov 'face 'secondary-selection)
15276 (push ov org-occur-highlights)))
15278 (defun org-remove-occur-highlights (&optional beg end noremove)
15279 "Remove the occur highlights from the buffer.
15280 BEG and END are ignored. If NOREMOVE is nil, remove this function
15281 from the `before-change-functions' in the current buffer."
15282 (interactive)
15283 (unless org-inhibit-highlight-removal
15284 (mapc 'org-delete-overlay org-occur-highlights)
15285 (setq org-occur-highlights nil)
15286 (unless noremove
15287 (remove-hook 'before-change-functions
15288 'org-remove-occur-highlights 'local))))
15290 ;;;; Priorities
15292 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15293 "Regular expression matching the priority indicator.")
15295 (defvar org-remove-priority-next-time nil)
15297 (defun org-priority-up ()
15298 "Increase the priority of the current item."
15299 (interactive)
15300 (org-priority 'up))
15302 (defun org-priority-down ()
15303 "Decrease the priority of the current item."
15304 (interactive)
15305 (org-priority 'down))
15307 (defun org-priority (&optional action)
15308 "Change the priority of an item by ARG.
15309 ACTION can be `set', `up', `down', or a character."
15310 (interactive)
15311 (setq action (or action 'set))
15312 (let (current new news have remove)
15313 (save-excursion
15314 (org-back-to-heading)
15315 (if (looking-at org-priority-regexp)
15316 (setq current (string-to-char (match-string 2))
15317 have t)
15318 (setq current org-default-priority))
15319 (cond
15320 ((or (eq action 'set) (integerp action))
15321 (if (integerp action)
15322 (setq new action)
15323 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15324 (setq new (read-char-exclusive)))
15325 (if (and (= (upcase org-highest-priority) org-highest-priority)
15326 (= (upcase org-lowest-priority) org-lowest-priority))
15327 (setq new (upcase new)))
15328 (cond ((equal new ?\ ) (setq remove t))
15329 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15330 (error "Priority must be between `%c' and `%c'"
15331 org-highest-priority org-lowest-priority))))
15332 ((eq action 'up)
15333 (if (and (not have) (eq last-command this-command))
15334 (setq new org-lowest-priority)
15335 (setq new (if (and org-priority-start-cycle-with-default (not have))
15336 org-default-priority (1- current)))))
15337 ((eq action 'down)
15338 (if (and (not have) (eq last-command this-command))
15339 (setq new org-highest-priority)
15340 (setq new (if (and org-priority-start-cycle-with-default (not have))
15341 org-default-priority (1+ current)))))
15342 (t (error "Invalid action")))
15343 (if (or (< (upcase new) org-highest-priority)
15344 (> (upcase new) org-lowest-priority))
15345 (setq remove t))
15346 (setq news (format "%c" new))
15347 (if have
15348 (if remove
15349 (replace-match "" t t nil 1)
15350 (replace-match news t t nil 2))
15351 (if remove
15352 (error "No priority cookie found in line")
15353 (looking-at org-todo-line-regexp)
15354 (if (match-end 2)
15355 (progn
15356 (goto-char (match-end 2))
15357 (insert " [#" news "]"))
15358 (goto-char (match-beginning 3))
15359 (insert "[#" news "] ")))))
15360 (org-preserve-lc (org-set-tags nil 'align))
15361 (if remove
15362 (message "Priority removed")
15363 (message "Priority of current item set to %s" news))))
15366 (defun org-get-priority (s)
15367 "Find priority cookie and return priority."
15368 (save-match-data
15369 (if (not (string-match org-priority-regexp s))
15370 (* 1000 (- org-lowest-priority org-default-priority))
15371 (* 1000 (- org-lowest-priority
15372 (string-to-char (match-string 2 s)))))))
15374 ;;;; Tags
15376 (defun org-scan-tags (action matcher &optional todo-only)
15377 "Scan headline tags with inheritance and produce output ACTION.
15378 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15379 evaluated, testing if a given set of tags qualifies a headline for
15380 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15381 are included in the output."
15382 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15383 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15384 (org-re
15385 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15386 (props (list 'face nil
15387 'done-face 'org-done
15388 'undone-face nil
15389 'mouse-face 'highlight
15390 'org-not-done-regexp org-not-done-regexp
15391 'org-todo-regexp org-todo-regexp
15392 'keymap org-agenda-keymap
15393 'help-echo
15394 (format "mouse-2 or RET jump to org file %s"
15395 (abbreviate-file-name
15396 (or (buffer-file-name (buffer-base-buffer))
15397 (buffer-name (buffer-base-buffer)))))))
15398 (case-fold-search nil)
15399 lspos
15400 tags tags-list tags-alist (llast 0) rtn level category i txt
15401 todo marker entry priority)
15402 (save-excursion
15403 (goto-char (point-min))
15404 (when (eq action 'sparse-tree)
15405 (org-overview)
15406 (org-remove-occur-highlights))
15407 (while (re-search-forward re nil t)
15408 (catch :skip
15409 (setq todo (if (match-end 1) (match-string 2))
15410 tags (if (match-end 4) (match-string 4)))
15411 (goto-char (setq lspos (1+ (match-beginning 0))))
15412 (setq level (org-reduced-level (funcall outline-level))
15413 category (org-get-category))
15414 (setq i llast llast level)
15415 ;; remove tag lists from same and sublevels
15416 (while (>= i level)
15417 (when (setq entry (assoc i tags-alist))
15418 (setq tags-alist (delete entry tags-alist)))
15419 (setq i (1- i)))
15420 ;; add the nex tags
15421 (when tags
15422 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15423 tags-alist
15424 (cons (cons level tags) tags-alist)))
15425 ;; compile tags for current headline
15426 (setq tags-list
15427 (if org-use-tag-inheritance
15428 (apply 'append (mapcar 'cdr tags-alist))
15429 tags))
15430 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15431 (eval matcher)
15432 (or (not org-agenda-skip-archived-trees)
15433 (not (member org-archive-tag tags-list))))
15434 (and (eq action 'agenda) (org-agenda-skip))
15435 ;; list this headline
15437 (if (eq action 'sparse-tree)
15438 (progn
15439 (and org-highlight-sparse-tree-matches
15440 (org-get-heading) (match-end 0)
15441 (org-highlight-new-match
15442 (match-beginning 0) (match-beginning 1)))
15443 (org-show-context 'tags-tree))
15444 (setq txt (org-format-agenda-item
15446 (concat
15447 (if org-tags-match-list-sublevels
15448 (make-string (1- level) ?.) "")
15449 (org-get-heading))
15450 category tags-list)
15451 priority (org-get-priority txt))
15452 (goto-char lspos)
15453 (setq marker (org-agenda-new-marker))
15454 (org-add-props txt props
15455 'org-marker marker 'org-hd-marker marker 'org-category category
15456 'priority priority 'type "tagsmatch")
15457 (push txt rtn))
15458 ;; if we are to skip sublevels, jump to end of subtree
15459 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15460 (when (and (eq action 'sparse-tree)
15461 (not org-sparse-tree-open-archived-trees))
15462 (org-hide-archived-subtrees (point-min) (point-max)))
15463 (nreverse rtn)))
15465 (defvar todo-only) ;; dynamically scoped
15467 (defun org-tags-sparse-tree (&optional todo-only match)
15468 "Create a sparse tree according to tags string MATCH.
15469 MATCH can contain positive and negative selection of tags, like
15470 \"+WORK+URGENT-WITHBOSS\".
15471 If optional argument TODO_ONLY is non-nil, only select lines that are
15472 also TODO lines."
15473 (interactive "P")
15474 (org-prepare-agenda-buffers (list (current-buffer)))
15475 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15477 (defvar org-cached-props nil)
15478 (defun org-cached-entry-get (pom property)
15479 (if (or (eq t org-use-property-inheritance)
15480 (member property org-use-property-inheritance))
15481 ;; Caching is not possible, check it directly
15482 (org-entry-get pom property 'inherit)
15483 ;; Get all properties, so that we can do complicated checks easily
15484 (cdr (assoc property (or org-cached-props
15485 (setq org-cached-props
15486 (org-entry-properties pom)))))))
15488 (defun org-global-tags-completion-table (&optional files)
15489 "Return the list of all tags in all agenda buffer/files."
15490 (save-excursion
15491 (org-uniquify
15492 (delq nil
15493 (apply 'append
15494 (mapcar
15495 (lambda (file)
15496 (set-buffer (find-file-noselect file))
15497 (append (org-get-buffer-tags)
15498 (mapcar (lambda (x) (if (stringp (car-safe x))
15499 (list (car-safe x)) nil))
15500 org-tag-alist)))
15501 (if (and files (car files))
15502 files
15503 (org-agenda-files))))))))
15505 (defun org-make-tags-matcher (match)
15506 "Create the TAGS//TODO matcher form for the selection string MATCH."
15507 ;; todo-only is scoped dynamically into this function, and the function
15508 ;; may change it it the matcher asksk for it.
15509 (unless match
15510 ;; Get a new match request, with completion
15511 (let ((org-last-tags-completion-table
15512 (org-global-tags-completion-table)))
15513 (setq match (completing-read
15514 "Match: " 'org-tags-completion-function nil nil nil
15515 'org-tags-history))))
15517 ;; Parse the string and create a lisp form
15518 (let ((match0 match)
15519 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15520 minus tag mm
15521 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15522 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15523 (if (string-match "/+" match)
15524 ;; match contains also a todo-matching request
15525 (progn
15526 (setq tagsmatch (substring match 0 (match-beginning 0))
15527 todomatch (substring match (match-end 0)))
15528 (if (string-match "^!" todomatch)
15529 (setq todo-only t todomatch (substring todomatch 1)))
15530 (if (string-match "^\\s-*$" todomatch)
15531 (setq todomatch nil)))
15532 ;; only matching tags
15533 (setq tagsmatch match todomatch nil))
15535 ;; Make the tags matcher
15536 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15537 (setq tagsmatcher t)
15538 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15539 (while (setq term (pop orterms))
15540 (while (and (equal (substring term -1) "\\") orterms)
15541 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15542 (while (string-match re term)
15543 (setq minus (and (match-end 1)
15544 (equal (match-string 1 term) "-"))
15545 tag (match-string 2 term)
15546 re-p (equal (string-to-char tag) ?{)
15547 level-p (match-end 3)
15548 prop-p (match-end 4)
15549 mm (cond
15550 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15551 (level-p `(= level ,(string-to-number
15552 (match-string 3 term))))
15553 (prop-p
15554 (setq pn (match-string 4 term)
15555 pv (match-string 5 term)
15556 cat-p (equal pn "CATEGORY")
15557 re-p (equal (string-to-char pv) ?{)
15558 pv (substring pv 1 -1))
15559 (if (equal pn "CATEGORY")
15560 (setq gv '(get-text-property (point) 'org-category))
15561 (setq gv `(org-cached-entry-get nil ,pn)))
15562 (if re-p
15563 `(string-match ,pv (or ,gv ""))
15564 `(equal ,pv (or ,gv ""))))
15565 (t `(member ,(downcase tag) tags-list)))
15566 mm (if minus (list 'not mm) mm)
15567 term (substring term (match-end 0)))
15568 (push mm tagsmatcher))
15569 (push (if (> (length tagsmatcher) 1)
15570 (cons 'and tagsmatcher)
15571 (car tagsmatcher))
15572 orlist)
15573 (setq tagsmatcher nil))
15574 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15575 (setq tagsmatcher
15576 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15578 ;; Make the todo matcher
15579 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15580 (setq todomatcher t)
15581 (setq orterms (org-split-string todomatch "|") orlist nil)
15582 (while (setq term (pop orterms))
15583 (while (string-match re term)
15584 (setq minus (and (match-end 1)
15585 (equal (match-string 1 term) "-"))
15586 kwd (match-string 2 term)
15587 re-p (equal (string-to-char kwd) ?{)
15588 term (substring term (match-end 0))
15589 mm (if re-p
15590 `(string-match ,(substring kwd 1 -1) todo)
15591 (list 'equal 'todo kwd))
15592 mm (if minus (list 'not mm) mm))
15593 (push mm todomatcher))
15594 (push (if (> (length todomatcher) 1)
15595 (cons 'and todomatcher)
15596 (car todomatcher))
15597 orlist)
15598 (setq todomatcher nil))
15599 (setq todomatcher (if (> (length orlist) 1)
15600 (cons 'or orlist) (car orlist))))
15602 ;; Return the string and lisp forms of the matcher
15603 (setq matcher (if todomatcher
15604 (list 'and tagsmatcher todomatcher)
15605 tagsmatcher))
15606 (cons match0 matcher)))
15608 (defun org-match-any-p (re list)
15609 "Does re match any element of list?"
15610 (setq list (mapcar (lambda (x) (string-match re x)) list))
15611 (delq nil list))
15613 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15614 (defvar org-tags-overlay (org-make-overlay 1 1))
15615 (org-detach-overlay org-tags-overlay)
15617 (defun org-align-tags-here (to-col)
15618 ;; Assumes that this is a headline
15619 (let ((pos (point)) (col (current-column)) tags)
15620 (beginning-of-line 1)
15621 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15622 (< pos (match-beginning 2)))
15623 (progn
15624 (setq tags (match-string 2))
15625 (goto-char (match-beginning 1))
15626 (insert " ")
15627 (delete-region (point) (1+ (match-end 0)))
15628 (backward-char 1)
15629 (move-to-column
15630 (max (1+ (current-column))
15631 (1+ col)
15632 (if (> to-col 0)
15633 to-col
15634 (- (abs to-col) (length tags))))
15636 (insert tags)
15637 (move-to-column (min (current-column) col) t))
15638 (goto-char pos))))
15640 (defun org-set-tags (&optional arg just-align)
15641 "Set the tags for the current headline.
15642 With prefix ARG, realign all tags in headings in the current buffer."
15643 (interactive "P")
15644 (let* ((re (concat "^" outline-regexp))
15645 (current (org-get-tags-string))
15646 (col (current-column))
15647 (org-setting-tags t)
15648 table current-tags inherited-tags ; computed below when needed
15649 tags p0 c0 c1 rpl)
15650 (if arg
15651 (save-excursion
15652 (goto-char (point-min))
15653 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15654 (while (re-search-forward re nil t)
15655 (org-set-tags nil t)
15656 (end-of-line 1)))
15657 (message "All tags realigned to column %d" org-tags-column))
15658 (if just-align
15659 (setq tags current)
15660 ;; Get a new set of tags from the user
15661 (save-excursion
15662 (setq table (or org-tag-alist (org-get-buffer-tags))
15663 org-last-tags-completion-table table
15664 current-tags (org-split-string current ":")
15665 inherited-tags (nreverse
15666 (nthcdr (length current-tags)
15667 (nreverse (org-get-tags-at))))
15668 tags
15669 (if (or (eq t org-use-fast-tag-selection)
15670 (and org-use-fast-tag-selection
15671 (delq nil (mapcar 'cdr table))))
15672 (org-fast-tag-selection
15673 current-tags inherited-tags table
15674 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15675 (let ((org-add-colon-after-tag-completion t))
15676 (org-trim
15677 (org-without-partial-completion
15678 (completing-read "Tags: " 'org-tags-completion-function
15679 nil nil current 'org-tags-history)))))))
15680 (while (string-match "[-+&]+" tags)
15681 ;; No boolean logic, just a list
15682 (setq tags (replace-match ":" t t tags))))
15684 (if (string-match "\\`[\t ]*\\'" tags)
15685 (setq tags "")
15686 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15687 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15689 ;; Insert new tags at the correct column
15690 (beginning-of-line 1)
15691 (cond
15692 ((and (equal current "") (equal tags "")))
15693 ((re-search-forward
15694 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15695 (point-at-eol) t)
15696 (if (equal tags "")
15697 (setq rpl "")
15698 (goto-char (match-beginning 0))
15699 (setq c0 (current-column) p0 (point)
15700 c1 (max (1+ c0) (if (> org-tags-column 0)
15701 org-tags-column
15702 (- (- org-tags-column) (length tags))))
15703 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15704 (replace-match rpl t t)
15705 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15706 tags)
15707 (t (error "Tags alignment failed")))
15708 (move-to-column col)
15709 (unless just-align
15710 (run-hooks 'org-after-tags-change-hook)))))
15712 (defun org-change-tag-in-region (beg end tag off)
15713 "Add or remove TAG for each entry in the region.
15714 This works in the agenda, and also in an org-mode buffer."
15715 (interactive
15716 (list (region-beginning) (region-end)
15717 (let ((org-last-tags-completion-table
15718 (if (org-mode-p)
15719 (org-get-buffer-tags)
15720 (org-global-tags-completion-table))))
15721 (completing-read
15722 "Tag: " 'org-tags-completion-function nil nil nil
15723 'org-tags-history))
15724 (progn
15725 (message "[s]et or [r]emove? ")
15726 (equal (read-char-exclusive) ?r))))
15727 (if (fboundp 'deactivate-mark) (deactivate-mark))
15728 (let ((agendap (equal major-mode 'org-agenda-mode))
15729 l1 l2 m buf pos newhead (cnt 0))
15730 (goto-char end)
15731 (setq l2 (1- (org-current-line)))
15732 (goto-char beg)
15733 (setq l1 (org-current-line))
15734 (loop for l from l1 to l2 do
15735 (goto-line l)
15736 (setq m (get-text-property (point) 'org-hd-marker))
15737 (when (or (and (org-mode-p) (org-on-heading-p))
15738 (and agendap m))
15739 (setq buf (if agendap (marker-buffer m) (current-buffer))
15740 pos (if agendap m (point)))
15741 (with-current-buffer buf
15742 (save-excursion
15743 (save-restriction
15744 (goto-char pos)
15745 (setq cnt (1+ cnt))
15746 (org-toggle-tag tag (if off 'off 'on))
15747 (setq newhead (org-get-heading)))))
15748 (and agendap (org-agenda-change-all-lines newhead m))))
15749 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15751 (defun org-tags-completion-function (string predicate &optional flag)
15752 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15753 (confirm (lambda (x) (stringp (car x)))))
15754 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15755 (setq s1 (match-string 1 string)
15756 s2 (match-string 2 string))
15757 (setq s1 "" s2 string))
15758 (cond
15759 ((eq flag nil)
15760 ;; try completion
15761 (setq rtn (try-completion s2 ctable confirm))
15762 (if (stringp rtn)
15763 (setq rtn
15764 (concat s1 s2 (substring rtn (length s2))
15765 (if (and org-add-colon-after-tag-completion
15766 (assoc rtn ctable))
15767 ":" ""))))
15768 rtn)
15769 ((eq flag t)
15770 ;; all-completions
15771 (all-completions s2 ctable confirm)
15773 ((eq flag 'lambda)
15774 ;; exact match?
15775 (assoc s2 ctable)))
15778 (defun org-fast-tag-insert (kwd tags face &optional end)
15779 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15780 (insert (format "%-12s" (concat kwd ":"))
15781 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15782 (or end "")))
15784 (defun org-fast-tag-show-exit (flag)
15785 (save-excursion
15786 (goto-line 3)
15787 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15788 (replace-match ""))
15789 (when flag
15790 (end-of-line 1)
15791 (move-to-column (- (window-width) 19) t)
15792 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15794 (defun org-set-current-tags-overlay (current prefix)
15795 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15796 (if (featurep 'xemacs)
15797 (org-overlay-display org-tags-overlay (concat prefix s)
15798 'secondary-selection)
15799 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15800 (org-overlay-display org-tags-overlay (concat prefix s)))))
15802 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15803 "Fast tag selection with single keys.
15804 CURRENT is the current list of tags in the headline, INHERITED is the
15805 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15806 possibly with grouping information. TODO-TABLE is a similar table with
15807 TODO keywords, should these have keys assigned to them.
15808 If the keys are nil, a-z are automatically assigned.
15809 Returns the new tags string, or nil to not change the current settings."
15810 (let* ((fulltable (append table todo-table))
15811 (maxlen (apply 'max (mapcar
15812 (lambda (x)
15813 (if (stringp (car x)) (string-width (car x)) 0))
15814 fulltable)))
15815 (buf (current-buffer))
15816 (expert (eq org-fast-tag-selection-single-key 'expert))
15817 (buffer-tags nil)
15818 (fwidth (+ maxlen 3 1 3))
15819 (ncol (/ (- (window-width) 4) fwidth))
15820 (i-face 'org-done)
15821 (c-face 'org-todo)
15822 tg cnt e c char c1 c2 ntable tbl rtn
15823 ov-start ov-end ov-prefix
15824 (exit-after-next org-fast-tag-selection-single-key)
15825 (done-keywords org-done-keywords)
15826 groups ingroup)
15827 (save-excursion
15828 (beginning-of-line 1)
15829 (if (looking-at
15830 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15831 (setq ov-start (match-beginning 1)
15832 ov-end (match-end 1)
15833 ov-prefix "")
15834 (setq ov-start (1- (point-at-eol))
15835 ov-end (1+ ov-start))
15836 (skip-chars-forward "^\n\r")
15837 (setq ov-prefix
15838 (concat
15839 (buffer-substring (1- (point)) (point))
15840 (if (> (current-column) org-tags-column)
15842 (make-string (- org-tags-column (current-column)) ?\ ))))))
15843 (org-move-overlay org-tags-overlay ov-start ov-end)
15844 (save-window-excursion
15845 (if expert
15846 (set-buffer (get-buffer-create " *Org tags*"))
15847 (delete-other-windows)
15848 (split-window-vertically)
15849 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15850 (erase-buffer)
15851 (org-set-local 'org-done-keywords done-keywords)
15852 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15853 (org-fast-tag-insert "Current" current c-face "\n\n")
15854 (org-fast-tag-show-exit exit-after-next)
15855 (org-set-current-tags-overlay current ov-prefix)
15856 (setq tbl fulltable char ?a cnt 0)
15857 (while (setq e (pop tbl))
15858 (cond
15859 ((equal e '(:startgroup))
15860 (push '() groups) (setq ingroup t)
15861 (when (not (= cnt 0))
15862 (setq cnt 0)
15863 (insert "\n"))
15864 (insert "{ "))
15865 ((equal e '(:endgroup))
15866 (setq ingroup nil cnt 0)
15867 (insert "}\n"))
15869 (setq tg (car e) c2 nil)
15870 (if (cdr e)
15871 (setq c (cdr e))
15872 ;; automatically assign a character.
15873 (setq c1 (string-to-char
15874 (downcase (substring
15875 tg (if (= (string-to-char tg) ?@) 1 0)))))
15876 (if (or (rassoc c1 ntable) (rassoc c1 table))
15877 (while (or (rassoc char ntable) (rassoc char table))
15878 (setq char (1+ char)))
15879 (setq c2 c1))
15880 (setq c (or c2 char)))
15881 (if ingroup (push tg (car groups)))
15882 (setq tg (org-add-props tg nil 'face
15883 (cond
15884 ((not (assoc tg table))
15885 (org-get-todo-face tg))
15886 ((member tg current) c-face)
15887 ((member tg inherited) i-face)
15888 (t nil))))
15889 (if (and (= cnt 0) (not ingroup)) (insert " "))
15890 (insert "[" c "] " tg (make-string
15891 (- fwidth 4 (length tg)) ?\ ))
15892 (push (cons tg c) ntable)
15893 (when (= (setq cnt (1+ cnt)) ncol)
15894 (insert "\n")
15895 (if ingroup (insert " "))
15896 (setq cnt 0)))))
15897 (setq ntable (nreverse ntable))
15898 (insert "\n")
15899 (goto-char (point-min))
15900 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15901 (fit-window-to-buffer))
15902 (setq rtn
15903 (catch 'exit
15904 (while t
15905 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15906 (if groups " [!] no groups" " [!]groups")
15907 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15908 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15909 (cond
15910 ((= c ?\r) (throw 'exit t))
15911 ((= c ?!)
15912 (setq groups (not groups))
15913 (goto-char (point-min))
15914 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15915 ((= c ?\C-c)
15916 (if (not expert)
15917 (org-fast-tag-show-exit
15918 (setq exit-after-next (not exit-after-next)))
15919 (setq expert nil)
15920 (delete-other-windows)
15921 (split-window-vertically)
15922 (org-switch-to-buffer-other-window " *Org tags*")
15923 (and (fboundp 'fit-window-to-buffer)
15924 (fit-window-to-buffer))))
15925 ((or (= c ?\C-g)
15926 (and (= c ?q) (not (rassoc c ntable))))
15927 (org-detach-overlay org-tags-overlay)
15928 (setq quit-flag t))
15929 ((= c ?\ )
15930 (setq current nil)
15931 (if exit-after-next (setq exit-after-next 'now)))
15932 ((= c ?\t)
15933 (condition-case nil
15934 (setq tg (completing-read
15935 "Tag: "
15936 (or buffer-tags
15937 (with-current-buffer buf
15938 (org-get-buffer-tags)))))
15939 (quit (setq tg "")))
15940 (when (string-match "\\S-" tg)
15941 (add-to-list 'buffer-tags (list tg))
15942 (if (member tg current)
15943 (setq current (delete tg current))
15944 (push tg current)))
15945 (if exit-after-next (setq exit-after-next 'now)))
15946 ((setq e (rassoc c todo-table) tg (car e))
15947 (with-current-buffer buf
15948 (save-excursion (org-todo tg)))
15949 (if exit-after-next (setq exit-after-next 'now)))
15950 ((setq e (rassoc c ntable) tg (car e))
15951 (if (member tg current)
15952 (setq current (delete tg current))
15953 (loop for g in groups do
15954 (if (member tg g)
15955 (mapc (lambda (x)
15956 (setq current (delete x current)))
15957 g)))
15958 (push tg current))
15959 (if exit-after-next (setq exit-after-next 'now))))
15961 ;; Create a sorted list
15962 (setq current
15963 (sort current
15964 (lambda (a b)
15965 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15966 (if (eq exit-after-next 'now) (throw 'exit t))
15967 (goto-char (point-min))
15968 (beginning-of-line 2)
15969 (delete-region (point) (point-at-eol))
15970 (org-fast-tag-insert "Current" current c-face)
15971 (org-set-current-tags-overlay current ov-prefix)
15972 (while (re-search-forward
15973 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15974 (setq tg (match-string 1))
15975 (add-text-properties
15976 (match-beginning 1) (match-end 1)
15977 (list 'face
15978 (cond
15979 ((member tg current) c-face)
15980 ((member tg inherited) i-face)
15981 (t (get-text-property (match-beginning 1) 'face))))))
15982 (goto-char (point-min)))))
15983 (org-detach-overlay org-tags-overlay)
15984 (if rtn
15985 (mapconcat 'identity current ":")
15986 nil))))
15988 (defun org-get-tags-string ()
15989 "Get the TAGS string in the current headline."
15990 (unless (org-on-heading-p t)
15991 (error "Not on a heading"))
15992 (save-excursion
15993 (beginning-of-line 1)
15994 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15995 (org-match-string-no-properties 1)
15996 "")))
15998 (defun org-get-tags ()
15999 "Get the list of tags specified in the current headline."
16000 (org-split-string (org-get-tags-string) ":"))
16002 (defun org-get-buffer-tags ()
16003 "Get a table of all tags used in the buffer, for completion."
16004 (let (tags)
16005 (save-excursion
16006 (goto-char (point-min))
16007 (while (re-search-forward
16008 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16009 (when (equal (char-after (point-at-bol 0)) ?*)
16010 (mapc (lambda (x) (add-to-list 'tags x))
16011 (org-split-string (org-match-string-no-properties 1) ":")))))
16012 (mapcar 'list tags)))
16015 ;;;; Properties
16017 ;;; Setting and retrieving properties
16019 (defconst org-special-properties
16020 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16021 "TIMESTAMP" "TIMESTAMP_IA")
16022 "The special properties valid in Org-mode.
16024 These are properties that are not defined in the property drawer,
16025 but in some other way.")
16027 (defconst org-default-properties
16028 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16029 "LOCATION" "LOGGING" "COLUMNS")
16030 "Some properties that are used by Org-mode for various purposes.
16031 Being in this list makes sure that they are offered for completion.")
16033 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16034 "Regular expression matching the first line of a property drawer.")
16036 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16037 "Regular expression matching the first line of a property drawer.")
16039 (defun org-property-action ()
16040 "Do an action on properties."
16041 (interactive)
16042 (let (c)
16043 (org-at-property-p)
16044 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16045 (setq c (read-char-exclusive))
16046 (cond
16047 ((equal c ?s)
16048 (call-interactively 'org-set-property))
16049 ((equal c ?d)
16050 (call-interactively 'org-delete-property))
16051 ((equal c ?D)
16052 (call-interactively 'org-delete-property-globally))
16053 ((equal c ?c)
16054 (call-interactively 'org-compute-property-at-point))
16055 (t (error "No such property action %c" c)))))
16057 (defun org-at-property-p ()
16058 "Is the cursor in a property line?"
16059 ;; FIXME: Does not check if we are actually in the drawer.
16060 ;; FIXME: also returns true on any drawers.....
16061 ;; This is used by C-c C-c for property action.
16062 (save-excursion
16063 (beginning-of-line 1)
16064 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16066 (defmacro org-with-point-at (pom &rest body)
16067 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16068 (declare (indent 1) (debug t))
16069 `(save-excursion
16070 (if (markerp pom) (set-buffer (marker-buffer pom)))
16071 (save-excursion
16072 (goto-char (or pom (point)))
16073 ,@body)))
16075 (defun org-get-property-block (&optional beg end force)
16076 "Return the (beg . end) range of the body of the property drawer.
16077 BEG and END can be beginning and end of subtree, if not given
16078 they will be found.
16079 If the drawer does not exist and FORCE is non-nil, create the drawer."
16080 (catch 'exit
16081 (save-excursion
16082 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16083 (end (or end (progn (outline-next-heading) (point)))))
16084 (goto-char beg)
16085 (if (re-search-forward org-property-start-re end t)
16086 (setq beg (1+ (match-end 0)))
16087 (if force
16088 (save-excursion
16089 (org-insert-property-drawer)
16090 (setq end (progn (outline-next-heading) (point))))
16091 (throw 'exit nil))
16092 (goto-char beg)
16093 (if (re-search-forward org-property-start-re end t)
16094 (setq beg (1+ (match-end 0)))))
16095 (if (re-search-forward org-property-end-re end t)
16096 (setq end (match-beginning 0))
16097 (or force (throw 'exit nil))
16098 (goto-char beg)
16099 (setq end beg)
16100 (org-indent-line-function)
16101 (insert ":END:\n"))
16102 (cons beg end)))))
16104 (defun org-entry-properties (&optional pom which)
16105 "Get all properties of the entry at point-or-marker POM.
16106 This includes the TODO keyword, the tags, time strings for deadline,
16107 scheduled, and clocking, and any additional properties defined in the
16108 entry. The return value is an alist, keys may occur multiple times
16109 if the property key was used several times.
16110 POM may also be nil, in which case the current entry is used.
16111 If WHICH is nil or `all', get all properties. If WHICH is
16112 `special' or `standard', only get that subclass."
16113 (setq which (or which 'all))
16114 (org-with-point-at pom
16115 (let ((clockstr (substring org-clock-string 0 -1))
16116 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16117 beg end range props sum-props key value string clocksum)
16118 (save-excursion
16119 (when (condition-case nil (org-back-to-heading t) (error nil))
16120 (setq beg (point))
16121 (setq sum-props (get-text-property (point) 'org-summaries))
16122 (setq clocksum (get-text-property (point) :org-clock-minutes))
16123 (outline-next-heading)
16124 (setq end (point))
16125 (when (memq which '(all special))
16126 ;; Get the special properties, like TODO and tags
16127 (goto-char beg)
16128 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16129 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16130 (when (looking-at org-priority-regexp)
16131 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16132 (when (and (setq value (org-get-tags-string))
16133 (string-match "\\S-" value))
16134 (push (cons "TAGS" value) props))
16135 (when (setq value (org-get-tags-at))
16136 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16137 props))
16138 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16139 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16140 string (if (equal key clockstr)
16141 (org-no-properties
16142 (org-trim
16143 (buffer-substring
16144 (match-beginning 3) (goto-char (point-at-eol)))))
16145 (substring (org-match-string-no-properties 3) 1 -1)))
16146 (unless key
16147 (if (= (char-after (match-beginning 3)) ?\[)
16148 (setq key "TIMESTAMP_IA")
16149 (setq key "TIMESTAMP")))
16150 (when (or (equal key clockstr) (not (assoc key props)))
16151 (push (cons key string) props)))
16155 (when (memq which '(all standard))
16156 ;; Get the standard properties, like :PORP: ...
16157 (setq range (org-get-property-block beg end))
16158 (when range
16159 (goto-char (car range))
16160 (while (re-search-forward
16161 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16162 (cdr range) t)
16163 (setq key (org-match-string-no-properties 1)
16164 value (org-trim (or (org-match-string-no-properties 2) "")))
16165 (unless (member key excluded)
16166 (push (cons key (or value "")) props)))))
16167 (if clocksum
16168 (push (cons "CLOCKSUM"
16169 (org-column-number-to-string (/ (float clocksum) 60.)
16170 'add_times))
16171 props))
16172 (append sum-props (nreverse props)))))))
16174 (defun org-entry-get (pom property &optional inherit)
16175 "Get value of PROPERTY for entry at point-or-marker POM.
16176 If INHERIT is non-nil and the entry does not have the property,
16177 then also check higher levels of the hierarchy.
16178 If the property is present but empty, the return value is the empty string.
16179 If the property is not present at all, nil is returned."
16180 (org-with-point-at pom
16181 (if inherit
16182 (org-entry-get-with-inheritance property)
16183 (if (member property org-special-properties)
16184 ;; We need a special property. Use brute force, get all properties.
16185 (cdr (assoc property (org-entry-properties nil 'special)))
16186 (let ((range (org-get-property-block)))
16187 (if (and range
16188 (goto-char (car range))
16189 (re-search-forward
16190 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16191 (cdr range) t))
16192 ;; Found the property, return it.
16193 (if (match-end 1)
16194 (org-match-string-no-properties 1)
16195 "")))))))
16197 (defun org-entry-delete (pom property)
16198 "Delete the property PROPERTY from entry at point-or-marker POM."
16199 (org-with-point-at pom
16200 (if (member property org-special-properties)
16201 nil ; cannot delete these properties.
16202 (let ((range (org-get-property-block)))
16203 (if (and range
16204 (goto-char (car range))
16205 (re-search-forward
16206 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16207 (cdr range) t))
16208 (progn
16209 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16211 nil)))))
16213 ;; Multi-values properties are properties that contain multiple values
16214 ;; These values are assumed to be single words, separated by whitespace.
16215 (defun org-entry-add-to-multivalued-property (pom property value)
16216 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16217 (let* ((old (org-entry-get pom property))
16218 (values (and old (org-split-string old "[ \t]"))))
16219 (unless (member value values)
16220 (setq values (cons value values))
16221 (org-entry-put pom property
16222 (mapconcat 'identity values " ")))))
16224 (defun org-entry-remove-from-multivalued-property (pom property value)
16225 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16226 (let* ((old (org-entry-get pom property))
16227 (values (and old (org-split-string old "[ \t]"))))
16228 (when (member value values)
16229 (setq values (delete value values))
16230 (org-entry-put pom property
16231 (mapconcat 'identity values " ")))))
16233 (defun org-entry-member-in-multivalued-property (pom property value)
16234 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16235 (let* ((old (org-entry-get pom property))
16236 (values (and old (org-split-string old "[ \t]"))))
16237 (member value values)))
16239 (defvar org-entry-property-inherited-from (make-marker))
16241 (defun org-entry-get-with-inheritance (property)
16242 "Get entry property, and search higher levels if not present."
16243 (let (tmp)
16244 (save-excursion
16245 (save-restriction
16246 (widen)
16247 (catch 'ex
16248 (while t
16249 (when (setq tmp (org-entry-get nil property))
16250 (org-back-to-heading t)
16251 (move-marker org-entry-property-inherited-from (point))
16252 (throw 'ex tmp))
16253 (or (org-up-heading-safe) (throw 'ex nil)))))
16254 (or tmp (cdr (assoc property org-local-properties))
16255 (cdr (assoc property org-global-properties))))))
16257 (defun org-entry-put (pom property value)
16258 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16259 (org-with-point-at pom
16260 (org-back-to-heading t)
16261 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16262 range)
16263 (cond
16264 ((equal property "TODO")
16265 (when (and (stringp value) (string-match "\\S-" value)
16266 (not (member value org-todo-keywords-1)))
16267 (error "\"%s\" is not a valid TODO state" value))
16268 (if (or (not value)
16269 (not (string-match "\\S-" value)))
16270 (setq value 'none))
16271 (org-todo value)
16272 (org-set-tags nil 'align))
16273 ((equal property "PRIORITY")
16274 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16275 (string-to-char value) ?\ ))
16276 (org-set-tags nil 'align))
16277 ((equal property "SCHEDULED")
16278 (if (re-search-forward org-scheduled-time-regexp end t)
16279 (cond
16280 ((eq value 'earlier) (org-timestamp-change -1 'day))
16281 ((eq value 'later) (org-timestamp-change 1 'day))
16282 (t (call-interactively 'org-schedule)))
16283 (call-interactively 'org-schedule)))
16284 ((equal property "DEADLINE")
16285 (if (re-search-forward org-deadline-time-regexp end t)
16286 (cond
16287 ((eq value 'earlier) (org-timestamp-change -1 'day))
16288 ((eq value 'later) (org-timestamp-change 1 'day))
16289 (t (call-interactively 'org-deadline)))
16290 (call-interactively 'org-deadline)))
16291 ((member property org-special-properties)
16292 (error "The %s property can not yet be set with `org-entry-put'"
16293 property))
16294 (t ; a non-special property
16295 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16296 (setq range (org-get-property-block beg end 'force))
16297 (goto-char (car range))
16298 (if (re-search-forward
16299 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16300 (progn
16301 (delete-region (match-beginning 1) (match-end 1))
16302 (goto-char (match-beginning 1)))
16303 (goto-char (cdr range))
16304 (insert "\n")
16305 (backward-char 1)
16306 (org-indent-line-function)
16307 (insert ":" property ":"))
16308 (and value (insert " " value))
16309 (org-indent-line-function)))))))
16311 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16312 "Get all property keys in the current buffer.
16313 With INCLUDE-SPECIALS, also list the special properties that relect things
16314 like tags and TODO state.
16315 With INCLUDE-DEFAULTS, also include properties that has special meaning
16316 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16317 With INCLUDE-COLUMNS, also include property names given in COLUMN
16318 formats in the current buffer."
16319 (let (rtn range cfmt cols s p)
16320 (save-excursion
16321 (save-restriction
16322 (widen)
16323 (goto-char (point-min))
16324 (while (re-search-forward org-property-start-re nil t)
16325 (setq range (org-get-property-block))
16326 (goto-char (car range))
16327 (while (re-search-forward
16328 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16329 (cdr range) t)
16330 (add-to-list 'rtn (org-match-string-no-properties 1)))
16331 (outline-next-heading))))
16333 (when include-specials
16334 (setq rtn (append org-special-properties rtn)))
16336 (when include-defaults
16337 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16339 (when include-columns
16340 (save-excursion
16341 (save-restriction
16342 (widen)
16343 (goto-char (point-min))
16344 (while (re-search-forward
16345 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16346 nil t)
16347 (setq cfmt (match-string 2) s 0)
16348 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16349 cfmt s)
16350 (setq s (match-end 0)
16351 p (match-string 1 cfmt))
16352 (unless (or (equal p "ITEM")
16353 (member p org-special-properties))
16354 (add-to-list 'rtn (match-string 1 cfmt))))))))
16356 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16358 (defun org-property-values (key)
16359 "Return a list of all values of property KEY."
16360 (save-excursion
16361 (save-restriction
16362 (widen)
16363 (goto-char (point-min))
16364 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16365 values)
16366 (while (re-search-forward re nil t)
16367 (add-to-list 'values (org-trim (match-string 1))))
16368 (delete "" values)))))
16370 (defun org-insert-property-drawer ()
16371 "Insert a property drawer into the current entry."
16372 (interactive)
16373 (org-back-to-heading t)
16374 (looking-at outline-regexp)
16375 (let ((indent (- (match-end 0)(match-beginning 0)))
16376 (beg (point))
16377 (re (concat "^[ \t]*" org-keyword-time-regexp))
16378 end hiddenp)
16379 (outline-next-heading)
16380 (setq end (point))
16381 (goto-char beg)
16382 (while (re-search-forward re end t))
16383 (setq hiddenp (org-invisible-p))
16384 (end-of-line 1)
16385 (and (equal (char-after) ?\n) (forward-char 1))
16386 (org-skip-over-state-notes)
16387 (skip-chars-backward " \t\n\r")
16388 (if (eq (char-before) ?*) (forward-char 1))
16389 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16390 (beginning-of-line 0)
16391 (indent-to-column indent)
16392 (beginning-of-line 2)
16393 (indent-to-column indent)
16394 (beginning-of-line 0)
16395 (if hiddenp
16396 (save-excursion
16397 (org-back-to-heading t)
16398 (hide-entry))
16399 (org-flag-drawer t))))
16401 (defun org-set-property (property value)
16402 "In the current entry, set PROPERTY to VALUE.
16403 When called interactively, this will prompt for a property name, offering
16404 completion on existing and default properties. And then it will prompt
16405 for a value, offering competion either on allowed values (via an inherited
16406 xxx_ALL property) or on existing values in other instances of this property
16407 in the current file."
16408 (interactive
16409 (let* ((prop (completing-read
16410 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16411 (cur (org-entry-get nil prop))
16412 (allowed (org-property-get-allowed-values nil prop 'table))
16413 (existing (mapcar 'list (org-property-values prop)))
16414 (val (if allowed
16415 (completing-read "Value: " allowed nil 'req-match)
16416 (completing-read
16417 (concat "Value" (if (and cur (string-match "\\S-" cur))
16418 (concat "[" cur "]") "")
16419 ": ")
16420 existing nil nil "" nil cur))))
16421 (list prop (if (equal val "") cur val))))
16422 (unless (equal (org-entry-get nil property) value)
16423 (org-entry-put nil property value)))
16425 (defun org-delete-property (property)
16426 "In the current entry, delete PROPERTY."
16427 (interactive
16428 (let* ((prop (completing-read
16429 "Property: " (org-entry-properties nil 'standard))))
16430 (list prop)))
16431 (message "Property %s %s" property
16432 (if (org-entry-delete nil property)
16433 "deleted"
16434 "was not present in the entry")))
16436 (defun org-delete-property-globally (property)
16437 "Remove PROPERTY globally, from all entries."
16438 (interactive
16439 (let* ((prop (completing-read
16440 "Globally remove property: "
16441 (mapcar 'list (org-buffer-property-keys)))))
16442 (list prop)))
16443 (save-excursion
16444 (save-restriction
16445 (widen)
16446 (goto-char (point-min))
16447 (let ((cnt 0))
16448 (while (re-search-forward
16449 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16450 nil t)
16451 (setq cnt (1+ cnt))
16452 (replace-match ""))
16453 (message "Property \"%s\" removed from %d entries" property cnt)))))
16455 (defvar org-columns-current-fmt-compiled) ; defined below
16457 (defun org-compute-property-at-point ()
16458 "Compute the property at point.
16459 This looks for an enclosing column format, extracts the operator and
16460 then applies it to the proerty in the column format's scope."
16461 (interactive)
16462 (unless (org-at-property-p)
16463 (error "Not at a property"))
16464 (let ((prop (org-match-string-no-properties 2)))
16465 (org-columns-get-format-and-top-level)
16466 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16467 (error "No operator defined for property %s" prop))
16468 (org-columns-compute prop)))
16470 (defun org-property-get-allowed-values (pom property &optional table)
16471 "Get allowed values for the property PROPERTY.
16472 When TABLE is non-nil, return an alist that can directly be used for
16473 completion."
16474 (let (vals)
16475 (cond
16476 ((equal property "TODO")
16477 (setq vals (org-with-point-at pom
16478 (append org-todo-keywords-1 '("")))))
16479 ((equal property "PRIORITY")
16480 (let ((n org-lowest-priority))
16481 (while (>= n org-highest-priority)
16482 (push (char-to-string n) vals)
16483 (setq n (1- n)))))
16484 ((member property org-special-properties))
16486 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16488 (when (and vals (string-match "\\S-" vals))
16489 (setq vals (car (read-from-string (concat "(" vals ")"))))
16490 (setq vals (mapcar (lambda (x)
16491 (cond ((stringp x) x)
16492 ((numberp x) (number-to-string x))
16493 ((symbolp x) (symbol-name x))
16494 (t "???")))
16495 vals)))))
16496 (if table (mapcar 'list vals) vals)))
16498 (defun org-property-previous-allowed-value (&optional previous)
16499 "Switch to the next allowed value for this property."
16500 (interactive)
16501 (org-property-next-allowed-value t))
16503 (defun org-property-next-allowed-value (&optional previous)
16504 "Switch to the next allowed value for this property."
16505 (interactive)
16506 (unless (org-at-property-p)
16507 (error "Not at a property"))
16508 (let* ((key (match-string 2))
16509 (value (match-string 3))
16510 (allowed (or (org-property-get-allowed-values (point) key)
16511 (and (member value '("[ ]" "[-]" "[X]"))
16512 '("[ ]" "[X]"))))
16513 nval)
16514 (unless allowed
16515 (error "Allowed values for this property have not been defined"))
16516 (if previous (setq allowed (reverse allowed)))
16517 (if (member value allowed)
16518 (setq nval (car (cdr (member value allowed)))))
16519 (setq nval (or nval (car allowed)))
16520 (if (equal nval value)
16521 (error "Only one allowed value for this property"))
16522 (org-at-property-p)
16523 (replace-match (concat " :" key ": " nval) t t)
16524 (org-indent-line-function)
16525 (beginning-of-line 1)
16526 (skip-chars-forward " \t")))
16528 (defun org-find-entry-with-id (ident)
16529 "Locate the entry that contains the ID property with exact value IDENT.
16530 IDENT can be a string, a symbol or a number, this function will search for
16531 the string representation of it.
16532 Return the position where this entry starts, or nil if there is no such entry."
16533 (let ((id (cond
16534 ((stringp ident) ident)
16535 ((symbol-name ident) (symbol-name ident))
16536 ((numberp ident) (number-to-string ident))
16537 (t (error "IDENT %s must be a string, symbol or number" ident))))
16538 (case-fold-search nil))
16539 (save-excursion
16540 (save-restriction
16541 (widen)
16542 (goto-char (point-min))
16543 (when (re-search-forward
16544 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16545 nil t)
16546 (org-back-to-heading)
16547 (point))))))
16549 ;;; Column View
16551 (defvar org-columns-overlays nil
16552 "Holds the list of current column overlays.")
16554 (defvar org-columns-current-fmt nil
16555 "Local variable, holds the currently active column format.")
16556 (defvar org-columns-current-fmt-compiled nil
16557 "Local variable, holds the currently active column format.
16558 This is the compiled version of the format.")
16559 (defvar org-columns-current-widths nil
16560 "Loval variable, holds the currently widths of fields.")
16561 (defvar org-columns-current-maxwidths nil
16562 "Loval variable, holds the currently active maximum column widths.")
16563 (defvar org-columns-begin-marker (make-marker)
16564 "Points to the position where last a column creation command was called.")
16565 (defvar org-columns-top-level-marker (make-marker)
16566 "Points to the position where current columns region starts.")
16568 (defvar org-columns-map (make-sparse-keymap)
16569 "The keymap valid in column display.")
16571 (defun org-columns-content ()
16572 "Switch to contents view while in columns view."
16573 (interactive)
16574 (org-overview)
16575 (org-content))
16577 (org-defkey org-columns-map "c" 'org-columns-content)
16578 (org-defkey org-columns-map "o" 'org-overview)
16579 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16580 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16581 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16582 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16583 (org-defkey org-columns-map "v" 'org-columns-show-value)
16584 (org-defkey org-columns-map "q" 'org-columns-quit)
16585 (org-defkey org-columns-map "r" 'org-columns-redo)
16586 (org-defkey org-columns-map "g" 'org-columns-redo)
16587 (org-defkey org-columns-map [left] 'backward-char)
16588 (org-defkey org-columns-map "\M-b" 'backward-char)
16589 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16590 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16591 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16592 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16593 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16594 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16595 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16596 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16597 (org-defkey org-columns-map "<" 'org-columns-narrow)
16598 (org-defkey org-columns-map ">" 'org-columns-widen)
16599 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16600 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16601 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16602 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16604 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16605 '("Column"
16606 ["Edit property" org-columns-edit-value t]
16607 ["Next allowed value" org-columns-next-allowed-value t]
16608 ["Previous allowed value" org-columns-previous-allowed-value t]
16609 ["Show full value" org-columns-show-value t]
16610 ["Edit allowed values" org-columns-edit-allowed t]
16611 "--"
16612 ["Edit column attributes" org-columns-edit-attributes t]
16613 ["Increase column width" org-columns-widen t]
16614 ["Decrease column width" org-columns-narrow t]
16615 "--"
16616 ["Move column right" org-columns-move-right t]
16617 ["Move column left" org-columns-move-left t]
16618 ["Add column" org-columns-new t]
16619 ["Delete column" org-columns-delete t]
16620 "--"
16621 ["CONTENTS" org-columns-content t]
16622 ["OVERVIEW" org-overview t]
16623 ["Refresh columns display" org-columns-redo t]
16624 "--"
16625 ["Open link" org-columns-open-link t]
16626 "--"
16627 ["Quit" org-columns-quit t]))
16629 (defun org-columns-new-overlay (beg end &optional string face)
16630 "Create a new column overlay and add it to the list."
16631 (let ((ov (org-make-overlay beg end)))
16632 (org-overlay-put ov 'face (or face 'secondary-selection))
16633 (org-overlay-display ov string face)
16634 (push ov org-columns-overlays)
16635 ov))
16637 (defun org-columns-display-here (&optional props)
16638 "Overlay the current line with column display."
16639 (interactive)
16640 (let* ((fmt org-columns-current-fmt-compiled)
16641 (beg (point-at-bol))
16642 (level-face (save-excursion
16643 (beginning-of-line 1)
16644 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16645 (org-get-level-face 2))))
16646 (color (list :foreground
16647 (face-attribute (or level-face 'default) :foreground)))
16648 props pom property ass width f string ov column val modval)
16649 ;; Check if the entry is in another buffer.
16650 (unless props
16651 (if (eq major-mode 'org-agenda-mode)
16652 (setq pom (or (get-text-property (point) 'org-hd-marker)
16653 (get-text-property (point) 'org-marker))
16654 props (if pom (org-entry-properties pom) nil))
16655 (setq props (org-entry-properties nil))))
16656 ;; Walk the format
16657 (while (setq column (pop fmt))
16658 (setq property (car column)
16659 ass (if (equal property "ITEM")
16660 (cons "ITEM"
16661 (save-match-data
16662 (org-no-properties
16663 (org-remove-tabs
16664 (buffer-substring-no-properties
16665 (point-at-bol) (point-at-eol))))))
16666 (assoc property props))
16667 width (or (cdr (assoc property org-columns-current-maxwidths))
16668 (nth 2 column)
16669 (length property))
16670 f (format "%%-%d.%ds | " width width)
16671 val (or (cdr ass) "")
16672 modval (if (equal property "ITEM")
16673 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16674 string (format f (or modval val)))
16675 ;; Create the overlay
16676 (org-unmodified
16677 (setq ov (org-columns-new-overlay
16678 beg (setq beg (1+ beg)) string
16679 (list color 'org-column)))
16680 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16681 (org-overlay-put ov 'keymap org-columns-map)
16682 (org-overlay-put ov 'org-columns-key property)
16683 (org-overlay-put ov 'org-columns-value (cdr ass))
16684 (org-overlay-put ov 'org-columns-value-modified modval)
16685 (org-overlay-put ov 'org-columns-pom pom)
16686 (org-overlay-put ov 'org-columns-format f))
16687 (if (or (not (char-after beg))
16688 (equal (char-after beg) ?\n))
16689 (let ((inhibit-read-only t))
16690 (save-excursion
16691 (goto-char beg)
16692 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16693 ;; Make the rest of the line disappear.
16694 (org-unmodified
16695 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16696 (org-overlay-put ov 'invisible t)
16697 (org-overlay-put ov 'keymap org-columns-map)
16698 (org-overlay-put ov 'intangible t)
16699 (push ov org-columns-overlays)
16700 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16701 (org-overlay-put ov 'keymap org-columns-map)
16702 (push ov org-columns-overlays)
16703 (let ((inhibit-read-only t))
16704 (put-text-property (max (point-min) (1- (point-at-bol)))
16705 (min (point-max) (1+ (point-at-eol)))
16706 'read-only "Type `e' to edit property")))))
16708 (defvar org-previous-header-line-format nil
16709 "The header line format before column view was turned on.")
16710 (defvar org-columns-inhibit-recalculation nil
16711 "Inhibit recomputing of columns on column view startup.")
16714 (defvar header-line-format)
16715 (defun org-columns-display-here-title ()
16716 "Overlay the newline before the current line with the table title."
16717 (interactive)
16718 (let ((fmt org-columns-current-fmt-compiled)
16719 string (title "")
16720 property width f column str widths)
16721 (while (setq column (pop fmt))
16722 (setq property (car column)
16723 str (or (nth 1 column) property)
16724 width (or (cdr (assoc property org-columns-current-maxwidths))
16725 (nth 2 column)
16726 (length str))
16727 widths (push width widths)
16728 f (format "%%-%d.%ds | " width width)
16729 string (format f str)
16730 title (concat title string)))
16731 (setq title (concat
16732 (org-add-props " " nil 'display '(space :align-to 0))
16733 (org-add-props title nil 'face '(:weight bold :underline t))))
16734 (org-set-local 'org-previous-header-line-format header-line-format)
16735 (org-set-local 'org-columns-current-widths (nreverse widths))
16736 (setq header-line-format title)))
16738 (defun org-columns-remove-overlays ()
16739 "Remove all currently active column overlays."
16740 (interactive)
16741 (when (marker-buffer org-columns-begin-marker)
16742 (with-current-buffer (marker-buffer org-columns-begin-marker)
16743 (when (local-variable-p 'org-previous-header-line-format)
16744 (setq header-line-format org-previous-header-line-format)
16745 (kill-local-variable 'org-previous-header-line-format))
16746 (move-marker org-columns-begin-marker nil)
16747 (move-marker org-columns-top-level-marker nil)
16748 (org-unmodified
16749 (mapc 'org-delete-overlay org-columns-overlays)
16750 (setq org-columns-overlays nil)
16751 (let ((inhibit-read-only t))
16752 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16754 (defun org-columns-cleanup-item (item fmt)
16755 "Remove from ITEM what is a column in the format FMT."
16756 (if (not org-complex-heading-regexp)
16757 item
16758 (when (string-match org-complex-heading-regexp item)
16759 (concat
16760 (org-add-props (concat (match-string 1 item) " ") nil
16761 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16762 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16763 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16764 " " (match-string 4 item)
16765 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16767 (defun org-columns-show-value ()
16768 "Show the full value of the property."
16769 (interactive)
16770 (let ((value (get-char-property (point) 'org-columns-value)))
16771 (message "Value is: %s" (or value ""))))
16773 (defun org-columns-quit ()
16774 "Remove the column overlays and in this way exit column editing."
16775 (interactive)
16776 (org-unmodified
16777 (org-columns-remove-overlays)
16778 (let ((inhibit-read-only t))
16779 (remove-text-properties (point-min) (point-max) '(read-only t))))
16780 (when (eq major-mode 'org-agenda-mode)
16781 (message
16782 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16784 (defun org-columns-check-computed ()
16785 "Check if this column value is computed.
16786 If yes, throw an error indicating that changing it does not make sense."
16787 (let ((val (get-char-property (point) 'org-columns-value)))
16788 (when (and (stringp val)
16789 (get-char-property 0 'org-computed val))
16790 (error "This value is computed from the entry's children"))))
16792 (defun org-columns-todo (&optional arg)
16793 "Change the TODO state during column view."
16794 (interactive "P")
16795 (org-columns-edit-value "TODO"))
16797 (defun org-columns-set-tags-or-toggle (&optional arg)
16798 "Toggle checkbox at point, or set tags for current headline."
16799 (interactive "P")
16800 (if (string-match "\\`\\[[ xX-]\\]\\'"
16801 (get-char-property (point) 'org-columns-value))
16802 (org-columns-next-allowed-value)
16803 (org-columns-edit-value "TAGS")))
16805 (defun org-columns-edit-value (&optional key)
16806 "Edit the value of the property at point in column view.
16807 Where possible, use the standard interface for changing this line."
16808 (interactive)
16809 (org-columns-check-computed)
16810 (let* ((external-key key)
16811 (col (current-column))
16812 (key (or key (get-char-property (point) 'org-columns-key)))
16813 (value (get-char-property (point) 'org-columns-value))
16814 (bol (point-at-bol)) (eol (point-at-eol))
16815 (pom (or (get-text-property bol 'org-hd-marker)
16816 (point))) ; keep despite of compiler waring
16817 (line-overlays
16818 (delq nil (mapcar (lambda (x)
16819 (and (eq (overlay-buffer x) (current-buffer))
16820 (>= (overlay-start x) bol)
16821 (<= (overlay-start x) eol)
16823 org-columns-overlays)))
16824 nval eval allowed)
16825 (cond
16826 ((equal key "CLOCKSUM")
16827 (error "This special column cannot be edited"))
16828 ((equal key "ITEM")
16829 (setq eval '(org-with-point-at pom
16830 (org-edit-headline))))
16831 ((equal key "TODO")
16832 (setq eval '(org-with-point-at pom
16833 (let ((current-prefix-arg
16834 (if external-key current-prefix-arg '(4))))
16835 (call-interactively 'org-todo)))))
16836 ((equal key "PRIORITY")
16837 (setq eval '(org-with-point-at pom
16838 (call-interactively 'org-priority))))
16839 ((equal key "TAGS")
16840 (setq eval '(org-with-point-at pom
16841 (let ((org-fast-tag-selection-single-key
16842 (if (eq org-fast-tag-selection-single-key 'expert)
16843 t org-fast-tag-selection-single-key)))
16844 (call-interactively 'org-set-tags)))))
16845 ((equal key "DEADLINE")
16846 (setq eval '(org-with-point-at pom
16847 (call-interactively 'org-deadline))))
16848 ((equal key "SCHEDULED")
16849 (setq eval '(org-with-point-at pom
16850 (call-interactively 'org-schedule))))
16852 (setq allowed (org-property-get-allowed-values pom key 'table))
16853 (if allowed
16854 (setq nval (completing-read "Value: " allowed nil t))
16855 (setq nval (read-string "Edit: " value)))
16856 (setq nval (org-trim nval))
16857 (when (not (equal nval value))
16858 (setq eval '(org-entry-put pom key nval)))))
16859 (when eval
16860 (let ((inhibit-read-only t))
16861 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16862 (unwind-protect
16863 (progn
16864 (setq org-columns-overlays
16865 (org-delete-all line-overlays org-columns-overlays))
16866 (mapc 'org-delete-overlay line-overlays)
16867 (org-columns-eval eval))
16868 (org-columns-display-here))))
16869 (move-to-column col)
16870 (if (and (org-mode-p)
16871 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16872 (org-columns-update key))))
16874 (defun org-edit-headline () ; FIXME: this is not columns specific
16875 "Edit the current headline, the part without TODO keyword, TAGS."
16876 (org-back-to-heading)
16877 (when (looking-at org-todo-line-regexp)
16878 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16879 (txt (match-string 3))
16880 (post "")
16881 txt2)
16882 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16883 (setq post (match-string 0 txt)
16884 txt (substring txt 0 (match-beginning 0))))
16885 (setq txt2 (read-string "Edit: " txt))
16886 (when (not (equal txt txt2))
16887 (beginning-of-line 1)
16888 (insert pre txt2 post)
16889 (delete-region (point) (point-at-eol))
16890 (org-set-tags nil t)))))
16892 (defun org-columns-edit-allowed ()
16893 "Edit the list of allowed values for the current property."
16894 (interactive)
16895 (let* ((key (get-char-property (point) 'org-columns-key))
16896 (key1 (concat key "_ALL"))
16897 (allowed (org-entry-get (point) key1 t))
16898 nval)
16899 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16900 (setq nval (read-string "Allowed: " allowed))
16901 (org-entry-put
16902 (cond ((marker-position org-entry-property-inherited-from)
16903 org-entry-property-inherited-from)
16904 ((marker-position org-columns-top-level-marker)
16905 org-columns-top-level-marker))
16906 key1 nval)))
16908 (defmacro org-no-warnings (&rest body)
16909 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16911 (defun org-columns-eval (form)
16912 (let (hidep)
16913 (save-excursion
16914 (beginning-of-line 1)
16915 ;; `next-line' is needed here, because it skips invisible line.
16916 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16917 (setq hidep (org-on-heading-p 1)))
16918 (eval form)
16919 (and hidep (hide-entry))))
16921 (defun org-columns-previous-allowed-value ()
16922 "Switch to the previous allowed value for this column."
16923 (interactive)
16924 (org-columns-next-allowed-value t))
16926 (defun org-columns-next-allowed-value (&optional previous)
16927 "Switch to the next allowed value for this column."
16928 (interactive)
16929 (org-columns-check-computed)
16930 (let* ((col (current-column))
16931 (key (get-char-property (point) 'org-columns-key))
16932 (value (get-char-property (point) 'org-columns-value))
16933 (bol (point-at-bol)) (eol (point-at-eol))
16934 (pom (or (get-text-property bol 'org-hd-marker)
16935 (point))) ; keep despite of compiler waring
16936 (line-overlays
16937 (delq nil (mapcar (lambda (x)
16938 (and (eq (overlay-buffer x) (current-buffer))
16939 (>= (overlay-start x) bol)
16940 (<= (overlay-start x) eol)
16942 org-columns-overlays)))
16943 (allowed (or (org-property-get-allowed-values pom key)
16944 (and (memq
16945 (nth 4 (assoc key org-columns-current-fmt-compiled))
16946 '(checkbox checkbox-n-of-m checkbox-percent))
16947 '("[ ]" "[X]"))))
16948 nval)
16949 (when (equal key "ITEM")
16950 (error "Cannot edit item headline from here"))
16951 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16952 (error "Allowed values for this property have not been defined"))
16953 (if (member key '("SCHEDULED" "DEADLINE"))
16954 (setq nval (if previous 'earlier 'later))
16955 (if previous (setq allowed (reverse allowed)))
16956 (if (member value allowed)
16957 (setq nval (car (cdr (member value allowed)))))
16958 (setq nval (or nval (car allowed)))
16959 (if (equal nval value)
16960 (error "Only one allowed value for this property")))
16961 (let ((inhibit-read-only t))
16962 (remove-text-properties (1- bol) eol '(read-only t))
16963 (unwind-protect
16964 (progn
16965 (setq org-columns-overlays
16966 (org-delete-all line-overlays org-columns-overlays))
16967 (mapc 'org-delete-overlay line-overlays)
16968 (org-columns-eval '(org-entry-put pom key nval)))
16969 (org-columns-display-here)))
16970 (move-to-column col)
16971 (if (and (org-mode-p)
16972 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16973 (org-columns-update key))))
16975 (defun org-verify-version (task)
16976 (cond
16977 ((eq task 'columns)
16978 (if (or (featurep 'xemacs)
16979 (< emacs-major-version 22))
16980 (error "Emacs 22 is required for the columns feature")))))
16982 (defun org-columns-open-link (&optional arg)
16983 (interactive "P")
16984 (let ((value (get-char-property (point) 'org-columns-value)))
16985 (org-open-link-from-string value arg)))
16987 (defun org-open-link-from-string (s &optional arg)
16988 "Open a link in the string S, as if it was in Org-mode."
16989 (interactive)
16990 (with-temp-buffer
16991 (let ((org-inhibit-startup t))
16992 (org-mode)
16993 (insert s)
16994 (goto-char (point-min))
16995 (org-open-at-point arg))))
16997 (defun org-columns-get-format-and-top-level ()
16998 (let (fmt)
16999 (when (condition-case nil (org-back-to-heading) (error nil))
17000 (move-marker org-entry-property-inherited-from nil)
17001 (setq fmt (org-entry-get nil "COLUMNS" t)))
17002 (setq fmt (or fmt org-columns-default-format))
17003 (org-set-local 'org-columns-current-fmt fmt)
17004 (org-columns-compile-format fmt)
17005 (if (marker-position org-entry-property-inherited-from)
17006 (move-marker org-columns-top-level-marker
17007 org-entry-property-inherited-from)
17008 (move-marker org-columns-top-level-marker (point)))
17009 fmt))
17011 (defun org-columns ()
17012 "Turn on column view on an org-mode file."
17013 (interactive)
17014 (org-verify-version 'columns)
17015 (org-columns-remove-overlays)
17016 (move-marker org-columns-begin-marker (point))
17017 (let (beg end fmt cache maxwidths)
17018 (setq fmt (org-columns-get-format-and-top-level))
17019 (save-excursion
17020 (goto-char org-columns-top-level-marker)
17021 (setq beg (point))
17022 (unless org-columns-inhibit-recalculation
17023 (org-columns-compute-all))
17024 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17025 (point-max)))
17026 ;; Get and cache the properties
17027 (goto-char beg)
17028 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17029 (save-excursion
17030 (save-restriction
17031 (narrow-to-region beg end)
17032 (org-clock-sum))))
17033 (while (re-search-forward (concat "^" outline-regexp) end t)
17034 (push (cons (org-current-line) (org-entry-properties)) cache))
17035 (when cache
17036 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17037 (org-set-local 'org-columns-current-maxwidths maxwidths)
17038 (org-columns-display-here-title)
17039 (mapc (lambda (x)
17040 (goto-line (car x))
17041 (org-columns-display-here (cdr x)))
17042 cache)))))
17044 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17045 "Insert a new column, to the leeft o the current column."
17046 (interactive)
17047 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17048 cell)
17049 (setq prop (completing-read
17050 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17051 nil nil prop))
17052 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17053 (setq width (read-string "Column width: " (if width (number-to-string width))))
17054 (if (string-match "\\S-" width)
17055 (setq width (string-to-number width))
17056 (setq width nil))
17057 (setq fmt (completing-read "Summary [none]: "
17058 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17059 nil t))
17060 (if (string-match "\\S-" fmt)
17061 (setq fmt (intern fmt))
17062 (setq fmt nil))
17063 (if (eq fmt 'none) (setq fmt nil))
17064 (if editp
17065 (progn
17066 (setcar editp prop)
17067 (setcdr editp (list title width nil fmt)))
17068 (setq cell (nthcdr (1- (current-column))
17069 org-columns-current-fmt-compiled))
17070 (setcdr cell (cons (list prop title width nil fmt)
17071 (cdr cell))))
17072 (org-columns-store-format)
17073 (org-columns-redo)))
17075 (defun org-columns-delete ()
17076 "Delete the column at point from columns view."
17077 (interactive)
17078 (let* ((n (current-column))
17079 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17080 (when (y-or-n-p
17081 (format "Are you sure you want to remove column \"%s\"? " title))
17082 (setq org-columns-current-fmt-compiled
17083 (delq (nth n org-columns-current-fmt-compiled)
17084 org-columns-current-fmt-compiled))
17085 (org-columns-store-format)
17086 (org-columns-redo)
17087 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17088 (backward-char 1)))))
17090 (defun org-columns-edit-attributes ()
17091 "Edit the attributes of the current column."
17092 (interactive)
17093 (let* ((n (current-column))
17094 (info (nth n org-columns-current-fmt-compiled)))
17095 (apply 'org-columns-new info)))
17097 (defun org-columns-widen (arg)
17098 "Make the column wider by ARG characters."
17099 (interactive "p")
17100 (let* ((n (current-column))
17101 (entry (nth n org-columns-current-fmt-compiled))
17102 (width (or (nth 2 entry)
17103 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17104 (setq width (max 1 (+ width arg)))
17105 (setcar (nthcdr 2 entry) width)
17106 (org-columns-store-format)
17107 (org-columns-redo)))
17109 (defun org-columns-narrow (arg)
17110 "Make the column nrrower by ARG characters."
17111 (interactive "p")
17112 (org-columns-widen (- arg)))
17114 (defun org-columns-move-right ()
17115 "Swap this column with the one to the right."
17116 (interactive)
17117 (let* ((n (current-column))
17118 (cell (nthcdr n org-columns-current-fmt-compiled))
17120 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17121 (error "Cannot shift this column further to the right"))
17122 (setq e (car cell))
17123 (setcar cell (car (cdr cell)))
17124 (setcdr cell (cons e (cdr (cdr cell))))
17125 (org-columns-store-format)
17126 (org-columns-redo)
17127 (forward-char 1)))
17129 (defun org-columns-move-left ()
17130 "Swap this column with the one to the left."
17131 (interactive)
17132 (let* ((n (current-column)))
17133 (when (= n 0)
17134 (error "Cannot shift this column further to the left"))
17135 (backward-char 1)
17136 (org-columns-move-right)
17137 (backward-char 1)))
17139 (defun org-columns-store-format ()
17140 "Store the text version of the current columns format in appropriate place.
17141 This is either in the COLUMNS property of the node starting the current column
17142 display, or in the #+COLUMNS line of the current buffer."
17143 (let (fmt (cnt 0))
17144 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17145 (org-set-local 'org-columns-current-fmt fmt)
17146 (if (marker-position org-columns-top-level-marker)
17147 (save-excursion
17148 (goto-char org-columns-top-level-marker)
17149 (if (and (org-at-heading-p)
17150 (org-entry-get nil "COLUMNS"))
17151 (org-entry-put nil "COLUMNS" fmt)
17152 (goto-char (point-min))
17153 ;; Overwrite all #+COLUMNS lines....
17154 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17155 (setq cnt (1+ cnt))
17156 (replace-match (concat "#+COLUMNS: " fmt) t t))
17157 (unless (> cnt 0)
17158 (goto-char (point-min))
17159 (or (org-on-heading-p t) (outline-next-heading))
17160 (let ((inhibit-read-only t))
17161 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17162 (org-set-local 'org-columns-default-format fmt))))))
17164 (defvar org-overriding-columns-format nil
17165 "When set, overrides any other definition.")
17166 (defvar org-agenda-view-columns-initially nil
17167 "When set, switch to columns view immediately after creating the agenda.")
17169 (defun org-agenda-columns ()
17170 "Turn on column view in the agenda."
17171 (interactive)
17172 (org-verify-version 'columns)
17173 (org-columns-remove-overlays)
17174 (move-marker org-columns-begin-marker (point))
17175 (let (fmt cache maxwidths m)
17176 (cond
17177 ((and (local-variable-p 'org-overriding-columns-format)
17178 org-overriding-columns-format)
17179 (setq fmt org-overriding-columns-format))
17180 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17181 (setq fmt (org-entry-get m "COLUMNS" t)))
17182 ((and (boundp 'org-columns-current-fmt)
17183 (local-variable-p 'org-columns-current-fmt)
17184 org-columns-current-fmt)
17185 (setq fmt org-columns-current-fmt))
17186 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17187 (setq m (get-text-property m 'org-hd-marker))
17188 (setq fmt (org-entry-get m "COLUMNS" t))))
17189 (setq fmt (or fmt org-columns-default-format))
17190 (org-set-local 'org-columns-current-fmt fmt)
17191 (org-columns-compile-format fmt)
17192 (save-excursion
17193 ;; Get and cache the properties
17194 (goto-char (point-min))
17195 (while (not (eobp))
17196 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17197 (get-text-property (point) 'org-marker)))
17198 (push (cons (org-current-line) (org-entry-properties m)) cache))
17199 (beginning-of-line 2))
17200 (when cache
17201 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17202 (org-set-local 'org-columns-current-maxwidths maxwidths)
17203 (org-columns-display-here-title)
17204 (mapc (lambda (x)
17205 (goto-line (car x))
17206 (org-columns-display-here (cdr x)))
17207 cache)))))
17209 (defun org-columns-get-autowidth-alist (s cache)
17210 "Derive the maximum column widths from the format and the cache."
17211 (let ((start 0) rtn)
17212 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17213 (push (cons (match-string 1 s) 1) rtn)
17214 (setq start (match-end 0)))
17215 (mapc (lambda (x)
17216 (setcdr x (apply 'max
17217 (mapcar
17218 (lambda (y)
17219 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17220 cache))))
17221 rtn)
17222 rtn))
17224 (defun org-columns-compute-all ()
17225 "Compute all columns that have operators defined."
17226 (org-unmodified
17227 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17228 (let ((columns org-columns-current-fmt-compiled) col)
17229 (while (setq col (pop columns))
17230 (when (nth 3 col)
17231 (save-excursion
17232 (org-columns-compute (car col)))))))
17234 (defun org-columns-update (property)
17235 "Recompute PROPERTY, and update the columns display for it."
17236 (org-columns-compute property)
17237 (let (fmt val pos)
17238 (save-excursion
17239 (mapc (lambda (ov)
17240 (when (equal (org-overlay-get ov 'org-columns-key) property)
17241 (setq pos (org-overlay-start ov))
17242 (goto-char pos)
17243 (when (setq val (cdr (assoc property
17244 (get-text-property
17245 (point-at-bol) 'org-summaries))))
17246 (setq fmt (org-overlay-get ov 'org-columns-format))
17247 (org-overlay-put ov 'org-columns-value val)
17248 (org-overlay-put ov 'display (format fmt val)))))
17249 org-columns-overlays))))
17251 (defun org-columns-compute (property)
17252 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17253 (interactive)
17254 (let* ((re (concat "^" outline-regexp))
17255 (lmax 30) ; Does anyone use deeper levels???
17256 (lsum (make-vector lmax 0))
17257 (lflag (make-vector lmax nil))
17258 (level 0)
17259 (ass (assoc property org-columns-current-fmt-compiled))
17260 (format (nth 4 ass))
17261 (printf (nth 5 ass))
17262 (beg org-columns-top-level-marker)
17263 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17264 (save-excursion
17265 ;; Find the region to compute
17266 (goto-char beg)
17267 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17268 (goto-char end)
17269 ;; Walk the tree from the back and do the computations
17270 (while (re-search-backward re beg t)
17271 (setq sumpos (match-beginning 0)
17272 last-level level
17273 level (org-outline-level)
17274 val (org-entry-get nil property)
17275 valflag (and val (string-match "\\S-" val)))
17276 (cond
17277 ((< level last-level)
17278 ;; put the sum of lower levels here as a property
17279 (setq sum (aref lsum last-level) ; current sum
17280 flag (aref lflag last-level) ; any valid entries from children?
17281 str (org-column-number-to-string sum format printf)
17282 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17283 useval (if flag str1 (if valflag val ""))
17284 sum-alist (get-text-property sumpos 'org-summaries))
17285 (if (assoc property sum-alist)
17286 (setcdr (assoc property sum-alist) useval)
17287 (push (cons property useval) sum-alist)
17288 (org-unmodified
17289 (add-text-properties sumpos (1+ sumpos)
17290 (list 'org-summaries sum-alist))))
17291 (when val
17292 (org-entry-put nil property (if flag str val)))
17293 ;; add current to current level accumulator
17294 (when (or flag valflag)
17295 (aset lsum level (+ (aref lsum level)
17296 (if flag sum (org-column-string-to-number
17297 (if flag str val) format))))
17298 (aset lflag level t))
17299 ;; clear accumulators for deeper levels
17300 (loop for l from (1+ level) to (1- lmax) do
17301 (aset lsum l 0)
17302 (aset lflag l nil)))
17303 ((>= level last-level)
17304 ;; add what we have here to the accumulator for this level
17305 (aset lsum level (+ (aref lsum level)
17306 (org-column-string-to-number (or val "0") format)))
17307 (and valflag (aset lflag level t)))
17308 (t (error "This should not happen")))))))
17310 (defun org-columns-redo ()
17311 "Construct the column display again."
17312 (interactive)
17313 (message "Recomputing columns...")
17314 (save-excursion
17315 (if (marker-position org-columns-begin-marker)
17316 (goto-char org-columns-begin-marker))
17317 (org-columns-remove-overlays)
17318 (if (org-mode-p)
17319 (call-interactively 'org-columns)
17320 (call-interactively 'org-agenda-columns)))
17321 (message "Recomputing columns...done"))
17323 (defun org-columns-not-in-agenda ()
17324 (if (eq major-mode 'org-agenda-mode)
17325 (error "This command is only allowed in Org-mode buffers")))
17328 (defun org-string-to-number (s)
17329 "Convert string to number, and interpret hh:mm:ss."
17330 (if (not (string-match ":" s))
17331 (string-to-number s)
17332 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17333 (while l
17334 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17335 sum)))
17337 (defun org-column-number-to-string (n fmt &optional printf)
17338 "Convert a computed column number to a string value, according to FMT."
17339 (cond
17340 ((eq fmt 'add_times)
17341 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17342 (format "%d:%02d" h m)))
17343 ((eq fmt 'checkbox)
17344 (cond ((= n (floor n)) "[X]")
17345 ((> n 1.) "[-]")
17346 (t "[ ]")))
17347 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17348 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17349 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17350 (printf (format printf n))
17351 ((eq fmt 'currency)
17352 (format "%.2f" n))
17353 (t (number-to-string n))))
17355 (defun org-nofm-to-completion (n m &optional percent)
17356 (if (not percent)
17357 (format "[%d/%d]" n m)
17358 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17360 (defun org-column-string-to-number (s fmt)
17361 "Convert a column value to a number that can be used for column computing."
17362 (cond
17363 ((string-match ":" s)
17364 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17365 (while l
17366 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17367 sum))
17368 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17369 (if (equal s "[X]") 1. 0.000001))
17370 (t (string-to-number s))))
17372 (defun org-columns-uncompile-format (cfmt)
17373 "Turn the compiled columns format back into a string representation."
17374 (let ((rtn "") e s prop title op width fmt printf)
17375 (while (setq e (pop cfmt))
17376 (setq prop (car e)
17377 title (nth 1 e)
17378 width (nth 2 e)
17379 op (nth 3 e)
17380 fmt (nth 4 e)
17381 printf (nth 5 e))
17382 (cond
17383 ((eq fmt 'add_times) (setq op ":"))
17384 ((eq fmt 'checkbox) (setq op "X"))
17385 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17386 ((eq fmt 'checkbox-percent) (setq op "X%"))
17387 ((eq fmt 'add_numbers) (setq op "+"))
17388 ((eq fmt 'currency) (setq op "$")))
17389 (if (and op printf) (setq op (concat op ";" printf)))
17390 (if (equal title prop) (setq title nil))
17391 (setq s (concat "%" (if width (number-to-string width))
17392 prop
17393 (if title (concat "(" title ")"))
17394 (if op (concat "{" op "}"))))
17395 (setq rtn (concat rtn " " s)))
17396 (org-trim rtn)))
17398 (defun org-columns-compile-format (fmt)
17399 "Turn a column format string into an alist of specifications.
17400 The alist has one entry for each column in the format. The elements of
17401 that list are:
17402 property the property
17403 title the title field for the columns
17404 width the column width in characters, can be nil for automatic
17405 operator the operator if any
17406 format the output format for computed results, derived from operator
17407 printf a printf format for computed values"
17408 (let ((start 0) width prop title op f printf)
17409 (setq org-columns-current-fmt-compiled nil)
17410 (while (string-match
17411 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17412 fmt start)
17413 (setq start (match-end 0)
17414 width (match-string 1 fmt)
17415 prop (match-string 2 fmt)
17416 title (or (match-string 3 fmt) prop)
17417 op (match-string 4 fmt)
17418 f nil
17419 printf nil)
17420 (if width (setq width (string-to-number width)))
17421 (when (and op (string-match ";" op))
17422 (setq printf (substring op (match-end 0))
17423 op (substring op 0 (match-beginning 0))))
17424 (cond
17425 ((equal op "+") (setq f 'add_numbers))
17426 ((equal op "$") (setq f 'currency))
17427 ((equal op ":") (setq f 'add_times))
17428 ((equal op "X") (setq f 'checkbox))
17429 ((equal op "X/") (setq f 'checkbox-n-of-m))
17430 ((equal op "X%") (setq f 'checkbox-percent))
17432 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17433 (setq org-columns-current-fmt-compiled
17434 (nreverse org-columns-current-fmt-compiled))))
17437 ;;; Dynamic block for Column view
17439 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17440 "Get the column view of the current buffer or subtree.
17441 The first optional argument MAXLEVEL sets the level limit. A
17442 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17443 empty rows, an empty row being one where all the column view
17444 specifiers except ITEM are empty. This function returns a list
17445 containing the title row and all other rows. Each row is a list
17446 of fields."
17447 (save-excursion
17448 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17449 (n (length title)) row tbl)
17450 (goto-char (point-min))
17451 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17452 (or (null maxlevel)
17453 (>= maxlevel
17454 (if org-odd-levels-only
17455 (/ (1+ (length (match-string 1))) 2)
17456 (length (match-string 1))))))
17457 (when (get-char-property (match-beginning 0) 'org-columns-key)
17458 (setq row nil)
17459 (loop for i from 0 to (1- n) do
17460 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17461 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17463 row))
17464 (setq row (nreverse row))
17465 (unless (and skip-empty-rows
17466 (eq 1 (length (delete "" (delete-dups row)))))
17467 (push row tbl))))
17468 (append (list title 'hline) (nreverse tbl)))))
17470 (defun org-dblock-write:columnview (params)
17471 "Write the column view table.
17472 PARAMS is a property list of parameters:
17474 :width enforce same column widths with <N> specifiers.
17475 :id the :ID: property of the entry where the columns view
17476 should be built, as a string. When `local', call locally.
17477 When `global' call column view with the cursor at the beginning
17478 of the buffer (usually this means that the whole buffer switches
17479 to column view).
17480 :hlines When t, insert a hline before each item. When a number, insert
17481 a hline before each level <= that number.
17482 :vlines When t, make each column a colgroup to enforce vertical lines.
17483 :maxlevel When set to a number, don't capture headlines below this level.
17484 :skip-empty-rows
17485 When t, skip rows where all specifiers other than ITEM are empty."
17486 (let ((pos (move-marker (make-marker) (point)))
17487 (hlines (plist-get params :hlines))
17488 (vlines (plist-get params :vlines))
17489 (maxlevel (plist-get params :maxlevel))
17490 (skip-empty-rows (plist-get params :skip-empty-rows))
17491 tbl id idpos nfields tmp)
17492 (save-excursion
17493 (save-restriction
17494 (when (setq id (plist-get params :id))
17495 (cond ((not id) nil)
17496 ((eq id 'global) (goto-char (point-min)))
17497 ((eq id 'local) nil)
17498 ((setq idpos (org-find-entry-with-id id))
17499 (goto-char idpos))
17500 (t (error "Cannot find entry with :ID: %s" id))))
17501 (org-columns)
17502 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17503 (setq nfields (length (car tbl)))
17504 (org-columns-quit)))
17505 (goto-char pos)
17506 (move-marker pos nil)
17507 (when tbl
17508 (when (plist-get params :hlines)
17509 (setq tmp nil)
17510 (while tbl
17511 (if (eq (car tbl) 'hline)
17512 (push (pop tbl) tmp)
17513 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17514 (if (and (not (eq (car tmp) 'hline))
17515 (or (eq hlines t)
17516 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17517 (push 'hline tmp)))
17518 (push (pop tbl) tmp)))
17519 (setq tbl (nreverse tmp)))
17520 (when vlines
17521 (setq tbl (mapcar (lambda (x)
17522 (if (eq 'hline x) x (cons "" x)))
17523 tbl))
17524 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17525 (setq pos (point))
17526 (insert (org-listtable-to-string tbl))
17527 (when (plist-get params :width)
17528 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17529 org-columns-current-widths "|")))
17530 (goto-char pos)
17531 (org-table-align))))
17533 (defun org-listtable-to-string (tbl)
17534 "Convert a listtable TBL to a string that contains the Org-mode table.
17535 The table still need to be alligned. The resulting string has no leading
17536 and tailing newline characters."
17537 (mapconcat
17538 (lambda (x)
17539 (cond
17540 ((listp x)
17541 (concat "|" (mapconcat 'identity x "|") "|"))
17542 ((eq x 'hline) "|-|")
17543 (t (error "Garbage in listtable: %s" x))))
17544 tbl "\n"))
17546 (defun org-insert-columns-dblock ()
17547 "Create a dynamic block capturing a column view table."
17548 (interactive)
17549 (let ((defaults '(:name "columnview" :hlines 1))
17550 (id (completing-read
17551 "Capture columns (local, global, entry with :ID: property) [local]: "
17552 (append '(("global") ("local"))
17553 (mapcar 'list (org-property-values "ID"))))))
17554 (if (equal id "") (setq id 'local))
17555 (if (equal id "global") (setq id 'global))
17556 (setq defaults (append defaults (list :id id)))
17557 (org-create-dblock defaults)
17558 (org-update-dblock)))
17560 ;;;; Timestamps
17562 (defvar org-last-changed-timestamp nil)
17563 (defvar org-time-was-given) ; dynamically scoped parameter
17564 (defvar org-end-time-was-given) ; dynamically scoped parameter
17565 (defvar org-ts-what) ; dynamically scoped parameter
17567 (defun org-time-stamp (arg)
17568 "Prompt for a date/time and insert a time stamp.
17569 If the user specifies a time like HH:MM, or if this command is called
17570 with a prefix argument, the time stamp will contain date and time.
17571 Otherwise, only the date will be included. All parts of a date not
17572 specified by the user will be filled in from the current date/time.
17573 So if you press just return without typing anything, the time stamp
17574 will represent the current date/time. If there is already a timestamp
17575 at the cursor, it will be modified."
17576 (interactive "P")
17577 (let* ((ts nil)
17578 (default-time
17579 ;; Default time is either today, or, when entering a range,
17580 ;; the range start.
17581 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17582 (save-excursion
17583 (re-search-backward
17584 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17585 (- (point) 20) t)))
17586 (apply 'encode-time (org-parse-time-string (match-string 1)))
17587 (current-time)))
17588 (default-input (and ts (org-get-compact-tod ts)))
17589 org-time-was-given org-end-time-was-given time)
17590 (cond
17591 ((and (org-at-timestamp-p)
17592 (eq last-command 'org-time-stamp)
17593 (eq this-command 'org-time-stamp))
17594 (insert "--")
17595 (setq time (let ((this-command this-command))
17596 (org-read-date arg 'totime nil nil default-time default-input)))
17597 (org-insert-time-stamp time (or org-time-was-given arg)))
17598 ((org-at-timestamp-p)
17599 (setq time (let ((this-command this-command))
17600 (org-read-date arg 'totime nil nil default-time default-input)))
17601 (when (org-at-timestamp-p) ; just to get the match data
17602 (replace-match "")
17603 (setq org-last-changed-timestamp
17604 (org-insert-time-stamp
17605 time (or org-time-was-given arg)
17606 nil nil nil (list org-end-time-was-given))))
17607 (message "Timestamp updated"))
17609 (setq time (let ((this-command this-command))
17610 (org-read-date arg 'totime nil nil default-time default-input)))
17611 (org-insert-time-stamp time (or org-time-was-given arg)
17612 nil nil nil (list org-end-time-was-given))))))
17614 ;; FIXME: can we use this for something else????
17615 ;; like computing time differences?????
17616 (defun org-get-compact-tod (s)
17617 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17618 (let* ((t1 (match-string 1 s))
17619 (h1 (string-to-number (match-string 2 s)))
17620 (m1 (string-to-number (match-string 3 s)))
17621 (t2 (and (match-end 4) (match-string 5 s)))
17622 (h2 (and t2 (string-to-number (match-string 6 s))))
17623 (m2 (and t2 (string-to-number (match-string 7 s))))
17624 dh dm)
17625 (if (not t2)
17627 (setq dh (- h2 h1) dm (- m2 m1))
17628 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17629 (concat t1 "+" (number-to-string dh)
17630 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17632 (defun org-time-stamp-inactive (&optional arg)
17633 "Insert an inactive time stamp.
17634 An inactive time stamp is enclosed in square brackets instead of angle
17635 brackets. It is inactive in the sense that it does not trigger agenda entries,
17636 does not link to the calendar and cannot be changed with the S-cursor keys.
17637 So these are more for recording a certain time/date."
17638 (interactive "P")
17639 (let (org-time-was-given org-end-time-was-given time)
17640 (setq time (org-read-date arg 'totime))
17641 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17642 nil nil (list org-end-time-was-given))))
17644 (defvar org-date-ovl (org-make-overlay 1 1))
17645 (org-overlay-put org-date-ovl 'face 'org-warning)
17646 (org-detach-overlay org-date-ovl)
17648 (defvar org-ans1) ; dynamically scoped parameter
17649 (defvar org-ans2) ; dynamically scoped parameter
17651 (defvar org-plain-time-of-day-regexp) ; defined below
17653 (defvar org-read-date-overlay nil)
17654 (defvar org-dcst nil) ; dynamically scoped
17656 (defun org-read-date (&optional with-time to-time from-string prompt
17657 default-time default-input)
17658 "Read a date, possibly a time, and make things smooth for the user.
17659 The prompt will suggest to enter an ISO date, but you can also enter anything
17660 which will at least partially be understood by `parse-time-string'.
17661 Unrecognized parts of the date will default to the current day, month, year,
17662 hour and minute. If this command is called to replace a timestamp at point,
17663 of to enter the second timestamp of a range, the default time is taken from the
17664 existing stamp. For example,
17665 3-2-5 --> 2003-02-05
17666 feb 15 --> currentyear-02-15
17667 sep 12 9 --> 2009-09-12
17668 12:45 --> today 12:45
17669 22 sept 0:34 --> currentyear-09-22 0:34
17670 12 --> currentyear-currentmonth-12
17671 Fri --> nearest Friday (today or later)
17672 etc.
17674 Furthermore you can specify a relative date by giving, as the *first* thing
17675 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17676 change in days weeks, months, years.
17677 With a single plus or minus, the date is relative to today. With a double
17678 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17679 +4d --> four days from today
17680 +4 --> same as above
17681 +2w --> two weeks from today
17682 ++5 --> five days from default date
17684 The function understands only English month and weekday abbreviations,
17685 but this can be configured with the variables `parse-time-months' and
17686 `parse-time-weekdays'.
17688 While prompting, a calendar is popped up - you can also select the
17689 date with the mouse (button 1). The calendar shows a period of three
17690 months. To scroll it to other months, use the keys `>' and `<'.
17691 If you don't like the calendar, turn it off with
17692 \(setq org-read-date-popup-calendar nil)
17694 With optional argument TO-TIME, the date will immediately be converted
17695 to an internal time.
17696 With an optional argument WITH-TIME, the prompt will suggest to also
17697 insert a time. Note that when WITH-TIME is not set, you can still
17698 enter a time, and this function will inform the calling routine about
17699 this change. The calling routine may then choose to change the format
17700 used to insert the time stamp into the buffer to include the time.
17701 With optional argument FROM-STRING, read from this string instead from
17702 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17703 the time/date that is used for everything that is not specified by the
17704 user."
17705 (require 'parse-time)
17706 (let* ((org-time-stamp-rounding-minutes
17707 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17708 (org-dcst org-display-custom-times)
17709 (ct (org-current-time))
17710 (def (or default-time ct))
17711 (defdecode (decode-time def))
17712 (dummy (progn
17713 (when (< (nth 2 defdecode) org-extend-today-until)
17714 (setcar (nthcdr 2 defdecode) -1)
17715 (setcar (nthcdr 1 defdecode) 59)
17716 (setq def (apply 'encode-time defdecode)
17717 defdecode (decode-time def)))))
17718 (calendar-move-hook nil)
17719 (view-diary-entries-initially nil)
17720 (view-calendar-holidays-initially nil)
17721 (timestr (format-time-string
17722 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17723 (prompt (concat (if prompt (concat prompt " ") "")
17724 (format "Date+time [%s]: " timestr)))
17725 ans (org-ans0 "") org-ans1 org-ans2 final)
17727 (cond
17728 (from-string (setq ans from-string))
17729 (org-read-date-popup-calendar
17730 (save-excursion
17731 (save-window-excursion
17732 (calendar)
17733 (calendar-forward-day (- (time-to-days def)
17734 (calendar-absolute-from-gregorian
17735 (calendar-current-date))))
17736 (org-eval-in-calendar nil t)
17737 (let* ((old-map (current-local-map))
17738 (map (copy-keymap calendar-mode-map))
17739 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17740 (org-defkey map (kbd "RET") 'org-calendar-select)
17741 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17742 'org-calendar-select-mouse)
17743 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17744 'org-calendar-select-mouse)
17745 (org-defkey minibuffer-local-map [(meta shift left)]
17746 (lambda () (interactive)
17747 (org-eval-in-calendar '(calendar-backward-month 1))))
17748 (org-defkey minibuffer-local-map [(meta shift right)]
17749 (lambda () (interactive)
17750 (org-eval-in-calendar '(calendar-forward-month 1))))
17751 (org-defkey minibuffer-local-map [(meta shift up)]
17752 (lambda () (interactive)
17753 (org-eval-in-calendar '(calendar-backward-year 1))))
17754 (org-defkey minibuffer-local-map [(meta shift down)]
17755 (lambda () (interactive)
17756 (org-eval-in-calendar '(calendar-forward-year 1))))
17757 (org-defkey minibuffer-local-map [(shift up)]
17758 (lambda () (interactive)
17759 (org-eval-in-calendar '(calendar-backward-week 1))))
17760 (org-defkey minibuffer-local-map [(shift down)]
17761 (lambda () (interactive)
17762 (org-eval-in-calendar '(calendar-forward-week 1))))
17763 (org-defkey minibuffer-local-map [(shift left)]
17764 (lambda () (interactive)
17765 (org-eval-in-calendar '(calendar-backward-day 1))))
17766 (org-defkey minibuffer-local-map [(shift right)]
17767 (lambda () (interactive)
17768 (org-eval-in-calendar '(calendar-forward-day 1))))
17769 (org-defkey minibuffer-local-map ">"
17770 (lambda () (interactive)
17771 (org-eval-in-calendar '(scroll-calendar-left 1))))
17772 (org-defkey minibuffer-local-map "<"
17773 (lambda () (interactive)
17774 (org-eval-in-calendar '(scroll-calendar-right 1))))
17775 (unwind-protect
17776 (progn
17777 (use-local-map map)
17778 (add-hook 'post-command-hook 'org-read-date-display)
17779 (setq org-ans0 (read-string prompt default-input nil nil))
17780 ;; org-ans0: from prompt
17781 ;; org-ans1: from mouse click
17782 ;; org-ans2: from calendar motion
17783 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17784 (remove-hook 'post-command-hook 'org-read-date-display)
17785 (use-local-map old-map)
17786 (when org-read-date-overlay
17787 (org-delete-overlay org-read-date-overlay)
17788 (setq org-read-date-overlay nil)))))))
17790 (t ; Naked prompt only
17791 (unwind-protect
17792 (setq ans (read-string prompt default-input nil timestr))
17793 (when org-read-date-overlay
17794 (org-delete-overlay org-read-date-overlay)
17795 (setq org-read-date-overlay nil)))))
17797 (setq final (org-read-date-analyze ans def defdecode))
17799 (if to-time
17800 (apply 'encode-time final)
17801 (if (and (boundp 'org-time-was-given) org-time-was-given)
17802 (format "%04d-%02d-%02d %02d:%02d"
17803 (nth 5 final) (nth 4 final) (nth 3 final)
17804 (nth 2 final) (nth 1 final))
17805 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17806 (defvar def)
17807 (defvar defdecode)
17808 (defvar with-time)
17809 (defun org-read-date-display ()
17810 "Display the currrent date prompt interpretation in the minibuffer."
17811 (when org-read-date-display-live
17812 (when org-read-date-overlay
17813 (org-delete-overlay org-read-date-overlay))
17814 (let ((p (point)))
17815 (end-of-line 1)
17816 (while (not (equal (buffer-substring
17817 (max (point-min) (- (point) 4)) (point))
17818 " "))
17819 (insert " "))
17820 (goto-char p))
17821 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17822 " " (or org-ans1 org-ans2)))
17823 (org-end-time-was-given nil)
17824 (f (org-read-date-analyze ans def defdecode))
17825 (fmts (if org-dcst
17826 org-time-stamp-custom-formats
17827 org-time-stamp-formats))
17828 (fmt (if (or with-time
17829 (and (boundp 'org-time-was-given) org-time-was-given))
17830 (cdr fmts)
17831 (car fmts)))
17832 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17833 (when (and org-end-time-was-given
17834 (string-match org-plain-time-of-day-regexp txt))
17835 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17836 org-end-time-was-given
17837 (substring txt (match-end 0)))))
17838 (setq org-read-date-overlay
17839 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17840 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17842 (defun org-read-date-analyze (ans def defdecode)
17843 "Analyze the combined answer of the date prompt."
17844 ;; FIXME: cleanup and comment
17845 (let (delta deltan deltaw deltadef year month day
17846 hour minute second wday pm h2 m2 tl wday1)
17848 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17849 (setq ans (replace-match "" t t ans)
17850 deltan (car delta)
17851 deltaw (nth 1 delta)
17852 deltadef (nth 2 delta)))
17854 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17855 (when (string-match
17856 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17857 (setq year (if (match-end 2)
17858 (string-to-number (match-string 2 ans))
17859 (string-to-number (format-time-string "%Y")))
17860 month (string-to-number (match-string 3 ans))
17861 day (string-to-number (match-string 4 ans)))
17862 (if (< year 100) (setq year (+ 2000 year)))
17863 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17864 t nil ans)))
17865 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17866 ;; If there is a time with am/pm, and *no* time without it, we convert
17867 ;; so that matching will be successful.
17868 (loop for i from 1 to 2 do ; twice, for end time as well
17869 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17870 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17871 (setq hour (string-to-number (match-string 1 ans))
17872 minute (if (match-end 3)
17873 (string-to-number (match-string 3 ans))
17875 pm (equal ?p
17876 (string-to-char (downcase (match-string 4 ans)))))
17877 (if (and (= hour 12) (not pm))
17878 (setq hour 0)
17879 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17880 (setq ans (replace-match (format "%02d:%02d" hour minute)
17881 t t ans))))
17883 ;; Check if a time range is given as a duration
17884 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17885 (setq hour (string-to-number (match-string 1 ans))
17886 h2 (+ hour (string-to-number (match-string 3 ans)))
17887 minute (string-to-number (match-string 2 ans))
17888 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17889 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17890 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17892 ;; Check if there is a time range
17893 (when (boundp 'org-end-time-was-given)
17894 (setq org-time-was-given nil)
17895 (when (and (string-match org-plain-time-of-day-regexp ans)
17896 (match-end 8))
17897 (setq org-end-time-was-given (match-string 8 ans))
17898 (setq ans (concat (substring ans 0 (match-beginning 7))
17899 (substring ans (match-end 7))))))
17901 (setq tl (parse-time-string ans)
17902 day (or (nth 3 tl) (nth 3 defdecode))
17903 month (or (nth 4 tl)
17904 (if (and org-read-date-prefer-future
17905 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17906 (1+ (nth 4 defdecode))
17907 (nth 4 defdecode)))
17908 year (or (nth 5 tl)
17909 (if (and org-read-date-prefer-future
17910 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17911 (1+ (nth 5 defdecode))
17912 (nth 5 defdecode)))
17913 hour (or (nth 2 tl) (nth 2 defdecode))
17914 minute (or (nth 1 tl) (nth 1 defdecode))
17915 second (or (nth 0 tl) 0)
17916 wday (nth 6 tl))
17917 (when deltan
17918 (unless deltadef
17919 (let ((now (decode-time (current-time))))
17920 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17921 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17922 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17923 ((equal deltaw "m") (setq month (+ month deltan)))
17924 ((equal deltaw "y") (setq year (+ year deltan)))))
17925 (when (and wday (not (nth 3 tl)))
17926 ;; Weekday was given, but no day, so pick that day in the week
17927 ;; on or after the derived date.
17928 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17929 (unless (equal wday wday1)
17930 (setq day (+ day (% (- wday wday1 -7) 7)))))
17931 (if (and (boundp 'org-time-was-given)
17932 (nth 2 tl))
17933 (setq org-time-was-given t))
17934 (if (< year 100) (setq year (+ 2000 year)))
17935 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17936 (list second minute hour day month year)))
17938 (defvar parse-time-weekdays)
17940 (defun org-read-date-get-relative (s today default)
17941 "Check string S for special relative date string.
17942 TODAY and DEFAULT are internal times, for today and for a default.
17943 Return shift list (N what def-flag)
17944 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17945 N is the number of WHATs to shift.
17946 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17947 the DEFAULT date rather than TODAY."
17948 (when (string-match
17949 (concat
17950 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17951 "\\([0-9]+\\)?"
17952 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17953 "\\([ \t]\\|$\\)") s)
17954 (let* ((dir (if (match-end 1)
17955 (string-to-char (substring (match-string 1 s) -1))
17956 ?+))
17957 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17958 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17959 (what (if (match-end 3) (match-string 3 s) "d"))
17960 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17961 (date (if rel default today))
17962 (wday (nth 6 (decode-time date)))
17963 delta)
17964 (if wday1
17965 (progn
17966 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17967 (if (= dir ?-) (setq delta (- delta 7)))
17968 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17969 (list delta "d" rel))
17970 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17972 (defun org-eval-in-calendar (form &optional keepdate)
17973 "Eval FORM in the calendar window and return to current window.
17974 Also, store the cursor date in variable org-ans2."
17975 (let ((sw (selected-window)))
17976 (select-window (get-buffer-window "*Calendar*"))
17977 (eval form)
17978 (when (and (not keepdate) (calendar-cursor-to-date))
17979 (let* ((date (calendar-cursor-to-date))
17980 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17981 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17982 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17983 (select-window sw)))
17985 ; ;; Update the prompt to show new default date
17986 ; (save-excursion
17987 ; (goto-char (point-min))
17988 ; (when (and org-ans2
17989 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17990 ; (get-text-property (match-end 0) 'field))
17991 ; (let ((inhibit-read-only t))
17992 ; (replace-match (concat "[" org-ans2 "]") t t)
17993 ; (add-text-properties (point-min) (1+ (match-end 0))
17994 ; (text-properties-at (1+ (point-min)))))))))
17996 (defun org-calendar-select ()
17997 "Return to `org-read-date' with the date currently selected.
17998 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17999 (interactive)
18000 (when (calendar-cursor-to-date)
18001 (let* ((date (calendar-cursor-to-date))
18002 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18003 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18004 (if (active-minibuffer-window) (exit-minibuffer))))
18006 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18007 "Insert a date stamp for the date given by the internal TIME.
18008 WITH-HM means, use the stamp format that includes the time of the day.
18009 INACTIVE means use square brackets instead of angular ones, so that the
18010 stamp will not contribute to the agenda.
18011 PRE and POST are optional strings to be inserted before and after the
18012 stamp.
18013 The command returns the inserted time stamp."
18014 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18015 stamp)
18016 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18017 (insert-before-markers (or pre ""))
18018 (insert-before-markers (setq stamp (format-time-string fmt time)))
18019 (when (listp extra)
18020 (setq extra (car extra))
18021 (if (and (stringp extra)
18022 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18023 (setq extra (format "-%02d:%02d"
18024 (string-to-number (match-string 1 extra))
18025 (string-to-number (match-string 2 extra))))
18026 (setq extra nil)))
18027 (when extra
18028 (backward-char 1)
18029 (insert-before-markers extra)
18030 (forward-char 1))
18031 (insert-before-markers (or post ""))
18032 stamp))
18034 (defun org-toggle-time-stamp-overlays ()
18035 "Toggle the use of custom time stamp formats."
18036 (interactive)
18037 (setq org-display-custom-times (not org-display-custom-times))
18038 (unless org-display-custom-times
18039 (let ((p (point-min)) (bmp (buffer-modified-p)))
18040 (while (setq p (next-single-property-change p 'display))
18041 (if (and (get-text-property p 'display)
18042 (eq (get-text-property p 'face) 'org-date))
18043 (remove-text-properties
18044 p (setq p (next-single-property-change p 'display))
18045 '(display t))))
18046 (set-buffer-modified-p bmp)))
18047 (if (featurep 'xemacs)
18048 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18049 (org-restart-font-lock)
18050 (setq org-table-may-need-update t)
18051 (if org-display-custom-times
18052 (message "Time stamps are overlayed with custom format")
18053 (message "Time stamp overlays removed")))
18055 (defun org-display-custom-time (beg end)
18056 "Overlay modified time stamp format over timestamp between BED and END."
18057 (let* ((ts (buffer-substring beg end))
18058 t1 w1 with-hm tf time str w2 (off 0))
18059 (save-match-data
18060 (setq t1 (org-parse-time-string ts t))
18061 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
18062 (setq off (- (match-end 0) (match-beginning 0)))))
18063 (setq end (- end off))
18064 (setq w1 (- end beg)
18065 with-hm (and (nth 1 t1) (nth 2 t1))
18066 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18067 time (org-fix-decoded-time t1)
18068 str (org-add-props
18069 (format-time-string
18070 (substring tf 1 -1) (apply 'encode-time time))
18071 nil 'mouse-face 'highlight)
18072 w2 (length str))
18073 (if (not (= w2 w1))
18074 (add-text-properties (1+ beg) (+ 2 beg)
18075 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18076 (if (featurep 'xemacs)
18077 (progn
18078 (put-text-property beg end 'invisible t)
18079 (put-text-property beg end 'end-glyph (make-glyph str)))
18080 (put-text-property beg end 'display str))))
18082 (defun org-translate-time (string)
18083 "Translate all timestamps in STRING to custom format.
18084 But do this only if the variable `org-display-custom-times' is set."
18085 (when org-display-custom-times
18086 (save-match-data
18087 (let* ((start 0)
18088 (re org-ts-regexp-both)
18089 t1 with-hm inactive tf time str beg end)
18090 (while (setq start (string-match re string start))
18091 (setq beg (match-beginning 0)
18092 end (match-end 0)
18093 t1 (save-match-data
18094 (org-parse-time-string (substring string beg end) t))
18095 with-hm (and (nth 1 t1) (nth 2 t1))
18096 inactive (equal (substring string beg (1+ beg)) "[")
18097 tf (funcall (if with-hm 'cdr 'car)
18098 org-time-stamp-custom-formats)
18099 time (org-fix-decoded-time t1)
18100 str (format-time-string
18101 (concat
18102 (if inactive "[" "<") (substring tf 1 -1)
18103 (if inactive "]" ">"))
18104 (apply 'encode-time time))
18105 string (replace-match str t t string)
18106 start (+ start (length str)))))))
18107 string)
18109 (defun org-fix-decoded-time (time)
18110 "Set 0 instead of nil for the first 6 elements of time.
18111 Don't touch the rest."
18112 (let ((n 0))
18113 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18115 (defun org-days-to-time (timestamp-string)
18116 "Difference between TIMESTAMP-STRING and now in days."
18117 (- (time-to-days (org-time-string-to-time timestamp-string))
18118 (time-to-days (current-time))))
18120 (defun org-deadline-close (timestamp-string &optional ndays)
18121 "Is the time in TIMESTAMP-STRING close to the current date?"
18122 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18123 (and (< (org-days-to-time timestamp-string) ndays)
18124 (not (org-entry-is-done-p))))
18126 (defun org-get-wdays (ts)
18127 "Get the deadline lead time appropriate for timestring TS."
18128 (cond
18129 ((<= org-deadline-warning-days 0)
18130 ;; 0 or negative, enforce this value no matter what
18131 (- org-deadline-warning-days))
18132 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18133 ;; lead time is specified.
18134 (floor (* (string-to-number (match-string 1 ts))
18135 (cdr (assoc (match-string 2 ts)
18136 '(("d" . 1) ("w" . 7)
18137 ("m" . 30.4) ("y" . 365.25)))))))
18138 ;; go for the default.
18139 (t org-deadline-warning-days)))
18141 (defun org-calendar-select-mouse (ev)
18142 "Return to `org-read-date' with the date currently selected.
18143 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18144 (interactive "e")
18145 (mouse-set-point ev)
18146 (when (calendar-cursor-to-date)
18147 (let* ((date (calendar-cursor-to-date))
18148 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18149 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18150 (if (active-minibuffer-window) (exit-minibuffer))))
18152 (defun org-check-deadlines (ndays)
18153 "Check if there are any deadlines due or past due.
18154 A deadline is considered due if it happens within `org-deadline-warning-days'
18155 days from today's date. If the deadline appears in an entry marked DONE,
18156 it is not shown. The prefix arg NDAYS can be used to test that many
18157 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18158 (interactive "P")
18159 (let* ((org-warn-days
18160 (cond
18161 ((equal ndays '(4)) 100000)
18162 (ndays (prefix-numeric-value ndays))
18163 (t (abs org-deadline-warning-days))))
18164 (case-fold-search nil)
18165 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18166 (callback
18167 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18169 (message "%d deadlines past-due or due within %d days"
18170 (org-occur regexp nil callback)
18171 org-warn-days)))
18173 (defun org-check-before-date (date)
18174 "Check if there are deadlines or scheduled entries before DATE."
18175 (interactive (list (org-read-date)))
18176 (let ((case-fold-search nil)
18177 (regexp (concat "\\<\\(" org-deadline-string
18178 "\\|" org-scheduled-string
18179 "\\) *<\\([^>]+\\)>"))
18180 (callback
18181 (lambda () (time-less-p
18182 (org-time-string-to-time (match-string 2))
18183 (org-time-string-to-time date)))))
18184 (message "%d entries before %s"
18185 (org-occur regexp nil callback) date)))
18187 (defun org-evaluate-time-range (&optional to-buffer)
18188 "Evaluate a time range by computing the difference between start and end.
18189 Normally the result is just printed in the echo area, but with prefix arg
18190 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18191 If the time range is actually in a table, the result is inserted into the
18192 next column.
18193 For time difference computation, a year is assumed to be exactly 365
18194 days in order to avoid rounding problems."
18195 (interactive "P")
18197 (org-clock-update-time-maybe)
18198 (save-excursion
18199 (unless (org-at-date-range-p t)
18200 (goto-char (point-at-bol))
18201 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18202 (if (not (org-at-date-range-p t))
18203 (error "Not at a time-stamp range, and none found in current line")))
18204 (let* ((ts1 (match-string 1))
18205 (ts2 (match-string 2))
18206 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18207 (match-end (match-end 0))
18208 (time1 (org-time-string-to-time ts1))
18209 (time2 (org-time-string-to-time ts2))
18210 (t1 (time-to-seconds time1))
18211 (t2 (time-to-seconds time2))
18212 (diff (abs (- t2 t1)))
18213 (negative (< (- t2 t1) 0))
18214 ;; (ys (floor (* 365 24 60 60)))
18215 (ds (* 24 60 60))
18216 (hs (* 60 60))
18217 (fy "%dy %dd %02d:%02d")
18218 (fy1 "%dy %dd")
18219 (fd "%dd %02d:%02d")
18220 (fd1 "%dd")
18221 (fh "%02d:%02d")
18222 y d h m align)
18223 (if havetime
18224 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18226 d (floor (/ diff ds)) diff (mod diff ds)
18227 h (floor (/ diff hs)) diff (mod diff hs)
18228 m (floor (/ diff 60)))
18229 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18231 d (floor (+ (/ diff ds) 0.5))
18232 h 0 m 0))
18233 (if (not to-buffer)
18234 (message "%s" (org-make-tdiff-string y d h m))
18235 (if (org-at-table-p)
18236 (progn
18237 (goto-char match-end)
18238 (setq align t)
18239 (and (looking-at " *|") (goto-char (match-end 0))))
18240 (goto-char match-end))
18241 (if (looking-at
18242 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18243 (replace-match ""))
18244 (if negative (insert " -"))
18245 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18246 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18247 (insert " " (format fh h m))))
18248 (if align (org-table-align))
18249 (message "Time difference inserted")))))
18251 (defun org-make-tdiff-string (y d h m)
18252 (let ((fmt "")
18253 (l nil))
18254 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18255 l (push y l)))
18256 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18257 l (push d l)))
18258 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18259 l (push h l)))
18260 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18261 l (push m l)))
18262 (apply 'format fmt (nreverse l))))
18264 (defun org-time-string-to-time (s)
18265 (apply 'encode-time (org-parse-time-string s)))
18267 (defun org-time-string-to-absolute (s &optional daynr prefer)
18268 "Convert a time stamp to an absolute day number.
18269 If there is a specifyer for a cyclic time stamp, get the closest date to
18270 DAYNR."
18271 (cond
18272 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18273 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18274 daynr
18275 (+ daynr 1000)))
18276 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18277 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18278 (time-to-days (current-time))) (match-string 0 s)
18279 prefer))
18280 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18282 (defun org-time-from-absolute (d)
18283 "Return the time corresponding to date D.
18284 D may be an absolute day number, or a calendar-type list (month day year)."
18285 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18286 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18288 (defun org-calendar-holiday ()
18289 "List of holidays, for Diary display in Org-mode."
18290 (require 'holidays)
18291 (let ((hl (funcall
18292 (if (fboundp 'calendar-check-holidays)
18293 'calendar-check-holidays 'check-calendar-holidays) date)))
18294 (if hl (mapconcat 'identity hl "; "))))
18296 (defun org-diary-sexp-entry (sexp entry date)
18297 "Process a SEXP diary ENTRY for DATE."
18298 (require 'diary-lib)
18299 (let ((result (if calendar-debug-sexp
18300 (let ((stack-trace-on-error t))
18301 (eval (car (read-from-string sexp))))
18302 (condition-case nil
18303 (eval (car (read-from-string sexp)))
18304 (error
18305 (beep)
18306 (message "Bad sexp at line %d in %s: %s"
18307 (org-current-line)
18308 (buffer-file-name) sexp)
18309 (sleep-for 2))))))
18310 (cond ((stringp result) result)
18311 ((and (consp result)
18312 (stringp (cdr result))) (cdr result))
18313 (result entry)
18314 (t nil))))
18316 (defun org-diary-to-ical-string (frombuf)
18317 "Get iCalendar entries from diary entries in buffer FROMBUF.
18318 This uses the icalendar.el library."
18319 (let* ((tmpdir (if (featurep 'xemacs)
18320 (temp-directory)
18321 temporary-file-directory))
18322 (tmpfile (make-temp-name
18323 (expand-file-name "orgics" tmpdir)))
18324 buf rtn b e)
18325 (save-excursion
18326 (set-buffer frombuf)
18327 (icalendar-export-region (point-min) (point-max) tmpfile)
18328 (setq buf (find-buffer-visiting tmpfile))
18329 (set-buffer buf)
18330 (goto-char (point-min))
18331 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18332 (setq b (match-beginning 0)))
18333 (goto-char (point-max))
18334 (if (re-search-backward "^END:VEVENT" nil t)
18335 (setq e (match-end 0)))
18336 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18337 (kill-buffer buf)
18338 (kill-buffer frombuf)
18339 (delete-file tmpfile)
18340 rtn))
18342 (defun org-closest-date (start current change prefer)
18343 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18344 When PREFER is `past' return a date that is either CURRENT or past.
18345 When PREFER is `future', return a date that is either CURRENT or future."
18346 ;; Make the proper lists from the dates
18347 (catch 'exit
18348 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18349 dn dw sday cday n1 n2
18350 d m y y1 y2 date1 date2 nmonths nm ny m2)
18352 (setq start (org-date-to-gregorian start)
18353 current (org-date-to-gregorian
18354 (if org-agenda-repeating-timestamp-show-all
18355 current
18356 (time-to-days (current-time))))
18357 sday (calendar-absolute-from-gregorian start)
18358 cday (calendar-absolute-from-gregorian current))
18360 (if (<= cday sday) (throw 'exit sday))
18362 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18363 (setq dn (string-to-number (match-string 1 change))
18364 dw (cdr (assoc (match-string 2 change) a1)))
18365 (error "Invalid change specifyer: %s" change))
18366 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18367 (cond
18368 ((eq dw 'day)
18369 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18370 n2 (+ n1 dn)))
18371 ((eq dw 'year)
18372 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18373 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18374 (setq date1 (list m d y1)
18375 n1 (calendar-absolute-from-gregorian date1)
18376 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18377 n2 (calendar-absolute-from-gregorian date2)))
18378 ((eq dw 'month)
18379 ;; approx number of month between the tow dates
18380 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18381 ;; How often does dn fit in there?
18382 (setq d (nth 1 start) m (car start) y (nth 2 start)
18383 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18384 m (+ m nm)
18385 ny (floor (/ m 12))
18386 y (+ y ny)
18387 m (- m (* ny 12)))
18388 (while (> m 12) (setq m (- m 12) y (1+ y)))
18389 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18390 (setq m2 (+ m dn) y2 y)
18391 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18392 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18393 (while (< n2 cday)
18394 (setq n1 n2 m m2 y y2)
18395 (setq m2 (+ m dn) y2 y)
18396 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18397 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18399 (if org-agenda-repeating-timestamp-show-all
18400 (cond
18401 ((eq prefer 'past) n1)
18402 ((eq prefer 'future) (if (= cday n1) n1 n2))
18403 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18404 (cond
18405 ((eq prefer 'past) n1)
18406 ((eq prefer 'future) (if (= cday n1) n1 n2))
18407 (t (if (= cday n1) n1 n2)))))))
18409 (defun org-date-to-gregorian (date)
18410 "Turn any specification of DATE into a gregorian date for the calendar."
18411 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18412 ((and (listp date) (= (length date) 3)) date)
18413 ((stringp date)
18414 (setq date (org-parse-time-string date))
18415 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18416 ((listp date)
18417 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18419 (defun org-parse-time-string (s &optional nodefault)
18420 "Parse the standard Org-mode time string.
18421 This should be a lot faster than the normal `parse-time-string'.
18422 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18423 hour and minute fields will be nil if not given."
18424 (if (string-match org-ts-regexp0 s)
18425 (list 0
18426 (if (or (match-beginning 8) (not nodefault))
18427 (string-to-number (or (match-string 8 s) "0")))
18428 (if (or (match-beginning 7) (not nodefault))
18429 (string-to-number (or (match-string 7 s) "0")))
18430 (string-to-number (match-string 4 s))
18431 (string-to-number (match-string 3 s))
18432 (string-to-number (match-string 2 s))
18433 nil nil nil)
18434 (make-list 9 0)))
18436 (defun org-timestamp-up (&optional arg)
18437 "Increase the date item at the cursor by one.
18438 If the cursor is on the year, change the year. If it is on the month or
18439 the day, change that.
18440 With prefix ARG, change by that many units."
18441 (interactive "p")
18442 (org-timestamp-change (prefix-numeric-value arg)))
18444 (defun org-timestamp-down (&optional arg)
18445 "Decrease the date item at the cursor by one.
18446 If the cursor is on the year, change the year. If it is on the month or
18447 the day, change that.
18448 With prefix ARG, change by that many units."
18449 (interactive "p")
18450 (org-timestamp-change (- (prefix-numeric-value arg))))
18452 (defun org-timestamp-up-day (&optional arg)
18453 "Increase the date in the time stamp by one day.
18454 With prefix ARG, change that many days."
18455 (interactive "p")
18456 (if (and (not (org-at-timestamp-p t))
18457 (org-on-heading-p))
18458 (org-todo 'up)
18459 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18461 (defun org-timestamp-down-day (&optional arg)
18462 "Decrease the date in the time stamp by one day.
18463 With prefix ARG, change that many days."
18464 (interactive "p")
18465 (if (and (not (org-at-timestamp-p t))
18466 (org-on-heading-p))
18467 (org-todo 'down)
18468 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18470 (defsubst org-pos-in-match-range (pos n)
18471 (and (match-beginning n)
18472 (<= (match-beginning n) pos)
18473 (>= (match-end n) pos)))
18475 (defun org-at-timestamp-p (&optional inactive-ok)
18476 "Determine if the cursor is in or at a timestamp."
18477 (interactive)
18478 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18479 (pos (point))
18480 (ans (or (looking-at tsr)
18481 (save-excursion
18482 (skip-chars-backward "^[<\n\r\t")
18483 (if (> (point) (point-min)) (backward-char 1))
18484 (and (looking-at tsr)
18485 (> (- (match-end 0) pos) -1))))))
18486 (and ans
18487 (boundp 'org-ts-what)
18488 (setq org-ts-what
18489 (cond
18490 ((= pos (match-beginning 0)) 'bracket)
18491 ((= pos (1- (match-end 0))) 'bracket)
18492 ((org-pos-in-match-range pos 2) 'year)
18493 ((org-pos-in-match-range pos 3) 'month)
18494 ((org-pos-in-match-range pos 7) 'hour)
18495 ((org-pos-in-match-range pos 8) 'minute)
18496 ((or (org-pos-in-match-range pos 4)
18497 (org-pos-in-match-range pos 5)) 'day)
18498 ((and (> pos (or (match-end 8) (match-end 5)))
18499 (< pos (match-end 0)))
18500 (- pos (or (match-end 8) (match-end 5))))
18501 (t 'day))))
18502 ans))
18504 (defun org-toggle-timestamp-type ()
18506 (interactive)
18507 (when (org-at-timestamp-p t)
18508 (save-excursion
18509 (goto-char (match-beginning 0))
18510 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18511 (goto-char (1- (match-end 0)))
18512 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18513 (message "Timestamp is now %sactive"
18514 (if (equal (char-before) ?>) "in" ""))))
18516 (defun org-timestamp-change (n &optional what)
18517 "Change the date in the time stamp at point.
18518 The date will be changed by N times WHAT. WHAT can be `day', `month',
18519 `year', `minute', `second'. If WHAT is not given, the cursor position
18520 in the timestamp determines what will be changed."
18521 (let ((pos (point))
18522 with-hm inactive
18523 org-ts-what
18524 extra
18525 ts time time0)
18526 (if (not (org-at-timestamp-p t))
18527 (error "Not at a timestamp"))
18528 (if (and (not what) (eq org-ts-what 'bracket))
18529 (org-toggle-timestamp-type)
18530 (if (and (not what) (not (eq org-ts-what 'day))
18531 org-display-custom-times
18532 (get-text-property (point) 'display)
18533 (not (get-text-property (1- (point)) 'display)))
18534 (setq org-ts-what 'day))
18535 (setq org-ts-what (or what org-ts-what)
18536 inactive (= (char-after (match-beginning 0)) ?\[)
18537 ts (match-string 0))
18538 (replace-match "")
18539 (if (string-match
18540 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18542 (setq extra (match-string 1 ts)))
18543 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18544 (setq with-hm t))
18545 (setq time0 (org-parse-time-string ts))
18546 (setq time
18547 (encode-time (or (car time0) 0)
18548 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18549 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18550 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18551 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18552 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18553 (nthcdr 6 time0)))
18554 (when (integerp org-ts-what)
18555 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18556 (if (eq what 'calendar)
18557 (let ((cal-date (org-get-date-from-calendar)))
18558 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18559 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18560 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18561 (setcar time0 (or (car time0) 0))
18562 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18563 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18564 (setq time (apply 'encode-time time0))))
18565 (setq org-last-changed-timestamp
18566 (org-insert-time-stamp time with-hm inactive nil nil extra))
18567 (org-clock-update-time-maybe)
18568 (goto-char pos)
18569 ;; Try to recenter the calendar window, if any
18570 (if (and org-calendar-follow-timestamp-change
18571 (get-buffer-window "*Calendar*" t)
18572 (memq org-ts-what '(day month year)))
18573 (org-recenter-calendar (time-to-days time))))))
18575 ;; FIXME: does not yet work for lead times
18576 (defun org-modify-ts-extra (s pos n)
18577 "Change the different parts of the lead-time and repeat fields in timestamp."
18578 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18579 ng h m new)
18580 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18581 (cond
18582 ((or (org-pos-in-match-range pos 2)
18583 (org-pos-in-match-range pos 3))
18584 (setq m (string-to-number (match-string 3 s))
18585 h (string-to-number (match-string 2 s)))
18586 (if (org-pos-in-match-range pos 2)
18587 (setq h (+ h n))
18588 (setq m (+ m n)))
18589 (if (< m 0) (setq m (+ m 60) h (1- h)))
18590 (if (> m 59) (setq m (- m 60) h (1+ h)))
18591 (setq h (min 24 (max 0 h)))
18592 (setq ng 1 new (format "-%02d:%02d" h m)))
18593 ((org-pos-in-match-range pos 6)
18594 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18595 ((org-pos-in-match-range pos 5)
18596 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18598 (when ng
18599 (setq s (concat
18600 (substring s 0 (match-beginning ng))
18602 (substring s (match-end ng))))))
18605 (defun org-recenter-calendar (date)
18606 "If the calendar is visible, recenter it to DATE."
18607 (let* ((win (selected-window))
18608 (cwin (get-buffer-window "*Calendar*" t))
18609 (calendar-move-hook nil))
18610 (when cwin
18611 (select-window cwin)
18612 (calendar-goto-date (if (listp date) date
18613 (calendar-gregorian-from-absolute date)))
18614 (select-window win))))
18616 (defun org-goto-calendar (&optional arg)
18617 "Go to the Emacs calendar at the current date.
18618 If there is a time stamp in the current line, go to that date.
18619 A prefix ARG can be used to force the current date."
18620 (interactive "P")
18621 (let ((tsr org-ts-regexp) diff
18622 (calendar-move-hook nil)
18623 (view-calendar-holidays-initially nil)
18624 (view-diary-entries-initially nil))
18625 (if (or (org-at-timestamp-p)
18626 (save-excursion
18627 (beginning-of-line 1)
18628 (looking-at (concat ".*" tsr))))
18629 (let ((d1 (time-to-days (current-time)))
18630 (d2 (time-to-days
18631 (org-time-string-to-time (match-string 1)))))
18632 (setq diff (- d2 d1))))
18633 (calendar)
18634 (calendar-goto-today)
18635 (if (and diff (not arg)) (calendar-forward-day diff))))
18637 (defun org-get-date-from-calendar ()
18638 "Return a list (month day year) of date at point in calendar."
18639 (with-current-buffer "*Calendar*"
18640 (save-match-data
18641 (calendar-cursor-to-date))))
18643 (defun org-date-from-calendar ()
18644 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18645 If there is already a time stamp at the cursor position, update it."
18646 (interactive)
18647 (if (org-at-timestamp-p t)
18648 (org-timestamp-change 0 'calendar)
18649 (let ((cal-date (org-get-date-from-calendar)))
18650 (org-insert-time-stamp
18651 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18653 (defvar appt-time-msg-list)
18655 ;;;###autoload
18656 (defun org-agenda-to-appt (&optional refresh filter)
18657 "Activate appointments found in `org-agenda-files'.
18658 With a \\[universal-argument] prefix, refresh the list of
18659 appointements.
18661 If FILTER is t, interactively prompt the user for a regular
18662 expression, and filter out entries that don't match it.
18664 If FILTER is a string, use this string as a regular expression
18665 for filtering entries out.
18667 FILTER can also be an alist with the car of each cell being
18668 either 'headline or 'category. For example:
18670 '((headline \"IMPORTANT\")
18671 (category \"Work\"))
18673 will only add headlines containing IMPORTANT or headlines
18674 belonging to the \"Work\" category."
18675 (interactive "P")
18676 (require 'calendar)
18677 (if refresh (setq appt-time-msg-list nil))
18678 (if (eq filter t)
18679 (setq filter (read-from-minibuffer "Regexp filter: ")))
18680 (let* ((cnt 0) ; count added events
18681 (org-agenda-new-buffers nil)
18682 (org-deadline-warning-days 0)
18683 (today (org-date-to-gregorian
18684 (time-to-days (current-time))))
18685 (files (org-agenda-files)) entries file)
18686 ;; Get all entries which may contain an appt
18687 (while (setq file (pop files))
18688 (setq entries
18689 (append entries
18690 (org-agenda-get-day-entries
18691 file today :timestamp :scheduled :deadline))))
18692 (setq entries (delq nil entries))
18693 ;; Map thru entries and find if we should filter them out
18694 (mapc
18695 (lambda(x)
18696 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18697 (cat (get-text-property 1 'org-category x))
18698 (tod (get-text-property 1 'time-of-day x))
18699 (ok (or (null filter)
18700 (and (stringp filter) (string-match filter evt))
18701 (and (listp filter)
18702 (or (string-match
18703 (cadr (assoc 'category filter)) cat)
18704 (string-match
18705 (cadr (assoc 'headline filter)) evt))))))
18706 ;; FIXME: Shall we remove text-properties for the appt text?
18707 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18708 (when (and ok tod)
18709 (setq tod (number-to-string tod)
18710 tod (when (string-match
18711 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18712 (concat (match-string 1 tod) ":"
18713 (match-string 2 tod))))
18714 (appt-add tod evt)
18715 (setq cnt (1+ cnt))))) entries)
18716 (org-release-buffers org-agenda-new-buffers)
18717 (if (eq cnt 0)
18718 (message "No event to add")
18719 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18721 ;;; The clock for measuring work time.
18723 (defvar org-mode-line-string "")
18724 (put 'org-mode-line-string 'risky-local-variable t)
18726 (defvar org-mode-line-timer nil)
18727 (defvar org-clock-heading "")
18728 (defvar org-clock-start-time "")
18730 (defun org-update-mode-line ()
18731 (let* ((delta (- (time-to-seconds (current-time))
18732 (time-to-seconds org-clock-start-time)))
18733 (h (floor delta 3600))
18734 (m (floor (- delta (* 3600 h)) 60)))
18735 (setq org-mode-line-string
18736 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18737 'help-echo "Org-mode clock is running"))
18738 (force-mode-line-update)))
18740 (defvar org-clock-marker (make-marker)
18741 "Marker recording the last clock-in.")
18742 (defvar org-clock-mode-line-entry nil
18743 "Information for the modeline about the running clock.")
18745 (defun org-clock-in ()
18746 "Start the clock on the current item.
18747 If necessary, clock-out of the currently active clock."
18748 (interactive)
18749 (org-clock-out t)
18750 (let (ts)
18751 (save-excursion
18752 (org-back-to-heading t)
18753 (when (and org-clock-in-switch-to-state
18754 (not (looking-at (concat outline-regexp "[ \t]*"
18755 org-clock-in-switch-to-state
18756 "\\>"))))
18757 (org-todo org-clock-in-switch-to-state))
18758 (if (and org-clock-heading-function
18759 (functionp org-clock-heading-function))
18760 (setq org-clock-heading (funcall org-clock-heading-function))
18761 (if (looking-at org-complex-heading-regexp)
18762 (setq org-clock-heading (match-string 4))
18763 (setq org-clock-heading "???")))
18764 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18765 (org-clock-find-position)
18767 (insert "\n") (backward-char 1)
18768 (indent-relative)
18769 (insert org-clock-string " ")
18770 (setq org-clock-start-time (current-time))
18771 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18772 (move-marker org-clock-marker (point) (buffer-base-buffer))
18773 (or global-mode-string (setq global-mode-string '("")))
18774 (or (memq 'org-mode-line-string global-mode-string)
18775 (setq global-mode-string
18776 (append global-mode-string '(org-mode-line-string))))
18777 (org-update-mode-line)
18778 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18779 (message "Clock started at %s" ts))))
18781 (defun org-clock-find-position ()
18782 "Find the location where the next clock line should be inserted."
18783 (org-back-to-heading t)
18784 (catch 'exit
18785 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18786 (re (concat "^[ \t]*" org-clock-string))
18787 (cnt 0)
18788 first last)
18789 (goto-char beg)
18790 (when (eobp) (newline) (setq end (max (point) end)))
18791 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18792 ;; we seem to have a CLOCK drawer, so go there.
18793 (beginning-of-line 2)
18794 (throw 'exit t))
18795 ;; Lets count the CLOCK lines
18796 (goto-char beg)
18797 (while (re-search-forward re end t)
18798 (setq first (or first (match-beginning 0))
18799 last (match-beginning 0)
18800 cnt (1+ cnt)))
18801 (when (and (integerp org-clock-into-drawer)
18802 (>= (1+ cnt) org-clock-into-drawer))
18803 ;; Wrap current entries into a new drawer
18804 (goto-char last)
18805 (beginning-of-line 2)
18806 (if (org-at-item-p) (org-end-of-item))
18807 (insert ":END:\n")
18808 (beginning-of-line 0)
18809 (org-indent-line-function)
18810 (goto-char first)
18811 (insert ":CLOCK:\n")
18812 (beginning-of-line 0)
18813 (org-indent-line-function)
18814 (org-flag-drawer t)
18815 (beginning-of-line 2)
18816 (throw 'exit nil))
18818 (goto-char beg)
18819 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18820 (not (equal (match-string 1) org-clock-string)))
18821 ;; Planning info, skip to after it
18822 (beginning-of-line 2)
18823 (or (bolp) (newline)))
18824 (when (eq t org-clock-into-drawer)
18825 (insert ":CLOCK:\n:END:\n")
18826 (beginning-of-line -1)
18827 (org-indent-line-function)
18828 (org-flag-drawer t)
18829 (beginning-of-line 2)
18830 (org-indent-line-function)))))
18832 (defun org-clock-out (&optional fail-quietly)
18833 "Stop the currently running clock.
18834 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18835 (interactive)
18836 (catch 'exit
18837 (if (not (marker-buffer org-clock-marker))
18838 (if fail-quietly (throw 'exit t) (error "No active clock")))
18839 (let (ts te s h m)
18840 (save-excursion
18841 (set-buffer (marker-buffer org-clock-marker))
18842 (goto-char org-clock-marker)
18843 (beginning-of-line 1)
18844 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18845 (equal (match-string 1) org-clock-string))
18846 (setq ts (match-string 2))
18847 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18848 (goto-char (match-end 0))
18849 (delete-region (point) (point-at-eol))
18850 (insert "--")
18851 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18852 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18853 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18854 h (floor (/ s 3600))
18855 s (- s (* 3600 h))
18856 m (floor (/ s 60))
18857 s (- s (* 60 s)))
18858 (insert " => " (format "%2d:%02d" h m))
18859 (move-marker org-clock-marker nil)
18860 (when org-log-note-clock-out
18861 (org-add-log-maybe 'clock-out))
18862 (when org-mode-line-timer
18863 (cancel-timer org-mode-line-timer)
18864 (setq org-mode-line-timer nil))
18865 (setq global-mode-string
18866 (delq 'org-mode-line-string global-mode-string))
18867 (force-mode-line-update)
18868 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18870 (defun org-clock-cancel ()
18871 "Cancel the running clock be removing the start timestamp."
18872 (interactive)
18873 (if (not (marker-buffer org-clock-marker))
18874 (error "No active clock"))
18875 (save-excursion
18876 (set-buffer (marker-buffer org-clock-marker))
18877 (goto-char org-clock-marker)
18878 (delete-region (1- (point-at-bol)) (point-at-eol)))
18879 (setq global-mode-string
18880 (delq 'org-mode-line-string global-mode-string))
18881 (force-mode-line-update)
18882 (message "Clock canceled"))
18884 (defun org-clock-goto (&optional delete-windows)
18885 "Go to the currently clocked-in entry."
18886 (interactive "P")
18887 (if (not (marker-buffer org-clock-marker))
18888 (error "No active clock"))
18889 (switch-to-buffer-other-window
18890 (marker-buffer org-clock-marker))
18891 (if delete-windows (delete-other-windows))
18892 (goto-char org-clock-marker)
18893 (org-show-entry)
18894 (org-back-to-heading)
18895 (recenter))
18897 (defvar org-clock-file-total-minutes nil
18898 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18899 (make-variable-buffer-local 'org-clock-file-total-minutes)
18901 (defun org-clock-sum (&optional tstart tend)
18902 "Sum the times for each subtree.
18903 Puts the resulting times in minutes as a text property on each headline."
18904 (interactive)
18905 (let* ((bmp (buffer-modified-p))
18906 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18907 org-clock-string
18908 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18909 (lmax 30)
18910 (ltimes (make-vector lmax 0))
18911 (t1 0)
18912 (level 0)
18913 ts te dt
18914 time)
18915 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18916 (save-excursion
18917 (goto-char (point-max))
18918 (while (re-search-backward re nil t)
18919 (cond
18920 ((match-end 2)
18921 ;; Two time stamps
18922 (setq ts (match-string 2)
18923 te (match-string 3)
18924 ts (time-to-seconds
18925 (apply 'encode-time (org-parse-time-string ts)))
18926 te (time-to-seconds
18927 (apply 'encode-time (org-parse-time-string te)))
18928 ts (if tstart (max ts tstart) ts)
18929 te (if tend (min te tend) te)
18930 dt (- te ts)
18931 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18932 ((match-end 4)
18933 ;; A naket time
18934 (setq t1 (+ t1 (string-to-number (match-string 5))
18935 (* 60 (string-to-number (match-string 4))))))
18936 (t ;; A headline
18937 (setq level (- (match-end 1) (match-beginning 1)))
18938 (when (or (> t1 0) (> (aref ltimes level) 0))
18939 (loop for l from 0 to level do
18940 (aset ltimes l (+ (aref ltimes l) t1)))
18941 (setq t1 0 time (aref ltimes level))
18942 (loop for l from level to (1- lmax) do
18943 (aset ltimes l 0))
18944 (goto-char (match-beginning 0))
18945 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18946 (setq org-clock-file-total-minutes (aref ltimes 0)))
18947 (set-buffer-modified-p bmp)))
18949 (defun org-clock-display (&optional total-only)
18950 "Show subtree times in the entire buffer.
18951 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18952 in the echo area."
18953 (interactive)
18954 (org-remove-clock-overlays)
18955 (let (time h m p)
18956 (org-clock-sum)
18957 (unless total-only
18958 (save-excursion
18959 (goto-char (point-min))
18960 (while (or (and (equal (setq p (point)) (point-min))
18961 (get-text-property p :org-clock-minutes))
18962 (setq p (next-single-property-change
18963 (point) :org-clock-minutes)))
18964 (goto-char p)
18965 (when (setq time (get-text-property p :org-clock-minutes))
18966 (org-put-clock-overlay time (funcall outline-level))))
18967 (setq h (/ org-clock-file-total-minutes 60)
18968 m (- org-clock-file-total-minutes (* 60 h)))
18969 ;; Arrange to remove the overlays upon next change.
18970 (when org-remove-highlights-with-change
18971 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18972 nil 'local))))
18973 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18975 (defvar org-clock-overlays nil)
18976 (make-variable-buffer-local 'org-clock-overlays)
18978 (defun org-put-clock-overlay (time &optional level)
18979 "Put an overlays on the current line, displaying TIME.
18980 If LEVEL is given, prefix time with a corresponding number of stars.
18981 This creates a new overlay and stores it in `org-clock-overlays', so that it
18982 will be easy to remove."
18983 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18984 (l (if level (org-get-legal-level level 0) 0))
18985 (off 0)
18986 ov tx)
18987 (move-to-column c)
18988 (unless (eolp) (skip-chars-backward "^ \t"))
18989 (skip-chars-backward " \t")
18990 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18991 tx (concat (buffer-substring (1- (point)) (point))
18992 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18993 (org-add-props (format "%s %2d:%02d%s"
18994 (make-string l ?*) h m
18995 (make-string (- 16 l) ?\ ))
18996 '(face secondary-selection))
18997 ""))
18998 (if (not (featurep 'xemacs))
18999 (org-overlay-put ov 'display tx)
19000 (org-overlay-put ov 'invisible t)
19001 (org-overlay-put ov 'end-glyph (make-glyph tx)))
19002 (push ov org-clock-overlays)))
19004 (defun org-remove-clock-overlays (&optional beg end noremove)
19005 "Remove the occur highlights from the buffer.
19006 BEG and END are ignored. If NOREMOVE is nil, remove this function
19007 from the `before-change-functions' in the current buffer."
19008 (interactive)
19009 (unless org-inhibit-highlight-removal
19010 (mapc 'org-delete-overlay org-clock-overlays)
19011 (setq org-clock-overlays nil)
19012 (unless noremove
19013 (remove-hook 'before-change-functions
19014 'org-remove-clock-overlays 'local))))
19016 (defun org-clock-out-if-current ()
19017 "Clock out if the current entry contains the running clock.
19018 This is used to stop the clock after a TODO entry is marked DONE,
19019 and is only done if the variable `org-clock-out-when-done' is not nil."
19020 (when (and org-clock-out-when-done
19021 (member state org-done-keywords)
19022 (equal (marker-buffer org-clock-marker) (current-buffer))
19023 (< (point) org-clock-marker)
19024 (> (save-excursion (outline-next-heading) (point))
19025 org-clock-marker))
19026 ;; Clock out, but don't accept a logging message for this.
19027 (let ((org-log-note-clock-out nil))
19028 (org-clock-out))))
19030 (add-hook 'org-after-todo-state-change-hook
19031 'org-clock-out-if-current)
19033 (defun org-check-running-clock ()
19034 "Check if the current buffer contains the running clock.
19035 If yes, offer to stop it and to save the buffer with the changes."
19036 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19037 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19038 (buffer-name))))
19039 (org-clock-out)
19040 (when (y-or-n-p "Save changed buffer?")
19041 (save-buffer))))
19043 (defun org-clock-report (&optional arg)
19044 "Create a table containing a report about clocked time.
19045 If the cursor is inside an existing clocktable block, then the table
19046 will be updated. If not, a new clocktable will be inserted.
19047 When called with a prefix argument, move to the first clock table in the
19048 buffer and update it."
19049 (interactive "P")
19050 (org-remove-clock-overlays)
19051 (when arg
19052 (org-find-dblock "clocktable")
19053 (org-show-entry))
19054 (if (org-in-clocktable-p)
19055 (goto-char (org-in-clocktable-p))
19056 (org-create-dblock (list :name "clocktable"
19057 :maxlevel 2 :scope 'file)))
19058 (org-update-dblock))
19060 (defun org-in-clocktable-p ()
19061 "Check if the cursor is in a clocktable."
19062 (let ((pos (point)) start)
19063 (save-excursion
19064 (end-of-line 1)
19065 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19066 (setq start (match-beginning 0))
19067 (re-search-forward "^#\\+END:.*" nil t)
19068 (>= (match-end 0) pos)
19069 start))))
19071 (defun org-clock-update-time-maybe ()
19072 "If this is a CLOCK line, update it and return t.
19073 Otherwise, return nil."
19074 (interactive)
19075 (save-excursion
19076 (beginning-of-line 1)
19077 (skip-chars-forward " \t")
19078 (when (looking-at org-clock-string)
19079 (let ((re (concat "[ \t]*" org-clock-string
19080 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19081 "\\([ \t]*=>.*\\)?"))
19082 ts te h m s)
19083 (if (not (looking-at re))
19085 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19086 (end-of-line 1)
19087 (setq ts (match-string 1)
19088 te (match-string 2))
19089 (setq s (- (time-to-seconds
19090 (apply 'encode-time (org-parse-time-string te)))
19091 (time-to-seconds
19092 (apply 'encode-time (org-parse-time-string ts))))
19093 h (floor (/ s 3600))
19094 s (- s (* 3600 h))
19095 m (floor (/ s 60))
19096 s (- s (* 60 s)))
19097 (insert " => " (format "%2d:%02d" h m))
19098 t)))))
19100 (defun org-clock-special-range (key &optional time as-strings)
19101 "Return two times bordering a special time range.
19102 Key is a symbol specifying the range and can be one of `today', `yesterday',
19103 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19104 A week starts Monday 0:00 and ends Sunday 24:00.
19105 The range is determined relative to TIME. TIME defaults to the current time.
19106 The return value is a cons cell with two internal times like the ones
19107 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19108 the returned times will be formatted strings."
19109 (let* ((tm (decode-time (or time (current-time))))
19110 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19111 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19112 (dow (nth 6 tm))
19113 s1 m1 h1 d1 month1 y1 diff ts te fm)
19114 (cond
19115 ((eq key 'today)
19116 (setq h 0 m 0 h1 24 m1 0))
19117 ((eq key 'yesterday)
19118 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19119 ((eq key 'thisweek)
19120 (setq diff (if (= dow 0) 6 (1- dow))
19121 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19122 ((eq key 'lastweek)
19123 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19124 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19125 ((eq key 'thismonth)
19126 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19127 ((eq key 'lastmonth)
19128 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19129 ((eq key 'thisyear)
19130 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19131 ((eq key 'lastyear)
19132 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19133 (t (error "No such time block %s" key)))
19134 (setq ts (encode-time s m h d month y)
19135 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19136 (or d1 d) (or month1 month) (or y1 y)))
19137 (setq fm (cdr org-time-stamp-formats))
19138 (if as-strings
19139 (cons (format-time-string fm ts) (format-time-string fm te))
19140 (cons ts te))))
19142 (defun org-dblock-write:clocktable (params)
19143 "Write the standard clocktable."
19144 (catch 'exit
19145 (let* ((hlchars '((1 . "*") (2 . "/")))
19146 (ins (make-marker))
19147 (total-time nil)
19148 (scope (plist-get params :scope))
19149 (tostring (plist-get params :tostring))
19150 (multifile (plist-get params :multifile))
19151 (header (plist-get params :header))
19152 (maxlevel (or (plist-get params :maxlevel) 3))
19153 (step (plist-get params :step))
19154 (emph (plist-get params :emphasize))
19155 (ts (plist-get params :tstart))
19156 (te (plist-get params :tend))
19157 (block (plist-get params :block))
19158 ipos time h m p level hlc hdl
19159 cc beg end pos tbl)
19160 (when step
19161 (org-clocktable-steps params)
19162 (throw 'exit nil))
19163 (when block
19164 (setq cc (org-clock-special-range block nil t)
19165 ts (car cc) te (cdr cc)))
19166 (if ts (setq ts (time-to-seconds
19167 (apply 'encode-time (org-parse-time-string ts)))))
19168 (if te (setq te (time-to-seconds
19169 (apply 'encode-time (org-parse-time-string te)))))
19170 (move-marker ins (point))
19171 (setq ipos (point))
19173 ;; Get the right scope
19174 (setq pos (point))
19175 (save-restriction
19176 (cond
19177 ((not scope))
19178 ((eq scope 'file) (widen))
19179 ((eq scope 'subtree) (org-narrow-to-subtree))
19180 ((eq scope 'tree)
19181 (while (org-up-heading-safe))
19182 (org-narrow-to-subtree))
19183 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19184 (symbol-name scope)))
19185 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19186 (catch 'exit
19187 (while (org-up-heading-safe)
19188 (looking-at outline-regexp)
19189 (if (<= (org-reduced-level (funcall outline-level)) level)
19190 (throw 'exit nil))))
19191 (org-narrow-to-subtree))
19192 ((or (listp scope) (eq scope 'agenda))
19193 (let* ((files (if (listp scope) scope (org-agenda-files)))
19194 (scope 'agenda)
19195 (p1 (copy-sequence params))
19196 file)
19197 (plist-put p1 :tostring t)
19198 (plist-put p1 :multifile t)
19199 (plist-put p1 :scope 'file)
19200 (org-prepare-agenda-buffers files)
19201 (while (setq file (pop files))
19202 (with-current-buffer (find-buffer-visiting file)
19203 (push (org-clocktable-add-file
19204 file (org-dblock-write:clocktable p1)) tbl)
19205 (setq total-time (+ (or total-time 0)
19206 org-clock-file-total-minutes)))))))
19207 (goto-char pos)
19209 (unless (eq scope 'agenda)
19210 (org-clock-sum ts te)
19211 (goto-char (point-min))
19212 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19213 (goto-char p)
19214 (when (setq time (get-text-property p :org-clock-minutes))
19215 (save-excursion
19216 (beginning-of-line 1)
19217 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19218 (setq level (org-reduced-level
19219 (- (match-end 1) (match-beginning 1))))
19220 (<= level maxlevel))
19221 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19222 hdl (match-string 2)
19223 h (/ time 60)
19224 m (- time (* 60 h)))
19225 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19226 (push (concat
19227 "| " (int-to-string level) "|" hlc hdl hlc " |"
19228 (make-string (1- level) ?|)
19229 hlc (format "%d:%02d" h m) hlc
19230 " |") tbl))))))
19231 (setq tbl (nreverse tbl))
19232 (if tostring
19233 (if tbl (mapconcat 'identity tbl "\n") nil)
19234 (goto-char ins)
19235 (insert-before-markers
19236 (or header
19237 (concat
19238 "Clock summary at ["
19239 (substring
19240 (format-time-string (cdr org-time-stamp-formats))
19241 1 -1)
19242 "]."
19243 (if block
19244 (format " Considered range is /%s/." block)
19246 "\n\n"))
19247 (if (eq scope 'agenda) "|File" "")
19248 "|L|Headline|Time|\n")
19249 (setq total-time (or total-time org-clock-file-total-minutes)
19250 h (/ total-time 60)
19251 m (- total-time (* 60 h)))
19252 (insert-before-markers
19253 "|-\n|"
19254 (if (eq scope 'agenda) "|" "")
19256 "*Total time*| "
19257 (format "*%d:%02d*" h m)
19258 "|\n|-\n")
19259 (setq tbl (delq nil tbl))
19260 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19261 (equal (substring (car tbl) 0 2) "|-"))
19262 (pop tbl))
19263 (insert-before-markers (mapconcat
19264 'identity (delq nil tbl)
19265 (if (eq scope 'agenda) "\n|-\n" "\n")))
19266 (backward-delete-char 1)
19267 (goto-char ipos)
19268 (skip-chars-forward "^|")
19269 (org-table-align))))))
19271 (defun org-clocktable-steps (params)
19272 (let* ((p1 (copy-sequence params))
19273 (ts (plist-get p1 :tstart))
19274 (te (plist-get p1 :tend))
19275 (step0 (plist-get p1 :step))
19276 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19277 (block (plist-get p1 :block))
19279 (when block
19280 (setq cc (org-clock-special-range block nil t)
19281 ts (car cc) te (cdr cc)))
19282 (if ts (setq ts (time-to-seconds
19283 (apply 'encode-time (org-parse-time-string ts)))))
19284 (if te (setq te (time-to-seconds
19285 (apply 'encode-time (org-parse-time-string te)))))
19286 (plist-put p1 :header "")
19287 (plist-put p1 :step nil)
19288 (plist-put p1 :block nil)
19289 (while (< ts te)
19290 (or (bolp) (insert "\n"))
19291 (plist-put p1 :tstart (format-time-string
19292 (car org-time-stamp-formats)
19293 (seconds-to-time ts)))
19294 (plist-put p1 :tend (format-time-string
19295 (car org-time-stamp-formats)
19296 (seconds-to-time (setq ts (+ ts step)))))
19297 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19298 (plist-get p1 :tstart) "\n")
19299 (org-dblock-write:clocktable p1)
19300 (re-search-forward "#\\+END:")
19301 (end-of-line 0))))
19304 (defun org-clocktable-add-file (file table)
19305 (if table
19306 (let ((lines (org-split-string table "\n"))
19307 (ff (file-name-nondirectory file)))
19308 (mapconcat 'identity
19309 (mapcar (lambda (x)
19310 (if (string-match org-table-dataline-regexp x)
19311 (concat "|" ff x)
19313 lines)
19314 "\n"))))
19316 ;; FIXME: I don't think anybody uses this, ask David
19317 (defun org-collect-clock-time-entries ()
19318 "Return an internal list with clocking information.
19319 This list has one entry for each CLOCK interval.
19320 FIXME: describe the elements."
19321 (interactive)
19322 (let ((re (concat "^[ \t]*" org-clock-string
19323 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19324 rtn beg end next cont level title total closedp leafp
19325 clockpos titlepos h m donep)
19326 (save-excursion
19327 (org-clock-sum)
19328 (goto-char (point-min))
19329 (while (re-search-forward re nil t)
19330 (setq clockpos (match-beginning 0)
19331 beg (match-string 1) end (match-string 2)
19332 cont (match-end 0))
19333 (setq beg (apply 'encode-time (org-parse-time-string beg))
19334 end (apply 'encode-time (org-parse-time-string end)))
19335 (org-back-to-heading t)
19336 (setq donep (org-entry-is-done-p))
19337 (setq titlepos (point)
19338 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19339 h (/ total 60) m (- total (* 60 h))
19340 total (cons h m))
19341 (looking-at "\\(\\*+\\) +\\(.*\\)")
19342 (setq level (- (match-end 1) (match-beginning 1))
19343 title (org-match-string-no-properties 2))
19344 (save-excursion (outline-next-heading) (setq next (point)))
19345 (setq closedp (re-search-forward org-closed-time-regexp next t))
19346 (goto-char next)
19347 (setq leafp (and (looking-at "^\\*+ ")
19348 (<= (- (match-end 0) (point)) level)))
19349 (push (list beg end clockpos closedp donep
19350 total title titlepos level leafp)
19351 rtn)
19352 (goto-char cont)))
19353 (nreverse rtn)))
19355 ;;;; Agenda, and Diary Integration
19357 ;;; Define the Org-agenda-mode
19359 (defvar org-agenda-mode-map (make-sparse-keymap)
19360 "Keymap for `org-agenda-mode'.")
19362 (defvar org-agenda-menu) ; defined later in this file.
19363 (defvar org-agenda-follow-mode nil)
19364 (defvar org-agenda-show-log nil)
19365 (defvar org-agenda-redo-command nil)
19366 (defvar org-agenda-query-string nil)
19367 (defvar org-agenda-mode-hook nil)
19368 (defvar org-agenda-type nil)
19369 (defvar org-agenda-force-single-file nil)
19371 (defun org-agenda-mode ()
19372 "Mode for time-sorted view on action items in Org-mode files.
19374 The following commands are available:
19376 \\{org-agenda-mode-map}"
19377 (interactive)
19378 (kill-all-local-variables)
19379 (setq org-agenda-undo-list nil
19380 org-agenda-pending-undo-list nil)
19381 (setq major-mode 'org-agenda-mode)
19382 ;; Keep global-font-lock-mode from turning on font-lock-mode
19383 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19384 (setq mode-name "Org-Agenda")
19385 (use-local-map org-agenda-mode-map)
19386 (easy-menu-add org-agenda-menu)
19387 (if org-startup-truncated (setq truncate-lines t))
19388 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19389 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19390 ;; Make sure properties are removed when copying text
19391 (when (boundp 'buffer-substring-filters)
19392 (org-set-local 'buffer-substring-filters
19393 (cons (lambda (x)
19394 (set-text-properties 0 (length x) nil x) x)
19395 buffer-substring-filters)))
19396 (unless org-agenda-keep-modes
19397 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19398 org-agenda-show-log nil))
19399 (easy-menu-change
19400 '("Agenda") "Agenda Files"
19401 (append
19402 (list
19403 (vector
19404 (if (get 'org-agenda-files 'org-restrict)
19405 "Restricted to single file"
19406 "Edit File List")
19407 '(org-edit-agenda-file-list)
19408 (not (get 'org-agenda-files 'org-restrict)))
19409 "--")
19410 (mapcar 'org-file-menu-entry (org-agenda-files))))
19411 (org-agenda-set-mode-name)
19412 (apply
19413 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19414 (list 'org-agenda-mode-hook)))
19416 (substitute-key-definition 'undo 'org-agenda-undo
19417 org-agenda-mode-map global-map)
19418 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19419 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19420 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19421 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19422 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19423 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19424 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19425 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19426 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19427 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19428 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19429 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19430 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19431 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19432 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19433 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19434 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19435 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19436 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19437 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19438 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19439 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19440 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19441 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19442 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19443 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19444 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19445 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19446 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19448 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19449 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19450 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19451 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19452 (while l (org-defkey org-agenda-mode-map
19453 (int-to-string (pop l)) 'digit-argument)))
19455 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19456 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19457 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19458 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19459 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19460 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19461 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19462 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19463 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19464 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19465 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19466 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19467 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19468 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19469 (org-defkey org-agenda-mode-map "n" 'next-line)
19470 (org-defkey org-agenda-mode-map "p" 'previous-line)
19471 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19472 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19473 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19474 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19475 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19476 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19477 (eval-after-load "calendar"
19478 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19479 'org-calendar-goto-agenda))
19480 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19481 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19482 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19483 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19484 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19485 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19486 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19487 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19488 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19489 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19490 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19491 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19492 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19493 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19494 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19495 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19496 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19497 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19498 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19499 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19500 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19501 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19503 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19504 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19505 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19506 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19508 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19509 "Local keymap for agenda entries from Org-mode.")
19511 (org-defkey org-agenda-keymap
19512 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19513 (org-defkey org-agenda-keymap
19514 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19515 (when org-agenda-mouse-1-follows-link
19516 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19517 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19518 '("Agenda"
19519 ("Agenda Files")
19520 "--"
19521 ["Show" org-agenda-show t]
19522 ["Go To (other window)" org-agenda-goto t]
19523 ["Go To (this window)" org-agenda-switch-to t]
19524 ["Follow Mode" org-agenda-follow-mode
19525 :style toggle :selected org-agenda-follow-mode :active t]
19526 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19527 "--"
19528 ["Cycle TODO" org-agenda-todo t]
19529 ["Archive subtree" org-agenda-archive t]
19530 ["Delete subtree" org-agenda-kill t]
19531 "--"
19532 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19533 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19534 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19535 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19536 "--"
19537 ("Tags and Properties"
19538 ["Show all Tags" org-agenda-show-tags t]
19539 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19540 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19541 "--"
19542 ["Column View" org-columns t])
19543 ("Date/Schedule"
19544 ["Schedule" org-agenda-schedule t]
19545 ["Set Deadline" org-agenda-deadline t]
19546 "--"
19547 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19548 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19549 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19550 ("Clock"
19551 ["Clock in" org-agenda-clock-in t]
19552 ["Clock out" org-agenda-clock-out t]
19553 ["Clock cancel" org-agenda-clock-cancel t]
19554 ["Goto running clock" org-clock-goto t])
19555 ("Priority"
19556 ["Set Priority" org-agenda-priority t]
19557 ["Increase Priority" org-agenda-priority-up t]
19558 ["Decrease Priority" org-agenda-priority-down t]
19559 ["Show Priority" org-agenda-show-priority t])
19560 ("Calendar/Diary"
19561 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19562 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19563 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19564 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19565 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19566 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19567 "--"
19568 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19569 "--"
19570 ("View"
19571 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19572 :style radio :selected (equal org-agenda-ndays 1)]
19573 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19574 :style radio :selected (equal org-agenda-ndays 7)]
19575 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19576 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19577 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19578 :style radio :selected (member org-agenda-ndays '(365 366))]
19579 "--"
19580 ["Show Logbook entries" org-agenda-log-mode
19581 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19582 ["Include Diary" org-agenda-toggle-diary
19583 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19584 ["Use Time Grid" org-agenda-toggle-time-grid
19585 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19586 ["Write view to file" org-write-agenda t]
19587 ["Rebuild buffer" org-agenda-redo t]
19588 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19589 "--"
19590 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19591 "--"
19592 ["Quit" org-agenda-quit t]
19593 ["Exit and Release Buffers" org-agenda-exit t]
19596 ;;; Agenda undo
19598 (defvar org-agenda-allow-remote-undo t
19599 "Non-nil means, allow remote undo from the agenda buffer.")
19600 (defvar org-agenda-undo-list nil
19601 "List of undoable operations in the agenda since last refresh.")
19602 (defvar org-agenda-undo-has-started-in nil
19603 "Buffers that have already seen `undo-start' in the current undo sequence.")
19604 (defvar org-agenda-pending-undo-list nil
19605 "In a series of undo commands, this is the list of remaning undo items.")
19607 (defmacro org-if-unprotected (&rest body)
19608 "Execute BODY if there is no `org-protected' text property at point."
19609 (declare (debug t))
19610 `(unless (get-text-property (point) 'org-protected)
19611 ,@body))
19613 (defmacro org-with-remote-undo (_buffer &rest _body)
19614 "Execute BODY while recording undo information in two buffers."
19615 (declare (indent 1) (debug t))
19616 `(let ((_cline (org-current-line))
19617 (_cmd this-command)
19618 (_buf1 (current-buffer))
19619 (_buf2 ,_buffer)
19620 (_undo1 buffer-undo-list)
19621 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19622 _c1 _c2)
19623 ,@_body
19624 (when org-agenda-allow-remote-undo
19625 (setq _c1 (org-verify-change-for-undo
19626 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19627 _c2 (org-verify-change-for-undo
19628 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19629 (when (or _c1 _c2)
19630 ;; make sure there are undo boundaries
19631 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19632 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19633 ;; remember which buffer to undo
19634 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19635 org-agenda-undo-list)))))
19637 (defun org-agenda-undo ()
19638 "Undo a remote editing step in the agenda.
19639 This undoes changes both in the agenda buffer and in the remote buffer
19640 that have been changed along."
19641 (interactive)
19642 (or org-agenda-allow-remote-undo
19643 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19644 (if (not (eq this-command last-command))
19645 (setq org-agenda-undo-has-started-in nil
19646 org-agenda-pending-undo-list org-agenda-undo-list))
19647 (if (not org-agenda-pending-undo-list)
19648 (error "No further undo information"))
19649 (let* ((entry (pop org-agenda-pending-undo-list))
19650 buf line cmd rembuf)
19651 (setq cmd (pop entry) line (pop entry))
19652 (setq rembuf (nth 2 entry))
19653 (org-with-remote-undo rembuf
19654 (while (bufferp (setq buf (pop entry)))
19655 (if (pop entry)
19656 (with-current-buffer buf
19657 (let ((last-undo-buffer buf)
19658 (inhibit-read-only t))
19659 (unless (memq buf org-agenda-undo-has-started-in)
19660 (push buf org-agenda-undo-has-started-in)
19661 (make-local-variable 'pending-undo-list)
19662 (undo-start))
19663 (while (and pending-undo-list
19664 (listp pending-undo-list)
19665 (not (car pending-undo-list)))
19666 (pop pending-undo-list))
19667 (undo-more 1))))))
19668 (goto-line line)
19669 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19671 (defun org-verify-change-for-undo (l1 l2)
19672 "Verify that a real change occurred between the undo lists L1 and L2."
19673 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19674 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19675 (not (eq l1 l2)))
19677 ;;; Agenda dispatch
19679 (defvar org-agenda-restrict nil)
19680 (defvar org-agenda-restrict-begin (make-marker))
19681 (defvar org-agenda-restrict-end (make-marker))
19682 (defvar org-agenda-last-dispatch-buffer nil)
19683 (defvar org-agenda-overriding-restriction nil)
19685 ;;;###autoload
19686 (defun org-agenda (arg &optional keys restriction)
19687 "Dispatch agenda commands to collect entries to the agenda buffer.
19688 Prompts for a command to execute. Any prefix arg will be passed
19689 on to the selected command. The default selections are:
19691 a Call `org-agenda-list' to display the agenda for current day or week.
19692 t Call `org-todo-list' to display the global todo list.
19693 T Call `org-todo-list' to display the global todo list, select only
19694 entries with a specific TODO keyword (the user gets a prompt).
19695 m Call `org-tags-view' to display headlines with tags matching
19696 a condition (the user is prompted for the condition).
19697 M Like `m', but select only TODO entries, no ordinary headlines.
19698 L Create a timeline for the current buffer.
19699 e Export views to associated files.
19701 More commands can be added by configuring the variable
19702 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19703 searches can be pre-defined in this way.
19705 If the current buffer is in Org-mode and visiting a file, you can also
19706 first press `<' once to indicate that the agenda should be temporarily
19707 \(until the next use of \\[org-agenda]) restricted to the current file.
19708 Pressing `<' twice means to restrict to the current subtree or region
19709 \(if active)."
19710 (interactive "P")
19711 (catch 'exit
19712 (let* ((prefix-descriptions nil)
19713 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19714 (org-agenda-custom-commands
19715 ;; normalize different versions
19716 (delq nil
19717 (mapcar
19718 (lambda (x)
19719 (cond ((stringp (cdr x))
19720 (push x prefix-descriptions)
19721 nil)
19722 ((stringp (nth 1 x)) x)
19723 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19724 (t (cons (car x) (cons "" (cdr x))))))
19725 org-agenda-custom-commands)))
19726 (buf (current-buffer))
19727 (bfn (buffer-file-name (buffer-base-buffer)))
19728 entry key type match lprops ans)
19729 ;; Turn off restriction unless there is an overriding one
19730 (unless org-agenda-overriding-restriction
19731 (put 'org-agenda-files 'org-restrict nil)
19732 (setq org-agenda-restrict nil)
19733 (move-marker org-agenda-restrict-begin nil)
19734 (move-marker org-agenda-restrict-end nil))
19735 ;; Delete old local properties
19736 (put 'org-agenda-redo-command 'org-lprops nil)
19737 ;; Remember where this call originated
19738 (setq org-agenda-last-dispatch-buffer (current-buffer))
19739 (unless keys
19740 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19741 keys (car ans)
19742 restriction (cdr ans)))
19743 ;; Estabish the restriction, if any
19744 (when (and (not org-agenda-overriding-restriction) restriction)
19745 (put 'org-agenda-files 'org-restrict (list bfn))
19746 (cond
19747 ((eq restriction 'region)
19748 (setq org-agenda-restrict t)
19749 (move-marker org-agenda-restrict-begin (region-beginning))
19750 (move-marker org-agenda-restrict-end (region-end)))
19751 ((eq restriction 'subtree)
19752 (save-excursion
19753 (setq org-agenda-restrict t)
19754 (org-back-to-heading t)
19755 (move-marker org-agenda-restrict-begin (point))
19756 (move-marker org-agenda-restrict-end
19757 (progn (org-end-of-subtree t)))))))
19759 (require 'calendar) ; FIXME: can we avoid this for some commands?
19760 ;; For example the todo list should not need it (but does...)
19761 (cond
19762 ((setq entry (assoc keys org-agenda-custom-commands))
19763 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19764 (progn
19765 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19766 (put 'org-agenda-redo-command 'org-lprops lprops)
19767 (cond
19768 ((eq type 'agenda)
19769 (org-let lprops '(org-agenda-list current-prefix-arg)))
19770 ((eq type 'alltodo)
19771 (org-let lprops '(org-todo-list current-prefix-arg)))
19772 ((eq type 'search)
19773 (org-let lprops '(org-search-view current-prefix-arg match)))
19774 ((eq type 'stuck)
19775 (org-let lprops '(org-agenda-list-stuck-projects
19776 current-prefix-arg)))
19777 ((eq type 'tags)
19778 (org-let lprops '(org-tags-view current-prefix-arg match)))
19779 ((eq type 'tags-todo)
19780 (org-let lprops '(org-tags-view '(4) match)))
19781 ((eq type 'todo)
19782 (org-let lprops '(org-todo-list match)))
19783 ((eq type 'tags-tree)
19784 (org-check-for-org-mode)
19785 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19786 ((eq type 'todo-tree)
19787 (org-check-for-org-mode)
19788 (org-let lprops
19789 '(org-occur (concat "^" outline-regexp "[ \t]*"
19790 (regexp-quote match) "\\>"))))
19791 ((eq type 'occur-tree)
19792 (org-check-for-org-mode)
19793 (org-let lprops '(org-occur match)))
19794 ((functionp type)
19795 (org-let lprops '(funcall type match)))
19796 ((fboundp type)
19797 (org-let lprops '(funcall type match)))
19798 (t (error "Invalid custom agenda command type %s" type))))
19799 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19800 ((equal keys "C")
19801 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19802 (customize-variable 'org-agenda-custom-commands))
19803 ((equal keys "a") (call-interactively 'org-agenda-list))
19804 ((equal keys "s") (call-interactively 'org-search-view))
19805 ((equal keys "t") (call-interactively 'org-todo-list))
19806 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19807 ((equal keys "m") (call-interactively 'org-tags-view))
19808 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19809 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19810 ((equal keys "L")
19811 (unless (org-mode-p)
19812 (error "This is not an Org-mode file"))
19813 (unless restriction
19814 (put 'org-agenda-files 'org-restrict (list bfn))
19815 (org-call-with-arg 'org-timeline arg)))
19816 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19817 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19818 ((equal keys "!") (customize-variable 'org-stuck-projects))
19819 (t (error "Invalid agenda key"))))))
19821 (defun org-agenda-normalize-custom-commands (cmds)
19822 (delq nil
19823 (mapcar
19824 (lambda (x)
19825 (cond ((stringp (cdr x)) nil)
19826 ((stringp (nth 1 x)) x)
19827 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19828 (t (cons (car x) (cons "" (cdr x))))))
19829 cmds)))
19831 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19832 "The user interface for selecting an agenda command."
19833 (catch 'exit
19834 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19835 (restrict-ok (and bfn (org-mode-p)))
19836 (region-p (org-region-active-p))
19837 (custom org-agenda-custom-commands)
19838 (selstring "")
19839 restriction second-time
19840 c entry key type match prefixes rmheader header-end custom1 desc)
19841 (save-window-excursion
19842 (delete-other-windows)
19843 (org-switch-to-buffer-other-window " *Agenda Commands*")
19844 (erase-buffer)
19845 (insert (eval-when-compile
19846 (let ((header
19848 Press key for an agenda command: < Buffer,subtree/region restriction
19849 -------------------------------- > Remove restriction
19850 a Agenda for current week or day e Export agenda views
19851 t List of all TODO entries T Entries with special TODO kwd
19852 m Match a TAGS query M Like m, but only TODO entries
19853 L Timeline for current buffer # List stuck projects (!=configure)
19854 s Search for keywords C Configure custom agenda commands
19855 / Multi-occur
19857 (start 0))
19858 (while (string-match
19859 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19860 header start)
19861 (setq start (match-end 0))
19862 (add-text-properties (match-beginning 2) (match-end 2)
19863 '(face bold) header))
19864 header)))
19865 (setq header-end (move-marker (make-marker) (point)))
19866 (while t
19867 (setq custom1 custom)
19868 (when (eq rmheader t)
19869 (goto-line 1)
19870 (re-search-forward ":" nil t)
19871 (delete-region (match-end 0) (point-at-eol))
19872 (forward-char 1)
19873 (looking-at "-+")
19874 (delete-region (match-end 0) (point-at-eol))
19875 (move-marker header-end (match-end 0)))
19876 (goto-char header-end)
19877 (delete-region (point) (point-max))
19878 (while (setq entry (pop custom1))
19879 (setq key (car entry) desc (nth 1 entry)
19880 type (nth 2 entry) match (nth 3 entry))
19881 (if (> (length key) 1)
19882 (add-to-list 'prefixes (string-to-char key))
19883 (insert
19884 (format
19885 "\n%-4s%-14s: %s"
19886 (org-add-props (copy-sequence key)
19887 '(face bold))
19888 (cond
19889 ((string-match "\\S-" desc) desc)
19890 ((eq type 'agenda) "Agenda for current week or day")
19891 ((eq type 'alltodo) "List of all TODO entries")
19892 ((eq type 'search) "Word search")
19893 ((eq type 'stuck) "List of stuck projects")
19894 ((eq type 'todo) "TODO keyword")
19895 ((eq type 'tags) "Tags query")
19896 ((eq type 'tags-todo) "Tags (TODO)")
19897 ((eq type 'tags-tree) "Tags tree")
19898 ((eq type 'todo-tree) "TODO kwd tree")
19899 ((eq type 'occur-tree) "Occur tree")
19900 ((functionp type) (if (symbolp type)
19901 (symbol-name type)
19902 "Lambda expression"))
19903 (t "???"))
19904 (cond
19905 ((stringp match)
19906 (org-add-props match nil 'face 'org-warning))
19907 (match
19908 (format "set of %d commands" (length match)))
19909 (t ""))))))
19910 (when prefixes
19911 (mapc (lambda (x)
19912 (insert
19913 (format "\n%s %s"
19914 (org-add-props (char-to-string x)
19915 nil 'face 'bold)
19916 (or (cdr (assoc (concat selstring (char-to-string x))
19917 prefix-descriptions))
19918 "Prefix key"))))
19919 prefixes))
19920 (goto-char (point-min))
19921 (when (fboundp 'fit-window-to-buffer)
19922 (if second-time
19923 (if (not (pos-visible-in-window-p (point-max)))
19924 (fit-window-to-buffer))
19925 (setq second-time t)
19926 (fit-window-to-buffer)))
19927 (message "Press key for agenda command%s:"
19928 (if (or restrict-ok org-agenda-overriding-restriction)
19929 (if org-agenda-overriding-restriction
19930 " (restriction lock active)"
19931 (if restriction
19932 (format " (restricted to %s)" restriction)
19933 " (unrestricted)"))
19934 ""))
19935 (setq c (read-char-exclusive))
19936 (message "")
19937 (cond
19938 ((assoc (char-to-string c) custom)
19939 (setq selstring (concat selstring (char-to-string c)))
19940 (throw 'exit (cons selstring restriction)))
19941 ((memq c prefixes)
19942 (setq selstring (concat selstring (char-to-string c))
19943 prefixes nil
19944 rmheader (or rmheader t)
19945 custom (delq nil (mapcar
19946 (lambda (x)
19947 (if (or (= (length (car x)) 1)
19948 (/= (string-to-char (car x)) c))
19950 (cons (substring (car x) 1) (cdr x))))
19951 custom))))
19952 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19953 (message "Restriction is only possible in Org-mode buffers")
19954 (ding) (sit-for 1))
19955 ((eq c ?1)
19956 (org-agenda-remove-restriction-lock 'noupdate)
19957 (setq restriction 'buffer))
19958 ((eq c ?0)
19959 (org-agenda-remove-restriction-lock 'noupdate)
19960 (setq restriction (if region-p 'region 'subtree)))
19961 ((eq c ?<)
19962 (org-agenda-remove-restriction-lock 'noupdate)
19963 (setq restriction
19964 (cond
19965 ((eq restriction 'buffer)
19966 (if region-p 'region 'subtree))
19967 ((memq restriction '(subtree region))
19968 nil)
19969 (t 'buffer))))
19970 ((eq c ?>)
19971 (org-agenda-remove-restriction-lock 'noupdate)
19972 (setq restriction nil))
19973 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19974 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19975 ((and (> (length selstring) 0) (eq c ?\d))
19976 (delete-window)
19977 (org-agenda-get-restriction-and-command prefix-descriptions))
19979 ((equal c ?q) (error "Abort"))
19980 (t (error "Invalid key %c" c))))))))
19982 (defun org-run-agenda-series (name series)
19983 (org-prepare-agenda name)
19984 (let* ((org-agenda-multi t)
19985 (redo (list 'org-run-agenda-series name (list 'quote series)))
19986 (cmds (car series))
19987 (gprops (nth 1 series))
19988 match ;; The byte compiler incorrectly complains about this. Keep it!
19989 cmd type lprops)
19990 (while (setq cmd (pop cmds))
19991 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19992 (cond
19993 ((eq type 'agenda)
19994 (org-let2 gprops lprops
19995 '(call-interactively 'org-agenda-list)))
19996 ((eq type 'alltodo)
19997 (org-let2 gprops lprops
19998 '(call-interactively 'org-todo-list)))
19999 ((eq type 'search)
20000 (org-let2 gprops lprops
20001 '(org-search-view current-prefix-arg match)))
20002 ((eq type 'stuck)
20003 (org-let2 gprops lprops
20004 '(call-interactively 'org-agenda-list-stuck-projects)))
20005 ((eq type 'tags)
20006 (org-let2 gprops lprops
20007 '(org-tags-view current-prefix-arg match)))
20008 ((eq type 'tags-todo)
20009 (org-let2 gprops lprops
20010 '(org-tags-view '(4) match)))
20011 ((eq type 'todo)
20012 (org-let2 gprops lprops
20013 '(org-todo-list match)))
20014 ((fboundp type)
20015 (org-let2 gprops lprops
20016 '(funcall type match)))
20017 (t (error "Invalid type in command series"))))
20018 (widen)
20019 (setq org-agenda-redo-command redo)
20020 (goto-char (point-min)))
20021 (org-finalize-agenda))
20023 ;;;###autoload
20024 (defmacro org-batch-agenda (cmd-key &rest parameters)
20025 "Run an agenda command in batch mode and send the result to STDOUT.
20026 If CMD-KEY is a string of length 1, it is used as a key in
20027 `org-agenda-custom-commands' and triggers this command. If it is a
20028 longer string it is used as a tags/todo match string.
20029 Paramters are alternating variable names and values that will be bound
20030 before running the agenda command."
20031 (let (pars)
20032 (while parameters
20033 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20034 (if (> (length cmd-key) 2)
20035 (eval (list 'let (nreverse pars)
20036 (list 'org-tags-view nil cmd-key)))
20037 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20038 (set-buffer org-agenda-buffer-name)
20039 (princ (org-encode-for-stdout (buffer-string)))))
20041 (defun org-encode-for-stdout (string)
20042 (if (fboundp 'encode-coding-string)
20043 (encode-coding-string string buffer-file-coding-system)
20044 string))
20046 (defvar org-agenda-info nil)
20048 ;;;###autoload
20049 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20050 "Run an agenda command in batch mode and send the result to STDOUT.
20051 If CMD-KEY is a string of length 1, it is used as a key in
20052 `org-agenda-custom-commands' and triggers this command. If it is a
20053 longer string it is used as a tags/todo match string.
20054 Paramters are alternating variable names and values that will be bound
20055 before running the agenda command.
20057 The output gives a line for each selected agenda item. Each
20058 item is a list of comma-separated values, like this:
20060 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20062 category The category of the item
20063 head The headline, without TODO kwd, TAGS and PRIORITY
20064 type The type of the agenda entry, can be
20065 todo selected in TODO match
20066 tagsmatch selected in tags match
20067 diary imported from diary
20068 deadline a deadline on given date
20069 scheduled scheduled on given date
20070 timestamp entry has timestamp on given date
20071 closed entry was closed on given date
20072 upcoming-deadline warning about deadline
20073 past-scheduled forwarded scheduled item
20074 block entry has date block including g. date
20075 todo The todo keyword, if any
20076 tags All tags including inherited ones, separated by colons
20077 date The relevant date, like 2007-2-14
20078 time The time, like 15:00-16:50
20079 extra Sting with extra planning info
20080 priority-l The priority letter if any was given
20081 priority-n The computed numerical priority
20082 agenda-day The day in the agenda where this is listed"
20084 (let (pars)
20085 (while parameters
20086 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20087 (push (list 'org-agenda-remove-tags t) pars)
20088 (if (> (length cmd-key) 2)
20089 (eval (list 'let (nreverse pars)
20090 (list 'org-tags-view nil cmd-key)))
20091 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20092 (set-buffer org-agenda-buffer-name)
20093 (let* ((lines (org-split-string (buffer-string) "\n"))
20094 line)
20095 (while (setq line (pop lines))
20096 (catch 'next
20097 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20098 (setq org-agenda-info
20099 (org-fix-agenda-info (text-properties-at 0 line)))
20100 (princ
20101 (org-encode-for-stdout
20102 (mapconcat 'org-agenda-export-csv-mapper
20103 '(org-category txt type todo tags date time-of-day extra
20104 priority-letter priority agenda-day)
20105 ",")))
20106 (princ "\n"))))))
20108 (defun org-fix-agenda-info (props)
20109 "Make sure all properties on an agenda item have a canonical form,
20110 so the export commands can easily use it."
20111 (let (tmp re)
20112 (when (setq tmp (plist-get props 'tags))
20113 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20114 (when (setq tmp (plist-get props 'date))
20115 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20116 (let ((calendar-date-display-form '(year "-" month "-" day)))
20117 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20119 (setq tmp (calendar-date-string tmp)))
20120 (setq props (plist-put props 'date tmp)))
20121 (when (setq tmp (plist-get props 'day))
20122 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20123 (let ((calendar-date-display-form '(year "-" month "-" day)))
20124 (setq tmp (calendar-date-string tmp)))
20125 (setq props (plist-put props 'day tmp))
20126 (setq props (plist-put props 'agenda-day tmp)))
20127 (when (setq tmp (plist-get props 'txt))
20128 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20129 (plist-put props 'priority-letter (match-string 1 tmp))
20130 (setq tmp (replace-match "" t t tmp)))
20131 (when (and (setq re (plist-get props 'org-todo-regexp))
20132 (setq re (concat "\\`\\.*" re " ?"))
20133 (string-match re tmp))
20134 (plist-put props 'todo (match-string 1 tmp))
20135 (setq tmp (replace-match "" t t tmp)))
20136 (plist-put props 'txt tmp)))
20137 props)
20139 (defun org-agenda-export-csv-mapper (prop)
20140 (let ((res (plist-get org-agenda-info prop)))
20141 (setq res
20142 (cond
20143 ((not res) "")
20144 ((stringp res) res)
20145 (t (prin1-to-string res))))
20146 (while (string-match "," res)
20147 (setq res (replace-match ";" t t res)))
20148 (org-trim res)))
20151 ;;;###autoload
20152 (defun org-store-agenda-views (&rest parameters)
20153 (interactive)
20154 (eval (list 'org-batch-store-agenda-views)))
20156 ;; FIXME, why is this a macro?????
20157 ;;;###autoload
20158 (defmacro org-batch-store-agenda-views (&rest parameters)
20159 "Run all custom agenda commands that have a file argument."
20160 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20161 (pop-up-frames nil)
20162 (dir default-directory)
20163 pars cmd thiscmdkey files opts)
20164 (while parameters
20165 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20166 (setq pars (reverse pars))
20167 (save-window-excursion
20168 (while cmds
20169 (setq cmd (pop cmds)
20170 thiscmdkey (car cmd)
20171 opts (nth 4 cmd)
20172 files (nth 5 cmd))
20173 (if (stringp files) (setq files (list files)))
20174 (when files
20175 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20176 (list 'org-agenda nil thiscmdkey)))
20177 (set-buffer org-agenda-buffer-name)
20178 (while files
20179 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20180 (list 'org-write-agenda
20181 (expand-file-name (pop files) dir) t))))
20182 (and (get-buffer org-agenda-buffer-name)
20183 (kill-buffer org-agenda-buffer-name)))))))
20185 (defun org-write-agenda (file &optional nosettings)
20186 "Write the current buffer (an agenda view) as a file.
20187 Depending on the extension of the file name, plain text (.txt),
20188 HTML (.html or .htm) or Postscript (.ps) is produced.
20189 If NOSETTINGS is given, do not scope the settings of
20190 `org-agenda-exporter-settings' into the export commands. This is used when
20191 the settings have already been scoped and we do not wish to overrule other,
20192 higher priority settings."
20193 (interactive "FWrite agenda to file: ")
20194 (if (not (file-writable-p file))
20195 (error "Cannot write agenda to file %s" file))
20196 (cond
20197 ((string-match "\\.html?\\'" file) (require 'htmlize))
20198 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20199 (org-let (if nosettings nil org-agenda-exporter-settings)
20200 '(save-excursion
20201 (save-window-excursion
20202 (cond
20203 ((string-match "\\.html?\\'" file)
20204 (set-buffer (htmlize-buffer (current-buffer)))
20206 (when (and org-agenda-export-html-style
20207 (string-match "<style>" org-agenda-export-html-style))
20208 ;; replace <style> section with org-agenda-export-html-style
20209 (goto-char (point-min))
20210 (kill-region (- (search-forward "<style") 6)
20211 (search-forward "</style>"))
20212 (insert org-agenda-export-html-style))
20213 (write-file file)
20214 (kill-buffer (current-buffer))
20215 (message "HTML written to %s" file))
20216 ((string-match "\\.ps\\'" file)
20217 (ps-print-buffer-with-faces file)
20218 (message "Postscript written to %s" file))
20220 (let ((bs (buffer-string)))
20221 (find-file file)
20222 (insert bs)
20223 (save-buffer 0)
20224 (kill-buffer (current-buffer))
20225 (message "Plain text written to %s" file))))))
20226 (set-buffer org-agenda-buffer-name)))
20228 (defmacro org-no-read-only (&rest body)
20229 "Inhibit read-only for BODY."
20230 `(let ((inhibit-read-only t)) ,@body))
20232 (defun org-check-for-org-mode ()
20233 "Make sure current buffer is in org-mode. Error if not."
20234 (or (org-mode-p)
20235 (error "Cannot execute org-mode agenda command on buffer in %s."
20236 major-mode)))
20238 (defun org-fit-agenda-window ()
20239 "Fit the window to the buffer size."
20240 (and (memq org-agenda-window-setup '(reorganize-frame))
20241 (fboundp 'fit-window-to-buffer)
20242 (fit-window-to-buffer
20244 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20245 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20247 ;;; Agenda file list
20249 (defun org-agenda-files (&optional unrestricted)
20250 "Get the list of agenda files.
20251 Optional UNRESTRICTED means return the full list even if a restriction
20252 is currently in place."
20253 (let ((files
20254 (cond
20255 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20256 ((stringp org-agenda-files) (org-read-agenda-file-list))
20257 ((listp org-agenda-files) org-agenda-files)
20258 (t (error "Invalid value of `org-agenda-files'")))))
20259 (setq files (apply 'append
20260 (mapcar (lambda (f)
20261 (if (file-directory-p f)
20262 (directory-files f t
20263 org-agenda-file-regexp)
20264 (list f)))
20265 files)))
20266 (if org-agenda-skip-unavailable-files
20267 (delq nil
20268 (mapcar (function
20269 (lambda (file)
20270 (and (file-readable-p file) file)))
20271 files))
20272 files))) ; `org-check-agenda-file' will remove them from the list
20274 (defun org-edit-agenda-file-list ()
20275 "Edit the list of agenda files.
20276 Depending on setup, this either uses customize to edit the variable
20277 `org-agenda-files', or it visits the file that is holding the list. In the
20278 latter case, the buffer is set up in a way that saving it automatically kills
20279 the buffer and restores the previous window configuration."
20280 (interactive)
20281 (if (stringp org-agenda-files)
20282 (let ((cw (current-window-configuration)))
20283 (find-file org-agenda-files)
20284 (org-set-local 'org-window-configuration cw)
20285 (org-add-hook 'after-save-hook
20286 (lambda ()
20287 (set-window-configuration
20288 (prog1 org-window-configuration
20289 (kill-buffer (current-buffer))))
20290 (org-install-agenda-files-menu)
20291 (message "New agenda file list installed"))
20292 nil 'local)
20293 (message "%s" (substitute-command-keys
20294 "Edit list and finish with \\[save-buffer]")))
20295 (customize-variable 'org-agenda-files)))
20297 (defun org-store-new-agenda-file-list (list)
20298 "Set new value for the agenda file list and save it correcly."
20299 (if (stringp org-agenda-files)
20300 (let ((f org-agenda-files) b)
20301 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20302 (with-temp-file f
20303 (insert (mapconcat 'identity list "\n") "\n")))
20304 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20305 (setq org-agenda-files list)
20306 (customize-save-variable 'org-agenda-files org-agenda-files))))
20308 (defun org-read-agenda-file-list ()
20309 "Read the list of agenda files from a file."
20310 (when (stringp org-agenda-files)
20311 (with-temp-buffer
20312 (insert-file-contents org-agenda-files)
20313 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20316 ;;;###autoload
20317 (defun org-cycle-agenda-files ()
20318 "Cycle through the files in `org-agenda-files'.
20319 If the current buffer visits an agenda file, find the next one in the list.
20320 If the current buffer does not, find the first agenda file."
20321 (interactive)
20322 (let* ((fs (org-agenda-files t))
20323 (files (append fs (list (car fs))))
20324 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20325 file)
20326 (unless files (error "No agenda files"))
20327 (catch 'exit
20328 (while (setq file (pop files))
20329 (if (equal (file-truename file) tcf)
20330 (when (car files)
20331 (find-file (car files))
20332 (throw 'exit t))))
20333 (find-file (car fs)))
20334 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20336 (defun org-agenda-file-to-front (&optional to-end)
20337 "Move/add the current file to the top of the agenda file list.
20338 If the file is not present in the list, it is added to the front. If it is
20339 present, it is moved there. With optional argument TO-END, add/move to the
20340 end of the list."
20341 (interactive "P")
20342 (let ((org-agenda-skip-unavailable-files nil)
20343 (file-alist (mapcar (lambda (x)
20344 (cons (file-truename x) x))
20345 (org-agenda-files t)))
20346 (ctf (file-truename buffer-file-name))
20347 x had)
20348 (setq x (assoc ctf file-alist) had x)
20350 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20351 (if to-end
20352 (setq file-alist (append (delq x file-alist) (list x)))
20353 (setq file-alist (cons x (delq x file-alist))))
20354 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20355 (org-install-agenda-files-menu)
20356 (message "File %s to %s of agenda file list"
20357 (if had "moved" "added") (if to-end "end" "front"))))
20359 (defun org-remove-file (&optional file)
20360 "Remove current file from the list of files in variable `org-agenda-files'.
20361 These are the files which are being checked for agenda entries.
20362 Optional argument FILE means, use this file instead of the current."
20363 (interactive)
20364 (let* ((org-agenda-skip-unavailable-files nil)
20365 (file (or file buffer-file-name))
20366 (true-file (file-truename file))
20367 (afile (abbreviate-file-name file))
20368 (files (delq nil (mapcar
20369 (lambda (x)
20370 (if (equal true-file
20371 (file-truename x))
20372 nil x))
20373 (org-agenda-files t)))))
20374 (if (not (= (length files) (length (org-agenda-files t))))
20375 (progn
20376 (org-store-new-agenda-file-list files)
20377 (org-install-agenda-files-menu)
20378 (message "Removed file: %s" afile))
20379 (message "File was not in list: %s (not removed)" afile))))
20381 (defun org-file-menu-entry (file)
20382 (vector file (list 'find-file file) t))
20384 (defun org-check-agenda-file (file)
20385 "Make sure FILE exists. If not, ask user what to do."
20386 (when (not (file-exists-p file))
20387 (message "non-existent file %s. [R]emove from list or [A]bort?"
20388 (abbreviate-file-name file))
20389 (let ((r (downcase (read-char-exclusive))))
20390 (cond
20391 ((equal r ?r)
20392 (org-remove-file file)
20393 (throw 'nextfile t))
20394 (t (error "Abort"))))))
20396 ;;; Agenda prepare and finalize
20398 (defvar org-agenda-multi nil) ; dynammically scoped
20399 (defvar org-agenda-buffer-name "*Org Agenda*")
20400 (defvar org-pre-agenda-window-conf nil)
20401 (defvar org-agenda-name nil)
20402 (defun org-prepare-agenda (&optional name)
20403 (setq org-todo-keywords-for-agenda nil)
20404 (setq org-done-keywords-for-agenda nil)
20405 (if org-agenda-multi
20406 (progn
20407 (setq buffer-read-only nil)
20408 (goto-char (point-max))
20409 (unless (or (bobp) org-agenda-compact-blocks)
20410 (insert "\n" (make-string (window-width) ?=) "\n"))
20411 (narrow-to-region (point) (point-max)))
20412 (org-agenda-reset-markers)
20413 (org-prepare-agenda-buffers (org-agenda-files))
20414 (setq org-todo-keywords-for-agenda
20415 (org-uniquify org-todo-keywords-for-agenda))
20416 (setq org-done-keywords-for-agenda
20417 (org-uniquify org-done-keywords-for-agenda))
20418 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20419 (awin (get-buffer-window abuf)))
20420 (cond
20421 ((equal (current-buffer) abuf) nil)
20422 (awin (select-window awin))
20423 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20424 ((equal org-agenda-window-setup 'current-window)
20425 (switch-to-buffer abuf))
20426 ((equal org-agenda-window-setup 'other-window)
20427 (org-switch-to-buffer-other-window abuf))
20428 ((equal org-agenda-window-setup 'other-frame)
20429 (switch-to-buffer-other-frame abuf))
20430 ((equal org-agenda-window-setup 'reorganize-frame)
20431 (delete-other-windows)
20432 (org-switch-to-buffer-other-window abuf))))
20433 (setq buffer-read-only nil)
20434 (erase-buffer)
20435 (org-agenda-mode)
20436 (and name (not org-agenda-name)
20437 (org-set-local 'org-agenda-name name)))
20438 (setq buffer-read-only nil))
20440 (defun org-finalize-agenda ()
20441 "Finishing touch for the agenda buffer, called just before displaying it."
20442 (unless org-agenda-multi
20443 (save-excursion
20444 (let ((inhibit-read-only t))
20445 (goto-char (point-min))
20446 (while (org-activate-bracket-links (point-max))
20447 (add-text-properties (match-beginning 0) (match-end 0)
20448 '(face org-link)))
20449 (org-agenda-align-tags)
20450 (unless org-agenda-with-colors
20451 (remove-text-properties (point-min) (point-max) '(face nil))))
20452 (if (and (boundp 'org-overriding-columns-format)
20453 org-overriding-columns-format)
20454 (org-set-local 'org-overriding-columns-format
20455 org-overriding-columns-format))
20456 (if (and (boundp 'org-agenda-view-columns-initially)
20457 org-agenda-view-columns-initially)
20458 (org-agenda-columns))
20459 (when org-agenda-fontify-priorities
20460 (org-fontify-priorities))
20461 (run-hooks 'org-finalize-agenda-hook)
20462 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20465 (defun org-fontify-priorities ()
20466 "Make highest priority lines bold, and lowest italic."
20467 (interactive)
20468 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20469 (org-delete-overlay o)))
20470 (org-overlays-in (point-min) (point-max)))
20471 (save-excursion
20472 (let ((inhibit-read-only t)
20473 b e p ov h l)
20474 (goto-char (point-min))
20475 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20476 (setq h (or (get-char-property (point) 'org-highest-priority)
20477 org-highest-priority)
20478 l (or (get-char-property (point) 'org-lowest-priority)
20479 org-lowest-priority)
20480 p (string-to-char (match-string 1))
20481 b (match-beginning 0) e (point-at-eol)
20482 ov (org-make-overlay b e))
20483 (org-overlay-put
20484 ov 'face
20485 (cond ((listp org-agenda-fontify-priorities)
20486 (cdr (assoc p org-agenda-fontify-priorities)))
20487 ((equal p l) 'italic)
20488 ((equal p h) 'bold)))
20489 (org-overlay-put ov 'org-type 'org-priority)))))
20491 (defun org-prepare-agenda-buffers (files)
20492 "Create buffers for all agenda files, protect archived trees and comments."
20493 (interactive)
20494 (let ((pa '(:org-archived t))
20495 (pc '(:org-comment t))
20496 (pall '(:org-archived t :org-comment t))
20497 (inhibit-read-only t)
20498 (rea (concat ":" org-archive-tag ":"))
20499 bmp file re)
20500 (save-excursion
20501 (save-restriction
20502 (while (setq file (pop files))
20503 (if (bufferp file)
20504 (set-buffer file)
20505 (org-check-agenda-file file)
20506 (set-buffer (org-get-agenda-file-buffer file)))
20507 (widen)
20508 (setq bmp (buffer-modified-p))
20509 (org-refresh-category-properties)
20510 (setq org-todo-keywords-for-agenda
20511 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20512 (setq org-done-keywords-for-agenda
20513 (append org-done-keywords-for-agenda org-done-keywords))
20514 (save-excursion
20515 (remove-text-properties (point-min) (point-max) pall)
20516 (when org-agenda-skip-archived-trees
20517 (goto-char (point-min))
20518 (while (re-search-forward rea nil t)
20519 (if (org-on-heading-p t)
20520 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20521 (goto-char (point-min))
20522 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20523 (while (re-search-forward re nil t)
20524 (add-text-properties
20525 (match-beginning 0) (org-end-of-subtree t) pc)))
20526 (set-buffer-modified-p bmp))))))
20528 (defvar org-agenda-skip-function nil
20529 "Function to be called at each match during agenda construction.
20530 If this function returns nil, the current match should not be skipped.
20531 Otherwise, the function must return a position from where the search
20532 should be continued.
20533 This may also be a Lisp form, it will be evaluated.
20534 Never set this variable using `setq' or so, because then it will apply
20535 to all future agenda commands. Instead, bind it with `let' to scope
20536 it dynamically into the agenda-constructing command. A good way to set
20537 it is through options in org-agenda-custom-commands.")
20539 (defun org-agenda-skip ()
20540 "Throw to `:skip' in places that should be skipped.
20541 Also moves point to the end of the skipped region, so that search can
20542 continue from there."
20543 (let ((p (point-at-bol)) to fp)
20544 (and org-agenda-skip-archived-trees
20545 (get-text-property p :org-archived)
20546 (org-end-of-subtree t)
20547 (throw :skip t))
20548 (and (get-text-property p :org-comment)
20549 (org-end-of-subtree t)
20550 (throw :skip t))
20551 (if (equal (char-after p) ?#) (throw :skip t))
20552 (when (and (or (setq fp (functionp org-agenda-skip-function))
20553 (consp org-agenda-skip-function))
20554 (setq to (save-excursion
20555 (save-match-data
20556 (if fp
20557 (funcall org-agenda-skip-function)
20558 (eval org-agenda-skip-function))))))
20559 (goto-char to)
20560 (throw :skip t))))
20562 (defvar org-agenda-markers nil
20563 "List of all currently active markers created by `org-agenda'.")
20564 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20565 "Creation time of the last agenda marker.")
20567 (defun org-agenda-new-marker (&optional pos)
20568 "Return a new agenda marker.
20569 Org-mode keeps a list of these markers and resets them when they are
20570 no longer in use."
20571 (let ((m (copy-marker (or pos (point)))))
20572 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20573 (push m org-agenda-markers)
20576 (defun org-agenda-reset-markers ()
20577 "Reset markers created by `org-agenda'."
20578 (while org-agenda-markers
20579 (move-marker (pop org-agenda-markers) nil)))
20581 (defun org-get-agenda-file-buffer (file)
20582 "Get a buffer visiting FILE. If the buffer needs to be created, add
20583 it to the list of buffers which might be released later."
20584 (let ((buf (org-find-base-buffer-visiting file)))
20585 (if buf
20586 buf ; just return it
20587 ;; Make a new buffer and remember it
20588 (setq buf (find-file-noselect file))
20589 (if buf (push buf org-agenda-new-buffers))
20590 buf)))
20592 (defun org-release-buffers (blist)
20593 "Release all buffers in list, asking the user for confirmation when needed.
20594 When a buffer is unmodified, it is just killed. When modified, it is saved
20595 \(if the user agrees) and then killed."
20596 (let (buf file)
20597 (while (setq buf (pop blist))
20598 (setq file (buffer-file-name buf))
20599 (when (and (buffer-modified-p buf)
20600 file
20601 (y-or-n-p (format "Save file %s? " file)))
20602 (with-current-buffer buf (save-buffer)))
20603 (kill-buffer buf))))
20605 (defun org-get-category (&optional pos)
20606 "Get the category applying to position POS."
20607 (get-text-property (or pos (point)) 'org-category))
20609 ;;; Agenda timeline
20611 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20613 (defun org-timeline (&optional include-all)
20614 "Show a time-sorted view of the entries in the current org file.
20615 Only entries with a time stamp of today or later will be listed. With
20616 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20617 under the current date.
20618 If the buffer contains an active region, only check the region for
20619 dates."
20620 (interactive "P")
20621 (require 'calendar)
20622 (org-compile-prefix-format 'timeline)
20623 (org-set-sorting-strategy 'timeline)
20624 (let* ((dopast t)
20625 (dotodo include-all)
20626 (doclosed org-agenda-show-log)
20627 (entry buffer-file-name)
20628 (date (calendar-current-date))
20629 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20630 (end (if (org-region-active-p) (region-end) (point-max)))
20631 (day-numbers (org-get-all-dates beg end 'no-ranges
20632 t doclosed ; always include today
20633 org-timeline-show-empty-dates))
20634 (org-deadline-warning-days 0)
20635 (org-agenda-only-exact-dates t)
20636 (today (time-to-days (current-time)))
20637 (past t)
20638 args
20639 s e rtn d emptyp)
20640 (setq org-agenda-redo-command
20641 (list 'progn
20642 (list 'org-switch-to-buffer-other-window (current-buffer))
20643 (list 'org-timeline (list 'quote include-all))))
20644 (if (not dopast)
20645 ;; Remove past dates from the list of dates.
20646 (setq day-numbers (delq nil (mapcar (lambda(x)
20647 (if (>= x today) x nil))
20648 day-numbers))))
20649 (org-prepare-agenda (concat "Timeline "
20650 (file-name-nondirectory buffer-file-name)))
20651 (if doclosed (push :closed args))
20652 (push :timestamp args)
20653 (push :deadline args)
20654 (push :scheduled args)
20655 (push :sexp args)
20656 (if dotodo (push :todo args))
20657 (while (setq d (pop day-numbers))
20658 (if (and (listp d) (eq (car d) :omitted))
20659 (progn
20660 (setq s (point))
20661 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20662 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20663 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20664 (if (and (>= d today)
20665 dopast
20666 past)
20667 (progn
20668 (setq past nil)
20669 (insert (make-string 79 ?-) "\n")))
20670 (setq date (calendar-gregorian-from-absolute d))
20671 (setq s (point))
20672 (setq rtn (and (not emptyp)
20673 (apply 'org-agenda-get-day-entries entry
20674 date args)))
20675 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20676 (progn
20677 (insert
20678 (if (stringp org-agenda-format-date)
20679 (format-time-string org-agenda-format-date
20680 (org-time-from-absolute date))
20681 (funcall org-agenda-format-date date))
20682 "\n")
20683 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20684 (put-text-property s (1- (point)) 'org-date-line t)
20685 (if (equal d today)
20686 (put-text-property s (1- (point)) 'org-today t))
20687 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20688 (put-text-property s (1- (point)) 'day d)))))
20689 (goto-char (point-min))
20690 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20691 (point-min)))
20692 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20693 (org-finalize-agenda)
20694 (setq buffer-read-only t)))
20696 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20697 "Return a list of all relevant day numbers from BEG to END buffer positions.
20698 If NO-RANGES is non-nil, include only the start and end dates of a range,
20699 not every single day in the range. If FORCE-TODAY is non-nil, make
20700 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20701 inactive time stamps (those in square brackets) are included.
20702 When EMPTY is non-nil, also include days without any entries."
20703 (let ((re (concat
20704 (if pre-re pre-re "")
20705 (if inactive org-ts-regexp-both org-ts-regexp)))
20706 dates dates1 date day day1 day2 ts1 ts2)
20707 (if force-today
20708 (setq dates (list (time-to-days (current-time)))))
20709 (save-excursion
20710 (goto-char beg)
20711 (while (re-search-forward re end t)
20712 (setq day (time-to-days (org-time-string-to-time
20713 (substring (match-string 1) 0 10))))
20714 (or (memq day dates) (push day dates)))
20715 (unless no-ranges
20716 (goto-char beg)
20717 (while (re-search-forward org-tr-regexp end t)
20718 (setq ts1 (substring (match-string 1) 0 10)
20719 ts2 (substring (match-string 2) 0 10)
20720 day1 (time-to-days (org-time-string-to-time ts1))
20721 day2 (time-to-days (org-time-string-to-time ts2)))
20722 (while (< (setq day1 (1+ day1)) day2)
20723 (or (memq day1 dates) (push day1 dates)))))
20724 (setq dates (sort dates '<))
20725 (when empty
20726 (while (setq day (pop dates))
20727 (setq day2 (car dates))
20728 (push day dates1)
20729 (when (and day2 empty)
20730 (if (or (eq empty t)
20731 (and (numberp empty) (<= (- day2 day) empty)))
20732 (while (< (setq day (1+ day)) day2)
20733 (push (list day) dates1))
20734 (push (cons :omitted (- day2 day)) dates1))))
20735 (setq dates (nreverse dates1)))
20736 dates)))
20738 ;;; Agenda Daily/Weekly
20740 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20741 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20742 (defvar org-agenda-last-arguments nil
20743 "The arguments of the previous call to org-agenda")
20744 (defvar org-starting-day nil) ; local variable in the agenda buffer
20745 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20746 (defvar org-include-all-loc nil) ; local variable
20747 (defvar org-agenda-remove-date nil) ; dynamically scoped
20749 ;;;###autoload
20750 (defun org-agenda-list (&optional include-all start-day ndays)
20751 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20752 The view will be for the current day or week, but from the overview buffer
20753 you will be able to go to other days/weeks.
20755 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20756 all unfinished TODO items will also be shown, before the agenda.
20757 This feature is considered obsolete, please use the TODO list or a block
20758 agenda instead.
20760 With a numeric prefix argument in an interactive call, the agenda will
20761 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20762 the number of days. NDAYS defaults to `org-agenda-ndays'.
20764 START-DAY defaults to TODAY, or to the most recent match for the weekday
20765 given in `org-agenda-start-on-weekday'."
20766 (interactive "P")
20767 (if (and (integerp include-all) (> include-all 0))
20768 (setq ndays include-all include-all nil))
20769 (setq ndays (or ndays org-agenda-ndays)
20770 start-day (or start-day org-agenda-start-day))
20771 (if org-agenda-overriding-arguments
20772 (setq include-all (car org-agenda-overriding-arguments)
20773 start-day (nth 1 org-agenda-overriding-arguments)
20774 ndays (nth 2 org-agenda-overriding-arguments)))
20775 (if (stringp start-day)
20776 ;; Convert to an absolute day number
20777 (setq start-day (time-to-days (org-read-date nil t start-day))))
20778 (setq org-agenda-last-arguments (list include-all start-day ndays))
20779 (org-compile-prefix-format 'agenda)
20780 (org-set-sorting-strategy 'agenda)
20781 (require 'calendar)
20782 (let* ((org-agenda-start-on-weekday
20783 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20784 org-agenda-start-on-weekday nil))
20785 (thefiles (org-agenda-files))
20786 (files thefiles)
20787 (today (time-to-days
20788 (time-subtract (current-time)
20789 (list 0 (* 3600 org-extend-today-until) 0))))
20790 (sd (or start-day today))
20791 (start (if (or (null org-agenda-start-on-weekday)
20792 (< org-agenda-ndays 7))
20794 (let* ((nt (calendar-day-of-week
20795 (calendar-gregorian-from-absolute sd)))
20796 (n1 org-agenda-start-on-weekday)
20797 (d (- nt n1)))
20798 (- sd (+ (if (< d 0) 7 0) d)))))
20799 (day-numbers (list start))
20800 (day-cnt 0)
20801 (inhibit-redisplay (not debug-on-error))
20802 s e rtn rtnall file date d start-pos end-pos todayp nd)
20803 (setq org-agenda-redo-command
20804 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20805 ;; Make the list of days
20806 (setq ndays (or ndays org-agenda-ndays)
20807 nd ndays)
20808 (while (> ndays 1)
20809 (push (1+ (car day-numbers)) day-numbers)
20810 (setq ndays (1- ndays)))
20811 (setq day-numbers (nreverse day-numbers))
20812 (org-prepare-agenda "Day/Week")
20813 (org-set-local 'org-starting-day (car day-numbers))
20814 (org-set-local 'org-include-all-loc include-all)
20815 (org-set-local 'org-agenda-span
20816 (org-agenda-ndays-to-span nd))
20817 (when (and (or include-all org-agenda-include-all-todo)
20818 (member today day-numbers))
20819 (setq files thefiles
20820 rtnall nil)
20821 (while (setq file (pop files))
20822 (catch 'nextfile
20823 (org-check-agenda-file file)
20824 (setq date (calendar-gregorian-from-absolute today)
20825 rtn (org-agenda-get-day-entries
20826 file date :todo))
20827 (setq rtnall (append rtnall rtn))))
20828 (when rtnall
20829 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20830 (add-text-properties (point-min) (1- (point))
20831 (list 'face 'org-agenda-structure))
20832 (insert (org-finalize-agenda-entries rtnall) "\n")))
20833 (unless org-agenda-compact-blocks
20834 (setq s (point))
20835 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20836 "-agenda:\n")
20837 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20838 'org-date-line t)))
20839 (while (setq d (pop day-numbers))
20840 (setq date (calendar-gregorian-from-absolute d)
20841 s (point))
20842 (if (or (setq todayp (= d today))
20843 (and (not start-pos) (= d sd)))
20844 (setq start-pos (point))
20845 (if (and start-pos (not end-pos))
20846 (setq end-pos (point))))
20847 (setq files thefiles
20848 rtnall nil)
20849 (while (setq file (pop files))
20850 (catch 'nextfile
20851 (org-check-agenda-file file)
20852 (if org-agenda-show-log
20853 (setq rtn (org-agenda-get-day-entries
20854 file date
20855 :deadline :scheduled :timestamp :sexp :closed))
20856 (setq rtn (org-agenda-get-day-entries
20857 file date
20858 :deadline :scheduled :sexp :timestamp)))
20859 (setq rtnall (append rtnall rtn))))
20860 (if org-agenda-include-diary
20861 (progn
20862 (require 'diary-lib)
20863 (setq rtn (org-get-entries-from-diary date))
20864 (setq rtnall (append rtnall rtn))))
20865 (if (or rtnall org-agenda-show-all-dates)
20866 (progn
20867 (setq day-cnt (1+ day-cnt))
20868 (insert
20869 (if (stringp org-agenda-format-date)
20870 (format-time-string org-agenda-format-date
20871 (org-time-from-absolute date))
20872 (funcall org-agenda-format-date date))
20873 "\n")
20874 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20875 (put-text-property s (1- (point)) 'org-date-line t)
20876 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20877 (if todayp (put-text-property s (1- (point)) 'org-today t))
20878 (if rtnall (insert
20879 (org-finalize-agenda-entries
20880 (org-agenda-add-time-grid-maybe
20881 rtnall nd todayp))
20882 "\n"))
20883 (put-text-property s (1- (point)) 'day d)
20884 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20885 (goto-char (point-min))
20886 (org-fit-agenda-window)
20887 (unless (and (pos-visible-in-window-p (point-min))
20888 (pos-visible-in-window-p (point-max)))
20889 (goto-char (1- (point-max)))
20890 (recenter -1)
20891 (if (not (pos-visible-in-window-p (or start-pos 1)))
20892 (progn
20893 (goto-char (or start-pos 1))
20894 (recenter 1))))
20895 (goto-char (or start-pos 1))
20896 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20897 (org-finalize-agenda)
20898 (setq buffer-read-only t)
20899 (message "")))
20901 (defun org-agenda-ndays-to-span (n)
20902 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20904 ;;; Agenda word search
20906 (defvar org-agenda-search-history nil)
20908 ;;;###autoload
20909 (defun org-search-view (&optional arg string)
20910 "Show all entries that contain words or regular expressions.
20911 If the first character of the search string is an asterisks,
20912 search only the headlines.
20914 The search string is broken into \"words\" by splitting at whitespace.
20915 The individual words are then interpreted as a boolean expression with
20916 logical AND. Words prefixed with a minus must not occur in the entry.
20917 Words without a prefix or prefixed with a plus must occur in the entry.
20918 Matching is case-insensitive and the words are enclosed by word delimiters.
20920 Words enclosed by curly braces are interpreted as regular expressions
20921 that must or must not match in the entry.
20923 This command searches the agenda files, and in addition the files listed
20924 in `org-agenda-text-search-extra-files'."
20925 (interactive "P")
20926 (org-compile-prefix-format 'search)
20927 (org-set-sorting-strategy 'search)
20928 (org-prepare-agenda "SEARCH")
20929 (let* ((props (list 'face nil
20930 'done-face 'org-done
20931 'org-not-done-regexp org-not-done-regexp
20932 'org-todo-regexp org-todo-regexp
20933 'mouse-face 'highlight
20934 'keymap org-agenda-keymap
20935 'help-echo (format "mouse-2 or RET jump to location")))
20936 regexp rtn rtnall files file pos
20937 marker priority category tags c neg re
20938 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
20939 (unless (and (not arg)
20940 (stringp string)
20941 (string-match "\\S-" string))
20942 (setq string (read-string "[+-]Word/{Regexp} ...: "
20943 (cond
20944 ((integerp arg) (cons string arg))
20945 (arg string))
20946 'org-agenda-search-history)))
20947 (setq org-agenda-redo-command
20948 (list 'org-search-view 'current-prefix-arg string))
20949 (setq org-agenda-query-string string)
20951 (if (equal (string-to-char string) ?*)
20952 (setq hdl-only t
20953 words (substring string 1))
20954 (setq words string))
20955 (setq words (org-split-string words))
20956 (mapc (lambda (w)
20957 (setq c (string-to-char w))
20958 (if (equal c ?-)
20959 (setq neg t w (substring w 1))
20960 (if (equal c ?+)
20961 (setq neg nil w (substring w 1))
20962 (setq neg nil)))
20963 (if (string-match "\\`{.*}\\'" w)
20964 (setq re (substring w 1 -1))
20965 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
20966 (if neg (push re regexps-) (push re regexps+)))
20967 words)
20968 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
20969 (if (not regexps+)
20970 (setq regexp (concat "^" org-outline-regexp))
20971 (setq regexp (pop regexps+))
20972 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
20973 regexp))))
20974 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
20975 rtnall nil)
20976 (while (setq file (pop files))
20977 (setq ee nil)
20978 (catch 'nextfile
20979 (org-check-agenda-file file)
20980 (setq buffer (if (file-exists-p file)
20981 (org-get-agenda-file-buffer file)
20982 (error "No such file %s" file)))
20983 (if (not buffer)
20984 ;; If file does not exist, make sure an error message is sent
20985 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
20986 file))))
20987 (with-current-buffer buffer
20988 (unless (org-mode-p)
20989 (error "Agenda file %s is not in `org-mode'" file))
20990 (let ((case-fold-search t))
20991 (save-excursion
20992 (save-restriction
20993 (if org-agenda-restrict
20994 (narrow-to-region org-agenda-restrict-begin
20995 org-agenda-restrict-end)
20996 (widen))
20997 (goto-char (point-min))
20998 (unless (or (org-on-heading-p)
20999 (outline-next-heading))
21000 (throw 'nextfile t))
21001 (goto-char (max (point-min) (1- (point))))
21002 (while (re-search-forward regexp nil t)
21003 (org-back-to-heading t)
21004 (skip-chars-forward "* ")
21005 (setq beg (point-at-bol)
21006 beg1 (point)
21007 end (progn (outline-next-heading) (point)))
21008 (catch :skip
21009 (goto-char beg)
21010 (org-agenda-skip)
21011 (setq str (buffer-substring-no-properties
21012 (point-at-bol)
21013 (if hdl-only (point-at-eol) end)))
21014 (mapc (lambda (wr) (when (string-match wr str)
21015 (goto-char (1- end))
21016 (throw :skip t)))
21017 regexps-)
21018 (mapc (lambda (wr) (unless (string-match wr str)
21019 (goto-char (1- end))
21020 (throw :skip t)))
21021 regexps+)
21022 (goto-char beg)
21023 (setq marker (org-agenda-new-marker (point))
21024 category (org-get-category)
21025 tags (org-get-tags-at (point))
21026 txt (org-format-agenda-item
21028 (buffer-substring-no-properties
21029 beg1 (point-at-eol))
21030 category tags))
21031 (org-add-props txt props
21032 'org-marker marker 'org-hd-marker marker
21033 'priority 1000 'org-category category
21034 'type "search")
21035 (push txt ee)
21036 (goto-char (1- end)))))))))
21037 (setq rtn (nreverse ee))
21038 (setq rtnall (append rtnall rtn)))
21039 (if org-agenda-overriding-header
21040 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21041 nil 'face 'org-agenda-structure) "\n")
21042 (insert "Search words: ")
21043 (add-text-properties (point-min) (1- (point))
21044 (list 'face 'org-agenda-structure))
21045 (setq pos (point))
21046 (insert string "\n")
21047 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21048 (setq pos (point))
21049 (unless org-agenda-multi
21050 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21051 (add-text-properties pos (1- (point))
21052 (list 'face 'org-agenda-structure))))
21053 (when rtnall
21054 (insert (org-finalize-agenda-entries rtnall) "\n"))
21055 (goto-char (point-min))
21056 (org-fit-agenda-window)
21057 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21058 (org-finalize-agenda)
21059 (setq buffer-read-only t)))
21061 ;;; Agenda TODO list
21063 (defvar org-select-this-todo-keyword nil)
21064 (defvar org-last-arg nil)
21066 ;;;###autoload
21067 (defun org-todo-list (arg)
21068 "Show all TODO entries from all agenda file in a single list.
21069 The prefix arg can be used to select a specific TODO keyword and limit
21070 the list to these. When using \\[universal-argument], you will be prompted
21071 for a keyword. A numeric prefix directly selects the Nth keyword in
21072 `org-todo-keywords-1'."
21073 (interactive "P")
21074 (require 'calendar)
21075 (org-compile-prefix-format 'todo)
21076 (org-set-sorting-strategy 'todo)
21077 (org-prepare-agenda "TODO")
21078 (let* ((today (time-to-days (current-time)))
21079 (date (calendar-gregorian-from-absolute today))
21080 (kwds org-todo-keywords-for-agenda)
21081 (completion-ignore-case t)
21082 (org-select-this-todo-keyword
21083 (if (stringp arg) arg
21084 (and arg (integerp arg) (> arg 0)
21085 (nth (1- arg) kwds))))
21086 rtn rtnall files file pos)
21087 (when (equal arg '(4))
21088 (setq org-select-this-todo-keyword
21089 (completing-read "Keyword (or KWD1|K2D2|...): "
21090 (mapcar 'list kwds) nil nil)))
21091 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21092 (org-set-local 'org-last-arg arg)
21093 (setq org-agenda-redo-command
21094 '(org-todo-list (or current-prefix-arg org-last-arg)))
21095 (setq files (org-agenda-files)
21096 rtnall nil)
21097 (while (setq file (pop files))
21098 (catch 'nextfile
21099 (org-check-agenda-file file)
21100 (setq rtn (org-agenda-get-day-entries file date :todo))
21101 (setq rtnall (append rtnall rtn))))
21102 (if org-agenda-overriding-header
21103 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21104 nil 'face 'org-agenda-structure) "\n")
21105 (insert "Global list of TODO items of type: ")
21106 (add-text-properties (point-min) (1- (point))
21107 (list 'face 'org-agenda-structure))
21108 (setq pos (point))
21109 (insert (or org-select-this-todo-keyword "ALL") "\n")
21110 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21111 (setq pos (point))
21112 (unless org-agenda-multi
21113 (insert "Available with `N r': (0)ALL")
21114 (let ((n 0) s)
21115 (mapc (lambda (x)
21116 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21117 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21118 (insert "\n "))
21119 (insert " " s))
21120 kwds))
21121 (insert "\n"))
21122 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21123 (when rtnall
21124 (insert (org-finalize-agenda-entries rtnall) "\n"))
21125 (goto-char (point-min))
21126 (org-fit-agenda-window)
21127 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21128 (org-finalize-agenda)
21129 (setq buffer-read-only t)))
21131 ;;; Agenda tags match
21133 ;;;###autoload
21134 (defun org-tags-view (&optional todo-only match)
21135 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21136 The prefix arg TODO-ONLY limits the search to TODO entries."
21137 (interactive "P")
21138 (org-compile-prefix-format 'tags)
21139 (org-set-sorting-strategy 'tags)
21140 (let* ((org-tags-match-list-sublevels
21141 (if todo-only t org-tags-match-list-sublevels))
21142 (completion-ignore-case t)
21143 rtn rtnall files file pos matcher
21144 buffer)
21145 (setq matcher (org-make-tags-matcher match)
21146 match (car matcher) matcher (cdr matcher))
21147 (org-prepare-agenda (concat "TAGS " match))
21148 (setq org-agenda-redo-command
21149 (list 'org-tags-view (list 'quote todo-only)
21150 (list 'if 'current-prefix-arg nil match)))
21151 (setq files (org-agenda-files)
21152 rtnall nil)
21153 (while (setq file (pop files))
21154 (catch 'nextfile
21155 (org-check-agenda-file file)
21156 (setq buffer (if (file-exists-p file)
21157 (org-get-agenda-file-buffer file)
21158 (error "No such file %s" file)))
21159 (if (not buffer)
21160 ;; If file does not exist, merror message to agenda
21161 (setq rtn (list
21162 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21163 rtnall (append rtnall rtn))
21164 (with-current-buffer buffer
21165 (unless (org-mode-p)
21166 (error "Agenda file %s is not in `org-mode'" file))
21167 (save-excursion
21168 (save-restriction
21169 (if org-agenda-restrict
21170 (narrow-to-region org-agenda-restrict-begin
21171 org-agenda-restrict-end)
21172 (widen))
21173 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21174 (setq rtnall (append rtnall rtn))))))))
21175 (if org-agenda-overriding-header
21176 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21177 nil 'face 'org-agenda-structure) "\n")
21178 (insert "Headlines with TAGS match: ")
21179 (add-text-properties (point-min) (1- (point))
21180 (list 'face 'org-agenda-structure))
21181 (setq pos (point))
21182 (insert match "\n")
21183 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21184 (setq pos (point))
21185 (unless org-agenda-multi
21186 (insert "Press `C-u r' to search again with new search string\n"))
21187 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21188 (when rtnall
21189 (insert (org-finalize-agenda-entries rtnall) "\n"))
21190 (goto-char (point-min))
21191 (org-fit-agenda-window)
21192 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21193 (org-finalize-agenda)
21194 (setq buffer-read-only t)))
21196 ;;; Agenda Finding stuck projects
21198 (defvar org-agenda-skip-regexp nil
21199 "Regular expression used in skipping subtrees for the agenda.
21200 This is basically a temporary global variable that can be set and then
21201 used by user-defined selections using `org-agenda-skip-function'.")
21203 (defvar org-agenda-overriding-header nil
21204 "When this is set during todo and tags searches, will replace header.")
21206 (defun org-agenda-skip-subtree-when-regexp-matches ()
21207 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21208 If yes, it returns the end position of this tree, causing agenda commands
21209 to skip this subtree. This is a function that can be put into
21210 `org-agenda-skip-function' for the duration of a command."
21211 (let ((end (save-excursion (org-end-of-subtree t)))
21212 skip)
21213 (save-excursion
21214 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21215 (and skip end)))
21217 (defun org-agenda-skip-entry-if (&rest conditions)
21218 "Skip entry if any of CONDITIONS is true.
21219 See `org-agenda-skip-if' for details."
21220 (org-agenda-skip-if nil conditions))
21222 (defun org-agenda-skip-subtree-if (&rest conditions)
21223 "Skip entry if any of CONDITIONS is true.
21224 See `org-agenda-skip-if' for details."
21225 (org-agenda-skip-if t conditions))
21227 (defun org-agenda-skip-if (subtree conditions)
21228 "Checks current entity for CONDITIONS.
21229 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21230 the entry, i.e. the text before the next heading is checked.
21232 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21233 from different tests. Valid conditions are:
21235 scheduled Check if there is a scheduled cookie
21236 notscheduled Check if there is no scheduled cookie
21237 deadline Check if there is a deadline
21238 notdeadline Check if there is no deadline
21239 regexp Check if regexp matches
21240 notregexp Check if regexp does not match.
21242 The regexp is taken from the conditions list, it must come right after
21243 the `regexp' or `notregexp' element.
21245 If any of these conditions is met, this function returns the end point of
21246 the entity, causing the search to continue from there. This is a function
21247 that can be put into `org-agenda-skip-function' for the duration of a command."
21248 (let (beg end m)
21249 (org-back-to-heading t)
21250 (setq beg (point)
21251 end (if subtree
21252 (progn (org-end-of-subtree t) (point))
21253 (progn (outline-next-heading) (1- (point)))))
21254 (goto-char beg)
21255 (and
21257 (and (memq 'scheduled conditions)
21258 (re-search-forward org-scheduled-time-regexp end t))
21259 (and (memq 'notscheduled conditions)
21260 (not (re-search-forward org-scheduled-time-regexp end t)))
21261 (and (memq 'deadline conditions)
21262 (re-search-forward org-deadline-time-regexp end t))
21263 (and (memq 'notdeadline conditions)
21264 (not (re-search-forward org-deadline-time-regexp end t)))
21265 (and (setq m (memq 'regexp conditions))
21266 (stringp (nth 1 m))
21267 (re-search-forward (nth 1 m) end t))
21268 (and (setq m (memq 'notregexp conditions))
21269 (stringp (nth 1 m))
21270 (not (re-search-forward (nth 1 m) end t))))
21271 end)))
21273 ;;;###autoload
21274 (defun org-agenda-list-stuck-projects (&rest ignore)
21275 "Create agenda view for projects that are stuck.
21276 Stuck projects are project that have no next actions. For the definitions
21277 of what a project is and how to check if it stuck, customize the variable
21278 `org-stuck-projects'.
21279 MATCH is being ignored."
21280 (interactive)
21281 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21282 ;; FIXME: we could have used org-agenda-skip-if here.
21283 (org-agenda-overriding-header "List of stuck projects: ")
21284 (matcher (nth 0 org-stuck-projects))
21285 (todo (nth 1 org-stuck-projects))
21286 (todo-wds (if (member "*" todo)
21287 (progn
21288 (org-prepare-agenda-buffers (org-agenda-files))
21289 (org-delete-all
21290 org-done-keywords-for-agenda
21291 (copy-sequence org-todo-keywords-for-agenda)))
21292 todo))
21293 (todo-re (concat "^\\*+[ \t]+\\("
21294 (mapconcat 'identity todo-wds "\\|")
21295 "\\)\\>"))
21296 (tags (nth 2 org-stuck-projects))
21297 (tags-re (if (member "*" tags)
21298 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21299 (concat "^\\*+ .*:\\("
21300 (mapconcat 'identity tags "\\|")
21301 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21302 (gen-re (nth 3 org-stuck-projects))
21303 (re-list
21304 (delq nil
21305 (list
21306 (if todo todo-re)
21307 (if tags tags-re)
21308 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21309 gen-re)))))
21310 (setq org-agenda-skip-regexp
21311 (if re-list
21312 (mapconcat 'identity re-list "\\|")
21313 (error "No information how to identify unstuck projects")))
21314 (org-tags-view nil matcher)
21315 (with-current-buffer org-agenda-buffer-name
21316 (setq org-agenda-redo-command
21317 '(org-agenda-list-stuck-projects
21318 (or current-prefix-arg org-last-arg))))))
21320 ;;; Diary integration
21322 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21324 (defun org-get-entries-from-diary (date)
21325 "Get the (Emacs Calendar) diary entries for DATE."
21326 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21327 (diary-display-hook '(fancy-diary-display))
21328 (pop-up-frames nil)
21329 (list-diary-entries-hook
21330 (cons 'org-diary-default-entry list-diary-entries-hook))
21331 (diary-file-name-prefix-function nil) ; turn this feature off
21332 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21333 entries
21334 (org-disable-agenda-to-diary t))
21335 (save-excursion
21336 (save-window-excursion
21337 (funcall (if (fboundp 'diary-list-entries)
21338 'diary-list-entries 'list-diary-entries)
21339 date 1)))
21340 (if (not (get-buffer fancy-diary-buffer))
21341 (setq entries nil)
21342 (with-current-buffer fancy-diary-buffer
21343 (setq buffer-read-only nil)
21344 (if (zerop (buffer-size))
21345 ;; No entries
21346 (setq entries nil)
21347 ;; Omit the date and other unnecessary stuff
21348 (org-agenda-cleanup-fancy-diary)
21349 ;; Add prefix to each line and extend the text properties
21350 (if (zerop (buffer-size))
21351 (setq entries nil)
21352 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21353 (set-buffer-modified-p nil)
21354 (kill-buffer fancy-diary-buffer)))
21355 (when entries
21356 (setq entries (org-split-string entries "\n"))
21357 (setq entries
21358 (mapcar
21359 (lambda (x)
21360 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21361 ;; Extend the text properties to the beginning of the line
21362 (org-add-props x (text-properties-at (1- (length x)) x)
21363 'type "diary" 'date date))
21364 entries)))))
21366 (defun org-agenda-cleanup-fancy-diary ()
21367 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21368 This gets rid of the date, the underline under the date, and
21369 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21370 date. It also removes lines that contain only whitespace."
21371 (goto-char (point-min))
21372 (if (looking-at ".*?:[ \t]*")
21373 (progn
21374 (replace-match "")
21375 (re-search-forward "\n=+$" nil t)
21376 (replace-match "")
21377 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21378 (re-search-forward "\n=+$" nil t)
21379 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21380 (goto-char (point-min))
21381 (while (re-search-forward "^ +\n" nil t)
21382 (replace-match ""))
21383 (goto-char (point-min))
21384 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21385 (replace-match "")))
21387 ;; Make sure entries from the diary have the right text properties.
21388 (eval-after-load "diary-lib"
21389 '(if (boundp 'diary-modify-entry-list-string-function)
21390 ;; We can rely on the hook, nothing to do
21392 ;; Hook not avaiable, must use advice to make this work
21393 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21394 "Make the position visible."
21395 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21396 (stringp string)
21397 buffer-file-name)
21398 (setq string (org-modify-diary-entry-string string))))))
21400 (defun org-modify-diary-entry-string (string)
21401 "Add text properties to string, allowing org-mode to act on it."
21402 (org-add-props string nil
21403 'mouse-face 'highlight
21404 'keymap org-agenda-keymap
21405 'help-echo (if buffer-file-name
21406 (format "mouse-2 or RET jump to diary file %s"
21407 (abbreviate-file-name buffer-file-name))
21409 'org-agenda-diary-link t
21410 'org-marker (org-agenda-new-marker (point-at-bol))))
21412 (defun org-diary-default-entry ()
21413 "Add a dummy entry to the diary.
21414 Needed to avoid empty dates which mess up holiday display."
21415 ;; Catch the error if dealing with the new add-to-diary-alist
21416 (when org-disable-agenda-to-diary
21417 (condition-case nil
21418 (add-to-diary-list original-date "Org-mode dummy" "")
21419 (error
21420 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21422 ;;;###autoload
21423 (defun org-diary (&rest args)
21424 "Return diary information from org-files.
21425 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21426 It accesses org files and extracts information from those files to be
21427 listed in the diary. The function accepts arguments specifying what
21428 items should be listed. The following arguments are allowed:
21430 :timestamp List the headlines of items containing a date stamp or
21431 date range matching the selected date. Deadlines will
21432 also be listed, on the expiration day.
21434 :sexp List entries resulting from diary-like sexps.
21436 :deadline List any deadlines past due, or due within
21437 `org-deadline-warning-days'. The listing occurs only
21438 in the diary for *today*, not at any other date. If
21439 an entry is marked DONE, it is no longer listed.
21441 :scheduled List all items which are scheduled for the given date.
21442 The diary for *today* also contains items which were
21443 scheduled earlier and are not yet marked DONE.
21445 :todo List all TODO items from the org-file. This may be a
21446 long list - so this is not turned on by default.
21447 Like deadlines, these entries only show up in the
21448 diary for *today*, not at any other date.
21450 The call in the diary file should look like this:
21452 &%%(org-diary) ~/path/to/some/orgfile.org
21454 Use a separate line for each org file to check. Or, if you omit the file name,
21455 all files listed in `org-agenda-files' will be checked automatically:
21457 &%%(org-diary)
21459 If you don't give any arguments (as in the example above), the default
21460 arguments (:deadline :scheduled :timestamp :sexp) are used.
21461 So the example above may also be written as
21463 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21465 The function expects the lisp variables `entry' and `date' to be provided
21466 by the caller, because this is how the calendar works. Don't use this
21467 function from a program - use `org-agenda-get-day-entries' instead."
21468 (when (> (- (time-to-seconds (current-time))
21469 org-agenda-last-marker-time)
21471 (org-agenda-reset-markers))
21472 (org-compile-prefix-format 'agenda)
21473 (org-set-sorting-strategy 'agenda)
21474 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21475 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21476 (list entry)
21477 (org-agenda-files t)))
21478 file rtn results)
21479 (org-prepare-agenda-buffers files)
21480 ;; If this is called during org-agenda, don't return any entries to
21481 ;; the calendar. Org Agenda will list these entries itself.
21482 (if org-disable-agenda-to-diary (setq files nil))
21483 (while (setq file (pop files))
21484 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21485 (setq results (append results rtn)))
21486 (if results
21487 (concat (org-finalize-agenda-entries results) "\n"))))
21489 ;;; Agenda entry finders
21491 (defun org-agenda-get-day-entries (file date &rest args)
21492 "Does the work for `org-diary' and `org-agenda'.
21493 FILE is the path to a file to be checked for entries. DATE is date like
21494 the one returned by `calendar-current-date'. ARGS are symbols indicating
21495 which kind of entries should be extracted. For details about these, see
21496 the documentation of `org-diary'."
21497 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21498 (let* ((org-startup-folded nil)
21499 (org-startup-align-all-tables nil)
21500 (buffer (if (file-exists-p file)
21501 (org-get-agenda-file-buffer file)
21502 (error "No such file %s" file)))
21503 arg results rtn)
21504 (if (not buffer)
21505 ;; If file does not exist, make sure an error message ends up in diary
21506 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21507 (with-current-buffer buffer
21508 (unless (org-mode-p)
21509 (error "Agenda file %s is not in `org-mode'" file))
21510 (let ((case-fold-search nil))
21511 (save-excursion
21512 (save-restriction
21513 (if org-agenda-restrict
21514 (narrow-to-region org-agenda-restrict-begin
21515 org-agenda-restrict-end)
21516 (widen))
21517 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21518 (while (setq arg (pop args))
21519 (cond
21520 ((and (eq arg :todo)
21521 (equal date (calendar-current-date)))
21522 (setq rtn (org-agenda-get-todos))
21523 (setq results (append results rtn)))
21524 ((eq arg :timestamp)
21525 (setq rtn (org-agenda-get-blocks))
21526 (setq results (append results rtn))
21527 (setq rtn (org-agenda-get-timestamps))
21528 (setq results (append results rtn)))
21529 ((eq arg :sexp)
21530 (setq rtn (org-agenda-get-sexps))
21531 (setq results (append results rtn)))
21532 ((eq arg :scheduled)
21533 (setq rtn (org-agenda-get-scheduled))
21534 (setq results (append results rtn)))
21535 ((eq arg :closed)
21536 (setq rtn (org-agenda-get-closed))
21537 (setq results (append results rtn)))
21538 ((eq arg :deadline)
21539 (setq rtn (org-agenda-get-deadlines))
21540 (setq results (append results rtn))))))))
21541 results))))
21543 (defun org-entry-is-todo-p ()
21544 (member (org-get-todo-state) org-not-done-keywords))
21546 (defun org-entry-is-done-p ()
21547 (member (org-get-todo-state) org-done-keywords))
21549 (defun org-get-todo-state ()
21550 (save-excursion
21551 (org-back-to-heading t)
21552 (and (looking-at org-todo-line-regexp)
21553 (match-end 2)
21554 (match-string 2))))
21556 (defun org-at-date-range-p (&optional inactive-ok)
21557 "Is the cursor inside a date range?"
21558 (interactive)
21559 (save-excursion
21560 (catch 'exit
21561 (let ((pos (point)))
21562 (skip-chars-backward "^[<\r\n")
21563 (skip-chars-backward "<[")
21564 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21565 (>= (match-end 0) pos)
21566 (throw 'exit t))
21567 (skip-chars-backward "^<[\r\n")
21568 (skip-chars-backward "<[")
21569 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21570 (>= (match-end 0) pos)
21571 (throw 'exit t)))
21572 nil)))
21574 (defun org-agenda-get-todos ()
21575 "Return the TODO information for agenda display."
21576 (let* ((props (list 'face nil
21577 'done-face 'org-done
21578 'org-not-done-regexp org-not-done-regexp
21579 'org-todo-regexp org-todo-regexp
21580 'mouse-face 'highlight
21581 'keymap org-agenda-keymap
21582 'help-echo
21583 (format "mouse-2 or RET jump to org file %s"
21584 (abbreviate-file-name buffer-file-name))))
21585 ;; FIXME: get rid of the \n at some point but watch out
21586 (regexp (concat "^\\*+[ \t]+\\("
21587 (if org-select-this-todo-keyword
21588 (if (equal org-select-this-todo-keyword "*")
21589 org-todo-regexp
21590 (concat "\\<\\("
21591 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21592 "\\)\\>"))
21593 org-not-done-regexp)
21594 "[^\n\r]*\\)"))
21595 marker priority category tags
21596 ee txt beg end)
21597 (goto-char (point-min))
21598 (while (re-search-forward regexp nil t)
21599 (catch :skip
21600 (save-match-data
21601 (beginning-of-line)
21602 (setq beg (point) end (progn (outline-next-heading) (point)))
21603 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21604 (re-search-forward org-ts-regexp end t))
21605 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21606 (re-search-forward org-scheduled-time-regexp end t))
21607 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21608 (re-search-forward org-deadline-time-regexp end t)
21609 (org-deadline-close (match-string 1))))
21610 (goto-char (1+ beg))
21611 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21612 (throw :skip nil)))
21613 (goto-char beg)
21614 (org-agenda-skip)
21615 (goto-char (match-beginning 1))
21616 (setq marker (org-agenda-new-marker (match-beginning 0))
21617 category (org-get-category)
21618 tags (org-get-tags-at (point))
21619 txt (org-format-agenda-item "" (match-string 1) category tags)
21620 priority (1+ (org-get-priority txt)))
21621 (org-add-props txt props
21622 'org-marker marker 'org-hd-marker marker
21623 'priority priority 'org-category category
21624 'type "todo")
21625 (push txt ee)
21626 (if org-agenda-todo-list-sublevels
21627 (goto-char (match-end 1))
21628 (org-end-of-subtree 'invisible))))
21629 (nreverse ee)))
21631 (defconst org-agenda-no-heading-message
21632 "No heading for this item in buffer or region.")
21634 (defun org-agenda-get-timestamps ()
21635 "Return the date stamp information for agenda display."
21636 (let* ((props (list 'face nil
21637 'org-not-done-regexp org-not-done-regexp
21638 'org-todo-regexp org-todo-regexp
21639 'mouse-face 'highlight
21640 'keymap org-agenda-keymap
21641 'help-echo
21642 (format "mouse-2 or RET jump to org file %s"
21643 (abbreviate-file-name buffer-file-name))))
21644 (d1 (calendar-absolute-from-gregorian date))
21645 (remove-re
21646 (concat
21647 (regexp-quote
21648 (format-time-string
21649 "<%Y-%m-%d"
21650 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21651 ".*?>"))
21652 (regexp
21653 (concat
21654 (regexp-quote
21655 (substring
21656 (format-time-string
21657 (car org-time-stamp-formats)
21658 (apply 'encode-time ; DATE bound by calendar
21659 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21660 0 11))
21661 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21662 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21663 marker hdmarker deadlinep scheduledp donep tmp priority category
21664 ee txt timestr tags b0 b3 e3 head)
21665 (goto-char (point-min))
21666 (while (re-search-forward regexp nil t)
21667 (setq b0 (match-beginning 0)
21668 b3 (match-beginning 3) e3 (match-end 3))
21669 (catch :skip
21670 (and (org-at-date-range-p) (throw :skip nil))
21671 (org-agenda-skip)
21672 (if (and (match-end 1)
21673 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21674 (throw :skip nil))
21675 (if (and e3
21676 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21677 (throw :skip nil))
21678 (setq marker (org-agenda-new-marker b0)
21679 category (org-get-category b0)
21680 tmp (buffer-substring (max (point-min)
21681 (- b0 org-ds-keyword-length))
21683 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21684 deadlinep (string-match org-deadline-regexp tmp)
21685 scheduledp (string-match org-scheduled-regexp tmp)
21686 donep (org-entry-is-done-p))
21687 (if (or scheduledp deadlinep) (throw :skip t))
21688 (if (string-match ">" timestr)
21689 ;; substring should only run to end of time stamp
21690 (setq timestr (substring timestr 0 (match-end 0))))
21691 (save-excursion
21692 (if (re-search-backward "^\\*+ " nil t)
21693 (progn
21694 (goto-char (match-beginning 0))
21695 (setq hdmarker (org-agenda-new-marker)
21696 tags (org-get-tags-at))
21697 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21698 (setq head (match-string 1))
21699 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21700 (setq txt (org-format-agenda-item
21701 nil head category tags timestr nil
21702 remove-re)))
21703 (setq txt org-agenda-no-heading-message))
21704 (setq priority (org-get-priority txt))
21705 (org-add-props txt props
21706 'org-marker marker 'org-hd-marker hdmarker)
21707 (org-add-props txt nil 'priority priority
21708 'org-category category 'date date
21709 'type "timestamp")
21710 (push txt ee))
21711 (outline-next-heading)))
21712 (nreverse ee)))
21714 (defun org-agenda-get-sexps ()
21715 "Return the sexp information for agenda display."
21716 (require 'diary-lib)
21717 (let* ((props (list 'face nil
21718 'mouse-face 'highlight
21719 'keymap org-agenda-keymap
21720 'help-echo
21721 (format "mouse-2 or RET jump to org file %s"
21722 (abbreviate-file-name buffer-file-name))))
21723 (regexp "^&?%%(")
21724 marker category ee txt tags entry result beg b sexp sexp-entry)
21725 (goto-char (point-min))
21726 (while (re-search-forward regexp nil t)
21727 (catch :skip
21728 (org-agenda-skip)
21729 (setq beg (match-beginning 0))
21730 (goto-char (1- (match-end 0)))
21731 (setq b (point))
21732 (forward-sexp 1)
21733 (setq sexp (buffer-substring b (point)))
21734 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21735 (org-trim (match-string 1))
21736 ""))
21737 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21738 (when result
21739 (setq marker (org-agenda-new-marker beg)
21740 category (org-get-category beg))
21742 (if (string-match "\\S-" result)
21743 (setq txt result)
21744 (setq txt "SEXP entry returned empty string"))
21746 (setq txt (org-format-agenda-item
21747 "" txt category tags 'time))
21748 (org-add-props txt props 'org-marker marker)
21749 (org-add-props txt nil
21750 'org-category category 'date date
21751 'type "sexp")
21752 (push txt ee))))
21753 (nreverse ee)))
21755 (defun org-agenda-get-closed ()
21756 "Return the logged TODO entries for agenda display."
21757 (let* ((props (list 'mouse-face 'highlight
21758 'org-not-done-regexp org-not-done-regexp
21759 'org-todo-regexp org-todo-regexp
21760 'keymap org-agenda-keymap
21761 'help-echo
21762 (format "mouse-2 or RET jump to org file %s"
21763 (abbreviate-file-name buffer-file-name))))
21764 (regexp (concat
21765 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21766 (regexp-quote
21767 (substring
21768 (format-time-string
21769 (car org-time-stamp-formats)
21770 (apply 'encode-time ; DATE bound by calendar
21771 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21772 1 11))))
21773 marker hdmarker priority category tags closedp
21774 ee txt timestr)
21775 (goto-char (point-min))
21776 (while (re-search-forward regexp nil t)
21777 (catch :skip
21778 (org-agenda-skip)
21779 (setq marker (org-agenda-new-marker (match-beginning 0))
21780 closedp (equal (match-string 1) org-closed-string)
21781 category (org-get-category (match-beginning 0))
21782 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21783 ;; donep (org-entry-is-done-p)
21785 (if (string-match "\\]" timestr)
21786 ;; substring should only run to end of time stamp
21787 (setq timestr (substring timestr 0 (match-end 0))))
21788 (save-excursion
21789 (if (re-search-backward "^\\*+ " nil t)
21790 (progn
21791 (goto-char (match-beginning 0))
21792 (setq hdmarker (org-agenda-new-marker)
21793 tags (org-get-tags-at))
21794 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21795 (setq txt (org-format-agenda-item
21796 (if closedp "Closed: " "Clocked: ")
21797 (match-string 1) category tags timestr)))
21798 (setq txt org-agenda-no-heading-message))
21799 (setq priority 100000)
21800 (org-add-props txt props
21801 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21802 'priority priority 'org-category category
21803 'type "closed" 'date date
21804 'undone-face 'org-warning 'done-face 'org-done)
21805 (push txt ee))
21806 (goto-char (point-at-eol))))
21807 (nreverse ee)))
21809 (defun org-agenda-get-deadlines ()
21810 "Return the deadline information for agenda display."
21811 (let* ((props (list 'mouse-face 'highlight
21812 'org-not-done-regexp org-not-done-regexp
21813 'org-todo-regexp org-todo-regexp
21814 'keymap org-agenda-keymap
21815 'help-echo
21816 (format "mouse-2 or RET jump to org file %s"
21817 (abbreviate-file-name buffer-file-name))))
21818 (regexp org-deadline-time-regexp)
21819 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21820 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21821 d2 diff dfrac wdays pos pos1 category tags
21822 ee txt head face s upcomingp donep timestr)
21823 (goto-char (point-min))
21824 (while (re-search-forward regexp nil t)
21825 (catch :skip
21826 (org-agenda-skip)
21827 (setq s (match-string 1)
21828 pos (1- (match-beginning 1))
21829 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21830 diff (- d2 d1)
21831 wdays (org-get-wdays s)
21832 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21833 upcomingp (and todayp (> diff 0)))
21834 ;; When to show a deadline in the calendar:
21835 ;; If the expiration is within wdays warning time.
21836 ;; Past-due deadlines are only shown on the current date
21837 (if (or (and (<= diff wdays)
21838 (and todayp (not org-agenda-only-exact-dates)))
21839 (= diff 0))
21840 (save-excursion
21841 (setq category (org-get-category))
21842 (if (re-search-backward "^\\*+[ \t]+" nil t)
21843 (progn
21844 (goto-char (match-end 0))
21845 (setq pos1 (match-beginning 0))
21846 (setq tags (org-get-tags-at pos1))
21847 (setq head (buffer-substring-no-properties
21848 (point)
21849 (progn (skip-chars-forward "^\r\n")
21850 (point))))
21851 (setq donep (string-match org-looking-at-done-regexp head))
21852 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21853 (setq timestr
21854 (concat (substring s (match-beginning 1)) " "))
21855 (setq timestr 'time))
21856 (if (and donep
21857 (or org-agenda-skip-deadline-if-done
21858 (not (= diff 0))))
21859 (setq txt nil)
21860 (setq txt (org-format-agenda-item
21861 (if (= diff 0)
21862 (car org-agenda-deadline-leaders)
21863 (format (nth 1 org-agenda-deadline-leaders)
21864 diff))
21865 head category tags timestr))))
21866 (setq txt org-agenda-no-heading-message))
21867 (when txt
21868 (setq face (org-agenda-deadline-face dfrac wdays))
21869 (org-add-props txt props
21870 'org-marker (org-agenda-new-marker pos)
21871 'org-hd-marker (org-agenda-new-marker pos1)
21872 'priority (+ (- diff)
21873 (org-get-priority txt))
21874 'org-category category
21875 'type (if upcomingp "upcoming-deadline" "deadline")
21876 'date (if upcomingp date d2)
21877 'face (if donep 'org-done face)
21878 'undone-face face 'done-face 'org-done)
21879 (push txt ee))))))
21880 (nreverse ee)))
21882 (defun org-agenda-deadline-face (fraction &optional wdays)
21883 "Return the face to displaying a deadline item.
21884 FRACTION is what fraction of the head-warning time has passed."
21885 (if (equal wdays 0) (setq fraction 1.))
21886 (let ((faces org-agenda-deadline-faces) f)
21887 (catch 'exit
21888 (while (setq f (pop faces))
21889 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21891 (defun org-agenda-get-scheduled ()
21892 "Return the scheduled information for agenda display."
21893 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21894 'org-todo-regexp org-todo-regexp
21895 'done-face 'org-done
21896 'mouse-face 'highlight
21897 'keymap org-agenda-keymap
21898 'help-echo
21899 (format "mouse-2 or RET jump to org file %s"
21900 (abbreviate-file-name buffer-file-name))))
21901 (regexp org-scheduled-time-regexp)
21902 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21903 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21904 d2 diff pos pos1 category tags
21905 ee txt head pastschedp donep face timestr s)
21906 (goto-char (point-min))
21907 (while (re-search-forward regexp nil t)
21908 (catch :skip
21909 (org-agenda-skip)
21910 (setq s (match-string 1)
21911 pos (1- (match-beginning 1))
21912 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21913 ;;; is this right?
21914 ;;; do we need to do this for deadleine too????
21915 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21916 diff (- d2 d1))
21917 (setq pastschedp (and todayp (< diff 0)))
21918 ;; When to show a scheduled item in the calendar:
21919 ;; If it is on or past the date.
21920 (if (or (and (< diff 0)
21921 (and todayp (not org-agenda-only-exact-dates)))
21922 (= diff 0))
21923 (save-excursion
21924 (setq category (org-get-category))
21925 (if (re-search-backward "^\\*+[ \t]+" nil t)
21926 (progn
21927 (goto-char (match-end 0))
21928 (setq pos1 (match-beginning 0))
21929 (setq tags (org-get-tags-at))
21930 (setq head (buffer-substring-no-properties
21931 (point)
21932 (progn (skip-chars-forward "^\r\n") (point))))
21933 (setq donep (string-match org-looking-at-done-regexp head))
21934 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21935 (setq timestr
21936 (concat (substring s (match-beginning 1)) " "))
21937 (setq timestr 'time))
21938 (if (and donep
21939 (or org-agenda-skip-scheduled-if-done
21940 (not (= diff 0))))
21941 (setq txt nil)
21942 (setq txt (org-format-agenda-item
21943 (if (= diff 0)
21944 (car org-agenda-scheduled-leaders)
21945 (format (nth 1 org-agenda-scheduled-leaders)
21946 (- 1 diff)))
21947 head category tags timestr))))
21948 (setq txt org-agenda-no-heading-message))
21949 (when txt
21950 (setq face (if pastschedp
21951 'org-scheduled-previously
21952 'org-scheduled-today))
21953 (org-add-props txt props
21954 'undone-face face
21955 'face (if donep 'org-done face)
21956 'org-marker (org-agenda-new-marker pos)
21957 'org-hd-marker (org-agenda-new-marker pos1)
21958 'type (if pastschedp "past-scheduled" "scheduled")
21959 'date (if pastschedp d2 date)
21960 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21961 'org-category category)
21962 (push txt ee))))))
21963 (nreverse ee)))
21965 (defun org-agenda-get-blocks ()
21966 "Return the date-range information for agenda display."
21967 (let* ((props (list 'face nil
21968 'org-not-done-regexp org-not-done-regexp
21969 'org-todo-regexp org-todo-regexp
21970 'mouse-face 'highlight
21971 'keymap org-agenda-keymap
21972 'help-echo
21973 (format "mouse-2 or RET jump to org file %s"
21974 (abbreviate-file-name buffer-file-name))))
21975 (regexp org-tr-regexp)
21976 (d0 (calendar-absolute-from-gregorian date))
21977 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21978 donep head)
21979 (goto-char (point-min))
21980 (while (re-search-forward regexp nil t)
21981 (catch :skip
21982 (org-agenda-skip)
21983 (setq pos (point))
21984 (setq timestr (match-string 0)
21985 s1 (match-string 1)
21986 s2 (match-string 2)
21987 d1 (time-to-days (org-time-string-to-time s1))
21988 d2 (time-to-days (org-time-string-to-time s2)))
21989 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21990 ;; Only allow days between the limits, because the normal
21991 ;; date stamps will catch the limits.
21992 (save-excursion
21993 (setq marker (org-agenda-new-marker (point)))
21994 (setq category (org-get-category))
21995 (if (re-search-backward "^\\*+ " nil t)
21996 (progn
21997 (goto-char (match-beginning 0))
21998 (setq hdmarker (org-agenda-new-marker (point)))
21999 (setq tags (org-get-tags-at))
22000 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22001 (setq head (match-string 1))
22002 (and org-agenda-skip-timestamp-if-done
22003 (org-entry-is-done-p)
22004 (throw :skip t))
22005 (setq txt (org-format-agenda-item
22006 (format (if (= d1 d2) "" "(%d/%d): ")
22007 (1+ (- d0 d1)) (1+ (- d2 d1)))
22008 head category tags
22009 (if (= d0 d1) timestr))))
22010 (setq txt org-agenda-no-heading-message))
22011 (org-add-props txt props
22012 'org-marker marker 'org-hd-marker hdmarker
22013 'type "block" 'date date
22014 'priority (org-get-priority txt) 'org-category category)
22015 (push txt ee)))
22016 (goto-char pos)))
22017 ;; Sort the entries by expiration date.
22018 (nreverse ee)))
22020 ;;; Agenda presentation and sorting
22022 (defconst org-plain-time-of-day-regexp
22023 (concat
22024 "\\(\\<[012]?[0-9]"
22025 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22026 "\\(--?"
22027 "\\(\\<[012]?[0-9]"
22028 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22029 "\\)?")
22030 "Regular expression to match a plain time or time range.
22031 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22032 groups carry important information:
22033 0 the full match
22034 1 the first time, range or not
22035 8 the second time, if it is a range.")
22037 (defconst org-plain-time-extension-regexp
22038 (concat
22039 "\\(\\<[012]?[0-9]"
22040 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22041 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22042 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22043 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22044 groups carry important information:
22045 0 the full match
22046 7 hours of duration
22047 9 minutes of duration")
22049 (defconst org-stamp-time-of-day-regexp
22050 (concat
22051 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22052 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22053 "\\(--?"
22054 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22055 "Regular expression to match a timestamp time or time range.
22056 After a match, the following groups carry important information:
22057 0 the full match
22058 1 date plus weekday, for backreferencing to make sure both times on same day
22059 2 the first time, range or not
22060 4 the second time, if it is a range.")
22062 (defvar org-prefix-has-time nil
22063 "A flag, set by `org-compile-prefix-format'.
22064 The flag is set if the currently compiled format contains a `%t'.")
22065 (defvar org-prefix-has-tag nil
22066 "A flag, set by `org-compile-prefix-format'.
22067 The flag is set if the currently compiled format contains a `%T'.")
22069 (defun org-format-agenda-item (extra txt &optional category tags dotime
22070 noprefix remove-re)
22071 "Format TXT to be inserted into the agenda buffer.
22072 In particular, it adds the prefix and corresponding text properties. EXTRA
22073 must be a string and replaces the `%s' specifier in the prefix format.
22074 CATEGORY (string, symbol or nil) may be used to overrule the default
22075 category taken from local variable or file name. It will replace the `%c'
22076 specifier in the format. DOTIME, when non-nil, indicates that a
22077 time-of-day should be extracted from TXT for sorting of this entry, and for
22078 the `%t' specifier in the format. When DOTIME is a string, this string is
22079 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22080 only the correctly processes TXT should be returned - this is used by
22081 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22082 Any match of REMOVE-RE will be removed from TXT."
22083 (save-match-data
22084 ;; Diary entries sometimes have extra whitespace at the beginning
22085 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22086 (let* ((category (or category
22087 org-category
22088 (if buffer-file-name
22089 (file-name-sans-extension
22090 (file-name-nondirectory buffer-file-name))
22091 "")))
22092 (tag (if tags (nth (1- (length tags)) tags) ""))
22093 time ; time and tag are needed for the eval of the prefix format
22094 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22095 (time-of-day (and dotime (org-get-time-of-day ts)))
22096 stamp plain s0 s1 s2 rtn srp)
22097 (when (and dotime time-of-day org-prefix-has-time)
22098 ;; Extract starting and ending time and move them to prefix
22099 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22100 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22101 (setq s0 (match-string 0 ts)
22102 srp (and stamp (match-end 3))
22103 s1 (match-string (if plain 1 2) ts)
22104 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22106 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22107 ;; them, we might want to remove them there to avoid duplication.
22108 ;; The user can turn this off with a variable.
22109 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22110 (string-match (concat (regexp-quote s0) " *") txt)
22111 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22112 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22113 (= (match-beginning 0) 0)
22115 (setq txt (replace-match "" nil nil txt))))
22116 ;; Normalize the time(s) to 24 hour
22117 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22118 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22120 (when (and s1 (not s2) org-agenda-default-appointment-duration
22121 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22122 (let ((m (+ (string-to-number (match-string 2 s1))
22123 (* 60 (string-to-number (match-string 1 s1)))
22124 org-agenda-default-appointment-duration))
22126 (setq h (/ m 60) m (- m (* h 60)))
22127 (setq s2 (format "%02d:%02d" h m))))
22129 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22130 txt)
22131 ;; Tags are in the string
22132 (if (or (eq org-agenda-remove-tags t)
22133 (and org-agenda-remove-tags
22134 org-prefix-has-tag))
22135 (setq txt (replace-match "" t t txt))
22136 (setq txt (replace-match
22137 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22138 (match-string 2 txt))
22139 t t txt))))
22141 (when remove-re
22142 (while (string-match remove-re txt)
22143 (setq txt (replace-match "" t t txt))))
22145 ;; Create the final string
22146 (if noprefix
22147 (setq rtn txt)
22148 ;; Prepare the variables needed in the eval of the compiled format
22149 (setq time (cond (s2 (concat s1 "-" s2))
22150 (s1 (concat s1 "......"))
22151 (t ""))
22152 extra (or extra "")
22153 category (if (symbolp category) (symbol-name category) category))
22154 ;; Evaluate the compiled format
22155 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22157 ;; And finally add the text properties
22158 (org-add-props rtn nil
22159 'org-category (downcase category) 'tags tags
22160 'org-highest-priority org-highest-priority
22161 'org-lowest-priority org-lowest-priority
22162 'prefix-length (- (length rtn) (length txt))
22163 'time-of-day time-of-day
22164 'txt txt
22165 'time time
22166 'extra extra
22167 'dotime dotime))))
22169 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22170 (defvar org-agenda-sorting-strategy-selected nil)
22172 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22173 (catch 'exit
22174 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22175 ((and todayp (member 'today (car org-agenda-time-grid))))
22176 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22177 ((member 'weekly (car org-agenda-time-grid)))
22178 (t (throw 'exit list)))
22179 (let* ((have (delq nil (mapcar
22180 (lambda (x) (get-text-property 1 'time-of-day x))
22181 list)))
22182 (string (nth 1 org-agenda-time-grid))
22183 (gridtimes (nth 2 org-agenda-time-grid))
22184 (req (car org-agenda-time-grid))
22185 (remove (member 'remove-match req))
22186 new time)
22187 (if (and (member 'require-timed req) (not have))
22188 ;; don't show empty grid
22189 (throw 'exit list))
22190 (while (setq time (pop gridtimes))
22191 (unless (and remove (member time have))
22192 (setq time (int-to-string time))
22193 (push (org-format-agenda-item
22194 nil string "" nil
22195 (concat (substring time 0 -2) ":" (substring time -2)))
22196 new)
22197 (put-text-property
22198 1 (length (car new)) 'face 'org-time-grid (car new))))
22199 (if (member 'time-up org-agenda-sorting-strategy-selected)
22200 (append new list)
22201 (append list new)))))
22203 (defun org-compile-prefix-format (key)
22204 "Compile the prefix format into a Lisp form that can be evaluated.
22205 The resulting form is returned and stored in the variable
22206 `org-prefix-format-compiled'."
22207 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22208 (let ((s (cond
22209 ((stringp org-agenda-prefix-format)
22210 org-agenda-prefix-format)
22211 ((assq key org-agenda-prefix-format)
22212 (cdr (assq key org-agenda-prefix-format)))
22213 (t " %-12:c%?-12t% s")))
22214 (start 0)
22215 varform vars var e c f opt)
22216 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22217 s start)
22218 (setq var (cdr (assoc (match-string 4 s)
22219 '(("c" . category) ("t" . time) ("s" . extra)
22220 ("T" . tag))))
22221 c (or (match-string 3 s) "")
22222 opt (match-beginning 1)
22223 start (1+ (match-beginning 0)))
22224 (if (equal var 'time) (setq org-prefix-has-time t))
22225 (if (equal var 'tag) (setq org-prefix-has-tag t))
22226 (setq f (concat "%" (match-string 2 s) "s"))
22227 (if opt
22228 (setq varform
22229 `(if (equal "" ,var)
22231 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22232 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22233 (setq s (replace-match "%s" t nil s))
22234 (push varform vars))
22235 (setq vars (nreverse vars))
22236 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22238 (defun org-set-sorting-strategy (key)
22239 (if (symbolp (car org-agenda-sorting-strategy))
22240 ;; the old format
22241 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22242 (setq org-agenda-sorting-strategy-selected
22243 (or (cdr (assq key org-agenda-sorting-strategy))
22244 (cdr (assq 'agenda org-agenda-sorting-strategy))
22245 '(time-up category-keep priority-down)))))
22247 (defun org-get-time-of-day (s &optional string mod24)
22248 "Check string S for a time of day.
22249 If found, return it as a military time number between 0 and 2400.
22250 If not found, return nil.
22251 The optional STRING argument forces conversion into a 5 character wide string
22252 HH:MM."
22253 (save-match-data
22254 (when
22255 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22256 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22257 (let* ((h (string-to-number (match-string 1 s)))
22258 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22259 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22260 (am-p (equal ampm "am"))
22261 (h1 (cond ((not ampm) h)
22262 ((= h 12) (if am-p 0 12))
22263 (t (+ h (if am-p 0 12)))))
22264 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22265 (mod h1 24) h1))
22266 (t0 (+ (* 100 h2) m))
22267 (t1 (concat (if (>= h1 24) "+" " ")
22268 (if (< t0 100) "0" "")
22269 (if (< t0 10) "0" "")
22270 (int-to-string t0))))
22271 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22273 (defun org-finalize-agenda-entries (list &optional nosort)
22274 "Sort and concatenate the agenda items."
22275 (setq list (mapcar 'org-agenda-highlight-todo list))
22276 (if nosort
22277 list
22278 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22280 (defun org-agenda-highlight-todo (x)
22281 (let (re pl)
22282 (if (eq x 'line)
22283 (save-excursion
22284 (beginning-of-line 1)
22285 (setq re (get-text-property (point) 'org-todo-regexp))
22286 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22287 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22288 (add-text-properties (match-beginning 0) (match-end 0)
22289 (list 'face (org-get-todo-face 0)))
22290 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22291 (delete-region (match-beginning 1) (1- (match-end 0)))
22292 (goto-char (match-beginning 1))
22293 (insert (format org-agenda-todo-keyword-format s)))))
22294 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22295 pl (get-text-property 0 'prefix-length x))
22296 (when (and re
22297 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22298 x (or pl 0)) pl))
22299 (add-text-properties
22300 (or (match-end 1) (match-end 0)) (match-end 0)
22301 (list 'face (org-get-todo-face (match-string 2 x)))
22303 (setq x (concat (substring x 0 (match-end 1))
22304 (format org-agenda-todo-keyword-format
22305 (match-string 2 x))
22307 (substring x (match-end 3)))))
22308 x)))
22310 (defsubst org-cmp-priority (a b)
22311 "Compare the priorities of string A and B."
22312 (let ((pa (or (get-text-property 1 'priority a) 0))
22313 (pb (or (get-text-property 1 'priority b) 0)))
22314 (cond ((> pa pb) +1)
22315 ((< pa pb) -1)
22316 (t nil))))
22318 (defsubst org-cmp-category (a b)
22319 "Compare the string values of categories of strings A and B."
22320 (let ((ca (or (get-text-property 1 'org-category a) ""))
22321 (cb (or (get-text-property 1 'org-category b) "")))
22322 (cond ((string-lessp ca cb) -1)
22323 ((string-lessp cb ca) +1)
22324 (t nil))))
22326 (defsubst org-cmp-tag (a b)
22327 "Compare the string values of categories of strings A and B."
22328 (let ((ta (car (last (get-text-property 1 'tags a))))
22329 (tb (car (last (get-text-property 1 'tags b)))))
22330 (cond ((not ta) +1)
22331 ((not tb) -1)
22332 ((string-lessp ta tb) -1)
22333 ((string-lessp tb ta) +1)
22334 (t nil))))
22336 (defsubst org-cmp-time (a b)
22337 "Compare the time-of-day values of strings A and B."
22338 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22339 (ta (or (get-text-property 1 'time-of-day a) def))
22340 (tb (or (get-text-property 1 'time-of-day b) def)))
22341 (cond ((< ta tb) -1)
22342 ((< tb ta) +1)
22343 (t nil))))
22345 (defun org-entries-lessp (a b)
22346 "Predicate for sorting agenda entries."
22347 ;; The following variables will be used when the form is evaluated.
22348 ;; So even though the compiler complains, keep them.
22349 (let* ((time-up (org-cmp-time a b))
22350 (time-down (if time-up (- time-up) nil))
22351 (priority-up (org-cmp-priority a b))
22352 (priority-down (if priority-up (- priority-up) nil))
22353 (category-up (org-cmp-category a b))
22354 (category-down (if category-up (- category-up) nil))
22355 (category-keep (if category-up +1 nil))
22356 (tag-up (org-cmp-tag a b))
22357 (tag-down (if tag-up (- tag-up) nil)))
22358 (cdr (assoc
22359 (eval (cons 'or org-agenda-sorting-strategy-selected))
22360 '((-1 . t) (1 . nil) (nil . nil))))))
22362 ;;; Agenda restriction lock
22364 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22365 "Overlay to mark the headline to which arenda commands are restricted.")
22366 (org-overlay-put org-agenda-restriction-lock-overlay
22367 'face 'org-agenda-restriction-lock)
22368 (org-overlay-put org-agenda-restriction-lock-overlay
22369 'help-echo "Agendas are currently limited to this subtree.")
22370 (org-detach-overlay org-agenda-restriction-lock-overlay)
22371 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22372 "Overlay marking the agenda restriction line in speedbar.")
22373 (org-overlay-put org-speedbar-restriction-lock-overlay
22374 'face 'org-agenda-restriction-lock)
22375 (org-overlay-put org-speedbar-restriction-lock-overlay
22376 'help-echo "Agendas are currently limited to this item.")
22377 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22379 (defun org-agenda-set-restriction-lock (&optional type)
22380 "Set restriction lock for agenda, to current subtree or file.
22381 Restriction will be the file if TYPE is `file', or if type is the
22382 universal prefix '(4), or if the cursor is before the first headline
22383 in the file. Otherwise, restriction will be to the current subtree."
22384 (interactive "P")
22385 (and (equal type '(4)) (setq type 'file))
22386 (setq type (cond
22387 (type type)
22388 ((org-at-heading-p) 'subtree)
22389 ((condition-case nil (org-back-to-heading t) (error nil))
22390 'subtree)
22391 (t 'file)))
22392 (if (eq type 'subtree)
22393 (progn
22394 (setq org-agenda-restrict t)
22395 (setq org-agenda-overriding-restriction 'subtree)
22396 (put 'org-agenda-files 'org-restrict
22397 (list (buffer-file-name (buffer-base-buffer))))
22398 (org-back-to-heading t)
22399 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22400 (move-marker org-agenda-restrict-begin (point))
22401 (move-marker org-agenda-restrict-end
22402 (save-excursion (org-end-of-subtree t)))
22403 (message "Locking agenda restriction to subtree"))
22404 (put 'org-agenda-files 'org-restrict
22405 (list (buffer-file-name (buffer-base-buffer))))
22406 (setq org-agenda-restrict nil)
22407 (setq org-agenda-overriding-restriction 'file)
22408 (move-marker org-agenda-restrict-begin nil)
22409 (move-marker org-agenda-restrict-end nil)
22410 (message "Locking agenda restriction to file"))
22411 (setq current-prefix-arg nil)
22412 (org-agenda-maybe-redo))
22414 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22415 "Remove the agenda restriction lock."
22416 (interactive "P")
22417 (org-detach-overlay org-agenda-restriction-lock-overlay)
22418 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22419 (setq org-agenda-overriding-restriction nil)
22420 (setq org-agenda-restrict nil)
22421 (put 'org-agenda-files 'org-restrict nil)
22422 (move-marker org-agenda-restrict-begin nil)
22423 (move-marker org-agenda-restrict-end nil)
22424 (setq current-prefix-arg nil)
22425 (message "Agenda restriction lock removed")
22426 (or noupdate (org-agenda-maybe-redo)))
22428 (defun org-agenda-maybe-redo ()
22429 "If there is any window showing the agenda view, update it."
22430 (let ((w (get-buffer-window org-agenda-buffer-name t))
22431 (w0 (selected-window)))
22432 (when w
22433 (select-window w)
22434 (org-agenda-redo)
22435 (select-window w0)
22436 (if org-agenda-overriding-restriction
22437 (message "Agenda view shifted to new %s restriction"
22438 org-agenda-overriding-restriction)
22439 (message "Agenda restriction lock removed")))))
22441 ;;; Agenda commands
22443 (defun org-agenda-check-type (error &rest types)
22444 "Check if agenda buffer is of allowed type.
22445 If ERROR is non-nil, throw an error, otherwise just return nil."
22446 (if (memq org-agenda-type types)
22448 (if error
22449 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22450 nil)))
22452 (defun org-agenda-quit ()
22453 "Exit agenda by removing the window or the buffer."
22454 (interactive)
22455 (let ((buf (current-buffer)))
22456 (if (not (one-window-p)) (delete-window))
22457 (kill-buffer buf)
22458 (org-agenda-reset-markers)
22459 (org-columns-remove-overlays))
22460 ;; Maybe restore the pre-agenda window configuration.
22461 (and org-agenda-restore-windows-after-quit
22462 (not (eq org-agenda-window-setup 'other-frame))
22463 org-pre-agenda-window-conf
22464 (set-window-configuration org-pre-agenda-window-conf)))
22466 (defun org-agenda-exit ()
22467 "Exit agenda by removing the window or the buffer.
22468 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22469 Org-mode buffers visited directly by the user will not be touched."
22470 (interactive)
22471 (org-release-buffers org-agenda-new-buffers)
22472 (setq org-agenda-new-buffers nil)
22473 (org-agenda-quit))
22475 (defun org-agenda-execute (arg)
22476 "Execute another agenda command, keeping same window.\\<global-map>
22477 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22478 (interactive "P")
22479 (let ((org-agenda-window-setup 'current-window))
22480 (org-agenda arg)))
22482 (defun org-save-all-org-buffers ()
22483 "Save all Org-mode buffers without user confirmation."
22484 (interactive)
22485 (message "Saving all Org-mode buffers...")
22486 (save-some-buffers t 'org-mode-p)
22487 (message "Saving all Org-mode buffers... done"))
22489 (defun org-agenda-redo ()
22490 "Rebuild Agenda.
22491 When this is the global TODO list, a prefix argument will be interpreted."
22492 (interactive)
22493 (let* ((org-agenda-keep-modes t)
22494 (line (org-current-line))
22495 (window-line (- line (org-current-line (window-start))))
22496 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22497 (message "Rebuilding agenda buffer...")
22498 (org-let lprops '(eval org-agenda-redo-command))
22499 (setq org-agenda-undo-list nil
22500 org-agenda-pending-undo-list nil)
22501 (message "Rebuilding agenda buffer...done")
22502 (goto-line line)
22503 (recenter window-line)))
22505 (defun org-agenda-manipulate-query-add ()
22506 "Manipulate the query by adding a search term with positive selection.
22507 Positive selection means, the term must be matched for selection of an entry."
22508 (interactive)
22509 (org-agenda-manipulate-query ?\[))
22510 (defun org-agenda-manipulate-query-subtract ()
22511 "Manipulate the query by adding a search term with negative selection.
22512 Negative selection means, term must not be matched for selection of an entry."
22513 (interactive)
22514 (org-agenda-manipulate-query ?\]))
22515 (defun org-agenda-manipulate-query-add-re ()
22516 "Manipulate the query by adding a search regexp with positive selection.
22517 Positive selection means, the regexp must match for selection of an entry."
22518 (interactive)
22519 (org-agenda-manipulate-query ?\{))
22520 (defun org-agenda-manipulate-query-subtract-re ()
22521 "Manipulate the query by adding a search regexp with negative selection.
22522 Negative selection means, regexp must not match for selection of an entry."
22523 (interactive)
22524 (org-agenda-manipulate-query ?\}))
22525 (defun org-agenda-manipulate-query (char)
22526 (cond
22527 ((eq org-agenda-type 'search)
22528 (org-add-to-string
22529 'org-agenda-query-string
22530 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22531 (?\{ . " +{}") (?\} . " -{}")))))
22532 (setq org-agenda-redo-command
22533 (list 'org-search-view
22534 (+ (length org-agenda-query-string)
22535 (if (member char '(?\{ ?\})) 0 1))
22536 org-agenda-query-string))
22537 (set-register org-agenda-query-register org-agenda-query-string)
22538 (org-agenda-redo))
22539 (t (error "Canot manipulate query for %s-type agenda buffers"
22540 org-agenda-type))))
22542 (defun org-add-to-string (var string)
22543 (set var (concat (symbol-value var) string)))
22545 (defun org-agenda-goto-date (date)
22546 "Jump to DATE in agenda."
22547 (interactive (list (org-read-date)))
22548 (org-agenda-list nil date))
22550 (defun org-agenda-goto-today ()
22551 "Go to today."
22552 (interactive)
22553 (org-agenda-check-type t 'timeline 'agenda)
22554 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22555 (cond
22556 (tdpos (goto-char tdpos))
22557 ((eq org-agenda-type 'agenda)
22558 (let* ((sd (time-to-days
22559 (time-subtract (current-time)
22560 (list 0 (* 3600 org-extend-today-until) 0))))
22561 (comp (org-agenda-compute-time-span sd org-agenda-span))
22562 (org-agenda-overriding-arguments org-agenda-last-arguments))
22563 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22564 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22565 (org-agenda-redo)
22566 (org-agenda-find-same-or-today-or-agenda)))
22567 (t (error "Cannot find today")))))
22569 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22570 (goto-char
22571 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22572 (text-property-any (point-min) (point-max) 'org-today t)
22573 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22574 (point-min))))
22576 (defun org-agenda-later (arg)
22577 "Go forward in time by thee current span.
22578 With prefix ARG, go forward that many times the current span."
22579 (interactive "p")
22580 (org-agenda-check-type t 'agenda)
22581 (let* ((span org-agenda-span)
22582 (sd org-starting-day)
22583 (greg (calendar-gregorian-from-absolute sd))
22584 (cnt (get-text-property (point) 'org-day-cnt))
22585 greg2 nd)
22586 (cond
22587 ((eq span 'day)
22588 (setq sd (+ arg sd) nd 1))
22589 ((eq span 'week)
22590 (setq sd (+ (* 7 arg) sd) nd 7))
22591 ((eq span 'month)
22592 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22593 sd (calendar-absolute-from-gregorian greg2))
22594 (setcar greg2 (1+ (car greg2)))
22595 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22596 ((eq span 'year)
22597 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22598 sd (calendar-absolute-from-gregorian greg2))
22599 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22600 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22601 (let ((org-agenda-overriding-arguments
22602 (list (car org-agenda-last-arguments) sd nd t)))
22603 (org-agenda-redo)
22604 (org-agenda-find-same-or-today-or-agenda cnt))))
22606 (defun org-agenda-earlier (arg)
22607 "Go backward in time by the current span.
22608 With prefix ARG, go backward that many times the current span."
22609 (interactive "p")
22610 (org-agenda-later (- arg)))
22612 (defun org-agenda-day-view ()
22613 "Switch to daily view for agenda."
22614 (interactive)
22615 (setq org-agenda-ndays 1)
22616 (org-agenda-change-time-span 'day))
22617 (defun org-agenda-week-view ()
22618 "Switch to daily view for agenda."
22619 (interactive)
22620 (setq org-agenda-ndays 7)
22621 (org-agenda-change-time-span 'week))
22622 (defun org-agenda-month-view ()
22623 "Switch to daily view for agenda."
22624 (interactive)
22625 (org-agenda-change-time-span 'month))
22626 (defun org-agenda-year-view ()
22627 "Switch to daily view for agenda."
22628 (interactive)
22629 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22630 (org-agenda-change-time-span 'year)
22631 (error "Abort")))
22633 (defun org-agenda-change-time-span (span)
22634 "Change the agenda view to SPAN.
22635 SPAN may be `day', `week', `month', `year'."
22636 (org-agenda-check-type t 'agenda)
22637 (if (equal org-agenda-span span)
22638 (error "Viewing span is already \"%s\"" span))
22639 (let* ((sd (or (get-text-property (point) 'day)
22640 org-starting-day))
22641 (computed (org-agenda-compute-time-span sd span))
22642 (org-agenda-overriding-arguments
22643 (list (car org-agenda-last-arguments)
22644 (car computed) (cdr computed) t)))
22645 (org-agenda-redo)
22646 (org-agenda-find-same-or-today-or-agenda))
22647 (org-agenda-set-mode-name)
22648 (message "Switched to %s view" span))
22650 (defun org-agenda-compute-time-span (sd span)
22651 "Compute starting date and number of days for agenda.
22652 SPAN may be `day', `week', `month', `year'. The return value
22653 is a cons cell with the starting date and the number of days,
22654 so that the date SD will be in that range."
22655 (let* ((greg (calendar-gregorian-from-absolute sd))
22657 (cond
22658 ((eq span 'day)
22659 (setq nd 1))
22660 ((eq span 'week)
22661 (let* ((nt (calendar-day-of-week
22662 (calendar-gregorian-from-absolute sd)))
22663 (d (if org-agenda-start-on-weekday
22664 (- nt org-agenda-start-on-weekday)
22665 0)))
22666 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22667 (setq nd 7)))
22668 ((eq span 'month)
22669 (setq sd (calendar-absolute-from-gregorian
22670 (list (car greg) 1 (nth 2 greg)))
22671 nd (- (calendar-absolute-from-gregorian
22672 (list (1+ (car greg)) 1 (nth 2 greg)))
22673 sd)))
22674 ((eq span 'year)
22675 (setq sd (calendar-absolute-from-gregorian
22676 (list 1 1 (nth 2 greg)))
22677 nd (- (calendar-absolute-from-gregorian
22678 (list 1 1 (1+ (nth 2 greg))))
22679 sd))))
22680 (cons sd nd)))
22682 ;; FIXME: does not work if user makes date format that starts with a blank
22683 (defun org-agenda-next-date-line (&optional arg)
22684 "Jump to the next line indicating a date in agenda buffer."
22685 (interactive "p")
22686 (org-agenda-check-type t 'agenda 'timeline)
22687 (beginning-of-line 1)
22688 (if (looking-at "^\\S-") (forward-char 1))
22689 (if (not (re-search-forward "^\\S-" nil t arg))
22690 (progn
22691 (backward-char 1)
22692 (error "No next date after this line in this buffer")))
22693 (goto-char (match-beginning 0)))
22695 (defun org-agenda-previous-date-line (&optional arg)
22696 "Jump to the previous line indicating a date in agenda buffer."
22697 (interactive "p")
22698 (org-agenda-check-type t 'agenda 'timeline)
22699 (beginning-of-line 1)
22700 (if (not (re-search-backward "^\\S-" nil t arg))
22701 (error "No previous date before this line in this buffer")))
22703 ;; Initialize the highlight
22704 (defvar org-hl (org-make-overlay 1 1))
22705 (org-overlay-put org-hl 'face 'highlight)
22707 (defun org-highlight (begin end &optional buffer)
22708 "Highlight a region with overlay."
22709 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22710 org-hl begin end (or buffer (current-buffer))))
22712 (defun org-unhighlight ()
22713 "Detach overlay INDEX."
22714 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22716 ;; FIXME this is currently not used.
22717 (defun org-highlight-until-next-command (beg end &optional buffer)
22718 (org-highlight beg end buffer)
22719 (add-hook 'pre-command-hook 'org-unhighlight-once))
22720 (defun org-unhighlight-once ()
22721 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22722 (org-unhighlight))
22724 (defun org-agenda-follow-mode ()
22725 "Toggle follow mode in an agenda buffer."
22726 (interactive)
22727 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22728 (org-agenda-set-mode-name)
22729 (message "Follow mode is %s"
22730 (if org-agenda-follow-mode "on" "off")))
22732 (defun org-agenda-log-mode ()
22733 "Toggle log mode in an agenda buffer."
22734 (interactive)
22735 (org-agenda-check-type t 'agenda 'timeline)
22736 (setq org-agenda-show-log (not org-agenda-show-log))
22737 (org-agenda-set-mode-name)
22738 (org-agenda-redo)
22739 (message "Log mode is %s"
22740 (if org-agenda-show-log "on" "off")))
22742 (defun org-agenda-toggle-diary ()
22743 "Toggle diary inclusion in an agenda buffer."
22744 (interactive)
22745 (org-agenda-check-type t 'agenda)
22746 (setq org-agenda-include-diary (not org-agenda-include-diary))
22747 (org-agenda-redo)
22748 (org-agenda-set-mode-name)
22749 (message "Diary inclusion turned %s"
22750 (if org-agenda-include-diary "on" "off")))
22752 (defun org-agenda-toggle-time-grid ()
22753 "Toggle time grid in an agenda buffer."
22754 (interactive)
22755 (org-agenda-check-type t 'agenda)
22756 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22757 (org-agenda-redo)
22758 (org-agenda-set-mode-name)
22759 (message "Time-grid turned %s"
22760 (if org-agenda-use-time-grid "on" "off")))
22762 (defun org-agenda-set-mode-name ()
22763 "Set the mode name to indicate all the small mode settings."
22764 (setq mode-name
22765 (concat "Org-Agenda"
22766 (if (equal org-agenda-ndays 1) " Day" "")
22767 (if (equal org-agenda-ndays 7) " Week" "")
22768 (if org-agenda-follow-mode " Follow" "")
22769 (if org-agenda-include-diary " Diary" "")
22770 (if org-agenda-use-time-grid " Grid" "")
22771 (if org-agenda-show-log " Log" "")))
22772 (force-mode-line-update))
22774 (defun org-agenda-post-command-hook ()
22775 (and (eolp) (not (bolp)) (backward-char 1))
22776 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22777 (if (and org-agenda-follow-mode
22778 (get-text-property (point) 'org-marker))
22779 (org-agenda-show)))
22781 (defun org-agenda-show-priority ()
22782 "Show the priority of the current item.
22783 This priority is composed of the main priority given with the [#A] cookies,
22784 and by additional input from the age of a schedules or deadline entry."
22785 (interactive)
22786 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22787 (message "Priority is %d" (if pri pri -1000))))
22789 (defun org-agenda-show-tags ()
22790 "Show the tags applicable to the current item."
22791 (interactive)
22792 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22793 (if tags
22794 (message "Tags are :%s:"
22795 (org-no-properties (mapconcat 'identity tags ":")))
22796 (message "No tags associated with this line"))))
22798 (defun org-agenda-goto (&optional highlight)
22799 "Go to the Org-mode file which contains the item at point."
22800 (interactive)
22801 (let* ((marker (or (get-text-property (point) 'org-marker)
22802 (org-agenda-error)))
22803 (buffer (marker-buffer marker))
22804 (pos (marker-position marker)))
22805 (switch-to-buffer-other-window buffer)
22806 (widen)
22807 (goto-char pos)
22808 (when (org-mode-p)
22809 (org-show-context 'agenda)
22810 (save-excursion
22811 (and (outline-next-heading)
22812 (org-flag-heading nil)))) ; show the next heading
22813 (recenter (/ (window-height) 2))
22814 (run-hooks 'org-agenda-after-show-hook)
22815 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22817 (defvar org-agenda-after-show-hook nil
22818 "Normal hook run after an item has been shown from the agenda.
22819 Point is in the buffer where the item originated.")
22821 (defun org-agenda-kill ()
22822 "Kill the entry or subtree belonging to the current agenda entry."
22823 (interactive)
22824 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22825 (let* ((marker (or (get-text-property (point) 'org-marker)
22826 (org-agenda-error)))
22827 (buffer (marker-buffer marker))
22828 (pos (marker-position marker))
22829 (type (get-text-property (point) 'type))
22830 dbeg dend (n 0) conf)
22831 (org-with-remote-undo buffer
22832 (with-current-buffer buffer
22833 (save-excursion
22834 (goto-char pos)
22835 (if (and (org-mode-p) (not (member type '("sexp"))))
22836 (setq dbeg (progn (org-back-to-heading t) (point))
22837 dend (org-end-of-subtree t t))
22838 (setq dbeg (point-at-bol)
22839 dend (min (point-max) (1+ (point-at-eol)))))
22840 (goto-char dbeg)
22841 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22842 (setq conf (or (eq t org-agenda-confirm-kill)
22843 (and (numberp org-agenda-confirm-kill)
22844 (> n org-agenda-confirm-kill))))
22845 (and conf
22846 (not (y-or-n-p
22847 (format "Delete entry with %d lines in buffer \"%s\"? "
22848 n (buffer-name buffer))))
22849 (error "Abort"))
22850 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22851 (with-current-buffer buffer (delete-region dbeg dend))
22852 (message "Agenda item and source killed"))))
22854 (defun org-agenda-archive ()
22855 "Kill the entry or subtree belonging to the current agenda entry."
22856 (interactive)
22857 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22858 (let* ((marker (or (get-text-property (point) 'org-marker)
22859 (org-agenda-error)))
22860 (buffer (marker-buffer marker))
22861 (pos (marker-position marker)))
22862 (org-with-remote-undo buffer
22863 (with-current-buffer buffer
22864 (if (org-mode-p)
22865 (save-excursion
22866 (goto-char pos)
22867 (org-remove-subtree-entries-from-agenda)
22868 (org-back-to-heading t)
22869 (org-archive-subtree))
22870 (error "Archiving works only in Org-mode files"))))))
22872 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22873 "Remove all lines in the agenda that correspond to a given subtree.
22874 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22875 If this information is not given, the function uses the tree at point."
22876 (let ((buf (or buf (current-buffer))) m p)
22877 (save-excursion
22878 (unless (and beg end)
22879 (org-back-to-heading t)
22880 (setq beg (point))
22881 (org-end-of-subtree t)
22882 (setq end (point)))
22883 (set-buffer (get-buffer org-agenda-buffer-name))
22884 (save-excursion
22885 (goto-char (point-max))
22886 (beginning-of-line 1)
22887 (while (not (bobp))
22888 (when (and (setq m (get-text-property (point) 'org-marker))
22889 (equal buf (marker-buffer m))
22890 (setq p (marker-position m))
22891 (>= p beg)
22892 (<= p end))
22893 (let ((inhibit-read-only t))
22894 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22895 (beginning-of-line 0))))))
22897 (defun org-agenda-open-link ()
22898 "Follow the link in the current line, if any."
22899 (interactive)
22900 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22901 (save-excursion
22902 (save-restriction
22903 (narrow-to-region (point-at-bol) (point-at-eol))
22904 (org-open-at-point))))
22906 (defun org-agenda-copy-local-variable (var)
22907 "Get a variable from a referenced buffer and install it here."
22908 (let ((m (get-text-property (point) 'org-marker)))
22909 (when (and m (buffer-live-p (marker-buffer m)))
22910 (org-set-local var (with-current-buffer (marker-buffer m)
22911 (symbol-value var))))))
22913 (defun org-agenda-switch-to (&optional delete-other-windows)
22914 "Go to the Org-mode file which contains the item at point."
22915 (interactive)
22916 (let* ((marker (or (get-text-property (point) 'org-marker)
22917 (org-agenda-error)))
22918 (buffer (marker-buffer marker))
22919 (pos (marker-position marker)))
22920 (switch-to-buffer buffer)
22921 (and delete-other-windows (delete-other-windows))
22922 (widen)
22923 (goto-char pos)
22924 (when (org-mode-p)
22925 (org-show-context 'agenda)
22926 (save-excursion
22927 (and (outline-next-heading)
22928 (org-flag-heading nil)))))) ; show the next heading
22930 (defun org-agenda-goto-mouse (ev)
22931 "Go to the Org-mode file which contains the item at the mouse click."
22932 (interactive "e")
22933 (mouse-set-point ev)
22934 (org-agenda-goto))
22936 (defun org-agenda-show ()
22937 "Display the Org-mode file which contains the item at point."
22938 (interactive)
22939 (let ((win (selected-window)))
22940 (org-agenda-goto t)
22941 (select-window win)))
22943 (defun org-agenda-recenter (arg)
22944 "Display the Org-mode file which contains the item at point and recenter."
22945 (interactive "P")
22946 (let ((win (selected-window)))
22947 (org-agenda-goto t)
22948 (recenter arg)
22949 (select-window win)))
22951 (defun org-agenda-show-mouse (ev)
22952 "Display the Org-mode file which contains the item at the mouse click."
22953 (interactive "e")
22954 (mouse-set-point ev)
22955 (org-agenda-show))
22957 (defun org-agenda-check-no-diary ()
22958 "Check if the entry is a diary link and abort if yes."
22959 (if (get-text-property (point) 'org-agenda-diary-link)
22960 (org-agenda-error)))
22962 (defun org-agenda-error ()
22963 (error "Command not allowed in this line"))
22965 (defun org-agenda-tree-to-indirect-buffer ()
22966 "Show the subtree corresponding to the current entry in an indirect buffer.
22967 This calls the command `org-tree-to-indirect-buffer' from the original
22968 Org-mode buffer.
22969 With numerical prefix arg ARG, go up to this level and then take that tree.
22970 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22971 dedicated frame)."
22972 (interactive)
22973 (org-agenda-check-no-diary)
22974 (let* ((marker (or (get-text-property (point) 'org-marker)
22975 (org-agenda-error)))
22976 (buffer (marker-buffer marker))
22977 (pos (marker-position marker)))
22978 (with-current-buffer buffer
22979 (save-excursion
22980 (goto-char pos)
22981 (call-interactively 'org-tree-to-indirect-buffer)))))
22983 (defvar org-last-heading-marker (make-marker)
22984 "Marker pointing to the headline that last changed its TODO state
22985 by a remote command from the agenda.")
22987 (defun org-agenda-todo-nextset ()
22988 "Switch TODO entry to next sequence."
22989 (interactive)
22990 (org-agenda-todo 'nextset))
22992 (defun org-agenda-todo-previousset ()
22993 "Switch TODO entry to previous sequence."
22994 (interactive)
22995 (org-agenda-todo 'previousset))
22997 (defun org-agenda-todo (&optional arg)
22998 "Cycle TODO state of line at point, also in Org-mode file.
22999 This changes the line at point, all other lines in the agenda referring to
23000 the same tree node, and the headline of the tree node in the Org-mode file."
23001 (interactive "P")
23002 (org-agenda-check-no-diary)
23003 (let* ((col (current-column))
23004 (marker (or (get-text-property (point) 'org-marker)
23005 (org-agenda-error)))
23006 (buffer (marker-buffer marker))
23007 (pos (marker-position marker))
23008 (hdmarker (get-text-property (point) 'org-hd-marker))
23009 (inhibit-read-only t)
23010 newhead)
23011 (org-with-remote-undo buffer
23012 (with-current-buffer buffer
23013 (widen)
23014 (goto-char pos)
23015 (org-show-context 'agenda)
23016 (save-excursion
23017 (and (outline-next-heading)
23018 (org-flag-heading nil))) ; show the next heading
23019 (org-todo arg)
23020 (and (bolp) (forward-char 1))
23021 (setq newhead (org-get-heading))
23022 (save-excursion
23023 (org-back-to-heading)
23024 (move-marker org-last-heading-marker (point))))
23025 (beginning-of-line 1)
23026 (save-excursion
23027 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23028 (move-to-column col))))
23030 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23031 "Change all lines in the agenda buffer which match HDMARKER.
23032 The new content of the line will be NEWHEAD (as modified by
23033 `org-format-agenda-item'). HDMARKER is checked with
23034 `equal' against all `org-hd-marker' text properties in the file.
23035 If FIXFACE is non-nil, the face of each item is modified acording to
23036 the new TODO state."
23037 (let* ((inhibit-read-only t)
23038 props m pl undone-face done-face finish new dotime cat tags)
23039 (save-excursion
23040 (goto-char (point-max))
23041 (beginning-of-line 1)
23042 (while (not finish)
23043 (setq finish (bobp))
23044 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23045 (equal m hdmarker))
23046 (setq props (text-properties-at (point))
23047 dotime (get-text-property (point) 'dotime)
23048 cat (get-text-property (point) 'org-category)
23049 tags (get-text-property (point) 'tags)
23050 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23051 pl (get-text-property (point) 'prefix-length)
23052 undone-face (get-text-property (point) 'undone-face)
23053 done-face (get-text-property (point) 'done-face))
23054 (move-to-column pl)
23055 (cond
23056 ((equal new "")
23057 (beginning-of-line 1)
23058 (and (looking-at ".*\n?") (replace-match "")))
23059 ((looking-at ".*")
23060 (replace-match new t t)
23061 (beginning-of-line 1)
23062 (add-text-properties (point-at-bol) (point-at-eol) props)
23063 (when fixface
23064 (add-text-properties
23065 (point-at-bol) (point-at-eol)
23066 (list 'face
23067 (if org-last-todo-state-is-todo
23068 undone-face done-face))))
23069 (org-agenda-highlight-todo 'line)
23070 (beginning-of-line 1))
23071 (t (error "Line update did not work"))))
23072 (beginning-of-line 0)))
23073 (org-finalize-agenda)))
23075 (defun org-agenda-align-tags (&optional line)
23076 "Align all tags in agenda items to `org-agenda-tags-column'."
23077 (let ((inhibit-read-only t) l c)
23078 (save-excursion
23079 (goto-char (if line (point-at-bol) (point-min)))
23080 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23081 (if line (point-at-eol) nil) t)
23082 (add-text-properties
23083 (match-beginning 2) (match-end 2)
23084 (list 'face (delq nil (list 'org-tag (get-text-property
23085 (match-beginning 2) 'face)))))
23086 (setq l (- (match-end 2) (match-beginning 2))
23087 c (if (< org-agenda-tags-column 0)
23088 (- (abs org-agenda-tags-column) l)
23089 org-agenda-tags-column))
23090 (delete-region (match-beginning 1) (match-end 1))
23091 (goto-char (match-beginning 1))
23092 (insert (org-add-props
23093 (make-string (max 1 (- c (current-column))) ?\ )
23094 (text-properties-at (point))))))))
23096 (defun org-agenda-priority-up ()
23097 "Increase the priority of line at point, also in Org-mode file."
23098 (interactive)
23099 (org-agenda-priority 'up))
23101 (defun org-agenda-priority-down ()
23102 "Decrease the priority of line at point, also in Org-mode file."
23103 (interactive)
23104 (org-agenda-priority 'down))
23106 (defun org-agenda-priority (&optional force-direction)
23107 "Set the priority of line at point, also in Org-mode file.
23108 This changes the line at point, all other lines in the agenda referring to
23109 the same tree node, and the headline of the tree node in the Org-mode file."
23110 (interactive)
23111 (org-agenda-check-no-diary)
23112 (let* ((marker (or (get-text-property (point) 'org-marker)
23113 (org-agenda-error)))
23114 (hdmarker (get-text-property (point) 'org-hd-marker))
23115 (buffer (marker-buffer hdmarker))
23116 (pos (marker-position hdmarker))
23117 (inhibit-read-only t)
23118 newhead)
23119 (org-with-remote-undo buffer
23120 (with-current-buffer buffer
23121 (widen)
23122 (goto-char pos)
23123 (org-show-context 'agenda)
23124 (save-excursion
23125 (and (outline-next-heading)
23126 (org-flag-heading nil))) ; show the next heading
23127 (funcall 'org-priority force-direction)
23128 (end-of-line 1)
23129 (setq newhead (org-get-heading)))
23130 (org-agenda-change-all-lines newhead hdmarker)
23131 (beginning-of-line 1))))
23133 (defun org-get-tags-at (&optional pos)
23134 "Get a list of all headline tags applicable at POS.
23135 POS defaults to point. If tags are inherited, the list contains
23136 the targets in the same sequence as the headlines appear, i.e.
23137 the tags of the current headline come last."
23138 (interactive)
23139 (let (tags lastpos)
23140 (save-excursion
23141 (save-restriction
23142 (widen)
23143 (goto-char (or pos (point)))
23144 (save-match-data
23145 (org-back-to-heading t)
23146 (condition-case nil
23147 (while (not (equal lastpos (point)))
23148 (setq lastpos (point))
23149 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23150 (setq tags (append (org-split-string
23151 (org-match-string-no-properties 1) ":")
23152 tags)))
23153 (or org-use-tag-inheritance (error ""))
23154 (org-up-heading-all 1))
23155 (error nil))))
23156 tags)))
23158 ;; FIXME: should fix the tags property of the agenda line.
23159 (defun org-agenda-set-tags ()
23160 "Set tags for the current headline."
23161 (interactive)
23162 (org-agenda-check-no-diary)
23163 (if (and (org-region-active-p) (interactive-p))
23164 (call-interactively 'org-change-tag-in-region)
23165 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23166 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23167 (org-agenda-error)))
23168 (buffer (marker-buffer hdmarker))
23169 (pos (marker-position hdmarker))
23170 (inhibit-read-only t)
23171 newhead)
23172 (org-with-remote-undo buffer
23173 (with-current-buffer buffer
23174 (widen)
23175 (goto-char pos)
23176 (save-excursion
23177 (org-show-context 'agenda))
23178 (save-excursion
23179 (and (outline-next-heading)
23180 (org-flag-heading nil))) ; show the next heading
23181 (goto-char pos)
23182 (call-interactively 'org-set-tags)
23183 (end-of-line 1)
23184 (setq newhead (org-get-heading)))
23185 (org-agenda-change-all-lines newhead hdmarker)
23186 (beginning-of-line 1)))))
23188 (defun org-agenda-toggle-archive-tag ()
23189 "Toggle the archive tag for the current entry."
23190 (interactive)
23191 (org-agenda-check-no-diary)
23192 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23193 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23194 (org-agenda-error)))
23195 (buffer (marker-buffer hdmarker))
23196 (pos (marker-position hdmarker))
23197 (inhibit-read-only t)
23198 newhead)
23199 (org-with-remote-undo buffer
23200 (with-current-buffer buffer
23201 (widen)
23202 (goto-char pos)
23203 (org-show-context 'agenda)
23204 (save-excursion
23205 (and (outline-next-heading)
23206 (org-flag-heading nil))) ; show the next heading
23207 (call-interactively 'org-toggle-archive-tag)
23208 (end-of-line 1)
23209 (setq newhead (org-get-heading)))
23210 (org-agenda-change-all-lines newhead hdmarker)
23211 (beginning-of-line 1))))
23213 (defun org-agenda-date-later (arg &optional what)
23214 "Change the date of this item to one day later."
23215 (interactive "p")
23216 (org-agenda-check-type t 'agenda 'timeline)
23217 (org-agenda-check-no-diary)
23218 (let* ((marker (or (get-text-property (point) 'org-marker)
23219 (org-agenda-error)))
23220 (buffer (marker-buffer marker))
23221 (pos (marker-position marker)))
23222 (org-with-remote-undo buffer
23223 (with-current-buffer buffer
23224 (widen)
23225 (goto-char pos)
23226 (if (not (org-at-timestamp-p))
23227 (error "Cannot find time stamp"))
23228 (org-timestamp-change arg (or what 'day)))
23229 (org-agenda-show-new-time marker org-last-changed-timestamp))
23230 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23232 (defun org-agenda-date-earlier (arg &optional what)
23233 "Change the date of this item to one day earlier."
23234 (interactive "p")
23235 (org-agenda-date-later (- arg) what))
23237 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23238 "Show new date stamp via text properties."
23239 ;; We use text properties to make this undoable
23240 (let ((inhibit-read-only t))
23241 (setq stamp (concat " " prefix " => " stamp))
23242 (save-excursion
23243 (goto-char (point-max))
23244 (while (not (bobp))
23245 (when (equal marker (get-text-property (point) 'org-marker))
23246 (move-to-column (- (window-width) (length stamp)) t)
23247 (if (featurep 'xemacs)
23248 ;; Use `duplicable' property to trigger undo recording
23249 (let ((ex (make-extent nil nil))
23250 (gl (make-glyph stamp)))
23251 (set-glyph-face gl 'secondary-selection)
23252 (set-extent-properties
23253 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23254 (insert-extent ex (1- (point)) (point-at-eol)))
23255 (add-text-properties
23256 (1- (point)) (point-at-eol)
23257 (list 'display (org-add-props stamp nil
23258 'face 'secondary-selection))))
23259 (beginning-of-line 1))
23260 (beginning-of-line 0)))))
23262 (defun org-agenda-date-prompt (arg)
23263 "Change the date of this item. Date is prompted for, with default today.
23264 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23265 be used to request time specification in the time stamp."
23266 (interactive "P")
23267 (org-agenda-check-type t 'agenda 'timeline)
23268 (org-agenda-check-no-diary)
23269 (let* ((marker (or (get-text-property (point) 'org-marker)
23270 (org-agenda-error)))
23271 (buffer (marker-buffer marker))
23272 (pos (marker-position marker)))
23273 (org-with-remote-undo buffer
23274 (with-current-buffer buffer
23275 (widen)
23276 (goto-char pos)
23277 (if (not (org-at-timestamp-p))
23278 (error "Cannot find time stamp"))
23279 (org-time-stamp arg)
23280 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23282 (defun org-agenda-schedule (arg)
23283 "Schedule the item at point."
23284 (interactive "P")
23285 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23286 (org-agenda-check-no-diary)
23287 (let* ((marker (or (get-text-property (point) 'org-marker)
23288 (org-agenda-error)))
23289 (buffer (marker-buffer marker))
23290 (pos (marker-position marker))
23291 (org-insert-labeled-timestamps-at-point nil)
23293 (message "%s" (marker-insertion-type marker)) (sit-for 3)
23294 (set-marker-insertion-type marker t)
23295 (org-with-remote-undo buffer
23296 (with-current-buffer buffer
23297 (widen)
23298 (goto-char pos)
23299 (setq ts (org-schedule arg)))
23300 (org-agenda-show-new-time marker ts "S"))
23301 (message "Item scheduled for %s" ts)))
23303 (defun org-agenda-deadline (arg)
23304 "Schedule the item at point."
23305 (interactive "P")
23306 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23307 (org-agenda-check-no-diary)
23308 (let* ((marker (or (get-text-property (point) 'org-marker)
23309 (org-agenda-error)))
23310 (buffer (marker-buffer marker))
23311 (pos (marker-position marker))
23312 (org-insert-labeled-timestamps-at-point nil)
23314 (org-with-remote-undo buffer
23315 (with-current-buffer buffer
23316 (widen)
23317 (goto-char pos)
23318 (setq ts (org-deadline arg)))
23319 (org-agenda-show-new-time marker ts "S"))
23320 (message "Deadline for this item set to %s" ts)))
23322 (defun org-get-heading (&optional no-tags)
23323 "Return the heading of the current entry, without the stars."
23324 (save-excursion
23325 (org-back-to-heading t)
23326 (if (looking-at
23327 (if no-tags
23328 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23329 "\\*+[ \t]+\\([^\r\n]*\\)"))
23330 (match-string 1) "")))
23332 (defun org-agenda-clock-in (&optional arg)
23333 "Start the clock on the currently selected item."
23334 (interactive "P")
23335 (org-agenda-check-no-diary)
23336 (let* ((marker (or (get-text-property (point) 'org-marker)
23337 (org-agenda-error)))
23338 (pos (marker-position marker)))
23339 (org-with-remote-undo (marker-buffer marker)
23340 (with-current-buffer (marker-buffer marker)
23341 (widen)
23342 (goto-char pos)
23343 (org-clock-in)))))
23345 (defun org-agenda-clock-out (&optional arg)
23346 "Stop the currently running clock."
23347 (interactive "P")
23348 (unless (marker-buffer org-clock-marker)
23349 (error "No running clock"))
23350 (org-with-remote-undo (marker-buffer org-clock-marker)
23351 (org-clock-out)))
23353 (defun org-agenda-clock-cancel (&optional arg)
23354 "Cancel the currently running clock."
23355 (interactive "P")
23356 (unless (marker-buffer org-clock-marker)
23357 (error "No running clock"))
23358 (org-with-remote-undo (marker-buffer org-clock-marker)
23359 (org-clock-cancel)))
23361 (defun org-agenda-diary-entry ()
23362 "Make a diary entry, like the `i' command from the calendar.
23363 All the standard commands work: block, weekly etc."
23364 (interactive)
23365 (org-agenda-check-type t 'agenda 'timeline)
23366 (require 'diary-lib)
23367 (let* ((char (progn
23368 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23369 (read-char-exclusive)))
23370 (cmd (cdr (assoc char
23371 '((?d . insert-diary-entry)
23372 (?w . insert-weekly-diary-entry)
23373 (?m . insert-monthly-diary-entry)
23374 (?y . insert-yearly-diary-entry)
23375 (?a . insert-anniversary-diary-entry)
23376 (?b . insert-block-diary-entry)
23377 (?c . insert-cyclic-diary-entry)))))
23378 (oldf (symbol-function 'calendar-cursor-to-date))
23379 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23380 (point (point))
23381 (mark (or (mark t) (point))))
23382 (unless cmd
23383 (error "No command associated with <%c>" char))
23384 (unless (and (get-text-property point 'day)
23385 (or (not (equal ?b char))
23386 (get-text-property mark 'day)))
23387 (error "Don't know which date to use for diary entry"))
23388 ;; We implement this by hacking the `calendar-cursor-to-date' function
23389 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23390 (let ((calendar-mark-ring
23391 (list (calendar-gregorian-from-absolute
23392 (or (get-text-property mark 'day)
23393 (get-text-property point 'day))))))
23394 (unwind-protect
23395 (progn
23396 (fset 'calendar-cursor-to-date
23397 (lambda (&optional error)
23398 (calendar-gregorian-from-absolute
23399 (get-text-property point 'day))))
23400 (call-interactively cmd))
23401 (fset 'calendar-cursor-to-date oldf)))))
23404 (defun org-agenda-execute-calendar-command (cmd)
23405 "Execute a calendar command from the agenda, with the date associated to
23406 the cursor position."
23407 (org-agenda-check-type t 'agenda 'timeline)
23408 (require 'diary-lib)
23409 (unless (get-text-property (point) 'day)
23410 (error "Don't know which date to use for calendar command"))
23411 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23412 (point (point))
23413 (date (calendar-gregorian-from-absolute
23414 (get-text-property point 'day)))
23415 ;; the following 3 vars are needed in the calendar
23416 (displayed-day (extract-calendar-day date))
23417 (displayed-month (extract-calendar-month date))
23418 (displayed-year (extract-calendar-year date)))
23419 (unwind-protect
23420 (progn
23421 (fset 'calendar-cursor-to-date
23422 (lambda (&optional error)
23423 (calendar-gregorian-from-absolute
23424 (get-text-property point 'day))))
23425 (call-interactively cmd))
23426 (fset 'calendar-cursor-to-date oldf))))
23428 (defun org-agenda-phases-of-moon ()
23429 "Display the phases of the moon for the 3 months around the cursor date."
23430 (interactive)
23431 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23433 (defun org-agenda-holidays ()
23434 "Display the holidays for the 3 months around the cursor date."
23435 (interactive)
23436 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23438 (defun org-agenda-sunrise-sunset (arg)
23439 "Display sunrise and sunset for the cursor date.
23440 Latitude and longitude can be specified with the variables
23441 `calendar-latitude' and `calendar-longitude'. When called with prefix
23442 argument, latitude and longitude will be prompted for."
23443 (interactive "P")
23444 (let ((calendar-longitude (if arg nil calendar-longitude))
23445 (calendar-latitude (if arg nil calendar-latitude))
23446 (calendar-location-name
23447 (if arg "the given coordinates" calendar-location-name)))
23448 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23450 (defun org-agenda-goto-calendar ()
23451 "Open the Emacs calendar with the date at the cursor."
23452 (interactive)
23453 (org-agenda-check-type t 'agenda 'timeline)
23454 (let* ((day (or (get-text-property (point) 'day)
23455 (error "Don't know which date to open in calendar")))
23456 (date (calendar-gregorian-from-absolute day))
23457 (calendar-move-hook nil)
23458 (view-calendar-holidays-initially nil)
23459 (view-diary-entries-initially nil))
23460 (calendar)
23461 (calendar-goto-date date)))
23463 (defun org-calendar-goto-agenda ()
23464 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23465 This is a command that has to be installed in `calendar-mode-map'."
23466 (interactive)
23467 (org-agenda-list nil (calendar-absolute-from-gregorian
23468 (calendar-cursor-to-date))
23469 nil))
23471 (defun org-agenda-convert-date ()
23472 (interactive)
23473 (org-agenda-check-type t 'agenda 'timeline)
23474 (let ((day (get-text-property (point) 'day))
23475 date s)
23476 (unless day
23477 (error "Don't know which date to convert"))
23478 (setq date (calendar-gregorian-from-absolute day))
23479 (setq s (concat
23480 "Gregorian: " (calendar-date-string date) "\n"
23481 "ISO: " (calendar-iso-date-string date) "\n"
23482 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23483 "Julian: " (calendar-julian-date-string date) "\n"
23484 "Astron. JD: " (calendar-astro-date-string date)
23485 " (Julian date number at noon UTC)\n"
23486 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23487 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23488 "French: " (calendar-french-date-string date) "\n"
23489 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23490 "Mayan: " (calendar-mayan-date-string date) "\n"
23491 "Coptic: " (calendar-coptic-date-string date) "\n"
23492 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23493 "Persian: " (calendar-persian-date-string date) "\n"
23494 "Chinese: " (calendar-chinese-date-string date) "\n"))
23495 (with-output-to-temp-buffer "*Dates*"
23496 (princ s))
23497 (if (fboundp 'fit-window-to-buffer)
23498 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23501 ;;;; Embedded LaTeX
23503 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23504 "Keymap for the minor `org-cdlatex-mode'.")
23506 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23507 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23508 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23509 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23510 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23512 (defvar org-cdlatex-texmathp-advice-is-done nil
23513 "Flag remembering if we have applied the advice to texmathp already.")
23515 (define-minor-mode org-cdlatex-mode
23516 "Toggle the minor `org-cdlatex-mode'.
23517 This mode supports entering LaTeX environment and math in LaTeX fragments
23518 in Org-mode.
23519 \\{org-cdlatex-mode-map}"
23520 nil " OCDL" nil
23521 (when org-cdlatex-mode (require 'cdlatex))
23522 (unless org-cdlatex-texmathp-advice-is-done
23523 (setq org-cdlatex-texmathp-advice-is-done t)
23524 (defadvice texmathp (around org-math-always-on activate)
23525 "Always return t in org-mode buffers.
23526 This is because we want to insert math symbols without dollars even outside
23527 the LaTeX math segments. If Orgmode thinks that point is actually inside
23528 en embedded LaTeX fragement, let texmathp do its job.
23529 \\[org-cdlatex-mode-map]"
23530 (interactive)
23531 (let (p)
23532 (cond
23533 ((not (org-mode-p)) ad-do-it)
23534 ((eq this-command 'cdlatex-math-symbol)
23535 (setq ad-return-value t
23536 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23538 (let ((p (org-inside-LaTeX-fragment-p)))
23539 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23540 (setq ad-return-value t
23541 texmathp-why '("Org-mode embedded math" . 0))
23542 (if p ad-do-it)))))))))
23544 (defun turn-on-org-cdlatex ()
23545 "Unconditionally turn on `org-cdlatex-mode'."
23546 (org-cdlatex-mode 1))
23548 (defun org-inside-LaTeX-fragment-p ()
23549 "Test if point is inside a LaTeX fragment.
23550 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23551 sequence appearing also before point.
23552 Even though the matchers for math are configurable, this function assumes
23553 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23554 delimiters are skipped when they have been removed by customization.
23555 The return value is nil, or a cons cell with the delimiter and
23556 and the position of this delimiter.
23558 This function does a reasonably good job, but can locally be fooled by
23559 for example currency specifications. For example it will assume being in
23560 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23561 fragments that are properly closed, but during editing, we have to live
23562 with the uncertainty caused by missing closing delimiters. This function
23563 looks only before point, not after."
23564 (catch 'exit
23565 (let ((pos (point))
23566 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23567 (lim (progn
23568 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23569 (point)))
23570 dd-on str (start 0) m re)
23571 (goto-char pos)
23572 (when dodollar
23573 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23574 re (nth 1 (assoc "$" org-latex-regexps)))
23575 (while (string-match re str start)
23576 (cond
23577 ((= (match-end 0) (length str))
23578 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23579 ((= (match-end 0) (- (length str) 5))
23580 (throw 'exit nil))
23581 (t (setq start (match-end 0))))))
23582 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23583 (goto-char pos)
23584 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23585 (and (match-beginning 2) (throw 'exit nil))
23586 ;; count $$
23587 (while (re-search-backward "\\$\\$" lim t)
23588 (setq dd-on (not dd-on)))
23589 (goto-char pos)
23590 (if dd-on (cons "$$" m))))))
23593 (defun org-try-cdlatex-tab ()
23594 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23595 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23596 - inside a LaTeX fragment, or
23597 - after the first word in a line, where an abbreviation expansion could
23598 insert a LaTeX environment."
23599 (when org-cdlatex-mode
23600 (cond
23601 ((save-excursion
23602 (skip-chars-backward "a-zA-Z0-9*")
23603 (skip-chars-backward " \t")
23604 (bolp))
23605 (cdlatex-tab) t)
23606 ((org-inside-LaTeX-fragment-p)
23607 (cdlatex-tab) t)
23608 (t nil))))
23610 (defun org-cdlatex-underscore-caret (&optional arg)
23611 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23612 Revert to the normal definition outside of these fragments."
23613 (interactive "P")
23614 (if (org-inside-LaTeX-fragment-p)
23615 (call-interactively 'cdlatex-sub-superscript)
23616 (let (org-cdlatex-mode)
23617 (call-interactively (key-binding (vector last-input-event))))))
23619 (defun org-cdlatex-math-modify (&optional arg)
23620 "Execute `cdlatex-math-modify' in LaTeX fragments.
23621 Revert to the normal definition outside of these fragments."
23622 (interactive "P")
23623 (if (org-inside-LaTeX-fragment-p)
23624 (call-interactively 'cdlatex-math-modify)
23625 (let (org-cdlatex-mode)
23626 (call-interactively (key-binding (vector last-input-event))))))
23628 (defvar org-latex-fragment-image-overlays nil
23629 "List of overlays carrying the images of latex fragments.")
23630 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23632 (defun org-remove-latex-fragment-image-overlays ()
23633 "Remove all overlays with LaTeX fragment images in current buffer."
23634 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23635 (setq org-latex-fragment-image-overlays nil))
23637 (defun org-preview-latex-fragment (&optional subtree)
23638 "Preview the LaTeX fragment at point, or all locally or globally.
23639 If the cursor is in a LaTeX fragment, create the image and overlay
23640 it over the source code. If there is no fragment at point, display
23641 all fragments in the current text, from one headline to the next. With
23642 prefix SUBTREE, display all fragments in the current subtree. With a
23643 double prefix `C-u C-u', or when the cursor is before the first headline,
23644 display all fragments in the buffer.
23645 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23646 (interactive "P")
23647 (org-remove-latex-fragment-image-overlays)
23648 (save-excursion
23649 (save-restriction
23650 (let (beg end at msg)
23651 (cond
23652 ((or (equal subtree '(16))
23653 (not (save-excursion
23654 (re-search-backward (concat "^" outline-regexp) nil t))))
23655 (setq beg (point-min) end (point-max)
23656 msg "Creating images for buffer...%s"))
23657 ((equal subtree '(4))
23658 (org-back-to-heading)
23659 (setq beg (point) end (org-end-of-subtree t)
23660 msg "Creating images for subtree...%s"))
23662 (if (setq at (org-inside-LaTeX-fragment-p))
23663 (goto-char (max (point-min) (- (cdr at) 2)))
23664 (org-back-to-heading))
23665 (setq beg (point) end (progn (outline-next-heading) (point))
23666 msg (if at "Creating image...%s"
23667 "Creating images for entry...%s"))))
23668 (message msg "")
23669 (narrow-to-region beg end)
23670 (goto-char beg)
23671 (org-format-latex
23672 (concat "ltxpng/" (file-name-sans-extension
23673 (file-name-nondirectory
23674 buffer-file-name)))
23675 default-directory 'overlays msg at 'forbuffer)
23676 (message msg "done. Use `C-c C-c' to remove images.")))))
23678 (defvar org-latex-regexps
23679 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23680 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23681 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23682 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23683 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23684 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23685 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23686 "Regular expressions for matching embedded LaTeX.")
23688 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23689 "Replace LaTeX fragments with links to an image, and produce images."
23690 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23691 (let* ((prefixnodir (file-name-nondirectory prefix))
23692 (absprefix (expand-file-name prefix dir))
23693 (todir (file-name-directory absprefix))
23694 (opt org-format-latex-options)
23695 (matchers (plist-get opt :matchers))
23696 (re-list org-latex-regexps)
23697 (cnt 0) txt link beg end re e checkdir
23698 m n block linkfile movefile ov)
23699 ;; Check if there are old images files with this prefix, and remove them
23700 (when (file-directory-p todir)
23701 (mapc 'delete-file
23702 (directory-files
23703 todir 'full
23704 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23705 ;; Check the different regular expressions
23706 (while (setq e (pop re-list))
23707 (setq m (car e) re (nth 1 e) n (nth 2 e)
23708 block (if (nth 3 e) "\n\n" ""))
23709 (when (member m matchers)
23710 (goto-char (point-min))
23711 (while (re-search-forward re nil t)
23712 (when (or (not at) (equal (cdr at) (match-beginning n)))
23713 (setq txt (match-string n)
23714 beg (match-beginning n) end (match-end n)
23715 cnt (1+ cnt)
23716 linkfile (format "%s_%04d.png" prefix cnt)
23717 movefile (format "%s_%04d.png" absprefix cnt)
23718 link (concat block "[[file:" linkfile "]]" block))
23719 (if msg (message msg cnt))
23720 (goto-char beg)
23721 (unless checkdir ; make sure the directory exists
23722 (setq checkdir t)
23723 (or (file-directory-p todir) (make-directory todir)))
23724 (org-create-formula-image
23725 txt movefile opt forbuffer)
23726 (if overlays
23727 (progn
23728 (setq ov (org-make-overlay beg end))
23729 (if (featurep 'xemacs)
23730 (progn
23731 (org-overlay-put ov 'invisible t)
23732 (org-overlay-put
23733 ov 'end-glyph
23734 (make-glyph (vector 'png :file movefile))))
23735 (org-overlay-put
23736 ov 'display
23737 (list 'image :type 'png :file movefile :ascent 'center)))
23738 (push ov org-latex-fragment-image-overlays)
23739 (goto-char end))
23740 (delete-region beg end)
23741 (insert link))))))))
23743 ;; This function borrows from Ganesh Swami's latex2png.el
23744 (defun org-create-formula-image (string tofile options buffer)
23745 (let* ((tmpdir (if (featurep 'xemacs)
23746 (temp-directory)
23747 temporary-file-directory))
23748 (texfilebase (make-temp-name
23749 (expand-file-name "orgtex" tmpdir)))
23750 (texfile (concat texfilebase ".tex"))
23751 (dvifile (concat texfilebase ".dvi"))
23752 (pngfile (concat texfilebase ".png"))
23753 (fnh (face-attribute 'default :height nil))
23754 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23755 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23756 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23757 "Black"))
23758 (bg (or (plist-get options (if buffer :background :html-background))
23759 "Transparent")))
23760 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23761 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23762 (with-temp-file texfile
23763 (insert org-format-latex-header
23764 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23765 (let ((dir default-directory))
23766 (condition-case nil
23767 (progn
23768 (cd tmpdir)
23769 (call-process "latex" nil nil nil texfile))
23770 (error nil))
23771 (cd dir))
23772 (if (not (file-exists-p dvifile))
23773 (progn (message "Failed to create dvi file from %s" texfile) nil)
23774 (call-process "dvipng" nil nil nil
23775 "-E" "-fg" fg "-bg" bg
23776 "-D" dpi
23777 ;;"-x" scale "-y" scale
23778 "-T" "tight"
23779 "-o" pngfile
23780 dvifile)
23781 (if (not (file-exists-p pngfile))
23782 (progn (message "Failed to create png file from %s" texfile) nil)
23783 ;; Use the requested file name and clean up
23784 (copy-file pngfile tofile 'replace)
23785 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23786 (delete-file (concat texfilebase e)))
23787 pngfile))))
23789 (defun org-dvipng-color (attr)
23790 "Return an rgb color specification for dvipng."
23791 (apply 'format "rgb %s %s %s"
23792 (mapcar 'org-normalize-color
23793 (color-values (face-attribute 'default attr nil)))))
23795 (defun org-normalize-color (value)
23796 "Return string to be used as color value for an RGB component."
23797 (format "%g" (/ value 65535.0)))
23799 ;;;; Exporting
23801 ;;; Variables, constants, and parameter plists
23803 (defconst org-level-max 20)
23805 (defvar org-export-html-preamble nil
23806 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23807 (defvar org-export-html-postamble nil
23808 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23809 (defvar org-export-html-auto-preamble t
23810 "Should default preamble be inserted? Set by publishing functions.")
23811 (defvar org-export-html-auto-postamble t
23812 "Should default postamble be inserted? Set by publishing functions.")
23813 (defvar org-current-export-file nil) ; dynamically scoped parameter
23814 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23817 (defconst org-export-plist-vars
23818 '((:language . org-export-default-language)
23819 (:customtime . org-display-custom-times)
23820 (:headline-levels . org-export-headline-levels)
23821 (:section-numbers . org-export-with-section-numbers)
23822 (:table-of-contents . org-export-with-toc)
23823 (:preserve-breaks . org-export-preserve-breaks)
23824 (:archived-trees . org-export-with-archived-trees)
23825 (:emphasize . org-export-with-emphasize)
23826 (:sub-superscript . org-export-with-sub-superscripts)
23827 (:special-strings . org-export-with-special-strings)
23828 (:footnotes . org-export-with-footnotes)
23829 (:drawers . org-export-with-drawers)
23830 (:tags . org-export-with-tags)
23831 (:TeX-macros . org-export-with-TeX-macros)
23832 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23833 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23834 (:fixed-width . org-export-with-fixed-width)
23835 (:timestamps . org-export-with-timestamps)
23836 (:author-info . org-export-author-info)
23837 (:time-stamp-file . org-export-time-stamp-file)
23838 (:tables . org-export-with-tables)
23839 (:table-auto-headline . org-export-highlight-first-table-line)
23840 (:style . org-export-html-style)
23841 (:agenda-style . org-agenda-export-html-style)
23842 (:convert-org-links . org-export-html-link-org-files-as-html)
23843 (:inline-images . org-export-html-inline-images)
23844 (:html-extension . org-export-html-extension)
23845 (:html-table-tag . org-export-html-table-tag)
23846 (:expand-quoted-html . org-export-html-expand)
23847 (:timestamp . org-export-html-with-timestamp)
23848 (:publishing-directory . org-export-publishing-directory)
23849 (:preamble . org-export-html-preamble)
23850 (:postamble . org-export-html-postamble)
23851 (:auto-preamble . org-export-html-auto-preamble)
23852 (:auto-postamble . org-export-html-auto-postamble)
23853 (:author . user-full-name)
23854 (:email . user-mail-address)))
23856 (defun org-default-export-plist ()
23857 "Return the property list with default settings for the export variables."
23858 (let ((l org-export-plist-vars) rtn e)
23859 (while (setq e (pop l))
23860 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23861 rtn))
23863 (defun org-infile-export-plist ()
23864 "Return the property list with file-local settings for export."
23865 (save-excursion
23866 (save-restriction
23867 (widen)
23868 (goto-char 0)
23869 (let ((re (org-make-options-regexp
23870 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23871 p key val text options)
23872 (while (re-search-forward re nil t)
23873 (setq key (org-match-string-no-properties 1)
23874 val (org-match-string-no-properties 2))
23875 (cond
23876 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23877 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23878 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23879 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23880 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23881 ((string-equal key "TEXT")
23882 (setq text (if text (concat text "\n" val) val)))
23883 ((string-equal key "OPTIONS") (setq options val))))
23884 (setq p (plist-put p :text text))
23885 (when options
23886 (let ((op '(("H" . :headline-levels)
23887 ("num" . :section-numbers)
23888 ("toc" . :table-of-contents)
23889 ("\\n" . :preserve-breaks)
23890 ("@" . :expand-quoted-html)
23891 (":" . :fixed-width)
23892 ("|" . :tables)
23893 ("^" . :sub-superscript)
23894 ("-" . :special-strings)
23895 ("f" . :footnotes)
23896 ("d" . :drawers)
23897 ("tags" . :tags)
23898 ("*" . :emphasize)
23899 ("TeX" . :TeX-macros)
23900 ("LaTeX" . :LaTeX-fragments)
23901 ("skip" . :skip-before-1st-heading)
23902 ("author" . :author-info)
23903 ("timestamp" . :time-stamp-file)))
23905 (while (setq o (pop op))
23906 (if (string-match (concat (regexp-quote (car o))
23907 ":\\([^ \t\n\r;,.]*\\)")
23908 options)
23909 (setq p (plist-put p (cdr o)
23910 (car (read-from-string
23911 (match-string 1 options)))))))))
23912 p))))
23914 (defun org-export-directory (type plist)
23915 (let* ((val (plist-get plist :publishing-directory))
23916 (dir (if (listp val)
23917 (or (cdr (assoc type val)) ".")
23918 val)))
23919 dir))
23921 (defun org-skip-comments (lines)
23922 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23923 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23924 (re2 "^\\(\\*+\\)[ \t\n\r]")
23925 (case-fold-search nil)
23926 rtn line level)
23927 (while (setq line (pop lines))
23928 (cond
23929 ((and (string-match re1 line)
23930 (setq level (- (match-end 1) (match-beginning 1))))
23931 ;; Beginning of a COMMENT subtree. Skip it.
23932 (while (and (setq line (pop lines))
23933 (or (not (string-match re2 line))
23934 (> (- (match-end 1) (match-beginning 1)) level))))
23935 (setq lines (cons line lines)))
23936 ((string-match "^#" line)
23937 ;; an ordinary comment line
23939 ((and org-export-table-remove-special-lines
23940 (string-match "^[ \t]*|" line)
23941 (or (string-match "^[ \t]*| *[!_^] *|" line)
23942 (and (string-match "| *<[0-9]+> *|" line)
23943 (not (string-match "| *[^ <|]" line)))))
23944 ;; a special table line that should be removed
23946 (t (setq rtn (cons line rtn)))))
23947 (nreverse rtn)))
23949 (defun org-export (&optional arg)
23950 (interactive)
23951 (let ((help "[t] insert the export option template
23952 \[v] limit export to visible part of outline tree
23954 \[a] export as ASCII
23956 \[h] export as HTML
23957 \[H] export as HTML to temporary buffer
23958 \[R] export region as HTML
23959 \[b] export as HTML and browse immediately
23960 \[x] export as XOXO
23962 \[l] export as LaTeX
23963 \[L] export as LaTeX to temporary buffer
23965 \[i] export current file as iCalendar file
23966 \[I] export all agenda files as iCalendar files
23967 \[c] export agenda files into combined iCalendar file
23969 \[F] publish current file
23970 \[P] publish current project
23971 \[X] publish... (project will be prompted for)
23972 \[A] publish all projects")
23973 (cmds
23974 '((?t . org-insert-export-options-template)
23975 (?v . org-export-visible)
23976 (?a . org-export-as-ascii)
23977 (?h . org-export-as-html)
23978 (?b . org-export-as-html-and-open)
23979 (?H . org-export-as-html-to-buffer)
23980 (?R . org-export-region-as-html)
23981 (?x . org-export-as-xoxo)
23982 (?l . org-export-as-latex)
23983 (?L . org-export-as-latex-to-buffer)
23984 (?i . org-export-icalendar-this-file)
23985 (?I . org-export-icalendar-all-agenda-files)
23986 (?c . org-export-icalendar-combine-agenda-files)
23987 (?F . org-publish-current-file)
23988 (?P . org-publish-current-project)
23989 (?X . org-publish)
23990 (?A . org-publish-all)))
23991 r1 r2 ass)
23992 (save-window-excursion
23993 (delete-other-windows)
23994 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23995 (princ help))
23996 (message "Select command: ")
23997 (setq r1 (read-char-exclusive)))
23998 (setq r2 (if (< r1 27) (+ r1 96) r1))
23999 (if (setq ass (assq r2 cmds))
24000 (call-interactively (cdr ass))
24001 (error "No command associated with key %c" r1))))
24003 (defconst org-html-entities
24004 '(("nbsp")
24005 ("iexcl")
24006 ("cent")
24007 ("pound")
24008 ("curren")
24009 ("yen")
24010 ("brvbar")
24011 ("vert" . "&#124;")
24012 ("sect")
24013 ("uml")
24014 ("copy")
24015 ("ordf")
24016 ("laquo")
24017 ("not")
24018 ("shy")
24019 ("reg")
24020 ("macr")
24021 ("deg")
24022 ("plusmn")
24023 ("sup2")
24024 ("sup3")
24025 ("acute")
24026 ("micro")
24027 ("para")
24028 ("middot")
24029 ("odot"."o")
24030 ("star"."*")
24031 ("cedil")
24032 ("sup1")
24033 ("ordm")
24034 ("raquo")
24035 ("frac14")
24036 ("frac12")
24037 ("frac34")
24038 ("iquest")
24039 ("Agrave")
24040 ("Aacute")
24041 ("Acirc")
24042 ("Atilde")
24043 ("Auml")
24044 ("Aring") ("AA"."&Aring;")
24045 ("AElig")
24046 ("Ccedil")
24047 ("Egrave")
24048 ("Eacute")
24049 ("Ecirc")
24050 ("Euml")
24051 ("Igrave")
24052 ("Iacute")
24053 ("Icirc")
24054 ("Iuml")
24055 ("ETH")
24056 ("Ntilde")
24057 ("Ograve")
24058 ("Oacute")
24059 ("Ocirc")
24060 ("Otilde")
24061 ("Ouml")
24062 ("times")
24063 ("Oslash")
24064 ("Ugrave")
24065 ("Uacute")
24066 ("Ucirc")
24067 ("Uuml")
24068 ("Yacute")
24069 ("THORN")
24070 ("szlig")
24071 ("agrave")
24072 ("aacute")
24073 ("acirc")
24074 ("atilde")
24075 ("auml")
24076 ("aring")
24077 ("aelig")
24078 ("ccedil")
24079 ("egrave")
24080 ("eacute")
24081 ("ecirc")
24082 ("euml")
24083 ("igrave")
24084 ("iacute")
24085 ("icirc")
24086 ("iuml")
24087 ("eth")
24088 ("ntilde")
24089 ("ograve")
24090 ("oacute")
24091 ("ocirc")
24092 ("otilde")
24093 ("ouml")
24094 ("divide")
24095 ("oslash")
24096 ("ugrave")
24097 ("uacute")
24098 ("ucirc")
24099 ("uuml")
24100 ("yacute")
24101 ("thorn")
24102 ("yuml")
24103 ("fnof")
24104 ("Alpha")
24105 ("Beta")
24106 ("Gamma")
24107 ("Delta")
24108 ("Epsilon")
24109 ("Zeta")
24110 ("Eta")
24111 ("Theta")
24112 ("Iota")
24113 ("Kappa")
24114 ("Lambda")
24115 ("Mu")
24116 ("Nu")
24117 ("Xi")
24118 ("Omicron")
24119 ("Pi")
24120 ("Rho")
24121 ("Sigma")
24122 ("Tau")
24123 ("Upsilon")
24124 ("Phi")
24125 ("Chi")
24126 ("Psi")
24127 ("Omega")
24128 ("alpha")
24129 ("beta")
24130 ("gamma")
24131 ("delta")
24132 ("epsilon")
24133 ("varepsilon"."&epsilon;")
24134 ("zeta")
24135 ("eta")
24136 ("theta")
24137 ("iota")
24138 ("kappa")
24139 ("lambda")
24140 ("mu")
24141 ("nu")
24142 ("xi")
24143 ("omicron")
24144 ("pi")
24145 ("rho")
24146 ("sigmaf") ("varsigma"."&sigmaf;")
24147 ("sigma")
24148 ("tau")
24149 ("upsilon")
24150 ("phi")
24151 ("chi")
24152 ("psi")
24153 ("omega")
24154 ("thetasym") ("vartheta"."&thetasym;")
24155 ("upsih")
24156 ("piv")
24157 ("bull") ("bullet"."&bull;")
24158 ("hellip") ("dots"."&hellip;")
24159 ("prime")
24160 ("Prime")
24161 ("oline")
24162 ("frasl")
24163 ("weierp")
24164 ("image")
24165 ("real")
24166 ("trade")
24167 ("alefsym")
24168 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24169 ("uarr") ("uparrow"."&uarr;")
24170 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24171 ("darr")("downarrow"."&darr;")
24172 ("harr") ("leftrightarrow"."&harr;")
24173 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24174 ("lArr") ("Leftarrow"."&lArr;")
24175 ("uArr") ("Uparrow"."&uArr;")
24176 ("rArr") ("Rightarrow"."&rArr;")
24177 ("dArr") ("Downarrow"."&dArr;")
24178 ("hArr") ("Leftrightarrow"."&hArr;")
24179 ("forall")
24180 ("part") ("partial"."&part;")
24181 ("exist") ("exists"."&exist;")
24182 ("empty") ("emptyset"."&empty;")
24183 ("nabla")
24184 ("isin") ("in"."&isin;")
24185 ("notin")
24186 ("ni")
24187 ("prod")
24188 ("sum")
24189 ("minus")
24190 ("lowast") ("ast"."&lowast;")
24191 ("radic")
24192 ("prop") ("proptp"."&prop;")
24193 ("infin") ("infty"."&infin;")
24194 ("ang") ("angle"."&ang;")
24195 ("and") ("wedge"."&and;")
24196 ("or") ("vee"."&or;")
24197 ("cap")
24198 ("cup")
24199 ("int")
24200 ("there4")
24201 ("sim")
24202 ("cong") ("simeq"."&cong;")
24203 ("asymp")("approx"."&asymp;")
24204 ("ne") ("neq"."&ne;")
24205 ("equiv")
24206 ("le")
24207 ("ge")
24208 ("sub") ("subset"."&sub;")
24209 ("sup") ("supset"."&sup;")
24210 ("nsub")
24211 ("sube")
24212 ("supe")
24213 ("oplus")
24214 ("otimes")
24215 ("perp")
24216 ("sdot") ("cdot"."&sdot;")
24217 ("lceil")
24218 ("rceil")
24219 ("lfloor")
24220 ("rfloor")
24221 ("lang")
24222 ("rang")
24223 ("loz") ("Diamond"."&loz;")
24224 ("spades") ("spadesuit"."&spades;")
24225 ("clubs") ("clubsuit"."&clubs;")
24226 ("hearts") ("diamondsuit"."&hearts;")
24227 ("diams") ("diamondsuit"."&diams;")
24228 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24229 ("quot")
24230 ("amp")
24231 ("lt")
24232 ("gt")
24233 ("OElig")
24234 ("oelig")
24235 ("Scaron")
24236 ("scaron")
24237 ("Yuml")
24238 ("circ")
24239 ("tilde")
24240 ("ensp")
24241 ("emsp")
24242 ("thinsp")
24243 ("zwnj")
24244 ("zwj")
24245 ("lrm")
24246 ("rlm")
24247 ("ndash")
24248 ("mdash")
24249 ("lsquo")
24250 ("rsquo")
24251 ("sbquo")
24252 ("ldquo")
24253 ("rdquo")
24254 ("bdquo")
24255 ("dagger")
24256 ("Dagger")
24257 ("permil")
24258 ("lsaquo")
24259 ("rsaquo")
24260 ("euro")
24262 ("arccos"."arccos")
24263 ("arcsin"."arcsin")
24264 ("arctan"."arctan")
24265 ("arg"."arg")
24266 ("cos"."cos")
24267 ("cosh"."cosh")
24268 ("cot"."cot")
24269 ("coth"."coth")
24270 ("csc"."csc")
24271 ("deg"."deg")
24272 ("det"."det")
24273 ("dim"."dim")
24274 ("exp"."exp")
24275 ("gcd"."gcd")
24276 ("hom"."hom")
24277 ("inf"."inf")
24278 ("ker"."ker")
24279 ("lg"."lg")
24280 ("lim"."lim")
24281 ("liminf"."liminf")
24282 ("limsup"."limsup")
24283 ("ln"."ln")
24284 ("log"."log")
24285 ("max"."max")
24286 ("min"."min")
24287 ("Pr"."Pr")
24288 ("sec"."sec")
24289 ("sin"."sin")
24290 ("sinh"."sinh")
24291 ("sup"."sup")
24292 ("tan"."tan")
24293 ("tanh"."tanh")
24295 "Entities for TeX->HTML translation.
24296 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24297 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24298 In that case, \"\\ent\" will be translated to \"&other;\".
24299 The list contains HTML entities for Latin-1, Greek and other symbols.
24300 It is supplemented by a number of commonly used TeX macros with appropriate
24301 translations. There is currently no way for users to extend this.")
24303 ;;; General functions for all backends
24305 (defun org-cleaned-string-for-export (string &rest parameters)
24306 "Cleanup a buffer STRING so that links can be created safely."
24307 (interactive)
24308 (let* ((re-radio (and org-target-link-regexp
24309 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24310 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24311 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24312 (re-archive (concat ":" org-archive-tag ":"))
24313 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24314 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24315 (htmlp (plist-get parameters :for-html))
24316 (asciip (plist-get parameters :for-ascii))
24317 (latexp (plist-get parameters :for-LaTeX))
24318 (commentsp (plist-get parameters :comments))
24319 (archived-trees (plist-get parameters :archived-trees))
24320 (inhibit-read-only t)
24321 (drawers org-drawers)
24322 (exp-drawers (plist-get parameters :drawers))
24323 (outline-regexp "\\*+ ")
24324 a b xx
24325 rtn p)
24326 (with-current-buffer (get-buffer-create " org-mode-tmp")
24327 (erase-buffer)
24328 (insert string)
24329 ;; Remove license-to-kill stuff
24330 (while (setq p (text-property-any (point-min) (point-max)
24331 :org-license-to-kill t))
24332 (delete-region p (next-single-property-change p :org-license-to-kill)))
24334 (let ((org-inhibit-startup t)) (org-mode))
24335 (untabify (point-min) (point-max))
24337 ;; Get rid of drawers
24338 (unless (eq t exp-drawers)
24339 (goto-char (point-min))
24340 (let ((re (concat "^[ \t]*:\\("
24341 (mapconcat
24342 'identity
24343 (org-delete-all exp-drawers
24344 (copy-sequence drawers))
24345 "\\|")
24346 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24347 (while (re-search-forward re nil t)
24348 (replace-match ""))))
24350 ;; Get the correct stuff before the first headline
24351 (when (plist-get parameters :skip-before-1st-heading)
24352 (goto-char (point-min))
24353 (when (re-search-forward "^\\*+[ \t]" nil t)
24354 (delete-region (point-min) (match-beginning 0))
24355 (goto-char (point-min))
24356 (insert "\n")))
24357 (when (plist-get parameters :add-text)
24358 (goto-char (point-min))
24359 (insert (plist-get parameters :add-text) "\n"))
24361 ;; Get rid of archived trees
24362 (when (not (eq archived-trees t))
24363 (goto-char (point-min))
24364 (while (re-search-forward re-archive nil t)
24365 (if (not (org-on-heading-p t))
24366 (org-end-of-subtree t)
24367 (beginning-of-line 1)
24368 (setq a (if archived-trees
24369 (1+ (point-at-eol)) (point))
24370 b (org-end-of-subtree t))
24371 (if (> b a) (delete-region a b)))))
24373 ;; Find targets in comments and move them out of comments,
24374 ;; but mark them as targets that should be invisible
24375 (goto-char (point-min))
24376 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24377 (replace-match "\\1(INVISIBLE)"))
24379 ;; Protect backend specific stuff, throw away the others.
24380 (let ((formatters
24381 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24382 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24383 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24384 fmt)
24385 (goto-char (point-min))
24386 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24387 (goto-char (match-end 0))
24388 (while (not (looking-at "#\\+END_EXAMPLE"))
24389 (insert ": ")
24390 (beginning-of-line 2)))
24391 (goto-char (point-min))
24392 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24393 (add-text-properties (match-beginning 0) (match-end 0)
24394 '(org-protected t)))
24395 (while formatters
24396 (setq fmt (pop formatters))
24397 (when (car fmt)
24398 (goto-char (point-min))
24399 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24400 ":[ \t]*\\(.*\\)") nil t)
24401 (replace-match "\\1" t)
24402 (add-text-properties
24403 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24404 '(org-protected t))))
24405 (goto-char (point-min))
24406 (while (re-search-forward
24407 (concat "^#\\+"
24408 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24409 (cadddr fmt) "\\>.*\n?") nil t)
24410 (if (car fmt)
24411 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24412 '(org-protected t))
24413 (delete-region (match-beginning 0) (match-end 0))))))
24415 ;; Protect quoted subtrees
24416 (goto-char (point-min))
24417 (while (re-search-forward re-quote nil t)
24418 (goto-char (match-beginning 0))
24419 (end-of-line 1)
24420 (add-text-properties (point) (org-end-of-subtree t)
24421 '(org-protected t)))
24423 ;; Protect verbatim elements
24424 (goto-char (point-min))
24425 (while (re-search-forward org-verbatim-re nil t)
24426 (add-text-properties (match-beginning 4) (match-end 4)
24427 '(org-protected t))
24428 (goto-char (1+ (match-end 4))))
24430 ;; Remove subtrees that are commented
24431 (goto-char (point-min))
24432 (while (re-search-forward re-commented nil t)
24433 (goto-char (match-beginning 0))
24434 (delete-region (point) (org-end-of-subtree t)))
24436 ;; Remove special table lines
24437 (when org-export-table-remove-special-lines
24438 (goto-char (point-min))
24439 (while (re-search-forward "^[ \t]*|" nil t)
24440 (beginning-of-line 1)
24441 (if (or (looking-at "[ \t]*| *[!_^] *|")
24442 (and (looking-at ".*?| *<[0-9]+> *|")
24443 (not (looking-at ".*?| *[^ <|]"))))
24444 (delete-region (max (point-min) (1- (point-at-bol)))
24445 (point-at-eol))
24446 (end-of-line 1))))
24448 ;; Specific LaTeX stuff
24449 (when latexp
24450 (require 'org-export-latex nil)
24451 (org-export-latex-cleaned-string))
24453 (when asciip
24454 (org-export-ascii-clean-string))
24456 ;; Specific HTML stuff
24457 (when htmlp
24458 ;; Convert LaTeX fragments to images
24459 (when (plist-get parameters :LaTeX-fragments)
24460 (org-format-latex
24461 (concat "ltxpng/" (file-name-sans-extension
24462 (file-name-nondirectory
24463 org-current-export-file)))
24464 org-current-export-dir nil "Creating LaTeX image %s"))
24465 (message "Exporting..."))
24467 ;; Remove or replace comments
24468 (goto-char (point-min))
24469 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24470 (if commentsp
24471 (progn (add-text-properties
24472 (match-beginning 0) (match-end 0) '(org-protected t))
24473 (replace-match (format commentsp (match-string 1)) t t))
24474 (replace-match "")))
24476 ;; Find matches for radio targets and turn them into internal links
24477 (goto-char (point-min))
24478 (when re-radio
24479 (while (re-search-forward re-radio nil t)
24480 (org-if-unprotected
24481 (replace-match "\\1[[\\2]]"))))
24483 ;; Find all links that contain a newline and put them into a single line
24484 (goto-char (point-min))
24485 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24486 (org-if-unprotected
24487 (replace-match "\\1 \\3")
24488 (goto-char (match-beginning 0))))
24491 ;; Normalize links: Convert angle and plain links into bracket links
24492 ;; Expand link abbreviations
24493 (goto-char (point-min))
24494 (while (re-search-forward re-plain-link nil t)
24495 (goto-char (1- (match-end 0)))
24496 (org-if-unprotected
24497 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24498 ":" (match-string 3) "]]")))
24499 ;; added 'org-link face to links
24500 (put-text-property 0 (length s) 'face 'org-link s)
24501 (replace-match s t t))))
24502 (goto-char (point-min))
24503 (while (re-search-forward re-angle-link nil t)
24504 (goto-char (1- (match-end 0)))
24505 (org-if-unprotected
24506 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24507 ":" (match-string 3) "]]")))
24508 (put-text-property 0 (length s) 'face 'org-link s)
24509 (replace-match s t t))))
24510 (goto-char (point-min))
24511 (while (re-search-forward org-bracket-link-regexp nil t)
24512 (org-if-unprotected
24513 (let* ((s (concat "[[" (setq xx (save-match-data
24514 (org-link-expand-abbrev (match-string 1))))
24516 (if (match-end 3)
24517 (match-string 2)
24518 (concat "[" xx "]"))
24519 "]")))
24520 (put-text-property 0 (length s) 'face 'org-link s)
24521 (replace-match s t t))))
24523 ;; Find multiline emphasis and put them into single line
24524 (when (plist-get parameters :emph-multiline)
24525 (goto-char (point-min))
24526 (while (re-search-forward org-emph-re nil t)
24527 (if (not (= (char-after (match-beginning 3))
24528 (char-after (match-beginning 4))))
24529 (org-if-unprotected
24530 (subst-char-in-region (match-beginning 0) (match-end 0)
24531 ?\n ?\ t)
24532 (goto-char (1- (match-end 0))))
24533 (goto-char (1+ (match-beginning 0))))))
24535 (setq rtn (buffer-string)))
24536 (kill-buffer " org-mode-tmp")
24537 rtn))
24539 (defun org-export-grab-title-from-buffer ()
24540 "Get a title for the current document, from looking at the buffer."
24541 (let ((inhibit-read-only t))
24542 (save-excursion
24543 (goto-char (point-min))
24544 (let ((end (save-excursion (outline-next-heading) (point))))
24545 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24546 ;; Mark the line so that it will not be exported as normal text.
24547 (org-unmodified
24548 (add-text-properties (match-beginning 0) (match-end 0)
24549 (list :org-license-to-kill t)))
24550 ;; Return the title string
24551 (org-trim (match-string 0)))))))
24553 (defun org-export-get-title-from-subtree ()
24554 "Return subtree title and exclude it from export."
24555 (let (title (m (mark)))
24556 (save-excursion
24557 (goto-char (region-beginning))
24558 (when (and (org-at-heading-p)
24559 (>= (org-end-of-subtree t t) (region-end)))
24560 ;; This is a subtree, we take the title from the first heading
24561 (goto-char (region-beginning))
24562 (looking-at org-todo-line-regexp)
24563 (setq title (match-string 3))
24564 (org-unmodified
24565 (add-text-properties (point) (1+ (point-at-eol))
24566 (list :org-license-to-kill t)))))
24567 title))
24569 (defun org-solidify-link-text (s &optional alist)
24570 "Take link text and make a safe target out of it."
24571 (save-match-data
24572 (let* ((rtn
24573 (mapconcat
24574 'identity
24575 (org-split-string s "[ \t\r\n]+") "--"))
24576 (a (assoc rtn alist)))
24577 (or (cdr a) rtn))))
24579 (defun org-get-min-level (lines)
24580 "Get the minimum level in LINES."
24581 (let ((re "^\\(\\*+\\) ") l min)
24582 (catch 'exit
24583 (while (setq l (pop lines))
24584 (if (string-match re l)
24585 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24586 1)))
24588 ;; Variable holding the vector with section numbers
24589 (defvar org-section-numbers (make-vector org-level-max 0))
24591 (defun org-init-section-numbers ()
24592 "Initialize the vector for the section numbers."
24593 (let* ((level -1)
24594 (numbers (nreverse (org-split-string "" "\\.")))
24595 (depth (1- (length org-section-numbers)))
24596 (i depth) number-string)
24597 (while (>= i 0)
24598 (if (> i level)
24599 (aset org-section-numbers i 0)
24600 (setq number-string (or (car numbers) "0"))
24601 (if (string-match "\\`[A-Z]\\'" number-string)
24602 (aset org-section-numbers i
24603 (- (string-to-char number-string) ?A -1))
24604 (aset org-section-numbers i (string-to-number number-string)))
24605 (pop numbers))
24606 (setq i (1- i)))))
24608 (defun org-section-number (&optional level)
24609 "Return a string with the current section number.
24610 When LEVEL is non-nil, increase section numbers on that level."
24611 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24612 (when level
24613 (when (> level -1)
24614 (aset org-section-numbers
24615 level (1+ (aref org-section-numbers level))))
24616 (setq idx (1+ level))
24617 (while (<= idx depth)
24618 (if (not (= idx 1))
24619 (aset org-section-numbers idx 0))
24620 (setq idx (1+ idx))))
24621 (setq idx 0)
24622 (while (<= idx depth)
24623 (setq n (aref org-section-numbers idx))
24624 (setq string (concat string (if (not (string= string "")) "." "")
24625 (int-to-string n)))
24626 (setq idx (1+ idx)))
24627 (save-match-data
24628 (if (string-match "\\`\\([@0]\\.\\)+" string)
24629 (setq string (replace-match "" t nil string)))
24630 (if (string-match "\\(\\.0\\)+\\'" string)
24631 (setq string (replace-match "" t nil string))))
24632 string))
24634 ;;; ASCII export
24636 (defvar org-last-level nil) ; dynamically scoped variable
24637 (defvar org-min-level nil) ; dynamically scoped variable
24638 (defvar org-levels-open nil) ; dynamically scoped parameter
24639 (defvar org-ascii-current-indentation nil) ; For communication
24641 (defun org-export-as-ascii (arg)
24642 "Export the outline as a pretty ASCII file.
24643 If there is an active region, export only the region.
24644 The prefix ARG specifies how many levels of the outline should become
24645 underlined headlines. The default is 3."
24646 (interactive "P")
24647 (setq-default org-todo-line-regexp org-todo-line-regexp)
24648 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24649 (org-infile-export-plist)))
24650 (region-p (org-region-active-p))
24651 (subtree-p
24652 (when region-p
24653 (save-excursion
24654 (goto-char (region-beginning))
24655 (and (org-at-heading-p)
24656 (>= (org-end-of-subtree t t) (region-end))))))
24657 (custom-times org-display-custom-times)
24658 (org-ascii-current-indentation '(0 . 0))
24659 (level 0) line txt
24660 (umax nil)
24661 (umax-toc nil)
24662 (case-fold-search nil)
24663 (filename (concat (file-name-as-directory
24664 (org-export-directory :ascii opt-plist))
24665 (file-name-sans-extension
24666 (or (and subtree-p
24667 (org-entry-get (region-beginning)
24668 "EXPORT_FILE_NAME" t))
24669 (file-name-nondirectory buffer-file-name)))
24670 ".txt"))
24671 (filename (if (equal (file-truename filename)
24672 (file-truename buffer-file-name))
24673 (concat filename ".txt")
24674 filename))
24675 (buffer (find-file-noselect filename))
24676 (org-levels-open (make-vector org-level-max nil))
24677 (odd org-odd-levels-only)
24678 (date (plist-get opt-plist :date))
24679 (author (plist-get opt-plist :author))
24680 (title (or (and subtree-p (org-export-get-title-from-subtree))
24681 (plist-get opt-plist :title)
24682 (and (not
24683 (plist-get opt-plist :skip-before-1st-heading))
24684 (org-export-grab-title-from-buffer))
24685 (file-name-sans-extension
24686 (file-name-nondirectory buffer-file-name))))
24687 (email (plist-get opt-plist :email))
24688 (language (plist-get opt-plist :language))
24689 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24690 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24691 (todo nil)
24692 (lang-words nil)
24693 (region
24694 (buffer-substring
24695 (if (org-region-active-p) (region-beginning) (point-min))
24696 (if (org-region-active-p) (region-end) (point-max))))
24697 (lines (org-split-string
24698 (org-cleaned-string-for-export
24699 region
24700 :for-ascii t
24701 :skip-before-1st-heading
24702 (plist-get opt-plist :skip-before-1st-heading)
24703 :drawers (plist-get opt-plist :drawers)
24704 :verbatim-multiline t
24705 :archived-trees
24706 (plist-get opt-plist :archived-trees)
24707 :add-text (plist-get opt-plist :text))
24708 "\n"))
24709 thetoc have-headings first-heading-pos
24710 table-open table-buffer)
24712 (let ((inhibit-read-only t))
24713 (org-unmodified
24714 (remove-text-properties (point-min) (point-max)
24715 '(:org-license-to-kill t))))
24717 (setq org-min-level (org-get-min-level lines))
24718 (setq org-last-level org-min-level)
24719 (org-init-section-numbers)
24721 (find-file-noselect filename)
24723 (setq lang-words (or (assoc language org-export-language-setup)
24724 (assoc "en" org-export-language-setup)))
24725 (switch-to-buffer-other-window buffer)
24726 (erase-buffer)
24727 (fundamental-mode)
24728 ;; create local variables for all options, to make sure all called
24729 ;; functions get the correct information
24730 (mapc (lambda (x)
24731 (set (make-local-variable (cdr x))
24732 (plist-get opt-plist (car x))))
24733 org-export-plist-vars)
24734 (org-set-local 'org-odd-levels-only odd)
24735 (setq umax (if arg (prefix-numeric-value arg)
24736 org-export-headline-levels))
24737 (setq umax-toc (if (integerp org-export-with-toc)
24738 (min org-export-with-toc umax)
24739 umax))
24741 ;; File header
24742 (if title (org-insert-centered title ?=))
24743 (insert "\n")
24744 (if (and (or author email)
24745 org-export-author-info)
24746 (insert (concat (nth 1 lang-words) ": " (or author "")
24747 (if email (concat " <" email ">") "")
24748 "\n")))
24750 (cond
24751 ((and date (string-match "%" date))
24752 (setq date (format-time-string date (current-time))))
24753 (date)
24754 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24756 (if (and date org-export-time-stamp-file)
24757 (insert (concat (nth 2 lang-words) ": " date"\n")))
24759 (insert "\n\n")
24761 (if org-export-with-toc
24762 (progn
24763 (push (concat (nth 3 lang-words) "\n") thetoc)
24764 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24765 (mapc '(lambda (line)
24766 (if (string-match org-todo-line-regexp
24767 line)
24768 ;; This is a headline
24769 (progn
24770 (setq have-headings t)
24771 (setq level (- (match-end 1) (match-beginning 1))
24772 level (org-tr-level level)
24773 txt (match-string 3 line)
24774 todo
24775 (or (and org-export-mark-todo-in-toc
24776 (match-beginning 2)
24777 (not (member (match-string 2 line)
24778 org-done-keywords)))
24779 ; TODO, not DONE
24780 (and org-export-mark-todo-in-toc
24781 (= level umax-toc)
24782 (org-search-todo-below
24783 line lines level))))
24784 (setq txt (org-html-expand-for-ascii txt))
24786 (while (string-match org-bracket-link-regexp txt)
24787 (setq txt
24788 (replace-match
24789 (match-string (if (match-end 2) 3 1) txt)
24790 t t txt)))
24792 (if (and (memq org-export-with-tags '(not-in-toc nil))
24793 (string-match
24794 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24795 txt))
24796 (setq txt (replace-match "" t t txt)))
24797 (if (string-match quote-re0 txt)
24798 (setq txt (replace-match "" t t txt)))
24800 (if org-export-with-section-numbers
24801 (setq txt (concat (org-section-number level)
24802 " " txt)))
24803 (if (<= level umax-toc)
24804 (progn
24805 (push
24806 (concat
24807 (make-string
24808 (* (max 0 (- level org-min-level)) 4) ?\ )
24809 (format (if todo "%s (*)\n" "%s\n") txt))
24810 thetoc)
24811 (setq org-last-level level))
24812 ))))
24813 lines)
24814 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24816 (org-init-section-numbers)
24817 (while (setq line (pop lines))
24818 ;; Remove the quoted HTML tags.
24819 (setq line (org-html-expand-for-ascii line))
24820 ;; Remove targets
24821 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24822 (setq line (replace-match "" t t line)))
24823 ;; Replace internal links
24824 (while (string-match org-bracket-link-regexp line)
24825 (setq line (replace-match
24826 (if (match-end 3) "[\\3]" "[\\1]")
24827 t nil line)))
24828 (when custom-times
24829 (setq line (org-translate-time line)))
24830 (cond
24831 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24832 ;; a Headline
24833 (setq first-heading-pos (or first-heading-pos (point)))
24834 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24835 txt (match-string 2 line))
24836 (org-ascii-level-start level txt umax lines))
24838 ((and org-export-with-tables
24839 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24840 (if (not table-open)
24841 ;; New table starts
24842 (setq table-open t table-buffer nil))
24843 ;; Accumulate lines
24844 (setq table-buffer (cons line table-buffer))
24845 (when (or (not lines)
24846 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24847 (car lines))))
24848 (setq table-open nil
24849 table-buffer (nreverse table-buffer))
24850 (insert (mapconcat
24851 (lambda (x)
24852 (org-fix-indentation x org-ascii-current-indentation))
24853 (org-format-table-ascii table-buffer)
24854 "\n") "\n")))
24856 (setq line (org-fix-indentation line org-ascii-current-indentation))
24857 (if (and org-export-with-fixed-width
24858 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24859 (setq line (replace-match "\\1" nil nil line)))
24860 (insert line "\n"))))
24862 (normal-mode)
24864 ;; insert the table of contents
24865 (when thetoc
24866 (goto-char (point-min))
24867 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24868 (progn
24869 (goto-char (match-beginning 0))
24870 (replace-match ""))
24871 (goto-char first-heading-pos))
24872 (mapc 'insert thetoc)
24873 (or (looking-at "[ \t]*\n[ \t]*\n")
24874 (insert "\n\n")))
24876 ;; Convert whitespace place holders
24877 (goto-char (point-min))
24878 (let (beg end)
24879 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24880 (setq end (next-single-property-change beg 'org-whitespace))
24881 (goto-char beg)
24882 (delete-region beg end)
24883 (insert (make-string (- end beg) ?\ ))))
24885 (save-buffer)
24886 ;; remove display and invisible chars
24887 (let (beg end)
24888 (goto-char (point-min))
24889 (while (setq beg (next-single-property-change (point) 'display))
24890 (setq end (next-single-property-change beg 'display))
24891 (delete-region beg end)
24892 (goto-char beg)
24893 (insert "=>"))
24894 (goto-char (point-min))
24895 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24896 (setq end (next-single-property-change beg 'org-cwidth))
24897 (delete-region beg end)
24898 (goto-char beg)))
24899 (goto-char (point-min))))
24901 (defun org-export-ascii-clean-string ()
24902 "Do extra work for ASCII export"
24903 (goto-char (point-min))
24904 (while (re-search-forward org-verbatim-re nil t)
24905 (goto-char (match-end 2))
24906 (backward-delete-char 1) (insert "'")
24907 (goto-char (match-beginning 2))
24908 (delete-char 1) (insert "`")
24909 (goto-char (match-end 2))))
24911 (defun org-search-todo-below (line lines level)
24912 "Search the subtree below LINE for any TODO entries."
24913 (let ((rest (cdr (memq line lines)))
24914 (re org-todo-line-regexp)
24915 line lv todo)
24916 (catch 'exit
24917 (while (setq line (pop rest))
24918 (if (string-match re line)
24919 (progn
24920 (setq lv (- (match-end 1) (match-beginning 1))
24921 todo (and (match-beginning 2)
24922 (not (member (match-string 2 line)
24923 org-done-keywords))))
24924 ; TODO, not DONE
24925 (if (<= lv level) (throw 'exit nil))
24926 (if todo (throw 'exit t))))))))
24928 (defun org-html-expand-for-ascii (line)
24929 "Handle quoted HTML for ASCII export."
24930 (if org-export-html-expand
24931 (while (string-match "@<[^<>\n]*>" line)
24932 ;; We just remove the tags for now.
24933 (setq line (replace-match "" nil nil line))))
24934 line)
24936 (defun org-insert-centered (s &optional underline)
24937 "Insert the string S centered and underline it with character UNDERLINE."
24938 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24939 (insert (make-string ind ?\ ) s "\n")
24940 (if underline
24941 (insert (make-string ind ?\ )
24942 (make-string (string-width s) underline)
24943 "\n"))))
24945 (defun org-ascii-level-start (level title umax &optional lines)
24946 "Insert a new level in ASCII export."
24947 (let (char (n (- level umax 1)) (ind 0))
24948 (if (> level umax)
24949 (progn
24950 (insert (make-string (* 2 n) ?\ )
24951 (char-to-string (nth (% n (length org-export-ascii-bullets))
24952 org-export-ascii-bullets))
24953 " " title "\n")
24954 ;; find the indentation of the next non-empty line
24955 (catch 'stop
24956 (while lines
24957 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24958 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24959 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24960 (pop lines)))
24961 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24962 (if (or (not (equal (char-before) ?\n))
24963 (not (equal (char-before (1- (point))) ?\n)))
24964 (insert "\n"))
24965 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24966 (unless org-export-with-tags
24967 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24968 (setq title (replace-match "" t t title))))
24969 (if org-export-with-section-numbers
24970 (setq title (concat (org-section-number level) " " title)))
24971 (insert title "\n" (make-string (string-width title) char) "\n")
24972 (setq org-ascii-current-indentation '(0 . 0)))))
24974 (defun org-export-visible (type arg)
24975 "Create a copy of the visible part of the current buffer, and export it.
24976 The copy is created in a temporary buffer and removed after use.
24977 TYPE is the final key (as a string) that also select the export command in
24978 the `C-c C-e' export dispatcher.
24979 As a special case, if the you type SPC at the prompt, the temporary
24980 org-mode file will not be removed but presented to you so that you can
24981 continue to use it. The prefix arg ARG is passed through to the exporting
24982 command."
24983 (interactive
24984 (list (progn
24985 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24986 (read-char-exclusive))
24987 current-prefix-arg))
24988 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24989 (error "Invalid export key"))
24990 (let* ((binding (cdr (assoc type
24991 '((?a . org-export-as-ascii)
24992 (?\C-a . org-export-as-ascii)
24993 (?b . org-export-as-html-and-open)
24994 (?\C-b . org-export-as-html-and-open)
24995 (?h . org-export-as-html)
24996 (?H . org-export-as-html-to-buffer)
24997 (?R . org-export-region-as-html)
24998 (?x . org-export-as-xoxo)))))
24999 (keepp (equal type ?\ ))
25000 (file buffer-file-name)
25001 (buffer (get-buffer-create "*Org Export Visible*"))
25002 s e)
25003 ;; Need to hack the drawers here.
25004 (save-excursion
25005 (goto-char (point-min))
25006 (while (re-search-forward org-drawer-regexp nil t)
25007 (goto-char (match-beginning 1))
25008 (or (org-invisible-p) (org-flag-drawer nil))))
25009 (with-current-buffer buffer (erase-buffer))
25010 (save-excursion
25011 (setq s (goto-char (point-min)))
25012 (while (not (= (point) (point-max)))
25013 (goto-char (org-find-invisible))
25014 (append-to-buffer buffer s (point))
25015 (setq s (goto-char (org-find-visible))))
25016 (org-cycle-hide-drawers 'all)
25017 (goto-char (point-min))
25018 (unless keepp
25019 ;; Copy all comment lines to the end, to make sure #+ settings are
25020 ;; still available for the second export step. Kind of a hack, but
25021 ;; does do the trick.
25022 (if (looking-at "#[^\r\n]*")
25023 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25024 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25025 (append-to-buffer buffer (1+ (match-beginning 0))
25026 (min (point-max) (1+ (match-end 0))))))
25027 (set-buffer buffer)
25028 (let ((buffer-file-name file)
25029 (org-inhibit-startup t))
25030 (org-mode)
25031 (show-all)
25032 (unless keepp (funcall binding arg))))
25033 (if (not keepp)
25034 (kill-buffer buffer)
25035 (switch-to-buffer-other-window buffer)
25036 (goto-char (point-min)))))
25038 (defun org-find-visible ()
25039 (let ((s (point)))
25040 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25041 (get-char-property s 'invisible)))
25043 (defun org-find-invisible ()
25044 (let ((s (point)))
25045 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25046 (not (get-char-property s 'invisible))))
25049 ;;; HTML export
25051 (defun org-get-current-options ()
25052 "Return a string with current options as keyword options.
25053 Does include HTML export options as well as TODO and CATEGORY stuff."
25054 (format
25055 "#+TITLE: %s
25056 #+AUTHOR: %s
25057 #+EMAIL: %s
25058 #+LANGUAGE: %s
25059 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25060 #+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
25061 #+CATEGORY: %s
25062 #+SEQ_TODO: %s
25063 #+TYP_TODO: %s
25064 #+PRIORITIES: %c %c %c
25065 #+DRAWERS: %s
25066 #+STARTUP: %s %s %s %s %s
25067 #+TAGS: %s
25068 #+ARCHIVE: %s
25069 #+LINK: %s
25071 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25072 org-export-headline-levels
25073 org-export-with-section-numbers
25074 org-export-with-toc
25075 org-export-preserve-breaks
25076 org-export-html-expand
25077 org-export-with-fixed-width
25078 org-export-with-tables
25079 org-export-with-sub-superscripts
25080 org-export-with-special-strings
25081 org-export-with-footnotes
25082 org-export-with-emphasize
25083 org-export-with-TeX-macros
25084 org-export-with-LaTeX-fragments
25085 org-export-skip-text-before-1st-heading
25086 org-export-with-drawers
25087 org-export-with-tags
25088 (file-name-nondirectory buffer-file-name)
25089 "TODO FEEDBACK VERIFY DONE"
25090 "Me Jason Marie DONE"
25091 org-highest-priority org-lowest-priority org-default-priority
25092 (mapconcat 'identity org-drawers " ")
25093 (cdr (assoc org-startup-folded
25094 '((nil . "showall") (t . "overview") (content . "content"))))
25095 (if org-odd-levels-only "odd" "oddeven")
25096 (if org-hide-leading-stars "hidestars" "showstars")
25097 (if org-startup-align-all-tables "align" "noalign")
25098 (cond ((eq org-log-done t) "logdone")
25099 ((equal org-log-done 'note) "lognotedone")
25100 ((not org-log-done) "nologdone"))
25101 (or (mapconcat (lambda (x)
25102 (cond
25103 ((equal '(:startgroup) x) "{")
25104 ((equal '(:endgroup) x) "}")
25105 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25106 (t (car x))))
25107 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25108 org-archive-location
25109 "org file:~/org/%s.org"
25112 (defun org-insert-export-options-template ()
25113 "Insert into the buffer a template with information for exporting."
25114 (interactive)
25115 (if (not (bolp)) (newline))
25116 (let ((s (org-get-current-options)))
25117 (and (string-match "#\\+CATEGORY" s)
25118 (setq s (substring s 0 (match-beginning 0))))
25119 (insert s)))
25121 (defun org-toggle-fixed-width-section (arg)
25122 "Toggle the fixed-width export.
25123 If there is no active region, the QUOTE keyword at the current headline is
25124 inserted or removed. When present, it causes the text between this headline
25125 and the next to be exported as fixed-width text, and unmodified.
25126 If there is an active region, this command adds or removes a colon as the
25127 first character of this line. If the first character of a line is a colon,
25128 this line is also exported in fixed-width font."
25129 (interactive "P")
25130 (let* ((cc 0)
25131 (regionp (org-region-active-p))
25132 (beg (if regionp (region-beginning) (point)))
25133 (end (if regionp (region-end)))
25134 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25135 (case-fold-search nil)
25136 (re "[ \t]*\\(:\\)")
25137 off)
25138 (if regionp
25139 (save-excursion
25140 (goto-char beg)
25141 (setq cc (current-column))
25142 (beginning-of-line 1)
25143 (setq off (looking-at re))
25144 (while (> nlines 0)
25145 (setq nlines (1- nlines))
25146 (beginning-of-line 1)
25147 (cond
25148 (arg
25149 (move-to-column cc t)
25150 (insert ":\n")
25151 (forward-line -1))
25152 ((and off (looking-at re))
25153 (replace-match "" t t nil 1))
25154 ((not off) (move-to-column cc t) (insert ":")))
25155 (forward-line 1)))
25156 (save-excursion
25157 (org-back-to-heading)
25158 (if (looking-at (concat outline-regexp
25159 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25160 (replace-match "" t t nil 1)
25161 (if (looking-at outline-regexp)
25162 (progn
25163 (goto-char (match-end 0))
25164 (insert org-quote-string " "))))))))
25166 (defun org-export-as-html-and-open (arg)
25167 "Export the outline as HTML and immediately open it with a browser.
25168 If there is an active region, export only the region.
25169 The prefix ARG specifies how many levels of the outline should become
25170 headlines. The default is 3. Lower levels will become bulleted lists."
25171 (interactive "P")
25172 (org-export-as-html arg 'hidden)
25173 (org-open-file buffer-file-name))
25175 (defun org-export-as-html-batch ()
25176 "Call `org-export-as-html', may be used in batch processing as
25177 emacs --batch
25178 --load=$HOME/lib/emacs/org.el
25179 --eval \"(setq org-export-headline-levels 2)\"
25180 --visit=MyFile --funcall org-export-as-html-batch"
25181 (org-export-as-html org-export-headline-levels 'hidden))
25183 (defun org-export-as-html-to-buffer (arg)
25184 "Call `org-exort-as-html` with output to a temporary buffer.
25185 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25186 (interactive "P")
25187 (org-export-as-html arg nil nil "*Org HTML Export*")
25188 (switch-to-buffer-other-window "*Org HTML Export*"))
25190 (defun org-replace-region-by-html (beg end)
25191 "Assume the current region has org-mode syntax, and convert it to HTML.
25192 This can be used in any buffer. For example, you could write an
25193 itemized list in org-mode syntax in an HTML buffer and then use this
25194 command to convert it."
25195 (interactive "r")
25196 (let (reg html buf pop-up-frames)
25197 (save-window-excursion
25198 (if (org-mode-p)
25199 (setq html (org-export-region-as-html
25200 beg end t 'string))
25201 (setq reg (buffer-substring beg end)
25202 buf (get-buffer-create "*Org tmp*"))
25203 (with-current-buffer buf
25204 (erase-buffer)
25205 (insert reg)
25206 (org-mode)
25207 (setq html (org-export-region-as-html
25208 (point-min) (point-max) t 'string)))
25209 (kill-buffer buf)))
25210 (delete-region beg end)
25211 (insert html)))
25213 (defun org-export-region-as-html (beg end &optional body-only buffer)
25214 "Convert region from BEG to END in org-mode buffer to HTML.
25215 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25216 contents, and only produce the region of converted text, useful for
25217 cut-and-paste operations.
25218 If BUFFER is a buffer or a string, use/create that buffer as a target
25219 of the converted HTML. If BUFFER is the symbol `string', return the
25220 produced HTML as a string and leave not buffer behind. For example,
25221 a Lisp program could call this function in the following way:
25223 (setq html (org-export-region-as-html beg end t 'string))
25225 When called interactively, the output buffer is selected, and shown
25226 in a window. A non-interactive call will only retunr the buffer."
25227 (interactive "r\nP")
25228 (when (interactive-p)
25229 (setq buffer "*Org HTML Export*"))
25230 (let ((transient-mark-mode t) (zmacs-regions t)
25231 rtn)
25232 (goto-char end)
25233 (set-mark (point)) ;; to activate the region
25234 (goto-char beg)
25235 (setq rtn (org-export-as-html
25236 nil nil nil
25237 buffer body-only))
25238 (if (fboundp 'deactivate-mark) (deactivate-mark))
25239 (if (and (interactive-p) (bufferp rtn))
25240 (switch-to-buffer-other-window rtn)
25241 rtn)))
25243 (defvar html-table-tag nil) ; dynamically scoped into this.
25244 (defun org-export-as-html (arg &optional hidden ext-plist
25245 to-buffer body-only pub-dir)
25246 "Export the outline as a pretty HTML file.
25247 If there is an active region, export only the region. The prefix
25248 ARG specifies how many levels of the outline should become
25249 headlines. The default is 3. Lower levels will become bulleted
25250 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25251 EXT-PLIST is a property list with external parameters overriding
25252 org-mode's default settings, but still inferior to file-local
25253 settings. When TO-BUFFER is non-nil, create a buffer with that
25254 name and export to that buffer. If TO-BUFFER is the symbol
25255 `string', don't leave any buffer behind but just return the
25256 resulting HTML as a string. When BODY-ONLY is set, don't produce
25257 the file header and footer, simply return the content of
25258 <body>...</body>, without even the body tags themselves. When
25259 PUB-DIR is set, use this as the publishing directory."
25260 (interactive "P")
25262 ;; Make sure we have a file name when we need it.
25263 (when (and (not (or to-buffer body-only))
25264 (not buffer-file-name))
25265 (if (buffer-base-buffer)
25266 (org-set-local 'buffer-file-name
25267 (with-current-buffer (buffer-base-buffer)
25268 buffer-file-name))
25269 (error "Need a file name to be able to export.")))
25271 (message "Exporting...")
25272 (setq-default org-todo-line-regexp org-todo-line-regexp)
25273 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25274 (setq-default org-done-keywords org-done-keywords)
25275 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25276 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25277 ext-plist
25278 (org-infile-export-plist)))
25280 (style (plist-get opt-plist :style))
25281 (html-extension (plist-get opt-plist :html-extension))
25282 (link-validate (plist-get opt-plist :link-validation-function))
25283 valid thetoc have-headings first-heading-pos
25284 (odd org-odd-levels-only)
25285 (region-p (org-region-active-p))
25286 (subtree-p
25287 (when region-p
25288 (save-excursion
25289 (goto-char (region-beginning))
25290 (and (org-at-heading-p)
25291 (>= (org-end-of-subtree t t) (region-end))))))
25292 ;; The following two are dynamically scoped into other
25293 ;; routines below.
25294 (org-current-export-dir
25295 (or pub-dir (org-export-directory :html opt-plist)))
25296 (org-current-export-file buffer-file-name)
25297 (level 0) (line "") (origline "") txt todo
25298 (umax nil)
25299 (umax-toc nil)
25300 (filename (if to-buffer nil
25301 (expand-file-name
25302 (concat
25303 (file-name-sans-extension
25304 (or (and subtree-p
25305 (org-entry-get (region-beginning)
25306 "EXPORT_FILE_NAME" t))
25307 (file-name-nondirectory buffer-file-name)))
25308 "." html-extension)
25309 (file-name-as-directory
25310 (or pub-dir (org-export-directory :html opt-plist))))))
25311 (current-dir (if buffer-file-name
25312 (file-name-directory buffer-file-name)
25313 default-directory))
25314 (buffer (if to-buffer
25315 (cond
25316 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25317 (t (get-buffer-create to-buffer)))
25318 (find-file-noselect filename)))
25319 (org-levels-open (make-vector org-level-max nil))
25320 (date (plist-get opt-plist :date))
25321 (author (plist-get opt-plist :author))
25322 (title (or (and subtree-p (org-export-get-title-from-subtree))
25323 (plist-get opt-plist :title)
25324 (and (not
25325 (plist-get opt-plist :skip-before-1st-heading))
25326 (org-export-grab-title-from-buffer))
25327 (and buffer-file-name
25328 (file-name-sans-extension
25329 (file-name-nondirectory buffer-file-name)))
25330 "UNTITLED"))
25331 (html-table-tag (plist-get opt-plist :html-table-tag))
25332 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25333 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25334 (inquote nil)
25335 (infixed nil)
25336 (in-local-list nil)
25337 (local-list-num nil)
25338 (local-list-indent nil)
25339 (llt org-plain-list-ordered-item-terminator)
25340 (email (plist-get opt-plist :email))
25341 (language (plist-get opt-plist :language))
25342 (lang-words nil)
25343 (target-alist nil) tg
25344 (head-count 0) cnt
25345 (start 0)
25346 (coding-system (and (boundp 'buffer-file-coding-system)
25347 buffer-file-coding-system))
25348 (coding-system-for-write (or org-export-html-coding-system
25349 coding-system))
25350 (save-buffer-coding-system (or org-export-html-coding-system
25351 coding-system))
25352 (charset (and coding-system-for-write
25353 (fboundp 'coding-system-get)
25354 (coding-system-get coding-system-for-write
25355 'mime-charset)))
25356 (region
25357 (buffer-substring
25358 (if region-p (region-beginning) (point-min))
25359 (if region-p (region-end) (point-max))))
25360 (lines
25361 (org-split-string
25362 (org-cleaned-string-for-export
25363 region
25364 :emph-multiline t
25365 :for-html t
25366 :skip-before-1st-heading
25367 (plist-get opt-plist :skip-before-1st-heading)
25368 :drawers (plist-get opt-plist :drawers)
25369 :archived-trees
25370 (plist-get opt-plist :archived-trees)
25371 :add-text
25372 (plist-get opt-plist :text)
25373 :LaTeX-fragments
25374 (plist-get opt-plist :LaTeX-fragments))
25375 "[\r\n]"))
25376 table-open type
25377 table-buffer table-orig-buffer
25378 ind start-is-num starter didclose
25379 rpl path desc descp desc1 desc2 link
25382 (let ((inhibit-read-only t))
25383 (org-unmodified
25384 (remove-text-properties (point-min) (point-max)
25385 '(:org-license-to-kill t))))
25387 (message "Exporting...")
25389 (setq org-min-level (org-get-min-level lines))
25390 (setq org-last-level org-min-level)
25391 (org-init-section-numbers)
25393 (cond
25394 ((and date (string-match "%" date))
25395 (setq date (format-time-string date (current-time))))
25396 (date)
25397 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25399 ;; Get the language-dependent settings
25400 (setq lang-words (or (assoc language org-export-language-setup)
25401 (assoc "en" org-export-language-setup)))
25403 ;; Switch to the output buffer
25404 (set-buffer buffer)
25405 (let ((inhibit-read-only t)) (erase-buffer))
25406 (fundamental-mode)
25408 (and (fboundp 'set-buffer-file-coding-system)
25409 (set-buffer-file-coding-system coding-system-for-write))
25411 (let ((case-fold-search nil)
25412 (org-odd-levels-only odd))
25413 ;; create local variables for all options, to make sure all called
25414 ;; functions get the correct information
25415 (mapc (lambda (x)
25416 (set (make-local-variable (cdr x))
25417 (plist-get opt-plist (car x))))
25418 org-export-plist-vars)
25419 (setq umax (if arg (prefix-numeric-value arg)
25420 org-export-headline-levels))
25421 (setq umax-toc (if (integerp org-export-with-toc)
25422 (min org-export-with-toc umax)
25423 umax))
25424 (unless body-only
25425 ;; File header
25426 (insert (format
25427 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25428 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25429 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25430 lang=\"%s\" xml:lang=\"%s\">
25431 <head>
25432 <title>%s</title>
25433 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25434 <meta name=\"generator\" content=\"Org-mode\"/>
25435 <meta name=\"generated\" content=\"%s\"/>
25436 <meta name=\"author\" content=\"%s\"/>
25438 </head><body>
25440 language language (org-html-expand title)
25441 (or charset "iso-8859-1") date author style))
25443 (insert (or (plist-get opt-plist :preamble) ""))
25445 (when (plist-get opt-plist :auto-preamble)
25446 (if title (insert (format org-export-html-title-format
25447 (org-html-expand title))))))
25449 (if (and org-export-with-toc (not body-only))
25450 (progn
25451 (push (format "<h%d>%s</h%d>\n"
25452 org-export-html-toplevel-hlevel
25453 (nth 3 lang-words)
25454 org-export-html-toplevel-hlevel)
25455 thetoc)
25456 (push "<ul>\n<li>" thetoc)
25457 (setq lines
25458 (mapcar '(lambda (line)
25459 (if (string-match org-todo-line-regexp line)
25460 ;; This is a headline
25461 (progn
25462 (setq have-headings t)
25463 (setq level (- (match-end 1) (match-beginning 1))
25464 level (org-tr-level level)
25465 txt (save-match-data
25466 (org-html-expand
25467 (org-export-cleanup-toc-line
25468 (match-string 3 line))))
25469 todo
25470 (or (and org-export-mark-todo-in-toc
25471 (match-beginning 2)
25472 (not (member (match-string 2 line)
25473 org-done-keywords)))
25474 ; TODO, not DONE
25475 (and org-export-mark-todo-in-toc
25476 (= level umax-toc)
25477 (org-search-todo-below
25478 line lines level))))
25479 (if (string-match
25480 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25481 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25482 (if (string-match quote-re0 txt)
25483 (setq txt (replace-match "" t t txt)))
25484 (if org-export-with-section-numbers
25485 (setq txt (concat (org-section-number level)
25486 " " txt)))
25487 (if (<= level (max umax umax-toc))
25488 (setq head-count (+ head-count 1)))
25489 (if (<= level umax-toc)
25490 (progn
25491 (if (> level org-last-level)
25492 (progn
25493 (setq cnt (- level org-last-level))
25494 (while (>= (setq cnt (1- cnt)) 0)
25495 (push "\n<ul>\n<li>" thetoc))
25496 (push "\n" thetoc)))
25497 (if (< level org-last-level)
25498 (progn
25499 (setq cnt (- org-last-level level))
25500 (while (>= (setq cnt (1- cnt)) 0)
25501 (push "</li>\n</ul>" thetoc))
25502 (push "\n" thetoc)))
25503 ;; Check for targets
25504 (while (string-match org-target-regexp line)
25505 (setq tg (match-string 1 line)
25506 line (replace-match
25507 (concat "@<span class=\"target\">" tg "@</span> ")
25508 t t line))
25509 (push (cons (org-solidify-link-text tg)
25510 (format "sec-%d" head-count))
25511 target-alist))
25512 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25513 (setq txt (replace-match "" t t txt)))
25514 (push
25515 (format
25516 (if todo
25517 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25518 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25519 head-count txt) thetoc)
25521 (setq org-last-level level))
25523 line)
25524 lines))
25525 (while (> org-last-level (1- org-min-level))
25526 (setq org-last-level (1- org-last-level))
25527 (push "</li>\n</ul>\n" thetoc))
25528 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25530 (setq head-count 0)
25531 (org-init-section-numbers)
25533 (while (setq line (pop lines) origline line)
25534 (catch 'nextline
25536 ;; end of quote section?
25537 (when (and inquote (string-match "^\\*+ " line))
25538 (insert "</pre>\n")
25539 (setq inquote nil))
25540 ;; inside a quote section?
25541 (when inquote
25542 (insert (org-html-protect line) "\n")
25543 (throw 'nextline nil))
25545 ;; verbatim lines
25546 (when (and org-export-with-fixed-width
25547 (string-match "^[ \t]*:\\(.*\\)" line))
25548 (when (not infixed)
25549 (setq infixed t)
25550 (insert "<pre>\n"))
25551 (insert (org-html-protect (match-string 1 line)) "\n")
25552 (when (and lines
25553 (not (string-match "^[ \t]*\\(:.*\\)"
25554 (car lines))))
25555 (setq infixed nil)
25556 (insert "</pre>\n"))
25557 (throw 'nextline nil))
25559 ;; Protected HTML
25560 (when (get-text-property 0 'org-protected line)
25561 (let (par)
25562 (when (re-search-backward
25563 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25564 (setq par (match-string 1))
25565 (replace-match "\\2\n"))
25566 (insert line "\n")
25567 (while (and lines
25568 (or (= (length (car lines)) 0)
25569 (get-text-property 0 'org-protected (car lines))))
25570 (insert (pop lines) "\n"))
25571 (and par (insert "<p>\n")))
25572 (throw 'nextline nil))
25574 ;; Horizontal line
25575 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25576 (insert "\n<hr/>\n")
25577 (throw 'nextline nil))
25579 ;; make targets to anchors
25580 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25581 (cond
25582 ((match-end 2)
25583 (setq line (replace-match
25584 (concat "@<a name=\""
25585 (org-solidify-link-text (match-string 1 line))
25586 "\">\\nbsp@</a>")
25587 t t line)))
25588 ((and org-export-with-toc (equal (string-to-char line) ?*))
25589 (setq line (replace-match
25590 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25591 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25592 t t line)))
25594 (setq line (replace-match
25595 (concat "@<a name=\""
25596 (org-solidify-link-text (match-string 1 line))
25597 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25598 t t line)))))
25600 (setq line (org-html-handle-time-stamps line))
25602 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25603 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25604 ;; Also handle sub_superscripts and checkboxes
25605 (or (string-match org-table-hline-regexp line)
25606 (setq line (org-html-expand line)))
25608 ;; Format the links
25609 (setq start 0)
25610 (while (string-match org-bracket-link-analytic-regexp line start)
25611 (setq start (match-beginning 0))
25612 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25613 (setq path (match-string 3 line))
25614 (setq desc1 (if (match-end 5) (match-string 5 line))
25615 desc2 (if (match-end 2) (concat type ":" path) path)
25616 descp (and desc1 (not (equal desc1 desc2)))
25617 desc (or desc1 desc2))
25618 ;; Make an image out of the description if that is so wanted
25619 (when (and descp (org-file-image-p desc))
25620 (save-match-data
25621 (if (string-match "^file:" desc)
25622 (setq desc (substring desc (match-end 0)))))
25623 (setq desc (concat "<img src=\"" desc "\"/>")))
25624 ;; FIXME: do we need to unescape here somewhere?
25625 (cond
25626 ((equal type "internal")
25627 (setq rpl
25628 (concat
25629 "<a href=\"#"
25630 (org-solidify-link-text
25631 (save-match-data (org-link-unescape path)) target-alist)
25632 "\">" desc "</a>")))
25633 ((member type '("http" "https"))
25634 ;; standard URL, just check if we need to inline an image
25635 (if (and (or (eq t org-export-html-inline-images)
25636 (and org-export-html-inline-images (not descp)))
25637 (org-file-image-p path))
25638 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25639 (setq link (concat type ":" path))
25640 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25641 ((member type '("ftp" "mailto" "news"))
25642 ;; standard URL
25643 (setq link (concat type ":" path))
25644 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25645 ((string= type "file")
25646 ;; FILE link
25647 (let* ((filename path)
25648 (abs-p (file-name-absolute-p filename))
25649 thefile file-is-image-p search)
25650 (save-match-data
25651 (if (string-match "::\\(.*\\)" filename)
25652 (setq search (match-string 1 filename)
25653 filename (replace-match "" t nil filename)))
25654 (setq valid
25655 (if (functionp link-validate)
25656 (funcall link-validate filename current-dir)
25658 (setq file-is-image-p (org-file-image-p filename))
25659 (setq thefile (if abs-p (expand-file-name filename) filename))
25660 (when (and org-export-html-link-org-files-as-html
25661 (string-match "\\.org$" thefile))
25662 (setq thefile (concat (substring thefile 0
25663 (match-beginning 0))
25664 "." html-extension))
25665 (if (and search
25666 ;; make sure this is can be used as target search
25667 (not (string-match "^[0-9]*$" search))
25668 (not (string-match "^\\*" search))
25669 (not (string-match "^/.*/$" search)))
25670 (setq thefile (concat thefile "#"
25671 (org-solidify-link-text
25672 (org-link-unescape search)))))
25673 (when (string-match "^file:" desc)
25674 (setq desc (replace-match "" t t desc))
25675 (if (string-match "\\.org$" desc)
25676 (setq desc (replace-match "" t t desc))))))
25677 (setq rpl (if (and file-is-image-p
25678 (or (eq t org-export-html-inline-images)
25679 (and org-export-html-inline-images
25680 (not descp))))
25681 (concat "<img src=\"" thefile "\"/>")
25682 (concat "<a href=\"" thefile "\">" desc "</a>")))
25683 (if (not valid) (setq rpl desc))))
25684 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25685 (setq rpl (concat "<i>&lt;" type ":"
25686 (save-match-data (org-link-unescape path))
25687 "&gt;</i>"))))
25688 (setq line (replace-match rpl t t line)
25689 start (+ start (length rpl))))
25691 ;; TODO items
25692 (if (and (string-match org-todo-line-regexp line)
25693 (match-beginning 2))
25695 (setq line
25696 (concat (substring line 0 (match-beginning 2))
25697 "<span class=\""
25698 (if (member (match-string 2 line)
25699 org-done-keywords)
25700 "done" "todo")
25701 "\">" (match-string 2 line)
25702 "</span>" (substring line (match-end 2)))))
25704 ;; Does this contain a reference to a footnote?
25705 (when org-export-with-footnotes
25706 (setq start 0)
25707 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25708 (if (get-text-property (match-beginning 2) 'org-protected line)
25709 (setq start (match-end 2))
25710 (let ((n (match-string 2 line)))
25711 (setq line
25712 (replace-match
25713 (format
25714 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25715 (match-string 1 line) n n n)
25716 t t line))))))
25718 (cond
25719 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25720 ;; This is a headline
25721 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25722 txt (match-string 2 line))
25723 (if (string-match quote-re0 txt)
25724 (setq txt (replace-match "" t t txt)))
25725 (if (<= level (max umax umax-toc))
25726 (setq head-count (+ head-count 1)))
25727 (when in-local-list
25728 ;; Close any local lists before inserting a new header line
25729 (while local-list-num
25730 (org-close-li)
25731 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25732 (pop local-list-num))
25733 (setq local-list-indent nil
25734 in-local-list nil))
25735 (setq first-heading-pos (or first-heading-pos (point)))
25736 (org-html-level-start level txt umax
25737 (and org-export-with-toc (<= level umax))
25738 head-count)
25739 ;; QUOTES
25740 (when (string-match quote-re line)
25741 (insert "<pre>")
25742 (setq inquote t)))
25744 ((and org-export-with-tables
25745 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25746 (if (not table-open)
25747 ;; New table starts
25748 (setq table-open t table-buffer nil table-orig-buffer nil))
25749 ;; Accumulate lines
25750 (setq table-buffer (cons line table-buffer)
25751 table-orig-buffer (cons origline table-orig-buffer))
25752 (when (or (not lines)
25753 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25754 (car lines))))
25755 (setq table-open nil
25756 table-buffer (nreverse table-buffer)
25757 table-orig-buffer (nreverse table-orig-buffer))
25758 (org-close-par-maybe)
25759 (insert (org-format-table-html table-buffer table-orig-buffer))))
25761 ;; Normal lines
25762 (when (string-match
25763 (cond
25764 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25765 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25766 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25767 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25768 line)
25769 (setq ind (org-get-string-indentation line)
25770 start-is-num (match-beginning 4)
25771 starter (if (match-beginning 2)
25772 (substring (match-string 2 line) 0 -1))
25773 line (substring line (match-beginning 5)))
25774 (unless (string-match "[^ \t]" line)
25775 ;; empty line. Pretend indentation is large.
25776 (setq ind (if org-empty-line-terminates-plain-lists
25778 (1+ (or (car local-list-indent) 1)))))
25779 (setq didclose nil)
25780 (while (and in-local-list
25781 (or (and (= ind (car local-list-indent))
25782 (not starter))
25783 (< ind (car local-list-indent))))
25784 (setq didclose t)
25785 (org-close-li)
25786 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25787 (pop local-list-num) (pop local-list-indent)
25788 (setq in-local-list local-list-indent))
25789 (cond
25790 ((and starter
25791 (or (not in-local-list)
25792 (> ind (car local-list-indent))))
25793 ;; Start new (level of) list
25794 (org-close-par-maybe)
25795 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25796 (push start-is-num local-list-num)
25797 (push ind local-list-indent)
25798 (setq in-local-list t))
25799 (starter
25800 ;; continue current list
25801 (org-close-li)
25802 (insert "<li>\n"))
25803 (didclose
25804 ;; we did close a list, normal text follows: need <p>
25805 (org-open-par)))
25806 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25807 (setq line
25808 (replace-match
25809 (if (equal (match-string 1 line) "X")
25810 "<b>[X]</b>"
25811 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25812 t t line))))
25814 ;; Empty lines start a new paragraph. If hand-formatted lists
25815 ;; are not fully interpreted, lines starting with "-", "+", "*"
25816 ;; also start a new paragraph.
25817 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25819 ;; Is this the start of a footnote?
25820 (when org-export-with-footnotes
25821 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25822 (org-close-par-maybe)
25823 (let ((n (match-string 1 line)))
25824 (setq line (replace-match
25825 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25827 ;; Check if the line break needs to be conserved
25828 (cond
25829 ((string-match "\\\\\\\\[ \t]*$" line)
25830 (setq line (replace-match "<br/>" t t line)))
25831 (org-export-preserve-breaks
25832 (setq line (concat line "<br/>"))))
25834 (insert line "\n")))))
25836 ;; Properly close all local lists and other lists
25837 (when inquote (insert "</pre>\n"))
25838 (when in-local-list
25839 ;; Close any local lists before inserting a new header line
25840 (while local-list-num
25841 (org-close-li)
25842 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25843 (pop local-list-num))
25844 (setq local-list-indent nil
25845 in-local-list nil))
25846 (org-html-level-start 1 nil umax
25847 (and org-export-with-toc (<= level umax))
25848 head-count)
25850 (unless body-only
25851 (when (plist-get opt-plist :auto-postamble)
25852 (insert "<div id=\"postamble\">")
25853 (when (and org-export-author-info author)
25854 (insert "<p class=\"author\"> "
25855 (nth 1 lang-words) ": " author "\n")
25856 (when email
25857 (if (listp (split-string email ",+ *"))
25858 (mapc (lambda(e)
25859 (insert "<a href=\"mailto:" e "\">&lt;"
25860 e "&gt;</a>\n"))
25861 (split-string email ",+ *"))
25862 (insert "<a href=\"mailto:" email "\">&lt;"
25863 email "&gt;</a>\n")))
25864 (insert "</p>\n"))
25865 (when (and date org-export-time-stamp-file)
25866 (insert "<p class=\"date\"> "
25867 (nth 2 lang-words) ": "
25868 date "</p>\n"))
25869 (insert "</div>"))
25871 (if org-export-html-with-timestamp
25872 (insert org-export-html-html-helper-timestamp))
25873 (insert (or (plist-get opt-plist :postamble) ""))
25874 (insert "</body>\n</html>\n"))
25876 (normal-mode)
25877 (if (eq major-mode default-major-mode) (html-mode))
25879 ;; insert the table of contents
25880 (goto-char (point-min))
25881 (when thetoc
25882 (if (or (re-search-forward
25883 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25884 (re-search-forward
25885 "\\[TABLE-OF-CONTENTS\\]" nil t))
25886 (progn
25887 (goto-char (match-beginning 0))
25888 (replace-match ""))
25889 (goto-char first-heading-pos)
25890 (when (looking-at "\\s-*</p>")
25891 (goto-char (match-end 0))
25892 (insert "\n")))
25893 (insert "<div id=\"table-of-contents\">\n")
25894 (mapc 'insert thetoc)
25895 (insert "</div>\n"))
25896 ;; remove empty paragraphs and lists
25897 (goto-char (point-min))
25898 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25899 (replace-match ""))
25900 (goto-char (point-min))
25901 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25902 (replace-match ""))
25903 (goto-char (point-min))
25904 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25905 (replace-match ""))
25906 ;; Convert whitespace place holders
25907 (goto-char (point-min))
25908 (let (beg end n)
25909 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25910 (setq n (get-text-property beg 'org-whitespace)
25911 end (next-single-property-change beg 'org-whitespace))
25912 (goto-char beg)
25913 (delete-region beg end)
25914 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25915 (make-string n ?x)))))
25917 (or to-buffer (progn (save-buffer) (kill-buffer (current-buffer))))
25918 (goto-char (point-min))
25919 (message "Exporting... done")
25920 (if (eq to-buffer 'string)
25921 (prog1 (buffer-substring (point-min) (point-max))
25922 (kill-buffer (current-buffer)))
25923 (current-buffer)))))
25925 (defvar org-table-colgroup-info nil)
25926 (defun org-format-table-ascii (lines)
25927 "Format a table for ascii export."
25928 (if (stringp lines)
25929 (setq lines (org-split-string lines "\n")))
25930 (if (not (string-match "^[ \t]*|" (car lines)))
25931 ;; Table made by table.el - test for spanning
25932 lines
25934 ;; A normal org table
25935 ;; Get rid of hlines at beginning and end
25936 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25937 (setq lines (nreverse lines))
25938 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25939 (setq lines (nreverse lines))
25940 (when org-export-table-remove-special-lines
25941 ;; Check if the table has a marking column. If yes remove the
25942 ;; column and the special lines
25943 (setq lines (org-table-clean-before-export lines)))
25944 ;; Get rid of the vertical lines except for grouping
25945 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25946 rtn line vl1 start)
25947 (while (setq line (pop lines))
25948 (if (string-match org-table-hline-regexp line)
25949 (and (string-match "|\\(.*\\)|" line)
25950 (setq line (replace-match " \\1" t nil line)))
25951 (setq start 0 vl1 vl)
25952 (while (string-match "|" line start)
25953 (setq start (match-end 0))
25954 (or (pop vl1) (setq line (replace-match " " t t line)))))
25955 (push line rtn))
25956 (nreverse rtn))))
25958 (defun org-colgroup-info-to-vline-list (info)
25959 (let (vl new last)
25960 (while info
25961 (setq last new new (pop info))
25962 (if (or (memq last '(:end :startend))
25963 (memq new '(:start :startend)))
25964 (push t vl)
25965 (push nil vl)))
25966 (setq vl (nreverse vl))
25967 (and vl (setcar vl nil))
25968 vl))
25970 (defun org-format-table-html (lines olines)
25971 "Find out which HTML converter to use and return the HTML code."
25972 (if (stringp lines)
25973 (setq lines (org-split-string lines "\n")))
25974 (if (string-match "^[ \t]*|" (car lines))
25975 ;; A normal org table
25976 (org-format-org-table-html lines)
25977 ;; Table made by table.el - test for spanning
25978 (let* ((hlines (delq nil (mapcar
25979 (lambda (x)
25980 (if (string-match "^[ \t]*\\+-" x) x
25981 nil))
25982 lines)))
25983 (first (car hlines))
25984 (ll (and (string-match "\\S-+" first)
25985 (match-string 0 first)))
25986 (re (concat "^[ \t]*" (regexp-quote ll)))
25987 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25988 hlines))))
25989 (if (and (not spanning)
25990 (not org-export-prefer-native-exporter-for-tables))
25991 ;; We can use my own converter with HTML conversions
25992 (org-format-table-table-html lines)
25993 ;; Need to use the code generator in table.el, with the original text.
25994 (org-format-table-table-html-using-table-generate-source olines)))))
25996 (defun org-format-org-table-html (lines &optional splice)
25997 "Format a table into HTML."
25998 ;; Get rid of hlines at beginning and end
25999 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26000 (setq lines (nreverse lines))
26001 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26002 (setq lines (nreverse lines))
26003 (when org-export-table-remove-special-lines
26004 ;; Check if the table has a marking column. If yes remove the
26005 ;; column and the special lines
26006 (setq lines (org-table-clean-before-export lines)))
26008 (let ((head (and org-export-highlight-first-table-line
26009 (delq nil (mapcar
26010 (lambda (x) (string-match "^[ \t]*|-" x))
26011 (cdr lines)))))
26012 (nlines 0) fnum i
26013 tbopen line fields html gr colgropen)
26014 (if splice (setq head nil))
26015 (unless splice (push (if head "<thead>" "<tbody>") html))
26016 (setq tbopen t)
26017 (while (setq line (pop lines))
26018 (catch 'next-line
26019 (if (string-match "^[ \t]*|-" line)
26020 (progn
26021 (unless splice
26022 (push (if head "</thead>" "</tbody>") html)
26023 (if lines (push "<tbody>" html) (setq tbopen nil)))
26024 (setq head nil) ;; head ends here, first time around
26025 ;; ignore this line
26026 (throw 'next-line t)))
26027 ;; Break the line into fields
26028 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26029 (unless fnum (setq fnum (make-vector (length fields) 0)))
26030 (setq nlines (1+ nlines) i -1)
26031 (push (concat "<tr>"
26032 (mapconcat
26033 (lambda (x)
26034 (setq i (1+ i))
26035 (if (and (< i nlines)
26036 (string-match org-table-number-regexp x))
26037 (incf (aref fnum i)))
26038 (if head
26039 (concat (car org-export-table-header-tags) x
26040 (cdr org-export-table-header-tags))
26041 (concat (car org-export-table-data-tags) x
26042 (cdr org-export-table-data-tags))))
26043 fields "")
26044 "</tr>")
26045 html)))
26046 (unless splice (if tbopen (push "</tbody>" html)))
26047 (unless splice (push "</table>\n" html))
26048 (setq html (nreverse html))
26049 (unless splice
26050 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26051 (push (mapconcat
26052 (lambda (x)
26053 (setq gr (pop org-table-colgroup-info))
26054 (format "%s<col align=\"%s\"></col>%s"
26055 (if (memq gr '(:start :startend))
26056 (prog1
26057 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26058 (setq colgropen t))
26060 (if (> (/ (float x) nlines) org-table-number-fraction)
26061 "right" "left")
26062 (if (memq gr '(:end :startend))
26063 (progn (setq colgropen nil) "</colgroup>")
26064 "")))
26065 fnum "")
26066 html)
26067 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26068 (push html-table-tag html))
26069 (concat (mapconcat 'identity html "\n") "\n")))
26071 (defun org-table-clean-before-export (lines)
26072 "Check if the table has a marking column.
26073 If yes remove the column and the special lines."
26074 (setq org-table-colgroup-info nil)
26075 (if (memq nil
26076 (mapcar
26077 (lambda (x) (or (string-match "^[ \t]*|-" x)
26078 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26079 lines))
26080 (progn
26081 (setq org-table-clean-did-remove-column nil)
26082 (delq nil
26083 (mapcar
26084 (lambda (x)
26085 (cond
26086 ((string-match "^[ \t]*| */ *|" x)
26087 (setq org-table-colgroup-info
26088 (mapcar (lambda (x)
26089 (cond ((member x '("<" "&lt;")) :start)
26090 ((member x '(">" "&gt;")) :end)
26091 ((member x '("<>" "&lt;&gt;")) :startend)
26092 (t nil)))
26093 (org-split-string x "[ \t]*|[ \t]*")))
26094 nil)
26095 (t x)))
26096 lines)))
26097 (setq org-table-clean-did-remove-column t)
26098 (delq nil
26099 (mapcar
26100 (lambda (x)
26101 (cond
26102 ((string-match "^[ \t]*| */ *|" x)
26103 (setq org-table-colgroup-info
26104 (mapcar (lambda (x)
26105 (cond ((member x '("<" "&lt;")) :start)
26106 ((member x '(">" "&gt;")) :end)
26107 ((member x '("<>" "&lt;&gt;")) :startend)
26108 (t nil)))
26109 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26110 nil)
26111 ((string-match "^[ \t]*| *[!_^/] *|" x)
26112 nil) ; ignore this line
26113 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26114 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26115 ;; remove the first column
26116 (replace-match "\\1|" t nil x))))
26117 lines))))
26119 (defun org-format-table-table-html (lines)
26120 "Format a table generated by table.el into HTML.
26121 This conversion does *not* use `table-generate-source' from table.el.
26122 This has the advantage that Org-mode's HTML conversions can be used.
26123 But it has the disadvantage, that no cell- or row-spanning is allowed."
26124 (let (line field-buffer
26125 (head org-export-highlight-first-table-line)
26126 fields html empty)
26127 (setq html (concat html-table-tag "\n"))
26128 (while (setq line (pop lines))
26129 (setq empty "&nbsp;")
26130 (catch 'next-line
26131 (if (string-match "^[ \t]*\\+-" line)
26132 (progn
26133 (if field-buffer
26134 (progn
26135 (setq
26136 html
26137 (concat
26138 html
26139 "<tr>"
26140 (mapconcat
26141 (lambda (x)
26142 (if (equal x "") (setq x empty))
26143 (if head
26144 (concat (car org-export-table-header-tags) x
26145 (cdr org-export-table-header-tags))
26146 (concat (car org-export-table-data-tags) x
26147 (cdr org-export-table-data-tags))))
26148 field-buffer "\n")
26149 "</tr>\n"))
26150 (setq head nil)
26151 (setq field-buffer nil)))
26152 ;; Ignore this line
26153 (throw 'next-line t)))
26154 ;; Break the line into fields and store the fields
26155 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26156 (if field-buffer
26157 (setq field-buffer (mapcar
26158 (lambda (x)
26159 (concat x "<br/>" (pop fields)))
26160 field-buffer))
26161 (setq field-buffer fields))))
26162 (setq html (concat html "</table>\n"))
26163 html))
26165 (defun org-format-table-table-html-using-table-generate-source (lines)
26166 "Format a table into html, using `table-generate-source' from table.el.
26167 This has the advantage that cell- or row-spanning is allowed.
26168 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26169 (require 'table)
26170 (with-current-buffer (get-buffer-create " org-tmp1 ")
26171 (erase-buffer)
26172 (insert (mapconcat 'identity lines "\n"))
26173 (goto-char (point-min))
26174 (if (not (re-search-forward "|[^+]" nil t))
26175 (error "Error processing table"))
26176 (table-recognize-table)
26177 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26178 (table-generate-source 'html " org-tmp2 ")
26179 (set-buffer " org-tmp2 ")
26180 (buffer-substring (point-min) (point-max))))
26182 (defun org-html-handle-time-stamps (s)
26183 "Format time stamps in string S, or remove them."
26184 (catch 'exit
26185 (let (r b)
26186 (while (string-match org-maybe-keyword-time-regexp s)
26187 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26188 ;; never export CLOCK
26189 (throw 'exit ""))
26190 (or b (setq b (substring s 0 (match-beginning 0))))
26191 (if (not org-export-with-timestamps)
26192 (setq r (concat r (substring s 0 (match-beginning 0)))
26193 s (substring s (match-end 0)))
26194 (setq r (concat
26195 r (substring s 0 (match-beginning 0))
26196 (if (match-end 1)
26197 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26198 (match-string 1 s)))
26199 (format " @<span class=\"timestamp\">%s@</span>"
26200 (substring
26201 (org-translate-time (match-string 3 s)) 1 -1)))
26202 s (substring s (match-end 0)))))
26203 ;; Line break if line started and ended with time stamp stuff
26204 (if (not r)
26206 (setq r (concat r s))
26207 (unless (string-match "\\S-" (concat b s))
26208 (setq r (concat r "@<br/>")))
26209 r))))
26211 (defun org-html-protect (s)
26212 ;; convert & to &amp;, < to &lt; and > to &gt;
26213 (let ((start 0))
26214 (while (string-match "&" s start)
26215 (setq s (replace-match "&amp;" t t s)
26216 start (1+ (match-beginning 0))))
26217 (while (string-match "<" s)
26218 (setq s (replace-match "&lt;" t t s)))
26219 (while (string-match ">" s)
26220 (setq s (replace-match "&gt;" t t s))))
26223 (defun org-export-cleanup-toc-line (s)
26224 "Remove tags and time staps from lines going into the toc."
26225 (when (memq org-export-with-tags '(not-in-toc nil))
26226 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26227 (setq s (replace-match "" t t s))))
26228 (when org-export-remove-timestamps-from-toc
26229 (while (string-match org-maybe-keyword-time-regexp s)
26230 (setq s (replace-match "" t t s))))
26231 (while (string-match org-bracket-link-regexp s)
26232 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26233 t t s)))
26236 (defun org-html-expand (string)
26237 "Prepare STRING for HTML export. Applies all active conversions.
26238 If there are links in the string, don't modify these."
26239 (let* ((re (concat org-bracket-link-regexp "\\|"
26240 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26241 m s l res)
26242 (while (setq m (string-match re string))
26243 (setq s (substring string 0 m)
26244 l (match-string 0 string)
26245 string (substring string (match-end 0)))
26246 (push (org-html-do-expand s) res)
26247 (push l res))
26248 (push (org-html-do-expand string) res)
26249 (apply 'concat (nreverse res))))
26251 (defun org-html-do-expand (s)
26252 "Apply all active conversions to translate special ASCII to HTML."
26253 (setq s (org-html-protect s))
26254 (if org-export-html-expand
26255 (let ((start 0))
26256 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26257 (setq s (replace-match "<\\1>" t nil s)))))
26258 (if org-export-with-emphasize
26259 (setq s (org-export-html-convert-emphasize s)))
26260 (if org-export-with-special-strings
26261 (setq s (org-export-html-convert-special-strings s)))
26262 (if org-export-with-sub-superscripts
26263 (setq s (org-export-html-convert-sub-super s)))
26264 (if org-export-with-TeX-macros
26265 (let ((start 0) wd ass)
26266 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26267 (if (get-text-property (match-beginning 0) 'org-protected s)
26268 (setq start (match-end 0))
26269 (setq wd (match-string 1 s))
26270 (if (setq ass (assoc wd org-html-entities))
26271 (setq s (replace-match (or (cdr ass)
26272 (concat "&" (car ass) ";"))
26273 t t s))
26274 (setq start (+ start (length wd))))))))
26277 (defun org-create-multibrace-regexp (left right n)
26278 "Create a regular expression which will match a balanced sexp.
26279 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26280 as single character strings.
26281 The regexp returned will match the entire expression including the
26282 delimiters. It will also define a single group which contains the
26283 match except for the outermost delimiters. The maximum depth of
26284 stacked delimiters is N. Escaping delimiters is not possible."
26285 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26286 (or "\\|")
26287 (re nothing)
26288 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26289 (while (> n 1)
26290 (setq n (1- n)
26291 re (concat re or next)
26292 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26293 (concat left "\\(" re "\\)" right)))
26295 (defvar org-match-substring-regexp
26296 (concat
26297 "\\([^\\]\\)\\([_^]\\)\\("
26298 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26299 "\\|"
26300 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26301 "\\|"
26302 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26303 "The regular expression matching a sub- or superscript.")
26305 (defvar org-match-substring-with-braces-regexp
26306 (concat
26307 "\\([^\\]\\)\\([_^]\\)\\("
26308 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26309 "\\)")
26310 "The regular expression matching a sub- or superscript, forcing braces.")
26312 (defconst org-export-html-special-string-regexps
26313 '(("\\\\-" . "&shy;")
26314 ("---\\([^-]\\)" . "&mdash;\\1")
26315 ("--\\([^-]\\)" . "&ndash;\\1")
26316 ("\\.\\.\\." . "&hellip;"))
26317 "Regular expressions for special string conversion.")
26319 (defun org-export-html-convert-special-strings (string)
26320 "Convert special characters in STRING to HTML."
26321 (let ((all org-export-html-special-string-regexps)
26322 e a re rpl start)
26323 (while (setq a (pop all))
26324 (setq re (car a) rpl (cdr a) start 0)
26325 (while (string-match re string start)
26326 (if (get-text-property (match-beginning 0) 'org-protected string)
26327 (setq start (match-end 0))
26328 (setq string (replace-match rpl t nil string)))))
26329 string))
26331 (defun org-export-html-convert-sub-super (string)
26332 "Convert sub- and superscripts in STRING to HTML."
26333 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26334 (while (string-match org-match-substring-regexp string s)
26335 (cond
26336 ((and requireb (match-end 8)) (setq s (match-end 2)))
26337 ((get-text-property (match-beginning 2) 'org-protected string)
26338 (setq s (match-end 2)))
26340 (setq s (match-end 1)
26341 key (if (string= (match-string 2 string) "_") "sub" "sup")
26342 c (or (match-string 8 string)
26343 (match-string 6 string)
26344 (match-string 5 string))
26345 string (replace-match
26346 (concat (match-string 1 string)
26347 "<" key ">" c "</" key ">")
26348 t t string)))))
26349 (while (string-match "\\\\\\([_^]\\)" string)
26350 (setq string (replace-match (match-string 1 string) t t string)))
26351 string))
26353 (defun org-export-html-convert-emphasize (string)
26354 "Apply emphasis."
26355 (let ((s 0) rpl)
26356 (while (string-match org-emph-re string s)
26357 (if (not (equal
26358 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26359 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26360 (setq s (match-beginning 0)
26362 (concat
26363 (match-string 1 string)
26364 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26365 (match-string 4 string)
26366 (nth 3 (assoc (match-string 3 string)
26367 org-emphasis-alist))
26368 (match-string 5 string))
26369 string (replace-match rpl t t string)
26370 s (+ s (- (length rpl) 2)))
26371 (setq s (1+ s))))
26372 string))
26374 (defvar org-par-open nil)
26375 (defun org-open-par ()
26376 "Insert <p>, but first close previous paragraph if any."
26377 (org-close-par-maybe)
26378 (insert "\n<p>")
26379 (setq org-par-open t))
26380 (defun org-close-par-maybe ()
26381 "Close paragraph if there is one open."
26382 (when org-par-open
26383 (insert "</p>")
26384 (setq org-par-open nil)))
26385 (defun org-close-li ()
26386 "Close <li> if necessary."
26387 (org-close-par-maybe)
26388 (insert "</li>\n"))
26390 (defvar body-only) ; dynamically scoped into this.
26391 (defun org-html-level-start (level title umax with-toc head-count)
26392 "Insert a new level in HTML export.
26393 When TITLE is nil, just close all open levels."
26394 (org-close-par-maybe)
26395 (let ((l org-level-max))
26396 (while (>= l level)
26397 (if (aref org-levels-open (1- l))
26398 (progn
26399 (org-html-level-close l umax)
26400 (aset org-levels-open (1- l) nil)))
26401 (setq l (1- l)))
26402 (when title
26403 ;; If title is nil, this means this function is called to close
26404 ;; all levels, so the rest is done only if title is given
26405 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26406 (setq title (replace-match
26407 (if org-export-with-tags
26408 (save-match-data
26409 (concat
26410 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26411 (mapconcat 'identity (org-split-string
26412 (match-string 1 title) ":")
26413 "&nbsp;")
26414 "</span>"))
26416 t t title)))
26417 (if (> level umax)
26418 (progn
26419 (if (aref org-levels-open (1- level))
26420 (progn
26421 (org-close-li)
26422 (insert "<li>" title "<br/>\n"))
26423 (aset org-levels-open (1- level) t)
26424 (org-close-par-maybe)
26425 (insert "<ul>\n<li>" title "<br/>\n")))
26426 (aset org-levels-open (1- level) t)
26427 (if (and org-export-with-section-numbers (not body-only))
26428 (setq title (concat (org-section-number level) " " title)))
26429 (setq level (+ level org-export-html-toplevel-hlevel -1))
26430 (if with-toc
26431 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26432 level level head-count title level))
26433 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26434 (org-open-par)))))
26436 (defun org-html-level-close (level max-outline-level)
26437 "Terminate one level in HTML export."
26438 (if (<= level max-outline-level)
26439 (insert "</div>\n")
26440 (org-close-li)
26441 (insert "</ul>\n")))
26443 ;;; iCalendar export
26445 ;;;###autoload
26446 (defun org-export-icalendar-this-file ()
26447 "Export current file as an iCalendar file.
26448 The iCalendar file will be located in the same directory as the Org-mode
26449 file, but with extension `.ics'."
26450 (interactive)
26451 (org-export-icalendar nil buffer-file-name))
26453 ;;;###autoload
26454 (defun org-export-icalendar-all-agenda-files ()
26455 "Export all files in `org-agenda-files' to iCalendar .ics files.
26456 Each iCalendar file will be located in the same directory as the Org-mode
26457 file, but with extension `.ics'."
26458 (interactive)
26459 (apply 'org-export-icalendar nil (org-agenda-files t)))
26461 ;;;###autoload
26462 (defun org-export-icalendar-combine-agenda-files ()
26463 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26464 The file is stored under the name `org-combined-agenda-icalendar-file'."
26465 (interactive)
26466 (apply 'org-export-icalendar t (org-agenda-files t)))
26468 (defun org-export-icalendar (combine &rest files)
26469 "Create iCalendar files for all elements of FILES.
26470 If COMBINE is non-nil, combine all calendar entries into a single large
26471 file and store it under the name `org-combined-agenda-icalendar-file'."
26472 (save-excursion
26473 (org-prepare-agenda-buffers files)
26474 (let* ((dir (org-export-directory
26475 :ical (list :publishing-directory
26476 org-export-publishing-directory)))
26477 file ical-file ical-buffer category started org-agenda-new-buffers)
26479 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26480 (when combine
26481 (setq ical-file
26482 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26483 org-combined-agenda-icalendar-file
26484 (expand-file-name org-combined-agenda-icalendar-file dir))
26485 ical-buffer (org-get-agenda-file-buffer ical-file))
26486 (set-buffer ical-buffer) (erase-buffer))
26487 (while (setq file (pop files))
26488 (catch 'nextfile
26489 (org-check-agenda-file file)
26490 (set-buffer (org-get-agenda-file-buffer file))
26491 (unless combine
26492 (setq ical-file (concat (file-name-as-directory dir)
26493 (file-name-sans-extension
26494 (file-name-nondirectory buffer-file-name))
26495 ".ics"))
26496 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26497 (with-current-buffer ical-buffer (erase-buffer)))
26498 (setq category (or org-category
26499 (file-name-sans-extension
26500 (file-name-nondirectory buffer-file-name))))
26501 (if (symbolp category) (setq category (symbol-name category)))
26502 (let ((standard-output ical-buffer))
26503 (if combine
26504 (and (not started) (setq started t)
26505 (org-start-icalendar-file org-icalendar-combined-name))
26506 (org-start-icalendar-file category))
26507 (org-print-icalendar-entries combine)
26508 (when (or (and combine (not files)) (not combine))
26509 (org-finish-icalendar-file)
26510 (set-buffer ical-buffer)
26511 (save-buffer)
26512 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26513 (org-release-buffers org-agenda-new-buffers))))
26515 (defvar org-after-save-iCalendar-file-hook nil
26516 "Hook run after an iCalendar file has been saved.
26517 The iCalendar buffer is still current when this hook is run.
26518 A good way to use this is to tell a desktop calenndar application to re-read
26519 the iCalendar file.")
26521 (defun org-print-icalendar-entries (&optional combine)
26522 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26523 When COMBINE is non nil, add the category to each line."
26524 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26525 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26526 (dts (org-ical-ts-to-string
26527 (format-time-string (cdr org-time-stamp-formats) (current-time))
26528 "DTSTART"))
26529 hd ts ts2 state status (inc t) pos b sexp rrule
26530 scheduledp deadlinep tmp pri category entry location summary desc
26531 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26532 (org-refresh-category-properties)
26533 (save-excursion
26534 (goto-char (point-min))
26535 (while (re-search-forward re1 nil t)
26536 (catch :skip
26537 (org-agenda-skip)
26538 (setq pos (match-beginning 0)
26539 ts (match-string 0)
26540 inc t
26541 hd (org-get-heading)
26542 summary (org-icalendar-cleanup-string
26543 (org-entry-get nil "SUMMARY"))
26544 desc (org-icalendar-cleanup-string
26545 (or (org-entry-get nil "DESCRIPTION")
26546 (and org-icalendar-include-body (org-get-entry)))
26547 t org-icalendar-include-body)
26548 location (org-icalendar-cleanup-string
26549 (org-entry-get nil "LOCATION"))
26550 category (org-get-category))
26551 (if (looking-at re2)
26552 (progn
26553 (goto-char (match-end 0))
26554 (setq ts2 (match-string 1) inc nil))
26555 (setq tmp (buffer-substring (max (point-min)
26556 (- pos org-ds-keyword-length))
26557 pos)
26558 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26559 (progn
26560 (setq inc nil)
26561 (replace-match "\\1" t nil ts))
26563 deadlinep (string-match org-deadline-regexp tmp)
26564 scheduledp (string-match org-scheduled-regexp tmp)
26565 ;; donep (org-entry-is-done-p)
26567 (if (or (string-match org-tr-regexp hd)
26568 (string-match org-ts-regexp hd))
26569 (setq hd (replace-match "" t t hd)))
26570 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26571 (setq rrule
26572 (concat "\nRRULE:FREQ="
26573 (cdr (assoc
26574 (match-string 2 ts)
26575 '(("d" . "DAILY")("w" . "WEEKLY")
26576 ("m" . "MONTHLY")("y" . "YEARLY"))))
26577 ";INTERVAL=" (match-string 1 ts)))
26578 (setq rrule ""))
26579 (setq summary (or summary hd))
26580 (if (string-match org-bracket-link-regexp summary)
26581 (setq summary
26582 (replace-match (if (match-end 3)
26583 (match-string 3 summary)
26584 (match-string 1 summary))
26585 t t summary)))
26586 (if deadlinep (setq summary (concat "DL: " summary)))
26587 (if scheduledp (setq summary (concat "S: " summary)))
26588 (if (string-match "\\`<%%" ts)
26589 (with-current-buffer sexp-buffer
26590 (insert (substring ts 1 -1) " " summary "\n"))
26591 (princ (format "BEGIN:VEVENT
26593 %s%s
26594 SUMMARY:%s%s%s
26595 CATEGORIES:%s
26596 END:VEVENT\n"
26597 (org-ical-ts-to-string ts "DTSTART")
26598 (org-ical-ts-to-string ts2 "DTEND" inc)
26599 rrule summary
26600 (if (and desc (string-match "\\S-" desc))
26601 (concat "\nDESCRIPTION: " desc) "")
26602 (if (and location (string-match "\\S-" location))
26603 (concat "\nLOCATION: " location) "")
26604 category)))))
26606 (when (and org-icalendar-include-sexps
26607 (condition-case nil (require 'icalendar) (error nil))
26608 (fboundp 'icalendar-export-region))
26609 ;; Get all the literal sexps
26610 (goto-char (point-min))
26611 (while (re-search-forward "^&?%%(" nil t)
26612 (catch :skip
26613 (org-agenda-skip)
26614 (setq b (match-beginning 0))
26615 (goto-char (1- (match-end 0)))
26616 (forward-sexp 1)
26617 (end-of-line 1)
26618 (setq sexp (buffer-substring b (point)))
26619 (with-current-buffer sexp-buffer
26620 (insert sexp "\n"))
26621 (princ (org-diary-to-ical-string sexp-buffer)))))
26623 (when org-icalendar-include-todo
26624 (goto-char (point-min))
26625 (while (re-search-forward org-todo-line-regexp nil t)
26626 (catch :skip
26627 (org-agenda-skip)
26628 (setq state (match-string 2))
26629 (setq status (if (member state org-done-keywords)
26630 "COMPLETED" "NEEDS-ACTION"))
26631 (when (and state
26632 (or (not (member state org-done-keywords))
26633 (eq org-icalendar-include-todo 'all))
26634 (not (member org-archive-tag (org-get-tags-at)))
26636 (setq hd (match-string 3)
26637 summary (org-icalendar-cleanup-string
26638 (org-entry-get nil "SUMMARY"))
26639 desc (org-icalendar-cleanup-string
26640 (or (org-entry-get nil "DESCRIPTION")
26641 (and org-icalendar-include-body (org-get-entry)))
26642 t org-icalendar-include-body)
26643 location (org-icalendar-cleanup-string
26644 (org-entry-get nil "LOCATION")))
26645 (if (string-match org-bracket-link-regexp hd)
26646 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26647 (match-string 1 hd))
26648 t t hd)))
26649 (if (string-match org-priority-regexp hd)
26650 (setq pri (string-to-char (match-string 2 hd))
26651 hd (concat (substring hd 0 (match-beginning 1))
26652 (substring hd (match-end 1))))
26653 (setq pri org-default-priority))
26654 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26655 (- org-lowest-priority org-highest-priority))))))
26657 (princ (format "BEGIN:VTODO
26659 SUMMARY:%s%s%s
26660 CATEGORIES:%s
26661 SEQUENCE:1
26662 PRIORITY:%d
26663 STATUS:%s
26664 END:VTODO\n"
26666 (or summary hd)
26667 (if (and location (string-match "\\S-" location))
26668 (concat "\nLOCATION: " location) "")
26669 (if (and desc (string-match "\\S-" desc))
26670 (concat "\nDESCRIPTION: " desc) "")
26671 category pri status)))))))))
26673 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26674 "Take out stuff and quote what needs to be quoted.
26675 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26676 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26677 characters."
26678 (if (not s)
26680 (when is-body
26681 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26682 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26683 (while (string-match re s) (setq s (replace-match "" t t s)))
26684 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26685 (let ((start 0))
26686 (while (string-match "\\([,;\\]\\)" s start)
26687 (setq start (+ (match-beginning 0) 2)
26688 s (replace-match "\\\\\\1" nil nil s))))
26689 (when is-body
26690 (while (string-match "[ \t]*\n[ \t]*" s)
26691 (setq s (replace-match "\\n" t t s))))
26692 (setq s (org-trim s))
26693 (if is-body
26694 (if maxlength
26695 (if (and (numberp maxlength)
26696 (> (length s) maxlength))
26697 (setq s (substring s 0 maxlength)))))
26700 (defun org-get-entry ()
26701 "Clean-up description string."
26702 (save-excursion
26703 (org-back-to-heading t)
26704 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26706 (defun org-start-icalendar-file (name)
26707 "Start an iCalendar file by inserting the header."
26708 (let ((user user-full-name)
26709 (name (or name "unknown"))
26710 (timezone (cadr (current-time-zone))))
26711 (princ
26712 (format "BEGIN:VCALENDAR
26713 VERSION:2.0
26714 X-WR-CALNAME:%s
26715 PRODID:-//%s//Emacs with Org-mode//EN
26716 X-WR-TIMEZONE:%s
26717 CALSCALE:GREGORIAN\n" name user timezone))))
26719 (defun org-finish-icalendar-file ()
26720 "Finish an iCalendar file by inserting the END statement."
26721 (princ "END:VCALENDAR\n"))
26723 (defun org-ical-ts-to-string (s keyword &optional inc)
26724 "Take a time string S and convert it to iCalendar format.
26725 KEYWORD is added in front, to make a complete line like DTSTART....
26726 When INC is non-nil, increase the hour by two (if time string contains
26727 a time), or the day by one (if it does not contain a time)."
26728 (let ((t1 (org-parse-time-string s 'nodefault))
26729 t2 fmt have-time time)
26730 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26731 (setq t2 t1 have-time t)
26732 (setq t2 (org-parse-time-string s)))
26733 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26734 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26735 (when inc
26736 (if have-time
26737 (if org-agenda-default-appointment-duration
26738 (setq mi (+ org-agenda-default-appointment-duration mi))
26739 (setq h (+ 2 h)))
26740 (setq d (1+ d))))
26741 (setq time (encode-time s mi h d m y)))
26742 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26743 (concat keyword (format-time-string fmt time))))
26745 ;;; XOXO export
26747 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26748 (with-current-buffer buffer
26749 (apply 'insert output)))
26750 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26752 (defun org-export-as-xoxo (&optional buffer)
26753 "Export the org buffer as XOXO.
26754 The XOXO buffer is named *xoxo-<source buffer name>*"
26755 (interactive (list (current-buffer)))
26756 ;; A quickie abstraction
26758 ;; Output everything as XOXO
26759 (with-current-buffer (get-buffer buffer)
26760 (let* ((pos (point))
26761 (opt-plist (org-combine-plists (org-default-export-plist)
26762 (org-infile-export-plist)))
26763 (filename (concat (file-name-as-directory
26764 (org-export-directory :xoxo opt-plist))
26765 (file-name-sans-extension
26766 (file-name-nondirectory buffer-file-name))
26767 ".html"))
26768 (out (find-file-noselect filename))
26769 (last-level 1)
26770 (hanging-li nil))
26771 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26772 ;; Check the output buffer is empty.
26773 (with-current-buffer out (erase-buffer))
26774 ;; Kick off the output
26775 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26776 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26777 (let* ((hd (match-string-no-properties 1))
26778 (level (length hd))
26779 (text (concat
26780 (match-string-no-properties 2)
26781 (save-excursion
26782 (goto-char (match-end 0))
26783 (let ((str ""))
26784 (catch 'loop
26785 (while 't
26786 (forward-line)
26787 (if (looking-at "^[ \t]\\(.*\\)")
26788 (setq str (concat str (match-string-no-properties 1)))
26789 (throw 'loop str)))))))))
26791 ;; Handle level rendering
26792 (cond
26793 ((> level last-level)
26794 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26796 ((< level last-level)
26797 (dotimes (- (- last-level level) 1)
26798 (if hanging-li
26799 (org-export-as-xoxo-insert-into out "</li>\n"))
26800 (org-export-as-xoxo-insert-into out "</ol>\n"))
26801 (when hanging-li
26802 (org-export-as-xoxo-insert-into out "</li>\n")
26803 (setq hanging-li nil)))
26805 ((equal level last-level)
26806 (if hanging-li
26807 (org-export-as-xoxo-insert-into out "</li>\n")))
26810 (setq last-level level)
26812 ;; And output the new li
26813 (setq hanging-li 't)
26814 (if (equal ?+ (elt text 0))
26815 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26816 (org-export-as-xoxo-insert-into out "<li>" text))))
26818 ;; Finally finish off the ol
26819 (dotimes (- last-level 1)
26820 (if hanging-li
26821 (org-export-as-xoxo-insert-into out "</li>\n"))
26822 (org-export-as-xoxo-insert-into out "</ol>\n"))
26824 (goto-char pos)
26825 ;; Finish the buffer off and clean it up.
26826 (switch-to-buffer-other-window out)
26827 (indent-region (point-min) (point-max) nil)
26828 (save-buffer)
26829 (goto-char (point-min))
26833 ;;;; Key bindings
26835 ;; Make `C-c C-x' a prefix key
26836 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26838 ;; TAB key with modifiers
26839 (org-defkey org-mode-map "\C-i" 'org-cycle)
26840 (org-defkey org-mode-map [(tab)] 'org-cycle)
26841 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26842 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26843 (org-defkey org-mode-map "\M-\t" 'org-complete)
26844 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26845 ;; The following line is necessary under Suse GNU/Linux
26846 (unless (featurep 'xemacs)
26847 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26848 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26849 (define-key org-mode-map [backtab] 'org-shifttab)
26851 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26852 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26853 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26855 ;; Cursor keys with modifiers
26856 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26857 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26858 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26859 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26861 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26862 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26863 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26864 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26866 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26867 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26868 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26869 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26871 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26872 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26874 ;;; Extra keys for tty access.
26875 ;; We only set them when really needed because otherwise the
26876 ;; menus don't show the simple keys
26878 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26879 (not window-system))
26880 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26881 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26882 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26883 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26884 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26885 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26886 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26887 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26888 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26889 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26890 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26891 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26892 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26893 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26894 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26895 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26896 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26897 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26898 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26899 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26900 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26901 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26903 ;; All the other keys
26905 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26906 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26907 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26908 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26909 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26910 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26911 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26912 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26913 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26914 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26915 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26916 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26917 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26918 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26919 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26920 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26921 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26922 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26923 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26924 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26925 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26926 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26927 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26928 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26929 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26930 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26931 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26932 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26933 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26934 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26935 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26936 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26937 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26938 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26939 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26940 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26941 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26942 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26943 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26944 (org-defkey org-mode-map "\C-c^" 'org-sort)
26945 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26946 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26947 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26948 (org-defkey org-mode-map "\C-m" 'org-return)
26949 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26950 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26951 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26952 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26953 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26954 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26955 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26956 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26957 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26958 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26959 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26960 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26961 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26962 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26963 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26964 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26965 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26967 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26968 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26969 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26970 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26972 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26973 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26974 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26975 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26976 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26977 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26978 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26979 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26980 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26981 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26982 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26983 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26985 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26987 (when (featurep 'xemacs)
26988 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26990 (defsubst org-table-p () (org-at-table-p))
26992 (defun org-self-insert-command (N)
26993 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26994 If the cursor is in a table looking at whitespace, the whitespace is
26995 overwritten, and the table is not marked as requiring realignment."
26996 (interactive "p")
26997 (if (and (org-table-p)
26998 (progn
26999 ;; check if we blank the field, and if that triggers align
27000 (and org-table-auto-blank-field
27001 (member last-command
27002 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27003 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27004 ;; got extra space, this field does not determine column width
27005 (let (org-table-may-need-update) (org-table-blank-field))
27006 ;; no extra space, this field may determine column width
27007 (org-table-blank-field)))
27009 (eq N 1)
27010 (looking-at "[^|\n]* |"))
27011 (let (org-table-may-need-update)
27012 (goto-char (1- (match-end 0)))
27013 (delete-backward-char 1)
27014 (goto-char (match-beginning 0))
27015 (self-insert-command N))
27016 (setq org-table-may-need-update t)
27017 (self-insert-command N)
27018 (org-fix-tags-on-the-fly)))
27020 (defun org-fix-tags-on-the-fly ()
27021 (when (and (equal (char-after (point-at-bol)) ?*)
27022 (org-on-heading-p))
27023 (org-align-tags-here org-tags-column)))
27025 (defun org-delete-backward-char (N)
27026 "Like `delete-backward-char', insert whitespace at field end in tables.
27027 When deleting backwards, in tables this function will insert whitespace in
27028 front of the next \"|\" separator, to keep the table aligned. The table will
27029 still be marked for re-alignment if the field did fill the entire column,
27030 because, in this case the deletion might narrow the column."
27031 (interactive "p")
27032 (if (and (org-table-p)
27033 (eq N 1)
27034 (string-match "|" (buffer-substring (point-at-bol) (point)))
27035 (looking-at ".*?|"))
27036 (let ((pos (point))
27037 (noalign (looking-at "[^|\n\r]* |"))
27038 (c org-table-may-need-update))
27039 (backward-delete-char N)
27040 (skip-chars-forward "^|")
27041 (insert " ")
27042 (goto-char (1- pos))
27043 ;; noalign: if there were two spaces at the end, this field
27044 ;; does not determine the width of the column.
27045 (if noalign (setq org-table-may-need-update c)))
27046 (backward-delete-char N)
27047 (org-fix-tags-on-the-fly)))
27049 (defun org-delete-char (N)
27050 "Like `delete-char', but insert whitespace at field end in tables.
27051 When deleting characters, in tables this function will insert whitespace in
27052 front of the next \"|\" separator, to keep the table aligned. The table will
27053 still be marked for re-alignment if the field did fill the entire column,
27054 because, in this case the deletion might narrow the column."
27055 (interactive "p")
27056 (if (and (org-table-p)
27057 (not (bolp))
27058 (not (= (char-after) ?|))
27059 (eq N 1))
27060 (if (looking-at ".*?|")
27061 (let ((pos (point))
27062 (noalign (looking-at "[^|\n\r]* |"))
27063 (c org-table-may-need-update))
27064 (replace-match (concat
27065 (substring (match-string 0) 1 -1)
27066 " |"))
27067 (goto-char pos)
27068 ;; noalign: if there were two spaces at the end, this field
27069 ;; does not determine the width of the column.
27070 (if noalign (setq org-table-may-need-update c)))
27071 (delete-char N))
27072 (delete-char N)
27073 (org-fix-tags-on-the-fly)))
27075 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27076 (put 'org-self-insert-command 'delete-selection t)
27077 (put 'orgtbl-self-insert-command 'delete-selection t)
27078 (put 'org-delete-char 'delete-selection 'supersede)
27079 (put 'org-delete-backward-char 'delete-selection 'supersede)
27081 ;; Make `flyspell-mode' delay after some commands
27082 (put 'org-self-insert-command 'flyspell-delayed t)
27083 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27084 (put 'org-delete-char 'flyspell-delayed t)
27085 (put 'org-delete-backward-char 'flyspell-delayed t)
27087 ;; Make pabbrev-mode expand after org-mode commands
27088 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27089 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27091 ;; How to do this: Measure non-white length of current string
27092 ;; If equal to column width, we should realign.
27094 (defun org-remap (map &rest commands)
27095 "In MAP, remap the functions given in COMMANDS.
27096 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27097 (let (new old)
27098 (while commands
27099 (setq old (pop commands) new (pop commands))
27100 (if (fboundp 'command-remapping)
27101 (org-defkey map (vector 'remap old) new)
27102 (substitute-key-definition old new map global-map)))))
27104 (when (eq org-enable-table-editor 'optimized)
27105 ;; If the user wants maximum table support, we need to hijack
27106 ;; some standard editing functions
27107 (org-remap org-mode-map
27108 'self-insert-command 'org-self-insert-command
27109 'delete-char 'org-delete-char
27110 'delete-backward-char 'org-delete-backward-char)
27111 (org-defkey org-mode-map "|" 'org-force-self-insert))
27113 (defun org-shiftcursor-error ()
27114 "Throw an error because Shift-Cursor command was applied in wrong context."
27115 (error "This command is active in special context like tables, headlines or timestamps"))
27117 (defun org-shifttab (&optional arg)
27118 "Global visibility cycling or move to previous table field.
27119 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27120 on context.
27121 See the individual commands for more information."
27122 (interactive "P")
27123 (cond
27124 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27125 (arg (message "Content view to level: ")
27126 (org-content (prefix-numeric-value arg))
27127 (setq org-cycle-global-status 'overview))
27128 (t (call-interactively 'org-global-cycle))))
27130 (defun org-shiftmetaleft ()
27131 "Promote subtree or delete table column.
27132 Calls `org-promote-subtree', `org-outdent-item',
27133 or `org-table-delete-column', depending on context.
27134 See the individual commands for more information."
27135 (interactive)
27136 (cond
27137 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27138 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27139 ((org-at-item-p) (call-interactively 'org-outdent-item))
27140 (t (org-shiftcursor-error))))
27142 (defun org-shiftmetaright ()
27143 "Demote subtree or insert table column.
27144 Calls `org-demote-subtree', `org-indent-item',
27145 or `org-table-insert-column', depending on context.
27146 See the individual commands for more information."
27147 (interactive)
27148 (cond
27149 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27150 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27151 ((org-at-item-p) (call-interactively 'org-indent-item))
27152 (t (org-shiftcursor-error))))
27154 (defun org-shiftmetaup (&optional arg)
27155 "Move subtree up or kill table row.
27156 Calls `org-move-subtree-up' or `org-table-kill-row' or
27157 `org-move-item-up' depending on context. See the individual commands
27158 for more information."
27159 (interactive "P")
27160 (cond
27161 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27162 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27163 ((org-at-item-p) (call-interactively 'org-move-item-up))
27164 (t (org-shiftcursor-error))))
27165 (defun org-shiftmetadown (&optional arg)
27166 "Move subtree down or insert table row.
27167 Calls `org-move-subtree-down' or `org-table-insert-row' or
27168 `org-move-item-down', depending on context. See the individual
27169 commands for more information."
27170 (interactive "P")
27171 (cond
27172 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27173 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27174 ((org-at-item-p) (call-interactively 'org-move-item-down))
27175 (t (org-shiftcursor-error))))
27177 (defun org-metaleft (&optional arg)
27178 "Promote heading or move table column to left.
27179 Calls `org-do-promote' or `org-table-move-column', depending on context.
27180 With no specific context, calls the Emacs default `backward-word'.
27181 See the individual commands for more information."
27182 (interactive "P")
27183 (cond
27184 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27185 ((or (org-on-heading-p) (org-region-active-p))
27186 (call-interactively 'org-do-promote))
27187 ((org-at-item-p) (call-interactively 'org-outdent-item))
27188 (t (call-interactively 'backward-word))))
27190 (defun org-metaright (&optional arg)
27191 "Demote subtree or move table column to right.
27192 Calls `org-do-demote' or `org-table-move-column', depending on context.
27193 With no specific context, calls the Emacs default `forward-word'.
27194 See the individual commands for more information."
27195 (interactive "P")
27196 (cond
27197 ((org-at-table-p) (call-interactively 'org-table-move-column))
27198 ((or (org-on-heading-p) (org-region-active-p))
27199 (call-interactively 'org-do-demote))
27200 ((org-at-item-p) (call-interactively 'org-indent-item))
27201 (t (call-interactively 'forward-word))))
27203 (defun org-metaup (&optional arg)
27204 "Move subtree up or move table row up.
27205 Calls `org-move-subtree-up' or `org-table-move-row' or
27206 `org-move-item-up', depending on context. See the individual commands
27207 for more information."
27208 (interactive "P")
27209 (cond
27210 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27211 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27212 ((org-at-item-p) (call-interactively 'org-move-item-up))
27213 (t (transpose-lines 1) (beginning-of-line -1))))
27215 (defun org-metadown (&optional arg)
27216 "Move subtree down or move table row down.
27217 Calls `org-move-subtree-down' or `org-table-move-row' or
27218 `org-move-item-down', depending on context. See the individual
27219 commands for more information."
27220 (interactive "P")
27221 (cond
27222 ((org-at-table-p) (call-interactively 'org-table-move-row))
27223 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27224 ((org-at-item-p) (call-interactively 'org-move-item-down))
27225 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27227 (defun org-shiftup (&optional arg)
27228 "Increase item in timestamp or increase priority of current headline.
27229 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27230 depending on context. See the individual commands for more information."
27231 (interactive "P")
27232 (cond
27233 ((org-at-timestamp-p t)
27234 (call-interactively (if org-edit-timestamp-down-means-later
27235 'org-timestamp-down 'org-timestamp-up)))
27236 ((org-on-heading-p) (call-interactively 'org-priority-up))
27237 ((org-at-item-p) (call-interactively 'org-previous-item))
27238 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27240 (defun org-shiftdown (&optional arg)
27241 "Decrease item in timestamp or decrease priority of current headline.
27242 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27243 depending on context. See the individual commands for more information."
27244 (interactive "P")
27245 (cond
27246 ((org-at-timestamp-p t)
27247 (call-interactively (if org-edit-timestamp-down-means-later
27248 'org-timestamp-up 'org-timestamp-down)))
27249 ((org-on-heading-p) (call-interactively 'org-priority-down))
27250 (t (call-interactively 'org-next-item))))
27252 (defun org-shiftright ()
27253 "Next TODO keyword or timestamp one day later, depending on context."
27254 (interactive)
27255 (cond
27256 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27257 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27258 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27259 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27260 (t (org-shiftcursor-error))))
27262 (defun org-shiftleft ()
27263 "Previous TODO keyword or timestamp one day earlier, depending on context."
27264 (interactive)
27265 (cond
27266 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27267 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27268 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27269 ((org-at-property-p)
27270 (call-interactively 'org-property-previous-allowed-value))
27271 (t (org-shiftcursor-error))))
27273 (defun org-shiftcontrolright ()
27274 "Switch to next TODO set."
27275 (interactive)
27276 (cond
27277 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27278 (t (org-shiftcursor-error))))
27280 (defun org-shiftcontrolleft ()
27281 "Switch to previous TODO set."
27282 (interactive)
27283 (cond
27284 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27285 (t (org-shiftcursor-error))))
27287 (defun org-ctrl-c-ret ()
27288 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27289 (interactive)
27290 (cond
27291 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27292 (t (call-interactively 'org-insert-heading))))
27294 (defun org-copy-special ()
27295 "Copy region in table or copy current subtree.
27296 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27297 See the individual commands for more information."
27298 (interactive)
27299 (call-interactively
27300 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27302 (defun org-cut-special ()
27303 "Cut region in table or cut current subtree.
27304 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27305 See the individual commands for more information."
27306 (interactive)
27307 (call-interactively
27308 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27310 (defun org-paste-special (arg)
27311 "Paste rectangular region into table, or past subtree relative to level.
27312 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27313 See the individual commands for more information."
27314 (interactive "P")
27315 (if (org-at-table-p)
27316 (org-table-paste-rectangle)
27317 (org-paste-subtree arg)))
27319 (defun org-ctrl-c-ctrl-c (&optional arg)
27320 "Set tags in headline, or update according to changed information at point.
27322 This command does many different things, depending on context:
27324 - If the cursor is in a headline, prompt for tags and insert them
27325 into the current line, aligned to `org-tags-column'. When called
27326 with prefix arg, realign all tags in the current buffer.
27328 - If the cursor is in one of the special #+KEYWORD lines, this
27329 triggers scanning the buffer for these lines and updating the
27330 information.
27332 - If the cursor is inside a table, realign the table. This command
27333 works even if the automatic table editor has been turned off.
27335 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27336 the entire table.
27338 - If the cursor is a the beginning of a dynamic block, update it.
27340 - If the cursor is inside a table created by the table.el package,
27341 activate that table.
27343 - If the current buffer is a remember buffer, close note and file it.
27344 with a prefix argument, file it without further interaction to the default
27345 location.
27347 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27348 links in this buffer.
27350 - If the cursor is on a numbered item in a plain list, renumber the
27351 ordered list.
27353 - If the cursor is on a checkbox, toggle it."
27354 (interactive "P")
27355 (let ((org-enable-table-editor t))
27356 (cond
27357 ((or org-clock-overlays
27358 org-occur-highlights
27359 org-latex-fragment-image-overlays)
27360 (org-remove-clock-overlays)
27361 (org-remove-occur-highlights)
27362 (org-remove-latex-fragment-image-overlays)
27363 (message "Temporary highlights/overlays removed from current buffer"))
27364 ((and (local-variable-p 'org-finish-function (current-buffer))
27365 (fboundp org-finish-function))
27366 (funcall org-finish-function))
27367 ((org-at-property-p)
27368 (call-interactively 'org-property-action))
27369 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27370 ((org-on-heading-p) (call-interactively 'org-set-tags))
27371 ((org-at-table.el-p)
27372 (require 'table)
27373 (beginning-of-line 1)
27374 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27375 (call-interactively 'table-recognize-table))
27376 ((org-at-table-p)
27377 (org-table-maybe-eval-formula)
27378 (if arg
27379 (call-interactively 'org-table-recalculate)
27380 (org-table-maybe-recalculate-line))
27381 (call-interactively 'org-table-align))
27382 ((org-at-item-checkbox-p)
27383 (call-interactively 'org-toggle-checkbox))
27384 ((org-at-item-p)
27385 (call-interactively 'org-maybe-renumber-ordered-list))
27386 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27387 ;; Dynamic block
27388 (beginning-of-line 1)
27389 (org-update-dblock))
27390 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27391 (cond
27392 ((equal (match-string 1) "TBLFM")
27393 ;; Recalculate the table before this line
27394 (save-excursion
27395 (beginning-of-line 1)
27396 (skip-chars-backward " \r\n\t")
27397 (if (org-at-table-p)
27398 (org-call-with-arg 'org-table-recalculate t))))
27400 (call-interactively 'org-mode-restart))))
27401 (t (error "C-c C-c can do nothing useful at this location.")))))
27403 (defun org-mode-restart ()
27404 "Restart Org-mode, to scan again for special lines.
27405 Also updates the keyword regular expressions."
27406 (interactive)
27407 (let ((org-inhibit-startup t)) (org-mode))
27408 (message "Org-mode restarted to refresh keyword and special line setup"))
27410 (defun org-kill-note-or-show-branches ()
27411 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27412 (interactive)
27413 (if (not org-finish-function)
27414 (call-interactively 'show-branches)
27415 (let ((org-note-abort t))
27416 (funcall org-finish-function))))
27418 (defun org-return (&optional indent)
27419 "Goto next table row or insert a newline.
27420 Calls `org-table-next-row' or `newline', depending on context.
27421 See the individual commands for more information."
27422 (interactive)
27423 (cond
27424 ((bobp) (if indent (newline-and-indent) (newline)))
27425 ((and (org-at-heading-p)
27426 (looking-at
27427 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27428 (org-show-entry)
27429 (end-of-line 1)
27430 (newline))
27431 ((org-at-table-p)
27432 (org-table-justify-field-maybe)
27433 (call-interactively 'org-table-next-row))
27434 (t (if indent (newline-and-indent) (newline)))))
27436 (defun org-return-indent ()
27437 (interactive)
27438 "Goto next table row or insert a newline and indent.
27439 Calls `org-table-next-row' or `newline-and-indent', depending on
27440 context. See the individual commands for more information."
27441 (org-return t))
27443 (defun org-ctrl-c-minus ()
27444 "Insert separator line in table or modify bullet type in list.
27445 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
27446 depending on context."
27447 (interactive)
27448 (cond
27449 ((org-at-table-p)
27450 (call-interactively 'org-table-insert-hline))
27451 ((org-on-heading-p)
27452 ;; Convert to item
27453 (save-excursion
27454 (beginning-of-line 1)
27455 (if (looking-at "\\*+ ")
27456 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27457 ((org-in-item-p)
27458 (call-interactively 'org-cycle-list-bullet))
27459 (t (error "`C-c -' does have no function here."))))
27461 (defun org-meta-return (&optional arg)
27462 "Insert a new heading or wrap a region in a table.
27463 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27464 See the individual commands for more information."
27465 (interactive "P")
27466 (cond
27467 ((org-at-table-p)
27468 (call-interactively 'org-table-wrap-region))
27469 (t (call-interactively 'org-insert-heading))))
27471 ;;; Menu entries
27473 ;; Define the Org-mode menus
27474 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27475 '("Tbl"
27476 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27477 ["Next Field" org-cycle (org-at-table-p)]
27478 ["Previous Field" org-shifttab (org-at-table-p)]
27479 ["Next Row" org-return (org-at-table-p)]
27480 "--"
27481 ["Blank Field" org-table-blank-field (org-at-table-p)]
27482 ["Edit Field" org-table-edit-field (org-at-table-p)]
27483 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27484 "--"
27485 ("Column"
27486 ["Move Column Left" org-metaleft (org-at-table-p)]
27487 ["Move Column Right" org-metaright (org-at-table-p)]
27488 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27489 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27490 ("Row"
27491 ["Move Row Up" org-metaup (org-at-table-p)]
27492 ["Move Row Down" org-metadown (org-at-table-p)]
27493 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27494 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27495 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27496 "--"
27497 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27498 ("Rectangle"
27499 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27500 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27501 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27502 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27503 "--"
27504 ("Calculate"
27505 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27506 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27507 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27508 "--"
27509 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27510 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27511 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27512 "--"
27513 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27514 "--"
27515 ["Sum Column/Rectangle" org-table-sum
27516 (or (org-at-table-p) (org-region-active-p))]
27517 ["Which Column?" org-table-current-column (org-at-table-p)])
27518 ["Debug Formulas"
27519 org-table-toggle-formula-debugger
27520 :style toggle :selected org-table-formula-debug]
27521 ["Show Col/Row Numbers"
27522 org-table-toggle-coordinate-overlays
27523 :style toggle :selected org-table-overlay-coordinates]
27524 "--"
27525 ["Create" org-table-create (and (not (org-at-table-p))
27526 org-enable-table-editor)]
27527 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27528 ["Import from File" org-table-import (not (org-at-table-p))]
27529 ["Export to File" org-table-export (org-at-table-p)]
27530 "--"
27531 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27533 (easy-menu-define org-org-menu org-mode-map "Org menu"
27534 '("Org"
27535 ("Show/Hide"
27536 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27537 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27538 ["Sparse Tree" org-occur t]
27539 ["Reveal Context" org-reveal t]
27540 ["Show All" show-all t]
27541 "--"
27542 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27543 "--"
27544 ["New Heading" org-insert-heading t]
27545 ("Navigate Headings"
27546 ["Up" outline-up-heading t]
27547 ["Next" outline-next-visible-heading t]
27548 ["Previous" outline-previous-visible-heading t]
27549 ["Next Same Level" outline-forward-same-level t]
27550 ["Previous Same Level" outline-backward-same-level t]
27551 "--"
27552 ["Jump" org-goto t])
27553 ("Edit Structure"
27554 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27555 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27556 "--"
27557 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27558 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27559 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27560 "--"
27561 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27562 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27563 ["Demote Heading" org-metaright (not (org-at-table-p))]
27564 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27565 "--"
27566 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27567 "--"
27568 ["Convert to odd levels" org-convert-to-odd-levels t]
27569 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27570 ("Editing"
27571 ["Emphasis..." org-emphasize t])
27572 ("Archive"
27573 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27574 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27575 ; :active t :keys "C-u C-c C-x C-a"]
27576 ["Sparse trees open ARCHIVE trees"
27577 (setq org-sparse-tree-open-archived-trees
27578 (not org-sparse-tree-open-archived-trees))
27579 :style toggle :selected org-sparse-tree-open-archived-trees]
27580 ["Cycling opens ARCHIVE trees"
27581 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27582 :style toggle :selected org-cycle-open-archived-trees]
27583 ["Agenda includes ARCHIVE trees"
27584 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27585 :style toggle :selected (not org-agenda-skip-archived-trees)]
27586 "--"
27587 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27588 ; ["Check and Move Children" (org-archive-subtree '(4))
27589 ; :active t :keys "C-u C-c C-x C-s"]
27591 "--"
27592 ("TODO Lists"
27593 ["TODO/DONE/-" org-todo t]
27594 ("Select keyword"
27595 ["Next keyword" org-shiftright (org-on-heading-p)]
27596 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27597 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27598 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27599 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27600 ["Show TODO Tree" org-show-todo-tree t]
27601 ["Global TODO list" org-todo-list t]
27602 "--"
27603 ["Set Priority" org-priority t]
27604 ["Priority Up" org-shiftup t]
27605 ["Priority Down" org-shiftdown t])
27606 ("TAGS and Properties"
27607 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27608 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27609 "--"
27610 ["Set property" 'org-set-property t]
27611 ["Column view of properties" org-columns t]
27612 ["Insert Column View DBlock" org-insert-columns-dblock t])
27613 ("Dates and Scheduling"
27614 ["Timestamp" org-time-stamp t]
27615 ["Timestamp (inactive)" org-time-stamp-inactive t]
27616 ("Change Date"
27617 ["1 Day Later" org-shiftright t]
27618 ["1 Day Earlier" org-shiftleft t]
27619 ["1 ... Later" org-shiftup t]
27620 ["1 ... Earlier" org-shiftdown t])
27621 ["Compute Time Range" org-evaluate-time-range t]
27622 ["Schedule Item" org-schedule t]
27623 ["Deadline" org-deadline t]
27624 "--"
27625 ["Custom time format" org-toggle-time-stamp-overlays
27626 :style radio :selected org-display-custom-times]
27627 "--"
27628 ["Goto Calendar" org-goto-calendar t]
27629 ["Date from Calendar" org-date-from-calendar t])
27630 ("Logging work"
27631 ["Clock in" org-clock-in t]
27632 ["Clock out" org-clock-out t]
27633 ["Clock cancel" org-clock-cancel t]
27634 ["Goto running clock" org-clock-goto t]
27635 ["Display times" org-clock-display t]
27636 ["Create clock table" org-clock-report t]
27637 "--"
27638 ["Record DONE time"
27639 (progn (setq org-log-done (not org-log-done))
27640 (message "Switching to %s will %s record a timestamp"
27641 (car org-done-keywords)
27642 (if org-log-done "automatically" "not")))
27643 :style toggle :selected org-log-done])
27644 "--"
27645 ["Agenda Command..." org-agenda t]
27646 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27647 ("File List for Agenda")
27648 ("Special views current file"
27649 ["TODO Tree" org-show-todo-tree t]
27650 ["Check Deadlines" org-check-deadlines t]
27651 ["Timeline" org-timeline t]
27652 ["Tags Tree" org-tags-sparse-tree t])
27653 "--"
27654 ("Hyperlinks"
27655 ["Store Link (Global)" org-store-link t]
27656 ["Insert Link" org-insert-link t]
27657 ["Follow Link" org-open-at-point t]
27658 "--"
27659 ["Next link" org-next-link t]
27660 ["Previous link" org-previous-link t]
27661 "--"
27662 ["Descriptive Links"
27663 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27664 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27665 ["Literal Links"
27666 (progn
27667 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27668 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27669 "--"
27670 ["Export/Publish..." org-export t]
27671 ("LaTeX"
27672 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27673 :selected org-cdlatex-mode]
27674 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27675 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27676 ["Modify math symbol" org-cdlatex-math-modify
27677 (org-inside-LaTeX-fragment-p)]
27678 ["Export LaTeX fragments as images"
27679 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27680 :style toggle :selected org-export-with-LaTeX-fragments])
27681 "--"
27682 ("Documentation"
27683 ["Show Version" org-version t]
27684 ["Info Documentation" org-info t])
27685 ("Customize"
27686 ["Browse Org Group" org-customize t]
27687 "--"
27688 ["Expand This Menu" org-create-customize-menu
27689 (fboundp 'customize-menu-create)])
27690 "--"
27691 ["Refresh setup" org-mode-restart t]
27694 (defun org-info (&optional node)
27695 "Read documentation for Org-mode in the info system.
27696 With optional NODE, go directly to that node."
27697 (interactive)
27698 (require 'info)
27699 (info (format "(org)%s" (or node ""))))
27701 (defun org-install-agenda-files-menu ()
27702 (let ((bl (buffer-list)))
27703 (save-excursion
27704 (while bl
27705 (set-buffer (pop bl))
27706 (if (org-mode-p) (setq bl nil)))
27707 (when (org-mode-p)
27708 (easy-menu-change
27709 '("Org") "File List for Agenda"
27710 (append
27711 (list
27712 ["Edit File List" (org-edit-agenda-file-list) t]
27713 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27714 ["Remove Current File from List" org-remove-file t]
27715 ["Cycle through agenda files" org-cycle-agenda-files t]
27716 ["Occur in all agenda files" org-occur-in-agenda-files t]
27717 "--")
27718 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27720 ;;;; Documentation
27722 (defun org-customize ()
27723 "Call the customize function with org as argument."
27724 (interactive)
27725 (customize-browse 'org))
27727 (defun org-create-customize-menu ()
27728 "Create a full customization menu for Org-mode, insert it into the menu."
27729 (interactive)
27730 (if (fboundp 'customize-menu-create)
27731 (progn
27732 (easy-menu-change
27733 '("Org") "Customize"
27734 `(["Browse Org group" org-customize t]
27735 "--"
27736 ,(customize-menu-create 'org)
27737 ["Set" Custom-set t]
27738 ["Save" Custom-save t]
27739 ["Reset to Current" Custom-reset-current t]
27740 ["Reset to Saved" Custom-reset-saved t]
27741 ["Reset to Standard Settings" Custom-reset-standard t]))
27742 (message "\"Org\"-menu now contains full customization menu"))
27743 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27745 ;;;; Miscellaneous stuff
27748 ;;; Generally useful functions
27750 (defun org-context ()
27751 "Return a list of contexts of the current cursor position.
27752 If several contexts apply, all are returned.
27753 Each context entry is a list with a symbol naming the context, and
27754 two positions indicating start and end of the context. Possible
27755 contexts are:
27757 :headline anywhere in a headline
27758 :headline-stars on the leading stars in a headline
27759 :todo-keyword on a TODO keyword (including DONE) in a headline
27760 :tags on the TAGS in a headline
27761 :priority on the priority cookie in a headline
27762 :item on the first line of a plain list item
27763 :item-bullet on the bullet/number of a plain list item
27764 :checkbox on the checkbox in a plain list item
27765 :table in an org-mode table
27766 :table-special on a special filed in a table
27767 :table-table in a table.el table
27768 :link on a hyperlink
27769 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27770 :target on a <<target>>
27771 :radio-target on a <<<radio-target>>>
27772 :latex-fragment on a LaTeX fragment
27773 :latex-preview on a LaTeX fragment with overlayed preview image
27775 This function expects the position to be visible because it uses font-lock
27776 faces as a help to recognize the following contexts: :table-special, :link,
27777 and :keyword."
27778 (let* ((f (get-text-property (point) 'face))
27779 (faces (if (listp f) f (list f)))
27780 (p (point)) clist o)
27781 ;; First the large context
27782 (cond
27783 ((org-on-heading-p t)
27784 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27785 (when (progn
27786 (beginning-of-line 1)
27787 (looking-at org-todo-line-tags-regexp))
27788 (push (org-point-in-group p 1 :headline-stars) clist)
27789 (push (org-point-in-group p 2 :todo-keyword) clist)
27790 (push (org-point-in-group p 4 :tags) clist))
27791 (goto-char p)
27792 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27793 (if (looking-at "\\[#[A-Z0-9]\\]")
27794 (push (org-point-in-group p 0 :priority) clist)))
27796 ((org-at-item-p)
27797 (push (org-point-in-group p 2 :item-bullet) clist)
27798 (push (list :item (point-at-bol)
27799 (save-excursion (org-end-of-item) (point)))
27800 clist)
27801 (and (org-at-item-checkbox-p)
27802 (push (org-point-in-group p 0 :checkbox) clist)))
27804 ((org-at-table-p)
27805 (push (list :table (org-table-begin) (org-table-end)) clist)
27806 (if (memq 'org-formula faces)
27807 (push (list :table-special
27808 (previous-single-property-change p 'face)
27809 (next-single-property-change p 'face)) clist)))
27810 ((org-at-table-p 'any)
27811 (push (list :table-table) clist)))
27812 (goto-char p)
27814 ;; Now the small context
27815 (cond
27816 ((org-at-timestamp-p)
27817 (push (org-point-in-group p 0 :timestamp) clist))
27818 ((memq 'org-link faces)
27819 (push (list :link
27820 (previous-single-property-change p 'face)
27821 (next-single-property-change p 'face)) clist))
27822 ((memq 'org-special-keyword faces)
27823 (push (list :keyword
27824 (previous-single-property-change p 'face)
27825 (next-single-property-change p 'face)) clist))
27826 ((org-on-target-p)
27827 (push (org-point-in-group p 0 :target) clist)
27828 (goto-char (1- (match-beginning 0)))
27829 (if (looking-at org-radio-target-regexp)
27830 (push (org-point-in-group p 0 :radio-target) clist))
27831 (goto-char p))
27832 ((setq o (car (delq nil
27833 (mapcar
27834 (lambda (x)
27835 (if (memq x org-latex-fragment-image-overlays) x))
27836 (org-overlays-at (point))))))
27837 (push (list :latex-fragment
27838 (org-overlay-start o) (org-overlay-end o)) clist)
27839 (push (list :latex-preview
27840 (org-overlay-start o) (org-overlay-end o)) clist))
27841 ((org-inside-LaTeX-fragment-p)
27842 ;; FIXME: positions wrong.
27843 (push (list :latex-fragment (point) (point)) clist)))
27845 (setq clist (nreverse (delq nil clist)))
27846 clist))
27848 ;; FIXME: Compare with at-regexp-p Do we need both?
27849 (defun org-in-regexp (re &optional nlines visually)
27850 "Check if point is inside a match of regexp.
27851 Normally only the current line is checked, but you can include NLINES extra
27852 lines both before and after point into the search.
27853 If VISUALLY is set, require that the cursor is not after the match but
27854 really on, so that the block visually is on the match."
27855 (catch 'exit
27856 (let ((pos (point))
27857 (eol (point-at-eol (+ 1 (or nlines 0))))
27858 (inc (if visually 1 0)))
27859 (save-excursion
27860 (beginning-of-line (- 1 (or nlines 0)))
27861 (while (re-search-forward re eol t)
27862 (if (and (<= (match-beginning 0) pos)
27863 (>= (+ inc (match-end 0)) pos))
27864 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27866 (defun org-at-regexp-p (regexp)
27867 "Is point inside a match of REGEXP in the current line?"
27868 (catch 'exit
27869 (save-excursion
27870 (let ((pos (point)) (end (point-at-eol)))
27871 (beginning-of-line 1)
27872 (while (re-search-forward regexp end t)
27873 (if (and (<= (match-beginning 0) pos)
27874 (>= (match-end 0) pos))
27875 (throw 'exit t)))
27876 nil))))
27878 (defun org-occur-in-agenda-files (regexp &optional nlines)
27879 "Call `multi-occur' with buffers for all agenda files."
27880 (interactive "sOrg-files matching: \np")
27881 (let* ((files (org-agenda-files))
27882 (tnames (mapcar 'file-truename files))
27883 (extra org-agenda-text-search-extra-files)
27885 (while (setq f (pop extra))
27886 (unless (member (file-truename f) tnames)
27887 (add-to-list 'files f 'append)
27888 (add-to-list 'tnames (file-truename f) 'append)))
27889 (multi-occur
27890 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27891 regexp)))
27893 (if (boundp 'occur-mode-find-occurrence-hook)
27894 ;; Emacs 23
27895 (add-hook 'occur-mode-find-occurrence-hook
27896 (lambda ()
27897 (when (org-mode-p)
27898 (org-reveal))))
27899 ;; Emacs 22
27900 (defadvice occur-mode-goto-occurrence
27901 (after org-occur-reveal activate)
27902 (and (org-mode-p) (org-reveal)))
27903 (defadvice occur-mode-goto-occurrence-other-window
27904 (after org-occur-reveal activate)
27905 (and (org-mode-p) (org-reveal)))
27906 (defadvice occur-mode-display-occurrence
27907 (after org-occur-reveal activate)
27908 (when (org-mode-p)
27909 (let ((pos (occur-mode-find-occurrence)))
27910 (with-current-buffer (marker-buffer pos)
27911 (save-excursion
27912 (goto-char pos)
27913 (org-reveal)))))))
27915 (defun org-uniquify (list)
27916 "Remove duplicate elements from LIST."
27917 (let (res)
27918 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27919 res))
27921 (defun org-delete-all (elts list)
27922 "Remove all elements in ELTS from LIST."
27923 (while elts
27924 (setq list (delete (pop elts) list)))
27925 list)
27927 (defun org-back-over-empty-lines ()
27928 "Move backwards over witespace, to the beginning of the first empty line.
27929 Returns the number o empty lines passed."
27930 (let ((pos (point)))
27931 (skip-chars-backward " \t\n\r")
27932 (beginning-of-line 2)
27933 (goto-char (min (point) pos))
27934 (count-lines (point) pos)))
27936 (defun org-skip-whitespace ()
27937 (skip-chars-forward " \t\n\r"))
27939 (defun org-point-in-group (point group &optional context)
27940 "Check if POINT is in match-group GROUP.
27941 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27942 match. If the match group does ot exist or point is not inside it,
27943 return nil."
27944 (and (match-beginning group)
27945 (>= point (match-beginning group))
27946 (<= point (match-end group))
27947 (if context
27948 (list context (match-beginning group) (match-end group))
27949 t)))
27951 (defun org-switch-to-buffer-other-window (&rest args)
27952 "Switch to buffer in a second window on the current frame.
27953 In particular, do not allow pop-up frames."
27954 (let (pop-up-frames special-display-buffer-names special-display-regexps
27955 special-display-function)
27956 (apply 'switch-to-buffer-other-window args)))
27958 (defun org-combine-plists (&rest plists)
27959 "Create a single property list from all plists in PLISTS.
27960 The process starts by copying the first list, and then setting properties
27961 from the other lists. Settings in the last list are the most significant
27962 ones and overrule settings in the other lists."
27963 (let ((rtn (copy-sequence (pop plists)))
27964 p v ls)
27965 (while plists
27966 (setq ls (pop plists))
27967 (while ls
27968 (setq p (pop ls) v (pop ls))
27969 (setq rtn (plist-put rtn p v))))
27970 rtn))
27972 (defun org-move-line-down (arg)
27973 "Move the current line down. With prefix argument, move it past ARG lines."
27974 (interactive "p")
27975 (let ((col (current-column))
27976 beg end pos)
27977 (beginning-of-line 1) (setq beg (point))
27978 (beginning-of-line 2) (setq end (point))
27979 (beginning-of-line (+ 1 arg))
27980 (setq pos (move-marker (make-marker) (point)))
27981 (insert (delete-and-extract-region beg end))
27982 (goto-char pos)
27983 (move-to-column col)))
27985 (defun org-move-line-up (arg)
27986 "Move the current line up. With prefix argument, move it past ARG lines."
27987 (interactive "p")
27988 (let ((col (current-column))
27989 beg end pos)
27990 (beginning-of-line 1) (setq beg (point))
27991 (beginning-of-line 2) (setq end (point))
27992 (beginning-of-line (- arg))
27993 (setq pos (move-marker (make-marker) (point)))
27994 (insert (delete-and-extract-region beg end))
27995 (goto-char pos)
27996 (move-to-column col)))
27998 (defun org-replace-escapes (string table)
27999 "Replace %-escapes in STRING with values in TABLE.
28000 TABLE is an association list with keys like \"%a\" and string values.
28001 The sequences in STRING may contain normal field width and padding information,
28002 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28003 so values can contain further %-escapes if they are define later in TABLE."
28004 (let ((case-fold-search nil)
28005 e re rpl)
28006 (while (setq e (pop table))
28007 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28008 (while (string-match re string)
28009 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28010 (cdr e)))
28011 (setq string (replace-match rpl t t string))))
28012 string))
28015 (defun org-sublist (list start end)
28016 "Return a section of LIST, from START to END.
28017 Counting starts at 1."
28018 (let (rtn (c start))
28019 (setq list (nthcdr (1- start) list))
28020 (while (and list (<= c end))
28021 (push (pop list) rtn)
28022 (setq c (1+ c)))
28023 (nreverse rtn)))
28025 (defun org-find-base-buffer-visiting (file)
28026 "Like `find-buffer-visiting' but alway return the base buffer and
28027 not an indirect buffer"
28028 (let ((buf (find-buffer-visiting file)))
28029 (if buf
28030 (or (buffer-base-buffer buf) buf)
28031 nil)))
28033 (defun org-image-file-name-regexp ()
28034 "Return regexp matching the file names of images."
28035 (if (fboundp 'image-file-name-regexp)
28036 (image-file-name-regexp)
28037 (let ((image-file-name-extensions
28038 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28039 "xbm" "xpm" "pbm" "pgm" "ppm")))
28040 (concat "\\."
28041 (regexp-opt (nconc (mapcar 'upcase
28042 image-file-name-extensions)
28043 image-file-name-extensions)
28045 "\\'"))))
28047 (defun org-file-image-p (file)
28048 "Return non-nil if FILE is an image."
28049 (save-match-data
28050 (string-match (org-image-file-name-regexp) file)))
28052 ;;; Paragraph filling stuff.
28053 ;; We want this to be just right, so use the full arsenal.
28055 (defun org-indent-line-function ()
28056 "Indent line like previous, but further if previous was headline or item."
28057 (interactive)
28058 (let* ((pos (point))
28059 (itemp (org-at-item-p))
28060 column bpos bcol tpos tcol bullet btype bullet-type)
28061 ;; Find the previous relevant line
28062 (beginning-of-line 1)
28063 (cond
28064 ((looking-at "#") (setq column 0))
28065 ((looking-at "\\*+ ") (setq column 0))
28067 (beginning-of-line 0)
28068 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28069 (beginning-of-line 0))
28070 (cond
28071 ((looking-at "\\*+[ \t]+")
28072 (goto-char (match-end 0))
28073 (setq column (current-column)))
28074 ((org-in-item-p)
28075 (org-beginning-of-item)
28076 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28077 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28078 (setq bpos (match-beginning 1) tpos (match-end 0)
28079 bcol (progn (goto-char bpos) (current-column))
28080 tcol (progn (goto-char tpos) (current-column))
28081 bullet (match-string 1)
28082 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28083 (if (not itemp)
28084 (setq column tcol)
28085 (goto-char pos)
28086 (beginning-of-line 1)
28087 (if (looking-at "\\S-")
28088 (progn
28089 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28090 (setq bullet (match-string 1)
28091 btype (if (string-match "[0-9]" bullet) "n" bullet))
28092 (setq column (if (equal btype bullet-type) bcol tcol)))
28093 (setq column (org-get-indentation)))))
28094 (t (setq column (org-get-indentation))))))
28095 (goto-char pos)
28096 (if (<= (current-column) (current-indentation))
28097 (indent-line-to column)
28098 (save-excursion (indent-line-to column)))
28099 (setq column (current-column))
28100 (beginning-of-line 1)
28101 (if (looking-at
28102 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28103 (replace-match (concat "\\1" (format org-property-format
28104 (match-string 2) (match-string 3)))
28105 t nil))
28106 (move-to-column column)))
28108 (defun org-set-autofill-regexps ()
28109 (interactive)
28110 ;; In the paragraph separator we include headlines, because filling
28111 ;; text in a line directly attached to a headline would otherwise
28112 ;; fill the headline as well.
28113 (org-set-local 'comment-start-skip "^#+[ \t]*")
28114 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28115 ;; The paragraph starter includes hand-formatted lists.
28116 (org-set-local 'paragraph-start
28117 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28118 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28119 ;; But only if the user has not turned off tables or fixed-width regions
28120 (org-set-local
28121 'auto-fill-inhibit-regexp
28122 (concat "\\*+ \\|#\\+"
28123 "\\|[ \t]*" org-keyword-time-regexp
28124 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28125 (concat
28126 "\\|[ \t]*["
28127 (if org-enable-table-editor "|" "")
28128 (if org-enable-fixed-width-editor ":" "")
28129 "]"))))
28130 ;; We use our own fill-paragraph function, to make sure that tables
28131 ;; and fixed-width regions are not wrapped. That function will pass
28132 ;; through to `fill-paragraph' when appropriate.
28133 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28134 ; Adaptive filling: To get full control, first make sure that
28135 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28136 (org-set-local 'adaptive-fill-regexp "\000")
28137 (org-set-local 'adaptive-fill-function
28138 'org-adaptive-fill-function)
28139 (org-set-local
28140 'align-mode-rules-list
28141 '((org-in-buffer-settings
28142 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28143 (modes . '(org-mode))))))
28145 (defun org-fill-paragraph (&optional justify)
28146 "Re-align a table, pass through to fill-paragraph if no table."
28147 (let ((table-p (org-at-table-p))
28148 (table.el-p (org-at-table.el-p)))
28149 (cond ((and (equal (char-after (point-at-bol)) ?*)
28150 (save-excursion (goto-char (point-at-bol))
28151 (looking-at outline-regexp)))
28152 t) ; skip headlines
28153 (table.el-p t) ; skip table.el tables
28154 (table-p (org-table-align) t) ; align org-mode tables
28155 (t nil)))) ; call paragraph-fill
28157 ;; For reference, this is the default value of adaptive-fill-regexp
28158 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28160 (defun org-adaptive-fill-function ()
28161 "Return a fill prefix for org-mode files.
28162 In particular, this makes sure hanging paragraphs for hand-formatted lists
28163 work correctly."
28164 (cond ((looking-at "#[ \t]+")
28165 (match-string 0))
28166 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28167 (save-excursion
28168 (goto-char (match-end 0))
28169 (make-string (current-column) ?\ )))
28170 (t nil)))
28172 ;;;; Functions extending outline functionality
28175 (defun org-beginning-of-line (&optional arg)
28176 "Go to the beginning of the current line. If that is invisible, continue
28177 to a visible line beginning. This makes the function of C-a more intuitive.
28178 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28179 first attempt, and only move to after the tags when the cursor is already
28180 beyond the end of the headline."
28181 (interactive "P")
28182 (let ((pos (point)))
28183 (beginning-of-line 1)
28184 (if (bobp)
28186 (backward-char 1)
28187 (if (org-invisible-p)
28188 (while (and (not (bobp)) (org-invisible-p))
28189 (backward-char 1)
28190 (beginning-of-line 1))
28191 (forward-char 1)))
28192 (when org-special-ctrl-a/e
28193 (cond
28194 ((and (looking-at org-todo-line-regexp)
28195 (= (char-after (match-end 1)) ?\ ))
28196 (goto-char
28197 (if (eq org-special-ctrl-a/e t)
28198 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28199 ((= pos (point)) (match-beginning 3))
28200 (t (point)))
28201 (cond ((> pos (point)) (point))
28202 ((not (eq last-command this-command)) (point))
28203 (t (match-beginning 3))))))
28204 ((org-at-item-p)
28205 (goto-char
28206 (if (eq org-special-ctrl-a/e t)
28207 (cond ((> pos (match-end 4)) (match-end 4))
28208 ((= pos (point)) (match-end 4))
28209 (t (point)))
28210 (cond ((> pos (point)) (point))
28211 ((not (eq last-command this-command)) (point))
28212 (t (match-end 4))))))))))
28214 (defun org-end-of-line (&optional arg)
28215 "Go to the end of the line.
28216 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28217 first attempt, and only move to after the tags when the cursor is already
28218 beyond the end of the headline."
28219 (interactive "P")
28220 (if (or (not org-special-ctrl-a/e)
28221 (not (org-on-heading-p)))
28222 (end-of-line arg)
28223 (let ((pos (point)))
28224 (beginning-of-line 1)
28225 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28226 (if (eq org-special-ctrl-a/e t)
28227 (if (or (< pos (match-beginning 1))
28228 (= pos (match-end 0)))
28229 (goto-char (match-beginning 1))
28230 (goto-char (match-end 0)))
28231 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28232 (goto-char (match-end 0))
28233 (goto-char (match-beginning 1))))
28234 (end-of-line arg)))))
28236 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28237 (define-key org-mode-map "\C-e" 'org-end-of-line)
28239 (defun org-kill-line (&optional arg)
28240 "Kill line, to tags or end of line."
28241 (interactive "P")
28242 (cond
28243 ((or (not org-special-ctrl-k)
28244 (bolp)
28245 (not (org-on-heading-p)))
28246 (call-interactively 'kill-line))
28247 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28248 (kill-region (point) (match-beginning 1))
28249 (org-set-tags nil t))
28250 (t (kill-region (point) (point-at-eol)))))
28252 (define-key org-mode-map "\C-k" 'org-kill-line)
28254 (defun org-invisible-p ()
28255 "Check if point is at a character currently not visible."
28256 ;; Early versions of noutline don't have `outline-invisible-p'.
28257 (if (fboundp 'outline-invisible-p)
28258 (outline-invisible-p)
28259 (get-char-property (point) 'invisible)))
28261 (defun org-invisible-p2 ()
28262 "Check if point is at a character currently not visible."
28263 (save-excursion
28264 (if (and (eolp) (not (bobp))) (backward-char 1))
28265 ;; Early versions of noutline don't have `outline-invisible-p'.
28266 (if (fboundp 'outline-invisible-p)
28267 (outline-invisible-p)
28268 (get-char-property (point) 'invisible))))
28270 (defalias 'org-back-to-heading 'outline-back-to-heading)
28271 (defalias 'org-on-heading-p 'outline-on-heading-p)
28272 (defalias 'org-at-heading-p 'outline-on-heading-p)
28273 (defun org-at-heading-or-item-p ()
28274 (or (org-on-heading-p) (org-at-item-p)))
28276 (defun org-on-target-p ()
28277 (or (org-in-regexp org-radio-target-regexp)
28278 (org-in-regexp org-target-regexp)))
28280 (defun org-up-heading-all (arg)
28281 "Move to the heading line of which the present line is a subheading.
28282 This function considers both visible and invisible heading lines.
28283 With argument, move up ARG levels."
28284 (if (fboundp 'outline-up-heading-all)
28285 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28286 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28288 (defun org-up-heading-safe ()
28289 "Move to the heading line of which the present line is a subheading.
28290 This version will not throw an error. It will return the level of the
28291 headline found, or nil if no higher level is found."
28292 (let ((pos (point)) start-level level
28293 (re (concat "^" outline-regexp)))
28294 (catch 'exit
28295 (outline-back-to-heading t)
28296 (setq start-level (funcall outline-level))
28297 (if (equal start-level 1) (throw 'exit nil))
28298 (while (re-search-backward re nil t)
28299 (setq level (funcall outline-level))
28300 (if (< level start-level) (throw 'exit level)))
28301 nil)))
28303 (defun org-first-sibling-p ()
28304 "Is this heading the first child of its parents?"
28305 (interactive)
28306 (let ((re (concat "^" outline-regexp))
28307 level l)
28308 (unless (org-at-heading-p t)
28309 (error "Not at a heading"))
28310 (setq level (funcall outline-level))
28311 (save-excursion
28312 (if (not (re-search-backward re nil t))
28314 (setq l (funcall outline-level))
28315 (< l level)))))
28317 (defun org-goto-sibling (&optional previous)
28318 "Goto the next sibling, even if it is invisible.
28319 When PREVIOUS is set, go to the previous sibling instead. Returns t
28320 when a sibling was found. When none is found, return nil and don't
28321 move point."
28322 (let ((fun (if previous 're-search-backward 're-search-forward))
28323 (pos (point))
28324 (re (concat "^" outline-regexp))
28325 level l)
28326 (when (condition-case nil (org-back-to-heading t) (error nil))
28327 (setq level (funcall outline-level))
28328 (catch 'exit
28329 (or previous (forward-char 1))
28330 (while (funcall fun re nil t)
28331 (setq l (funcall outline-level))
28332 (when (< l level) (goto-char pos) (throw 'exit nil))
28333 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28334 (goto-char pos)
28335 nil))))
28337 (defun org-show-siblings ()
28338 "Show all siblings of the current headline."
28339 (save-excursion
28340 (while (org-goto-sibling) (org-flag-heading nil)))
28341 (save-excursion
28342 (while (org-goto-sibling 'previous)
28343 (org-flag-heading nil))))
28345 (defun org-show-hidden-entry ()
28346 "Show an entry where even the heading is hidden."
28347 (save-excursion
28348 (org-show-entry)))
28350 (defun org-flag-heading (flag &optional entry)
28351 "Flag the current heading. FLAG non-nil means make invisible.
28352 When ENTRY is non-nil, show the entire entry."
28353 (save-excursion
28354 (org-back-to-heading t)
28355 ;; Check if we should show the entire entry
28356 (if entry
28357 (progn
28358 (org-show-entry)
28359 (save-excursion
28360 (and (outline-next-heading)
28361 (org-flag-heading nil))))
28362 (outline-flag-region (max (point-min) (1- (point)))
28363 (save-excursion (outline-end-of-heading) (point))
28364 flag))))
28366 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28367 ;; This is an exact copy of the original function, but it uses
28368 ;; `org-back-to-heading', to make it work also in invisible
28369 ;; trees. And is uses an invisible-OK argument.
28370 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28371 (org-back-to-heading invisible-OK)
28372 (let ((first t)
28373 (level (funcall outline-level)))
28374 (while (and (not (eobp))
28375 (or first (> (funcall outline-level) level)))
28376 (setq first nil)
28377 (outline-next-heading))
28378 (unless to-heading
28379 (if (memq (preceding-char) '(?\n ?\^M))
28380 (progn
28381 ;; Go to end of line before heading
28382 (forward-char -1)
28383 (if (memq (preceding-char) '(?\n ?\^M))
28384 ;; leave blank line before heading
28385 (forward-char -1))))))
28386 (point))
28388 (defun org-show-subtree ()
28389 "Show everything after this heading at deeper levels."
28390 (outline-flag-region
28391 (point)
28392 (save-excursion
28393 (outline-end-of-subtree) (outline-next-heading) (point))
28394 nil))
28396 (defun org-show-entry ()
28397 "Show the body directly following this heading.
28398 Show the heading too, if it is currently invisible."
28399 (interactive)
28400 (save-excursion
28401 (condition-case nil
28402 (progn
28403 (org-back-to-heading t)
28404 (outline-flag-region
28405 (max (point-min) (1- (point)))
28406 (save-excursion
28407 (re-search-forward
28408 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28409 (or (match-beginning 1) (point-max)))
28410 nil))
28411 (error nil))))
28413 (defun org-make-options-regexp (kwds)
28414 "Make a regular expression for keyword lines."
28415 (concat
28417 "#?[ \t]*\\+\\("
28418 (mapconcat 'regexp-quote kwds "\\|")
28419 "\\):[ \t]*"
28420 "\\(.+\\)"))
28422 ;; Make isearch reveal the necessary context
28423 (defun org-isearch-end ()
28424 "Reveal context after isearch exits."
28425 (when isearch-success ; only if search was successful
28426 (if (featurep 'xemacs)
28427 ;; Under XEmacs, the hook is run in the correct place,
28428 ;; we directly show the context.
28429 (org-show-context 'isearch)
28430 ;; In Emacs the hook runs *before* restoring the overlays.
28431 ;; So we have to use a one-time post-command-hook to do this.
28432 ;; (Emacs 22 has a special variable, see function `org-mode')
28433 (unless (and (boundp 'isearch-mode-end-hook-quit)
28434 isearch-mode-end-hook-quit)
28435 ;; Only when the isearch was not quitted.
28436 (org-add-hook 'post-command-hook 'org-isearch-post-command
28437 'append 'local)))))
28439 (defun org-isearch-post-command ()
28440 "Remove self from hook, and show context."
28441 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28442 (org-show-context 'isearch))
28445 ;;;; Integration with and fixes for other packages
28447 ;;; Imenu support
28449 (defvar org-imenu-markers nil
28450 "All markers currently used by Imenu.")
28451 (make-variable-buffer-local 'org-imenu-markers)
28453 (defun org-imenu-new-marker (&optional pos)
28454 "Return a new marker for use by Imenu, and remember the marker."
28455 (let ((m (make-marker)))
28456 (move-marker m (or pos (point)))
28457 (push m org-imenu-markers)
28460 (defun org-imenu-get-tree ()
28461 "Produce the index for Imenu."
28462 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28463 (setq org-imenu-markers nil)
28464 (let* ((n org-imenu-depth)
28465 (re (concat "^" outline-regexp))
28466 (subs (make-vector (1+ n) nil))
28467 (last-level 0)
28468 m tree level head)
28469 (save-excursion
28470 (save-restriction
28471 (widen)
28472 (goto-char (point-max))
28473 (while (re-search-backward re nil t)
28474 (setq level (org-reduced-level (funcall outline-level)))
28475 (when (<= level n)
28476 (looking-at org-complex-heading-regexp)
28477 (setq head (org-match-string-no-properties 4)
28478 m (org-imenu-new-marker))
28479 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28480 (if (>= level last-level)
28481 (push (cons head m) (aref subs level))
28482 (push (cons head (aref subs (1+ level))) (aref subs level))
28483 (loop for i from (1+ level) to n do (aset subs i nil)))
28484 (setq last-level level)))))
28485 (aref subs 1)))
28487 (eval-after-load "imenu"
28488 '(progn
28489 (add-hook 'imenu-after-jump-hook
28490 (lambda () (org-show-context 'org-goto)))))
28492 ;; Speedbar support
28494 (defun org-speedbar-set-agenda-restriction ()
28495 "Restrict future agenda commands to the location at point in speedbar.
28496 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28497 (interactive)
28498 (let (p m tp np dir txt w)
28499 (cond
28500 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28501 'org-imenu t))
28502 (setq m (get-text-property p 'org-imenu-marker))
28503 (save-excursion
28504 (save-restriction
28505 (set-buffer (marker-buffer m))
28506 (goto-char m)
28507 (org-agenda-set-restriction-lock 'subtree))))
28508 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28509 'speedbar-function 'speedbar-find-file))
28510 (setq tp (previous-single-property-change
28511 (1+ p) 'speedbar-function)
28512 np (next-single-property-change
28513 tp 'speedbar-function)
28514 dir (speedbar-line-directory)
28515 txt (buffer-substring-no-properties (or tp (point-min))
28516 (or np (point-max))))
28517 (save-excursion
28518 (save-restriction
28519 (set-buffer (find-file-noselect
28520 (let ((default-directory dir))
28521 (expand-file-name txt))))
28522 (unless (org-mode-p)
28523 (error "Cannot restrict to non-Org-mode file"))
28524 (org-agenda-set-restriction-lock 'file))))
28525 (t (error "Don't know how to restrict Org-mode's agenda")))
28526 (org-move-overlay org-speedbar-restriction-lock-overlay
28527 (point-at-bol) (point-at-eol))
28528 (setq current-prefix-arg nil)
28529 (org-agenda-maybe-redo)))
28531 (eval-after-load "speedbar"
28532 '(progn
28533 (speedbar-add-supported-extension ".org")
28534 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28535 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28536 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28537 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28538 (add-hook 'speedbar-visiting-tag-hook
28539 (lambda () (org-show-context 'org-goto)))))
28542 ;;; Fixes and Hacks
28544 ;; Make flyspell not check words in links, to not mess up our keymap
28545 (defun org-mode-flyspell-verify ()
28546 "Don't let flyspell put overlays at active buttons."
28547 (not (get-text-property (point) 'keymap)))
28549 ;; Make `bookmark-jump' show the jump location if it was hidden.
28550 (eval-after-load "bookmark"
28551 '(if (boundp 'bookmark-after-jump-hook)
28552 ;; We can use the hook
28553 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28554 ;; Hook not available, use advice
28555 (defadvice bookmark-jump (after org-make-visible activate)
28556 "Make the position visible."
28557 (org-bookmark-jump-unhide))))
28559 (defun org-bookmark-jump-unhide ()
28560 "Unhide the current position, to show the bookmark location."
28561 (and (org-mode-p)
28562 (or (org-invisible-p)
28563 (save-excursion (goto-char (max (point-min) (1- (point))))
28564 (org-invisible-p)))
28565 (org-show-context 'bookmark-jump)))
28567 ;; Fix a bug in htmlize where there are text properties (face nil)
28568 (eval-after-load "htmlize"
28569 '(progn
28570 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28571 "Make sure there are no nil faces"
28572 (setq ad-return-value (delq nil ad-return-value)))))
28574 ;; Make session.el ignore our circular variable
28575 (eval-after-load "session"
28576 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28578 ;;;; Experimental code
28580 (defun org-closed-in-range ()
28581 "Sparse tree of items closed in a certain time range.
28582 Still experimental, may disappear in the future."
28583 (interactive)
28584 ;; Get the time interval from the user.
28585 (let* ((time1 (time-to-seconds
28586 (org-read-date nil 'to-time nil "Starting date: ")))
28587 (time2 (time-to-seconds
28588 (org-read-date nil 'to-time nil "End date:")))
28589 ;; callback function
28590 (callback (lambda ()
28591 (let ((time
28592 (time-to-seconds
28593 (apply 'encode-time
28594 (org-parse-time-string
28595 (match-string 1))))))
28596 ;; check if time in interval
28597 (and (>= time time1) (<= time time2))))))
28598 ;; make tree, check each match with the callback
28599 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28601 ;;;; Finish up
28603 (provide 'org)
28605 (run-hooks 'org-load-hook)
28607 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28608 ;;; org.el ends here