Silence the byte-compiler for org-publish.el.
[org-mode.git] / org.el
blob4c9663d6a217986cec41f19d7e586b06f16da0bc
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 that are listed in `org-default-extensions'."
176 (mapc 'require org-default-extensions))
178 ;; FIXME: Needs a separate group...
179 (defcustom org-completion-fallback-command 'hippie-expand
180 "The expansion command called by \\[org-complete] in normal context.
181 Normal means, no org-mode-specific context."
182 :group 'org
183 :type 'function)
185 (defgroup org-startup nil
186 "Options concerning startup of Org-mode."
187 :tag "Org Startup"
188 :group 'org)
190 (defcustom org-startup-folded t
191 "Non-nil means, entering Org-mode will switch to OVERVIEW.
192 This can also be configured on a per-file basis by adding one of
193 the following lines anywhere in the buffer:
195 #+STARTUP: fold
196 #+STARTUP: nofold
197 #+STARTUP: content"
198 :group 'org-startup
199 :type '(choice
200 (const :tag "nofold: show all" nil)
201 (const :tag "fold: overview" t)
202 (const :tag "content: all headlines" content)))
204 (defcustom org-startup-truncated t
205 "Non-nil means, entering Org-mode will set `truncate-lines'.
206 This is useful since some lines containing links can be very long and
207 uninteresting. Also tables look terrible when wrapped."
208 :group 'org-startup
209 :type 'boolean)
211 (defcustom org-startup-align-all-tables nil
212 "Non-nil means, align all tables when visiting a file.
213 This is useful when the column width in tables is forced with <N> cookies
214 in table fields. Such tables will look correct only after the first re-align.
215 This can also be configured on a per-file basis by adding one of
216 the following lines anywhere in the buffer:
217 #+STARTUP: align
218 #+STARTUP: noalign"
219 :group 'org-startup
220 :type 'boolean)
222 (defcustom org-insert-mode-line-in-empty-file nil
223 "Non-nil means insert the first line setting Org-mode in empty files.
224 When the function `org-mode' is called interactively in an empty file, this
225 normally means that the file name does not automatically trigger Org-mode.
226 To ensure that the file will always be in Org-mode in the future, a
227 line enforcing Org-mode will be inserted into the buffer, if this option
228 has been set."
229 :group 'org-startup
230 :type 'boolean)
232 (defcustom org-replace-disputed-keys nil
233 "Non-nil means use alternative key bindings for some keys.
234 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
235 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
236 If you want to use Org-mode together with one of these other modes,
237 or more generally if you would like to move some Org-mode commands to
238 other keys, set this variable and configure the keys with the variable
239 `org-disputed-keys'.
241 This option is only relevant at load-time of Org-mode, and must be set
242 *before* org.el is loaded. Changing it requires a restart of Emacs to
243 become effective."
244 :group 'org-startup
245 :type 'boolean)
247 (if (fboundp 'defvaralias)
248 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
250 (defcustom org-disputed-keys
251 '(([(shift up)] . [(meta p)])
252 ([(shift down)] . [(meta n)])
253 ([(shift left)] . [(meta -)])
254 ([(shift right)] . [(meta +)])
255 ([(control shift right)] . [(meta shift +)])
256 ([(control shift left)] . [(meta shift -)]))
257 "Keys for which Org-mode and other modes compete.
258 This is an alist, cars are the default keys, second element specifies
259 the alternative to use when `org-replace-disputed-keys' is t.
261 Keys can be specified in any syntax supported by `define-key'.
262 The value of this option takes effect only at Org-mode's startup,
263 therefore you'll have to restart Emacs to apply it after changing."
264 :group 'org-startup
265 :type 'alist)
267 (defun org-key (key)
268 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
269 Or return the original if not disputed."
270 (if org-replace-disputed-keys
271 (let* ((nkey (key-description key))
272 (x (org-find-if (lambda (x)
273 (equal (key-description (car x)) nkey))
274 org-disputed-keys)))
275 (if x (cdr x) key))
276 key))
278 (defun org-find-if (predicate seq)
279 (catch 'exit
280 (while seq
281 (if (funcall predicate (car seq))
282 (throw 'exit (car seq))
283 (pop seq)))))
285 (defun org-defkey (keymap key def)
286 "Define a key, possibly translated, as returned by `org-key'."
287 (define-key keymap (org-key key) def))
289 (defcustom org-ellipsis nil
290 "The ellipsis to use in the Org-mode outline.
291 When nil, just use the standard three dots. When a string, use that instead,
292 When a face, use the standart 3 dots, but with the specified face.
293 The change affects only Org-mode (which will then use its own display table).
294 Changing this requires executing `M-x org-mode' in a buffer to become
295 effective."
296 :group 'org-startup
297 :type '(choice (const :tag "Default" nil)
298 (face :tag "Face" :value org-warning)
299 (string :tag "String" :value "...#")))
301 (defvar org-display-table nil
302 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
304 (defgroup org-keywords nil
305 "Keywords in Org-mode."
306 :tag "Org Keywords"
307 :group 'org)
309 (defcustom org-deadline-string "DEADLINE:"
310 "String to mark deadline entries.
311 A deadline is this string, followed by a time stamp. Should be a word,
312 terminated by a colon. You can insert a schedule keyword and
313 a timestamp with \\[org-deadline].
314 Changes become only effective after restarting Emacs."
315 :group 'org-keywords
316 :type 'string)
318 (defcustom org-scheduled-string "SCHEDULED:"
319 "String to mark scheduled TODO entries.
320 A schedule is this string, followed by a time stamp. Should be a word,
321 terminated by a colon. You can insert a schedule keyword and
322 a timestamp with \\[org-schedule].
323 Changes become only effective after restarting Emacs."
324 :group 'org-keywords
325 :type 'string)
327 (defcustom org-closed-string "CLOSED:"
328 "String used as the prefix for timestamps logging closing a TODO entry."
329 :group 'org-keywords
330 :type 'string)
332 (defcustom org-clock-string "CLOCK:"
333 "String used as prefix for timestamps clocking work hours on an item."
334 :group 'org-keywords
335 :type 'string)
337 (defcustom org-comment-string "COMMENT"
338 "Entries starting with this keyword will never be exported.
339 An entry can be toggled between COMMENT and normal with
340 \\[org-toggle-comment].
341 Changes become only effective after restarting Emacs."
342 :group 'org-keywords
343 :type 'string)
345 (defcustom org-quote-string "QUOTE"
346 "Entries starting with this keyword will be exported in fixed-width font.
347 Quoting applies only to the text in the entry following the headline, and does
348 not extend beyond the next headline, even if that is lower level.
349 An entry can be toggled between QUOTE and normal with
350 \\[org-toggle-fixed-width-section]."
351 :group 'org-keywords
352 :type 'string)
354 (defconst org-repeat-re
355 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
356 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
357 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
358 "Regular expression for specifying repeated events.
359 After a match, group 1 contains the repeat expression.")
361 (defgroup org-structure nil
362 "Options concerning the general structure of Org-mode files."
363 :tag "Org Structure"
364 :group 'org)
366 (defgroup org-reveal-location nil
367 "Options about how to make context of a location visible."
368 :tag "Org Reveal Location"
369 :group 'org-structure)
371 (defconst org-context-choice
372 '(choice
373 (const :tag "Always" t)
374 (const :tag "Never" nil)
375 (repeat :greedy t :tag "Individual contexts"
376 (cons
377 (choice :tag "Context"
378 (const agenda)
379 (const org-goto)
380 (const occur-tree)
381 (const tags-tree)
382 (const link-search)
383 (const mark-goto)
384 (const bookmark-jump)
385 (const isearch)
386 (const default))
387 (boolean))))
388 "Contexts for the reveal options.")
390 (defcustom org-show-hierarchy-above '((default . t))
391 "Non-nil means, show full hierarchy when revealing a location.
392 Org-mode often shows locations in an org-mode file which might have
393 been invisible before. When this is set, the hierarchy of headings
394 above the exposed location is shown.
395 Turning this off for example for sparse trees makes them very compact.
396 Instead of t, this can also be an alist specifying this option for different
397 contexts. Valid contexts are
398 agenda when exposing an entry from the agenda
399 org-goto when using the command `org-goto' on key C-c C-j
400 occur-tree when using the command `org-occur' on key C-c /
401 tags-tree when constructing a sparse tree based on tags matches
402 link-search when exposing search matches associated with a link
403 mark-goto when exposing the jump goal of a mark
404 bookmark-jump when exposing a bookmark location
405 isearch when exiting from an incremental search
406 default default for all contexts not set explicitly"
407 :group 'org-reveal-location
408 :type org-context-choice)
410 (defcustom org-show-following-heading '((default . nil))
411 "Non-nil means, show following heading when revealing a location.
412 Org-mode often shows locations in an org-mode file which might have
413 been invisible before. When this is set, the heading following the
414 match is shown.
415 Turning this off for example for sparse trees makes them very compact,
416 but makes it harder to edit the location of the match. In such a case,
417 use the command \\[org-reveal] to show more context.
418 Instead of t, this can also be an alist specifying this option for different
419 contexts. See `org-show-hierarchy-above' for valid contexts."
420 :group 'org-reveal-location
421 :type org-context-choice)
423 (defcustom org-show-siblings '((default . nil) (isearch t))
424 "Non-nil means, show all sibling heading when revealing a location.
425 Org-mode often shows locations in an org-mode file which might have
426 been invisible before. When this is set, the sibling of the current entry
427 heading are all made visible. If `org-show-hierarchy-above' is t,
428 the same happens on each level of the hierarchy above the current entry.
430 By default this is on for the isearch context, off for all other contexts.
431 Turning this off for example for sparse trees makes them very compact,
432 but makes it harder to edit the location of the match. In such a case,
433 use the command \\[org-reveal] to show more context.
434 Instead of t, this can also be an alist specifying this option for different
435 contexts. See `org-show-hierarchy-above' for valid contexts."
436 :group 'org-reveal-location
437 :type org-context-choice)
439 (defcustom org-show-entry-below '((default . nil))
440 "Non-nil means, show the entry below a headline when revealing a location.
441 Org-mode often shows locations in an org-mode file which might have
442 been invisible before. When this is set, the text below the headline that is
443 exposed is also shown.
445 By default this is off for all contexts.
446 Instead of t, this can also be an alist specifying this option for different
447 contexts. See `org-show-hierarchy-above' for valid contexts."
448 :group 'org-reveal-location
449 :type org-context-choice)
451 (defgroup org-cycle nil
452 "Options concerning visibility cycling in Org-mode."
453 :tag "Org Cycle"
454 :group 'org-structure)
456 (defcustom org-drawers '("PROPERTIES" "CLOCK")
457 "Names of drawers. Drawers are not opened by cycling on the headline above.
458 Drawers only open with a TAB on the drawer line itself. A drawer looks like
459 this:
460 :DRAWERNAME:
461 .....
462 :END:
463 The drawer \"PROPERTIES\" is special for capturing properties through
464 the property API.
466 Drawers can be defined on the per-file basis with a line like:
468 #+DRAWERS: HIDDEN STATE PROPERTIES"
469 :group 'org-structure
470 :type '(repeat (string :tag "Drawer Name")))
472 (defcustom org-cycle-global-at-bob nil
473 "Cycle globally if cursor is at beginning of buffer and not at a headline.
474 This makes it possible to do global cycling without having to use S-TAB or
475 C-u TAB. For this special case to work, the first line of the buffer
476 must not be a headline - it may be empty ot some other text. When used in
477 this way, `org-cycle-hook' is disables temporarily, to make sure the
478 cursor stays at the beginning of the buffer.
479 When this option is nil, don't do anything special at the beginning
480 of the buffer."
481 :group 'org-cycle
482 :type 'boolean)
484 (defcustom org-cycle-emulate-tab t
485 "Where should `org-cycle' emulate TAB.
486 nil Never
487 white Only in completely white lines
488 whitestart Only at the beginning of lines, before the first non-white char
489 t Everywhere except in headlines
490 exc-hl-bol Everywhere except at the start of a headline
491 If TAB is used in a place where it does not emulate TAB, the current subtree
492 visibility is cycled."
493 :group 'org-cycle
494 :type '(choice (const :tag "Never" nil)
495 (const :tag "Only in completely white lines" white)
496 (const :tag "Before first char in a line" whitestart)
497 (const :tag "Everywhere except in headlines" t)
498 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
501 (defcustom org-cycle-separator-lines 2
502 "Number of empty lines needed to keep an empty line between collapsed trees.
503 If you leave an empty line between the end of a subtree and the following
504 headline, this empty line is hidden when the subtree is folded.
505 Org-mode will leave (exactly) one empty line visible if the number of
506 empty lines is equal or larger to the number given in this variable.
507 So the default 2 means, at least 2 empty lines after the end of a subtree
508 are needed to produce free space between a collapsed subtree and the
509 following headline.
511 Special case: when 0, never leave empty lines in collapsed view."
512 :group 'org-cycle
513 :type 'integer)
515 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
516 org-cycle-hide-drawers
517 org-cycle-show-empty-lines
518 org-optimize-window-after-visibility-change)
519 "Hook that is run after `org-cycle' has changed the buffer visibility.
520 The function(s) in this hook must accept a single argument which indicates
521 the new state that was set by the most recent `org-cycle' command. The
522 argument is a symbol. After a global state change, it can have the values
523 `overview', `content', or `all'. After a local state change, it can have
524 the values `folded', `children', or `subtree'."
525 :group 'org-cycle
526 :type 'hook)
528 (defgroup org-edit-structure nil
529 "Options concerning structure editing in Org-mode."
530 :tag "Org Edit Structure"
531 :group 'org-structure)
533 (defcustom org-odd-levels-only nil
534 "Non-nil means, skip even levels and only use odd levels for the outline.
535 This has the effect that two stars are being added/taken away in
536 promotion/demotion commands. It also influences how levels are
537 handled by the exporters.
538 Changing it requires restart of `font-lock-mode' to become effective
539 for fontification also in regions already fontified.
540 You may also set this on a per-file basis by adding one of the following
541 lines to the buffer:
543 #+STARTUP: odd
544 #+STARTUP: oddeven"
545 :group 'org-edit-structure
546 :group 'org-font-lock
547 :type 'boolean)
549 (defcustom org-adapt-indentation t
550 "Non-nil means, adapt indentation when promoting and demoting.
551 When this is set and the *entire* text in an entry is indented, the
552 indentation is increased by one space in a demotion command, and
553 decreased by one in a promotion command. If any line in the entry
554 body starts at column 0, indentation is not changed at all."
555 :group 'org-edit-structure
556 :type 'boolean)
558 (defcustom org-special-ctrl-a/e nil
559 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
560 When t, `C-a' will bring back the cursor to the beginning of the
561 headline text, i.e. after the stars and after a possible TODO keyword.
562 In an item, this will be the position after the bullet.
563 When the cursor is already at that position, another `C-a' will bring
564 it to the beginning of the line.
565 `C-e' will jump to the end of the headline, ignoring the presence of tags
566 in the headline. A second `C-e' will then jump to the true end of the
567 line, after any tags.
568 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
569 and only a directly following, identical keypress will bring the cursor
570 to the special positions."
571 :group 'org-edit-structure
572 :type '(choice
573 (const :tag "off" nil)
574 (const :tag "after bullet first" t)
575 (const :tag "border first" reversed)))
577 (if (fboundp 'defvaralias)
578 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
580 (defcustom org-special-ctrl-k nil
581 "Non-nil means `C-k' will behave specially in headlines.
582 When nil, `C-k' will call the default `kill-line' command.
583 When t, the following will happen while the cursor is in the headline:
585 - When the cursor is at the beginning of a headline, kill the entire
586 line and possible the folded subtree below the line.
587 - When in the middle of the headline text, kill the headline up to the tags.
588 - When after the headline text, kill the tags."
589 :group 'org-edit-structure
590 :type 'boolean)
592 (defcustom org-M-RET-may-split-line '((default . t))
593 "Non-nil means, M-RET will split the line at the cursor position.
594 When nil, it will go to the end of the line before making a
595 new line.
596 You may also set this option in a different way for different
597 contexts. Valid contexts are:
599 headline when creating a new headline
600 item when creating a new item
601 table in a table field
602 default the value to be used for all contexts not explicitly
603 customized"
604 :group 'org-structure
605 :group 'org-table
606 :type '(choice
607 (const :tag "Always" t)
608 (const :tag "Never" nil)
609 (repeat :greedy t :tag "Individual contexts"
610 (cons
611 (choice :tag "Context"
612 (const headline)
613 (const item)
614 (const table)
615 (const default))
616 (boolean)))))
619 (defcustom org-blank-before-new-entry '((heading . nil)
620 (plain-list-item . nil))
621 "Should `org-insert-heading' leave a blank line before new heading/item?
622 The value is an alist, with `heading' and `plain-list-item' as car,
623 and a boolean flag as cdr."
624 :group 'org-edit-structure
625 :type '(list
626 (cons (const heading) (boolean))
627 (cons (const plain-list-item) (boolean))))
629 (defcustom org-insert-heading-hook nil
630 "Hook being run after inserting a new heading."
631 :group 'org-edit-structure
632 :type 'hook)
634 (defcustom org-enable-fixed-width-editor t
635 "Non-nil means, lines starting with \":\" are treated as fixed-width.
636 This currently only means, they are never auto-wrapped.
637 When nil, such lines will be treated like ordinary lines.
638 See also the QUOTE keyword."
639 :group 'org-edit-structure
640 :type 'boolean)
642 (defcustom org-goto-auto-isearch t
643 "Non-nil means, typing characters in org-goto starts incremental search."
644 :group 'org-edit-structure
645 :type 'boolean)
647 (defgroup org-sparse-trees nil
648 "Options concerning sparse trees in Org-mode."
649 :tag "Org Sparse Trees"
650 :group 'org-structure)
652 (defcustom org-highlight-sparse-tree-matches t
653 "Non-nil means, highlight all matches that define a sparse tree.
654 The highlights will automatically disappear the next time the buffer is
655 changed by an edit command."
656 :group 'org-sparse-trees
657 :type 'boolean)
659 (defcustom org-remove-highlights-with-change t
660 "Non-nil means, any change to the buffer will remove temporary highlights.
661 Such highlights are created by `org-occur' and `org-clock-display'.
662 When nil, `C-c C-c needs to be used to get rid of the highlights.
663 The highlights created by `org-preview-latex-fragment' always need
664 `C-c C-c' to be removed."
665 :group 'org-sparse-trees
666 :group 'org-time
667 :type 'boolean)
670 (defcustom org-occur-hook '(org-first-headline-recenter)
671 "Hook that is run after `org-occur' has constructed a sparse tree.
672 This can be used to recenter the window to show as much of the structure
673 as possible."
674 :group 'org-sparse-trees
675 :type 'hook)
677 (defgroup org-plain-lists nil
678 "Options concerning plain lists in Org-mode."
679 :tag "Org Plain lists"
680 :group 'org-structure)
682 (defcustom org-cycle-include-plain-lists nil
683 "Non-nil means, include plain lists into visibility cycling.
684 This means that during cycling, plain list items will *temporarily* be
685 interpreted as outline headlines with a level given by 1000+i where i is the
686 indentation of the bullet. In all other operations, plain list items are
687 not seen as headlines. For example, you cannot assign a TODO keyword to
688 such an item."
689 :group 'org-plain-lists
690 :type 'boolean)
692 (defcustom org-plain-list-ordered-item-terminator t
693 "The character that makes a line with leading number an ordered list item.
694 Valid values are ?. and ?\). To get both terminators, use t. While
695 ?. may look nicer, it creates the danger that a line with leading
696 number may be incorrectly interpreted as an item. ?\) therefore is
697 the safe choice."
698 :group 'org-plain-lists
699 :type '(choice (const :tag "dot like in \"2.\"" ?.)
700 (const :tag "paren like in \"2)\"" ?\))
701 (const :tab "both" t)))
703 (defcustom org-auto-renumber-ordered-lists t
704 "Non-nil means, automatically renumber ordered plain lists.
705 Renumbering happens when the sequence have been changed with
706 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
707 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
708 :group 'org-plain-lists
709 :type 'boolean)
711 (defcustom org-provide-checkbox-statistics t
712 "Non-nil means, update checkbox statistics after insert and toggle.
713 When this is set, checkbox statistics is updated each time you either insert
714 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
715 with \\[org-ctrl-c-ctrl-c\\]."
716 :group 'org-plain-lists
717 :type 'boolean)
719 (defgroup org-archive nil
720 "Options concerning archiving in Org-mode."
721 :tag "Org Archive"
722 :group 'org-structure)
724 (defcustom org-archive-tag "ARCHIVE"
725 "The tag that marks a subtree as archived.
726 An archived subtree does not open during visibility cycling, and does
727 not contribute to the agenda listings.
728 After changing this, font-lock must be restarted in the relevant buffers to
729 get the proper fontification."
730 :group 'org-archive
731 :group 'org-keywords
732 :type 'string)
734 (defcustom org-agenda-skip-archived-trees t
735 "Non-nil means, the agenda will skip any items located in archived trees.
736 An archived tree is a tree marked with the tag ARCHIVE."
737 :group 'org-archive
738 :group 'org-agenda-skip
739 :type 'boolean)
741 (defcustom org-cycle-open-archived-trees nil
742 "Non-nil means, `org-cycle' will open archived trees.
743 An archived tree is a tree marked with the tag ARCHIVE.
744 When nil, archived trees will stay folded. You can still open them with
745 normal outline commands like `show-all', but not with the cycling commands."
746 :group 'org-archive
747 :group 'org-cycle
748 :type 'boolean)
750 (defcustom org-sparse-tree-open-archived-trees nil
751 "Non-nil means sparse tree construction shows matches in archived trees.
752 When nil, matches in these trees are highlighted, but the trees are kept in
753 collapsed state."
754 :group 'org-archive
755 :group 'org-sparse-trees
756 :type 'boolean)
758 (defcustom org-archive-location "%s_archive::"
759 "The location where subtrees should be archived.
760 This string consists of two parts, separated by a double-colon.
762 The first part is a file name - when omitted, archiving happens in the same
763 file. %s will be replaced by the current file name (without directory part).
764 Archiving to a different file is useful to keep archived entries from
765 contributing to the Org-mode Agenda.
767 The part after the double colon is a headline. The archived entries will be
768 filed under that headline. When omitted, the subtrees are simply filed away
769 at the end of the file, as top-level entries.
771 Here are a few examples:
772 \"%s_archive::\"
773 If the current file is Projects.org, archive in file
774 Projects.org_archive, as top-level trees. This is the default.
776 \"::* Archived Tasks\"
777 Archive in the current file, under the top-level headline
778 \"* Archived Tasks\".
780 \"~/org/archive.org::\"
781 Archive in file ~/org/archive.org (absolute path), as top-level trees.
783 \"basement::** Finished Tasks\"
784 Archive in file ./basement (relative path), as level 3 trees
785 below the level 2 heading \"** Finished Tasks\".
787 You may set this option on a per-file basis by adding to the buffer a
788 line like
790 #+ARCHIVE: basement::** Finished Tasks"
791 :group 'org-archive
792 :type 'string)
794 (defcustom org-archive-mark-done t
795 "Non-nil means, mark entries as DONE when they are moved to the archive file.
796 This can be a string to set the keyword to use. When t, Org-mode will
797 use the first keyword in its list that means done."
798 :group 'org-archive
799 :type '(choice
800 (const :tag "No" nil)
801 (const :tag "Yes" t)
802 (string :tag "Use this keyword")))
804 (defcustom org-archive-stamp-time t
805 "Non-nil means, add a time stamp to entries moved to an archive file.
806 This variable is obsolete and has no effect anymore, instead add ot remove
807 `time' from the variablle `org-archive-save-context-info'."
808 :group 'org-archive
809 :type 'boolean)
811 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
812 "Parts of context info that should be stored as properties when archiving.
813 When a subtree is moved to an archive file, it looses information given by
814 context, like inherited tags, the category, and possibly also the TODO
815 state (depending on the variable `org-archive-mark-done').
816 This variable can be a list of any of the following symbols:
818 time The time of archiving.
819 file The file where the entry originates.
820 itags The local tags, in the headline of the subtree.
821 ltags The tags the subtree inherits from further up the hierarchy.
822 todo The pre-archive TODO state.
823 category The category, taken from file name or #+CATEGORY lines.
824 olpath The outline path to the item. These are all headlines above
825 the current item, separated by /, like a file path.
827 For each symbol present in the list, a property will be created in
828 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
829 information."
830 :group 'org-archive
831 :type '(set :greedy t
832 (const :tag "Time" time)
833 (const :tag "File" file)
834 (const :tag "Category" category)
835 (const :tag "TODO state" todo)
836 (const :tag "TODO state" priority)
837 (const :tag "Inherited tags" itags)
838 (const :tag "Outline path" olpath)
839 (const :tag "Local tags" ltags)))
841 (defgroup org-imenu-and-speedbar nil
842 "Options concerning imenu and speedbar in Org-mode."
843 :tag "Org Imenu and Speedbar"
844 :group 'org-structure)
846 (defcustom org-imenu-depth 2
847 "The maximum level for Imenu access to Org-mode headlines.
848 This also applied for speedbar access."
849 :group 'org-imenu-and-speedbar
850 :type 'number)
852 (defgroup org-table nil
853 "Options concerning tables in Org-mode."
854 :tag "Org Table"
855 :group 'org)
857 (defcustom org-enable-table-editor 'optimized
858 "Non-nil means, lines starting with \"|\" are handled by the table editor.
859 When nil, such lines will be treated like ordinary lines.
861 When equal to the symbol `optimized', the table editor will be optimized to
862 do the following:
863 - Automatic overwrite mode in front of whitespace in table fields.
864 This makes the structure of the table stay in tact as long as the edited
865 field does not exceed the column width.
866 - Minimize the number of realigns. Normally, the table is aligned each time
867 TAB or RET are pressed to move to another field. With optimization this
868 happens only if changes to a field might have changed the column width.
869 Optimization requires replacing the functions `self-insert-command',
870 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
871 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
872 very good at guessing when a re-align will be necessary, but you can always
873 force one with \\[org-ctrl-c-ctrl-c].
875 If you would like to use the optimized version in Org-mode, but the
876 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
878 This variable can be used to turn on and off the table editor during a session,
879 but in order to toggle optimization, a restart is required.
881 See also the variable `org-table-auto-blank-field'."
882 :group 'org-table
883 :type '(choice
884 (const :tag "off" nil)
885 (const :tag "on" t)
886 (const :tag "on, optimized" optimized)))
888 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
889 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
890 In the optimized version, the table editor takes over all simple keys that
891 normally just insert a character. In tables, the characters are inserted
892 in a way to minimize disturbing the table structure (i.e. in overwrite mode
893 for empty fields). Outside tables, the correct binding of the keys is
894 restored.
896 The default for this option is t if the optimized version is also used in
897 Org-mode. See the variable `org-enable-table-editor' for details. Changing
898 this variable requires a restart of Emacs to become effective."
899 :group 'org-table
900 :type 'boolean)
902 (defcustom orgtbl-radio-table-templates
903 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
904 % END RECEIVE ORGTBL %n
905 \\begin{comment}
906 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
907 | | |
908 \\end{comment}\n")
909 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
910 @c END RECEIVE ORGTBL %n
911 @ignore
912 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
913 | | |
914 @end ignore\n")
915 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
916 <!-- END RECEIVE ORGTBL %n -->
917 <!--
918 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
919 | | |
920 -->\n"))
921 "Templates for radio tables in different major modes.
922 All occurrences of %n in a template will be replaced with the name of the
923 table, obtained by prompting the user."
924 :group 'org-table
925 :type '(repeat
926 (list (symbol :tag "Major mode")
927 (string :tag "Format"))))
929 (defgroup org-table-settings nil
930 "Settings for tables in Org-mode."
931 :tag "Org Table Settings"
932 :group 'org-table)
934 (defcustom org-table-default-size "5x2"
935 "The default size for newly created tables, Columns x Rows."
936 :group 'org-table-settings
937 :type 'string)
939 (defcustom org-table-number-regexp
940 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
941 "Regular expression for recognizing numbers in table columns.
942 If a table column contains mostly numbers, it will be aligned to the
943 right. If not, it will be aligned to the left.
945 The default value of this option is a regular expression which allows
946 anything which looks remotely like a number as used in scientific
947 context. For example, all of the following will be considered a
948 number:
949 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
951 Other options offered by the customize interface are more restrictive."
952 :group 'org-table-settings
953 :type '(choice
954 (const :tag "Positive Integers"
955 "^[0-9]+$")
956 (const :tag "Integers"
957 "^[-+]?[0-9]+$")
958 (const :tag "Floating Point Numbers"
959 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
960 (const :tag "Floating Point Number or Integer"
961 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
962 (const :tag "Exponential, Floating point, Integer"
963 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
964 (const :tag "Very General Number-Like, including hex"
965 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
966 (string :tag "Regexp:")))
968 (defcustom org-table-number-fraction 0.5
969 "Fraction of numbers in a column required to make the column align right.
970 In a column all non-white fields are considered. If at least this
971 fraction of fields is matched by `org-table-number-fraction',
972 alignment to the right border applies."
973 :group 'org-table-settings
974 :type 'number)
976 (defgroup org-table-editing nil
977 "Behavior of tables during editing in Org-mode."
978 :tag "Org Table Editing"
979 :group 'org-table)
981 (defcustom org-table-automatic-realign t
982 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
983 When nil, aligning is only done with \\[org-table-align], or after column
984 removal/insertion."
985 :group 'org-table-editing
986 :type 'boolean)
988 (defcustom org-table-auto-blank-field t
989 "Non-nil means, automatically blank table field when starting to type into it.
990 This only happens when typing immediately after a field motion
991 command (TAB, S-TAB or RET).
992 Only relevant when `org-enable-table-editor' is equal to `optimized'."
993 :group 'org-table-editing
994 :type 'boolean)
996 (defcustom org-table-tab-jumps-over-hlines t
997 "Non-nil means, tab in the last column of a table with jump over a hline.
998 If a horizontal separator line is following the current line,
999 `org-table-next-field' can either create a new row before that line, or jump
1000 over the line. When this option is nil, a new line will be created before
1001 this line."
1002 :group 'org-table-editing
1003 :type 'boolean)
1005 (defcustom org-table-tab-recognizes-table.el t
1006 "Non-nil means, TAB will automatically notice a table.el table.
1007 When it sees such a table, it moves point into it and - if necessary -
1008 calls `table-recognize-table'."
1009 :group 'org-table-editing
1010 :type 'boolean)
1012 (defgroup org-table-calculation nil
1013 "Options concerning tables in Org-mode."
1014 :tag "Org Table Calculation"
1015 :group 'org-table)
1017 (defcustom org-table-use-standard-references t
1018 "Should org-mode work with table refrences like B3 instead of @3$2?
1019 Possible values are:
1020 nil never use them
1021 from accept as input, do not present for editing
1022 t: accept as input and present for editing"
1023 :group 'org-table-calculation
1024 :type '(choice
1025 (const :tag "Never, don't even check unser input for them" nil)
1026 (const :tag "Always, both as user input, and when editing" t)
1027 (const :tag "Convert user input, don't offer during editing" 'from)))
1029 (defcustom org-table-copy-increment t
1030 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1031 :group 'org-table-calculation
1032 :type 'boolean)
1034 (defcustom org-calc-default-modes
1035 '(calc-internal-prec 12
1036 calc-float-format (float 5)
1037 calc-angle-mode deg
1038 calc-prefer-frac nil
1039 calc-symbolic-mode nil
1040 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1041 calc-display-working-message t
1043 "List with Calc mode settings for use in calc-eval for table formulas.
1044 The list must contain alternating symbols (Calc modes variables and values).
1045 Don't remove any of the default settings, just change the values. Org-mode
1046 relies on the variables to be present in the list."
1047 :group 'org-table-calculation
1048 :type 'plist)
1050 (defcustom org-table-formula-evaluate-inline t
1051 "Non-nil means, TAB and RET evaluate a formula in current table field.
1052 If the current field starts with an equal sign, it is assumed to be a formula
1053 which should be evaluated as described in the manual and in the documentation
1054 string of the command `org-table-eval-formula'. This feature requires the
1055 Emacs calc package.
1056 When this variable is nil, formula calculation is only available through
1057 the command \\[org-table-eval-formula]."
1058 :group 'org-table-calculation
1059 :type 'boolean)
1061 (defcustom org-table-formula-use-constants t
1062 "Non-nil means, interpret constants in formulas in tables.
1063 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1064 by the value given in `org-table-formula-constants', or by a value obtained
1065 from the `constants.el' package."
1066 :group 'org-table-calculation
1067 :type 'boolean)
1069 (defcustom org-table-formula-constants nil
1070 "Alist with constant names and values, for use in table formulas.
1071 The car of each element is a name of a constant, without the `$' before it.
1072 The cdr is the value as a string. For example, if you'd like to use the
1073 speed of light in a formula, you would configure
1075 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1077 and then use it in an equation like `$1*$c'.
1079 Constants can also be defined on a per-file basis using a line like
1081 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1082 :group 'org-table-calculation
1083 :type '(repeat
1084 (cons (string :tag "name")
1085 (string :tag "value"))))
1087 (defvar org-table-formula-constants-local nil
1088 "Local version of `org-table-formula-constants'.")
1089 (make-variable-buffer-local 'org-table-formula-constants-local)
1091 (defcustom org-table-allow-automatic-line-recalculation t
1092 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1093 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1094 :group 'org-table-calculation
1095 :type 'boolean)
1097 (defgroup org-link nil
1098 "Options concerning links in Org-mode."
1099 :tag "Org Link"
1100 :group 'org)
1102 (defvar org-link-abbrev-alist-local nil
1103 "Buffer-local version of `org-link-abbrev-alist', which see.
1104 The value of this is taken from the #+LINK lines.")
1105 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1107 (defcustom org-link-abbrev-alist nil
1108 "Alist of link abbreviations.
1109 The car of each element is a string, to be replaced at the start of a link.
1110 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1111 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1113 [[linkkey:tag][description]]
1115 If REPLACE is a string, the tag will simply be appended to create the link.
1116 If the string contains \"%s\", the tag will be inserted there.
1118 REPLACE may also be a function that will be called with the tag as the
1119 only argument to create the link, which should be returned as a string.
1121 See the manual for examples."
1122 :group 'org-link
1123 :type 'alist)
1125 (defcustom org-descriptive-links t
1126 "Non-nil means, hide link part and only show description of bracket links.
1127 Bracket links are like [[link][descritpion]]. This variable sets the initial
1128 state in new org-mode buffers. The setting can then be toggled on a
1129 per-buffer basis from the Org->Hyperlinks menu."
1130 :group 'org-link
1131 :type 'boolean)
1133 (defcustom org-link-file-path-type 'adaptive
1134 "How the path name in file links should be stored.
1135 Valid values are:
1137 relative Relative to the current directory, i.e. the directory of the file
1138 into which the link is being inserted.
1139 absolute Absolute path, if possible with ~ for home directory.
1140 noabbrev Absolute path, no abbreviation of home directory.
1141 adaptive Use relative path for files in the current directory and sub-
1142 directories of it. For other files, use an absolute path."
1143 :group 'org-link
1144 :type '(choice
1145 (const relative)
1146 (const absolute)
1147 (const noabbrev)
1148 (const adaptive)))
1150 (defcustom org-activate-links '(bracket angle plain radio tag date)
1151 "Types of links that should be activated in Org-mode files.
1152 This is a list of symbols, each leading to the activation of a certain link
1153 type. In principle, it does not hurt to turn on most link types - there may
1154 be a small gain when turning off unused link types. The types are:
1156 bracket The recommended [[link][description]] or [[link]] links with hiding.
1157 angular Links in angular brackes that may contain whitespace like
1158 <bbdb:Carsten Dominik>.
1159 plain Plain links in normal text, no whitespace, like http://google.com.
1160 radio Text that is matched by a radio target, see manual for details.
1161 tag Tag settings in a headline (link to tag search).
1162 date Time stamps (link to calendar).
1164 Changing this variable requires a restart of Emacs to become effective."
1165 :group 'org-link
1166 :type '(set (const :tag "Double bracket links (new style)" bracket)
1167 (const :tag "Angular bracket links (old style)" angular)
1168 (const :tag "Plain text links" plain)
1169 (const :tag "Radio target matches" radio)
1170 (const :tag "Tags" tag)
1171 (const :tag "Timestamps" date)))
1173 (defgroup org-link-store nil
1174 "Options concerning storing links in Org-mode"
1175 :tag "Org Store Link"
1176 :group 'org-link)
1178 (defcustom org-email-link-description-format "Email %c: %.30s"
1179 "Format of the description part of a link to an email or usenet message.
1180 The following %-excapes will be replaced by corresponding information:
1182 %F full \"From\" field
1183 %f name, taken from \"From\" field, address if no name
1184 %T full \"To\" field
1185 %t first name in \"To\" field, address if no name
1186 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1187 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1188 %s subject
1189 %m message-id.
1191 You may use normal field width specification between the % and the letter.
1192 This is for example useful to limit the length of the subject.
1194 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1195 :group 'org-link-store
1196 :type 'string)
1198 (defcustom org-from-is-user-regexp
1199 (let (r1 r2)
1200 (when (and user-mail-address (not (string= user-mail-address "")))
1201 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1202 (when (and user-full-name (not (string= user-full-name "")))
1203 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1204 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1205 "Regexp mached against the \"From:\" header of an email or usenet message.
1206 It should match if the message is from the user him/herself."
1207 :group 'org-link-store
1208 :type 'regexp)
1210 (defcustom org-context-in-file-links t
1211 "Non-nil means, file links from `org-store-link' contain context.
1212 A search string will be added to the file name with :: as separator and
1213 used to find the context when the link is activated by the command
1214 `org-open-at-point'.
1215 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1216 negates this setting for the duration of the command."
1217 :group 'org-link-store
1218 :type 'boolean)
1220 (defcustom org-keep-stored-link-after-insertion nil
1221 "Non-nil means, keep link in list for entire session.
1223 The command `org-store-link' adds a link pointing to the current
1224 location to an internal list. These links accumulate during a session.
1225 The command `org-insert-link' can be used to insert links into any
1226 Org-mode file (offering completion for all stored links). When this
1227 option is nil, every link which has been inserted once using \\[org-insert-link]
1228 will be removed from the list, to make completing the unused links
1229 more efficient."
1230 :group 'org-link-store
1231 :type 'boolean)
1233 (defcustom org-usenet-links-prefer-google nil
1234 "Non-nil means, `org-store-link' will create web links to Google groups.
1235 When nil, Gnus will be used for such links.
1236 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1237 negates this setting for the duration of the command."
1238 :group 'org-link-store
1239 :type 'boolean)
1241 (defgroup org-link-follow nil
1242 "Options concerning following links in Org-mode"
1243 :tag "Org Follow Link"
1244 :group 'org-link)
1246 (defcustom org-tab-follows-link nil
1247 "Non-nil means, on links TAB will follow the link.
1248 Needs to be set before org.el is loaded."
1249 :group 'org-link-follow
1250 :type 'boolean)
1252 (defcustom org-return-follows-link nil
1253 "Non-nil means, on links RET will follow the link.
1254 Needs to be set before org.el is loaded."
1255 :group 'org-link-follow
1256 :type 'boolean)
1258 (defcustom org-mouse-1-follows-link
1259 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1260 "Non-nil means, mouse-1 on a link will follow the link.
1261 A longer mouse click will still set point. Does not work on XEmacs.
1262 Needs to be set before org.el is loaded."
1263 :group 'org-link-follow
1264 :type 'boolean)
1266 (defcustom org-mark-ring-length 4
1267 "Number of different positions to be recorded in the ring
1268 Changing this requires a restart of Emacs to work correctly."
1269 :group 'org-link-follow
1270 :type 'interger)
1272 (defcustom org-link-frame-setup
1273 '((vm . vm-visit-folder-other-frame)
1274 (gnus . gnus-other-frame)
1275 (file . find-file-other-window))
1276 "Setup the frame configuration for following links.
1277 When following a link with Emacs, it may often be useful to display
1278 this link in another window or frame. This variable can be used to
1279 set this up for the different types of links.
1280 For VM, use any of
1281 `vm-visit-folder'
1282 `vm-visit-folder-other-frame'
1283 For Gnus, use any of
1284 `gnus'
1285 `gnus-other-frame'
1286 For FILE, use any of
1287 `find-file'
1288 `find-file-other-window'
1289 `find-file-other-frame'
1290 For the calendar, use the variable `calendar-setup'.
1291 For BBDB, it is currently only possible to display the matches in
1292 another window."
1293 :group 'org-link-follow
1294 :type '(list
1295 (cons (const vm)
1296 (choice
1297 (const vm-visit-folder)
1298 (const vm-visit-folder-other-window)
1299 (const vm-visit-folder-other-frame)))
1300 (cons (const gnus)
1301 (choice
1302 (const gnus)
1303 (const gnus-other-frame)))
1304 (cons (const file)
1305 (choice
1306 (const find-file)
1307 (const find-file-other-window)
1308 (const find-file-other-frame)))))
1310 (defcustom org-display-internal-link-with-indirect-buffer nil
1311 "Non-nil means, use indirect buffer to display infile links.
1312 Activating internal links (from one location in a file to another location
1313 in the same file) normally just jumps to the location. When the link is
1314 activated with a C-u prefix (or with mouse-3), the link is displayed in
1315 another window. When this option is set, the other window actually displays
1316 an indirect buffer clone of the current buffer, to avoid any visibility
1317 changes to the current buffer."
1318 :group 'org-link-follow
1319 :type 'boolean)
1321 (defcustom org-open-non-existing-files nil
1322 "Non-nil means, `org-open-file' will open non-existing files.
1323 When nil, an error will be generated."
1324 :group 'org-link-follow
1325 :type 'boolean)
1327 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1328 "Function and arguments to call for following mailto links.
1329 This is a list with the first element being a lisp function, and the
1330 remaining elements being arguments to the function. In string arguments,
1331 %a will be replaced by the address, and %s will be replaced by the subject
1332 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1333 :group 'org-link-follow
1334 :type '(choice
1335 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1336 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1337 (const :tag "message-mail" (message-mail "%a" "%s"))
1338 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1340 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1341 "Non-nil means, ask for confirmation before executing shell links.
1342 Shell links can be dangerous: just think about a link
1344 [[shell:rm -rf ~/*][Google Search]]
1346 This link would show up in your Org-mode document as \"Google Search\",
1347 but really it would remove your entire home directory.
1348 Therefore we advise against setting this variable to nil.
1349 Just change it to `y-or-n-p' of you want to confirm with a
1350 single keystroke rather than having to type \"yes\"."
1351 :group 'org-link-follow
1352 :type '(choice
1353 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1354 (const :tag "with y-or-n (faster)" y-or-n-p)
1355 (const :tag "no confirmation (dangerous)" nil)))
1357 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1358 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1359 Elisp links can be dangerous: just think about a link
1361 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1363 This link would show up in your Org-mode document as \"Google Search\",
1364 but really it would remove your entire home directory.
1365 Therefore we advise against setting this variable to nil.
1366 Just change it to `y-or-n-p' of you want to confirm with a
1367 single keystroke rather than having to type \"yes\"."
1368 :group 'org-link-follow
1369 :type '(choice
1370 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1371 (const :tag "with y-or-n (faster)" y-or-n-p)
1372 (const :tag "no confirmation (dangerous)" nil)))
1374 (defconst org-file-apps-defaults-gnu
1375 '((remote . emacs)
1376 (t . mailcap))
1377 "Default file applications on a UNIX or GNU/Linux system.
1378 See `org-file-apps'.")
1380 (defconst org-file-apps-defaults-macosx
1381 '((remote . emacs)
1382 (t . "open %s")
1383 ("ps" . "gv %s")
1384 ("ps.gz" . "gv %s")
1385 ("eps" . "gv %s")
1386 ("eps.gz" . "gv %s")
1387 ("dvi" . "xdvi %s")
1388 ("fig" . "xfig %s"))
1389 "Default file applications on a MacOS X system.
1390 The system \"open\" is known as a default, but we use X11 applications
1391 for some files for which the OS does not have a good default.
1392 See `org-file-apps'.")
1394 (defconst org-file-apps-defaults-windowsnt
1395 (list
1396 '(remote . emacs)
1397 (cons t
1398 (list (if (featurep 'xemacs)
1399 'mswindows-shell-execute
1400 'w32-shell-execute)
1401 "open" 'file)))
1402 "Default file applications on a Windows NT system.
1403 The system \"open\" is used for most files.
1404 See `org-file-apps'.")
1406 (defcustom org-file-apps
1408 ("txt" . emacs)
1409 ("tex" . emacs)
1410 ("ltx" . emacs)
1411 ("org" . emacs)
1412 ("el" . emacs)
1413 ("bib" . emacs)
1415 "External applications for opening `file:path' items in a document.
1416 Org-mode uses system defaults for different file types, but
1417 you can use this variable to set the application for a given file
1418 extension. The entries in this list are cons cells where the car identifies
1419 files and the cdr the corresponding command. Possible values for the
1420 file identifier are
1421 \"ext\" A string identifying an extension
1422 `directory' Matches a directory
1423 `remote' Matches a remote file, accessible through tramp or efs.
1424 Remote files most likely should be visited through Emacs
1425 because external applications cannot handle such paths.
1426 t Default for all remaining files
1428 Possible values for the command are:
1429 `emacs' The file will be visited by the current Emacs process.
1430 `default' Use the default application for this file type.
1431 string A command to be executed by a shell; %s will be replaced
1432 by the path to the file.
1433 sexp A Lisp form which will be evaluated. The file path will
1434 be available in the Lisp variable `file'.
1435 For more examples, see the system specific constants
1436 `org-file-apps-defaults-macosx'
1437 `org-file-apps-defaults-windowsnt'
1438 `org-file-apps-defaults-gnu'."
1439 :group 'org-link-follow
1440 :type '(repeat
1441 (cons (choice :value ""
1442 (string :tag "Extension")
1443 (const :tag "Default for unrecognized files" t)
1444 (const :tag "Remote file" remote)
1445 (const :tag "Links to a directory" directory))
1446 (choice :value ""
1447 (const :tag "Visit with Emacs" emacs)
1448 (const :tag "Use system default" default)
1449 (string :tag "Command")
1450 (sexp :tag "Lisp form")))))
1452 (defcustom org-mhe-search-all-folders nil
1453 "Non-nil means, that the search for the mh-message will be extended to
1454 all folders if the message cannot be found in the folder given in the link.
1455 Searching all folders is very efficient with one of the search engines
1456 supported by MH-E, but will be slow with pick."
1457 :group 'org-link-follow
1458 :type 'boolean)
1460 (defgroup org-remember nil
1461 "Options concerning interaction with remember.el."
1462 :tag "Org Remember"
1463 :group 'org)
1465 (defcustom org-directory "~/org"
1466 "Directory with org files.
1467 This directory will be used as default to prompt for org files.
1468 Used by the hooks for remember.el."
1469 :group 'org-remember
1470 :type 'directory)
1472 (defcustom org-default-notes-file "~/.notes"
1473 "Default target for storing notes.
1474 Used by the hooks for remember.el. This can be a string, or nil to mean
1475 the value of `remember-data-file'.
1476 You can set this on a per-template basis with the variable
1477 `org-remember-templates'."
1478 :group 'org-remember
1479 :type '(choice
1480 (const :tag "Default from remember-data-file" nil)
1481 file))
1483 (defcustom org-remember-store-without-prompt t
1484 "Non-nil means, `C-c C-c' stores remember note without further promts.
1485 In this case, you need `C-u C-c C-c' to get the prompts for
1486 note file and headline.
1487 When this variable is nil, `C-c C-c' give you the prompts, and
1488 `C-u C-c C-c' trigger the fasttrack."
1489 :group 'org-remember
1490 :type 'boolean)
1492 (defcustom org-remember-interactive-interface 'refile
1493 "The interface to be used for interactive filing of remember notes.
1494 This is only used when the interactive mode for selecting a filing
1495 location is used (see the variable `org-remember-store-without-prompt').
1496 Allowed vaues are:
1497 outline The interface shows an outline of the relevant file
1498 and the correct heading is found by moving through
1499 the outline or by searching with incremental search.
1500 outline-path-completion Headlines in the current buffer are offered via
1501 completion.
1502 refile Use the refile interface, and offer headlines,
1503 possibly from different buffers."
1504 :group 'org-remember
1505 :type '(choice
1506 (const :tag "Refile" refile)
1507 (const :tag "Outline" outline)
1508 (const :tag "Outline-path-completion" outline-path-completion)))
1510 (defcustom org-goto-interface 'outline
1511 "The default interface to be used for `org-goto'.
1512 Allowed vaues are:
1513 outline The interface shows an outline of the relevant file
1514 and the correct heading is found by moving through
1515 the outline or by searching with incremental search.
1516 outline-path-completion Headlines in the current buffer are offered via
1517 completion."
1518 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1519 :type '(choice
1520 (const :tag "Outline" outline)
1521 (const :tag "Outline-path-completion" outline-path-completion)))
1523 (defcustom org-remember-default-headline ""
1524 "The headline that should be the default location in the notes file.
1525 When filing remember notes, the cursor will start at that position.
1526 You can set this on a per-template basis with the variable
1527 `org-remember-templates'."
1528 :group 'org-remember
1529 :type 'string)
1531 (defcustom org-remember-templates nil
1532 "Templates for the creation of remember buffers.
1533 When nil, just let remember make the buffer.
1534 When not nil, this is a list of 5-element lists. In each entry, the first
1535 element is the name of the template, which should be a single short word.
1536 The second element is a character, a unique key to select this template.
1537 The third element is the template. The fourth element is optional and can
1538 specify a destination file for remember items created with this template.
1539 The default file is given by `org-default-notes-file'. An optional fifth
1540 element can specify the headline in that file that should be offered
1541 first when the user is asked to file the entry. The default headline is
1542 given in the variable `org-remember-default-headline'.
1544 The template specifies the structure of the remember buffer. It should have
1545 a first line starting with a star, to act as the org-mode headline.
1546 Furthermore, the following %-escapes will be replaced with content:
1548 %^{prompt} Prompt the user for a string and replace this sequence with it.
1549 A default value and a completion table ca be specified like this:
1550 %^{prompt|default|completion2|completion3|...}
1551 %t time stamp, date only
1552 %T time stamp with date and time
1553 %u, %U like the above, but inactive time stamps
1554 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1555 You may define a prompt like %^{Please specify birthday}t
1556 %n user name (taken from `user-full-name')
1557 %a annotation, normally the link created with org-store-link
1558 %i initial content, the region active. If %i is indented,
1559 the entire inserted text will be indented as well.
1560 %c content of the clipboard, or current kill ring head
1561 %^g prompt for tags, with completion on tags in target file
1562 %^G prompt for tags, with completion all tags in all agenda files
1563 %:keyword specific information for certain link types, see below
1564 %[pathname] insert the contents of the file given by `pathname'
1565 %(sexp) evaluate elisp `(sexp)' and replace with the result
1566 %! Store this note immediately after filling the template
1568 %? After completing the template, position cursor here.
1570 Apart from these general escapes, you can access information specific to the
1571 link type that is created. For example, calling `remember' in emails or gnus
1572 will record the author and the subject of the message, which you can access
1573 with %:author and %:subject, respectively. Here is a complete list of what
1574 is recorded for each link type.
1576 Link type | Available information
1577 -------------------+------------------------------------------------------
1578 bbdb | %:type %:name %:company
1579 vm, wl, mh, rmail | %:type %:subject %:message-id
1580 | %:from %:fromname %:fromaddress
1581 | %:to %:toname %:toaddress
1582 | %:fromto (either \"to NAME\" or \"from NAME\")
1583 gnus | %:group, for messages also all email fields
1584 w3, w3m | %:type %:url
1585 info | %:type %:file %:node
1586 calendar | %:type %:date"
1587 :group 'org-remember
1588 :get (lambda (var) ; Make sure all entries have 5 elements
1589 (mapcar (lambda (x)
1590 (if (not (stringp (car x))) (setq x (cons "" x)))
1591 (cond ((= (length x) 4) (append x '("")))
1592 ((= (length x) 3) (append x '("" "")))
1593 (t x)))
1594 (default-value var)))
1595 :type '(repeat
1596 :tag "enabled"
1597 (list :value ("" ?a "\n" nil nil)
1598 (string :tag "Name")
1599 (character :tag "Selection Key")
1600 (string :tag "Template")
1601 (choice
1602 (file :tag "Destination file")
1603 (const :tag "Prompt for file" nil))
1604 (choice
1605 (string :tag "Destination headline")
1606 (const :tag "Selection interface for heading")))))
1608 (defcustom org-reverse-note-order nil
1609 "Non-nil means, store new notes at the beginning of a file or entry.
1610 When nil, new notes will be filed to the end of a file or entry.
1611 This can also be a list with cons cells of regular expressions that
1612 are matched against file names, and values."
1613 :group 'org-remember
1614 :type '(choice
1615 (const :tag "Reverse always" t)
1616 (const :tag "Reverse never" nil)
1617 (repeat :tag "By file name regexp"
1618 (cons regexp boolean))))
1620 (defcustom org-refile-targets nil
1621 "Targets for refiling entries with \\[org-refile].
1622 This is list of cons cells. Each cell contains:
1623 - a specification of the files to be considered, either a list of files,
1624 or a symbol whose function or value fields will be used to retrieve
1625 a file name or a list of file names. Nil means, refile to a different
1626 heading in the current buffer.
1627 - A specification of how to find candidate refile targets. This may be
1628 any of
1629 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1630 This tag has to be present in all target headlines, inheritance will
1631 not be considered.
1632 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1633 todo keyword.
1634 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1635 headlines that are refiling targets.
1636 - a cons cell (:level . N). Any headline of level N is considered a target.
1637 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1638 ;; FIXME: what if there are a var and func with same name???
1639 :group 'org-remember
1640 :type '(repeat
1641 (cons
1642 (choice :value org-agenda-files
1643 (const :tag "All agenda files" org-agenda-files)
1644 (const :tag "Current buffer" nil)
1645 (function) (variable) (file))
1646 (choice :tag "Identify target headline by"
1647 (cons :tag "Specific tag" (const :tag) (string))
1648 (cons :tag "TODO keyword" (const :todo) (string))
1649 (cons :tag "Regular expression" (const :regexp) (regexp))
1650 (cons :tag "Level number" (const :level) (integer))
1651 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1653 (defcustom org-refile-use-outline-path nil
1654 "Non-nil means, provide refile targets as paths.
1655 So a level 3 headline will be available as level1/level2/level3.
1656 When the value is `file', also include the file name (without directory)
1657 into the path. When `full-file-path', include the full file path."
1658 :group 'org-remember
1659 :type '(choice
1660 (const :tag "Not" nil)
1661 (const :tag "Yes" t)
1662 (const :tag "Start with file name" file)
1663 (const :tag "Start with full file path" full-file-path)))
1665 (defgroup org-todo nil
1666 "Options concerning TODO items in Org-mode."
1667 :tag "Org TODO"
1668 :group 'org)
1670 (defgroup org-progress nil
1671 "Options concerning Progress logging in Org-mode."
1672 :tag "Org Progress"
1673 :group 'org-time)
1675 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1676 "List of TODO entry keyword sequences and their interpretation.
1677 \\<org-mode-map>This is a list of sequences.
1679 Each sequence starts with a symbol, either `sequence' or `type',
1680 indicating if the keywords should be interpreted as a sequence of
1681 action steps, or as different types of TODO items. The first
1682 keywords are states requiring action - these states will select a headline
1683 for inclusion into the global TODO list Org-mode produces. If one of
1684 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1685 signify that no further action is necessary. If \"|\" is not found,
1686 the last keyword is treated as the only DONE state of the sequence.
1688 The command \\[org-todo] cycles an entry through these states, and one
1689 additional state where no keyword is present. For details about this
1690 cycling, see the manual.
1692 TODO keywords and interpretation can also be set on a per-file basis with
1693 the special #+SEQ_TODO and #+TYP_TODO lines.
1695 Each keyword can optionally specify a character for fast state selection
1696 \(in combination with the variable `org-use-fast-todo-selection')
1697 and specifiers for state change logging, using the same syntax
1698 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1699 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1700 indicates to record a time stamp each time this state is selected.
1701 \"WAIT(w@)\" says that the user should in addition be prompted for a
1702 note, and \"WAIT(w@/@)\" says that a note should be taken both when
1703 entering and when leaving this state.
1705 For backward compatibility, this variable may also be just a list
1706 of keywords - in this case the interptetation (sequence or type) will be
1707 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1708 :group 'org-todo
1709 :group 'org-keywords
1710 :type '(choice
1711 (repeat :tag "Old syntax, just keywords"
1712 (string :tag "Keyword"))
1713 (repeat :tag "New syntax"
1714 (cons
1715 (choice
1716 :tag "Interpretation"
1717 (const :tag "Sequence (cycling hits every state)" sequence)
1718 (const :tag "Type (cycling directly to DONE)" type))
1719 (repeat
1720 (string :tag "Keyword"))))))
1722 (defvar org-todo-keywords-1 nil
1723 "All TODO and DONE keywords active in a buffer.")
1724 (make-variable-buffer-local 'org-todo-keywords-1)
1725 (defvar org-todo-keywords-for-agenda nil)
1726 (defvar org-done-keywords-for-agenda nil)
1727 (defvar org-not-done-keywords nil)
1728 (make-variable-buffer-local 'org-not-done-keywords)
1729 (defvar org-done-keywords nil)
1730 (make-variable-buffer-local 'org-done-keywords)
1731 (defvar org-todo-heads nil)
1732 (make-variable-buffer-local 'org-todo-heads)
1733 (defvar org-todo-sets nil)
1734 (make-variable-buffer-local 'org-todo-sets)
1735 (defvar org-todo-log-states nil)
1736 (make-variable-buffer-local 'org-todo-log-states)
1737 (defvar org-todo-kwd-alist nil)
1738 (make-variable-buffer-local 'org-todo-kwd-alist)
1739 (defvar org-todo-key-alist nil)
1740 (make-variable-buffer-local 'org-todo-key-alist)
1741 (defvar org-todo-key-trigger nil)
1742 (make-variable-buffer-local 'org-todo-key-trigger)
1744 (defcustom org-todo-interpretation 'sequence
1745 "Controls how TODO keywords are interpreted.
1746 This variable is in principle obsolete and is only used for
1747 backward compatibility, if the interpretation of todo keywords is
1748 not given already in `org-todo-keywords'. See that variable for
1749 more information."
1750 :group 'org-todo
1751 :group 'org-keywords
1752 :type '(choice (const sequence)
1753 (const type)))
1755 (defcustom org-use-fast-todo-selection 'prefix
1756 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1757 This variable describes if and under what circumstances the cycling
1758 mechanism for TODO keywords will be replaced by a single-key, direct
1759 selection scheme.
1761 When nil, fast selection is never used.
1763 When the symbol `prefix', it will be used when `org-todo' is called with
1764 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1765 in an agenda buffer.
1767 When t, fast selection is used by default. In this case, the prefix
1768 argument forces cycling instead.
1770 In all cases, the special interface is only used if access keys have actually
1771 been assigned by the user, i.e. if keywords in the configuration are followed
1772 by a letter in parenthesis, like TODO(t)."
1773 :group 'org-todo
1774 :type '(choice
1775 (const :tag "Never" nil)
1776 (const :tag "By default" t)
1777 (const :tag "Only with C-u C-c C-t" prefix)))
1779 (defcustom org-after-todo-state-change-hook nil
1780 "Hook which is run after the state of a TODO item was changed.
1781 The new state (a string with a TODO keyword, or nil) is available in the
1782 Lisp variable `state'."
1783 :group 'org-todo
1784 :type 'hook)
1786 (defcustom org-log-done nil
1787 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1788 When equal to the list (done), also prompt for a closing note.
1789 This can also be configured on a per-file basis by adding one of
1790 the following lines anywhere in the buffer:
1792 #+STARTUP: logdone
1793 #+STARTUP: lognotedone
1794 #+STARTUP: nologdone"
1795 :group 'org-todo
1796 :group 'org-progress
1797 :type '(choice
1798 (const :tag "No logging" nil)
1799 (const :tag "Record CLOSED timestamp" time)
1800 (const :tag "Record CLOSED timestamp with closing note." note)))
1802 ;; Normalize old uses of org-log-done.
1803 (cond
1804 ((eq org-log-done t) (setq org-log-done 'time))
1805 ((and (listp org-log-done) (memq 'done org-log-done))
1806 (setq org-log-done 'note)))
1808 ;; FIXME: document
1809 (defcustom org-log-note-clock-out nil
1810 "Non-nil means, recored a note when clocking out of an item.
1811 This can also be configured on a per-file basis by adding one of
1812 the following lines anywhere in the buffer:
1814 #+STARTUP: lognoteclock-out
1815 #+STARTUP: nolognoteclock-out"
1816 :group 'org-todo
1817 :group 'org-progress
1818 :type 'boolean)
1820 (defcustom org-log-done-with-time t
1821 "Non-nil means, the CLOSED time stamp will contain date and time.
1822 When nil, only the date will be recorded."
1823 :group 'org-progress
1824 :type 'boolean)
1826 (defcustom org-log-note-headings
1827 '((done . "CLOSING NOTE %t")
1828 (state . "State %-12s %t")
1829 (clock-out . ""))
1830 "Headings for notes added when clocking out or closing TODO items.
1831 The value is an alist, with the car being a symbol indicating the note
1832 context, and the cdr is the heading to be used. The heading may also be the
1833 empty string.
1834 %t in the heading will be replaced by a time stamp.
1835 %s will be replaced by the new TODO state, in double quotes.
1836 %u will be replaced by the user name.
1837 %U will be replaced by the full user name."
1838 :group 'org-todo
1839 :group 'org-progress
1840 :type '(list :greedy t
1841 (cons (const :tag "Heading when closing an item" done) string)
1842 (cons (const :tag
1843 "Heading when changing todo state (todo sequence only)"
1844 state) string)
1845 (cons (const :tag "Heading when clocking out" clock-out) string)))
1847 (defcustom org-log-states-order-reversed t
1848 "Non-nil means, the latest state change note will be directly after heading.
1849 When nil, the notes will be orderer according to time."
1850 :group 'org-todo
1851 :group 'org-progress
1852 :type 'boolean)
1854 (defcustom org-log-repeat 'time
1855 "Non-nil means, record moving through the DONE state when triggering repeat.
1856 An auto-repeating tasks is immediately switched back to TODO when marked
1857 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1858 the TODO keyword definition, or recording a cloing note by setting
1859 `org-log-done', there will be no record of the task moving trhough DONE.
1860 This variable forces taking a note anyway. Possible values are:
1862 nil Don't force a record
1863 time Record a time stamp
1864 note Record a note
1866 This option can also be set with on a per-file-basis with
1868 #+STARTUP: logrepeat
1869 #+STARTUP: lognoterepeat
1870 #+STARTUP: nologrepeat
1872 You can have local logging settings for a subtree by setting the LOGGING
1873 property to one or more of these keywords."
1874 :group 'org-todo
1875 :group 'org-progress
1876 :type '(choice
1877 (const :tag "Don't force a record" nil)
1878 (const :tag "Force recording the DONE state" time)
1879 (const :tag "Force recording a note with the DONE state" note)))
1881 (defcustom org-clock-into-drawer 2
1882 "Should clocking info be wrapped into a drawer?
1883 When t, clocking info will always be inserted into a :CLOCK: drawer.
1884 If necessary, the drawer will be created.
1885 When nil, the drawer will not be created, but used when present.
1886 When an integer and the number of clocking entries in an item
1887 reaches or exceeds this number, a drawer will be created."
1888 :group 'org-todo
1889 :group 'org-progress
1890 :type '(choice
1891 (const :tag "Always" t)
1892 (const :tag "Only when drawer exists" nil)
1893 (integer :tag "When at least N clock entries")))
1895 (defcustom org-clock-out-when-done t
1896 "When t, the clock will be stopped when the relevant entry is marked DONE.
1897 Nil means, clock will keep running until stopped explicitly with
1898 `C-c C-x C-o', or until the clock is started in a different item."
1899 :group 'org-progress
1900 :type 'boolean)
1902 (defcustom org-clock-in-switch-to-state nil
1903 "Set task to a special todo state while clocking it.
1904 The value should be the state to which the entry should be switched."
1905 :group 'org-progress
1906 :group 'org-todo
1907 :type '(choice
1908 (const :tag "Don't force a state" nil)
1909 (string :tag "State")))
1911 (defgroup org-priorities nil
1912 "Priorities in Org-mode."
1913 :tag "Org Priorities"
1914 :group 'org-todo)
1916 (defcustom org-highest-priority ?A
1917 "The highest priority of TODO items. A character like ?A, ?B etc.
1918 Must have a smaller ASCII number than `org-lowest-priority'."
1919 :group 'org-priorities
1920 :type 'character)
1922 (defcustom org-lowest-priority ?C
1923 "The lowest priority of TODO items. A character like ?A, ?B etc.
1924 Must have a larger ASCII number than `org-highest-priority'."
1925 :group 'org-priorities
1926 :type 'character)
1928 (defcustom org-default-priority ?B
1929 "The default priority of TODO items.
1930 This is the priority an item get if no explicit priority is given."
1931 :group 'org-priorities
1932 :type 'character)
1934 (defcustom org-priority-start-cycle-with-default t
1935 "Non-nil means, start with default priority when starting to cycle.
1936 When this is nil, the first step in the cycle will be (depending on the
1937 command used) one higher or lower that the default priority."
1938 :group 'org-priorities
1939 :type 'boolean)
1941 (defgroup org-time nil
1942 "Options concerning time stamps and deadlines in Org-mode."
1943 :tag "Org Time"
1944 :group 'org)
1946 (defcustom org-insert-labeled-timestamps-at-point nil
1947 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1948 When nil, these labeled time stamps are forces into the second line of an
1949 entry, just after the headline. When scheduling from the global TODO list,
1950 the time stamp will always be forced into the second line."
1951 :group 'org-time
1952 :type 'boolean)
1954 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1955 "Formats for `format-time-string' which are used for time stamps.
1956 It is not recommended to change this constant.")
1958 (defcustom org-time-stamp-rounding-minutes 0
1959 "Number of minutes to round time stamps to upon insertion.
1960 When zero, insert the time unmodified. Useful rounding numbers
1961 should be factors of 60, so for example 5, 10, 15.
1962 When this is not zero, you can still force an exact time-stamp by using
1963 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1964 :group 'org-time
1965 :type 'integer)
1967 (defcustom org-display-custom-times nil
1968 "Non-nil means, overlay custom formats over all time stamps.
1969 The formats are defined through the variable `org-time-stamp-custom-formats'.
1970 To turn this on on a per-file basis, insert anywhere in the file:
1971 #+STARTUP: customtime"
1972 :group 'org-time
1973 :set 'set-default
1974 :type 'sexp)
1975 (make-variable-buffer-local 'org-display-custom-times)
1977 (defcustom org-time-stamp-custom-formats
1978 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1979 "Custom formats for time stamps. See `format-time-string' for the syntax.
1980 These are overlayed over the default ISO format if the variable
1981 `org-display-custom-times' is set. Time like %H:%M should be at the
1982 end of the second format."
1983 :group 'org-time
1984 :type 'sexp)
1986 (defun org-time-stamp-format (&optional long inactive)
1987 "Get the right format for a time string."
1988 (let ((f (if long (cdr org-time-stamp-formats)
1989 (car org-time-stamp-formats))))
1990 (if inactive
1991 (concat "[" (substring f 1 -1) "]")
1992 f)))
1994 (defcustom org-read-date-prefer-future t
1995 "Non-nil means, assume future for incomplete date input from user.
1996 This affects the following situations:
1997 1. The user gives a day, but no month.
1998 For example, if today is the 15th, and you enter \"3\", Org-mode will
1999 read this as the third of *next* month. However, if you enter \"17\",
2000 it will be considered as *this* month.
2001 2. The user gives a month but not a year.
2002 For example, if it is april and you enter \"feb 2\", this will be read
2003 as feb 2, *next* year. \"May 5\", however, will be this year.
2005 When this option is nil, the current month and year will always be used
2006 as defaults."
2007 :group 'org-time
2008 :type 'boolean)
2010 (defcustom org-read-date-display-live t
2011 "Non-nil means, display current interpretation of date prompt live.
2012 This display will be in an overlay, in the minibuffer."
2013 :group 'org-time
2014 :type 'boolean)
2016 (defcustom org-read-date-popup-calendar t
2017 "Non-nil means, pop up a calendar when prompting for a date.
2018 In the calendar, the date can be selected with mouse-1. However, the
2019 minibuffer will also be active, and you can simply enter the date as well.
2020 When nil, only the minibuffer will be available."
2021 :group 'org-time
2022 :type 'boolean)
2023 (if (fboundp 'defvaralias)
2024 (defvaralias 'org-popup-calendar-for-date-prompt
2025 'org-read-date-popup-calendar))
2027 (defcustom org-extend-today-until 0
2028 "The hour when your day really ends.
2029 This has influence for the following applications:
2030 - When switching the agenda to \"today\". It it is still earlier than
2031 the time given here, the day recognized as TODAY is actually yesterday.
2032 - When a date is read from the user and it is still before the time given
2033 here, the current date and time will be assumed to be yesterday, 23:59.
2035 FIXME:
2036 IMPORTANT: This is still a very experimental feature, it may disappear
2037 again or it may be extended to mean more things."
2038 :group 'org-time
2039 :type 'number)
2041 (defcustom org-edit-timestamp-down-means-later nil
2042 "Non-nil means, S-down will increase the time in a time stamp.
2043 When nil, S-up will increase."
2044 :group 'org-time
2045 :type 'boolean)
2047 (defcustom org-calendar-follow-timestamp-change t
2048 "Non-nil means, make the calendar window follow timestamp changes.
2049 When a timestamp is modified and the calendar window is visible, it will be
2050 moved to the new date."
2051 :group 'org-time
2052 :type 'boolean)
2054 (defcustom org-clock-heading-function nil
2055 "When non-nil, should be a function to create `org-clock-heading'.
2056 This is the string shown in the mode line when a clock is running.
2057 The function is called with point at the beginning of the headline."
2058 :group 'org-time ; FIXME: Should we have a separate group????
2059 :type 'function)
2061 (defgroup org-tags nil
2062 "Options concerning tags in Org-mode."
2063 :tag "Org Tags"
2064 :group 'org)
2066 (defcustom org-tag-alist nil
2067 "List of tags allowed in Org-mode files.
2068 When this list is nil, Org-mode will base TAG input on what is already in the
2069 buffer.
2070 The value of this variable is an alist, the car of each entry must be a
2071 keyword as a string, the cdr may be a character that is used to select
2072 that tag through the fast-tag-selection interface.
2073 See the manual for details."
2074 :group 'org-tags
2075 :type '(repeat
2076 (choice
2077 (cons (string :tag "Tag name")
2078 (character :tag "Access char"))
2079 (const :tag "Start radio group" (:startgroup))
2080 (const :tag "End radio group" (:endgroup)))))
2082 (defcustom org-use-fast-tag-selection 'auto
2083 "Non-nil means, use fast tag selection scheme.
2084 This is a special interface to select and deselect tags with single keys.
2085 When nil, fast selection is never used.
2086 When the symbol `auto', fast selection is used if and only if selection
2087 characters for tags have been configured, either through the variable
2088 `org-tag-alist' or through a #+TAGS line in the buffer.
2089 When t, fast selection is always used and selection keys are assigned
2090 automatically if necessary."
2091 :group 'org-tags
2092 :type '(choice
2093 (const :tag "Always" t)
2094 (const :tag "Never" nil)
2095 (const :tag "When selection characters are configured" 'auto)))
2097 (defcustom org-fast-tag-selection-single-key nil
2098 "Non-nil means, fast tag selection exits after first change.
2099 When nil, you have to press RET to exit it.
2100 During fast tag selection, you can toggle this flag with `C-c'.
2101 This variable can also have the value `expert'. In this case, the window
2102 displaying the tags menu is not even shown, until you press C-c again."
2103 :group 'org-tags
2104 :type '(choice
2105 (const :tag "No" nil)
2106 (const :tag "Yes" t)
2107 (const :tag "Expert" expert)))
2109 (defvar org-fast-tag-selection-include-todo nil
2110 "Non-nil means, fast tags selection interface will also offer TODO states.
2111 This is an undocumented feature, you should not rely on it.")
2113 (defcustom org-tags-column -80
2114 "The column to which tags should be indented in a headline.
2115 If this number is positive, it specifies the column. If it is negative,
2116 it means that the tags should be flushright to that column. For example,
2117 -80 works well for a normal 80 character screen."
2118 :group 'org-tags
2119 :type 'integer)
2121 (defcustom org-auto-align-tags t
2122 "Non-nil means, realign tags after pro/demotion of TODO state change.
2123 These operations change the length of a headline and therefore shift
2124 the tags around. With this options turned on, after each such operation
2125 the tags are again aligned to `org-tags-column'."
2126 :group 'org-tags
2127 :type 'boolean)
2129 (defcustom org-use-tag-inheritance t
2130 "Non-nil means, tags in levels apply also for sublevels.
2131 When nil, only the tags directly given in a specific line apply there.
2132 If you turn off this option, you very likely want to turn on the
2133 companion option `org-tags-match-list-sublevels'."
2134 :group 'org-tags
2135 :type 'boolean)
2137 (defcustom org-tags-match-list-sublevels nil
2138 "Non-nil means list also sublevels of headlines matching tag search.
2139 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2140 the sublevels of a headline matching a tag search often also match
2141 the same search. Listing all of them can create very long lists.
2142 Setting this variable to nil causes subtrees of a match to be skipped.
2143 This option is off by default, because inheritance in on. If you turn
2144 inheritance off, you very likely want to turn this option on.
2146 As a special case, if the tag search is restricted to TODO items, the
2147 value of this variable is ignored and sublevels are always checked, to
2148 make sure all corresponding TODO items find their way into the list."
2149 :group 'org-tags
2150 :type 'boolean)
2152 (defvar org-tags-history nil
2153 "History of minibuffer reads for tags.")
2154 (defvar org-last-tags-completion-table nil
2155 "The last used completion table for tags.")
2156 (defvar org-after-tags-change-hook nil
2157 "Hook that is run after the tags in a line have changed.")
2159 (defgroup org-properties nil
2160 "Options concerning properties in Org-mode."
2161 :tag "Org Properties"
2162 :group 'org)
2164 (defcustom org-property-format "%-10s %s"
2165 "How property key/value pairs should be formatted by `indent-line'.
2166 When `indent-line' hits a property definition, it will format the line
2167 according to this format, mainly to make sure that the values are
2168 lined-up with respect to each other."
2169 :group 'org-properties
2170 :type 'string)
2172 (defcustom org-use-property-inheritance nil
2173 "Non-nil means, properties apply also for sublevels.
2174 This setting is only relevant during property searches, not when querying
2175 an entry with `org-entry-get'. To retrieve a property with inheritance,
2176 you need to call `org-entry-get' with the inheritance flag.
2177 Turning this on can cause significant overhead when doing a search, so
2178 this is turned off by default.
2179 When nil, only the properties directly given in the current entry count.
2180 The value may also be a list of properties that shouldhave inheritance.
2182 However, note that some special properties use inheritance under special
2183 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2184 and the properties ending in \"_ALL\" when they are used as descriptor
2185 for valid values of a property."
2186 :group 'org-properties
2187 :type '(choice
2188 (const :tag "Not" nil)
2189 (const :tag "Always" nil)
2190 (repeat :tag "Specific properties" (string :tag "Property"))))
2192 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2193 "The default column format, if no other format has been defined.
2194 This variable can be set on the per-file basis by inserting a line
2196 #+COLUMNS: %25ITEM ....."
2197 :group 'org-properties
2198 :type 'string)
2200 (defcustom org-global-properties nil
2201 "List of property/value pairs that can be inherited by any entry.
2202 You can set buffer-local values for this by adding lines like
2204 #+PROPERTY: NAME VALUE"
2205 :group 'org-properties
2206 :type '(repeat
2207 (cons (string :tag "Property")
2208 (string :tag "Value"))))
2210 (defvar org-local-properties nil
2211 "List of property/value pairs that can be inherited by any entry.
2212 Valid for the current buffer.
2213 This variable is populated from #+PROPERTY lines.")
2215 (defgroup org-agenda nil
2216 "Options concerning agenda views in Org-mode."
2217 :tag "Org Agenda"
2218 :group 'org)
2220 (defvar org-category nil
2221 "Variable used by org files to set a category for agenda display.
2222 Such files should use a file variable to set it, for example
2224 # -*- mode: org; org-category: \"ELisp\"
2226 or contain a special line
2228 #+CATEGORY: ELisp
2230 If the file does not specify a category, then file's base name
2231 is used instead.")
2232 (make-variable-buffer-local 'org-category)
2234 (defcustom org-agenda-files nil
2235 "The files to be used for agenda display.
2236 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2237 \\[org-remove-file]. You can also use customize to edit the list.
2239 If an entry is a directory, all files in that directory that are matched by
2240 `org-agenda-file-regexp' will be part of the file list.
2242 If the value of the variable is not a list but a single file name, then
2243 the list of agenda files is actually stored and maintained in that file, one
2244 agenda file per line."
2245 :group 'org-agenda
2246 :type '(choice
2247 (repeat :tag "List of files and directories" file)
2248 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2250 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2251 "Regular expression to match files for `org-agenda-files'.
2252 If any element in the list in that variable contains a directory instead
2253 of a normal file, all files in that directory that are matched by this
2254 regular expression will be included."
2255 :group 'org-agenda
2256 :type 'regexp)
2258 (defcustom org-agenda-skip-unavailable-files nil
2259 "t means to just skip non-reachable files in `org-agenda-files'.
2260 Nil means to remove them, after a query, from the list."
2261 :group 'org-agenda
2262 :type 'boolean)
2264 (defcustom org-agenda-text-search-extra-files nil
2265 "List of extra files to be searched by text search commands.
2266 These files will be search in addition to the agenda files bu the
2267 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2268 Note that these files will only be searched for text search commands,
2269 not for the other agenda views like todo lists, tag earches or the weekly
2270 agenda. This variable is intended to list notes and possibly archive files
2271 that should also be searched by these two commands."
2272 :group 'org-agenda
2273 :type '(repeat file))
2275 (if (fboundp 'defvaralias)
2276 (defvaralias 'org-agenda-multi-occur-extra-files
2277 'org-agenda-text-search-extra-files))
2279 (defcustom org-agenda-confirm-kill 1
2280 "When set, remote killing from the agenda buffer needs confirmation.
2281 When t, a confirmation is always needed. When a number N, confirmation is
2282 only needed when the text to be killed contains more than N non-white lines."
2283 :group 'org-agenda
2284 :type '(choice
2285 (const :tag "Never" nil)
2286 (const :tag "Always" t)
2287 (number :tag "When more than N lines")))
2289 (defcustom org-calendar-to-agenda-key [?c]
2290 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2291 The command `org-calendar-goto-agenda' will be bound to this key. The
2292 default is the character `c' because then `c' can be used to switch back and
2293 forth between agenda and calendar."
2294 :group 'org-agenda
2295 :type 'sexp)
2297 (defcustom org-agenda-compact-blocks nil
2298 "Non-nil means, make the block agenda more compact.
2299 This is done by leaving out unnecessary lines."
2300 :group 'org-agenda
2301 :type nil)
2303 (defgroup org-agenda-export nil
2304 "Options concerning exporting agenda views in Org-mode."
2305 :tag "Org Agenda Export"
2306 :group 'org-agenda)
2308 (defcustom org-agenda-with-colors t
2309 "Non-nil means, use colors in agenda views."
2310 :group 'org-agenda-export
2311 :type 'boolean)
2313 (defcustom org-agenda-exporter-settings nil
2314 "Alist of variable/value pairs that should be active during agenda export.
2315 This is a good place to set uptions for ps-print and for htmlize."
2316 :group 'org-agenda-export
2317 :type '(repeat
2318 (list
2319 (variable)
2320 (sexp :tag "Value"))))
2322 (defcustom org-agenda-export-html-style ""
2323 "The style specification for exported HTML Agenda files.
2324 If this variable contains a string, it will replace the default <style>
2325 section as produced by `htmlize'.
2326 Since there are different ways of setting style information, this variable
2327 needs to contain the full HTML structure to provide a style, including the
2328 surrounding HTML tags. The style specifications should include definitions
2329 the fonts used by the agenda, here is an example:
2331 <style type=\"text/css\">
2332 p { font-weight: normal; color: gray; }
2333 .org-agenda-structure {
2334 font-size: 110%;
2335 color: #003399;
2336 font-weight: 600;
2338 .org-todo {
2339 color: #cc6666;Week-agenda:
2340 font-weight: bold;
2342 .org-done {
2343 color: #339933;
2345 .title { text-align: center; }
2346 .todo, .deadline { color: red; }
2347 .done { color: green; }
2348 </style>
2350 or, if you want to keep the style in a file,
2352 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2354 As the value of this option simply gets inserted into the HTML <head> header,
2355 you can \"misuse\" it to also add other text to the header. However,
2356 <style>...</style> is required, if not present the variable will be ignored."
2357 :group 'org-agenda-export
2358 :group 'org-export-html
2359 :type 'string)
2361 (defgroup org-agenda-custom-commands nil
2362 "Options concerning agenda views in Org-mode."
2363 :tag "Org Agenda Custom Commands"
2364 :group 'org-agenda)
2366 (defcustom org-agenda-custom-commands nil
2367 "Custom commands for the agenda.
2368 These commands will be offered on the splash screen displayed by the
2369 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2371 (key desc type match options files)
2373 key The key (one or more characters as a string) to be associated
2374 with the command.
2375 desc A description of the commend, when omitted or nil, a default
2376 description is built using MATCH.
2377 type The command type, any of the following symbols:
2378 agenda The daily/weekly agenda.
2379 todo Entries with a specific TODO keyword, in all agenda files.
2380 search Entries containing search words entry or headline.
2381 tags Tags/Property/TODO match in all agenda files.
2382 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2383 todo-tree Sparse tree of specific TODO keyword in *current* file.
2384 tags-tree Sparse tree with all tags matches in *current* file.
2385 occur-tree Occur sparse tree for *current* file.
2386 ... A user-defined function.
2387 match What to search for:
2388 - a single keyword for TODO keyword searches
2389 - a tags match expression for tags searches
2390 - a regular expression for occur searches
2391 options A list of option settings, similar to that in a let form, so like
2392 this: ((opt1 val1) (opt2 val2) ...)
2393 files A list of files file to write the produced agenda buffer to
2394 with the command `org-store-agenda-views'.
2395 If a file name ends in \".html\", an HTML version of the buffer
2396 is written out. If it ends in \".ps\", a postscript version is
2397 produced. Otherwide, only the plain text is written to the file.
2399 You can also define a set of commands, to create a composite agenda buffer.
2400 In this case, an entry looks like this:
2402 (key desc (cmd1 cmd2 ...) general-options file)
2404 where
2406 desc A description string to be displayed in the dispatcher menu.
2407 cmd An agenda command, similar to the above. However, tree commands
2408 are no allowed, but instead you can get agenda and global todo list.
2409 So valid commands for a set are:
2410 (agenda)
2411 (alltodo)
2412 (stuck)
2413 (todo \"match\" options files)
2414 (search \"match\" options files)
2415 (tags \"match\" options files)
2416 (tags-todo \"match\" options files)
2418 Each command can carry a list of options, and another set of options can be
2419 given for the whole set of commands. Individual command options take
2420 precedence over the general options.
2422 When using several characters as key to a command, the first characters
2423 are prefix commands. For the dispatcher to display useful information, you
2424 should provide a description for the prefix, like
2426 (setq org-agenda-custom-commands
2427 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2428 (\"hl\" tags \"+HOME+Lisa\")
2429 (\"hp\" tags \"+HOME+Peter\")
2430 (\"hk\" tags \"+HOME+Kim\")))"
2431 :group 'org-agenda-custom-commands
2432 :type '(repeat
2433 (choice :value ("a" "" tags "" nil)
2434 (list :tag "Single command"
2435 (string :tag "Access Key(s) ")
2436 (option (string :tag "Description"))
2437 (choice
2438 (const :tag "Agenda" agenda)
2439 (const :tag "TODO list" alltodo)
2440 (const :tag "Search words" search)
2441 (const :tag "Stuck projects" stuck)
2442 (const :tag "Tags search (all agenda files)" tags)
2443 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2444 (const :tag "TODO keyword search (all agenda files)" todo)
2445 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2446 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2447 (const :tag "Occur tree (current buffer)" occur-tree)
2448 (sexp :tag "Other, user-defined function"))
2449 (string :tag "Match")
2450 (repeat :tag "Local options"
2451 (list (variable :tag "Option") (sexp :tag "Value")))
2452 (option (repeat :tag "Export" (file :tag "Export to"))))
2453 (list :tag "Command series, all agenda files"
2454 (string :tag "Access Key(s)")
2455 (string :tag "Description ")
2456 (repeat
2457 (choice
2458 (const :tag "Agenda" (agenda))
2459 (const :tag "TODO list" (alltodo))
2460 (list :tag "Search words"
2461 (const :format "" search)
2462 (string :tag "Match")
2463 (repeat :tag "Local options"
2464 (list (variable :tag "Option")
2465 (sexp :tag "Value"))))
2466 (const :tag "Stuck projects" (stuck))
2467 (list :tag "Tags search"
2468 (const :format "" tags)
2469 (string :tag "Match")
2470 (repeat :tag "Local options"
2471 (list (variable :tag "Option")
2472 (sexp :tag "Value"))))
2474 (list :tag "Tags search, TODO entries only"
2475 (const :format "" tags-todo)
2476 (string :tag "Match")
2477 (repeat :tag "Local options"
2478 (list (variable :tag "Option")
2479 (sexp :tag "Value"))))
2481 (list :tag "TODO keyword search"
2482 (const :format "" todo)
2483 (string :tag "Match")
2484 (repeat :tag "Local options"
2485 (list (variable :tag "Option")
2486 (sexp :tag "Value"))))
2488 (list :tag "Other, user-defined function"
2489 (symbol :tag "function")
2490 (string :tag "Match")
2491 (repeat :tag "Local options"
2492 (list (variable :tag "Option")
2493 (sexp :tag "Value"))))))
2495 (repeat :tag "General options"
2496 (list (variable :tag "Option")
2497 (sexp :tag "Value")))
2498 (option (repeat :tag "Export" (file :tag "Export to"))))
2499 (cons :tag "Prefix key documentation"
2500 (string :tag "Access Key(s)")
2501 (string :tag "Description ")))))
2503 (defcustom org-agenda-query-register ?o
2504 "The register holding the current query string.
2505 The prupose of this is that if you construct a query string interactively,
2506 you can then use it to define a custom command."
2507 :group 'org-agenda-custom-commands
2508 :type 'character)
2510 (defcustom org-stuck-projects
2511 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2512 "How to identify stuck projects.
2513 This is a list of four items:
2514 1. A tags/todo matcher string that is used to identify a project.
2515 The entire tree below a headline matched by this is considered one project.
2516 2. A list of TODO keywords identifying non-stuck projects.
2517 If the project subtree contains any headline with one of these todo
2518 keywords, the project is considered to be not stuck. If you specify
2519 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2520 3. A list of tags identifying non-stuck projects.
2521 If the project subtree contains any headline with one of these tags,
2522 the project is considered to be not stuck. If you specify \"*\" as
2523 a tag, any tag will mark the project unstuck.
2524 4. An arbitrary regular expression matching non-stuck projects.
2526 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2527 or `C-c a #' to produce the list."
2528 :group 'org-agenda-custom-commands
2529 :type '(list
2530 (string :tag "Tags/TODO match to identify a project")
2531 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2532 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2533 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2536 (defgroup org-agenda-skip nil
2537 "Options concerning skipping parts of agenda files."
2538 :tag "Org Agenda Skip"
2539 :group 'org-agenda)
2541 (defcustom org-agenda-todo-list-sublevels t
2542 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2543 When nil, the sublevels of a TODO entry are not checked, resulting in
2544 potentially much shorter TODO lists."
2545 :group 'org-agenda-skip
2546 :group 'org-todo
2547 :type 'boolean)
2549 (defcustom org-agenda-todo-ignore-with-date nil
2550 "Non-nil means, don't show entries with a date in the global todo list.
2551 You can use this if you prefer to mark mere appointments with a TODO keyword,
2552 but don't want them to show up in the TODO list.
2553 When this is set, it also covers deadlines and scheduled items, the settings
2554 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2555 will be ignored."
2556 :group 'org-agenda-skip
2557 :group 'org-todo
2558 :type 'boolean)
2560 (defcustom org-agenda-todo-ignore-scheduled nil
2561 "Non-nil means, don't show scheduled entries in the global todo list.
2562 The idea behind this is that by scheduling it, you have already taken care
2563 of this item.
2564 See also `org-agenda-todo-ignore-with-date'."
2565 :group 'org-agenda-skip
2566 :group 'org-todo
2567 :type 'boolean)
2569 (defcustom org-agenda-todo-ignore-deadlines nil
2570 "Non-nil means, don't show near deadline entries in the global todo list.
2571 Near means closer than `org-deadline-warning-days' days.
2572 The idea behind this is that such items will appear in the agenda anyway.
2573 See also `org-agenda-todo-ignore-with-date'."
2574 :group 'org-agenda-skip
2575 :group 'org-todo
2576 :type 'boolean)
2578 (defcustom org-agenda-skip-scheduled-if-done nil
2579 "Non-nil means don't show scheduled items in agenda when they are done.
2580 This is relevant for the daily/weekly agenda, not for the TODO list. And
2581 it applies only to the actual date of the scheduling. Warnings about
2582 an item with a past scheduling dates are always turned off when the item
2583 is DONE."
2584 :group 'org-agenda-skip
2585 :type 'boolean)
2587 (defcustom org-agenda-skip-deadline-if-done nil
2588 "Non-nil means don't show deadines when the corresponding item is done.
2589 When nil, the deadline is still shown and should give you a happy feeling.
2590 This is relevant for the daily/weekly agenda. And it applied only to the
2591 actualy date of the deadline. Warnings about approching and past-due
2592 deadlines are always turned off when the item is DONE."
2593 :group 'org-agenda-skip
2594 :type 'boolean)
2596 (defcustom org-agenda-skip-timestamp-if-done nil
2597 "Non-nil means don't select item by timestamp or -range if it is DONE."
2598 :group 'org-agenda-skip
2599 :type 'boolean)
2601 (defcustom org-timeline-show-empty-dates 3
2602 "Non-nil means, `org-timeline' also shows dates without an entry.
2603 When nil, only the days which actually have entries are shown.
2604 When t, all days between the first and the last date are shown.
2605 When an integer, show also empty dates, but if there is a gap of more than
2606 N days, just insert a special line indicating the size of the gap."
2607 :group 'org-agenda-skip
2608 :type '(choice
2609 (const :tag "None" nil)
2610 (const :tag "All" t)
2611 (number :tag "at most")))
2614 (defgroup org-agenda-startup nil
2615 "Options concerning initial settings in the Agenda in Org Mode."
2616 :tag "Org Agenda Startup"
2617 :group 'org-agenda)
2619 (defcustom org-finalize-agenda-hook nil
2620 "Hook run just before displaying an agenda buffer."
2621 :group 'org-agenda-startup
2622 :type 'hook)
2624 (defcustom org-agenda-mouse-1-follows-link nil
2625 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2626 A longer mouse click will still set point. Does not work on XEmacs.
2627 Needs to be set before org.el is loaded."
2628 :group 'org-agenda-startup
2629 :type 'boolean)
2631 (defcustom org-agenda-start-with-follow-mode nil
2632 "The initial value of follow-mode in a newly created agenda window."
2633 :group 'org-agenda-startup
2634 :type 'boolean)
2636 (defgroup org-agenda-windows nil
2637 "Options concerning the windows used by the Agenda in Org Mode."
2638 :tag "Org Agenda Windows"
2639 :group 'org-agenda)
2641 (defcustom org-agenda-window-setup 'reorganize-frame
2642 "How the agenda buffer should be displayed.
2643 Possible values for this option are:
2645 current-window Show agenda in the current window, keeping all other windows.
2646 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2647 other-window Use `switch-to-buffer-other-window' to display agenda.
2648 reorganize-frame Show only two windows on the current frame, the current
2649 window and the agenda.
2650 See also the variable `org-agenda-restore-windows-after-quit'."
2651 :group 'org-agenda-windows
2652 :type '(choice
2653 (const current-window)
2654 (const other-frame)
2655 (const other-window)
2656 (const reorganize-frame)))
2658 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2659 "The min and max height of the agenda window as a fraction of frame height.
2660 The value of the variable is a cons cell with two numbers between 0 and 1.
2661 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2662 :group 'org-agenda-windows
2663 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2665 (defcustom org-agenda-restore-windows-after-quit nil
2666 "Non-nil means, restore window configuration open exiting agenda.
2667 Before the window configuration is changed for displaying the agenda,
2668 the current status is recorded. When the agenda is exited with
2669 `q' or `x' and this option is set, the old state is restored. If
2670 `org-agenda-window-setup' is `other-frame', the value of this
2671 option will be ignored.."
2672 :group 'org-agenda-windows
2673 :type 'boolean)
2675 (defcustom org-indirect-buffer-display 'other-window
2676 "How should indirect tree buffers be displayed?
2677 This applies to indirect buffers created with the commands
2678 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2679 Valid values are:
2680 current-window Display in the current window
2681 other-window Just display in another window.
2682 dedicated-frame Create one new frame, and re-use it each time.
2683 new-frame Make a new frame each time. Note that in this case
2684 previously-made indirect buffers are kept, and you need to
2685 kill these buffers yourself."
2686 :group 'org-structure
2687 :group 'org-agenda-windows
2688 :type '(choice
2689 (const :tag "In current window" current-window)
2690 (const :tag "In current frame, other window" other-window)
2691 (const :tag "Each time a new frame" new-frame)
2692 (const :tag "One dedicated frame" dedicated-frame)))
2694 (defgroup org-agenda-daily/weekly nil
2695 "Options concerning the daily/weekly agenda."
2696 :tag "Org Agenda Daily/Weekly"
2697 :group 'org-agenda)
2699 (defcustom org-agenda-ndays 7
2700 "Number of days to include in overview display.
2701 Should be 1 or 7."
2702 :group 'org-agenda-daily/weekly
2703 :type 'number)
2705 (defcustom org-agenda-start-on-weekday 1
2706 "Non-nil means, start the overview always on the specified weekday.
2707 0 denotes Sunday, 1 denotes Monday etc.
2708 When nil, always start on the current day."
2709 :group 'org-agenda-daily/weekly
2710 :type '(choice (const :tag "Today" nil)
2711 (number :tag "Weekday No.")))
2713 (defcustom org-agenda-show-all-dates t
2714 "Non-nil means, `org-agenda' shows every day in the selected range.
2715 When nil, only the days which actually have entries are shown."
2716 :group 'org-agenda-daily/weekly
2717 :type 'boolean)
2719 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2720 "Format string for displaying dates in the agenda.
2721 Used by the daily/weekly agenda and by the timeline. This should be
2722 a format string understood by `format-time-string', or a function returning
2723 the formatted date as a string. The function must take a single argument,
2724 a calendar-style date list like (month day year)."
2725 :group 'org-agenda-daily/weekly
2726 :type '(choice
2727 (string :tag "Format string")
2728 (function :tag "Function")))
2730 (defun org-agenda-format-date-aligned (date)
2731 "Format a date string for display in the daily/weekly agenda, or timeline.
2732 This function makes sure that dates are aligned for easy reading."
2733 (format "%-9s %2d %s %4d"
2734 (calendar-day-name date)
2735 (extract-calendar-day date)
2736 (calendar-month-name (extract-calendar-month date))
2737 (extract-calendar-year date)))
2739 (defcustom org-agenda-include-diary nil
2740 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2741 :group 'org-agenda-daily/weekly
2742 :type 'boolean)
2744 (defcustom org-agenda-include-all-todo nil
2745 "Set means weekly/daily agenda will always contain all TODO entries.
2746 The TODO entries will be listed at the top of the agenda, before
2747 the entries for specific days."
2748 :group 'org-agenda-daily/weekly
2749 :type 'boolean)
2751 (defcustom org-agenda-repeating-timestamp-show-all t
2752 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2753 When nil, only one occurence is shown, either today or the
2754 nearest into the future."
2755 :group 'org-agenda-daily/weekly
2756 :type 'boolean)
2758 (defcustom org-deadline-warning-days 14
2759 "No. of days before expiration during which a deadline becomes active.
2760 This variable governs the display in sparse trees and in the agenda.
2761 When 0 or negative, it means use this number (the absolute value of it)
2762 even if a deadline has a different individual lead time specified."
2763 :group 'org-time
2764 :group 'org-agenda-daily/weekly
2765 :type 'number)
2767 (defcustom org-scheduled-past-days 10000
2768 "No. of days to continue listing scheduled items that are not marked DONE.
2769 When an item is scheduled on a date, it shows up in the agenda on this
2770 day and will be listed until it is marked done for the number of days
2771 given here."
2772 :group 'org-agenda-daily/weekly
2773 :type 'number)
2775 (defgroup org-agenda-time-grid nil
2776 "Options concerning the time grid in the Org-mode Agenda."
2777 :tag "Org Agenda Time Grid"
2778 :group 'org-agenda)
2780 (defcustom org-agenda-use-time-grid t
2781 "Non-nil means, show a time grid in the agenda schedule.
2782 A time grid is a set of lines for specific times (like every two hours between
2783 8:00 and 20:00). The items scheduled for a day at specific times are
2784 sorted in between these lines.
2785 For details about when the grid will be shown, and what it will look like, see
2786 the variable `org-agenda-time-grid'."
2787 :group 'org-agenda-time-grid
2788 :type 'boolean)
2790 (defcustom org-agenda-time-grid
2791 '((daily today require-timed)
2792 "----------------"
2793 (800 1000 1200 1400 1600 1800 2000))
2795 "The settings for time grid for agenda display.
2796 This is a list of three items. The first item is again a list. It contains
2797 symbols specifying conditions when the grid should be displayed:
2799 daily if the agenda shows a single day
2800 weekly if the agenda shows an entire week
2801 today show grid on current date, independent of daily/weekly display
2802 require-timed show grid only if at least one item has a time specification
2804 The second item is a string which will be places behing the grid time.
2806 The third item is a list of integers, indicating the times that should have
2807 a grid line."
2808 :group 'org-agenda-time-grid
2809 :type
2810 '(list
2811 (set :greedy t :tag "Grid Display Options"
2812 (const :tag "Show grid in single day agenda display" daily)
2813 (const :tag "Show grid in weekly agenda display" weekly)
2814 (const :tag "Always show grid for today" today)
2815 (const :tag "Show grid only if any timed entries are present"
2816 require-timed)
2817 (const :tag "Skip grid times already present in an entry"
2818 remove-match))
2819 (string :tag "Grid String")
2820 (repeat :tag "Grid Times" (integer :tag "Time"))))
2822 (defgroup org-agenda-sorting nil
2823 "Options concerning sorting in the Org-mode Agenda."
2824 :tag "Org Agenda Sorting"
2825 :group 'org-agenda)
2827 (defconst org-sorting-choice
2828 '(choice
2829 (const time-up) (const time-down)
2830 (const category-keep) (const category-up) (const category-down)
2831 (const tag-down) (const tag-up)
2832 (const priority-up) (const priority-down))
2833 "Sorting choices.")
2835 (defcustom org-agenda-sorting-strategy
2836 '((agenda time-up category-keep priority-down)
2837 (todo category-keep priority-down)
2838 (tags category-keep priority-down)
2839 (search category-keep))
2840 "Sorting structure for the agenda items of a single day.
2841 This is a list of symbols which will be used in sequence to determine
2842 if an entry should be listed before another entry. The following
2843 symbols are recognized:
2845 time-up Put entries with time-of-day indications first, early first
2846 time-down Put entries with time-of-day indications first, late first
2847 category-keep Keep the default order of categories, corresponding to the
2848 sequence in `org-agenda-files'.
2849 category-up Sort alphabetically by category, A-Z.
2850 category-down Sort alphabetically by category, Z-A.
2851 tag-up Sort alphabetically by last tag, A-Z.
2852 tag-down Sort alphabetically by last tag, Z-A.
2853 priority-up Sort numerically by priority, high priority last.
2854 priority-down Sort numerically by priority, high priority first.
2856 The different possibilities will be tried in sequence, and testing stops
2857 if one comparison returns a \"not-equal\". For example, the default
2858 '(time-up category-keep priority-down)
2859 means: Pull out all entries having a specified time of day and sort them,
2860 in order to make a time schedule for the current day the first thing in the
2861 agenda listing for the day. Of the entries without a time indication, keep
2862 the grouped in categories, don't sort the categories, but keep them in
2863 the sequence given in `org-agenda-files'. Within each category sort by
2864 priority.
2866 Leaving out `category-keep' would mean that items will be sorted across
2867 categories by priority.
2869 Instead of a single list, this can also be a set of list for specific
2870 contents, with a context symbol in the car of the list, any of
2871 `agenda', `todo', `tags' for the corresponding agenda views."
2872 :group 'org-agenda-sorting
2873 :type `(choice
2874 (repeat :tag "General" ,org-sorting-choice)
2875 (list :tag "Individually"
2876 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2877 (repeat ,org-sorting-choice))
2878 (cons (const :tag "Strategy for TODO lists" todo)
2879 (repeat ,org-sorting-choice))
2880 (cons (const :tag "Strategy for Tags matches" tags)
2881 (repeat ,org-sorting-choice)))))
2883 (defcustom org-sort-agenda-notime-is-late t
2884 "Non-nil means, items without time are considered late.
2885 This is only relevant for sorting. When t, items which have no explicit
2886 time like 15:30 will be considered as 99:01, i.e. later than any items which
2887 do have a time. When nil, the default time is before 0:00. You can use this
2888 option to decide if the schedule for today should come before or after timeless
2889 agenda entries."
2890 :group 'org-agenda-sorting
2891 :type 'boolean)
2893 (defgroup org-agenda-line-format nil
2894 "Options concerning the entry prefix in the Org-mode agenda display."
2895 :tag "Org Agenda Line Format"
2896 :group 'org-agenda)
2898 (defcustom org-agenda-prefix-format
2899 '((agenda . " %-12:c%?-12t% s")
2900 (timeline . " % s")
2901 (todo . " %-12:c")
2902 (tags . " %-12:c")
2903 (search . " %-12:c"))
2904 "Format specifications for the prefix of items in the agenda views.
2905 An alist with four entries, for the different agenda types. The keys to the
2906 sublists are `agenda', `timeline', `todo', and `tags'. The values
2907 are format strings.
2908 This format works similar to a printf format, with the following meaning:
2910 %c the category of the item, \"Diary\" for entries from the diary, or
2911 as given by the CATEGORY keyword or derived from the file name.
2912 %T the *last* tag of the item. Last because inherited tags come
2913 first in the list.
2914 %t the time-of-day specification if one applies to the entry, in the
2915 format HH:MM
2916 %s Scheduling/Deadline information, a short string
2918 All specifiers work basically like the standard `%s' of printf, but may
2919 contain two additional characters: A question mark just after the `%' and
2920 a whitespace/punctuation character just before the final letter.
2922 If the first character after `%' is a question mark, the entire field
2923 will only be included if the corresponding value applies to the
2924 current entry. This is useful for fields which should have fixed
2925 width when present, but zero width when absent. For example,
2926 \"%?-12t\" will result in a 12 character time field if a time of the
2927 day is specified, but will completely disappear in entries which do
2928 not contain a time.
2930 If there is punctuation or whitespace character just before the final
2931 format letter, this character will be appended to the field value if
2932 the value is not empty. For example, the format \"%-12:c\" leads to
2933 \"Diary: \" if the category is \"Diary\". If the category were be
2934 empty, no additional colon would be interted.
2936 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2937 - Indent the line with two space characters
2938 - Give the category in a 12 chars wide field, padded with whitespace on
2939 the right (because of `-'). Append a colon if there is a category
2940 (because of `:').
2941 - If there is a time-of-day, put it into a 12 chars wide field. If no
2942 time, don't put in an empty field, just skip it (because of '?').
2943 - Finally, put the scheduling information and append a whitespace.
2945 As another example, if you don't want the time-of-day of entries in
2946 the prefix, you could use:
2948 (setq org-agenda-prefix-format \" %-11:c% s\")
2950 See also the variables `org-agenda-remove-times-when-in-prefix' and
2951 `org-agenda-remove-tags'."
2952 :type '(choice
2953 (string :tag "General format")
2954 (list :greedy t :tag "View dependent"
2955 (cons (const agenda) (string :tag "Format"))
2956 (cons (const timeline) (string :tag "Format"))
2957 (cons (const todo) (string :tag "Format"))
2958 (cons (const tags) (string :tag "Format"))
2959 (cons (const search) (string :tag "Format"))))
2960 :group 'org-agenda-line-format)
2962 (defvar org-prefix-format-compiled nil
2963 "The compiled version of the most recently used prefix format.
2964 See the variable `org-agenda-prefix-format'.")
2966 (defcustom org-agenda-todo-keyword-format "%-1s"
2967 "Format for the TODO keyword in agenda lines.
2968 Set this to something like \"%-12s\" if you want all TODO keywords
2969 to occupy a fixed space in the agenda display."
2970 :group 'org-agenda-line-format
2971 :type 'string)
2973 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2974 "Text preceeding scheduled items in the agenda view.
2975 This is a list with two strings. The first applies when the item is
2976 scheduled on the current day. The second applies when it has been scheduled
2977 previously, it may contain a %d to capture how many days ago the item was
2978 scheduled."
2979 :group 'org-agenda-line-format
2980 :type '(list
2981 (string :tag "Scheduled today ")
2982 (string :tag "Scheduled previously")))
2984 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2985 "Text preceeding deadline items in the agenda view.
2986 This is a list with two strings. The first applies when the item has its
2987 deadline on the current day. The second applies when it is in the past or
2988 in the future, it may contain %d to capture how many days away the deadline
2989 is (was)."
2990 :group 'org-agenda-line-format
2991 :type '(list
2992 (string :tag "Deadline today ")
2993 (string :tag "Deadline relative")))
2995 (defcustom org-agenda-remove-times-when-in-prefix t
2996 "Non-nil means, remove duplicate time specifications in agenda items.
2997 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2998 time-of-day specification in a headline or diary entry is extracted and
2999 placed into the prefix. If this option is non-nil, the original specification
3000 \(a timestamp or -range, or just a plain time(range) specification like
3001 11:30-4pm) will be removed for agenda display. This makes the agenda less
3002 cluttered.
3003 The option can be t or nil. It may also be the symbol `beg', indicating
3004 that the time should only be removed what it is located at the beginning of
3005 the headline/diary entry."
3006 :group 'org-agenda-line-format
3007 :type '(choice
3008 (const :tag "Always" t)
3009 (const :tag "Never" nil)
3010 (const :tag "When at beginning of entry" beg)))
3013 (defcustom org-agenda-default-appointment-duration nil
3014 "Default duration for appointments that only have a starting time.
3015 When nil, no duration is specified in such cases.
3016 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3017 :group 'org-agenda-line-format
3018 :type '(choice
3019 (integer :tag "Minutes")
3020 (const :tag "No default duration")))
3023 (defcustom org-agenda-remove-tags nil
3024 "Non-nil means, remove the tags from the headline copy in the agenda.
3025 When this is the symbol `prefix', only remove tags when
3026 `org-agenda-prefix-format' contains a `%T' specifier."
3027 :group 'org-agenda-line-format
3028 :type '(choice
3029 (const :tag "Always" t)
3030 (const :tag "Never" nil)
3031 (const :tag "When prefix format contains %T" prefix)))
3033 (if (fboundp 'defvaralias)
3034 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3035 'org-agenda-remove-tags))
3037 (defcustom org-agenda-tags-column -80
3038 "Shift tags in agenda items to this column.
3039 If this number is positive, it specifies the column. If it is negative,
3040 it means that the tags should be flushright to that column. For example,
3041 -80 works well for a normal 80 character screen."
3042 :group 'org-agenda-line-format
3043 :type 'integer)
3045 (if (fboundp 'defvaralias)
3046 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3048 (defcustom org-agenda-fontify-priorities t
3049 "Non-nil means, highlight low and high priorities in agenda.
3050 When t, the highest priority entries are bold, lowest priority italic.
3051 This may also be an association list of priority faces. The face may be
3052 a names face, or a list like `(:background \"Red\")'."
3053 :group 'org-agenda-line-format
3054 :type '(choice
3055 (const :tag "Never" nil)
3056 (const :tag "Defaults" t)
3057 (repeat :tag "Specify"
3058 (list (character :tag "Priority" :value ?A)
3059 (sexp :tag "face")))))
3061 (defgroup org-latex nil
3062 "Options for embedding LaTeX code into Org-mode"
3063 :tag "Org LaTeX"
3064 :group 'org)
3066 (defcustom org-format-latex-options
3067 '(:foreground default :background default :scale 1.0
3068 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3069 :matchers ("begin" "$" "$$" "\\(" "\\["))
3070 "Options for creating images from LaTeX fragments.
3071 This is a property list with the following properties:
3072 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3073 `default' means use the forground of the default face.
3074 :background the background color, or \"Transparent\".
3075 `default' means use the background of the default face.
3076 :scale a scaling factor for the size of the images
3077 :html-foreground, :html-background, :html-scale
3078 The same numbers for HTML export.
3079 :matchers a list indicating which matchers should be used to
3080 find LaTeX fragments. Valid members of this list are:
3081 \"begin\" find environments
3082 \"$\" find math expressions surrounded by $...$
3083 \"$$\" find math expressions surrounded by $$....$$
3084 \"\\(\" find math expressions surrounded by \\(...\\)
3085 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3086 :group 'org-latex
3087 :type 'plist)
3089 (defcustom org-format-latex-header "\\documentclass{article}
3090 \\usepackage{fullpage} % do not remove
3091 \\usepackage{amssymb}
3092 \\usepackage[usenames]{color}
3093 \\usepackage{amsmath}
3094 \\usepackage{latexsym}
3095 \\usepackage[mathscr]{eucal}
3096 \\pagestyle{empty} % do not remove"
3097 "The document header used for processing LaTeX fragments."
3098 :group 'org-latex
3099 :type 'string)
3101 (defgroup org-export nil
3102 "Options for exporting org-listings."
3103 :tag "Org Export"
3104 :group 'org)
3106 (defgroup org-export-general nil
3107 "General options for exporting Org-mode files."
3108 :tag "Org Export General"
3109 :group 'org-export)
3111 ;; FIXME
3112 (defvar org-export-publishing-directory nil)
3114 (defcustom org-export-with-special-strings t
3115 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3116 When this option is turned on, these strings will be exported as:
3118 Org HTML LaTeX
3119 -----+----------+--------
3120 \\- &shy; \\-
3121 -- &ndash; --
3122 --- &mdash; ---
3123 ... &hellip; \ldots
3125 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3126 :group 'org-export-translation
3127 :type 'boolean)
3129 (defcustom org-export-language-setup
3130 '(("en" "Author" "Date" "Table of Contents")
3131 ("cs" "Autor" "Datum" "Obsah")
3132 ("da" "Ophavsmand" "Dato" "Indhold")
3133 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3134 ("es" "Autor" "Fecha" "\xcdndice")
3135 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3136 ("it" "Autore" "Data" "Indice")
3137 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3138 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3139 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3140 "Terms used in export text, translated to different languages.
3141 Use the variable `org-export-default-language' to set the language,
3142 or use the +OPTION lines for a per-file setting."
3143 :group 'org-export-general
3144 :type '(repeat
3145 (list
3146 (string :tag "HTML language tag")
3147 (string :tag "Author")
3148 (string :tag "Date")
3149 (string :tag "Table of Contents"))))
3151 (defcustom org-export-default-language "en"
3152 "The default language of HTML export, as a string.
3153 This should have an association in `org-export-language-setup'."
3154 :group 'org-export-general
3155 :type 'string)
3157 (defcustom org-export-skip-text-before-1st-heading t
3158 "Non-nil means, skip all text before the first headline when exporting.
3159 When nil, that text is exported as well."
3160 :group 'org-export-general
3161 :type 'boolean)
3163 (defcustom org-export-headline-levels 3
3164 "The last level which is still exported as a headline.
3165 Inferior levels will produce itemize lists when exported.
3166 Note that a numeric prefix argument to an exporter function overrides
3167 this setting.
3169 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3170 :group 'org-export-general
3171 :type 'number)
3173 (defcustom org-export-with-section-numbers t
3174 "Non-nil means, add section numbers to headlines when exporting.
3176 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3177 :group 'org-export-general
3178 :type 'boolean)
3180 (defcustom org-export-with-toc t
3181 "Non-nil means, create a table of contents in exported files.
3182 The TOC contains headlines with levels up to`org-export-headline-levels'.
3183 When an integer, include levels up to N in the toc, this may then be
3184 different from `org-export-headline-levels', but it will not be allowed
3185 to be larger than the number of headline levels.
3186 When nil, no table of contents is made.
3188 Headlines which contain any TODO items will be marked with \"(*)\" in
3189 ASCII export, and with red color in HTML output, if the option
3190 `org-export-mark-todo-in-toc' is set.
3192 In HTML output, the TOC will be clickable.
3194 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3195 or \"toc:3\"."
3196 :group 'org-export-general
3197 :type '(choice
3198 (const :tag "No Table of Contents" nil)
3199 (const :tag "Full Table of Contents" t)
3200 (integer :tag "TOC to level")))
3202 (defcustom org-export-mark-todo-in-toc nil
3203 "Non-nil means, mark TOC lines that contain any open TODO items."
3204 :group 'org-export-general
3205 :type 'boolean)
3207 (defcustom org-export-preserve-breaks nil
3208 "Non-nil means, preserve all line breaks when exporting.
3209 Normally, in HTML output paragraphs will be reformatted. In ASCII
3210 export, line breaks will always be preserved, regardless of this variable.
3212 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3213 :group 'org-export-general
3214 :type 'boolean)
3216 (defcustom org-export-with-archived-trees 'headline
3217 "Whether subtrees with the ARCHIVE tag should be exported.
3218 This can have three different values
3219 nil Do not export, pretend this tree is not present
3220 t Do export the entire tree
3221 headline Only export the headline, but skip the tree below it."
3222 :group 'org-export-general
3223 :group 'org-archive
3224 :type '(choice
3225 (const :tag "not at all" nil)
3226 (const :tag "headline only" 'headline)
3227 (const :tag "entirely" t)))
3229 (defcustom org-export-author-info t
3230 "Non-nil means, insert author name and email into the exported file.
3232 This option can also be set with the +OPTIONS line,
3233 e.g. \"author-info:nil\"."
3234 :group 'org-export-general
3235 :type 'boolean)
3237 (defcustom org-export-time-stamp-file t
3238 "Non-nil means, insert a time stamp into the exported file.
3239 The time stamp shows when the file was created.
3241 This option can also be set with the +OPTIONS line,
3242 e.g. \"timestamp:nil\"."
3243 :group 'org-export-general
3244 :type 'boolean)
3246 (defcustom org-export-with-timestamps t
3247 "If nil, do not export time stamps and associated keywords."
3248 :group 'org-export-general
3249 :type 'boolean)
3251 (defcustom org-export-remove-timestamps-from-toc t
3252 "If nil, remove timestamps from the table of contents entries."
3253 :group 'org-export-general
3254 :type 'boolean)
3256 (defcustom org-export-with-tags 'not-in-toc
3257 "If nil, do not export tags, just remove them from headlines.
3258 If this is the symbol `not-in-toc', tags will be removed from table of
3259 contents entries, but still be shown in the headlines of the document.
3261 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3262 :group 'org-export-general
3263 :type '(choice
3264 (const :tag "Off" nil)
3265 (const :tag "Not in TOC" not-in-toc)
3266 (const :tag "On" t)))
3268 (defcustom org-export-with-drawers nil
3269 "Non-nil means, export with drawers like the property drawer.
3270 When t, all drawers are exported. This may also be a list of
3271 drawer names to export."
3272 :group 'org-export-general
3273 :type '(choice
3274 (const :tag "All drawers" t)
3275 (const :tag "None" nil)
3276 (repeat :tag "Selected drawers"
3277 (string :tag "Drawer name"))))
3279 (defgroup org-export-translation nil
3280 "Options for translating special ascii sequences for the export backends."
3281 :tag "Org Export Translation"
3282 :group 'org-export)
3284 (defcustom org-export-with-emphasize t
3285 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3286 If the export target supports emphasizing text, the word will be
3287 typeset in bold, italic, or underlined, respectively. Works only for
3288 single words, but you can say: I *really* *mean* *this*.
3289 Not all export backends support this.
3291 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3292 :group 'org-export-translation
3293 :type 'boolean)
3295 (defcustom org-export-with-footnotes t
3296 "If nil, export [1] as a footnote marker.
3297 Lines starting with [1] will be formatted as footnotes.
3299 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3300 :group 'org-export-translation
3301 :type 'boolean)
3303 (defcustom org-export-with-sub-superscripts t
3304 "Non-nil means, interpret \"_\" and \"^\" for export.
3305 When this option is turned on, you can use TeX-like syntax for sub- and
3306 superscripts. Several characters after \"_\" or \"^\" will be
3307 considered as a single item - so grouping with {} is normally not
3308 needed. For example, the following things will be parsed as single
3309 sub- or superscripts.
3311 10^24 or 10^tau several digits will be considered 1 item.
3312 10^-12 or 10^-tau a leading sign with digits or a word
3313 x^2-y^3 will be read as x^2 - y^3, because items are
3314 terminated by almost any nonword/nondigit char.
3315 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3317 Still, ambiguity is possible - so when in doubt use {} to enclose the
3318 sub/superscript. If you set this variable to the symbol `{}',
3319 the braces are *required* in order to trigger interpretations as
3320 sub/superscript. This can be helpful in documents that need \"_\"
3321 frequently in plain text.
3323 Not all export backends support this, but HTML does.
3325 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3326 :group 'org-export-translation
3327 :type '(choice
3328 (const :tag "Always interpret" t)
3329 (const :tag "Only with braces" {})
3330 (const :tag "Never interpret" nil)))
3332 (defcustom org-export-with-special-strings t
3333 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3334 When this option is turned on, these strings will be exported as:
3336 \\- : &shy;
3337 -- : &ndash;
3338 --- : &mdash;
3340 Not all export backends support this, but HTML does.
3342 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3343 :group 'org-export-translation
3344 :type 'boolean)
3346 (defcustom org-export-with-TeX-macros t
3347 "Non-nil means, interpret simple TeX-like macros when exporting.
3348 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3349 No only real TeX macros will work here, but the standard HTML entities
3350 for math can be used as macro names as well. For a list of supported
3351 names in HTML export, see the constant `org-html-entities'.
3352 Not all export backends support this.
3354 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3355 :group 'org-export-translation
3356 :group 'org-export-latex
3357 :type 'boolean)
3359 (defcustom org-export-with-LaTeX-fragments nil
3360 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3361 When set, the exporter will find LaTeX environments if the \\begin line is
3362 the first non-white thing on a line. It will also find the math delimiters
3363 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3364 display math.
3366 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3367 :group 'org-export-translation
3368 :group 'org-export-latex
3369 :type 'boolean)
3371 (defcustom org-export-with-fixed-width t
3372 "Non-nil means, lines starting with \":\" will be in fixed width font.
3373 This can be used to have pre-formatted text, fragments of code etc. For
3374 example:
3375 : ;; Some Lisp examples
3376 : (while (defc cnt)
3377 : (ding))
3378 will be looking just like this in also HTML. See also the QUOTE keyword.
3379 Not all export backends support this.
3381 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3382 :group 'org-export-translation
3383 :type 'boolean)
3385 (defcustom org-match-sexp-depth 3
3386 "Number of stacked braces for sub/superscript matching.
3387 This has to be set before loading org.el to be effective."
3388 :group 'org-export-translation
3389 :type 'integer)
3391 (defgroup org-export-tables nil
3392 "Options for exporting tables in Org-mode."
3393 :tag "Org Export Tables"
3394 :group 'org-export)
3396 (defcustom org-export-with-tables t
3397 "If non-nil, lines starting with \"|\" define a table.
3398 For example:
3400 | Name | Address | Birthday |
3401 |-------------+----------+-----------|
3402 | Arthur Dent | England | 29.2.2100 |
3404 Not all export backends support this.
3406 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3407 :group 'org-export-tables
3408 :type 'boolean)
3410 (defcustom org-export-highlight-first-table-line t
3411 "Non-nil means, highlight the first table line.
3412 In HTML export, this means use <th> instead of <td>.
3413 In tables created with table.el, this applies to the first table line.
3414 In Org-mode tables, all lines before the first horizontal separator
3415 line will be formatted with <th> tags."
3416 :group 'org-export-tables
3417 :type 'boolean)
3419 (defcustom org-export-table-remove-special-lines t
3420 "Remove special lines and marking characters in calculating tables.
3421 This removes the special marking character column from tables that are set
3422 up for spreadsheet calculations. It also removes the entire lines
3423 marked with `!', `_', or `^'. The lines with `$' are kept, because
3424 the values of constants may be useful to have."
3425 :group 'org-export-tables
3426 :type 'boolean)
3428 (defcustom org-export-prefer-native-exporter-for-tables nil
3429 "Non-nil means, always export tables created with table.el natively.
3430 Natively means, use the HTML code generator in table.el.
3431 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3432 the table does not use row- or column-spanning). This has the
3433 advantage, that the automatic HTML conversions for math symbols and
3434 sub/superscripts can be applied. Org-mode's HTML generator is also
3435 much faster."
3436 :group 'org-export-tables
3437 :type 'boolean)
3439 (defgroup org-export-ascii nil
3440 "Options specific for ASCII export of Org-mode files."
3441 :tag "Org Export ASCII"
3442 :group 'org-export)
3444 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3445 "Characters for underlining headings in ASCII export.
3446 In the given sequence, these characters will be used for level 1, 2, ..."
3447 :group 'org-export-ascii
3448 :type '(repeat character))
3450 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3451 "Bullet characters for headlines converted to lists in ASCII export.
3452 The first character is used for the first lest level generated in this
3453 way, and so on. If there are more levels than characters given here,
3454 the list will be repeated.
3455 Note that plain lists will keep the same bullets as the have in the
3456 Org-mode file."
3457 :group 'org-export-ascii
3458 :type '(repeat character))
3460 (defgroup org-export-xml nil
3461 "Options specific for XML export of Org-mode files."
3462 :tag "Org Export XML"
3463 :group 'org-export)
3465 (defgroup org-export-html nil
3466 "Options specific for HTML export of Org-mode files."
3467 :tag "Org Export HTML"
3468 :group 'org-export)
3470 (defcustom org-export-html-coding-system nil
3472 :group 'org-export-html
3473 :type 'coding-system)
3475 (defcustom org-export-html-extension "html"
3476 "The extension for exported HTML files."
3477 :group 'org-export-html
3478 :type 'string)
3480 (defcustom org-export-html-style
3481 "<style type=\"text/css\">
3482 html {
3483 font-family: Times, serif;
3484 font-size: 12pt;
3486 .title { text-align: center; }
3487 .todo { color: red; }
3488 .done { color: green; }
3489 .timestamp { color: grey }
3490 .timestamp-kwd { color: CadetBlue }
3491 .tag { background-color:lightblue; font-weight:normal }
3492 .target { background-color: lavender; }
3493 pre {
3494 border: 1pt solid #AEBDCC;
3495 background-color: #F3F5F7;
3496 padding: 5pt;
3497 font-family: courier, monospace;
3499 table { border-collapse: collapse; }
3500 td, th {
3501 vertical-align: top;
3502 <!--border: 1pt solid #ADB9CC;-->
3504 </style>"
3505 "The default style specification for exported HTML files.
3506 Since there are different ways of setting style information, this variable
3507 needs to contain the full HTML structure to provide a style, including the
3508 surrounding HTML tags. The style specifications should include definitions
3509 for new classes todo, done, title, and deadline. For example, legal values
3510 would be:
3512 <style type=\"text/css\">
3513 p { font-weight: normal; color: gray; }
3514 h1 { color: black; }
3515 .title { text-align: center; }
3516 .todo, .deadline { color: red; }
3517 .done { color: green; }
3518 </style>
3520 or, if you want to keep the style in a file,
3522 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3524 As the value of this option simply gets inserted into the HTML <head> header,
3525 you can \"misuse\" it to add arbitrary text to the header."
3526 :group 'org-export-html
3527 :type 'string)
3530 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3531 "Format for typesetting the document title in HTML export."
3532 :group 'org-export-html
3533 :type 'string)
3535 (defcustom org-export-html-toplevel-hlevel 2
3536 "The <H> level for level 1 headings in HTML export."
3537 :group 'org-export-html
3538 :type 'string)
3540 (defcustom org-export-html-link-org-files-as-html t
3541 "Non-nil means, make file links to `file.org' point to `file.html'.
3542 When org-mode is exporting an org-mode file to HTML, links to
3543 non-html files are directly put into a href tag in HTML.
3544 However, links to other Org-mode files (recognized by the
3545 extension `.org.) should become links to the corresponding html
3546 file, assuming that the linked org-mode file will also be
3547 converted to HTML.
3548 When nil, the links still point to the plain `.org' file."
3549 :group 'org-export-html
3550 :type 'boolean)
3552 (defcustom org-export-html-inline-images 'maybe
3553 "Non-nil means, inline images into exported HTML pages.
3554 This is done using an <img> tag. When nil, an anchor with href is used to
3555 link to the image. If this option is `maybe', then images in links with
3556 an empty description will be inlined, while images with a description will
3557 be linked only."
3558 :group 'org-export-html
3559 :type '(choice (const :tag "Never" nil)
3560 (const :tag "Always" t)
3561 (const :tag "When there is no description" maybe)))
3563 ;; FIXME: rename
3564 (defcustom org-export-html-expand t
3565 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3566 When nil, these tags will be exported as plain text and therefore
3567 not be interpreted by a browser.
3569 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3570 :group 'org-export-html
3571 :type 'boolean)
3573 (defcustom org-export-html-table-tag
3574 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3575 "The HTML tag that is used to start a table.
3576 This must be a <table> tag, but you may change the options like
3577 borders and spacing."
3578 :group 'org-export-html
3579 :type 'string)
3581 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3582 "The opening tag for table header fields.
3583 This is customizable so that alignment options can be specified."
3584 :group 'org-export-tables
3585 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3587 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3588 "The opening tag for table data fields.
3589 This is customizable so that alignment options can be specified."
3590 :group 'org-export-tables
3591 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3593 (defcustom org-export-html-with-timestamp nil
3594 "If non-nil, write `org-export-html-html-helper-timestamp'
3595 into the exported HTML text. Otherwise, the buffer will just be saved
3596 to a file."
3597 :group 'org-export-html
3598 :type 'boolean)
3600 (defcustom org-export-html-html-helper-timestamp
3601 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3602 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3603 :group 'org-export-html
3604 :type 'string)
3606 (defgroup org-export-icalendar nil
3607 "Options specific for iCalendar export of Org-mode files."
3608 :tag "Org Export iCalendar"
3609 :group 'org-export)
3611 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3612 "The file name for the iCalendar file covering all agenda files.
3613 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3614 The file name should be absolute, the file will be overwritten without warning."
3615 :group 'org-export-icalendar
3616 :type 'file)
3618 (defcustom org-icalendar-include-todo nil
3619 "Non-nil means, export to iCalendar files should also cover TODO items."
3620 :group 'org-export-icalendar
3621 :type '(choice
3622 (const :tag "None" nil)
3623 (const :tag "Unfinished" t)
3624 (const :tag "All" all)))
3626 (defcustom org-icalendar-include-sexps t
3627 "Non-nil means, export to iCalendar files should also cover sexp entries.
3628 These are entries like in the diary, but directly in an Org-mode file."
3629 :group 'org-export-icalendar
3630 :type 'boolean)
3632 (defcustom org-icalendar-include-body 100
3633 "Amount of text below headline to be included in iCalendar export.
3634 This is a number of characters that should maximally be included.
3635 Properties, scheduling and clocking lines will always be removed.
3636 The text will be inserted into the DESCRIPTION field."
3637 :group 'org-export-icalendar
3638 :type '(choice
3639 (const :tag "Nothing" nil)
3640 (const :tag "Everything" t)
3641 (integer :tag "Max characters")))
3643 (defcustom org-icalendar-combined-name "OrgMode"
3644 "Calendar name for the combined iCalendar representing all agenda files."
3645 :group 'org-export-icalendar
3646 :type 'string)
3648 (defgroup org-font-lock nil
3649 "Font-lock settings for highlighting in Org-mode."
3650 :tag "Org Font Lock"
3651 :group 'org)
3653 (defcustom org-level-color-stars-only nil
3654 "Non-nil means fontify only the stars in each headline.
3655 When nil, the entire headline is fontified.
3656 Changing it requires restart of `font-lock-mode' to become effective
3657 also in regions already fontified."
3658 :group 'org-font-lock
3659 :type 'boolean)
3661 (defcustom org-hide-leading-stars nil
3662 "Non-nil means, hide the first N-1 stars in a headline.
3663 This works by using the face `org-hide' for these stars. This
3664 face is white for a light background, and black for a dark
3665 background. You may have to customize the face `org-hide' to
3666 make this work.
3667 Changing it requires restart of `font-lock-mode' to become effective
3668 also in regions already fontified.
3669 You may also set this on a per-file basis by adding one of the following
3670 lines to the buffer:
3672 #+STARTUP: hidestars
3673 #+STARTUP: showstars"
3674 :group 'org-font-lock
3675 :type 'boolean)
3677 (defcustom org-fontify-done-headline nil
3678 "Non-nil means, change the face of a headline if it is marked DONE.
3679 Normally, only the TODO/DONE keyword indicates the state of a headline.
3680 When this is non-nil, the headline after the keyword is set to the
3681 `org-headline-done' as an additional indication."
3682 :group 'org-font-lock
3683 :type 'boolean)
3685 (defcustom org-fontify-emphasized-text t
3686 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3687 Changing this variable requires a restart of Emacs to take effect."
3688 :group 'org-font-lock
3689 :type 'boolean)
3691 (defcustom org-highlight-latex-fragments-and-specials nil
3692 "Non-nil means, fontify what is treated specially by the exporters."
3693 :group 'org-font-lock
3694 :type 'boolean)
3696 (defcustom org-hide-emphasis-markers nil
3697 "Non-nil mean font-lock should hide the emphasis marker characters."
3698 :group 'org-font-lock
3699 :type 'boolean)
3701 (defvar org-emph-re nil
3702 "Regular expression for matching emphasis.")
3703 (defvar org-verbatim-re nil
3704 "Regular expression for matching verbatim text.")
3705 (defvar org-emphasis-regexp-components) ; defined just below
3706 (defvar org-emphasis-alist) ; defined just below
3707 (defun org-set-emph-re (var val)
3708 "Set variable and compute the emphasis regular expression."
3709 (set var val)
3710 (when (and (boundp 'org-emphasis-alist)
3711 (boundp 'org-emphasis-regexp-components)
3712 org-emphasis-alist org-emphasis-regexp-components)
3713 (let* ((e org-emphasis-regexp-components)
3714 (pre (car e))
3715 (post (nth 1 e))
3716 (border (nth 2 e))
3717 (body (nth 3 e))
3718 (nl (nth 4 e))
3719 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3720 (body1 (concat body "*?"))
3721 (markers (mapconcat 'car org-emphasis-alist ""))
3722 (vmarkers (mapconcat
3723 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3724 org-emphasis-alist "")))
3725 ;; make sure special characters appear at the right position in the class
3726 (if (string-match "\\^" markers)
3727 (setq markers (concat (replace-match "" t t markers) "^")))
3728 (if (string-match "-" markers)
3729 (setq markers (concat (replace-match "" t t markers) "-")))
3730 (if (string-match "\\^" vmarkers)
3731 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3732 (if (string-match "-" vmarkers)
3733 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3734 (if (> nl 0)
3735 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3736 (int-to-string nl) "\\}")))
3737 ;; Make the regexp
3738 (setq org-emph-re
3739 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3740 "\\("
3741 "\\([" markers "]\\)"
3742 "\\("
3743 "[^" border "]\\|"
3744 "[^" border (if (and nil stacked) markers) "]"
3745 body1
3746 "[^" border (if (and nil stacked) markers) "]"
3747 "\\)"
3748 "\\3\\)"
3749 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3750 (setq org-verbatim-re
3751 (concat "\\([" pre "]\\|^\\)"
3752 "\\("
3753 "\\([" vmarkers "]\\)"
3754 "\\("
3755 "[^" border "]\\|"
3756 "[^" border "]"
3757 body1
3758 "[^" border "]"
3759 "\\)"
3760 "\\3\\)"
3761 "\\([" post "]\\|$\\)")))))
3763 (defcustom org-emphasis-regexp-components
3764 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3765 "Components used to build the regular expression for emphasis.
3766 This is a list with 6 entries. Terminology: In an emphasis string
3767 like \" *strong word* \", we call the initial space PREMATCH, the final
3768 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3769 and \"trong wor\" is the body. The different components in this variable
3770 specify what is allowed/forbidden in each part:
3772 pre Chars allowed as prematch. Beginning of line will be allowed too.
3773 post Chars allowed as postmatch. End of line will be allowed too.
3774 border The chars *forbidden* as border characters.
3775 body-regexp A regexp like \".\" to match a body character. Don't use
3776 non-shy groups here, and don't allow newline here.
3777 newline The maximum number of newlines allowed in an emphasis exp.
3779 Use customize to modify this, or restart Emacs after changing it."
3780 :group 'org-font-lock
3781 :set 'org-set-emph-re
3782 :type '(list
3783 (sexp :tag "Allowed chars in pre ")
3784 (sexp :tag "Allowed chars in post ")
3785 (sexp :tag "Forbidden chars in border ")
3786 (sexp :tag "Regexp for body ")
3787 (integer :tag "number of newlines allowed")
3788 (option (boolean :tag "Stacking (DISABLED) "))))
3790 (defcustom org-emphasis-alist
3791 '(("*" bold "<b>" "</b>")
3792 ("/" italic "<i>" "</i>")
3793 ("_" underline "<u>" "</u>")
3794 ("=" org-code "<code>" "</code>" verbatim)
3795 ("~" org-verbatim "" "" verbatim)
3796 ("+" (:strike-through t) "<del>" "</del>")
3798 "Special syntax for emphasized text.
3799 Text starting and ending with a special character will be emphasized, for
3800 example *bold*, _underlined_ and /italic/. This variable sets the marker
3801 characters, the face to be used by font-lock for highlighting in Org-mode
3802 Emacs buffers, and the HTML tags to be used for this.
3803 Use customize to modify this, or restart Emacs after changing it."
3804 :group 'org-font-lock
3805 :set 'org-set-emph-re
3806 :type '(repeat
3807 (list
3808 (string :tag "Marker character")
3809 (choice
3810 (face :tag "Font-lock-face")
3811 (plist :tag "Face property list"))
3812 (string :tag "HTML start tag")
3813 (string :tag "HTML end tag")
3814 (option (const verbatim)))))
3816 ;;; The faces
3818 (defgroup org-faces nil
3819 "Faces in Org-mode."
3820 :tag "Org Faces"
3821 :group 'org-font-lock)
3823 (defun org-compatible-face (inherits specs)
3824 "Make a compatible face specification.
3825 If INHERITS is an existing face and if the Emacs version supports it,
3826 just inherit the face. If not, use SPECS to define the face.
3827 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3828 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3829 to the top of the list. The `min-colors' attribute will be removed from
3830 any other entries, and any resulting duplicates will be removed entirely."
3831 (cond
3832 ((and inherits (facep inherits)
3833 (not (featurep 'xemacs)) (> emacs-major-version 22))
3834 ;; In Emacs 23, we use inheritance where possible.
3835 ;; We only do this in Emacs 23, because only there the outline
3836 ;; faces have been changed to the original org-mode-level-faces.
3837 (list (list t :inherit inherits)))
3838 ((or (featurep 'xemacs) (< emacs-major-version 22))
3839 ;; These do not understand the `min-colors' attribute.
3840 (let (r e a)
3841 (while (setq e (pop specs))
3842 (cond
3843 ((memq (car e) '(t default)) (push e r))
3844 ((setq a (member '(min-colors 8) (car e)))
3845 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3846 (cdr e)))))
3847 ((setq a (assq 'min-colors (car e)))
3848 (setq e (cons (delq a (car e)) (cdr e)))
3849 (or (assoc (car e) r) (push e r)))
3850 (t (or (assoc (car e) r) (push e r)))))
3851 (nreverse r)))
3852 (t specs)))
3853 (put 'org-compatible-face 'lisp-indent-function 1)
3855 (defface org-hide
3856 '((((background light)) (:foreground "white"))
3857 (((background dark)) (:foreground "black")))
3858 "Face used to hide leading stars in headlines.
3859 The forground color of this face should be equal to the background
3860 color of the frame."
3861 :group 'org-faces)
3863 (defface org-level-1 ;; font-lock-function-name-face
3864 (org-compatible-face 'outline-1
3865 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3866 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3867 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3868 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3869 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3870 (t (:bold t))))
3871 "Face used for level 1 headlines."
3872 :group 'org-faces)
3874 (defface org-level-2 ;; font-lock-variable-name-face
3875 (org-compatible-face 'outline-2
3876 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3877 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3878 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3879 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3880 (t (:bold t))))
3881 "Face used for level 2 headlines."
3882 :group 'org-faces)
3884 (defface org-level-3 ;; font-lock-keyword-face
3885 (org-compatible-face 'outline-3
3886 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3887 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3888 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3889 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3890 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3891 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3892 (t (:bold t))))
3893 "Face used for level 3 headlines."
3894 :group 'org-faces)
3896 (defface org-level-4 ;; font-lock-comment-face
3897 (org-compatible-face 'outline-4
3898 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3899 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3900 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3901 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3902 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3903 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3904 (t (:bold t))))
3905 "Face used for level 4 headlines."
3906 :group 'org-faces)
3908 (defface org-level-5 ;; font-lock-type-face
3909 (org-compatible-face 'outline-5
3910 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3911 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3912 (((class color) (min-colors 8)) (:foreground "green"))))
3913 "Face used for level 5 headlines."
3914 :group 'org-faces)
3916 (defface org-level-6 ;; font-lock-constant-face
3917 (org-compatible-face 'outline-6
3918 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3919 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3920 (((class color) (min-colors 8)) (:foreground "magenta"))))
3921 "Face used for level 6 headlines."
3922 :group 'org-faces)
3924 (defface org-level-7 ;; font-lock-builtin-face
3925 (org-compatible-face 'outline-7
3926 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3927 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3928 (((class color) (min-colors 8)) (:foreground "blue"))))
3929 "Face used for level 7 headlines."
3930 :group 'org-faces)
3932 (defface org-level-8 ;; font-lock-string-face
3933 (org-compatible-face 'outline-8
3934 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3935 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3936 (((class color) (min-colors 8)) (:foreground "green"))))
3937 "Face used for level 8 headlines."
3938 :group 'org-faces)
3940 (defface org-special-keyword ;; font-lock-string-face
3941 (org-compatible-face nil
3942 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3943 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3944 (t (:italic t))))
3945 "Face used for special keywords."
3946 :group 'org-faces)
3948 (defface org-drawer ;; font-lock-function-name-face
3949 (org-compatible-face nil
3950 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3951 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3952 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3953 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3954 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3955 (t (:bold t))))
3956 "Face used for drawers."
3957 :group 'org-faces)
3959 (defface org-property-value nil
3960 "Face used for the value of a property."
3961 :group 'org-faces)
3963 (defface org-column
3964 (org-compatible-face nil
3965 '((((class color) (min-colors 16) (background light))
3966 (:background "grey90"))
3967 (((class color) (min-colors 16) (background dark))
3968 (:background "grey30"))
3969 (((class color) (min-colors 8))
3970 (:background "cyan" :foreground "black"))
3971 (t (:inverse-video t))))
3972 "Face for column display of entry properties."
3973 :group 'org-faces)
3975 (when (fboundp 'set-face-attribute)
3976 ;; Make sure that a fixed-width face is used when we have a column table.
3977 (set-face-attribute 'org-column nil
3978 :height (face-attribute 'default :height)
3979 :family (face-attribute 'default :family)))
3981 (defface org-warning
3982 (org-compatible-face 'font-lock-warning-face
3983 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3984 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3985 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3986 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3987 (t (:bold t))))
3988 "Face for deadlines and TODO keywords."
3989 :group 'org-faces)
3991 (defface org-archived ; similar to shadow
3992 (org-compatible-face 'shadow
3993 '((((class color grayscale) (min-colors 88) (background light))
3994 (:foreground "grey50"))
3995 (((class color grayscale) (min-colors 88) (background dark))
3996 (:foreground "grey70"))
3997 (((class color) (min-colors 8) (background light))
3998 (:foreground "green"))
3999 (((class color) (min-colors 8) (background dark))
4000 (:foreground "yellow"))))
4001 "Face for headline with the ARCHIVE tag."
4002 :group 'org-faces)
4004 (defface org-link
4005 '((((class color) (background light)) (:foreground "Purple" :underline t))
4006 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4007 (t (:underline t)))
4008 "Face for links."
4009 :group 'org-faces)
4011 (defface org-ellipsis
4012 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4013 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4014 (t (:strike-through t)))
4015 "Face for the ellipsis in folded text."
4016 :group 'org-faces)
4018 (defface org-target
4019 '((((class color) (background light)) (:underline t))
4020 (((class color) (background dark)) (:underline t))
4021 (t (:underline t)))
4022 "Face for links."
4023 :group 'org-faces)
4025 (defface org-date
4026 '((((class color) (background light)) (:foreground "Purple" :underline t))
4027 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4028 (t (:underline t)))
4029 "Face for links."
4030 :group 'org-faces)
4032 (defface org-sexp-date
4033 '((((class color) (background light)) (:foreground "Purple"))
4034 (((class color) (background dark)) (:foreground "Cyan"))
4035 (t (:underline t)))
4036 "Face for links."
4037 :group 'org-faces)
4039 (defface org-tag
4040 '((t (:bold t)))
4041 "Face for tags."
4042 :group 'org-faces)
4044 (defface org-todo ; font-lock-warning-face
4045 (org-compatible-face nil
4046 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4047 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4048 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4049 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4050 (t (:inverse-video t :bold t))))
4051 "Face for TODO keywords."
4052 :group 'org-faces)
4054 (defface org-done ;; font-lock-type-face
4055 (org-compatible-face nil
4056 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4057 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4058 (((class color) (min-colors 8)) (:foreground "green"))
4059 (t (:bold t))))
4060 "Face used for todo keywords that indicate DONE items."
4061 :group 'org-faces)
4063 (defface org-headline-done ;; font-lock-string-face
4064 (org-compatible-face nil
4065 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4066 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4067 (((class color) (min-colors 8) (background light)) (:bold nil))))
4068 "Face used to indicate that a headline is DONE.
4069 This face is only used if `org-fontify-done-headline' is set. If applies
4070 to the part of the headline after the DONE keyword."
4071 :group 'org-faces)
4073 (defcustom org-todo-keyword-faces nil
4074 "Faces for specific TODO keywords.
4075 This is a list of cons cells, with TODO keywords in the car
4076 and faces in the cdr. The face can be a symbol, or a property
4077 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4078 :group 'org-faces
4079 :group 'org-todo
4080 :type '(repeat
4081 (cons
4082 (string :tag "keyword")
4083 (sexp :tag "face"))))
4085 (defface org-table ;; font-lock-function-name-face
4086 (org-compatible-face nil
4087 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4088 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4089 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4090 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4091 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4092 (((class color) (min-colors 8) (background dark)))))
4093 "Face used for tables."
4094 :group 'org-faces)
4096 (defface org-formula
4097 (org-compatible-face nil
4098 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4099 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4100 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4101 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4102 (t (:bold t :italic t))))
4103 "Face for formulas."
4104 :group 'org-faces)
4106 (defface org-code
4107 (org-compatible-face nil
4108 '((((class color grayscale) (min-colors 88) (background light))
4109 (:foreground "grey50"))
4110 (((class color grayscale) (min-colors 88) (background dark))
4111 (:foreground "grey70"))
4112 (((class color) (min-colors 8) (background light))
4113 (:foreground "green"))
4114 (((class color) (min-colors 8) (background dark))
4115 (:foreground "yellow"))))
4116 "Face for fixed-with text like code snippets."
4117 :group 'org-faces
4118 :version "22.1")
4120 (defface org-verbatim
4121 (org-compatible-face nil
4122 '((((class color grayscale) (min-colors 88) (background light))
4123 (:foreground "grey50" :underline t))
4124 (((class color grayscale) (min-colors 88) (background dark))
4125 (:foreground "grey70" :underline t))
4126 (((class color) (min-colors 8) (background light))
4127 (:foreground "green" :underline t))
4128 (((class color) (min-colors 8) (background dark))
4129 (:foreground "yellow" :underline t))))
4130 "Face for fixed-with text like code snippets."
4131 :group 'org-faces
4132 :version "22.1")
4134 (defface org-agenda-structure ;; font-lock-function-name-face
4135 (org-compatible-face nil
4136 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4137 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4138 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4139 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4140 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4141 (t (:bold t))))
4142 "Face used in agenda for captions and dates."
4143 :group 'org-faces)
4145 (defface org-scheduled-today
4146 (org-compatible-face nil
4147 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4148 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4149 (((class color) (min-colors 8)) (:foreground "green"))
4150 (t (:bold t :italic t))))
4151 "Face for items scheduled for a certain day."
4152 :group 'org-faces)
4154 (defface org-scheduled-previously
4155 (org-compatible-face nil
4156 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4157 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4158 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4159 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4160 (t (:bold t))))
4161 "Face for items scheduled previously, and not yet done."
4162 :group 'org-faces)
4164 (defface org-upcoming-deadline
4165 (org-compatible-face nil
4166 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4167 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4168 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4169 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4170 (t (:bold t))))
4171 "Face for items scheduled previously, and not yet done."
4172 :group 'org-faces)
4174 (defcustom org-agenda-deadline-faces
4175 '((1.0 . org-warning)
4176 (0.5 . org-upcoming-deadline)
4177 (0.0 . default))
4178 "Faces for showing deadlines in the agenda.
4179 This is a list of cons cells. The cdr of each cell is a face to be used,
4180 and it can also just be like '(:foreground \"yellow\").
4181 Each car is a fraction of the head-warning time that must have passed for
4182 this the face in the cdr to be used for display. The numbers must be
4183 given in descending order. The head-warning time is normally taken
4184 from `org-deadline-warning-days', but can also be specified in the deadline
4185 timestamp itself, like this:
4187 DEADLINE: <2007-08-13 Mon -8d>
4189 You may use d for days, w for weeks, m for months and y for years. Months
4190 and years will only be treated in an approximate fashion (30.4 days for a
4191 month and 365.24 days for a year)."
4192 :group 'org-faces
4193 :group 'org-agenda-daily/weekly
4194 :type '(repeat
4195 (cons
4196 (number :tag "Fraction of head-warning time passed")
4197 (sexp :tag "Face"))))
4199 ;; FIXME: this is not a good face yet.
4200 (defface org-agenda-restriction-lock
4201 (org-compatible-face nil
4202 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4203 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4204 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4205 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4206 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4207 (t (:inverse-video t))))
4208 "Face for showing the agenda restriction lock."
4209 :group 'org-faces)
4211 (defface org-time-grid ;; font-lock-variable-name-face
4212 (org-compatible-face nil
4213 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4214 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4215 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4216 "Face used for time grids."
4217 :group 'org-faces)
4219 (defconst org-level-faces
4220 '(org-level-1 org-level-2 org-level-3 org-level-4
4221 org-level-5 org-level-6 org-level-7 org-level-8
4224 (defcustom org-n-level-faces (length org-level-faces)
4225 "The number of different faces to be used for headlines.
4226 Org-mode defines 8 different headline faces, so this can be at most 8.
4227 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4228 :type 'number
4229 :group 'org-faces)
4231 ;;; Functions and variables from ther packages
4232 ;; Declared here to avoid compiler warnings
4234 (eval-and-compile
4235 (unless (fboundp 'declare-function)
4236 (defmacro declare-function (fn file &optional arglist fileonly))))
4238 ;; XEmacs only
4239 (defvar outline-mode-menu-heading)
4240 (defvar outline-mode-menu-show)
4241 (defvar outline-mode-menu-hide)
4242 (defvar zmacs-regions) ; XEmacs regions
4244 ;; Emacs only
4245 (defvar mark-active)
4247 ;; Various packages
4248 ;; FIXME: get the argument lists for the UNKNOWN stuff
4249 (declare-function add-to-diary-list "diary-lib"
4250 (date string specifier &optional marker globcolor literal))
4251 (declare-function table--at-cell-p "table" (position &optional object at-column))
4252 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4253 (declare-function bbdb "ext:bbdb-com" (string elidep))
4254 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4255 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4256 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4257 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4258 (declare-function bbdb-record-name "ext:bbdb" (record))
4259 (declare-function bibtex-beginning-of-entry "bibtex" ())
4260 (declare-function bibtex-generate-autokey "bibtex" ())
4261 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4262 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4263 (defvar calc-embedded-close-formula)
4264 (defvar calc-embedded-open-formula)
4265 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4266 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4267 (declare-function calendar-check-holidays "holidays" (date))
4268 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4269 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4270 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4271 (declare-function calendar-forward-day "cal-move" (arg))
4272 (declare-function calendar-french-date-string "cal-french" (&optional date))
4273 (declare-function calendar-goto-date "cal-move" (date))
4274 (declare-function calendar-goto-today "cal-move" ())
4275 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4276 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4277 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4278 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4279 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4280 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4281 (defvar calendar-mode-map)
4282 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4283 (declare-function cdlatex-tab "ext:cdlatex" ())
4284 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4285 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4286 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4287 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4288 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4289 (defvar font-lock-unfontify-region-function)
4290 (declare-function gnus-article-show-summary "gnus-art" ())
4291 (declare-function gnus-summary-last-subject "gnus-sum" ())
4292 (defvar gnus-other-frame-object)
4293 (defvar gnus-group-name)
4294 (defvar gnus-article-current)
4295 (defvar Info-current-file)
4296 (defvar Info-current-node)
4297 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4298 (declare-function mh-find-path "mh-utils" ())
4299 (declare-function mh-get-header-field "mh-utils" (field))
4300 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4301 (declare-function mh-header-display "mh-show" ())
4302 (declare-function mh-index-previous-folder "mh-search" ())
4303 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4304 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4305 (declare-function mh-search-choose "mh-search" (&optional searcher))
4306 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4307 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4308 (declare-function mh-show-header-display "mh-show" t t)
4309 (declare-function mh-show-msg "mh-show" (msg))
4310 (declare-function mh-show-show "mh-show" t t)
4311 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4312 (defvar mh-progs)
4313 (defvar mh-current-folder)
4314 (defvar mh-show-folder-buffer)
4315 (defvar mh-index-folder)
4316 (defvar mh-searcher)
4317 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4318 (declare-function parse-time-string "parse-time" (string))
4319 (declare-function remember "remember" (&optional initial))
4320 (declare-function remember-buffer-desc "remember" ())
4321 (declare-function remember-finalize "remember" ())
4322 (defvar remember-save-after-remembering)
4323 (defvar remember-data-file)
4324 (defvar remember-register)
4325 (defvar remember-buffer)
4326 (defvar remember-handler-functions)
4327 (defvar remember-annotation-functions)
4328 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4329 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4330 (declare-function rmail-what-message "rmail" ())
4331 (defvar rmail-current-message)
4332 (defvar texmathp-why)
4333 (declare-function vm-beginning-of-message "ext:vm-page" ())
4334 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4335 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4336 (declare-function vm-isearch-narrow "ext:vm-search" ())
4337 (declare-function vm-isearch-update "ext:vm-search" ())
4338 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4339 (declare-function vm-su-message-id "ext:vm-summary" (m))
4340 (declare-function vm-su-subject "ext:vm-summary" (m))
4341 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4342 (defvar vm-message-pointer)
4343 (defvar vm-folder-directory)
4344 (defvar w3m-current-url)
4345 (defvar w3m-current-title)
4346 ;; backward compatibility to old version of wl
4347 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4348 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4349 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4350 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4351 (declare-function wl-summary-line-from "ext:wl-summary" ())
4352 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4353 (declare-function wl-summary-message-number "ext:wl-summary" ())
4354 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4355 (defvar wl-summary-buffer-elmo-folder)
4356 (defvar wl-summary-buffer-folder-name)
4357 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4359 (defvar org-latex-regexps)
4360 (defvar constants-unit-system)
4362 ;;; Variables for pre-computed regular expressions, all buffer local
4364 (defvar org-drawer-regexp nil
4365 "Matches first line of a hidden block.")
4366 (make-variable-buffer-local 'org-drawer-regexp)
4367 (defvar org-todo-regexp nil
4368 "Matches any of the TODO state keywords.")
4369 (make-variable-buffer-local 'org-todo-regexp)
4370 (defvar org-not-done-regexp nil
4371 "Matches any of the TODO state keywords except the last one.")
4372 (make-variable-buffer-local 'org-not-done-regexp)
4373 (defvar org-todo-line-regexp nil
4374 "Matches a headline and puts TODO state into group 2 if present.")
4375 (make-variable-buffer-local 'org-todo-line-regexp)
4376 (defvar org-complex-heading-regexp nil
4377 "Matches a headline and puts everything into groups:
4378 group 1: the stars
4379 group 2: The todo keyword, maybe
4380 group 3: Priority cookie
4381 group 4: True headline
4382 group 5: Tags")
4383 (make-variable-buffer-local 'org-complex-heading-regexp)
4384 (defvar org-todo-line-tags-regexp nil
4385 "Matches a headline and puts TODO state into group 2 if present.
4386 Also put tags into group 4 if tags are present.")
4387 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4388 (defvar org-nl-done-regexp nil
4389 "Matches newline followed by a headline with the DONE keyword.")
4390 (make-variable-buffer-local 'org-nl-done-regexp)
4391 (defvar org-looking-at-done-regexp nil
4392 "Matches the DONE keyword a point.")
4393 (make-variable-buffer-local 'org-looking-at-done-regexp)
4394 (defvar org-ds-keyword-length 12
4395 "Maximum length of the Deadline and SCHEDULED keywords.")
4396 (make-variable-buffer-local 'org-ds-keyword-length)
4397 (defvar org-deadline-regexp nil
4398 "Matches the DEADLINE keyword.")
4399 (make-variable-buffer-local 'org-deadline-regexp)
4400 (defvar org-deadline-time-regexp nil
4401 "Matches the DEADLINE keyword together with a time stamp.")
4402 (make-variable-buffer-local 'org-deadline-time-regexp)
4403 (defvar org-deadline-line-regexp nil
4404 "Matches the DEADLINE keyword and the rest of the line.")
4405 (make-variable-buffer-local 'org-deadline-line-regexp)
4406 (defvar org-scheduled-regexp nil
4407 "Matches the SCHEDULED keyword.")
4408 (make-variable-buffer-local 'org-scheduled-regexp)
4409 (defvar org-scheduled-time-regexp nil
4410 "Matches the SCHEDULED keyword together with a time stamp.")
4411 (make-variable-buffer-local 'org-scheduled-time-regexp)
4412 (defvar org-closed-time-regexp nil
4413 "Matches the CLOSED keyword together with a time stamp.")
4414 (make-variable-buffer-local 'org-closed-time-regexp)
4416 (defvar org-keyword-time-regexp nil
4417 "Matches any of the 4 keywords, together with the time stamp.")
4418 (make-variable-buffer-local 'org-keyword-time-regexp)
4419 (defvar org-keyword-time-not-clock-regexp nil
4420 "Matches any of the 3 keywords, together with the time stamp.")
4421 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4422 (defvar org-maybe-keyword-time-regexp nil
4423 "Matches a timestamp, possibly preceeded by a keyword.")
4424 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4425 (defvar org-planning-or-clock-line-re nil
4426 "Matches a line with planning or clock info.")
4427 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4429 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4430 rear-nonsticky t mouse-map t fontified t)
4431 "Properties to remove when a string without properties is wanted.")
4433 (defsubst org-match-string-no-properties (num &optional string)
4434 (if (featurep 'xemacs)
4435 (let ((s (match-string num string)))
4436 (remove-text-properties 0 (length s) org-rm-props s)
4438 (match-string-no-properties num string)))
4440 (defsubst org-no-properties (s)
4441 (if (fboundp 'set-text-properties)
4442 (set-text-properties 0 (length s) nil s)
4443 (remove-text-properties 0 (length s) org-rm-props s))
4446 (defsubst org-get-alist-option (option key)
4447 (cond ((eq key t) t)
4448 ((eq option t) t)
4449 ((assoc key option) (cdr (assoc key option)))
4450 (t (cdr (assq 'default option)))))
4452 (defsubst org-inhibit-invisibility ()
4453 "Modified `buffer-invisibility-spec' for Emacs 21.
4454 Some ops with invisible text do not work correctly on Emacs 21. For these
4455 we turn off invisibility temporarily. Use this in a `let' form."
4456 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4458 (defsubst org-set-local (var value)
4459 "Make VAR local in current buffer and set it to VALUE."
4460 (set (make-variable-buffer-local var) value))
4462 (defsubst org-mode-p ()
4463 "Check if the current buffer is in Org-mode."
4464 (eq major-mode 'org-mode))
4466 (defsubst org-last (list)
4467 "Return the last element of LIST."
4468 (car (last list)))
4470 (defun org-let (list &rest body)
4471 (eval (cons 'let (cons list body))))
4472 (put 'org-let 'lisp-indent-function 1)
4474 (defun org-let2 (list1 list2 &rest body)
4475 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4476 (put 'org-let2 'lisp-indent-function 2)
4477 (defconst org-startup-options
4478 '(("fold" org-startup-folded t)
4479 ("overview" org-startup-folded t)
4480 ("nofold" org-startup-folded nil)
4481 ("showall" org-startup-folded nil)
4482 ("content" org-startup-folded content)
4483 ("hidestars" org-hide-leading-stars t)
4484 ("showstars" org-hide-leading-stars nil)
4485 ("odd" org-odd-levels-only t)
4486 ("oddeven" org-odd-levels-only nil)
4487 ("align" org-startup-align-all-tables t)
4488 ("noalign" org-startup-align-all-tables nil)
4489 ("customtime" org-display-custom-times t)
4490 ("logdone" org-log-done time)
4491 ("lognotedone" org-log-done note)
4492 ("nologdone" org-log-done nil)
4493 ("lognoteclock-out" org-log-note-clock-out t)
4494 ("nolognoteclock-out" org-log-note-clock-out nil)
4495 ("logrepeat" org-log-repeat state)
4496 ("lognoterepeat" org-log-repeat note)
4497 ("nologrepeat" org-log-repeat nil)
4498 ("constcgs" constants-unit-system cgs)
4499 ("constSI" constants-unit-system SI))
4500 "Variable associated with STARTUP options for org-mode.
4501 Each element is a list of three items: The startup options as written
4502 in the #+STARTUP line, the corresponding variable, and the value to
4503 set this variable to if the option is found. An optional forth element PUSH
4504 means to push this value onto the list in the variable.")
4506 (defun org-set-regexps-and-options ()
4507 "Precompute regular expressions for current buffer."
4508 (when (org-mode-p)
4509 (org-set-local 'org-todo-kwd-alist nil)
4510 (org-set-local 'org-todo-key-alist nil)
4511 (org-set-local 'org-todo-key-trigger nil)
4512 (org-set-local 'org-todo-keywords-1 nil)
4513 (org-set-local 'org-done-keywords nil)
4514 (org-set-local 'org-todo-heads nil)
4515 (org-set-local 'org-todo-sets nil)
4516 (org-set-local 'org-todo-log-states nil)
4517 (let ((re (org-make-options-regexp
4518 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4519 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4520 "CONSTANTS" "PROPERTY" "DRAWERS")))
4521 (splitre "[ \t]+")
4522 kwds kws0 kwsa key log value cat arch tags const links hw dws
4523 tail sep kws1 prio props drawers)
4524 (save-excursion
4525 (save-restriction
4526 (widen)
4527 (goto-char (point-min))
4528 (while (re-search-forward re nil t)
4529 (setq key (match-string 1) value (org-match-string-no-properties 2))
4530 (cond
4531 ((equal key "CATEGORY")
4532 (if (string-match "[ \t]+$" value)
4533 (setq value (replace-match "" t t value)))
4534 (setq cat value))
4535 ((member key '("SEQ_TODO" "TODO"))
4536 (push (cons 'sequence (org-split-string value splitre)) kwds))
4537 ((equal key "TYP_TODO")
4538 (push (cons 'type (org-split-string value splitre)) kwds))
4539 ((equal key "TAGS")
4540 (setq tags (append tags (org-split-string value splitre))))
4541 ((equal key "COLUMNS")
4542 (org-set-local 'org-columns-default-format value))
4543 ((equal key "LINK")
4544 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4545 (push (cons (match-string 1 value)
4546 (org-trim (match-string 2 value)))
4547 links)))
4548 ((equal key "PRIORITIES")
4549 (setq prio (org-split-string value " +")))
4550 ((equal key "PROPERTY")
4551 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4552 (push (cons (match-string 1 value) (match-string 2 value))
4553 props)))
4554 ((equal key "DRAWERS")
4555 (setq drawers (org-split-string value splitre)))
4556 ((equal key "CONSTANTS")
4557 (setq const (append const (org-split-string value splitre))))
4558 ((equal key "STARTUP")
4559 (let ((opts (org-split-string value splitre))
4560 l var val)
4561 (while (setq l (pop opts))
4562 (when (setq l (assoc l org-startup-options))
4563 (setq var (nth 1 l) val (nth 2 l))
4564 (if (not (nth 3 l))
4565 (set (make-local-variable var) val)
4566 (if (not (listp (symbol-value var)))
4567 (set (make-local-variable var) nil))
4568 (set (make-local-variable var) (symbol-value var))
4569 (add-to-list var val))))))
4570 ((equal key "ARCHIVE")
4571 (string-match " *$" value)
4572 (setq arch (replace-match "" t t value))
4573 (remove-text-properties 0 (length arch)
4574 '(face t fontified t) arch)))
4576 (when cat
4577 (org-set-local 'org-category (intern cat))
4578 (push (cons "CATEGORY" cat) props))
4579 (when prio
4580 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4581 (setq prio (mapcar 'string-to-char prio))
4582 (org-set-local 'org-highest-priority (nth 0 prio))
4583 (org-set-local 'org-lowest-priority (nth 1 prio))
4584 (org-set-local 'org-default-priority (nth 2 prio)))
4585 (and props (org-set-local 'org-local-properties (nreverse props)))
4586 (and drawers (org-set-local 'org-drawers drawers))
4587 (and arch (org-set-local 'org-archive-location arch))
4588 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4589 ;; Process the TODO keywords
4590 (unless kwds
4591 ;; Use the global values as if they had been given locally.
4592 (setq kwds (default-value 'org-todo-keywords))
4593 (if (stringp (car kwds))
4594 (setq kwds (list (cons org-todo-interpretation
4595 (default-value 'org-todo-keywords)))))
4596 (setq kwds (reverse kwds)))
4597 (setq kwds (nreverse kwds))
4598 (let (inter kws kw)
4599 (while (setq kws (pop kwds))
4600 (setq inter (pop kws) sep (member "|" kws)
4601 kws0 (delete "|" (copy-sequence kws))
4602 kwsa nil
4603 kws1 (mapcar
4604 (lambda (x)
4605 ;; 1 2
4606 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4607 (progn
4608 (setq kw (match-string 1 x)
4609 key (and (match-end 2) (match-string 2 x))
4610 log (org-extract-log-state-settings x))
4611 (push (cons kw (and key (string-to-char key))) kwsa)
4612 (and log (push log org-todo-log-states))
4614 (error "Invalid TODO keyword %s" x)))
4615 kws0)
4616 kwsa (if kwsa (append '((:startgroup))
4617 (nreverse kwsa)
4618 '((:endgroup))))
4619 hw (car kws1)
4620 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4621 tail (list inter hw (car dws) (org-last dws)))
4622 (add-to-list 'org-todo-heads hw 'append)
4623 (push kws1 org-todo-sets)
4624 (setq org-done-keywords (append org-done-keywords dws nil))
4625 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4626 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4627 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4628 (setq org-todo-sets (nreverse org-todo-sets)
4629 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4630 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4631 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4632 ;; Process the constants
4633 (when const
4634 (let (e cst)
4635 (while (setq e (pop const))
4636 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4637 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4638 (setq org-table-formula-constants-local cst)))
4640 ;; Process the tags.
4641 (when tags
4642 (let (e tgs)
4643 (while (setq e (pop tags))
4644 (cond
4645 ((equal e "{") (push '(:startgroup) tgs))
4646 ((equal e "}") (push '(:endgroup) tgs))
4647 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4648 (push (cons (match-string 1 e)
4649 (string-to-char (match-string 2 e)))
4650 tgs))
4651 (t (push (list e) tgs))))
4652 (org-set-local 'org-tag-alist nil)
4653 (while (setq e (pop tgs))
4654 (or (and (stringp (car e))
4655 (assoc (car e) org-tag-alist))
4656 (push e org-tag-alist))))))
4658 ;; Compute the regular expressions and other local variables
4659 (if (not org-done-keywords)
4660 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4661 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4662 (length org-scheduled-string)))
4663 org-drawer-regexp
4664 (concat "^[ \t]*:\\("
4665 (mapconcat 'regexp-quote org-drawers "\\|")
4666 "\\):[ \t]*$")
4667 org-not-done-keywords
4668 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4669 org-todo-regexp
4670 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4671 "\\|") "\\)\\>")
4672 org-not-done-regexp
4673 (concat "\\<\\("
4674 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4675 "\\)\\>")
4676 org-todo-line-regexp
4677 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4678 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4679 "\\)\\>\\)?[ \t]*\\(.*\\)")
4680 org-complex-heading-regexp
4681 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4682 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4683 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4684 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4685 org-nl-done-regexp
4686 (concat "\n\\*+[ \t]+"
4687 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4688 "\\)" "\\>")
4689 org-todo-line-tags-regexp
4690 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4691 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4692 (org-re
4693 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4694 org-looking-at-done-regexp
4695 (concat "^" "\\(?:"
4696 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4697 "\\>")
4698 org-deadline-regexp (concat "\\<" org-deadline-string)
4699 org-deadline-time-regexp
4700 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4701 org-deadline-line-regexp
4702 (concat "\\<\\(" org-deadline-string "\\).*")
4703 org-scheduled-regexp
4704 (concat "\\<" org-scheduled-string)
4705 org-scheduled-time-regexp
4706 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4707 org-closed-time-regexp
4708 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4709 org-keyword-time-regexp
4710 (concat "\\<\\(" org-scheduled-string
4711 "\\|" org-deadline-string
4712 "\\|" org-closed-string
4713 "\\|" org-clock-string "\\)"
4714 " *[[<]\\([^]>]+\\)[]>]")
4715 org-keyword-time-not-clock-regexp
4716 (concat "\\<\\(" org-scheduled-string
4717 "\\|" org-deadline-string
4718 "\\|" org-closed-string
4719 "\\)"
4720 " *[[<]\\([^]>]+\\)[]>]")
4721 org-maybe-keyword-time-regexp
4722 (concat "\\(\\<\\(" org-scheduled-string
4723 "\\|" org-deadline-string
4724 "\\|" org-closed-string
4725 "\\|" org-clock-string "\\)\\)?"
4726 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4727 org-planning-or-clock-line-re
4728 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4729 "\\|" org-deadline-string
4730 "\\|" org-closed-string "\\|" org-clock-string
4731 "\\)\\>\\)")
4733 (org-compute-latex-and-specials-regexp)
4734 (org-set-font-lock-defaults)))
4736 (defun org-extract-log-state-settings (x)
4737 "Extract the log state setting from a TODO keyword string.
4738 This will extract info from a string like \"WAIT(w@/!)\"."
4739 (let (kw key log1 log2)
4740 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4741 (setq kw (match-string 1 x)
4742 key (and (match-end 2) (match-string 2 x))
4743 log1 (and (match-end 3) (match-string 3 x))
4744 log2 (and (match-end 4) (match-string 4 x)))
4745 (and (or log1 log2)
4746 (list kw
4747 (and log1 (if (equal log1 "!") 'time 'note))
4748 (and log2 (if (equal log2 "!") 'time 'note)))))))
4750 (defun org-remove-keyword-keys (list)
4751 "Remove a pair of parenthesis at the end of each string in LIST."
4752 (mapcar (lambda (x)
4753 (if (string-match "(.*)$" x)
4754 (substring x 0 (match-beginning 0))
4756 list))
4758 ;; FIXME: this could be done much better, using second characters etc.
4759 (defun org-assign-fast-keys (alist)
4760 "Assign fast keys to a keyword-key alist.
4761 Respect keys that are already there."
4762 (let (new e k c c1 c2 (char ?a))
4763 (while (setq e (pop alist))
4764 (cond
4765 ((equal e '(:startgroup)) (push e new))
4766 ((equal e '(:endgroup)) (push e new))
4768 (setq k (car e) c2 nil)
4769 (if (cdr e)
4770 (setq c (cdr e))
4771 ;; automatically assign a character.
4772 (setq c1 (string-to-char
4773 (downcase (substring
4774 k (if (= (string-to-char k) ?@) 1 0)))))
4775 (if (or (rassoc c1 new) (rassoc c1 alist))
4776 (while (or (rassoc char new) (rassoc char alist))
4777 (setq char (1+ char)))
4778 (setq c2 c1))
4779 (setq c (or c2 char)))
4780 (push (cons k c) new))))
4781 (nreverse new)))
4783 ;;; Some variables ujsed in various places
4785 (defvar org-window-configuration nil
4786 "Used in various places to store a window configuration.")
4787 (defvar org-finish-function nil
4788 "Function to be called when `C-c C-c' is used.
4789 This is for getting out of special buffers like remember.")
4792 ;; FIXME: Occasionally check by commenting these, to make sure
4793 ;; no other functions uses these, forgetting to let-bind them.
4794 (defvar entry)
4795 (defvar state)
4796 (defvar last-state)
4797 (defvar date)
4798 (defvar description)
4800 ;; Defined somewhere in this file, but used before definition.
4801 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4802 (defvar org-agenda-buffer-name)
4803 (defvar org-agenda-undo-list)
4804 (defvar org-agenda-pending-undo-list)
4805 (defvar org-agenda-overriding-header)
4806 (defvar orgtbl-mode)
4807 (defvar org-html-entities)
4808 (defvar org-struct-menu)
4809 (defvar org-org-menu)
4810 (defvar org-tbl-menu)
4811 (defvar org-agenda-keymap)
4813 ;;;; Emacs/XEmacs compatibility
4815 ;; Overlay compatibility functions
4816 (defun org-make-overlay (beg end &optional buffer)
4817 (if (featurep 'xemacs)
4818 (make-extent beg end buffer)
4819 (make-overlay beg end buffer)))
4820 (defun org-delete-overlay (ovl)
4821 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4822 (defun org-detach-overlay (ovl)
4823 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4824 (defun org-move-overlay (ovl beg end &optional buffer)
4825 (if (featurep 'xemacs)
4826 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4827 (move-overlay ovl beg end buffer)))
4828 (defun org-overlay-put (ovl prop value)
4829 (if (featurep 'xemacs)
4830 (set-extent-property ovl prop value)
4831 (overlay-put ovl prop value)))
4832 (defun org-overlay-display (ovl text &optional face evap)
4833 "Make overlay OVL display TEXT with face FACE."
4834 (if (featurep 'xemacs)
4835 (let ((gl (make-glyph text)))
4836 (and face (set-glyph-face gl face))
4837 (set-extent-property ovl 'invisible t)
4838 (set-extent-property ovl 'end-glyph gl))
4839 (overlay-put ovl 'display text)
4840 (if face (overlay-put ovl 'face face))
4841 (if evap (overlay-put ovl 'evaporate t))))
4842 (defun org-overlay-before-string (ovl text &optional face evap)
4843 "Make overlay OVL display TEXT with face FACE."
4844 (if (featurep 'xemacs)
4845 (let ((gl (make-glyph text)))
4846 (and face (set-glyph-face gl face))
4847 (set-extent-property ovl 'begin-glyph gl))
4848 (if face (org-add-props text nil 'face face))
4849 (overlay-put ovl 'before-string text)
4850 (if evap (overlay-put ovl 'evaporate t))))
4851 (defun org-overlay-get (ovl prop)
4852 (if (featurep 'xemacs)
4853 (extent-property ovl prop)
4854 (overlay-get ovl prop)))
4855 (defun org-overlays-at (pos)
4856 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4857 (defun org-overlays-in (&optional start end)
4858 (if (featurep 'xemacs)
4859 (extent-list nil start end)
4860 (overlays-in start end)))
4861 (defun org-overlay-start (o)
4862 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4863 (defun org-overlay-end (o)
4864 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4865 (defun org-find-overlays (prop &optional pos delete)
4866 "Find all overlays specifying PROP at POS or point.
4867 If DELETE is non-nil, delete all those overlays."
4868 (let ((overlays (org-overlays-at (or pos (point))))
4869 ov found)
4870 (while (setq ov (pop overlays))
4871 (if (org-overlay-get ov prop)
4872 (if delete (org-delete-overlay ov) (push ov found))))
4873 found))
4875 ;; Region compatibility
4877 (defun org-add-hook (hook function &optional append local)
4878 "Add-hook, compatible with both Emacsen."
4879 (if (and local (featurep 'xemacs))
4880 (add-local-hook hook function append)
4881 (add-hook hook function append local)))
4883 (defvar org-ignore-region nil
4884 "To temporarily disable the active region.")
4886 (defun org-region-active-p ()
4887 "Is `transient-mark-mode' on and the region active?
4888 Works on both Emacs and XEmacs."
4889 (if org-ignore-region
4891 (if (featurep 'xemacs)
4892 (and zmacs-regions (region-active-p))
4893 (if (fboundp 'use-region-p)
4894 (use-region-p)
4895 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4897 ;; Invisibility compatibility
4899 (defun org-add-to-invisibility-spec (arg)
4900 "Add elements to `buffer-invisibility-spec'.
4901 See documentation for `buffer-invisibility-spec' for the kind of elements
4902 that can be added."
4903 (cond
4904 ((fboundp 'add-to-invisibility-spec)
4905 (add-to-invisibility-spec arg))
4906 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4907 (setq buffer-invisibility-spec (list arg)))
4909 (setq buffer-invisibility-spec
4910 (cons arg buffer-invisibility-spec)))))
4912 (defun org-remove-from-invisibility-spec (arg)
4913 "Remove elements from `buffer-invisibility-spec'."
4914 (if (fboundp 'remove-from-invisibility-spec)
4915 (remove-from-invisibility-spec arg)
4916 (if (consp buffer-invisibility-spec)
4917 (setq buffer-invisibility-spec
4918 (delete arg buffer-invisibility-spec)))))
4920 (defun org-in-invisibility-spec-p (arg)
4921 "Is ARG a member of `buffer-invisibility-spec'?"
4922 (if (consp buffer-invisibility-spec)
4923 (member arg buffer-invisibility-spec)
4924 nil))
4926 ;;;; Define the Org-mode
4928 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4929 (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."))
4932 ;; We use a before-change function to check if a table might need
4933 ;; an update.
4934 (defvar org-table-may-need-update t
4935 "Indicates that a table might need an update.
4936 This variable is set by `org-before-change-function'.
4937 `org-table-align' sets it back to nil.")
4938 (defvar org-mode-map)
4939 (defvar org-mode-hook nil)
4940 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4941 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4942 (defvar org-table-buffer-is-an nil)
4943 (defconst org-outline-regexp "\\*+ ")
4945 ;;;###autoload
4946 (define-derived-mode org-mode outline-mode "Org"
4947 "Outline-based notes management and organizer, alias
4948 \"Carsten's outline-mode for keeping track of everything.\"
4950 Org-mode develops organizational tasks around a NOTES file which
4951 contains information about projects as plain text. Org-mode is
4952 implemented on top of outline-mode, which is ideal to keep the content
4953 of large files well structured. It supports ToDo items, deadlines and
4954 time stamps, which magically appear in the diary listing of the Emacs
4955 calendar. Tables are easily created with a built-in table editor.
4956 Plain text URL-like links connect to websites, emails (VM), Usenet
4957 messages (Gnus), BBDB entries, and any files related to the project.
4958 For printing and sharing of notes, an Org-mode file (or a part of it)
4959 can be exported as a structured ASCII or HTML file.
4961 The following commands are available:
4963 \\{org-mode-map}"
4965 ;; Get rid of Outline menus, they are not needed
4966 ;; Need to do this here because define-derived-mode sets up
4967 ;; the keymap so late. Still, it is a waste to call this each time
4968 ;; we switch another buffer into org-mode.
4969 (if (featurep 'xemacs)
4970 (when (boundp 'outline-mode-menu-heading)
4971 ;; Assume this is Greg's port, it used easymenu
4972 (easy-menu-remove outline-mode-menu-heading)
4973 (easy-menu-remove outline-mode-menu-show)
4974 (easy-menu-remove outline-mode-menu-hide))
4975 (define-key org-mode-map [menu-bar headings] 'undefined)
4976 (define-key org-mode-map [menu-bar hide] 'undefined)
4977 (define-key org-mode-map [menu-bar show] 'undefined))
4979 (easy-menu-add org-org-menu)
4980 (easy-menu-add org-tbl-menu)
4981 (org-install-agenda-files-menu)
4982 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4983 (org-add-to-invisibility-spec '(org-cwidth))
4984 (when (featurep 'xemacs)
4985 (org-set-local 'line-move-ignore-invisible t))
4986 (org-set-local 'outline-regexp org-outline-regexp)
4987 (org-set-local 'outline-level 'org-outline-level)
4988 (when (and org-ellipsis
4989 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4990 (fboundp 'make-glyph-code))
4991 (unless org-display-table
4992 (setq org-display-table (make-display-table)))
4993 (set-display-table-slot
4994 org-display-table 4
4995 (vconcat (mapcar
4996 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4997 org-ellipsis)))
4998 (if (stringp org-ellipsis) org-ellipsis "..."))))
4999 (setq buffer-display-table org-display-table))
5000 (org-set-regexps-and-options)
5001 ;; Calc embedded
5002 (org-set-local 'calc-embedded-open-mode "# ")
5003 (modify-syntax-entry ?# "<")
5004 (modify-syntax-entry ?@ "w")
5005 (if org-startup-truncated (setq truncate-lines t))
5006 (org-set-local 'font-lock-unfontify-region-function
5007 'org-unfontify-region)
5008 ;; Activate before-change-function
5009 (org-set-local 'org-table-may-need-update t)
5010 (org-add-hook 'before-change-functions 'org-before-change-function nil
5011 'local)
5012 ;; Check for running clock before killing a buffer
5013 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5014 ;; Paragraphs and auto-filling
5015 (org-set-autofill-regexps)
5016 (setq indent-line-function 'org-indent-line-function)
5017 (org-update-radio-target-regexp)
5019 ;; Comment characters
5020 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5021 (org-set-local 'comment-padding " ")
5023 ;; Align options lines
5024 (org-set-local
5025 'align-mode-rules-list
5026 '((org-in-buffer-settings
5027 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5028 (modes . '(org-mode)))))
5030 ;; Imenu
5031 (org-set-local 'imenu-create-index-function
5032 'org-imenu-get-tree)
5034 ;; Make isearch reveal context
5035 (if (or (featurep 'xemacs)
5036 (not (boundp 'outline-isearch-open-invisible-function)))
5037 ;; Emacs 21 and XEmacs make use of the hook
5038 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5039 ;; Emacs 22 deals with this through a special variable
5040 (org-set-local 'outline-isearch-open-invisible-function
5041 (lambda (&rest ignore) (org-show-context 'isearch))))
5043 ;; If empty file that did not turn on org-mode automatically, make it to.
5044 (if (and org-insert-mode-line-in-empty-file
5045 (interactive-p)
5046 (= (point-min) (point-max)))
5047 (insert "# -*- mode: org -*-\n\n"))
5049 (unless org-inhibit-startup
5050 (when org-startup-align-all-tables
5051 (let ((bmp (buffer-modified-p)))
5052 (org-table-map-tables 'org-table-align)
5053 (set-buffer-modified-p bmp)))
5054 (org-cycle-hide-drawers 'all)
5055 (cond
5056 ((eq org-startup-folded t)
5057 (org-cycle '(4)))
5058 ((eq org-startup-folded 'content)
5059 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5060 (org-cycle '(4)) (org-cycle '(4)))))))
5062 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5064 (defsubst org-call-with-arg (command arg)
5065 "Call COMMAND interactively, but pretend prefix are was ARG."
5066 (let ((current-prefix-arg arg)) (call-interactively command)))
5068 (defsubst org-current-line (&optional pos)
5069 (save-excursion
5070 (and pos (goto-char pos))
5071 ;; works also in narrowed buffer, because we start at 1, not point-min
5072 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5074 (defun org-current-time ()
5075 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5076 (if (> org-time-stamp-rounding-minutes 0)
5077 (let ((r org-time-stamp-rounding-minutes)
5078 (time (decode-time)))
5079 (apply 'encode-time
5080 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5081 (nthcdr 2 time))))
5082 (current-time)))
5084 (defun org-add-props (string plist &rest props)
5085 "Add text properties to entire string, from beginning to end.
5086 PLIST may be a list of properties, PROPS are individual properties and values
5087 that will be added to PLIST. Returns the string that was modified."
5088 (add-text-properties
5089 0 (length string) (if props (append plist props) plist) string)
5090 string)
5091 (put 'org-add-props 'lisp-indent-function 2)
5094 ;;;; Font-Lock stuff, including the activators
5096 (defvar org-mouse-map (make-sparse-keymap))
5097 (org-defkey org-mouse-map
5098 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5099 (org-defkey org-mouse-map
5100 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5101 (when org-mouse-1-follows-link
5102 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5103 (when org-tab-follows-link
5104 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5105 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5106 (when org-return-follows-link
5107 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5108 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5110 (require 'font-lock)
5112 (defconst org-non-link-chars "]\t\n\r<>")
5113 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5114 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5115 (defvar org-link-re-with-space nil
5116 "Matches a link with spaces, optional angular brackets around it.")
5117 (defvar org-link-re-with-space2 nil
5118 "Matches a link with spaces, optional angular brackets around it.")
5119 (defvar org-angle-link-re nil
5120 "Matches link with angular brackets, spaces are allowed.")
5121 (defvar org-plain-link-re nil
5122 "Matches plain link, without spaces.")
5123 (defvar org-bracket-link-regexp nil
5124 "Matches a link in double brackets.")
5125 (defvar org-bracket-link-analytic-regexp nil
5126 "Regular expression used to analyze links.
5127 Here is what the match groups contain after a match:
5128 1: http:
5129 2: http
5130 3: path
5131 4: [desc]
5132 5: desc")
5133 (defvar org-any-link-re nil
5134 "Regular expression matching any link.")
5136 (defun org-make-link-regexps ()
5137 "Update the link regular expressions.
5138 This should be called after the variable `org-link-types' has changed."
5139 (setq org-link-re-with-space
5140 (concat
5141 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5142 "\\([^" org-non-link-chars " ]"
5143 "[^" org-non-link-chars "]*"
5144 "[^" org-non-link-chars " ]\\)>?")
5145 org-link-re-with-space2
5146 (concat
5147 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5148 "\\([^" org-non-link-chars " ]"
5149 "[^]\t\n\r]*"
5150 "[^" org-non-link-chars " ]\\)>?")
5151 org-angle-link-re
5152 (concat
5153 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5154 "\\([^" org-non-link-chars " ]"
5155 "[^" org-non-link-chars "]*"
5156 "\\)>")
5157 org-plain-link-re
5158 (concat
5159 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5160 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5161 org-bracket-link-regexp
5162 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5163 org-bracket-link-analytic-regexp
5164 (concat
5165 "\\[\\["
5166 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5167 "\\([^]]+\\)"
5168 "\\]"
5169 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5170 "\\]")
5171 org-any-link-re
5172 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5173 org-angle-link-re "\\)\\|\\("
5174 org-plain-link-re "\\)")))
5176 (org-make-link-regexps)
5178 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5179 "Regular expression for fast time stamp matching.")
5180 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5181 "Regular expression for fast time stamp matching.")
5182 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5183 "Regular expression matching time strings for analysis.
5184 This one does not require the space after the date.")
5185 (defconst org-ts-regexp1 "\\(\\([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 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5188 "Regular expression matching time stamps, with groups.")
5189 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5190 "Regular expression matching time stamps (also [..]), with groups.")
5191 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5192 "Regular expression matching a time stamp range.")
5193 (defconst org-tr-regexp-both
5194 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5195 "Regular expression matching a time stamp range.")
5196 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5197 org-ts-regexp "\\)?")
5198 "Regular expression matching a time stamp or time stamp range.")
5199 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5200 org-ts-regexp-both "\\)?")
5201 "Regular expression matching a time stamp or time stamp range.
5202 The time stamps may be either active or inactive.")
5204 (defvar org-emph-face nil)
5206 (defun org-do-emphasis-faces (limit)
5207 "Run through the buffer and add overlays to links."
5208 (let (rtn)
5209 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5210 (if (not (= (char-after (match-beginning 3))
5211 (char-after (match-beginning 4))))
5212 (progn
5213 (setq rtn t)
5214 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5215 'face
5216 (nth 1 (assoc (match-string 3)
5217 org-emphasis-alist)))
5218 (add-text-properties (match-beginning 2) (match-end 2)
5219 '(font-lock-multiline t))
5220 (when org-hide-emphasis-markers
5221 (add-text-properties (match-end 4) (match-beginning 5)
5222 '(invisible org-link))
5223 (add-text-properties (match-beginning 3) (match-end 3)
5224 '(invisible org-link)))))
5225 (backward-char 1))
5226 rtn))
5228 (defun org-emphasize (&optional char)
5229 "Insert or change an emphasis, i.e. a font like bold or italic.
5230 If there is an active region, change that region to a new emphasis.
5231 If there is no region, just insert the marker characters and position
5232 the cursor between them.
5233 CHAR should be either the marker character, or the first character of the
5234 HTML tag associated with that emphasis. If CHAR is a space, the means
5235 to remove the emphasis of the selected region.
5236 If char is not given (for example in an interactive call) it
5237 will be prompted for."
5238 (interactive)
5239 (let ((eal org-emphasis-alist) e det
5240 (erc org-emphasis-regexp-components)
5241 (prompt "")
5242 (string "") beg end move tag c s)
5243 (if (org-region-active-p)
5244 (setq beg (region-beginning) end (region-end)
5245 string (buffer-substring beg end))
5246 (setq move t))
5248 (while (setq e (pop eal))
5249 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5250 c (aref tag 0))
5251 (push (cons c (string-to-char (car e))) det)
5252 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5253 (substring tag 1)))))
5254 (unless char
5255 (message "%s" (concat "Emphasis marker or tag:" prompt))
5256 (setq char (read-char-exclusive)))
5257 (setq char (or (cdr (assoc char det)) char))
5258 (if (equal char ?\ )
5259 (setq s "" move nil)
5260 (unless (assoc (char-to-string char) org-emphasis-alist)
5261 (error "No such emphasis marker: \"%c\"" char))
5262 (setq s (char-to-string char)))
5263 (while (and (> (length string) 1)
5264 (equal (substring string 0 1) (substring string -1))
5265 (assoc (substring string 0 1) org-emphasis-alist))
5266 (setq string (substring string 1 -1)))
5267 (setq string (concat s string s))
5268 (if beg (delete-region beg end))
5269 (unless (or (bolp)
5270 (string-match (concat "[" (nth 0 erc) "\n]")
5271 (char-to-string (char-before (point)))))
5272 (insert " "))
5273 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5274 (char-to-string (char-after (point))))
5275 (insert " ") (backward-char 1))
5276 (insert string)
5277 (and move (backward-char 1))))
5279 (defconst org-nonsticky-props
5280 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5283 (defun org-activate-plain-links (limit)
5284 "Run through the buffer and add overlays to links."
5285 (catch 'exit
5286 (let (f)
5287 (while (re-search-forward org-plain-link-re limit t)
5288 (setq f (get-text-property (match-beginning 0) 'face))
5289 (if (or (eq f 'org-tag)
5290 (and (listp f) (memq 'org-tag f)))
5292 (add-text-properties (match-beginning 0) (match-end 0)
5293 (list 'mouse-face 'highlight
5294 'rear-nonsticky org-nonsticky-props
5295 'keymap org-mouse-map
5297 (throw 'exit t))))))
5299 (defun org-activate-code (limit)
5300 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5301 (unless (get-text-property (match-beginning 1) 'face)
5302 (remove-text-properties (match-beginning 0) (match-end 0)
5303 '(display t invisible t intangible t))
5304 t)))
5306 (defun org-activate-angle-links (limit)
5307 "Run through the buffer and add overlays to links."
5308 (if (re-search-forward org-angle-link-re limit t)
5309 (progn
5310 (add-text-properties (match-beginning 0) (match-end 0)
5311 (list 'mouse-face 'highlight
5312 'rear-nonsticky org-nonsticky-props
5313 'keymap org-mouse-map
5315 t)))
5317 (defmacro org-maybe-intangible (props)
5318 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5319 In emacs 21, invisible text is not avoided by the command loop, so the
5320 intangible property is needed to make sure point skips this text.
5321 In Emacs 22, this is not necessary. The intangible text property has
5322 led to problems with flyspell. These problems are fixed in flyspell.el,
5323 but we still avoid setting the property in Emacs 22 and later.
5324 We use a macro so that the test can happen at compilation time."
5325 (if (< emacs-major-version 22)
5326 `(append '(intangible t) ,props)
5327 props))
5329 (defun org-activate-bracket-links (limit)
5330 "Run through the buffer and add overlays to bracketed links."
5331 (if (re-search-forward org-bracket-link-regexp limit t)
5332 (let* ((help (concat "LINK: "
5333 (org-match-string-no-properties 1)))
5334 ;; FIXME: above we should remove the escapes.
5335 ;; but that requires another match, protecting match data,
5336 ;; a lot of overhead for font-lock.
5337 (ip (org-maybe-intangible
5338 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5339 'keymap org-mouse-map 'mouse-face 'highlight
5340 'font-lock-multiline t 'help-echo help)))
5341 (vp (list 'rear-nonsticky org-nonsticky-props
5342 'keymap org-mouse-map 'mouse-face 'highlight
5343 ' font-lock-multiline t 'help-echo help)))
5344 ;; We need to remove the invisible property here. Table narrowing
5345 ;; may have made some of this invisible.
5346 (remove-text-properties (match-beginning 0) (match-end 0)
5347 '(invisible nil))
5348 (if (match-end 3)
5349 (progn
5350 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5351 (add-text-properties (match-beginning 3) (match-end 3) vp)
5352 (add-text-properties (match-end 3) (match-end 0) ip))
5353 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5354 (add-text-properties (match-beginning 1) (match-end 1) vp)
5355 (add-text-properties (match-end 1) (match-end 0) ip))
5356 t)))
5358 (defun org-activate-dates (limit)
5359 "Run through the buffer and add overlays to dates."
5360 (if (re-search-forward org-tsr-regexp-both limit t)
5361 (progn
5362 (add-text-properties (match-beginning 0) (match-end 0)
5363 (list 'mouse-face 'highlight
5364 'rear-nonsticky org-nonsticky-props
5365 'keymap org-mouse-map))
5366 (when org-display-custom-times
5367 (if (match-end 3)
5368 (org-display-custom-time (match-beginning 3) (match-end 3)))
5369 (org-display-custom-time (match-beginning 1) (match-end 1)))
5370 t)))
5372 (defvar org-target-link-regexp nil
5373 "Regular expression matching radio targets in plain text.")
5374 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5375 "Regular expression matching a link target.")
5376 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5377 "Regular expression matching a radio target.")
5378 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5379 "Regular expression matching any target.")
5381 (defun org-activate-target-links (limit)
5382 "Run through the buffer and add overlays to target matches."
5383 (when org-target-link-regexp
5384 (let ((case-fold-search t))
5385 (if (re-search-forward org-target-link-regexp limit t)
5386 (progn
5387 (add-text-properties (match-beginning 0) (match-end 0)
5388 (list 'mouse-face 'highlight
5389 'rear-nonsticky org-nonsticky-props
5390 'keymap org-mouse-map
5391 'help-echo "Radio target link"
5392 'org-linked-text t))
5393 t)))))
5395 (defun org-update-radio-target-regexp ()
5396 "Find all radio targets in this file and update the regular expression."
5397 (interactive)
5398 (when (memq 'radio org-activate-links)
5399 (setq org-target-link-regexp
5400 (org-make-target-link-regexp (org-all-targets 'radio)))
5401 (org-restart-font-lock)))
5403 (defun org-hide-wide-columns (limit)
5404 (let (s e)
5405 (setq s (text-property-any (point) (or limit (point-max))
5406 'org-cwidth t))
5407 (when s
5408 (setq e (next-single-property-change s 'org-cwidth))
5409 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5410 (goto-char e)
5411 t)))
5413 (defvar org-latex-and-specials-regexp nil
5414 "Regular expression for highlighting export special stuff.")
5415 (defvar org-match-substring-regexp)
5416 (defvar org-match-substring-with-braces-regexp)
5417 (defvar org-export-html-special-string-regexps)
5419 (defun org-compute-latex-and-specials-regexp ()
5420 "Compute regular expression for stuff treated specially by exporters."
5421 (if (not org-highlight-latex-fragments-and-specials)
5422 (org-set-local 'org-latex-and-specials-regexp nil)
5423 (let*
5424 ((matchers (plist-get org-format-latex-options :matchers))
5425 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5426 org-latex-regexps)))
5427 (options (org-combine-plists (org-default-export-plist)
5428 (org-infile-export-plist)))
5429 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5430 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5431 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5432 (org-export-html-expand (plist-get options :expand-quoted-html))
5433 (org-export-with-special-strings (plist-get options :special-strings))
5434 (re-sub
5435 (cond
5436 ((equal org-export-with-sub-superscripts '{})
5437 (list org-match-substring-with-braces-regexp))
5438 (org-export-with-sub-superscripts
5439 (list org-match-substring-regexp))
5440 (t nil)))
5441 (re-latex
5442 (if org-export-with-LaTeX-fragments
5443 (mapcar (lambda (x) (nth 1 x)) latexs)))
5444 (re-macros
5445 (if org-export-with-TeX-macros
5446 (list (concat "\\\\"
5447 (regexp-opt
5448 (append (mapcar 'car org-html-entities)
5449 (if (boundp 'org-latex-entities)
5450 org-latex-entities nil))
5451 'words))) ; FIXME
5453 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5454 (re-special (if org-export-with-special-strings
5455 (mapcar (lambda (x) (car x))
5456 org-export-html-special-string-regexps)))
5457 (re-rest
5458 (delq nil
5459 (list
5460 (if org-export-html-expand "@<[^>\n]+>")
5461 ))))
5462 (org-set-local
5463 'org-latex-and-specials-regexp
5464 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5465 re-rest) "\\|")))))
5467 (defface org-latex-and-export-specials
5468 (let ((font (cond ((assq :inherit custom-face-attributes)
5469 '(:inherit underline))
5470 (t '(:underline t)))))
5471 `((((class grayscale) (background light))
5472 (:foreground "DimGray" ,@font))
5473 (((class grayscale) (background dark))
5474 (:foreground "LightGray" ,@font))
5475 (((class color) (background light))
5476 (:foreground "SaddleBrown"))
5477 (((class color) (background dark))
5478 (:foreground "burlywood"))
5479 (t (,@font))))
5480 "Face used to highlight math latex and other special exporter stuff."
5481 :group 'org-faces)
5483 (defun org-do-latex-and-special-faces (limit)
5484 "Run through the buffer and add overlays to links."
5485 (when org-latex-and-specials-regexp
5486 (let (rtn d)
5487 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5488 limit t))
5489 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5490 'face))
5491 '(org-code org-verbatim underline)))
5492 (progn
5493 (setq rtn t
5494 d (cond ((member (char-after (1+ (match-beginning 0)))
5495 '(?_ ?^)) 1)
5496 (t 0)))
5497 (font-lock-prepend-text-property
5498 (+ d (match-beginning 0)) (match-end 0)
5499 'face 'org-latex-and-export-specials)
5500 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5501 '(font-lock-multiline t)))))
5502 rtn)))
5504 (defun org-restart-font-lock ()
5505 "Restart font-lock-mode, to force refontification."
5506 (when (and (boundp 'font-lock-mode) font-lock-mode)
5507 (font-lock-mode -1)
5508 (font-lock-mode 1)))
5510 (defun org-all-targets (&optional radio)
5511 "Return a list of all targets in this file.
5512 With optional argument RADIO, only find radio targets."
5513 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5514 rtn)
5515 (save-excursion
5516 (goto-char (point-min))
5517 (while (re-search-forward re nil t)
5518 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5519 rtn)))
5521 (defun org-make-target-link-regexp (targets)
5522 "Make regular expression matching all strings in TARGETS.
5523 The regular expression finds the targets also if there is a line break
5524 between words."
5525 (and targets
5526 (concat
5527 "\\<\\("
5528 (mapconcat
5529 (lambda (x)
5530 (while (string-match " +" x)
5531 (setq x (replace-match "\\s-+" t t x)))
5533 targets
5534 "\\|")
5535 "\\)\\>")))
5537 (defun org-activate-tags (limit)
5538 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5539 (progn
5540 (add-text-properties (match-beginning 1) (match-end 1)
5541 (list 'mouse-face 'highlight
5542 'rear-nonsticky org-nonsticky-props
5543 'keymap org-mouse-map))
5544 t)))
5546 (defun org-outline-level ()
5547 (save-excursion
5548 (looking-at outline-regexp)
5549 (if (match-beginning 1)
5550 (+ (org-get-string-indentation (match-string 1)) 1000)
5551 (1- (- (match-end 0) (match-beginning 0))))))
5553 (defvar org-font-lock-keywords nil)
5555 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5556 "Regular expression matching a property line.")
5558 (defun org-set-font-lock-defaults ()
5559 (let* ((em org-fontify-emphasized-text)
5560 (lk org-activate-links)
5561 (org-font-lock-extra-keywords
5562 (list
5563 ;; Headlines
5564 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5565 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5566 ;; Table lines
5567 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5568 (1 'org-table t))
5569 ;; Table internals
5570 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5571 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5572 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5573 ;; Drawers
5574 (list org-drawer-regexp '(0 'org-special-keyword t))
5575 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5576 ;; Properties
5577 (list org-property-re
5578 '(1 'org-special-keyword t)
5579 '(3 'org-property-value t))
5580 (if org-format-transports-properties-p
5581 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5582 ;; Links
5583 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5584 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5585 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5586 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5587 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5588 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5589 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5590 '(org-hide-wide-columns (0 nil append))
5591 ;; TODO lines
5592 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5593 '(1 (org-get-todo-face 1) t))
5594 ;; DONE
5595 (if org-fontify-done-headline
5596 (list (concat "^[*]+ +\\<\\("
5597 (mapconcat 'regexp-quote org-done-keywords "\\|")
5598 "\\)\\(.*\\)")
5599 '(2 'org-headline-done t))
5600 nil)
5601 ;; Priorities
5602 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5603 ;; Special keywords
5604 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5605 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5606 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5607 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5608 ;; Emphasis
5609 (if em
5610 (if (featurep 'xemacs)
5611 '(org-do-emphasis-faces (0 nil append))
5612 '(org-do-emphasis-faces)))
5613 ;; Checkboxes
5614 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5615 2 'bold prepend)
5616 (if org-provide-checkbox-statistics
5617 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5618 (0 (org-get-checkbox-statistics-face) t)))
5619 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5620 '(1 'org-archived prepend))
5621 ;; Specials
5622 '(org-do-latex-and-special-faces)
5623 ;; Code
5624 '(org-activate-code (1 'org-code t))
5625 ;; COMMENT
5626 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5627 "\\|" org-quote-string "\\)\\>")
5628 '(1 'org-special-keyword t))
5629 '("^#.*" (0 'font-lock-comment-face t))
5631 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5632 ;; Now set the full font-lock-keywords
5633 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5634 (org-set-local 'font-lock-defaults
5635 '(org-font-lock-keywords t nil nil backward-paragraph))
5636 (kill-local-variable 'font-lock-keywords) nil))
5638 (defvar org-m nil)
5639 (defvar org-l nil)
5640 (defvar org-f nil)
5641 (defun org-get-level-face (n)
5642 "Get the right face for match N in font-lock matching of healdines."
5643 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5644 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5645 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5646 (cond
5647 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5648 ((eq n 2) org-f)
5649 (t (if org-level-color-stars-only nil org-f))))
5651 (defun org-get-todo-face (kwd)
5652 "Get the right face for a TODO keyword KWD.
5653 If KWD is a number, get the corresponding match group."
5654 (if (numberp kwd) (setq kwd (match-string kwd)))
5655 (or (cdr (assoc kwd org-todo-keyword-faces))
5656 (and (member kwd org-done-keywords) 'org-done)
5657 'org-todo))
5659 (defun org-unfontify-region (beg end &optional maybe_loudly)
5660 "Remove fontification and activation overlays from links."
5661 (font-lock-default-unfontify-region beg end)
5662 (let* ((buffer-undo-list t)
5663 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5664 (inhibit-modification-hooks t)
5665 deactivate-mark buffer-file-name buffer-file-truename)
5666 (remove-text-properties beg end
5667 '(mouse-face t keymap t org-linked-text t
5668 invisible t intangible t))))
5670 ;;;; Visibility cycling, including org-goto and indirect buffer
5672 ;;; Cycling
5674 (defvar org-cycle-global-status nil)
5675 (make-variable-buffer-local 'org-cycle-global-status)
5676 (defvar org-cycle-subtree-status nil)
5677 (make-variable-buffer-local 'org-cycle-subtree-status)
5679 ;;;###autoload
5680 (defun org-cycle (&optional arg)
5681 "Visibility cycling for Org-mode.
5683 - When this function is called with a prefix argument, rotate the entire
5684 buffer through 3 states (global cycling)
5685 1. OVERVIEW: Show only top-level headlines.
5686 2. CONTENTS: Show all headlines of all levels, but no body text.
5687 3. SHOW ALL: Show everything.
5689 - When point is at the beginning of a headline, rotate the subtree started
5690 by this line through 3 different states (local cycling)
5691 1. FOLDED: Only the main headline is shown.
5692 2. CHILDREN: The main headline and the direct children are shown.
5693 From this state, you can move to one of the children
5694 and zoom in further.
5695 3. SUBTREE: Show the entire subtree, including body text.
5697 - When there is a numeric prefix, go up to a heading with level ARG, do
5698 a `show-subtree' and return to the previous cursor position. If ARG
5699 is negative, go up that many levels.
5701 - When point is not at the beginning of a headline, execute
5702 `indent-relative', like TAB normally does. See the option
5703 `org-cycle-emulate-tab' for details.
5705 - Special case: if point is at the beginning of the buffer and there is
5706 no headline in line 1, this function will act as if called with prefix arg.
5707 But only if also the variable `org-cycle-global-at-bob' is t."
5708 (interactive "P")
5709 (let* ((outline-regexp
5710 (if (and (org-mode-p) org-cycle-include-plain-lists)
5711 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5712 outline-regexp))
5713 (bob-special (and org-cycle-global-at-bob (bobp)
5714 (not (looking-at outline-regexp))))
5715 (org-cycle-hook
5716 (if bob-special
5717 (delq 'org-optimize-window-after-visibility-change
5718 (copy-sequence org-cycle-hook))
5719 org-cycle-hook))
5720 (pos (point)))
5722 (if (or bob-special (equal arg '(4)))
5723 ;; special case: use global cycling
5724 (setq arg t))
5726 (cond
5728 ((org-at-table-p 'any)
5729 ;; Enter the table or move to the next field in the table
5730 (or (org-table-recognize-table.el)
5731 (progn
5732 (if arg (org-table-edit-field t)
5733 (org-table-justify-field-maybe)
5734 (call-interactively 'org-table-next-field)))))
5736 ((eq arg t) ;; Global cycling
5738 (cond
5739 ((and (eq last-command this-command)
5740 (eq org-cycle-global-status 'overview))
5741 ;; We just created the overview - now do table of contents
5742 ;; This can be slow in very large buffers, so indicate action
5743 (message "CONTENTS...")
5744 (org-content)
5745 (message "CONTENTS...done")
5746 (setq org-cycle-global-status 'contents)
5747 (run-hook-with-args 'org-cycle-hook 'contents))
5749 ((and (eq last-command this-command)
5750 (eq org-cycle-global-status 'contents))
5751 ;; We just showed the table of contents - now show everything
5752 (show-all)
5753 (message "SHOW ALL")
5754 (setq org-cycle-global-status 'all)
5755 (run-hook-with-args 'org-cycle-hook 'all))
5758 ;; Default action: go to overview
5759 (org-overview)
5760 (message "OVERVIEW")
5761 (setq org-cycle-global-status 'overview)
5762 (run-hook-with-args 'org-cycle-hook 'overview))))
5764 ((and org-drawers org-drawer-regexp
5765 (save-excursion
5766 (beginning-of-line 1)
5767 (looking-at org-drawer-regexp)))
5768 ;; Toggle block visibility
5769 (org-flag-drawer
5770 (not (get-char-property (match-end 0) 'invisible))))
5772 ((integerp arg)
5773 ;; Show-subtree, ARG levels up from here.
5774 (save-excursion
5775 (org-back-to-heading)
5776 (outline-up-heading (if (< arg 0) (- arg)
5777 (- (funcall outline-level) arg)))
5778 (org-show-subtree)))
5780 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5781 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5782 ;; At a heading: rotate between three different views
5783 (org-back-to-heading)
5784 (let ((goal-column 0) eoh eol eos)
5785 ;; First, some boundaries
5786 (save-excursion
5787 (org-back-to-heading)
5788 (save-excursion
5789 (beginning-of-line 2)
5790 (while (and (not (eobp)) ;; this is like `next-line'
5791 (get-char-property (1- (point)) 'invisible))
5792 (beginning-of-line 2)) (setq eol (point)))
5793 (outline-end-of-heading) (setq eoh (point))
5794 (org-end-of-subtree t)
5795 (unless (eobp)
5796 (skip-chars-forward " \t\n")
5797 (beginning-of-line 1) ; in case this is an item
5799 (setq eos (1- (point))))
5800 ;; Find out what to do next and set `this-command'
5801 (cond
5802 ((= eos eoh)
5803 ;; Nothing is hidden behind this heading
5804 (message "EMPTY ENTRY")
5805 (setq org-cycle-subtree-status nil)
5806 (save-excursion
5807 (goto-char eos)
5808 (outline-next-heading)
5809 (if (org-invisible-p) (org-flag-heading nil))))
5810 ((or (>= eol eos)
5811 (not (string-match "\\S-" (buffer-substring eol eos))))
5812 ;; Entire subtree is hidden in one line: open it
5813 (org-show-entry)
5814 (show-children)
5815 (message "CHILDREN")
5816 (save-excursion
5817 (goto-char eos)
5818 (outline-next-heading)
5819 (if (org-invisible-p) (org-flag-heading nil)))
5820 (setq org-cycle-subtree-status 'children)
5821 (run-hook-with-args 'org-cycle-hook 'children))
5822 ((and (eq last-command this-command)
5823 (eq org-cycle-subtree-status 'children))
5824 ;; We just showed the children, now show everything.
5825 (org-show-subtree)
5826 (message "SUBTREE")
5827 (setq org-cycle-subtree-status 'subtree)
5828 (run-hook-with-args 'org-cycle-hook 'subtree))
5830 ;; Default action: hide the subtree.
5831 (hide-subtree)
5832 (message "FOLDED")
5833 (setq org-cycle-subtree-status 'folded)
5834 (run-hook-with-args 'org-cycle-hook 'folded)))))
5836 ;; TAB emulation
5837 (buffer-read-only (org-back-to-heading))
5839 ((org-try-cdlatex-tab))
5841 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5842 (or (not (bolp))
5843 (not (looking-at outline-regexp))))
5844 (call-interactively (global-key-binding "\t")))
5846 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5847 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5848 (or (and (eq org-cycle-emulate-tab 'white)
5849 (= (match-end 0) (point-at-eol)))
5850 (and (eq org-cycle-emulate-tab 'whitestart)
5851 (>= (match-end 0) pos))))
5853 (eq org-cycle-emulate-tab t))
5854 ; (if (and (looking-at "[ \n\r\t]")
5855 ; (string-match "^[ \t]*$" (buffer-substring
5856 ; (point-at-bol) (point))))
5857 ; (progn
5858 ; (beginning-of-line 1)
5859 ; (and (looking-at "[ \t]+") (replace-match ""))))
5860 (call-interactively (global-key-binding "\t")))
5862 (t (save-excursion
5863 (org-back-to-heading)
5864 (org-cycle))))))
5866 ;;;###autoload
5867 (defun org-global-cycle (&optional arg)
5868 "Cycle the global visibility. For details see `org-cycle'."
5869 (interactive "P")
5870 (let ((org-cycle-include-plain-lists
5871 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5872 (if (integerp arg)
5873 (progn
5874 (show-all)
5875 (hide-sublevels arg)
5876 (setq org-cycle-global-status 'contents))
5877 (org-cycle '(4)))))
5879 (defun org-overview ()
5880 "Switch to overview mode, shoing only top-level headlines.
5881 Really, this shows all headlines with level equal or greater than the level
5882 of the first headline in the buffer. This is important, because if the
5883 first headline is not level one, then (hide-sublevels 1) gives confusing
5884 results."
5885 (interactive)
5886 (let ((level (save-excursion
5887 (goto-char (point-min))
5888 (if (re-search-forward (concat "^" outline-regexp) nil t)
5889 (progn
5890 (goto-char (match-beginning 0))
5891 (funcall outline-level))))))
5892 (and level (hide-sublevels level))))
5894 (defun org-content (&optional arg)
5895 "Show all headlines in the buffer, like a table of contents.
5896 With numerical argument N, show content up to level N."
5897 (interactive "P")
5898 (save-excursion
5899 ;; Visit all headings and show their offspring
5900 (and (integerp arg) (org-overview))
5901 (goto-char (point-max))
5902 (catch 'exit
5903 (while (and (progn (condition-case nil
5904 (outline-previous-visible-heading 1)
5905 (error (goto-char (point-min))))
5907 (looking-at outline-regexp))
5908 (if (integerp arg)
5909 (show-children (1- arg))
5910 (show-branches))
5911 (if (bobp) (throw 'exit nil))))))
5914 (defun org-optimize-window-after-visibility-change (state)
5915 "Adjust the window after a change in outline visibility.
5916 This function is the default value of the hook `org-cycle-hook'."
5917 (when (get-buffer-window (current-buffer))
5918 (cond
5919 ; ((eq state 'overview) (org-first-headline-recenter 1))
5920 ; ((eq state 'overview) (org-beginning-of-line))
5921 ((eq state 'content) nil)
5922 ((eq state 'all) nil)
5923 ((eq state 'folded) nil)
5924 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5925 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5927 (defun org-compact-display-after-subtree-move ()
5928 (let (beg end)
5929 (save-excursion
5930 (if (org-up-heading-safe)
5931 (progn
5932 (hide-subtree)
5933 (show-entry)
5934 (show-children)
5935 (org-cycle-show-empty-lines 'children)
5936 (org-cycle-hide-drawers 'children))
5937 (org-overview)))))
5939 (defun org-cycle-show-empty-lines (state)
5940 "Show empty lines above all visible headlines.
5941 The region to be covered depends on STATE when called through
5942 `org-cycle-hook'. Lisp program can use t for STATE to get the
5943 entire buffer covered. Note that an empty line is only shown if there
5944 are at least `org-cycle-separator-lines' empty lines before the headeline."
5945 (when (> org-cycle-separator-lines 0)
5946 (save-excursion
5947 (let* ((n org-cycle-separator-lines)
5948 (re (cond
5949 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5950 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5951 (t (let ((ns (number-to-string (- n 2))))
5952 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5953 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5954 beg end)
5955 (cond
5956 ((memq state '(overview contents t))
5957 (setq beg (point-min) end (point-max)))
5958 ((memq state '(children folded))
5959 (setq beg (point) end (progn (org-end-of-subtree t t)
5960 (beginning-of-line 2)
5961 (point)))))
5962 (when beg
5963 (goto-char beg)
5964 (while (re-search-forward re end t)
5965 (if (not (get-char-property (match-end 1) 'invisible))
5966 (outline-flag-region
5967 (match-beginning 1) (match-end 1) nil)))))))
5968 ;; Never hide empty lines at the end of the file.
5969 (save-excursion
5970 (goto-char (point-max))
5971 (outline-previous-heading)
5972 (outline-end-of-heading)
5973 (if (and (looking-at "[ \t\n]+")
5974 (= (match-end 0) (point-max)))
5975 (outline-flag-region (point) (match-end 0) nil))))
5977 (defun org-subtree-end-visible-p ()
5978 "Is the end of the current subtree visible?"
5979 (pos-visible-in-window-p
5980 (save-excursion (org-end-of-subtree t) (point))))
5982 (defun org-first-headline-recenter (&optional N)
5983 "Move cursor to the first headline and recenter the headline.
5984 Optional argument N means, put the headline into the Nth line of the window."
5985 (goto-char (point-min))
5986 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5987 (beginning-of-line)
5988 (recenter (prefix-numeric-value N))))
5990 ;;; Org-goto
5992 (defvar org-goto-window-configuration nil)
5993 (defvar org-goto-marker nil)
5994 (defvar org-goto-map
5995 (let ((map (make-sparse-keymap)))
5996 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5997 (while (setq cmd (pop cmds))
5998 (substitute-key-definition cmd cmd map global-map)))
5999 (suppress-keymap map)
6000 (org-defkey map "\C-m" 'org-goto-ret)
6001 (org-defkey map [(return)] 'org-goto-ret)
6002 (org-defkey map [(left)] 'org-goto-left)
6003 (org-defkey map [(right)] 'org-goto-right)
6004 (org-defkey map [(control ?g)] 'org-goto-quit)
6005 (org-defkey map "\C-i" 'org-cycle)
6006 (org-defkey map [(tab)] 'org-cycle)
6007 (org-defkey map [(down)] 'outline-next-visible-heading)
6008 (org-defkey map [(up)] 'outline-previous-visible-heading)
6009 (if org-goto-auto-isearch
6010 (if (fboundp 'define-key-after)
6011 (define-key-after map [t] 'org-goto-local-auto-isearch)
6012 nil)
6013 (org-defkey map "q" 'org-goto-quit)
6014 (org-defkey map "n" 'outline-next-visible-heading)
6015 (org-defkey map "p" 'outline-previous-visible-heading)
6016 (org-defkey map "f" 'outline-forward-same-level)
6017 (org-defkey map "b" 'outline-backward-same-level)
6018 (org-defkey map "u" 'outline-up-heading))
6019 (org-defkey map "/" 'org-occur)
6020 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6021 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6022 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6023 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6024 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6025 map))
6027 (defconst org-goto-help
6028 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6029 RET=jump to location [Q]uit and return to previous location
6030 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6032 (defvar org-goto-start-pos) ; dynamically scoped parameter
6034 (defun org-goto (&optional alternative-interface)
6035 "Look up a different location in the current file, keeping current visibility.
6037 When you want look-up or go to a different location in a document, the
6038 fastest way is often to fold the entire buffer and then dive into the tree.
6039 This method has the disadvantage, that the previous location will be folded,
6040 which may not be what you want.
6042 This command works around this by showing a copy of the current buffer
6043 in an indirect buffer, in overview mode. You can dive into the tree in
6044 that copy, use org-occur and incremental search to find a location.
6045 When pressing RET or `Q', the command returns to the original buffer in
6046 which the visibility is still unchanged. After RET is will also jump to
6047 the location selected in the indirect buffer and expose the
6048 the headline hierarchy above."
6049 (interactive "P")
6050 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6051 (org-refile-use-outline-path t)
6052 (interface
6053 (if (not alternative-interface)
6054 org-goto-interface
6055 (if (eq org-goto-interface 'outline)
6056 'outline-path-completion
6057 'outline)))
6058 (org-goto-start-pos (point))
6059 (selected-point
6060 (if (eq interface 'outline)
6061 (car (org-get-location (current-buffer) org-goto-help))
6062 (nth 3 (org-refile-get-location "Goto: ")))))
6063 (if selected-point
6064 (progn
6065 (org-mark-ring-push org-goto-start-pos)
6066 (goto-char selected-point)
6067 (if (or (org-invisible-p) (org-invisible-p2))
6068 (org-show-context 'org-goto)))
6069 (message "Quit"))))
6071 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6072 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6073 (defvar org-goto-local-auto-isearch-map) ; defined below
6075 (defun org-get-location (buf help)
6076 "Let the user select a location in the Org-mode buffer BUF.
6077 This function uses a recursive edit. It returns the selected position
6078 or nil."
6079 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6080 (isearch-hide-immediately nil)
6081 (isearch-search-fun-function
6082 (lambda () 'org-goto-local-search-forward-headings))
6083 (org-goto-selected-point org-goto-exit-command))
6084 (save-excursion
6085 (save-window-excursion
6086 (delete-other-windows)
6087 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6088 (switch-to-buffer
6089 (condition-case nil
6090 (make-indirect-buffer (current-buffer) "*org-goto*")
6091 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6092 (with-output-to-temp-buffer "*Help*"
6093 (princ help))
6094 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6095 (setq buffer-read-only nil)
6096 (let ((org-startup-truncated t)
6097 (org-startup-folded nil)
6098 (org-startup-align-all-tables nil))
6099 (org-mode)
6100 (org-overview))
6101 (setq buffer-read-only t)
6102 (if (and (boundp 'org-goto-start-pos)
6103 (integer-or-marker-p org-goto-start-pos))
6104 (let ((org-show-hierarchy-above t)
6105 (org-show-siblings t)
6106 (org-show-following-heading t))
6107 (goto-char org-goto-start-pos)
6108 (and (org-invisible-p) (org-show-context)))
6109 (goto-char (point-min)))
6110 (org-beginning-of-line)
6111 (message "Select location and press RET")
6112 (use-local-map org-goto-map)
6113 (recursive-edit)
6115 (kill-buffer "*org-goto*")
6116 (cons org-goto-selected-point org-goto-exit-command)))
6118 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6119 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6120 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6121 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6123 (defun org-goto-local-search-forward-headings (string bound noerror)
6124 "Search and make sure that anu matches are in headlines."
6125 (catch 'return
6126 (while (search-forward string bound noerror)
6127 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6128 (and (member :headline context)
6129 (not (member :tags context))))
6130 (throw 'return (point))))))
6132 (defun org-goto-local-auto-isearch ()
6133 "Start isearch."
6134 (interactive)
6135 (goto-char (point-min))
6136 (let ((keys (this-command-keys)))
6137 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6138 (isearch-mode t)
6139 (isearch-process-search-char (string-to-char keys)))))
6141 (defun org-goto-ret (&optional arg)
6142 "Finish `org-goto' by going to the new location."
6143 (interactive "P")
6144 (setq org-goto-selected-point (point)
6145 org-goto-exit-command 'return)
6146 (throw 'exit nil))
6148 (defun org-goto-left ()
6149 "Finish `org-goto' by going to the new location."
6150 (interactive)
6151 (if (org-on-heading-p)
6152 (progn
6153 (beginning-of-line 1)
6154 (setq org-goto-selected-point (point)
6155 org-goto-exit-command 'left)
6156 (throw 'exit nil))
6157 (error "Not on a heading")))
6159 (defun org-goto-right ()
6160 "Finish `org-goto' by going to the new location."
6161 (interactive)
6162 (if (org-on-heading-p)
6163 (progn
6164 (setq org-goto-selected-point (point)
6165 org-goto-exit-command 'right)
6166 (throw 'exit nil))
6167 (error "Not on a heading")))
6169 (defun org-goto-quit ()
6170 "Finish `org-goto' without cursor motion."
6171 (interactive)
6172 (setq org-goto-selected-point nil)
6173 (setq org-goto-exit-command 'quit)
6174 (throw 'exit nil))
6176 ;;; Indirect buffer display of subtrees
6178 (defvar org-indirect-dedicated-frame nil
6179 "This is the frame being used for indirect tree display.")
6180 (defvar org-last-indirect-buffer nil)
6182 (defun org-tree-to-indirect-buffer (&optional arg)
6183 "Create indirect buffer and narrow it to current subtree.
6184 With numerical prefix ARG, go up to this level and then take that tree.
6185 If ARG is negative, go up that many levels.
6186 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6187 indirect buffer previously made with this command, to avoid proliferation of
6188 indirect buffers. However, when you call the command with a `C-u' prefix, or
6189 when `org-indirect-buffer-display' is `new-frame', the last buffer
6190 is kept so that you can work with several indirect buffers at the same time.
6191 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6192 requests that a new frame be made for the new buffer, so that the dedicated
6193 frame is not changed."
6194 (interactive "P")
6195 (let ((cbuf (current-buffer))
6196 (cwin (selected-window))
6197 (pos (point))
6198 beg end level heading ibuf)
6199 (save-excursion
6200 (org-back-to-heading t)
6201 (when (numberp arg)
6202 (setq level (org-outline-level))
6203 (if (< arg 0) (setq arg (+ level arg)))
6204 (while (> (setq level (org-outline-level)) arg)
6205 (outline-up-heading 1 t)))
6206 (setq beg (point)
6207 heading (org-get-heading))
6208 (org-end-of-subtree t) (setq end (point)))
6209 (if (and (buffer-live-p org-last-indirect-buffer)
6210 (not (eq org-indirect-buffer-display 'new-frame))
6211 (not arg))
6212 (kill-buffer org-last-indirect-buffer))
6213 (setq ibuf (org-get-indirect-buffer cbuf)
6214 org-last-indirect-buffer ibuf)
6215 (cond
6216 ((or (eq org-indirect-buffer-display 'new-frame)
6217 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6218 (select-frame (make-frame))
6219 (delete-other-windows)
6220 (switch-to-buffer ibuf)
6221 (org-set-frame-title heading))
6222 ((eq org-indirect-buffer-display 'dedicated-frame)
6223 (raise-frame
6224 (select-frame (or (and org-indirect-dedicated-frame
6225 (frame-live-p org-indirect-dedicated-frame)
6226 org-indirect-dedicated-frame)
6227 (setq org-indirect-dedicated-frame (make-frame)))))
6228 (delete-other-windows)
6229 (switch-to-buffer ibuf)
6230 (org-set-frame-title (concat "Indirect: " heading)))
6231 ((eq org-indirect-buffer-display 'current-window)
6232 (switch-to-buffer ibuf))
6233 ((eq org-indirect-buffer-display 'other-window)
6234 (pop-to-buffer ibuf))
6235 (t (error "Invalid value.")))
6236 (if (featurep 'xemacs)
6237 (save-excursion (org-mode) (turn-on-font-lock)))
6238 (narrow-to-region beg end)
6239 (show-all)
6240 (goto-char pos)
6241 (and (window-live-p cwin) (select-window cwin))))
6243 (defun org-get-indirect-buffer (&optional buffer)
6244 (setq buffer (or buffer (current-buffer)))
6245 (let ((n 1) (base (buffer-name buffer)) bname)
6246 (while (buffer-live-p
6247 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6248 (setq n (1+ n)))
6249 (condition-case nil
6250 (make-indirect-buffer buffer bname 'clone)
6251 (error (make-indirect-buffer buffer bname)))))
6253 (defun org-set-frame-title (title)
6254 "Set the title of the current frame to the string TITLE."
6255 ;; FIXME: how to name a single frame in XEmacs???
6256 (unless (featurep 'xemacs)
6257 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6259 ;;;; Structure editing
6261 ;;; Inserting headlines
6263 (defun org-insert-heading (&optional force-heading)
6264 "Insert a new heading or item with same depth at point.
6265 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6266 If point is at the beginning of a headline, insert a sibling before the
6267 current headline. If point is not at the beginning, do not split the line,
6268 but create the new hedline after the current line."
6269 (interactive "P")
6270 (if (= (buffer-size) 0)
6271 (insert "\n* ")
6272 (when (or force-heading (not (org-insert-item)))
6273 (let* ((head (save-excursion
6274 (condition-case nil
6275 (progn
6276 (org-back-to-heading)
6277 (match-string 0))
6278 (error "*"))))
6279 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6280 pos)
6281 (cond
6282 ((and (org-on-heading-p) (bolp)
6283 (or (bobp)
6284 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6285 ;; insert before the current line
6286 (open-line (if blank 2 1)))
6287 ((and (bolp)
6288 (or (bobp)
6289 (save-excursion
6290 (backward-char 1) (not (org-invisible-p)))))
6291 ;; insert right here
6292 nil)
6294 ; ;; in the middle of the line
6295 ; (org-show-entry)
6296 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6297 ; (if (and
6298 ; (org-on-heading-p)
6299 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6300 ; ;; protect the tags
6301 ;; (let ((tags (match-string 2)) pos)
6302 ; (delete-region (match-beginning 1) (match-end 1))
6303 ; (setq pos (point-at-bol))
6304 ; (newline (if blank 2 1))
6305 ; (save-excursion
6306 ; (goto-char pos)
6307 ; (end-of-line 1)
6308 ; (insert " " tags)
6309 ; (org-set-tags nil 'align)))
6310 ; (newline (if blank 2 1)))
6311 ; (newline (if blank 2 1))))
6314 ;; in the middle of the line
6315 (org-show-entry)
6316 (let ((split
6317 (org-get-alist-option org-M-RET-may-split-line 'headline))
6318 tags pos)
6319 (if (org-on-heading-p)
6320 (progn
6321 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6322 (setq tags (and (match-end 2) (match-string 2)))
6323 (and (match-end 1)
6324 (delete-region (match-beginning 1) (match-end 1)))
6325 (setq pos (point-at-bol))
6326 (or split (end-of-line 1))
6327 (delete-horizontal-space)
6328 (newline (if blank 2 1))
6329 (when tags
6330 (save-excursion
6331 (goto-char pos)
6332 (end-of-line 1)
6333 (insert " " tags)
6334 (org-set-tags nil 'align))))
6335 (or split (end-of-line 1))
6336 (newline (if blank 2 1))))))
6337 (insert head) (just-one-space)
6338 (setq pos (point))
6339 (end-of-line 1)
6340 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6341 (run-hooks 'org-insert-heading-hook)))))
6343 (defun org-insert-heading-after-current ()
6344 "Insert a new heading with same level as current, after current subtree."
6345 (interactive)
6346 (org-back-to-heading)
6347 (org-insert-heading)
6348 (org-move-subtree-down)
6349 (end-of-line 1))
6351 (defun org-insert-todo-heading (arg)
6352 "Insert a new heading with the same level and TODO state as current heading.
6353 If the heading has no TODO state, or if the state is DONE, use the first
6354 state (TODO by default). Also with prefix arg, force first state."
6355 (interactive "P")
6356 (when (not (org-insert-item 'checkbox))
6357 (org-insert-heading)
6358 (save-excursion
6359 (org-back-to-heading)
6360 (outline-previous-heading)
6361 (looking-at org-todo-line-regexp))
6362 (if (or arg
6363 (not (match-beginning 2))
6364 (member (match-string 2) org-done-keywords))
6365 (insert (car org-todo-keywords-1) " ")
6366 (insert (match-string 2) " "))))
6368 (defun org-insert-subheading (arg)
6369 "Insert a new subheading and demote it.
6370 Works for outline headings and for plain lists alike."
6371 (interactive "P")
6372 (org-insert-heading arg)
6373 (cond
6374 ((org-on-heading-p) (org-do-demote))
6375 ((org-at-item-p) (org-indent-item 1))))
6377 (defun org-insert-todo-subheading (arg)
6378 "Insert a new subheading with TODO keyword or checkbox and demote it.
6379 Works for outline headings and for plain lists alike."
6380 (interactive "P")
6381 (org-insert-todo-heading arg)
6382 (cond
6383 ((org-on-heading-p) (org-do-demote))
6384 ((org-at-item-p) (org-indent-item 1))))
6386 ;;; Promotion and Demotion
6388 (defun org-promote-subtree ()
6389 "Promote the entire subtree.
6390 See also `org-promote'."
6391 (interactive)
6392 (save-excursion
6393 (org-map-tree 'org-promote))
6394 (org-fix-position-after-promote))
6396 (defun org-demote-subtree ()
6397 "Demote the entire subtree. See `org-demote'.
6398 See also `org-promote'."
6399 (interactive)
6400 (save-excursion
6401 (org-map-tree 'org-demote))
6402 (org-fix-position-after-promote))
6405 (defun org-do-promote ()
6406 "Promote the current heading higher up the tree.
6407 If the region is active in `transient-mark-mode', promote all headings
6408 in the region."
6409 (interactive)
6410 (save-excursion
6411 (if (org-region-active-p)
6412 (org-map-region 'org-promote (region-beginning) (region-end))
6413 (org-promote)))
6414 (org-fix-position-after-promote))
6416 (defun org-do-demote ()
6417 "Demote the current heading lower down the tree.
6418 If the region is active in `transient-mark-mode', demote all headings
6419 in the region."
6420 (interactive)
6421 (save-excursion
6422 (if (org-region-active-p)
6423 (org-map-region 'org-demote (region-beginning) (region-end))
6424 (org-demote)))
6425 (org-fix-position-after-promote))
6427 (defun org-fix-position-after-promote ()
6428 "Make sure that after pro/demotion cursor position is right."
6429 (let ((pos (point)))
6430 (when (save-excursion
6431 (beginning-of-line 1)
6432 (looking-at org-todo-line-regexp)
6433 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6434 (cond ((eobp) (insert " "))
6435 ((eolp) (insert " "))
6436 ((equal (char-after) ?\ ) (forward-char 1))))))
6438 (defun org-reduced-level (l)
6439 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6441 (defun org-get-legal-level (level &optional change)
6442 "Rectify a level change under the influence of `org-odd-levels-only'
6443 LEVEL is a current level, CHANGE is by how much the level should be
6444 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6445 even level numbers will become the next higher odd number."
6446 (if org-odd-levels-only
6447 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6448 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6449 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6450 (max 1 (+ level change))))
6452 (defun org-promote ()
6453 "Promote the current heading higher up the tree.
6454 If the region is active in `transient-mark-mode', promote all headings
6455 in the region."
6456 (org-back-to-heading t)
6457 (let* ((level (save-match-data (funcall outline-level)))
6458 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6459 (diff (abs (- level (length up-head) -1))))
6460 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6461 (replace-match up-head nil t)
6462 ;; Fixup tag positioning
6463 (and org-auto-align-tags (org-set-tags nil t))
6464 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6466 (defun org-demote ()
6467 "Demote the current heading lower down the tree.
6468 If the region is active in `transient-mark-mode', demote all headings
6469 in the region."
6470 (org-back-to-heading t)
6471 (let* ((level (save-match-data (funcall outline-level)))
6472 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6473 (diff (abs (- level (length down-head) -1))))
6474 (replace-match down-head nil t)
6475 ;; Fixup tag positioning
6476 (and org-auto-align-tags (org-set-tags nil t))
6477 (if org-adapt-indentation (org-fixup-indentation diff))))
6479 (defun org-map-tree (fun)
6480 "Call FUN for every heading underneath the current one."
6481 (org-back-to-heading)
6482 (let ((level (funcall outline-level)))
6483 (save-excursion
6484 (funcall fun)
6485 (while (and (progn
6486 (outline-next-heading)
6487 (> (funcall outline-level) level))
6488 (not (eobp)))
6489 (funcall fun)))))
6491 (defun org-map-region (fun beg end)
6492 "Call FUN for every heading between BEG and END."
6493 (let ((org-ignore-region t))
6494 (save-excursion
6495 (setq end (copy-marker end))
6496 (goto-char beg)
6497 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6498 (< (point) end))
6499 (funcall fun))
6500 (while (and (progn
6501 (outline-next-heading)
6502 (< (point) end))
6503 (not (eobp)))
6504 (funcall fun)))))
6506 (defun org-fixup-indentation (diff)
6507 "Change the indentation in the current entry by DIFF
6508 However, if any line in the current entry has no indentation, or if it
6509 would end up with no indentation after the change, nothing at all is done."
6510 (save-excursion
6511 (let ((end (save-excursion (outline-next-heading)
6512 (point-marker)))
6513 (prohibit (if (> diff 0)
6514 "^\\S-"
6515 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6516 col)
6517 (unless (save-excursion (end-of-line 1)
6518 (re-search-forward prohibit end t))
6519 (while (and (< (point) end)
6520 (re-search-forward "^[ \t]+" end t))
6521 (goto-char (match-end 0))
6522 (setq col (current-column))
6523 (if (< diff 0) (replace-match ""))
6524 (indent-to (+ diff col))))
6525 (move-marker end nil))))
6527 (defun org-convert-to-odd-levels ()
6528 "Convert an org-mode file with all levels allowed to one with odd levels.
6529 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6530 level 5 etc."
6531 (interactive)
6532 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6533 (let ((org-odd-levels-only nil) n)
6534 (save-excursion
6535 (goto-char (point-min))
6536 (while (re-search-forward "^\\*\\*+ " nil t)
6537 (setq n (- (length (match-string 0)) 2))
6538 (while (>= (setq n (1- n)) 0)
6539 (org-demote))
6540 (end-of-line 1))))))
6543 (defun org-convert-to-oddeven-levels ()
6544 "Convert an org-mode file with only odd levels to one with odd and even levels.
6545 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6546 section with an even level, conversion would destroy the structure of the file. An error
6547 is signaled in this case."
6548 (interactive)
6549 (goto-char (point-min))
6550 ;; First check if there are no even levels
6551 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6552 (org-show-context t)
6553 (error "Not all levels are odd in this file. Conversion not possible."))
6554 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6555 (let ((org-odd-levels-only nil) n)
6556 (save-excursion
6557 (goto-char (point-min))
6558 (while (re-search-forward "^\\*\\*+ " nil t)
6559 (setq n (/ (1- (length (match-string 0))) 2))
6560 (while (>= (setq n (1- n)) 0)
6561 (org-promote))
6562 (end-of-line 1))))))
6564 (defun org-tr-level (n)
6565 "Make N odd if required."
6566 (if org-odd-levels-only (1+ (/ n 2)) n))
6568 ;;; Vertical tree motion, cutting and pasting of subtrees
6570 (defun org-move-subtree-up (&optional arg)
6571 "Move the current subtree up past ARG headlines of the same level."
6572 (interactive "p")
6573 (org-move-subtree-down (- (prefix-numeric-value arg))))
6575 (defun org-move-subtree-down (&optional arg)
6576 "Move the current subtree down past ARG headlines of the same level."
6577 (interactive "p")
6578 (setq arg (prefix-numeric-value arg))
6579 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6580 'outline-get-last-sibling))
6581 (ins-point (make-marker))
6582 (cnt (abs arg))
6583 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6584 ;; Select the tree
6585 (org-back-to-heading)
6586 (setq beg0 (point))
6587 (save-excursion
6588 (setq ne-beg (org-back-over-empty-lines))
6589 (setq beg (point)))
6590 (save-match-data
6591 (save-excursion (outline-end-of-heading)
6592 (setq folded (org-invisible-p)))
6593 (outline-end-of-subtree))
6594 (outline-next-heading)
6595 (setq ne-end (org-back-over-empty-lines))
6596 (setq end (point))
6597 (goto-char beg0)
6598 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6599 ;; include less whitespace
6600 (save-excursion
6601 (goto-char beg)
6602 (forward-line (- ne-beg ne-end))
6603 (setq beg (point))))
6604 ;; Find insertion point, with error handling
6605 (while (> cnt 0)
6606 (or (and (funcall movfunc) (looking-at outline-regexp))
6607 (progn (goto-char beg0)
6608 (error "Cannot move past superior level or buffer limit")))
6609 (setq cnt (1- cnt)))
6610 (if (> arg 0)
6611 ;; Moving forward - still need to move over subtree
6612 (progn (org-end-of-subtree t t)
6613 (save-excursion
6614 (org-back-over-empty-lines)
6615 (or (bolp) (newline)))))
6616 (setq ne-ins (org-back-over-empty-lines))
6617 (move-marker ins-point (point))
6618 (setq txt (buffer-substring beg end))
6619 (delete-region beg end)
6620 (outline-flag-region (1- beg) beg nil)
6621 (outline-flag-region (1- (point)) (point) nil)
6622 (insert txt)
6623 (or (bolp) (insert "\n"))
6624 (setq ins-end (point))
6625 (goto-char ins-point)
6626 (org-skip-whitespace)
6627 (when (and (< arg 0)
6628 (org-first-sibling-p)
6629 (> ne-ins ne-beg))
6630 ;; Move whitespace back to beginning
6631 (save-excursion
6632 (goto-char ins-end)
6633 (let ((kill-whole-line t))
6634 (kill-line (- ne-ins ne-beg)) (point)))
6635 (insert (make-string (- ne-ins ne-beg) ?\n)))
6636 (move-marker ins-point nil)
6637 (org-compact-display-after-subtree-move)
6638 (unless folded
6639 (org-show-entry)
6640 (show-children)
6641 (org-cycle-hide-drawers 'children))))
6643 (defvar org-subtree-clip ""
6644 "Clipboard for cut and paste of subtrees.
6645 This is actually only a copy of the kill, because we use the normal kill
6646 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6648 (defvar org-subtree-clip-folded nil
6649 "Was the last copied subtree folded?
6650 This is used to fold the tree back after pasting.")
6652 (defun org-cut-subtree (&optional n)
6653 "Cut the current subtree into the clipboard.
6654 With prefix arg N, cut this many sequential subtrees.
6655 This is a short-hand for marking the subtree and then cutting it."
6656 (interactive "p")
6657 (org-copy-subtree n 'cut))
6659 (defun org-copy-subtree (&optional n cut)
6660 "Cut the current subtree into the clipboard.
6661 With prefix arg N, cut this many sequential subtrees.
6662 This is a short-hand for marking the subtree and then copying it.
6663 If CUT is non-nil, actually cut the subtree."
6664 (interactive "p")
6665 (let (beg end folded (beg0 (point)))
6666 (if (interactive-p)
6667 (org-back-to-heading nil) ; take what looks like a subtree
6668 (org-back-to-heading t)) ; take what is really there
6669 (org-back-over-empty-lines)
6670 (setq beg (point))
6671 (skip-chars-forward " \t\r\n")
6672 (save-match-data
6673 (save-excursion (outline-end-of-heading)
6674 (setq folded (org-invisible-p)))
6675 (condition-case nil
6676 (outline-forward-same-level (1- n))
6677 (error nil))
6678 (org-end-of-subtree t t))
6679 (org-back-over-empty-lines)
6680 (setq end (point))
6681 (goto-char beg0)
6682 (when (> end beg)
6683 (setq org-subtree-clip-folded folded)
6684 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6685 (setq org-subtree-clip (current-kill 0))
6686 (message "%s: Subtree(s) with %d characters"
6687 (if cut "Cut" "Copied")
6688 (length org-subtree-clip)))))
6690 (defun org-paste-subtree (&optional level tree)
6691 "Paste the clipboard as a subtree, with modification of headline level.
6692 The entire subtree is promoted or demoted in order to match a new headline
6693 level. By default, the new level is derived from the visible headings
6694 before and after the insertion point, and taken to be the inferior headline
6695 level of the two. So if the previous visible heading is level 3 and the
6696 next is level 4 (or vice versa), level 4 will be used for insertion.
6697 This makes sure that the subtree remains an independent subtree and does
6698 not swallow low level entries.
6700 You can also force a different level, either by using a numeric prefix
6701 argument, or by inserting the heading marker by hand. For example, if the
6702 cursor is after \"*****\", then the tree will be shifted to level 5.
6704 If you want to insert the tree as is, just use \\[yank].
6706 If optional TREE is given, use this text instead of the kill ring."
6707 (interactive "P")
6708 (unless (org-kill-is-subtree-p tree)
6709 (error "%s"
6710 (substitute-command-keys
6711 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6712 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6713 (^re (concat "^\\(" outline-regexp "\\)"))
6714 (re (concat "\\(" outline-regexp "\\)"))
6715 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6717 (old-level (if (string-match ^re txt)
6718 (- (match-end 0) (match-beginning 0) 1)
6719 -1))
6720 (force-level (cond (level (prefix-numeric-value level))
6721 ((string-match
6722 ^re_ (buffer-substring (point-at-bol) (point)))
6723 (- (match-end 1) (match-beginning 1)))
6724 (t nil)))
6725 (previous-level (save-excursion
6726 (condition-case nil
6727 (progn
6728 (outline-previous-visible-heading 1)
6729 (if (looking-at re)
6730 (- (match-end 0) (match-beginning 0) 1)
6732 (error 1))))
6733 (next-level (save-excursion
6734 (condition-case nil
6735 (progn
6736 (or (looking-at outline-regexp)
6737 (outline-next-visible-heading 1))
6738 (if (looking-at re)
6739 (- (match-end 0) (match-beginning 0) 1)
6741 (error 1))))
6742 (new-level (or force-level (max previous-level next-level)))
6743 (shift (if (or (= old-level -1)
6744 (= new-level -1)
6745 (= old-level new-level))
6747 (- new-level old-level)))
6748 (delta (if (> shift 0) -1 1))
6749 (func (if (> shift 0) 'org-demote 'org-promote))
6750 (org-odd-levels-only nil)
6751 beg end)
6752 ;; Remove the forced level indicator
6753 (if force-level
6754 (delete-region (point-at-bol) (point)))
6755 ;; Paste
6756 (beginning-of-line 1)
6757 (org-back-over-empty-lines) ;; FIXME: correct fix????
6758 (setq beg (point))
6759 (insert-before-markers txt) ;; FIXME: correct fix????
6760 (unless (string-match "\n\\'" txt) (insert "\n"))
6761 (setq end (point))
6762 (goto-char beg)
6763 (skip-chars-forward " \t\n\r")
6764 (setq beg (point))
6765 ;; Shift if necessary
6766 (unless (= shift 0)
6767 (save-restriction
6768 (narrow-to-region beg end)
6769 (while (not (= shift 0))
6770 (org-map-region func (point-min) (point-max))
6771 (setq shift (+ delta shift)))
6772 (goto-char (point-min))))
6773 (when (interactive-p)
6774 (message "Clipboard pasted as level %d subtree" new-level))
6775 (if (and kill-ring
6776 (eq org-subtree-clip (current-kill 0))
6777 org-subtree-clip-folded)
6778 ;; The tree was folded before it was killed/copied
6779 (hide-subtree))))
6781 (defun org-kill-is-subtree-p (&optional txt)
6782 "Check if the current kill is an outline subtree, or a set of trees.
6783 Returns nil if kill does not start with a headline, or if the first
6784 headline level is not the largest headline level in the tree.
6785 So this will actually accept several entries of equal levels as well,
6786 which is OK for `org-paste-subtree'.
6787 If optional TXT is given, check this string instead of the current kill."
6788 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6789 (start-level (and kill
6790 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6791 org-outline-regexp "\\)")
6792 kill)
6793 (- (match-end 2) (match-beginning 2) 1)))
6794 (re (concat "^" org-outline-regexp))
6795 (start (1+ (match-beginning 2))))
6796 (if (not start-level)
6797 (progn
6798 nil) ;; does not even start with a heading
6799 (catch 'exit
6800 (while (setq start (string-match re kill (1+ start)))
6801 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6802 (throw 'exit nil)))
6803 t))))
6805 (defun org-narrow-to-subtree ()
6806 "Narrow buffer to the current subtree."
6807 (interactive)
6808 (save-excursion
6809 (save-match-data
6810 (narrow-to-region
6811 (progn (org-back-to-heading) (point))
6812 (progn (org-end-of-subtree t t) (point))))))
6815 ;;; Outline Sorting
6817 (defun org-sort (with-case)
6818 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6819 Optional argument WITH-CASE means sort case-sensitively."
6820 (interactive "P")
6821 (if (org-at-table-p)
6822 (org-call-with-arg 'org-table-sort-lines with-case)
6823 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6825 (defvar org-priority-regexp) ; defined later in the file
6827 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6828 "Sort entries on a certain level of an outline tree.
6829 If there is an active region, the entries in the region are sorted.
6830 Else, if the cursor is before the first entry, sort the top-level items.
6831 Else, the children of the entry at point are sorted.
6833 Sorting can be alphabetically, numerically, and by date/time as given by
6834 the first time stamp in the entry. The command prompts for the sorting
6835 type unless it has been given to the function through the SORTING-TYPE
6836 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6837 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6838 called with point at the beginning of the record. It must return either
6839 a string or a number that should serve as the sorting key for that record.
6841 Comparing entries ignores case by default. However, with an optional argument
6842 WITH-CASE, the sorting considers case as well."
6843 (interactive "P")
6844 (let ((case-func (if with-case 'identity 'downcase))
6845 start beg end stars re re2
6846 txt what tmp plain-list-p)
6847 ;; Find beginning and end of region to sort
6848 (cond
6849 ((org-region-active-p)
6850 ;; we will sort the region
6851 (setq end (region-end)
6852 what "region")
6853 (goto-char (region-beginning))
6854 (if (not (org-on-heading-p)) (outline-next-heading))
6855 (setq start (point)))
6856 ((org-at-item-p)
6857 ;; we will sort this plain list
6858 (org-beginning-of-item-list) (setq start (point))
6859 (org-end-of-item-list) (setq end (point))
6860 (goto-char start)
6861 (setq plain-list-p t
6862 what "plain list"))
6863 ((or (org-on-heading-p)
6864 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6865 ;; we will sort the children of the current headline
6866 (org-back-to-heading)
6867 (setq start (point)
6868 end (progn (org-end-of-subtree t t)
6869 (org-back-over-empty-lines)
6870 (point))
6871 what "children")
6872 (goto-char start)
6873 (show-subtree)
6874 (outline-next-heading))
6876 ;; we will sort the top-level entries in this file
6877 (goto-char (point-min))
6878 (or (org-on-heading-p) (outline-next-heading))
6879 (setq start (point) end (point-max) what "top-level")
6880 (goto-char start)
6881 (show-all)))
6883 (setq beg (point))
6884 (if (>= beg end) (error "Nothing to sort"))
6886 (unless plain-list-p
6887 (looking-at "\\(\\*+\\)")
6888 (setq stars (match-string 1)
6889 re (concat "^" (regexp-quote stars) " +")
6890 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6891 txt (buffer-substring beg end))
6892 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6893 (if (and (not (equal stars "*")) (string-match re2 txt))
6894 (error "Region to sort contains a level above the first entry")))
6896 (unless sorting-type
6897 (message
6898 (if plain-list-p
6899 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6900 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6901 what)
6902 (setq sorting-type (read-char-exclusive))
6904 (and (= (downcase sorting-type) ?f)
6905 (setq getkey-func
6906 (completing-read "Sort using function: "
6907 obarray 'fboundp t nil nil))
6908 (setq getkey-func (intern getkey-func)))
6910 (and (= (downcase sorting-type) ?r)
6911 (setq property
6912 (completing-read "Property: "
6913 (mapcar 'list (org-buffer-property-keys t))
6914 nil t))))
6916 (message "Sorting entries...")
6918 (save-restriction
6919 (narrow-to-region start end)
6921 (let ((dcst (downcase sorting-type))
6922 (now (current-time)))
6923 (sort-subr
6924 (/= dcst sorting-type)
6925 ;; This function moves to the beginning character of the "record" to
6926 ;; be sorted.
6927 (if plain-list-p
6928 (lambda nil
6929 (if (org-at-item-p) t (goto-char (point-max))))
6930 (lambda nil
6931 (if (re-search-forward re nil t)
6932 (goto-char (match-beginning 0))
6933 (goto-char (point-max)))))
6934 ;; This function moves to the last character of the "record" being
6935 ;; sorted.
6936 (if plain-list-p
6937 'org-end-of-item
6938 (lambda nil
6939 (save-match-data
6940 (condition-case nil
6941 (outline-forward-same-level 1)
6942 (error
6943 (goto-char (point-max)))))))
6945 ;; This function returns the value that gets sorted against.
6946 (if plain-list-p
6947 (lambda nil
6948 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6949 (cond
6950 ((= dcst ?n)
6951 (string-to-number (buffer-substring (match-end 0)
6952 (point-at-eol))))
6953 ((= dcst ?a)
6954 (buffer-substring (match-end 0) (point-at-eol)))
6955 ((= dcst ?t)
6956 (if (re-search-forward org-ts-regexp
6957 (point-at-eol) t)
6958 (org-time-string-to-time (match-string 0))
6959 now))
6960 ((= dcst ?f)
6961 (if getkey-func
6962 (progn
6963 (setq tmp (funcall getkey-func))
6964 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6965 tmp)
6966 (error "Invalid key function `%s'" getkey-func)))
6967 (t (error "Invalid sorting type `%c'" sorting-type)))))
6968 (lambda nil
6969 (cond
6970 ((= dcst ?n)
6971 (if (looking-at outline-regexp)
6972 (string-to-number (buffer-substring (match-end 0)
6973 (point-at-eol)))
6974 nil))
6975 ((= dcst ?a)
6976 (funcall case-func (buffer-substring (point-at-bol)
6977 (point-at-eol))))
6978 ((= dcst ?t)
6979 (if (re-search-forward org-ts-regexp
6980 (save-excursion
6981 (forward-line 2)
6982 (point)) t)
6983 (org-time-string-to-time (match-string 0))
6984 now))
6985 ((= dcst ?p)
6986 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6987 (string-to-char (match-string 2))
6988 org-default-priority))
6989 ((= dcst ?r)
6990 (or (org-entry-get nil property) ""))
6991 ((= dcst ?f)
6992 (if getkey-func
6993 (progn
6994 (setq tmp (funcall getkey-func))
6995 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6996 tmp)
6997 (error "Invalid key function `%s'" getkey-func)))
6998 (t (error "Invalid sorting type `%c'" sorting-type)))))
7000 (cond
7001 ((= dcst ?a) 'string<)
7002 ((= dcst ?t) 'time-less-p)
7003 (t nil)))))
7004 (message "Sorting entries...done")))
7006 (defun org-do-sort (table what &optional with-case sorting-type)
7007 "Sort TABLE of WHAT according to SORTING-TYPE.
7008 The user will be prompted for the SORTING-TYPE if the call to this
7009 function does not specify it. WHAT is only for the prompt, to indicate
7010 what is being sorted. The sorting key will be extracted from
7011 the car of the elements of the table.
7012 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7013 (unless sorting-type
7014 (message
7015 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7016 what)
7017 (setq sorting-type (read-char-exclusive)))
7018 (let ((dcst (downcase sorting-type))
7019 extractfun comparefun)
7020 ;; Define the appropriate functions
7021 (cond
7022 ((= dcst ?n)
7023 (setq extractfun 'string-to-number
7024 comparefun (if (= dcst sorting-type) '< '>)))
7025 ((= dcst ?a)
7026 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7027 (lambda(x) (downcase (org-sort-remove-invisible x))))
7028 comparefun (if (= dcst sorting-type)
7029 'string<
7030 (lambda (a b) (and (not (string< a b))
7031 (not (string= a b)))))))
7032 ((= dcst ?t)
7033 (setq extractfun
7034 (lambda (x)
7035 (if (string-match org-ts-regexp x)
7036 (time-to-seconds
7037 (org-time-string-to-time (match-string 0 x)))
7039 comparefun (if (= dcst sorting-type) '< '>)))
7040 (t (error "Invalid sorting type `%c'" sorting-type)))
7042 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7043 table)
7044 (lambda (a b) (funcall comparefun (car a) (car b))))))
7046 ;;;; Plain list items, including checkboxes
7048 ;;; Plain list items
7050 (defun org-at-item-p ()
7051 "Is point in a line starting a hand-formatted item?"
7052 (let ((llt org-plain-list-ordered-item-terminator))
7053 (save-excursion
7054 (goto-char (point-at-bol))
7055 (looking-at
7056 (cond
7057 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7058 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7059 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7060 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7062 (defun org-in-item-p ()
7063 "It the cursor inside a plain list item.
7064 Does not have to be the first line."
7065 (save-excursion
7066 (condition-case nil
7067 (progn
7068 (org-beginning-of-item)
7069 (org-at-item-p)
7071 (error nil))))
7073 (defun org-insert-item (&optional checkbox)
7074 "Insert a new item at the current level.
7075 Return t when things worked, nil when we are not in an item."
7076 (when (save-excursion
7077 (condition-case nil
7078 (progn
7079 (org-beginning-of-item)
7080 (org-at-item-p)
7081 (if (org-invisible-p) (error "Invisible item"))
7083 (error nil)))
7084 (let* ((bul (match-string 0))
7085 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7086 (match-end 0)))
7087 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7088 pos)
7089 (cond
7090 ((and (org-at-item-p) (<= (point) eow))
7091 ;; before the bullet
7092 (beginning-of-line 1)
7093 (open-line (if blank 2 1)))
7094 ((<= (point) eow)
7095 (beginning-of-line 1))
7097 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7098 (end-of-line 1)
7099 (delete-horizontal-space))
7100 (newline (if blank 2 1))))
7101 (insert bul (if checkbox "[ ]" ""))
7102 (just-one-space)
7103 (setq pos (point))
7104 (end-of-line 1)
7105 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7106 (org-maybe-renumber-ordered-list)
7107 (and checkbox (org-update-checkbox-count-maybe))
7110 ;;; Checkboxes
7112 (defun org-at-item-checkbox-p ()
7113 "Is point at a line starting a plain-list item with a checklet?"
7114 (and (org-at-item-p)
7115 (save-excursion
7116 (goto-char (match-end 0))
7117 (skip-chars-forward " \t")
7118 (looking-at "\\[[- X]\\]"))))
7120 (defun org-toggle-checkbox (&optional arg)
7121 "Toggle the checkbox in the current line."
7122 (interactive "P")
7123 (catch 'exit
7124 (let (beg end status (firstnew 'unknown))
7125 (cond
7126 ((org-region-active-p)
7127 (setq beg (region-beginning) end (region-end)))
7128 ((org-on-heading-p)
7129 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7130 ((org-at-item-checkbox-p)
7131 (let ((pos (point)))
7132 (replace-match
7133 (cond (arg "[-]")
7134 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7135 (t "[ ]"))
7136 t t)
7137 (goto-char pos))
7138 (throw 'exit t))
7139 (t (error "Not at a checkbox or heading, and no active region")))
7140 (save-excursion
7141 (goto-char beg)
7142 (while (< (point) end)
7143 (when (org-at-item-checkbox-p)
7144 (setq status (equal (match-string 0) "[X]"))
7145 (when (eq firstnew 'unknown)
7146 (setq firstnew (not status)))
7147 (replace-match
7148 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7149 (beginning-of-line 2)))))
7150 (org-update-checkbox-count-maybe))
7152 (defun org-update-checkbox-count-maybe ()
7153 "Update checkbox statistics unless turned off by user."
7154 (when org-provide-checkbox-statistics
7155 (org-update-checkbox-count)))
7157 (defun org-update-checkbox-count (&optional all)
7158 "Update the checkbox statistics in the current section.
7159 This will find all statistic cookies like [57%] and [6/12] and update them
7160 with the current numbers. With optional prefix argument ALL, do this for
7161 the whole buffer."
7162 (interactive "P")
7163 (save-excursion
7164 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7165 (beg (condition-case nil
7166 (progn (outline-back-to-heading) (point))
7167 (error (point-min))))
7168 (end (move-marker (make-marker)
7169 (progn (outline-next-heading) (point))))
7170 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7171 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7172 (re-find (concat re "\\|" re-box))
7173 beg-cookie end-cookie is-percent c-on c-off lim
7174 eline curr-ind next-ind continue-from startsearch
7175 (cstat 0)
7177 (when all
7178 (goto-char (point-min))
7179 (outline-next-heading)
7180 (setq beg (point) end (point-max)))
7181 (goto-char end)
7182 ;; find each statistic cookie
7183 (while (re-search-backward re-find beg t)
7184 (setq beg-cookie (match-beginning 1)
7185 end-cookie (match-end 1)
7186 cstat (+ cstat (if end-cookie 1 0))
7187 startsearch (point-at-eol)
7188 continue-from (point-at-bol)
7189 is-percent (match-beginning 2)
7190 lim (cond
7191 ((org-on-heading-p) (outline-next-heading) (point))
7192 ((org-at-item-p) (org-end-of-item) (point))
7193 (t nil))
7194 c-on 0
7195 c-off 0)
7196 (when lim
7197 ;; find first checkbox for this cookie and gather
7198 ;; statistics from all that are at this indentation level
7199 (goto-char startsearch)
7200 (if (re-search-forward re-box lim t)
7201 (progn
7202 (org-beginning-of-item)
7203 (setq curr-ind (org-get-indentation))
7204 (setq next-ind curr-ind)
7205 (while (= curr-ind next-ind)
7206 (save-excursion (end-of-line) (setq eline (point)))
7207 (if (re-search-forward re-box eline t)
7208 (if (member (match-string 2) '("[ ]" "[-]"))
7209 (setq c-off (1+ c-off))
7210 (setq c-on (1+ c-on))
7213 (org-end-of-item)
7214 (setq next-ind (org-get-indentation))
7216 (goto-char continue-from)
7217 ;; update cookie
7218 (when end-cookie
7219 (delete-region beg-cookie end-cookie)
7220 (goto-char beg-cookie)
7221 (insert
7222 (if is-percent
7223 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7224 (format "[%d/%d]" c-on (+ c-on c-off)))))
7225 ;; update items checkbox if it has one
7226 (when (org-at-item-p)
7227 (org-beginning-of-item)
7228 (when (and (> (+ c-on c-off) 0)
7229 (re-search-forward re-box (point-at-eol) t))
7230 (setq beg-cookie (match-beginning 2)
7231 end-cookie (match-end 2))
7232 (delete-region beg-cookie end-cookie)
7233 (goto-char beg-cookie)
7234 (cond ((= c-off 0) (insert "[X]"))
7235 ((= c-on 0) (insert "[ ]"))
7236 (t (insert "[-]")))
7238 (goto-char continue-from))
7239 (when (interactive-p)
7240 (message "Checkbox satistics updated %s (%d places)"
7241 (if all "in entire file" "in current outline entry") cstat)))))
7243 (defun org-get-checkbox-statistics-face ()
7244 "Select the face for checkbox statistics.
7245 The face will be `org-done' when all relevant boxes are checked. Otherwise
7246 it will be `org-todo'."
7247 (if (match-end 1)
7248 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7249 (if (and (> (match-end 2) (match-beginning 2))
7250 (equal (match-string 2) (match-string 3)))
7251 'org-done
7252 'org-todo)))
7254 (defun org-get-indentation (&optional line)
7255 "Get the indentation of the current line, interpreting tabs.
7256 When LINE is given, assume it represents a line and compute its indentation."
7257 (if line
7258 (if (string-match "^ *" (org-remove-tabs line))
7259 (match-end 0))
7260 (save-excursion
7261 (beginning-of-line 1)
7262 (skip-chars-forward " \t")
7263 (current-column))))
7265 (defun org-remove-tabs (s &optional width)
7266 "Replace tabulators in S with spaces.
7267 Assumes that s is a single line, starting in column 0."
7268 (setq width (or width tab-width))
7269 (while (string-match "\t" s)
7270 (setq s (replace-match
7271 (make-string
7272 (- (* width (/ (+ (match-beginning 0) width) width))
7273 (match-beginning 0)) ?\ )
7274 t t s)))
7277 (defun org-fix-indentation (line ind)
7278 "Fix indentation in LINE.
7279 IND is a cons cell with target and minimum indentation.
7280 If the current indenation in LINE is smaller than the minimum,
7281 leave it alone. If it is larger than ind, set it to the target."
7282 (let* ((l (org-remove-tabs line))
7283 (i (org-get-indentation l))
7284 (i1 (car ind)) (i2 (cdr ind)))
7285 (if (>= i i2) (setq l (substring line i2)))
7286 (if (> i1 0)
7287 (concat (make-string i1 ?\ ) l)
7288 l)))
7290 (defcustom org-empty-line-terminates-plain-lists nil
7291 "Non-nil means, an empty line ends all plain list levels.
7292 When nil, empty lines are part of the preceeding item."
7293 :group 'org-plain-lists
7294 :type 'boolean)
7296 (defun org-beginning-of-item ()
7297 "Go to the beginning of the current hand-formatted item.
7298 If the cursor is not in an item, throw an error."
7299 (interactive)
7300 (let ((pos (point))
7301 (limit (save-excursion
7302 (condition-case nil
7303 (progn
7304 (org-back-to-heading)
7305 (beginning-of-line 2) (point))
7306 (error (point-min)))))
7307 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7308 ind ind1)
7309 (if (org-at-item-p)
7310 (beginning-of-line 1)
7311 (beginning-of-line 1)
7312 (skip-chars-forward " \t")
7313 (setq ind (current-column))
7314 (if (catch 'exit
7315 (while t
7316 (beginning-of-line 0)
7317 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7319 (if (looking-at "[ \t]*$")
7320 (setq ind1 ind-empty)
7321 (skip-chars-forward " \t")
7322 (setq ind1 (current-column)))
7323 (if (< ind1 ind)
7324 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7326 (goto-char pos)
7327 (error "Not in an item")))))
7329 (defun org-end-of-item ()
7330 "Go to the end of the current hand-formatted item.
7331 If the cursor is not in an item, throw an error."
7332 (interactive)
7333 (let* ((pos (point))
7334 ind1
7335 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7336 (limit (save-excursion (outline-next-heading) (point)))
7337 (ind (save-excursion
7338 (org-beginning-of-item)
7339 (skip-chars-forward " \t")
7340 (current-column)))
7341 (end (catch 'exit
7342 (while t
7343 (beginning-of-line 2)
7344 (if (eobp) (throw 'exit (point)))
7345 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7346 (if (looking-at "[ \t]*$")
7347 (setq ind1 ind-empty)
7348 (skip-chars-forward " \t")
7349 (setq ind1 (current-column)))
7350 (if (<= ind1 ind)
7351 (throw 'exit (point-at-bol)))))))
7352 (if end
7353 (goto-char end)
7354 (goto-char pos)
7355 (error "Not in an item"))))
7357 (defun org-next-item ()
7358 "Move to the beginning of the next item in the current plain list.
7359 Error if not at a plain list, or if this is the last item in the list."
7360 (interactive)
7361 (let (ind ind1 (pos (point)))
7362 (org-beginning-of-item)
7363 (setq ind (org-get-indentation))
7364 (org-end-of-item)
7365 (setq ind1 (org-get-indentation))
7366 (unless (and (org-at-item-p) (= ind ind1))
7367 (goto-char pos)
7368 (error "On last item"))))
7370 (defun org-previous-item ()
7371 "Move to the beginning of the previous item in the current plain list.
7372 Error if not at a plain list, or if this is the first item in the list."
7373 (interactive)
7374 (let (beg ind ind1 (pos (point)))
7375 (org-beginning-of-item)
7376 (setq beg (point))
7377 (setq ind (org-get-indentation))
7378 (goto-char beg)
7379 (catch 'exit
7380 (while t
7381 (beginning-of-line 0)
7382 (if (looking-at "[ \t]*$")
7384 (if (<= (setq ind1 (org-get-indentation)) ind)
7385 (throw 'exit t)))))
7386 (condition-case nil
7387 (if (or (not (org-at-item-p))
7388 (< ind1 (1- ind)))
7389 (error "")
7390 (org-beginning-of-item))
7391 (error (goto-char pos)
7392 (error "On first item")))))
7394 (defun org-first-list-item-p ()
7395 "Is this heading the item in a plain list?"
7396 (unless (org-at-item-p)
7397 (error "Not at a plain list item"))
7398 (org-beginning-of-item)
7399 (= (point) (save-excursion (org-beginning-of-item-list))))
7401 (defun org-move-item-down ()
7402 "Move the plain list item at point down, i.e. swap with following item.
7403 Subitems (items with larger indentation) are considered part of the item,
7404 so this really moves item trees."
7405 (interactive)
7406 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7407 (org-beginning-of-item)
7408 (setq beg0 (point))
7409 (save-excursion
7410 (setq ne-beg (org-back-over-empty-lines))
7411 (setq beg (point)))
7412 (goto-char beg0)
7413 (setq ind (org-get-indentation))
7414 (org-end-of-item)
7415 (setq end0 (point))
7416 (setq ind1 (org-get-indentation))
7417 (setq ne-end (org-back-over-empty-lines))
7418 (setq end (point))
7419 (goto-char beg0)
7420 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7421 ;; include less whitespace
7422 (save-excursion
7423 (goto-char beg)
7424 (forward-line (- ne-beg ne-end))
7425 (setq beg (point))))
7426 (goto-char end0)
7427 (if (and (org-at-item-p) (= ind ind1))
7428 (progn
7429 (org-end-of-item)
7430 (org-back-over-empty-lines)
7431 (setq txt (buffer-substring beg end))
7432 (save-excursion
7433 (delete-region beg end))
7434 (setq pos (point))
7435 (insert txt)
7436 (goto-char pos) (org-skip-whitespace)
7437 (org-maybe-renumber-ordered-list))
7438 (goto-char pos)
7439 (error "Cannot move this item further down"))))
7441 (defun org-move-item-up (arg)
7442 "Move the plain list item at point up, i.e. swap with previous item.
7443 Subitems (items with larger indentation) are considered part of the item,
7444 so this really moves item trees."
7445 (interactive "p")
7446 (let (beg beg0 end ind ind1 (pos (point)) txt
7447 ne-beg ne-ins ins-end)
7448 (org-beginning-of-item)
7449 (setq beg0 (point))
7450 (setq ind (org-get-indentation))
7451 (save-excursion
7452 (setq ne-beg (org-back-over-empty-lines))
7453 (setq beg (point)))
7454 (goto-char beg0)
7455 (org-end-of-item)
7456 (setq end (point))
7457 (goto-char beg0)
7458 (catch 'exit
7459 (while t
7460 (beginning-of-line 0)
7461 (if (looking-at "[ \t]*$")
7462 (if org-empty-line-terminates-plain-lists
7463 (progn
7464 (goto-char pos)
7465 (error "Cannot move this item further up"))
7466 nil)
7467 (if (<= (setq ind1 (org-get-indentation)) ind)
7468 (throw 'exit t)))))
7469 (condition-case nil
7470 (org-beginning-of-item)
7471 (error (goto-char beg)
7472 (error "Cannot move this item further up")))
7473 (setq ind1 (org-get-indentation))
7474 (if (and (org-at-item-p) (= ind ind1))
7475 (progn
7476 (setq ne-ins (org-back-over-empty-lines))
7477 (setq txt (buffer-substring beg end))
7478 (save-excursion
7479 (delete-region beg end))
7480 (setq pos (point))
7481 (insert txt)
7482 (setq ins-end (point))
7483 (goto-char pos) (org-skip-whitespace)
7485 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7486 ;; Move whitespace back to beginning
7487 (save-excursion
7488 (goto-char ins-end)
7489 (let ((kill-whole-line t))
7490 (kill-line (- ne-ins ne-beg)) (point)))
7491 (insert (make-string (- ne-ins ne-beg) ?\n)))
7493 (org-maybe-renumber-ordered-list))
7494 (goto-char pos)
7495 (error "Cannot move this item further up"))))
7497 (defun org-maybe-renumber-ordered-list ()
7498 "Renumber the ordered list at point if setup allows it.
7499 This tests the user option `org-auto-renumber-ordered-lists' before
7500 doing the renumbering."
7501 (interactive)
7502 (when (and org-auto-renumber-ordered-lists
7503 (org-at-item-p))
7504 (if (match-beginning 3)
7505 (org-renumber-ordered-list 1)
7506 (org-fix-bullet-type))))
7508 (defun org-maybe-renumber-ordered-list-safe ()
7509 (condition-case nil
7510 (save-excursion
7511 (org-maybe-renumber-ordered-list))
7512 (error nil)))
7514 (defun org-cycle-list-bullet (&optional which)
7515 "Cycle through the different itemize/enumerate bullets.
7516 This cycle the entire list level through the sequence:
7518 `-' -> `+' -> `*' -> `1.' -> `1)'
7520 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7521 0 meand `-', 1 means `+' etc."
7522 (interactive "P")
7523 (org-preserve-lc
7524 (org-beginning-of-item-list)
7525 (org-at-item-p)
7526 (beginning-of-line 1)
7527 (let ((current (match-string 0))
7528 (prevp (eq which 'previous))
7529 new)
7530 (setq new (cond
7531 ((and (numberp which)
7532 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7533 ((string-match "-" current) (if prevp "1)" "+"))
7534 ((string-match "\\+" current)
7535 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7536 ((string-match "\\*" current) (if prevp "+" "1."))
7537 ((string-match "\\." current) (if prevp "*" "1)"))
7538 ((string-match ")" current) (if prevp "1." "-"))
7539 (t (error "This should not happen"))))
7540 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7541 (org-fix-bullet-type)
7542 (org-maybe-renumber-ordered-list))))
7544 (defun org-get-string-indentation (s)
7545 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7546 (let ((n -1) (i 0) (w tab-width) c)
7547 (catch 'exit
7548 (while (< (setq n (1+ n)) (length s))
7549 (setq c (aref s n))
7550 (cond ((= c ?\ ) (setq i (1+ i)))
7551 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7552 (t (throw 'exit t)))))
7555 (defun org-renumber-ordered-list (arg)
7556 "Renumber an ordered plain list.
7557 Cursor needs to be in the first line of an item, the line that starts
7558 with something like \"1.\" or \"2)\"."
7559 (interactive "p")
7560 (unless (and (org-at-item-p)
7561 (match-beginning 3))
7562 (error "This is not an ordered list"))
7563 (let ((line (org-current-line))
7564 (col (current-column))
7565 (ind (org-get-string-indentation
7566 (buffer-substring (point-at-bol) (match-beginning 3))))
7567 ;; (term (substring (match-string 3) -1))
7568 ind1 (n (1- arg))
7569 fmt)
7570 ;; find where this list begins
7571 (org-beginning-of-item-list)
7572 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7573 (setq fmt (concat "%d" (match-string 1)))
7574 (beginning-of-line 0)
7575 ;; walk forward and replace these numbers
7576 (catch 'exit
7577 (while t
7578 (catch 'next
7579 (beginning-of-line 2)
7580 (if (eobp) (throw 'exit nil))
7581 (if (looking-at "[ \t]*$") (throw 'next nil))
7582 (skip-chars-forward " \t") (setq ind1 (current-column))
7583 (if (> ind1 ind) (throw 'next t))
7584 (if (< ind1 ind) (throw 'exit t))
7585 (if (not (org-at-item-p)) (throw 'exit nil))
7586 (delete-region (match-beginning 2) (match-end 2))
7587 (goto-char (match-beginning 2))
7588 (insert (format fmt (setq n (1+ n)))))))
7589 (goto-line line)
7590 (move-to-column col)))
7592 (defun org-fix-bullet-type ()
7593 "Make sure all items in this list have the same bullet as the firsst item."
7594 (interactive)
7595 (unless (org-at-item-p) (error "This is not a list"))
7596 (let ((line (org-current-line))
7597 (col (current-column))
7598 (ind (current-indentation))
7599 ind1 bullet)
7600 ;; find where this list begins
7601 (org-beginning-of-item-list)
7602 (beginning-of-line 1)
7603 ;; find out what the bullet type is
7604 (looking-at "[ \t]*\\(\\S-+\\)")
7605 (setq bullet (match-string 1))
7606 ;; walk forward and replace these numbers
7607 (beginning-of-line 0)
7608 (catch 'exit
7609 (while t
7610 (catch 'next
7611 (beginning-of-line 2)
7612 (if (eobp) (throw 'exit nil))
7613 (if (looking-at "[ \t]*$") (throw 'next nil))
7614 (skip-chars-forward " \t") (setq ind1 (current-column))
7615 (if (> ind1 ind) (throw 'next t))
7616 (if (< ind1 ind) (throw 'exit t))
7617 (if (not (org-at-item-p)) (throw 'exit nil))
7618 (skip-chars-forward " \t")
7619 (looking-at "\\S-+")
7620 (replace-match bullet))))
7621 (goto-line line)
7622 (move-to-column col)
7623 (if (string-match "[0-9]" bullet)
7624 (org-renumber-ordered-list 1))))
7626 (defun org-beginning-of-item-list ()
7627 "Go to the beginning of the current item list.
7628 I.e. to the first item in this list."
7629 (interactive)
7630 (org-beginning-of-item)
7631 (let ((pos (point-at-bol))
7632 (ind (org-get-indentation))
7633 ind1)
7634 ;; find where this list begins
7635 (catch 'exit
7636 (while t
7637 (catch 'next
7638 (beginning-of-line 0)
7639 (if (looking-at "[ \t]*$")
7640 (throw (if (bobp) 'exit 'next) t))
7641 (skip-chars-forward " \t") (setq ind1 (current-column))
7642 (if (or (< ind1 ind)
7643 (and (= ind1 ind)
7644 (not (org-at-item-p)))
7645 (bobp))
7646 (throw 'exit t)
7647 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7648 (goto-char pos)))
7651 (defun org-end-of-item-list ()
7652 "Go to the end of the current item list.
7653 I.e. to the text after the last item."
7654 (interactive)
7655 (org-beginning-of-item)
7656 (let ((pos (point-at-bol))
7657 (ind (org-get-indentation))
7658 ind1)
7659 ;; find where this list begins
7660 (catch 'exit
7661 (while t
7662 (catch 'next
7663 (beginning-of-line 2)
7664 (if (looking-at "[ \t]*$")
7665 (throw (if (eobp) 'exit 'next) t))
7666 (skip-chars-forward " \t") (setq ind1 (current-column))
7667 (if (or (< ind1 ind)
7668 (and (= ind1 ind)
7669 (not (org-at-item-p)))
7670 (eobp))
7671 (progn
7672 (setq pos (point-at-bol))
7673 (throw 'exit t))))))
7674 (goto-char pos)))
7677 (defvar org-last-indent-begin-marker (make-marker))
7678 (defvar org-last-indent-end-marker (make-marker))
7680 (defun org-outdent-item (arg)
7681 "Outdent a local list item."
7682 (interactive "p")
7683 (org-indent-item (- arg)))
7685 (defun org-indent-item (arg)
7686 "Indent a local list item."
7687 (interactive "p")
7688 (unless (org-at-item-p)
7689 (error "Not on an item"))
7690 (save-excursion
7691 (let (beg end ind ind1 tmp delta ind-down ind-up)
7692 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7693 (setq beg org-last-indent-begin-marker
7694 end org-last-indent-end-marker)
7695 (org-beginning-of-item)
7696 (setq beg (move-marker org-last-indent-begin-marker (point)))
7697 (org-end-of-item)
7698 (setq end (move-marker org-last-indent-end-marker (point))))
7699 (goto-char beg)
7700 (setq tmp (org-item-indent-positions)
7701 ind (car tmp)
7702 ind-down (nth 2 tmp)
7703 ind-up (nth 1 tmp)
7704 delta (if (> arg 0)
7705 (if ind-down (- ind-down ind) 2)
7706 (if ind-up (- ind-up ind) -2)))
7707 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7708 (while (< (point) end)
7709 (beginning-of-line 1)
7710 (skip-chars-forward " \t") (setq ind1 (current-column))
7711 (delete-region (point-at-bol) (point))
7712 (or (eolp) (indent-to-column (+ ind1 delta)))
7713 (beginning-of-line 2))))
7714 (org-fix-bullet-type)
7715 (org-maybe-renumber-ordered-list-safe)
7716 (save-excursion
7717 (beginning-of-line 0)
7718 (condition-case nil (org-beginning-of-item) (error nil))
7719 (org-maybe-renumber-ordered-list-safe)))
7721 (defun org-item-indent-positions ()
7722 "Return indentation for plain list items.
7723 This returns a list with three values: The current indentation, the
7724 parent indentation and the indentation a child should habe.
7725 Assumes cursor in item line."
7726 (let* ((bolpos (point-at-bol))
7727 (ind (org-get-indentation))
7728 ind-down ind-up pos)
7729 (save-excursion
7730 (org-beginning-of-item-list)
7731 (skip-chars-backward "\n\r \t")
7732 (when (org-in-item-p)
7733 (org-beginning-of-item)
7734 (setq ind-up (org-get-indentation))))
7735 (setq pos (point))
7736 (save-excursion
7737 (cond
7738 ((and (condition-case nil (progn (org-previous-item) t)
7739 (error nil))
7740 (or (forward-char 1) t)
7741 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7742 (setq ind-down (org-get-indentation)))
7743 ((and (goto-char pos)
7744 (org-at-item-p))
7745 (goto-char (match-end 0))
7746 (skip-chars-forward " \t")
7747 (setq ind-down (current-column)))))
7748 (list ind ind-up ind-down)))
7750 ;;; The orgstruct minor mode
7752 ;; Define a minor mode which can be used in other modes in order to
7753 ;; integrate the org-mode structure editing commands.
7755 ;; This is really a hack, because the org-mode structure commands use
7756 ;; keys which normally belong to the major mode. Here is how it
7757 ;; works: The minor mode defines all the keys necessary to operate the
7758 ;; structure commands, but wraps the commands into a function which
7759 ;; tests if the cursor is currently at a headline or a plain list
7760 ;; item. If that is the case, the structure command is used,
7761 ;; temporarily setting many Org-mode variables like regular
7762 ;; expressions for filling etc. However, when any of those keys is
7763 ;; used at a different location, function uses `key-binding' to look
7764 ;; up if the key has an associated command in another currently active
7765 ;; keymap (minor modes, major mode, global), and executes that
7766 ;; command. There might be problems if any of the keys is otherwise
7767 ;; used as a prefix key.
7769 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7770 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7771 ;; addresses this by checking explicitly for both bindings.
7773 (defvar orgstruct-mode-map (make-sparse-keymap)
7774 "Keymap for the minor `orgstruct-mode'.")
7776 (defvar org-local-vars nil
7777 "List of local variables, for use by `orgstruct-mode'")
7779 ;;;###autoload
7780 (define-minor-mode orgstruct-mode
7781 "Toggle the minor more `orgstruct-mode'.
7782 This mode is for using Org-mode structure commands in other modes.
7783 The following key behave as if Org-mode was active, if the cursor
7784 is on a headline, or on a plain list item (both in the definition
7785 of Org-mode).
7787 M-up Move entry/item up
7788 M-down Move entry/item down
7789 M-left Promote
7790 M-right Demote
7791 M-S-up Move entry/item up
7792 M-S-down Move entry/item down
7793 M-S-left Promote subtree
7794 M-S-right Demote subtree
7795 M-q Fill paragraph and items like in Org-mode
7796 C-c ^ Sort entries
7797 C-c - Cycle list bullet
7798 TAB Cycle item visibility
7799 M-RET Insert new heading/item
7800 S-M-RET Insert new TODO heading / Chekbox item
7801 C-c C-c Set tags / toggle checkbox"
7802 nil " OrgStruct" nil
7803 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7805 ;;;###autoload
7806 (defun turn-on-orgstruct ()
7807 "Unconditionally turn on `orgstruct-mode'."
7808 (orgstruct-mode 1))
7810 ;;;###autoload
7811 (defun turn-on-orgstruct++ ()
7812 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7813 In addition to setting orgstruct-mode, this also exports all indentation and
7814 autofilling variables from org-mode into the buffer. Note that turning
7815 off orgstruct-mode will *not* remove these additional settings."
7816 (orgstruct-mode 1)
7817 (let (var val)
7818 (mapc
7819 (lambda (x)
7820 (when (string-match
7821 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7822 (symbol-name (car x)))
7823 (setq var (car x) val (nth 1 x))
7824 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7825 org-local-vars)))
7827 (defun orgstruct-error ()
7828 "Error when there is no default binding for a structure key."
7829 (interactive)
7830 (error "This key has no function outside structure elements"))
7832 (defun orgstruct-setup ()
7833 "Setup orgstruct keymaps."
7834 (let ((nfunc 0)
7835 (bindings
7836 (list
7837 '([(meta up)] org-metaup)
7838 '([(meta down)] org-metadown)
7839 '([(meta left)] org-metaleft)
7840 '([(meta right)] org-metaright)
7841 '([(meta shift up)] org-shiftmetaup)
7842 '([(meta shift down)] org-shiftmetadown)
7843 '([(meta shift left)] org-shiftmetaleft)
7844 '([(meta shift right)] org-shiftmetaright)
7845 '([(shift up)] org-shiftup)
7846 '([(shift down)] org-shiftdown)
7847 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7848 '("\M-q" fill-paragraph)
7849 '("\C-c^" org-sort)
7850 '("\C-c-" org-cycle-list-bullet)))
7851 elt key fun cmd)
7852 (while (setq elt (pop bindings))
7853 (setq nfunc (1+ nfunc))
7854 (setq key (org-key (car elt))
7855 fun (nth 1 elt)
7856 cmd (orgstruct-make-binding fun nfunc key))
7857 (org-defkey orgstruct-mode-map key cmd))
7859 ;; Special treatment needed for TAB and RET
7860 (org-defkey orgstruct-mode-map [(tab)]
7861 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7862 (org-defkey orgstruct-mode-map "\C-i"
7863 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7865 (org-defkey orgstruct-mode-map "\M-\C-m"
7866 (orgstruct-make-binding 'org-insert-heading 105
7867 "\M-\C-m" [(meta return)]))
7868 (org-defkey orgstruct-mode-map [(meta return)]
7869 (orgstruct-make-binding 'org-insert-heading 106
7870 [(meta return)] "\M-\C-m"))
7872 (org-defkey orgstruct-mode-map [(shift meta return)]
7873 (orgstruct-make-binding 'org-insert-todo-heading 107
7874 [(meta return)] "\M-\C-m"))
7876 (unless org-local-vars
7877 (setq org-local-vars (org-get-local-variables)))
7881 (defun orgstruct-make-binding (fun n &rest keys)
7882 "Create a function for binding in the structure minor mode.
7883 FUN is the command to call inside a table. N is used to create a unique
7884 command name. KEYS are keys that should be checked in for a command
7885 to execute outside of tables."
7886 (eval
7887 (list 'defun
7888 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7889 '(arg)
7890 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7891 "Outside of structure, run the binding of `"
7892 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7893 "'.")
7894 '(interactive "p")
7895 (list 'if
7896 '(org-context-p 'headline 'item)
7897 (list 'org-run-like-in-org-mode (list 'quote fun))
7898 (list 'let '(orgstruct-mode)
7899 (list 'call-interactively
7900 (append '(or)
7901 (mapcar (lambda (k)
7902 (list 'key-binding k))
7903 keys)
7904 '('orgstruct-error))))))))
7906 (defun org-context-p (&rest contexts)
7907 "Check if local context is and of CONTEXTS.
7908 Possible values in the list of contexts are `table', `headline', and `item'."
7909 (let ((pos (point)))
7910 (goto-char (point-at-bol))
7911 (prog1 (or (and (memq 'table contexts)
7912 (looking-at "[ \t]*|"))
7913 (and (memq 'headline contexts)
7914 (looking-at "\\*+"))
7915 (and (memq 'item contexts)
7916 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7917 (goto-char pos))))
7919 (defun org-get-local-variables ()
7920 "Return a list of all local variables in an org-mode buffer."
7921 (let (varlist)
7922 (with-current-buffer (get-buffer-create "*Org tmp*")
7923 (erase-buffer)
7924 (org-mode)
7925 (setq varlist (buffer-local-variables)))
7926 (kill-buffer "*Org tmp*")
7927 (delq nil
7928 (mapcar
7929 (lambda (x)
7930 (setq x
7931 (if (symbolp x)
7932 (list x)
7933 (list (car x) (list 'quote (cdr x)))))
7934 (if (string-match
7935 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7936 (symbol-name (car x)))
7937 x nil))
7938 varlist))))
7940 ;;;###autoload
7941 (defun org-run-like-in-org-mode (cmd)
7942 (unless org-local-vars
7943 (setq org-local-vars (org-get-local-variables)))
7944 (eval (list 'let org-local-vars
7945 (list 'call-interactively (list 'quote cmd)))))
7947 ;;;; Archiving
7949 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7951 (defun org-archive-subtree (&optional find-done)
7952 "Move the current subtree to the archive.
7953 The archive can be a certain top-level heading in the current file, or in
7954 a different file. The tree will be moved to that location, the subtree
7955 heading be marked DONE, and the current time will be added.
7957 When called with prefix argument FIND-DONE, find whole trees without any
7958 open TODO items and archive them (after getting confirmation from the user).
7959 If the cursor is not at a headline when this comand is called, try all level
7960 1 trees. If the cursor is on a headline, only try the direct children of
7961 this heading."
7962 (interactive "P")
7963 (if find-done
7964 (org-archive-all-done)
7965 ;; Save all relevant TODO keyword-relatex variables
7967 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7968 (tr-org-todo-keywords-1 org-todo-keywords-1)
7969 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7970 (tr-org-done-keywords org-done-keywords)
7971 (tr-org-todo-regexp org-todo-regexp)
7972 (tr-org-todo-line-regexp org-todo-line-regexp)
7973 (tr-org-odd-levels-only org-odd-levels-only)
7974 (this-buffer (current-buffer))
7975 (org-archive-location org-archive-location)
7976 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7977 ;; start of variables that will be used for saving context
7978 ;; The compiler complains about them - keep them anyway!
7979 (file (abbreviate-file-name (buffer-file-name)))
7980 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7981 (time (format-time-string
7982 (substring (cdr org-time-stamp-formats) 1 -1)
7983 (current-time)))
7984 afile heading buffer level newfile-p
7985 category todo priority
7986 ;; start of variables that will be used for savind context
7987 ltags itags prop)
7989 ;; Try to find a local archive location
7990 (save-excursion
7991 (save-restriction
7992 (widen)
7993 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7994 (if (and prop (string-match "\\S-" prop))
7995 (setq org-archive-location prop)
7996 (if (or (re-search-backward re nil t)
7997 (re-search-forward re nil t))
7998 (setq org-archive-location (match-string 1))))))
8000 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8001 (progn
8002 (setq afile (format (match-string 1 org-archive-location)
8003 (file-name-nondirectory buffer-file-name))
8004 heading (match-string 2 org-archive-location)))
8005 (error "Invalid `org-archive-location'"))
8006 (if (> (length afile) 0)
8007 (setq newfile-p (not (file-exists-p afile))
8008 buffer (find-file-noselect afile))
8009 (setq buffer (current-buffer)))
8010 (unless buffer
8011 (error "Cannot access file \"%s\"" afile))
8012 (if (and (> (length heading) 0)
8013 (string-match "^\\*+" heading))
8014 (setq level (match-end 0))
8015 (setq heading nil level 0))
8016 (save-excursion
8017 (org-back-to-heading t)
8018 ;; Get context information that will be lost by moving the tree
8019 (org-refresh-category-properties)
8020 (setq category (org-get-category)
8021 todo (and (looking-at org-todo-line-regexp)
8022 (match-string 2))
8023 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8024 ltags (org-get-tags)
8025 itags (org-delete-all ltags (org-get-tags-at)))
8026 (setq ltags (mapconcat 'identity ltags " ")
8027 itags (mapconcat 'identity itags " "))
8028 ;; We first only copy, in case something goes wrong
8029 ;; we need to protect this-command, to avoid kill-region sets it,
8030 ;; which would lead to duplication of subtrees
8031 (let (this-command) (org-copy-subtree))
8032 (set-buffer buffer)
8033 ;; Enforce org-mode for the archive buffer
8034 (if (not (org-mode-p))
8035 ;; Force the mode for future visits.
8036 (let ((org-insert-mode-line-in-empty-file t)
8037 (org-inhibit-startup t))
8038 (call-interactively 'org-mode)))
8039 (when newfile-p
8040 (goto-char (point-max))
8041 (insert (format "\nArchived entries from file %s\n\n"
8042 (buffer-file-name this-buffer))))
8043 ;; Force the TODO keywords of the original buffer
8044 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8045 (org-todo-keywords-1 tr-org-todo-keywords-1)
8046 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8047 (org-done-keywords tr-org-done-keywords)
8048 (org-todo-regexp tr-org-todo-regexp)
8049 (org-todo-line-regexp tr-org-todo-line-regexp)
8050 (org-odd-levels-only
8051 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8052 org-odd-levels-only
8053 tr-org-odd-levels-only)))
8054 (goto-char (point-min))
8055 (show-all)
8056 (if heading
8057 (progn
8058 (if (re-search-forward
8059 (concat "^" (regexp-quote heading)
8060 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8061 nil t)
8062 (goto-char (match-end 0))
8063 ;; Heading not found, just insert it at the end
8064 (goto-char (point-max))
8065 (or (bolp) (insert "\n"))
8066 (insert "\n" heading "\n")
8067 (end-of-line 0))
8068 ;; Make the subtree visible
8069 (show-subtree)
8070 (org-end-of-subtree t)
8071 (skip-chars-backward " \t\r\n")
8072 (and (looking-at "[ \t\r\n]*")
8073 (replace-match "\n\n")))
8074 ;; No specific heading, just go to end of file.
8075 (goto-char (point-max)) (insert "\n"))
8076 ;; Paste
8077 (org-paste-subtree (org-get-legal-level level 1))
8079 ;; Mark the entry as done
8080 (when (and org-archive-mark-done
8081 (looking-at org-todo-line-regexp)
8082 (or (not (match-end 2))
8083 (not (member (match-string 2) org-done-keywords))))
8084 (let (org-log-done org-todo-log-states)
8085 (org-todo
8086 (car (or (member org-archive-mark-done org-done-keywords)
8087 org-done-keywords)))))
8089 ;; Add the context info
8090 (when org-archive-save-context-info
8091 (let ((l org-archive-save-context-info) e n v)
8092 (while (setq e (pop l))
8093 (when (and (setq v (symbol-value e))
8094 (stringp v) (string-match "\\S-" v))
8095 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8096 (org-entry-put (point) n v)))))
8098 ;; Save and kill the buffer, if it is not the same buffer.
8099 (if (not (eq this-buffer buffer))
8100 (progn (save-buffer) (kill-buffer buffer)))))
8101 ;; Here we are back in the original buffer. Everything seems to have
8102 ;; worked. So now cut the tree and finish up.
8103 (let (this-command) (org-cut-subtree))
8104 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8105 (message "Subtree archived %s"
8106 (if (eq this-buffer buffer)
8107 (concat "under heading: " heading)
8108 (concat "in file: " (abbreviate-file-name afile)))))))
8110 (defun org-refresh-category-properties ()
8111 "Refresh category text properties in teh buffer."
8112 (let ((def-cat (cond
8113 ((null org-category)
8114 (if buffer-file-name
8115 (file-name-sans-extension
8116 (file-name-nondirectory buffer-file-name))
8117 "???"))
8118 ((symbolp org-category) (symbol-name org-category))
8119 (t org-category)))
8120 beg end cat pos optionp)
8121 (org-unmodified
8122 (save-excursion
8123 (save-restriction
8124 (widen)
8125 (goto-char (point-min))
8126 (put-text-property (point) (point-max) 'org-category def-cat)
8127 (while (re-search-forward
8128 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8129 (setq pos (match-end 0)
8130 optionp (equal (char-after (match-beginning 0)) ?#)
8131 cat (org-trim (match-string 2)))
8132 (if optionp
8133 (setq beg (point-at-bol) end (point-max))
8134 (org-back-to-heading t)
8135 (setq beg (point) end (org-end-of-subtree t t)))
8136 (put-text-property beg end 'org-category cat)
8137 (goto-char pos)))))))
8139 (defun org-archive-all-done (&optional tag)
8140 "Archive sublevels of the current tree without open TODO items.
8141 If the cursor is not on a headline, try all level 1 trees. If
8142 it is on a headline, try all direct children.
8143 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8144 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8145 (rea (concat ".*:" org-archive-tag ":"))
8146 (begm (make-marker))
8147 (endm (make-marker))
8148 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8149 "Move subtree to archive (no open TODO items)? "))
8150 beg end (cntarch 0))
8151 (if (org-on-heading-p)
8152 (progn
8153 (setq re1 (concat "^" (regexp-quote
8154 (make-string
8155 (1+ (- (match-end 0) (match-beginning 0) 1))
8156 ?*))
8157 " "))
8158 (move-marker begm (point))
8159 (move-marker endm (org-end-of-subtree t)))
8160 (setq re1 "^* ")
8161 (move-marker begm (point-min))
8162 (move-marker endm (point-max)))
8163 (save-excursion
8164 (goto-char begm)
8165 (while (re-search-forward re1 endm t)
8166 (setq beg (match-beginning 0)
8167 end (save-excursion (org-end-of-subtree t) (point)))
8168 (goto-char beg)
8169 (if (re-search-forward re end t)
8170 (goto-char end)
8171 (goto-char beg)
8172 (if (and (or (not tag) (not (looking-at rea)))
8173 (y-or-n-p question))
8174 (progn
8175 (if tag
8176 (org-toggle-tag org-archive-tag 'on)
8177 (org-archive-subtree))
8178 (setq cntarch (1+ cntarch)))
8179 (goto-char end)))))
8180 (message "%d trees archived" cntarch)))
8182 (defun org-cycle-hide-drawers (state)
8183 "Re-hide all drawers after a visibility state change."
8184 (when (and (org-mode-p)
8185 (not (memq state '(overview folded))))
8186 (save-excursion
8187 (let* ((globalp (memq state '(contents all)))
8188 (beg (if globalp (point-min) (point)))
8189 (end (if globalp (point-max) (org-end-of-subtree t))))
8190 (goto-char beg)
8191 (while (re-search-forward org-drawer-regexp end t)
8192 (org-flag-drawer t))))))
8194 (defun org-flag-drawer (flag)
8195 (save-excursion
8196 (beginning-of-line 1)
8197 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8198 (let ((b (match-end 0))
8199 (outline-regexp org-outline-regexp))
8200 (if (re-search-forward
8201 "^[ \t]*:END:"
8202 (save-excursion (outline-next-heading) (point)) t)
8203 (outline-flag-region b (point-at-eol) flag)
8204 (error ":END: line missing"))))))
8206 (defun org-cycle-hide-archived-subtrees (state)
8207 "Re-hide all archived subtrees after a visibility state change."
8208 (when (and (not org-cycle-open-archived-trees)
8209 (not (memq state '(overview folded))))
8210 (save-excursion
8211 (let* ((globalp (memq state '(contents all)))
8212 (beg (if globalp (point-min) (point)))
8213 (end (if globalp (point-max) (org-end-of-subtree t))))
8214 (org-hide-archived-subtrees beg end)
8215 (goto-char beg)
8216 (if (looking-at (concat ".*:" org-archive-tag ":"))
8217 (message "%s" (substitute-command-keys
8218 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8220 (defun org-force-cycle-archived ()
8221 "Cycle subtree even if it is archived."
8222 (interactive)
8223 (setq this-command 'org-cycle)
8224 (let ((org-cycle-open-archived-trees t))
8225 (call-interactively 'org-cycle)))
8227 (defun org-hide-archived-subtrees (beg end)
8228 "Re-hide all archived subtrees after a visibility state change."
8229 (save-excursion
8230 (let* ((re (concat ":" org-archive-tag ":")))
8231 (goto-char beg)
8232 (while (re-search-forward re end t)
8233 (and (org-on-heading-p) (hide-subtree))
8234 (org-end-of-subtree t)))))
8236 (defun org-toggle-tag (tag &optional onoff)
8237 "Toggle the tag TAG for the current line.
8238 If ONOFF is `on' or `off', don't toggle but set to this state."
8239 (unless (org-on-heading-p t) (error "Not on headling"))
8240 (let (res current)
8241 (save-excursion
8242 (beginning-of-line)
8243 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8244 (point-at-eol) t)
8245 (progn
8246 (setq current (match-string 1))
8247 (replace-match ""))
8248 (setq current ""))
8249 (setq current (nreverse (org-split-string current ":")))
8250 (cond
8251 ((eq onoff 'on)
8252 (setq res t)
8253 (or (member tag current) (push tag current)))
8254 ((eq onoff 'off)
8255 (or (not (member tag current)) (setq current (delete tag current))))
8256 (t (if (member tag current)
8257 (setq current (delete tag current))
8258 (setq res t)
8259 (push tag current))))
8260 (end-of-line 1)
8261 (if current
8262 (progn
8263 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8264 (org-set-tags nil t))
8265 (delete-horizontal-space))
8266 (run-hooks 'org-after-tags-change-hook))
8267 res))
8269 (defun org-toggle-archive-tag (&optional arg)
8270 "Toggle the archive tag for the current headline.
8271 With prefix ARG, check all children of current headline and offer tagging
8272 the children that do not contain any open TODO items."
8273 (interactive "P")
8274 (if arg
8275 (org-archive-all-done 'tag)
8276 (let (set)
8277 (save-excursion
8278 (org-back-to-heading t)
8279 (setq set (org-toggle-tag org-archive-tag))
8280 (when set (hide-subtree)))
8281 (and set (beginning-of-line 1))
8282 (message "Subtree %s" (if set "archived" "unarchived")))))
8285 ;;;; Tables
8287 ;;; The table editor
8289 ;; Watch out: Here we are talking about two different kind of tables.
8290 ;; Most of the code is for the tables created with the Org-mode table editor.
8291 ;; Sometimes, we talk about tables created and edited with the table.el
8292 ;; Emacs package. We call the former org-type tables, and the latter
8293 ;; table.el-type tables.
8295 (defun org-before-change-function (beg end)
8296 "Every change indicates that a table might need an update."
8297 (setq org-table-may-need-update t))
8299 (defconst org-table-line-regexp "^[ \t]*|"
8300 "Detects an org-type table line.")
8301 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8302 "Detects an org-type table line.")
8303 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8304 "Detects a table line marked for automatic recalculation.")
8305 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8306 "Detects a table line marked for automatic recalculation.")
8307 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8308 "Detects a table line marked for automatic recalculation.")
8309 (defconst org-table-hline-regexp "^[ \t]*|-"
8310 "Detects an org-type table hline.")
8311 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8312 "Detects a table-type table hline.")
8313 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8314 "Detects an org-type or table-type table.")
8315 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8316 "Searching from within a table (any type) this finds the first line
8317 outside the table.")
8318 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8319 "Searching from within a table (any type) this finds the first line
8320 outside the table.")
8322 (defvar org-table-last-highlighted-reference nil)
8323 (defvar org-table-formula-history nil)
8325 (defvar org-table-column-names nil
8326 "Alist with column names, derived from the `!' line.")
8327 (defvar org-table-column-name-regexp nil
8328 "Regular expression matching the current column names.")
8329 (defvar org-table-local-parameters nil
8330 "Alist with parameter names, derived from the `$' line.")
8331 (defvar org-table-named-field-locations nil
8332 "Alist with locations of named fields.")
8334 (defvar org-table-current-line-types nil
8335 "Table row types, non-nil only for the duration of a comand.")
8336 (defvar org-table-current-begin-line nil
8337 "Table begin line, non-nil only for the duration of a comand.")
8338 (defvar org-table-current-begin-pos nil
8339 "Table begin position, non-nil only for the duration of a comand.")
8340 (defvar org-table-dlines nil
8341 "Vector of data line line numbers in the current table.")
8342 (defvar org-table-hlines nil
8343 "Vector of hline line numbers in the current table.")
8345 (defconst org-table-range-regexp
8346 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8347 ;; 1 2 3 4 5
8348 "Regular expression for matching ranges in formulas.")
8350 (defconst org-table-range-regexp2
8351 (concat
8352 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8353 "\\.\\."
8354 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8355 "Match a range for reference display.")
8357 (defconst org-table-translate-regexp
8358 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8359 "Match a reference that needs translation, for reference display.")
8361 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8363 (defun org-table-create-with-table.el ()
8364 "Use the table.el package to insert a new table.
8365 If there is already a table at point, convert between Org-mode tables
8366 and table.el tables."
8367 (interactive)
8368 (require 'table)
8369 (cond
8370 ((org-at-table.el-p)
8371 (if (y-or-n-p "Convert table to Org-mode table? ")
8372 (org-table-convert)))
8373 ((org-at-table-p)
8374 (if (y-or-n-p "Convert table to table.el table? ")
8375 (org-table-convert)))
8376 (t (call-interactively 'table-insert))))
8378 (defun org-table-create-or-convert-from-region (arg)
8379 "Convert region to table, or create an empty table.
8380 If there is an active region, convert it to a table, using the function
8381 `org-table-convert-region'. See the documentation of that function
8382 to learn how the prefix argument is interpreted to determine the field
8383 separator.
8384 If there is no such region, create an empty table with `org-table-create'."
8385 (interactive "P")
8386 (if (org-region-active-p)
8387 (org-table-convert-region (region-beginning) (region-end) arg)
8388 (org-table-create arg)))
8390 (defun org-table-create (&optional size)
8391 "Query for a size and insert a table skeleton.
8392 SIZE is a string Columns x Rows like for example \"3x2\"."
8393 (interactive "P")
8394 (unless size
8395 (setq size (read-string
8396 (concat "Table size Columns x Rows [e.g. "
8397 org-table-default-size "]: ")
8398 "" nil org-table-default-size)))
8400 (let* ((pos (point))
8401 (indent (make-string (current-column) ?\ ))
8402 (split (org-split-string size " *x *"))
8403 (rows (string-to-number (nth 1 split)))
8404 (columns (string-to-number (car split)))
8405 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8406 "\n")))
8407 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8408 (point-at-bol) (point)))
8409 (beginning-of-line 1)
8410 (newline))
8411 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8412 (dotimes (i rows) (insert line))
8413 (goto-char pos)
8414 (if (> rows 1)
8415 ;; Insert a hline after the first row.
8416 (progn
8417 (end-of-line 1)
8418 (insert "\n|-")
8419 (goto-char pos)))
8420 (org-table-align)))
8422 (defun org-table-convert-region (beg0 end0 &optional separator)
8423 "Convert region to a table.
8424 The region goes from BEG0 to END0, but these borders will be moved
8425 slightly, to make sure a beginning of line in the first line is included.
8427 SEPARATOR specifies the field separator in the lines. It can have the
8428 following values:
8430 '(4) Use the comma as a field separator
8431 '(16) Use a TAB as field separator
8432 integer When a number, use that many spaces as field separator
8433 nil When nil, the command tries to be smart and figure out the
8434 separator in the following way:
8435 - when each line contains a TAB, assume TAB-separated material
8436 - when each line contains a comme, assume CSV material
8437 - else, assume one or more SPACE charcters as separator."
8438 (interactive "rP")
8439 (let* ((beg (min beg0 end0))
8440 (end (max beg0 end0))
8442 (goto-char beg)
8443 (beginning-of-line 1)
8444 (setq beg (move-marker (make-marker) (point)))
8445 (goto-char end)
8446 (if (bolp) (backward-char 1) (end-of-line 1))
8447 (setq end (move-marker (make-marker) (point)))
8448 ;; Get the right field separator
8449 (unless separator
8450 (goto-char beg)
8451 (setq separator
8452 (cond
8453 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8454 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8455 (t 1))))
8456 (setq re (cond
8457 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8458 ((equal separator '(16)) "^\\|\t")
8459 ((integerp separator)
8460 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8461 (t (error "This should not happen"))))
8462 (goto-char beg)
8463 (while (re-search-forward re end t)
8464 (replace-match "| " t t))
8465 (goto-char beg)
8466 (insert " ")
8467 (org-table-align)))
8469 (defun org-table-import (file arg)
8470 "Import FILE as a table.
8471 The file is assumed to be tab-separated. Such files can be produced by most
8472 spreadsheet and database applications. If no tabs (at least one per line)
8473 are found, lines will be split on whitespace into fields."
8474 (interactive "f\nP")
8475 (or (bolp) (newline))
8476 (let ((beg (point))
8477 (pm (point-max)))
8478 (insert-file-contents file)
8479 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8481 (defun org-table-export ()
8482 "Export table as a tab-separated file.
8483 Such a file can be imported into a spreadsheet program like Excel."
8484 (interactive)
8485 (let* ((beg (org-table-begin))
8486 (end (org-table-end))
8487 (table (buffer-substring beg end))
8488 (file (read-file-name "Export table to: "))
8489 buf)
8490 (unless (or (not (file-exists-p file))
8491 (y-or-n-p (format "Overwrite file %s? " file)))
8492 (error "Abort"))
8493 (with-current-buffer (find-file-noselect file)
8494 (setq buf (current-buffer))
8495 (erase-buffer)
8496 (fundamental-mode)
8497 (insert table)
8498 (goto-char (point-min))
8499 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8500 (replace-match "" t t)
8501 (end-of-line 1))
8502 (goto-char (point-min))
8503 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8504 (replace-match "" t t)
8505 (goto-char (min (1+ (point)) (point-max))))
8506 (goto-char (point-min))
8507 (while (re-search-forward "^-[-+]*$" nil t)
8508 (replace-match "")
8509 (if (looking-at "\n")
8510 (delete-char 1)))
8511 (goto-char (point-min))
8512 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8513 (replace-match "\t" t t))
8514 (save-buffer))
8515 (kill-buffer buf)))
8517 (defvar org-table-aligned-begin-marker (make-marker)
8518 "Marker at the beginning of the table last aligned.
8519 Used to check if cursor still is in that table, to minimize realignment.")
8520 (defvar org-table-aligned-end-marker (make-marker)
8521 "Marker at the end of the table last aligned.
8522 Used to check if cursor still is in that table, to minimize realignment.")
8523 (defvar org-table-last-alignment nil
8524 "List of flags for flushright alignment, from the last re-alignment.
8525 This is being used to correctly align a single field after TAB or RET.")
8526 (defvar org-table-last-column-widths nil
8527 "List of max width of fields in each column.
8528 This is being used to correctly align a single field after TAB or RET.")
8529 (defvar org-table-overlay-coordinates nil
8530 "Overlay coordinates after each align of a table.")
8531 (make-variable-buffer-local 'org-table-overlay-coordinates)
8533 (defvar org-last-recalc-line nil)
8534 (defconst org-narrow-column-arrow "=>"
8535 "Used as display property in narrowed table columns.")
8537 (defun org-table-align ()
8538 "Align the table at point by aligning all vertical bars."
8539 (interactive)
8540 (let* (
8541 ;; Limits of table
8542 (beg (org-table-begin))
8543 (end (org-table-end))
8544 ;; Current cursor position
8545 (linepos (org-current-line))
8546 (colpos (org-table-current-column))
8547 (winstart (window-start))
8548 (winstartline (org-current-line (min winstart (1- (point-max)))))
8549 lines (new "") lengths l typenums ty fields maxfields i
8550 column
8551 (indent "") cnt frac
8552 rfmt hfmt
8553 (spaces '(1 . 1))
8554 (sp1 (car spaces))
8555 (sp2 (cdr spaces))
8556 (rfmt1 (concat
8557 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8558 (hfmt1 (concat
8559 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8560 emptystrings links dates emph narrow fmax f1 len c e)
8561 (untabify beg end)
8562 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8563 ;; Check if we have links or dates
8564 (goto-char beg)
8565 (setq links (re-search-forward org-bracket-link-regexp end t))
8566 (goto-char beg)
8567 (setq emph (and org-hide-emphasis-markers
8568 (re-search-forward org-emph-re end t)))
8569 (goto-char beg)
8570 (setq dates (and org-display-custom-times
8571 (re-search-forward org-ts-regexp-both end t)))
8572 ;; Make sure the link properties are right
8573 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8574 ;; Make sure the date properties are right
8575 (when dates (goto-char beg) (while (org-activate-dates end)))
8576 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8578 ;; Check if we are narrowing any columns
8579 (goto-char beg)
8580 (setq narrow (and org-format-transports-properties-p
8581 (re-search-forward "<[0-9]+>" end t)))
8582 ;; Get the rows
8583 (setq lines (org-split-string
8584 (buffer-substring beg end) "\n"))
8585 ;; Store the indentation of the first line
8586 (if (string-match "^ *" (car lines))
8587 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8588 ;; Mark the hlines by setting the corresponding element to nil
8589 ;; At the same time, we remove trailing space.
8590 (setq lines (mapcar (lambda (l)
8591 (if (string-match "^ *|-" l)
8593 (if (string-match "[ \t]+$" l)
8594 (substring l 0 (match-beginning 0))
8595 l)))
8596 lines))
8597 ;; Get the data fields by splitting the lines.
8598 (setq fields (mapcar
8599 (lambda (l)
8600 (org-split-string l " *| *"))
8601 (delq nil (copy-sequence lines))))
8602 ;; How many fields in the longest line?
8603 (condition-case nil
8604 (setq maxfields (apply 'max (mapcar 'length fields)))
8605 (error
8606 (kill-region beg end)
8607 (org-table-create org-table-default-size)
8608 (error "Empty table - created default table")))
8609 ;; A list of empty strings to fill any short rows on output
8610 (setq emptystrings (make-list maxfields ""))
8611 ;; Check for special formatting.
8612 (setq i -1)
8613 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8614 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8615 ;; Check if there is an explicit width specified
8616 (when narrow
8617 (setq c column fmax nil)
8618 (while c
8619 (setq e (pop c))
8620 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8621 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8622 ;; Find fields that are wider than fmax, and shorten them
8623 (when fmax
8624 (loop for xx in column do
8625 (when (and (stringp xx)
8626 (> (org-string-width xx) fmax))
8627 (org-add-props xx nil
8628 'help-echo
8629 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8630 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8631 (unless (> f1 1)
8632 (error "Cannot narrow field starting with wide link \"%s\""
8633 (match-string 0 xx)))
8634 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8635 (add-text-properties (- f1 2) f1
8636 (list 'display org-narrow-column-arrow)
8637 xx)))))
8638 ;; Get the maximum width for each column
8639 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8640 ;; Get the fraction of numbers, to decide about alignment of the column
8641 (setq cnt 0 frac 0.0)
8642 (loop for x in column do
8643 (if (equal x "")
8645 (setq frac ( / (+ (* frac cnt)
8646 (if (string-match org-table-number-regexp x) 1 0))
8647 (setq cnt (1+ cnt))))))
8648 (push (>= frac org-table-number-fraction) typenums))
8649 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8651 ;; Store the alignment of this table, for later editing of single fields
8652 (setq org-table-last-alignment typenums
8653 org-table-last-column-widths lengths)
8655 ;; With invisible characters, `format' does not get the field width right
8656 ;; So we need to make these fields wide by hand.
8657 (when (or links emph)
8658 (loop for i from 0 upto (1- maxfields) do
8659 (setq len (nth i lengths))
8660 (loop for j from 0 upto (1- (length fields)) do
8661 (setq c (nthcdr i (car (nthcdr j fields))))
8662 (if (and (stringp (car c))
8663 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8664 ; (string-match org-bracket-link-regexp (car c))
8665 (< (org-string-width (car c)) len))
8666 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8668 ;; Compute the formats needed for output of the table
8669 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8670 (while (setq l (pop lengths))
8671 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8672 (setq rfmt (concat rfmt (format rfmt1 ty l))
8673 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8674 (setq rfmt (concat rfmt "\n")
8675 hfmt (concat (substring hfmt 0 -1) "|\n"))
8677 (setq new (mapconcat
8678 (lambda (l)
8679 (if l (apply 'format rfmt
8680 (append (pop fields) emptystrings))
8681 hfmt))
8682 lines ""))
8683 ;; Replace the old one
8684 (delete-region beg end)
8685 (move-marker end nil)
8686 (move-marker org-table-aligned-begin-marker (point))
8687 (insert new)
8688 (move-marker org-table-aligned-end-marker (point))
8689 (when (and orgtbl-mode (not (org-mode-p)))
8690 (goto-char org-table-aligned-begin-marker)
8691 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8692 ;; Try to move to the old location
8693 (goto-line winstartline)
8694 (setq winstart (point-at-bol))
8695 (goto-line linepos)
8696 (set-window-start (selected-window) winstart 'noforce)
8697 (org-table-goto-column colpos)
8698 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8699 (setq org-table-may-need-update nil)
8702 (defun org-string-width (s)
8703 "Compute width of string, ignoring invisible characters.
8704 This ignores character with invisibility property `org-link', and also
8705 characters with property `org-cwidth', because these will become invisible
8706 upon the next fontification round."
8707 (let (b l)
8708 (when (or (eq t buffer-invisibility-spec)
8709 (assq 'org-link buffer-invisibility-spec))
8710 (while (setq b (text-property-any 0 (length s)
8711 'invisible 'org-link s))
8712 (setq s (concat (substring s 0 b)
8713 (substring s (or (next-single-property-change
8714 b 'invisible s) (length s)))))))
8715 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8716 (setq s (concat (substring s 0 b)
8717 (substring s (or (next-single-property-change
8718 b 'org-cwidth s) (length s))))))
8719 (setq l (string-width s) b -1)
8720 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8721 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8724 (defun org-table-begin (&optional table-type)
8725 "Find the beginning of the table and return its position.
8726 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8727 (save-excursion
8728 (if (not (re-search-backward
8729 (if table-type org-table-any-border-regexp
8730 org-table-border-regexp)
8731 nil t))
8732 (progn (goto-char (point-min)) (point))
8733 (goto-char (match-beginning 0))
8734 (beginning-of-line 2)
8735 (point))))
8737 (defun org-table-end (&optional table-type)
8738 "Find the end of the table and return its position.
8739 With argument TABLE-TYPE, go to the end of a table.el-type table."
8740 (save-excursion
8741 (if (not (re-search-forward
8742 (if table-type org-table-any-border-regexp
8743 org-table-border-regexp)
8744 nil t))
8745 (goto-char (point-max))
8746 (goto-char (match-beginning 0)))
8747 (point-marker)))
8749 (defun org-table-justify-field-maybe (&optional new)
8750 "Justify the current field, text to left, number to right.
8751 Optional argument NEW may specify text to replace the current field content."
8752 (cond
8753 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8754 ((org-at-table-hline-p))
8755 ((and (not new)
8756 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8757 (current-buffer)))
8758 (< (point) org-table-aligned-begin-marker)
8759 (>= (point) org-table-aligned-end-marker)))
8760 ;; This is not the same table, force a full re-align
8761 (setq org-table-may-need-update t))
8762 (t ;; realign the current field, based on previous full realign
8763 (let* ((pos (point)) s
8764 (col (org-table-current-column))
8765 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8766 l f n o e)
8767 (when (> col 0)
8768 (skip-chars-backward "^|\n")
8769 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8770 (progn
8771 (setq s (match-string 1)
8772 o (match-string 0)
8773 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8774 e (not (= (match-beginning 2) (match-end 2))))
8775 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8776 l (if e "|" (setq org-table-may-need-update t) ""))
8777 n (format f s))
8778 (if new
8779 (if (<= (length new) l) ;; FIXME: length -> str-width?
8780 (setq n (format f new))
8781 (setq n (concat new "|") org-table-may-need-update t)))
8782 (or (equal n o)
8783 (let (org-table-may-need-update)
8784 (replace-match n t t))))
8785 (setq org-table-may-need-update t))
8786 (goto-char pos))))))
8788 (defun org-table-next-field ()
8789 "Go to the next field in the current table, creating new lines as needed.
8790 Before doing so, re-align the table if necessary."
8791 (interactive)
8792 (org-table-maybe-eval-formula)
8793 (org-table-maybe-recalculate-line)
8794 (if (and org-table-automatic-realign
8795 org-table-may-need-update)
8796 (org-table-align))
8797 (let ((end (org-table-end)))
8798 (if (org-at-table-hline-p)
8799 (end-of-line 1))
8800 (condition-case nil
8801 (progn
8802 (re-search-forward "|" end)
8803 (if (looking-at "[ \t]*$")
8804 (re-search-forward "|" end))
8805 (if (and (looking-at "-")
8806 org-table-tab-jumps-over-hlines
8807 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8808 (goto-char (match-beginning 1)))
8809 (if (looking-at "-")
8810 (progn
8811 (beginning-of-line 0)
8812 (org-table-insert-row 'below))
8813 (if (looking-at " ") (forward-char 1))))
8814 (error
8815 (org-table-insert-row 'below)))))
8817 (defun org-table-previous-field ()
8818 "Go to the previous field in the table.
8819 Before doing so, re-align the table if necessary."
8820 (interactive)
8821 (org-table-justify-field-maybe)
8822 (org-table-maybe-recalculate-line)
8823 (if (and org-table-automatic-realign
8824 org-table-may-need-update)
8825 (org-table-align))
8826 (if (org-at-table-hline-p)
8827 (end-of-line 1))
8828 (re-search-backward "|" (org-table-begin))
8829 (re-search-backward "|" (org-table-begin))
8830 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8831 (re-search-backward "|" (org-table-begin)))
8832 (if (looking-at "| ?")
8833 (goto-char (match-end 0))))
8835 (defun org-table-next-row ()
8836 "Go to the next row (same column) in the current table.
8837 Before doing so, re-align the table if necessary."
8838 (interactive)
8839 (org-table-maybe-eval-formula)
8840 (org-table-maybe-recalculate-line)
8841 (if (or (looking-at "[ \t]*$")
8842 (save-excursion (skip-chars-backward " \t") (bolp)))
8843 (newline)
8844 (if (and org-table-automatic-realign
8845 org-table-may-need-update)
8846 (org-table-align))
8847 (let ((col (org-table-current-column)))
8848 (beginning-of-line 2)
8849 (if (or (not (org-at-table-p))
8850 (org-at-table-hline-p))
8851 (progn
8852 (beginning-of-line 0)
8853 (org-table-insert-row 'below)))
8854 (org-table-goto-column col)
8855 (skip-chars-backward "^|\n\r")
8856 (if (looking-at " ") (forward-char 1)))))
8858 (defun org-table-copy-down (n)
8859 "Copy a field down in the current column.
8860 If the field at the cursor is empty, copy into it the content of the nearest
8861 non-empty field above. With argument N, use the Nth non-empty field.
8862 If the current field is not empty, it is copied down to the next row, and
8863 the cursor is moved with it. Therefore, repeating this command causes the
8864 column to be filled row-by-row.
8865 If the variable `org-table-copy-increment' is non-nil and the field is an
8866 integer or a timestamp, it will be incremented while copying. In the case of
8867 a timestamp, if the cursor is on the year, change the year. If it is on the
8868 month or the day, change that. Point will stay on the current date field
8869 in order to easily repeat the interval."
8870 (interactive "p")
8871 (let* ((colpos (org-table-current-column))
8872 (col (current-column))
8873 (field (org-table-get-field))
8874 (non-empty (string-match "[^ \t]" field))
8875 (beg (org-table-begin))
8876 txt)
8877 (org-table-check-inside-data-field)
8878 (if non-empty
8879 (progn
8880 (setq txt (org-trim field))
8881 (org-table-next-row)
8882 (org-table-blank-field))
8883 (save-excursion
8884 (setq txt
8885 (catch 'exit
8886 (while (progn (beginning-of-line 1)
8887 (re-search-backward org-table-dataline-regexp
8888 beg t))
8889 (org-table-goto-column colpos t)
8890 (if (and (looking-at
8891 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8892 (= (setq n (1- n)) 0))
8893 (throw 'exit (match-string 1))))))))
8894 (if txt
8895 (progn
8896 (if (and org-table-copy-increment
8897 (string-match "^[0-9]+$" txt))
8898 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8899 (insert txt)
8900 (move-to-column col)
8901 (if (and org-table-copy-increment (org-at-timestamp-p t))
8902 (org-timestamp-up 1)
8903 (org-table-maybe-recalculate-line))
8904 (org-table-align)
8905 (move-to-column col))
8906 (error "No non-empty field found"))))
8908 (defun org-table-check-inside-data-field ()
8909 "Is point inside a table data field?
8910 I.e. not on a hline or before the first or after the last column?
8911 This actually throws an error, so it aborts the current command."
8912 (if (or (not (org-at-table-p))
8913 (= (org-table-current-column) 0)
8914 (org-at-table-hline-p)
8915 (looking-at "[ \t]*$"))
8916 (error "Not in table data field")))
8918 (defvar org-table-clip nil
8919 "Clipboard for table regions.")
8921 (defun org-table-blank-field ()
8922 "Blank the current table field or active region."
8923 (interactive)
8924 (org-table-check-inside-data-field)
8925 (if (and (interactive-p) (org-region-active-p))
8926 (let (org-table-clip)
8927 (org-table-cut-region (region-beginning) (region-end)))
8928 (skip-chars-backward "^|")
8929 (backward-char 1)
8930 (if (looking-at "|[^|\n]+")
8931 (let* ((pos (match-beginning 0))
8932 (match (match-string 0))
8933 (len (org-string-width match)))
8934 (replace-match (concat "|" (make-string (1- len) ?\ )))
8935 (goto-char (+ 2 pos))
8936 (substring match 1)))))
8938 (defun org-table-get-field (&optional n replace)
8939 "Return the value of the field in column N of current row.
8940 N defaults to current field.
8941 If REPLACE is a string, replace field with this value. The return value
8942 is always the old value."
8943 (and n (org-table-goto-column n))
8944 (skip-chars-backward "^|\n")
8945 (backward-char 1)
8946 (if (looking-at "|[^|\r\n]*")
8947 (let* ((pos (match-beginning 0))
8948 (val (buffer-substring (1+ pos) (match-end 0))))
8949 (if replace
8950 (replace-match (concat "|" replace) t t))
8951 (goto-char (min (point-at-eol) (+ 2 pos)))
8952 val)
8953 (forward-char 1) ""))
8955 (defun org-table-field-info (arg)
8956 "Show info about the current field, and highlight any reference at point."
8957 (interactive "P")
8958 (org-table-get-specials)
8959 (save-excursion
8960 (let* ((pos (point))
8961 (col (org-table-current-column))
8962 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8963 (name (car (rassoc (list (org-current-line) col)
8964 org-table-named-field-locations)))
8965 (eql (org-table-get-stored-formulas))
8966 (dline (org-table-current-dline))
8967 (ref (format "@%d$%d" dline col))
8968 (ref1 (org-table-convert-refs-to-an ref))
8969 (fequation (or (assoc name eql) (assoc ref eql)))
8970 (cequation (assoc (int-to-string col) eql))
8971 (eqn (or fequation cequation)))
8972 (goto-char pos)
8973 (condition-case nil
8974 (org-table-show-reference 'local)
8975 (error nil))
8976 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8977 dline col
8978 (if cname (concat " or $" cname) "")
8979 dline col ref1
8980 (if name (concat " or $" name) "")
8981 ;; FIXME: formula info not correct if special table line
8982 (if eqn
8983 (concat ", formula: "
8984 (org-table-formula-to-user
8985 (concat
8986 (if (string-match "^[$@]"(car eqn)) "" "$")
8987 (car eqn) "=" (cdr eqn))))
8988 "")))))
8990 (defun org-table-current-column ()
8991 "Find out which column we are in.
8992 When called interactively, column is also displayed in echo area."
8993 (interactive)
8994 (if (interactive-p) (org-table-check-inside-data-field))
8995 (save-excursion
8996 (let ((cnt 0) (pos (point)))
8997 (beginning-of-line 1)
8998 (while (search-forward "|" pos t)
8999 (setq cnt (1+ cnt)))
9000 (if (interactive-p) (message "This is table column %d" cnt))
9001 cnt)))
9003 (defun org-table-current-dline ()
9004 "Find out what table data line we are in.
9005 Only datalins count for this."
9006 (interactive)
9007 (if (interactive-p) (org-table-check-inside-data-field))
9008 (save-excursion
9009 (let ((cnt 0) (pos (point)))
9010 (goto-char (org-table-begin))
9011 (while (<= (point) pos)
9012 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9013 (beginning-of-line 2))
9014 (if (interactive-p) (message "This is table line %d" cnt))
9015 cnt)))
9017 (defun org-table-goto-column (n &optional on-delim force)
9018 "Move the cursor to the Nth column in the current table line.
9019 With optional argument ON-DELIM, stop with point before the left delimiter
9020 of the field.
9021 If there are less than N fields, just go to after the last delimiter.
9022 However, when FORCE is non-nil, create new columns if necessary."
9023 (interactive "p")
9024 (let ((pos (point-at-eol)))
9025 (beginning-of-line 1)
9026 (when (> n 0)
9027 (while (and (> (setq n (1- n)) -1)
9028 (or (search-forward "|" pos t)
9029 (and force
9030 (progn (end-of-line 1)
9031 (skip-chars-backward "^|")
9032 (insert " | "))))))
9033 ; (backward-char 2) t)))))
9034 (when (and force (not (looking-at ".*|")))
9035 (save-excursion (end-of-line 1) (insert " | ")))
9036 (if on-delim
9037 (backward-char 1)
9038 (if (looking-at " ") (forward-char 1))))))
9040 (defun org-at-table-p (&optional table-type)
9041 "Return t if the cursor is inside an org-type table.
9042 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9043 (if org-enable-table-editor
9044 (save-excursion
9045 (beginning-of-line 1)
9046 (looking-at (if table-type org-table-any-line-regexp
9047 org-table-line-regexp)))
9048 nil))
9050 (defun org-at-table.el-p ()
9051 "Return t if and only if we are at a table.el table."
9052 (and (org-at-table-p 'any)
9053 (save-excursion
9054 (goto-char (org-table-begin 'any))
9055 (looking-at org-table1-hline-regexp))))
9057 (defun org-table-recognize-table.el ()
9058 "If there is a table.el table nearby, recognize it and move into it."
9059 (if org-table-tab-recognizes-table.el
9060 (if (org-at-table.el-p)
9061 (progn
9062 (beginning-of-line 1)
9063 (if (looking-at org-table-dataline-regexp)
9065 (if (looking-at org-table1-hline-regexp)
9066 (progn
9067 (beginning-of-line 2)
9068 (if (looking-at org-table-any-border-regexp)
9069 (beginning-of-line -1)))))
9070 (if (re-search-forward "|" (org-table-end t) t)
9071 (progn
9072 (require 'table)
9073 (if (table--at-cell-p (point))
9075 (message "recognizing table.el table...")
9076 (table-recognize-table)
9077 (message "recognizing table.el table...done")))
9078 (error "This should not happen..."))
9080 nil)
9081 nil))
9083 (defun org-at-table-hline-p ()
9084 "Return t if the cursor is inside a hline in a table."
9085 (if org-enable-table-editor
9086 (save-excursion
9087 (beginning-of-line 1)
9088 (looking-at org-table-hline-regexp))
9089 nil))
9091 (defun org-table-insert-column ()
9092 "Insert a new column into the table."
9093 (interactive)
9094 (if (not (org-at-table-p))
9095 (error "Not at a table"))
9096 (org-table-find-dataline)
9097 (let* ((col (max 1 (org-table-current-column)))
9098 (beg (org-table-begin))
9099 (end (org-table-end))
9100 ;; Current cursor position
9101 (linepos (org-current-line))
9102 (colpos col))
9103 (goto-char beg)
9104 (while (< (point) end)
9105 (if (org-at-table-hline-p)
9107 (org-table-goto-column col t)
9108 (insert "| "))
9109 (beginning-of-line 2))
9110 (move-marker end nil)
9111 (goto-line linepos)
9112 (org-table-goto-column colpos)
9113 (org-table-align)
9114 (org-table-fix-formulas "$" nil (1- col) 1)))
9116 (defun org-table-find-dataline ()
9117 "Find a dataline in the current table, which is needed for column commands."
9118 (if (and (org-at-table-p)
9119 (not (org-at-table-hline-p)))
9121 (let ((col (current-column))
9122 (end (org-table-end)))
9123 (move-to-column col)
9124 (while (and (< (point) end)
9125 (or (not (= (current-column) col))
9126 (org-at-table-hline-p)))
9127 (beginning-of-line 2)
9128 (move-to-column col))
9129 (if (and (org-at-table-p)
9130 (not (org-at-table-hline-p)))
9132 (error
9133 "Please position cursor in a data line for column operations")))))
9135 (defun org-table-delete-column ()
9136 "Delete a column from the table."
9137 (interactive)
9138 (if (not (org-at-table-p))
9139 (error "Not at a table"))
9140 (org-table-find-dataline)
9141 (org-table-check-inside-data-field)
9142 (let* ((col (org-table-current-column))
9143 (beg (org-table-begin))
9144 (end (org-table-end))
9145 ;; Current cursor position
9146 (linepos (org-current-line))
9147 (colpos col))
9148 (goto-char beg)
9149 (while (< (point) end)
9150 (if (org-at-table-hline-p)
9152 (org-table-goto-column col t)
9153 (and (looking-at "|[^|\n]+|")
9154 (replace-match "|")))
9155 (beginning-of-line 2))
9156 (move-marker end nil)
9157 (goto-line linepos)
9158 (org-table-goto-column colpos)
9159 (org-table-align)
9160 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9161 col -1 col)))
9163 (defun org-table-move-column-right ()
9164 "Move column to the right."
9165 (interactive)
9166 (org-table-move-column nil))
9167 (defun org-table-move-column-left ()
9168 "Move column to the left."
9169 (interactive)
9170 (org-table-move-column 'left))
9172 (defun org-table-move-column (&optional left)
9173 "Move the current column to the right. With arg LEFT, move to the left."
9174 (interactive "P")
9175 (if (not (org-at-table-p))
9176 (error "Not at a table"))
9177 (org-table-find-dataline)
9178 (org-table-check-inside-data-field)
9179 (let* ((col (org-table-current-column))
9180 (col1 (if left (1- col) col))
9181 (beg (org-table-begin))
9182 (end (org-table-end))
9183 ;; Current cursor position
9184 (linepos (org-current-line))
9185 (colpos (if left (1- col) (1+ col))))
9186 (if (and left (= col 1))
9187 (error "Cannot move column further left"))
9188 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9189 (error "Cannot move column further right"))
9190 (goto-char beg)
9191 (while (< (point) end)
9192 (if (org-at-table-hline-p)
9194 (org-table-goto-column col1 t)
9195 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9196 (replace-match "|\\2|\\1|")))
9197 (beginning-of-line 2))
9198 (move-marker end nil)
9199 (goto-line linepos)
9200 (org-table-goto-column colpos)
9201 (org-table-align)
9202 (org-table-fix-formulas
9203 "$" (list (cons (number-to-string col) (number-to-string colpos))
9204 (cons (number-to-string colpos) (number-to-string col))))))
9206 (defun org-table-move-row-down ()
9207 "Move table row down."
9208 (interactive)
9209 (org-table-move-row nil))
9210 (defun org-table-move-row-up ()
9211 "Move table row up."
9212 (interactive)
9213 (org-table-move-row 'up))
9215 (defun org-table-move-row (&optional up)
9216 "Move the current table line down. With arg UP, move it up."
9217 (interactive "P")
9218 (let* ((col (current-column))
9219 (pos (point))
9220 (hline1p (save-excursion (beginning-of-line 1)
9221 (looking-at org-table-hline-regexp)))
9222 (dline1 (org-table-current-dline))
9223 (dline2 (+ dline1 (if up -1 1)))
9224 (tonew (if up 0 2))
9225 txt hline2p)
9226 (beginning-of-line tonew)
9227 (unless (org-at-table-p)
9228 (goto-char pos)
9229 (error "Cannot move row further"))
9230 (setq hline2p (looking-at org-table-hline-regexp))
9231 (goto-char pos)
9232 (beginning-of-line 1)
9233 (setq pos (point))
9234 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9235 (delete-region (point) (1+ (point-at-eol)))
9236 (beginning-of-line tonew)
9237 (insert txt)
9238 (beginning-of-line 0)
9239 (move-to-column col)
9240 (unless (or hline1p hline2p)
9241 (org-table-fix-formulas
9242 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9243 (cons (number-to-string dline2) (number-to-string dline1)))))))
9245 (defun org-table-insert-row (&optional arg)
9246 "Insert a new row above the current line into the table.
9247 With prefix ARG, insert below the current line."
9248 (interactive "P")
9249 (if (not (org-at-table-p))
9250 (error "Not at a table"))
9251 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9252 (new (org-table-clean-line line)))
9253 ;; Fix the first field if necessary
9254 (if (string-match "^[ \t]*| *[#$] *|" line)
9255 (setq new (replace-match (match-string 0 line) t t new)))
9256 (beginning-of-line (if arg 2 1))
9257 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9258 (beginning-of-line 0)
9259 (re-search-forward "| ?" (point-at-eol) t)
9260 (and (or org-table-may-need-update org-table-overlay-coordinates)
9261 (org-table-align))
9262 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9264 (defun org-table-insert-hline (&optional above)
9265 "Insert a horizontal-line below the current line into the table.
9266 With prefix ABOVE, insert above the current line."
9267 (interactive "P")
9268 (if (not (org-at-table-p))
9269 (error "Not at a table"))
9270 (let ((line (org-table-clean-line
9271 (buffer-substring (point-at-bol) (point-at-eol))))
9272 (col (current-column)))
9273 (while (string-match "|\\( +\\)|" line)
9274 (setq line (replace-match
9275 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9276 ?-) "|") t t line)))
9277 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9278 (beginning-of-line (if above 1 2))
9279 (insert line "\n")
9280 (beginning-of-line (if above 1 -1))
9281 (move-to-column col)
9282 (and org-table-overlay-coordinates (org-table-align))))
9284 (defun org-table-hline-and-move (&optional same-column)
9285 "Insert a hline and move to the row below that line."
9286 (interactive "P")
9287 (let ((col (org-table-current-column)))
9288 (org-table-maybe-eval-formula)
9289 (org-table-maybe-recalculate-line)
9290 (org-table-insert-hline)
9291 (end-of-line 2)
9292 (if (looking-at "\n[ \t]*|-")
9293 (progn (insert "\n|") (org-table-align))
9294 (org-table-next-field))
9295 (if same-column (org-table-goto-column col))))
9297 (defun org-table-clean-line (s)
9298 "Convert a table line S into a string with only \"|\" and space.
9299 In particular, this does handle wide and invisible characters."
9300 (if (string-match "^[ \t]*|-" s)
9301 ;; It's a hline, just map the characters
9302 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9303 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9304 (setq s (replace-match
9305 (concat "|" (make-string (org-string-width (match-string 1 s))
9306 ?\ ) "|")
9307 t t s)))
9310 (defun org-table-kill-row ()
9311 "Delete the current row or horizontal line from the table."
9312 (interactive)
9313 (if (not (org-at-table-p))
9314 (error "Not at a table"))
9315 (let ((col (current-column))
9316 (dline (org-table-current-dline)))
9317 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9318 (if (not (org-at-table-p)) (beginning-of-line 0))
9319 (move-to-column col)
9320 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9321 dline -1 dline)))
9323 (defun org-table-sort-lines (with-case &optional sorting-type)
9324 "Sort table lines according to the column at point.
9326 The position of point indicates the column to be used for
9327 sorting, and the range of lines is the range between the nearest
9328 horizontal separator lines, or the entire table of no such lines
9329 exist. If point is before the first column, you will be prompted
9330 for the sorting column. If there is an active region, the mark
9331 specifies the first line and the sorting column, while point
9332 should be in the last line to be included into the sorting.
9334 The command then prompts for the sorting type which can be
9335 alphabetically, numerically, or by time (as given in a time stamp
9336 in the field). Sorting in reverse order is also possible.
9338 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9340 If SORTING-TYPE is specified when this function is called from a Lisp
9341 program, no prompting will take place. SORTING-TYPE must be a character,
9342 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9343 should be done in reverse order."
9344 (interactive "P")
9345 (let* ((thisline (org-current-line))
9346 (thiscol (org-table-current-column))
9347 beg end bcol ecol tend tbeg column lns pos)
9348 (when (equal thiscol 0)
9349 (if (interactive-p)
9350 (setq thiscol
9351 (string-to-number
9352 (read-string "Use column N for sorting: ")))
9353 (setq thiscol 1))
9354 (org-table-goto-column thiscol))
9355 (org-table-check-inside-data-field)
9356 (if (org-region-active-p)
9357 (progn
9358 (setq beg (region-beginning) end (region-end))
9359 (goto-char beg)
9360 (setq column (org-table-current-column)
9361 beg (point-at-bol))
9362 (goto-char end)
9363 (setq end (point-at-bol 2)))
9364 (setq column (org-table-current-column)
9365 pos (point)
9366 tbeg (org-table-begin)
9367 tend (org-table-end))
9368 (if (re-search-backward org-table-hline-regexp tbeg t)
9369 (setq beg (point-at-bol 2))
9370 (goto-char tbeg)
9371 (setq beg (point-at-bol 1)))
9372 (goto-char pos)
9373 (if (re-search-forward org-table-hline-regexp tend t)
9374 (setq end (point-at-bol 1))
9375 (goto-char tend)
9376 (setq end (point-at-bol))))
9377 (setq beg (move-marker (make-marker) beg)
9378 end (move-marker (make-marker) end))
9379 (untabify beg end)
9380 (goto-char beg)
9381 (org-table-goto-column column)
9382 (skip-chars-backward "^|")
9383 (setq bcol (current-column))
9384 (org-table-goto-column (1+ column))
9385 (skip-chars-backward "^|")
9386 (setq ecol (1- (current-column)))
9387 (org-table-goto-column column)
9388 (setq lns (mapcar (lambda(x) (cons
9389 (org-sort-remove-invisible
9390 (nth (1- column)
9391 (org-split-string x "[ \t]*|[ \t]*")))
9393 (org-split-string (buffer-substring beg end) "\n")))
9394 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9395 (delete-region beg end)
9396 (move-marker beg nil)
9397 (move-marker end nil)
9398 (insert (mapconcat 'cdr lns "\n") "\n")
9399 (goto-line thisline)
9400 (org-table-goto-column thiscol)
9401 (message "%d lines sorted, based on column %d" (length lns) column)))
9403 ;; FIXME: maybe we will not need this? Table sorting is broken....
9404 (defun org-sort-remove-invisible (s)
9405 (remove-text-properties 0 (length s) org-rm-props s)
9406 (while (string-match org-bracket-link-regexp s)
9407 (setq s (replace-match (if (match-end 2)
9408 (match-string 3 s)
9409 (match-string 1 s)) t t s)))
9412 (defun org-table-cut-region (beg end)
9413 "Copy region in table to the clipboard and blank all relevant fields."
9414 (interactive "r")
9415 (org-table-copy-region beg end 'cut))
9417 (defun org-table-copy-region (beg end &optional cut)
9418 "Copy rectangular region in table to clipboard.
9419 A special clipboard is used which can only be accessed
9420 with `org-table-paste-rectangle'."
9421 (interactive "rP")
9422 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9423 region cols
9424 (rpl (if cut " " nil)))
9425 (goto-char beg)
9426 (org-table-check-inside-data-field)
9427 (setq l01 (org-current-line)
9428 c01 (org-table-current-column))
9429 (goto-char end)
9430 (org-table-check-inside-data-field)
9431 (setq l02 (org-current-line)
9432 c02 (org-table-current-column))
9433 (setq l1 (min l01 l02) l2 (max l01 l02)
9434 c1 (min c01 c02) c2 (max c01 c02))
9435 (catch 'exit
9436 (while t
9437 (catch 'nextline
9438 (if (> l1 l2) (throw 'exit t))
9439 (goto-line l1)
9440 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9441 (setq cols nil ic1 c1 ic2 c2)
9442 (while (< ic1 (1+ ic2))
9443 (push (org-table-get-field ic1 rpl) cols)
9444 (setq ic1 (1+ ic1)))
9445 (push (nreverse cols) region)
9446 (setq l1 (1+ l1)))))
9447 (setq org-table-clip (nreverse region))
9448 (if cut (org-table-align))
9449 org-table-clip))
9451 (defun org-table-paste-rectangle ()
9452 "Paste a rectangular region into a table.
9453 The upper right corner ends up in the current field. All involved fields
9454 will be overwritten. If the rectangle does not fit into the present table,
9455 the table is enlarged as needed. The process ignores horizontal separator
9456 lines."
9457 (interactive)
9458 (unless (and org-table-clip (listp org-table-clip))
9459 (error "First cut/copy a region to paste!"))
9460 (org-table-check-inside-data-field)
9461 (let* ((clip org-table-clip)
9462 (line (org-current-line))
9463 (col (org-table-current-column))
9464 (org-enable-table-editor t)
9465 (org-table-automatic-realign nil)
9466 c cols field)
9467 (while (setq cols (pop clip))
9468 (while (org-at-table-hline-p) (beginning-of-line 2))
9469 (if (not (org-at-table-p))
9470 (progn (end-of-line 0) (org-table-next-field)))
9471 (setq c col)
9472 (while (setq field (pop cols))
9473 (org-table-goto-column c nil 'force)
9474 (org-table-get-field nil field)
9475 (setq c (1+ c)))
9476 (beginning-of-line 2))
9477 (goto-line line)
9478 (org-table-goto-column col)
9479 (org-table-align)))
9481 (defun org-table-convert ()
9482 "Convert from `org-mode' table to table.el and back.
9483 Obviously, this only works within limits. When an Org-mode table is
9484 converted to table.el, all horizontal separator lines get lost, because
9485 table.el uses these as cell boundaries and has no notion of horizontal lines.
9486 A table.el table can be converted to an Org-mode table only if it does not
9487 do row or column spanning. Multiline cells will become multiple cells.
9488 Beware, Org-mode does not test if the table can be successfully converted - it
9489 blindly applies a recipe that works for simple tables."
9490 (interactive)
9491 (require 'table)
9492 (if (org-at-table.el-p)
9493 ;; convert to Org-mode table
9494 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9495 (end (move-marker (make-marker) (org-table-end t))))
9496 (table-unrecognize-region beg end)
9497 (goto-char beg)
9498 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9499 (replace-match ""))
9500 (goto-char beg))
9501 (if (org-at-table-p)
9502 ;; convert to table.el table
9503 (let ((beg (move-marker (make-marker) (org-table-begin)))
9504 (end (move-marker (make-marker) (org-table-end))))
9505 ;; first, get rid of all horizontal lines
9506 (goto-char beg)
9507 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9508 (replace-match ""))
9509 ;; insert a hline before first
9510 (goto-char beg)
9511 (org-table-insert-hline 'above)
9512 (beginning-of-line -1)
9513 ;; insert a hline after each line
9514 (while (progn (beginning-of-line 3) (< (point) end))
9515 (org-table-insert-hline))
9516 (goto-char beg)
9517 (setq end (move-marker end (org-table-end)))
9518 ;; replace "+" at beginning and ending of hlines
9519 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9520 (replace-match "\\1+-"))
9521 (goto-char beg)
9522 (while (re-search-forward "-|[ \t]*$" end t)
9523 (replace-match "-+"))
9524 (goto-char beg)))))
9526 (defun org-table-wrap-region (arg)
9527 "Wrap several fields in a column like a paragraph.
9528 This is useful if you'd like to spread the contents of a field over several
9529 lines, in order to keep the table compact.
9531 If there is an active region, and both point and mark are in the same column,
9532 the text in the column is wrapped to minimum width for the given number of
9533 lines. Generally, this makes the table more compact. A prefix ARG may be
9534 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9535 formats the selected text to two lines. If the region was longer than two
9536 lines, the remaining lines remain empty. A negative prefix argument reduces
9537 the current number of lines by that amount. The wrapped text is pasted back
9538 into the table. If you formatted it to more lines than it was before, fields
9539 further down in the table get overwritten - so you might need to make space in
9540 the table first.
9542 If there is no region, the current field is split at the cursor position and
9543 the text fragment to the right of the cursor is prepended to the field one
9544 line down.
9546 If there is no region, but you specify a prefix ARG, the current field gets
9547 blank, and the content is appended to the field above."
9548 (interactive "P")
9549 (org-table-check-inside-data-field)
9550 (if (org-region-active-p)
9551 ;; There is a region: fill as a paragraph
9552 (let* ((beg (region-beginning))
9553 (cline (save-excursion (goto-char beg) (org-current-line)))
9554 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9555 nlines)
9556 (org-table-cut-region (region-beginning) (region-end))
9557 (if (> (length (car org-table-clip)) 1)
9558 (error "Region must be limited to single column"))
9559 (setq nlines (if arg
9560 (if (< arg 1)
9561 (+ (length org-table-clip) arg)
9562 arg)
9563 (length org-table-clip)))
9564 (setq org-table-clip
9565 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9566 nil nlines)))
9567 (goto-line cline)
9568 (org-table-goto-column ccol)
9569 (org-table-paste-rectangle))
9570 ;; No region, split the current field at point
9571 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9572 (skip-chars-forward "^\r\n|"))
9573 (if arg
9574 ;; combine with field above
9575 (let ((s (org-table-blank-field))
9576 (col (org-table-current-column)))
9577 (beginning-of-line 0)
9578 (while (org-at-table-hline-p) (beginning-of-line 0))
9579 (org-table-goto-column col)
9580 (skip-chars-forward "^|")
9581 (skip-chars-backward " ")
9582 (insert " " (org-trim s))
9583 (org-table-align))
9584 ;; split field
9585 (if (looking-at "\\([^|]+\\)+|")
9586 (let ((s (match-string 1)))
9587 (replace-match " |")
9588 (goto-char (match-beginning 0))
9589 (org-table-next-row)
9590 (insert (org-trim s) " ")
9591 (org-table-align))
9592 (org-table-next-row)))))
9594 (defvar org-field-marker nil)
9596 (defun org-table-edit-field (arg)
9597 "Edit table field in a different window.
9598 This is mainly useful for fields that contain hidden parts.
9599 When called with a \\[universal-argument] prefix, just make the full field visible so that
9600 it can be edited in place."
9601 (interactive "P")
9602 (if arg
9603 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9604 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9605 (remove-text-properties b e '(org-cwidth t invisible t
9606 display t intangible t))
9607 (if (and (boundp 'font-lock-mode) font-lock-mode)
9608 (font-lock-fontify-block)))
9609 (let ((pos (move-marker (make-marker) (point)))
9610 (field (org-table-get-field))
9611 (cw (current-window-configuration))
9613 (org-switch-to-buffer-other-window "*Org tmp*")
9614 (erase-buffer)
9615 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9616 (let ((org-inhibit-startup t)) (org-mode))
9617 (goto-char (setq p (point-max)))
9618 (insert (org-trim field))
9619 (remove-text-properties p (point-max)
9620 '(invisible t org-cwidth t display t
9621 intangible t))
9622 (goto-char p)
9623 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9624 (org-set-local 'org-window-configuration cw)
9625 (org-set-local 'org-field-marker pos)
9626 (message "Edit and finish with C-c C-c"))))
9628 (defun org-table-finish-edit-field ()
9629 "Finish editing a table data field.
9630 Remove all newline characters, insert the result into the table, realign
9631 the table and kill the editing buffer."
9632 (let ((pos org-field-marker)
9633 (cw org-window-configuration)
9634 (cb (current-buffer))
9635 text)
9636 (goto-char (point-min))
9637 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9638 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9639 (replace-match " "))
9640 (setq text (org-trim (buffer-string)))
9641 (set-window-configuration cw)
9642 (kill-buffer cb)
9643 (select-window (get-buffer-window (marker-buffer pos)))
9644 (goto-char pos)
9645 (move-marker pos nil)
9646 (org-table-check-inside-data-field)
9647 (org-table-get-field nil text)
9648 (org-table-align)
9649 (message "New field value inserted")))
9651 (defun org-trim (s)
9652 "Remove whitespace at beginning and end of string."
9653 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9654 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9657 (defun org-wrap (string &optional width lines)
9658 "Wrap string to either a number of lines, or a width in characters.
9659 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9660 that costs. If there is a word longer than WIDTH, the text is actually
9661 wrapped to the length of that word.
9662 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9663 many lines, whatever width that takes.
9664 The return value is a list of lines, without newlines at the end."
9665 (let* ((words (org-split-string string "[ \t\n]+"))
9666 (maxword (apply 'max (mapcar 'org-string-width words)))
9667 w ll)
9668 (cond (width
9669 (org-do-wrap words (max maxword width)))
9670 (lines
9671 (setq w maxword)
9672 (setq ll (org-do-wrap words maxword))
9673 (if (<= (length ll) lines)
9675 (setq ll words)
9676 (while (> (length ll) lines)
9677 (setq w (1+ w))
9678 (setq ll (org-do-wrap words w)))
9679 ll))
9680 (t (error "Cannot wrap this")))))
9683 (defun org-do-wrap (words width)
9684 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9685 (let (lines line)
9686 (while words
9687 (setq line (pop words))
9688 (while (and words (< (+ (length line) (length (car words))) width))
9689 (setq line (concat line " " (pop words))))
9690 (setq lines (push line lines)))
9691 (nreverse lines)))
9693 (defun org-split-string (string &optional separators)
9694 "Splits STRING into substrings at SEPARATORS.
9695 No empty strings are returned if there are matches at the beginning
9696 and end of string."
9697 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9698 (start 0)
9699 notfirst
9700 (list nil))
9701 (while (and (string-match rexp string
9702 (if (and notfirst
9703 (= start (match-beginning 0))
9704 (< start (length string)))
9705 (1+ start) start))
9706 (< (match-beginning 0) (length string)))
9707 (setq notfirst t)
9708 (or (eq (match-beginning 0) 0)
9709 (and (eq (match-beginning 0) (match-end 0))
9710 (eq (match-beginning 0) start))
9711 (setq list
9712 (cons (substring string start (match-beginning 0))
9713 list)))
9714 (setq start (match-end 0)))
9715 (or (eq start (length string))
9716 (setq list
9717 (cons (substring string start)
9718 list)))
9719 (nreverse list)))
9721 (defun org-table-map-tables (function)
9722 "Apply FUNCTION to the start of all tables in the buffer."
9723 (save-excursion
9724 (save-restriction
9725 (widen)
9726 (goto-char (point-min))
9727 (while (re-search-forward org-table-any-line-regexp nil t)
9728 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9729 (beginning-of-line 1)
9730 (if (looking-at org-table-line-regexp)
9731 (save-excursion (funcall function)))
9732 (re-search-forward org-table-any-border-regexp nil 1))))
9733 (message "Mapping tables: done"))
9735 (defvar org-timecnt) ; dynamically scoped parameter
9737 (defun org-table-sum (&optional beg end nlast)
9738 "Sum numbers in region of current table column.
9739 The result will be displayed in the echo area, and will be available
9740 as kill to be inserted with \\[yank].
9742 If there is an active region, it is interpreted as a rectangle and all
9743 numbers in that rectangle will be summed. If there is no active
9744 region and point is located in a table column, sum all numbers in that
9745 column.
9747 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9748 numbers are assumed to be times as well (in decimal hours) and the
9749 numbers are added as such.
9751 If NLAST is a number, only the NLAST fields will actually be summed."
9752 (interactive)
9753 (save-excursion
9754 (let (col (org-timecnt 0) diff h m s org-table-clip)
9755 (cond
9756 ((and beg end)) ; beg and end given explicitly
9757 ((org-region-active-p)
9758 (setq beg (region-beginning) end (region-end)))
9760 (setq col (org-table-current-column))
9761 (goto-char (org-table-begin))
9762 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9763 (error "No table data"))
9764 (org-table-goto-column col)
9765 (setq beg (point))
9766 (goto-char (org-table-end))
9767 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9768 (error "No table data"))
9769 (org-table-goto-column col)
9770 (setq end (point))))
9771 (let* ((items (apply 'append (org-table-copy-region beg end)))
9772 (items1 (cond ((not nlast) items)
9773 ((>= nlast (length items)) items)
9774 (t (setq items (reverse items))
9775 (setcdr (nthcdr (1- nlast) items) nil)
9776 (nreverse items))))
9777 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9778 items1)))
9779 (res (apply '+ numbers))
9780 (sres (if (= org-timecnt 0)
9781 (format "%g" res)
9782 (setq diff (* 3600 res)
9783 h (floor (/ diff 3600)) diff (mod diff 3600)
9784 m (floor (/ diff 60)) diff (mod diff 60)
9785 s diff)
9786 (format "%d:%02d:%02d" h m s))))
9787 (kill-new sres)
9788 (if (interactive-p)
9789 (message "%s"
9790 (substitute-command-keys
9791 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9792 (length numbers) sres))))
9793 sres))))
9795 (defun org-table-get-number-for-summing (s)
9796 (let (n)
9797 (if (string-match "^ *|? *" s)
9798 (setq s (replace-match "" nil nil s)))
9799 (if (string-match " *|? *$" s)
9800 (setq s (replace-match "" nil nil s)))
9801 (setq n (string-to-number s))
9802 (cond
9803 ((and (string-match "0" s)
9804 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9805 ((string-match "\\`[ \t]+\\'" s) nil)
9806 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9807 (let ((h (string-to-number (or (match-string 1 s) "0")))
9808 (m (string-to-number (or (match-string 2 s) "0")))
9809 (s (string-to-number (or (match-string 4 s) "0"))))
9810 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9811 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9812 ((equal n 0) nil)
9813 (t n))))
9815 (defun org-table-current-field-formula (&optional key noerror)
9816 "Return the formula active for the current field.
9817 Assumes that specials are in place.
9818 If KEY is given, return the key to this formula.
9819 Otherwise return the formula preceeded with \"=\" or \":=\"."
9820 (let* ((name (car (rassoc (list (org-current-line)
9821 (org-table-current-column))
9822 org-table-named-field-locations)))
9823 (col (org-table-current-column))
9824 (scol (int-to-string col))
9825 (ref (format "@%d$%d" (org-table-current-dline) col))
9826 (stored-list (org-table-get-stored-formulas noerror))
9827 (ass (or (assoc name stored-list)
9828 (assoc ref stored-list)
9829 (assoc scol stored-list))))
9830 (if key
9831 (car ass)
9832 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9833 (cdr ass))))))
9835 (defun org-table-get-formula (&optional equation named)
9836 "Read a formula from the minibuffer, offer stored formula as default.
9837 When NAMED is non-nil, look for a named equation."
9838 (let* ((stored-list (org-table-get-stored-formulas))
9839 (name (car (rassoc (list (org-current-line)
9840 (org-table-current-column))
9841 org-table-named-field-locations)))
9842 (ref (format "@%d$%d" (org-table-current-dline)
9843 (org-table-current-column)))
9844 (refass (assoc ref stored-list))
9845 (scol (if named
9846 (if name name ref)
9847 (int-to-string (org-table-current-column))))
9848 (dummy (and (or name refass) (not named)
9849 (not (y-or-n-p "Replace field formula with column formula? " ))
9850 (error "Abort")))
9851 (name (or name ref))
9852 (org-table-may-need-update nil)
9853 (stored (cdr (assoc scol stored-list)))
9854 (eq (cond
9855 ((and stored equation (string-match "^ *=? *$" equation))
9856 stored)
9857 ((stringp equation)
9858 equation)
9859 (t (org-table-formula-from-user
9860 (read-string
9861 (org-table-formula-to-user
9862 (format "%s formula %s%s="
9863 (if named "Field" "Column")
9864 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9865 scol))
9866 (if stored (org-table-formula-to-user stored) "")
9867 'org-table-formula-history
9868 )))))
9869 mustsave)
9870 (when (not (string-match "\\S-" eq))
9871 ;; remove formula
9872 (setq stored-list (delq (assoc scol stored-list) stored-list))
9873 (org-table-store-formulas stored-list)
9874 (error "Formula removed"))
9875 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9876 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9877 (if (and name (not named))
9878 ;; We set the column equation, delete the named one.
9879 (setq stored-list (delq (assoc name stored-list) stored-list)
9880 mustsave t))
9881 (if stored
9882 (setcdr (assoc scol stored-list) eq)
9883 (setq stored-list (cons (cons scol eq) stored-list)))
9884 (if (or mustsave (not (equal stored eq)))
9885 (org-table-store-formulas stored-list))
9886 eq))
9888 (defun org-table-store-formulas (alist)
9889 "Store the list of formulas below the current table."
9890 (setq alist (sort alist 'org-table-formula-less-p))
9891 (save-excursion
9892 (goto-char (org-table-end))
9893 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9894 (progn
9895 ;; don't overwrite TBLFM, we might use text properties to store stuff
9896 (goto-char (match-beginning 2))
9897 (delete-region (match-beginning 2) (match-end 0)))
9898 (insert "#+TBLFM:"))
9899 (insert " "
9900 (mapconcat (lambda (x)
9901 (concat
9902 (if (equal (string-to-char (car x)) ?@) "" "$")
9903 (car x) "=" (cdr x)))
9904 alist "::")
9905 "\n")))
9907 (defsubst org-table-formula-make-cmp-string (a)
9908 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9909 (concat
9910 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9911 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9912 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9914 (defun org-table-formula-less-p (a b)
9915 "Compare two formulas for sorting."
9916 (let ((as (org-table-formula-make-cmp-string (car a)))
9917 (bs (org-table-formula-make-cmp-string (car b))))
9918 (and as bs (string< as bs))))
9920 (defun org-table-get-stored-formulas (&optional noerror)
9921 "Return an alist with the stored formulas directly after current table."
9922 (interactive)
9923 (let (scol eq eq-alist strings string seen)
9924 (save-excursion
9925 (goto-char (org-table-end))
9926 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9927 (setq strings (org-split-string (match-string 2) " *:: *"))
9928 (while (setq string (pop strings))
9929 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9930 (setq scol (if (match-end 2)
9931 (match-string 2 string)
9932 (match-string 1 string))
9933 eq (match-string 3 string)
9934 eq-alist (cons (cons scol eq) eq-alist))
9935 (if (member scol seen)
9936 (if noerror
9937 (progn
9938 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9939 (ding)
9940 (sit-for 2))
9941 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9942 (push scol seen))))))
9943 (nreverse eq-alist)))
9945 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9946 "Modify the equations after the table structure has been edited.
9947 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9948 For all numbers larger than LIMIT, shift them by DELTA."
9949 (save-excursion
9950 (goto-char (org-table-end))
9951 (when (looking-at "#\\+TBLFM:")
9952 (let ((re (concat key "\\([0-9]+\\)"))
9953 (re2
9954 (when remove
9955 (if (equal key "$")
9956 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9957 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9958 s n a)
9959 (when remove
9960 (while (re-search-forward re2 (point-at-eol) t)
9961 (replace-match "")))
9962 (while (re-search-forward re (point-at-eol) t)
9963 (setq s (match-string 1) n (string-to-number s))
9964 (cond
9965 ((setq a (assoc s replace))
9966 (replace-match (concat key (cdr a)) t t))
9967 ((and limit (> n limit))
9968 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9970 (defun org-table-get-specials ()
9971 "Get the column names and local parameters for this table."
9972 (save-excursion
9973 (let ((beg (org-table-begin)) (end (org-table-end))
9974 names name fields fields1 field cnt
9975 c v l line col types dlines hlines)
9976 (setq org-table-column-names nil
9977 org-table-local-parameters nil
9978 org-table-named-field-locations nil
9979 org-table-current-begin-line nil
9980 org-table-current-begin-pos nil
9981 org-table-current-line-types nil)
9982 (goto-char beg)
9983 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9984 (setq names (org-split-string (match-string 1) " *| *")
9985 cnt 1)
9986 (while (setq name (pop names))
9987 (setq cnt (1+ cnt))
9988 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9989 (push (cons name (int-to-string cnt)) org-table-column-names))))
9990 (setq org-table-column-names (nreverse org-table-column-names))
9991 (setq org-table-column-name-regexp
9992 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9993 (goto-char beg)
9994 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9995 (setq fields (org-split-string (match-string 1) " *| *"))
9996 (while (setq field (pop fields))
9997 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9998 (push (cons (match-string 1 field) (match-string 2 field))
9999 org-table-local-parameters))))
10000 (goto-char beg)
10001 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10002 (setq c (match-string 1)
10003 fields (org-split-string (match-string 2) " *| *"))
10004 (save-excursion
10005 (beginning-of-line (if (equal c "_") 2 0))
10006 (setq line (org-current-line) col 1)
10007 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10008 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10009 (while (and fields1 (setq field (pop fields)))
10010 (setq v (pop fields1) col (1+ col))
10011 (when (and (stringp field) (stringp v)
10012 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10013 (push (cons field v) org-table-local-parameters)
10014 (push (list field line col) org-table-named-field-locations))))
10015 ;; Analyse the line types
10016 (goto-char beg)
10017 (setq org-table-current-begin-line (org-current-line)
10018 org-table-current-begin-pos (point)
10019 l org-table-current-begin-line)
10020 (while (looking-at "[ \t]*|\\(-\\)?")
10021 (push (if (match-end 1) 'hline 'dline) types)
10022 (if (match-end 1) (push l hlines) (push l dlines))
10023 (beginning-of-line 2)
10024 (setq l (1+ l)))
10025 (setq org-table-current-line-types (apply 'vector (nreverse types))
10026 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10027 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10029 (defun org-table-maybe-eval-formula ()
10030 "Check if the current field starts with \"=\" or \":=\".
10031 If yes, store the formula and apply it."
10032 ;; We already know we are in a table. Get field will only return a formula
10033 ;; when appropriate. It might return a separator line, but no problem.
10034 (when org-table-formula-evaluate-inline
10035 (let* ((field (org-trim (or (org-table-get-field) "")))
10036 named eq)
10037 (when (string-match "^:?=\\(.*\\)" field)
10038 (setq named (equal (string-to-char field) ?:)
10039 eq (match-string 1 field))
10040 (if (or (fboundp 'calc-eval)
10041 (equal (substring eq 0 (min 2 (length eq))) "'("))
10042 (org-table-eval-formula (if named '(4) nil)
10043 (org-table-formula-from-user eq))
10044 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10046 (defvar org-recalc-commands nil
10047 "List of commands triggering the recalculation of a line.
10048 Will be filled automatically during use.")
10050 (defvar org-recalc-marks
10051 '((" " . "Unmarked: no special line, no automatic recalculation")
10052 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10053 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10054 ("!" . "Column name definition line. Reference in formula as $name.")
10055 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10056 ("_" . "Names for values in row below this one.")
10057 ("^" . "Names for values in row above this one.")))
10059 (defun org-table-rotate-recalc-marks (&optional newchar)
10060 "Rotate the recalculation mark in the first column.
10061 If in any row, the first field is not consistent with a mark,
10062 insert a new column for the markers.
10063 When there is an active region, change all the lines in the region,
10064 after prompting for the marking character.
10065 After each change, a message will be displayed indicating the meaning
10066 of the new mark."
10067 (interactive)
10068 (unless (org-at-table-p) (error "Not at a table"))
10069 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10070 (beg (org-table-begin))
10071 (end (org-table-end))
10072 (l (org-current-line))
10073 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10074 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10075 (have-col
10076 (save-excursion
10077 (goto-char beg)
10078 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10079 (col (org-table-current-column))
10080 (forcenew (car (assoc newchar org-recalc-marks)))
10081 epos new)
10082 (when l1
10083 (message "Change region to what mark? Type # * ! $ or SPC: ")
10084 (setq newchar (char-to-string (read-char-exclusive))
10085 forcenew (car (assoc newchar org-recalc-marks))))
10086 (if (and newchar (not forcenew))
10087 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10088 newchar))
10089 (if l1 (goto-line l1))
10090 (save-excursion
10091 (beginning-of-line 1)
10092 (unless (looking-at org-table-dataline-regexp)
10093 (error "Not at a table data line")))
10094 (unless have-col
10095 (org-table-goto-column 1)
10096 (org-table-insert-column)
10097 (org-table-goto-column (1+ col)))
10098 (setq epos (point-at-eol))
10099 (save-excursion
10100 (beginning-of-line 1)
10101 (org-table-get-field
10102 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10103 (concat " "
10104 (setq new (or forcenew
10105 (cadr (member (match-string 1) marks))))
10106 " ")
10107 " # ")))
10108 (if (and l1 l2)
10109 (progn
10110 (goto-line l1)
10111 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10112 (and (looking-at org-table-dataline-regexp)
10113 (org-table-get-field 1 (concat " " new " "))))
10114 (goto-line l1)))
10115 (if (not (= epos (point-at-eol))) (org-table-align))
10116 (goto-line l)
10117 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10119 (defun org-table-maybe-recalculate-line ()
10120 "Recompute the current line if marked for it, and if we haven't just done it."
10121 (interactive)
10122 (and org-table-allow-automatic-line-recalculation
10123 (not (and (memq last-command org-recalc-commands)
10124 (equal org-last-recalc-line (org-current-line))))
10125 (save-excursion (beginning-of-line 1)
10126 (looking-at org-table-auto-recalculate-regexp))
10127 (org-table-recalculate) t))
10129 (defvar org-table-formula-debug nil
10130 "Non-nil means, debug table formulas.
10131 When nil, simply write \"#ERROR\" in corrupted fields.")
10132 (make-variable-buffer-local 'org-table-formula-debug)
10134 (defvar modes)
10135 (defsubst org-set-calc-mode (var &optional value)
10136 (if (stringp var)
10137 (setq var (assoc var '(("D" calc-angle-mode deg)
10138 ("R" calc-angle-mode rad)
10139 ("F" calc-prefer-frac t)
10140 ("S" calc-symbolic-mode t)))
10141 value (nth 2 var) var (nth 1 var)))
10142 (if (memq var modes)
10143 (setcar (cdr (memq var modes)) value)
10144 (cons var (cons value modes)))
10145 modes)
10147 (defun org-table-eval-formula (&optional arg equation
10148 suppress-align suppress-const
10149 suppress-store suppress-analysis)
10150 "Replace the table field value at the cursor by the result of a calculation.
10152 This function makes use of Dave Gillespie's Calc package, in my view the
10153 most exciting program ever written for GNU Emacs. So you need to have Calc
10154 installed in order to use this function.
10156 In a table, this command replaces the value in the current field with the
10157 result of a formula. It also installs the formula as the \"current\" column
10158 formula, by storing it in a special line below the table. When called
10159 with a `C-u' prefix, the current field must ba a named field, and the
10160 formula is installed as valid in only this specific field.
10162 When called with two `C-u' prefixes, insert the active equation
10163 for the field back into the current field, so that it can be
10164 edited there. This is useful in order to use \\[org-table-show-reference]
10165 to check the referenced fields.
10167 When called, the command first prompts for a formula, which is read in
10168 the minibuffer. Previously entered formulas are available through the
10169 history list, and the last used formula is offered as a default.
10170 These stored formulas are adapted correctly when moving, inserting, or
10171 deleting columns with the corresponding commands.
10173 The formula can be any algebraic expression understood by the Calc package.
10174 For details, see the Org-mode manual.
10176 This function can also be called from Lisp programs and offers
10177 additional arguments: EQUATION can be the formula to apply. If this
10178 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10179 used to speed-up recursive calls by by-passing unnecessary aligns.
10180 SUPPRESS-CONST suppresses the interpretation of constants in the
10181 formula, assuming that this has been done already outside the function.
10182 SUPPRESS-STORE means the formula should not be stored, either because
10183 it is already stored, or because it is a modified equation that should
10184 not overwrite the stored one."
10185 (interactive "P")
10186 (org-table-check-inside-data-field)
10187 (or suppress-analysis (org-table-get-specials))
10188 (if (equal arg '(16))
10189 (let ((eq (org-table-current-field-formula)))
10190 (or eq (error "No equation active for current field"))
10191 (org-table-get-field nil eq)
10192 (org-table-align)
10193 (setq org-table-may-need-update t))
10194 (let* (fields
10195 (ndown (if (integerp arg) arg 1))
10196 (org-table-automatic-realign nil)
10197 (case-fold-search nil)
10198 (down (> ndown 1))
10199 (formula (if (and equation suppress-store)
10200 equation
10201 (org-table-get-formula equation (equal arg '(4)))))
10202 (n0 (org-table-current-column))
10203 (modes (copy-sequence org-calc-default-modes))
10204 (numbers nil) ; was a variable, now fixed default
10205 (keep-empty nil)
10206 n form form0 bw fmt x ev orig c lispp literal)
10207 ;; Parse the format string. Since we have a lot of modes, this is
10208 ;; a lot of work. However, I think calc still uses most of the time.
10209 (if (string-match ";" formula)
10210 (let ((tmp (org-split-string formula ";")))
10211 (setq formula (car tmp)
10212 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10213 (nth 1 tmp)))
10214 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10215 (setq c (string-to-char (match-string 1 fmt))
10216 n (string-to-number (match-string 2 fmt)))
10217 (if (= c ?p)
10218 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10219 (setq modes (org-set-calc-mode
10220 'calc-float-format
10221 (list (cdr (assoc c '((?n . float) (?f . fix)
10222 (?s . sci) (?e . eng))))
10223 n))))
10224 (setq fmt (replace-match "" t t fmt)))
10225 (if (string-match "[NT]" fmt)
10226 (setq numbers (equal (match-string 0 fmt) "N")
10227 fmt (replace-match "" t t fmt)))
10228 (if (string-match "L" fmt)
10229 (setq literal t
10230 fmt (replace-match "" t t fmt)))
10231 (if (string-match "E" fmt)
10232 (setq keep-empty t
10233 fmt (replace-match "" t t fmt)))
10234 (while (string-match "[DRFS]" fmt)
10235 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10236 (setq fmt (replace-match "" t t fmt)))
10237 (unless (string-match "\\S-" fmt)
10238 (setq fmt nil))))
10239 (if (and (not suppress-const) org-table-formula-use-constants)
10240 (setq formula (org-table-formula-substitute-names formula)))
10241 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10242 (while (> ndown 0)
10243 (setq fields (org-split-string
10244 (org-no-properties
10245 (buffer-substring (point-at-bol) (point-at-eol)))
10246 " *| *"))
10247 (if (eq numbers t)
10248 (setq fields (mapcar
10249 (lambda (x) (number-to-string (string-to-number x)))
10250 fields)))
10251 (setq ndown (1- ndown))
10252 (setq form (copy-sequence formula)
10253 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10254 (if (and lispp literal) (setq lispp 'literal))
10255 ;; Check for old vertical references
10256 (setq form (org-rewrite-old-row-references form))
10257 ;; Insert complex ranges
10258 (while (string-match org-table-range-regexp form)
10259 (setq form
10260 (replace-match
10261 (save-match-data
10262 (org-table-make-reference
10263 (org-table-get-range (match-string 0 form) nil n0)
10264 keep-empty numbers lispp))
10265 t t form)))
10266 ;; Insert simple ranges
10267 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10268 (setq form
10269 (replace-match
10270 (save-match-data
10271 (org-table-make-reference
10272 (org-sublist
10273 fields (string-to-number (match-string 1 form))
10274 (string-to-number (match-string 2 form)))
10275 keep-empty numbers lispp))
10276 t t form)))
10277 (setq form0 form)
10278 ;; Insert the references to fields in same row
10279 (while (string-match "\\$\\([0-9]+\\)" form)
10280 (setq n (string-to-number (match-string 1 form))
10281 x (nth (1- (if (= n 0) n0 n)) fields))
10282 (unless x (error "Invalid field specifier \"%s\""
10283 (match-string 0 form)))
10284 (setq form (replace-match
10285 (save-match-data
10286 (org-table-make-reference x nil numbers lispp))
10287 t t form)))
10289 (if lispp
10290 (setq ev (condition-case nil
10291 (eval (eval (read form)))
10292 (error "#ERROR"))
10293 ev (if (numberp ev) (number-to-string ev) ev))
10294 (or (fboundp 'calc-eval)
10295 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10296 (setq ev (calc-eval (cons form modes)
10297 (if numbers 'num))))
10299 (when org-table-formula-debug
10300 (with-output-to-temp-buffer "*Substitution History*"
10301 (princ (format "Substitution history of formula
10302 Orig: %s
10303 $xyz-> %s
10304 @r$c-> %s
10305 $1-> %s\n" orig formula form0 form))
10306 (if (listp ev)
10307 (princ (format " %s^\nError: %s"
10308 (make-string (car ev) ?\-) (nth 1 ev)))
10309 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10310 ev (or fmt "NONE")
10311 (if fmt (format fmt (string-to-number ev)) ev)))))
10312 (setq bw (get-buffer-window "*Substitution History*"))
10313 (shrink-window-if-larger-than-buffer bw)
10314 (unless (and (interactive-p) (not ndown))
10315 (unless (let (inhibit-redisplay)
10316 (y-or-n-p "Debugging Formula. Continue to next? "))
10317 (org-table-align)
10318 (error "Abort"))
10319 (delete-window bw)
10320 (message "")))
10321 (if (listp ev) (setq fmt nil ev "#ERROR"))
10322 (org-table-justify-field-maybe
10323 (if fmt (format fmt (string-to-number ev)) ev))
10324 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10325 (call-interactively 'org-return)
10326 (setq ndown 0)))
10327 (and down (org-table-maybe-recalculate-line))
10328 (or suppress-align (and org-table-may-need-update
10329 (org-table-align))))))
10331 (defun org-table-put-field-property (prop value)
10332 (save-excursion
10333 (put-text-property (progn (skip-chars-backward "^|") (point))
10334 (progn (skip-chars-forward "^|") (point))
10335 prop value)))
10337 (defun org-table-get-range (desc &optional tbeg col highlight)
10338 "Get a calc vector from a column, accorting to descriptor DESC.
10339 Optional arguments TBEG and COL can give the beginning of the table and
10340 the current column, to avoid unnecessary parsing.
10341 HIGHLIGHT means, just highlight the range."
10342 (if (not (equal (string-to-char desc) ?@))
10343 (setq desc (concat "@" desc)))
10344 (save-excursion
10345 (or tbeg (setq tbeg (org-table-begin)))
10346 (or col (setq col (org-table-current-column)))
10347 (let ((thisline (org-current-line))
10348 beg end c1 c2 r1 r2 rangep tmp)
10349 (unless (string-match org-table-range-regexp desc)
10350 (error "Invalid table range specifier `%s'" desc))
10351 (setq rangep (match-end 3)
10352 r1 (and (match-end 1) (match-string 1 desc))
10353 r2 (and (match-end 4) (match-string 4 desc))
10354 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10355 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10357 (and c1 (setq c1 (+ (string-to-number c1)
10358 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10359 (and c2 (setq c2 (+ (string-to-number c2)
10360 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10361 (if (equal r1 "") (setq r1 nil))
10362 (if (equal r2 "") (setq r2 nil))
10363 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10364 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10365 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10366 (if (not r1) (setq r1 thisline))
10367 (if (not r2) (setq r2 thisline))
10368 (if (not c1) (setq c1 col))
10369 (if (not c2) (setq c2 col))
10370 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10371 ;; just one field
10372 (progn
10373 (goto-line r1)
10374 (while (not (looking-at org-table-dataline-regexp))
10375 (beginning-of-line 2))
10376 (prog1 (org-trim (org-table-get-field c1))
10377 (if highlight (org-table-highlight-rectangle (point) (point)))))
10378 ;; A range, return a vector
10379 ;; First sort the numbers to get a regular ractangle
10380 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10381 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10382 (goto-line r1)
10383 (while (not (looking-at org-table-dataline-regexp))
10384 (beginning-of-line 2))
10385 (org-table-goto-column c1)
10386 (setq beg (point))
10387 (goto-line r2)
10388 (while (not (looking-at org-table-dataline-regexp))
10389 (beginning-of-line 0))
10390 (org-table-goto-column c2)
10391 (setq end (point))
10392 (if highlight
10393 (org-table-highlight-rectangle
10394 beg (progn (skip-chars-forward "^|\n") (point))))
10395 ;; return string representation of calc vector
10396 (mapcar 'org-trim
10397 (apply 'append (org-table-copy-region beg end)))))))
10399 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10400 "Analyze descriptor DESC and retrieve the corresponding line number.
10401 The cursor is currently in line CLINE, the table begins in line BLINE,
10402 and TABLE is a vector with line types."
10403 (if (string-match "^[0-9]+$" desc)
10404 (aref org-table-dlines (string-to-number desc))
10405 (setq cline (or cline (org-current-line))
10406 bline (or bline org-table-current-begin-line)
10407 table (or table org-table-current-line-types))
10408 (if (or
10409 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10410 ;; 1 2 3 4 5 6
10411 (and (not (match-end 3)) (not (match-end 6)))
10412 (and (match-end 3) (match-end 6) (not (match-end 5))))
10413 (error "invalid row descriptor `%s'" desc))
10414 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10415 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10416 (odir (and (match-end 5) (match-string 5 desc)))
10417 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10418 (i (- cline bline))
10419 (rel (and (match-end 6)
10420 (or (and (match-end 1) (not (match-end 3)))
10421 (match-end 5)))))
10422 (if (and hn (not hdir))
10423 (progn
10424 (setq i 0 hdir "+")
10425 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10426 (if (and (not hn) on (not odir))
10427 (error "should never happen");;(aref org-table-dlines on)
10428 (if (and hn (> hn 0))
10429 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10430 (if on
10431 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10432 (+ bline i)))))
10434 (defun org-find-row-type (table i type backwards relative n)
10435 (let ((l (length table)))
10436 (while (> n 0)
10437 (while (and (setq i (+ i (if backwards -1 1)))
10438 (>= i 0) (< i l)
10439 (not (eq (aref table i) type))
10440 (if (and relative (eq (aref table i) 'hline))
10441 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10442 t)))
10443 (setq n (1- n)))
10444 (if (or (< i 0) (>= i l))
10445 (error "Row descriptior leads outside table")
10446 i)))
10448 (defun org-rewrite-old-row-references (s)
10449 (if (string-match "&[-+0-9I]" s)
10450 (error "Formula contains old &row reference, please rewrite using @-syntax")
10453 (defun org-table-make-reference (elements keep-empty numbers lispp)
10454 "Convert list ELEMENTS to something appropriate to insert into formula.
10455 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10456 NUMBERS indicates that everything should be converted to numbers.
10457 LISPP means to return something appropriate for a Lisp list."
10458 (if (stringp elements) ; just a single val
10459 (if lispp
10460 (if (eq lispp 'literal)
10461 elements
10462 (prin1-to-string (if numbers (string-to-number elements) elements)))
10463 (if (equal elements "") (setq elements "0"))
10464 (if numbers (number-to-string (string-to-number elements)) elements))
10465 (unless keep-empty
10466 (setq elements
10467 (delq nil
10468 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10469 elements))))
10470 (setq elements (or elements '("0")))
10471 (if lispp
10472 (mapconcat
10473 (lambda (x)
10474 (if (eq lispp 'literal)
10476 (prin1-to-string (if numbers (string-to-number x) x))))
10477 elements " ")
10478 (concat "[" (mapconcat
10479 (lambda (x)
10480 (if numbers (number-to-string (string-to-number x)) x))
10481 elements
10482 ",") "]"))))
10484 (defun org-table-recalculate (&optional all noalign)
10485 "Recalculate the current table line by applying all stored formulas.
10486 With prefix arg ALL, do this for all lines in the table."
10487 (interactive "P")
10488 (or (memq this-command org-recalc-commands)
10489 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10490 (unless (org-at-table-p) (error "Not at a table"))
10491 (if (equal all '(16))
10492 (org-table-iterate)
10493 (org-table-get-specials)
10494 (let* ((eqlist (sort (org-table-get-stored-formulas)
10495 (lambda (a b) (string< (car a) (car b)))))
10496 (inhibit-redisplay (not debug-on-error))
10497 (line-re org-table-dataline-regexp)
10498 (thisline (org-current-line))
10499 (thiscol (org-table-current-column))
10500 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10501 ;; Insert constants in all formulas
10502 (setq eqlist
10503 (mapcar (lambda (x)
10504 (setcdr x (org-table-formula-substitute-names (cdr x)))
10506 eqlist))
10507 ;; Split the equation list
10508 (while (setq eq (pop eqlist))
10509 (if (<= (string-to-char (car eq)) ?9)
10510 (push eq eqlnum)
10511 (push eq eqlname)))
10512 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10513 (if all
10514 (progn
10515 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10516 (goto-char (setq beg (org-table-begin)))
10517 (if (re-search-forward org-table-calculate-mark-regexp end t)
10518 ;; This is a table with marked lines, compute selected lines
10519 (setq line-re org-table-recalculate-regexp)
10520 ;; Move forward to the first non-header line
10521 (if (and (re-search-forward org-table-dataline-regexp end t)
10522 (re-search-forward org-table-hline-regexp end t)
10523 (re-search-forward org-table-dataline-regexp end t))
10524 (setq beg (match-beginning 0))
10525 nil))) ;; just leave beg where it is
10526 (setq beg (point-at-bol)
10527 end (move-marker (make-marker) (1+ (point-at-eol)))))
10528 (goto-char beg)
10529 (and all (message "Re-applying formulas to full table..."))
10531 ;; First find the named fields, and mark them untouchanble
10532 (remove-text-properties beg end '(org-untouchable t))
10533 (while (setq eq (pop eqlname))
10534 (setq name (car eq)
10535 a (assoc name org-table-named-field-locations))
10536 (and (not a)
10537 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10538 (setq a (list name
10539 (aref org-table-dlines
10540 (string-to-number (match-string 1 name)))
10541 (string-to-number (match-string 2 name)))))
10542 (when (and a (or all (equal (nth 1 a) thisline)))
10543 (message "Re-applying formula to field: %s" name)
10544 (goto-line (nth 1 a))
10545 (org-table-goto-column (nth 2 a))
10546 (push (append a (list (cdr eq))) eqlname1)
10547 (org-table-put-field-property :org-untouchable t)))
10549 ;; Now evauluate the column formulas, but skip fields covered by
10550 ;; field formulas
10551 (goto-char beg)
10552 (while (re-search-forward line-re end t)
10553 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10554 ;; Unprotected line, recalculate
10555 (and all (message "Re-applying formulas to full table...(line %d)"
10556 (setq cnt (1+ cnt))))
10557 (setq org-last-recalc-line (org-current-line))
10558 (setq eql eqlnum)
10559 (while (setq entry (pop eql))
10560 (goto-line org-last-recalc-line)
10561 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10562 (unless (get-text-property (point) :org-untouchable)
10563 (org-table-eval-formula nil (cdr entry)
10564 'noalign 'nocst 'nostore 'noanalysis)))))
10566 ;; Now evaluate the field formulas
10567 (while (setq eq (pop eqlname1))
10568 (message "Re-applying formula to field: %s" (car eq))
10569 (goto-line (nth 1 eq))
10570 (org-table-goto-column (nth 2 eq))
10571 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10572 'nostore 'noanalysis))
10574 (goto-line thisline)
10575 (org-table-goto-column thiscol)
10576 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10577 (or noalign (and org-table-may-need-update (org-table-align))
10578 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10580 ;; back to initial position
10581 (message "Re-applying formulas...done")
10582 (goto-line thisline)
10583 (org-table-goto-column thiscol)
10584 (or noalign (and org-table-may-need-update (org-table-align))
10585 (and all (message "Re-applying formulas...done"))))))
10587 (defun org-table-iterate (&optional arg)
10588 "Recalculate the table until it does not change anymore."
10589 (interactive "P")
10590 (let ((imax (if arg (prefix-numeric-value arg) 10))
10591 (i 0)
10592 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10593 thistbl)
10594 (catch 'exit
10595 (while (< i imax)
10596 (setq i (1+ i))
10597 (org-table-recalculate 'all)
10598 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10599 (if (not (string= lasttbl thistbl))
10600 (setq lasttbl thistbl)
10601 (if (> i 1)
10602 (message "Convergence after %d iterations" i)
10603 (message "Table was already stable"))
10604 (throw 'exit t)))
10605 (error "No convergence after %d iterations" i))))
10607 (defun org-table-formula-substitute-names (f)
10608 "Replace $const with values in string F."
10609 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10610 ;; First, check for column names
10611 (while (setq start (string-match org-table-column-name-regexp f start))
10612 (setq start (1+ start))
10613 (setq a (assoc (match-string 1 f) org-table-column-names))
10614 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10615 ;; Parameters and constants
10616 (setq start 0)
10617 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10618 (setq start (1+ start))
10619 (if (setq a (save-match-data
10620 (org-table-get-constant (match-string 1 f))))
10621 (setq f (replace-match
10622 (concat (if pp "(") a (if pp ")")) t t f))))
10623 (if org-table-formula-debug
10624 (put-text-property 0 (length f) :orig-formula f1 f))
10627 (defun org-table-get-constant (const)
10628 "Find the value for a parameter or constant in a formula.
10629 Parameters get priority."
10630 (or (cdr (assoc const org-table-local-parameters))
10631 (cdr (assoc const org-table-formula-constants-local))
10632 (cdr (assoc const org-table-formula-constants))
10633 (and (fboundp 'constants-get) (constants-get const))
10634 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10635 (org-entry-get nil (substring const 5) 'inherit))
10636 "#UNDEFINED_NAME"))
10638 (defvar org-table-fedit-map
10639 (let ((map (make-sparse-keymap)))
10640 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10641 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10642 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10643 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10644 (org-defkey map "\C-c?" 'org-table-show-reference)
10645 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10646 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10647 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10648 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10649 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10650 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10651 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10652 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10653 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10654 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10655 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10656 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10657 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10658 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10659 map))
10661 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10662 '("Edit-Formulas"
10663 ["Finish and Install" org-table-fedit-finish t]
10664 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10665 ["Abort" org-table-fedit-abort t]
10666 "--"
10667 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10668 ["Complete Lisp Symbol" lisp-complete-symbol t]
10669 "--"
10670 "Shift Reference at Point"
10671 ["Up" org-table-fedit-ref-up t]
10672 ["Down" org-table-fedit-ref-down t]
10673 ["Left" org-table-fedit-ref-left t]
10674 ["Right" org-table-fedit-ref-right t]
10676 "Change Test Row for Column Formulas"
10677 ["Up" org-table-fedit-line-up t]
10678 ["Down" org-table-fedit-line-down t]
10679 "--"
10680 ["Scroll Table Window" org-table-fedit-scroll t]
10681 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10682 ["Show Table Grid" org-table-fedit-toggle-coordinates
10683 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10684 org-table-overlay-coordinates)]
10685 "--"
10686 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10687 :style toggle :selected org-table-buffer-is-an]))
10689 (defvar org-pos)
10691 (defun org-table-edit-formulas ()
10692 "Edit the formulas of the current table in a separate buffer."
10693 (interactive)
10694 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10695 (beginning-of-line 0))
10696 (unless (org-at-table-p) (error "Not at a table"))
10697 (org-table-get-specials)
10698 (let ((key (org-table-current-field-formula 'key 'noerror))
10699 (eql (sort (org-table-get-stored-formulas 'noerror)
10700 'org-table-formula-less-p))
10701 (pos (move-marker (make-marker) (point)))
10702 (startline 1)
10703 (wc (current-window-configuration))
10704 (titles '((column . "# Column Formulas\n")
10705 (field . "# Field Formulas\n")
10706 (named . "# Named Field Formulas\n")))
10707 entry s type title)
10708 (org-switch-to-buffer-other-window "*Edit Formulas*")
10709 (erase-buffer)
10710 ;; Keep global-font-lock-mode from turning on font-lock-mode
10711 (let ((font-lock-global-modes '(not fundamental-mode)))
10712 (fundamental-mode))
10713 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10714 (org-set-local 'org-pos pos)
10715 (org-set-local 'org-window-configuration wc)
10716 (use-local-map org-table-fedit-map)
10717 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10718 (easy-menu-add org-table-fedit-menu)
10719 (setq startline (org-current-line))
10720 (while (setq entry (pop eql))
10721 (setq type (cond
10722 ((equal (string-to-char (car entry)) ?@) 'field)
10723 ((string-match "^[0-9]" (car entry)) 'column)
10724 (t 'named)))
10725 (when (setq title (assq type titles))
10726 (or (bobp) (insert "\n"))
10727 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10728 (setq titles (delq title titles)))
10729 (if (equal key (car entry)) (setq startline (org-current-line)))
10730 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10731 (car entry) " = " (cdr entry) "\n"))
10732 (remove-text-properties 0 (length s) '(face nil) s)
10733 (insert s))
10734 (if (eq org-table-use-standard-references t)
10735 (org-table-fedit-toggle-ref-type))
10736 (goto-line startline)
10737 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10739 (defun org-table-fedit-post-command ()
10740 (when (not (memq this-command '(lisp-complete-symbol)))
10741 (let ((win (selected-window)))
10742 (save-excursion
10743 (condition-case nil
10744 (org-table-show-reference)
10745 (error nil))
10746 (select-window win)))))
10748 (defun org-table-formula-to-user (s)
10749 "Convert a formula from internal to user representation."
10750 (if (eq org-table-use-standard-references t)
10751 (org-table-convert-refs-to-an s)
10754 (defun org-table-formula-from-user (s)
10755 "Convert a formula from user to internal representation."
10756 (if org-table-use-standard-references
10757 (org-table-convert-refs-to-rc s)
10760 (defun org-table-convert-refs-to-rc (s)
10761 "Convert spreadsheet references from AB7 to @7$28.
10762 Works for single references, but also for entire formulas and even the
10763 full TBLFM line."
10764 (let ((start 0))
10765 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10766 (cond
10767 ((match-end 3)
10768 ;; format match, just advance
10769 (setq start (match-end 0)))
10770 ((and (> (match-beginning 0) 0)
10771 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10772 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10773 ;; 3.e5 or something like this.
10774 (setq start (match-end 0)))
10776 (setq start (match-beginning 0)
10777 s (replace-match
10778 (if (equal (match-string 2 s) "&")
10779 (format "$%d" (org-letters-to-number (match-string 1 s)))
10780 (format "@%d$%d"
10781 (string-to-number (match-string 2 s))
10782 (org-letters-to-number (match-string 1 s))))
10783 t t s)))))
10786 (defun org-table-convert-refs-to-an (s)
10787 "Convert spreadsheet references from to @7$28 to AB7.
10788 Works for single references, but also for entire formulas and even the
10789 full TBLFM line."
10790 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10791 (setq s (replace-match
10792 (format "%s%d"
10793 (org-number-to-letters
10794 (string-to-number (match-string 2 s)))
10795 (string-to-number (match-string 1 s)))
10796 t t s)))
10797 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10798 (setq s (replace-match (concat "\\1"
10799 (org-number-to-letters
10800 (string-to-number (match-string 2 s))) "&")
10801 t nil s)))
10804 (defun org-letters-to-number (s)
10805 "Convert a base 26 number represented by letters into an integer.
10806 For example: AB -> 28."
10807 (let ((n 0))
10808 (setq s (upcase s))
10809 (while (> (length s) 0)
10810 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10811 s (substring s 1)))
10814 (defun org-number-to-letters (n)
10815 "Convert an integer into a base 26 number represented by letters.
10816 For example: 28 -> AB."
10817 (let ((s ""))
10818 (while (> n 0)
10819 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10820 n (/ (1- n) 26)))
10823 (defun org-table-fedit-convert-buffer (function)
10824 "Convert all references in this buffer, using FUNTION."
10825 (let ((line (org-current-line)))
10826 (goto-char (point-min))
10827 (while (not (eobp))
10828 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10829 (delete-region (point) (point-at-eol))
10830 (or (eobp) (forward-char 1)))
10831 (goto-line line)))
10833 (defun org-table-fedit-toggle-ref-type ()
10834 "Convert all references in the buffer from B3 to @3$2 and back."
10835 (interactive)
10836 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10837 (org-table-fedit-convert-buffer
10838 (if org-table-buffer-is-an
10839 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10840 (message "Reference type switched to %s"
10841 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10843 (defun org-table-fedit-ref-up ()
10844 "Shift the reference at point one row/hline up."
10845 (interactive)
10846 (org-table-fedit-shift-reference 'up))
10847 (defun org-table-fedit-ref-down ()
10848 "Shift the reference at point one row/hline down."
10849 (interactive)
10850 (org-table-fedit-shift-reference 'down))
10851 (defun org-table-fedit-ref-left ()
10852 "Shift the reference at point one field to the left."
10853 (interactive)
10854 (org-table-fedit-shift-reference 'left))
10855 (defun org-table-fedit-ref-right ()
10856 "Shift the reference at point one field to the right."
10857 (interactive)
10858 (org-table-fedit-shift-reference 'right))
10860 (defun org-table-fedit-shift-reference (dir)
10861 (cond
10862 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10863 (if (memq dir '(left right))
10864 (org-rematch-and-replace 1 (eq dir 'left))
10865 (error "Cannot shift reference in this direction")))
10866 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10867 ;; A B3-like reference
10868 (if (memq dir '(up down))
10869 (org-rematch-and-replace 2 (eq dir 'up))
10870 (org-rematch-and-replace 1 (eq dir 'left))))
10871 ((org-at-regexp-p
10872 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10873 ;; An internal reference
10874 (if (memq dir '(up down))
10875 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10876 (org-rematch-and-replace 5 (eq dir 'left))))))
10878 (defun org-rematch-and-replace (n &optional decr hline)
10879 "Re-match the group N, and replace it with the shifted refrence."
10880 (or (match-end n) (error "Cannot shift reference in this direction"))
10881 (goto-char (match-beginning n))
10882 (and (looking-at (regexp-quote (match-string n)))
10883 (replace-match (org-shift-refpart (match-string 0) decr hline)
10884 t t)))
10886 (defun org-shift-refpart (ref &optional decr hline)
10887 "Shift a refrence part REF.
10888 If DECR is set, decrease the references row/column, else increase.
10889 If HLINE is set, this may be a hline reference, it certainly is not
10890 a translation reference."
10891 (save-match-data
10892 (let* ((sign (string-match "^[-+]" ref)) n)
10894 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10895 (cond
10896 ((and hline (string-match "^I+" ref))
10897 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10898 (setq n (+ n (if decr -1 1)))
10899 (if (= n 0) (setq n (+ n (if decr -1 1))))
10900 (if sign
10901 (setq sign (if (< n 0) "-" "+") n (abs n))
10902 (setq n (max 1 n)))
10903 (concat sign (make-string n ?I)))
10905 ((string-match "^[0-9]+" ref)
10906 (setq n (string-to-number (concat sign ref)))
10907 (setq n (+ n (if decr -1 1)))
10908 (if sign
10909 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10910 (number-to-string (max 1 n))))
10912 ((string-match "^[a-zA-Z]+" ref)
10913 (org-number-to-letters
10914 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10916 (t (error "Cannot shift reference"))))))
10918 (defun org-table-fedit-toggle-coordinates ()
10919 "Toggle the display of coordinates in the refrenced table."
10920 (interactive)
10921 (let ((pos (marker-position org-pos)))
10922 (with-current-buffer (marker-buffer org-pos)
10923 (save-excursion
10924 (goto-char pos)
10925 (org-table-toggle-coordinate-overlays)))))
10927 (defun org-table-fedit-finish (&optional arg)
10928 "Parse the buffer for formula definitions and install them.
10929 With prefix ARG, apply the new formulas to the table."
10930 (interactive "P")
10931 (org-table-remove-rectangle-highlight)
10932 (if org-table-use-standard-references
10933 (progn
10934 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10935 (setq org-table-buffer-is-an nil)))
10936 (let ((pos org-pos) eql var form)
10937 (goto-char (point-min))
10938 (while (re-search-forward
10939 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10940 nil t)
10941 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10942 form (match-string 3))
10943 (setq form (org-trim form))
10944 (when (not (equal form ""))
10945 (while (string-match "[ \t]*\n[ \t]*" form)
10946 (setq form (replace-match " " t t form)))
10947 (when (assoc var eql)
10948 (error "Double formulas for %s" var))
10949 (push (cons var form) eql)))
10950 (setq org-pos nil)
10951 (set-window-configuration org-window-configuration)
10952 (select-window (get-buffer-window (marker-buffer pos)))
10953 (goto-char pos)
10954 (unless (org-at-table-p)
10955 (error "Lost table position - cannot install formulae"))
10956 (org-table-store-formulas eql)
10957 (move-marker pos nil)
10958 (kill-buffer "*Edit Formulas*")
10959 (if arg
10960 (org-table-recalculate 'all)
10961 (message "New formulas installed - press C-u C-c C-c to apply."))))
10963 (defun org-table-fedit-abort ()
10964 "Abort editing formulas, without installing the changes."
10965 (interactive)
10966 (org-table-remove-rectangle-highlight)
10967 (let ((pos org-pos))
10968 (set-window-configuration org-window-configuration)
10969 (select-window (get-buffer-window (marker-buffer pos)))
10970 (goto-char pos)
10971 (move-marker pos nil)
10972 (message "Formula editing aborted without installing changes")))
10974 (defun org-table-fedit-lisp-indent ()
10975 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10976 (interactive)
10977 (let ((pos (point)) beg end ind)
10978 (beginning-of-line 1)
10979 (cond
10980 ((looking-at "[ \t]")
10981 (goto-char pos)
10982 (call-interactively 'lisp-indent-line))
10983 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10984 ((not (fboundp 'pp-buffer))
10985 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10986 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10987 (goto-char (- (match-end 0) 2))
10988 (setq beg (point))
10989 (setq ind (make-string (current-column) ?\ ))
10990 (condition-case nil (forward-sexp 1)
10991 (error
10992 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10993 (setq end (point))
10994 (save-restriction
10995 (narrow-to-region beg end)
10996 (if (eq last-command this-command)
10997 (progn
10998 (goto-char (point-min))
10999 (setq this-command nil)
11000 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11001 (replace-match " ")))
11002 (pp-buffer)
11003 (untabify (point-min) (point-max))
11004 (goto-char (1+ (point-min)))
11005 (while (re-search-forward "^." nil t)
11006 (beginning-of-line 1)
11007 (insert ind))
11008 (goto-char (point-max))
11009 (backward-delete-char 1)))
11010 (goto-char beg))
11011 (t nil))))
11013 (defvar org-show-positions nil)
11015 (defun org-table-show-reference (&optional local)
11016 "Show the location/value of the $ expression at point."
11017 (interactive)
11018 (org-table-remove-rectangle-highlight)
11019 (catch 'exit
11020 (let ((pos (if local (point) org-pos))
11021 (face2 'highlight)
11022 (org-inhibit-highlight-removal t)
11023 (win (selected-window))
11024 (org-show-positions nil)
11025 var name e what match dest)
11026 (if local (org-table-get-specials))
11027 (setq what (cond
11028 ((or (org-at-regexp-p org-table-range-regexp2)
11029 (org-at-regexp-p org-table-translate-regexp)
11030 (org-at-regexp-p org-table-range-regexp))
11031 (setq match
11032 (save-match-data
11033 (org-table-convert-refs-to-rc (match-string 0))))
11034 'range)
11035 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11036 ((org-at-regexp-p "\\$[0-9]+") 'column)
11037 ((not local) nil)
11038 (t (error "No reference at point")))
11039 match (and what (or match (match-string 0))))
11040 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11041 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11042 'secondary-selection))
11043 (org-add-hook 'before-change-functions
11044 'org-table-remove-rectangle-highlight)
11045 (if (eq what 'name) (setq var (substring match 1)))
11046 (when (eq what 'range)
11047 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11048 (setq match (org-table-formula-substitute-names match)))
11049 (unless local
11050 (save-excursion
11051 (end-of-line 1)
11052 (re-search-backward "^\\S-" nil t)
11053 (beginning-of-line 1)
11054 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11055 (setq dest
11056 (save-match-data
11057 (org-table-convert-refs-to-rc (match-string 1))))
11058 (org-table-add-rectangle-overlay
11059 (match-beginning 1) (match-end 1) face2))))
11060 (if (and (markerp pos) (marker-buffer pos))
11061 (if (get-buffer-window (marker-buffer pos))
11062 (select-window (get-buffer-window (marker-buffer pos)))
11063 (org-switch-to-buffer-other-window (get-buffer-window
11064 (marker-buffer pos)))))
11065 (goto-char pos)
11066 (org-table-force-dataline)
11067 (when dest
11068 (setq name (substring dest 1))
11069 (cond
11070 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11071 (setq e (assoc name org-table-named-field-locations))
11072 (goto-line (nth 1 e))
11073 (org-table-goto-column (nth 2 e)))
11074 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11075 (let ((l (string-to-number (match-string 1 dest)))
11076 (c (string-to-number (match-string 2 dest))))
11077 (goto-line (aref org-table-dlines l))
11078 (org-table-goto-column c)))
11079 (t (org-table-goto-column (string-to-number name))))
11080 (move-marker pos (point))
11081 (org-table-highlight-rectangle nil nil face2))
11082 (cond
11083 ((equal dest match))
11084 ((not match))
11085 ((eq what 'range)
11086 (condition-case nil
11087 (save-excursion
11088 (org-table-get-range match nil nil 'highlight))
11089 (error nil)))
11090 ((setq e (assoc var org-table-named-field-locations))
11091 (goto-line (nth 1 e))
11092 (org-table-goto-column (nth 2 e))
11093 (org-table-highlight-rectangle (point) (point))
11094 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11095 ((setq e (assoc var org-table-column-names))
11096 (org-table-goto-column (string-to-number (cdr e)))
11097 (org-table-highlight-rectangle (point) (point))
11098 (goto-char (org-table-begin))
11099 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11100 (org-table-end) t)
11101 (progn
11102 (goto-char (match-beginning 1))
11103 (org-table-highlight-rectangle)
11104 (message "Named column (column %s)" (cdr e)))
11105 (error "Column name not found")))
11106 ((eq what 'column)
11107 ;; column number
11108 (org-table-goto-column (string-to-number (substring match 1)))
11109 (org-table-highlight-rectangle (point) (point))
11110 (message "Column %s" (substring match 1)))
11111 ((setq e (assoc var org-table-local-parameters))
11112 (goto-char (org-table-begin))
11113 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11114 (progn
11115 (goto-char (match-beginning 1))
11116 (org-table-highlight-rectangle)
11117 (message "Local parameter."))
11118 (error "Parameter not found")))
11120 (cond
11121 ((not var) (error "No reference at point"))
11122 ((setq e (assoc var org-table-formula-constants-local))
11123 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11124 var (cdr e)))
11125 ((setq e (assoc var org-table-formula-constants))
11126 (message "Constant: $%s=%s in `org-table-formula-constants'."
11127 var (cdr e)))
11128 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11129 (message "Constant: $%s=%s, from `constants.el'%s."
11130 var e (format " (%s units)" constants-unit-system)))
11131 (t (error "Undefined name $%s" var)))))
11132 (goto-char pos)
11133 (when (and org-show-positions
11134 (not (memq this-command '(org-table-fedit-scroll
11135 org-table-fedit-scroll-down))))
11136 (push pos org-show-positions)
11137 (push org-table-current-begin-pos org-show-positions)
11138 (let ((min (apply 'min org-show-positions))
11139 (max (apply 'max org-show-positions)))
11140 (goto-char min) (recenter 0)
11141 (goto-char max)
11142 (or (pos-visible-in-window-p max) (recenter -1))))
11143 (select-window win))))
11145 (defun org-table-force-dataline ()
11146 "Make sure the cursor is in a dataline in a table."
11147 (unless (save-excursion
11148 (beginning-of-line 1)
11149 (looking-at org-table-dataline-regexp))
11150 (let* ((re org-table-dataline-regexp)
11151 (p1 (save-excursion (re-search-forward re nil 'move)))
11152 (p2 (save-excursion (re-search-backward re nil 'move))))
11153 (cond ((and p1 p2)
11154 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11155 p1 p2)))
11156 ((or p1 p2) (goto-char (or p1 p2)))
11157 (t (error "No table dataline around here"))))))
11159 (defun org-table-fedit-line-up ()
11160 "Move cursor one line up in the window showing the table."
11161 (interactive)
11162 (org-table-fedit-move 'previous-line))
11164 (defun org-table-fedit-line-down ()
11165 "Move cursor one line down in the window showing the table."
11166 (interactive)
11167 (org-table-fedit-move 'next-line))
11169 (defun org-table-fedit-move (command)
11170 "Move the cursor in the window shoinw the table.
11171 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11172 (let ((org-table-allow-automatic-line-recalculation nil)
11173 (pos org-pos) (win (selected-window)) p)
11174 (select-window (get-buffer-window (marker-buffer org-pos)))
11175 (setq p (point))
11176 (call-interactively command)
11177 (while (and (org-at-table-p)
11178 (org-at-table-hline-p))
11179 (call-interactively command))
11180 (or (org-at-table-p) (goto-char p))
11181 (move-marker pos (point))
11182 (select-window win)))
11184 (defun org-table-fedit-scroll (N)
11185 (interactive "p")
11186 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11187 (scroll-other-window N)))
11189 (defun org-table-fedit-scroll-down (N)
11190 (interactive "p")
11191 (org-table-fedit-scroll (- N)))
11193 (defvar org-table-rectangle-overlays nil)
11195 (defun org-table-add-rectangle-overlay (beg end &optional face)
11196 "Add a new overlay."
11197 (let ((ov (org-make-overlay beg end)))
11198 (org-overlay-put ov 'face (or face 'secondary-selection))
11199 (push ov org-table-rectangle-overlays)))
11201 (defun org-table-highlight-rectangle (&optional beg end face)
11202 "Highlight rectangular region in a table."
11203 (setq beg (or beg (point)) end (or end (point)))
11204 (let ((b (min beg end))
11205 (e (max beg end))
11206 l1 c1 l2 c2 tmp)
11207 (and (boundp 'org-show-positions)
11208 (setq org-show-positions (cons b (cons e org-show-positions))))
11209 (goto-char (min beg end))
11210 (setq l1 (org-current-line)
11211 c1 (org-table-current-column))
11212 (goto-char (max beg end))
11213 (setq l2 (org-current-line)
11214 c2 (org-table-current-column))
11215 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11216 (goto-line l1)
11217 (beginning-of-line 1)
11218 (loop for line from l1 to l2 do
11219 (when (looking-at org-table-dataline-regexp)
11220 (org-table-goto-column c1)
11221 (skip-chars-backward "^|\n") (setq beg (point))
11222 (org-table-goto-column c2)
11223 (skip-chars-forward "^|\n") (setq end (point))
11224 (org-table-add-rectangle-overlay beg end face))
11225 (beginning-of-line 2))
11226 (goto-char b))
11227 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11229 (defun org-table-remove-rectangle-highlight (&rest ignore)
11230 "Remove the rectangle overlays."
11231 (unless org-inhibit-highlight-removal
11232 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11233 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11234 (setq org-table-rectangle-overlays nil)))
11236 (defvar org-table-coordinate-overlays nil
11237 "Collects the cooordinate grid overlays, so that they can be removed.")
11238 (make-variable-buffer-local 'org-table-coordinate-overlays)
11240 (defun org-table-overlay-coordinates ()
11241 "Add overlays to the table at point, to show row/column coordinates."
11242 (interactive)
11243 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11244 (setq org-table-coordinate-overlays nil)
11245 (save-excursion
11246 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11247 (goto-char (org-table-begin))
11248 (while (org-at-table-p)
11249 (setq eol (point-at-eol))
11250 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11251 (push ov org-table-coordinate-overlays)
11252 (setq hline (looking-at org-table-hline-regexp))
11253 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11254 (format "%4d" (setq id (1+ id)))))
11255 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11256 (when hline
11257 (setq ic 0)
11258 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11259 (setq beg (1+ (match-beginning 0))
11260 ic (1+ ic)
11261 s1 (concat "$" (int-to-string ic))
11262 s2 (org-number-to-letters ic)
11263 str (if (eq org-table-use-standard-references t) s2 s1))
11264 (setq ov (org-make-overlay beg (+ beg (length str))))
11265 (push ov org-table-coordinate-overlays)
11266 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11267 (beginning-of-line 2)))))
11269 (defun org-table-toggle-coordinate-overlays ()
11270 "Toggle the display of Row/Column numbers in tables."
11271 (interactive)
11272 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11273 (message "Row/Column number display turned %s"
11274 (if org-table-overlay-coordinates "on" "off"))
11275 (if (and (org-at-table-p) org-table-overlay-coordinates)
11276 (org-table-align))
11277 (unless org-table-overlay-coordinates
11278 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11279 (setq org-table-coordinate-overlays nil)))
11281 (defun org-table-toggle-formula-debugger ()
11282 "Toggle the formula debugger in tables."
11283 (interactive)
11284 (setq org-table-formula-debug (not org-table-formula-debug))
11285 (message "Formula debugging has been turned %s"
11286 (if org-table-formula-debug "on" "off")))
11288 ;;; The orgtbl minor mode
11290 ;; Define a minor mode which can be used in other modes in order to
11291 ;; integrate the org-mode table editor.
11293 ;; This is really a hack, because the org-mode table editor uses several
11294 ;; keys which normally belong to the major mode, for example the TAB and
11295 ;; RET keys. Here is how it works: The minor mode defines all the keys
11296 ;; necessary to operate the table editor, but wraps the commands into a
11297 ;; function which tests if the cursor is currently inside a table. If that
11298 ;; is the case, the table editor command is executed. However, when any of
11299 ;; those keys is used outside a table, the function uses `key-binding' to
11300 ;; look up if the key has an associated command in another currently active
11301 ;; keymap (minor modes, major mode, global), and executes that command.
11302 ;; There might be problems if any of the keys used by the table editor is
11303 ;; otherwise used as a prefix key.
11305 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11306 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11307 ;; addresses this by checking explicitly for both bindings.
11309 ;; The optimized version (see variable `orgtbl-optimized') takes over
11310 ;; all keys which are bound to `self-insert-command' in the *global map*.
11311 ;; Some modes bind other commands to simple characters, for example
11312 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11313 ;; active, this binding is ignored inside tables and replaced with a
11314 ;; modified self-insert.
11316 (defvar orgtbl-mode nil
11317 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11318 table editor in arbitrary modes.")
11319 (make-variable-buffer-local 'orgtbl-mode)
11321 (defvar orgtbl-mode-map (make-keymap)
11322 "Keymap for `orgtbl-mode'.")
11324 ;;;###autoload
11325 (defun turn-on-orgtbl ()
11326 "Unconditionally turn on `orgtbl-mode'."
11327 (orgtbl-mode 1))
11329 (defvar org-old-auto-fill-inhibit-regexp nil
11330 "Local variable used by `orgtbl-mode'")
11332 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11333 "Matches a line belonging to an orgtbl.")
11335 (defconst orgtbl-extra-font-lock-keywords
11336 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11337 0 (quote 'org-table) 'prepend))
11338 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11340 ;;;###autoload
11341 (defun orgtbl-mode (&optional arg)
11342 "The `org-mode' table editor as a minor mode for use in other modes."
11343 (interactive)
11344 (if (org-mode-p)
11345 ;; Exit without error, in case some hook functions calls this
11346 ;; by accident in org-mode.
11347 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11348 (setq orgtbl-mode
11349 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11350 (if orgtbl-mode
11351 (progn
11352 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11353 ;; Make sure we are first in minor-mode-map-alist
11354 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11355 (and c (setq minor-mode-map-alist
11356 (cons c (delq c minor-mode-map-alist)))))
11357 (org-set-local (quote org-table-may-need-update) t)
11358 (org-add-hook 'before-change-functions 'org-before-change-function
11359 nil 'local)
11360 (org-set-local 'org-old-auto-fill-inhibit-regexp
11361 auto-fill-inhibit-regexp)
11362 (org-set-local 'auto-fill-inhibit-regexp
11363 (if auto-fill-inhibit-regexp
11364 (concat orgtbl-line-start-regexp "\\|"
11365 auto-fill-inhibit-regexp)
11366 orgtbl-line-start-regexp))
11367 (org-add-to-invisibility-spec '(org-cwidth))
11368 (when (fboundp 'font-lock-add-keywords)
11369 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11370 (org-restart-font-lock))
11371 (easy-menu-add orgtbl-mode-menu)
11372 (run-hooks 'orgtbl-mode-hook))
11373 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11374 (org-cleanup-narrow-column-properties)
11375 (org-remove-from-invisibility-spec '(org-cwidth))
11376 (remove-hook 'before-change-functions 'org-before-change-function t)
11377 (when (fboundp 'font-lock-remove-keywords)
11378 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11379 (org-restart-font-lock))
11380 (easy-menu-remove orgtbl-mode-menu)
11381 (force-mode-line-update 'all))))
11383 (defun org-cleanup-narrow-column-properties ()
11384 "Remove all properties related to narrow-column invisibility."
11385 (let ((s 1))
11386 (while (setq s (text-property-any s (point-max)
11387 'display org-narrow-column-arrow))
11388 (remove-text-properties s (1+ s) '(display t)))
11389 (setq s 1)
11390 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11391 (remove-text-properties s (1+ s) '(org-cwidth t)))
11392 (setq s 1)
11393 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11394 (remove-text-properties s (1+ s) '(invisible t)))))
11396 ;; Install it as a minor mode.
11397 (put 'orgtbl-mode :included t)
11398 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11399 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11401 (defun orgtbl-make-binding (fun n &rest keys)
11402 "Create a function for binding in the table minor mode.
11403 FUN is the command to call inside a table. N is used to create a unique
11404 command name. KEYS are keys that should be checked in for a command
11405 to execute outside of tables."
11406 (eval
11407 (list 'defun
11408 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11409 '(arg)
11410 (concat "In tables, run `" (symbol-name fun) "'.\n"
11411 "Outside of tables, run the binding of `"
11412 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11413 "'.")
11414 '(interactive "p")
11415 (list 'if
11416 '(org-at-table-p)
11417 (list 'call-interactively (list 'quote fun))
11418 (list 'let '(orgtbl-mode)
11419 (list 'call-interactively
11420 (append '(or)
11421 (mapcar (lambda (k)
11422 (list 'key-binding k))
11423 keys)
11424 '('orgtbl-error))))))))
11426 (defun orgtbl-error ()
11427 "Error when there is no default binding for a table key."
11428 (interactive)
11429 (error "This key has no function outside tables"))
11431 (defun orgtbl-setup ()
11432 "Setup orgtbl keymaps."
11433 (let ((nfunc 0)
11434 (bindings
11435 (list
11436 '([(meta shift left)] org-table-delete-column)
11437 '([(meta left)] org-table-move-column-left)
11438 '([(meta right)] org-table-move-column-right)
11439 '([(meta shift right)] org-table-insert-column)
11440 '([(meta shift up)] org-table-kill-row)
11441 '([(meta shift down)] org-table-insert-row)
11442 '([(meta up)] org-table-move-row-up)
11443 '([(meta down)] org-table-move-row-down)
11444 '("\C-c\C-w" org-table-cut-region)
11445 '("\C-c\M-w" org-table-copy-region)
11446 '("\C-c\C-y" org-table-paste-rectangle)
11447 '("\C-c-" org-table-insert-hline)
11448 '("\C-c}" org-table-toggle-coordinate-overlays)
11449 '("\C-c{" org-table-toggle-formula-debugger)
11450 '("\C-m" org-table-next-row)
11451 '([(shift return)] org-table-copy-down)
11452 '("\C-c\C-q" org-table-wrap-region)
11453 '("\C-c?" org-table-field-info)
11454 '("\C-c " org-table-blank-field)
11455 '("\C-c+" org-table-sum)
11456 '("\C-c=" org-table-eval-formula)
11457 '("\C-c'" org-table-edit-formulas)
11458 '("\C-c`" org-table-edit-field)
11459 '("\C-c*" org-table-recalculate)
11460 '("\C-c|" org-table-create-or-convert-from-region)
11461 '("\C-c^" org-table-sort-lines)
11462 '([(control ?#)] org-table-rotate-recalc-marks)))
11463 elt key fun cmd)
11464 (while (setq elt (pop bindings))
11465 (setq nfunc (1+ nfunc))
11466 (setq key (org-key (car elt))
11467 fun (nth 1 elt)
11468 cmd (orgtbl-make-binding fun nfunc key))
11469 (org-defkey orgtbl-mode-map key cmd))
11471 ;; Special treatment needed for TAB and RET
11472 (org-defkey orgtbl-mode-map [(return)]
11473 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11474 (org-defkey orgtbl-mode-map "\C-m"
11475 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11477 (org-defkey orgtbl-mode-map [(tab)]
11478 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11479 (org-defkey orgtbl-mode-map "\C-i"
11480 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11482 (org-defkey orgtbl-mode-map [(shift tab)]
11483 (orgtbl-make-binding 'org-table-previous-field 104
11484 [(shift tab)] [(tab)] "\C-i"))
11486 (org-defkey orgtbl-mode-map "\M-\C-m"
11487 (orgtbl-make-binding 'org-table-wrap-region 105
11488 "\M-\C-m" [(meta return)]))
11489 (org-defkey orgtbl-mode-map [(meta return)]
11490 (orgtbl-make-binding 'org-table-wrap-region 106
11491 [(meta return)] "\M-\C-m"))
11493 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11494 (when orgtbl-optimized
11495 ;; If the user wants maximum table support, we need to hijack
11496 ;; some standard editing functions
11497 (org-remap orgtbl-mode-map
11498 'self-insert-command 'orgtbl-self-insert-command
11499 'delete-char 'org-delete-char
11500 'delete-backward-char 'org-delete-backward-char)
11501 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11502 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11503 '("OrgTbl"
11504 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11505 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11506 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11507 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11508 "--"
11509 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11510 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11511 ["Copy Field from Above"
11512 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11513 "--"
11514 ("Column"
11515 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11516 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11517 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11518 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11519 ("Row"
11520 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11521 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11522 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11523 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11524 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11525 "--"
11526 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11527 ("Rectangle"
11528 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11529 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11530 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11531 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11532 "--"
11533 ("Radio tables"
11534 ["Insert table template" orgtbl-insert-radio-table
11535 (assq major-mode orgtbl-radio-table-templates)]
11536 ["Comment/uncomment table" orgtbl-toggle-comment t])
11537 "--"
11538 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11539 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11540 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11541 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11542 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11543 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11544 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11545 ["Sum Column/Rectangle" org-table-sum
11546 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11547 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11548 ["Debug Formulas"
11549 org-table-toggle-formula-debugger :active (org-at-table-p)
11550 :keys "C-c {"
11551 :style toggle :selected org-table-formula-debug]
11552 ["Show Col/Row Numbers"
11553 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11554 :keys "C-c }"
11555 :style toggle :selected org-table-overlay-coordinates]
11559 (defun orgtbl-ctrl-c-ctrl-c (arg)
11560 "If the cursor is inside a table, realign the table.
11561 It it is a table to be sent away to a receiver, do it.
11562 With prefix arg, also recompute table."
11563 (interactive "P")
11564 (let ((pos (point)) action)
11565 (save-excursion
11566 (beginning-of-line 1)
11567 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11568 ((looking-at "[ \t]*|") pos)
11569 ((looking-at "#\\+TBLFM:") 'recalc))))
11570 (cond
11571 ((integerp action)
11572 (goto-char action)
11573 (org-table-maybe-eval-formula)
11574 (if arg
11575 (call-interactively 'org-table-recalculate)
11576 (org-table-maybe-recalculate-line))
11577 (call-interactively 'org-table-align)
11578 (orgtbl-send-table 'maybe))
11579 ((eq action 'recalc)
11580 (save-excursion
11581 (beginning-of-line 1)
11582 (skip-chars-backward " \r\n\t")
11583 (if (org-at-table-p)
11584 (org-call-with-arg 'org-table-recalculate t))))
11585 (t (let (orgtbl-mode)
11586 (call-interactively (key-binding "\C-c\C-c")))))))
11588 (defun orgtbl-tab (arg)
11589 "Justification and field motion for `orgtbl-mode'."
11590 (interactive "P")
11591 (if arg (org-table-edit-field t)
11592 (org-table-justify-field-maybe)
11593 (org-table-next-field)))
11595 (defun orgtbl-ret ()
11596 "Justification and field motion for `orgtbl-mode'."
11597 (interactive)
11598 (org-table-justify-field-maybe)
11599 (org-table-next-row))
11601 (defun orgtbl-self-insert-command (N)
11602 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11603 If the cursor is in a table looking at whitespace, the whitespace is
11604 overwritten, and the table is not marked as requiring realignment."
11605 (interactive "p")
11606 (if (and (org-at-table-p)
11608 (and org-table-auto-blank-field
11609 (member last-command
11610 '(orgtbl-hijacker-command-100
11611 orgtbl-hijacker-command-101
11612 orgtbl-hijacker-command-102
11613 orgtbl-hijacker-command-103
11614 orgtbl-hijacker-command-104
11615 orgtbl-hijacker-command-105))
11616 (org-table-blank-field))
11618 (eq N 1)
11619 (looking-at "[^|\n]* +|"))
11620 (let (org-table-may-need-update)
11621 (goto-char (1- (match-end 0)))
11622 (delete-backward-char 1)
11623 (goto-char (match-beginning 0))
11624 (self-insert-command N))
11625 (setq org-table-may-need-update t)
11626 (let (orgtbl-mode)
11627 (call-interactively (key-binding (vector last-input-event))))))
11629 (defun org-force-self-insert (N)
11630 "Needed to enforce self-insert under remapping."
11631 (interactive "p")
11632 (self-insert-command N))
11634 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11635 "Regula expression matching exponentials as produced by calc.")
11637 (defvar org-table-clean-did-remove-column nil)
11639 (defun orgtbl-export (table target)
11640 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11641 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11642 org-table-last-alignment org-table-last-column-widths
11643 maxcol column)
11644 (if (not (fboundp func))
11645 (error "Cannot export orgtbl table to %s" target))
11646 (setq lines (org-table-clean-before-export lines))
11647 (setq table
11648 (mapcar
11649 (lambda (x)
11650 (if (string-match org-table-hline-regexp x)
11651 'hline
11652 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11653 lines))
11654 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11655 table)))
11656 (loop for i from (1- maxcol) downto 0 do
11657 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11658 (setq column (delq nil column))
11659 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11660 (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))
11661 (funcall func table nil)))
11663 (defun orgtbl-send-table (&optional maybe)
11664 "Send a tranformed version of this table to the receiver position.
11665 With argument MAYBE, fail quietly if no transformation is defined for
11666 this table."
11667 (interactive)
11668 (catch 'exit
11669 (unless (org-at-table-p) (error "Not at a table"))
11670 ;; when non-interactive, we assume align has just happened.
11671 (when (interactive-p) (org-table-align))
11672 (save-excursion
11673 (goto-char (org-table-begin))
11674 (beginning-of-line 0)
11675 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11676 (if maybe
11677 (throw 'exit nil)
11678 (error "Don't know how to transform this table."))))
11679 (let* ((name (match-string 1))
11681 (transform (intern (match-string 2)))
11682 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11683 (skip (plist-get params :skip))
11684 (skipcols (plist-get params :skipcols))
11685 (txt (buffer-substring-no-properties
11686 (org-table-begin) (org-table-end)))
11687 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11688 (lines (org-table-clean-before-export lines))
11689 (i0 (if org-table-clean-did-remove-column 2 1))
11690 (table (mapcar
11691 (lambda (x)
11692 (if (string-match org-table-hline-regexp x)
11693 'hline
11694 (org-remove-by-index
11695 (org-split-string (org-trim x) "\\s-*|\\s-*")
11696 skipcols i0)))
11697 lines))
11698 (fun (if (= i0 2) 'cdr 'identity))
11699 (org-table-last-alignment
11700 (org-remove-by-index (funcall fun org-table-last-alignment)
11701 skipcols i0))
11702 (org-table-last-column-widths
11703 (org-remove-by-index (funcall fun org-table-last-column-widths)
11704 skipcols i0)))
11706 (unless (fboundp transform)
11707 (error "No such transformation function %s" transform))
11708 (setq txt (funcall transform table params))
11709 ;; Find the insertion place
11710 (save-excursion
11711 (goto-char (point-min))
11712 (unless (re-search-forward
11713 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11714 (error "Don't know where to insert translated table"))
11715 (goto-char (match-beginning 0))
11716 (beginning-of-line 2)
11717 (setq beg (point))
11718 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11719 (error "Cannot find end of insertion region"))
11720 (beginning-of-line 1)
11721 (delete-region beg (point))
11722 (goto-char beg)
11723 (insert txt "\n"))
11724 (message "Table converted and installed at receiver location"))))
11726 (defun org-remove-by-index (list indices &optional i0)
11727 "Remove the elements in LIST with indices in INDICES.
11728 First element has index 0, or I0 if given."
11729 (if (not indices)
11730 list
11731 (if (integerp indices) (setq indices (list indices)))
11732 (setq i0 (1- (or i0 0)))
11733 (delq :rm (mapcar (lambda (x)
11734 (setq i0 (1+ i0))
11735 (if (memq i0 indices) :rm x))
11736 list))))
11738 (defun orgtbl-toggle-comment ()
11739 "Comment or uncomment the orgtbl at point."
11740 (interactive)
11741 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11742 (re2 (concat "^" orgtbl-line-start-regexp))
11743 (commented (save-excursion (beginning-of-line 1)
11744 (cond ((looking-at re1) t)
11745 ((looking-at re2) nil)
11746 (t (error "Not at an org table")))))
11747 (re (if commented re1 re2))
11748 beg end)
11749 (save-excursion
11750 (beginning-of-line 1)
11751 (while (looking-at re) (beginning-of-line 0))
11752 (beginning-of-line 2)
11753 (setq beg (point))
11754 (while (looking-at re) (beginning-of-line 2))
11755 (setq end (point)))
11756 (comment-region beg end (if commented '(4) nil))))
11758 (defun orgtbl-insert-radio-table ()
11759 "Insert a radio table template appropriate for this major mode."
11760 (interactive)
11761 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11762 (txt (nth 1 e))
11763 name pos)
11764 (unless e (error "No radio table setup defined for %s" major-mode))
11765 (setq name (read-string "Table name: "))
11766 (while (string-match "%n" txt)
11767 (setq txt (replace-match name t t txt)))
11768 (or (bolp) (insert "\n"))
11769 (setq pos (point))
11770 (insert txt)
11771 (goto-char pos)))
11773 (defun org-get-param (params header i sym &optional hsym)
11774 "Get parameter value for symbol SYM.
11775 If this is a header line, actually get the value for the symbol with an
11776 additional \"h\" inserted after the colon.
11777 If the value is a protperty list, get the element for the current column.
11778 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11779 (let ((val (plist-get params sym)))
11780 (and hsym header (setq val (or (plist-get params hsym) val)))
11781 (if (consp val) (plist-get val i) val)))
11783 (defun orgtbl-to-generic (table params)
11784 "Convert the orgtbl-mode TABLE to some other format.
11785 This generic routine can be used for many standard cases.
11786 TABLE is a list, each entry either the symbol `hline' for a horizontal
11787 separator line, or a list of fields for that line.
11788 PARAMS is a property list of parameters that can influence the conversion.
11789 For the generic converter, some parameters are obligatory: You need to
11790 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11791 :splice, you must have :tstart and :tend.
11793 Valid parameters are
11795 :tstart String to start the table. Ignored when :splice is t.
11796 :tend String to end the table. Ignored when :splice is t.
11798 :splice When set to t, return only table body lines, don't wrap
11799 them into :tstart and :tend. Default is nil.
11801 :hline String to be inserted on horizontal separation lines.
11802 May be nil to ignore hlines.
11804 :lstart String to start a new table line.
11805 :lend String to end a table line
11806 :sep Separator between two fields
11807 :lfmt Format for entire line, with enough %s to capture all fields.
11808 If this is present, :lstart, :lend, and :sep are ignored.
11809 :fmt A format to be used to wrap the field, should contain
11810 %s for the original field value. For example, to wrap
11811 everything in dollars, you could use :fmt \"$%s$\".
11812 This may also be a property list with column numbers and
11813 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11815 :hlstart :hlend :hlsep :hlfmt :hfmt
11816 Same as above, specific for the header lines in the table.
11817 All lines before the first hline are treated as header.
11818 If any of these is not present, the data line value is used.
11820 :efmt Use this format to print numbers with exponentials.
11821 The format should have %s twice for inserting mantissa
11822 and exponent, for example \"%s\\\\times10^{%s}\". This
11823 may also be a property list with column numbers and
11824 formats. :fmt will still be applied after :efmt.
11826 In addition to this, the parameters :skip and :skipcols are always handled
11827 directly by `orgtbl-send-table'. See manual."
11828 (interactive)
11829 (let* ((p params)
11830 (splicep (plist-get p :splice))
11831 (hline (plist-get p :hline))
11832 rtn line i fm efm lfmt h)
11834 ;; Do we have a header?
11835 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11836 (setq h t))
11838 ;; Put header
11839 (unless splicep
11840 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11842 ;; Now loop over all lines
11843 (while (setq line (pop table))
11844 (if (eq line 'hline)
11845 ;; A horizontal separator line
11846 (progn (if hline (push hline rtn))
11847 (setq h nil)) ; no longer in header
11848 ;; A normal line. Convert the fields, push line onto the result list
11849 (setq i 0)
11850 (setq line
11851 (mapcar
11852 (lambda (f)
11853 (setq i (1+ i)
11854 fm (org-get-param p h i :fmt :hfmt)
11855 efm (org-get-param p h i :efmt))
11856 (if (and efm (string-match orgtbl-exp-regexp f))
11857 (setq f (format
11858 efm (match-string 1 f) (match-string 2 f))))
11859 (if fm (setq f (format fm f)))
11861 line))
11862 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11863 (push (apply 'format lfmt line) rtn)
11864 (push (concat
11865 (org-get-param p h i :lstart :hlstart)
11866 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11867 (org-get-param p h i :lend :hlend))
11868 rtn))))
11870 (unless splicep
11871 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11873 (mapconcat 'identity (nreverse rtn) "\n")))
11875 (defun orgtbl-to-latex (table params)
11876 "Convert the orgtbl-mode TABLE to LaTeX.
11877 TABLE is a list, each entry either the symbol `hline' for a horizontal
11878 separator line, or a list of fields for that line.
11879 PARAMS is a property list of parameters that can influence the conversion.
11880 Supports all parameters from `orgtbl-to-generic'. Most important for
11881 LaTeX are:
11883 :splice When set to t, return only table body lines, don't wrap
11884 them into a tabular environment. Default is nil.
11886 :fmt A format to be used to wrap the field, should contain %s for the
11887 original field value. For example, to wrap everything in dollars,
11888 use :fmt \"$%s$\". This may also be a property list with column
11889 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11891 :efmt Format for transforming numbers with exponentials. The format
11892 should have %s twice for inserting mantissa and exponent, for
11893 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11894 This may also be a property list with column numbers and formats.
11896 The general parameters :skip and :skipcols have already been applied when
11897 this function is called."
11898 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11899 org-table-last-alignment ""))
11900 (params2
11901 (list
11902 :tstart (concat "\\begin{tabular}{" alignment "}")
11903 :tend "\\end{tabular}"
11904 :lstart "" :lend " \\\\" :sep " & "
11905 :efmt "%s\\,(%s)" :hline "\\hline")))
11906 (orgtbl-to-generic table (org-combine-plists params2 params))))
11908 (defun orgtbl-to-html (table params)
11909 "Convert the orgtbl-mode TABLE to LaTeX.
11910 TABLE is a list, each entry either the symbol `hline' for a horizontal
11911 separator line, or a list of fields for that line.
11912 PARAMS is a property list of parameters that can influence the conversion.
11913 Currently this function recognizes the following parameters:
11915 :splice When set to t, return only table body lines, don't wrap
11916 them into a <table> environment. Default is nil.
11918 The general parameters :skip and :skipcols have already been applied when
11919 this function is called. The function does *not* use `orgtbl-to-generic',
11920 so you cannot specify parameters for it."
11921 (let* ((splicep (plist-get params :splice))
11922 html)
11923 ;; Just call the formatter we already have
11924 ;; We need to make text lines for it, so put the fields back together.
11925 (setq html (org-format-org-table-html
11926 (mapcar
11927 (lambda (x)
11928 (if (eq x 'hline)
11929 "|----+----|"
11930 (concat "| " (mapconcat 'identity x " | ") " |")))
11931 table)
11932 splicep))
11933 (if (string-match "\n+\\'" html)
11934 (setq html (replace-match "" t t html)))
11935 html))
11937 (defun orgtbl-to-texinfo (table params)
11938 "Convert the orgtbl-mode TABLE to TeXInfo.
11939 TABLE is a list, each entry either the symbol `hline' for a horizontal
11940 separator line, or a list of fields for that line.
11941 PARAMS is a property list of parameters that can influence the conversion.
11942 Supports all parameters from `orgtbl-to-generic'. Most important for
11943 TeXInfo are:
11945 :splice nil/t When set to t, return only table body lines, don't wrap
11946 them into a multitable environment. Default is nil.
11948 :fmt fmt A format to be used to wrap the field, should contain
11949 %s for the original field value. For example, to wrap
11950 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11951 This may also be a property list with column numbers and
11952 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11954 :cf \"f1 f2..\" The column fractions for the table. By default these
11955 are computed automatically from the width of the columns
11956 under org-mode.
11958 The general parameters :skip and :skipcols have already been applied when
11959 this function is called."
11960 (let* ((total (float (apply '+ org-table-last-column-widths)))
11961 (colfrac (or (plist-get params :cf)
11962 (mapconcat
11963 (lambda (x) (format "%.3f" (/ (float x) total)))
11964 org-table-last-column-widths " ")))
11965 (params2
11966 (list
11967 :tstart (concat "@multitable @columnfractions " colfrac)
11968 :tend "@end multitable"
11969 :lstart "@item " :lend "" :sep " @tab "
11970 :hlstart "@headitem ")))
11971 (orgtbl-to-generic table (org-combine-plists params2 params))))
11973 ;;;; Link Stuff
11975 ;;; Link abbreviations
11977 (defun org-link-expand-abbrev (link)
11978 "Apply replacements as defined in `org-link-abbrev-alist."
11979 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11980 (let* ((key (match-string 1 link))
11981 (as (or (assoc key org-link-abbrev-alist-local)
11982 (assoc key org-link-abbrev-alist)))
11983 (tag (and (match-end 2) (match-string 3 link)))
11984 rpl)
11985 (if (not as)
11986 link
11987 (setq rpl (cdr as))
11988 (cond
11989 ((symbolp rpl) (funcall rpl tag))
11990 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11991 (t (concat rpl tag)))))
11992 link))
11994 ;;; Storing and inserting links
11996 (defvar org-insert-link-history nil
11997 "Minibuffer history for links inserted with `org-insert-link'.")
11999 (defvar org-stored-links nil
12000 "Contains the links stored with `org-store-link'.")
12002 (defvar org-store-link-plist nil
12003 "Plist with info about the most recently link created with `org-store-link'.")
12005 (defvar org-link-protocols nil
12006 "Link protocols added to Org-mode using `org-add-link-type'.")
12008 (defvar org-store-link-functions nil
12009 "List of functions that are called to create and store a link.
12010 Each function will be called in turn until one returns a non-nil
12011 value. Each function should check if it is responsible for creating
12012 this link (for example by looking at the major mode).
12013 If not, it must exit and return nil.
12014 If yes, it should return a non-nil value after a calling
12015 `org-store-link-props' with a list of properties and values.
12016 Special properties are:
12018 :type The link prefix. like \"http\". This must be given.
12019 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12020 This is obligatory as well.
12021 :description Optional default description for the second pair
12022 of brackets in an Org-mode link. The user can still change
12023 this when inserting this link into an Org-mode buffer.
12025 In addition to these, any additional properties can be specified
12026 and then used in remember templates.")
12028 (defun org-add-link-type (type &optional follow publish)
12029 "Add TYPE to the list of `org-link-types'.
12030 Re-compute all regular expressions depending on `org-link-types'
12031 FOLLOW and PUBLISH are two functions. Both take the link path as
12032 an argument.
12033 FOLLOW should do whatever is necessary to follow the link, for example
12034 to find a file or display a mail message.
12036 PUBLISH takes the path and retuns the string that should be used when
12037 this document is published. FIMXE: This is actually not yet implemented."
12038 (add-to-list 'org-link-types type t)
12039 (org-make-link-regexps)
12040 (add-to-list 'org-link-protocols
12041 (list type follow publish)))
12043 (defun org-add-agenda-custom-command (entry)
12044 "Replace or add a command in `org-agenda-custom-commands'.
12045 This is mostly for hacking and trying a new command - once the command
12046 works you probably want to add it to `org-agenda-custom-commands' for good."
12047 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12048 (if ass
12049 (setcdr ass (cdr entry))
12050 (push entry org-agenda-custom-commands))))
12052 ;;;###autoload
12053 (defun org-store-link (arg)
12054 "\\<org-mode-map>Store an org-link to the current location.
12055 This link is added to `org-stored-links' and can later be inserted
12056 into an org-buffer with \\[org-insert-link].
12058 For some link types, a prefix arg is interpreted:
12059 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12060 For file links, arg negates `org-context-in-file-links'."
12061 (interactive "P")
12062 (setq org-store-link-plist nil) ; reset
12063 (let (link cpltxt desc description search txt)
12064 (cond
12066 ((run-hook-with-args-until-success 'org-store-link-functions)
12067 (setq link (plist-get org-store-link-plist :link)
12068 desc (or (plist-get org-store-link-plist :description) link)))
12070 ((eq major-mode 'bbdb-mode)
12071 (let ((name (bbdb-record-name (bbdb-current-record)))
12072 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12073 (setq cpltxt (concat "bbdb:" (or name company))
12074 link (org-make-link cpltxt))
12075 (org-store-link-props :type "bbdb" :name name :company company)))
12077 ((eq major-mode 'Info-mode)
12078 (setq link (org-make-link "info:"
12079 (file-name-nondirectory Info-current-file)
12080 ":" Info-current-node))
12081 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12082 ":" Info-current-node))
12083 (org-store-link-props :type "info" :file Info-current-file
12084 :node Info-current-node))
12086 ((eq major-mode 'calendar-mode)
12087 (let ((cd (calendar-cursor-to-date)))
12088 (setq link
12089 (format-time-string
12090 (car org-time-stamp-formats)
12091 (apply 'encode-time
12092 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12093 nil nil nil))))
12094 (org-store-link-props :type "calendar" :date cd)))
12096 ((or (eq major-mode 'vm-summary-mode)
12097 (eq major-mode 'vm-presentation-mode))
12098 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12099 (vm-follow-summary-cursor)
12100 (save-excursion
12101 (vm-select-folder-buffer)
12102 (let* ((message (car vm-message-pointer))
12103 (folder buffer-file-name)
12104 (subject (vm-su-subject message))
12105 (to (vm-get-header-contents message "To"))
12106 (from (vm-get-header-contents message "From"))
12107 (message-id (vm-su-message-id message)))
12108 (org-store-link-props :type "vm" :from from :to to :subject subject
12109 :message-id message-id)
12110 (setq message-id (org-remove-angle-brackets message-id))
12111 (setq folder (abbreviate-file-name folder))
12112 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12113 folder)
12114 (setq folder (replace-match "" t t folder)))
12115 (setq cpltxt (org-email-link-description))
12116 (setq link (org-make-link "vm:" folder "#" message-id)))))
12118 ((eq major-mode 'wl-summary-mode)
12119 (let* ((msgnum (wl-summary-message-number))
12120 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12121 msgnum 'message-id))
12122 (wl-message-entity
12123 (if (fboundp 'elmo-message-entity)
12124 (elmo-message-entity
12125 wl-summary-buffer-elmo-folder msgnum)
12126 (elmo-msgdb-overview-get-entity
12127 msgnum (wl-summary-buffer-msgdb))))
12128 (from (wl-summary-line-from))
12129 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12130 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12131 (wl-summary-line-subject))))
12132 (org-store-link-props :type "wl" :from from :to to
12133 :subject subject :message-id message-id)
12134 (setq message-id (org-remove-angle-brackets message-id))
12135 (setq cpltxt (org-email-link-description))
12136 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12137 "#" message-id))))
12139 ((or (equal major-mode 'mh-folder-mode)
12140 (equal major-mode 'mh-show-mode))
12141 (let ((from (org-mhe-get-header "From:"))
12142 (to (org-mhe-get-header "To:"))
12143 (message-id (org-mhe-get-header "Message-Id:"))
12144 (subject (org-mhe-get-header "Subject:")))
12145 (org-store-link-props :type "mh" :from from :to to
12146 :subject subject :message-id message-id)
12147 (setq cpltxt (org-email-link-description))
12148 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12149 (org-remove-angle-brackets message-id)))))
12151 ((or (eq major-mode 'rmail-mode)
12152 (eq major-mode 'rmail-summary-mode))
12153 (save-window-excursion
12154 (save-restriction
12155 (when (eq major-mode 'rmail-summary-mode)
12156 (rmail-show-message rmail-current-message))
12157 (rmail-narrow-to-non-pruned-header)
12158 (let ((folder buffer-file-name)
12159 (message-id (mail-fetch-field "message-id"))
12160 (from (mail-fetch-field "from"))
12161 (to (mail-fetch-field "to"))
12162 (subject (mail-fetch-field "subject")))
12163 (org-store-link-props
12164 :type "rmail" :from from :to to
12165 :subject subject :message-id message-id)
12166 (setq message-id (org-remove-angle-brackets message-id))
12167 (setq cpltxt (org-email-link-description))
12168 (setq link (org-make-link "rmail:" folder "#" message-id)))
12169 (rmail-show-message rmail-current-message))))
12171 ((eq major-mode 'gnus-group-mode)
12172 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12173 (gnus-group-group-name)) ; version
12174 ((fboundp 'gnus-group-name)
12175 (gnus-group-name))
12176 (t "???"))))
12177 (unless group (error "Not on a group"))
12178 (org-store-link-props :type "gnus" :group group)
12179 (setq cpltxt (concat
12180 (if (org-xor arg org-usenet-links-prefer-google)
12181 "http://groups.google.com/groups?group="
12182 "gnus:")
12183 group)
12184 link (org-make-link cpltxt))))
12186 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12187 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12188 (let* ((group gnus-newsgroup-name)
12189 (article (gnus-summary-article-number))
12190 (header (gnus-summary-article-header article))
12191 (from (mail-header-from header))
12192 (message-id (mail-header-id header))
12193 (date (mail-header-date header))
12194 (subject (gnus-summary-subject-string)))
12195 (org-store-link-props :type "gnus" :from from :subject subject
12196 :message-id message-id :group group)
12197 (setq cpltxt (org-email-link-description))
12198 (if (org-xor arg org-usenet-links-prefer-google)
12199 (setq link
12200 (concat
12201 cpltxt "\n "
12202 (format "http://groups.google.com/groups?as_umsgid=%s"
12203 (org-fixup-message-id-for-http message-id))))
12204 (setq link (org-make-link "gnus:" group
12205 "#" (number-to-string article))))))
12207 ((eq major-mode 'w3-mode)
12208 (setq cpltxt (url-view-url t)
12209 link (org-make-link cpltxt))
12210 (org-store-link-props :type "w3" :url (url-view-url t)))
12212 ((eq major-mode 'w3m-mode)
12213 (setq cpltxt (or w3m-current-title w3m-current-url)
12214 link (org-make-link w3m-current-url))
12215 (org-store-link-props :type "w3m" :url (url-view-url t)))
12217 ((setq search (run-hook-with-args-until-success
12218 'org-create-file-search-functions))
12219 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12220 "::" search))
12221 (setq cpltxt (or description link)))
12223 ((eq major-mode 'image-mode)
12224 (setq cpltxt (concat "file:"
12225 (abbreviate-file-name buffer-file-name))
12226 link (org-make-link cpltxt))
12227 (org-store-link-props :type "image" :file buffer-file-name))
12229 ((eq major-mode 'dired-mode)
12230 ;; link to the file in the current line
12231 (setq cpltxt (concat "file:"
12232 (abbreviate-file-name
12233 (expand-file-name
12234 (dired-get-filename nil t))))
12235 link (org-make-link cpltxt)))
12237 ((and buffer-file-name (org-mode-p))
12238 ;; Just link to current headline
12239 (setq cpltxt (concat "file:"
12240 (abbreviate-file-name buffer-file-name)))
12241 ;; Add a context search string
12242 (when (org-xor org-context-in-file-links arg)
12243 ;; Check if we are on a target
12244 (if (org-in-regexp "<<\\(.*?\\)>>")
12245 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12246 (setq txt (cond
12247 ((org-on-heading-p) nil)
12248 ((org-region-active-p)
12249 (buffer-substring (region-beginning) (region-end)))
12250 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12251 (when (or (null txt) (string-match "\\S-" txt))
12252 (setq cpltxt
12253 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12254 desc "NONE"))))
12255 (if (string-match "::\\'" cpltxt)
12256 (setq cpltxt (substring cpltxt 0 -2)))
12257 (setq link (org-make-link cpltxt)))
12259 ((buffer-file-name (buffer-base-buffer))
12260 ;; Just link to this file here.
12261 (setq cpltxt (concat "file:"
12262 (abbreviate-file-name
12263 (buffer-file-name (buffer-base-buffer)))))
12264 ;; Add a context string
12265 (when (org-xor org-context-in-file-links arg)
12266 (setq txt (if (org-region-active-p)
12267 (buffer-substring (region-beginning) (region-end))
12268 (buffer-substring (point-at-bol) (point-at-eol))))
12269 ;; Only use search option if there is some text.
12270 (when (string-match "\\S-" txt)
12271 (setq cpltxt
12272 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12273 desc "NONE")))
12274 (setq link (org-make-link cpltxt)))
12276 ((interactive-p)
12277 (error "Cannot link to a buffer which is not visiting a file"))
12279 (t (setq link nil)))
12281 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12282 (setq link (or link cpltxt)
12283 desc (or desc cpltxt))
12284 (if (equal desc "NONE") (setq desc nil))
12286 (if (and (interactive-p) link)
12287 (progn
12288 (setq org-stored-links
12289 (cons (list link desc) org-stored-links))
12290 (message "Stored: %s" (or desc link)))
12291 (and link (org-make-link-string link desc)))))
12293 (defun org-store-link-props (&rest plist)
12294 "Store link properties, extract names and addresses."
12295 (let (x adr)
12296 (when (setq x (plist-get plist :from))
12297 (setq adr (mail-extract-address-components x))
12298 (plist-put plist :fromname (car adr))
12299 (plist-put plist :fromaddress (nth 1 adr)))
12300 (when (setq x (plist-get plist :to))
12301 (setq adr (mail-extract-address-components x))
12302 (plist-put plist :toname (car adr))
12303 (plist-put plist :toaddress (nth 1 adr))))
12304 (let ((from (plist-get plist :from))
12305 (to (plist-get plist :to)))
12306 (when (and from to org-from-is-user-regexp)
12307 (plist-put plist :fromto
12308 (if (string-match org-from-is-user-regexp from)
12309 (concat "to %t")
12310 (concat "from %f")))))
12311 (setq org-store-link-plist plist))
12313 (defun org-email-link-description (&optional fmt)
12314 "Return the description part of an email link.
12315 This takes information from `org-store-link-plist' and formats it
12316 according to FMT (default from `org-email-link-description-format')."
12317 (setq fmt (or fmt org-email-link-description-format))
12318 (let* ((p org-store-link-plist)
12319 (to (plist-get p :toaddress))
12320 (from (plist-get p :fromaddress))
12321 (table
12322 (list
12323 (cons "%c" (plist-get p :fromto))
12324 (cons "%F" (plist-get p :from))
12325 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12326 (cons "%T" (plist-get p :to))
12327 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12328 (cons "%s" (plist-get p :subject))
12329 (cons "%m" (plist-get p :message-id)))))
12330 (when (string-match "%c" fmt)
12331 ;; Check if the user wrote this message
12332 (if (and org-from-is-user-regexp from to
12333 (save-match-data (string-match org-from-is-user-regexp from)))
12334 (setq fmt (replace-match "to %t" t t fmt))
12335 (setq fmt (replace-match "from %f" t t fmt))))
12336 (org-replace-escapes fmt table)))
12338 (defun org-make-org-heading-search-string (&optional string heading)
12339 "Make search string for STRING or current headline."
12340 (interactive)
12341 (let ((s (or string (org-get-heading))))
12342 (unless (and string (not heading))
12343 ;; We are using a headline, clean up garbage in there.
12344 (if (string-match org-todo-regexp s)
12345 (setq s (replace-match "" t t s)))
12346 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12347 (setq s (replace-match "" t t s)))
12348 (setq s (org-trim s))
12349 (if (string-match (concat "^\\(" org-quote-string "\\|"
12350 org-comment-string "\\)") s)
12351 (setq s (replace-match "" t t s)))
12352 (while (string-match org-ts-regexp s)
12353 (setq s (replace-match "" t t s))))
12354 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12355 (setq s (replace-match " " t t s)))
12356 (or string (setq s (concat "*" s))) ; Add * for headlines
12357 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12359 (defun org-make-link (&rest strings)
12360 "Concatenate STRINGS."
12361 (apply 'concat strings))
12363 (defun org-make-link-string (link &optional description)
12364 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12365 (unless (string-match "\\S-" link)
12366 (error "Empty link"))
12367 (when (stringp description)
12368 ;; Remove brackets from the description, they are fatal.
12369 (while (string-match "\\[" description)
12370 (setq description (replace-match "{" t t description)))
12371 (while (string-match "\\]" description)
12372 (setq description (replace-match "}" t t description))))
12373 (when (equal (org-link-escape link) description)
12374 ;; No description needed, it is identical
12375 (setq description nil))
12376 (when (and (not description)
12377 (not (equal link (org-link-escape link))))
12378 (setq description link))
12379 (concat "[[" (org-link-escape link) "]"
12380 (if description (concat "[" description "]") "")
12381 "]"))
12383 (defconst org-link-escape-chars
12384 '((?\ . "%20")
12385 (?\[ . "%5B")
12386 (?\] . "%5D")
12387 (?\340 . "%E0") ; `a
12388 (?\342 . "%E2") ; ^a
12389 (?\347 . "%E7") ; ,c
12390 (?\350 . "%E8") ; `e
12391 (?\351 . "%E9") ; 'e
12392 (?\352 . "%EA") ; ^e
12393 (?\356 . "%EE") ; ^i
12394 (?\364 . "%F4") ; ^o
12395 (?\371 . "%F9") ; `u
12396 (?\373 . "%FB") ; ^u
12397 (?\; . "%3B")
12398 (?? . "%3F")
12399 (?= . "%3D")
12400 (?+ . "%2B")
12402 "Association list of escapes for some characters problematic in links.
12403 This is the list that is used for internal purposes.")
12405 (defconst org-link-escape-chars-browser
12406 '((?\ . "%20")) ; 32 for the SPC char
12407 "Association list of escapes for some characters problematic in links.
12408 This is the list that is used before handing over to the browser.")
12410 (defun org-link-escape (text &optional table)
12411 "Escape charaters in TEXT that are problematic for links."
12412 (setq table (or table org-link-escape-chars))
12413 (when text
12414 (let ((re (mapconcat (lambda (x) (regexp-quote
12415 (char-to-string (car x))))
12416 table "\\|")))
12417 (while (string-match re text)
12418 (setq text
12419 (replace-match
12420 (cdr (assoc (string-to-char (match-string 0 text))
12421 table))
12422 t t text)))
12423 text)))
12425 (defun org-link-unescape (text &optional table)
12426 "Reverse the action of `org-link-escape'."
12427 (setq table (or table org-link-escape-chars))
12428 (when text
12429 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12430 table "\\|")))
12431 (while (string-match re text)
12432 (setq text
12433 (replace-match
12434 (char-to-string (car (rassoc (match-string 0 text) table)))
12435 t t text)))
12436 text)))
12438 (defun org-xor (a b)
12439 "Exclusive or."
12440 (if a (not b) b))
12442 (defun org-get-header (header)
12443 "Find a header field in the current buffer."
12444 (save-excursion
12445 (goto-char (point-min))
12446 (let ((case-fold-search t) s)
12447 (cond
12448 ((eq header 'from)
12449 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12450 (setq s (match-string 1)))
12451 (while (string-match "\"" s)
12452 (setq s (replace-match "" t t s)))
12453 (if (string-match "[<(].*" s)
12454 (setq s (replace-match "" t t s))))
12455 ((eq header 'message-id)
12456 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12457 (setq s (match-string 1))))
12458 ((eq header 'subject)
12459 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12460 (setq s (match-string 1)))))
12461 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12462 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12463 s)))
12466 (defun org-fixup-message-id-for-http (s)
12467 "Replace special characters in a message id, so it can be used in an http query."
12468 (while (string-match "<" s)
12469 (setq s (replace-match "%3C" t t s)))
12470 (while (string-match ">" s)
12471 (setq s (replace-match "%3E" t t s)))
12472 (while (string-match "@" s)
12473 (setq s (replace-match "%40" t t s)))
12476 ;;;###autoload
12477 (defun org-insert-link-global ()
12478 "Insert a link like Org-mode does.
12479 This command can be called in any mode to insert a link in Org-mode syntax."
12480 (interactive)
12481 (org-run-like-in-org-mode 'org-insert-link))
12483 (defun org-insert-link (&optional complete-file)
12484 "Insert a link. At the prompt, enter the link.
12486 Completion can be used to select a link previously stored with
12487 `org-store-link'. When the empty string is entered (i.e. if you just
12488 press RET at the prompt), the link defaults to the most recently
12489 stored link. As SPC triggers completion in the minibuffer, you need to
12490 use M-SPC or C-q SPC to force the insertion of a space character.
12492 You will also be prompted for a description, and if one is given, it will
12493 be displayed in the buffer instead of the link.
12495 If there is already a link at point, this command will allow you to edit link
12496 and description parts.
12498 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12499 selected using completion. The path to the file will be relative to
12500 the current directory if the file is in the current directory or a
12501 subdirectory. Otherwise, the link will be the absolute path as
12502 completed in the minibuffer (i.e. normally ~/path/to/file).
12504 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12505 is in the current directory or below.
12506 With three \\[universal-argument] prefixes, negate the meaning of
12507 `org-keep-stored-link-after-insertion'."
12508 (interactive "P")
12509 (let* ((wcf (current-window-configuration))
12510 (region (if (org-region-active-p)
12511 (buffer-substring (region-beginning) (region-end))))
12512 (remove (and region (list (region-beginning) (region-end))))
12513 (desc region)
12514 tmphist ; byte-compile incorrectly complains about this
12515 link entry file)
12516 (cond
12517 ((org-in-regexp org-bracket-link-regexp 1)
12518 ;; We do have a link at point, and we are going to edit it.
12519 (setq remove (list (match-beginning 0) (match-end 0)))
12520 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12521 (setq link (read-string "Link: "
12522 (org-link-unescape
12523 (org-match-string-no-properties 1)))))
12524 ((or (org-in-regexp org-angle-link-re)
12525 (org-in-regexp org-plain-link-re))
12526 ;; Convert to bracket link
12527 (setq remove (list (match-beginning 0) (match-end 0))
12528 link (read-string "Link: "
12529 (org-remove-angle-brackets (match-string 0)))))
12530 ((equal complete-file '(4))
12531 ;; Completing read for file names.
12532 (setq file (read-file-name "File: "))
12533 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12534 (pwd1 (file-name-as-directory (abbreviate-file-name
12535 (expand-file-name ".")))))
12536 (cond
12537 ((equal complete-file '(16))
12538 (setq link (org-make-link
12539 "file:"
12540 (abbreviate-file-name (expand-file-name file)))))
12541 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12542 (setq link (org-make-link "file:" (match-string 1 file))))
12543 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12544 (expand-file-name file))
12545 (setq link (org-make-link
12546 "file:" (match-string 1 (expand-file-name file)))))
12547 (t (setq link (org-make-link "file:" file))))))
12549 ;; Read link, with completion for stored links.
12550 (with-output-to-temp-buffer "*Org Links*"
12551 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12552 (when org-stored-links
12553 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12554 (princ (mapconcat
12555 (lambda (x)
12556 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12557 (reverse org-stored-links) "\n"))))
12558 (let ((cw (selected-window)))
12559 (select-window (get-buffer-window "*Org Links*"))
12560 (shrink-window-if-larger-than-buffer)
12561 (setq truncate-lines t)
12562 (select-window cw))
12563 ;; Fake a link history, containing the stored links.
12564 (setq tmphist (append (mapcar 'car org-stored-links)
12565 org-insert-link-history))
12566 (unwind-protect
12567 (setq link (org-completing-read
12568 "Link: "
12569 (append
12570 (mapcar (lambda (x) (list (concat (car x) ":")))
12571 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12572 (mapcar (lambda (x) (list (concat x ":")))
12573 org-link-types))
12574 nil nil nil
12575 'tmphist
12576 (or (car (car org-stored-links)))))
12577 (set-window-configuration wcf)
12578 (kill-buffer "*Org Links*"))
12579 (setq entry (assoc link org-stored-links))
12580 (or entry (push link org-insert-link-history))
12581 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12582 (not org-keep-stored-link-after-insertion))
12583 (setq org-stored-links (delq (assoc link org-stored-links)
12584 org-stored-links)))
12585 (setq desc (or desc (nth 1 entry)))))
12587 (if (string-match org-plain-link-re link)
12588 ;; URL-like link, normalize the use of angular brackets.
12589 (setq link (org-make-link (org-remove-angle-brackets link))))
12591 ;; Check if we are linking to the current file with a search option
12592 ;; If yes, simplify the link by using only the search option.
12593 (when (and buffer-file-name
12594 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12595 (let* ((path (match-string 1 link))
12596 (case-fold-search nil)
12597 (search (match-string 2 link)))
12598 (save-match-data
12599 (if (equal (file-truename buffer-file-name) (file-truename path))
12600 ;; We are linking to this same file, with a search option
12601 (setq link search)))))
12603 ;; Check if we can/should use a relative path. If yes, simplify the link
12604 (when (string-match "\\<file:\\(.*\\)" link)
12605 (let* ((path (match-string 1 link))
12606 (origpath path)
12607 (case-fold-search nil))
12608 (cond
12609 ((eq org-link-file-path-type 'absolute)
12610 (setq path (abbreviate-file-name (expand-file-name path))))
12611 ((eq org-link-file-path-type 'noabbrev)
12612 (setq path (expand-file-name path)))
12613 ((eq org-link-file-path-type 'relative)
12614 (setq path (file-relative-name path)))
12616 (save-match-data
12617 (if (string-match (concat "^" (regexp-quote
12618 (file-name-as-directory
12619 (expand-file-name "."))))
12620 (expand-file-name path))
12621 ;; We are linking a file with relative path name.
12622 (setq path (substring (expand-file-name path)
12623 (match-end 0)))))))
12624 (setq link (concat "file:" path))
12625 (if (equal desc origpath)
12626 (setq desc path))))
12628 (setq desc (read-string "Description: " desc))
12629 (unless (string-match "\\S-" desc) (setq desc nil))
12630 (if remove (apply 'delete-region remove))
12631 (insert (org-make-link-string link desc))))
12633 (defun org-completing-read (&rest args)
12634 (let ((minibuffer-local-completion-map
12635 (copy-keymap minibuffer-local-completion-map)))
12636 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12637 (apply 'completing-read args)))
12639 ;;; Opening/following a link
12640 (defvar org-link-search-failed nil)
12642 (defun org-next-link ()
12643 "Move forward to the next link.
12644 If the link is in hidden text, expose it."
12645 (interactive)
12646 (when (and org-link-search-failed (eq this-command last-command))
12647 (goto-char (point-min))
12648 (message "Link search wrapped back to beginning of buffer"))
12649 (setq org-link-search-failed nil)
12650 (let* ((pos (point))
12651 (ct (org-context))
12652 (a (assoc :link ct)))
12653 (if a (goto-char (nth 2 a)))
12654 (if (re-search-forward org-any-link-re nil t)
12655 (progn
12656 (goto-char (match-beginning 0))
12657 (if (org-invisible-p) (org-show-context)))
12658 (goto-char pos)
12659 (setq org-link-search-failed t)
12660 (error "No further link found"))))
12662 (defun org-previous-link ()
12663 "Move backward to the previous link.
12664 If the link is in hidden text, expose it."
12665 (interactive)
12666 (when (and org-link-search-failed (eq this-command last-command))
12667 (goto-char (point-max))
12668 (message "Link search wrapped back to end of buffer"))
12669 (setq org-link-search-failed nil)
12670 (let* ((pos (point))
12671 (ct (org-context))
12672 (a (assoc :link ct)))
12673 (if a (goto-char (nth 1 a)))
12674 (if (re-search-backward org-any-link-re nil t)
12675 (progn
12676 (goto-char (match-beginning 0))
12677 (if (org-invisible-p) (org-show-context)))
12678 (goto-char pos)
12679 (setq org-link-search-failed t)
12680 (error "No further link found"))))
12682 (defun org-find-file-at-mouse (ev)
12683 "Open file link or URL at mouse."
12684 (interactive "e")
12685 (mouse-set-point ev)
12686 (org-open-at-point 'in-emacs))
12688 (defun org-open-at-mouse (ev)
12689 "Open file link or URL at mouse."
12690 (interactive "e")
12691 (mouse-set-point ev)
12692 (org-open-at-point))
12694 (defvar org-window-config-before-follow-link nil
12695 "The window configuration before following a link.
12696 This is saved in case the need arises to restore it.")
12698 (defvar org-open-link-marker (make-marker)
12699 "Marker pointing to the location where `org-open-at-point; was called.")
12701 ;;;###autoload
12702 (defun org-open-at-point-global ()
12703 "Follow a link like Org-mode does.
12704 This command can be called in any mode to follow a link that has
12705 Org-mode syntax."
12706 (interactive)
12707 (org-run-like-in-org-mode 'org-open-at-point))
12709 (defun org-open-at-point (&optional in-emacs)
12710 "Open link at or after point.
12711 If there is no link at point, this function will search forward up to
12712 the end of the current subtree.
12713 Normally, files will be opened by an appropriate application. If the
12714 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12715 (interactive "P")
12716 (move-marker org-open-link-marker (point))
12717 (setq org-window-config-before-follow-link (current-window-configuration))
12718 (org-remove-occur-highlights nil nil t)
12719 (if (org-at-timestamp-p t)
12720 (org-follow-timestamp-link)
12721 (let (type path link line search (pos (point)))
12722 (catch 'match
12723 (save-excursion
12724 (skip-chars-forward "^]\n\r")
12725 (when (org-in-regexp org-bracket-link-regexp)
12726 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12727 (while (string-match " *\n *" link)
12728 (setq link (replace-match " " t t link)))
12729 (setq link (org-link-expand-abbrev link))
12730 (if (string-match org-link-re-with-space2 link)
12731 (setq type (match-string 1 link) path (match-string 2 link))
12732 (setq type "thisfile" path link))
12733 (throw 'match t)))
12735 (when (get-text-property (point) 'org-linked-text)
12736 (setq type "thisfile"
12737 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12738 (1+ (point)) (point))
12739 path (buffer-substring
12740 (previous-single-property-change pos 'org-linked-text)
12741 (next-single-property-change pos 'org-linked-text)))
12742 (throw 'match t))
12744 (save-excursion
12745 (when (or (org-in-regexp org-angle-link-re)
12746 (org-in-regexp org-plain-link-re))
12747 (setq type (match-string 1) path (match-string 2))
12748 (throw 'match t)))
12749 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12750 (setq type "tree-match"
12751 path (match-string 1))
12752 (throw 'match t))
12753 (save-excursion
12754 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12755 (setq type "tags"
12756 path (match-string 1))
12757 (while (string-match ":" path)
12758 (setq path (replace-match "+" t t path)))
12759 (throw 'match t))))
12760 (unless path
12761 (error "No link found"))
12762 ;; Remove any trailing spaces in path
12763 (if (string-match " +\\'" path)
12764 (setq path (replace-match "" t t path)))
12766 (cond
12768 ((assoc type org-link-protocols)
12769 (funcall (nth 1 (assoc type org-link-protocols)) path))
12771 ((equal type "mailto")
12772 (let ((cmd (car org-link-mailto-program))
12773 (args (cdr org-link-mailto-program)) args1
12774 (address path) (subject "") a)
12775 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12776 (setq address (match-string 1 path)
12777 subject (org-link-escape (match-string 2 path))))
12778 (while args
12779 (cond
12780 ((not (stringp (car args))) (push (pop args) args1))
12781 (t (setq a (pop args))
12782 (if (string-match "%a" a)
12783 (setq a (replace-match address t t a)))
12784 (if (string-match "%s" a)
12785 (setq a (replace-match subject t t a)))
12786 (push a args1))))
12787 (apply cmd (nreverse args1))))
12789 ((member type '("http" "https" "ftp" "news"))
12790 (browse-url (concat type ":" (org-link-escape
12791 path org-link-escape-chars-browser))))
12793 ((member type '("message"))
12794 (browse-url (concat type ":" path)))
12796 ((string= type "tags")
12797 (org-tags-view in-emacs path))
12798 ((string= type "thisfile")
12799 (if in-emacs
12800 (switch-to-buffer-other-window
12801 (org-get-buffer-for-internal-link (current-buffer)))
12802 (org-mark-ring-push))
12803 (let ((cmd `(org-link-search
12804 ,path
12805 ,(cond ((equal in-emacs '(4)) 'occur)
12806 ((equal in-emacs '(16)) 'org-occur)
12807 (t nil))
12808 ,pos)))
12809 (condition-case nil (eval cmd)
12810 (error (progn (widen) (eval cmd))))))
12812 ((string= type "tree-match")
12813 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12815 ((string= type "file")
12816 (if (string-match "::\\([0-9]+\\)\\'" path)
12817 (setq line (string-to-number (match-string 1 path))
12818 path (substring path 0 (match-beginning 0)))
12819 (if (string-match "::\\(.+\\)\\'" path)
12820 (setq search (match-string 1 path)
12821 path (substring path 0 (match-beginning 0)))))
12822 (if (string-match "[*?{]" (file-name-nondirectory path))
12823 (dired path)
12824 (org-open-file path in-emacs line search)))
12826 ((string= type "news")
12827 (org-follow-gnus-link path))
12829 ((string= type "bbdb")
12830 (org-follow-bbdb-link path))
12832 ((string= type "info")
12833 (org-follow-info-link path))
12835 ((string= type "gnus")
12836 (let (group article)
12837 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12838 (error "Error in Gnus link"))
12839 (setq group (match-string 1 path)
12840 article (match-string 3 path))
12841 (org-follow-gnus-link group article)))
12843 ((string= type "vm")
12844 (let (folder article)
12845 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12846 (error "Error in VM link"))
12847 (setq folder (match-string 1 path)
12848 article (match-string 3 path))
12849 ;; in-emacs is the prefix arg, will be interpreted as read-only
12850 (org-follow-vm-link folder article in-emacs)))
12852 ((string= type "wl")
12853 (let (folder article)
12854 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12855 (error "Error in Wanderlust link"))
12856 (setq folder (match-string 1 path)
12857 article (match-string 3 path))
12858 (org-follow-wl-link folder article)))
12860 ((string= type "mhe")
12861 (let (folder article)
12862 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12863 (error "Error in MHE link"))
12864 (setq folder (match-string 1 path)
12865 article (match-string 3 path))
12866 (org-follow-mhe-link folder article)))
12868 ((string= type "rmail")
12869 (let (folder article)
12870 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12871 (error "Error in RMAIL link"))
12872 (setq folder (match-string 1 path)
12873 article (match-string 3 path))
12874 (org-follow-rmail-link folder article)))
12876 ((string= type "shell")
12877 (let ((cmd path))
12878 (if (or (not org-confirm-shell-link-function)
12879 (funcall org-confirm-shell-link-function
12880 (format "Execute \"%s\" in shell? "
12881 (org-add-props cmd nil
12882 'face 'org-warning))))
12883 (progn
12884 (message "Executing %s" cmd)
12885 (shell-command cmd))
12886 (error "Abort"))))
12888 ((string= type "elisp")
12889 (let ((cmd path))
12890 (if (or (not org-confirm-elisp-link-function)
12891 (funcall org-confirm-elisp-link-function
12892 (format "Execute \"%s\" as elisp? "
12893 (org-add-props cmd nil
12894 'face 'org-warning))))
12895 (message "%s => %s" cmd (eval (read cmd)))
12896 (error "Abort"))))
12899 (browse-url-at-point)))))
12900 (move-marker org-open-link-marker nil))
12902 ;;; File search
12904 (defvar org-create-file-search-functions nil
12905 "List of functions to construct the right search string for a file link.
12906 These functions are called in turn with point at the location to
12907 which the link should point.
12909 A function in the hook should first test if it would like to
12910 handle this file type, for example by checking the major-mode or
12911 the file extension. If it decides not to handle this file, it
12912 should just return nil to give other functions a chance. If it
12913 does handle the file, it must return the search string to be used
12914 when following the link. The search string will be part of the
12915 file link, given after a double colon, and `org-open-at-point'
12916 will automatically search for it. If special measures must be
12917 taken to make the search successful, another function should be
12918 added to the companion hook `org-execute-file-search-functions',
12919 which see.
12921 A function in this hook may also use `setq' to set the variable
12922 `description' to provide a suggestion for the descriptive text to
12923 be used for this link when it gets inserted into an Org-mode
12924 buffer with \\[org-insert-link].")
12926 (defvar org-execute-file-search-functions nil
12927 "List of functions to execute a file search triggered by a link.
12929 Functions added to this hook must accept a single argument, the
12930 search string that was part of the file link, the part after the
12931 double colon. The function must first check if it would like to
12932 handle this search, for example by checking the major-mode or the
12933 file extension. If it decides not to handle this search, it
12934 should just return nil to give other functions a chance. If it
12935 does handle the search, it must return a non-nil value to keep
12936 other functions from trying.
12938 Each function can access the current prefix argument through the
12939 variable `current-prefix-argument'. Note that a single prefix is
12940 used to force opening a link in Emacs, so it may be good to only
12941 use a numeric or double prefix to guide the search function.
12943 In case this is needed, a function in this hook can also restore
12944 the window configuration before `org-open-at-point' was called using:
12946 (set-window-configuration org-window-config-before-follow-link)")
12948 (defun org-link-search (s &optional type avoid-pos)
12949 "Search for a link search option.
12950 If S is surrounded by forward slashes, it is interpreted as a
12951 regular expression. In org-mode files, this will create an `org-occur'
12952 sparse tree. In ordinary files, `occur' will be used to list matches.
12953 If the current buffer is in `dired-mode', grep will be used to search
12954 in all files. If AVOID-POS is given, ignore matches near that position."
12955 (let ((case-fold-search t)
12956 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12957 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12958 (append '(("") (" ") ("\t") ("\n"))
12959 org-emphasis-alist)
12960 "\\|") "\\)"))
12961 (pos (point))
12962 (pre "") (post "")
12963 words re0 re1 re2 re3 re4 re5 re2a reall)
12964 (cond
12965 ;; First check if there are any special
12966 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12967 ;; Now try the builtin stuff
12968 ((save-excursion
12969 (goto-char (point-min))
12970 (and
12971 (re-search-forward
12972 (concat "<<" (regexp-quote s0) ">>") nil t)
12973 (setq pos (match-beginning 0))))
12974 ;; There is an exact target for this
12975 (goto-char pos))
12976 ((string-match "^/\\(.*\\)/$" s)
12977 ;; A regular expression
12978 (cond
12979 ((org-mode-p)
12980 (org-occur (match-string 1 s)))
12981 ;;((eq major-mode 'dired-mode)
12982 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12983 (t (org-do-occur (match-string 1 s)))))
12985 ;; A normal search strings
12986 (when (equal (string-to-char s) ?*)
12987 ;; Anchor on headlines, post may include tags.
12988 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12989 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12990 s (substring s 1)))
12991 (remove-text-properties
12992 0 (length s)
12993 '(face nil mouse-face nil keymap nil fontified nil) s)
12994 ;; Make a series of regular expressions to find a match
12995 (setq words (org-split-string s "[ \n\r\t]+")
12996 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12997 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12998 "\\)" markers)
12999 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13000 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13001 re1 (concat pre re2 post)
13002 re3 (concat pre re4 post)
13003 re5 (concat pre ".*" re4)
13004 re2 (concat pre re2)
13005 re2a (concat pre re2a)
13006 re4 (concat pre re4)
13007 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13008 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13009 re5 "\\)"
13011 (cond
13012 ((eq type 'org-occur) (org-occur reall))
13013 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13014 (t (goto-char (point-min))
13015 (if (or (org-search-not-self 1 re0 nil t)
13016 (org-search-not-self 1 re1 nil t)
13017 (org-search-not-self 1 re2 nil t)
13018 (org-search-not-self 1 re2a nil t)
13019 (org-search-not-self 1 re3 nil t)
13020 (org-search-not-self 1 re4 nil t)
13021 (org-search-not-self 1 re5 nil t)
13023 (goto-char (match-beginning 1))
13024 (goto-char pos)
13025 (error "No match")))))
13027 ;; Normal string-search
13028 (goto-char (point-min))
13029 (if (search-forward s nil t)
13030 (goto-char (match-beginning 0))
13031 (error "No match"))))
13032 (and (org-mode-p) (org-show-context 'link-search))))
13034 (defun org-search-not-self (group &rest args)
13035 "Execute `re-search-forward', but only accept matches that do not
13036 enclose the position of `org-open-link-marker'."
13037 (let ((m org-open-link-marker))
13038 (catch 'exit
13039 (while (apply 're-search-forward args)
13040 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13041 (goto-char (match-end group))
13042 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13043 (> (match-beginning 0) (marker-position m))
13044 (< (match-end 0) (marker-position m)))
13045 (save-match-data
13046 (or (not (org-in-regexp
13047 org-bracket-link-analytic-regexp 1))
13048 (not (match-end 4)) ; no description
13049 (and (<= (match-beginning 4) (point))
13050 (>= (match-end 4) (point))))))
13051 (throw 'exit (point))))))))
13053 (defun org-get-buffer-for-internal-link (buffer)
13054 "Return a buffer to be used for displaying the link target of internal links."
13055 (cond
13056 ((not org-display-internal-link-with-indirect-buffer)
13057 buffer)
13058 ((string-match "(Clone)$" (buffer-name buffer))
13059 (message "Buffer is already a clone, not making another one")
13060 ;; we also do not modify visibility in this case
13061 buffer)
13062 (t ; make a new indirect buffer for displaying the link
13063 (let* ((bn (buffer-name buffer))
13064 (ibn (concat bn "(Clone)"))
13065 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13066 (with-current-buffer ib (org-overview))
13067 ib))))
13069 (defun org-do-occur (regexp &optional cleanup)
13070 "Call the Emacs command `occur'.
13071 If CLEANUP is non-nil, remove the printout of the regular expression
13072 in the *Occur* buffer. This is useful if the regex is long and not useful
13073 to read."
13074 (occur regexp)
13075 (when cleanup
13076 (let ((cwin (selected-window)) win beg end)
13077 (when (setq win (get-buffer-window "*Occur*"))
13078 (select-window win))
13079 (goto-char (point-min))
13080 (when (re-search-forward "match[a-z]+" nil t)
13081 (setq beg (match-end 0))
13082 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13083 (setq end (1- (match-beginning 0)))))
13084 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13085 (goto-char (point-min))
13086 (select-window cwin))))
13088 ;;; The mark ring for links jumps
13090 (defvar org-mark-ring nil
13091 "Mark ring for positions before jumps in Org-mode.")
13092 (defvar org-mark-ring-last-goto nil
13093 "Last position in the mark ring used to go back.")
13094 ;; Fill and close the ring
13095 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13096 (loop for i from 1 to org-mark-ring-length do
13097 (push (make-marker) org-mark-ring))
13098 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13099 org-mark-ring)
13101 (defun org-mark-ring-push (&optional pos buffer)
13102 "Put the current position or POS into the mark ring and rotate it."
13103 (interactive)
13104 (setq pos (or pos (point)))
13105 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13106 (move-marker (car org-mark-ring)
13107 (or pos (point))
13108 (or buffer (current-buffer)))
13109 (message "%s"
13110 (substitute-command-keys
13111 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13113 (defun org-mark-ring-goto (&optional n)
13114 "Jump to the previous position in the mark ring.
13115 With prefix arg N, jump back that many stored positions. When
13116 called several times in succession, walk through the entire ring.
13117 Org-mode commands jumping to a different position in the current file,
13118 or to another Org-mode file, automatically push the old position
13119 onto the ring."
13120 (interactive "p")
13121 (let (p m)
13122 (if (eq last-command this-command)
13123 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13124 (setq p org-mark-ring))
13125 (setq org-mark-ring-last-goto p)
13126 (setq m (car p))
13127 (switch-to-buffer (marker-buffer m))
13128 (goto-char m)
13129 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13131 (defun org-remove-angle-brackets (s)
13132 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13133 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13135 (defun org-add-angle-brackets (s)
13136 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13137 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13140 ;;; Following specific links
13142 (defun org-follow-timestamp-link ()
13143 (cond
13144 ((org-at-date-range-p t)
13145 (let ((org-agenda-start-on-weekday)
13146 (t1 (match-string 1))
13147 (t2 (match-string 2)))
13148 (setq t1 (time-to-days (org-time-string-to-time t1))
13149 t2 (time-to-days (org-time-string-to-time t2)))
13150 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13151 ((org-at-timestamp-p t)
13152 (org-agenda-list nil (time-to-days (org-time-string-to-time
13153 (substring (match-string 1) 0 10)))
13155 (t (error "This should not happen"))))
13158 (defun org-follow-bbdb-link (name)
13159 "Follow a BBDB link to NAME."
13160 (require 'bbdb)
13161 (let ((inhibit-redisplay (not debug-on-error))
13162 (bbdb-electric-p nil))
13163 (catch 'exit
13164 ;; Exact match on name
13165 (bbdb-name (concat "\\`" name "\\'") nil)
13166 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13167 ;; Exact match on name
13168 (bbdb-company (concat "\\`" name "\\'") nil)
13169 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13170 ;; Partial match on name
13171 (bbdb-name name nil)
13172 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13173 ;; Partial match on company
13174 (bbdb-company name nil)
13175 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13176 ;; General match including network address and notes
13177 (bbdb name nil)
13178 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13179 (delete-window (get-buffer-window "*BBDB*"))
13180 (error "No matching BBDB record")))))
13182 (defun org-follow-info-link (name)
13183 "Follow an info file & node link to NAME."
13184 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13185 (string-match "\\(.*\\)" name))
13186 (progn
13187 (require 'info)
13188 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13189 (Info-find-node (match-string 1 name) (match-string 2 name))
13190 (Info-find-node (match-string 1 name) "Top")))
13191 (message "Could not open: %s" name)))
13193 (defun org-follow-gnus-link (&optional group article)
13194 "Follow a Gnus link to GROUP and ARTICLE."
13195 (require 'gnus)
13196 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13197 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13198 (cond ((and group article)
13199 (gnus-group-read-group 1 nil group)
13200 (gnus-summary-goto-article (string-to-number article) nil t))
13201 (group (gnus-group-jump-to-group group))))
13203 (defun org-follow-vm-link (&optional folder article readonly)
13204 "Follow a VM link to FOLDER and ARTICLE."
13205 (require 'vm)
13206 (setq article (org-add-angle-brackets article))
13207 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13208 ;; ange-ftp or efs or tramp access
13209 (let ((user (or (match-string 1 folder) (user-login-name)))
13210 (host (match-string 2 folder))
13211 (file (match-string 3 folder)))
13212 (cond
13213 ((featurep 'tramp)
13214 ;; use tramp to access the file
13215 (if (featurep 'xemacs)
13216 (setq folder (format "[%s@%s]%s" user host file))
13217 (setq folder (format "/%s@%s:%s" user host file))))
13219 ;; use ange-ftp or efs
13220 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13221 (setq folder (format "/%s@%s:%s" user host file))))))
13222 (when folder
13223 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13224 (sit-for 0.1)
13225 (when article
13226 (vm-select-folder-buffer)
13227 (widen)
13228 (let ((case-fold-search t))
13229 (goto-char (point-min))
13230 (if (not (re-search-forward
13231 (concat "^" "message-id: *" (regexp-quote article))))
13232 (error "Could not find the specified message in this folder"))
13233 (vm-isearch-update)
13234 (vm-isearch-narrow)
13235 (vm-beginning-of-message)
13236 (vm-summarize)))))
13238 (defun org-follow-wl-link (folder article)
13239 "Follow a Wanderlust link to FOLDER and ARTICLE."
13240 (if (and (string= folder "%")
13241 article
13242 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13243 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13244 ;; Thus, we recompose folder and article ids.
13245 (setq folder (format "%s#%s" folder (match-string 1 article))
13246 article (match-string 3 article)))
13247 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13248 (error "No such folder: %s" folder))
13249 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13250 (and article
13251 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13252 (wl-summary-redisplay)))
13254 (defun org-follow-rmail-link (folder article)
13255 "Follow an RMAIL link to FOLDER and ARTICLE."
13256 (setq article (org-add-angle-brackets article))
13257 (let (message-number)
13258 (save-excursion
13259 (save-window-excursion
13260 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13261 (setq message-number
13262 (save-restriction
13263 (widen)
13264 (goto-char (point-max))
13265 (if (re-search-backward
13266 (concat "^Message-ID:\\s-+" (regexp-quote
13267 (or article "")))
13268 nil t)
13269 (rmail-what-message))))))
13270 (if message-number
13271 (progn
13272 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13273 (rmail-show-message message-number)
13274 message-number)
13275 (error "Message not found"))))
13277 ;;; mh-e integration based on planner-mode
13278 (defun org-mhe-get-message-real-folder ()
13279 "Return the name of the current message real folder, so if you use
13280 sequences, it will now work."
13281 (save-excursion
13282 (let* ((folder
13283 (if (equal major-mode 'mh-folder-mode)
13284 mh-current-folder
13285 ;; Refer to the show buffer
13286 mh-show-folder-buffer))
13287 (end-index
13288 (if (boundp 'mh-index-folder)
13289 (min (length mh-index-folder) (length folder))))
13291 ;; a simple test on mh-index-data does not work, because
13292 ;; mh-index-data is always nil in a show buffer.
13293 (if (and (boundp 'mh-index-folder)
13294 (string= mh-index-folder (substring folder 0 end-index)))
13295 (if (equal major-mode 'mh-show-mode)
13296 (save-window-excursion
13297 (let (pop-up-frames)
13298 (when (buffer-live-p (get-buffer folder))
13299 (progn
13300 (pop-to-buffer folder)
13301 (org-mhe-get-message-folder-from-index)
13304 (org-mhe-get-message-folder-from-index)
13306 folder
13310 (defun org-mhe-get-message-folder-from-index ()
13311 "Returns the name of the message folder in a index folder buffer."
13312 (save-excursion
13313 (mh-index-previous-folder)
13314 (re-search-forward "^\\(+.*\\)$" nil t)
13315 (message "%s" (match-string 1))))
13317 (defun org-mhe-get-message-folder ()
13318 "Return the name of the current message folder. Be careful if you
13319 use sequences."
13320 (save-excursion
13321 (if (equal major-mode 'mh-folder-mode)
13322 mh-current-folder
13323 ;; Refer to the show buffer
13324 mh-show-folder-buffer)))
13326 (defun org-mhe-get-message-num ()
13327 "Return the number of the current message. Be careful if you
13328 use sequences."
13329 (save-excursion
13330 (if (equal major-mode 'mh-folder-mode)
13331 (mh-get-msg-num nil)
13332 ;; Refer to the show buffer
13333 (mh-show-buffer-message-number))))
13335 (defun org-mhe-get-header (header)
13336 "Return a header of the message in folder mode. This will create a
13337 show buffer for the corresponding message. If you have a more clever
13338 idea..."
13339 (let* ((folder (org-mhe-get-message-folder))
13340 (num (org-mhe-get-message-num))
13341 (buffer (get-buffer-create (concat "show-" folder)))
13342 (header-field))
13343 (with-current-buffer buffer
13344 (mh-display-msg num folder)
13345 (if (equal major-mode 'mh-folder-mode)
13346 (mh-header-display)
13347 (mh-show-header-display))
13348 (set-buffer buffer)
13349 (setq header-field (mh-get-header-field header))
13350 (if (equal major-mode 'mh-folder-mode)
13351 (mh-show)
13352 (mh-show-show))
13353 header-field)))
13355 (defun org-follow-mhe-link (folder article)
13356 "Follow an MHE link to FOLDER and ARTICLE.
13357 If ARTICLE is nil FOLDER is shown. If the configuration variable
13358 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13359 ARTICLE is searched in all folders. Indexed searches (swish++,
13360 namazu, and others supported by MH-E) will always search in all
13361 folders."
13362 (require 'mh-e)
13363 (require 'mh-search)
13364 (require 'mh-utils)
13365 (mh-find-path)
13366 (if (not article)
13367 (mh-visit-folder (mh-normalize-folder-name folder))
13368 (setq article (org-add-angle-brackets article))
13369 (mh-search-choose)
13370 (if (equal mh-searcher 'pick)
13371 (progn
13372 (mh-search folder (list "--message-id" article))
13373 (when (and org-mhe-search-all-folders
13374 (not (org-mhe-get-message-real-folder)))
13375 (kill-this-buffer)
13376 (mh-search "+" (list "--message-id" article))))
13377 (mh-search "+" article))
13378 (if (org-mhe-get-message-real-folder)
13379 (mh-show-msg 1)
13380 (kill-this-buffer)
13381 (error "Message not found"))))
13383 ;;; BibTeX links
13385 ;; Use the custom search meachnism to construct and use search strings for
13386 ;; file links to BibTeX database entries.
13388 (defun org-create-file-search-in-bibtex ()
13389 "Create the search string and description for a BibTeX database entry."
13390 (when (eq major-mode 'bibtex-mode)
13391 ;; yes, we want to construct this search string.
13392 ;; Make a good description for this entry, using names, year and the title
13393 ;; Put it into the `description' variable which is dynamically scoped.
13394 (let ((bibtex-autokey-names 1)
13395 (bibtex-autokey-names-stretch 1)
13396 (bibtex-autokey-name-case-convert-function 'identity)
13397 (bibtex-autokey-name-separator " & ")
13398 (bibtex-autokey-additional-names " et al.")
13399 (bibtex-autokey-year-length 4)
13400 (bibtex-autokey-name-year-separator " ")
13401 (bibtex-autokey-titlewords 3)
13402 (bibtex-autokey-titleword-separator " ")
13403 (bibtex-autokey-titleword-case-convert-function 'identity)
13404 (bibtex-autokey-titleword-length 'infty)
13405 (bibtex-autokey-year-title-separator ": "))
13406 (setq description (bibtex-generate-autokey)))
13407 ;; Now parse the entry, get the key and return it.
13408 (save-excursion
13409 (bibtex-beginning-of-entry)
13410 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13412 (defun org-execute-file-search-in-bibtex (s)
13413 "Find the link search string S as a key for a database entry."
13414 (when (eq major-mode 'bibtex-mode)
13415 ;; Yes, we want to do the search in this file.
13416 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13417 (goto-char (point-min))
13418 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13419 (regexp-quote s) "[ \t\n]*,") nil t)
13420 (goto-char (match-beginning 0)))
13421 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13422 ;; Use double prefix to indicate that any web link should be browsed
13423 (let ((b (current-buffer)) (p (point)))
13424 ;; Restore the window configuration because we just use the web link
13425 (set-window-configuration org-window-config-before-follow-link)
13426 (save-excursion (set-buffer b) (goto-char p)
13427 (bibtex-url)))
13428 (recenter 0)) ; Move entry start to beginning of window
13429 ;; return t to indicate that the search is done.
13432 ;; Finally add the functions to the right hooks.
13433 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13434 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13436 ;; end of Bibtex link setup
13438 ;;; Following file links
13440 (defun org-open-file (path &optional in-emacs line search)
13441 "Open the file at PATH.
13442 First, this expands any special file name abbreviations. Then the
13443 configuration variable `org-file-apps' is checked if it contains an
13444 entry for this file type, and if yes, the corresponding command is launched.
13445 If no application is found, Emacs simply visits the file.
13446 With optional argument IN-EMACS, Emacs will visit the file.
13447 Optional LINE specifies a line to go to, optional SEARCH a string to
13448 search for. If LINE or SEARCH is given, the file will always be
13449 opened in Emacs.
13450 If the file does not exist, an error is thrown."
13451 (setq in-emacs (or in-emacs line search))
13452 (let* ((file (if (equal path "")
13453 buffer-file-name
13454 (substitute-in-file-name (expand-file-name path))))
13455 (apps (append org-file-apps (org-default-apps)))
13456 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13457 (dirp (if remp nil (file-directory-p file)))
13458 (dfile (downcase file))
13459 (old-buffer (current-buffer))
13460 (old-pos (point))
13461 (old-mode major-mode)
13462 ext cmd)
13463 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13464 (setq ext (match-string 1 dfile))
13465 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13466 (setq ext (match-string 1 dfile))))
13467 (if in-emacs
13468 (setq cmd 'emacs)
13469 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13470 (and dirp (cdr (assoc 'directory apps)))
13471 (cdr (assoc ext apps))
13472 (cdr (assoc t apps)))))
13473 (when (eq cmd 'mailcap)
13474 (require 'mailcap)
13475 (mailcap-parse-mailcaps)
13476 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13477 (command (mailcap-mime-info mime-type)))
13478 (if (stringp command)
13479 (setq cmd command)
13480 (setq cmd 'emacs))))
13481 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13482 (not (file-exists-p file))
13483 (not org-open-non-existing-files))
13484 (error "No such file: %s" file))
13485 (cond
13486 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13487 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13488 (while (string-match "['\"]%s['\"]" cmd)
13489 (setq cmd (replace-match "%s" t t cmd)))
13490 (while (string-match "%s" cmd)
13491 (setq cmd (replace-match
13492 (save-match-data (shell-quote-argument file))
13493 t t cmd)))
13494 (save-window-excursion
13495 (start-process-shell-command cmd nil cmd)))
13496 ((or (stringp cmd)
13497 (eq cmd 'emacs))
13498 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13499 (widen)
13500 (if line (goto-line line)
13501 (if search (org-link-search search))))
13502 ((consp cmd)
13503 (eval cmd))
13504 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13505 (and (org-mode-p) (eq old-mode 'org-mode)
13506 (or (not (equal old-buffer (current-buffer)))
13507 (not (equal old-pos (point))))
13508 (org-mark-ring-push old-pos old-buffer))))
13510 (defun org-default-apps ()
13511 "Return the default applications for this operating system."
13512 (cond
13513 ((eq system-type 'darwin)
13514 org-file-apps-defaults-macosx)
13515 ((eq system-type 'windows-nt)
13516 org-file-apps-defaults-windowsnt)
13517 (t org-file-apps-defaults-gnu)))
13519 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13520 (defun org-file-remote-p (file)
13521 "Test whether FILE specifies a location on a remote system.
13522 Return non-nil if the location is indeed remote.
13524 For example, the filename \"/user@host:/foo\" specifies a location
13525 on the system \"/user@host:\"."
13526 (cond ((fboundp 'file-remote-p)
13527 (file-remote-p file))
13528 ((fboundp 'tramp-handle-file-remote-p)
13529 (tramp-handle-file-remote-p file))
13530 ((and (boundp 'ange-ftp-name-format)
13531 (string-match (car ange-ftp-name-format) file))
13533 (t nil)))
13536 ;;;; Hooks for remember.el, and refiling
13538 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13539 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13541 ;;;###autoload
13542 (defun org-remember-insinuate ()
13543 "Setup remember.el for use wiht Org-mode."
13544 (require 'remember)
13545 (setq remember-annotation-functions '(org-remember-annotation))
13546 (setq remember-handler-functions '(org-remember-handler))
13547 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13549 ;;;###autoload
13550 (defun org-remember-annotation ()
13551 "Return a link to the current location as an annotation for remember.el.
13552 If you are using Org-mode files as target for data storage with
13553 remember.el, then the annotations should include a link compatible with the
13554 conventions in Org-mode. This function returns such a link."
13555 (org-store-link nil))
13557 (defconst org-remember-help
13558 "Select a destination location for the note.
13559 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13560 RET on headline -> Store as sublevel entry to current headline
13561 RET at beg-of-buf -> Append to file as level 2 headline
13562 <left>/<right> -> before/after current headline, same headings level")
13564 (defvar org-remember-previous-location nil)
13565 (defvar org-force-remember-template-char) ;; dynamically scoped
13567 (defun org-select-remember-template (&optional use-char)
13568 (when org-remember-templates
13569 (let* ((templates (mapcar (lambda (x)
13570 (if (stringp (car x))
13571 (append (list (nth 1 x) (car x)) (cddr x))
13572 (append (list (car x) "") (cdr x))))
13573 org-remember-templates))
13574 (char (or use-char
13575 (cond
13576 ((= (length templates) 1)
13577 (caar templates))
13578 ((and (boundp 'org-force-remember-template-char)
13579 org-force-remember-template-char)
13580 (if (stringp org-force-remember-template-char)
13581 (string-to-char org-force-remember-template-char)
13582 org-force-remember-template-char))
13584 (message "Select template: %s"
13585 (mapconcat
13586 (lambda (x)
13587 (cond
13588 ((not (string-match "\\S-" (nth 1 x)))
13589 (format "[%c]" (car x)))
13590 ((equal (downcase (car x))
13591 (downcase (aref (nth 1 x) 0)))
13592 (format "[%c]%s" (car x)
13593 (substring (nth 1 x) 1)))
13594 (t (format "[%c]%s" (car x) (nth 1 x)))))
13595 templates " "))
13596 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13597 (when (equal char0 ?\C-g)
13598 (jump-to-register remember-register)
13599 (kill-buffer remember-buffer))
13600 char0))))))
13601 (cddr (assoc char templates)))))
13603 (defvar x-last-selected-text)
13604 (defvar x-last-selected-text-primary)
13606 ;;;###autoload
13607 (defun org-remember-apply-template (&optional use-char skip-interactive)
13608 "Initialize *remember* buffer with template, invoke `org-mode'.
13609 This function should be placed into `remember-mode-hook' and in fact requires
13610 to be run from that hook to function properly."
13611 (if org-remember-templates
13612 (let* ((entry (org-select-remember-template use-char))
13613 (tpl (car entry))
13614 (plist-p (if org-store-link-plist t nil))
13615 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13616 (string-match "\\S-" (nth 1 entry)))
13617 (nth 1 entry)
13618 org-default-notes-file))
13619 (headline (nth 2 entry))
13620 (v-c (or (and (eq window-system 'x)
13621 (fboundp 'x-cut-buffer-or-selection-value)
13622 (x-cut-buffer-or-selection-value))
13623 (org-bound-and-true-p x-last-selected-text)
13624 (org-bound-and-true-p x-last-selected-text-primary)
13625 (and (> (length kill-ring) 0) (current-kill 0))))
13626 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13627 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13628 (v-u (concat "[" (substring v-t 1 -1) "]"))
13629 (v-U (concat "[" (substring v-T 1 -1) "]"))
13630 ;; `initial' and `annotation' are bound in `remember'
13631 (v-i (if (boundp 'initial) initial))
13632 (v-a (if (and (boundp 'annotation) annotation)
13633 (if (equal annotation "[[]]") "" annotation)
13634 ""))
13635 (v-A (if (and v-a
13636 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13637 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13638 v-a))
13639 (v-n user-full-name)
13640 (org-startup-folded nil)
13641 org-time-was-given org-end-time-was-given x
13642 prompt completions char time pos default histvar)
13643 (setq org-store-link-plist
13644 (append (list :annotation v-a :initial v-i)
13645 org-store-link-plist))
13646 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13647 (erase-buffer)
13648 (insert (substitute-command-keys
13649 (format
13650 "## Filing location: Select interactively, default, or last used:
13651 ## %s to select file and header location interactively.
13652 ## %s \"%s\" -> \"* %s\"
13653 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13654 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13655 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13656 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13657 (abbreviate-file-name (or file org-default-notes-file))
13658 (or headline "")
13659 (or (car org-remember-previous-location) "???")
13660 (or (cdr org-remember-previous-location) "???"))))
13661 (insert tpl) (goto-char (point-min))
13662 ;; Simple %-escapes
13663 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13664 (when (and initial (equal (match-string 0) "%i"))
13665 (save-match-data
13666 (let* ((lead (buffer-substring
13667 (point-at-bol) (match-beginning 0))))
13668 (setq v-i (mapconcat 'identity
13669 (org-split-string initial "\n")
13670 (concat "\n" lead))))))
13671 (replace-match
13672 (or (eval (intern (concat "v-" (match-string 1)))) "")
13673 t t))
13675 ;; %[] Insert contents of a file.
13676 (goto-char (point-min))
13677 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13678 (let ((start (match-beginning 0))
13679 (end (match-end 0))
13680 (filename (expand-file-name (match-string 1))))
13681 (goto-char start)
13682 (delete-region start end)
13683 (condition-case error
13684 (insert-file-contents filename)
13685 (error (insert (format "%%![Couldn't insert %s: %s]"
13686 filename error))))))
13687 ;; %() embedded elisp
13688 (goto-char (point-min))
13689 (while (re-search-forward "%\\((.+)\\)" nil t)
13690 (goto-char (match-beginning 0))
13691 (let ((template-start (point)))
13692 (forward-char 1)
13693 (let ((result
13694 (condition-case error
13695 (eval (read (current-buffer)))
13696 (error (format "%%![Error: %s]" error)))))
13697 (delete-region template-start (point))
13698 (insert result))))
13700 ;; From the property list
13701 (when plist-p
13702 (goto-char (point-min))
13703 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13704 (and (setq x (or (plist-get org-store-link-plist
13705 (intern (match-string 1))) ""))
13706 (replace-match x t t))))
13708 ;; Turn on org-mode in the remember buffer, set local variables
13709 (org-mode)
13710 (org-set-local 'org-finish-function 'org-remember-finalize)
13711 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13712 (org-set-local 'org-default-notes-file file))
13713 (if (and headline (stringp headline) (string-match "\\S-" headline))
13714 (org-set-local 'org-remember-default-headline headline))
13715 ;; Interactive template entries
13716 (goto-char (point-min))
13717 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13718 (setq char (if (match-end 3) (match-string 3))
13719 prompt (if (match-end 2) (match-string 2)))
13720 (goto-char (match-beginning 0))
13721 (replace-match "")
13722 (setq completions nil default nil)
13723 (when prompt
13724 (setq completions (org-split-string prompt "|")
13725 prompt (pop completions)
13726 default (car completions)
13727 histvar (intern (concat
13728 "org-remember-template-prompt-history::"
13729 (or prompt "")))
13730 completions (mapcar 'list completions)))
13731 (cond
13732 ((member char '("G" "g"))
13733 (let* ((org-last-tags-completion-table
13734 (org-global-tags-completion-table
13735 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13736 (org-add-colon-after-tag-completion t)
13737 (ins (completing-read
13738 (if prompt (concat prompt ": ") "Tags: ")
13739 'org-tags-completion-function nil nil nil
13740 'org-tags-history)))
13741 (setq ins (mapconcat 'identity
13742 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13743 ":"))
13744 (when (string-match "\\S-" ins)
13745 (or (equal (char-before) ?:) (insert ":"))
13746 (insert ins)
13747 (or (equal (char-after) ?:) (insert ":")))))
13748 (char
13749 (setq org-time-was-given (equal (upcase char) char))
13750 (setq time (org-read-date (equal (upcase char) "U") t nil
13751 prompt))
13752 (org-insert-time-stamp time org-time-was-given
13753 (member char '("u" "U"))
13754 nil nil (list org-end-time-was-given)))
13756 (insert (org-completing-read
13757 (concat (if prompt prompt "Enter string")
13758 (if default (concat " [" default "]"))
13759 ": ")
13760 completions nil nil nil histvar default)))))
13761 (goto-char (point-min))
13762 (if (re-search-forward "%\\?" nil t)
13763 (replace-match "")
13764 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13765 (org-mode)
13766 (org-set-local 'org-finish-function 'org-remember-finalize))
13767 (when (save-excursion
13768 (goto-char (point-min))
13769 (re-search-forward "%!" nil t))
13770 (replace-match "")
13771 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13773 (defun org-remember-finish-immediately ()
13774 "File remember note immediately.
13775 This should be run in `post-command-hook' and will remove itself
13776 from that hook."
13777 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13778 (when org-finish-function
13779 (funcall org-finish-function)))
13781 (defvar org-clock-marker) ; Defined below
13782 (defun org-remember-finalize ()
13783 "Finalize the remember process."
13784 (unless (fboundp 'remember-finalize)
13785 (defalias 'remember-finalize 'remember-buffer))
13786 (when (and org-clock-marker
13787 (equal (marker-buffer org-clock-marker) (current-buffer)))
13788 ;; FIXME: test this, this is w/o notetaking!
13789 (let (org-log-note-clock-out) (org-clock-out)))
13790 (when buffer-file-name
13791 (save-buffer)
13792 (setq buffer-file-name nil))
13793 (remember-finalize))
13795 ;;;###autoload
13796 (defun org-remember (&optional goto org-force-remember-template-char)
13797 "Call `remember'. If this is already a remember buffer, re-apply template.
13798 If there is an active region, make sure remember uses it as initial content
13799 of the remember buffer.
13801 When called interactively with a `C-u' prefix argument GOTO, don't remember
13802 anything, just go to the file/headline where the selected template usually
13803 stores its notes. With a double prefix arg `C-u C-u', go to the last
13804 note stored by remember.
13806 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13807 associated with a template in `org-remember-templates'."
13808 (interactive "P")
13809 (cond
13810 ((equal goto '(4)) (org-go-to-remember-target))
13811 ((equal goto '(16)) (org-remember-goto-last-stored))
13813 (if (memq org-finish-function '(remember-buffer remember-finalize))
13814 (progn
13815 (when (< (length org-remember-templates) 2)
13816 (error "No other template available"))
13817 (erase-buffer)
13818 (let ((annotation (plist-get org-store-link-plist :annotation))
13819 (initial (plist-get org-store-link-plist :initial)))
13820 (org-remember-apply-template))
13821 (message "Press C-c C-c to remember data"))
13822 (if (org-region-active-p)
13823 (remember (buffer-substring (point) (mark)))
13824 (call-interactively 'remember))))))
13826 (defun org-remember-goto-last-stored ()
13827 "Go to the location where the last remember note was stored."
13828 (interactive)
13829 (bookmark-jump "org-remember-last-stored")
13830 (message "This is the last note stored by remember"))
13832 (defun org-go-to-remember-target (&optional template-key)
13833 "Go to the target location of a remember template.
13834 The user is queried for the template."
13835 (interactive)
13836 (let* ((entry (org-select-remember-template template-key))
13837 (file (nth 1 entry))
13838 (heading (nth 2 entry))
13839 visiting)
13840 (unless (and file (stringp file) (string-match "\\S-" file))
13841 (setq file org-default-notes-file))
13842 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13843 (setq heading org-remember-default-headline))
13844 (setq visiting (org-find-base-buffer-visiting file))
13845 (if (not visiting) (find-file-noselect file))
13846 (switch-to-buffer (or visiting (get-file-buffer file)))
13847 (widen)
13848 (goto-char (point-min))
13849 (if (re-search-forward
13850 (concat "^\\*+[ \t]+" (regexp-quote heading)
13851 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13852 nil t)
13853 (goto-char (match-beginning 0))
13854 (error "Target headline not found: %s" heading))))
13856 (defvar org-note-abort nil) ; dynamically scoped
13858 ;;;###autoload
13859 (defun org-remember-handler ()
13860 "Store stuff from remember.el into an org file.
13861 First prompts for an org file. If the user just presses return, the value
13862 of `org-default-notes-file' is used.
13863 Then the command offers the headings tree of the selected file in order to
13864 file the text at a specific location.
13865 You can either immediately press RET to get the note appended to the
13866 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13867 find a better place. Then press RET or <left> or <right> in insert the note.
13869 Key Cursor position Note gets inserted
13870 -----------------------------------------------------------------------------
13871 RET buffer-start as level 1 heading at end of file
13872 RET on headline as sublevel of the heading at cursor
13873 RET no heading at cursor position, level taken from context.
13874 Or use prefix arg to specify level manually.
13875 <left> on headline as same level, before current heading
13876 <right> on headline as same level, after current heading
13878 So the fastest way to store the note is to press RET RET to append it to
13879 the default file. This way your current train of thought is not
13880 interrupted, in accordance with the principles of remember.el.
13881 You can also get the fast execution without prompting by using
13882 C-u C-c C-c to exit the remember buffer. See also the variable
13883 `org-remember-store-without-prompt'.
13885 Before being stored away, the function ensures that the text has a
13886 headline, i.e. a first line that starts with a \"*\". If not, a headline
13887 is constructed from the current date and some additional data.
13889 If the variable `org-adapt-indentation' is non-nil, the entire text is
13890 also indented so that it starts in the same column as the headline
13891 \(i.e. after the stars).
13893 See also the variable `org-reverse-note-order'."
13894 (goto-char (point-min))
13895 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13896 (replace-match ""))
13897 (goto-char (point-max))
13898 (beginning-of-line 1)
13899 (while (looking-at "[ \t]*$\\|##.*")
13900 (delete-region (1- (point)) (point-max))
13901 (beginning-of-line 1))
13902 (catch 'quit
13903 (if org-note-abort (throw 'quit nil))
13904 (let* ((txt (buffer-substring (point-min) (point-max)))
13905 (fastp (org-xor (equal current-prefix-arg '(4))
13906 org-remember-store-without-prompt))
13907 (file (cond
13908 (fastp org-default-notes-file)
13909 ((and (eq org-remember-interactive-interface 'refile)
13910 org-refile-targets)
13911 org-default-notes-file)
13912 ((not (and (equal current-prefix-arg '(16))
13913 org-remember-previous-location))
13914 (org-get-org-file))))
13915 (heading org-remember-default-headline)
13916 (visiting (and file (org-find-base-buffer-visiting file)))
13917 (org-startup-folded nil)
13918 (org-startup-align-all-tables nil)
13919 (org-goto-start-pos 1)
13920 spos exitcmd level indent reversed)
13921 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13922 (setq file (car org-remember-previous-location)
13923 heading (cdr org-remember-previous-location)
13924 fastp t))
13925 (setq current-prefix-arg nil)
13926 (if (string-match "[ \t\n]+\\'" txt)
13927 (setq txt (replace-match "" t t txt)))
13928 ;; Modify text so that it becomes a nice subtree which can be inserted
13929 ;; into an org tree.
13930 (let* ((lines (split-string txt "\n"))
13931 first)
13932 (setq first (car lines) lines (cdr lines))
13933 (if (string-match "^\\*+ " first)
13934 ;; Is already a headline
13935 (setq indent nil)
13936 ;; We need to add a headline: Use time and first buffer line
13937 (setq lines (cons first lines)
13938 first (concat "* " (current-time-string)
13939 " (" (remember-buffer-desc) ")")
13940 indent " "))
13941 (if (and org-adapt-indentation indent)
13942 (setq lines (mapcar
13943 (lambda (x)
13944 (if (string-match "\\S-" x)
13945 (concat indent x) x))
13946 lines)))
13947 (setq txt (concat first "\n"
13948 (mapconcat 'identity lines "\n"))))
13949 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13950 (setq txt (replace-match "\n\n" t t txt))
13951 (if (string-match "[ \t\n]*\\'" txt)
13952 (setq txt (replace-match "\n" t t txt))))
13953 ;; Put the modified text back into the remember buffer, for refile.
13954 (erase-buffer)
13955 (insert txt)
13956 (goto-char (point-min))
13957 (when (and (eq org-remember-interactive-interface 'refile)
13958 (not fastp))
13959 (org-refile nil (or visiting (find-file-noselect file)))
13960 (throw 'quit t))
13961 ;; Find the file
13962 (if (not visiting) (find-file-noselect file))
13963 (with-current-buffer (or visiting (get-file-buffer file))
13964 (unless (org-mode-p)
13965 (error "Target files for remember notes must be in Org-mode"))
13966 (save-excursion
13967 (save-restriction
13968 (widen)
13969 (and (goto-char (point-min))
13970 (not (re-search-forward "^\\* " nil t))
13971 (insert "\n* " (or heading "Notes") "\n"))
13972 (setq reversed (org-notes-order-reversed-p))
13974 ;; Find the default location
13975 (when (and heading (stringp heading) (string-match "\\S-" heading))
13976 (goto-char (point-min))
13977 (if (re-search-forward
13978 (concat "^\\*+[ \t]+" (regexp-quote heading)
13979 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13980 nil t)
13981 (setq org-goto-start-pos (match-beginning 0))
13982 (when fastp
13983 (goto-char (point-max))
13984 (unless (bolp) (newline))
13985 (insert "* " heading "\n")
13986 (setq org-goto-start-pos (point-at-bol 0)))))
13988 ;; Ask the User for a location, using the appropriate interface
13989 (cond
13990 (fastp (setq spos org-goto-start-pos
13991 exitcmd 'return))
13992 ((eq org-remember-interactive-interface 'outline)
13993 (setq spos (org-get-location (current-buffer)
13994 org-remember-help)
13995 exitcmd (cdr spos)
13996 spos (car spos)))
13997 ((eq org-remember-interactive-interface 'outline-path-completion)
13998 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13999 (org-refile-use-outline-path t))
14000 (setq spos (org-refile-get-location "Heading: ")
14001 exitcmd 'return
14002 spos (nth 3 spos))))
14003 (t (error "this should not hapen")))
14004 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14005 ; not handle this note
14006 (goto-char spos)
14007 (cond ((org-on-heading-p t)
14008 (org-back-to-heading t)
14009 (setq level (funcall outline-level))
14010 (cond
14011 ((eq exitcmd 'return)
14012 ;; sublevel of current
14013 (setq org-remember-previous-location
14014 (cons (abbreviate-file-name file)
14015 (org-get-heading 'notags)))
14016 (if reversed
14017 (outline-next-heading)
14018 (org-end-of-subtree t)
14019 (if (not (bolp))
14020 (if (looking-at "[ \t]*\n")
14021 (beginning-of-line 2)
14022 (end-of-line 1)
14023 (insert "\n"))))
14024 (bookmark-set "org-remember-last-stored")
14025 (org-paste-subtree (org-get-legal-level level 1) txt))
14026 ((eq exitcmd 'left)
14027 ;; before current
14028 (bookmark-set "org-remember-last-stored")
14029 (org-paste-subtree level txt))
14030 ((eq exitcmd 'right)
14031 ;; after current
14032 (org-end-of-subtree t)
14033 (bookmark-set "org-remember-last-stored")
14034 (org-paste-subtree level txt))
14035 (t (error "This should not happen"))))
14037 ((and (bobp) (not reversed))
14038 ;; Put it at the end, one level below level 1
14039 (save-restriction
14040 (widen)
14041 (goto-char (point-max))
14042 (if (not (bolp)) (newline))
14043 (bookmark-set "org-remember-last-stored")
14044 (org-paste-subtree (org-get-legal-level 1 1) txt)))
14046 ((and (bobp) reversed)
14047 ;; Put it at the start, as level 1
14048 (save-restriction
14049 (widen)
14050 (goto-char (point-min))
14051 (re-search-forward "^\\*+ " nil t)
14052 (beginning-of-line 1)
14053 (bookmark-set "org-remember-last-stored")
14054 (org-paste-subtree 1 txt)))
14056 ;; Put it right there, with automatic level determined by
14057 ;; org-paste-subtree or from prefix arg
14058 (bookmark-set "org-remember-last-stored")
14059 (org-paste-subtree
14060 (if (numberp current-prefix-arg) current-prefix-arg)
14061 txt)))
14062 (when remember-save-after-remembering
14063 (save-buffer)
14064 (if (not visiting) (kill-buffer (current-buffer)))))))))
14066 t) ;; return t to indicate that we took care of this note.
14068 (defun org-get-org-file ()
14069 "Read a filename, with default directory `org-directory'."
14070 (let ((default (or org-default-notes-file remember-data-file)))
14071 (read-file-name (format "File name [%s]: " default)
14072 (file-name-as-directory org-directory)
14073 default)))
14075 (defun org-notes-order-reversed-p ()
14076 "Check if the current file should receive notes in reversed order."
14077 (cond
14078 ((not org-reverse-note-order) nil)
14079 ((eq t org-reverse-note-order) t)
14080 ((not (listp org-reverse-note-order)) nil)
14081 (t (catch 'exit
14082 (let ((all org-reverse-note-order)
14083 entry)
14084 (while (setq entry (pop all))
14085 (if (string-match (car entry) buffer-file-name)
14086 (throw 'exit (cdr entry))))
14087 nil)))))
14089 ;;; Refiling
14091 (defvar org-refile-target-table nil
14092 "The list of refile targets, created by `org-refile'.")
14094 (defvar org-agenda-new-buffers nil
14095 "Buffers created to visit agenda files.")
14097 (defun org-get-refile-targets (&optional default-buffer)
14098 "Produce a table with refile targets."
14099 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14100 targets txt re files f desc descre)
14101 (with-current-buffer (or default-buffer (current-buffer))
14102 (while (setq entry (pop entries))
14103 (setq files (car entry) desc (cdr entry))
14104 (cond
14105 ((null files) (setq files (list (current-buffer))))
14106 ((eq files 'org-agenda-files)
14107 (setq files (org-agenda-files 'unrestricted)))
14108 ((and (symbolp files) (fboundp files))
14109 (setq files (funcall files)))
14110 ((and (symbolp files) (boundp files))
14111 (setq files (symbol-value files))))
14112 (if (stringp files) (setq files (list files)))
14113 (cond
14114 ((eq (car desc) :tag)
14115 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14116 ((eq (car desc) :todo)
14117 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14118 ((eq (car desc) :regexp)
14119 (setq descre (cdr desc)))
14120 ((eq (car desc) :level)
14121 (setq descre (concat "^\\*\\{" (number-to-string
14122 (if org-odd-levels-only
14123 (1- (* 2 (cdr desc)))
14124 (cdr desc)))
14125 "\\}[ \t]")))
14126 ((eq (car desc) :maxlevel)
14127 (setq descre (concat "^\\*\\{1," (number-to-string
14128 (if org-odd-levels-only
14129 (1- (* 2 (cdr desc)))
14130 (cdr desc)))
14131 "\\}[ \t]")))
14132 (t (error "Bad refiling target description %s" desc)))
14133 (while (setq f (pop files))
14134 (save-excursion
14135 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14136 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14137 (save-excursion
14138 (save-restriction
14139 (widen)
14140 (goto-char (point-min))
14141 (while (re-search-forward descre nil t)
14142 (goto-char (point-at-bol))
14143 (when (looking-at org-complex-heading-regexp)
14144 (setq txt (match-string 4)
14145 re (concat "^" (regexp-quote
14146 (buffer-substring (match-beginning 1)
14147 (match-end 4)))))
14148 (if (match-end 5) (setq re (concat re "[ \t]+"
14149 (regexp-quote
14150 (match-string 5)))))
14151 (setq re (concat re "[ \t]*$"))
14152 (when org-refile-use-outline-path
14153 (setq txt (mapconcat 'identity
14154 (append
14155 (if (eq org-refile-use-outline-path 'file)
14156 (list (file-name-nondirectory
14157 (buffer-file-name (buffer-base-buffer))))
14158 (if (eq org-refile-use-outline-path 'full-file-path)
14159 (list (buffer-file-name (buffer-base-buffer)))))
14160 (org-get-outline-path)
14161 (list txt))
14162 "/")))
14163 (push (list txt f re (point)) targets))
14164 (goto-char (point-at-eol))))))))
14165 (nreverse targets))))
14167 (defun org-get-outline-path ()
14168 "Return the outline path to the current entry, as a list."
14169 (let (rtn)
14170 (save-excursion
14171 (while (org-up-heading-safe)
14172 (when (looking-at org-complex-heading-regexp)
14173 (push (org-match-string-no-properties 4) rtn)))
14174 rtn)))
14176 (defvar org-refile-history nil
14177 "History for refiling operations.")
14179 (defun org-refile (&optional goto default-buffer)
14180 "Move the entry at point to another heading.
14181 The list of target headings is compiled using the information in
14182 `org-refile-targets', which see. This list is created upon first use, and
14183 you can update it by calling this command with a double prefix (`C-u C-u').
14184 FIXME: Can we find a better way of updating?
14186 At the target location, the entry is filed as a subitem of the target heading.
14187 Depending on `org-reverse-note-order', the new subitem will either be the
14188 first of the last subitem.
14190 With prefix arg GOTO, the command will only visit the target location,
14191 not actually move anything.
14192 With a double prefix `C-c C-c', go to the location where the last refiling
14193 operation has put the subtree.
14195 With a double prefix argument, the command can be used to jump to any
14196 heading in the current buffer."
14197 (interactive "P")
14198 (let* ((cbuf (current-buffer))
14199 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14200 pos it nbuf file re level reversed)
14201 (if (equal goto '(16))
14202 (org-refile-goto-last-stored)
14203 (when (setq it (org-refile-get-location
14204 (if goto "Goto: " "Refile to: ") default-buffer))
14205 (setq file (nth 1 it)
14206 re (nth 2 it)
14207 pos (nth 3 it))
14208 (setq nbuf (or (find-buffer-visiting file)
14209 (find-file-noselect file)))
14210 (if goto
14211 (progn
14212 (switch-to-buffer nbuf)
14213 (goto-char pos)
14214 (org-show-context 'org-goto))
14215 (org-copy-special)
14216 (save-excursion
14217 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14218 (find-file-noselect file))))
14219 (setq reversed (org-notes-order-reversed-p))
14220 (save-excursion
14221 (save-restriction
14222 (widen)
14223 (goto-char pos)
14224 (looking-at outline-regexp)
14225 (setq level (org-get-legal-level (funcall outline-level) 1))
14226 (goto-char
14227 (if reversed
14228 (outline-next-heading)
14229 (or (save-excursion (outline-get-next-sibling))
14230 (org-end-of-subtree t t)
14231 (point-max))))
14232 (bookmark-set "org-refile-last-stored")
14233 (org-paste-subtree level))))
14234 (org-cut-special)
14235 (message "Entry refiled to \"%s\"" (car it)))))))
14237 (defun org-refile-goto-last-stored ()
14238 "Go to the location where the last refile was stored."
14239 (interactive)
14240 (bookmark-jump "org-refile-last-stored")
14241 (message "This is the location of the last refile"))
14243 (defun org-refile-get-location (&optional prompt default-buffer)
14244 "Prompt the user for a refile location, using PROMPT."
14245 (let ((org-refile-targets org-refile-targets)
14246 (org-refile-use-outline-path org-refile-use-outline-path))
14247 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14248 (unless org-refile-target-table
14249 (error "No refile targets"))
14250 (let* ((cbuf (current-buffer))
14251 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14252 (fname (and filename (file-truename filename)))
14253 (tbl (mapcar
14254 (lambda (x)
14255 (if (not (equal fname (file-truename (nth 1 x))))
14256 (cons (concat (car x) " (" (file-name-nondirectory
14257 (nth 1 x)) ")")
14258 (cdr x))
14260 org-refile-target-table))
14261 (completion-ignore-case t))
14262 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14263 tbl)))
14265 ;;;; Dynamic blocks
14267 (defun org-find-dblock (name)
14268 "Find the first dynamic block with name NAME in the buffer.
14269 If not found, stay at current position and return nil."
14270 (let (pos)
14271 (save-excursion
14272 (goto-char (point-min))
14273 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14274 nil t)
14275 (match-beginning 0))))
14276 (if pos (goto-char pos))
14277 pos))
14279 (defconst org-dblock-start-re
14280 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14281 "Matches the startline of a dynamic block, with parameters.")
14283 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14284 "Matches the end of a dyhamic block.")
14286 (defun org-create-dblock (plist)
14287 "Create a dynamic block section, with parameters taken from PLIST.
14288 PLIST must containe a :name entry which is used as name of the block."
14289 (unless (bolp) (newline))
14290 (let ((name (plist-get plist :name)))
14291 (insert "#+BEGIN: " name)
14292 (while plist
14293 (if (eq (car plist) :name)
14294 (setq plist (cddr plist))
14295 (insert " " (prin1-to-string (pop plist)))))
14296 (insert "\n\n#+END:\n")
14297 (beginning-of-line -2)))
14299 (defun org-prepare-dblock ()
14300 "Prepare dynamic block for refresh.
14301 This empties the block, puts the cursor at the insert position and returns
14302 the property list including an extra property :name with the block name."
14303 (unless (looking-at org-dblock-start-re)
14304 (error "Not at a dynamic block"))
14305 (let* ((begdel (1+ (match-end 0)))
14306 (name (org-no-properties (match-string 1)))
14307 (params (append (list :name name)
14308 (read (concat "(" (match-string 3) ")")))))
14309 (unless (re-search-forward org-dblock-end-re nil t)
14310 (error "Dynamic block not terminated"))
14311 (delete-region begdel (match-beginning 0))
14312 (goto-char begdel)
14313 (open-line 1)
14314 params))
14316 (defun org-map-dblocks (&optional command)
14317 "Apply COMMAND to all dynamic blocks in the current buffer.
14318 If COMMAND is not given, use `org-update-dblock'."
14319 (let ((cmd (or command 'org-update-dblock))
14320 pos)
14321 (save-excursion
14322 (goto-char (point-min))
14323 (while (re-search-forward org-dblock-start-re nil t)
14324 (goto-char (setq pos (match-beginning 0)))
14325 (condition-case nil
14326 (funcall cmd)
14327 (error (message "Error during update of dynamic block")))
14328 (goto-char pos)
14329 (unless (re-search-forward org-dblock-end-re nil t)
14330 (error "Dynamic block not terminated"))))))
14332 (defun org-dblock-update (&optional arg)
14333 "User command for updating dynamic blocks.
14334 Update the dynamic block at point. With prefix ARG, update all dynamic
14335 blocks in the buffer."
14336 (interactive "P")
14337 (if arg
14338 (org-update-all-dblocks)
14339 (or (looking-at org-dblock-start-re)
14340 (org-beginning-of-dblock))
14341 (org-update-dblock)))
14343 (defun org-update-dblock ()
14344 "Update the dynamic block at point
14345 This means to empty the block, parse for parameters and then call
14346 the correct writing function."
14347 (save-window-excursion
14348 (let* ((pos (point))
14349 (line (org-current-line))
14350 (params (org-prepare-dblock))
14351 (name (plist-get params :name))
14352 (cmd (intern (concat "org-dblock-write:" name))))
14353 (message "Updating dynamic block `%s' at line %d..." name line)
14354 (funcall cmd params)
14355 (message "Updating dynamic block `%s' at line %d...done" name line)
14356 (goto-char pos))))
14358 (defun org-beginning-of-dblock ()
14359 "Find the beginning of the dynamic block at point.
14360 Error if there is no scuh block at point."
14361 (let ((pos (point))
14362 beg)
14363 (end-of-line 1)
14364 (if (and (re-search-backward org-dblock-start-re nil t)
14365 (setq beg (match-beginning 0))
14366 (re-search-forward org-dblock-end-re nil t)
14367 (> (match-end 0) pos))
14368 (goto-char beg)
14369 (goto-char pos)
14370 (error "Not in a dynamic block"))))
14372 (defun org-update-all-dblocks ()
14373 "Update all dynamic blocks in the buffer.
14374 This function can be used in a hook."
14375 (when (org-mode-p)
14376 (org-map-dblocks 'org-update-dblock)))
14379 ;;;; Completion
14381 (defconst org-additional-option-like-keywords
14382 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14383 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14384 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14386 (defun org-complete (&optional arg)
14387 "Perform completion on word at point.
14388 At the beginning of a headline, this completes TODO keywords as given in
14389 `org-todo-keywords'.
14390 If the current word is preceded by a backslash, completes the TeX symbols
14391 that are supported for HTML support.
14392 If the current word is preceded by \"#+\", completes special words for
14393 setting file options.
14394 In the line after \"#+STARTUP:, complete valid keywords.\"
14395 At all other locations, this simply calls the value of
14396 `org-completion-fallback-command'."
14397 (interactive "P")
14398 (org-without-partial-completion
14399 (catch 'exit
14400 (let* ((end (point))
14401 (beg1 (save-excursion
14402 (skip-chars-backward (org-re "[:alnum:]_@"))
14403 (point)))
14404 (beg (save-excursion
14405 (skip-chars-backward "a-zA-Z0-9_:$")
14406 (point)))
14407 (confirm (lambda (x) (stringp (car x))))
14408 (searchhead (equal (char-before beg) ?*))
14409 (tag (and (equal (char-before beg1) ?:)
14410 (equal (char-after (point-at-bol)) ?*)))
14411 (prop (and (equal (char-before beg1) ?:)
14412 (not (equal (char-after (point-at-bol)) ?*))))
14413 (texp (equal (char-before beg) ?\\))
14414 (link (equal (char-before beg) ?\[))
14415 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14416 beg)
14417 "#+"))
14418 (startup (string-match "^#\\+STARTUP:.*"
14419 (buffer-substring (point-at-bol) (point))))
14420 (completion-ignore-case opt)
14421 (type nil)
14422 (tbl nil)
14423 (table (cond
14424 (opt
14425 (setq type :opt)
14426 (append
14427 (mapcar
14428 (lambda (x)
14429 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14430 (cons (match-string 2 x) (match-string 1 x)))
14431 (org-split-string (org-get-current-options) "\n"))
14432 (mapcar 'list org-additional-option-like-keywords)))
14433 (startup
14434 (setq type :startup)
14435 org-startup-options)
14436 (link (append org-link-abbrev-alist-local
14437 org-link-abbrev-alist))
14438 (texp
14439 (setq type :tex)
14440 org-html-entities)
14441 ((string-match "\\`\\*+[ \t]+\\'"
14442 (buffer-substring (point-at-bol) beg))
14443 (setq type :todo)
14444 (mapcar 'list org-todo-keywords-1))
14445 (searchhead
14446 (setq type :searchhead)
14447 (save-excursion
14448 (goto-char (point-min))
14449 (while (re-search-forward org-todo-line-regexp nil t)
14450 (push (list
14451 (org-make-org-heading-search-string
14452 (match-string 3) t))
14453 tbl)))
14454 tbl)
14455 (tag (setq type :tag beg beg1)
14456 (or org-tag-alist (org-get-buffer-tags)))
14457 (prop (setq type :prop beg beg1)
14458 (mapcar 'list (org-buffer-property-keys nil t t)))
14459 (t (progn
14460 (call-interactively org-completion-fallback-command)
14461 (throw 'exit nil)))))
14462 (pattern (buffer-substring-no-properties beg end))
14463 (completion (try-completion pattern table confirm)))
14464 (cond ((eq completion t)
14465 (if (not (assoc (upcase pattern) table))
14466 (message "Already complete")
14467 (if (equal type :opt)
14468 (insert (substring (cdr (assoc (upcase pattern) table))
14469 (length pattern)))
14470 (if (memq type '(:tag :prop)) (insert ":")))))
14471 ((null completion)
14472 (message "Can't find completion for \"%s\"" pattern)
14473 (ding))
14474 ((not (string= pattern completion))
14475 (delete-region beg end)
14476 (if (string-match " +$" completion)
14477 (setq completion (replace-match "" t t completion)))
14478 (insert completion)
14479 (if (get-buffer-window "*Completions*")
14480 (delete-window (get-buffer-window "*Completions*")))
14481 (if (assoc completion table)
14482 (if (eq type :todo) (insert " ")
14483 (if (memq type '(:tag :prop)) (insert ":"))))
14484 (if (and (equal type :opt) (assoc completion table))
14485 (message "%s" (substitute-command-keys
14486 "Press \\[org-complete] again to insert example settings"))))
14488 (message "Making completion list...")
14489 (let ((list (sort (all-completions pattern table confirm)
14490 'string<)))
14491 (with-output-to-temp-buffer "*Completions*"
14492 (condition-case nil
14493 ;; Protection needed for XEmacs and emacs 21
14494 (display-completion-list list pattern)
14495 (error (display-completion-list list)))))
14496 (message "Making completion list...%s" "done")))))))
14498 ;;;; TODO, DEADLINE, Comments
14500 (defun org-toggle-comment ()
14501 "Change the COMMENT state of an entry."
14502 (interactive)
14503 (save-excursion
14504 (org-back-to-heading)
14505 (let (case-fold-search)
14506 (if (looking-at (concat outline-regexp
14507 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14508 (replace-match "" t t nil 1)
14509 (if (looking-at outline-regexp)
14510 (progn
14511 (goto-char (match-end 0))
14512 (insert org-comment-string " ")))))))
14514 (defvar org-last-todo-state-is-todo nil
14515 "This is non-nil when the last TODO state change led to a TODO state.
14516 If the last change removed the TODO tag or switched to DONE, then
14517 this is nil.")
14519 (defvar org-setting-tags nil) ; dynamically skiped
14521 ;; FIXME: better place
14522 (defun org-property-or-variable-value (var &optional inherit)
14523 "Check if there is a property fixing the value of VAR.
14524 If yes, return this value. If not, return the current value of the variable."
14525 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14526 (if (and prop (stringp prop) (string-match "\\S-" prop))
14527 (read prop)
14528 (symbol-value var))))
14530 (defun org-parse-local-options (string var)
14531 "Parse STRING for startup setting relevant for variable VAR."
14532 (let ((rtn (symbol-value var))
14533 e opts)
14534 (save-match-data
14535 (if (or (not string) (not (string-match "\\S-" string)))
14537 (setq opts (delq nil (mapcar (lambda (x)
14538 (setq e (assoc x org-startup-options))
14539 (if (eq (nth 1 e) var) e nil))
14540 (org-split-string string "[ \t]+"))))
14541 (if (not opts)
14543 (setq rtn nil)
14544 (while (setq e (pop opts))
14545 (if (not (nth 3 e))
14546 (setq rtn (nth 2 e))
14547 (if (not (listp rtn)) (setq rtn nil))
14548 (push (nth 2 e) rtn)))
14549 rtn)))))
14551 (defvar org-blocker-hook nil
14552 "Hook for functions that are allowed to block a state change.
14554 Each function gets as its single argument a property list, see
14555 `org-trigger-hook' for more information about this list.
14557 If any of the functions in this hook returns nil, the state change
14558 is blocked.")
14560 (defvar org-trigger-hook nil
14561 "Hook for functions that are triggered by a state change.
14563 Each function gets as its single argument a property list with at least
14564 the following elements:
14566 (:type type-of-change :position pos-at-entry-start
14567 :from old-state :to new-state)
14569 Depending on the type, more properties may be present.
14571 This mechanism is currently implemented for:
14573 TODO state changes
14574 ------------------
14575 :type todo-state-change
14576 :from previous state (keyword as a string), or nil
14577 :to new state (keyword as a string), or nil")
14580 (defun org-todo (&optional arg)
14581 "Change the TODO state of an item.
14582 The state of an item is given by a keyword at the start of the heading,
14583 like
14584 *** TODO Write paper
14585 *** DONE Call mom
14587 The different keywords are specified in the variable `org-todo-keywords'.
14588 By default the available states are \"TODO\" and \"DONE\".
14589 So for this example: when the item starts with TODO, it is changed to DONE.
14590 When it starts with DONE, the DONE is removed. And when neither TODO nor
14591 DONE are present, add TODO at the beginning of the heading.
14593 With C-u prefix arg, use completion to determine the new state.
14594 With numeric prefix arg, switch to that state.
14596 For calling through lisp, arg is also interpreted in the following way:
14597 'none -> empty state
14598 \"\"(empty string) -> switch to empty state
14599 'done -> switch to DONE
14600 'nextset -> switch to the next set of keywords
14601 'previousset -> switch to the previous set of keywords
14602 \"WAITING\" -> switch to the specified keyword, but only if it
14603 really is a member of `org-todo-keywords'."
14604 (interactive "P")
14605 (save-excursion
14606 (catch 'exit
14607 (org-back-to-heading)
14608 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14609 (or (looking-at (concat " +" org-todo-regexp " *"))
14610 (looking-at " *"))
14611 (let* ((match-data (match-data))
14612 (startpos (point-at-bol))
14613 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14614 (org-log-done org-log-done)
14615 (org-log-repeat org-log-repeat)
14616 (org-todo-log-states org-todo-log-states)
14617 (this (match-string 1))
14618 (hl-pos (match-beginning 0))
14619 (head (org-get-todo-sequence-head this))
14620 (ass (assoc head org-todo-kwd-alist))
14621 (interpret (nth 1 ass))
14622 (done-word (nth 3 ass))
14623 (final-done-word (nth 4 ass))
14624 (last-state (or this ""))
14625 (completion-ignore-case t)
14626 (member (member this org-todo-keywords-1))
14627 (tail (cdr member))
14628 (state (cond
14629 ((and org-todo-key-trigger
14630 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14631 (and (not arg) org-use-fast-todo-selection
14632 (not (eq org-use-fast-todo-selection 'prefix)))))
14633 ;; Use fast selection
14634 (org-fast-todo-selection))
14635 ((and (equal arg '(4))
14636 (or (not org-use-fast-todo-selection)
14637 (not org-todo-key-trigger)))
14638 ;; Read a state with completion
14639 (completing-read "State: " (mapcar (lambda(x) (list x))
14640 org-todo-keywords-1)
14641 nil t))
14642 ((eq arg 'right)
14643 (if this
14644 (if tail (car tail) nil)
14645 (car org-todo-keywords-1)))
14646 ((eq arg 'left)
14647 (if (equal member org-todo-keywords-1)
14649 (if this
14650 (nth (- (length org-todo-keywords-1) (length tail) 2)
14651 org-todo-keywords-1)
14652 (org-last org-todo-keywords-1))))
14653 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14654 (setq arg nil))) ; hack to fall back to cycling
14655 (arg
14656 ;; user or caller requests a specific state
14657 (cond
14658 ((equal arg "") nil)
14659 ((eq arg 'none) nil)
14660 ((eq arg 'done) (or done-word (car org-done-keywords)))
14661 ((eq arg 'nextset)
14662 (or (car (cdr (member head org-todo-heads)))
14663 (car org-todo-heads)))
14664 ((eq arg 'previousset)
14665 (let ((org-todo-heads (reverse org-todo-heads)))
14666 (or (car (cdr (member head org-todo-heads)))
14667 (car org-todo-heads))))
14668 ((car (member arg org-todo-keywords-1)))
14669 ((nth (1- (prefix-numeric-value arg))
14670 org-todo-keywords-1))))
14671 ((null member) (or head (car org-todo-keywords-1)))
14672 ((equal this final-done-word) nil) ;; -> make empty
14673 ((null tail) nil) ;; -> first entry
14674 ((eq interpret 'sequence)
14675 (car tail))
14676 ((memq interpret '(type priority))
14677 (if (eq this-command last-command)
14678 (car tail)
14679 (if (> (length tail) 0)
14680 (or done-word (car org-done-keywords))
14681 nil)))
14682 (t nil)))
14683 (next (if state (concat " " state " ") " "))
14684 (change-plist (list :type 'todo-state-change :from this :to state
14685 :position startpos))
14686 dolog now-done-p)
14687 (when org-blocker-hook
14688 (unless (save-excursion
14689 (save-match-data
14690 (run-hook-with-args-until-failure
14691 'org-blocker-hook change-plist)))
14692 (if (interactive-p)
14693 (error "TODO state change from %s to %s blocked" this state)
14694 ;; fail silently
14695 (message "TODO state change from %s to %s blocked" this state)
14696 (throw 'exit nil))))
14697 (store-match-data match-data)
14698 (replace-match next t t)
14699 (unless (pos-visible-in-window-p hl-pos)
14700 (message "TODO state changed to %s" (org-trim next)))
14701 (unless head
14702 (setq head (org-get-todo-sequence-head state)
14703 ass (assoc head org-todo-kwd-alist)
14704 interpret (nth 1 ass)
14705 done-word (nth 3 ass)
14706 final-done-word (nth 4 ass)))
14707 (when (memq arg '(nextset previousset))
14708 (message "Keyword-Set %d/%d: %s"
14709 (- (length org-todo-sets) -1
14710 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14711 (length org-todo-sets)
14712 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14713 (setq org-last-todo-state-is-todo
14714 (not (member state org-done-keywords)))
14715 (setq now-done-p (and (member state org-done-keywords)
14716 (not (member this org-done-keywords))))
14717 (and logging (org-local-logging logging))
14718 (when (and (or org-todo-log-states org-log-done)
14719 (not (memq arg '(nextset previousset))))
14720 ;; we need to look at recording a time and note
14721 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14722 (nth 2 (assoc this org-todo-log-states))))
14723 (when (and state
14724 (member state org-not-done-keywords)
14725 (not (member this org-not-done-keywords)))
14726 ;; This is now a todo state and was not one before
14727 ;; If there was a CLOSED time stamp, get rid of it.
14728 (org-add-planning-info nil nil 'closed))
14729 (when (and now-done-p org-log-done)
14730 ;; It is now done, and it was not done before
14731 (org-add-planning-info 'closed (org-current-time))
14732 (if (and (not dolog) (eq 'note org-log-done))
14733 (org-add-log-maybe 'done state 'findpos 'note)))
14734 (when (and state dolog)
14735 ;; This is a non-nil state, and we need to log it
14736 (org-add-log-maybe 'state state 'findpos dolog)))
14737 ;; Fixup tag positioning
14738 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14739 (run-hooks 'org-after-todo-state-change-hook)
14740 (if (and arg (not (member state org-done-keywords)))
14741 (setq head (org-get-todo-sequence-head state)))
14742 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14743 ;; Do we need to trigger a repeat?
14744 (when now-done-p (org-auto-repeat-maybe state))
14745 ;; Fixup cursor location if close to the keyword
14746 (if (and (outline-on-heading-p)
14747 (not (bolp))
14748 (save-excursion (beginning-of-line 1)
14749 (looking-at org-todo-line-regexp))
14750 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14751 (progn
14752 (goto-char (or (match-end 2) (match-end 1)))
14753 (just-one-space)))
14754 (when org-trigger-hook
14755 (save-excursion
14756 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14758 (defun org-local-logging (value)
14759 "Get logging settings from a property VALUE."
14760 (let* (words w a)
14761 ;; directly set the variables, they are already local.
14762 (setq org-log-done nil
14763 org-log-repeat nil
14764 org-todo-log-states nil)
14765 (setq words (org-split-string value))
14766 (while (setq w (pop words))
14767 (cond
14768 ((setq a (assoc w org-startup-options))
14769 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14770 (set (nth 1 a) (nth 2 a))))
14771 ((setq a (org-extract-log-state-settings w))
14772 (and (member (car a) org-todo-keywords-1)
14773 (push a org-todo-log-states)))))))
14775 (defun org-get-todo-sequence-head (kwd)
14776 "Return the head of the TODO sequence to which KWD belongs.
14777 If KWD is not set, check if there is a text property remembering the
14778 right sequence."
14779 (let (p)
14780 (cond
14781 ((not kwd)
14782 (or (get-text-property (point-at-bol) 'org-todo-head)
14783 (progn
14784 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14785 nil (point-at-eol)))
14786 (get-text-property p 'org-todo-head))))
14787 ((not (member kwd org-todo-keywords-1))
14788 (car org-todo-keywords-1))
14789 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14791 (defun org-fast-todo-selection ()
14792 "Fast TODO keyword selection with single keys.
14793 Returns the new TODO keyword, or nil if no state change should occur."
14794 (let* ((fulltable org-todo-key-alist)
14795 (done-keywords org-done-keywords) ;; needed for the faces.
14796 (maxlen (apply 'max (mapcar
14797 (lambda (x)
14798 (if (stringp (car x)) (string-width (car x)) 0))
14799 fulltable)))
14800 (expert nil)
14801 (fwidth (+ maxlen 3 1 3))
14802 (ncol (/ (- (window-width) 4) fwidth))
14803 tg cnt e c tbl
14804 groups ingroup)
14805 (save-window-excursion
14806 (if expert
14807 (set-buffer (get-buffer-create " *Org todo*"))
14808 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14809 (erase-buffer)
14810 (org-set-local 'org-done-keywords done-keywords)
14811 (setq tbl fulltable cnt 0)
14812 (while (setq e (pop tbl))
14813 (cond
14814 ((equal e '(:startgroup))
14815 (push '() groups) (setq ingroup t)
14816 (when (not (= cnt 0))
14817 (setq cnt 0)
14818 (insert "\n"))
14819 (insert "{ "))
14820 ((equal e '(:endgroup))
14821 (setq ingroup nil cnt 0)
14822 (insert "}\n"))
14824 (setq tg (car e) c (cdr e))
14825 (if ingroup (push tg (car groups)))
14826 (setq tg (org-add-props tg nil 'face
14827 (org-get-todo-face tg)))
14828 (if (and (= cnt 0) (not ingroup)) (insert " "))
14829 (insert "[" c "] " tg (make-string
14830 (- fwidth 4 (length tg)) ?\ ))
14831 (when (= (setq cnt (1+ cnt)) ncol)
14832 (insert "\n")
14833 (if ingroup (insert " "))
14834 (setq cnt 0)))))
14835 (insert "\n")
14836 (goto-char (point-min))
14837 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14838 (fit-window-to-buffer))
14839 (message "[a-z..]:Set [SPC]:clear")
14840 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14841 (cond
14842 ((or (= c ?\C-g)
14843 (and (= c ?q) (not (rassoc c fulltable))))
14844 (setq quit-flag t))
14845 ((= c ?\ ) nil)
14846 ((setq e (rassoc c fulltable) tg (car e))
14848 (t (setq quit-flag t))))))
14850 (defun org-get-repeat ()
14851 "Check if tere is a deadline/schedule with repeater in this entry."
14852 (save-match-data
14853 (save-excursion
14854 (org-back-to-heading t)
14855 (if (re-search-forward
14856 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14857 (match-string 1)))))
14859 (defvar org-last-changed-timestamp)
14860 (defvar org-log-post-message)
14861 (defvar org-log-note-purpose)
14862 (defun org-auto-repeat-maybe (done-word)
14863 "Check if the current headline contains a repeated deadline/schedule.
14864 If yes, set TODO state back to what it was and change the base date
14865 of repeating deadline/scheduled time stamps to new date.
14866 This function is run automatically after each state change to a DONE state."
14867 ;; last-state is dynamically scoped into this function
14868 (let* ((repeat (org-get-repeat))
14869 (aa (assoc last-state org-todo-kwd-alist))
14870 (interpret (nth 1 aa))
14871 (head (nth 2 aa))
14872 (whata '(("d" . day) ("m" . month) ("y" . year)))
14873 (msg "Entry repeats: ")
14874 (org-log-done nil)
14875 (org-todo-log-states nil)
14876 re type n what ts)
14877 (when repeat
14878 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14879 (org-todo (if (eq interpret 'type) last-state head))
14880 (when (and org-log-repeat
14881 (or (not (memq 'org-add-log-note
14882 (default-value 'post-command-hook)))
14883 (eq org-log-note-purpose 'done)))
14884 ;; Make sure a note is taken;
14885 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14886 'findpos org-log-repeat))
14887 (org-back-to-heading t)
14888 (org-add-planning-info nil nil 'closed)
14889 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14890 org-deadline-time-regexp "\\)\\|\\("
14891 org-ts-regexp "\\)"))
14892 (while (re-search-forward
14893 re (save-excursion (outline-next-heading) (point)) t)
14894 (setq type (if (match-end 1) org-scheduled-string
14895 (if (match-end 3) org-deadline-string "Plain:"))
14896 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14897 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14898 (setq n (string-to-number (match-string 1 ts))
14899 what (match-string 2 ts))
14900 (if (equal what "w") (setq n (* n 7) what "d"))
14901 (org-timestamp-change n (cdr (assoc what whata)))
14902 (setq msg (concat msg type org-last-changed-timestamp " "))))
14903 (setq org-log-post-message msg)
14904 (message "%s" msg))))
14906 (defun org-show-todo-tree (arg)
14907 "Make a compact tree which shows all headlines marked with TODO.
14908 The tree will show the lines where the regexp matches, and all higher
14909 headlines above the match.
14910 With a \\[universal-argument] prefix, also show the DONE entries.
14911 With a numeric prefix N, construct a sparse tree for the Nth element
14912 of `org-todo-keywords-1'."
14913 (interactive "P")
14914 (let ((case-fold-search nil)
14915 (kwd-re
14916 (cond ((null arg) org-not-done-regexp)
14917 ((equal arg '(4))
14918 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14919 (mapcar 'list org-todo-keywords-1))))
14920 (concat "\\("
14921 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14922 "\\)\\>")))
14923 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14924 (regexp-quote (nth (1- (prefix-numeric-value arg))
14925 org-todo-keywords-1)))
14926 (t (error "Invalid prefix argument: %s" arg)))))
14927 (message "%d TODO entries found"
14928 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14930 (defun org-deadline (&optional remove)
14931 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14932 With argument REMOVE, remove any deadline from the item."
14933 (interactive "P")
14934 (if remove
14935 (progn
14936 (org-remove-timestamp-with-keyword org-deadline-string)
14937 (message "Item no longer has a deadline."))
14938 (org-add-planning-info 'deadline nil 'closed)))
14940 (defun org-schedule (&optional remove)
14941 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14942 With argument REMOVE, remove any scheduling date from the item."
14943 (interactive "P")
14944 (if remove
14945 (progn
14946 (org-remove-timestamp-with-keyword org-scheduled-string)
14947 (message "Item is no longer scheduled."))
14948 (org-add-planning-info 'scheduled nil 'closed)))
14950 (defun org-remove-timestamp-with-keyword (keyword)
14951 "Remove all time stamps with KEYWORD in the current entry."
14952 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14953 beg)
14954 (save-excursion
14955 (org-back-to-heading t)
14956 (setq beg (point))
14957 (org-end-of-subtree t t)
14958 (while (re-search-backward re beg t)
14959 (replace-match "")
14960 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14961 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14963 (defun org-add-planning-info (what &optional time &rest remove)
14964 "Insert new timestamp with keyword in the line directly after the headline.
14965 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14966 If non is given, the user is prompted for a date.
14967 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14968 be removed."
14969 (interactive)
14970 (let (org-time-was-given org-end-time-was-given)
14971 (when what (setq time (or time (org-read-date nil 'to-time))))
14972 (when (and org-insert-labeled-timestamps-at-point
14973 (member what '(scheduled deadline)))
14974 (insert
14975 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14976 (org-insert-time-stamp time org-time-was-given
14977 nil nil nil (list org-end-time-was-given))
14978 (setq what nil))
14979 (save-excursion
14980 (save-restriction
14981 (let (col list elt ts buffer-invisibility-spec)
14982 (org-back-to-heading t)
14983 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14984 (goto-char (match-end 1))
14985 (setq col (current-column))
14986 (goto-char (match-end 0))
14987 (if (eobp) (insert "\n") (forward-char 1))
14988 (if (and (not (looking-at outline-regexp))
14989 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14990 "[^\r\n]*"))
14991 (not (equal (match-string 1) org-clock-string)))
14992 (narrow-to-region (match-beginning 0) (match-end 0))
14993 (insert-before-markers "\n")
14994 (backward-char 1)
14995 (narrow-to-region (point) (point))
14996 (indent-to-column col))
14997 ;; Check if we have to remove something.
14998 (setq list (cons what remove))
14999 (while list
15000 (setq elt (pop list))
15001 (goto-char (point-min))
15002 (when (or (and (eq elt 'scheduled)
15003 (re-search-forward org-scheduled-time-regexp nil t))
15004 (and (eq elt 'deadline)
15005 (re-search-forward org-deadline-time-regexp nil t))
15006 (and (eq elt 'closed)
15007 (re-search-forward org-closed-time-regexp nil t)))
15008 (replace-match "")
15009 (if (looking-at "--+<[^>]+>") (replace-match ""))
15010 (if (looking-at " +") (replace-match ""))))
15011 (goto-char (point-max))
15012 (when what
15013 (insert
15014 (if (not (equal (char-before) ?\ )) " " "")
15015 (cond ((eq what 'scheduled) org-scheduled-string)
15016 ((eq what 'deadline) org-deadline-string)
15017 ((eq what 'closed) org-closed-string))
15018 " ")
15019 (setq ts (org-insert-time-stamp
15020 time
15021 (or org-time-was-given
15022 (and (eq what 'closed) org-log-done-with-time))
15023 (eq what 'closed)
15024 nil nil (list org-end-time-was-given)))
15025 (end-of-line 1))
15026 (goto-char (point-min))
15027 (widen)
15028 (if (looking-at "[ \t]+\r?\n")
15029 (replace-match ""))
15030 ts)))))
15032 (defvar org-log-note-marker (make-marker))
15033 (defvar org-log-note-purpose nil)
15034 (defvar org-log-note-state nil)
15035 (defvar org-log-note-how nil)
15036 (defvar org-log-note-window-configuration nil)
15037 (defvar org-log-note-return-to (make-marker))
15038 (defvar org-log-post-message nil
15039 "Message to be displayed after a log note has been stored.
15040 The auto-repeater uses this.")
15042 (defun org-add-log-maybe (&optional purpose state findpos how)
15043 "Set up the post command hook to take a note.
15044 If this is about to TODO state change, the new state is expected in STATE.
15045 When FINDPOS is non-nil, find the correct position for the note in
15046 the current entry. If not, assume that it can be inserted at point."
15047 (save-excursion
15048 (when findpos
15049 (org-back-to-heading t)
15050 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15051 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15052 "[^\r\n]*\\)?"))
15053 (goto-char (match-end 0))
15054 (unless org-log-states-order-reversed
15055 (and (= (char-after) ?\n) (forward-char 1))
15056 (org-skip-over-state-notes)
15057 (skip-chars-backward " \t\n\r")))
15058 (move-marker org-log-note-marker (point))
15059 (setq org-log-note-purpose purpose
15060 org-log-note-state state
15061 org-log-note-how how)
15062 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15064 (defun org-skip-over-state-notes ()
15065 "Skip past the list of State notes in an entry."
15066 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15067 (while (looking-at "[ \t]*- State")
15068 (condition-case nil
15069 (org-next-item)
15070 (error (org-end-of-item)))))
15072 (defun org-add-log-note (&optional purpose)
15073 "Pop up a window for taking a note, and add this note later at point."
15074 (remove-hook 'post-command-hook 'org-add-log-note)
15075 (setq org-log-note-window-configuration (current-window-configuration))
15076 (delete-other-windows)
15077 (move-marker org-log-note-return-to (point))
15078 (switch-to-buffer (marker-buffer org-log-note-marker))
15079 (goto-char org-log-note-marker)
15080 (org-switch-to-buffer-other-window "*Org Note*")
15081 (erase-buffer)
15082 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15083 (org-store-log-note)
15084 (let ((org-inhibit-startup t)) (org-mode))
15085 (insert (format "# Insert note for %s.
15086 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15087 (cond
15088 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15089 ((eq org-log-note-purpose 'done) "closed todo item")
15090 ((eq org-log-note-purpose 'state)
15091 (format "state change to \"%s\"" org-log-note-state))
15092 (t (error "This should not happen")))))
15093 (org-set-local 'org-finish-function 'org-store-log-note)))
15095 (defun org-store-log-note ()
15096 "Finish taking a log note, and insert it to where it belongs."
15097 (let ((txt (buffer-string))
15098 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15099 lines ind)
15100 (kill-buffer (current-buffer))
15101 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15102 (setq txt (replace-match "" t t txt)))
15103 (if (string-match "\\s-+\\'" txt)
15104 (setq txt (replace-match "" t t txt)))
15105 (setq lines (org-split-string txt "\n"))
15106 (when (and note (string-match "\\S-" note))
15107 (setq note
15108 (org-replace-escapes
15109 note
15110 (list (cons "%u" (user-login-name))
15111 (cons "%U" user-full-name)
15112 (cons "%t" (format-time-string
15113 (org-time-stamp-format 'long 'inactive)
15114 (current-time)))
15115 (cons "%s" (if org-log-note-state
15116 (concat "\"" org-log-note-state "\"")
15117 "")))))
15118 (if lines (setq note (concat note " \\\\")))
15119 (push note lines))
15120 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15121 (when lines
15122 (save-excursion
15123 (set-buffer (marker-buffer org-log-note-marker))
15124 (save-excursion
15125 (goto-char org-log-note-marker)
15126 (move-marker org-log-note-marker nil)
15127 (end-of-line 1)
15128 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15129 (indent-relative nil)
15130 (insert "- " (pop lines))
15131 (org-indent-line-function)
15132 (beginning-of-line 1)
15133 (looking-at "[ \t]*")
15134 (setq ind (concat (match-string 0) " "))
15135 (end-of-line 1)
15136 (while lines (insert "\n" ind (pop lines)))))))
15137 (set-window-configuration org-log-note-window-configuration)
15138 (with-current-buffer (marker-buffer org-log-note-return-to)
15139 (goto-char org-log-note-return-to))
15140 (move-marker org-log-note-return-to nil)
15141 (and org-log-post-message (message "%s" org-log-post-message)))
15143 ;; FIXME: what else would be useful?
15144 ;; - priority
15145 ;; - date
15147 (defun org-sparse-tree (&optional arg)
15148 "Create a sparse tree, prompt for the details.
15149 This command can create sparse trees. You first need to select the type
15150 of match used to create the tree:
15152 t Show entries with a specific TODO keyword.
15153 T Show entries selected by a tags match.
15154 p Enter a property name and its value (both with completion on existing
15155 names/values) and show entries with that property.
15156 r Show entries matching a regular expression
15157 d Show deadlines due within `org-deadline-warning-days'."
15158 (interactive "P")
15159 (let (ans kwd value)
15160 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15161 (setq ans (read-char-exclusive))
15162 (cond
15163 ((equal ans ?d)
15164 (call-interactively 'org-check-deadlines))
15165 ((equal ans ?b)
15166 (call-interactively 'org-check-before-date))
15167 ((equal ans ?t)
15168 (org-show-todo-tree '(4)))
15169 ((equal ans ?T)
15170 (call-interactively 'org-tags-sparse-tree))
15171 ((member ans '(?p ?P))
15172 (setq kwd (completing-read "Property: "
15173 (mapcar 'list (org-buffer-property-keys))))
15174 (setq value (completing-read "Value: "
15175 (mapcar 'list (org-property-values kwd))))
15176 (unless (string-match "\\`{.*}\\'" value)
15177 (setq value (concat "\"" value "\"")))
15178 (org-tags-sparse-tree arg (concat kwd "=" value)))
15179 ((member ans '(?r ?R ?/))
15180 (call-interactively 'org-occur))
15181 (t (error "No such sparse tree command \"%c\"" ans)))))
15183 (defvar org-occur-highlights nil)
15184 (make-variable-buffer-local 'org-occur-highlights)
15186 (defun org-occur (regexp &optional keep-previous callback)
15187 "Make a compact tree which shows all matches of REGEXP.
15188 The tree will show the lines where the regexp matches, and all higher
15189 headlines above the match. It will also show the heading after the match,
15190 to make sure editing the matching entry is easy.
15191 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15192 call to `org-occur' will be kept, to allow stacking of calls to this
15193 command.
15194 If CALLBACK is non-nil, it is a function which is called to confirm
15195 that the match should indeed be shown."
15196 (interactive "sRegexp: \nP")
15197 (or keep-previous (org-remove-occur-highlights nil nil t))
15198 (let ((cnt 0))
15199 (save-excursion
15200 (goto-char (point-min))
15201 (if (or (not keep-previous) ; do not want to keep
15202 (not org-occur-highlights)) ; no previous matches
15203 ;; hide everything
15204 (org-overview))
15205 (while (re-search-forward regexp nil t)
15206 (when (or (not callback)
15207 (save-match-data (funcall callback)))
15208 (setq cnt (1+ cnt))
15209 (when org-highlight-sparse-tree-matches
15210 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15211 (org-show-context 'occur-tree))))
15212 (when org-remove-highlights-with-change
15213 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15214 nil 'local))
15215 (unless org-sparse-tree-open-archived-trees
15216 (org-hide-archived-subtrees (point-min) (point-max)))
15217 (run-hooks 'org-occur-hook)
15218 (if (interactive-p)
15219 (message "%d match(es) for regexp %s" cnt regexp))
15220 cnt))
15222 (defun org-show-context (&optional key)
15223 "Make sure point and context and visible.
15224 How much context is shown depends upon the variables
15225 `org-show-hierarchy-above', `org-show-following-heading'. and
15226 `org-show-siblings'."
15227 (let ((heading-p (org-on-heading-p t))
15228 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15229 (following-p (org-get-alist-option org-show-following-heading key))
15230 (entry-p (org-get-alist-option org-show-entry-below key))
15231 (siblings-p (org-get-alist-option org-show-siblings key)))
15232 (catch 'exit
15233 ;; Show heading or entry text
15234 (if (and heading-p (not entry-p))
15235 (org-flag-heading nil) ; only show the heading
15236 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15237 (org-show-hidden-entry))) ; show entire entry
15238 (when following-p
15239 ;; Show next sibling, or heading below text
15240 (save-excursion
15241 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15242 (org-flag-heading nil))))
15243 (when siblings-p (org-show-siblings))
15244 (when hierarchy-p
15245 ;; show all higher headings, possibly with siblings
15246 (save-excursion
15247 (while (and (condition-case nil
15248 (progn (org-up-heading-all 1) t)
15249 (error nil))
15250 (not (bobp)))
15251 (org-flag-heading nil)
15252 (when siblings-p (org-show-siblings))))))))
15254 (defun org-reveal (&optional siblings)
15255 "Show current entry, hierarchy above it, and the following headline.
15256 This can be used to show a consistent set of context around locations
15257 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15258 not t for the search context.
15260 With optional argument SIBLINGS, on each level of the hierarchy all
15261 siblings are shown. This repairs the tree structure to what it would
15262 look like when opened with hierarchical calls to `org-cycle'."
15263 (interactive "P")
15264 (let ((org-show-hierarchy-above t)
15265 (org-show-following-heading t)
15266 (org-show-siblings (if siblings t org-show-siblings)))
15267 (org-show-context nil)))
15269 (defun org-highlight-new-match (beg end)
15270 "Highlight from BEG to END and mark the highlight is an occur headline."
15271 (let ((ov (org-make-overlay beg end)))
15272 (org-overlay-put ov 'face 'secondary-selection)
15273 (push ov org-occur-highlights)))
15275 (defun org-remove-occur-highlights (&optional beg end noremove)
15276 "Remove the occur highlights from the buffer.
15277 BEG and END are ignored. If NOREMOVE is nil, remove this function
15278 from the `before-change-functions' in the current buffer."
15279 (interactive)
15280 (unless org-inhibit-highlight-removal
15281 (mapc 'org-delete-overlay org-occur-highlights)
15282 (setq org-occur-highlights nil)
15283 (unless noremove
15284 (remove-hook 'before-change-functions
15285 'org-remove-occur-highlights 'local))))
15287 ;;;; Priorities
15289 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15290 "Regular expression matching the priority indicator.")
15292 (defvar org-remove-priority-next-time nil)
15294 (defun org-priority-up ()
15295 "Increase the priority of the current item."
15296 (interactive)
15297 (org-priority 'up))
15299 (defun org-priority-down ()
15300 "Decrease the priority of the current item."
15301 (interactive)
15302 (org-priority 'down))
15304 (defun org-priority (&optional action)
15305 "Change the priority of an item by ARG.
15306 ACTION can be `set', `up', `down', or a character."
15307 (interactive)
15308 (setq action (or action 'set))
15309 (let (current new news have remove)
15310 (save-excursion
15311 (org-back-to-heading)
15312 (if (looking-at org-priority-regexp)
15313 (setq current (string-to-char (match-string 2))
15314 have t)
15315 (setq current org-default-priority))
15316 (cond
15317 ((or (eq action 'set) (integerp action))
15318 (if (integerp action)
15319 (setq new action)
15320 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15321 (setq new (read-char-exclusive)))
15322 (if (and (= (upcase org-highest-priority) org-highest-priority)
15323 (= (upcase org-lowest-priority) org-lowest-priority))
15324 (setq new (upcase new)))
15325 (cond ((equal new ?\ ) (setq remove t))
15326 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15327 (error "Priority must be between `%c' and `%c'"
15328 org-highest-priority org-lowest-priority))))
15329 ((eq action 'up)
15330 (if (and (not have) (eq last-command this-command))
15331 (setq new org-lowest-priority)
15332 (setq new (if (and org-priority-start-cycle-with-default (not have))
15333 org-default-priority (1- current)))))
15334 ((eq action 'down)
15335 (if (and (not have) (eq last-command this-command))
15336 (setq new org-highest-priority)
15337 (setq new (if (and org-priority-start-cycle-with-default (not have))
15338 org-default-priority (1+ current)))))
15339 (t (error "Invalid action")))
15340 (if (or (< (upcase new) org-highest-priority)
15341 (> (upcase new) org-lowest-priority))
15342 (setq remove t))
15343 (setq news (format "%c" new))
15344 (if have
15345 (if remove
15346 (replace-match "" t t nil 1)
15347 (replace-match news t t nil 2))
15348 (if remove
15349 (error "No priority cookie found in line")
15350 (looking-at org-todo-line-regexp)
15351 (if (match-end 2)
15352 (progn
15353 (goto-char (match-end 2))
15354 (insert " [#" news "]"))
15355 (goto-char (match-beginning 3))
15356 (insert "[#" news "] ")))))
15357 (org-preserve-lc (org-set-tags nil 'align))
15358 (if remove
15359 (message "Priority removed")
15360 (message "Priority of current item set to %s" news))))
15363 (defun org-get-priority (s)
15364 "Find priority cookie and return priority."
15365 (save-match-data
15366 (if (not (string-match org-priority-regexp s))
15367 (* 1000 (- org-lowest-priority org-default-priority))
15368 (* 1000 (- org-lowest-priority
15369 (string-to-char (match-string 2 s)))))))
15371 ;;;; Tags
15373 (defun org-scan-tags (action matcher &optional todo-only)
15374 "Scan headline tags with inheritance and produce output ACTION.
15375 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15376 evaluated, testing if a given set of tags qualifies a headline for
15377 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15378 are included in the output."
15379 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15380 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15381 (org-re
15382 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15383 (props (list 'face nil
15384 'done-face 'org-done
15385 'undone-face nil
15386 'mouse-face 'highlight
15387 'org-not-done-regexp org-not-done-regexp
15388 'org-todo-regexp org-todo-regexp
15389 'keymap org-agenda-keymap
15390 'help-echo
15391 (format "mouse-2 or RET jump to org file %s"
15392 (abbreviate-file-name
15393 (or (buffer-file-name (buffer-base-buffer))
15394 (buffer-name (buffer-base-buffer)))))))
15395 (case-fold-search nil)
15396 lspos
15397 tags tags-list tags-alist (llast 0) rtn level category i txt
15398 todo marker entry priority)
15399 (save-excursion
15400 (goto-char (point-min))
15401 (when (eq action 'sparse-tree)
15402 (org-overview)
15403 (org-remove-occur-highlights))
15404 (while (re-search-forward re nil t)
15405 (catch :skip
15406 (setq todo (if (match-end 1) (match-string 2))
15407 tags (if (match-end 4) (match-string 4)))
15408 (goto-char (setq lspos (1+ (match-beginning 0))))
15409 (setq level (org-reduced-level (funcall outline-level))
15410 category (org-get-category))
15411 (setq i llast llast level)
15412 ;; remove tag lists from same and sublevels
15413 (while (>= i level)
15414 (when (setq entry (assoc i tags-alist))
15415 (setq tags-alist (delete entry tags-alist)))
15416 (setq i (1- i)))
15417 ;; add the nex tags
15418 (when tags
15419 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15420 tags-alist
15421 (cons (cons level tags) tags-alist)))
15422 ;; compile tags for current headline
15423 (setq tags-list
15424 (if org-use-tag-inheritance
15425 (apply 'append (mapcar 'cdr tags-alist))
15426 tags))
15427 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15428 (eval matcher)
15429 (or (not org-agenda-skip-archived-trees)
15430 (not (member org-archive-tag tags-list))))
15431 (and (eq action 'agenda) (org-agenda-skip))
15432 ;; list this headline
15434 (if (eq action 'sparse-tree)
15435 (progn
15436 (and org-highlight-sparse-tree-matches
15437 (org-get-heading) (match-end 0)
15438 (org-highlight-new-match
15439 (match-beginning 0) (match-beginning 1)))
15440 (org-show-context 'tags-tree))
15441 (setq txt (org-format-agenda-item
15443 (concat
15444 (if org-tags-match-list-sublevels
15445 (make-string (1- level) ?.) "")
15446 (org-get-heading))
15447 category tags-list)
15448 priority (org-get-priority txt))
15449 (goto-char lspos)
15450 (setq marker (org-agenda-new-marker))
15451 (org-add-props txt props
15452 'org-marker marker 'org-hd-marker marker 'org-category category
15453 'priority priority 'type "tagsmatch")
15454 (push txt rtn))
15455 ;; if we are to skip sublevels, jump to end of subtree
15456 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15457 (when (and (eq action 'sparse-tree)
15458 (not org-sparse-tree-open-archived-trees))
15459 (org-hide-archived-subtrees (point-min) (point-max)))
15460 (nreverse rtn)))
15462 (defvar todo-only) ;; dynamically scoped
15464 (defun org-tags-sparse-tree (&optional todo-only match)
15465 "Create a sparse tree according to tags string MATCH.
15466 MATCH can contain positive and negative selection of tags, like
15467 \"+WORK+URGENT-WITHBOSS\".
15468 If optional argument TODO_ONLY is non-nil, only select lines that are
15469 also TODO lines."
15470 (interactive "P")
15471 (org-prepare-agenda-buffers (list (current-buffer)))
15472 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15474 (defvar org-cached-props nil)
15475 (defun org-cached-entry-get (pom property)
15476 (if (or (eq t org-use-property-inheritance)
15477 (member property org-use-property-inheritance))
15478 ;; Caching is not possible, check it directly
15479 (org-entry-get pom property 'inherit)
15480 ;; Get all properties, so that we can do complicated checks easily
15481 (cdr (assoc property (or org-cached-props
15482 (setq org-cached-props
15483 (org-entry-properties pom)))))))
15485 (defun org-global-tags-completion-table (&optional files)
15486 "Return the list of all tags in all agenda buffer/files."
15487 (save-excursion
15488 (org-uniquify
15489 (delq nil
15490 (apply 'append
15491 (mapcar
15492 (lambda (file)
15493 (set-buffer (find-file-noselect file))
15494 (append (org-get-buffer-tags)
15495 (mapcar (lambda (x) (if (stringp (car-safe x))
15496 (list (car-safe x)) nil))
15497 org-tag-alist)))
15498 (if (and files (car files))
15499 files
15500 (org-agenda-files))))))))
15502 (defun org-make-tags-matcher (match)
15503 "Create the TAGS//TODO matcher form for the selection string MATCH."
15504 ;; todo-only is scoped dynamically into this function, and the function
15505 ;; may change it it the matcher asksk for it.
15506 (unless match
15507 ;; Get a new match request, with completion
15508 (let ((org-last-tags-completion-table
15509 (org-global-tags-completion-table)))
15510 (setq match (completing-read
15511 "Match: " 'org-tags-completion-function nil nil nil
15512 'org-tags-history))))
15514 ;; Parse the string and create a lisp form
15515 (let ((match0 match)
15516 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15517 minus tag mm
15518 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15519 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15520 (if (string-match "/+" match)
15521 ;; match contains also a todo-matching request
15522 (progn
15523 (setq tagsmatch (substring match 0 (match-beginning 0))
15524 todomatch (substring match (match-end 0)))
15525 (if (string-match "^!" todomatch)
15526 (setq todo-only t todomatch (substring todomatch 1)))
15527 (if (string-match "^\\s-*$" todomatch)
15528 (setq todomatch nil)))
15529 ;; only matching tags
15530 (setq tagsmatch match todomatch nil))
15532 ;; Make the tags matcher
15533 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15534 (setq tagsmatcher t)
15535 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15536 (while (setq term (pop orterms))
15537 (while (and (equal (substring term -1) "\\") orterms)
15538 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15539 (while (string-match re term)
15540 (setq minus (and (match-end 1)
15541 (equal (match-string 1 term) "-"))
15542 tag (match-string 2 term)
15543 re-p (equal (string-to-char tag) ?{)
15544 level-p (match-end 3)
15545 prop-p (match-end 4)
15546 mm (cond
15547 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15548 (level-p `(= level ,(string-to-number
15549 (match-string 3 term))))
15550 (prop-p
15551 (setq pn (match-string 4 term)
15552 pv (match-string 5 term)
15553 cat-p (equal pn "CATEGORY")
15554 re-p (equal (string-to-char pv) ?{)
15555 pv (substring pv 1 -1))
15556 (if (equal pn "CATEGORY")
15557 (setq gv '(get-text-property (point) 'org-category))
15558 (setq gv `(org-cached-entry-get nil ,pn)))
15559 (if re-p
15560 `(string-match ,pv (or ,gv ""))
15561 `(equal ,pv (or ,gv ""))))
15562 (t `(member ,(downcase tag) tags-list)))
15563 mm (if minus (list 'not mm) mm)
15564 term (substring term (match-end 0)))
15565 (push mm tagsmatcher))
15566 (push (if (> (length tagsmatcher) 1)
15567 (cons 'and tagsmatcher)
15568 (car tagsmatcher))
15569 orlist)
15570 (setq tagsmatcher nil))
15571 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15572 (setq tagsmatcher
15573 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15575 ;; Make the todo matcher
15576 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15577 (setq todomatcher t)
15578 (setq orterms (org-split-string todomatch "|") orlist nil)
15579 (while (setq term (pop orterms))
15580 (while (string-match re term)
15581 (setq minus (and (match-end 1)
15582 (equal (match-string 1 term) "-"))
15583 kwd (match-string 2 term)
15584 re-p (equal (string-to-char kwd) ?{)
15585 term (substring term (match-end 0))
15586 mm (if re-p
15587 `(string-match ,(substring kwd 1 -1) todo)
15588 (list 'equal 'todo kwd))
15589 mm (if minus (list 'not mm) mm))
15590 (push mm todomatcher))
15591 (push (if (> (length todomatcher) 1)
15592 (cons 'and todomatcher)
15593 (car todomatcher))
15594 orlist)
15595 (setq todomatcher nil))
15596 (setq todomatcher (if (> (length orlist) 1)
15597 (cons 'or orlist) (car orlist))))
15599 ;; Return the string and lisp forms of the matcher
15600 (setq matcher (if todomatcher
15601 (list 'and tagsmatcher todomatcher)
15602 tagsmatcher))
15603 (cons match0 matcher)))
15605 (defun org-match-any-p (re list)
15606 "Does re match any element of list?"
15607 (setq list (mapcar (lambda (x) (string-match re x)) list))
15608 (delq nil list))
15610 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15611 (defvar org-tags-overlay (org-make-overlay 1 1))
15612 (org-detach-overlay org-tags-overlay)
15614 (defun org-align-tags-here (to-col)
15615 ;; Assumes that this is a headline
15616 (let ((pos (point)) (col (current-column)) tags)
15617 (beginning-of-line 1)
15618 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15619 (< pos (match-beginning 2)))
15620 (progn
15621 (setq tags (match-string 2))
15622 (goto-char (match-beginning 1))
15623 (insert " ")
15624 (delete-region (point) (1+ (match-end 0)))
15625 (backward-char 1)
15626 (move-to-column
15627 (max (1+ (current-column))
15628 (1+ col)
15629 (if (> to-col 0)
15630 to-col
15631 (- (abs to-col) (length tags))))
15633 (insert tags)
15634 (move-to-column (min (current-column) col) t))
15635 (goto-char pos))))
15637 (defun org-set-tags (&optional arg just-align)
15638 "Set the tags for the current headline.
15639 With prefix ARG, realign all tags in headings in the current buffer."
15640 (interactive "P")
15641 (let* ((re (concat "^" outline-regexp))
15642 (current (org-get-tags-string))
15643 (col (current-column))
15644 (org-setting-tags t)
15645 table current-tags inherited-tags ; computed below when needed
15646 tags p0 c0 c1 rpl)
15647 (if arg
15648 (save-excursion
15649 (goto-char (point-min))
15650 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15651 (while (re-search-forward re nil t)
15652 (org-set-tags nil t)
15653 (end-of-line 1)))
15654 (message "All tags realigned to column %d" org-tags-column))
15655 (if just-align
15656 (setq tags current)
15657 ;; Get a new set of tags from the user
15658 (save-excursion
15659 (setq table (or org-tag-alist (org-get-buffer-tags))
15660 org-last-tags-completion-table table
15661 current-tags (org-split-string current ":")
15662 inherited-tags (nreverse
15663 (nthcdr (length current-tags)
15664 (nreverse (org-get-tags-at))))
15665 tags
15666 (if (or (eq t org-use-fast-tag-selection)
15667 (and org-use-fast-tag-selection
15668 (delq nil (mapcar 'cdr table))))
15669 (org-fast-tag-selection
15670 current-tags inherited-tags table
15671 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15672 (let ((org-add-colon-after-tag-completion t))
15673 (org-trim
15674 (org-without-partial-completion
15675 (completing-read "Tags: " 'org-tags-completion-function
15676 nil nil current 'org-tags-history)))))))
15677 (while (string-match "[-+&]+" tags)
15678 ;; No boolean logic, just a list
15679 (setq tags (replace-match ":" t t tags))))
15681 (if (string-match "\\`[\t ]*\\'" tags)
15682 (setq tags "")
15683 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15684 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15686 ;; Insert new tags at the correct column
15687 (beginning-of-line 1)
15688 (cond
15689 ((and (equal current "") (equal tags "")))
15690 ((re-search-forward
15691 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15692 (point-at-eol) t)
15693 (if (equal tags "")
15694 (setq rpl "")
15695 (goto-char (match-beginning 0))
15696 (setq c0 (current-column) p0 (point)
15697 c1 (max (1+ c0) (if (> org-tags-column 0)
15698 org-tags-column
15699 (- (- org-tags-column) (length tags))))
15700 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15701 (replace-match rpl t t)
15702 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15703 tags)
15704 (t (error "Tags alignment failed")))
15705 (move-to-column col)
15706 (unless just-align
15707 (run-hooks 'org-after-tags-change-hook)))))
15709 (defun org-change-tag-in-region (beg end tag off)
15710 "Add or remove TAG for each entry in the region.
15711 This works in the agenda, and also in an org-mode buffer."
15712 (interactive
15713 (list (region-beginning) (region-end)
15714 (let ((org-last-tags-completion-table
15715 (if (org-mode-p)
15716 (org-get-buffer-tags)
15717 (org-global-tags-completion-table))))
15718 (completing-read
15719 "Tag: " 'org-tags-completion-function nil nil nil
15720 'org-tags-history))
15721 (progn
15722 (message "[s]et or [r]emove? ")
15723 (equal (read-char-exclusive) ?r))))
15724 (if (fboundp 'deactivate-mark) (deactivate-mark))
15725 (let ((agendap (equal major-mode 'org-agenda-mode))
15726 l1 l2 m buf pos newhead (cnt 0))
15727 (goto-char end)
15728 (setq l2 (1- (org-current-line)))
15729 (goto-char beg)
15730 (setq l1 (org-current-line))
15731 (loop for l from l1 to l2 do
15732 (goto-line l)
15733 (setq m (get-text-property (point) 'org-hd-marker))
15734 (when (or (and (org-mode-p) (org-on-heading-p))
15735 (and agendap m))
15736 (setq buf (if agendap (marker-buffer m) (current-buffer))
15737 pos (if agendap m (point)))
15738 (with-current-buffer buf
15739 (save-excursion
15740 (save-restriction
15741 (goto-char pos)
15742 (setq cnt (1+ cnt))
15743 (org-toggle-tag tag (if off 'off 'on))
15744 (setq newhead (org-get-heading)))))
15745 (and agendap (org-agenda-change-all-lines newhead m))))
15746 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15748 (defun org-tags-completion-function (string predicate &optional flag)
15749 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15750 (confirm (lambda (x) (stringp (car x)))))
15751 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15752 (setq s1 (match-string 1 string)
15753 s2 (match-string 2 string))
15754 (setq s1 "" s2 string))
15755 (cond
15756 ((eq flag nil)
15757 ;; try completion
15758 (setq rtn (try-completion s2 ctable confirm))
15759 (if (stringp rtn)
15760 (setq rtn
15761 (concat s1 s2 (substring rtn (length s2))
15762 (if (and org-add-colon-after-tag-completion
15763 (assoc rtn ctable))
15764 ":" ""))))
15765 rtn)
15766 ((eq flag t)
15767 ;; all-completions
15768 (all-completions s2 ctable confirm)
15770 ((eq flag 'lambda)
15771 ;; exact match?
15772 (assoc s2 ctable)))
15775 (defun org-fast-tag-insert (kwd tags face &optional end)
15776 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15777 (insert (format "%-12s" (concat kwd ":"))
15778 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15779 (or end "")))
15781 (defun org-fast-tag-show-exit (flag)
15782 (save-excursion
15783 (goto-line 3)
15784 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15785 (replace-match ""))
15786 (when flag
15787 (end-of-line 1)
15788 (move-to-column (- (window-width) 19) t)
15789 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15791 (defun org-set-current-tags-overlay (current prefix)
15792 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15793 (if (featurep 'xemacs)
15794 (org-overlay-display org-tags-overlay (concat prefix s)
15795 'secondary-selection)
15796 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15797 (org-overlay-display org-tags-overlay (concat prefix s)))))
15799 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15800 "Fast tag selection with single keys.
15801 CURRENT is the current list of tags in the headline, INHERITED is the
15802 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15803 possibly with grouping information. TODO-TABLE is a similar table with
15804 TODO keywords, should these have keys assigned to them.
15805 If the keys are nil, a-z are automatically assigned.
15806 Returns the new tags string, or nil to not change the current settings."
15807 (let* ((fulltable (append table todo-table))
15808 (maxlen (apply 'max (mapcar
15809 (lambda (x)
15810 (if (stringp (car x)) (string-width (car x)) 0))
15811 fulltable)))
15812 (buf (current-buffer))
15813 (expert (eq org-fast-tag-selection-single-key 'expert))
15814 (buffer-tags nil)
15815 (fwidth (+ maxlen 3 1 3))
15816 (ncol (/ (- (window-width) 4) fwidth))
15817 (i-face 'org-done)
15818 (c-face 'org-todo)
15819 tg cnt e c char c1 c2 ntable tbl rtn
15820 ov-start ov-end ov-prefix
15821 (exit-after-next org-fast-tag-selection-single-key)
15822 (done-keywords org-done-keywords)
15823 groups ingroup)
15824 (save-excursion
15825 (beginning-of-line 1)
15826 (if (looking-at
15827 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15828 (setq ov-start (match-beginning 1)
15829 ov-end (match-end 1)
15830 ov-prefix "")
15831 (setq ov-start (1- (point-at-eol))
15832 ov-end (1+ ov-start))
15833 (skip-chars-forward "^\n\r")
15834 (setq ov-prefix
15835 (concat
15836 (buffer-substring (1- (point)) (point))
15837 (if (> (current-column) org-tags-column)
15839 (make-string (- org-tags-column (current-column)) ?\ ))))))
15840 (org-move-overlay org-tags-overlay ov-start ov-end)
15841 (save-window-excursion
15842 (if expert
15843 (set-buffer (get-buffer-create " *Org tags*"))
15844 (delete-other-windows)
15845 (split-window-vertically)
15846 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15847 (erase-buffer)
15848 (org-set-local 'org-done-keywords done-keywords)
15849 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15850 (org-fast-tag-insert "Current" current c-face "\n\n")
15851 (org-fast-tag-show-exit exit-after-next)
15852 (org-set-current-tags-overlay current ov-prefix)
15853 (setq tbl fulltable char ?a cnt 0)
15854 (while (setq e (pop tbl))
15855 (cond
15856 ((equal e '(:startgroup))
15857 (push '() groups) (setq ingroup t)
15858 (when (not (= cnt 0))
15859 (setq cnt 0)
15860 (insert "\n"))
15861 (insert "{ "))
15862 ((equal e '(:endgroup))
15863 (setq ingroup nil cnt 0)
15864 (insert "}\n"))
15866 (setq tg (car e) c2 nil)
15867 (if (cdr e)
15868 (setq c (cdr e))
15869 ;; automatically assign a character.
15870 (setq c1 (string-to-char
15871 (downcase (substring
15872 tg (if (= (string-to-char tg) ?@) 1 0)))))
15873 (if (or (rassoc c1 ntable) (rassoc c1 table))
15874 (while (or (rassoc char ntable) (rassoc char table))
15875 (setq char (1+ char)))
15876 (setq c2 c1))
15877 (setq c (or c2 char)))
15878 (if ingroup (push tg (car groups)))
15879 (setq tg (org-add-props tg nil 'face
15880 (cond
15881 ((not (assoc tg table))
15882 (org-get-todo-face tg))
15883 ((member tg current) c-face)
15884 ((member tg inherited) i-face)
15885 (t nil))))
15886 (if (and (= cnt 0) (not ingroup)) (insert " "))
15887 (insert "[" c "] " tg (make-string
15888 (- fwidth 4 (length tg)) ?\ ))
15889 (push (cons tg c) ntable)
15890 (when (= (setq cnt (1+ cnt)) ncol)
15891 (insert "\n")
15892 (if ingroup (insert " "))
15893 (setq cnt 0)))))
15894 (setq ntable (nreverse ntable))
15895 (insert "\n")
15896 (goto-char (point-min))
15897 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15898 (fit-window-to-buffer))
15899 (setq rtn
15900 (catch 'exit
15901 (while t
15902 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15903 (if groups " [!] no groups" " [!]groups")
15904 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15905 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15906 (cond
15907 ((= c ?\r) (throw 'exit t))
15908 ((= c ?!)
15909 (setq groups (not groups))
15910 (goto-char (point-min))
15911 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15912 ((= c ?\C-c)
15913 (if (not expert)
15914 (org-fast-tag-show-exit
15915 (setq exit-after-next (not exit-after-next)))
15916 (setq expert nil)
15917 (delete-other-windows)
15918 (split-window-vertically)
15919 (org-switch-to-buffer-other-window " *Org tags*")
15920 (and (fboundp 'fit-window-to-buffer)
15921 (fit-window-to-buffer))))
15922 ((or (= c ?\C-g)
15923 (and (= c ?q) (not (rassoc c ntable))))
15924 (org-detach-overlay org-tags-overlay)
15925 (setq quit-flag t))
15926 ((= c ?\ )
15927 (setq current nil)
15928 (if exit-after-next (setq exit-after-next 'now)))
15929 ((= c ?\t)
15930 (condition-case nil
15931 (setq tg (completing-read
15932 "Tag: "
15933 (or buffer-tags
15934 (with-current-buffer buf
15935 (org-get-buffer-tags)))))
15936 (quit (setq tg "")))
15937 (when (string-match "\\S-" tg)
15938 (add-to-list 'buffer-tags (list tg))
15939 (if (member tg current)
15940 (setq current (delete tg current))
15941 (push tg current)))
15942 (if exit-after-next (setq exit-after-next 'now)))
15943 ((setq e (rassoc c todo-table) tg (car e))
15944 (with-current-buffer buf
15945 (save-excursion (org-todo tg)))
15946 (if exit-after-next (setq exit-after-next 'now)))
15947 ((setq e (rassoc c ntable) tg (car e))
15948 (if (member tg current)
15949 (setq current (delete tg current))
15950 (loop for g in groups do
15951 (if (member tg g)
15952 (mapc (lambda (x)
15953 (setq current (delete x current)))
15954 g)))
15955 (push tg current))
15956 (if exit-after-next (setq exit-after-next 'now))))
15958 ;; Create a sorted list
15959 (setq current
15960 (sort current
15961 (lambda (a b)
15962 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15963 (if (eq exit-after-next 'now) (throw 'exit t))
15964 (goto-char (point-min))
15965 (beginning-of-line 2)
15966 (delete-region (point) (point-at-eol))
15967 (org-fast-tag-insert "Current" current c-face)
15968 (org-set-current-tags-overlay current ov-prefix)
15969 (while (re-search-forward
15970 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15971 (setq tg (match-string 1))
15972 (add-text-properties
15973 (match-beginning 1) (match-end 1)
15974 (list 'face
15975 (cond
15976 ((member tg current) c-face)
15977 ((member tg inherited) i-face)
15978 (t (get-text-property (match-beginning 1) 'face))))))
15979 (goto-char (point-min)))))
15980 (org-detach-overlay org-tags-overlay)
15981 (if rtn
15982 (mapconcat 'identity current ":")
15983 nil))))
15985 (defun org-get-tags-string ()
15986 "Get the TAGS string in the current headline."
15987 (unless (org-on-heading-p t)
15988 (error "Not on a heading"))
15989 (save-excursion
15990 (beginning-of-line 1)
15991 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15992 (org-match-string-no-properties 1)
15993 "")))
15995 (defun org-get-tags ()
15996 "Get the list of tags specified in the current headline."
15997 (org-split-string (org-get-tags-string) ":"))
15999 (defun org-get-buffer-tags ()
16000 "Get a table of all tags used in the buffer, for completion."
16001 (let (tags)
16002 (save-excursion
16003 (goto-char (point-min))
16004 (while (re-search-forward
16005 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16006 (when (equal (char-after (point-at-bol 0)) ?*)
16007 (mapc (lambda (x) (add-to-list 'tags x))
16008 (org-split-string (org-match-string-no-properties 1) ":")))))
16009 (mapcar 'list tags)))
16012 ;;;; Properties
16014 ;;; Setting and retrieving properties
16016 (defconst org-special-properties
16017 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16018 "TIMESTAMP" "TIMESTAMP_IA")
16019 "The special properties valid in Org-mode.
16021 These are properties that are not defined in the property drawer,
16022 but in some other way.")
16024 (defconst org-default-properties
16025 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16026 "LOCATION" "LOGGING" "COLUMNS")
16027 "Some properties that are used by Org-mode for various purposes.
16028 Being in this list makes sure that they are offered for completion.")
16030 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16031 "Regular expression matching the first line of a property drawer.")
16033 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16034 "Regular expression matching the first line of a property drawer.")
16036 (defun org-property-action ()
16037 "Do an action on properties."
16038 (interactive)
16039 (let (c)
16040 (org-at-property-p)
16041 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16042 (setq c (read-char-exclusive))
16043 (cond
16044 ((equal c ?s)
16045 (call-interactively 'org-set-property))
16046 ((equal c ?d)
16047 (call-interactively 'org-delete-property))
16048 ((equal c ?D)
16049 (call-interactively 'org-delete-property-globally))
16050 ((equal c ?c)
16051 (call-interactively 'org-compute-property-at-point))
16052 (t (error "No such property action %c" c)))))
16054 (defun org-at-property-p ()
16055 "Is the cursor in a property line?"
16056 ;; FIXME: Does not check if we are actually in the drawer.
16057 ;; FIXME: also returns true on any drawers.....
16058 ;; This is used by C-c C-c for property action.
16059 (save-excursion
16060 (beginning-of-line 1)
16061 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16063 (defmacro org-with-point-at (pom &rest body)
16064 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16065 (declare (indent 1) (debug t))
16066 `(save-excursion
16067 (if (markerp pom) (set-buffer (marker-buffer pom)))
16068 (save-excursion
16069 (goto-char (or pom (point)))
16070 ,@body)))
16072 (defun org-get-property-block (&optional beg end force)
16073 "Return the (beg . end) range of the body of the property drawer.
16074 BEG and END can be beginning and end of subtree, if not given
16075 they will be found.
16076 If the drawer does not exist and FORCE is non-nil, create the drawer."
16077 (catch 'exit
16078 (save-excursion
16079 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16080 (end (or end (progn (outline-next-heading) (point)))))
16081 (goto-char beg)
16082 (if (re-search-forward org-property-start-re end t)
16083 (setq beg (1+ (match-end 0)))
16084 (if force
16085 (save-excursion
16086 (org-insert-property-drawer)
16087 (setq end (progn (outline-next-heading) (point))))
16088 (throw 'exit nil))
16089 (goto-char beg)
16090 (if (re-search-forward org-property-start-re end t)
16091 (setq beg (1+ (match-end 0)))))
16092 (if (re-search-forward org-property-end-re end t)
16093 (setq end (match-beginning 0))
16094 (or force (throw 'exit nil))
16095 (goto-char beg)
16096 (setq end beg)
16097 (org-indent-line-function)
16098 (insert ":END:\n"))
16099 (cons beg end)))))
16101 (defun org-entry-properties (&optional pom which)
16102 "Get all properties of the entry at point-or-marker POM.
16103 This includes the TODO keyword, the tags, time strings for deadline,
16104 scheduled, and clocking, and any additional properties defined in the
16105 entry. The return value is an alist, keys may occur multiple times
16106 if the property key was used several times.
16107 POM may also be nil, in which case the current entry is used.
16108 If WHICH is nil or `all', get all properties. If WHICH is
16109 `special' or `standard', only get that subclass."
16110 (setq which (or which 'all))
16111 (org-with-point-at pom
16112 (let ((clockstr (substring org-clock-string 0 -1))
16113 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16114 beg end range props sum-props key value string clocksum)
16115 (save-excursion
16116 (when (condition-case nil (org-back-to-heading t) (error nil))
16117 (setq beg (point))
16118 (setq sum-props (get-text-property (point) 'org-summaries))
16119 (setq clocksum (get-text-property (point) :org-clock-minutes))
16120 (outline-next-heading)
16121 (setq end (point))
16122 (when (memq which '(all special))
16123 ;; Get the special properties, like TODO and tags
16124 (goto-char beg)
16125 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16126 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16127 (when (looking-at org-priority-regexp)
16128 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16129 (when (and (setq value (org-get-tags-string))
16130 (string-match "\\S-" value))
16131 (push (cons "TAGS" value) props))
16132 (when (setq value (org-get-tags-at))
16133 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16134 props))
16135 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16136 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16137 string (if (equal key clockstr)
16138 (org-no-properties
16139 (org-trim
16140 (buffer-substring
16141 (match-beginning 3) (goto-char (point-at-eol)))))
16142 (substring (org-match-string-no-properties 3) 1 -1)))
16143 (unless key
16144 (if (= (char-after (match-beginning 3)) ?\[)
16145 (setq key "TIMESTAMP_IA")
16146 (setq key "TIMESTAMP")))
16147 (when (or (equal key clockstr) (not (assoc key props)))
16148 (push (cons key string) props)))
16152 (when (memq which '(all standard))
16153 ;; Get the standard properties, like :PORP: ...
16154 (setq range (org-get-property-block beg end))
16155 (when range
16156 (goto-char (car range))
16157 (while (re-search-forward
16158 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16159 (cdr range) t)
16160 (setq key (org-match-string-no-properties 1)
16161 value (org-trim (or (org-match-string-no-properties 2) "")))
16162 (unless (member key excluded)
16163 (push (cons key (or value "")) props)))))
16164 (if clocksum
16165 (push (cons "CLOCKSUM"
16166 (org-column-number-to-string (/ (float clocksum) 60.)
16167 'add_times))
16168 props))
16169 (append sum-props (nreverse props)))))))
16171 (defun org-entry-get (pom property &optional inherit)
16172 "Get value of PROPERTY for entry at point-or-marker POM.
16173 If INHERIT is non-nil and the entry does not have the property,
16174 then also check higher levels of the hierarchy.
16175 If the property is present but empty, the return value is the empty string.
16176 If the property is not present at all, nil is returned."
16177 (org-with-point-at pom
16178 (if inherit
16179 (org-entry-get-with-inheritance property)
16180 (if (member property org-special-properties)
16181 ;; We need a special property. Use brute force, get all properties.
16182 (cdr (assoc property (org-entry-properties nil 'special)))
16183 (let ((range (org-get-property-block)))
16184 (if (and range
16185 (goto-char (car range))
16186 (re-search-forward
16187 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16188 (cdr range) t))
16189 ;; Found the property, return it.
16190 (if (match-end 1)
16191 (org-match-string-no-properties 1)
16192 "")))))))
16194 (defun org-entry-delete (pom property)
16195 "Delete the property PROPERTY from entry at point-or-marker POM."
16196 (org-with-point-at pom
16197 (if (member property org-special-properties)
16198 nil ; cannot delete these properties.
16199 (let ((range (org-get-property-block)))
16200 (if (and range
16201 (goto-char (car range))
16202 (re-search-forward
16203 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16204 (cdr range) t))
16205 (progn
16206 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16208 nil)))))
16210 ;; Multi-values properties are properties that contain multiple values
16211 ;; These values are assumed to be single words, separated by whitespace.
16212 (defun org-entry-add-to-multivalued-property (pom property value)
16213 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16214 (let* ((old (org-entry-get pom property))
16215 (values (and old (org-split-string old "[ \t]"))))
16216 (unless (member value values)
16217 (setq values (cons value values))
16218 (org-entry-put pom property
16219 (mapconcat 'identity values " ")))))
16221 (defun org-entry-remove-from-multivalued-property (pom property value)
16222 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16223 (let* ((old (org-entry-get pom property))
16224 (values (and old (org-split-string old "[ \t]"))))
16225 (when (member value values)
16226 (setq values (delete value values))
16227 (org-entry-put pom property
16228 (mapconcat 'identity values " ")))))
16230 (defun org-entry-member-in-multivalued-property (pom property value)
16231 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16232 (let* ((old (org-entry-get pom property))
16233 (values (and old (org-split-string old "[ \t]"))))
16234 (member value values)))
16236 (defvar org-entry-property-inherited-from (make-marker))
16238 (defun org-entry-get-with-inheritance (property)
16239 "Get entry property, and search higher levels if not present."
16240 (let (tmp)
16241 (save-excursion
16242 (save-restriction
16243 (widen)
16244 (catch 'ex
16245 (while t
16246 (when (setq tmp (org-entry-get nil property))
16247 (org-back-to-heading t)
16248 (move-marker org-entry-property-inherited-from (point))
16249 (throw 'ex tmp))
16250 (or (org-up-heading-safe) (throw 'ex nil)))))
16251 (or tmp (cdr (assoc property org-local-properties))
16252 (cdr (assoc property org-global-properties))))))
16254 (defun org-entry-put (pom property value)
16255 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16256 (org-with-point-at pom
16257 (org-back-to-heading t)
16258 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16259 range)
16260 (cond
16261 ((equal property "TODO")
16262 (when (and (stringp value) (string-match "\\S-" value)
16263 (not (member value org-todo-keywords-1)))
16264 (error "\"%s\" is not a valid TODO state" value))
16265 (if (or (not value)
16266 (not (string-match "\\S-" value)))
16267 (setq value 'none))
16268 (org-todo value)
16269 (org-set-tags nil 'align))
16270 ((equal property "PRIORITY")
16271 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16272 (string-to-char value) ?\ ))
16273 (org-set-tags nil 'align))
16274 ((equal property "SCHEDULED")
16275 (if (re-search-forward org-scheduled-time-regexp end t)
16276 (cond
16277 ((eq value 'earlier) (org-timestamp-change -1 'day))
16278 ((eq value 'later) (org-timestamp-change 1 'day))
16279 (t (call-interactively 'org-schedule)))
16280 (call-interactively 'org-schedule)))
16281 ((equal property "DEADLINE")
16282 (if (re-search-forward org-deadline-time-regexp end t)
16283 (cond
16284 ((eq value 'earlier) (org-timestamp-change -1 'day))
16285 ((eq value 'later) (org-timestamp-change 1 'day))
16286 (t (call-interactively 'org-deadline)))
16287 (call-interactively 'org-deadline)))
16288 ((member property org-special-properties)
16289 (error "The %s property can not yet be set with `org-entry-put'"
16290 property))
16291 (t ; a non-special property
16292 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16293 (setq range (org-get-property-block beg end 'force))
16294 (goto-char (car range))
16295 (if (re-search-forward
16296 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16297 (progn
16298 (delete-region (match-beginning 1) (match-end 1))
16299 (goto-char (match-beginning 1)))
16300 (goto-char (cdr range))
16301 (insert "\n")
16302 (backward-char 1)
16303 (org-indent-line-function)
16304 (insert ":" property ":"))
16305 (and value (insert " " value))
16306 (org-indent-line-function)))))))
16308 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16309 "Get all property keys in the current buffer.
16310 With INCLUDE-SPECIALS, also list the special properties that relect things
16311 like tags and TODO state.
16312 With INCLUDE-DEFAULTS, also include properties that has special meaning
16313 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16314 With INCLUDE-COLUMNS, also include property names given in COLUMN
16315 formats in the current buffer."
16316 (let (rtn range cfmt cols s p)
16317 (save-excursion
16318 (save-restriction
16319 (widen)
16320 (goto-char (point-min))
16321 (while (re-search-forward org-property-start-re nil t)
16322 (setq range (org-get-property-block))
16323 (goto-char (car range))
16324 (while (re-search-forward
16325 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16326 (cdr range) t)
16327 (add-to-list 'rtn (org-match-string-no-properties 1)))
16328 (outline-next-heading))))
16330 (when include-specials
16331 (setq rtn (append org-special-properties rtn)))
16333 (when include-defaults
16334 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16336 (when include-columns
16337 (save-excursion
16338 (save-restriction
16339 (widen)
16340 (goto-char (point-min))
16341 (while (re-search-forward
16342 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16343 nil t)
16344 (setq cfmt (match-string 2) s 0)
16345 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16346 cfmt s)
16347 (setq s (match-end 0)
16348 p (match-string 1 cfmt))
16349 (unless (or (equal p "ITEM")
16350 (member p org-special-properties))
16351 (add-to-list 'rtn (match-string 1 cfmt))))))))
16353 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16355 (defun org-property-values (key)
16356 "Return a list of all values of property KEY."
16357 (save-excursion
16358 (save-restriction
16359 (widen)
16360 (goto-char (point-min))
16361 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16362 values)
16363 (while (re-search-forward re nil t)
16364 (add-to-list 'values (org-trim (match-string 1))))
16365 (delete "" values)))))
16367 (defun org-insert-property-drawer ()
16368 "Insert a property drawer into the current entry."
16369 (interactive)
16370 (org-back-to-heading t)
16371 (looking-at outline-regexp)
16372 (let ((indent (- (match-end 0)(match-beginning 0)))
16373 (beg (point))
16374 (re (concat "^[ \t]*" org-keyword-time-regexp))
16375 end hiddenp)
16376 (outline-next-heading)
16377 (setq end (point))
16378 (goto-char beg)
16379 (while (re-search-forward re end t))
16380 (setq hiddenp (org-invisible-p))
16381 (end-of-line 1)
16382 (and (equal (char-after) ?\n) (forward-char 1))
16383 (org-skip-over-state-notes)
16384 (skip-chars-backward " \t\n\r")
16385 (if (eq (char-before) ?*) (forward-char 1))
16386 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16387 (beginning-of-line 0)
16388 (indent-to-column indent)
16389 (beginning-of-line 2)
16390 (indent-to-column indent)
16391 (beginning-of-line 0)
16392 (if hiddenp
16393 (save-excursion
16394 (org-back-to-heading t)
16395 (hide-entry))
16396 (org-flag-drawer t))))
16398 (defun org-set-property (property value)
16399 "In the current entry, set PROPERTY to VALUE.
16400 When called interactively, this will prompt for a property name, offering
16401 completion on existing and default properties. And then it will prompt
16402 for a value, offering competion either on allowed values (via an inherited
16403 xxx_ALL property) or on existing values in other instances of this property
16404 in the current file."
16405 (interactive
16406 (let* ((prop (completing-read
16407 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16408 (cur (org-entry-get nil prop))
16409 (allowed (org-property-get-allowed-values nil prop 'table))
16410 (existing (mapcar 'list (org-property-values prop)))
16411 (val (if allowed
16412 (completing-read "Value: " allowed nil 'req-match)
16413 (completing-read
16414 (concat "Value" (if (and cur (string-match "\\S-" cur))
16415 (concat "[" cur "]") "")
16416 ": ")
16417 existing nil nil "" nil cur))))
16418 (list prop (if (equal val "") cur val))))
16419 (unless (equal (org-entry-get nil property) value)
16420 (org-entry-put nil property value)))
16422 (defun org-delete-property (property)
16423 "In the current entry, delete PROPERTY."
16424 (interactive
16425 (let* ((prop (completing-read
16426 "Property: " (org-entry-properties nil 'standard))))
16427 (list prop)))
16428 (message "Property %s %s" property
16429 (if (org-entry-delete nil property)
16430 "deleted"
16431 "was not present in the entry")))
16433 (defun org-delete-property-globally (property)
16434 "Remove PROPERTY globally, from all entries."
16435 (interactive
16436 (let* ((prop (completing-read
16437 "Globally remove property: "
16438 (mapcar 'list (org-buffer-property-keys)))))
16439 (list prop)))
16440 (save-excursion
16441 (save-restriction
16442 (widen)
16443 (goto-char (point-min))
16444 (let ((cnt 0))
16445 (while (re-search-forward
16446 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16447 nil t)
16448 (setq cnt (1+ cnt))
16449 (replace-match ""))
16450 (message "Property \"%s\" removed from %d entries" property cnt)))))
16452 (defvar org-columns-current-fmt-compiled) ; defined below
16454 (defun org-compute-property-at-point ()
16455 "Compute the property at point.
16456 This looks for an enclosing column format, extracts the operator and
16457 then applies it to the proerty in the column format's scope."
16458 (interactive)
16459 (unless (org-at-property-p)
16460 (error "Not at a property"))
16461 (let ((prop (org-match-string-no-properties 2)))
16462 (org-columns-get-format-and-top-level)
16463 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16464 (error "No operator defined for property %s" prop))
16465 (org-columns-compute prop)))
16467 (defun org-property-get-allowed-values (pom property &optional table)
16468 "Get allowed values for the property PROPERTY.
16469 When TABLE is non-nil, return an alist that can directly be used for
16470 completion."
16471 (let (vals)
16472 (cond
16473 ((equal property "TODO")
16474 (setq vals (org-with-point-at pom
16475 (append org-todo-keywords-1 '("")))))
16476 ((equal property "PRIORITY")
16477 (let ((n org-lowest-priority))
16478 (while (>= n org-highest-priority)
16479 (push (char-to-string n) vals)
16480 (setq n (1- n)))))
16481 ((member property org-special-properties))
16483 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16485 (when (and vals (string-match "\\S-" vals))
16486 (setq vals (car (read-from-string (concat "(" vals ")"))))
16487 (setq vals (mapcar (lambda (x)
16488 (cond ((stringp x) x)
16489 ((numberp x) (number-to-string x))
16490 ((symbolp x) (symbol-name x))
16491 (t "???")))
16492 vals)))))
16493 (if table (mapcar 'list vals) vals)))
16495 (defun org-property-previous-allowed-value (&optional previous)
16496 "Switch to the next allowed value for this property."
16497 (interactive)
16498 (org-property-next-allowed-value t))
16500 (defun org-property-next-allowed-value (&optional previous)
16501 "Switch to the next allowed value for this property."
16502 (interactive)
16503 (unless (org-at-property-p)
16504 (error "Not at a property"))
16505 (let* ((key (match-string 2))
16506 (value (match-string 3))
16507 (allowed (or (org-property-get-allowed-values (point) key)
16508 (and (member value '("[ ]" "[-]" "[X]"))
16509 '("[ ]" "[X]"))))
16510 nval)
16511 (unless allowed
16512 (error "Allowed values for this property have not been defined"))
16513 (if previous (setq allowed (reverse allowed)))
16514 (if (member value allowed)
16515 (setq nval (car (cdr (member value allowed)))))
16516 (setq nval (or nval (car allowed)))
16517 (if (equal nval value)
16518 (error "Only one allowed value for this property"))
16519 (org-at-property-p)
16520 (replace-match (concat " :" key ": " nval) t t)
16521 (org-indent-line-function)
16522 (beginning-of-line 1)
16523 (skip-chars-forward " \t")))
16525 (defun org-find-entry-with-id (ident)
16526 "Locate the entry that contains the ID property with exact value IDENT.
16527 IDENT can be a string, a symbol or a number, this function will search for
16528 the string representation of it.
16529 Return the position where this entry starts, or nil if there is no such entry."
16530 (let ((id (cond
16531 ((stringp ident) ident)
16532 ((symbol-name ident) (symbol-name ident))
16533 ((numberp ident) (number-to-string ident))
16534 (t (error "IDENT %s must be a string, symbol or number" ident))))
16535 (case-fold-search nil))
16536 (save-excursion
16537 (save-restriction
16538 (widen)
16539 (goto-char (point-min))
16540 (when (re-search-forward
16541 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16542 nil t)
16543 (org-back-to-heading)
16544 (point))))))
16546 ;;; Column View
16548 (defvar org-columns-overlays nil
16549 "Holds the list of current column overlays.")
16551 (defvar org-columns-current-fmt nil
16552 "Local variable, holds the currently active column format.")
16553 (defvar org-columns-current-fmt-compiled nil
16554 "Local variable, holds the currently active column format.
16555 This is the compiled version of the format.")
16556 (defvar org-columns-current-widths nil
16557 "Loval variable, holds the currently widths of fields.")
16558 (defvar org-columns-current-maxwidths nil
16559 "Loval variable, holds the currently active maximum column widths.")
16560 (defvar org-columns-begin-marker (make-marker)
16561 "Points to the position where last a column creation command was called.")
16562 (defvar org-columns-top-level-marker (make-marker)
16563 "Points to the position where current columns region starts.")
16565 (defvar org-columns-map (make-sparse-keymap)
16566 "The keymap valid in column display.")
16568 (defun org-columns-content ()
16569 "Switch to contents view while in columns view."
16570 (interactive)
16571 (org-overview)
16572 (org-content))
16574 (org-defkey org-columns-map "c" 'org-columns-content)
16575 (org-defkey org-columns-map "o" 'org-overview)
16576 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16577 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16578 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16579 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16580 (org-defkey org-columns-map "v" 'org-columns-show-value)
16581 (org-defkey org-columns-map "q" 'org-columns-quit)
16582 (org-defkey org-columns-map "r" 'org-columns-redo)
16583 (org-defkey org-columns-map "g" 'org-columns-redo)
16584 (org-defkey org-columns-map [left] 'backward-char)
16585 (org-defkey org-columns-map "\M-b" 'backward-char)
16586 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16587 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16588 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16589 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16590 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16591 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16592 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16593 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16594 (org-defkey org-columns-map "<" 'org-columns-narrow)
16595 (org-defkey org-columns-map ">" 'org-columns-widen)
16596 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16597 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16598 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16599 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16601 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16602 '("Column"
16603 ["Edit property" org-columns-edit-value t]
16604 ["Next allowed value" org-columns-next-allowed-value t]
16605 ["Previous allowed value" org-columns-previous-allowed-value t]
16606 ["Show full value" org-columns-show-value t]
16607 ["Edit allowed values" org-columns-edit-allowed t]
16608 "--"
16609 ["Edit column attributes" org-columns-edit-attributes t]
16610 ["Increase column width" org-columns-widen t]
16611 ["Decrease column width" org-columns-narrow t]
16612 "--"
16613 ["Move column right" org-columns-move-right t]
16614 ["Move column left" org-columns-move-left t]
16615 ["Add column" org-columns-new t]
16616 ["Delete column" org-columns-delete t]
16617 "--"
16618 ["CONTENTS" org-columns-content t]
16619 ["OVERVIEW" org-overview t]
16620 ["Refresh columns display" org-columns-redo t]
16621 "--"
16622 ["Open link" org-columns-open-link t]
16623 "--"
16624 ["Quit" org-columns-quit t]))
16626 (defun org-columns-new-overlay (beg end &optional string face)
16627 "Create a new column overlay and add it to the list."
16628 (let ((ov (org-make-overlay beg end)))
16629 (org-overlay-put ov 'face (or face 'secondary-selection))
16630 (org-overlay-display ov string face)
16631 (push ov org-columns-overlays)
16632 ov))
16634 (defun org-columns-display-here (&optional props)
16635 "Overlay the current line with column display."
16636 (interactive)
16637 (let* ((fmt org-columns-current-fmt-compiled)
16638 (beg (point-at-bol))
16639 (level-face (save-excursion
16640 (beginning-of-line 1)
16641 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16642 (org-get-level-face 2))))
16643 (color (list :foreground
16644 (face-attribute (or level-face 'default) :foreground)))
16645 props pom property ass width f string ov column val modval)
16646 ;; Check if the entry is in another buffer.
16647 (unless props
16648 (if (eq major-mode 'org-agenda-mode)
16649 (setq pom (or (get-text-property (point) 'org-hd-marker)
16650 (get-text-property (point) 'org-marker))
16651 props (if pom (org-entry-properties pom) nil))
16652 (setq props (org-entry-properties nil))))
16653 ;; Walk the format
16654 (while (setq column (pop fmt))
16655 (setq property (car column)
16656 ass (if (equal property "ITEM")
16657 (cons "ITEM"
16658 (save-match-data
16659 (org-no-properties
16660 (org-remove-tabs
16661 (buffer-substring-no-properties
16662 (point-at-bol) (point-at-eol))))))
16663 (assoc property props))
16664 width (or (cdr (assoc property org-columns-current-maxwidths))
16665 (nth 2 column)
16666 (length property))
16667 f (format "%%-%d.%ds | " width width)
16668 val (or (cdr ass) "")
16669 modval (if (equal property "ITEM")
16670 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16671 string (format f (or modval val)))
16672 ;; Create the overlay
16673 (org-unmodified
16674 (setq ov (org-columns-new-overlay
16675 beg (setq beg (1+ beg)) string
16676 (list color 'org-column)))
16677 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16678 (org-overlay-put ov 'keymap org-columns-map)
16679 (org-overlay-put ov 'org-columns-key property)
16680 (org-overlay-put ov 'org-columns-value (cdr ass))
16681 (org-overlay-put ov 'org-columns-value-modified modval)
16682 (org-overlay-put ov 'org-columns-pom pom)
16683 (org-overlay-put ov 'org-columns-format f))
16684 (if (or (not (char-after beg))
16685 (equal (char-after beg) ?\n))
16686 (let ((inhibit-read-only t))
16687 (save-excursion
16688 (goto-char beg)
16689 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16690 ;; Make the rest of the line disappear.
16691 (org-unmodified
16692 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16693 (org-overlay-put ov 'invisible t)
16694 (org-overlay-put ov 'keymap org-columns-map)
16695 (org-overlay-put ov 'intangible t)
16696 (push ov org-columns-overlays)
16697 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16698 (org-overlay-put ov 'keymap org-columns-map)
16699 (push ov org-columns-overlays)
16700 (let ((inhibit-read-only t))
16701 (put-text-property (max (point-min) (1- (point-at-bol)))
16702 (min (point-max) (1+ (point-at-eol)))
16703 'read-only "Type `e' to edit property")))))
16705 (defvar org-previous-header-line-format nil
16706 "The header line format before column view was turned on.")
16707 (defvar org-columns-inhibit-recalculation nil
16708 "Inhibit recomputing of columns on column view startup.")
16711 (defvar header-line-format)
16712 (defun org-columns-display-here-title ()
16713 "Overlay the newline before the current line with the table title."
16714 (interactive)
16715 (let ((fmt org-columns-current-fmt-compiled)
16716 string (title "")
16717 property width f column str widths)
16718 (while (setq column (pop fmt))
16719 (setq property (car column)
16720 str (or (nth 1 column) property)
16721 width (or (cdr (assoc property org-columns-current-maxwidths))
16722 (nth 2 column)
16723 (length str))
16724 widths (push width widths)
16725 f (format "%%-%d.%ds | " width width)
16726 string (format f str)
16727 title (concat title string)))
16728 (setq title (concat
16729 (org-add-props " " nil 'display '(space :align-to 0))
16730 (org-add-props title nil 'face '(:weight bold :underline t))))
16731 (org-set-local 'org-previous-header-line-format header-line-format)
16732 (org-set-local 'org-columns-current-widths (nreverse widths))
16733 (setq header-line-format title)))
16735 (defun org-columns-remove-overlays ()
16736 "Remove all currently active column overlays."
16737 (interactive)
16738 (when (marker-buffer org-columns-begin-marker)
16739 (with-current-buffer (marker-buffer org-columns-begin-marker)
16740 (when (local-variable-p 'org-previous-header-line-format)
16741 (setq header-line-format org-previous-header-line-format)
16742 (kill-local-variable 'org-previous-header-line-format))
16743 (move-marker org-columns-begin-marker nil)
16744 (move-marker org-columns-top-level-marker nil)
16745 (org-unmodified
16746 (mapc 'org-delete-overlay org-columns-overlays)
16747 (setq org-columns-overlays nil)
16748 (let ((inhibit-read-only t))
16749 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16751 (defun org-columns-cleanup-item (item fmt)
16752 "Remove from ITEM what is a column in the format FMT."
16753 (if (not org-complex-heading-regexp)
16754 item
16755 (when (string-match org-complex-heading-regexp item)
16756 (concat
16757 (org-add-props (concat (match-string 1 item) " ") nil
16758 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16759 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16760 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16761 " " (match-string 4 item)
16762 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16764 (defun org-columns-show-value ()
16765 "Show the full value of the property."
16766 (interactive)
16767 (let ((value (get-char-property (point) 'org-columns-value)))
16768 (message "Value is: %s" (or value ""))))
16770 (defun org-columns-quit ()
16771 "Remove the column overlays and in this way exit column editing."
16772 (interactive)
16773 (org-unmodified
16774 (org-columns-remove-overlays)
16775 (let ((inhibit-read-only t))
16776 (remove-text-properties (point-min) (point-max) '(read-only t))))
16777 (when (eq major-mode 'org-agenda-mode)
16778 (message
16779 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16781 (defun org-columns-check-computed ()
16782 "Check if this column value is computed.
16783 If yes, throw an error indicating that changing it does not make sense."
16784 (let ((val (get-char-property (point) 'org-columns-value)))
16785 (when (and (stringp val)
16786 (get-char-property 0 'org-computed val))
16787 (error "This value is computed from the entry's children"))))
16789 (defun org-columns-todo (&optional arg)
16790 "Change the TODO state during column view."
16791 (interactive "P")
16792 (org-columns-edit-value "TODO"))
16794 (defun org-columns-set-tags-or-toggle (&optional arg)
16795 "Toggle checkbox at point, or set tags for current headline."
16796 (interactive "P")
16797 (if (string-match "\\`\\[[ xX-]\\]\\'"
16798 (get-char-property (point) 'org-columns-value))
16799 (org-columns-next-allowed-value)
16800 (org-columns-edit-value "TAGS")))
16802 (defun org-columns-edit-value (&optional key)
16803 "Edit the value of the property at point in column view.
16804 Where possible, use the standard interface for changing this line."
16805 (interactive)
16806 (org-columns-check-computed)
16807 (let* ((external-key key)
16808 (col (current-column))
16809 (key (or key (get-char-property (point) 'org-columns-key)))
16810 (value (get-char-property (point) 'org-columns-value))
16811 (bol (point-at-bol)) (eol (point-at-eol))
16812 (pom (or (get-text-property bol 'org-hd-marker)
16813 (point))) ; keep despite of compiler waring
16814 (line-overlays
16815 (delq nil (mapcar (lambda (x)
16816 (and (eq (overlay-buffer x) (current-buffer))
16817 (>= (overlay-start x) bol)
16818 (<= (overlay-start x) eol)
16820 org-columns-overlays)))
16821 nval eval allowed)
16822 (cond
16823 ((equal key "CLOCKSUM")
16824 (error "This special column cannot be edited"))
16825 ((equal key "ITEM")
16826 (setq eval '(org-with-point-at pom
16827 (org-edit-headline))))
16828 ((equal key "TODO")
16829 (setq eval '(org-with-point-at pom
16830 (let ((current-prefix-arg
16831 (if external-key current-prefix-arg '(4))))
16832 (call-interactively 'org-todo)))))
16833 ((equal key "PRIORITY")
16834 (setq eval '(org-with-point-at pom
16835 (call-interactively 'org-priority))))
16836 ((equal key "TAGS")
16837 (setq eval '(org-with-point-at pom
16838 (let ((org-fast-tag-selection-single-key
16839 (if (eq org-fast-tag-selection-single-key 'expert)
16840 t org-fast-tag-selection-single-key)))
16841 (call-interactively 'org-set-tags)))))
16842 ((equal key "DEADLINE")
16843 (setq eval '(org-with-point-at pom
16844 (call-interactively 'org-deadline))))
16845 ((equal key "SCHEDULED")
16846 (setq eval '(org-with-point-at pom
16847 (call-interactively 'org-schedule))))
16849 (setq allowed (org-property-get-allowed-values pom key 'table))
16850 (if allowed
16851 (setq nval (completing-read "Value: " allowed nil t))
16852 (setq nval (read-string "Edit: " value)))
16853 (setq nval (org-trim nval))
16854 (when (not (equal nval value))
16855 (setq eval '(org-entry-put pom key nval)))))
16856 (when eval
16857 (let ((inhibit-read-only t))
16858 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16859 (unwind-protect
16860 (progn
16861 (setq org-columns-overlays
16862 (org-delete-all line-overlays org-columns-overlays))
16863 (mapc 'org-delete-overlay line-overlays)
16864 (org-columns-eval eval))
16865 (org-columns-display-here))))
16866 (move-to-column col)
16867 (if (and (org-mode-p)
16868 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16869 (org-columns-update key))))
16871 (defun org-edit-headline () ; FIXME: this is not columns specific
16872 "Edit the current headline, the part without TODO keyword, TAGS."
16873 (org-back-to-heading)
16874 (when (looking-at org-todo-line-regexp)
16875 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16876 (txt (match-string 3))
16877 (post "")
16878 txt2)
16879 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16880 (setq post (match-string 0 txt)
16881 txt (substring txt 0 (match-beginning 0))))
16882 (setq txt2 (read-string "Edit: " txt))
16883 (when (not (equal txt txt2))
16884 (beginning-of-line 1)
16885 (insert pre txt2 post)
16886 (delete-region (point) (point-at-eol))
16887 (org-set-tags nil t)))))
16889 (defun org-columns-edit-allowed ()
16890 "Edit the list of allowed values for the current property."
16891 (interactive)
16892 (let* ((key (get-char-property (point) 'org-columns-key))
16893 (key1 (concat key "_ALL"))
16894 (allowed (org-entry-get (point) key1 t))
16895 nval)
16896 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16897 (setq nval (read-string "Allowed: " allowed))
16898 (org-entry-put
16899 (cond ((marker-position org-entry-property-inherited-from)
16900 org-entry-property-inherited-from)
16901 ((marker-position org-columns-top-level-marker)
16902 org-columns-top-level-marker))
16903 key1 nval)))
16905 (defmacro org-no-warnings (&rest body)
16906 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16908 (defun org-columns-eval (form)
16909 (let (hidep)
16910 (save-excursion
16911 (beginning-of-line 1)
16912 ;; `next-line' is needed here, because it skips invisible line.
16913 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16914 (setq hidep (org-on-heading-p 1)))
16915 (eval form)
16916 (and hidep (hide-entry))))
16918 (defun org-columns-previous-allowed-value ()
16919 "Switch to the previous allowed value for this column."
16920 (interactive)
16921 (org-columns-next-allowed-value t))
16923 (defun org-columns-next-allowed-value (&optional previous)
16924 "Switch to the next allowed value for this column."
16925 (interactive)
16926 (org-columns-check-computed)
16927 (let* ((col (current-column))
16928 (key (get-char-property (point) 'org-columns-key))
16929 (value (get-char-property (point) 'org-columns-value))
16930 (bol (point-at-bol)) (eol (point-at-eol))
16931 (pom (or (get-text-property bol 'org-hd-marker)
16932 (point))) ; keep despite of compiler waring
16933 (line-overlays
16934 (delq nil (mapcar (lambda (x)
16935 (and (eq (overlay-buffer x) (current-buffer))
16936 (>= (overlay-start x) bol)
16937 (<= (overlay-start x) eol)
16939 org-columns-overlays)))
16940 (allowed (or (org-property-get-allowed-values pom key)
16941 (and (memq
16942 (nth 4 (assoc key org-columns-current-fmt-compiled))
16943 '(checkbox checkbox-n-of-m checkbox-percent))
16944 '("[ ]" "[X]"))))
16945 nval)
16946 (when (equal key "ITEM")
16947 (error "Cannot edit item headline from here"))
16948 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16949 (error "Allowed values for this property have not been defined"))
16950 (if (member key '("SCHEDULED" "DEADLINE"))
16951 (setq nval (if previous 'earlier 'later))
16952 (if previous (setq allowed (reverse allowed)))
16953 (if (member value allowed)
16954 (setq nval (car (cdr (member value allowed)))))
16955 (setq nval (or nval (car allowed)))
16956 (if (equal nval value)
16957 (error "Only one allowed value for this property")))
16958 (let ((inhibit-read-only t))
16959 (remove-text-properties (1- bol) eol '(read-only t))
16960 (unwind-protect
16961 (progn
16962 (setq org-columns-overlays
16963 (org-delete-all line-overlays org-columns-overlays))
16964 (mapc 'org-delete-overlay line-overlays)
16965 (org-columns-eval '(org-entry-put pom key nval)))
16966 (org-columns-display-here)))
16967 (move-to-column col)
16968 (if (and (org-mode-p)
16969 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16970 (org-columns-update key))))
16972 (defun org-verify-version (task)
16973 (cond
16974 ((eq task 'columns)
16975 (if (or (featurep 'xemacs)
16976 (< emacs-major-version 22))
16977 (error "Emacs 22 is required for the columns feature")))))
16979 (defun org-columns-open-link (&optional arg)
16980 (interactive "P")
16981 (let ((value (get-char-property (point) 'org-columns-value)))
16982 (org-open-link-from-string value arg)))
16984 (defun org-open-link-from-string (s &optional arg)
16985 "Open a link in the string S, as if it was in Org-mode."
16986 (interactive)
16987 (with-temp-buffer
16988 (let ((org-inhibit-startup t))
16989 (org-mode)
16990 (insert s)
16991 (goto-char (point-min))
16992 (org-open-at-point arg))))
16994 (defun org-columns-get-format-and-top-level ()
16995 (let (fmt)
16996 (when (condition-case nil (org-back-to-heading) (error nil))
16997 (move-marker org-entry-property-inherited-from nil)
16998 (setq fmt (org-entry-get nil "COLUMNS" t)))
16999 (setq fmt (or fmt org-columns-default-format))
17000 (org-set-local 'org-columns-current-fmt fmt)
17001 (org-columns-compile-format fmt)
17002 (if (marker-position org-entry-property-inherited-from)
17003 (move-marker org-columns-top-level-marker
17004 org-entry-property-inherited-from)
17005 (move-marker org-columns-top-level-marker (point)))
17006 fmt))
17008 (defun org-columns ()
17009 "Turn on column view on an org-mode file."
17010 (interactive)
17011 (org-verify-version 'columns)
17012 (org-columns-remove-overlays)
17013 (move-marker org-columns-begin-marker (point))
17014 (let (beg end fmt cache maxwidths)
17015 (setq fmt (org-columns-get-format-and-top-level))
17016 (save-excursion
17017 (goto-char org-columns-top-level-marker)
17018 (setq beg (point))
17019 (unless org-columns-inhibit-recalculation
17020 (org-columns-compute-all))
17021 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17022 (point-max)))
17023 ;; Get and cache the properties
17024 (goto-char beg)
17025 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17026 (save-excursion
17027 (save-restriction
17028 (narrow-to-region beg end)
17029 (org-clock-sum))))
17030 (while (re-search-forward (concat "^" outline-regexp) end t)
17031 (push (cons (org-current-line) (org-entry-properties)) cache))
17032 (when cache
17033 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17034 (org-set-local 'org-columns-current-maxwidths maxwidths)
17035 (org-columns-display-here-title)
17036 (mapc (lambda (x)
17037 (goto-line (car x))
17038 (org-columns-display-here (cdr x)))
17039 cache)))))
17041 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17042 "Insert a new column, to the leeft o the current column."
17043 (interactive)
17044 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17045 cell)
17046 (setq prop (completing-read
17047 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17048 nil nil prop))
17049 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17050 (setq width (read-string "Column width: " (if width (number-to-string width))))
17051 (if (string-match "\\S-" width)
17052 (setq width (string-to-number width))
17053 (setq width nil))
17054 (setq fmt (completing-read "Summary [none]: "
17055 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17056 nil t))
17057 (if (string-match "\\S-" fmt)
17058 (setq fmt (intern fmt))
17059 (setq fmt nil))
17060 (if (eq fmt 'none) (setq fmt nil))
17061 (if editp
17062 (progn
17063 (setcar editp prop)
17064 (setcdr editp (list title width nil fmt)))
17065 (setq cell (nthcdr (1- (current-column))
17066 org-columns-current-fmt-compiled))
17067 (setcdr cell (cons (list prop title width nil fmt)
17068 (cdr cell))))
17069 (org-columns-store-format)
17070 (org-columns-redo)))
17072 (defun org-columns-delete ()
17073 "Delete the column at point from columns view."
17074 (interactive)
17075 (let* ((n (current-column))
17076 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17077 (when (y-or-n-p
17078 (format "Are you sure you want to remove column \"%s\"? " title))
17079 (setq org-columns-current-fmt-compiled
17080 (delq (nth n org-columns-current-fmt-compiled)
17081 org-columns-current-fmt-compiled))
17082 (org-columns-store-format)
17083 (org-columns-redo)
17084 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17085 (backward-char 1)))))
17087 (defun org-columns-edit-attributes ()
17088 "Edit the attributes of the current column."
17089 (interactive)
17090 (let* ((n (current-column))
17091 (info (nth n org-columns-current-fmt-compiled)))
17092 (apply 'org-columns-new info)))
17094 (defun org-columns-widen (arg)
17095 "Make the column wider by ARG characters."
17096 (interactive "p")
17097 (let* ((n (current-column))
17098 (entry (nth n org-columns-current-fmt-compiled))
17099 (width (or (nth 2 entry)
17100 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17101 (setq width (max 1 (+ width arg)))
17102 (setcar (nthcdr 2 entry) width)
17103 (org-columns-store-format)
17104 (org-columns-redo)))
17106 (defun org-columns-narrow (arg)
17107 "Make the column nrrower by ARG characters."
17108 (interactive "p")
17109 (org-columns-widen (- arg)))
17111 (defun org-columns-move-right ()
17112 "Swap this column with the one to the right."
17113 (interactive)
17114 (let* ((n (current-column))
17115 (cell (nthcdr n org-columns-current-fmt-compiled))
17117 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17118 (error "Cannot shift this column further to the right"))
17119 (setq e (car cell))
17120 (setcar cell (car (cdr cell)))
17121 (setcdr cell (cons e (cdr (cdr cell))))
17122 (org-columns-store-format)
17123 (org-columns-redo)
17124 (forward-char 1)))
17126 (defun org-columns-move-left ()
17127 "Swap this column with the one to the left."
17128 (interactive)
17129 (let* ((n (current-column)))
17130 (when (= n 0)
17131 (error "Cannot shift this column further to the left"))
17132 (backward-char 1)
17133 (org-columns-move-right)
17134 (backward-char 1)))
17136 (defun org-columns-store-format ()
17137 "Store the text version of the current columns format in appropriate place.
17138 This is either in the COLUMNS property of the node starting the current column
17139 display, or in the #+COLUMNS line of the current buffer."
17140 (let (fmt (cnt 0))
17141 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17142 (org-set-local 'org-columns-current-fmt fmt)
17143 (if (marker-position org-columns-top-level-marker)
17144 (save-excursion
17145 (goto-char org-columns-top-level-marker)
17146 (if (and (org-at-heading-p)
17147 (org-entry-get nil "COLUMNS"))
17148 (org-entry-put nil "COLUMNS" fmt)
17149 (goto-char (point-min))
17150 ;; Overwrite all #+COLUMNS lines....
17151 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17152 (setq cnt (1+ cnt))
17153 (replace-match (concat "#+COLUMNS: " fmt) t t))
17154 (unless (> cnt 0)
17155 (goto-char (point-min))
17156 (or (org-on-heading-p t) (outline-next-heading))
17157 (let ((inhibit-read-only t))
17158 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17159 (org-set-local 'org-columns-default-format fmt))))))
17161 (defvar org-overriding-columns-format nil
17162 "When set, overrides any other definition.")
17163 (defvar org-agenda-view-columns-initially nil
17164 "When set, switch to columns view immediately after creating the agenda.")
17166 (defun org-agenda-columns ()
17167 "Turn on column view in the agenda."
17168 (interactive)
17169 (org-verify-version 'columns)
17170 (org-columns-remove-overlays)
17171 (move-marker org-columns-begin-marker (point))
17172 (let (fmt cache maxwidths m)
17173 (cond
17174 ((and (local-variable-p 'org-overriding-columns-format)
17175 org-overriding-columns-format)
17176 (setq fmt org-overriding-columns-format))
17177 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17178 (setq fmt (org-entry-get m "COLUMNS" t)))
17179 ((and (boundp 'org-columns-current-fmt)
17180 (local-variable-p 'org-columns-current-fmt)
17181 org-columns-current-fmt)
17182 (setq fmt org-columns-current-fmt))
17183 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17184 (setq m (get-text-property m 'org-hd-marker))
17185 (setq fmt (org-entry-get m "COLUMNS" t))))
17186 (setq fmt (or fmt org-columns-default-format))
17187 (org-set-local 'org-columns-current-fmt fmt)
17188 (org-columns-compile-format fmt)
17189 (save-excursion
17190 ;; Get and cache the properties
17191 (goto-char (point-min))
17192 (while (not (eobp))
17193 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17194 (get-text-property (point) 'org-marker)))
17195 (push (cons (org-current-line) (org-entry-properties m)) cache))
17196 (beginning-of-line 2))
17197 (when cache
17198 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17199 (org-set-local 'org-columns-current-maxwidths maxwidths)
17200 (org-columns-display-here-title)
17201 (mapc (lambda (x)
17202 (goto-line (car x))
17203 (org-columns-display-here (cdr x)))
17204 cache)))))
17206 (defun org-columns-get-autowidth-alist (s cache)
17207 "Derive the maximum column widths from the format and the cache."
17208 (let ((start 0) rtn)
17209 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17210 (push (cons (match-string 1 s) 1) rtn)
17211 (setq start (match-end 0)))
17212 (mapc (lambda (x)
17213 (setcdr x (apply 'max
17214 (mapcar
17215 (lambda (y)
17216 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17217 cache))))
17218 rtn)
17219 rtn))
17221 (defun org-columns-compute-all ()
17222 "Compute all columns that have operators defined."
17223 (org-unmodified
17224 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17225 (let ((columns org-columns-current-fmt-compiled) col)
17226 (while (setq col (pop columns))
17227 (when (nth 3 col)
17228 (save-excursion
17229 (org-columns-compute (car col)))))))
17231 (defun org-columns-update (property)
17232 "Recompute PROPERTY, and update the columns display for it."
17233 (org-columns-compute property)
17234 (let (fmt val pos)
17235 (save-excursion
17236 (mapc (lambda (ov)
17237 (when (equal (org-overlay-get ov 'org-columns-key) property)
17238 (setq pos (org-overlay-start ov))
17239 (goto-char pos)
17240 (when (setq val (cdr (assoc property
17241 (get-text-property
17242 (point-at-bol) 'org-summaries))))
17243 (setq fmt (org-overlay-get ov 'org-columns-format))
17244 (org-overlay-put ov 'org-columns-value val)
17245 (org-overlay-put ov 'display (format fmt val)))))
17246 org-columns-overlays))))
17248 (defun org-columns-compute (property)
17249 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17250 (interactive)
17251 (let* ((re (concat "^" outline-regexp))
17252 (lmax 30) ; Does anyone use deeper levels???
17253 (lsum (make-vector lmax 0))
17254 (lflag (make-vector lmax nil))
17255 (level 0)
17256 (ass (assoc property org-columns-current-fmt-compiled))
17257 (format (nth 4 ass))
17258 (printf (nth 5 ass))
17259 (beg org-columns-top-level-marker)
17260 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17261 (save-excursion
17262 ;; Find the region to compute
17263 (goto-char beg)
17264 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17265 (goto-char end)
17266 ;; Walk the tree from the back and do the computations
17267 (while (re-search-backward re beg t)
17268 (setq sumpos (match-beginning 0)
17269 last-level level
17270 level (org-outline-level)
17271 val (org-entry-get nil property)
17272 valflag (and val (string-match "\\S-" val)))
17273 (cond
17274 ((< level last-level)
17275 ;; put the sum of lower levels here as a property
17276 (setq sum (aref lsum last-level) ; current sum
17277 flag (aref lflag last-level) ; any valid entries from children?
17278 str (org-column-number-to-string sum format printf)
17279 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17280 useval (if flag str1 (if valflag val ""))
17281 sum-alist (get-text-property sumpos 'org-summaries))
17282 (if (assoc property sum-alist)
17283 (setcdr (assoc property sum-alist) useval)
17284 (push (cons property useval) sum-alist)
17285 (org-unmodified
17286 (add-text-properties sumpos (1+ sumpos)
17287 (list 'org-summaries sum-alist))))
17288 (when val
17289 (org-entry-put nil property (if flag str val)))
17290 ;; add current to current level accumulator
17291 (when (or flag valflag)
17292 (aset lsum level (+ (aref lsum level)
17293 (if flag sum (org-column-string-to-number
17294 (if flag str val) format))))
17295 (aset lflag level t))
17296 ;; clear accumulators for deeper levels
17297 (loop for l from (1+ level) to (1- lmax) do
17298 (aset lsum l 0)
17299 (aset lflag l nil)))
17300 ((>= level last-level)
17301 ;; add what we have here to the accumulator for this level
17302 (aset lsum level (+ (aref lsum level)
17303 (org-column-string-to-number (or val "0") format)))
17304 (and valflag (aset lflag level t)))
17305 (t (error "This should not happen")))))))
17307 (defun org-columns-redo ()
17308 "Construct the column display again."
17309 (interactive)
17310 (message "Recomputing columns...")
17311 (save-excursion
17312 (if (marker-position org-columns-begin-marker)
17313 (goto-char org-columns-begin-marker))
17314 (org-columns-remove-overlays)
17315 (if (org-mode-p)
17316 (call-interactively 'org-columns)
17317 (call-interactively 'org-agenda-columns)))
17318 (message "Recomputing columns...done"))
17320 (defun org-columns-not-in-agenda ()
17321 (if (eq major-mode 'org-agenda-mode)
17322 (error "This command is only allowed in Org-mode buffers")))
17325 (defun org-string-to-number (s)
17326 "Convert string to number, and interpret hh:mm:ss."
17327 (if (not (string-match ":" s))
17328 (string-to-number s)
17329 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17330 (while l
17331 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17332 sum)))
17334 (defun org-column-number-to-string (n fmt &optional printf)
17335 "Convert a computed column number to a string value, according to FMT."
17336 (cond
17337 ((eq fmt 'add_times)
17338 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17339 (format "%d:%02d" h m)))
17340 ((eq fmt 'checkbox)
17341 (cond ((= n (floor n)) "[X]")
17342 ((> n 1.) "[-]")
17343 (t "[ ]")))
17344 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17345 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17346 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17347 (printf (format printf n))
17348 ((eq fmt 'currency)
17349 (format "%.2f" n))
17350 (t (number-to-string n))))
17352 (defun org-nofm-to-completion (n m &optional percent)
17353 (if (not percent)
17354 (format "[%d/%d]" n m)
17355 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17357 (defun org-column-string-to-number (s fmt)
17358 "Convert a column value to a number that can be used for column computing."
17359 (cond
17360 ((string-match ":" s)
17361 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17362 (while l
17363 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17364 sum))
17365 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17366 (if (equal s "[X]") 1. 0.000001))
17367 (t (string-to-number s))))
17369 (defun org-columns-uncompile-format (cfmt)
17370 "Turn the compiled columns format back into a string representation."
17371 (let ((rtn "") e s prop title op width fmt printf)
17372 (while (setq e (pop cfmt))
17373 (setq prop (car e)
17374 title (nth 1 e)
17375 width (nth 2 e)
17376 op (nth 3 e)
17377 fmt (nth 4 e)
17378 printf (nth 5 e))
17379 (cond
17380 ((eq fmt 'add_times) (setq op ":"))
17381 ((eq fmt 'checkbox) (setq op "X"))
17382 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17383 ((eq fmt 'checkbox-percent) (setq op "X%"))
17384 ((eq fmt 'add_numbers) (setq op "+"))
17385 ((eq fmt 'currency) (setq op "$")))
17386 (if (and op printf) (setq op (concat op ";" printf)))
17387 (if (equal title prop) (setq title nil))
17388 (setq s (concat "%" (if width (number-to-string width))
17389 prop
17390 (if title (concat "(" title ")"))
17391 (if op (concat "{" op "}"))))
17392 (setq rtn (concat rtn " " s)))
17393 (org-trim rtn)))
17395 (defun org-columns-compile-format (fmt)
17396 "Turn a column format string into an alist of specifications.
17397 The alist has one entry for each column in the format. The elements of
17398 that list are:
17399 property the property
17400 title the title field for the columns
17401 width the column width in characters, can be nil for automatic
17402 operator the operator if any
17403 format the output format for computed results, derived from operator
17404 printf a printf format for computed values"
17405 (let ((start 0) width prop title op f printf)
17406 (setq org-columns-current-fmt-compiled nil)
17407 (while (string-match
17408 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17409 fmt start)
17410 (setq start (match-end 0)
17411 width (match-string 1 fmt)
17412 prop (match-string 2 fmt)
17413 title (or (match-string 3 fmt) prop)
17414 op (match-string 4 fmt)
17415 f nil
17416 printf nil)
17417 (if width (setq width (string-to-number width)))
17418 (when (and op (string-match ";" op))
17419 (setq printf (substring op (match-end 0))
17420 op (substring op 0 (match-beginning 0))))
17421 (cond
17422 ((equal op "+") (setq f 'add_numbers))
17423 ((equal op "$") (setq f 'currency))
17424 ((equal op ":") (setq f 'add_times))
17425 ((equal op "X") (setq f 'checkbox))
17426 ((equal op "X/") (setq f 'checkbox-n-of-m))
17427 ((equal op "X%") (setq f 'checkbox-percent))
17429 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17430 (setq org-columns-current-fmt-compiled
17431 (nreverse org-columns-current-fmt-compiled))))
17434 ;;; Dynamic block for Column view
17436 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17437 "Get the column view of the current buffer or subtree.
17438 The first optional argument MAXLEVEL sets the level limit. A
17439 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17440 empty rows, an empty row being one where all the column view
17441 specifiers except ITEM are empty. This function returns a list
17442 containing the title row and all other rows. Each row is a list
17443 of fields."
17444 (save-excursion
17445 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17446 (n (length title)) row tbl)
17447 (goto-char (point-min))
17448 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17449 (or (null maxlevel)
17450 (>= maxlevel
17451 (if org-odd-levels-only
17452 (/ (1+ (length (match-string 1))) 2)
17453 (length (match-string 1))))))
17454 (when (get-char-property (match-beginning 0) 'org-columns-key)
17455 (setq row nil)
17456 (loop for i from 0 to (1- n) do
17457 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17458 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17460 row))
17461 (setq row (nreverse row))
17462 (unless (and skip-empty-rows
17463 (eq 1 (length (delete "" (delete-dups row)))))
17464 (push row tbl))))
17465 (append (list title 'hline) (nreverse tbl)))))
17467 (defun org-dblock-write:columnview (params)
17468 "Write the column view table.
17469 PARAMS is a property list of parameters:
17471 :width enforce same column widths with <N> specifiers.
17472 :id the :ID: property of the entry where the columns view
17473 should be built, as a string. When `local', call locally.
17474 When `global' call column view with the cursor at the beginning
17475 of the buffer (usually this means that the whole buffer switches
17476 to column view).
17477 :hlines When t, insert a hline before each item. When a number, insert
17478 a hline before each level <= that number.
17479 :vlines When t, make each column a colgroup to enforce vertical lines.
17480 :maxlevel When set to a number, don't capture headlines below this level.
17481 :skip-empty-rows
17482 When t, skip rows where all specifiers other than ITEM are empty."
17483 (let ((pos (move-marker (make-marker) (point)))
17484 (hlines (plist-get params :hlines))
17485 (vlines (plist-get params :vlines))
17486 (maxlevel (plist-get params :maxlevel))
17487 (skip-empty-rows (plist-get params :skip-empty-rows))
17488 tbl id idpos nfields tmp)
17489 (save-excursion
17490 (save-restriction
17491 (when (setq id (plist-get params :id))
17492 (cond ((not id) nil)
17493 ((eq id 'global) (goto-char (point-min)))
17494 ((eq id 'local) nil)
17495 ((setq idpos (org-find-entry-with-id id))
17496 (goto-char idpos))
17497 (t (error "Cannot find entry with :ID: %s" id))))
17498 (org-columns)
17499 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17500 (setq nfields (length (car tbl)))
17501 (org-columns-quit)))
17502 (goto-char pos)
17503 (move-marker pos nil)
17504 (when tbl
17505 (when (plist-get params :hlines)
17506 (setq tmp nil)
17507 (while tbl
17508 (if (eq (car tbl) 'hline)
17509 (push (pop tbl) tmp)
17510 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17511 (if (and (not (eq (car tmp) 'hline))
17512 (or (eq hlines t)
17513 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17514 (push 'hline tmp)))
17515 (push (pop tbl) tmp)))
17516 (setq tbl (nreverse tmp)))
17517 (when vlines
17518 (setq tbl (mapcar (lambda (x)
17519 (if (eq 'hline x) x (cons "" x)))
17520 tbl))
17521 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17522 (setq pos (point))
17523 (insert (org-listtable-to-string tbl))
17524 (when (plist-get params :width)
17525 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17526 org-columns-current-widths "|")))
17527 (goto-char pos)
17528 (org-table-align))))
17530 (defun org-listtable-to-string (tbl)
17531 "Convert a listtable TBL to a string that contains the Org-mode table.
17532 The table still need to be alligned. The resulting string has no leading
17533 and tailing newline characters."
17534 (mapconcat
17535 (lambda (x)
17536 (cond
17537 ((listp x)
17538 (concat "|" (mapconcat 'identity x "|") "|"))
17539 ((eq x 'hline) "|-|")
17540 (t (error "Garbage in listtable: %s" x))))
17541 tbl "\n"))
17543 (defun org-insert-columns-dblock ()
17544 "Create a dynamic block capturing a column view table."
17545 (interactive)
17546 (let ((defaults '(:name "columnview" :hlines 1))
17547 (id (completing-read
17548 "Capture columns (local, global, entry with :ID: property) [local]: "
17549 (append '(("global") ("local"))
17550 (mapcar 'list (org-property-values "ID"))))))
17551 (if (equal id "") (setq id 'local))
17552 (if (equal id "global") (setq id 'global))
17553 (setq defaults (append defaults (list :id id)))
17554 (org-create-dblock defaults)
17555 (org-update-dblock)))
17557 ;;;; Timestamps
17559 (defvar org-last-changed-timestamp nil)
17560 (defvar org-time-was-given) ; dynamically scoped parameter
17561 (defvar org-end-time-was-given) ; dynamically scoped parameter
17562 (defvar org-ts-what) ; dynamically scoped parameter
17564 (defun org-time-stamp (arg)
17565 "Prompt for a date/time and insert a time stamp.
17566 If the user specifies a time like HH:MM, or if this command is called
17567 with a prefix argument, the time stamp will contain date and time.
17568 Otherwise, only the date will be included. All parts of a date not
17569 specified by the user will be filled in from the current date/time.
17570 So if you press just return without typing anything, the time stamp
17571 will represent the current date/time. If there is already a timestamp
17572 at the cursor, it will be modified."
17573 (interactive "P")
17574 (let* ((ts nil)
17575 (default-time
17576 ;; Default time is either today, or, when entering a range,
17577 ;; the range start.
17578 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17579 (save-excursion
17580 (re-search-backward
17581 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17582 (- (point) 20) t)))
17583 (apply 'encode-time (org-parse-time-string (match-string 1)))
17584 (current-time)))
17585 (default-input (and ts (org-get-compact-tod ts)))
17586 org-time-was-given org-end-time-was-given time)
17587 (cond
17588 ((and (org-at-timestamp-p)
17589 (eq last-command 'org-time-stamp)
17590 (eq this-command 'org-time-stamp))
17591 (insert "--")
17592 (setq time (let ((this-command this-command))
17593 (org-read-date arg 'totime nil nil default-time default-input)))
17594 (org-insert-time-stamp time (or org-time-was-given arg)))
17595 ((org-at-timestamp-p)
17596 (setq time (let ((this-command this-command))
17597 (org-read-date arg 'totime nil nil default-time default-input)))
17598 (when (org-at-timestamp-p) ; just to get the match data
17599 (replace-match "")
17600 (setq org-last-changed-timestamp
17601 (org-insert-time-stamp
17602 time (or org-time-was-given arg)
17603 nil nil nil (list org-end-time-was-given))))
17604 (message "Timestamp updated"))
17606 (setq time (let ((this-command this-command))
17607 (org-read-date arg 'totime nil nil default-time default-input)))
17608 (org-insert-time-stamp time (or org-time-was-given arg)
17609 nil nil nil (list org-end-time-was-given))))))
17611 ;; FIXME: can we use this for something else????
17612 ;; like computing time differences?????
17613 (defun org-get-compact-tod (s)
17614 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17615 (let* ((t1 (match-string 1 s))
17616 (h1 (string-to-number (match-string 2 s)))
17617 (m1 (string-to-number (match-string 3 s)))
17618 (t2 (and (match-end 4) (match-string 5 s)))
17619 (h2 (and t2 (string-to-number (match-string 6 s))))
17620 (m2 (and t2 (string-to-number (match-string 7 s))))
17621 dh dm)
17622 (if (not t2)
17624 (setq dh (- h2 h1) dm (- m2 m1))
17625 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17626 (concat t1 "+" (number-to-string dh)
17627 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17629 (defun org-time-stamp-inactive (&optional arg)
17630 "Insert an inactive time stamp.
17631 An inactive time stamp is enclosed in square brackets instead of angle
17632 brackets. It is inactive in the sense that it does not trigger agenda entries,
17633 does not link to the calendar and cannot be changed with the S-cursor keys.
17634 So these are more for recording a certain time/date."
17635 (interactive "P")
17636 (let (org-time-was-given org-end-time-was-given time)
17637 (setq time (org-read-date arg 'totime))
17638 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17639 nil nil (list org-end-time-was-given))))
17641 (defvar org-date-ovl (org-make-overlay 1 1))
17642 (org-overlay-put org-date-ovl 'face 'org-warning)
17643 (org-detach-overlay org-date-ovl)
17645 (defvar org-ans1) ; dynamically scoped parameter
17646 (defvar org-ans2) ; dynamically scoped parameter
17648 (defvar org-plain-time-of-day-regexp) ; defined below
17650 (defvar org-read-date-overlay nil)
17651 (defvar org-dcst nil) ; dynamically scoped
17653 (defun org-read-date (&optional with-time to-time from-string prompt
17654 default-time default-input)
17655 "Read a date, possibly a time, and make things smooth for the user.
17656 The prompt will suggest to enter an ISO date, but you can also enter anything
17657 which will at least partially be understood by `parse-time-string'.
17658 Unrecognized parts of the date will default to the current day, month, year,
17659 hour and minute. If this command is called to replace a timestamp at point,
17660 of to enter the second timestamp of a range, the default time is taken from the
17661 existing stamp. For example,
17662 3-2-5 --> 2003-02-05
17663 feb 15 --> currentyear-02-15
17664 sep 12 9 --> 2009-09-12
17665 12:45 --> today 12:45
17666 22 sept 0:34 --> currentyear-09-22 0:34
17667 12 --> currentyear-currentmonth-12
17668 Fri --> nearest Friday (today or later)
17669 etc.
17671 Furthermore you can specify a relative date by giving, as the *first* thing
17672 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17673 change in days weeks, months, years.
17674 With a single plus or minus, the date is relative to today. With a double
17675 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17676 +4d --> four days from today
17677 +4 --> same as above
17678 +2w --> two weeks from today
17679 ++5 --> five days from default date
17681 The function understands only English month and weekday abbreviations,
17682 but this can be configured with the variables `parse-time-months' and
17683 `parse-time-weekdays'.
17685 While prompting, a calendar is popped up - you can also select the
17686 date with the mouse (button 1). The calendar shows a period of three
17687 months. To scroll it to other months, use the keys `>' and `<'.
17688 If you don't like the calendar, turn it off with
17689 \(setq org-read-date-popup-calendar nil)
17691 With optional argument TO-TIME, the date will immediately be converted
17692 to an internal time.
17693 With an optional argument WITH-TIME, the prompt will suggest to also
17694 insert a time. Note that when WITH-TIME is not set, you can still
17695 enter a time, and this function will inform the calling routine about
17696 this change. The calling routine may then choose to change the format
17697 used to insert the time stamp into the buffer to include the time.
17698 With optional argument FROM-STRING, read from this string instead from
17699 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17700 the time/date that is used for everything that is not specified by the
17701 user."
17702 (require 'parse-time)
17703 (let* ((org-time-stamp-rounding-minutes
17704 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17705 (org-dcst org-display-custom-times)
17706 (ct (org-current-time))
17707 (def (or default-time ct))
17708 (defdecode (decode-time def))
17709 (dummy (progn
17710 (when (< (nth 2 defdecode) org-extend-today-until)
17711 (setcar (nthcdr 2 defdecode) -1)
17712 (setcar (nthcdr 1 defdecode) 59)
17713 (setq def (apply 'encode-time defdecode)
17714 defdecode (decode-time def)))))
17715 (calendar-move-hook nil)
17716 (view-diary-entries-initially nil)
17717 (view-calendar-holidays-initially nil)
17718 (timestr (format-time-string
17719 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17720 (prompt (concat (if prompt (concat prompt " ") "")
17721 (format "Date+time [%s]: " timestr)))
17722 ans (org-ans0 "") org-ans1 org-ans2 final)
17724 (cond
17725 (from-string (setq ans from-string))
17726 (org-read-date-popup-calendar
17727 (save-excursion
17728 (save-window-excursion
17729 (calendar)
17730 (calendar-forward-day (- (time-to-days def)
17731 (calendar-absolute-from-gregorian
17732 (calendar-current-date))))
17733 (org-eval-in-calendar nil t)
17734 (let* ((old-map (current-local-map))
17735 (map (copy-keymap calendar-mode-map))
17736 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17737 (org-defkey map (kbd "RET") 'org-calendar-select)
17738 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17739 'org-calendar-select-mouse)
17740 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17741 'org-calendar-select-mouse)
17742 (org-defkey minibuffer-local-map [(meta shift left)]
17743 (lambda () (interactive)
17744 (org-eval-in-calendar '(calendar-backward-month 1))))
17745 (org-defkey minibuffer-local-map [(meta shift right)]
17746 (lambda () (interactive)
17747 (org-eval-in-calendar '(calendar-forward-month 1))))
17748 (org-defkey minibuffer-local-map [(meta shift up)]
17749 (lambda () (interactive)
17750 (org-eval-in-calendar '(calendar-backward-year 1))))
17751 (org-defkey minibuffer-local-map [(meta shift down)]
17752 (lambda () (interactive)
17753 (org-eval-in-calendar '(calendar-forward-year 1))))
17754 (org-defkey minibuffer-local-map [(shift up)]
17755 (lambda () (interactive)
17756 (org-eval-in-calendar '(calendar-backward-week 1))))
17757 (org-defkey minibuffer-local-map [(shift down)]
17758 (lambda () (interactive)
17759 (org-eval-in-calendar '(calendar-forward-week 1))))
17760 (org-defkey minibuffer-local-map [(shift left)]
17761 (lambda () (interactive)
17762 (org-eval-in-calendar '(calendar-backward-day 1))))
17763 (org-defkey minibuffer-local-map [(shift right)]
17764 (lambda () (interactive)
17765 (org-eval-in-calendar '(calendar-forward-day 1))))
17766 (org-defkey minibuffer-local-map ">"
17767 (lambda () (interactive)
17768 (org-eval-in-calendar '(scroll-calendar-left 1))))
17769 (org-defkey minibuffer-local-map "<"
17770 (lambda () (interactive)
17771 (org-eval-in-calendar '(scroll-calendar-right 1))))
17772 (unwind-protect
17773 (progn
17774 (use-local-map map)
17775 (add-hook 'post-command-hook 'org-read-date-display)
17776 (setq org-ans0 (read-string prompt default-input nil nil))
17777 ;; org-ans0: from prompt
17778 ;; org-ans1: from mouse click
17779 ;; org-ans2: from calendar motion
17780 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17781 (remove-hook 'post-command-hook 'org-read-date-display)
17782 (use-local-map old-map)
17783 (when org-read-date-overlay
17784 (org-delete-overlay org-read-date-overlay)
17785 (setq org-read-date-overlay nil)))))))
17787 (t ; Naked prompt only
17788 (unwind-protect
17789 (setq ans (read-string prompt default-input nil timestr))
17790 (when org-read-date-overlay
17791 (org-delete-overlay org-read-date-overlay)
17792 (setq org-read-date-overlay nil)))))
17794 (setq final (org-read-date-analyze ans def defdecode))
17796 (if to-time
17797 (apply 'encode-time final)
17798 (if (and (boundp 'org-time-was-given) org-time-was-given)
17799 (format "%04d-%02d-%02d %02d:%02d"
17800 (nth 5 final) (nth 4 final) (nth 3 final)
17801 (nth 2 final) (nth 1 final))
17802 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17803 (defvar def)
17804 (defvar defdecode)
17805 (defvar with-time)
17806 (defun org-read-date-display ()
17807 "Display the currrent date prompt interpretation in the minibuffer."
17808 (when org-read-date-display-live
17809 (when org-read-date-overlay
17810 (org-delete-overlay org-read-date-overlay))
17811 (let ((p (point)))
17812 (end-of-line 1)
17813 (while (not (equal (buffer-substring
17814 (max (point-min) (- (point) 4)) (point))
17815 " "))
17816 (insert " "))
17817 (goto-char p))
17818 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17819 " " (or org-ans1 org-ans2)))
17820 (org-end-time-was-given nil)
17821 (f (org-read-date-analyze ans def defdecode))
17822 (fmts (if org-dcst
17823 org-time-stamp-custom-formats
17824 org-time-stamp-formats))
17825 (fmt (if (or with-time
17826 (and (boundp 'org-time-was-given) org-time-was-given))
17827 (cdr fmts)
17828 (car fmts)))
17829 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17830 (when (and org-end-time-was-given
17831 (string-match org-plain-time-of-day-regexp txt))
17832 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17833 org-end-time-was-given
17834 (substring txt (match-end 0)))))
17835 (setq org-read-date-overlay
17836 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17837 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17839 (defun org-read-date-analyze (ans def defdecode)
17840 "Analyze the combined answer of the date prompt."
17841 ;; FIXME: cleanup and comment
17842 (let (delta deltan deltaw deltadef year month day
17843 hour minute second wday pm h2 m2 tl wday1)
17845 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17846 (setq ans (replace-match "" t t ans)
17847 deltan (car delta)
17848 deltaw (nth 1 delta)
17849 deltadef (nth 2 delta)))
17851 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17852 (when (string-match
17853 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17854 (setq year (if (match-end 2)
17855 (string-to-number (match-string 2 ans))
17856 (string-to-number (format-time-string "%Y")))
17857 month (string-to-number (match-string 3 ans))
17858 day (string-to-number (match-string 4 ans)))
17859 (if (< year 100) (setq year (+ 2000 year)))
17860 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17861 t nil ans)))
17862 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17863 ;; If there is a time with am/pm, and *no* time without it, we convert
17864 ;; so that matching will be successful.
17865 (loop for i from 1 to 2 do ; twice, for end time as well
17866 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17867 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17868 (setq hour (string-to-number (match-string 1 ans))
17869 minute (if (match-end 3)
17870 (string-to-number (match-string 3 ans))
17872 pm (equal ?p
17873 (string-to-char (downcase (match-string 4 ans)))))
17874 (if (and (= hour 12) (not pm))
17875 (setq hour 0)
17876 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17877 (setq ans (replace-match (format "%02d:%02d" hour minute)
17878 t t ans))))
17880 ;; Check if a time range is given as a duration
17881 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17882 (setq hour (string-to-number (match-string 1 ans))
17883 h2 (+ hour (string-to-number (match-string 3 ans)))
17884 minute (string-to-number (match-string 2 ans))
17885 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17886 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17887 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17889 ;; Check if there is a time range
17890 (when (boundp 'org-end-time-was-given)
17891 (setq org-time-was-given nil)
17892 (when (and (string-match org-plain-time-of-day-regexp ans)
17893 (match-end 8))
17894 (setq org-end-time-was-given (match-string 8 ans))
17895 (setq ans (concat (substring ans 0 (match-beginning 7))
17896 (substring ans (match-end 7))))))
17898 (setq tl (parse-time-string ans)
17899 day (or (nth 3 tl) (nth 3 defdecode))
17900 month (or (nth 4 tl)
17901 (if (and org-read-date-prefer-future
17902 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17903 (1+ (nth 4 defdecode))
17904 (nth 4 defdecode)))
17905 year (or (nth 5 tl)
17906 (if (and org-read-date-prefer-future
17907 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17908 (1+ (nth 5 defdecode))
17909 (nth 5 defdecode)))
17910 hour (or (nth 2 tl) (nth 2 defdecode))
17911 minute (or (nth 1 tl) (nth 1 defdecode))
17912 second (or (nth 0 tl) 0)
17913 wday (nth 6 tl))
17914 (when deltan
17915 (unless deltadef
17916 (let ((now (decode-time (current-time))))
17917 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17918 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17919 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17920 ((equal deltaw "m") (setq month (+ month deltan)))
17921 ((equal deltaw "y") (setq year (+ year deltan)))))
17922 (when (and wday (not (nth 3 tl)))
17923 ;; Weekday was given, but no day, so pick that day in the week
17924 ;; on or after the derived date.
17925 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17926 (unless (equal wday wday1)
17927 (setq day (+ day (% (- wday wday1 -7) 7)))))
17928 (if (and (boundp 'org-time-was-given)
17929 (nth 2 tl))
17930 (setq org-time-was-given t))
17931 (if (< year 100) (setq year (+ 2000 year)))
17932 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17933 (list second minute hour day month year)))
17935 (defvar parse-time-weekdays)
17937 (defun org-read-date-get-relative (s today default)
17938 "Check string S for special relative date string.
17939 TODAY and DEFAULT are internal times, for today and for a default.
17940 Return shift list (N what def-flag)
17941 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17942 N is the number of WHATs to shift.
17943 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17944 the DEFAULT date rather than TODAY."
17945 (when (string-match
17946 (concat
17947 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17948 "\\([0-9]+\\)?"
17949 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17950 "\\([ \t]\\|$\\)") s)
17951 (let* ((dir (if (match-end 1)
17952 (string-to-char (substring (match-string 1 s) -1))
17953 ?+))
17954 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17955 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17956 (what (if (match-end 3) (match-string 3 s) "d"))
17957 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17958 (date (if rel default today))
17959 (wday (nth 6 (decode-time date)))
17960 delta)
17961 (if wday1
17962 (progn
17963 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17964 (if (= dir ?-) (setq delta (- delta 7)))
17965 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17966 (list delta "d" rel))
17967 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17969 (defun org-eval-in-calendar (form &optional keepdate)
17970 "Eval FORM in the calendar window and return to current window.
17971 Also, store the cursor date in variable org-ans2."
17972 (let ((sw (selected-window)))
17973 (select-window (get-buffer-window "*Calendar*"))
17974 (eval form)
17975 (when (and (not keepdate) (calendar-cursor-to-date))
17976 (let* ((date (calendar-cursor-to-date))
17977 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17978 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17979 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17980 (select-window sw)))
17982 ; ;; Update the prompt to show new default date
17983 ; (save-excursion
17984 ; (goto-char (point-min))
17985 ; (when (and org-ans2
17986 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17987 ; (get-text-property (match-end 0) 'field))
17988 ; (let ((inhibit-read-only t))
17989 ; (replace-match (concat "[" org-ans2 "]") t t)
17990 ; (add-text-properties (point-min) (1+ (match-end 0))
17991 ; (text-properties-at (1+ (point-min)))))))))
17993 (defun org-calendar-select ()
17994 "Return to `org-read-date' with the date currently selected.
17995 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17996 (interactive)
17997 (when (calendar-cursor-to-date)
17998 (let* ((date (calendar-cursor-to-date))
17999 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18000 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18001 (if (active-minibuffer-window) (exit-minibuffer))))
18003 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18004 "Insert a date stamp for the date given by the internal TIME.
18005 WITH-HM means, use the stamp format that includes the time of the day.
18006 INACTIVE means use square brackets instead of angular ones, so that the
18007 stamp will not contribute to the agenda.
18008 PRE and POST are optional strings to be inserted before and after the
18009 stamp.
18010 The command returns the inserted time stamp."
18011 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18012 stamp)
18013 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18014 (insert-before-markers (or pre ""))
18015 (insert-before-markers (setq stamp (format-time-string fmt time)))
18016 (when (listp extra)
18017 (setq extra (car extra))
18018 (if (and (stringp extra)
18019 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18020 (setq extra (format "-%02d:%02d"
18021 (string-to-number (match-string 1 extra))
18022 (string-to-number (match-string 2 extra))))
18023 (setq extra nil)))
18024 (when extra
18025 (backward-char 1)
18026 (insert-before-markers extra)
18027 (forward-char 1))
18028 (insert-before-markers (or post ""))
18029 stamp))
18031 (defun org-toggle-time-stamp-overlays ()
18032 "Toggle the use of custom time stamp formats."
18033 (interactive)
18034 (setq org-display-custom-times (not org-display-custom-times))
18035 (unless org-display-custom-times
18036 (let ((p (point-min)) (bmp (buffer-modified-p)))
18037 (while (setq p (next-single-property-change p 'display))
18038 (if (and (get-text-property p 'display)
18039 (eq (get-text-property p 'face) 'org-date))
18040 (remove-text-properties
18041 p (setq p (next-single-property-change p 'display))
18042 '(display t))))
18043 (set-buffer-modified-p bmp)))
18044 (if (featurep 'xemacs)
18045 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18046 (org-restart-font-lock)
18047 (setq org-table-may-need-update t)
18048 (if org-display-custom-times
18049 (message "Time stamps are overlayed with custom format")
18050 (message "Time stamp overlays removed")))
18052 (defun org-display-custom-time (beg end)
18053 "Overlay modified time stamp format over timestamp between BED and END."
18054 (let* ((ts (buffer-substring beg end))
18055 t1 w1 with-hm tf time str w2 (off 0))
18056 (save-match-data
18057 (setq t1 (org-parse-time-string ts t))
18058 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
18059 (setq off (- (match-end 0) (match-beginning 0)))))
18060 (setq end (- end off))
18061 (setq w1 (- end beg)
18062 with-hm (and (nth 1 t1) (nth 2 t1))
18063 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18064 time (org-fix-decoded-time t1)
18065 str (org-add-props
18066 (format-time-string
18067 (substring tf 1 -1) (apply 'encode-time time))
18068 nil 'mouse-face 'highlight)
18069 w2 (length str))
18070 (if (not (= w2 w1))
18071 (add-text-properties (1+ beg) (+ 2 beg)
18072 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18073 (if (featurep 'xemacs)
18074 (progn
18075 (put-text-property beg end 'invisible t)
18076 (put-text-property beg end 'end-glyph (make-glyph str)))
18077 (put-text-property beg end 'display str))))
18079 (defun org-translate-time (string)
18080 "Translate all timestamps in STRING to custom format.
18081 But do this only if the variable `org-display-custom-times' is set."
18082 (when org-display-custom-times
18083 (save-match-data
18084 (let* ((start 0)
18085 (re org-ts-regexp-both)
18086 t1 with-hm inactive tf time str beg end)
18087 (while (setq start (string-match re string start))
18088 (setq beg (match-beginning 0)
18089 end (match-end 0)
18090 t1 (save-match-data
18091 (org-parse-time-string (substring string beg end) t))
18092 with-hm (and (nth 1 t1) (nth 2 t1))
18093 inactive (equal (substring string beg (1+ beg)) "[")
18094 tf (funcall (if with-hm 'cdr 'car)
18095 org-time-stamp-custom-formats)
18096 time (org-fix-decoded-time t1)
18097 str (format-time-string
18098 (concat
18099 (if inactive "[" "<") (substring tf 1 -1)
18100 (if inactive "]" ">"))
18101 (apply 'encode-time time))
18102 string (replace-match str t t string)
18103 start (+ start (length str)))))))
18104 string)
18106 (defun org-fix-decoded-time (time)
18107 "Set 0 instead of nil for the first 6 elements of time.
18108 Don't touch the rest."
18109 (let ((n 0))
18110 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18112 (defun org-days-to-time (timestamp-string)
18113 "Difference between TIMESTAMP-STRING and now in days."
18114 (- (time-to-days (org-time-string-to-time timestamp-string))
18115 (time-to-days (current-time))))
18117 (defun org-deadline-close (timestamp-string &optional ndays)
18118 "Is the time in TIMESTAMP-STRING close to the current date?"
18119 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18120 (and (< (org-days-to-time timestamp-string) ndays)
18121 (not (org-entry-is-done-p))))
18123 (defun org-get-wdays (ts)
18124 "Get the deadline lead time appropriate for timestring TS."
18125 (cond
18126 ((<= org-deadline-warning-days 0)
18127 ;; 0 or negative, enforce this value no matter what
18128 (- org-deadline-warning-days))
18129 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18130 ;; lead time is specified.
18131 (floor (* (string-to-number (match-string 1 ts))
18132 (cdr (assoc (match-string 2 ts)
18133 '(("d" . 1) ("w" . 7)
18134 ("m" . 30.4) ("y" . 365.25)))))))
18135 ;; go for the default.
18136 (t org-deadline-warning-days)))
18138 (defun org-calendar-select-mouse (ev)
18139 "Return to `org-read-date' with the date currently selected.
18140 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18141 (interactive "e")
18142 (mouse-set-point ev)
18143 (when (calendar-cursor-to-date)
18144 (let* ((date (calendar-cursor-to-date))
18145 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18146 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18147 (if (active-minibuffer-window) (exit-minibuffer))))
18149 (defun org-check-deadlines (ndays)
18150 "Check if there are any deadlines due or past due.
18151 A deadline is considered due if it happens within `org-deadline-warning-days'
18152 days from today's date. If the deadline appears in an entry marked DONE,
18153 it is not shown. The prefix arg NDAYS can be used to test that many
18154 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18155 (interactive "P")
18156 (let* ((org-warn-days
18157 (cond
18158 ((equal ndays '(4)) 100000)
18159 (ndays (prefix-numeric-value ndays))
18160 (t (abs org-deadline-warning-days))))
18161 (case-fold-search nil)
18162 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18163 (callback
18164 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18166 (message "%d deadlines past-due or due within %d days"
18167 (org-occur regexp nil callback)
18168 org-warn-days)))
18170 (defun org-check-before-date (date)
18171 "Check if there are deadlines or scheduled entries before DATE."
18172 (interactive (list (org-read-date)))
18173 (let ((case-fold-search nil)
18174 (regexp (concat "\\<\\(" org-deadline-string
18175 "\\|" org-scheduled-string
18176 "\\) *<\\([^>]+\\)>"))
18177 (callback
18178 (lambda () (time-less-p
18179 (org-time-string-to-time (match-string 2))
18180 (org-time-string-to-time date)))))
18181 (message "%d entries before %s"
18182 (org-occur regexp nil callback) date)))
18184 (defun org-evaluate-time-range (&optional to-buffer)
18185 "Evaluate a time range by computing the difference between start and end.
18186 Normally the result is just printed in the echo area, but with prefix arg
18187 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18188 If the time range is actually in a table, the result is inserted into the
18189 next column.
18190 For time difference computation, a year is assumed to be exactly 365
18191 days in order to avoid rounding problems."
18192 (interactive "P")
18194 (org-clock-update-time-maybe)
18195 (save-excursion
18196 (unless (org-at-date-range-p t)
18197 (goto-char (point-at-bol))
18198 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18199 (if (not (org-at-date-range-p t))
18200 (error "Not at a time-stamp range, and none found in current line")))
18201 (let* ((ts1 (match-string 1))
18202 (ts2 (match-string 2))
18203 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18204 (match-end (match-end 0))
18205 (time1 (org-time-string-to-time ts1))
18206 (time2 (org-time-string-to-time ts2))
18207 (t1 (time-to-seconds time1))
18208 (t2 (time-to-seconds time2))
18209 (diff (abs (- t2 t1)))
18210 (negative (< (- t2 t1) 0))
18211 ;; (ys (floor (* 365 24 60 60)))
18212 (ds (* 24 60 60))
18213 (hs (* 60 60))
18214 (fy "%dy %dd %02d:%02d")
18215 (fy1 "%dy %dd")
18216 (fd "%dd %02d:%02d")
18217 (fd1 "%dd")
18218 (fh "%02d:%02d")
18219 y d h m align)
18220 (if havetime
18221 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18223 d (floor (/ diff ds)) diff (mod diff ds)
18224 h (floor (/ diff hs)) diff (mod diff hs)
18225 m (floor (/ diff 60)))
18226 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18228 d (floor (+ (/ diff ds) 0.5))
18229 h 0 m 0))
18230 (if (not to-buffer)
18231 (message "%s" (org-make-tdiff-string y d h m))
18232 (if (org-at-table-p)
18233 (progn
18234 (goto-char match-end)
18235 (setq align t)
18236 (and (looking-at " *|") (goto-char (match-end 0))))
18237 (goto-char match-end))
18238 (if (looking-at
18239 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18240 (replace-match ""))
18241 (if negative (insert " -"))
18242 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18243 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18244 (insert " " (format fh h m))))
18245 (if align (org-table-align))
18246 (message "Time difference inserted")))))
18248 (defun org-make-tdiff-string (y d h m)
18249 (let ((fmt "")
18250 (l nil))
18251 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18252 l (push y l)))
18253 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18254 l (push d l)))
18255 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18256 l (push h l)))
18257 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18258 l (push m l)))
18259 (apply 'format fmt (nreverse l))))
18261 (defun org-time-string-to-time (s)
18262 (apply 'encode-time (org-parse-time-string s)))
18264 (defun org-time-string-to-absolute (s &optional daynr prefer)
18265 "Convert a time stamp to an absolute day number.
18266 If there is a specifyer for a cyclic time stamp, get the closest date to
18267 DAYNR."
18268 (cond
18269 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18270 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18271 daynr
18272 (+ daynr 1000)))
18273 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18274 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18275 (time-to-days (current-time))) (match-string 0 s)
18276 prefer))
18277 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18279 (defun org-time-from-absolute (d)
18280 "Return the time corresponding to date D.
18281 D may be an absolute day number, or a calendar-type list (month day year)."
18282 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18283 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18285 (defun org-calendar-holiday ()
18286 "List of holidays, for Diary display in Org-mode."
18287 (require 'holidays)
18288 (let ((hl (funcall
18289 (if (fboundp 'calendar-check-holidays)
18290 'calendar-check-holidays 'check-calendar-holidays) date)))
18291 (if hl (mapconcat 'identity hl "; "))))
18293 (defun org-diary-sexp-entry (sexp entry date)
18294 "Process a SEXP diary ENTRY for DATE."
18295 (require 'diary-lib)
18296 (let ((result (if calendar-debug-sexp
18297 (let ((stack-trace-on-error t))
18298 (eval (car (read-from-string sexp))))
18299 (condition-case nil
18300 (eval (car (read-from-string sexp)))
18301 (error
18302 (beep)
18303 (message "Bad sexp at line %d in %s: %s"
18304 (org-current-line)
18305 (buffer-file-name) sexp)
18306 (sleep-for 2))))))
18307 (cond ((stringp result) result)
18308 ((and (consp result)
18309 (stringp (cdr result))) (cdr result))
18310 (result entry)
18311 (t nil))))
18313 (defun org-diary-to-ical-string (frombuf)
18314 "Get iCalendar entries from diary entries in buffer FROMBUF.
18315 This uses the icalendar.el library."
18316 (let* ((tmpdir (if (featurep 'xemacs)
18317 (temp-directory)
18318 temporary-file-directory))
18319 (tmpfile (make-temp-name
18320 (expand-file-name "orgics" tmpdir)))
18321 buf rtn b e)
18322 (save-excursion
18323 (set-buffer frombuf)
18324 (icalendar-export-region (point-min) (point-max) tmpfile)
18325 (setq buf (find-buffer-visiting tmpfile))
18326 (set-buffer buf)
18327 (goto-char (point-min))
18328 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18329 (setq b (match-beginning 0)))
18330 (goto-char (point-max))
18331 (if (re-search-backward "^END:VEVENT" nil t)
18332 (setq e (match-end 0)))
18333 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18334 (kill-buffer buf)
18335 (kill-buffer frombuf)
18336 (delete-file tmpfile)
18337 rtn))
18339 (defun org-closest-date (start current change prefer)
18340 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18341 When PREFER is `past' return a date that is either CURRENT or past.
18342 When PREFER is `future', return a date that is either CURRENT or future."
18343 ;; Make the proper lists from the dates
18344 (catch 'exit
18345 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18346 dn dw sday cday n1 n2
18347 d m y y1 y2 date1 date2 nmonths nm ny m2)
18349 (setq start (org-date-to-gregorian start)
18350 current (org-date-to-gregorian
18351 (if org-agenda-repeating-timestamp-show-all
18352 current
18353 (time-to-days (current-time))))
18354 sday (calendar-absolute-from-gregorian start)
18355 cday (calendar-absolute-from-gregorian current))
18357 (if (<= cday sday) (throw 'exit sday))
18359 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18360 (setq dn (string-to-number (match-string 1 change))
18361 dw (cdr (assoc (match-string 2 change) a1)))
18362 (error "Invalid change specifyer: %s" change))
18363 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18364 (cond
18365 ((eq dw 'day)
18366 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18367 n2 (+ n1 dn)))
18368 ((eq dw 'year)
18369 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18370 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18371 (setq date1 (list m d y1)
18372 n1 (calendar-absolute-from-gregorian date1)
18373 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18374 n2 (calendar-absolute-from-gregorian date2)))
18375 ((eq dw 'month)
18376 ;; approx number of month between the tow dates
18377 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18378 ;; How often does dn fit in there?
18379 (setq d (nth 1 start) m (car start) y (nth 2 start)
18380 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18381 m (+ m nm)
18382 ny (floor (/ m 12))
18383 y (+ y ny)
18384 m (- m (* ny 12)))
18385 (while (> m 12) (setq m (- m 12) y (1+ y)))
18386 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18387 (setq m2 (+ m dn) y2 y)
18388 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18389 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18390 (while (< n2 cday)
18391 (setq n1 n2 m m2 y y2)
18392 (setq m2 (+ m dn) y2 y)
18393 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18394 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18396 (if org-agenda-repeating-timestamp-show-all
18397 (cond
18398 ((eq prefer 'past) n1)
18399 ((eq prefer 'future) (if (= cday n1) n1 n2))
18400 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18401 (cond
18402 ((eq prefer 'past) n1)
18403 ((eq prefer 'future) (if (= cday n1) n1 n2))
18404 (t (if (= cday n1) n1 n2)))))))
18406 (defun org-date-to-gregorian (date)
18407 "Turn any specification of DATE into a gregorian date for the calendar."
18408 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18409 ((and (listp date) (= (length date) 3)) date)
18410 ((stringp date)
18411 (setq date (org-parse-time-string date))
18412 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18413 ((listp date)
18414 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18416 (defun org-parse-time-string (s &optional nodefault)
18417 "Parse the standard Org-mode time string.
18418 This should be a lot faster than the normal `parse-time-string'.
18419 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18420 hour and minute fields will be nil if not given."
18421 (if (string-match org-ts-regexp0 s)
18422 (list 0
18423 (if (or (match-beginning 8) (not nodefault))
18424 (string-to-number (or (match-string 8 s) "0")))
18425 (if (or (match-beginning 7) (not nodefault))
18426 (string-to-number (or (match-string 7 s) "0")))
18427 (string-to-number (match-string 4 s))
18428 (string-to-number (match-string 3 s))
18429 (string-to-number (match-string 2 s))
18430 nil nil nil)
18431 (make-list 9 0)))
18433 (defun org-timestamp-up (&optional arg)
18434 "Increase the date item at the cursor by one.
18435 If the cursor is on the year, change the year. If it is on the month or
18436 the day, change that.
18437 With prefix ARG, change by that many units."
18438 (interactive "p")
18439 (org-timestamp-change (prefix-numeric-value arg)))
18441 (defun org-timestamp-down (&optional arg)
18442 "Decrease the date item at the cursor by one.
18443 If the cursor is on the year, change the year. If it is on the month or
18444 the day, change that.
18445 With prefix ARG, change by that many units."
18446 (interactive "p")
18447 (org-timestamp-change (- (prefix-numeric-value arg))))
18449 (defun org-timestamp-up-day (&optional arg)
18450 "Increase the date in the time stamp by one day.
18451 With prefix ARG, change that many days."
18452 (interactive "p")
18453 (if (and (not (org-at-timestamp-p t))
18454 (org-on-heading-p))
18455 (org-todo 'up)
18456 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18458 (defun org-timestamp-down-day (&optional arg)
18459 "Decrease the date in the time stamp by one day.
18460 With prefix ARG, change that many days."
18461 (interactive "p")
18462 (if (and (not (org-at-timestamp-p t))
18463 (org-on-heading-p))
18464 (org-todo 'down)
18465 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18467 (defsubst org-pos-in-match-range (pos n)
18468 (and (match-beginning n)
18469 (<= (match-beginning n) pos)
18470 (>= (match-end n) pos)))
18472 (defun org-at-timestamp-p (&optional inactive-ok)
18473 "Determine if the cursor is in or at a timestamp."
18474 (interactive)
18475 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18476 (pos (point))
18477 (ans (or (looking-at tsr)
18478 (save-excursion
18479 (skip-chars-backward "^[<\n\r\t")
18480 (if (> (point) (point-min)) (backward-char 1))
18481 (and (looking-at tsr)
18482 (> (- (match-end 0) pos) -1))))))
18483 (and ans
18484 (boundp 'org-ts-what)
18485 (setq org-ts-what
18486 (cond
18487 ((= pos (match-beginning 0)) 'bracket)
18488 ((= pos (1- (match-end 0))) 'bracket)
18489 ((org-pos-in-match-range pos 2) 'year)
18490 ((org-pos-in-match-range pos 3) 'month)
18491 ((org-pos-in-match-range pos 7) 'hour)
18492 ((org-pos-in-match-range pos 8) 'minute)
18493 ((or (org-pos-in-match-range pos 4)
18494 (org-pos-in-match-range pos 5)) 'day)
18495 ((and (> pos (or (match-end 8) (match-end 5)))
18496 (< pos (match-end 0)))
18497 (- pos (or (match-end 8) (match-end 5))))
18498 (t 'day))))
18499 ans))
18501 (defun org-toggle-timestamp-type ()
18503 (interactive)
18504 (when (org-at-timestamp-p t)
18505 (save-excursion
18506 (goto-char (match-beginning 0))
18507 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18508 (goto-char (1- (match-end 0)))
18509 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18510 (message "Timestamp is now %sactive"
18511 (if (equal (char-before) ?>) "in" ""))))
18513 (defun org-timestamp-change (n &optional what)
18514 "Change the date in the time stamp at point.
18515 The date will be changed by N times WHAT. WHAT can be `day', `month',
18516 `year', `minute', `second'. If WHAT is not given, the cursor position
18517 in the timestamp determines what will be changed."
18518 (let ((pos (point))
18519 with-hm inactive
18520 org-ts-what
18521 extra
18522 ts time time0)
18523 (if (not (org-at-timestamp-p t))
18524 (error "Not at a timestamp"))
18525 (if (and (not what) (eq org-ts-what 'bracket))
18526 (org-toggle-timestamp-type)
18527 (if (and (not what) (not (eq org-ts-what 'day))
18528 org-display-custom-times
18529 (get-text-property (point) 'display)
18530 (not (get-text-property (1- (point)) 'display)))
18531 (setq org-ts-what 'day))
18532 (setq org-ts-what (or what org-ts-what)
18533 inactive (= (char-after (match-beginning 0)) ?\[)
18534 ts (match-string 0))
18535 (replace-match "")
18536 (if (string-match
18537 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18539 (setq extra (match-string 1 ts)))
18540 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18541 (setq with-hm t))
18542 (setq time0 (org-parse-time-string ts))
18543 (setq time
18544 (encode-time (or (car time0) 0)
18545 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18546 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18547 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18548 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18549 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18550 (nthcdr 6 time0)))
18551 (when (integerp org-ts-what)
18552 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18553 (if (eq what 'calendar)
18554 (let ((cal-date (org-get-date-from-calendar)))
18555 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18556 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18557 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18558 (setcar time0 (or (car time0) 0))
18559 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18560 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18561 (setq time (apply 'encode-time time0))))
18562 (setq org-last-changed-timestamp
18563 (org-insert-time-stamp time with-hm inactive nil nil extra))
18564 (org-clock-update-time-maybe)
18565 (goto-char pos)
18566 ;; Try to recenter the calendar window, if any
18567 (if (and org-calendar-follow-timestamp-change
18568 (get-buffer-window "*Calendar*" t)
18569 (memq org-ts-what '(day month year)))
18570 (org-recenter-calendar (time-to-days time))))))
18572 ;; FIXME: does not yet work for lead times
18573 (defun org-modify-ts-extra (s pos n)
18574 "Change the different parts of the lead-time and repeat fields in timestamp."
18575 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18576 ng h m new)
18577 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18578 (cond
18579 ((or (org-pos-in-match-range pos 2)
18580 (org-pos-in-match-range pos 3))
18581 (setq m (string-to-number (match-string 3 s))
18582 h (string-to-number (match-string 2 s)))
18583 (if (org-pos-in-match-range pos 2)
18584 (setq h (+ h n))
18585 (setq m (+ m n)))
18586 (if (< m 0) (setq m (+ m 60) h (1- h)))
18587 (if (> m 59) (setq m (- m 60) h (1+ h)))
18588 (setq h (min 24 (max 0 h)))
18589 (setq ng 1 new (format "-%02d:%02d" h m)))
18590 ((org-pos-in-match-range pos 6)
18591 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18592 ((org-pos-in-match-range pos 5)
18593 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18595 (when ng
18596 (setq s (concat
18597 (substring s 0 (match-beginning ng))
18599 (substring s (match-end ng))))))
18602 (defun org-recenter-calendar (date)
18603 "If the calendar is visible, recenter it to DATE."
18604 (let* ((win (selected-window))
18605 (cwin (get-buffer-window "*Calendar*" t))
18606 (calendar-move-hook nil))
18607 (when cwin
18608 (select-window cwin)
18609 (calendar-goto-date (if (listp date) date
18610 (calendar-gregorian-from-absolute date)))
18611 (select-window win))))
18613 (defun org-goto-calendar (&optional arg)
18614 "Go to the Emacs calendar at the current date.
18615 If there is a time stamp in the current line, go to that date.
18616 A prefix ARG can be used to force the current date."
18617 (interactive "P")
18618 (let ((tsr org-ts-regexp) diff
18619 (calendar-move-hook nil)
18620 (view-calendar-holidays-initially nil)
18621 (view-diary-entries-initially nil))
18622 (if (or (org-at-timestamp-p)
18623 (save-excursion
18624 (beginning-of-line 1)
18625 (looking-at (concat ".*" tsr))))
18626 (let ((d1 (time-to-days (current-time)))
18627 (d2 (time-to-days
18628 (org-time-string-to-time (match-string 1)))))
18629 (setq diff (- d2 d1))))
18630 (calendar)
18631 (calendar-goto-today)
18632 (if (and diff (not arg)) (calendar-forward-day diff))))
18634 (defun org-get-date-from-calendar ()
18635 "Return a list (month day year) of date at point in calendar."
18636 (with-current-buffer "*Calendar*"
18637 (save-match-data
18638 (calendar-cursor-to-date))))
18640 (defun org-date-from-calendar ()
18641 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18642 If there is already a time stamp at the cursor position, update it."
18643 (interactive)
18644 (if (org-at-timestamp-p t)
18645 (org-timestamp-change 0 'calendar)
18646 (let ((cal-date (org-get-date-from-calendar)))
18647 (org-insert-time-stamp
18648 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18650 (defvar appt-time-msg-list)
18652 ;;;###autoload
18653 (defun org-agenda-to-appt (&optional refresh filter)
18654 "Activate appointments found in `org-agenda-files'.
18655 With a \\[universal-argument] prefix, refresh the list of
18656 appointements.
18658 If FILTER is t, interactively prompt the user for a regular
18659 expression, and filter out entries that don't match it.
18661 If FILTER is a string, use this string as a regular expression
18662 for filtering entries out.
18664 FILTER can also be an alist with the car of each cell being
18665 either 'headline or 'category. For example:
18667 '((headline \"IMPORTANT\")
18668 (category \"Work\"))
18670 will only add headlines containing IMPORTANT or headlines
18671 belonging to the \"Work\" category."
18672 (interactive "P")
18673 (require 'calendar)
18674 (if refresh (setq appt-time-msg-list nil))
18675 (if (eq filter t)
18676 (setq filter (read-from-minibuffer "Regexp filter: ")))
18677 (let* ((cnt 0) ; count added events
18678 (org-agenda-new-buffers nil)
18679 (org-deadline-warning-days 0)
18680 (today (org-date-to-gregorian
18681 (time-to-days (current-time))))
18682 (files (org-agenda-files)) entries file)
18683 ;; Get all entries which may contain an appt
18684 (while (setq file (pop files))
18685 (setq entries
18686 (append entries
18687 (org-agenda-get-day-entries
18688 file today :timestamp :scheduled :deadline))))
18689 (setq entries (delq nil entries))
18690 ;; Map thru entries and find if we should filter them out
18691 (mapc
18692 (lambda(x)
18693 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18694 (cat (get-text-property 1 'org-category x))
18695 (tod (get-text-property 1 'time-of-day x))
18696 (ok (or (null filter)
18697 (and (stringp filter) (string-match filter evt))
18698 (and (listp filter)
18699 (or (string-match
18700 (cadr (assoc 'category filter)) cat)
18701 (string-match
18702 (cadr (assoc 'headline filter)) evt))))))
18703 ;; FIXME: Shall we remove text-properties for the appt text?
18704 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18705 (when (and ok tod)
18706 (setq tod (number-to-string tod)
18707 tod (when (string-match
18708 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18709 (concat (match-string 1 tod) ":"
18710 (match-string 2 tod))))
18711 (appt-add tod evt)
18712 (setq cnt (1+ cnt))))) entries)
18713 (org-release-buffers org-agenda-new-buffers)
18714 (if (eq cnt 0)
18715 (message "No event to add")
18716 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18718 ;;; The clock for measuring work time.
18720 (defvar org-mode-line-string "")
18721 (put 'org-mode-line-string 'risky-local-variable t)
18723 (defvar org-mode-line-timer nil)
18724 (defvar org-clock-heading "")
18725 (defvar org-clock-start-time "")
18727 (defun org-update-mode-line ()
18728 (let* ((delta (- (time-to-seconds (current-time))
18729 (time-to-seconds org-clock-start-time)))
18730 (h (floor delta 3600))
18731 (m (floor (- delta (* 3600 h)) 60)))
18732 (setq org-mode-line-string
18733 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18734 'help-echo "Org-mode clock is running"))
18735 (force-mode-line-update)))
18737 (defvar org-clock-marker (make-marker)
18738 "Marker recording the last clock-in.")
18739 (defvar org-clock-mode-line-entry nil
18740 "Information for the modeline about the running clock.")
18742 (defun org-clock-in ()
18743 "Start the clock on the current item.
18744 If necessary, clock-out of the currently active clock."
18745 (interactive)
18746 (org-clock-out t)
18747 (let (ts)
18748 (save-excursion
18749 (org-back-to-heading t)
18750 (when (and org-clock-in-switch-to-state
18751 (not (looking-at (concat outline-regexp "[ \t]*"
18752 org-clock-in-switch-to-state
18753 "\\>"))))
18754 (org-todo org-clock-in-switch-to-state))
18755 (if (and org-clock-heading-function
18756 (functionp org-clock-heading-function))
18757 (setq org-clock-heading (funcall org-clock-heading-function))
18758 (if (looking-at org-complex-heading-regexp)
18759 (setq org-clock-heading (match-string 4))
18760 (setq org-clock-heading "???")))
18761 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18762 (org-clock-find-position)
18764 (insert "\n") (backward-char 1)
18765 (indent-relative)
18766 (insert org-clock-string " ")
18767 (setq org-clock-start-time (current-time))
18768 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18769 (move-marker org-clock-marker (point) (buffer-base-buffer))
18770 (or global-mode-string (setq global-mode-string '("")))
18771 (or (memq 'org-mode-line-string global-mode-string)
18772 (setq global-mode-string
18773 (append global-mode-string '(org-mode-line-string))))
18774 (org-update-mode-line)
18775 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18776 (message "Clock started at %s" ts))))
18778 (defun org-clock-find-position ()
18779 "Find the location where the next clock line should be inserted."
18780 (org-back-to-heading t)
18781 (catch 'exit
18782 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18783 (re (concat "^[ \t]*" org-clock-string))
18784 (cnt 0)
18785 first last)
18786 (goto-char beg)
18787 (when (eobp) (newline) (setq end (max (point) end)))
18788 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18789 ;; we seem to have a CLOCK drawer, so go there.
18790 (beginning-of-line 2)
18791 (throw 'exit t))
18792 ;; Lets count the CLOCK lines
18793 (goto-char beg)
18794 (while (re-search-forward re end t)
18795 (setq first (or first (match-beginning 0))
18796 last (match-beginning 0)
18797 cnt (1+ cnt)))
18798 (when (and (integerp org-clock-into-drawer)
18799 (>= (1+ cnt) org-clock-into-drawer))
18800 ;; Wrap current entries into a new drawer
18801 (goto-char last)
18802 (beginning-of-line 2)
18803 (if (org-at-item-p) (org-end-of-item))
18804 (insert ":END:\n")
18805 (beginning-of-line 0)
18806 (org-indent-line-function)
18807 (goto-char first)
18808 (insert ":CLOCK:\n")
18809 (beginning-of-line 0)
18810 (org-indent-line-function)
18811 (org-flag-drawer t)
18812 (beginning-of-line 2)
18813 (throw 'exit nil))
18815 (goto-char beg)
18816 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18817 (not (equal (match-string 1) org-clock-string)))
18818 ;; Planning info, skip to after it
18819 (beginning-of-line 2)
18820 (or (bolp) (newline)))
18821 (when (eq t org-clock-into-drawer)
18822 (insert ":CLOCK:\n:END:\n")
18823 (beginning-of-line -1)
18824 (org-indent-line-function)
18825 (org-flag-drawer t)
18826 (beginning-of-line 2)
18827 (org-indent-line-function)))))
18829 (defun org-clock-out (&optional fail-quietly)
18830 "Stop the currently running clock.
18831 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18832 (interactive)
18833 (catch 'exit
18834 (if (not (marker-buffer org-clock-marker))
18835 (if fail-quietly (throw 'exit t) (error "No active clock")))
18836 (let (ts te s h m)
18837 (save-excursion
18838 (set-buffer (marker-buffer org-clock-marker))
18839 (goto-char org-clock-marker)
18840 (beginning-of-line 1)
18841 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18842 (equal (match-string 1) org-clock-string))
18843 (setq ts (match-string 2))
18844 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18845 (goto-char (match-end 0))
18846 (delete-region (point) (point-at-eol))
18847 (insert "--")
18848 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18849 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18850 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18851 h (floor (/ s 3600))
18852 s (- s (* 3600 h))
18853 m (floor (/ s 60))
18854 s (- s (* 60 s)))
18855 (insert " => " (format "%2d:%02d" h m))
18856 (move-marker org-clock-marker nil)
18857 (when org-log-note-clock-out
18858 (org-add-log-maybe 'clock-out))
18859 (when org-mode-line-timer
18860 (cancel-timer org-mode-line-timer)
18861 (setq org-mode-line-timer nil))
18862 (setq global-mode-string
18863 (delq 'org-mode-line-string global-mode-string))
18864 (force-mode-line-update)
18865 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18867 (defun org-clock-cancel ()
18868 "Cancel the running clock be removing the start timestamp."
18869 (interactive)
18870 (if (not (marker-buffer org-clock-marker))
18871 (error "No active clock"))
18872 (save-excursion
18873 (set-buffer (marker-buffer org-clock-marker))
18874 (goto-char org-clock-marker)
18875 (delete-region (1- (point-at-bol)) (point-at-eol)))
18876 (setq global-mode-string
18877 (delq 'org-mode-line-string global-mode-string))
18878 (force-mode-line-update)
18879 (message "Clock canceled"))
18881 (defun org-clock-goto (&optional delete-windows)
18882 "Go to the currently clocked-in entry."
18883 (interactive "P")
18884 (if (not (marker-buffer org-clock-marker))
18885 (error "No active clock"))
18886 (switch-to-buffer-other-window
18887 (marker-buffer org-clock-marker))
18888 (if delete-windows (delete-other-windows))
18889 (goto-char org-clock-marker)
18890 (org-show-entry)
18891 (org-back-to-heading)
18892 (recenter))
18894 (defvar org-clock-file-total-minutes nil
18895 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18896 (make-variable-buffer-local 'org-clock-file-total-minutes)
18898 (defun org-clock-sum (&optional tstart tend)
18899 "Sum the times for each subtree.
18900 Puts the resulting times in minutes as a text property on each headline."
18901 (interactive)
18902 (let* ((bmp (buffer-modified-p))
18903 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18904 org-clock-string
18905 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18906 (lmax 30)
18907 (ltimes (make-vector lmax 0))
18908 (t1 0)
18909 (level 0)
18910 ts te dt
18911 time)
18912 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18913 (save-excursion
18914 (goto-char (point-max))
18915 (while (re-search-backward re nil t)
18916 (cond
18917 ((match-end 2)
18918 ;; Two time stamps
18919 (setq ts (match-string 2)
18920 te (match-string 3)
18921 ts (time-to-seconds
18922 (apply 'encode-time (org-parse-time-string ts)))
18923 te (time-to-seconds
18924 (apply 'encode-time (org-parse-time-string te)))
18925 ts (if tstart (max ts tstart) ts)
18926 te (if tend (min te tend) te)
18927 dt (- te ts)
18928 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18929 ((match-end 4)
18930 ;; A naket time
18931 (setq t1 (+ t1 (string-to-number (match-string 5))
18932 (* 60 (string-to-number (match-string 4))))))
18933 (t ;; A headline
18934 (setq level (- (match-end 1) (match-beginning 1)))
18935 (when (or (> t1 0) (> (aref ltimes level) 0))
18936 (loop for l from 0 to level do
18937 (aset ltimes l (+ (aref ltimes l) t1)))
18938 (setq t1 0 time (aref ltimes level))
18939 (loop for l from level to (1- lmax) do
18940 (aset ltimes l 0))
18941 (goto-char (match-beginning 0))
18942 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18943 (setq org-clock-file-total-minutes (aref ltimes 0)))
18944 (set-buffer-modified-p bmp)))
18946 (defun org-clock-display (&optional total-only)
18947 "Show subtree times in the entire buffer.
18948 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18949 in the echo area."
18950 (interactive)
18951 (org-remove-clock-overlays)
18952 (let (time h m p)
18953 (org-clock-sum)
18954 (unless total-only
18955 (save-excursion
18956 (goto-char (point-min))
18957 (while (or (and (equal (setq p (point)) (point-min))
18958 (get-text-property p :org-clock-minutes))
18959 (setq p (next-single-property-change
18960 (point) :org-clock-minutes)))
18961 (goto-char p)
18962 (when (setq time (get-text-property p :org-clock-minutes))
18963 (org-put-clock-overlay time (funcall outline-level))))
18964 (setq h (/ org-clock-file-total-minutes 60)
18965 m (- org-clock-file-total-minutes (* 60 h)))
18966 ;; Arrange to remove the overlays upon next change.
18967 (when org-remove-highlights-with-change
18968 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18969 nil 'local))))
18970 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18972 (defvar org-clock-overlays nil)
18973 (make-variable-buffer-local 'org-clock-overlays)
18975 (defun org-put-clock-overlay (time &optional level)
18976 "Put an overlays on the current line, displaying TIME.
18977 If LEVEL is given, prefix time with a corresponding number of stars.
18978 This creates a new overlay and stores it in `org-clock-overlays', so that it
18979 will be easy to remove."
18980 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18981 (l (if level (org-get-legal-level level 0) 0))
18982 (off 0)
18983 ov tx)
18984 (move-to-column c)
18985 (unless (eolp) (skip-chars-backward "^ \t"))
18986 (skip-chars-backward " \t")
18987 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18988 tx (concat (buffer-substring (1- (point)) (point))
18989 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18990 (org-add-props (format "%s %2d:%02d%s"
18991 (make-string l ?*) h m
18992 (make-string (- 16 l) ?\ ))
18993 '(face secondary-selection))
18994 ""))
18995 (if (not (featurep 'xemacs))
18996 (org-overlay-put ov 'display tx)
18997 (org-overlay-put ov 'invisible t)
18998 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18999 (push ov org-clock-overlays)))
19001 (defun org-remove-clock-overlays (&optional beg end noremove)
19002 "Remove the occur highlights from the buffer.
19003 BEG and END are ignored. If NOREMOVE is nil, remove this function
19004 from the `before-change-functions' in the current buffer."
19005 (interactive)
19006 (unless org-inhibit-highlight-removal
19007 (mapc 'org-delete-overlay org-clock-overlays)
19008 (setq org-clock-overlays nil)
19009 (unless noremove
19010 (remove-hook 'before-change-functions
19011 'org-remove-clock-overlays 'local))))
19013 (defun org-clock-out-if-current ()
19014 "Clock out if the current entry contains the running clock.
19015 This is used to stop the clock after a TODO entry is marked DONE,
19016 and is only done if the variable `org-clock-out-when-done' is not nil."
19017 (when (and org-clock-out-when-done
19018 (member state org-done-keywords)
19019 (equal (marker-buffer org-clock-marker) (current-buffer))
19020 (< (point) org-clock-marker)
19021 (> (save-excursion (outline-next-heading) (point))
19022 org-clock-marker))
19023 ;; Clock out, but don't accept a logging message for this.
19024 (let ((org-log-note-clock-out nil))
19025 (org-clock-out))))
19027 (add-hook 'org-after-todo-state-change-hook
19028 'org-clock-out-if-current)
19030 (defun org-check-running-clock ()
19031 "Check if the current buffer contains the running clock.
19032 If yes, offer to stop it and to save the buffer with the changes."
19033 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19034 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19035 (buffer-name))))
19036 (org-clock-out)
19037 (when (y-or-n-p "Save changed buffer?")
19038 (save-buffer))))
19040 (defun org-clock-report (&optional arg)
19041 "Create a table containing a report about clocked time.
19042 If the cursor is inside an existing clocktable block, then the table
19043 will be updated. If not, a new clocktable will be inserted.
19044 When called with a prefix argument, move to the first clock table in the
19045 buffer and update it."
19046 (interactive "P")
19047 (org-remove-clock-overlays)
19048 (when arg
19049 (org-find-dblock "clocktable")
19050 (org-show-entry))
19051 (if (org-in-clocktable-p)
19052 (goto-char (org-in-clocktable-p))
19053 (org-create-dblock (list :name "clocktable"
19054 :maxlevel 2 :scope 'file)))
19055 (org-update-dblock))
19057 (defun org-in-clocktable-p ()
19058 "Check if the cursor is in a clocktable."
19059 (let ((pos (point)) start)
19060 (save-excursion
19061 (end-of-line 1)
19062 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19063 (setq start (match-beginning 0))
19064 (re-search-forward "^#\\+END:.*" nil t)
19065 (>= (match-end 0) pos)
19066 start))))
19068 (defun org-clock-update-time-maybe ()
19069 "If this is a CLOCK line, update it and return t.
19070 Otherwise, return nil."
19071 (interactive)
19072 (save-excursion
19073 (beginning-of-line 1)
19074 (skip-chars-forward " \t")
19075 (when (looking-at org-clock-string)
19076 (let ((re (concat "[ \t]*" org-clock-string
19077 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19078 "\\([ \t]*=>.*\\)?"))
19079 ts te h m s)
19080 (if (not (looking-at re))
19082 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19083 (end-of-line 1)
19084 (setq ts (match-string 1)
19085 te (match-string 2))
19086 (setq s (- (time-to-seconds
19087 (apply 'encode-time (org-parse-time-string te)))
19088 (time-to-seconds
19089 (apply 'encode-time (org-parse-time-string ts))))
19090 h (floor (/ s 3600))
19091 s (- s (* 3600 h))
19092 m (floor (/ s 60))
19093 s (- s (* 60 s)))
19094 (insert " => " (format "%2d:%02d" h m))
19095 t)))))
19097 (defun org-clock-special-range (key &optional time as-strings)
19098 "Return two times bordering a special time range.
19099 Key is a symbol specifying the range and can be one of `today', `yesterday',
19100 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19101 A week starts Monday 0:00 and ends Sunday 24:00.
19102 The range is determined relative to TIME. TIME defaults to the current time.
19103 The return value is a cons cell with two internal times like the ones
19104 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19105 the returned times will be formatted strings."
19106 (let* ((tm (decode-time (or time (current-time))))
19107 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19108 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19109 (dow (nth 6 tm))
19110 s1 m1 h1 d1 month1 y1 diff ts te fm)
19111 (cond
19112 ((eq key 'today)
19113 (setq h 0 m 0 h1 24 m1 0))
19114 ((eq key 'yesterday)
19115 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19116 ((eq key 'thisweek)
19117 (setq diff (if (= dow 0) 6 (1- dow))
19118 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19119 ((eq key 'lastweek)
19120 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19121 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19122 ((eq key 'thismonth)
19123 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19124 ((eq key 'lastmonth)
19125 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19126 ((eq key 'thisyear)
19127 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19128 ((eq key 'lastyear)
19129 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19130 (t (error "No such time block %s" key)))
19131 (setq ts (encode-time s m h d month y)
19132 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19133 (or d1 d) (or month1 month) (or y1 y)))
19134 (setq fm (cdr org-time-stamp-formats))
19135 (if as-strings
19136 (cons (format-time-string fm ts) (format-time-string fm te))
19137 (cons ts te))))
19139 (defun org-dblock-write:clocktable (params)
19140 "Write the standard clocktable."
19141 (catch 'exit
19142 (let* ((hlchars '((1 . "*") (2 . "/")))
19143 (ins (make-marker))
19144 (total-time nil)
19145 (scope (plist-get params :scope))
19146 (tostring (plist-get params :tostring))
19147 (multifile (plist-get params :multifile))
19148 (header (plist-get params :header))
19149 (maxlevel (or (plist-get params :maxlevel) 3))
19150 (step (plist-get params :step))
19151 (emph (plist-get params :emphasize))
19152 (ts (plist-get params :tstart))
19153 (te (plist-get params :tend))
19154 (block (plist-get params :block))
19155 ipos time h m p level hlc hdl
19156 cc beg end pos tbl)
19157 (when step
19158 (org-clocktable-steps params)
19159 (throw 'exit nil))
19160 (when block
19161 (setq cc (org-clock-special-range block nil t)
19162 ts (car cc) te (cdr cc)))
19163 (if ts (setq ts (time-to-seconds
19164 (apply 'encode-time (org-parse-time-string ts)))))
19165 (if te (setq te (time-to-seconds
19166 (apply 'encode-time (org-parse-time-string te)))))
19167 (move-marker ins (point))
19168 (setq ipos (point))
19170 ;; Get the right scope
19171 (setq pos (point))
19172 (save-restriction
19173 (cond
19174 ((not scope))
19175 ((eq scope 'file) (widen))
19176 ((eq scope 'subtree) (org-narrow-to-subtree))
19177 ((eq scope 'tree)
19178 (while (org-up-heading-safe))
19179 (org-narrow-to-subtree))
19180 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19181 (symbol-name scope)))
19182 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19183 (catch 'exit
19184 (while (org-up-heading-safe)
19185 (looking-at outline-regexp)
19186 (if (<= (org-reduced-level (funcall outline-level)) level)
19187 (throw 'exit nil))))
19188 (org-narrow-to-subtree))
19189 ((or (listp scope) (eq scope 'agenda))
19190 (let* ((files (if (listp scope) scope (org-agenda-files)))
19191 (scope 'agenda)
19192 (p1 (copy-sequence params))
19193 file)
19194 (plist-put p1 :tostring t)
19195 (plist-put p1 :multifile t)
19196 (plist-put p1 :scope 'file)
19197 (org-prepare-agenda-buffers files)
19198 (while (setq file (pop files))
19199 (with-current-buffer (find-buffer-visiting file)
19200 (push (org-clocktable-add-file
19201 file (org-dblock-write:clocktable p1)) tbl)
19202 (setq total-time (+ (or total-time 0)
19203 org-clock-file-total-minutes)))))))
19204 (goto-char pos)
19206 (unless (eq scope 'agenda)
19207 (org-clock-sum ts te)
19208 (goto-char (point-min))
19209 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19210 (goto-char p)
19211 (when (setq time (get-text-property p :org-clock-minutes))
19212 (save-excursion
19213 (beginning-of-line 1)
19214 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19215 (setq level (org-reduced-level
19216 (- (match-end 1) (match-beginning 1))))
19217 (<= level maxlevel))
19218 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19219 hdl (match-string 2)
19220 h (/ time 60)
19221 m (- time (* 60 h)))
19222 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19223 (push (concat
19224 "| " (int-to-string level) "|" hlc hdl hlc " |"
19225 (make-string (1- level) ?|)
19226 hlc (format "%d:%02d" h m) hlc
19227 " |") tbl))))))
19228 (setq tbl (nreverse tbl))
19229 (if tostring
19230 (if tbl (mapconcat 'identity tbl "\n") nil)
19231 (goto-char ins)
19232 (insert-before-markers
19233 (or header
19234 (concat
19235 "Clock summary at ["
19236 (substring
19237 (format-time-string (cdr org-time-stamp-formats))
19238 1 -1)
19239 "]."
19240 (if block
19241 (format " Considered range is /%s/." block)
19243 "\n\n"))
19244 (if (eq scope 'agenda) "|File" "")
19245 "|L|Headline|Time|\n")
19246 (setq total-time (or total-time org-clock-file-total-minutes)
19247 h (/ total-time 60)
19248 m (- total-time (* 60 h)))
19249 (insert-before-markers
19250 "|-\n|"
19251 (if (eq scope 'agenda) "|" "")
19253 "*Total time*| "
19254 (format "*%d:%02d*" h m)
19255 "|\n|-\n")
19256 (setq tbl (delq nil tbl))
19257 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19258 (equal (substring (car tbl) 0 2) "|-"))
19259 (pop tbl))
19260 (insert-before-markers (mapconcat
19261 'identity (delq nil tbl)
19262 (if (eq scope 'agenda) "\n|-\n" "\n")))
19263 (backward-delete-char 1)
19264 (goto-char ipos)
19265 (skip-chars-forward "^|")
19266 (org-table-align))))))
19268 (defun org-clocktable-steps (params)
19269 (let* ((p1 (copy-sequence params))
19270 (ts (plist-get p1 :tstart))
19271 (te (plist-get p1 :tend))
19272 (step0 (plist-get p1 :step))
19273 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19274 (block (plist-get p1 :block))
19276 (when block
19277 (setq cc (org-clock-special-range block nil t)
19278 ts (car cc) te (cdr cc)))
19279 (if ts (setq ts (time-to-seconds
19280 (apply 'encode-time (org-parse-time-string ts)))))
19281 (if te (setq te (time-to-seconds
19282 (apply 'encode-time (org-parse-time-string te)))))
19283 (plist-put p1 :header "")
19284 (plist-put p1 :step nil)
19285 (plist-put p1 :block nil)
19286 (while (< ts te)
19287 (or (bolp) (insert "\n"))
19288 (plist-put p1 :tstart (format-time-string
19289 (car org-time-stamp-formats)
19290 (seconds-to-time ts)))
19291 (plist-put p1 :tend (format-time-string
19292 (car org-time-stamp-formats)
19293 (seconds-to-time (setq ts (+ ts step)))))
19294 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19295 (plist-get p1 :tstart) "\n")
19296 (org-dblock-write:clocktable p1)
19297 (re-search-forward "#\\+END:")
19298 (end-of-line 0))))
19301 (defun org-clocktable-add-file (file table)
19302 (if table
19303 (let ((lines (org-split-string table "\n"))
19304 (ff (file-name-nondirectory file)))
19305 (mapconcat 'identity
19306 (mapcar (lambda (x)
19307 (if (string-match org-table-dataline-regexp x)
19308 (concat "|" ff x)
19310 lines)
19311 "\n"))))
19313 ;; FIXME: I don't think anybody uses this, ask David
19314 (defun org-collect-clock-time-entries ()
19315 "Return an internal list with clocking information.
19316 This list has one entry for each CLOCK interval.
19317 FIXME: describe the elements."
19318 (interactive)
19319 (let ((re (concat "^[ \t]*" org-clock-string
19320 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19321 rtn beg end next cont level title total closedp leafp
19322 clockpos titlepos h m donep)
19323 (save-excursion
19324 (org-clock-sum)
19325 (goto-char (point-min))
19326 (while (re-search-forward re nil t)
19327 (setq clockpos (match-beginning 0)
19328 beg (match-string 1) end (match-string 2)
19329 cont (match-end 0))
19330 (setq beg (apply 'encode-time (org-parse-time-string beg))
19331 end (apply 'encode-time (org-parse-time-string end)))
19332 (org-back-to-heading t)
19333 (setq donep (org-entry-is-done-p))
19334 (setq titlepos (point)
19335 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19336 h (/ total 60) m (- total (* 60 h))
19337 total (cons h m))
19338 (looking-at "\\(\\*+\\) +\\(.*\\)")
19339 (setq level (- (match-end 1) (match-beginning 1))
19340 title (org-match-string-no-properties 2))
19341 (save-excursion (outline-next-heading) (setq next (point)))
19342 (setq closedp (re-search-forward org-closed-time-regexp next t))
19343 (goto-char next)
19344 (setq leafp (and (looking-at "^\\*+ ")
19345 (<= (- (match-end 0) (point)) level)))
19346 (push (list beg end clockpos closedp donep
19347 total title titlepos level leafp)
19348 rtn)
19349 (goto-char cont)))
19350 (nreverse rtn)))
19352 ;;;; Agenda, and Diary Integration
19354 ;;; Define the Org-agenda-mode
19356 (defvar org-agenda-mode-map (make-sparse-keymap)
19357 "Keymap for `org-agenda-mode'.")
19359 (defvar org-agenda-menu) ; defined later in this file.
19360 (defvar org-agenda-follow-mode nil)
19361 (defvar org-agenda-show-log nil)
19362 (defvar org-agenda-redo-command nil)
19363 (defvar org-agenda-query-string nil)
19364 (defvar org-agenda-mode-hook nil)
19365 (defvar org-agenda-type nil)
19366 (defvar org-agenda-force-single-file nil)
19368 (defun org-agenda-mode ()
19369 "Mode for time-sorted view on action items in Org-mode files.
19371 The following commands are available:
19373 \\{org-agenda-mode-map}"
19374 (interactive)
19375 (kill-all-local-variables)
19376 (setq org-agenda-undo-list nil
19377 org-agenda-pending-undo-list nil)
19378 (setq major-mode 'org-agenda-mode)
19379 ;; Keep global-font-lock-mode from turning on font-lock-mode
19380 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19381 (setq mode-name "Org-Agenda")
19382 (use-local-map org-agenda-mode-map)
19383 (easy-menu-add org-agenda-menu)
19384 (if org-startup-truncated (setq truncate-lines t))
19385 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19386 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19387 ;; Make sure properties are removed when copying text
19388 (when (boundp 'buffer-substring-filters)
19389 (org-set-local 'buffer-substring-filters
19390 (cons (lambda (x)
19391 (set-text-properties 0 (length x) nil x) x)
19392 buffer-substring-filters)))
19393 (unless org-agenda-keep-modes
19394 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19395 org-agenda-show-log nil))
19396 (easy-menu-change
19397 '("Agenda") "Agenda Files"
19398 (append
19399 (list
19400 (vector
19401 (if (get 'org-agenda-files 'org-restrict)
19402 "Restricted to single file"
19403 "Edit File List")
19404 '(org-edit-agenda-file-list)
19405 (not (get 'org-agenda-files 'org-restrict)))
19406 "--")
19407 (mapcar 'org-file-menu-entry (org-agenda-files))))
19408 (org-agenda-set-mode-name)
19409 (apply
19410 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19411 (list 'org-agenda-mode-hook)))
19413 (substitute-key-definition 'undo 'org-agenda-undo
19414 org-agenda-mode-map global-map)
19415 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19416 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19417 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19418 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19419 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19420 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19421 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19422 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19423 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19424 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19425 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19426 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19427 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19428 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19429 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19430 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19431 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19432 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19433 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19434 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19435 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19436 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19437 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19438 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19439 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19440 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19441 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19442 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19443 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19445 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19446 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19447 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19448 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19449 (while l (org-defkey org-agenda-mode-map
19450 (int-to-string (pop l)) 'digit-argument)))
19452 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19453 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19454 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19455 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19456 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19457 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19458 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19459 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19460 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19461 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19462 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19463 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19464 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19465 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19466 (org-defkey org-agenda-mode-map "n" 'next-line)
19467 (org-defkey org-agenda-mode-map "p" 'previous-line)
19468 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19469 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19470 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19471 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19472 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19473 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19474 (eval-after-load "calendar"
19475 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19476 'org-calendar-goto-agenda))
19477 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19478 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19479 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19480 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19481 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19482 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19483 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19484 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19485 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19486 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19487 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19488 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19489 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19490 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19491 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19492 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19493 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19494 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19495 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19496 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19497 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19498 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19500 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19501 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19502 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19503 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19505 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19506 "Local keymap for agenda entries from Org-mode.")
19508 (org-defkey org-agenda-keymap
19509 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19510 (org-defkey org-agenda-keymap
19511 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19512 (when org-agenda-mouse-1-follows-link
19513 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19514 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19515 '("Agenda"
19516 ("Agenda Files")
19517 "--"
19518 ["Show" org-agenda-show t]
19519 ["Go To (other window)" org-agenda-goto t]
19520 ["Go To (this window)" org-agenda-switch-to t]
19521 ["Follow Mode" org-agenda-follow-mode
19522 :style toggle :selected org-agenda-follow-mode :active t]
19523 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19524 "--"
19525 ["Cycle TODO" org-agenda-todo t]
19526 ["Archive subtree" org-agenda-archive t]
19527 ["Delete subtree" org-agenda-kill t]
19528 "--"
19529 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19530 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19531 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19532 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19533 "--"
19534 ("Tags and Properties"
19535 ["Show all Tags" org-agenda-show-tags t]
19536 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19537 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19538 "--"
19539 ["Column View" org-columns t])
19540 ("Date/Schedule"
19541 ["Schedule" org-agenda-schedule t]
19542 ["Set Deadline" org-agenda-deadline t]
19543 "--"
19544 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19545 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19546 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19547 ("Clock"
19548 ["Clock in" org-agenda-clock-in t]
19549 ["Clock out" org-agenda-clock-out t]
19550 ["Clock cancel" org-agenda-clock-cancel t]
19551 ["Goto running clock" org-clock-goto t])
19552 ("Priority"
19553 ["Set Priority" org-agenda-priority t]
19554 ["Increase Priority" org-agenda-priority-up t]
19555 ["Decrease Priority" org-agenda-priority-down t]
19556 ["Show Priority" org-agenda-show-priority t])
19557 ("Calendar/Diary"
19558 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19559 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19560 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19561 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19562 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19563 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19564 "--"
19565 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19566 "--"
19567 ("View"
19568 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19569 :style radio :selected (equal org-agenda-ndays 1)]
19570 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19571 :style radio :selected (equal org-agenda-ndays 7)]
19572 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19573 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19574 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19575 :style radio :selected (member org-agenda-ndays '(365 366))]
19576 "--"
19577 ["Show Logbook entries" org-agenda-log-mode
19578 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19579 ["Include Diary" org-agenda-toggle-diary
19580 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19581 ["Use Time Grid" org-agenda-toggle-time-grid
19582 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19583 ["Write view to file" org-write-agenda t]
19584 ["Rebuild buffer" org-agenda-redo t]
19585 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19586 "--"
19587 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19588 "--"
19589 ["Quit" org-agenda-quit t]
19590 ["Exit and Release Buffers" org-agenda-exit t]
19593 ;;; Agenda undo
19595 (defvar org-agenda-allow-remote-undo t
19596 "Non-nil means, allow remote undo from the agenda buffer.")
19597 (defvar org-agenda-undo-list nil
19598 "List of undoable operations in the agenda since last refresh.")
19599 (defvar org-agenda-undo-has-started-in nil
19600 "Buffers that have already seen `undo-start' in the current undo sequence.")
19601 (defvar org-agenda-pending-undo-list nil
19602 "In a series of undo commands, this is the list of remaning undo items.")
19604 (defmacro org-if-unprotected (&rest body)
19605 "Execute BODY if there is no `org-protected' text property at point."
19606 (declare (debug t))
19607 `(unless (get-text-property (point) 'org-protected)
19608 ,@body))
19610 (defmacro org-with-remote-undo (_buffer &rest _body)
19611 "Execute BODY while recording undo information in two buffers."
19612 (declare (indent 1) (debug t))
19613 `(let ((_cline (org-current-line))
19614 (_cmd this-command)
19615 (_buf1 (current-buffer))
19616 (_buf2 ,_buffer)
19617 (_undo1 buffer-undo-list)
19618 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19619 _c1 _c2)
19620 ,@_body
19621 (when org-agenda-allow-remote-undo
19622 (setq _c1 (org-verify-change-for-undo
19623 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19624 _c2 (org-verify-change-for-undo
19625 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19626 (when (or _c1 _c2)
19627 ;; make sure there are undo boundaries
19628 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19629 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19630 ;; remember which buffer to undo
19631 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19632 org-agenda-undo-list)))))
19634 (defun org-agenda-undo ()
19635 "Undo a remote editing step in the agenda.
19636 This undoes changes both in the agenda buffer and in the remote buffer
19637 that have been changed along."
19638 (interactive)
19639 (or org-agenda-allow-remote-undo
19640 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19641 (if (not (eq this-command last-command))
19642 (setq org-agenda-undo-has-started-in nil
19643 org-agenda-pending-undo-list org-agenda-undo-list))
19644 (if (not org-agenda-pending-undo-list)
19645 (error "No further undo information"))
19646 (let* ((entry (pop org-agenda-pending-undo-list))
19647 buf line cmd rembuf)
19648 (setq cmd (pop entry) line (pop entry))
19649 (setq rembuf (nth 2 entry))
19650 (org-with-remote-undo rembuf
19651 (while (bufferp (setq buf (pop entry)))
19652 (if (pop entry)
19653 (with-current-buffer buf
19654 (let ((last-undo-buffer buf)
19655 (inhibit-read-only t))
19656 (unless (memq buf org-agenda-undo-has-started-in)
19657 (push buf org-agenda-undo-has-started-in)
19658 (make-local-variable 'pending-undo-list)
19659 (undo-start))
19660 (while (and pending-undo-list
19661 (listp pending-undo-list)
19662 (not (car pending-undo-list)))
19663 (pop pending-undo-list))
19664 (undo-more 1))))))
19665 (goto-line line)
19666 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19668 (defun org-verify-change-for-undo (l1 l2)
19669 "Verify that a real change occurred between the undo lists L1 and L2."
19670 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19671 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19672 (not (eq l1 l2)))
19674 ;;; Agenda dispatch
19676 (defvar org-agenda-restrict nil)
19677 (defvar org-agenda-restrict-begin (make-marker))
19678 (defvar org-agenda-restrict-end (make-marker))
19679 (defvar org-agenda-last-dispatch-buffer nil)
19680 (defvar org-agenda-overriding-restriction nil)
19682 ;;;###autoload
19683 (defun org-agenda (arg &optional keys restriction)
19684 "Dispatch agenda commands to collect entries to the agenda buffer.
19685 Prompts for a command to execute. Any prefix arg will be passed
19686 on to the selected command. The default selections are:
19688 a Call `org-agenda-list' to display the agenda for current day or week.
19689 t Call `org-todo-list' to display the global todo list.
19690 T Call `org-todo-list' to display the global todo list, select only
19691 entries with a specific TODO keyword (the user gets a prompt).
19692 m Call `org-tags-view' to display headlines with tags matching
19693 a condition (the user is prompted for the condition).
19694 M Like `m', but select only TODO entries, no ordinary headlines.
19695 L Create a timeline for the current buffer.
19696 e Export views to associated files.
19698 More commands can be added by configuring the variable
19699 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19700 searches can be pre-defined in this way.
19702 If the current buffer is in Org-mode and visiting a file, you can also
19703 first press `<' once to indicate that the agenda should be temporarily
19704 \(until the next use of \\[org-agenda]) restricted to the current file.
19705 Pressing `<' twice means to restrict to the current subtree or region
19706 \(if active)."
19707 (interactive "P")
19708 (catch 'exit
19709 (let* ((prefix-descriptions nil)
19710 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19711 (org-agenda-custom-commands
19712 ;; normalize different versions
19713 (delq nil
19714 (mapcar
19715 (lambda (x)
19716 (cond ((stringp (cdr x))
19717 (push x prefix-descriptions)
19718 nil)
19719 ((stringp (nth 1 x)) x)
19720 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19721 (t (cons (car x) (cons "" (cdr x))))))
19722 org-agenda-custom-commands)))
19723 (buf (current-buffer))
19724 (bfn (buffer-file-name (buffer-base-buffer)))
19725 entry key type match lprops ans)
19726 ;; Turn off restriction unless there is an overriding one
19727 (unless org-agenda-overriding-restriction
19728 (put 'org-agenda-files 'org-restrict nil)
19729 (setq org-agenda-restrict nil)
19730 (move-marker org-agenda-restrict-begin nil)
19731 (move-marker org-agenda-restrict-end nil))
19732 ;; Delete old local properties
19733 (put 'org-agenda-redo-command 'org-lprops nil)
19734 ;; Remember where this call originated
19735 (setq org-agenda-last-dispatch-buffer (current-buffer))
19736 (unless keys
19737 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19738 keys (car ans)
19739 restriction (cdr ans)))
19740 ;; Estabish the restriction, if any
19741 (when (and (not org-agenda-overriding-restriction) restriction)
19742 (put 'org-agenda-files 'org-restrict (list bfn))
19743 (cond
19744 ((eq restriction 'region)
19745 (setq org-agenda-restrict t)
19746 (move-marker org-agenda-restrict-begin (region-beginning))
19747 (move-marker org-agenda-restrict-end (region-end)))
19748 ((eq restriction 'subtree)
19749 (save-excursion
19750 (setq org-agenda-restrict t)
19751 (org-back-to-heading t)
19752 (move-marker org-agenda-restrict-begin (point))
19753 (move-marker org-agenda-restrict-end
19754 (progn (org-end-of-subtree t)))))))
19756 (require 'calendar) ; FIXME: can we avoid this for some commands?
19757 ;; For example the todo list should not need it (but does...)
19758 (cond
19759 ((setq entry (assoc keys org-agenda-custom-commands))
19760 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19761 (progn
19762 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19763 (put 'org-agenda-redo-command 'org-lprops lprops)
19764 (cond
19765 ((eq type 'agenda)
19766 (org-let lprops '(org-agenda-list current-prefix-arg)))
19767 ((eq type 'alltodo)
19768 (org-let lprops '(org-todo-list current-prefix-arg)))
19769 ((eq type 'search)
19770 (org-let lprops '(org-search-view current-prefix-arg match)))
19771 ((eq type 'stuck)
19772 (org-let lprops '(org-agenda-list-stuck-projects
19773 current-prefix-arg)))
19774 ((eq type 'tags)
19775 (org-let lprops '(org-tags-view current-prefix-arg match)))
19776 ((eq type 'tags-todo)
19777 (org-let lprops '(org-tags-view '(4) match)))
19778 ((eq type 'todo)
19779 (org-let lprops '(org-todo-list match)))
19780 ((eq type 'tags-tree)
19781 (org-check-for-org-mode)
19782 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19783 ((eq type 'todo-tree)
19784 (org-check-for-org-mode)
19785 (org-let lprops
19786 '(org-occur (concat "^" outline-regexp "[ \t]*"
19787 (regexp-quote match) "\\>"))))
19788 ((eq type 'occur-tree)
19789 (org-check-for-org-mode)
19790 (org-let lprops '(org-occur match)))
19791 ((functionp type)
19792 (org-let lprops '(funcall type match)))
19793 ((fboundp type)
19794 (org-let lprops '(funcall type match)))
19795 (t (error "Invalid custom agenda command type %s" type))))
19796 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19797 ((equal keys "C")
19798 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19799 (customize-variable 'org-agenda-custom-commands))
19800 ((equal keys "a") (call-interactively 'org-agenda-list))
19801 ((equal keys "s") (call-interactively 'org-search-view))
19802 ((equal keys "t") (call-interactively 'org-todo-list))
19803 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19804 ((equal keys "m") (call-interactively 'org-tags-view))
19805 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19806 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19807 ((equal keys "L")
19808 (unless (org-mode-p)
19809 (error "This is not an Org-mode file"))
19810 (unless restriction
19811 (put 'org-agenda-files 'org-restrict (list bfn))
19812 (org-call-with-arg 'org-timeline arg)))
19813 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19814 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19815 ((equal keys "!") (customize-variable 'org-stuck-projects))
19816 (t (error "Invalid agenda key"))))))
19818 (defun org-agenda-normalize-custom-commands (cmds)
19819 (delq nil
19820 (mapcar
19821 (lambda (x)
19822 (cond ((stringp (cdr x)) nil)
19823 ((stringp (nth 1 x)) x)
19824 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19825 (t (cons (car x) (cons "" (cdr x))))))
19826 cmds)))
19828 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19829 "The user interface for selecting an agenda command."
19830 (catch 'exit
19831 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19832 (restrict-ok (and bfn (org-mode-p)))
19833 (region-p (org-region-active-p))
19834 (custom org-agenda-custom-commands)
19835 (selstring "")
19836 restriction second-time
19837 c entry key type match prefixes rmheader header-end custom1 desc)
19838 (save-window-excursion
19839 (delete-other-windows)
19840 (org-switch-to-buffer-other-window " *Agenda Commands*")
19841 (erase-buffer)
19842 (insert (eval-when-compile
19843 (let ((header
19845 Press key for an agenda command: < Buffer,subtree/region restriction
19846 -------------------------------- > Remove restriction
19847 a Agenda for current week or day e Export agenda views
19848 t List of all TODO entries T Entries with special TODO kwd
19849 m Match a TAGS query M Like m, but only TODO entries
19850 L Timeline for current buffer # List stuck projects (!=configure)
19851 s Search for keywords C Configure custom agenda commands
19852 / Multi-occur
19854 (start 0))
19855 (while (string-match
19856 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19857 header start)
19858 (setq start (match-end 0))
19859 (add-text-properties (match-beginning 2) (match-end 2)
19860 '(face bold) header))
19861 header)))
19862 (setq header-end (move-marker (make-marker) (point)))
19863 (while t
19864 (setq custom1 custom)
19865 (when (eq rmheader t)
19866 (goto-line 1)
19867 (re-search-forward ":" nil t)
19868 (delete-region (match-end 0) (point-at-eol))
19869 (forward-char 1)
19870 (looking-at "-+")
19871 (delete-region (match-end 0) (point-at-eol))
19872 (move-marker header-end (match-end 0)))
19873 (goto-char header-end)
19874 (delete-region (point) (point-max))
19875 (while (setq entry (pop custom1))
19876 (setq key (car entry) desc (nth 1 entry)
19877 type (nth 2 entry) match (nth 3 entry))
19878 (if (> (length key) 1)
19879 (add-to-list 'prefixes (string-to-char key))
19880 (insert
19881 (format
19882 "\n%-4s%-14s: %s"
19883 (org-add-props (copy-sequence key)
19884 '(face bold))
19885 (cond
19886 ((string-match "\\S-" desc) desc)
19887 ((eq type 'agenda) "Agenda for current week or day")
19888 ((eq type 'alltodo) "List of all TODO entries")
19889 ((eq type 'search) "Word search")
19890 ((eq type 'stuck) "List of stuck projects")
19891 ((eq type 'todo) "TODO keyword")
19892 ((eq type 'tags) "Tags query")
19893 ((eq type 'tags-todo) "Tags (TODO)")
19894 ((eq type 'tags-tree) "Tags tree")
19895 ((eq type 'todo-tree) "TODO kwd tree")
19896 ((eq type 'occur-tree) "Occur tree")
19897 ((functionp type) (if (symbolp type)
19898 (symbol-name type)
19899 "Lambda expression"))
19900 (t "???"))
19901 (cond
19902 ((stringp match)
19903 (org-add-props match nil 'face 'org-warning))
19904 (match
19905 (format "set of %d commands" (length match)))
19906 (t ""))))))
19907 (when prefixes
19908 (mapc (lambda (x)
19909 (insert
19910 (format "\n%s %s"
19911 (org-add-props (char-to-string x)
19912 nil 'face 'bold)
19913 (or (cdr (assoc (concat selstring (char-to-string x))
19914 prefix-descriptions))
19915 "Prefix key"))))
19916 prefixes))
19917 (goto-char (point-min))
19918 (when (fboundp 'fit-window-to-buffer)
19919 (if second-time
19920 (if (not (pos-visible-in-window-p (point-max)))
19921 (fit-window-to-buffer))
19922 (setq second-time t)
19923 (fit-window-to-buffer)))
19924 (message "Press key for agenda command%s:"
19925 (if (or restrict-ok org-agenda-overriding-restriction)
19926 (if org-agenda-overriding-restriction
19927 " (restriction lock active)"
19928 (if restriction
19929 (format " (restricted to %s)" restriction)
19930 " (unrestricted)"))
19931 ""))
19932 (setq c (read-char-exclusive))
19933 (message "")
19934 (cond
19935 ((assoc (char-to-string c) custom)
19936 (setq selstring (concat selstring (char-to-string c)))
19937 (throw 'exit (cons selstring restriction)))
19938 ((memq c prefixes)
19939 (setq selstring (concat selstring (char-to-string c))
19940 prefixes nil
19941 rmheader (or rmheader t)
19942 custom (delq nil (mapcar
19943 (lambda (x)
19944 (if (or (= (length (car x)) 1)
19945 (/= (string-to-char (car x)) c))
19947 (cons (substring (car x) 1) (cdr x))))
19948 custom))))
19949 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19950 (message "Restriction is only possible in Org-mode buffers")
19951 (ding) (sit-for 1))
19952 ((eq c ?1)
19953 (org-agenda-remove-restriction-lock 'noupdate)
19954 (setq restriction 'buffer))
19955 ((eq c ?0)
19956 (org-agenda-remove-restriction-lock 'noupdate)
19957 (setq restriction (if region-p 'region 'subtree)))
19958 ((eq c ?<)
19959 (org-agenda-remove-restriction-lock 'noupdate)
19960 (setq restriction
19961 (cond
19962 ((eq restriction 'buffer)
19963 (if region-p 'region 'subtree))
19964 ((memq restriction '(subtree region))
19965 nil)
19966 (t 'buffer))))
19967 ((eq c ?>)
19968 (org-agenda-remove-restriction-lock 'noupdate)
19969 (setq restriction nil))
19970 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19971 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19972 ((and (> (length selstring) 0) (eq c ?\d))
19973 (delete-window)
19974 (org-agenda-get-restriction-and-command prefix-descriptions))
19976 ((equal c ?q) (error "Abort"))
19977 (t (error "Invalid key %c" c))))))))
19979 (defun org-run-agenda-series (name series)
19980 (org-prepare-agenda name)
19981 (let* ((org-agenda-multi t)
19982 (redo (list 'org-run-agenda-series name (list 'quote series)))
19983 (cmds (car series))
19984 (gprops (nth 1 series))
19985 match ;; The byte compiler incorrectly complains about this. Keep it!
19986 cmd type lprops)
19987 (while (setq cmd (pop cmds))
19988 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19989 (cond
19990 ((eq type 'agenda)
19991 (org-let2 gprops lprops
19992 '(call-interactively 'org-agenda-list)))
19993 ((eq type 'alltodo)
19994 (org-let2 gprops lprops
19995 '(call-interactively 'org-todo-list)))
19996 ((eq type 'search)
19997 (org-let2 gprops lprops
19998 '(org-search-view current-prefix-arg match)))
19999 ((eq type 'stuck)
20000 (org-let2 gprops lprops
20001 '(call-interactively 'org-agenda-list-stuck-projects)))
20002 ((eq type 'tags)
20003 (org-let2 gprops lprops
20004 '(org-tags-view current-prefix-arg match)))
20005 ((eq type 'tags-todo)
20006 (org-let2 gprops lprops
20007 '(org-tags-view '(4) match)))
20008 ((eq type 'todo)
20009 (org-let2 gprops lprops
20010 '(org-todo-list match)))
20011 ((fboundp type)
20012 (org-let2 gprops lprops
20013 '(funcall type match)))
20014 (t (error "Invalid type in command series"))))
20015 (widen)
20016 (setq org-agenda-redo-command redo)
20017 (goto-char (point-min)))
20018 (org-finalize-agenda))
20020 ;;;###autoload
20021 (defmacro org-batch-agenda (cmd-key &rest parameters)
20022 "Run an agenda command in batch mode and send the result to STDOUT.
20023 If CMD-KEY is a string of length 1, it is used as a key in
20024 `org-agenda-custom-commands' and triggers this command. If it is a
20025 longer string it is used as a tags/todo match string.
20026 Paramters are alternating variable names and values that will be bound
20027 before running the agenda command."
20028 (let (pars)
20029 (while parameters
20030 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20031 (if (> (length cmd-key) 2)
20032 (eval (list 'let (nreverse pars)
20033 (list 'org-tags-view nil cmd-key)))
20034 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20035 (set-buffer org-agenda-buffer-name)
20036 (princ (org-encode-for-stdout (buffer-string)))))
20038 (defun org-encode-for-stdout (string)
20039 (if (fboundp 'encode-coding-string)
20040 (encode-coding-string string buffer-file-coding-system)
20041 string))
20043 (defvar org-agenda-info nil)
20045 ;;;###autoload
20046 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20047 "Run an agenda command in batch mode and send the result to STDOUT.
20048 If CMD-KEY is a string of length 1, it is used as a key in
20049 `org-agenda-custom-commands' and triggers this command. If it is a
20050 longer string it is used as a tags/todo match string.
20051 Paramters are alternating variable names and values that will be bound
20052 before running the agenda command.
20054 The output gives a line for each selected agenda item. Each
20055 item is a list of comma-separated values, like this:
20057 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20059 category The category of the item
20060 head The headline, without TODO kwd, TAGS and PRIORITY
20061 type The type of the agenda entry, can be
20062 todo selected in TODO match
20063 tagsmatch selected in tags match
20064 diary imported from diary
20065 deadline a deadline on given date
20066 scheduled scheduled on given date
20067 timestamp entry has timestamp on given date
20068 closed entry was closed on given date
20069 upcoming-deadline warning about deadline
20070 past-scheduled forwarded scheduled item
20071 block entry has date block including g. date
20072 todo The todo keyword, if any
20073 tags All tags including inherited ones, separated by colons
20074 date The relevant date, like 2007-2-14
20075 time The time, like 15:00-16:50
20076 extra Sting with extra planning info
20077 priority-l The priority letter if any was given
20078 priority-n The computed numerical priority
20079 agenda-day The day in the agenda where this is listed"
20081 (let (pars)
20082 (while parameters
20083 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20084 (push (list 'org-agenda-remove-tags t) pars)
20085 (if (> (length cmd-key) 2)
20086 (eval (list 'let (nreverse pars)
20087 (list 'org-tags-view nil cmd-key)))
20088 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20089 (set-buffer org-agenda-buffer-name)
20090 (let* ((lines (org-split-string (buffer-string) "\n"))
20091 line)
20092 (while (setq line (pop lines))
20093 (catch 'next
20094 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20095 (setq org-agenda-info
20096 (org-fix-agenda-info (text-properties-at 0 line)))
20097 (princ
20098 (org-encode-for-stdout
20099 (mapconcat 'org-agenda-export-csv-mapper
20100 '(org-category txt type todo tags date time-of-day extra
20101 priority-letter priority agenda-day)
20102 ",")))
20103 (princ "\n"))))))
20105 (defun org-fix-agenda-info (props)
20106 "Make sure all properties on an agenda item have a canonical form,
20107 so the export commands can easily use it."
20108 (let (tmp re)
20109 (when (setq tmp (plist-get props 'tags))
20110 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20111 (when (setq tmp (plist-get props 'date))
20112 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20113 (let ((calendar-date-display-form '(year "-" month "-" day)))
20114 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20116 (setq tmp (calendar-date-string tmp)))
20117 (setq props (plist-put props 'date tmp)))
20118 (when (setq tmp (plist-get props 'day))
20119 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20120 (let ((calendar-date-display-form '(year "-" month "-" day)))
20121 (setq tmp (calendar-date-string tmp)))
20122 (setq props (plist-put props 'day tmp))
20123 (setq props (plist-put props 'agenda-day tmp)))
20124 (when (setq tmp (plist-get props 'txt))
20125 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20126 (plist-put props 'priority-letter (match-string 1 tmp))
20127 (setq tmp (replace-match "" t t tmp)))
20128 (when (and (setq re (plist-get props 'org-todo-regexp))
20129 (setq re (concat "\\`\\.*" re " ?"))
20130 (string-match re tmp))
20131 (plist-put props 'todo (match-string 1 tmp))
20132 (setq tmp (replace-match "" t t tmp)))
20133 (plist-put props 'txt tmp)))
20134 props)
20136 (defun org-agenda-export-csv-mapper (prop)
20137 (let ((res (plist-get org-agenda-info prop)))
20138 (setq res
20139 (cond
20140 ((not res) "")
20141 ((stringp res) res)
20142 (t (prin1-to-string res))))
20143 (while (string-match "," res)
20144 (setq res (replace-match ";" t t res)))
20145 (org-trim res)))
20148 ;;;###autoload
20149 (defun org-store-agenda-views (&rest parameters)
20150 (interactive)
20151 (eval (list 'org-batch-store-agenda-views)))
20153 ;; FIXME, why is this a macro?????
20154 ;;;###autoload
20155 (defmacro org-batch-store-agenda-views (&rest parameters)
20156 "Run all custom agenda commands that have a file argument."
20157 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20158 (pop-up-frames nil)
20159 (dir default-directory)
20160 pars cmd thiscmdkey files opts)
20161 (while parameters
20162 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20163 (setq pars (reverse pars))
20164 (save-window-excursion
20165 (while cmds
20166 (setq cmd (pop cmds)
20167 thiscmdkey (car cmd)
20168 opts (nth 4 cmd)
20169 files (nth 5 cmd))
20170 (if (stringp files) (setq files (list files)))
20171 (when files
20172 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20173 (list 'org-agenda nil thiscmdkey)))
20174 (set-buffer org-agenda-buffer-name)
20175 (while files
20176 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20177 (list 'org-write-agenda
20178 (expand-file-name (pop files) dir) t))))
20179 (and (get-buffer org-agenda-buffer-name)
20180 (kill-buffer org-agenda-buffer-name)))))))
20182 (defun org-write-agenda (file &optional nosettings)
20183 "Write the current buffer (an agenda view) as a file.
20184 Depending on the extension of the file name, plain text (.txt),
20185 HTML (.html or .htm) or Postscript (.ps) is produced.
20186 If NOSETTINGS is given, do not scope the settings of
20187 `org-agenda-exporter-settings' into the export commands. This is used when
20188 the settings have already been scoped and we do not wish to overrule other,
20189 higher priority settings."
20190 (interactive "FWrite agenda to file: ")
20191 (if (not (file-writable-p file))
20192 (error "Cannot write agenda to file %s" file))
20193 (cond
20194 ((string-match "\\.html?\\'" file) (require 'htmlize))
20195 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20196 (org-let (if nosettings nil org-agenda-exporter-settings)
20197 '(save-excursion
20198 (save-window-excursion
20199 (cond
20200 ((string-match "\\.html?\\'" file)
20201 (set-buffer (htmlize-buffer (current-buffer)))
20203 (when (and org-agenda-export-html-style
20204 (string-match "<style>" org-agenda-export-html-style))
20205 ;; replace <style> section with org-agenda-export-html-style
20206 (goto-char (point-min))
20207 (kill-region (- (search-forward "<style") 6)
20208 (search-forward "</style>"))
20209 (insert org-agenda-export-html-style))
20210 (write-file file)
20211 (kill-buffer (current-buffer))
20212 (message "HTML written to %s" file))
20213 ((string-match "\\.ps\\'" file)
20214 (ps-print-buffer-with-faces file)
20215 (message "Postscript written to %s" file))
20217 (let ((bs (buffer-string)))
20218 (find-file file)
20219 (insert bs)
20220 (save-buffer 0)
20221 (kill-buffer (current-buffer))
20222 (message "Plain text written to %s" file))))))
20223 (set-buffer org-agenda-buffer-name)))
20225 (defmacro org-no-read-only (&rest body)
20226 "Inhibit read-only for BODY."
20227 `(let ((inhibit-read-only t)) ,@body))
20229 (defun org-check-for-org-mode ()
20230 "Make sure current buffer is in org-mode. Error if not."
20231 (or (org-mode-p)
20232 (error "Cannot execute org-mode agenda command on buffer in %s."
20233 major-mode)))
20235 (defun org-fit-agenda-window ()
20236 "Fit the window to the buffer size."
20237 (and (memq org-agenda-window-setup '(reorganize-frame))
20238 (fboundp 'fit-window-to-buffer)
20239 (fit-window-to-buffer
20241 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20242 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20244 ;;; Agenda file list
20246 (defun org-agenda-files (&optional unrestricted)
20247 "Get the list of agenda files.
20248 Optional UNRESTRICTED means return the full list even if a restriction
20249 is currently in place."
20250 (let ((files
20251 (cond
20252 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20253 ((stringp org-agenda-files) (org-read-agenda-file-list))
20254 ((listp org-agenda-files) org-agenda-files)
20255 (t (error "Invalid value of `org-agenda-files'")))))
20256 (setq files (apply 'append
20257 (mapcar (lambda (f)
20258 (if (file-directory-p f)
20259 (directory-files f t
20260 org-agenda-file-regexp)
20261 (list f)))
20262 files)))
20263 (if org-agenda-skip-unavailable-files
20264 (delq nil
20265 (mapcar (function
20266 (lambda (file)
20267 (and (file-readable-p file) file)))
20268 files))
20269 files))) ; `org-check-agenda-file' will remove them from the list
20271 (defun org-edit-agenda-file-list ()
20272 "Edit the list of agenda files.
20273 Depending on setup, this either uses customize to edit the variable
20274 `org-agenda-files', or it visits the file that is holding the list. In the
20275 latter case, the buffer is set up in a way that saving it automatically kills
20276 the buffer and restores the previous window configuration."
20277 (interactive)
20278 (if (stringp org-agenda-files)
20279 (let ((cw (current-window-configuration)))
20280 (find-file org-agenda-files)
20281 (org-set-local 'org-window-configuration cw)
20282 (org-add-hook 'after-save-hook
20283 (lambda ()
20284 (set-window-configuration
20285 (prog1 org-window-configuration
20286 (kill-buffer (current-buffer))))
20287 (org-install-agenda-files-menu)
20288 (message "New agenda file list installed"))
20289 nil 'local)
20290 (message "%s" (substitute-command-keys
20291 "Edit list and finish with \\[save-buffer]")))
20292 (customize-variable 'org-agenda-files)))
20294 (defun org-store-new-agenda-file-list (list)
20295 "Set new value for the agenda file list and save it correcly."
20296 (if (stringp org-agenda-files)
20297 (let ((f org-agenda-files) b)
20298 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20299 (with-temp-file f
20300 (insert (mapconcat 'identity list "\n") "\n")))
20301 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20302 (setq org-agenda-files list)
20303 (customize-save-variable 'org-agenda-files org-agenda-files))))
20305 (defun org-read-agenda-file-list ()
20306 "Read the list of agenda files from a file."
20307 (when (stringp org-agenda-files)
20308 (with-temp-buffer
20309 (insert-file-contents org-agenda-files)
20310 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20313 ;;;###autoload
20314 (defun org-cycle-agenda-files ()
20315 "Cycle through the files in `org-agenda-files'.
20316 If the current buffer visits an agenda file, find the next one in the list.
20317 If the current buffer does not, find the first agenda file."
20318 (interactive)
20319 (let* ((fs (org-agenda-files t))
20320 (files (append fs (list (car fs))))
20321 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20322 file)
20323 (unless files (error "No agenda files"))
20324 (catch 'exit
20325 (while (setq file (pop files))
20326 (if (equal (file-truename file) tcf)
20327 (when (car files)
20328 (find-file (car files))
20329 (throw 'exit t))))
20330 (find-file (car fs)))
20331 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20333 (defun org-agenda-file-to-front (&optional to-end)
20334 "Move/add the current file to the top of the agenda file list.
20335 If the file is not present in the list, it is added to the front. If it is
20336 present, it is moved there. With optional argument TO-END, add/move to the
20337 end of the list."
20338 (interactive "P")
20339 (let ((org-agenda-skip-unavailable-files nil)
20340 (file-alist (mapcar (lambda (x)
20341 (cons (file-truename x) x))
20342 (org-agenda-files t)))
20343 (ctf (file-truename buffer-file-name))
20344 x had)
20345 (setq x (assoc ctf file-alist) had x)
20347 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20348 (if to-end
20349 (setq file-alist (append (delq x file-alist) (list x)))
20350 (setq file-alist (cons x (delq x file-alist))))
20351 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20352 (org-install-agenda-files-menu)
20353 (message "File %s to %s of agenda file list"
20354 (if had "moved" "added") (if to-end "end" "front"))))
20356 (defun org-remove-file (&optional file)
20357 "Remove current file from the list of files in variable `org-agenda-files'.
20358 These are the files which are being checked for agenda entries.
20359 Optional argument FILE means, use this file instead of the current."
20360 (interactive)
20361 (let* ((org-agenda-skip-unavailable-files nil)
20362 (file (or file buffer-file-name))
20363 (true-file (file-truename file))
20364 (afile (abbreviate-file-name file))
20365 (files (delq nil (mapcar
20366 (lambda (x)
20367 (if (equal true-file
20368 (file-truename x))
20369 nil x))
20370 (org-agenda-files t)))))
20371 (if (not (= (length files) (length (org-agenda-files t))))
20372 (progn
20373 (org-store-new-agenda-file-list files)
20374 (org-install-agenda-files-menu)
20375 (message "Removed file: %s" afile))
20376 (message "File was not in list: %s (not removed)" afile))))
20378 (defun org-file-menu-entry (file)
20379 (vector file (list 'find-file file) t))
20381 (defun org-check-agenda-file (file)
20382 "Make sure FILE exists. If not, ask user what to do."
20383 (when (not (file-exists-p file))
20384 (message "non-existent file %s. [R]emove from list or [A]bort?"
20385 (abbreviate-file-name file))
20386 (let ((r (downcase (read-char-exclusive))))
20387 (cond
20388 ((equal r ?r)
20389 (org-remove-file file)
20390 (throw 'nextfile t))
20391 (t (error "Abort"))))))
20393 ;;; Agenda prepare and finalize
20395 (defvar org-agenda-multi nil) ; dynammically scoped
20396 (defvar org-agenda-buffer-name "*Org Agenda*")
20397 (defvar org-pre-agenda-window-conf nil)
20398 (defvar org-agenda-name nil)
20399 (defun org-prepare-agenda (&optional name)
20400 (setq org-todo-keywords-for-agenda nil)
20401 (setq org-done-keywords-for-agenda nil)
20402 (if org-agenda-multi
20403 (progn
20404 (setq buffer-read-only nil)
20405 (goto-char (point-max))
20406 (unless (or (bobp) org-agenda-compact-blocks)
20407 (insert "\n" (make-string (window-width) ?=) "\n"))
20408 (narrow-to-region (point) (point-max)))
20409 (org-agenda-reset-markers)
20410 (org-prepare-agenda-buffers (org-agenda-files))
20411 (setq org-todo-keywords-for-agenda
20412 (org-uniquify org-todo-keywords-for-agenda))
20413 (setq org-done-keywords-for-agenda
20414 (org-uniquify org-done-keywords-for-agenda))
20415 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20416 (awin (get-buffer-window abuf)))
20417 (cond
20418 ((equal (current-buffer) abuf) nil)
20419 (awin (select-window awin))
20420 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20421 ((equal org-agenda-window-setup 'current-window)
20422 (switch-to-buffer abuf))
20423 ((equal org-agenda-window-setup 'other-window)
20424 (org-switch-to-buffer-other-window abuf))
20425 ((equal org-agenda-window-setup 'other-frame)
20426 (switch-to-buffer-other-frame abuf))
20427 ((equal org-agenda-window-setup 'reorganize-frame)
20428 (delete-other-windows)
20429 (org-switch-to-buffer-other-window abuf))))
20430 (setq buffer-read-only nil)
20431 (erase-buffer)
20432 (org-agenda-mode)
20433 (and name (not org-agenda-name)
20434 (org-set-local 'org-agenda-name name)))
20435 (setq buffer-read-only nil))
20437 (defun org-finalize-agenda ()
20438 "Finishing touch for the agenda buffer, called just before displaying it."
20439 (unless org-agenda-multi
20440 (save-excursion
20441 (let ((inhibit-read-only t))
20442 (goto-char (point-min))
20443 (while (org-activate-bracket-links (point-max))
20444 (add-text-properties (match-beginning 0) (match-end 0)
20445 '(face org-link)))
20446 (org-agenda-align-tags)
20447 (unless org-agenda-with-colors
20448 (remove-text-properties (point-min) (point-max) '(face nil))))
20449 (if (and (boundp 'org-overriding-columns-format)
20450 org-overriding-columns-format)
20451 (org-set-local 'org-overriding-columns-format
20452 org-overriding-columns-format))
20453 (if (and (boundp 'org-agenda-view-columns-initially)
20454 org-agenda-view-columns-initially)
20455 (org-agenda-columns))
20456 (when org-agenda-fontify-priorities
20457 (org-fontify-priorities))
20458 (run-hooks 'org-finalize-agenda-hook)
20459 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20462 (defun org-fontify-priorities ()
20463 "Make highest priority lines bold, and lowest italic."
20464 (interactive)
20465 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20466 (org-delete-overlay o)))
20467 (org-overlays-in (point-min) (point-max)))
20468 (save-excursion
20469 (let ((inhibit-read-only t)
20470 b e p ov h l)
20471 (goto-char (point-min))
20472 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20473 (setq h (or (get-char-property (point) 'org-highest-priority)
20474 org-highest-priority)
20475 l (or (get-char-property (point) 'org-lowest-priority)
20476 org-lowest-priority)
20477 p (string-to-char (match-string 1))
20478 b (match-beginning 0) e (point-at-eol)
20479 ov (org-make-overlay b e))
20480 (org-overlay-put
20481 ov 'face
20482 (cond ((listp org-agenda-fontify-priorities)
20483 (cdr (assoc p org-agenda-fontify-priorities)))
20484 ((equal p l) 'italic)
20485 ((equal p h) 'bold)))
20486 (org-overlay-put ov 'org-type 'org-priority)))))
20488 (defun org-prepare-agenda-buffers (files)
20489 "Create buffers for all agenda files, protect archived trees and comments."
20490 (interactive)
20491 (let ((pa '(:org-archived t))
20492 (pc '(:org-comment t))
20493 (pall '(:org-archived t :org-comment t))
20494 (inhibit-read-only t)
20495 (rea (concat ":" org-archive-tag ":"))
20496 bmp file re)
20497 (save-excursion
20498 (save-restriction
20499 (while (setq file (pop files))
20500 (if (bufferp file)
20501 (set-buffer file)
20502 (org-check-agenda-file file)
20503 (set-buffer (org-get-agenda-file-buffer file)))
20504 (widen)
20505 (setq bmp (buffer-modified-p))
20506 (org-refresh-category-properties)
20507 (setq org-todo-keywords-for-agenda
20508 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20509 (setq org-done-keywords-for-agenda
20510 (append org-done-keywords-for-agenda org-done-keywords))
20511 (save-excursion
20512 (remove-text-properties (point-min) (point-max) pall)
20513 (when org-agenda-skip-archived-trees
20514 (goto-char (point-min))
20515 (while (re-search-forward rea nil t)
20516 (if (org-on-heading-p t)
20517 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20518 (goto-char (point-min))
20519 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20520 (while (re-search-forward re nil t)
20521 (add-text-properties
20522 (match-beginning 0) (org-end-of-subtree t) pc)))
20523 (set-buffer-modified-p bmp))))))
20525 (defvar org-agenda-skip-function nil
20526 "Function to be called at each match during agenda construction.
20527 If this function returns nil, the current match should not be skipped.
20528 Otherwise, the function must return a position from where the search
20529 should be continued.
20530 This may also be a Lisp form, it will be evaluated.
20531 Never set this variable using `setq' or so, because then it will apply
20532 to all future agenda commands. Instead, bind it with `let' to scope
20533 it dynamically into the agenda-constructing command. A good way to set
20534 it is through options in org-agenda-custom-commands.")
20536 (defun org-agenda-skip ()
20537 "Throw to `:skip' in places that should be skipped.
20538 Also moves point to the end of the skipped region, so that search can
20539 continue from there."
20540 (let ((p (point-at-bol)) to fp)
20541 (and org-agenda-skip-archived-trees
20542 (get-text-property p :org-archived)
20543 (org-end-of-subtree t)
20544 (throw :skip t))
20545 (and (get-text-property p :org-comment)
20546 (org-end-of-subtree t)
20547 (throw :skip t))
20548 (if (equal (char-after p) ?#) (throw :skip t))
20549 (when (and (or (setq fp (functionp org-agenda-skip-function))
20550 (consp org-agenda-skip-function))
20551 (setq to (save-excursion
20552 (save-match-data
20553 (if fp
20554 (funcall org-agenda-skip-function)
20555 (eval org-agenda-skip-function))))))
20556 (goto-char to)
20557 (throw :skip t))))
20559 (defvar org-agenda-markers nil
20560 "List of all currently active markers created by `org-agenda'.")
20561 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20562 "Creation time of the last agenda marker.")
20564 (defun org-agenda-new-marker (&optional pos)
20565 "Return a new agenda marker.
20566 Org-mode keeps a list of these markers and resets them when they are
20567 no longer in use."
20568 (let ((m (copy-marker (or pos (point)))))
20569 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20570 (push m org-agenda-markers)
20573 (defun org-agenda-reset-markers ()
20574 "Reset markers created by `org-agenda'."
20575 (while org-agenda-markers
20576 (move-marker (pop org-agenda-markers) nil)))
20578 (defun org-get-agenda-file-buffer (file)
20579 "Get a buffer visiting FILE. If the buffer needs to be created, add
20580 it to the list of buffers which might be released later."
20581 (let ((buf (org-find-base-buffer-visiting file)))
20582 (if buf
20583 buf ; just return it
20584 ;; Make a new buffer and remember it
20585 (setq buf (find-file-noselect file))
20586 (if buf (push buf org-agenda-new-buffers))
20587 buf)))
20589 (defun org-release-buffers (blist)
20590 "Release all buffers in list, asking the user for confirmation when needed.
20591 When a buffer is unmodified, it is just killed. When modified, it is saved
20592 \(if the user agrees) and then killed."
20593 (let (buf file)
20594 (while (setq buf (pop blist))
20595 (setq file (buffer-file-name buf))
20596 (when (and (buffer-modified-p buf)
20597 file
20598 (y-or-n-p (format "Save file %s? " file)))
20599 (with-current-buffer buf (save-buffer)))
20600 (kill-buffer buf))))
20602 (defun org-get-category (&optional pos)
20603 "Get the category applying to position POS."
20604 (get-text-property (or pos (point)) 'org-category))
20606 ;;; Agenda timeline
20608 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20610 (defun org-timeline (&optional include-all)
20611 "Show a time-sorted view of the entries in the current org file.
20612 Only entries with a time stamp of today or later will be listed. With
20613 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20614 under the current date.
20615 If the buffer contains an active region, only check the region for
20616 dates."
20617 (interactive "P")
20618 (require 'calendar)
20619 (org-compile-prefix-format 'timeline)
20620 (org-set-sorting-strategy 'timeline)
20621 (let* ((dopast t)
20622 (dotodo include-all)
20623 (doclosed org-agenda-show-log)
20624 (entry buffer-file-name)
20625 (date (calendar-current-date))
20626 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20627 (end (if (org-region-active-p) (region-end) (point-max)))
20628 (day-numbers (org-get-all-dates beg end 'no-ranges
20629 t doclosed ; always include today
20630 org-timeline-show-empty-dates))
20631 (org-deadline-warning-days 0)
20632 (org-agenda-only-exact-dates t)
20633 (today (time-to-days (current-time)))
20634 (past t)
20635 args
20636 s e rtn d emptyp)
20637 (setq org-agenda-redo-command
20638 (list 'progn
20639 (list 'org-switch-to-buffer-other-window (current-buffer))
20640 (list 'org-timeline (list 'quote include-all))))
20641 (if (not dopast)
20642 ;; Remove past dates from the list of dates.
20643 (setq day-numbers (delq nil (mapcar (lambda(x)
20644 (if (>= x today) x nil))
20645 day-numbers))))
20646 (org-prepare-agenda (concat "Timeline "
20647 (file-name-nondirectory buffer-file-name)))
20648 (if doclosed (push :closed args))
20649 (push :timestamp args)
20650 (push :deadline args)
20651 (push :scheduled args)
20652 (push :sexp args)
20653 (if dotodo (push :todo args))
20654 (while (setq d (pop day-numbers))
20655 (if (and (listp d) (eq (car d) :omitted))
20656 (progn
20657 (setq s (point))
20658 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20659 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20660 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20661 (if (and (>= d today)
20662 dopast
20663 past)
20664 (progn
20665 (setq past nil)
20666 (insert (make-string 79 ?-) "\n")))
20667 (setq date (calendar-gregorian-from-absolute d))
20668 (setq s (point))
20669 (setq rtn (and (not emptyp)
20670 (apply 'org-agenda-get-day-entries entry
20671 date args)))
20672 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20673 (progn
20674 (insert
20675 (if (stringp org-agenda-format-date)
20676 (format-time-string org-agenda-format-date
20677 (org-time-from-absolute date))
20678 (funcall org-agenda-format-date date))
20679 "\n")
20680 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20681 (put-text-property s (1- (point)) 'org-date-line t)
20682 (if (equal d today)
20683 (put-text-property s (1- (point)) 'org-today t))
20684 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20685 (put-text-property s (1- (point)) 'day d)))))
20686 (goto-char (point-min))
20687 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20688 (point-min)))
20689 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20690 (org-finalize-agenda)
20691 (setq buffer-read-only t)))
20693 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20694 "Return a list of all relevant day numbers from BEG to END buffer positions.
20695 If NO-RANGES is non-nil, include only the start and end dates of a range,
20696 not every single day in the range. If FORCE-TODAY is non-nil, make
20697 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20698 inactive time stamps (those in square brackets) are included.
20699 When EMPTY is non-nil, also include days without any entries."
20700 (let ((re (concat
20701 (if pre-re pre-re "")
20702 (if inactive org-ts-regexp-both org-ts-regexp)))
20703 dates dates1 date day day1 day2 ts1 ts2)
20704 (if force-today
20705 (setq dates (list (time-to-days (current-time)))))
20706 (save-excursion
20707 (goto-char beg)
20708 (while (re-search-forward re end t)
20709 (setq day (time-to-days (org-time-string-to-time
20710 (substring (match-string 1) 0 10))))
20711 (or (memq day dates) (push day dates)))
20712 (unless no-ranges
20713 (goto-char beg)
20714 (while (re-search-forward org-tr-regexp end t)
20715 (setq ts1 (substring (match-string 1) 0 10)
20716 ts2 (substring (match-string 2) 0 10)
20717 day1 (time-to-days (org-time-string-to-time ts1))
20718 day2 (time-to-days (org-time-string-to-time ts2)))
20719 (while (< (setq day1 (1+ day1)) day2)
20720 (or (memq day1 dates) (push day1 dates)))))
20721 (setq dates (sort dates '<))
20722 (when empty
20723 (while (setq day (pop dates))
20724 (setq day2 (car dates))
20725 (push day dates1)
20726 (when (and day2 empty)
20727 (if (or (eq empty t)
20728 (and (numberp empty) (<= (- day2 day) empty)))
20729 (while (< (setq day (1+ day)) day2)
20730 (push (list day) dates1))
20731 (push (cons :omitted (- day2 day)) dates1))))
20732 (setq dates (nreverse dates1)))
20733 dates)))
20735 ;;; Agenda Daily/Weekly
20737 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20738 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20739 (defvar org-agenda-last-arguments nil
20740 "The arguments of the previous call to org-agenda")
20741 (defvar org-starting-day nil) ; local variable in the agenda buffer
20742 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20743 (defvar org-include-all-loc nil) ; local variable
20744 (defvar org-agenda-remove-date nil) ; dynamically scoped
20746 ;;;###autoload
20747 (defun org-agenda-list (&optional include-all start-day ndays)
20748 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20749 The view will be for the current day or week, but from the overview buffer
20750 you will be able to go to other days/weeks.
20752 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20753 all unfinished TODO items will also be shown, before the agenda.
20754 This feature is considered obsolete, please use the TODO list or a block
20755 agenda instead.
20757 With a numeric prefix argument in an interactive call, the agenda will
20758 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20759 the number of days. NDAYS defaults to `org-agenda-ndays'.
20761 START-DAY defaults to TODAY, or to the most recent match for the weekday
20762 given in `org-agenda-start-on-weekday'."
20763 (interactive "P")
20764 (if (and (integerp include-all) (> include-all 0))
20765 (setq ndays include-all include-all nil))
20766 (setq ndays (or ndays org-agenda-ndays)
20767 start-day (or start-day org-agenda-start-day))
20768 (if org-agenda-overriding-arguments
20769 (setq include-all (car org-agenda-overriding-arguments)
20770 start-day (nth 1 org-agenda-overriding-arguments)
20771 ndays (nth 2 org-agenda-overriding-arguments)))
20772 (if (stringp start-day)
20773 ;; Convert to an absolute day number
20774 (setq start-day (time-to-days (org-read-date nil t start-day))))
20775 (setq org-agenda-last-arguments (list include-all start-day ndays))
20776 (org-compile-prefix-format 'agenda)
20777 (org-set-sorting-strategy 'agenda)
20778 (require 'calendar)
20779 (let* ((org-agenda-start-on-weekday
20780 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20781 org-agenda-start-on-weekday nil))
20782 (thefiles (org-agenda-files))
20783 (files thefiles)
20784 (today (time-to-days
20785 (time-subtract (current-time)
20786 (list 0 (* 3600 org-extend-today-until) 0))))
20787 (sd (or start-day today))
20788 (start (if (or (null org-agenda-start-on-weekday)
20789 (< org-agenda-ndays 7))
20791 (let* ((nt (calendar-day-of-week
20792 (calendar-gregorian-from-absolute sd)))
20793 (n1 org-agenda-start-on-weekday)
20794 (d (- nt n1)))
20795 (- sd (+ (if (< d 0) 7 0) d)))))
20796 (day-numbers (list start))
20797 (day-cnt 0)
20798 (inhibit-redisplay (not debug-on-error))
20799 s e rtn rtnall file date d start-pos end-pos todayp nd)
20800 (setq org-agenda-redo-command
20801 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20802 ;; Make the list of days
20803 (setq ndays (or ndays org-agenda-ndays)
20804 nd ndays)
20805 (while (> ndays 1)
20806 (push (1+ (car day-numbers)) day-numbers)
20807 (setq ndays (1- ndays)))
20808 (setq day-numbers (nreverse day-numbers))
20809 (org-prepare-agenda "Day/Week")
20810 (org-set-local 'org-starting-day (car day-numbers))
20811 (org-set-local 'org-include-all-loc include-all)
20812 (org-set-local 'org-agenda-span
20813 (org-agenda-ndays-to-span nd))
20814 (when (and (or include-all org-agenda-include-all-todo)
20815 (member today day-numbers))
20816 (setq files thefiles
20817 rtnall nil)
20818 (while (setq file (pop files))
20819 (catch 'nextfile
20820 (org-check-agenda-file file)
20821 (setq date (calendar-gregorian-from-absolute today)
20822 rtn (org-agenda-get-day-entries
20823 file date :todo))
20824 (setq rtnall (append rtnall rtn))))
20825 (when rtnall
20826 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20827 (add-text-properties (point-min) (1- (point))
20828 (list 'face 'org-agenda-structure))
20829 (insert (org-finalize-agenda-entries rtnall) "\n")))
20830 (unless org-agenda-compact-blocks
20831 (setq s (point))
20832 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20833 "-agenda:\n")
20834 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20835 'org-date-line t)))
20836 (while (setq d (pop day-numbers))
20837 (setq date (calendar-gregorian-from-absolute d)
20838 s (point))
20839 (if (or (setq todayp (= d today))
20840 (and (not start-pos) (= d sd)))
20841 (setq start-pos (point))
20842 (if (and start-pos (not end-pos))
20843 (setq end-pos (point))))
20844 (setq files thefiles
20845 rtnall nil)
20846 (while (setq file (pop files))
20847 (catch 'nextfile
20848 (org-check-agenda-file file)
20849 (if org-agenda-show-log
20850 (setq rtn (org-agenda-get-day-entries
20851 file date
20852 :deadline :scheduled :timestamp :sexp :closed))
20853 (setq rtn (org-agenda-get-day-entries
20854 file date
20855 :deadline :scheduled :sexp :timestamp)))
20856 (setq rtnall (append rtnall rtn))))
20857 (if org-agenda-include-diary
20858 (progn
20859 (require 'diary-lib)
20860 (setq rtn (org-get-entries-from-diary date))
20861 (setq rtnall (append rtnall rtn))))
20862 (if (or rtnall org-agenda-show-all-dates)
20863 (progn
20864 (setq day-cnt (1+ day-cnt))
20865 (insert
20866 (if (stringp org-agenda-format-date)
20867 (format-time-string org-agenda-format-date
20868 (org-time-from-absolute date))
20869 (funcall org-agenda-format-date date))
20870 "\n")
20871 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20872 (put-text-property s (1- (point)) 'org-date-line t)
20873 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20874 (if todayp (put-text-property s (1- (point)) 'org-today t))
20875 (if rtnall (insert
20876 (org-finalize-agenda-entries
20877 (org-agenda-add-time-grid-maybe
20878 rtnall nd todayp))
20879 "\n"))
20880 (put-text-property s (1- (point)) 'day d)
20881 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20882 (goto-char (point-min))
20883 (org-fit-agenda-window)
20884 (unless (and (pos-visible-in-window-p (point-min))
20885 (pos-visible-in-window-p (point-max)))
20886 (goto-char (1- (point-max)))
20887 (recenter -1)
20888 (if (not (pos-visible-in-window-p (or start-pos 1)))
20889 (progn
20890 (goto-char (or start-pos 1))
20891 (recenter 1))))
20892 (goto-char (or start-pos 1))
20893 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20894 (org-finalize-agenda)
20895 (setq buffer-read-only t)
20896 (message "")))
20898 (defun org-agenda-ndays-to-span (n)
20899 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20901 ;;; Agenda word search
20903 (defvar org-agenda-search-history nil)
20905 ;;;###autoload
20906 (defun org-search-view (&optional arg string)
20907 "Show all entries that contain words or regular expressions.
20908 If the first character of the search string is an asterisks,
20909 search only the headlines.
20911 The search string is broken into \"words\" by splitting at whitespace.
20912 The individual words are then interpreted as a boolean expression with
20913 logical AND. Words prefixed with a minus must not occur in the entry.
20914 Words without a prefix or prefixed with a plus must occur in the entry.
20915 Matching is case-insensitive and the words are enclosed by word delimiters.
20917 Words enclosed by curly braces are interpreted as regular expressions
20918 that must or must not match in the entry.
20920 This command searches the agenda files, and in addition the files listed
20921 in `org-agenda-text-search-extra-files'."
20922 (interactive "P")
20923 (org-compile-prefix-format 'search)
20924 (org-set-sorting-strategy 'search)
20925 (org-prepare-agenda "SEARCH")
20926 (let* ((props (list 'face nil
20927 'done-face 'org-done
20928 'org-not-done-regexp org-not-done-regexp
20929 'org-todo-regexp org-todo-regexp
20930 'mouse-face 'highlight
20931 'keymap org-agenda-keymap
20932 'help-echo (format "mouse-2 or RET jump to location")))
20933 regexp rtn rtnall files file pos
20934 marker priority category tags c neg re
20935 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
20936 (unless (and (not arg)
20937 (stringp string)
20938 (string-match "\\S-" string))
20939 (setq string (read-string "[+-]Word/{Regexp} ...: "
20940 (cond
20941 ((integerp arg) (cons string arg))
20942 (arg string))
20943 'org-agenda-search-history)))
20944 (setq org-agenda-redo-command
20945 (list 'org-search-view 'current-prefix-arg string))
20946 (setq org-agenda-query-string string)
20948 (if (equal (string-to-char string) ?*)
20949 (setq hdl-only t
20950 words (substring string 1))
20951 (setq words string))
20952 (setq words (org-split-string words))
20953 (mapc (lambda (w)
20954 (setq c (string-to-char w))
20955 (if (equal c ?-)
20956 (setq neg t w (substring w 1))
20957 (if (equal c ?+)
20958 (setq neg nil w (substring w 1))
20959 (setq neg nil)))
20960 (if (string-match "\\`{.*}\\'" w)
20961 (setq re (substring w 1 -1))
20962 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
20963 (if neg (push re regexps-) (push re regexps+)))
20964 words)
20965 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
20966 (if (not regexps+)
20967 (setq regexp (concat "^" org-outline-regexp))
20968 (setq regexp (pop regexps+))
20969 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
20970 regexp))))
20971 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
20972 rtnall nil)
20973 (while (setq file (pop files))
20974 (setq ee nil)
20975 (catch 'nextfile
20976 (org-check-agenda-file file)
20977 (setq buffer (if (file-exists-p file)
20978 (org-get-agenda-file-buffer file)
20979 (error "No such file %s" file)))
20980 (if (not buffer)
20981 ;; If file does not exist, make sure an error message is sent
20982 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
20983 file))))
20984 (with-current-buffer buffer
20985 (unless (org-mode-p)
20986 (error "Agenda file %s is not in `org-mode'" file))
20987 (let ((case-fold-search t))
20988 (save-excursion
20989 (save-restriction
20990 (if org-agenda-restrict
20991 (narrow-to-region org-agenda-restrict-begin
20992 org-agenda-restrict-end)
20993 (widen))
20994 (goto-char (point-min))
20995 (unless (or (org-on-heading-p)
20996 (outline-next-heading))
20997 (throw 'nextfile t))
20998 (goto-char (max (point-min) (1- (point))))
20999 (while (re-search-forward regexp nil t)
21000 (org-back-to-heading t)
21001 (skip-chars-forward "* ")
21002 (setq beg (point-at-bol)
21003 beg1 (point)
21004 end (progn (outline-next-heading) (point)))
21005 (catch :skip
21006 (goto-char beg)
21007 (org-agenda-skip)
21008 (setq str (buffer-substring-no-properties
21009 (point-at-bol)
21010 (if hdl-only (point-at-eol) end)))
21011 (mapc (lambda (wr) (when (string-match wr str)
21012 (goto-char (1- end))
21013 (throw :skip t)))
21014 regexps-)
21015 (mapc (lambda (wr) (unless (string-match wr str)
21016 (goto-char (1- end))
21017 (throw :skip t)))
21018 regexps+)
21019 (goto-char beg)
21020 (setq marker (org-agenda-new-marker (point))
21021 category (org-get-category)
21022 tags (org-get-tags-at (point))
21023 txt (org-format-agenda-item
21025 (buffer-substring-no-properties
21026 beg1 (point-at-eol))
21027 category tags))
21028 (org-add-props txt props
21029 'org-marker marker 'org-hd-marker marker
21030 'priority 1000 'org-category category
21031 'type "search")
21032 (push txt ee)
21033 (goto-char (1- end)))))))))
21034 (setq rtn (nreverse ee))
21035 (setq rtnall (append rtnall rtn)))
21036 (if org-agenda-overriding-header
21037 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21038 nil 'face 'org-agenda-structure) "\n")
21039 (insert "Search words: ")
21040 (add-text-properties (point-min) (1- (point))
21041 (list 'face 'org-agenda-structure))
21042 (setq pos (point))
21043 (insert string "\n")
21044 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21045 (setq pos (point))
21046 (unless org-agenda-multi
21047 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21048 (add-text-properties pos (1- (point))
21049 (list 'face 'org-agenda-structure))))
21050 (when rtnall
21051 (insert (org-finalize-agenda-entries rtnall) "\n"))
21052 (goto-char (point-min))
21053 (org-fit-agenda-window)
21054 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21055 (org-finalize-agenda)
21056 (setq buffer-read-only t)))
21058 ;;; Agenda TODO list
21060 (defvar org-select-this-todo-keyword nil)
21061 (defvar org-last-arg nil)
21063 ;;;###autoload
21064 (defun org-todo-list (arg)
21065 "Show all TODO entries from all agenda file in a single list.
21066 The prefix arg can be used to select a specific TODO keyword and limit
21067 the list to these. When using \\[universal-argument], you will be prompted
21068 for a keyword. A numeric prefix directly selects the Nth keyword in
21069 `org-todo-keywords-1'."
21070 (interactive "P")
21071 (require 'calendar)
21072 (org-compile-prefix-format 'todo)
21073 (org-set-sorting-strategy 'todo)
21074 (org-prepare-agenda "TODO")
21075 (let* ((today (time-to-days (current-time)))
21076 (date (calendar-gregorian-from-absolute today))
21077 (kwds org-todo-keywords-for-agenda)
21078 (completion-ignore-case t)
21079 (org-select-this-todo-keyword
21080 (if (stringp arg) arg
21081 (and arg (integerp arg) (> arg 0)
21082 (nth (1- arg) kwds))))
21083 rtn rtnall files file pos)
21084 (when (equal arg '(4))
21085 (setq org-select-this-todo-keyword
21086 (completing-read "Keyword (or KWD1|K2D2|...): "
21087 (mapcar 'list kwds) nil nil)))
21088 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21089 (org-set-local 'org-last-arg arg)
21090 (setq org-agenda-redo-command
21091 '(org-todo-list (or current-prefix-arg org-last-arg)))
21092 (setq files (org-agenda-files)
21093 rtnall nil)
21094 (while (setq file (pop files))
21095 (catch 'nextfile
21096 (org-check-agenda-file file)
21097 (setq rtn (org-agenda-get-day-entries file date :todo))
21098 (setq rtnall (append rtnall rtn))))
21099 (if org-agenda-overriding-header
21100 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21101 nil 'face 'org-agenda-structure) "\n")
21102 (insert "Global list of TODO items of type: ")
21103 (add-text-properties (point-min) (1- (point))
21104 (list 'face 'org-agenda-structure))
21105 (setq pos (point))
21106 (insert (or org-select-this-todo-keyword "ALL") "\n")
21107 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21108 (setq pos (point))
21109 (unless org-agenda-multi
21110 (insert "Available with `N r': (0)ALL")
21111 (let ((n 0) s)
21112 (mapc (lambda (x)
21113 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21114 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21115 (insert "\n "))
21116 (insert " " s))
21117 kwds))
21118 (insert "\n"))
21119 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21120 (when rtnall
21121 (insert (org-finalize-agenda-entries rtnall) "\n"))
21122 (goto-char (point-min))
21123 (org-fit-agenda-window)
21124 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21125 (org-finalize-agenda)
21126 (setq buffer-read-only t)))
21128 ;;; Agenda tags match
21130 ;;;###autoload
21131 (defun org-tags-view (&optional todo-only match)
21132 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21133 The prefix arg TODO-ONLY limits the search to TODO entries."
21134 (interactive "P")
21135 (org-compile-prefix-format 'tags)
21136 (org-set-sorting-strategy 'tags)
21137 (let* ((org-tags-match-list-sublevels
21138 (if todo-only t org-tags-match-list-sublevels))
21139 (completion-ignore-case t)
21140 rtn rtnall files file pos matcher
21141 buffer)
21142 (setq matcher (org-make-tags-matcher match)
21143 match (car matcher) matcher (cdr matcher))
21144 (org-prepare-agenda (concat "TAGS " match))
21145 (setq org-agenda-redo-command
21146 (list 'org-tags-view (list 'quote todo-only)
21147 (list 'if 'current-prefix-arg nil match)))
21148 (setq files (org-agenda-files)
21149 rtnall nil)
21150 (while (setq file (pop files))
21151 (catch 'nextfile
21152 (org-check-agenda-file file)
21153 (setq buffer (if (file-exists-p file)
21154 (org-get-agenda-file-buffer file)
21155 (error "No such file %s" file)))
21156 (if (not buffer)
21157 ;; If file does not exist, merror message to agenda
21158 (setq rtn (list
21159 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21160 rtnall (append rtnall rtn))
21161 (with-current-buffer buffer
21162 (unless (org-mode-p)
21163 (error "Agenda file %s is not in `org-mode'" file))
21164 (save-excursion
21165 (save-restriction
21166 (if org-agenda-restrict
21167 (narrow-to-region org-agenda-restrict-begin
21168 org-agenda-restrict-end)
21169 (widen))
21170 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21171 (setq rtnall (append rtnall rtn))))))))
21172 (if org-agenda-overriding-header
21173 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21174 nil 'face 'org-agenda-structure) "\n")
21175 (insert "Headlines with TAGS match: ")
21176 (add-text-properties (point-min) (1- (point))
21177 (list 'face 'org-agenda-structure))
21178 (setq pos (point))
21179 (insert match "\n")
21180 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21181 (setq pos (point))
21182 (unless org-agenda-multi
21183 (insert "Press `C-u r' to search again with new search string\n"))
21184 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21185 (when rtnall
21186 (insert (org-finalize-agenda-entries rtnall) "\n"))
21187 (goto-char (point-min))
21188 (org-fit-agenda-window)
21189 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21190 (org-finalize-agenda)
21191 (setq buffer-read-only t)))
21193 ;;; Agenda Finding stuck projects
21195 (defvar org-agenda-skip-regexp nil
21196 "Regular expression used in skipping subtrees for the agenda.
21197 This is basically a temporary global variable that can be set and then
21198 used by user-defined selections using `org-agenda-skip-function'.")
21200 (defvar org-agenda-overriding-header nil
21201 "When this is set during todo and tags searches, will replace header.")
21203 (defun org-agenda-skip-subtree-when-regexp-matches ()
21204 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21205 If yes, it returns the end position of this tree, causing agenda commands
21206 to skip this subtree. This is a function that can be put into
21207 `org-agenda-skip-function' for the duration of a command."
21208 (let ((end (save-excursion (org-end-of-subtree t)))
21209 skip)
21210 (save-excursion
21211 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21212 (and skip end)))
21214 (defun org-agenda-skip-entry-if (&rest conditions)
21215 "Skip entry if any of CONDITIONS is true.
21216 See `org-agenda-skip-if' for details."
21217 (org-agenda-skip-if nil conditions))
21219 (defun org-agenda-skip-subtree-if (&rest conditions)
21220 "Skip entry if any of CONDITIONS is true.
21221 See `org-agenda-skip-if' for details."
21222 (org-agenda-skip-if t conditions))
21224 (defun org-agenda-skip-if (subtree conditions)
21225 "Checks current entity for CONDITIONS.
21226 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21227 the entry, i.e. the text before the next heading is checked.
21229 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21230 from different tests. Valid conditions are:
21232 scheduled Check if there is a scheduled cookie
21233 notscheduled Check if there is no scheduled cookie
21234 deadline Check if there is a deadline
21235 notdeadline Check if there is no deadline
21236 regexp Check if regexp matches
21237 notregexp Check if regexp does not match.
21239 The regexp is taken from the conditions list, it must come right after
21240 the `regexp' or `notregexp' element.
21242 If any of these conditions is met, this function returns the end point of
21243 the entity, causing the search to continue from there. This is a function
21244 that can be put into `org-agenda-skip-function' for the duration of a command."
21245 (let (beg end m)
21246 (org-back-to-heading t)
21247 (setq beg (point)
21248 end (if subtree
21249 (progn (org-end-of-subtree t) (point))
21250 (progn (outline-next-heading) (1- (point)))))
21251 (goto-char beg)
21252 (and
21254 (and (memq 'scheduled conditions)
21255 (re-search-forward org-scheduled-time-regexp end t))
21256 (and (memq 'notscheduled conditions)
21257 (not (re-search-forward org-scheduled-time-regexp end t)))
21258 (and (memq 'deadline conditions)
21259 (re-search-forward org-deadline-time-regexp end t))
21260 (and (memq 'notdeadline conditions)
21261 (not (re-search-forward org-deadline-time-regexp end t)))
21262 (and (setq m (memq 'regexp conditions))
21263 (stringp (nth 1 m))
21264 (re-search-forward (nth 1 m) end t))
21265 (and (setq m (memq 'notregexp conditions))
21266 (stringp (nth 1 m))
21267 (not (re-search-forward (nth 1 m) end t))))
21268 end)))
21270 ;;;###autoload
21271 (defun org-agenda-list-stuck-projects (&rest ignore)
21272 "Create agenda view for projects that are stuck.
21273 Stuck projects are project that have no next actions. For the definitions
21274 of what a project is and how to check if it stuck, customize the variable
21275 `org-stuck-projects'.
21276 MATCH is being ignored."
21277 (interactive)
21278 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21279 ;; FIXME: we could have used org-agenda-skip-if here.
21280 (org-agenda-overriding-header "List of stuck projects: ")
21281 (matcher (nth 0 org-stuck-projects))
21282 (todo (nth 1 org-stuck-projects))
21283 (todo-wds (if (member "*" todo)
21284 (progn
21285 (org-prepare-agenda-buffers (org-agenda-files))
21286 (org-delete-all
21287 org-done-keywords-for-agenda
21288 (copy-sequence org-todo-keywords-for-agenda)))
21289 todo))
21290 (todo-re (concat "^\\*+[ \t]+\\("
21291 (mapconcat 'identity todo-wds "\\|")
21292 "\\)\\>"))
21293 (tags (nth 2 org-stuck-projects))
21294 (tags-re (if (member "*" tags)
21295 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21296 (concat "^\\*+ .*:\\("
21297 (mapconcat 'identity tags "\\|")
21298 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21299 (gen-re (nth 3 org-stuck-projects))
21300 (re-list
21301 (delq nil
21302 (list
21303 (if todo todo-re)
21304 (if tags tags-re)
21305 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21306 gen-re)))))
21307 (setq org-agenda-skip-regexp
21308 (if re-list
21309 (mapconcat 'identity re-list "\\|")
21310 (error "No information how to identify unstuck projects")))
21311 (org-tags-view nil matcher)
21312 (with-current-buffer org-agenda-buffer-name
21313 (setq org-agenda-redo-command
21314 '(org-agenda-list-stuck-projects
21315 (or current-prefix-arg org-last-arg))))))
21317 ;;; Diary integration
21319 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21321 (defun org-get-entries-from-diary (date)
21322 "Get the (Emacs Calendar) diary entries for DATE."
21323 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21324 (diary-display-hook '(fancy-diary-display))
21325 (pop-up-frames nil)
21326 (list-diary-entries-hook
21327 (cons 'org-diary-default-entry list-diary-entries-hook))
21328 (diary-file-name-prefix-function nil) ; turn this feature off
21329 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21330 entries
21331 (org-disable-agenda-to-diary t))
21332 (save-excursion
21333 (save-window-excursion
21334 (funcall (if (fboundp 'diary-list-entries)
21335 'diary-list-entries 'list-diary-entries)
21336 date 1)))
21337 (if (not (get-buffer fancy-diary-buffer))
21338 (setq entries nil)
21339 (with-current-buffer fancy-diary-buffer
21340 (setq buffer-read-only nil)
21341 (if (zerop (buffer-size))
21342 ;; No entries
21343 (setq entries nil)
21344 ;; Omit the date and other unnecessary stuff
21345 (org-agenda-cleanup-fancy-diary)
21346 ;; Add prefix to each line and extend the text properties
21347 (if (zerop (buffer-size))
21348 (setq entries nil)
21349 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21350 (set-buffer-modified-p nil)
21351 (kill-buffer fancy-diary-buffer)))
21352 (when entries
21353 (setq entries (org-split-string entries "\n"))
21354 (setq entries
21355 (mapcar
21356 (lambda (x)
21357 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21358 ;; Extend the text properties to the beginning of the line
21359 (org-add-props x (text-properties-at (1- (length x)) x)
21360 'type "diary" 'date date))
21361 entries)))))
21363 (defun org-agenda-cleanup-fancy-diary ()
21364 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21365 This gets rid of the date, the underline under the date, and
21366 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21367 date. It also removes lines that contain only whitespace."
21368 (goto-char (point-min))
21369 (if (looking-at ".*?:[ \t]*")
21370 (progn
21371 (replace-match "")
21372 (re-search-forward "\n=+$" nil t)
21373 (replace-match "")
21374 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21375 (re-search-forward "\n=+$" nil t)
21376 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21377 (goto-char (point-min))
21378 (while (re-search-forward "^ +\n" nil t)
21379 (replace-match ""))
21380 (goto-char (point-min))
21381 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21382 (replace-match "")))
21384 ;; Make sure entries from the diary have the right text properties.
21385 (eval-after-load "diary-lib"
21386 '(if (boundp 'diary-modify-entry-list-string-function)
21387 ;; We can rely on the hook, nothing to do
21389 ;; Hook not avaiable, must use advice to make this work
21390 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21391 "Make the position visible."
21392 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21393 (stringp string)
21394 buffer-file-name)
21395 (setq string (org-modify-diary-entry-string string))))))
21397 (defun org-modify-diary-entry-string (string)
21398 "Add text properties to string, allowing org-mode to act on it."
21399 (org-add-props string nil
21400 'mouse-face 'highlight
21401 'keymap org-agenda-keymap
21402 'help-echo (if buffer-file-name
21403 (format "mouse-2 or RET jump to diary file %s"
21404 (abbreviate-file-name buffer-file-name))
21406 'org-agenda-diary-link t
21407 'org-marker (org-agenda-new-marker (point-at-bol))))
21409 (defun org-diary-default-entry ()
21410 "Add a dummy entry to the diary.
21411 Needed to avoid empty dates which mess up holiday display."
21412 ;; Catch the error if dealing with the new add-to-diary-alist
21413 (when org-disable-agenda-to-diary
21414 (condition-case nil
21415 (add-to-diary-list original-date "Org-mode dummy" "")
21416 (error
21417 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21419 ;;;###autoload
21420 (defun org-diary (&rest args)
21421 "Return diary information from org-files.
21422 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21423 It accesses org files and extracts information from those files to be
21424 listed in the diary. The function accepts arguments specifying what
21425 items should be listed. The following arguments are allowed:
21427 :timestamp List the headlines of items containing a date stamp or
21428 date range matching the selected date. Deadlines will
21429 also be listed, on the expiration day.
21431 :sexp List entries resulting from diary-like sexps.
21433 :deadline List any deadlines past due, or due within
21434 `org-deadline-warning-days'. The listing occurs only
21435 in the diary for *today*, not at any other date. If
21436 an entry is marked DONE, it is no longer listed.
21438 :scheduled List all items which are scheduled for the given date.
21439 The diary for *today* also contains items which were
21440 scheduled earlier and are not yet marked DONE.
21442 :todo List all TODO items from the org-file. This may be a
21443 long list - so this is not turned on by default.
21444 Like deadlines, these entries only show up in the
21445 diary for *today*, not at any other date.
21447 The call in the diary file should look like this:
21449 &%%(org-diary) ~/path/to/some/orgfile.org
21451 Use a separate line for each org file to check. Or, if you omit the file name,
21452 all files listed in `org-agenda-files' will be checked automatically:
21454 &%%(org-diary)
21456 If you don't give any arguments (as in the example above), the default
21457 arguments (:deadline :scheduled :timestamp :sexp) are used.
21458 So the example above may also be written as
21460 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21462 The function expects the lisp variables `entry' and `date' to be provided
21463 by the caller, because this is how the calendar works. Don't use this
21464 function from a program - use `org-agenda-get-day-entries' instead."
21465 (when (> (- (time-to-seconds (current-time))
21466 org-agenda-last-marker-time)
21468 (org-agenda-reset-markers))
21469 (org-compile-prefix-format 'agenda)
21470 (org-set-sorting-strategy 'agenda)
21471 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21472 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21473 (list entry)
21474 (org-agenda-files t)))
21475 file rtn results)
21476 (org-prepare-agenda-buffers files)
21477 ;; If this is called during org-agenda, don't return any entries to
21478 ;; the calendar. Org Agenda will list these entries itself.
21479 (if org-disable-agenda-to-diary (setq files nil))
21480 (while (setq file (pop files))
21481 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21482 (setq results (append results rtn)))
21483 (if results
21484 (concat (org-finalize-agenda-entries results) "\n"))))
21486 ;;; Agenda entry finders
21488 (defun org-agenda-get-day-entries (file date &rest args)
21489 "Does the work for `org-diary' and `org-agenda'.
21490 FILE is the path to a file to be checked for entries. DATE is date like
21491 the one returned by `calendar-current-date'. ARGS are symbols indicating
21492 which kind of entries should be extracted. For details about these, see
21493 the documentation of `org-diary'."
21494 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21495 (let* ((org-startup-folded nil)
21496 (org-startup-align-all-tables nil)
21497 (buffer (if (file-exists-p file)
21498 (org-get-agenda-file-buffer file)
21499 (error "No such file %s" file)))
21500 arg results rtn)
21501 (if (not buffer)
21502 ;; If file does not exist, make sure an error message ends up in diary
21503 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21504 (with-current-buffer buffer
21505 (unless (org-mode-p)
21506 (error "Agenda file %s is not in `org-mode'" file))
21507 (let ((case-fold-search nil))
21508 (save-excursion
21509 (save-restriction
21510 (if org-agenda-restrict
21511 (narrow-to-region org-agenda-restrict-begin
21512 org-agenda-restrict-end)
21513 (widen))
21514 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21515 (while (setq arg (pop args))
21516 (cond
21517 ((and (eq arg :todo)
21518 (equal date (calendar-current-date)))
21519 (setq rtn (org-agenda-get-todos))
21520 (setq results (append results rtn)))
21521 ((eq arg :timestamp)
21522 (setq rtn (org-agenda-get-blocks))
21523 (setq results (append results rtn))
21524 (setq rtn (org-agenda-get-timestamps))
21525 (setq results (append results rtn)))
21526 ((eq arg :sexp)
21527 (setq rtn (org-agenda-get-sexps))
21528 (setq results (append results rtn)))
21529 ((eq arg :scheduled)
21530 (setq rtn (org-agenda-get-scheduled))
21531 (setq results (append results rtn)))
21532 ((eq arg :closed)
21533 (setq rtn (org-agenda-get-closed))
21534 (setq results (append results rtn)))
21535 ((eq arg :deadline)
21536 (setq rtn (org-agenda-get-deadlines))
21537 (setq results (append results rtn))))))))
21538 results))))
21540 (defun org-entry-is-todo-p ()
21541 (member (org-get-todo-state) org-not-done-keywords))
21543 (defun org-entry-is-done-p ()
21544 (member (org-get-todo-state) org-done-keywords))
21546 (defun org-get-todo-state ()
21547 (save-excursion
21548 (org-back-to-heading t)
21549 (and (looking-at org-todo-line-regexp)
21550 (match-end 2)
21551 (match-string 2))))
21553 (defun org-at-date-range-p (&optional inactive-ok)
21554 "Is the cursor inside a date range?"
21555 (interactive)
21556 (save-excursion
21557 (catch 'exit
21558 (let ((pos (point)))
21559 (skip-chars-backward "^[<\r\n")
21560 (skip-chars-backward "<[")
21561 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21562 (>= (match-end 0) pos)
21563 (throw 'exit t))
21564 (skip-chars-backward "^<[\r\n")
21565 (skip-chars-backward "<[")
21566 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21567 (>= (match-end 0) pos)
21568 (throw 'exit t)))
21569 nil)))
21571 (defun org-agenda-get-todos ()
21572 "Return the TODO information for agenda display."
21573 (let* ((props (list 'face nil
21574 'done-face 'org-done
21575 'org-not-done-regexp org-not-done-regexp
21576 'org-todo-regexp org-todo-regexp
21577 'mouse-face 'highlight
21578 'keymap org-agenda-keymap
21579 'help-echo
21580 (format "mouse-2 or RET jump to org file %s"
21581 (abbreviate-file-name buffer-file-name))))
21582 ;; FIXME: get rid of the \n at some point but watch out
21583 (regexp (concat "^\\*+[ \t]+\\("
21584 (if org-select-this-todo-keyword
21585 (if (equal org-select-this-todo-keyword "*")
21586 org-todo-regexp
21587 (concat "\\<\\("
21588 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21589 "\\)\\>"))
21590 org-not-done-regexp)
21591 "[^\n\r]*\\)"))
21592 marker priority category tags
21593 ee txt beg end)
21594 (goto-char (point-min))
21595 (while (re-search-forward regexp nil t)
21596 (catch :skip
21597 (save-match-data
21598 (beginning-of-line)
21599 (setq beg (point) end (progn (outline-next-heading) (point)))
21600 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21601 (re-search-forward org-ts-regexp end t))
21602 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21603 (re-search-forward org-scheduled-time-regexp end t))
21604 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21605 (re-search-forward org-deadline-time-regexp end t)
21606 (org-deadline-close (match-string 1))))
21607 (goto-char (1+ beg))
21608 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21609 (throw :skip nil)))
21610 (goto-char beg)
21611 (org-agenda-skip)
21612 (goto-char (match-beginning 1))
21613 (setq marker (org-agenda-new-marker (match-beginning 0))
21614 category (org-get-category)
21615 tags (org-get-tags-at (point))
21616 txt (org-format-agenda-item "" (match-string 1) category tags)
21617 priority (1+ (org-get-priority txt)))
21618 (org-add-props txt props
21619 'org-marker marker 'org-hd-marker marker
21620 'priority priority 'org-category category
21621 'type "todo")
21622 (push txt ee)
21623 (if org-agenda-todo-list-sublevels
21624 (goto-char (match-end 1))
21625 (org-end-of-subtree 'invisible))))
21626 (nreverse ee)))
21628 (defconst org-agenda-no-heading-message
21629 "No heading for this item in buffer or region.")
21631 (defun org-agenda-get-timestamps ()
21632 "Return the date stamp information for agenda display."
21633 (let* ((props (list 'face nil
21634 'org-not-done-regexp org-not-done-regexp
21635 'org-todo-regexp org-todo-regexp
21636 'mouse-face 'highlight
21637 'keymap org-agenda-keymap
21638 'help-echo
21639 (format "mouse-2 or RET jump to org file %s"
21640 (abbreviate-file-name buffer-file-name))))
21641 (d1 (calendar-absolute-from-gregorian date))
21642 (remove-re
21643 (concat
21644 (regexp-quote
21645 (format-time-string
21646 "<%Y-%m-%d"
21647 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21648 ".*?>"))
21649 (regexp
21650 (concat
21651 (regexp-quote
21652 (substring
21653 (format-time-string
21654 (car org-time-stamp-formats)
21655 (apply 'encode-time ; DATE bound by calendar
21656 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21657 0 11))
21658 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21659 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21660 marker hdmarker deadlinep scheduledp donep tmp priority category
21661 ee txt timestr tags b0 b3 e3 head)
21662 (goto-char (point-min))
21663 (while (re-search-forward regexp nil t)
21664 (setq b0 (match-beginning 0)
21665 b3 (match-beginning 3) e3 (match-end 3))
21666 (catch :skip
21667 (and (org-at-date-range-p) (throw :skip nil))
21668 (org-agenda-skip)
21669 (if (and (match-end 1)
21670 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21671 (throw :skip nil))
21672 (if (and e3
21673 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21674 (throw :skip nil))
21675 (setq marker (org-agenda-new-marker b0)
21676 category (org-get-category b0)
21677 tmp (buffer-substring (max (point-min)
21678 (- b0 org-ds-keyword-length))
21680 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21681 deadlinep (string-match org-deadline-regexp tmp)
21682 scheduledp (string-match org-scheduled-regexp tmp)
21683 donep (org-entry-is-done-p))
21684 (if (or scheduledp deadlinep) (throw :skip t))
21685 (if (string-match ">" timestr)
21686 ;; substring should only run to end of time stamp
21687 (setq timestr (substring timestr 0 (match-end 0))))
21688 (save-excursion
21689 (if (re-search-backward "^\\*+ " nil t)
21690 (progn
21691 (goto-char (match-beginning 0))
21692 (setq hdmarker (org-agenda-new-marker)
21693 tags (org-get-tags-at))
21694 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21695 (setq head (match-string 1))
21696 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21697 (setq txt (org-format-agenda-item
21698 nil head category tags timestr nil
21699 remove-re)))
21700 (setq txt org-agenda-no-heading-message))
21701 (setq priority (org-get-priority txt))
21702 (org-add-props txt props
21703 'org-marker marker 'org-hd-marker hdmarker)
21704 (org-add-props txt nil 'priority priority
21705 'org-category category 'date date
21706 'type "timestamp")
21707 (push txt ee))
21708 (outline-next-heading)))
21709 (nreverse ee)))
21711 (defun org-agenda-get-sexps ()
21712 "Return the sexp information for agenda display."
21713 (require 'diary-lib)
21714 (let* ((props (list 'face nil
21715 'mouse-face 'highlight
21716 'keymap org-agenda-keymap
21717 'help-echo
21718 (format "mouse-2 or RET jump to org file %s"
21719 (abbreviate-file-name buffer-file-name))))
21720 (regexp "^&?%%(")
21721 marker category ee txt tags entry result beg b sexp sexp-entry)
21722 (goto-char (point-min))
21723 (while (re-search-forward regexp nil t)
21724 (catch :skip
21725 (org-agenda-skip)
21726 (setq beg (match-beginning 0))
21727 (goto-char (1- (match-end 0)))
21728 (setq b (point))
21729 (forward-sexp 1)
21730 (setq sexp (buffer-substring b (point)))
21731 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21732 (org-trim (match-string 1))
21733 ""))
21734 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21735 (when result
21736 (setq marker (org-agenda-new-marker beg)
21737 category (org-get-category beg))
21739 (if (string-match "\\S-" result)
21740 (setq txt result)
21741 (setq txt "SEXP entry returned empty string"))
21743 (setq txt (org-format-agenda-item
21744 "" txt category tags 'time))
21745 (org-add-props txt props 'org-marker marker)
21746 (org-add-props txt nil
21747 'org-category category 'date date
21748 'type "sexp")
21749 (push txt ee))))
21750 (nreverse ee)))
21752 (defun org-agenda-get-closed ()
21753 "Return the logged TODO entries for agenda display."
21754 (let* ((props (list 'mouse-face 'highlight
21755 'org-not-done-regexp org-not-done-regexp
21756 'org-todo-regexp org-todo-regexp
21757 'keymap org-agenda-keymap
21758 'help-echo
21759 (format "mouse-2 or RET jump to org file %s"
21760 (abbreviate-file-name buffer-file-name))))
21761 (regexp (concat
21762 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21763 (regexp-quote
21764 (substring
21765 (format-time-string
21766 (car org-time-stamp-formats)
21767 (apply 'encode-time ; DATE bound by calendar
21768 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21769 1 11))))
21770 marker hdmarker priority category tags closedp
21771 ee txt timestr)
21772 (goto-char (point-min))
21773 (while (re-search-forward regexp nil t)
21774 (catch :skip
21775 (org-agenda-skip)
21776 (setq marker (org-agenda-new-marker (match-beginning 0))
21777 closedp (equal (match-string 1) org-closed-string)
21778 category (org-get-category (match-beginning 0))
21779 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21780 ;; donep (org-entry-is-done-p)
21782 (if (string-match "\\]" timestr)
21783 ;; substring should only run to end of time stamp
21784 (setq timestr (substring timestr 0 (match-end 0))))
21785 (save-excursion
21786 (if (re-search-backward "^\\*+ " nil t)
21787 (progn
21788 (goto-char (match-beginning 0))
21789 (setq hdmarker (org-agenda-new-marker)
21790 tags (org-get-tags-at))
21791 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21792 (setq txt (org-format-agenda-item
21793 (if closedp "Closed: " "Clocked: ")
21794 (match-string 1) category tags timestr)))
21795 (setq txt org-agenda-no-heading-message))
21796 (setq priority 100000)
21797 (org-add-props txt props
21798 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21799 'priority priority 'org-category category
21800 'type "closed" 'date date
21801 'undone-face 'org-warning 'done-face 'org-done)
21802 (push txt ee))
21803 (goto-char (point-at-eol))))
21804 (nreverse ee)))
21806 (defun org-agenda-get-deadlines ()
21807 "Return the deadline information for agenda display."
21808 (let* ((props (list 'mouse-face 'highlight
21809 'org-not-done-regexp org-not-done-regexp
21810 'org-todo-regexp org-todo-regexp
21811 'keymap org-agenda-keymap
21812 'help-echo
21813 (format "mouse-2 or RET jump to org file %s"
21814 (abbreviate-file-name buffer-file-name))))
21815 (regexp org-deadline-time-regexp)
21816 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21817 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21818 d2 diff dfrac wdays pos pos1 category tags
21819 ee txt head face s upcomingp donep timestr)
21820 (goto-char (point-min))
21821 (while (re-search-forward regexp nil t)
21822 (catch :skip
21823 (org-agenda-skip)
21824 (setq s (match-string 1)
21825 pos (1- (match-beginning 1))
21826 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21827 diff (- d2 d1)
21828 wdays (org-get-wdays s)
21829 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21830 upcomingp (and todayp (> diff 0)))
21831 ;; When to show a deadline in the calendar:
21832 ;; If the expiration is within wdays warning time.
21833 ;; Past-due deadlines are only shown on the current date
21834 (if (or (and (<= diff wdays)
21835 (and todayp (not org-agenda-only-exact-dates)))
21836 (= diff 0))
21837 (save-excursion
21838 (setq category (org-get-category))
21839 (if (re-search-backward "^\\*+[ \t]+" nil t)
21840 (progn
21841 (goto-char (match-end 0))
21842 (setq pos1 (match-beginning 0))
21843 (setq tags (org-get-tags-at pos1))
21844 (setq head (buffer-substring-no-properties
21845 (point)
21846 (progn (skip-chars-forward "^\r\n")
21847 (point))))
21848 (setq donep (string-match org-looking-at-done-regexp head))
21849 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21850 (setq timestr
21851 (concat (substring s (match-beginning 1)) " "))
21852 (setq timestr 'time))
21853 (if (and donep
21854 (or org-agenda-skip-deadline-if-done
21855 (not (= diff 0))))
21856 (setq txt nil)
21857 (setq txt (org-format-agenda-item
21858 (if (= diff 0)
21859 (car org-agenda-deadline-leaders)
21860 (format (nth 1 org-agenda-deadline-leaders)
21861 diff))
21862 head category tags timestr))))
21863 (setq txt org-agenda-no-heading-message))
21864 (when txt
21865 (setq face (org-agenda-deadline-face dfrac wdays))
21866 (org-add-props txt props
21867 'org-marker (org-agenda-new-marker pos)
21868 'org-hd-marker (org-agenda-new-marker pos1)
21869 'priority (+ (- diff)
21870 (org-get-priority txt))
21871 'org-category category
21872 'type (if upcomingp "upcoming-deadline" "deadline")
21873 'date (if upcomingp date d2)
21874 'face (if donep 'org-done face)
21875 'undone-face face 'done-face 'org-done)
21876 (push txt ee))))))
21877 (nreverse ee)))
21879 (defun org-agenda-deadline-face (fraction &optional wdays)
21880 "Return the face to displaying a deadline item.
21881 FRACTION is what fraction of the head-warning time has passed."
21882 (if (equal wdays 0) (setq fraction 1.))
21883 (let ((faces org-agenda-deadline-faces) f)
21884 (catch 'exit
21885 (while (setq f (pop faces))
21886 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21888 (defun org-agenda-get-scheduled ()
21889 "Return the scheduled information for agenda display."
21890 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21891 'org-todo-regexp org-todo-regexp
21892 'done-face 'org-done
21893 'mouse-face 'highlight
21894 'keymap org-agenda-keymap
21895 'help-echo
21896 (format "mouse-2 or RET jump to org file %s"
21897 (abbreviate-file-name buffer-file-name))))
21898 (regexp org-scheduled-time-regexp)
21899 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21900 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21901 d2 diff pos pos1 category tags
21902 ee txt head pastschedp donep face timestr s)
21903 (goto-char (point-min))
21904 (while (re-search-forward regexp nil t)
21905 (catch :skip
21906 (org-agenda-skip)
21907 (setq s (match-string 1)
21908 pos (1- (match-beginning 1))
21909 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21910 ;;; is this right?
21911 ;;; do we need to do this for deadleine too????
21912 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21913 diff (- d2 d1))
21914 (setq pastschedp (and todayp (< diff 0)))
21915 ;; When to show a scheduled item in the calendar:
21916 ;; If it is on or past the date.
21917 (if (or (and (< diff 0)
21918 (and todayp (not org-agenda-only-exact-dates)))
21919 (= diff 0))
21920 (save-excursion
21921 (setq category (org-get-category))
21922 (if (re-search-backward "^\\*+[ \t]+" nil t)
21923 (progn
21924 (goto-char (match-end 0))
21925 (setq pos1 (match-beginning 0))
21926 (setq tags (org-get-tags-at))
21927 (setq head (buffer-substring-no-properties
21928 (point)
21929 (progn (skip-chars-forward "^\r\n") (point))))
21930 (setq donep (string-match org-looking-at-done-regexp head))
21931 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21932 (setq timestr
21933 (concat (substring s (match-beginning 1)) " "))
21934 (setq timestr 'time))
21935 (if (and donep
21936 (or org-agenda-skip-scheduled-if-done
21937 (not (= diff 0))))
21938 (setq txt nil)
21939 (setq txt (org-format-agenda-item
21940 (if (= diff 0)
21941 (car org-agenda-scheduled-leaders)
21942 (format (nth 1 org-agenda-scheduled-leaders)
21943 (- 1 diff)))
21944 head category tags timestr))))
21945 (setq txt org-agenda-no-heading-message))
21946 (when txt
21947 (setq face (if pastschedp
21948 'org-scheduled-previously
21949 'org-scheduled-today))
21950 (org-add-props txt props
21951 'undone-face face
21952 'face (if donep 'org-done face)
21953 'org-marker (org-agenda-new-marker pos)
21954 'org-hd-marker (org-agenda-new-marker pos1)
21955 'type (if pastschedp "past-scheduled" "scheduled")
21956 'date (if pastschedp d2 date)
21957 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21958 'org-category category)
21959 (push txt ee))))))
21960 (nreverse ee)))
21962 (defun org-agenda-get-blocks ()
21963 "Return the date-range information for agenda display."
21964 (let* ((props (list 'face nil
21965 'org-not-done-regexp org-not-done-regexp
21966 'org-todo-regexp org-todo-regexp
21967 'mouse-face 'highlight
21968 'keymap org-agenda-keymap
21969 'help-echo
21970 (format "mouse-2 or RET jump to org file %s"
21971 (abbreviate-file-name buffer-file-name))))
21972 (regexp org-tr-regexp)
21973 (d0 (calendar-absolute-from-gregorian date))
21974 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21975 donep head)
21976 (goto-char (point-min))
21977 (while (re-search-forward regexp nil t)
21978 (catch :skip
21979 (org-agenda-skip)
21980 (setq pos (point))
21981 (setq timestr (match-string 0)
21982 s1 (match-string 1)
21983 s2 (match-string 2)
21984 d1 (time-to-days (org-time-string-to-time s1))
21985 d2 (time-to-days (org-time-string-to-time s2)))
21986 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21987 ;; Only allow days between the limits, because the normal
21988 ;; date stamps will catch the limits.
21989 (save-excursion
21990 (setq marker (org-agenda-new-marker (point)))
21991 (setq category (org-get-category))
21992 (if (re-search-backward "^\\*+ " nil t)
21993 (progn
21994 (goto-char (match-beginning 0))
21995 (setq hdmarker (org-agenda-new-marker (point)))
21996 (setq tags (org-get-tags-at))
21997 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21998 (setq head (match-string 1))
21999 (and org-agenda-skip-timestamp-if-done
22000 (org-entry-is-done-p)
22001 (throw :skip t))
22002 (setq txt (org-format-agenda-item
22003 (format (if (= d1 d2) "" "(%d/%d): ")
22004 (1+ (- d0 d1)) (1+ (- d2 d1)))
22005 head category tags
22006 (if (= d0 d1) timestr))))
22007 (setq txt org-agenda-no-heading-message))
22008 (org-add-props txt props
22009 'org-marker marker 'org-hd-marker hdmarker
22010 'type "block" 'date date
22011 'priority (org-get-priority txt) 'org-category category)
22012 (push txt ee)))
22013 (goto-char pos)))
22014 ;; Sort the entries by expiration date.
22015 (nreverse ee)))
22017 ;;; Agenda presentation and sorting
22019 (defconst org-plain-time-of-day-regexp
22020 (concat
22021 "\\(\\<[012]?[0-9]"
22022 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22023 "\\(--?"
22024 "\\(\\<[012]?[0-9]"
22025 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22026 "\\)?")
22027 "Regular expression to match a plain time or time range.
22028 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22029 groups carry important information:
22030 0 the full match
22031 1 the first time, range or not
22032 8 the second time, if it is a range.")
22034 (defconst org-plain-time-extension-regexp
22035 (concat
22036 "\\(\\<[012]?[0-9]"
22037 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22038 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22039 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22040 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22041 groups carry important information:
22042 0 the full match
22043 7 hours of duration
22044 9 minutes of duration")
22046 (defconst org-stamp-time-of-day-regexp
22047 (concat
22048 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22049 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22050 "\\(--?"
22051 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22052 "Regular expression to match a timestamp time or time range.
22053 After a match, the following groups carry important information:
22054 0 the full match
22055 1 date plus weekday, for backreferencing to make sure both times on same day
22056 2 the first time, range or not
22057 4 the second time, if it is a range.")
22059 (defvar org-prefix-has-time nil
22060 "A flag, set by `org-compile-prefix-format'.
22061 The flag is set if the currently compiled format contains a `%t'.")
22062 (defvar org-prefix-has-tag nil
22063 "A flag, set by `org-compile-prefix-format'.
22064 The flag is set if the currently compiled format contains a `%T'.")
22066 (defun org-format-agenda-item (extra txt &optional category tags dotime
22067 noprefix remove-re)
22068 "Format TXT to be inserted into the agenda buffer.
22069 In particular, it adds the prefix and corresponding text properties. EXTRA
22070 must be a string and replaces the `%s' specifier in the prefix format.
22071 CATEGORY (string, symbol or nil) may be used to overrule the default
22072 category taken from local variable or file name. It will replace the `%c'
22073 specifier in the format. DOTIME, when non-nil, indicates that a
22074 time-of-day should be extracted from TXT for sorting of this entry, and for
22075 the `%t' specifier in the format. When DOTIME is a string, this string is
22076 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22077 only the correctly processes TXT should be returned - this is used by
22078 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22079 Any match of REMOVE-RE will be removed from TXT."
22080 (save-match-data
22081 ;; Diary entries sometimes have extra whitespace at the beginning
22082 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22083 (let* ((category (or category
22084 org-category
22085 (if buffer-file-name
22086 (file-name-sans-extension
22087 (file-name-nondirectory buffer-file-name))
22088 "")))
22089 (tag (if tags (nth (1- (length tags)) tags) ""))
22090 time ; time and tag are needed for the eval of the prefix format
22091 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22092 (time-of-day (and dotime (org-get-time-of-day ts)))
22093 stamp plain s0 s1 s2 rtn srp)
22094 (when (and dotime time-of-day org-prefix-has-time)
22095 ;; Extract starting and ending time and move them to prefix
22096 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22097 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22098 (setq s0 (match-string 0 ts)
22099 srp (and stamp (match-end 3))
22100 s1 (match-string (if plain 1 2) ts)
22101 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22103 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22104 ;; them, we might want to remove them there to avoid duplication.
22105 ;; The user can turn this off with a variable.
22106 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22107 (string-match (concat (regexp-quote s0) " *") txt)
22108 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22109 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22110 (= (match-beginning 0) 0)
22112 (setq txt (replace-match "" nil nil txt))))
22113 ;; Normalize the time(s) to 24 hour
22114 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22115 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22117 (when (and s1 (not s2) org-agenda-default-appointment-duration
22118 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22119 (let ((m (+ (string-to-number (match-string 2 s1))
22120 (* 60 (string-to-number (match-string 1 s1)))
22121 org-agenda-default-appointment-duration))
22123 (setq h (/ m 60) m (- m (* h 60)))
22124 (setq s2 (format "%02d:%02d" h m))))
22126 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22127 txt)
22128 ;; Tags are in the string
22129 (if (or (eq org-agenda-remove-tags t)
22130 (and org-agenda-remove-tags
22131 org-prefix-has-tag))
22132 (setq txt (replace-match "" t t txt))
22133 (setq txt (replace-match
22134 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22135 (match-string 2 txt))
22136 t t txt))))
22138 (when remove-re
22139 (while (string-match remove-re txt)
22140 (setq txt (replace-match "" t t txt))))
22142 ;; Create the final string
22143 (if noprefix
22144 (setq rtn txt)
22145 ;; Prepare the variables needed in the eval of the compiled format
22146 (setq time (cond (s2 (concat s1 "-" s2))
22147 (s1 (concat s1 "......"))
22148 (t ""))
22149 extra (or extra "")
22150 category (if (symbolp category) (symbol-name category) category))
22151 ;; Evaluate the compiled format
22152 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22154 ;; And finally add the text properties
22155 (org-add-props rtn nil
22156 'org-category (downcase category) 'tags tags
22157 'org-highest-priority org-highest-priority
22158 'org-lowest-priority org-lowest-priority
22159 'prefix-length (- (length rtn) (length txt))
22160 'time-of-day time-of-day
22161 'txt txt
22162 'time time
22163 'extra extra
22164 'dotime dotime))))
22166 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22167 (defvar org-agenda-sorting-strategy-selected nil)
22169 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22170 (catch 'exit
22171 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22172 ((and todayp (member 'today (car org-agenda-time-grid))))
22173 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22174 ((member 'weekly (car org-agenda-time-grid)))
22175 (t (throw 'exit list)))
22176 (let* ((have (delq nil (mapcar
22177 (lambda (x) (get-text-property 1 'time-of-day x))
22178 list)))
22179 (string (nth 1 org-agenda-time-grid))
22180 (gridtimes (nth 2 org-agenda-time-grid))
22181 (req (car org-agenda-time-grid))
22182 (remove (member 'remove-match req))
22183 new time)
22184 (if (and (member 'require-timed req) (not have))
22185 ;; don't show empty grid
22186 (throw 'exit list))
22187 (while (setq time (pop gridtimes))
22188 (unless (and remove (member time have))
22189 (setq time (int-to-string time))
22190 (push (org-format-agenda-item
22191 nil string "" nil
22192 (concat (substring time 0 -2) ":" (substring time -2)))
22193 new)
22194 (put-text-property
22195 1 (length (car new)) 'face 'org-time-grid (car new))))
22196 (if (member 'time-up org-agenda-sorting-strategy-selected)
22197 (append new list)
22198 (append list new)))))
22200 (defun org-compile-prefix-format (key)
22201 "Compile the prefix format into a Lisp form that can be evaluated.
22202 The resulting form is returned and stored in the variable
22203 `org-prefix-format-compiled'."
22204 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22205 (let ((s (cond
22206 ((stringp org-agenda-prefix-format)
22207 org-agenda-prefix-format)
22208 ((assq key org-agenda-prefix-format)
22209 (cdr (assq key org-agenda-prefix-format)))
22210 (t " %-12:c%?-12t% s")))
22211 (start 0)
22212 varform vars var e c f opt)
22213 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22214 s start)
22215 (setq var (cdr (assoc (match-string 4 s)
22216 '(("c" . category) ("t" . time) ("s" . extra)
22217 ("T" . tag))))
22218 c (or (match-string 3 s) "")
22219 opt (match-beginning 1)
22220 start (1+ (match-beginning 0)))
22221 (if (equal var 'time) (setq org-prefix-has-time t))
22222 (if (equal var 'tag) (setq org-prefix-has-tag t))
22223 (setq f (concat "%" (match-string 2 s) "s"))
22224 (if opt
22225 (setq varform
22226 `(if (equal "" ,var)
22228 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22229 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22230 (setq s (replace-match "%s" t nil s))
22231 (push varform vars))
22232 (setq vars (nreverse vars))
22233 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22235 (defun org-set-sorting-strategy (key)
22236 (if (symbolp (car org-agenda-sorting-strategy))
22237 ;; the old format
22238 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22239 (setq org-agenda-sorting-strategy-selected
22240 (or (cdr (assq key org-agenda-sorting-strategy))
22241 (cdr (assq 'agenda org-agenda-sorting-strategy))
22242 '(time-up category-keep priority-down)))))
22244 (defun org-get-time-of-day (s &optional string mod24)
22245 "Check string S for a time of day.
22246 If found, return it as a military time number between 0 and 2400.
22247 If not found, return nil.
22248 The optional STRING argument forces conversion into a 5 character wide string
22249 HH:MM."
22250 (save-match-data
22251 (when
22252 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22253 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22254 (let* ((h (string-to-number (match-string 1 s)))
22255 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22256 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22257 (am-p (equal ampm "am"))
22258 (h1 (cond ((not ampm) h)
22259 ((= h 12) (if am-p 0 12))
22260 (t (+ h (if am-p 0 12)))))
22261 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22262 (mod h1 24) h1))
22263 (t0 (+ (* 100 h2) m))
22264 (t1 (concat (if (>= h1 24) "+" " ")
22265 (if (< t0 100) "0" "")
22266 (if (< t0 10) "0" "")
22267 (int-to-string t0))))
22268 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22270 (defun org-finalize-agenda-entries (list &optional nosort)
22271 "Sort and concatenate the agenda items."
22272 (setq list (mapcar 'org-agenda-highlight-todo list))
22273 (if nosort
22274 list
22275 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22277 (defun org-agenda-highlight-todo (x)
22278 (let (re pl)
22279 (if (eq x 'line)
22280 (save-excursion
22281 (beginning-of-line 1)
22282 (setq re (get-text-property (point) 'org-todo-regexp))
22283 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22284 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22285 (add-text-properties (match-beginning 0) (match-end 0)
22286 (list 'face (org-get-todo-face 0)))
22287 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22288 (delete-region (match-beginning 1) (1- (match-end 0)))
22289 (goto-char (match-beginning 1))
22290 (insert (format org-agenda-todo-keyword-format s)))))
22291 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22292 pl (get-text-property 0 'prefix-length x))
22293 (when (and re
22294 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22295 x (or pl 0)) pl))
22296 (add-text-properties
22297 (or (match-end 1) (match-end 0)) (match-end 0)
22298 (list 'face (org-get-todo-face (match-string 2 x)))
22300 (setq x (concat (substring x 0 (match-end 1))
22301 (format org-agenda-todo-keyword-format
22302 (match-string 2 x))
22304 (substring x (match-end 3)))))
22305 x)))
22307 (defsubst org-cmp-priority (a b)
22308 "Compare the priorities of string A and B."
22309 (let ((pa (or (get-text-property 1 'priority a) 0))
22310 (pb (or (get-text-property 1 'priority b) 0)))
22311 (cond ((> pa pb) +1)
22312 ((< pa pb) -1)
22313 (t nil))))
22315 (defsubst org-cmp-category (a b)
22316 "Compare the string values of categories of strings A and B."
22317 (let ((ca (or (get-text-property 1 'org-category a) ""))
22318 (cb (or (get-text-property 1 'org-category b) "")))
22319 (cond ((string-lessp ca cb) -1)
22320 ((string-lessp cb ca) +1)
22321 (t nil))))
22323 (defsubst org-cmp-tag (a b)
22324 "Compare the string values of categories of strings A and B."
22325 (let ((ta (car (last (get-text-property 1 'tags a))))
22326 (tb (car (last (get-text-property 1 'tags b)))))
22327 (cond ((not ta) +1)
22328 ((not tb) -1)
22329 ((string-lessp ta tb) -1)
22330 ((string-lessp tb ta) +1)
22331 (t nil))))
22333 (defsubst org-cmp-time (a b)
22334 "Compare the time-of-day values of strings A and B."
22335 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22336 (ta (or (get-text-property 1 'time-of-day a) def))
22337 (tb (or (get-text-property 1 'time-of-day b) def)))
22338 (cond ((< ta tb) -1)
22339 ((< tb ta) +1)
22340 (t nil))))
22342 (defun org-entries-lessp (a b)
22343 "Predicate for sorting agenda entries."
22344 ;; The following variables will be used when the form is evaluated.
22345 ;; So even though the compiler complains, keep them.
22346 (let* ((time-up (org-cmp-time a b))
22347 (time-down (if time-up (- time-up) nil))
22348 (priority-up (org-cmp-priority a b))
22349 (priority-down (if priority-up (- priority-up) nil))
22350 (category-up (org-cmp-category a b))
22351 (category-down (if category-up (- category-up) nil))
22352 (category-keep (if category-up +1 nil))
22353 (tag-up (org-cmp-tag a b))
22354 (tag-down (if tag-up (- tag-up) nil)))
22355 (cdr (assoc
22356 (eval (cons 'or org-agenda-sorting-strategy-selected))
22357 '((-1 . t) (1 . nil) (nil . nil))))))
22359 ;;; Agenda restriction lock
22361 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22362 "Overlay to mark the headline to which arenda commands are restricted.")
22363 (org-overlay-put org-agenda-restriction-lock-overlay
22364 'face 'org-agenda-restriction-lock)
22365 (org-overlay-put org-agenda-restriction-lock-overlay
22366 'help-echo "Agendas are currently limited to this subtree.")
22367 (org-detach-overlay org-agenda-restriction-lock-overlay)
22368 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22369 "Overlay marking the agenda restriction line in speedbar.")
22370 (org-overlay-put org-speedbar-restriction-lock-overlay
22371 'face 'org-agenda-restriction-lock)
22372 (org-overlay-put org-speedbar-restriction-lock-overlay
22373 'help-echo "Agendas are currently limited to this item.")
22374 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22376 (defun org-agenda-set-restriction-lock (&optional type)
22377 "Set restriction lock for agenda, to current subtree or file.
22378 Restriction will be the file if TYPE is `file', or if type is the
22379 universal prefix '(4), or if the cursor is before the first headline
22380 in the file. Otherwise, restriction will be to the current subtree."
22381 (interactive "P")
22382 (and (equal type '(4)) (setq type 'file))
22383 (setq type (cond
22384 (type type)
22385 ((org-at-heading-p) 'subtree)
22386 ((condition-case nil (org-back-to-heading t) (error nil))
22387 'subtree)
22388 (t 'file)))
22389 (if (eq type 'subtree)
22390 (progn
22391 (setq org-agenda-restrict t)
22392 (setq org-agenda-overriding-restriction 'subtree)
22393 (put 'org-agenda-files 'org-restrict
22394 (list (buffer-file-name (buffer-base-buffer))))
22395 (org-back-to-heading t)
22396 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22397 (move-marker org-agenda-restrict-begin (point))
22398 (move-marker org-agenda-restrict-end
22399 (save-excursion (org-end-of-subtree t)))
22400 (message "Locking agenda restriction to subtree"))
22401 (put 'org-agenda-files 'org-restrict
22402 (list (buffer-file-name (buffer-base-buffer))))
22403 (setq org-agenda-restrict nil)
22404 (setq org-agenda-overriding-restriction 'file)
22405 (move-marker org-agenda-restrict-begin nil)
22406 (move-marker org-agenda-restrict-end nil)
22407 (message "Locking agenda restriction to file"))
22408 (setq current-prefix-arg nil)
22409 (org-agenda-maybe-redo))
22411 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22412 "Remove the agenda restriction lock."
22413 (interactive "P")
22414 (org-detach-overlay org-agenda-restriction-lock-overlay)
22415 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22416 (setq org-agenda-overriding-restriction nil)
22417 (setq org-agenda-restrict nil)
22418 (put 'org-agenda-files 'org-restrict nil)
22419 (move-marker org-agenda-restrict-begin nil)
22420 (move-marker org-agenda-restrict-end nil)
22421 (setq current-prefix-arg nil)
22422 (message "Agenda restriction lock removed")
22423 (or noupdate (org-agenda-maybe-redo)))
22425 (defun org-agenda-maybe-redo ()
22426 "If there is any window showing the agenda view, update it."
22427 (let ((w (get-buffer-window org-agenda-buffer-name t))
22428 (w0 (selected-window)))
22429 (when w
22430 (select-window w)
22431 (org-agenda-redo)
22432 (select-window w0)
22433 (if org-agenda-overriding-restriction
22434 (message "Agenda view shifted to new %s restriction"
22435 org-agenda-overriding-restriction)
22436 (message "Agenda restriction lock removed")))))
22438 ;;; Agenda commands
22440 (defun org-agenda-check-type (error &rest types)
22441 "Check if agenda buffer is of allowed type.
22442 If ERROR is non-nil, throw an error, otherwise just return nil."
22443 (if (memq org-agenda-type types)
22445 (if error
22446 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22447 nil)))
22449 (defun org-agenda-quit ()
22450 "Exit agenda by removing the window or the buffer."
22451 (interactive)
22452 (let ((buf (current-buffer)))
22453 (if (not (one-window-p)) (delete-window))
22454 (kill-buffer buf)
22455 (org-agenda-reset-markers)
22456 (org-columns-remove-overlays))
22457 ;; Maybe restore the pre-agenda window configuration.
22458 (and org-agenda-restore-windows-after-quit
22459 (not (eq org-agenda-window-setup 'other-frame))
22460 org-pre-agenda-window-conf
22461 (set-window-configuration org-pre-agenda-window-conf)))
22463 (defun org-agenda-exit ()
22464 "Exit agenda by removing the window or the buffer.
22465 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22466 Org-mode buffers visited directly by the user will not be touched."
22467 (interactive)
22468 (org-release-buffers org-agenda-new-buffers)
22469 (setq org-agenda-new-buffers nil)
22470 (org-agenda-quit))
22472 (defun org-agenda-execute (arg)
22473 "Execute another agenda command, keeping same window.\\<global-map>
22474 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22475 (interactive "P")
22476 (let ((org-agenda-window-setup 'current-window))
22477 (org-agenda arg)))
22479 (defun org-save-all-org-buffers ()
22480 "Save all Org-mode buffers without user confirmation."
22481 (interactive)
22482 (message "Saving all Org-mode buffers...")
22483 (save-some-buffers t 'org-mode-p)
22484 (message "Saving all Org-mode buffers... done"))
22486 (defun org-agenda-redo ()
22487 "Rebuild Agenda.
22488 When this is the global TODO list, a prefix argument will be interpreted."
22489 (interactive)
22490 (let* ((org-agenda-keep-modes t)
22491 (line (org-current-line))
22492 (window-line (- line (org-current-line (window-start))))
22493 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22494 (message "Rebuilding agenda buffer...")
22495 (org-let lprops '(eval org-agenda-redo-command))
22496 (setq org-agenda-undo-list nil
22497 org-agenda-pending-undo-list nil)
22498 (message "Rebuilding agenda buffer...done")
22499 (goto-line line)
22500 (recenter window-line)))
22502 (defun org-agenda-manipulate-query-add ()
22503 "Manipulate the query by adding a search term with positive selection.
22504 Positive selection means, the term must be matched for selection of an entry."
22505 (interactive)
22506 (org-agenda-manipulate-query ?\[))
22507 (defun org-agenda-manipulate-query-subtract ()
22508 "Manipulate the query by adding a search term with negative selection.
22509 Negative selection means, term must not be matched for selection of an entry."
22510 (interactive)
22511 (org-agenda-manipulate-query ?\]))
22512 (defun org-agenda-manipulate-query-add-re ()
22513 "Manipulate the query by adding a search regexp with positive selection.
22514 Positive selection means, the regexp must match for selection of an entry."
22515 (interactive)
22516 (org-agenda-manipulate-query ?\{))
22517 (defun org-agenda-manipulate-query-subtract-re ()
22518 "Manipulate the query by adding a search regexp with negative selection.
22519 Negative selection means, regexp must not match for selection of an entry."
22520 (interactive)
22521 (org-agenda-manipulate-query ?\}))
22522 (defun org-agenda-manipulate-query (char)
22523 (cond
22524 ((eq org-agenda-type 'search)
22525 (org-add-to-string
22526 'org-agenda-query-string
22527 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22528 (?\{ . " +{}") (?\} . " -{}")))))
22529 (setq org-agenda-redo-command
22530 (list 'org-search-view
22531 (+ (length org-agenda-query-string)
22532 (if (member char '(?\{ ?\})) 0 1))
22533 org-agenda-query-string))
22534 (set-register org-agenda-query-register org-agenda-query-string)
22535 (org-agenda-redo))
22536 (t (error "Canot manipulate query for %s-type agenda buffers"
22537 org-agenda-type))))
22539 (defun org-add-to-string (var string)
22540 (set var (concat (symbol-value var) string)))
22542 (defun org-agenda-goto-date (date)
22543 "Jump to DATE in agenda."
22544 (interactive (list (org-read-date)))
22545 (org-agenda-list nil date))
22547 (defun org-agenda-goto-today ()
22548 "Go to today."
22549 (interactive)
22550 (org-agenda-check-type t 'timeline 'agenda)
22551 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22552 (cond
22553 (tdpos (goto-char tdpos))
22554 ((eq org-agenda-type 'agenda)
22555 (let* ((sd (time-to-days
22556 (time-subtract (current-time)
22557 (list 0 (* 3600 org-extend-today-until) 0))))
22558 (comp (org-agenda-compute-time-span sd org-agenda-span))
22559 (org-agenda-overriding-arguments org-agenda-last-arguments))
22560 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22561 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22562 (org-agenda-redo)
22563 (org-agenda-find-same-or-today-or-agenda)))
22564 (t (error "Cannot find today")))))
22566 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22567 (goto-char
22568 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22569 (text-property-any (point-min) (point-max) 'org-today t)
22570 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22571 (point-min))))
22573 (defun org-agenda-later (arg)
22574 "Go forward in time by thee current span.
22575 With prefix ARG, go forward that many times the current span."
22576 (interactive "p")
22577 (org-agenda-check-type t 'agenda)
22578 (let* ((span org-agenda-span)
22579 (sd org-starting-day)
22580 (greg (calendar-gregorian-from-absolute sd))
22581 (cnt (get-text-property (point) 'org-day-cnt))
22582 greg2 nd)
22583 (cond
22584 ((eq span 'day)
22585 (setq sd (+ arg sd) nd 1))
22586 ((eq span 'week)
22587 (setq sd (+ (* 7 arg) sd) nd 7))
22588 ((eq span 'month)
22589 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22590 sd (calendar-absolute-from-gregorian greg2))
22591 (setcar greg2 (1+ (car greg2)))
22592 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22593 ((eq span 'year)
22594 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22595 sd (calendar-absolute-from-gregorian greg2))
22596 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22597 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22598 (let ((org-agenda-overriding-arguments
22599 (list (car org-agenda-last-arguments) sd nd t)))
22600 (org-agenda-redo)
22601 (org-agenda-find-same-or-today-or-agenda cnt))))
22603 (defun org-agenda-earlier (arg)
22604 "Go backward in time by the current span.
22605 With prefix ARG, go backward that many times the current span."
22606 (interactive "p")
22607 (org-agenda-later (- arg)))
22609 (defun org-agenda-day-view ()
22610 "Switch to daily view for agenda."
22611 (interactive)
22612 (setq org-agenda-ndays 1)
22613 (org-agenda-change-time-span 'day))
22614 (defun org-agenda-week-view ()
22615 "Switch to daily view for agenda."
22616 (interactive)
22617 (setq org-agenda-ndays 7)
22618 (org-agenda-change-time-span 'week))
22619 (defun org-agenda-month-view ()
22620 "Switch to daily view for agenda."
22621 (interactive)
22622 (org-agenda-change-time-span 'month))
22623 (defun org-agenda-year-view ()
22624 "Switch to daily view for agenda."
22625 (interactive)
22626 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22627 (org-agenda-change-time-span 'year)
22628 (error "Abort")))
22630 (defun org-agenda-change-time-span (span)
22631 "Change the agenda view to SPAN.
22632 SPAN may be `day', `week', `month', `year'."
22633 (org-agenda-check-type t 'agenda)
22634 (if (equal org-agenda-span span)
22635 (error "Viewing span is already \"%s\"" span))
22636 (let* ((sd (or (get-text-property (point) 'day)
22637 org-starting-day))
22638 (computed (org-agenda-compute-time-span sd span))
22639 (org-agenda-overriding-arguments
22640 (list (car org-agenda-last-arguments)
22641 (car computed) (cdr computed) t)))
22642 (org-agenda-redo)
22643 (org-agenda-find-same-or-today-or-agenda))
22644 (org-agenda-set-mode-name)
22645 (message "Switched to %s view" span))
22647 (defun org-agenda-compute-time-span (sd span)
22648 "Compute starting date and number of days for agenda.
22649 SPAN may be `day', `week', `month', `year'. The return value
22650 is a cons cell with the starting date and the number of days,
22651 so that the date SD will be in that range."
22652 (let* ((greg (calendar-gregorian-from-absolute sd))
22654 (cond
22655 ((eq span 'day)
22656 (setq nd 1))
22657 ((eq span 'week)
22658 (let* ((nt (calendar-day-of-week
22659 (calendar-gregorian-from-absolute sd)))
22660 (d (if org-agenda-start-on-weekday
22661 (- nt org-agenda-start-on-weekday)
22662 0)))
22663 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22664 (setq nd 7)))
22665 ((eq span 'month)
22666 (setq sd (calendar-absolute-from-gregorian
22667 (list (car greg) 1 (nth 2 greg)))
22668 nd (- (calendar-absolute-from-gregorian
22669 (list (1+ (car greg)) 1 (nth 2 greg)))
22670 sd)))
22671 ((eq span 'year)
22672 (setq sd (calendar-absolute-from-gregorian
22673 (list 1 1 (nth 2 greg)))
22674 nd (- (calendar-absolute-from-gregorian
22675 (list 1 1 (1+ (nth 2 greg))))
22676 sd))))
22677 (cons sd nd)))
22679 ;; FIXME: does not work if user makes date format that starts with a blank
22680 (defun org-agenda-next-date-line (&optional arg)
22681 "Jump to the next line indicating a date in agenda buffer."
22682 (interactive "p")
22683 (org-agenda-check-type t 'agenda 'timeline)
22684 (beginning-of-line 1)
22685 (if (looking-at "^\\S-") (forward-char 1))
22686 (if (not (re-search-forward "^\\S-" nil t arg))
22687 (progn
22688 (backward-char 1)
22689 (error "No next date after this line in this buffer")))
22690 (goto-char (match-beginning 0)))
22692 (defun org-agenda-previous-date-line (&optional arg)
22693 "Jump to the previous line indicating a date in agenda buffer."
22694 (interactive "p")
22695 (org-agenda-check-type t 'agenda 'timeline)
22696 (beginning-of-line 1)
22697 (if (not (re-search-backward "^\\S-" nil t arg))
22698 (error "No previous date before this line in this buffer")))
22700 ;; Initialize the highlight
22701 (defvar org-hl (org-make-overlay 1 1))
22702 (org-overlay-put org-hl 'face 'highlight)
22704 (defun org-highlight (begin end &optional buffer)
22705 "Highlight a region with overlay."
22706 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22707 org-hl begin end (or buffer (current-buffer))))
22709 (defun org-unhighlight ()
22710 "Detach overlay INDEX."
22711 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22713 ;; FIXME this is currently not used.
22714 (defun org-highlight-until-next-command (beg end &optional buffer)
22715 (org-highlight beg end buffer)
22716 (add-hook 'pre-command-hook 'org-unhighlight-once))
22717 (defun org-unhighlight-once ()
22718 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22719 (org-unhighlight))
22721 (defun org-agenda-follow-mode ()
22722 "Toggle follow mode in an agenda buffer."
22723 (interactive)
22724 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22725 (org-agenda-set-mode-name)
22726 (message "Follow mode is %s"
22727 (if org-agenda-follow-mode "on" "off")))
22729 (defun org-agenda-log-mode ()
22730 "Toggle log mode in an agenda buffer."
22731 (interactive)
22732 (org-agenda-check-type t 'agenda 'timeline)
22733 (setq org-agenda-show-log (not org-agenda-show-log))
22734 (org-agenda-set-mode-name)
22735 (org-agenda-redo)
22736 (message "Log mode is %s"
22737 (if org-agenda-show-log "on" "off")))
22739 (defun org-agenda-toggle-diary ()
22740 "Toggle diary inclusion in an agenda buffer."
22741 (interactive)
22742 (org-agenda-check-type t 'agenda)
22743 (setq org-agenda-include-diary (not org-agenda-include-diary))
22744 (org-agenda-redo)
22745 (org-agenda-set-mode-name)
22746 (message "Diary inclusion turned %s"
22747 (if org-agenda-include-diary "on" "off")))
22749 (defun org-agenda-toggle-time-grid ()
22750 "Toggle time grid in an agenda buffer."
22751 (interactive)
22752 (org-agenda-check-type t 'agenda)
22753 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22754 (org-agenda-redo)
22755 (org-agenda-set-mode-name)
22756 (message "Time-grid turned %s"
22757 (if org-agenda-use-time-grid "on" "off")))
22759 (defun org-agenda-set-mode-name ()
22760 "Set the mode name to indicate all the small mode settings."
22761 (setq mode-name
22762 (concat "Org-Agenda"
22763 (if (equal org-agenda-ndays 1) " Day" "")
22764 (if (equal org-agenda-ndays 7) " Week" "")
22765 (if org-agenda-follow-mode " Follow" "")
22766 (if org-agenda-include-diary " Diary" "")
22767 (if org-agenda-use-time-grid " Grid" "")
22768 (if org-agenda-show-log " Log" "")))
22769 (force-mode-line-update))
22771 (defun org-agenda-post-command-hook ()
22772 (and (eolp) (not (bolp)) (backward-char 1))
22773 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22774 (if (and org-agenda-follow-mode
22775 (get-text-property (point) 'org-marker))
22776 (org-agenda-show)))
22778 (defun org-agenda-show-priority ()
22779 "Show the priority of the current item.
22780 This priority is composed of the main priority given with the [#A] cookies,
22781 and by additional input from the age of a schedules or deadline entry."
22782 (interactive)
22783 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22784 (message "Priority is %d" (if pri pri -1000))))
22786 (defun org-agenda-show-tags ()
22787 "Show the tags applicable to the current item."
22788 (interactive)
22789 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22790 (if tags
22791 (message "Tags are :%s:"
22792 (org-no-properties (mapconcat 'identity tags ":")))
22793 (message "No tags associated with this line"))))
22795 (defun org-agenda-goto (&optional highlight)
22796 "Go to the Org-mode file which contains the item at point."
22797 (interactive)
22798 (let* ((marker (or (get-text-property (point) 'org-marker)
22799 (org-agenda-error)))
22800 (buffer (marker-buffer marker))
22801 (pos (marker-position marker)))
22802 (switch-to-buffer-other-window buffer)
22803 (widen)
22804 (goto-char pos)
22805 (when (org-mode-p)
22806 (org-show-context 'agenda)
22807 (save-excursion
22808 (and (outline-next-heading)
22809 (org-flag-heading nil)))) ; show the next heading
22810 (recenter (/ (window-height) 2))
22811 (run-hooks 'org-agenda-after-show-hook)
22812 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22814 (defvar org-agenda-after-show-hook nil
22815 "Normal hook run after an item has been shown from the agenda.
22816 Point is in the buffer where the item originated.")
22818 (defun org-agenda-kill ()
22819 "Kill the entry or subtree belonging to the current agenda entry."
22820 (interactive)
22821 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22822 (let* ((marker (or (get-text-property (point) 'org-marker)
22823 (org-agenda-error)))
22824 (buffer (marker-buffer marker))
22825 (pos (marker-position marker))
22826 (type (get-text-property (point) 'type))
22827 dbeg dend (n 0) conf)
22828 (org-with-remote-undo buffer
22829 (with-current-buffer buffer
22830 (save-excursion
22831 (goto-char pos)
22832 (if (and (org-mode-p) (not (member type '("sexp"))))
22833 (setq dbeg (progn (org-back-to-heading t) (point))
22834 dend (org-end-of-subtree t t))
22835 (setq dbeg (point-at-bol)
22836 dend (min (point-max) (1+ (point-at-eol)))))
22837 (goto-char dbeg)
22838 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22839 (setq conf (or (eq t org-agenda-confirm-kill)
22840 (and (numberp org-agenda-confirm-kill)
22841 (> n org-agenda-confirm-kill))))
22842 (and conf
22843 (not (y-or-n-p
22844 (format "Delete entry with %d lines in buffer \"%s\"? "
22845 n (buffer-name buffer))))
22846 (error "Abort"))
22847 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22848 (with-current-buffer buffer (delete-region dbeg dend))
22849 (message "Agenda item and source killed"))))
22851 (defun org-agenda-archive ()
22852 "Kill the entry or subtree belonging to the current agenda entry."
22853 (interactive)
22854 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22855 (let* ((marker (or (get-text-property (point) 'org-marker)
22856 (org-agenda-error)))
22857 (buffer (marker-buffer marker))
22858 (pos (marker-position marker)))
22859 (org-with-remote-undo buffer
22860 (with-current-buffer buffer
22861 (if (org-mode-p)
22862 (save-excursion
22863 (goto-char pos)
22864 (org-remove-subtree-entries-from-agenda)
22865 (org-back-to-heading t)
22866 (org-archive-subtree))
22867 (error "Archiving works only in Org-mode files"))))))
22869 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22870 "Remove all lines in the agenda that correspond to a given subtree.
22871 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22872 If this information is not given, the function uses the tree at point."
22873 (let ((buf (or buf (current-buffer))) m p)
22874 (save-excursion
22875 (unless (and beg end)
22876 (org-back-to-heading t)
22877 (setq beg (point))
22878 (org-end-of-subtree t)
22879 (setq end (point)))
22880 (set-buffer (get-buffer org-agenda-buffer-name))
22881 (save-excursion
22882 (goto-char (point-max))
22883 (beginning-of-line 1)
22884 (while (not (bobp))
22885 (when (and (setq m (get-text-property (point) 'org-marker))
22886 (equal buf (marker-buffer m))
22887 (setq p (marker-position m))
22888 (>= p beg)
22889 (<= p end))
22890 (let ((inhibit-read-only t))
22891 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22892 (beginning-of-line 0))))))
22894 (defun org-agenda-open-link ()
22895 "Follow the link in the current line, if any."
22896 (interactive)
22897 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22898 (save-excursion
22899 (save-restriction
22900 (narrow-to-region (point-at-bol) (point-at-eol))
22901 (org-open-at-point))))
22903 (defun org-agenda-copy-local-variable (var)
22904 "Get a variable from a referenced buffer and install it here."
22905 (let ((m (get-text-property (point) 'org-marker)))
22906 (when (and m (buffer-live-p (marker-buffer m)))
22907 (org-set-local var (with-current-buffer (marker-buffer m)
22908 (symbol-value var))))))
22910 (defun org-agenda-switch-to (&optional delete-other-windows)
22911 "Go to the Org-mode file which contains the item at point."
22912 (interactive)
22913 (let* ((marker (or (get-text-property (point) 'org-marker)
22914 (org-agenda-error)))
22915 (buffer (marker-buffer marker))
22916 (pos (marker-position marker)))
22917 (switch-to-buffer buffer)
22918 (and delete-other-windows (delete-other-windows))
22919 (widen)
22920 (goto-char pos)
22921 (when (org-mode-p)
22922 (org-show-context 'agenda)
22923 (save-excursion
22924 (and (outline-next-heading)
22925 (org-flag-heading nil)))))) ; show the next heading
22927 (defun org-agenda-goto-mouse (ev)
22928 "Go to the Org-mode file which contains the item at the mouse click."
22929 (interactive "e")
22930 (mouse-set-point ev)
22931 (org-agenda-goto))
22933 (defun org-agenda-show ()
22934 "Display the Org-mode file which contains the item at point."
22935 (interactive)
22936 (let ((win (selected-window)))
22937 (org-agenda-goto t)
22938 (select-window win)))
22940 (defun org-agenda-recenter (arg)
22941 "Display the Org-mode file which contains the item at point and recenter."
22942 (interactive "P")
22943 (let ((win (selected-window)))
22944 (org-agenda-goto t)
22945 (recenter arg)
22946 (select-window win)))
22948 (defun org-agenda-show-mouse (ev)
22949 "Display the Org-mode file which contains the item at the mouse click."
22950 (interactive "e")
22951 (mouse-set-point ev)
22952 (org-agenda-show))
22954 (defun org-agenda-check-no-diary ()
22955 "Check if the entry is a diary link and abort if yes."
22956 (if (get-text-property (point) 'org-agenda-diary-link)
22957 (org-agenda-error)))
22959 (defun org-agenda-error ()
22960 (error "Command not allowed in this line"))
22962 (defun org-agenda-tree-to-indirect-buffer ()
22963 "Show the subtree corresponding to the current entry in an indirect buffer.
22964 This calls the command `org-tree-to-indirect-buffer' from the original
22965 Org-mode buffer.
22966 With numerical prefix arg ARG, go up to this level and then take that tree.
22967 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22968 dedicated frame)."
22969 (interactive)
22970 (org-agenda-check-no-diary)
22971 (let* ((marker (or (get-text-property (point) 'org-marker)
22972 (org-agenda-error)))
22973 (buffer (marker-buffer marker))
22974 (pos (marker-position marker)))
22975 (with-current-buffer buffer
22976 (save-excursion
22977 (goto-char pos)
22978 (call-interactively 'org-tree-to-indirect-buffer)))))
22980 (defvar org-last-heading-marker (make-marker)
22981 "Marker pointing to the headline that last changed its TODO state
22982 by a remote command from the agenda.")
22984 (defun org-agenda-todo-nextset ()
22985 "Switch TODO entry to next sequence."
22986 (interactive)
22987 (org-agenda-todo 'nextset))
22989 (defun org-agenda-todo-previousset ()
22990 "Switch TODO entry to previous sequence."
22991 (interactive)
22992 (org-agenda-todo 'previousset))
22994 (defun org-agenda-todo (&optional arg)
22995 "Cycle TODO state of line at point, also in Org-mode file.
22996 This changes the line at point, all other lines in the agenda referring to
22997 the same tree node, and the headline of the tree node in the Org-mode file."
22998 (interactive "P")
22999 (org-agenda-check-no-diary)
23000 (let* ((col (current-column))
23001 (marker (or (get-text-property (point) 'org-marker)
23002 (org-agenda-error)))
23003 (buffer (marker-buffer marker))
23004 (pos (marker-position marker))
23005 (hdmarker (get-text-property (point) 'org-hd-marker))
23006 (inhibit-read-only t)
23007 newhead)
23008 (org-with-remote-undo buffer
23009 (with-current-buffer buffer
23010 (widen)
23011 (goto-char pos)
23012 (org-show-context 'agenda)
23013 (save-excursion
23014 (and (outline-next-heading)
23015 (org-flag-heading nil))) ; show the next heading
23016 (org-todo arg)
23017 (and (bolp) (forward-char 1))
23018 (setq newhead (org-get-heading))
23019 (save-excursion
23020 (org-back-to-heading)
23021 (move-marker org-last-heading-marker (point))))
23022 (beginning-of-line 1)
23023 (save-excursion
23024 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23025 (move-to-column col))))
23027 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23028 "Change all lines in the agenda buffer which match HDMARKER.
23029 The new content of the line will be NEWHEAD (as modified by
23030 `org-format-agenda-item'). HDMARKER is checked with
23031 `equal' against all `org-hd-marker' text properties in the file.
23032 If FIXFACE is non-nil, the face of each item is modified acording to
23033 the new TODO state."
23034 (let* ((inhibit-read-only t)
23035 props m pl undone-face done-face finish new dotime cat tags)
23036 (save-excursion
23037 (goto-char (point-max))
23038 (beginning-of-line 1)
23039 (while (not finish)
23040 (setq finish (bobp))
23041 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23042 (equal m hdmarker))
23043 (setq props (text-properties-at (point))
23044 dotime (get-text-property (point) 'dotime)
23045 cat (get-text-property (point) 'org-category)
23046 tags (get-text-property (point) 'tags)
23047 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23048 pl (get-text-property (point) 'prefix-length)
23049 undone-face (get-text-property (point) 'undone-face)
23050 done-face (get-text-property (point) 'done-face))
23051 (move-to-column pl)
23052 (cond
23053 ((equal new "")
23054 (beginning-of-line 1)
23055 (and (looking-at ".*\n?") (replace-match "")))
23056 ((looking-at ".*")
23057 (replace-match new t t)
23058 (beginning-of-line 1)
23059 (add-text-properties (point-at-bol) (point-at-eol) props)
23060 (when fixface
23061 (add-text-properties
23062 (point-at-bol) (point-at-eol)
23063 (list 'face
23064 (if org-last-todo-state-is-todo
23065 undone-face done-face))))
23066 (org-agenda-highlight-todo 'line)
23067 (beginning-of-line 1))
23068 (t (error "Line update did not work"))))
23069 (beginning-of-line 0)))
23070 (org-finalize-agenda)))
23072 (defun org-agenda-align-tags (&optional line)
23073 "Align all tags in agenda items to `org-agenda-tags-column'."
23074 (let ((inhibit-read-only t) l c)
23075 (save-excursion
23076 (goto-char (if line (point-at-bol) (point-min)))
23077 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23078 (if line (point-at-eol) nil) t)
23079 (add-text-properties
23080 (match-beginning 2) (match-end 2)
23081 (list 'face (delq nil (list 'org-tag (get-text-property
23082 (match-beginning 2) 'face)))))
23083 (setq l (- (match-end 2) (match-beginning 2))
23084 c (if (< org-agenda-tags-column 0)
23085 (- (abs org-agenda-tags-column) l)
23086 org-agenda-tags-column))
23087 (delete-region (match-beginning 1) (match-end 1))
23088 (goto-char (match-beginning 1))
23089 (insert (org-add-props
23090 (make-string (max 1 (- c (current-column))) ?\ )
23091 (text-properties-at (point))))))))
23093 (defun org-agenda-priority-up ()
23094 "Increase the priority of line at point, also in Org-mode file."
23095 (interactive)
23096 (org-agenda-priority 'up))
23098 (defun org-agenda-priority-down ()
23099 "Decrease the priority of line at point, also in Org-mode file."
23100 (interactive)
23101 (org-agenda-priority 'down))
23103 (defun org-agenda-priority (&optional force-direction)
23104 "Set the priority of line at point, also in Org-mode file.
23105 This changes the line at point, all other lines in the agenda referring to
23106 the same tree node, and the headline of the tree node in the Org-mode file."
23107 (interactive)
23108 (org-agenda-check-no-diary)
23109 (let* ((marker (or (get-text-property (point) 'org-marker)
23110 (org-agenda-error)))
23111 (hdmarker (get-text-property (point) 'org-hd-marker))
23112 (buffer (marker-buffer hdmarker))
23113 (pos (marker-position hdmarker))
23114 (inhibit-read-only t)
23115 newhead)
23116 (org-with-remote-undo buffer
23117 (with-current-buffer buffer
23118 (widen)
23119 (goto-char pos)
23120 (org-show-context 'agenda)
23121 (save-excursion
23122 (and (outline-next-heading)
23123 (org-flag-heading nil))) ; show the next heading
23124 (funcall 'org-priority force-direction)
23125 (end-of-line 1)
23126 (setq newhead (org-get-heading)))
23127 (org-agenda-change-all-lines newhead hdmarker)
23128 (beginning-of-line 1))))
23130 (defun org-get-tags-at (&optional pos)
23131 "Get a list of all headline tags applicable at POS.
23132 POS defaults to point. If tags are inherited, the list contains
23133 the targets in the same sequence as the headlines appear, i.e.
23134 the tags of the current headline come last."
23135 (interactive)
23136 (let (tags lastpos)
23137 (save-excursion
23138 (save-restriction
23139 (widen)
23140 (goto-char (or pos (point)))
23141 (save-match-data
23142 (org-back-to-heading t)
23143 (condition-case nil
23144 (while (not (equal lastpos (point)))
23145 (setq lastpos (point))
23146 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23147 (setq tags (append (org-split-string
23148 (org-match-string-no-properties 1) ":")
23149 tags)))
23150 (or org-use-tag-inheritance (error ""))
23151 (org-up-heading-all 1))
23152 (error nil))))
23153 tags)))
23155 ;; FIXME: should fix the tags property of the agenda line.
23156 (defun org-agenda-set-tags ()
23157 "Set tags for the current headline."
23158 (interactive)
23159 (org-agenda-check-no-diary)
23160 (if (and (org-region-active-p) (interactive-p))
23161 (call-interactively 'org-change-tag-in-region)
23162 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23163 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23164 (org-agenda-error)))
23165 (buffer (marker-buffer hdmarker))
23166 (pos (marker-position hdmarker))
23167 (inhibit-read-only t)
23168 newhead)
23169 (org-with-remote-undo buffer
23170 (with-current-buffer buffer
23171 (widen)
23172 (goto-char pos)
23173 (save-excursion
23174 (org-show-context 'agenda))
23175 (save-excursion
23176 (and (outline-next-heading)
23177 (org-flag-heading nil))) ; show the next heading
23178 (goto-char pos)
23179 (call-interactively 'org-set-tags)
23180 (end-of-line 1)
23181 (setq newhead (org-get-heading)))
23182 (org-agenda-change-all-lines newhead hdmarker)
23183 (beginning-of-line 1)))))
23185 (defun org-agenda-toggle-archive-tag ()
23186 "Toggle the archive tag for the current entry."
23187 (interactive)
23188 (org-agenda-check-no-diary)
23189 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23190 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23191 (org-agenda-error)))
23192 (buffer (marker-buffer hdmarker))
23193 (pos (marker-position hdmarker))
23194 (inhibit-read-only t)
23195 newhead)
23196 (org-with-remote-undo buffer
23197 (with-current-buffer buffer
23198 (widen)
23199 (goto-char pos)
23200 (org-show-context 'agenda)
23201 (save-excursion
23202 (and (outline-next-heading)
23203 (org-flag-heading nil))) ; show the next heading
23204 (call-interactively 'org-toggle-archive-tag)
23205 (end-of-line 1)
23206 (setq newhead (org-get-heading)))
23207 (org-agenda-change-all-lines newhead hdmarker)
23208 (beginning-of-line 1))))
23210 (defun org-agenda-date-later (arg &optional what)
23211 "Change the date of this item to one day later."
23212 (interactive "p")
23213 (org-agenda-check-type t 'agenda 'timeline)
23214 (org-agenda-check-no-diary)
23215 (let* ((marker (or (get-text-property (point) 'org-marker)
23216 (org-agenda-error)))
23217 (buffer (marker-buffer marker))
23218 (pos (marker-position marker)))
23219 (org-with-remote-undo buffer
23220 (with-current-buffer buffer
23221 (widen)
23222 (goto-char pos)
23223 (if (not (org-at-timestamp-p))
23224 (error "Cannot find time stamp"))
23225 (org-timestamp-change arg (or what 'day)))
23226 (org-agenda-show-new-time marker org-last-changed-timestamp))
23227 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23229 (defun org-agenda-date-earlier (arg &optional what)
23230 "Change the date of this item to one day earlier."
23231 (interactive "p")
23232 (org-agenda-date-later (- arg) what))
23234 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23235 "Show new date stamp via text properties."
23236 ;; We use text properties to make this undoable
23237 (let ((inhibit-read-only t))
23238 (setq stamp (concat " " prefix " => " stamp))
23239 (save-excursion
23240 (goto-char (point-max))
23241 (while (not (bobp))
23242 (when (equal marker (get-text-property (point) 'org-marker))
23243 (move-to-column (- (window-width) (length stamp)) t)
23244 (if (featurep 'xemacs)
23245 ;; Use `duplicable' property to trigger undo recording
23246 (let ((ex (make-extent nil nil))
23247 (gl (make-glyph stamp)))
23248 (set-glyph-face gl 'secondary-selection)
23249 (set-extent-properties
23250 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23251 (insert-extent ex (1- (point)) (point-at-eol)))
23252 (add-text-properties
23253 (1- (point)) (point-at-eol)
23254 (list 'display (org-add-props stamp nil
23255 'face 'secondary-selection))))
23256 (beginning-of-line 1))
23257 (beginning-of-line 0)))))
23259 (defun org-agenda-date-prompt (arg)
23260 "Change the date of this item. Date is prompted for, with default today.
23261 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23262 be used to request time specification in the time stamp."
23263 (interactive "P")
23264 (org-agenda-check-type t 'agenda 'timeline)
23265 (org-agenda-check-no-diary)
23266 (let* ((marker (or (get-text-property (point) 'org-marker)
23267 (org-agenda-error)))
23268 (buffer (marker-buffer marker))
23269 (pos (marker-position marker)))
23270 (org-with-remote-undo buffer
23271 (with-current-buffer buffer
23272 (widen)
23273 (goto-char pos)
23274 (if (not (org-at-timestamp-p))
23275 (error "Cannot find time stamp"))
23276 (org-time-stamp arg)
23277 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23279 (defun org-agenda-schedule (arg)
23280 "Schedule the item at point."
23281 (interactive "P")
23282 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23283 (org-agenda-check-no-diary)
23284 (let* ((marker (or (get-text-property (point) 'org-marker)
23285 (org-agenda-error)))
23286 (buffer (marker-buffer marker))
23287 (pos (marker-position marker))
23288 (org-insert-labeled-timestamps-at-point nil)
23290 (message "%s" (marker-insertion-type marker)) (sit-for 3)
23291 (set-marker-insertion-type marker t)
23292 (org-with-remote-undo buffer
23293 (with-current-buffer buffer
23294 (widen)
23295 (goto-char pos)
23296 (setq ts (org-schedule arg)))
23297 (org-agenda-show-new-time marker ts "S"))
23298 (message "Item scheduled for %s" ts)))
23300 (defun org-agenda-deadline (arg)
23301 "Schedule the item at point."
23302 (interactive "P")
23303 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23304 (org-agenda-check-no-diary)
23305 (let* ((marker (or (get-text-property (point) 'org-marker)
23306 (org-agenda-error)))
23307 (buffer (marker-buffer marker))
23308 (pos (marker-position marker))
23309 (org-insert-labeled-timestamps-at-point nil)
23311 (org-with-remote-undo buffer
23312 (with-current-buffer buffer
23313 (widen)
23314 (goto-char pos)
23315 (setq ts (org-deadline arg)))
23316 (org-agenda-show-new-time marker ts "S"))
23317 (message "Deadline for this item set to %s" ts)))
23319 (defun org-get-heading (&optional no-tags)
23320 "Return the heading of the current entry, without the stars."
23321 (save-excursion
23322 (org-back-to-heading t)
23323 (if (looking-at
23324 (if no-tags
23325 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23326 "\\*+[ \t]+\\([^\r\n]*\\)"))
23327 (match-string 1) "")))
23329 (defun org-agenda-clock-in (&optional arg)
23330 "Start the clock on the currently selected item."
23331 (interactive "P")
23332 (org-agenda-check-no-diary)
23333 (let* ((marker (or (get-text-property (point) 'org-marker)
23334 (org-agenda-error)))
23335 (pos (marker-position marker)))
23336 (org-with-remote-undo (marker-buffer marker)
23337 (with-current-buffer (marker-buffer marker)
23338 (widen)
23339 (goto-char pos)
23340 (org-clock-in)))))
23342 (defun org-agenda-clock-out (&optional arg)
23343 "Stop the currently running clock."
23344 (interactive "P")
23345 (unless (marker-buffer org-clock-marker)
23346 (error "No running clock"))
23347 (org-with-remote-undo (marker-buffer org-clock-marker)
23348 (org-clock-out)))
23350 (defun org-agenda-clock-cancel (&optional arg)
23351 "Cancel the currently running clock."
23352 (interactive "P")
23353 (unless (marker-buffer org-clock-marker)
23354 (error "No running clock"))
23355 (org-with-remote-undo (marker-buffer org-clock-marker)
23356 (org-clock-cancel)))
23358 (defun org-agenda-diary-entry ()
23359 "Make a diary entry, like the `i' command from the calendar.
23360 All the standard commands work: block, weekly etc."
23361 (interactive)
23362 (org-agenda-check-type t 'agenda 'timeline)
23363 (require 'diary-lib)
23364 (let* ((char (progn
23365 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23366 (read-char-exclusive)))
23367 (cmd (cdr (assoc char
23368 '((?d . insert-diary-entry)
23369 (?w . insert-weekly-diary-entry)
23370 (?m . insert-monthly-diary-entry)
23371 (?y . insert-yearly-diary-entry)
23372 (?a . insert-anniversary-diary-entry)
23373 (?b . insert-block-diary-entry)
23374 (?c . insert-cyclic-diary-entry)))))
23375 (oldf (symbol-function 'calendar-cursor-to-date))
23376 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23377 (point (point))
23378 (mark (or (mark t) (point))))
23379 (unless cmd
23380 (error "No command associated with <%c>" char))
23381 (unless (and (get-text-property point 'day)
23382 (or (not (equal ?b char))
23383 (get-text-property mark 'day)))
23384 (error "Don't know which date to use for diary entry"))
23385 ;; We implement this by hacking the `calendar-cursor-to-date' function
23386 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23387 (let ((calendar-mark-ring
23388 (list (calendar-gregorian-from-absolute
23389 (or (get-text-property mark 'day)
23390 (get-text-property point 'day))))))
23391 (unwind-protect
23392 (progn
23393 (fset 'calendar-cursor-to-date
23394 (lambda (&optional error)
23395 (calendar-gregorian-from-absolute
23396 (get-text-property point 'day))))
23397 (call-interactively cmd))
23398 (fset 'calendar-cursor-to-date oldf)))))
23401 (defun org-agenda-execute-calendar-command (cmd)
23402 "Execute a calendar command from the agenda, with the date associated to
23403 the cursor position."
23404 (org-agenda-check-type t 'agenda 'timeline)
23405 (require 'diary-lib)
23406 (unless (get-text-property (point) 'day)
23407 (error "Don't know which date to use for calendar command"))
23408 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23409 (point (point))
23410 (date (calendar-gregorian-from-absolute
23411 (get-text-property point 'day)))
23412 ;; the following 3 vars are needed in the calendar
23413 (displayed-day (extract-calendar-day date))
23414 (displayed-month (extract-calendar-month date))
23415 (displayed-year (extract-calendar-year date)))
23416 (unwind-protect
23417 (progn
23418 (fset 'calendar-cursor-to-date
23419 (lambda (&optional error)
23420 (calendar-gregorian-from-absolute
23421 (get-text-property point 'day))))
23422 (call-interactively cmd))
23423 (fset 'calendar-cursor-to-date oldf))))
23425 (defun org-agenda-phases-of-moon ()
23426 "Display the phases of the moon for the 3 months around the cursor date."
23427 (interactive)
23428 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23430 (defun org-agenda-holidays ()
23431 "Display the holidays for the 3 months around the cursor date."
23432 (interactive)
23433 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23435 (defun org-agenda-sunrise-sunset (arg)
23436 "Display sunrise and sunset for the cursor date.
23437 Latitude and longitude can be specified with the variables
23438 `calendar-latitude' and `calendar-longitude'. When called with prefix
23439 argument, latitude and longitude will be prompted for."
23440 (interactive "P")
23441 (let ((calendar-longitude (if arg nil calendar-longitude))
23442 (calendar-latitude (if arg nil calendar-latitude))
23443 (calendar-location-name
23444 (if arg "the given coordinates" calendar-location-name)))
23445 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23447 (defun org-agenda-goto-calendar ()
23448 "Open the Emacs calendar with the date at the cursor."
23449 (interactive)
23450 (org-agenda-check-type t 'agenda 'timeline)
23451 (let* ((day (or (get-text-property (point) 'day)
23452 (error "Don't know which date to open in calendar")))
23453 (date (calendar-gregorian-from-absolute day))
23454 (calendar-move-hook nil)
23455 (view-calendar-holidays-initially nil)
23456 (view-diary-entries-initially nil))
23457 (calendar)
23458 (calendar-goto-date date)))
23460 (defun org-calendar-goto-agenda ()
23461 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23462 This is a command that has to be installed in `calendar-mode-map'."
23463 (interactive)
23464 (org-agenda-list nil (calendar-absolute-from-gregorian
23465 (calendar-cursor-to-date))
23466 nil))
23468 (defun org-agenda-convert-date ()
23469 (interactive)
23470 (org-agenda-check-type t 'agenda 'timeline)
23471 (let ((day (get-text-property (point) 'day))
23472 date s)
23473 (unless day
23474 (error "Don't know which date to convert"))
23475 (setq date (calendar-gregorian-from-absolute day))
23476 (setq s (concat
23477 "Gregorian: " (calendar-date-string date) "\n"
23478 "ISO: " (calendar-iso-date-string date) "\n"
23479 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23480 "Julian: " (calendar-julian-date-string date) "\n"
23481 "Astron. JD: " (calendar-astro-date-string date)
23482 " (Julian date number at noon UTC)\n"
23483 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23484 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23485 "French: " (calendar-french-date-string date) "\n"
23486 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23487 "Mayan: " (calendar-mayan-date-string date) "\n"
23488 "Coptic: " (calendar-coptic-date-string date) "\n"
23489 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23490 "Persian: " (calendar-persian-date-string date) "\n"
23491 "Chinese: " (calendar-chinese-date-string date) "\n"))
23492 (with-output-to-temp-buffer "*Dates*"
23493 (princ s))
23494 (if (fboundp 'fit-window-to-buffer)
23495 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23498 ;;;; Embedded LaTeX
23500 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23501 "Keymap for the minor `org-cdlatex-mode'.")
23503 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23504 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23505 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23506 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23507 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23509 (defvar org-cdlatex-texmathp-advice-is-done nil
23510 "Flag remembering if we have applied the advice to texmathp already.")
23512 (define-minor-mode org-cdlatex-mode
23513 "Toggle the minor `org-cdlatex-mode'.
23514 This mode supports entering LaTeX environment and math in LaTeX fragments
23515 in Org-mode.
23516 \\{org-cdlatex-mode-map}"
23517 nil " OCDL" nil
23518 (when org-cdlatex-mode (require 'cdlatex))
23519 (unless org-cdlatex-texmathp-advice-is-done
23520 (setq org-cdlatex-texmathp-advice-is-done t)
23521 (defadvice texmathp (around org-math-always-on activate)
23522 "Always return t in org-mode buffers.
23523 This is because we want to insert math symbols without dollars even outside
23524 the LaTeX math segments. If Orgmode thinks that point is actually inside
23525 en embedded LaTeX fragement, let texmathp do its job.
23526 \\[org-cdlatex-mode-map]"
23527 (interactive)
23528 (let (p)
23529 (cond
23530 ((not (org-mode-p)) ad-do-it)
23531 ((eq this-command 'cdlatex-math-symbol)
23532 (setq ad-return-value t
23533 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23535 (let ((p (org-inside-LaTeX-fragment-p)))
23536 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23537 (setq ad-return-value t
23538 texmathp-why '("Org-mode embedded math" . 0))
23539 (if p ad-do-it)))))))))
23541 (defun turn-on-org-cdlatex ()
23542 "Unconditionally turn on `org-cdlatex-mode'."
23543 (org-cdlatex-mode 1))
23545 (defun org-inside-LaTeX-fragment-p ()
23546 "Test if point is inside a LaTeX fragment.
23547 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23548 sequence appearing also before point.
23549 Even though the matchers for math are configurable, this function assumes
23550 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23551 delimiters are skipped when they have been removed by customization.
23552 The return value is nil, or a cons cell with the delimiter and
23553 and the position of this delimiter.
23555 This function does a reasonably good job, but can locally be fooled by
23556 for example currency specifications. For example it will assume being in
23557 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23558 fragments that are properly closed, but during editing, we have to live
23559 with the uncertainty caused by missing closing delimiters. This function
23560 looks only before point, not after."
23561 (catch 'exit
23562 (let ((pos (point))
23563 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23564 (lim (progn
23565 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23566 (point)))
23567 dd-on str (start 0) m re)
23568 (goto-char pos)
23569 (when dodollar
23570 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23571 re (nth 1 (assoc "$" org-latex-regexps)))
23572 (while (string-match re str start)
23573 (cond
23574 ((= (match-end 0) (length str))
23575 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23576 ((= (match-end 0) (- (length str) 5))
23577 (throw 'exit nil))
23578 (t (setq start (match-end 0))))))
23579 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23580 (goto-char pos)
23581 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23582 (and (match-beginning 2) (throw 'exit nil))
23583 ;; count $$
23584 (while (re-search-backward "\\$\\$" lim t)
23585 (setq dd-on (not dd-on)))
23586 (goto-char pos)
23587 (if dd-on (cons "$$" m))))))
23590 (defun org-try-cdlatex-tab ()
23591 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23592 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23593 - inside a LaTeX fragment, or
23594 - after the first word in a line, where an abbreviation expansion could
23595 insert a LaTeX environment."
23596 (when org-cdlatex-mode
23597 (cond
23598 ((save-excursion
23599 (skip-chars-backward "a-zA-Z0-9*")
23600 (skip-chars-backward " \t")
23601 (bolp))
23602 (cdlatex-tab) t)
23603 ((org-inside-LaTeX-fragment-p)
23604 (cdlatex-tab) t)
23605 (t nil))))
23607 (defun org-cdlatex-underscore-caret (&optional arg)
23608 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23609 Revert to the normal definition outside of these fragments."
23610 (interactive "P")
23611 (if (org-inside-LaTeX-fragment-p)
23612 (call-interactively 'cdlatex-sub-superscript)
23613 (let (org-cdlatex-mode)
23614 (call-interactively (key-binding (vector last-input-event))))))
23616 (defun org-cdlatex-math-modify (&optional arg)
23617 "Execute `cdlatex-math-modify' in LaTeX fragments.
23618 Revert to the normal definition outside of these fragments."
23619 (interactive "P")
23620 (if (org-inside-LaTeX-fragment-p)
23621 (call-interactively 'cdlatex-math-modify)
23622 (let (org-cdlatex-mode)
23623 (call-interactively (key-binding (vector last-input-event))))))
23625 (defvar org-latex-fragment-image-overlays nil
23626 "List of overlays carrying the images of latex fragments.")
23627 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23629 (defun org-remove-latex-fragment-image-overlays ()
23630 "Remove all overlays with LaTeX fragment images in current buffer."
23631 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23632 (setq org-latex-fragment-image-overlays nil))
23634 (defun org-preview-latex-fragment (&optional subtree)
23635 "Preview the LaTeX fragment at point, or all locally or globally.
23636 If the cursor is in a LaTeX fragment, create the image and overlay
23637 it over the source code. If there is no fragment at point, display
23638 all fragments in the current text, from one headline to the next. With
23639 prefix SUBTREE, display all fragments in the current subtree. With a
23640 double prefix `C-u C-u', or when the cursor is before the first headline,
23641 display all fragments in the buffer.
23642 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23643 (interactive "P")
23644 (org-remove-latex-fragment-image-overlays)
23645 (save-excursion
23646 (save-restriction
23647 (let (beg end at msg)
23648 (cond
23649 ((or (equal subtree '(16))
23650 (not (save-excursion
23651 (re-search-backward (concat "^" outline-regexp) nil t))))
23652 (setq beg (point-min) end (point-max)
23653 msg "Creating images for buffer...%s"))
23654 ((equal subtree '(4))
23655 (org-back-to-heading)
23656 (setq beg (point) end (org-end-of-subtree t)
23657 msg "Creating images for subtree...%s"))
23659 (if (setq at (org-inside-LaTeX-fragment-p))
23660 (goto-char (max (point-min) (- (cdr at) 2)))
23661 (org-back-to-heading))
23662 (setq beg (point) end (progn (outline-next-heading) (point))
23663 msg (if at "Creating image...%s"
23664 "Creating images for entry...%s"))))
23665 (message msg "")
23666 (narrow-to-region beg end)
23667 (goto-char beg)
23668 (org-format-latex
23669 (concat "ltxpng/" (file-name-sans-extension
23670 (file-name-nondirectory
23671 buffer-file-name)))
23672 default-directory 'overlays msg at 'forbuffer)
23673 (message msg "done. Use `C-c C-c' to remove images.")))))
23675 (defvar org-latex-regexps
23676 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23677 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23678 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23679 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23680 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23681 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23682 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23683 "Regular expressions for matching embedded LaTeX.")
23685 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23686 "Replace LaTeX fragments with links to an image, and produce images."
23687 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23688 (let* ((prefixnodir (file-name-nondirectory prefix))
23689 (absprefix (expand-file-name prefix dir))
23690 (todir (file-name-directory absprefix))
23691 (opt org-format-latex-options)
23692 (matchers (plist-get opt :matchers))
23693 (re-list org-latex-regexps)
23694 (cnt 0) txt link beg end re e checkdir
23695 m n block linkfile movefile ov)
23696 ;; Check if there are old images files with this prefix, and remove them
23697 (when (file-directory-p todir)
23698 (mapc 'delete-file
23699 (directory-files
23700 todir 'full
23701 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23702 ;; Check the different regular expressions
23703 (while (setq e (pop re-list))
23704 (setq m (car e) re (nth 1 e) n (nth 2 e)
23705 block (if (nth 3 e) "\n\n" ""))
23706 (when (member m matchers)
23707 (goto-char (point-min))
23708 (while (re-search-forward re nil t)
23709 (when (or (not at) (equal (cdr at) (match-beginning n)))
23710 (setq txt (match-string n)
23711 beg (match-beginning n) end (match-end n)
23712 cnt (1+ cnt)
23713 linkfile (format "%s_%04d.png" prefix cnt)
23714 movefile (format "%s_%04d.png" absprefix cnt)
23715 link (concat block "[[file:" linkfile "]]" block))
23716 (if msg (message msg cnt))
23717 (goto-char beg)
23718 (unless checkdir ; make sure the directory exists
23719 (setq checkdir t)
23720 (or (file-directory-p todir) (make-directory todir)))
23721 (org-create-formula-image
23722 txt movefile opt forbuffer)
23723 (if overlays
23724 (progn
23725 (setq ov (org-make-overlay beg end))
23726 (if (featurep 'xemacs)
23727 (progn
23728 (org-overlay-put ov 'invisible t)
23729 (org-overlay-put
23730 ov 'end-glyph
23731 (make-glyph (vector 'png :file movefile))))
23732 (org-overlay-put
23733 ov 'display
23734 (list 'image :type 'png :file movefile :ascent 'center)))
23735 (push ov org-latex-fragment-image-overlays)
23736 (goto-char end))
23737 (delete-region beg end)
23738 (insert link))))))))
23740 ;; This function borrows from Ganesh Swami's latex2png.el
23741 (defun org-create-formula-image (string tofile options buffer)
23742 (let* ((tmpdir (if (featurep 'xemacs)
23743 (temp-directory)
23744 temporary-file-directory))
23745 (texfilebase (make-temp-name
23746 (expand-file-name "orgtex" tmpdir)))
23747 (texfile (concat texfilebase ".tex"))
23748 (dvifile (concat texfilebase ".dvi"))
23749 (pngfile (concat texfilebase ".png"))
23750 (fnh (face-attribute 'default :height nil))
23751 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23752 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23753 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23754 "Black"))
23755 (bg (or (plist-get options (if buffer :background :html-background))
23756 "Transparent")))
23757 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23758 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23759 (with-temp-file texfile
23760 (insert org-format-latex-header
23761 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23762 (let ((dir default-directory))
23763 (condition-case nil
23764 (progn
23765 (cd tmpdir)
23766 (call-process "latex" nil nil nil texfile))
23767 (error nil))
23768 (cd dir))
23769 (if (not (file-exists-p dvifile))
23770 (progn (message "Failed to create dvi file from %s" texfile) nil)
23771 (call-process "dvipng" nil nil nil
23772 "-E" "-fg" fg "-bg" bg
23773 "-D" dpi
23774 ;;"-x" scale "-y" scale
23775 "-T" "tight"
23776 "-o" pngfile
23777 dvifile)
23778 (if (not (file-exists-p pngfile))
23779 (progn (message "Failed to create png file from %s" texfile) nil)
23780 ;; Use the requested file name and clean up
23781 (copy-file pngfile tofile 'replace)
23782 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23783 (delete-file (concat texfilebase e)))
23784 pngfile))))
23786 (defun org-dvipng-color (attr)
23787 "Return an rgb color specification for dvipng."
23788 (apply 'format "rgb %s %s %s"
23789 (mapcar 'org-normalize-color
23790 (color-values (face-attribute 'default attr nil)))))
23792 (defun org-normalize-color (value)
23793 "Return string to be used as color value for an RGB component."
23794 (format "%g" (/ value 65535.0)))
23796 ;;;; Exporting
23798 ;;; Variables, constants, and parameter plists
23800 (defconst org-level-max 20)
23802 (defvar org-export-html-preamble nil
23803 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23804 (defvar org-export-html-postamble nil
23805 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23806 (defvar org-export-html-auto-preamble t
23807 "Should default preamble be inserted? Set by publishing functions.")
23808 (defvar org-export-html-auto-postamble t
23809 "Should default postamble be inserted? Set by publishing functions.")
23810 (defvar org-current-export-file nil) ; dynamically scoped parameter
23811 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23814 (defconst org-export-plist-vars
23815 '((:language . org-export-default-language)
23816 (:customtime . org-display-custom-times)
23817 (:headline-levels . org-export-headline-levels)
23818 (:section-numbers . org-export-with-section-numbers)
23819 (:table-of-contents . org-export-with-toc)
23820 (:preserve-breaks . org-export-preserve-breaks)
23821 (:archived-trees . org-export-with-archived-trees)
23822 (:emphasize . org-export-with-emphasize)
23823 (:sub-superscript . org-export-with-sub-superscripts)
23824 (:special-strings . org-export-with-special-strings)
23825 (:footnotes . org-export-with-footnotes)
23826 (:drawers . org-export-with-drawers)
23827 (:tags . org-export-with-tags)
23828 (:TeX-macros . org-export-with-TeX-macros)
23829 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23830 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23831 (:fixed-width . org-export-with-fixed-width)
23832 (:timestamps . org-export-with-timestamps)
23833 (:author-info . org-export-author-info)
23834 (:time-stamp-file . org-export-time-stamp-file)
23835 (:tables . org-export-with-tables)
23836 (:table-auto-headline . org-export-highlight-first-table-line)
23837 (:style . org-export-html-style)
23838 (:agenda-style . org-agenda-export-html-style)
23839 (:convert-org-links . org-export-html-link-org-files-as-html)
23840 (:inline-images . org-export-html-inline-images)
23841 (:html-extension . org-export-html-extension)
23842 (:html-table-tag . org-export-html-table-tag)
23843 (:expand-quoted-html . org-export-html-expand)
23844 (:timestamp . org-export-html-with-timestamp)
23845 (:publishing-directory . org-export-publishing-directory)
23846 (:preamble . org-export-html-preamble)
23847 (:postamble . org-export-html-postamble)
23848 (:auto-preamble . org-export-html-auto-preamble)
23849 (:auto-postamble . org-export-html-auto-postamble)
23850 (:author . user-full-name)
23851 (:email . user-mail-address)))
23853 (defun org-default-export-plist ()
23854 "Return the property list with default settings for the export variables."
23855 (let ((l org-export-plist-vars) rtn e)
23856 (while (setq e (pop l))
23857 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23858 rtn))
23860 (defun org-infile-export-plist ()
23861 "Return the property list with file-local settings for export."
23862 (save-excursion
23863 (save-restriction
23864 (widen)
23865 (goto-char 0)
23866 (let ((re (org-make-options-regexp
23867 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23868 p key val text options)
23869 (while (re-search-forward re nil t)
23870 (setq key (org-match-string-no-properties 1)
23871 val (org-match-string-no-properties 2))
23872 (cond
23873 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23874 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23875 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23876 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23877 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23878 ((string-equal key "TEXT")
23879 (setq text (if text (concat text "\n" val) val)))
23880 ((string-equal key "OPTIONS") (setq options val))))
23881 (setq p (plist-put p :text text))
23882 (when options
23883 (let ((op '(("H" . :headline-levels)
23884 ("num" . :section-numbers)
23885 ("toc" . :table-of-contents)
23886 ("\\n" . :preserve-breaks)
23887 ("@" . :expand-quoted-html)
23888 (":" . :fixed-width)
23889 ("|" . :tables)
23890 ("^" . :sub-superscript)
23891 ("-" . :special-strings)
23892 ("f" . :footnotes)
23893 ("d" . :drawers)
23894 ("tags" . :tags)
23895 ("*" . :emphasize)
23896 ("TeX" . :TeX-macros)
23897 ("LaTeX" . :LaTeX-fragments)
23898 ("skip" . :skip-before-1st-heading)
23899 ("author" . :author-info)
23900 ("timestamp" . :time-stamp-file)))
23902 (while (setq o (pop op))
23903 (if (string-match (concat (regexp-quote (car o))
23904 ":\\([^ \t\n\r;,.]*\\)")
23905 options)
23906 (setq p (plist-put p (cdr o)
23907 (car (read-from-string
23908 (match-string 1 options)))))))))
23909 p))))
23911 (defun org-export-directory (type plist)
23912 (let* ((val (plist-get plist :publishing-directory))
23913 (dir (if (listp val)
23914 (or (cdr (assoc type val)) ".")
23915 val)))
23916 dir))
23918 (defun org-skip-comments (lines)
23919 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23920 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23921 (re2 "^\\(\\*+\\)[ \t\n\r]")
23922 (case-fold-search nil)
23923 rtn line level)
23924 (while (setq line (pop lines))
23925 (cond
23926 ((and (string-match re1 line)
23927 (setq level (- (match-end 1) (match-beginning 1))))
23928 ;; Beginning of a COMMENT subtree. Skip it.
23929 (while (and (setq line (pop lines))
23930 (or (not (string-match re2 line))
23931 (> (- (match-end 1) (match-beginning 1)) level))))
23932 (setq lines (cons line lines)))
23933 ((string-match "^#" line)
23934 ;; an ordinary comment line
23936 ((and org-export-table-remove-special-lines
23937 (string-match "^[ \t]*|" line)
23938 (or (string-match "^[ \t]*| *[!_^] *|" line)
23939 (and (string-match "| *<[0-9]+> *|" line)
23940 (not (string-match "| *[^ <|]" line)))))
23941 ;; a special table line that should be removed
23943 (t (setq rtn (cons line rtn)))))
23944 (nreverse rtn)))
23946 (defun org-export (&optional arg)
23947 (interactive)
23948 (let ((help "[t] insert the export option template
23949 \[v] limit export to visible part of outline tree
23951 \[a] export as ASCII
23953 \[h] export as HTML
23954 \[H] export as HTML to temporary buffer
23955 \[R] export region as HTML
23956 \[b] export as HTML and browse immediately
23957 \[x] export as XOXO
23959 \[l] export as LaTeX
23960 \[L] export as LaTeX to temporary buffer
23962 \[i] export current file as iCalendar file
23963 \[I] export all agenda files as iCalendar files
23964 \[c] export agenda files into combined iCalendar file
23966 \[F] publish current file
23967 \[P] publish current project
23968 \[X] publish... (project will be prompted for)
23969 \[A] publish all projects")
23970 (cmds
23971 '((?t . org-insert-export-options-template)
23972 (?v . org-export-visible)
23973 (?a . org-export-as-ascii)
23974 (?h . org-export-as-html)
23975 (?b . org-export-as-html-and-open)
23976 (?H . org-export-as-html-to-buffer)
23977 (?R . org-export-region-as-html)
23978 (?x . org-export-as-xoxo)
23979 (?l . org-export-as-latex)
23980 (?L . org-export-as-latex-to-buffer)
23981 (?i . org-export-icalendar-this-file)
23982 (?I . org-export-icalendar-all-agenda-files)
23983 (?c . org-export-icalendar-combine-agenda-files)
23984 (?F . org-publish-current-file)
23985 (?P . org-publish-current-project)
23986 (?X . org-publish)
23987 (?A . org-publish-all)))
23988 r1 r2 ass)
23989 (save-window-excursion
23990 (delete-other-windows)
23991 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23992 (princ help))
23993 (message "Select command: ")
23994 (setq r1 (read-char-exclusive)))
23995 (setq r2 (if (< r1 27) (+ r1 96) r1))
23996 (if (setq ass (assq r2 cmds))
23997 (call-interactively (cdr ass))
23998 (error "No command associated with key %c" r1))))
24000 (defconst org-html-entities
24001 '(("nbsp")
24002 ("iexcl")
24003 ("cent")
24004 ("pound")
24005 ("curren")
24006 ("yen")
24007 ("brvbar")
24008 ("vert" . "&#124;")
24009 ("sect")
24010 ("uml")
24011 ("copy")
24012 ("ordf")
24013 ("laquo")
24014 ("not")
24015 ("shy")
24016 ("reg")
24017 ("macr")
24018 ("deg")
24019 ("plusmn")
24020 ("sup2")
24021 ("sup3")
24022 ("acute")
24023 ("micro")
24024 ("para")
24025 ("middot")
24026 ("odot"."o")
24027 ("star"."*")
24028 ("cedil")
24029 ("sup1")
24030 ("ordm")
24031 ("raquo")
24032 ("frac14")
24033 ("frac12")
24034 ("frac34")
24035 ("iquest")
24036 ("Agrave")
24037 ("Aacute")
24038 ("Acirc")
24039 ("Atilde")
24040 ("Auml")
24041 ("Aring") ("AA"."&Aring;")
24042 ("AElig")
24043 ("Ccedil")
24044 ("Egrave")
24045 ("Eacute")
24046 ("Ecirc")
24047 ("Euml")
24048 ("Igrave")
24049 ("Iacute")
24050 ("Icirc")
24051 ("Iuml")
24052 ("ETH")
24053 ("Ntilde")
24054 ("Ograve")
24055 ("Oacute")
24056 ("Ocirc")
24057 ("Otilde")
24058 ("Ouml")
24059 ("times")
24060 ("Oslash")
24061 ("Ugrave")
24062 ("Uacute")
24063 ("Ucirc")
24064 ("Uuml")
24065 ("Yacute")
24066 ("THORN")
24067 ("szlig")
24068 ("agrave")
24069 ("aacute")
24070 ("acirc")
24071 ("atilde")
24072 ("auml")
24073 ("aring")
24074 ("aelig")
24075 ("ccedil")
24076 ("egrave")
24077 ("eacute")
24078 ("ecirc")
24079 ("euml")
24080 ("igrave")
24081 ("iacute")
24082 ("icirc")
24083 ("iuml")
24084 ("eth")
24085 ("ntilde")
24086 ("ograve")
24087 ("oacute")
24088 ("ocirc")
24089 ("otilde")
24090 ("ouml")
24091 ("divide")
24092 ("oslash")
24093 ("ugrave")
24094 ("uacute")
24095 ("ucirc")
24096 ("uuml")
24097 ("yacute")
24098 ("thorn")
24099 ("yuml")
24100 ("fnof")
24101 ("Alpha")
24102 ("Beta")
24103 ("Gamma")
24104 ("Delta")
24105 ("Epsilon")
24106 ("Zeta")
24107 ("Eta")
24108 ("Theta")
24109 ("Iota")
24110 ("Kappa")
24111 ("Lambda")
24112 ("Mu")
24113 ("Nu")
24114 ("Xi")
24115 ("Omicron")
24116 ("Pi")
24117 ("Rho")
24118 ("Sigma")
24119 ("Tau")
24120 ("Upsilon")
24121 ("Phi")
24122 ("Chi")
24123 ("Psi")
24124 ("Omega")
24125 ("alpha")
24126 ("beta")
24127 ("gamma")
24128 ("delta")
24129 ("epsilon")
24130 ("varepsilon"."&epsilon;")
24131 ("zeta")
24132 ("eta")
24133 ("theta")
24134 ("iota")
24135 ("kappa")
24136 ("lambda")
24137 ("mu")
24138 ("nu")
24139 ("xi")
24140 ("omicron")
24141 ("pi")
24142 ("rho")
24143 ("sigmaf") ("varsigma"."&sigmaf;")
24144 ("sigma")
24145 ("tau")
24146 ("upsilon")
24147 ("phi")
24148 ("chi")
24149 ("psi")
24150 ("omega")
24151 ("thetasym") ("vartheta"."&thetasym;")
24152 ("upsih")
24153 ("piv")
24154 ("bull") ("bullet"."&bull;")
24155 ("hellip") ("dots"."&hellip;")
24156 ("prime")
24157 ("Prime")
24158 ("oline")
24159 ("frasl")
24160 ("weierp")
24161 ("image")
24162 ("real")
24163 ("trade")
24164 ("alefsym")
24165 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24166 ("uarr") ("uparrow"."&uarr;")
24167 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24168 ("darr")("downarrow"."&darr;")
24169 ("harr") ("leftrightarrow"."&harr;")
24170 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24171 ("lArr") ("Leftarrow"."&lArr;")
24172 ("uArr") ("Uparrow"."&uArr;")
24173 ("rArr") ("Rightarrow"."&rArr;")
24174 ("dArr") ("Downarrow"."&dArr;")
24175 ("hArr") ("Leftrightarrow"."&hArr;")
24176 ("forall")
24177 ("part") ("partial"."&part;")
24178 ("exist") ("exists"."&exist;")
24179 ("empty") ("emptyset"."&empty;")
24180 ("nabla")
24181 ("isin") ("in"."&isin;")
24182 ("notin")
24183 ("ni")
24184 ("prod")
24185 ("sum")
24186 ("minus")
24187 ("lowast") ("ast"."&lowast;")
24188 ("radic")
24189 ("prop") ("proptp"."&prop;")
24190 ("infin") ("infty"."&infin;")
24191 ("ang") ("angle"."&ang;")
24192 ("and") ("wedge"."&and;")
24193 ("or") ("vee"."&or;")
24194 ("cap")
24195 ("cup")
24196 ("int")
24197 ("there4")
24198 ("sim")
24199 ("cong") ("simeq"."&cong;")
24200 ("asymp")("approx"."&asymp;")
24201 ("ne") ("neq"."&ne;")
24202 ("equiv")
24203 ("le")
24204 ("ge")
24205 ("sub") ("subset"."&sub;")
24206 ("sup") ("supset"."&sup;")
24207 ("nsub")
24208 ("sube")
24209 ("supe")
24210 ("oplus")
24211 ("otimes")
24212 ("perp")
24213 ("sdot") ("cdot"."&sdot;")
24214 ("lceil")
24215 ("rceil")
24216 ("lfloor")
24217 ("rfloor")
24218 ("lang")
24219 ("rang")
24220 ("loz") ("Diamond"."&loz;")
24221 ("spades") ("spadesuit"."&spades;")
24222 ("clubs") ("clubsuit"."&clubs;")
24223 ("hearts") ("diamondsuit"."&hearts;")
24224 ("diams") ("diamondsuit"."&diams;")
24225 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24226 ("quot")
24227 ("amp")
24228 ("lt")
24229 ("gt")
24230 ("OElig")
24231 ("oelig")
24232 ("Scaron")
24233 ("scaron")
24234 ("Yuml")
24235 ("circ")
24236 ("tilde")
24237 ("ensp")
24238 ("emsp")
24239 ("thinsp")
24240 ("zwnj")
24241 ("zwj")
24242 ("lrm")
24243 ("rlm")
24244 ("ndash")
24245 ("mdash")
24246 ("lsquo")
24247 ("rsquo")
24248 ("sbquo")
24249 ("ldquo")
24250 ("rdquo")
24251 ("bdquo")
24252 ("dagger")
24253 ("Dagger")
24254 ("permil")
24255 ("lsaquo")
24256 ("rsaquo")
24257 ("euro")
24259 ("arccos"."arccos")
24260 ("arcsin"."arcsin")
24261 ("arctan"."arctan")
24262 ("arg"."arg")
24263 ("cos"."cos")
24264 ("cosh"."cosh")
24265 ("cot"."cot")
24266 ("coth"."coth")
24267 ("csc"."csc")
24268 ("deg"."deg")
24269 ("det"."det")
24270 ("dim"."dim")
24271 ("exp"."exp")
24272 ("gcd"."gcd")
24273 ("hom"."hom")
24274 ("inf"."inf")
24275 ("ker"."ker")
24276 ("lg"."lg")
24277 ("lim"."lim")
24278 ("liminf"."liminf")
24279 ("limsup"."limsup")
24280 ("ln"."ln")
24281 ("log"."log")
24282 ("max"."max")
24283 ("min"."min")
24284 ("Pr"."Pr")
24285 ("sec"."sec")
24286 ("sin"."sin")
24287 ("sinh"."sinh")
24288 ("sup"."sup")
24289 ("tan"."tan")
24290 ("tanh"."tanh")
24292 "Entities for TeX->HTML translation.
24293 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24294 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24295 In that case, \"\\ent\" will be translated to \"&other;\".
24296 The list contains HTML entities for Latin-1, Greek and other symbols.
24297 It is supplemented by a number of commonly used TeX macros with appropriate
24298 translations. There is currently no way for users to extend this.")
24300 ;;; General functions for all backends
24302 (defun org-cleaned-string-for-export (string &rest parameters)
24303 "Cleanup a buffer STRING so that links can be created safely."
24304 (interactive)
24305 (let* ((re-radio (and org-target-link-regexp
24306 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24307 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24308 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24309 (re-archive (concat ":" org-archive-tag ":"))
24310 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24311 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24312 (htmlp (plist-get parameters :for-html))
24313 (asciip (plist-get parameters :for-ascii))
24314 (latexp (plist-get parameters :for-LaTeX))
24315 (commentsp (plist-get parameters :comments))
24316 (archived-trees (plist-get parameters :archived-trees))
24317 (inhibit-read-only t)
24318 (drawers org-drawers)
24319 (exp-drawers (plist-get parameters :drawers))
24320 (outline-regexp "\\*+ ")
24321 a b xx
24322 rtn p)
24323 (with-current-buffer (get-buffer-create " org-mode-tmp")
24324 (erase-buffer)
24325 (insert string)
24326 ;; Remove license-to-kill stuff
24327 (while (setq p (text-property-any (point-min) (point-max)
24328 :org-license-to-kill t))
24329 (delete-region p (next-single-property-change p :org-license-to-kill)))
24331 (let ((org-inhibit-startup t)) (org-mode))
24332 (untabify (point-min) (point-max))
24334 ;; Get rid of drawers
24335 (unless (eq t exp-drawers)
24336 (goto-char (point-min))
24337 (let ((re (concat "^[ \t]*:\\("
24338 (mapconcat
24339 'identity
24340 (org-delete-all exp-drawers
24341 (copy-sequence drawers))
24342 "\\|")
24343 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24344 (while (re-search-forward re nil t)
24345 (replace-match ""))))
24347 ;; Get the correct stuff before the first headline
24348 (when (plist-get parameters :skip-before-1st-heading)
24349 (goto-char (point-min))
24350 (when (re-search-forward "^\\*+[ \t]" nil t)
24351 (delete-region (point-min) (match-beginning 0))
24352 (goto-char (point-min))
24353 (insert "\n")))
24354 (when (plist-get parameters :add-text)
24355 (goto-char (point-min))
24356 (insert (plist-get parameters :add-text) "\n"))
24358 ;; Get rid of archived trees
24359 (when (not (eq archived-trees t))
24360 (goto-char (point-min))
24361 (while (re-search-forward re-archive nil t)
24362 (if (not (org-on-heading-p t))
24363 (org-end-of-subtree t)
24364 (beginning-of-line 1)
24365 (setq a (if archived-trees
24366 (1+ (point-at-eol)) (point))
24367 b (org-end-of-subtree t))
24368 (if (> b a) (delete-region a b)))))
24370 ;; Find targets in comments and move them out of comments,
24371 ;; but mark them as targets that should be invisible
24372 (goto-char (point-min))
24373 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24374 (replace-match "\\1(INVISIBLE)"))
24376 ;; Protect backend specific stuff, throw away the others.
24377 (let ((formatters
24378 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24379 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24380 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24381 fmt)
24382 (goto-char (point-min))
24383 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24384 (goto-char (match-end 0))
24385 (while (not (looking-at "#\\+END_EXAMPLE"))
24386 (insert ": ")
24387 (beginning-of-line 2)))
24388 (goto-char (point-min))
24389 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24390 (add-text-properties (match-beginning 0) (match-end 0)
24391 '(org-protected t)))
24392 (while formatters
24393 (setq fmt (pop formatters))
24394 (when (car fmt)
24395 (goto-char (point-min))
24396 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24397 ":[ \t]*\\(.*\\)") nil t)
24398 (replace-match "\\1" t)
24399 (add-text-properties
24400 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24401 '(org-protected t))))
24402 (goto-char (point-min))
24403 (while (re-search-forward
24404 (concat "^#\\+"
24405 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24406 (cadddr fmt) "\\>.*\n?") nil t)
24407 (if (car fmt)
24408 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24409 '(org-protected t))
24410 (delete-region (match-beginning 0) (match-end 0))))))
24412 ;; Protect quoted subtrees
24413 (goto-char (point-min))
24414 (while (re-search-forward re-quote nil t)
24415 (goto-char (match-beginning 0))
24416 (end-of-line 1)
24417 (add-text-properties (point) (org-end-of-subtree t)
24418 '(org-protected t)))
24420 ;; Protect verbatim elements
24421 (goto-char (point-min))
24422 (while (re-search-forward org-verbatim-re nil t)
24423 (add-text-properties (match-beginning 4) (match-end 4)
24424 '(org-protected t))
24425 (goto-char (1+ (match-end 4))))
24427 ;; Remove subtrees that are commented
24428 (goto-char (point-min))
24429 (while (re-search-forward re-commented nil t)
24430 (goto-char (match-beginning 0))
24431 (delete-region (point) (org-end-of-subtree t)))
24433 ;; Remove special table lines
24434 (when org-export-table-remove-special-lines
24435 (goto-char (point-min))
24436 (while (re-search-forward "^[ \t]*|" nil t)
24437 (beginning-of-line 1)
24438 (if (or (looking-at "[ \t]*| *[!_^] *|")
24439 (and (looking-at ".*?| *<[0-9]+> *|")
24440 (not (looking-at ".*?| *[^ <|]"))))
24441 (delete-region (max (point-min) (1- (point-at-bol)))
24442 (point-at-eol))
24443 (end-of-line 1))))
24445 ;; Specific LaTeX stuff
24446 (when latexp
24447 (require 'org-export-latex nil)
24448 (org-export-latex-cleaned-string))
24450 (when asciip
24451 (org-export-ascii-clean-string))
24453 ;; Specific HTML stuff
24454 (when htmlp
24455 ;; Convert LaTeX fragments to images
24456 (when (plist-get parameters :LaTeX-fragments)
24457 (org-format-latex
24458 (concat "ltxpng/" (file-name-sans-extension
24459 (file-name-nondirectory
24460 org-current-export-file)))
24461 org-current-export-dir nil "Creating LaTeX image %s"))
24462 (message "Exporting..."))
24464 ;; Remove or replace comments
24465 (goto-char (point-min))
24466 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24467 (if commentsp
24468 (progn (add-text-properties
24469 (match-beginning 0) (match-end 0) '(org-protected t))
24470 (replace-match (format commentsp (match-string 1)) t t))
24471 (replace-match "")))
24473 ;; Find matches for radio targets and turn them into internal links
24474 (goto-char (point-min))
24475 (when re-radio
24476 (while (re-search-forward re-radio nil t)
24477 (org-if-unprotected
24478 (replace-match "\\1[[\\2]]"))))
24480 ;; Find all links that contain a newline and put them into a single line
24481 (goto-char (point-min))
24482 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24483 (org-if-unprotected
24484 (replace-match "\\1 \\3")
24485 (goto-char (match-beginning 0))))
24488 ;; Normalize links: Convert angle and plain links into bracket links
24489 ;; Expand link abbreviations
24490 (goto-char (point-min))
24491 (while (re-search-forward re-plain-link nil t)
24492 (goto-char (1- (match-end 0)))
24493 (org-if-unprotected
24494 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24495 ":" (match-string 3) "]]")))
24496 ;; added 'org-link face to links
24497 (put-text-property 0 (length s) 'face 'org-link s)
24498 (replace-match s t t))))
24499 (goto-char (point-min))
24500 (while (re-search-forward re-angle-link nil t)
24501 (goto-char (1- (match-end 0)))
24502 (org-if-unprotected
24503 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24504 ":" (match-string 3) "]]")))
24505 (put-text-property 0 (length s) 'face 'org-link s)
24506 (replace-match s t t))))
24507 (goto-char (point-min))
24508 (while (re-search-forward org-bracket-link-regexp nil t)
24509 (org-if-unprotected
24510 (let* ((s (concat "[[" (setq xx (save-match-data
24511 (org-link-expand-abbrev (match-string 1))))
24513 (if (match-end 3)
24514 (match-string 2)
24515 (concat "[" xx "]"))
24516 "]")))
24517 (put-text-property 0 (length s) 'face 'org-link s)
24518 (replace-match s t t))))
24520 ;; Find multiline emphasis and put them into single line
24521 (when (plist-get parameters :emph-multiline)
24522 (goto-char (point-min))
24523 (while (re-search-forward org-emph-re nil t)
24524 (if (not (= (char-after (match-beginning 3))
24525 (char-after (match-beginning 4))))
24526 (org-if-unprotected
24527 (subst-char-in-region (match-beginning 0) (match-end 0)
24528 ?\n ?\ t)
24529 (goto-char (1- (match-end 0))))
24530 (goto-char (1+ (match-beginning 0))))))
24532 (setq rtn (buffer-string)))
24533 (kill-buffer " org-mode-tmp")
24534 rtn))
24536 (defun org-export-grab-title-from-buffer ()
24537 "Get a title for the current document, from looking at the buffer."
24538 (let ((inhibit-read-only t))
24539 (save-excursion
24540 (goto-char (point-min))
24541 (let ((end (save-excursion (outline-next-heading) (point))))
24542 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24543 ;; Mark the line so that it will not be exported as normal text.
24544 (org-unmodified
24545 (add-text-properties (match-beginning 0) (match-end 0)
24546 (list :org-license-to-kill t)))
24547 ;; Return the title string
24548 (org-trim (match-string 0)))))))
24550 (defun org-export-get-title-from-subtree ()
24551 "Return subtree title and exclude it from export."
24552 (let (title (m (mark)))
24553 (save-excursion
24554 (goto-char (region-beginning))
24555 (when (and (org-at-heading-p)
24556 (>= (org-end-of-subtree t t) (region-end)))
24557 ;; This is a subtree, we take the title from the first heading
24558 (goto-char (region-beginning))
24559 (looking-at org-todo-line-regexp)
24560 (setq title (match-string 3))
24561 (org-unmodified
24562 (add-text-properties (point) (1+ (point-at-eol))
24563 (list :org-license-to-kill t)))))
24564 title))
24566 (defun org-solidify-link-text (s &optional alist)
24567 "Take link text and make a safe target out of it."
24568 (save-match-data
24569 (let* ((rtn
24570 (mapconcat
24571 'identity
24572 (org-split-string s "[ \t\r\n]+") "--"))
24573 (a (assoc rtn alist)))
24574 (or (cdr a) rtn))))
24576 (defun org-get-min-level (lines)
24577 "Get the minimum level in LINES."
24578 (let ((re "^\\(\\*+\\) ") l min)
24579 (catch 'exit
24580 (while (setq l (pop lines))
24581 (if (string-match re l)
24582 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24583 1)))
24585 ;; Variable holding the vector with section numbers
24586 (defvar org-section-numbers (make-vector org-level-max 0))
24588 (defun org-init-section-numbers ()
24589 "Initialize the vector for the section numbers."
24590 (let* ((level -1)
24591 (numbers (nreverse (org-split-string "" "\\.")))
24592 (depth (1- (length org-section-numbers)))
24593 (i depth) number-string)
24594 (while (>= i 0)
24595 (if (> i level)
24596 (aset org-section-numbers i 0)
24597 (setq number-string (or (car numbers) "0"))
24598 (if (string-match "\\`[A-Z]\\'" number-string)
24599 (aset org-section-numbers i
24600 (- (string-to-char number-string) ?A -1))
24601 (aset org-section-numbers i (string-to-number number-string)))
24602 (pop numbers))
24603 (setq i (1- i)))))
24605 (defun org-section-number (&optional level)
24606 "Return a string with the current section number.
24607 When LEVEL is non-nil, increase section numbers on that level."
24608 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24609 (when level
24610 (when (> level -1)
24611 (aset org-section-numbers
24612 level (1+ (aref org-section-numbers level))))
24613 (setq idx (1+ level))
24614 (while (<= idx depth)
24615 (if (not (= idx 1))
24616 (aset org-section-numbers idx 0))
24617 (setq idx (1+ idx))))
24618 (setq idx 0)
24619 (while (<= idx depth)
24620 (setq n (aref org-section-numbers idx))
24621 (setq string (concat string (if (not (string= string "")) "." "")
24622 (int-to-string n)))
24623 (setq idx (1+ idx)))
24624 (save-match-data
24625 (if (string-match "\\`\\([@0]\\.\\)+" string)
24626 (setq string (replace-match "" t nil string)))
24627 (if (string-match "\\(\\.0\\)+\\'" string)
24628 (setq string (replace-match "" t nil string))))
24629 string))
24631 ;;; ASCII export
24633 (defvar org-last-level nil) ; dynamically scoped variable
24634 (defvar org-min-level nil) ; dynamically scoped variable
24635 (defvar org-levels-open nil) ; dynamically scoped parameter
24636 (defvar org-ascii-current-indentation nil) ; For communication
24638 (defun org-export-as-ascii (arg)
24639 "Export the outline as a pretty ASCII file.
24640 If there is an active region, export only the region.
24641 The prefix ARG specifies how many levels of the outline should become
24642 underlined headlines. The default is 3."
24643 (interactive "P")
24644 (setq-default org-todo-line-regexp org-todo-line-regexp)
24645 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24646 (org-infile-export-plist)))
24647 (region-p (org-region-active-p))
24648 (subtree-p
24649 (when region-p
24650 (save-excursion
24651 (goto-char (region-beginning))
24652 (and (org-at-heading-p)
24653 (>= (org-end-of-subtree t t) (region-end))))))
24654 (custom-times org-display-custom-times)
24655 (org-ascii-current-indentation '(0 . 0))
24656 (level 0) line txt
24657 (umax nil)
24658 (umax-toc nil)
24659 (case-fold-search nil)
24660 (filename (concat (file-name-as-directory
24661 (org-export-directory :ascii opt-plist))
24662 (file-name-sans-extension
24663 (or (and subtree-p
24664 (org-entry-get (region-beginning)
24665 "EXPORT_FILE_NAME" t))
24666 (file-name-nondirectory buffer-file-name)))
24667 ".txt"))
24668 (filename (if (equal (file-truename filename)
24669 (file-truename buffer-file-name))
24670 (concat filename ".txt")
24671 filename))
24672 (buffer (find-file-noselect filename))
24673 (org-levels-open (make-vector org-level-max nil))
24674 (odd org-odd-levels-only)
24675 (date (plist-get opt-plist :date))
24676 (author (plist-get opt-plist :author))
24677 (title (or (and subtree-p (org-export-get-title-from-subtree))
24678 (plist-get opt-plist :title)
24679 (and (not
24680 (plist-get opt-plist :skip-before-1st-heading))
24681 (org-export-grab-title-from-buffer))
24682 (file-name-sans-extension
24683 (file-name-nondirectory buffer-file-name))))
24684 (email (plist-get opt-plist :email))
24685 (language (plist-get opt-plist :language))
24686 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24687 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24688 (todo nil)
24689 (lang-words nil)
24690 (region
24691 (buffer-substring
24692 (if (org-region-active-p) (region-beginning) (point-min))
24693 (if (org-region-active-p) (region-end) (point-max))))
24694 (lines (org-split-string
24695 (org-cleaned-string-for-export
24696 region
24697 :for-ascii t
24698 :skip-before-1st-heading
24699 (plist-get opt-plist :skip-before-1st-heading)
24700 :drawers (plist-get opt-plist :drawers)
24701 :verbatim-multiline t
24702 :archived-trees
24703 (plist-get opt-plist :archived-trees)
24704 :add-text (plist-get opt-plist :text))
24705 "\n"))
24706 thetoc have-headings first-heading-pos
24707 table-open table-buffer)
24709 (let ((inhibit-read-only t))
24710 (org-unmodified
24711 (remove-text-properties (point-min) (point-max)
24712 '(:org-license-to-kill t))))
24714 (setq org-min-level (org-get-min-level lines))
24715 (setq org-last-level org-min-level)
24716 (org-init-section-numbers)
24718 (find-file-noselect filename)
24720 (setq lang-words (or (assoc language org-export-language-setup)
24721 (assoc "en" org-export-language-setup)))
24722 (switch-to-buffer-other-window buffer)
24723 (erase-buffer)
24724 (fundamental-mode)
24725 ;; create local variables for all options, to make sure all called
24726 ;; functions get the correct information
24727 (mapc (lambda (x)
24728 (set (make-local-variable (cdr x))
24729 (plist-get opt-plist (car x))))
24730 org-export-plist-vars)
24731 (org-set-local 'org-odd-levels-only odd)
24732 (setq umax (if arg (prefix-numeric-value arg)
24733 org-export-headline-levels))
24734 (setq umax-toc (if (integerp org-export-with-toc)
24735 (min org-export-with-toc umax)
24736 umax))
24738 ;; File header
24739 (if title (org-insert-centered title ?=))
24740 (insert "\n")
24741 (if (and (or author email)
24742 org-export-author-info)
24743 (insert (concat (nth 1 lang-words) ": " (or author "")
24744 (if email (concat " <" email ">") "")
24745 "\n")))
24747 (cond
24748 ((and date (string-match "%" date))
24749 (setq date (format-time-string date (current-time))))
24750 (date)
24751 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24753 (if (and date org-export-time-stamp-file)
24754 (insert (concat (nth 2 lang-words) ": " date"\n")))
24756 (insert "\n\n")
24758 (if org-export-with-toc
24759 (progn
24760 (push (concat (nth 3 lang-words) "\n") thetoc)
24761 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24762 (mapc '(lambda (line)
24763 (if (string-match org-todo-line-regexp
24764 line)
24765 ;; This is a headline
24766 (progn
24767 (setq have-headings t)
24768 (setq level (- (match-end 1) (match-beginning 1))
24769 level (org-tr-level level)
24770 txt (match-string 3 line)
24771 todo
24772 (or (and org-export-mark-todo-in-toc
24773 (match-beginning 2)
24774 (not (member (match-string 2 line)
24775 org-done-keywords)))
24776 ; TODO, not DONE
24777 (and org-export-mark-todo-in-toc
24778 (= level umax-toc)
24779 (org-search-todo-below
24780 line lines level))))
24781 (setq txt (org-html-expand-for-ascii txt))
24783 (while (string-match org-bracket-link-regexp txt)
24784 (setq txt
24785 (replace-match
24786 (match-string (if (match-end 2) 3 1) txt)
24787 t t txt)))
24789 (if (and (memq org-export-with-tags '(not-in-toc nil))
24790 (string-match
24791 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24792 txt))
24793 (setq txt (replace-match "" t t txt)))
24794 (if (string-match quote-re0 txt)
24795 (setq txt (replace-match "" t t txt)))
24797 (if org-export-with-section-numbers
24798 (setq txt (concat (org-section-number level)
24799 " " txt)))
24800 (if (<= level umax-toc)
24801 (progn
24802 (push
24803 (concat
24804 (make-string
24805 (* (max 0 (- level org-min-level)) 4) ?\ )
24806 (format (if todo "%s (*)\n" "%s\n") txt))
24807 thetoc)
24808 (setq org-last-level level))
24809 ))))
24810 lines)
24811 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24813 (org-init-section-numbers)
24814 (while (setq line (pop lines))
24815 ;; Remove the quoted HTML tags.
24816 (setq line (org-html-expand-for-ascii line))
24817 ;; Remove targets
24818 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24819 (setq line (replace-match "" t t line)))
24820 ;; Replace internal links
24821 (while (string-match org-bracket-link-regexp line)
24822 (setq line (replace-match
24823 (if (match-end 3) "[\\3]" "[\\1]")
24824 t nil line)))
24825 (when custom-times
24826 (setq line (org-translate-time line)))
24827 (cond
24828 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24829 ;; a Headline
24830 (setq first-heading-pos (or first-heading-pos (point)))
24831 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24832 txt (match-string 2 line))
24833 (org-ascii-level-start level txt umax lines))
24835 ((and org-export-with-tables
24836 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24837 (if (not table-open)
24838 ;; New table starts
24839 (setq table-open t table-buffer nil))
24840 ;; Accumulate lines
24841 (setq table-buffer (cons line table-buffer))
24842 (when (or (not lines)
24843 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24844 (car lines))))
24845 (setq table-open nil
24846 table-buffer (nreverse table-buffer))
24847 (insert (mapconcat
24848 (lambda (x)
24849 (org-fix-indentation x org-ascii-current-indentation))
24850 (org-format-table-ascii table-buffer)
24851 "\n") "\n")))
24853 (setq line (org-fix-indentation line org-ascii-current-indentation))
24854 (if (and org-export-with-fixed-width
24855 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24856 (setq line (replace-match "\\1" nil nil line)))
24857 (insert line "\n"))))
24859 (normal-mode)
24861 ;; insert the table of contents
24862 (when thetoc
24863 (goto-char (point-min))
24864 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24865 (progn
24866 (goto-char (match-beginning 0))
24867 (replace-match ""))
24868 (goto-char first-heading-pos))
24869 (mapc 'insert thetoc)
24870 (or (looking-at "[ \t]*\n[ \t]*\n")
24871 (insert "\n\n")))
24873 ;; Convert whitespace place holders
24874 (goto-char (point-min))
24875 (let (beg end)
24876 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24877 (setq end (next-single-property-change beg 'org-whitespace))
24878 (goto-char beg)
24879 (delete-region beg end)
24880 (insert (make-string (- end beg) ?\ ))))
24882 (save-buffer)
24883 ;; remove display and invisible chars
24884 (let (beg end)
24885 (goto-char (point-min))
24886 (while (setq beg (next-single-property-change (point) 'display))
24887 (setq end (next-single-property-change beg 'display))
24888 (delete-region beg end)
24889 (goto-char beg)
24890 (insert "=>"))
24891 (goto-char (point-min))
24892 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24893 (setq end (next-single-property-change beg 'org-cwidth))
24894 (delete-region beg end)
24895 (goto-char beg)))
24896 (goto-char (point-min))))
24898 (defun org-export-ascii-clean-string ()
24899 "Do extra work for ASCII export"
24900 (goto-char (point-min))
24901 (while (re-search-forward org-verbatim-re nil t)
24902 (goto-char (match-end 2))
24903 (backward-delete-char 1) (insert "'")
24904 (goto-char (match-beginning 2))
24905 (delete-char 1) (insert "`")
24906 (goto-char (match-end 2))))
24908 (defun org-search-todo-below (line lines level)
24909 "Search the subtree below LINE for any TODO entries."
24910 (let ((rest (cdr (memq line lines)))
24911 (re org-todo-line-regexp)
24912 line lv todo)
24913 (catch 'exit
24914 (while (setq line (pop rest))
24915 (if (string-match re line)
24916 (progn
24917 (setq lv (- (match-end 1) (match-beginning 1))
24918 todo (and (match-beginning 2)
24919 (not (member (match-string 2 line)
24920 org-done-keywords))))
24921 ; TODO, not DONE
24922 (if (<= lv level) (throw 'exit nil))
24923 (if todo (throw 'exit t))))))))
24925 (defun org-html-expand-for-ascii (line)
24926 "Handle quoted HTML for ASCII export."
24927 (if org-export-html-expand
24928 (while (string-match "@<[^<>\n]*>" line)
24929 ;; We just remove the tags for now.
24930 (setq line (replace-match "" nil nil line))))
24931 line)
24933 (defun org-insert-centered (s &optional underline)
24934 "Insert the string S centered and underline it with character UNDERLINE."
24935 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24936 (insert (make-string ind ?\ ) s "\n")
24937 (if underline
24938 (insert (make-string ind ?\ )
24939 (make-string (string-width s) underline)
24940 "\n"))))
24942 (defun org-ascii-level-start (level title umax &optional lines)
24943 "Insert a new level in ASCII export."
24944 (let (char (n (- level umax 1)) (ind 0))
24945 (if (> level umax)
24946 (progn
24947 (insert (make-string (* 2 n) ?\ )
24948 (char-to-string (nth (% n (length org-export-ascii-bullets))
24949 org-export-ascii-bullets))
24950 " " title "\n")
24951 ;; find the indentation of the next non-empty line
24952 (catch 'stop
24953 (while lines
24954 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24955 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24956 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24957 (pop lines)))
24958 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24959 (if (or (not (equal (char-before) ?\n))
24960 (not (equal (char-before (1- (point))) ?\n)))
24961 (insert "\n"))
24962 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24963 (unless org-export-with-tags
24964 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24965 (setq title (replace-match "" t t title))))
24966 (if org-export-with-section-numbers
24967 (setq title (concat (org-section-number level) " " title)))
24968 (insert title "\n" (make-string (string-width title) char) "\n")
24969 (setq org-ascii-current-indentation '(0 . 0)))))
24971 (defun org-export-visible (type arg)
24972 "Create a copy of the visible part of the current buffer, and export it.
24973 The copy is created in a temporary buffer and removed after use.
24974 TYPE is the final key (as a string) that also select the export command in
24975 the `C-c C-e' export dispatcher.
24976 As a special case, if the you type SPC at the prompt, the temporary
24977 org-mode file will not be removed but presented to you so that you can
24978 continue to use it. The prefix arg ARG is passed through to the exporting
24979 command."
24980 (interactive
24981 (list (progn
24982 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24983 (read-char-exclusive))
24984 current-prefix-arg))
24985 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24986 (error "Invalid export key"))
24987 (let* ((binding (cdr (assoc type
24988 '((?a . org-export-as-ascii)
24989 (?\C-a . org-export-as-ascii)
24990 (?b . org-export-as-html-and-open)
24991 (?\C-b . org-export-as-html-and-open)
24992 (?h . org-export-as-html)
24993 (?H . org-export-as-html-to-buffer)
24994 (?R . org-export-region-as-html)
24995 (?x . org-export-as-xoxo)))))
24996 (keepp (equal type ?\ ))
24997 (file buffer-file-name)
24998 (buffer (get-buffer-create "*Org Export Visible*"))
24999 s e)
25000 ;; Need to hack the drawers here.
25001 (save-excursion
25002 (goto-char (point-min))
25003 (while (re-search-forward org-drawer-regexp nil t)
25004 (goto-char (match-beginning 1))
25005 (or (org-invisible-p) (org-flag-drawer nil))))
25006 (with-current-buffer buffer (erase-buffer))
25007 (save-excursion
25008 (setq s (goto-char (point-min)))
25009 (while (not (= (point) (point-max)))
25010 (goto-char (org-find-invisible))
25011 (append-to-buffer buffer s (point))
25012 (setq s (goto-char (org-find-visible))))
25013 (org-cycle-hide-drawers 'all)
25014 (goto-char (point-min))
25015 (unless keepp
25016 ;; Copy all comment lines to the end, to make sure #+ settings are
25017 ;; still available for the second export step. Kind of a hack, but
25018 ;; does do the trick.
25019 (if (looking-at "#[^\r\n]*")
25020 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25021 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25022 (append-to-buffer buffer (1+ (match-beginning 0))
25023 (min (point-max) (1+ (match-end 0))))))
25024 (set-buffer buffer)
25025 (let ((buffer-file-name file)
25026 (org-inhibit-startup t))
25027 (org-mode)
25028 (show-all)
25029 (unless keepp (funcall binding arg))))
25030 (if (not keepp)
25031 (kill-buffer buffer)
25032 (switch-to-buffer-other-window buffer)
25033 (goto-char (point-min)))))
25035 (defun org-find-visible ()
25036 (let ((s (point)))
25037 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25038 (get-char-property s 'invisible)))
25040 (defun org-find-invisible ()
25041 (let ((s (point)))
25042 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25043 (not (get-char-property s 'invisible))))
25046 ;;; HTML export
25048 (defun org-get-current-options ()
25049 "Return a string with current options as keyword options.
25050 Does include HTML export options as well as TODO and CATEGORY stuff."
25051 (format
25052 "#+TITLE: %s
25053 #+AUTHOR: %s
25054 #+EMAIL: %s
25055 #+LANGUAGE: %s
25056 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25057 #+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
25058 #+CATEGORY: %s
25059 #+SEQ_TODO: %s
25060 #+TYP_TODO: %s
25061 #+PRIORITIES: %c %c %c
25062 #+DRAWERS: %s
25063 #+STARTUP: %s %s %s %s %s
25064 #+TAGS: %s
25065 #+ARCHIVE: %s
25066 #+LINK: %s
25068 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25069 org-export-headline-levels
25070 org-export-with-section-numbers
25071 org-export-with-toc
25072 org-export-preserve-breaks
25073 org-export-html-expand
25074 org-export-with-fixed-width
25075 org-export-with-tables
25076 org-export-with-sub-superscripts
25077 org-export-with-special-strings
25078 org-export-with-footnotes
25079 org-export-with-emphasize
25080 org-export-with-TeX-macros
25081 org-export-with-LaTeX-fragments
25082 org-export-skip-text-before-1st-heading
25083 org-export-with-drawers
25084 org-export-with-tags
25085 (file-name-nondirectory buffer-file-name)
25086 "TODO FEEDBACK VERIFY DONE"
25087 "Me Jason Marie DONE"
25088 org-highest-priority org-lowest-priority org-default-priority
25089 (mapconcat 'identity org-drawers " ")
25090 (cdr (assoc org-startup-folded
25091 '((nil . "showall") (t . "overview") (content . "content"))))
25092 (if org-odd-levels-only "odd" "oddeven")
25093 (if org-hide-leading-stars "hidestars" "showstars")
25094 (if org-startup-align-all-tables "align" "noalign")
25095 (cond ((eq org-log-done t) "logdone")
25096 ((equal org-log-done 'note) "lognotedone")
25097 ((not org-log-done) "nologdone"))
25098 (or (mapconcat (lambda (x)
25099 (cond
25100 ((equal '(:startgroup) x) "{")
25101 ((equal '(:endgroup) x) "}")
25102 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25103 (t (car x))))
25104 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25105 org-archive-location
25106 "org file:~/org/%s.org"
25109 (defun org-insert-export-options-template ()
25110 "Insert into the buffer a template with information for exporting."
25111 (interactive)
25112 (if (not (bolp)) (newline))
25113 (let ((s (org-get-current-options)))
25114 (and (string-match "#\\+CATEGORY" s)
25115 (setq s (substring s 0 (match-beginning 0))))
25116 (insert s)))
25118 (defun org-toggle-fixed-width-section (arg)
25119 "Toggle the fixed-width export.
25120 If there is no active region, the QUOTE keyword at the current headline is
25121 inserted or removed. When present, it causes the text between this headline
25122 and the next to be exported as fixed-width text, and unmodified.
25123 If there is an active region, this command adds or removes a colon as the
25124 first character of this line. If the first character of a line is a colon,
25125 this line is also exported in fixed-width font."
25126 (interactive "P")
25127 (let* ((cc 0)
25128 (regionp (org-region-active-p))
25129 (beg (if regionp (region-beginning) (point)))
25130 (end (if regionp (region-end)))
25131 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25132 (case-fold-search nil)
25133 (re "[ \t]*\\(:\\)")
25134 off)
25135 (if regionp
25136 (save-excursion
25137 (goto-char beg)
25138 (setq cc (current-column))
25139 (beginning-of-line 1)
25140 (setq off (looking-at re))
25141 (while (> nlines 0)
25142 (setq nlines (1- nlines))
25143 (beginning-of-line 1)
25144 (cond
25145 (arg
25146 (move-to-column cc t)
25147 (insert ":\n")
25148 (forward-line -1))
25149 ((and off (looking-at re))
25150 (replace-match "" t t nil 1))
25151 ((not off) (move-to-column cc t) (insert ":")))
25152 (forward-line 1)))
25153 (save-excursion
25154 (org-back-to-heading)
25155 (if (looking-at (concat outline-regexp
25156 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25157 (replace-match "" t t nil 1)
25158 (if (looking-at outline-regexp)
25159 (progn
25160 (goto-char (match-end 0))
25161 (insert org-quote-string " "))))))))
25163 (defun org-export-as-html-and-open (arg)
25164 "Export the outline as HTML and immediately open it with a browser.
25165 If there is an active region, export only the region.
25166 The prefix ARG specifies how many levels of the outline should become
25167 headlines. The default is 3. Lower levels will become bulleted lists."
25168 (interactive "P")
25169 (org-export-as-html arg 'hidden)
25170 (org-open-file buffer-file-name))
25172 (defun org-export-as-html-batch ()
25173 "Call `org-export-as-html', may be used in batch processing as
25174 emacs --batch
25175 --load=$HOME/lib/emacs/org.el
25176 --eval \"(setq org-export-headline-levels 2)\"
25177 --visit=MyFile --funcall org-export-as-html-batch"
25178 (org-export-as-html org-export-headline-levels 'hidden))
25180 (defun org-export-as-html-to-buffer (arg)
25181 "Call `org-exort-as-html` with output to a temporary buffer.
25182 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25183 (interactive "P")
25184 (org-export-as-html arg nil nil "*Org HTML Export*")
25185 (switch-to-buffer-other-window "*Org HTML Export*"))
25187 (defun org-replace-region-by-html (beg end)
25188 "Assume the current region has org-mode syntax, and convert it to HTML.
25189 This can be used in any buffer. For example, you could write an
25190 itemized list in org-mode syntax in an HTML buffer and then use this
25191 command to convert it."
25192 (interactive "r")
25193 (let (reg html buf pop-up-frames)
25194 (save-window-excursion
25195 (if (org-mode-p)
25196 (setq html (org-export-region-as-html
25197 beg end t 'string))
25198 (setq reg (buffer-substring beg end)
25199 buf (get-buffer-create "*Org tmp*"))
25200 (with-current-buffer buf
25201 (erase-buffer)
25202 (insert reg)
25203 (org-mode)
25204 (setq html (org-export-region-as-html
25205 (point-min) (point-max) t 'string)))
25206 (kill-buffer buf)))
25207 (delete-region beg end)
25208 (insert html)))
25210 (defun org-export-region-as-html (beg end &optional body-only buffer)
25211 "Convert region from BEG to END in org-mode buffer to HTML.
25212 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25213 contents, and only produce the region of converted text, useful for
25214 cut-and-paste operations.
25215 If BUFFER is a buffer or a string, use/create that buffer as a target
25216 of the converted HTML. If BUFFER is the symbol `string', return the
25217 produced HTML as a string and leave not buffer behind. For example,
25218 a Lisp program could call this function in the following way:
25220 (setq html (org-export-region-as-html beg end t 'string))
25222 When called interactively, the output buffer is selected, and shown
25223 in a window. A non-interactive call will only retunr the buffer."
25224 (interactive "r\nP")
25225 (when (interactive-p)
25226 (setq buffer "*Org HTML Export*"))
25227 (let ((transient-mark-mode t) (zmacs-regions t)
25228 rtn)
25229 (goto-char end)
25230 (set-mark (point)) ;; to activate the region
25231 (goto-char beg)
25232 (setq rtn (org-export-as-html
25233 nil nil nil
25234 buffer body-only))
25235 (if (fboundp 'deactivate-mark) (deactivate-mark))
25236 (if (and (interactive-p) (bufferp rtn))
25237 (switch-to-buffer-other-window rtn)
25238 rtn)))
25240 (defvar html-table-tag nil) ; dynamically scoped into this.
25241 (defun org-export-as-html (arg &optional hidden ext-plist
25242 to-buffer body-only pub-dir)
25243 "Export the outline as a pretty HTML file.
25244 If there is an active region, export only the region. The prefix
25245 ARG specifies how many levels of the outline should become
25246 headlines. The default is 3. Lower levels will become bulleted
25247 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25248 EXT-PLIST is a property list with external parameters overriding
25249 org-mode's default settings, but still inferior to file-local
25250 settings. When TO-BUFFER is non-nil, create a buffer with that
25251 name and export to that buffer. If TO-BUFFER is the symbol
25252 `string', don't leave any buffer behind but just return the
25253 resulting HTML as a string. When BODY-ONLY is set, don't produce
25254 the file header and footer, simply return the content of
25255 <body>...</body>, without even the body tags themselves. When
25256 PUB-DIR is set, use this as the publishing directory."
25257 (interactive "P")
25259 ;; Make sure we have a file name when we need it.
25260 (when (and (not (or to-buffer body-only))
25261 (not buffer-file-name))
25262 (if (buffer-base-buffer)
25263 (org-set-local 'buffer-file-name
25264 (with-current-buffer (buffer-base-buffer)
25265 buffer-file-name))
25266 (error "Need a file name to be able to export.")))
25268 (message "Exporting...")
25269 (setq-default org-todo-line-regexp org-todo-line-regexp)
25270 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25271 (setq-default org-done-keywords org-done-keywords)
25272 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25273 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25274 ext-plist
25275 (org-infile-export-plist)))
25277 (style (plist-get opt-plist :style))
25278 (html-extension (plist-get opt-plist :html-extension))
25279 (link-validate (plist-get opt-plist :link-validation-function))
25280 valid thetoc have-headings first-heading-pos
25281 (odd org-odd-levels-only)
25282 (region-p (org-region-active-p))
25283 (subtree-p
25284 (when region-p
25285 (save-excursion
25286 (goto-char (region-beginning))
25287 (and (org-at-heading-p)
25288 (>= (org-end-of-subtree t t) (region-end))))))
25289 ;; The following two are dynamically scoped into other
25290 ;; routines below.
25291 (org-current-export-dir
25292 (or pub-dir (org-export-directory :html opt-plist)))
25293 (org-current-export-file buffer-file-name)
25294 (level 0) (line "") (origline "") txt todo
25295 (umax nil)
25296 (umax-toc nil)
25297 (filename (if to-buffer nil
25298 (expand-file-name
25299 (concat
25300 (file-name-sans-extension
25301 (or (and subtree-p
25302 (org-entry-get (region-beginning)
25303 "EXPORT_FILE_NAME" t))
25304 (file-name-nondirectory buffer-file-name)))
25305 "." html-extension)
25306 (file-name-as-directory
25307 (or pub-dir (org-export-directory :html opt-plist))))))
25308 (current-dir (if buffer-file-name
25309 (file-name-directory buffer-file-name)
25310 default-directory))
25311 (buffer (if to-buffer
25312 (cond
25313 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25314 (t (get-buffer-create to-buffer)))
25315 (find-file-noselect filename)))
25316 (org-levels-open (make-vector org-level-max nil))
25317 (date (plist-get opt-plist :date))
25318 (author (plist-get opt-plist :author))
25319 (title (or (and subtree-p (org-export-get-title-from-subtree))
25320 (plist-get opt-plist :title)
25321 (and (not
25322 (plist-get opt-plist :skip-before-1st-heading))
25323 (org-export-grab-title-from-buffer))
25324 (and buffer-file-name
25325 (file-name-sans-extension
25326 (file-name-nondirectory buffer-file-name)))
25327 "UNTITLED"))
25328 (html-table-tag (plist-get opt-plist :html-table-tag))
25329 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25330 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25331 (inquote nil)
25332 (infixed nil)
25333 (in-local-list nil)
25334 (local-list-num nil)
25335 (local-list-indent nil)
25336 (llt org-plain-list-ordered-item-terminator)
25337 (email (plist-get opt-plist :email))
25338 (language (plist-get opt-plist :language))
25339 (lang-words nil)
25340 (target-alist nil) tg
25341 (head-count 0) cnt
25342 (start 0)
25343 (coding-system (and (boundp 'buffer-file-coding-system)
25344 buffer-file-coding-system))
25345 (coding-system-for-write (or org-export-html-coding-system
25346 coding-system))
25347 (save-buffer-coding-system (or org-export-html-coding-system
25348 coding-system))
25349 (charset (and coding-system-for-write
25350 (fboundp 'coding-system-get)
25351 (coding-system-get coding-system-for-write
25352 'mime-charset)))
25353 (region
25354 (buffer-substring
25355 (if region-p (region-beginning) (point-min))
25356 (if region-p (region-end) (point-max))))
25357 (lines
25358 (org-split-string
25359 (org-cleaned-string-for-export
25360 region
25361 :emph-multiline t
25362 :for-html t
25363 :skip-before-1st-heading
25364 (plist-get opt-plist :skip-before-1st-heading)
25365 :drawers (plist-get opt-plist :drawers)
25366 :archived-trees
25367 (plist-get opt-plist :archived-trees)
25368 :add-text
25369 (plist-get opt-plist :text)
25370 :LaTeX-fragments
25371 (plist-get opt-plist :LaTeX-fragments))
25372 "[\r\n]"))
25373 table-open type
25374 table-buffer table-orig-buffer
25375 ind start-is-num starter didclose
25376 rpl path desc descp desc1 desc2 link
25379 (let ((inhibit-read-only t))
25380 (org-unmodified
25381 (remove-text-properties (point-min) (point-max)
25382 '(:org-license-to-kill t))))
25384 (message "Exporting...")
25386 (setq org-min-level (org-get-min-level lines))
25387 (setq org-last-level org-min-level)
25388 (org-init-section-numbers)
25390 (cond
25391 ((and date (string-match "%" date))
25392 (setq date (format-time-string date (current-time))))
25393 (date)
25394 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25396 ;; Get the language-dependent settings
25397 (setq lang-words (or (assoc language org-export-language-setup)
25398 (assoc "en" org-export-language-setup)))
25400 ;; Switch to the output buffer
25401 (set-buffer buffer)
25402 (let ((inhibit-read-only t)) (erase-buffer))
25403 (fundamental-mode)
25405 (and (fboundp 'set-buffer-file-coding-system)
25406 (set-buffer-file-coding-system coding-system-for-write))
25408 (let ((case-fold-search nil)
25409 (org-odd-levels-only odd))
25410 ;; create local variables for all options, to make sure all called
25411 ;; functions get the correct information
25412 (mapc (lambda (x)
25413 (set (make-local-variable (cdr x))
25414 (plist-get opt-plist (car x))))
25415 org-export-plist-vars)
25416 (setq umax (if arg (prefix-numeric-value arg)
25417 org-export-headline-levels))
25418 (setq umax-toc (if (integerp org-export-with-toc)
25419 (min org-export-with-toc umax)
25420 umax))
25421 (unless body-only
25422 ;; File header
25423 (insert (format
25424 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25425 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25426 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25427 lang=\"%s\" xml:lang=\"%s\">
25428 <head>
25429 <title>%s</title>
25430 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25431 <meta name=\"generator\" content=\"Org-mode\"/>
25432 <meta name=\"generated\" content=\"%s\"/>
25433 <meta name=\"author\" content=\"%s\"/>
25435 </head><body>
25437 language language (org-html-expand title)
25438 (or charset "iso-8859-1") date author style))
25440 (insert (or (plist-get opt-plist :preamble) ""))
25442 (when (plist-get opt-plist :auto-preamble)
25443 (if title (insert (format org-export-html-title-format
25444 (org-html-expand title))))))
25446 (if (and org-export-with-toc (not body-only))
25447 (progn
25448 (push (format "<h%d>%s</h%d>\n"
25449 org-export-html-toplevel-hlevel
25450 (nth 3 lang-words)
25451 org-export-html-toplevel-hlevel)
25452 thetoc)
25453 (push "<ul>\n<li>" thetoc)
25454 (setq lines
25455 (mapcar '(lambda (line)
25456 (if (string-match org-todo-line-regexp line)
25457 ;; This is a headline
25458 (progn
25459 (setq have-headings t)
25460 (setq level (- (match-end 1) (match-beginning 1))
25461 level (org-tr-level level)
25462 txt (save-match-data
25463 (org-html-expand
25464 (org-export-cleanup-toc-line
25465 (match-string 3 line))))
25466 todo
25467 (or (and org-export-mark-todo-in-toc
25468 (match-beginning 2)
25469 (not (member (match-string 2 line)
25470 org-done-keywords)))
25471 ; TODO, not DONE
25472 (and org-export-mark-todo-in-toc
25473 (= level umax-toc)
25474 (org-search-todo-below
25475 line lines level))))
25476 (if (string-match
25477 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25478 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25479 (if (string-match quote-re0 txt)
25480 (setq txt (replace-match "" t t txt)))
25481 (if org-export-with-section-numbers
25482 (setq txt (concat (org-section-number level)
25483 " " txt)))
25484 (if (<= level (max umax umax-toc))
25485 (setq head-count (+ head-count 1)))
25486 (if (<= level umax-toc)
25487 (progn
25488 (if (> level org-last-level)
25489 (progn
25490 (setq cnt (- level org-last-level))
25491 (while (>= (setq cnt (1- cnt)) 0)
25492 (push "\n<ul>\n<li>" thetoc))
25493 (push "\n" thetoc)))
25494 (if (< level org-last-level)
25495 (progn
25496 (setq cnt (- org-last-level level))
25497 (while (>= (setq cnt (1- cnt)) 0)
25498 (push "</li>\n</ul>" thetoc))
25499 (push "\n" thetoc)))
25500 ;; Check for targets
25501 (while (string-match org-target-regexp line)
25502 (setq tg (match-string 1 line)
25503 line (replace-match
25504 (concat "@<span class=\"target\">" tg "@</span> ")
25505 t t line))
25506 (push (cons (org-solidify-link-text tg)
25507 (format "sec-%d" head-count))
25508 target-alist))
25509 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25510 (setq txt (replace-match "" t t txt)))
25511 (push
25512 (format
25513 (if todo
25514 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25515 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25516 head-count txt) thetoc)
25518 (setq org-last-level level))
25520 line)
25521 lines))
25522 (while (> org-last-level (1- org-min-level))
25523 (setq org-last-level (1- org-last-level))
25524 (push "</li>\n</ul>\n" thetoc))
25525 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25527 (setq head-count 0)
25528 (org-init-section-numbers)
25530 (while (setq line (pop lines) origline line)
25531 (catch 'nextline
25533 ;; end of quote section?
25534 (when (and inquote (string-match "^\\*+ " line))
25535 (insert "</pre>\n")
25536 (setq inquote nil))
25537 ;; inside a quote section?
25538 (when inquote
25539 (insert (org-html-protect line) "\n")
25540 (throw 'nextline nil))
25542 ;; verbatim lines
25543 (when (and org-export-with-fixed-width
25544 (string-match "^[ \t]*:\\(.*\\)" line))
25545 (when (not infixed)
25546 (setq infixed t)
25547 (insert "<pre>\n"))
25548 (insert (org-html-protect (match-string 1 line)) "\n")
25549 (when (and lines
25550 (not (string-match "^[ \t]*\\(:.*\\)"
25551 (car lines))))
25552 (setq infixed nil)
25553 (insert "</pre>\n"))
25554 (throw 'nextline nil))
25556 ;; Protected HTML
25557 (when (get-text-property 0 'org-protected line)
25558 (let (par)
25559 (when (re-search-backward
25560 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25561 (setq par (match-string 1))
25562 (replace-match "\\2\n"))
25563 (insert line "\n")
25564 (while (and lines
25565 (or (= (length (car lines)) 0)
25566 (get-text-property 0 'org-protected (car lines))))
25567 (insert (pop lines) "\n"))
25568 (and par (insert "<p>\n")))
25569 (throw 'nextline nil))
25571 ;; Horizontal line
25572 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25573 (insert "\n<hr/>\n")
25574 (throw 'nextline nil))
25576 ;; make targets to anchors
25577 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25578 (cond
25579 ((match-end 2)
25580 (setq line (replace-match
25581 (concat "@<a name=\""
25582 (org-solidify-link-text (match-string 1 line))
25583 "\">\\nbsp@</a>")
25584 t t line)))
25585 ((and org-export-with-toc (equal (string-to-char line) ?*))
25586 (setq line (replace-match
25587 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25588 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25589 t t line)))
25591 (setq line (replace-match
25592 (concat "@<a name=\""
25593 (org-solidify-link-text (match-string 1 line))
25594 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25595 t t line)))))
25597 (setq line (org-html-handle-time-stamps line))
25599 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25600 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25601 ;; Also handle sub_superscripts and checkboxes
25602 (or (string-match org-table-hline-regexp line)
25603 (setq line (org-html-expand line)))
25605 ;; Format the links
25606 (setq start 0)
25607 (while (string-match org-bracket-link-analytic-regexp line start)
25608 (setq start (match-beginning 0))
25609 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25610 (setq path (match-string 3 line))
25611 (setq desc1 (if (match-end 5) (match-string 5 line))
25612 desc2 (if (match-end 2) (concat type ":" path) path)
25613 descp (and desc1 (not (equal desc1 desc2)))
25614 desc (or desc1 desc2))
25615 ;; Make an image out of the description if that is so wanted
25616 (when (and descp (org-file-image-p desc))
25617 (save-match-data
25618 (if (string-match "^file:" desc)
25619 (setq desc (substring desc (match-end 0)))))
25620 (setq desc (concat "<img src=\"" desc "\"/>")))
25621 ;; FIXME: do we need to unescape here somewhere?
25622 (cond
25623 ((equal type "internal")
25624 (setq rpl
25625 (concat
25626 "<a href=\"#"
25627 (org-solidify-link-text
25628 (save-match-data (org-link-unescape path)) target-alist)
25629 "\">" desc "</a>")))
25630 ((member type '("http" "https"))
25631 ;; standard URL, just check if we need to inline an image
25632 (if (and (or (eq t org-export-html-inline-images)
25633 (and org-export-html-inline-images (not descp)))
25634 (org-file-image-p path))
25635 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25636 (setq link (concat type ":" path))
25637 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25638 ((member type '("ftp" "mailto" "news"))
25639 ;; standard URL
25640 (setq link (concat type ":" path))
25641 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25642 ((string= type "file")
25643 ;; FILE link
25644 (let* ((filename path)
25645 (abs-p (file-name-absolute-p filename))
25646 thefile file-is-image-p search)
25647 (save-match-data
25648 (if (string-match "::\\(.*\\)" filename)
25649 (setq search (match-string 1 filename)
25650 filename (replace-match "" t nil filename)))
25651 (setq valid
25652 (if (functionp link-validate)
25653 (funcall link-validate filename current-dir)
25655 (setq file-is-image-p (org-file-image-p filename))
25656 (setq thefile (if abs-p (expand-file-name filename) filename))
25657 (when (and org-export-html-link-org-files-as-html
25658 (string-match "\\.org$" thefile))
25659 (setq thefile (concat (substring thefile 0
25660 (match-beginning 0))
25661 "." html-extension))
25662 (if (and search
25663 ;; make sure this is can be used as target search
25664 (not (string-match "^[0-9]*$" search))
25665 (not (string-match "^\\*" search))
25666 (not (string-match "^/.*/$" search)))
25667 (setq thefile (concat thefile "#"
25668 (org-solidify-link-text
25669 (org-link-unescape search)))))
25670 (when (string-match "^file:" desc)
25671 (setq desc (replace-match "" t t desc))
25672 (if (string-match "\\.org$" desc)
25673 (setq desc (replace-match "" t t desc))))))
25674 (setq rpl (if (and file-is-image-p
25675 (or (eq t org-export-html-inline-images)
25676 (and org-export-html-inline-images
25677 (not descp))))
25678 (concat "<img src=\"" thefile "\"/>")
25679 (concat "<a href=\"" thefile "\">" desc "</a>")))
25680 (if (not valid) (setq rpl desc))))
25681 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25682 (setq rpl (concat "<i>&lt;" type ":"
25683 (save-match-data (org-link-unescape path))
25684 "&gt;</i>"))))
25685 (setq line (replace-match rpl t t line)
25686 start (+ start (length rpl))))
25688 ;; TODO items
25689 (if (and (string-match org-todo-line-regexp line)
25690 (match-beginning 2))
25692 (setq line
25693 (concat (substring line 0 (match-beginning 2))
25694 "<span class=\""
25695 (if (member (match-string 2 line)
25696 org-done-keywords)
25697 "done" "todo")
25698 "\">" (match-string 2 line)
25699 "</span>" (substring line (match-end 2)))))
25701 ;; Does this contain a reference to a footnote?
25702 (when org-export-with-footnotes
25703 (setq start 0)
25704 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25705 (if (get-text-property (match-beginning 2) 'org-protected line)
25706 (setq start (match-end 2))
25707 (let ((n (match-string 2 line)))
25708 (setq line
25709 (replace-match
25710 (format
25711 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25712 (match-string 1 line) n n n)
25713 t t line))))))
25715 (cond
25716 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25717 ;; This is a headline
25718 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25719 txt (match-string 2 line))
25720 (if (string-match quote-re0 txt)
25721 (setq txt (replace-match "" t t txt)))
25722 (if (<= level (max umax umax-toc))
25723 (setq head-count (+ head-count 1)))
25724 (when in-local-list
25725 ;; Close any local lists before inserting a new header line
25726 (while local-list-num
25727 (org-close-li)
25728 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25729 (pop local-list-num))
25730 (setq local-list-indent nil
25731 in-local-list nil))
25732 (setq first-heading-pos (or first-heading-pos (point)))
25733 (org-html-level-start level txt umax
25734 (and org-export-with-toc (<= level umax))
25735 head-count)
25736 ;; QUOTES
25737 (when (string-match quote-re line)
25738 (insert "<pre>")
25739 (setq inquote t)))
25741 ((and org-export-with-tables
25742 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25743 (if (not table-open)
25744 ;; New table starts
25745 (setq table-open t table-buffer nil table-orig-buffer nil))
25746 ;; Accumulate lines
25747 (setq table-buffer (cons line table-buffer)
25748 table-orig-buffer (cons origline table-orig-buffer))
25749 (when (or (not lines)
25750 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25751 (car lines))))
25752 (setq table-open nil
25753 table-buffer (nreverse table-buffer)
25754 table-orig-buffer (nreverse table-orig-buffer))
25755 (org-close-par-maybe)
25756 (insert (org-format-table-html table-buffer table-orig-buffer))))
25758 ;; Normal lines
25759 (when (string-match
25760 (cond
25761 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25762 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25763 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25764 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25765 line)
25766 (setq ind (org-get-string-indentation line)
25767 start-is-num (match-beginning 4)
25768 starter (if (match-beginning 2)
25769 (substring (match-string 2 line) 0 -1))
25770 line (substring line (match-beginning 5)))
25771 (unless (string-match "[^ \t]" line)
25772 ;; empty line. Pretend indentation is large.
25773 (setq ind (if org-empty-line-terminates-plain-lists
25775 (1+ (or (car local-list-indent) 1)))))
25776 (setq didclose nil)
25777 (while (and in-local-list
25778 (or (and (= ind (car local-list-indent))
25779 (not starter))
25780 (< ind (car local-list-indent))))
25781 (setq didclose t)
25782 (org-close-li)
25783 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25784 (pop local-list-num) (pop local-list-indent)
25785 (setq in-local-list local-list-indent))
25786 (cond
25787 ((and starter
25788 (or (not in-local-list)
25789 (> ind (car local-list-indent))))
25790 ;; Start new (level of) list
25791 (org-close-par-maybe)
25792 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25793 (push start-is-num local-list-num)
25794 (push ind local-list-indent)
25795 (setq in-local-list t))
25796 (starter
25797 ;; continue current list
25798 (org-close-li)
25799 (insert "<li>\n"))
25800 (didclose
25801 ;; we did close a list, normal text follows: need <p>
25802 (org-open-par)))
25803 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25804 (setq line
25805 (replace-match
25806 (if (equal (match-string 1 line) "X")
25807 "<b>[X]</b>"
25808 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25809 t t line))))
25811 ;; Empty lines start a new paragraph. If hand-formatted lists
25812 ;; are not fully interpreted, lines starting with "-", "+", "*"
25813 ;; also start a new paragraph.
25814 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25816 ;; Is this the start of a footnote?
25817 (when org-export-with-footnotes
25818 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25819 (org-close-par-maybe)
25820 (let ((n (match-string 1 line)))
25821 (setq line (replace-match
25822 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25824 ;; Check if the line break needs to be conserved
25825 (cond
25826 ((string-match "\\\\\\\\[ \t]*$" line)
25827 (setq line (replace-match "<br/>" t t line)))
25828 (org-export-preserve-breaks
25829 (setq line (concat line "<br/>"))))
25831 (insert line "\n")))))
25833 ;; Properly close all local lists and other lists
25834 (when inquote (insert "</pre>\n"))
25835 (when in-local-list
25836 ;; Close any local lists before inserting a new header line
25837 (while local-list-num
25838 (org-close-li)
25839 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25840 (pop local-list-num))
25841 (setq local-list-indent nil
25842 in-local-list nil))
25843 (org-html-level-start 1 nil umax
25844 (and org-export-with-toc (<= level umax))
25845 head-count)
25847 (unless body-only
25848 (when (plist-get opt-plist :auto-postamble)
25849 (insert "<div id=\"postamble\">")
25850 (when (and org-export-author-info author)
25851 (insert "<p class=\"author\"> "
25852 (nth 1 lang-words) ": " author "\n")
25853 (when email
25854 (if (listp (split-string email ",+ *"))
25855 (mapc (lambda(e)
25856 (insert "<a href=\"mailto:" e "\">&lt;"
25857 e "&gt;</a>\n"))
25858 (split-string email ",+ *"))
25859 (insert "<a href=\"mailto:" email "\">&lt;"
25860 email "&gt;</a>\n")))
25861 (insert "</p>\n"))
25862 (when (and date org-export-time-stamp-file)
25863 (insert "<p class=\"date\"> "
25864 (nth 2 lang-words) ": "
25865 date "</p>\n"))
25866 (insert "</div>"))
25868 (if org-export-html-with-timestamp
25869 (insert org-export-html-html-helper-timestamp))
25870 (insert (or (plist-get opt-plist :postamble) ""))
25871 (insert "</body>\n</html>\n"))
25873 (normal-mode)
25874 (if (eq major-mode default-major-mode) (html-mode))
25876 ;; insert the table of contents
25877 (goto-char (point-min))
25878 (when thetoc
25879 (if (or (re-search-forward
25880 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25881 (re-search-forward
25882 "\\[TABLE-OF-CONTENTS\\]" nil t))
25883 (progn
25884 (goto-char (match-beginning 0))
25885 (replace-match ""))
25886 (goto-char first-heading-pos)
25887 (when (looking-at "\\s-*</p>")
25888 (goto-char (match-end 0))
25889 (insert "\n")))
25890 (insert "<div id=\"table-of-contents\">\n")
25891 (mapc 'insert thetoc)
25892 (insert "</div>\n"))
25893 ;; remove empty paragraphs and lists
25894 (goto-char (point-min))
25895 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25896 (replace-match ""))
25897 (goto-char (point-min))
25898 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25899 (replace-match ""))
25900 (goto-char (point-min))
25901 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25902 (replace-match ""))
25903 ;; Convert whitespace place holders
25904 (goto-char (point-min))
25905 (let (beg end n)
25906 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25907 (setq n (get-text-property beg 'org-whitespace)
25908 end (next-single-property-change beg 'org-whitespace))
25909 (goto-char beg)
25910 (delete-region beg end)
25911 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25912 (make-string n ?x)))))
25914 (or to-buffer (progn (save-buffer) (kill-buffer (current-buffer))))
25915 (goto-char (point-min))
25916 (message "Exporting... done")
25917 (if (eq to-buffer 'string)
25918 (prog1 (buffer-substring (point-min) (point-max))
25919 (kill-buffer (current-buffer)))
25920 (current-buffer)))))
25922 (defvar org-table-colgroup-info nil)
25923 (defun org-format-table-ascii (lines)
25924 "Format a table for ascii export."
25925 (if (stringp lines)
25926 (setq lines (org-split-string lines "\n")))
25927 (if (not (string-match "^[ \t]*|" (car lines)))
25928 ;; Table made by table.el - test for spanning
25929 lines
25931 ;; A normal org table
25932 ;; Get rid of hlines at beginning and end
25933 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25934 (setq lines (nreverse lines))
25935 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25936 (setq lines (nreverse lines))
25937 (when org-export-table-remove-special-lines
25938 ;; Check if the table has a marking column. If yes remove the
25939 ;; column and the special lines
25940 (setq lines (org-table-clean-before-export lines)))
25941 ;; Get rid of the vertical lines except for grouping
25942 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25943 rtn line vl1 start)
25944 (while (setq line (pop lines))
25945 (if (string-match org-table-hline-regexp line)
25946 (and (string-match "|\\(.*\\)|" line)
25947 (setq line (replace-match " \\1" t nil line)))
25948 (setq start 0 vl1 vl)
25949 (while (string-match "|" line start)
25950 (setq start (match-end 0))
25951 (or (pop vl1) (setq line (replace-match " " t t line)))))
25952 (push line rtn))
25953 (nreverse rtn))))
25955 (defun org-colgroup-info-to-vline-list (info)
25956 (let (vl new last)
25957 (while info
25958 (setq last new new (pop info))
25959 (if (or (memq last '(:end :startend))
25960 (memq new '(:start :startend)))
25961 (push t vl)
25962 (push nil vl)))
25963 (setq vl (nreverse vl))
25964 (and vl (setcar vl nil))
25965 vl))
25967 (defun org-format-table-html (lines olines)
25968 "Find out which HTML converter to use and return the HTML code."
25969 (if (stringp lines)
25970 (setq lines (org-split-string lines "\n")))
25971 (if (string-match "^[ \t]*|" (car lines))
25972 ;; A normal org table
25973 (org-format-org-table-html lines)
25974 ;; Table made by table.el - test for spanning
25975 (let* ((hlines (delq nil (mapcar
25976 (lambda (x)
25977 (if (string-match "^[ \t]*\\+-" x) x
25978 nil))
25979 lines)))
25980 (first (car hlines))
25981 (ll (and (string-match "\\S-+" first)
25982 (match-string 0 first)))
25983 (re (concat "^[ \t]*" (regexp-quote ll)))
25984 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25985 hlines))))
25986 (if (and (not spanning)
25987 (not org-export-prefer-native-exporter-for-tables))
25988 ;; We can use my own converter with HTML conversions
25989 (org-format-table-table-html lines)
25990 ;; Need to use the code generator in table.el, with the original text.
25991 (org-format-table-table-html-using-table-generate-source olines)))))
25993 (defun org-format-org-table-html (lines &optional splice)
25994 "Format a table into HTML."
25995 ;; Get rid of hlines at beginning and end
25996 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25997 (setq lines (nreverse lines))
25998 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25999 (setq lines (nreverse lines))
26000 (when org-export-table-remove-special-lines
26001 ;; Check if the table has a marking column. If yes remove the
26002 ;; column and the special lines
26003 (setq lines (org-table-clean-before-export lines)))
26005 (let ((head (and org-export-highlight-first-table-line
26006 (delq nil (mapcar
26007 (lambda (x) (string-match "^[ \t]*|-" x))
26008 (cdr lines)))))
26009 (nlines 0) fnum i
26010 tbopen line fields html gr colgropen)
26011 (if splice (setq head nil))
26012 (unless splice (push (if head "<thead>" "<tbody>") html))
26013 (setq tbopen t)
26014 (while (setq line (pop lines))
26015 (catch 'next-line
26016 (if (string-match "^[ \t]*|-" line)
26017 (progn
26018 (unless splice
26019 (push (if head "</thead>" "</tbody>") html)
26020 (if lines (push "<tbody>" html) (setq tbopen nil)))
26021 (setq head nil) ;; head ends here, first time around
26022 ;; ignore this line
26023 (throw 'next-line t)))
26024 ;; Break the line into fields
26025 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26026 (unless fnum (setq fnum (make-vector (length fields) 0)))
26027 (setq nlines (1+ nlines) i -1)
26028 (push (concat "<tr>"
26029 (mapconcat
26030 (lambda (x)
26031 (setq i (1+ i))
26032 (if (and (< i nlines)
26033 (string-match org-table-number-regexp x))
26034 (incf (aref fnum i)))
26035 (if head
26036 (concat (car org-export-table-header-tags) x
26037 (cdr org-export-table-header-tags))
26038 (concat (car org-export-table-data-tags) x
26039 (cdr org-export-table-data-tags))))
26040 fields "")
26041 "</tr>")
26042 html)))
26043 (unless splice (if tbopen (push "</tbody>" html)))
26044 (unless splice (push "</table>\n" html))
26045 (setq html (nreverse html))
26046 (unless splice
26047 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26048 (push (mapconcat
26049 (lambda (x)
26050 (setq gr (pop org-table-colgroup-info))
26051 (format "%s<col align=\"%s\"></col>%s"
26052 (if (memq gr '(:start :startend))
26053 (prog1
26054 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26055 (setq colgropen t))
26057 (if (> (/ (float x) nlines) org-table-number-fraction)
26058 "right" "left")
26059 (if (memq gr '(:end :startend))
26060 (progn (setq colgropen nil) "</colgroup>")
26061 "")))
26062 fnum "")
26063 html)
26064 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26065 (push html-table-tag html))
26066 (concat (mapconcat 'identity html "\n") "\n")))
26068 (defun org-table-clean-before-export (lines)
26069 "Check if the table has a marking column.
26070 If yes remove the column and the special lines."
26071 (setq org-table-colgroup-info nil)
26072 (if (memq nil
26073 (mapcar
26074 (lambda (x) (or (string-match "^[ \t]*|-" x)
26075 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26076 lines))
26077 (progn
26078 (setq org-table-clean-did-remove-column nil)
26079 (delq nil
26080 (mapcar
26081 (lambda (x)
26082 (cond
26083 ((string-match "^[ \t]*| */ *|" x)
26084 (setq org-table-colgroup-info
26085 (mapcar (lambda (x)
26086 (cond ((member x '("<" "&lt;")) :start)
26087 ((member x '(">" "&gt;")) :end)
26088 ((member x '("<>" "&lt;&gt;")) :startend)
26089 (t nil)))
26090 (org-split-string x "[ \t]*|[ \t]*")))
26091 nil)
26092 (t x)))
26093 lines)))
26094 (setq org-table-clean-did-remove-column t)
26095 (delq nil
26096 (mapcar
26097 (lambda (x)
26098 (cond
26099 ((string-match "^[ \t]*| */ *|" x)
26100 (setq org-table-colgroup-info
26101 (mapcar (lambda (x)
26102 (cond ((member x '("<" "&lt;")) :start)
26103 ((member x '(">" "&gt;")) :end)
26104 ((member x '("<>" "&lt;&gt;")) :startend)
26105 (t nil)))
26106 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26107 nil)
26108 ((string-match "^[ \t]*| *[!_^/] *|" x)
26109 nil) ; ignore this line
26110 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26111 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26112 ;; remove the first column
26113 (replace-match "\\1|" t nil x))))
26114 lines))))
26116 (defun org-format-table-table-html (lines)
26117 "Format a table generated by table.el into HTML.
26118 This conversion does *not* use `table-generate-source' from table.el.
26119 This has the advantage that Org-mode's HTML conversions can be used.
26120 But it has the disadvantage, that no cell- or row-spanning is allowed."
26121 (let (line field-buffer
26122 (head org-export-highlight-first-table-line)
26123 fields html empty)
26124 (setq html (concat html-table-tag "\n"))
26125 (while (setq line (pop lines))
26126 (setq empty "&nbsp;")
26127 (catch 'next-line
26128 (if (string-match "^[ \t]*\\+-" line)
26129 (progn
26130 (if field-buffer
26131 (progn
26132 (setq
26133 html
26134 (concat
26135 html
26136 "<tr>"
26137 (mapconcat
26138 (lambda (x)
26139 (if (equal x "") (setq x empty))
26140 (if head
26141 (concat (car org-export-table-header-tags) x
26142 (cdr org-export-table-header-tags))
26143 (concat (car org-export-table-data-tags) x
26144 (cdr org-export-table-data-tags))))
26145 field-buffer "\n")
26146 "</tr>\n"))
26147 (setq head nil)
26148 (setq field-buffer nil)))
26149 ;; Ignore this line
26150 (throw 'next-line t)))
26151 ;; Break the line into fields and store the fields
26152 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26153 (if field-buffer
26154 (setq field-buffer (mapcar
26155 (lambda (x)
26156 (concat x "<br/>" (pop fields)))
26157 field-buffer))
26158 (setq field-buffer fields))))
26159 (setq html (concat html "</table>\n"))
26160 html))
26162 (defun org-format-table-table-html-using-table-generate-source (lines)
26163 "Format a table into html, using `table-generate-source' from table.el.
26164 This has the advantage that cell- or row-spanning is allowed.
26165 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26166 (require 'table)
26167 (with-current-buffer (get-buffer-create " org-tmp1 ")
26168 (erase-buffer)
26169 (insert (mapconcat 'identity lines "\n"))
26170 (goto-char (point-min))
26171 (if (not (re-search-forward "|[^+]" nil t))
26172 (error "Error processing table"))
26173 (table-recognize-table)
26174 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26175 (table-generate-source 'html " org-tmp2 ")
26176 (set-buffer " org-tmp2 ")
26177 (buffer-substring (point-min) (point-max))))
26179 (defun org-html-handle-time-stamps (s)
26180 "Format time stamps in string S, or remove them."
26181 (catch 'exit
26182 (let (r b)
26183 (while (string-match org-maybe-keyword-time-regexp s)
26184 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26185 ;; never export CLOCK
26186 (throw 'exit ""))
26187 (or b (setq b (substring s 0 (match-beginning 0))))
26188 (if (not org-export-with-timestamps)
26189 (setq r (concat r (substring s 0 (match-beginning 0)))
26190 s (substring s (match-end 0)))
26191 (setq r (concat
26192 r (substring s 0 (match-beginning 0))
26193 (if (match-end 1)
26194 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26195 (match-string 1 s)))
26196 (format " @<span class=\"timestamp\">%s@</span>"
26197 (substring
26198 (org-translate-time (match-string 3 s)) 1 -1)))
26199 s (substring s (match-end 0)))))
26200 ;; Line break if line started and ended with time stamp stuff
26201 (if (not r)
26203 (setq r (concat r s))
26204 (unless (string-match "\\S-" (concat b s))
26205 (setq r (concat r "@<br/>")))
26206 r))))
26208 (defun org-html-protect (s)
26209 ;; convert & to &amp;, < to &lt; and > to &gt;
26210 (let ((start 0))
26211 (while (string-match "&" s start)
26212 (setq s (replace-match "&amp;" t t s)
26213 start (1+ (match-beginning 0))))
26214 (while (string-match "<" s)
26215 (setq s (replace-match "&lt;" t t s)))
26216 (while (string-match ">" s)
26217 (setq s (replace-match "&gt;" t t s))))
26220 (defun org-export-cleanup-toc-line (s)
26221 "Remove tags and time staps from lines going into the toc."
26222 (when (memq org-export-with-tags '(not-in-toc nil))
26223 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26224 (setq s (replace-match "" t t s))))
26225 (when org-export-remove-timestamps-from-toc
26226 (while (string-match org-maybe-keyword-time-regexp s)
26227 (setq s (replace-match "" t t s))))
26228 (while (string-match org-bracket-link-regexp s)
26229 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26230 t t s)))
26233 (defun org-html-expand (string)
26234 "Prepare STRING for HTML export. Applies all active conversions.
26235 If there are links in the string, don't modify these."
26236 (let* ((re (concat org-bracket-link-regexp "\\|"
26237 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26238 m s l res)
26239 (while (setq m (string-match re string))
26240 (setq s (substring string 0 m)
26241 l (match-string 0 string)
26242 string (substring string (match-end 0)))
26243 (push (org-html-do-expand s) res)
26244 (push l res))
26245 (push (org-html-do-expand string) res)
26246 (apply 'concat (nreverse res))))
26248 (defun org-html-do-expand (s)
26249 "Apply all active conversions to translate special ASCII to HTML."
26250 (setq s (org-html-protect s))
26251 (if org-export-html-expand
26252 (let ((start 0))
26253 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26254 (setq s (replace-match "<\\1>" t nil s)))))
26255 (if org-export-with-emphasize
26256 (setq s (org-export-html-convert-emphasize s)))
26257 (if org-export-with-special-strings
26258 (setq s (org-export-html-convert-special-strings s)))
26259 (if org-export-with-sub-superscripts
26260 (setq s (org-export-html-convert-sub-super s)))
26261 (if org-export-with-TeX-macros
26262 (let ((start 0) wd ass)
26263 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26264 (if (get-text-property (match-beginning 0) 'org-protected s)
26265 (setq start (match-end 0))
26266 (setq wd (match-string 1 s))
26267 (if (setq ass (assoc wd org-html-entities))
26268 (setq s (replace-match (or (cdr ass)
26269 (concat "&" (car ass) ";"))
26270 t t s))
26271 (setq start (+ start (length wd))))))))
26274 (defun org-create-multibrace-regexp (left right n)
26275 "Create a regular expression which will match a balanced sexp.
26276 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26277 as single character strings.
26278 The regexp returned will match the entire expression including the
26279 delimiters. It will also define a single group which contains the
26280 match except for the outermost delimiters. The maximum depth of
26281 stacked delimiters is N. Escaping delimiters is not possible."
26282 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26283 (or "\\|")
26284 (re nothing)
26285 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26286 (while (> n 1)
26287 (setq n (1- n)
26288 re (concat re or next)
26289 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26290 (concat left "\\(" re "\\)" right)))
26292 (defvar org-match-substring-regexp
26293 (concat
26294 "\\([^\\]\\)\\([_^]\\)\\("
26295 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26296 "\\|"
26297 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26298 "\\|"
26299 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26300 "The regular expression matching a sub- or superscript.")
26302 (defvar org-match-substring-with-braces-regexp
26303 (concat
26304 "\\([^\\]\\)\\([_^]\\)\\("
26305 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26306 "\\)")
26307 "The regular expression matching a sub- or superscript, forcing braces.")
26309 (defconst org-export-html-special-string-regexps
26310 '(("\\\\-" . "&shy;")
26311 ("---\\([^-]\\)" . "&mdash;\\1")
26312 ("--\\([^-]\\)" . "&ndash;\\1")
26313 ("\\.\\.\\." . "&hellip;"))
26314 "Regular expressions for special string conversion.")
26316 (defun org-export-html-convert-special-strings (string)
26317 "Convert special characters in STRING to HTML."
26318 (let ((all org-export-html-special-string-regexps)
26319 e a re rpl start)
26320 (while (setq a (pop all))
26321 (setq re (car a) rpl (cdr a) start 0)
26322 (while (string-match re string start)
26323 (if (get-text-property (match-beginning 0) 'org-protected string)
26324 (setq start (match-end 0))
26325 (setq string (replace-match rpl t nil string)))))
26326 string))
26328 (defun org-export-html-convert-sub-super (string)
26329 "Convert sub- and superscripts in STRING to HTML."
26330 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26331 (while (string-match org-match-substring-regexp string s)
26332 (cond
26333 ((and requireb (match-end 8)) (setq s (match-end 2)))
26334 ((get-text-property (match-beginning 2) 'org-protected string)
26335 (setq s (match-end 2)))
26337 (setq s (match-end 1)
26338 key (if (string= (match-string 2 string) "_") "sub" "sup")
26339 c (or (match-string 8 string)
26340 (match-string 6 string)
26341 (match-string 5 string))
26342 string (replace-match
26343 (concat (match-string 1 string)
26344 "<" key ">" c "</" key ">")
26345 t t string)))))
26346 (while (string-match "\\\\\\([_^]\\)" string)
26347 (setq string (replace-match (match-string 1 string) t t string)))
26348 string))
26350 (defun org-export-html-convert-emphasize (string)
26351 "Apply emphasis."
26352 (let ((s 0) rpl)
26353 (while (string-match org-emph-re string s)
26354 (if (not (equal
26355 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26356 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26357 (setq s (match-beginning 0)
26359 (concat
26360 (match-string 1 string)
26361 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26362 (match-string 4 string)
26363 (nth 3 (assoc (match-string 3 string)
26364 org-emphasis-alist))
26365 (match-string 5 string))
26366 string (replace-match rpl t t string)
26367 s (+ s (- (length rpl) 2)))
26368 (setq s (1+ s))))
26369 string))
26371 (defvar org-par-open nil)
26372 (defun org-open-par ()
26373 "Insert <p>, but first close previous paragraph if any."
26374 (org-close-par-maybe)
26375 (insert "\n<p>")
26376 (setq org-par-open t))
26377 (defun org-close-par-maybe ()
26378 "Close paragraph if there is one open."
26379 (when org-par-open
26380 (insert "</p>")
26381 (setq org-par-open nil)))
26382 (defun org-close-li ()
26383 "Close <li> if necessary."
26384 (org-close-par-maybe)
26385 (insert "</li>\n"))
26387 (defvar body-only) ; dynamically scoped into this.
26388 (defun org-html-level-start (level title umax with-toc head-count)
26389 "Insert a new level in HTML export.
26390 When TITLE is nil, just close all open levels."
26391 (org-close-par-maybe)
26392 (let ((l org-level-max))
26393 (while (>= l level)
26394 (if (aref org-levels-open (1- l))
26395 (progn
26396 (org-html-level-close l umax)
26397 (aset org-levels-open (1- l) nil)))
26398 (setq l (1- l)))
26399 (when title
26400 ;; If title is nil, this means this function is called to close
26401 ;; all levels, so the rest is done only if title is given
26402 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26403 (setq title (replace-match
26404 (if org-export-with-tags
26405 (save-match-data
26406 (concat
26407 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26408 (mapconcat 'identity (org-split-string
26409 (match-string 1 title) ":")
26410 "&nbsp;")
26411 "</span>"))
26413 t t title)))
26414 (if (> level umax)
26415 (progn
26416 (if (aref org-levels-open (1- level))
26417 (progn
26418 (org-close-li)
26419 (insert "<li>" title "<br/>\n"))
26420 (aset org-levels-open (1- level) t)
26421 (org-close-par-maybe)
26422 (insert "<ul>\n<li>" title "<br/>\n")))
26423 (aset org-levels-open (1- level) t)
26424 (if (and org-export-with-section-numbers (not body-only))
26425 (setq title (concat (org-section-number level) " " title)))
26426 (setq level (+ level org-export-html-toplevel-hlevel -1))
26427 (if with-toc
26428 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26429 level level head-count title level))
26430 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26431 (org-open-par)))))
26433 (defun org-html-level-close (level max-outline-level)
26434 "Terminate one level in HTML export."
26435 (if (<= level max-outline-level)
26436 (insert "</div>\n")
26437 (org-close-li)
26438 (insert "</ul>\n")))
26440 ;;; iCalendar export
26442 ;;;###autoload
26443 (defun org-export-icalendar-this-file ()
26444 "Export current file as an iCalendar file.
26445 The iCalendar file will be located in the same directory as the Org-mode
26446 file, but with extension `.ics'."
26447 (interactive)
26448 (org-export-icalendar nil buffer-file-name))
26450 ;;;###autoload
26451 (defun org-export-icalendar-all-agenda-files ()
26452 "Export all files in `org-agenda-files' to iCalendar .ics files.
26453 Each iCalendar file will be located in the same directory as the Org-mode
26454 file, but with extension `.ics'."
26455 (interactive)
26456 (apply 'org-export-icalendar nil (org-agenda-files t)))
26458 ;;;###autoload
26459 (defun org-export-icalendar-combine-agenda-files ()
26460 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26461 The file is stored under the name `org-combined-agenda-icalendar-file'."
26462 (interactive)
26463 (apply 'org-export-icalendar t (org-agenda-files t)))
26465 (defun org-export-icalendar (combine &rest files)
26466 "Create iCalendar files for all elements of FILES.
26467 If COMBINE is non-nil, combine all calendar entries into a single large
26468 file and store it under the name `org-combined-agenda-icalendar-file'."
26469 (save-excursion
26470 (org-prepare-agenda-buffers files)
26471 (let* ((dir (org-export-directory
26472 :ical (list :publishing-directory
26473 org-export-publishing-directory)))
26474 file ical-file ical-buffer category started org-agenda-new-buffers)
26476 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26477 (when combine
26478 (setq ical-file
26479 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26480 org-combined-agenda-icalendar-file
26481 (expand-file-name org-combined-agenda-icalendar-file dir))
26482 ical-buffer (org-get-agenda-file-buffer ical-file))
26483 (set-buffer ical-buffer) (erase-buffer))
26484 (while (setq file (pop files))
26485 (catch 'nextfile
26486 (org-check-agenda-file file)
26487 (set-buffer (org-get-agenda-file-buffer file))
26488 (unless combine
26489 (setq ical-file (concat (file-name-as-directory dir)
26490 (file-name-sans-extension
26491 (file-name-nondirectory buffer-file-name))
26492 ".ics"))
26493 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26494 (with-current-buffer ical-buffer (erase-buffer)))
26495 (setq category (or org-category
26496 (file-name-sans-extension
26497 (file-name-nondirectory buffer-file-name))))
26498 (if (symbolp category) (setq category (symbol-name category)))
26499 (let ((standard-output ical-buffer))
26500 (if combine
26501 (and (not started) (setq started t)
26502 (org-start-icalendar-file org-icalendar-combined-name))
26503 (org-start-icalendar-file category))
26504 (org-print-icalendar-entries combine)
26505 (when (or (and combine (not files)) (not combine))
26506 (org-finish-icalendar-file)
26507 (set-buffer ical-buffer)
26508 (save-buffer)
26509 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26510 (org-release-buffers org-agenda-new-buffers))))
26512 (defvar org-after-save-iCalendar-file-hook nil
26513 "Hook run after an iCalendar file has been saved.
26514 The iCalendar buffer is still current when this hook is run.
26515 A good way to use this is to tell a desktop calenndar application to re-read
26516 the iCalendar file.")
26518 (defun org-print-icalendar-entries (&optional combine)
26519 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26520 When COMBINE is non nil, add the category to each line."
26521 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26522 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26523 (dts (org-ical-ts-to-string
26524 (format-time-string (cdr org-time-stamp-formats) (current-time))
26525 "DTSTART"))
26526 hd ts ts2 state status (inc t) pos b sexp rrule
26527 scheduledp deadlinep tmp pri category entry location summary desc
26528 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26529 (org-refresh-category-properties)
26530 (save-excursion
26531 (goto-char (point-min))
26532 (while (re-search-forward re1 nil t)
26533 (catch :skip
26534 (org-agenda-skip)
26535 (setq pos (match-beginning 0)
26536 ts (match-string 0)
26537 inc t
26538 hd (org-get-heading)
26539 summary (org-icalendar-cleanup-string
26540 (org-entry-get nil "SUMMARY"))
26541 desc (org-icalendar-cleanup-string
26542 (or (org-entry-get nil "DESCRIPTION")
26543 (and org-icalendar-include-body (org-get-entry)))
26544 t org-icalendar-include-body)
26545 location (org-icalendar-cleanup-string
26546 (org-entry-get nil "LOCATION"))
26547 category (org-get-category))
26548 (if (looking-at re2)
26549 (progn
26550 (goto-char (match-end 0))
26551 (setq ts2 (match-string 1) inc nil))
26552 (setq tmp (buffer-substring (max (point-min)
26553 (- pos org-ds-keyword-length))
26554 pos)
26555 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26556 (progn
26557 (setq inc nil)
26558 (replace-match "\\1" t nil ts))
26560 deadlinep (string-match org-deadline-regexp tmp)
26561 scheduledp (string-match org-scheduled-regexp tmp)
26562 ;; donep (org-entry-is-done-p)
26564 (if (or (string-match org-tr-regexp hd)
26565 (string-match org-ts-regexp hd))
26566 (setq hd (replace-match "" t t hd)))
26567 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26568 (setq rrule
26569 (concat "\nRRULE:FREQ="
26570 (cdr (assoc
26571 (match-string 2 ts)
26572 '(("d" . "DAILY")("w" . "WEEKLY")
26573 ("m" . "MONTHLY")("y" . "YEARLY"))))
26574 ";INTERVAL=" (match-string 1 ts)))
26575 (setq rrule ""))
26576 (setq summary (or summary hd))
26577 (if (string-match org-bracket-link-regexp summary)
26578 (setq summary
26579 (replace-match (if (match-end 3)
26580 (match-string 3 summary)
26581 (match-string 1 summary))
26582 t t summary)))
26583 (if deadlinep (setq summary (concat "DL: " summary)))
26584 (if scheduledp (setq summary (concat "S: " summary)))
26585 (if (string-match "\\`<%%" ts)
26586 (with-current-buffer sexp-buffer
26587 (insert (substring ts 1 -1) " " summary "\n"))
26588 (princ (format "BEGIN:VEVENT
26590 %s%s
26591 SUMMARY:%s%s%s
26592 CATEGORIES:%s
26593 END:VEVENT\n"
26594 (org-ical-ts-to-string ts "DTSTART")
26595 (org-ical-ts-to-string ts2 "DTEND" inc)
26596 rrule summary
26597 (if (and desc (string-match "\\S-" desc))
26598 (concat "\nDESCRIPTION: " desc) "")
26599 (if (and location (string-match "\\S-" location))
26600 (concat "\nLOCATION: " location) "")
26601 category)))))
26603 (when (and org-icalendar-include-sexps
26604 (condition-case nil (require 'icalendar) (error nil))
26605 (fboundp 'icalendar-export-region))
26606 ;; Get all the literal sexps
26607 (goto-char (point-min))
26608 (while (re-search-forward "^&?%%(" nil t)
26609 (catch :skip
26610 (org-agenda-skip)
26611 (setq b (match-beginning 0))
26612 (goto-char (1- (match-end 0)))
26613 (forward-sexp 1)
26614 (end-of-line 1)
26615 (setq sexp (buffer-substring b (point)))
26616 (with-current-buffer sexp-buffer
26617 (insert sexp "\n"))
26618 (princ (org-diary-to-ical-string sexp-buffer)))))
26620 (when org-icalendar-include-todo
26621 (goto-char (point-min))
26622 (while (re-search-forward org-todo-line-regexp nil t)
26623 (catch :skip
26624 (org-agenda-skip)
26625 (setq state (match-string 2))
26626 (setq status (if (member state org-done-keywords)
26627 "COMPLETED" "NEEDS-ACTION"))
26628 (when (and state
26629 (or (not (member state org-done-keywords))
26630 (eq org-icalendar-include-todo 'all))
26631 (not (member org-archive-tag (org-get-tags-at)))
26633 (setq hd (match-string 3)
26634 summary (org-icalendar-cleanup-string
26635 (org-entry-get nil "SUMMARY"))
26636 desc (org-icalendar-cleanup-string
26637 (or (org-entry-get nil "DESCRIPTION")
26638 (and org-icalendar-include-body (org-get-entry)))
26639 t org-icalendar-include-body)
26640 location (org-icalendar-cleanup-string
26641 (org-entry-get nil "LOCATION")))
26642 (if (string-match org-bracket-link-regexp hd)
26643 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26644 (match-string 1 hd))
26645 t t hd)))
26646 (if (string-match org-priority-regexp hd)
26647 (setq pri (string-to-char (match-string 2 hd))
26648 hd (concat (substring hd 0 (match-beginning 1))
26649 (substring hd (match-end 1))))
26650 (setq pri org-default-priority))
26651 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26652 (- org-lowest-priority org-highest-priority))))))
26654 (princ (format "BEGIN:VTODO
26656 SUMMARY:%s%s%s
26657 CATEGORIES:%s
26658 SEQUENCE:1
26659 PRIORITY:%d
26660 STATUS:%s
26661 END:VTODO\n"
26663 (or summary hd)
26664 (if (and location (string-match "\\S-" location))
26665 (concat "\nLOCATION: " location) "")
26666 (if (and desc (string-match "\\S-" desc))
26667 (concat "\nDESCRIPTION: " desc) "")
26668 category pri status)))))))))
26670 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26671 "Take out stuff and quote what needs to be quoted.
26672 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26673 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26674 characters."
26675 (if (not s)
26677 (when is-body
26678 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26679 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26680 (while (string-match re s) (setq s (replace-match "" t t s)))
26681 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26682 (let ((start 0))
26683 (while (string-match "\\([,;\\]\\)" s start)
26684 (setq start (+ (match-beginning 0) 2)
26685 s (replace-match "\\\\\\1" nil nil s))))
26686 (when is-body
26687 (while (string-match "[ \t]*\n[ \t]*" s)
26688 (setq s (replace-match "\\n" t t s))))
26689 (setq s (org-trim s))
26690 (if is-body
26691 (if maxlength
26692 (if (and (numberp maxlength)
26693 (> (length s) maxlength))
26694 (setq s (substring s 0 maxlength)))))
26697 (defun org-get-entry ()
26698 "Clean-up description string."
26699 (save-excursion
26700 (org-back-to-heading t)
26701 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26703 (defun org-start-icalendar-file (name)
26704 "Start an iCalendar file by inserting the header."
26705 (let ((user user-full-name)
26706 (name (or name "unknown"))
26707 (timezone (cadr (current-time-zone))))
26708 (princ
26709 (format "BEGIN:VCALENDAR
26710 VERSION:2.0
26711 X-WR-CALNAME:%s
26712 PRODID:-//%s//Emacs with Org-mode//EN
26713 X-WR-TIMEZONE:%s
26714 CALSCALE:GREGORIAN\n" name user timezone))))
26716 (defun org-finish-icalendar-file ()
26717 "Finish an iCalendar file by inserting the END statement."
26718 (princ "END:VCALENDAR\n"))
26720 (defun org-ical-ts-to-string (s keyword &optional inc)
26721 "Take a time string S and convert it to iCalendar format.
26722 KEYWORD is added in front, to make a complete line like DTSTART....
26723 When INC is non-nil, increase the hour by two (if time string contains
26724 a time), or the day by one (if it does not contain a time)."
26725 (let ((t1 (org-parse-time-string s 'nodefault))
26726 t2 fmt have-time time)
26727 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26728 (setq t2 t1 have-time t)
26729 (setq t2 (org-parse-time-string s)))
26730 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26731 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26732 (when inc
26733 (if have-time
26734 (if org-agenda-default-appointment-duration
26735 (setq mi (+ org-agenda-default-appointment-duration mi))
26736 (setq h (+ 2 h)))
26737 (setq d (1+ d))))
26738 (setq time (encode-time s mi h d m y)))
26739 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26740 (concat keyword (format-time-string fmt time))))
26742 ;;; XOXO export
26744 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26745 (with-current-buffer buffer
26746 (apply 'insert output)))
26747 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26749 (defun org-export-as-xoxo (&optional buffer)
26750 "Export the org buffer as XOXO.
26751 The XOXO buffer is named *xoxo-<source buffer name>*"
26752 (interactive (list (current-buffer)))
26753 ;; A quickie abstraction
26755 ;; Output everything as XOXO
26756 (with-current-buffer (get-buffer buffer)
26757 (let* ((pos (point))
26758 (opt-plist (org-combine-plists (org-default-export-plist)
26759 (org-infile-export-plist)))
26760 (filename (concat (file-name-as-directory
26761 (org-export-directory :xoxo opt-plist))
26762 (file-name-sans-extension
26763 (file-name-nondirectory buffer-file-name))
26764 ".html"))
26765 (out (find-file-noselect filename))
26766 (last-level 1)
26767 (hanging-li nil))
26768 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26769 ;; Check the output buffer is empty.
26770 (with-current-buffer out (erase-buffer))
26771 ;; Kick off the output
26772 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26773 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26774 (let* ((hd (match-string-no-properties 1))
26775 (level (length hd))
26776 (text (concat
26777 (match-string-no-properties 2)
26778 (save-excursion
26779 (goto-char (match-end 0))
26780 (let ((str ""))
26781 (catch 'loop
26782 (while 't
26783 (forward-line)
26784 (if (looking-at "^[ \t]\\(.*\\)")
26785 (setq str (concat str (match-string-no-properties 1)))
26786 (throw 'loop str)))))))))
26788 ;; Handle level rendering
26789 (cond
26790 ((> level last-level)
26791 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26793 ((< level last-level)
26794 (dotimes (- (- last-level level) 1)
26795 (if hanging-li
26796 (org-export-as-xoxo-insert-into out "</li>\n"))
26797 (org-export-as-xoxo-insert-into out "</ol>\n"))
26798 (when hanging-li
26799 (org-export-as-xoxo-insert-into out "</li>\n")
26800 (setq hanging-li nil)))
26802 ((equal level last-level)
26803 (if hanging-li
26804 (org-export-as-xoxo-insert-into out "</li>\n")))
26807 (setq last-level level)
26809 ;; And output the new li
26810 (setq hanging-li 't)
26811 (if (equal ?+ (elt text 0))
26812 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26813 (org-export-as-xoxo-insert-into out "<li>" text))))
26815 ;; Finally finish off the ol
26816 (dotimes (- last-level 1)
26817 (if hanging-li
26818 (org-export-as-xoxo-insert-into out "</li>\n"))
26819 (org-export-as-xoxo-insert-into out "</ol>\n"))
26821 (goto-char pos)
26822 ;; Finish the buffer off and clean it up.
26823 (switch-to-buffer-other-window out)
26824 (indent-region (point-min) (point-max) nil)
26825 (save-buffer)
26826 (goto-char (point-min))
26830 ;;;; Key bindings
26832 ;; Make `C-c C-x' a prefix key
26833 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26835 ;; TAB key with modifiers
26836 (org-defkey org-mode-map "\C-i" 'org-cycle)
26837 (org-defkey org-mode-map [(tab)] 'org-cycle)
26838 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26839 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26840 (org-defkey org-mode-map "\M-\t" 'org-complete)
26841 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26842 ;; The following line is necessary under Suse GNU/Linux
26843 (unless (featurep 'xemacs)
26844 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26845 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26846 (define-key org-mode-map [backtab] 'org-shifttab)
26848 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26849 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26850 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26852 ;; Cursor keys with modifiers
26853 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26854 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26855 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26856 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26858 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26859 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26860 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26861 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26863 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26864 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26865 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26866 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26868 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26869 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26871 ;;; Extra keys for tty access.
26872 ;; We only set them when really needed because otherwise the
26873 ;; menus don't show the simple keys
26875 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26876 (not window-system))
26877 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26878 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26879 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26880 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26881 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26882 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26883 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26884 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26885 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26886 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26887 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26888 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26889 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26890 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26891 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26892 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26893 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26894 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26895 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26896 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26897 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26898 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26900 ;; All the other keys
26902 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26903 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26904 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26905 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26906 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26907 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26908 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26909 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26910 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26911 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26912 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26913 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26914 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26915 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26916 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26917 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26918 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26919 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26920 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26921 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26922 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26923 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26924 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26925 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26926 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26927 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26928 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26929 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26930 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26931 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26932 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26933 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26934 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26935 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26936 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26937 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26938 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26939 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26940 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26941 (org-defkey org-mode-map "\C-c^" 'org-sort)
26942 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26943 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26944 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26945 (org-defkey org-mode-map "\C-m" 'org-return)
26946 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26947 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26948 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26949 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26950 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26951 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26952 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26953 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26954 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26955 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26956 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26957 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26958 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26959 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26960 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26961 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26962 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26964 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26965 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26966 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26967 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26969 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26970 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26971 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26972 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26973 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26974 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26975 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26976 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26977 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26978 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26979 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26980 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26982 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26984 (when (featurep 'xemacs)
26985 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26987 (defsubst org-table-p () (org-at-table-p))
26989 (defun org-self-insert-command (N)
26990 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26991 If the cursor is in a table looking at whitespace, the whitespace is
26992 overwritten, and the table is not marked as requiring realignment."
26993 (interactive "p")
26994 (if (and (org-table-p)
26995 (progn
26996 ;; check if we blank the field, and if that triggers align
26997 (and org-table-auto-blank-field
26998 (member last-command
26999 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27000 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27001 ;; got extra space, this field does not determine column width
27002 (let (org-table-may-need-update) (org-table-blank-field))
27003 ;; no extra space, this field may determine column width
27004 (org-table-blank-field)))
27006 (eq N 1)
27007 (looking-at "[^|\n]* |"))
27008 (let (org-table-may-need-update)
27009 (goto-char (1- (match-end 0)))
27010 (delete-backward-char 1)
27011 (goto-char (match-beginning 0))
27012 (self-insert-command N))
27013 (setq org-table-may-need-update t)
27014 (self-insert-command N)
27015 (org-fix-tags-on-the-fly)))
27017 (defun org-fix-tags-on-the-fly ()
27018 (when (and (equal (char-after (point-at-bol)) ?*)
27019 (org-on-heading-p))
27020 (org-align-tags-here org-tags-column)))
27022 (defun org-delete-backward-char (N)
27023 "Like `delete-backward-char', insert whitespace at field end in tables.
27024 When deleting backwards, in tables this function will insert whitespace in
27025 front of the next \"|\" separator, to keep the table aligned. The table will
27026 still be marked for re-alignment if the field did fill the entire column,
27027 because, in this case the deletion might narrow the column."
27028 (interactive "p")
27029 (if (and (org-table-p)
27030 (eq N 1)
27031 (string-match "|" (buffer-substring (point-at-bol) (point)))
27032 (looking-at ".*?|"))
27033 (let ((pos (point))
27034 (noalign (looking-at "[^|\n\r]* |"))
27035 (c org-table-may-need-update))
27036 (backward-delete-char N)
27037 (skip-chars-forward "^|")
27038 (insert " ")
27039 (goto-char (1- pos))
27040 ;; noalign: if there were two spaces at the end, this field
27041 ;; does not determine the width of the column.
27042 (if noalign (setq org-table-may-need-update c)))
27043 (backward-delete-char N)
27044 (org-fix-tags-on-the-fly)))
27046 (defun org-delete-char (N)
27047 "Like `delete-char', but insert whitespace at field end in tables.
27048 When deleting characters, in tables this function will insert whitespace in
27049 front of the next \"|\" separator, to keep the table aligned. The table will
27050 still be marked for re-alignment if the field did fill the entire column,
27051 because, in this case the deletion might narrow the column."
27052 (interactive "p")
27053 (if (and (org-table-p)
27054 (not (bolp))
27055 (not (= (char-after) ?|))
27056 (eq N 1))
27057 (if (looking-at ".*?|")
27058 (let ((pos (point))
27059 (noalign (looking-at "[^|\n\r]* |"))
27060 (c org-table-may-need-update))
27061 (replace-match (concat
27062 (substring (match-string 0) 1 -1)
27063 " |"))
27064 (goto-char pos)
27065 ;; noalign: if there were two spaces at the end, this field
27066 ;; does not determine the width of the column.
27067 (if noalign (setq org-table-may-need-update c)))
27068 (delete-char N))
27069 (delete-char N)
27070 (org-fix-tags-on-the-fly)))
27072 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27073 (put 'org-self-insert-command 'delete-selection t)
27074 (put 'orgtbl-self-insert-command 'delete-selection t)
27075 (put 'org-delete-char 'delete-selection 'supersede)
27076 (put 'org-delete-backward-char 'delete-selection 'supersede)
27078 ;; Make `flyspell-mode' delay after some commands
27079 (put 'org-self-insert-command 'flyspell-delayed t)
27080 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27081 (put 'org-delete-char 'flyspell-delayed t)
27082 (put 'org-delete-backward-char 'flyspell-delayed t)
27084 ;; Make pabbrev-mode expand after org-mode commands
27085 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27086 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27088 ;; How to do this: Measure non-white length of current string
27089 ;; If equal to column width, we should realign.
27091 (defun org-remap (map &rest commands)
27092 "In MAP, remap the functions given in COMMANDS.
27093 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27094 (let (new old)
27095 (while commands
27096 (setq old (pop commands) new (pop commands))
27097 (if (fboundp 'command-remapping)
27098 (org-defkey map (vector 'remap old) new)
27099 (substitute-key-definition old new map global-map)))))
27101 (when (eq org-enable-table-editor 'optimized)
27102 ;; If the user wants maximum table support, we need to hijack
27103 ;; some standard editing functions
27104 (org-remap org-mode-map
27105 'self-insert-command 'org-self-insert-command
27106 'delete-char 'org-delete-char
27107 'delete-backward-char 'org-delete-backward-char)
27108 (org-defkey org-mode-map "|" 'org-force-self-insert))
27110 (defun org-shiftcursor-error ()
27111 "Throw an error because Shift-Cursor command was applied in wrong context."
27112 (error "This command is active in special context like tables, headlines or timestamps"))
27114 (defun org-shifttab (&optional arg)
27115 "Global visibility cycling or move to previous table field.
27116 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27117 on context.
27118 See the individual commands for more information."
27119 (interactive "P")
27120 (cond
27121 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27122 (arg (message "Content view to level: ")
27123 (org-content (prefix-numeric-value arg))
27124 (setq org-cycle-global-status 'overview))
27125 (t (call-interactively 'org-global-cycle))))
27127 (defun org-shiftmetaleft ()
27128 "Promote subtree or delete table column.
27129 Calls `org-promote-subtree', `org-outdent-item',
27130 or `org-table-delete-column', depending on context.
27131 See the individual commands for more information."
27132 (interactive)
27133 (cond
27134 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27135 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27136 ((org-at-item-p) (call-interactively 'org-outdent-item))
27137 (t (org-shiftcursor-error))))
27139 (defun org-shiftmetaright ()
27140 "Demote subtree or insert table column.
27141 Calls `org-demote-subtree', `org-indent-item',
27142 or `org-table-insert-column', depending on context.
27143 See the individual commands for more information."
27144 (interactive)
27145 (cond
27146 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27147 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27148 ((org-at-item-p) (call-interactively 'org-indent-item))
27149 (t (org-shiftcursor-error))))
27151 (defun org-shiftmetaup (&optional arg)
27152 "Move subtree up or kill table row.
27153 Calls `org-move-subtree-up' or `org-table-kill-row' or
27154 `org-move-item-up' depending on context. See the individual commands
27155 for more information."
27156 (interactive "P")
27157 (cond
27158 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27159 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27160 ((org-at-item-p) (call-interactively 'org-move-item-up))
27161 (t (org-shiftcursor-error))))
27162 (defun org-shiftmetadown (&optional arg)
27163 "Move subtree down or insert table row.
27164 Calls `org-move-subtree-down' or `org-table-insert-row' or
27165 `org-move-item-down', depending on context. See the individual
27166 commands for more information."
27167 (interactive "P")
27168 (cond
27169 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27170 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27171 ((org-at-item-p) (call-interactively 'org-move-item-down))
27172 (t (org-shiftcursor-error))))
27174 (defun org-metaleft (&optional arg)
27175 "Promote heading or move table column to left.
27176 Calls `org-do-promote' or `org-table-move-column', depending on context.
27177 With no specific context, calls the Emacs default `backward-word'.
27178 See the individual commands for more information."
27179 (interactive "P")
27180 (cond
27181 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27182 ((or (org-on-heading-p) (org-region-active-p))
27183 (call-interactively 'org-do-promote))
27184 ((org-at-item-p) (call-interactively 'org-outdent-item))
27185 (t (call-interactively 'backward-word))))
27187 (defun org-metaright (&optional arg)
27188 "Demote subtree or move table column to right.
27189 Calls `org-do-demote' or `org-table-move-column', depending on context.
27190 With no specific context, calls the Emacs default `forward-word'.
27191 See the individual commands for more information."
27192 (interactive "P")
27193 (cond
27194 ((org-at-table-p) (call-interactively 'org-table-move-column))
27195 ((or (org-on-heading-p) (org-region-active-p))
27196 (call-interactively 'org-do-demote))
27197 ((org-at-item-p) (call-interactively 'org-indent-item))
27198 (t (call-interactively 'forward-word))))
27200 (defun org-metaup (&optional arg)
27201 "Move subtree up or move table row up.
27202 Calls `org-move-subtree-up' or `org-table-move-row' or
27203 `org-move-item-up', depending on context. See the individual commands
27204 for more information."
27205 (interactive "P")
27206 (cond
27207 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27208 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27209 ((org-at-item-p) (call-interactively 'org-move-item-up))
27210 (t (transpose-lines 1) (beginning-of-line -1))))
27212 (defun org-metadown (&optional arg)
27213 "Move subtree down or move table row down.
27214 Calls `org-move-subtree-down' or `org-table-move-row' or
27215 `org-move-item-down', depending on context. See the individual
27216 commands for more information."
27217 (interactive "P")
27218 (cond
27219 ((org-at-table-p) (call-interactively 'org-table-move-row))
27220 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27221 ((org-at-item-p) (call-interactively 'org-move-item-down))
27222 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27224 (defun org-shiftup (&optional arg)
27225 "Increase item in timestamp or increase priority of current headline.
27226 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27227 depending on context. See the individual commands for more information."
27228 (interactive "P")
27229 (cond
27230 ((org-at-timestamp-p t)
27231 (call-interactively (if org-edit-timestamp-down-means-later
27232 'org-timestamp-down 'org-timestamp-up)))
27233 ((org-on-heading-p) (call-interactively 'org-priority-up))
27234 ((org-at-item-p) (call-interactively 'org-previous-item))
27235 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27237 (defun org-shiftdown (&optional arg)
27238 "Decrease item in timestamp or decrease priority of current headline.
27239 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27240 depending on context. See the individual commands for more information."
27241 (interactive "P")
27242 (cond
27243 ((org-at-timestamp-p t)
27244 (call-interactively (if org-edit-timestamp-down-means-later
27245 'org-timestamp-up 'org-timestamp-down)))
27246 ((org-on-heading-p) (call-interactively 'org-priority-down))
27247 (t (call-interactively 'org-next-item))))
27249 (defun org-shiftright ()
27250 "Next TODO keyword or timestamp one day later, depending on context."
27251 (interactive)
27252 (cond
27253 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27254 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27255 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27256 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27257 (t (org-shiftcursor-error))))
27259 (defun org-shiftleft ()
27260 "Previous TODO keyword or timestamp one day earlier, depending on context."
27261 (interactive)
27262 (cond
27263 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27264 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27265 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27266 ((org-at-property-p)
27267 (call-interactively 'org-property-previous-allowed-value))
27268 (t (org-shiftcursor-error))))
27270 (defun org-shiftcontrolright ()
27271 "Switch to next TODO set."
27272 (interactive)
27273 (cond
27274 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27275 (t (org-shiftcursor-error))))
27277 (defun org-shiftcontrolleft ()
27278 "Switch to previous TODO set."
27279 (interactive)
27280 (cond
27281 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27282 (t (org-shiftcursor-error))))
27284 (defun org-ctrl-c-ret ()
27285 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27286 (interactive)
27287 (cond
27288 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27289 (t (call-interactively 'org-insert-heading))))
27291 (defun org-copy-special ()
27292 "Copy region in table or copy current subtree.
27293 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27294 See the individual commands for more information."
27295 (interactive)
27296 (call-interactively
27297 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27299 (defun org-cut-special ()
27300 "Cut region in table or cut current subtree.
27301 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27302 See the individual commands for more information."
27303 (interactive)
27304 (call-interactively
27305 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27307 (defun org-paste-special (arg)
27308 "Paste rectangular region into table, or past subtree relative to level.
27309 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27310 See the individual commands for more information."
27311 (interactive "P")
27312 (if (org-at-table-p)
27313 (org-table-paste-rectangle)
27314 (org-paste-subtree arg)))
27316 (defun org-ctrl-c-ctrl-c (&optional arg)
27317 "Set tags in headline, or update according to changed information at point.
27319 This command does many different things, depending on context:
27321 - If the cursor is in a headline, prompt for tags and insert them
27322 into the current line, aligned to `org-tags-column'. When called
27323 with prefix arg, realign all tags in the current buffer.
27325 - If the cursor is in one of the special #+KEYWORD lines, this
27326 triggers scanning the buffer for these lines and updating the
27327 information.
27329 - If the cursor is inside a table, realign the table. This command
27330 works even if the automatic table editor has been turned off.
27332 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27333 the entire table.
27335 - If the cursor is a the beginning of a dynamic block, update it.
27337 - If the cursor is inside a table created by the table.el package,
27338 activate that table.
27340 - If the current buffer is a remember buffer, close note and file it.
27341 with a prefix argument, file it without further interaction to the default
27342 location.
27344 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27345 links in this buffer.
27347 - If the cursor is on a numbered item in a plain list, renumber the
27348 ordered list.
27350 - If the cursor is on a checkbox, toggle it."
27351 (interactive "P")
27352 (let ((org-enable-table-editor t))
27353 (cond
27354 ((or org-clock-overlays
27355 org-occur-highlights
27356 org-latex-fragment-image-overlays)
27357 (org-remove-clock-overlays)
27358 (org-remove-occur-highlights)
27359 (org-remove-latex-fragment-image-overlays)
27360 (message "Temporary highlights/overlays removed from current buffer"))
27361 ((and (local-variable-p 'org-finish-function (current-buffer))
27362 (fboundp org-finish-function))
27363 (funcall org-finish-function))
27364 ((org-at-property-p)
27365 (call-interactively 'org-property-action))
27366 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27367 ((org-on-heading-p) (call-interactively 'org-set-tags))
27368 ((org-at-table.el-p)
27369 (require 'table)
27370 (beginning-of-line 1)
27371 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27372 (call-interactively 'table-recognize-table))
27373 ((org-at-table-p)
27374 (org-table-maybe-eval-formula)
27375 (if arg
27376 (call-interactively 'org-table-recalculate)
27377 (org-table-maybe-recalculate-line))
27378 (call-interactively 'org-table-align))
27379 ((org-at-item-checkbox-p)
27380 (call-interactively 'org-toggle-checkbox))
27381 ((org-at-item-p)
27382 (call-interactively 'org-maybe-renumber-ordered-list))
27383 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27384 ;; Dynamic block
27385 (beginning-of-line 1)
27386 (org-update-dblock))
27387 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27388 (cond
27389 ((equal (match-string 1) "TBLFM")
27390 ;; Recalculate the table before this line
27391 (save-excursion
27392 (beginning-of-line 1)
27393 (skip-chars-backward " \r\n\t")
27394 (if (org-at-table-p)
27395 (org-call-with-arg 'org-table-recalculate t))))
27397 (call-interactively 'org-mode-restart))))
27398 (t (error "C-c C-c can do nothing useful at this location.")))))
27400 (defun org-mode-restart ()
27401 "Restart Org-mode, to scan again for special lines.
27402 Also updates the keyword regular expressions."
27403 (interactive)
27404 (let ((org-inhibit-startup t)) (org-mode))
27405 (message "Org-mode restarted to refresh keyword and special line setup"))
27407 (defun org-kill-note-or-show-branches ()
27408 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27409 (interactive)
27410 (if (not org-finish-function)
27411 (call-interactively 'show-branches)
27412 (let ((org-note-abort t))
27413 (funcall org-finish-function))))
27415 (defun org-return (&optional indent)
27416 "Goto next table row or insert a newline.
27417 Calls `org-table-next-row' or `newline', depending on context.
27418 See the individual commands for more information."
27419 (interactive)
27420 (cond
27421 ((bobp) (if indent (newline-and-indent) (newline)))
27422 ((and (org-at-heading-p)
27423 (looking-at
27424 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27425 (org-show-entry)
27426 (end-of-line 1)
27427 (newline))
27428 ((org-at-table-p)
27429 (org-table-justify-field-maybe)
27430 (call-interactively 'org-table-next-row))
27431 (t (if indent (newline-and-indent) (newline)))))
27433 (defun org-return-indent ()
27434 (interactive)
27435 "Goto next table row or insert a newline and indent.
27436 Calls `org-table-next-row' or `newline-and-indent', depending on
27437 context. See the individual commands for more information."
27438 (org-return t))
27440 (defun org-ctrl-c-minus ()
27441 "Insert separator line in table or modify bullet type in list.
27442 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
27443 depending on context."
27444 (interactive)
27445 (cond
27446 ((org-at-table-p)
27447 (call-interactively 'org-table-insert-hline))
27448 ((org-on-heading-p)
27449 ;; Convert to item
27450 (save-excursion
27451 (beginning-of-line 1)
27452 (if (looking-at "\\*+ ")
27453 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27454 ((org-in-item-p)
27455 (call-interactively 'org-cycle-list-bullet))
27456 (t (error "`C-c -' does have no function here."))))
27458 (defun org-meta-return (&optional arg)
27459 "Insert a new heading or wrap a region in a table.
27460 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27461 See the individual commands for more information."
27462 (interactive "P")
27463 (cond
27464 ((org-at-table-p)
27465 (call-interactively 'org-table-wrap-region))
27466 (t (call-interactively 'org-insert-heading))))
27468 ;;; Menu entries
27470 ;; Define the Org-mode menus
27471 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27472 '("Tbl"
27473 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27474 ["Next Field" org-cycle (org-at-table-p)]
27475 ["Previous Field" org-shifttab (org-at-table-p)]
27476 ["Next Row" org-return (org-at-table-p)]
27477 "--"
27478 ["Blank Field" org-table-blank-field (org-at-table-p)]
27479 ["Edit Field" org-table-edit-field (org-at-table-p)]
27480 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27481 "--"
27482 ("Column"
27483 ["Move Column Left" org-metaleft (org-at-table-p)]
27484 ["Move Column Right" org-metaright (org-at-table-p)]
27485 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27486 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27487 ("Row"
27488 ["Move Row Up" org-metaup (org-at-table-p)]
27489 ["Move Row Down" org-metadown (org-at-table-p)]
27490 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27491 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27492 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27493 "--"
27494 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27495 ("Rectangle"
27496 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27497 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27498 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27499 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27500 "--"
27501 ("Calculate"
27502 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27503 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27504 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27505 "--"
27506 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27507 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27508 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27509 "--"
27510 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27511 "--"
27512 ["Sum Column/Rectangle" org-table-sum
27513 (or (org-at-table-p) (org-region-active-p))]
27514 ["Which Column?" org-table-current-column (org-at-table-p)])
27515 ["Debug Formulas"
27516 org-table-toggle-formula-debugger
27517 :style toggle :selected org-table-formula-debug]
27518 ["Show Col/Row Numbers"
27519 org-table-toggle-coordinate-overlays
27520 :style toggle :selected org-table-overlay-coordinates]
27521 "--"
27522 ["Create" org-table-create (and (not (org-at-table-p))
27523 org-enable-table-editor)]
27524 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27525 ["Import from File" org-table-import (not (org-at-table-p))]
27526 ["Export to File" org-table-export (org-at-table-p)]
27527 "--"
27528 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27530 (easy-menu-define org-org-menu org-mode-map "Org menu"
27531 '("Org"
27532 ("Show/Hide"
27533 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27534 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27535 ["Sparse Tree" org-occur t]
27536 ["Reveal Context" org-reveal t]
27537 ["Show All" show-all t]
27538 "--"
27539 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27540 "--"
27541 ["New Heading" org-insert-heading t]
27542 ("Navigate Headings"
27543 ["Up" outline-up-heading t]
27544 ["Next" outline-next-visible-heading t]
27545 ["Previous" outline-previous-visible-heading t]
27546 ["Next Same Level" outline-forward-same-level t]
27547 ["Previous Same Level" outline-backward-same-level t]
27548 "--"
27549 ["Jump" org-goto t])
27550 ("Edit Structure"
27551 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27552 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27553 "--"
27554 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27555 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27556 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27557 "--"
27558 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27559 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27560 ["Demote Heading" org-metaright (not (org-at-table-p))]
27561 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27562 "--"
27563 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27564 "--"
27565 ["Convert to odd levels" org-convert-to-odd-levels t]
27566 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27567 ("Editing"
27568 ["Emphasis..." org-emphasize t])
27569 ("Archive"
27570 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27571 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27572 ; :active t :keys "C-u C-c C-x C-a"]
27573 ["Sparse trees open ARCHIVE trees"
27574 (setq org-sparse-tree-open-archived-trees
27575 (not org-sparse-tree-open-archived-trees))
27576 :style toggle :selected org-sparse-tree-open-archived-trees]
27577 ["Cycling opens ARCHIVE trees"
27578 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27579 :style toggle :selected org-cycle-open-archived-trees]
27580 ["Agenda includes ARCHIVE trees"
27581 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27582 :style toggle :selected (not org-agenda-skip-archived-trees)]
27583 "--"
27584 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27585 ; ["Check and Move Children" (org-archive-subtree '(4))
27586 ; :active t :keys "C-u C-c C-x C-s"]
27588 "--"
27589 ("TODO Lists"
27590 ["TODO/DONE/-" org-todo t]
27591 ("Select keyword"
27592 ["Next keyword" org-shiftright (org-on-heading-p)]
27593 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27594 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27595 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27596 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27597 ["Show TODO Tree" org-show-todo-tree t]
27598 ["Global TODO list" org-todo-list t]
27599 "--"
27600 ["Set Priority" org-priority t]
27601 ["Priority Up" org-shiftup t]
27602 ["Priority Down" org-shiftdown t])
27603 ("TAGS and Properties"
27604 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27605 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27606 "--"
27607 ["Set property" 'org-set-property t]
27608 ["Column view of properties" org-columns t]
27609 ["Insert Column View DBlock" org-insert-columns-dblock t])
27610 ("Dates and Scheduling"
27611 ["Timestamp" org-time-stamp t]
27612 ["Timestamp (inactive)" org-time-stamp-inactive t]
27613 ("Change Date"
27614 ["1 Day Later" org-shiftright t]
27615 ["1 Day Earlier" org-shiftleft t]
27616 ["1 ... Later" org-shiftup t]
27617 ["1 ... Earlier" org-shiftdown t])
27618 ["Compute Time Range" org-evaluate-time-range t]
27619 ["Schedule Item" org-schedule t]
27620 ["Deadline" org-deadline t]
27621 "--"
27622 ["Custom time format" org-toggle-time-stamp-overlays
27623 :style radio :selected org-display-custom-times]
27624 "--"
27625 ["Goto Calendar" org-goto-calendar t]
27626 ["Date from Calendar" org-date-from-calendar t])
27627 ("Logging work"
27628 ["Clock in" org-clock-in t]
27629 ["Clock out" org-clock-out t]
27630 ["Clock cancel" org-clock-cancel t]
27631 ["Goto running clock" org-clock-goto t]
27632 ["Display times" org-clock-display t]
27633 ["Create clock table" org-clock-report t]
27634 "--"
27635 ["Record DONE time"
27636 (progn (setq org-log-done (not org-log-done))
27637 (message "Switching to %s will %s record a timestamp"
27638 (car org-done-keywords)
27639 (if org-log-done "automatically" "not")))
27640 :style toggle :selected org-log-done])
27641 "--"
27642 ["Agenda Command..." org-agenda t]
27643 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27644 ("File List for Agenda")
27645 ("Special views current file"
27646 ["TODO Tree" org-show-todo-tree t]
27647 ["Check Deadlines" org-check-deadlines t]
27648 ["Timeline" org-timeline t]
27649 ["Tags Tree" org-tags-sparse-tree t])
27650 "--"
27651 ("Hyperlinks"
27652 ["Store Link (Global)" org-store-link t]
27653 ["Insert Link" org-insert-link t]
27654 ["Follow Link" org-open-at-point t]
27655 "--"
27656 ["Next link" org-next-link t]
27657 ["Previous link" org-previous-link t]
27658 "--"
27659 ["Descriptive Links"
27660 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27661 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27662 ["Literal Links"
27663 (progn
27664 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27665 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27666 "--"
27667 ["Export/Publish..." org-export t]
27668 ("LaTeX"
27669 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27670 :selected org-cdlatex-mode]
27671 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27672 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27673 ["Modify math symbol" org-cdlatex-math-modify
27674 (org-inside-LaTeX-fragment-p)]
27675 ["Export LaTeX fragments as images"
27676 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27677 :style toggle :selected org-export-with-LaTeX-fragments])
27678 "--"
27679 ("Documentation"
27680 ["Show Version" org-version t]
27681 ["Info Documentation" org-info t])
27682 ("Customize"
27683 ["Browse Org Group" org-customize t]
27684 "--"
27685 ["Expand This Menu" org-create-customize-menu
27686 (fboundp 'customize-menu-create)])
27687 "--"
27688 ["Refresh setup" org-mode-restart t]
27691 (defun org-info (&optional node)
27692 "Read documentation for Org-mode in the info system.
27693 With optional NODE, go directly to that node."
27694 (interactive)
27695 (require 'info)
27696 (info (format "(org)%s" (or node ""))))
27698 (defun org-install-agenda-files-menu ()
27699 (let ((bl (buffer-list)))
27700 (save-excursion
27701 (while bl
27702 (set-buffer (pop bl))
27703 (if (org-mode-p) (setq bl nil)))
27704 (when (org-mode-p)
27705 (easy-menu-change
27706 '("Org") "File List for Agenda"
27707 (append
27708 (list
27709 ["Edit File List" (org-edit-agenda-file-list) t]
27710 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27711 ["Remove Current File from List" org-remove-file t]
27712 ["Cycle through agenda files" org-cycle-agenda-files t]
27713 ["Occur in all agenda files" org-occur-in-agenda-files t]
27714 "--")
27715 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27717 ;;;; Documentation
27719 (defun org-customize ()
27720 "Call the customize function with org as argument."
27721 (interactive)
27722 (customize-browse 'org))
27724 (defun org-create-customize-menu ()
27725 "Create a full customization menu for Org-mode, insert it into the menu."
27726 (interactive)
27727 (if (fboundp 'customize-menu-create)
27728 (progn
27729 (easy-menu-change
27730 '("Org") "Customize"
27731 `(["Browse Org group" org-customize t]
27732 "--"
27733 ,(customize-menu-create 'org)
27734 ["Set" Custom-set t]
27735 ["Save" Custom-save t]
27736 ["Reset to Current" Custom-reset-current t]
27737 ["Reset to Saved" Custom-reset-saved t]
27738 ["Reset to Standard Settings" Custom-reset-standard t]))
27739 (message "\"Org\"-menu now contains full customization menu"))
27740 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27742 ;;;; Miscellaneous stuff
27745 ;;; Generally useful functions
27747 (defun org-context ()
27748 "Return a list of contexts of the current cursor position.
27749 If several contexts apply, all are returned.
27750 Each context entry is a list with a symbol naming the context, and
27751 two positions indicating start and end of the context. Possible
27752 contexts are:
27754 :headline anywhere in a headline
27755 :headline-stars on the leading stars in a headline
27756 :todo-keyword on a TODO keyword (including DONE) in a headline
27757 :tags on the TAGS in a headline
27758 :priority on the priority cookie in a headline
27759 :item on the first line of a plain list item
27760 :item-bullet on the bullet/number of a plain list item
27761 :checkbox on the checkbox in a plain list item
27762 :table in an org-mode table
27763 :table-special on a special filed in a table
27764 :table-table in a table.el table
27765 :link on a hyperlink
27766 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27767 :target on a <<target>>
27768 :radio-target on a <<<radio-target>>>
27769 :latex-fragment on a LaTeX fragment
27770 :latex-preview on a LaTeX fragment with overlayed preview image
27772 This function expects the position to be visible because it uses font-lock
27773 faces as a help to recognize the following contexts: :table-special, :link,
27774 and :keyword."
27775 (let* ((f (get-text-property (point) 'face))
27776 (faces (if (listp f) f (list f)))
27777 (p (point)) clist o)
27778 ;; First the large context
27779 (cond
27780 ((org-on-heading-p t)
27781 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27782 (when (progn
27783 (beginning-of-line 1)
27784 (looking-at org-todo-line-tags-regexp))
27785 (push (org-point-in-group p 1 :headline-stars) clist)
27786 (push (org-point-in-group p 2 :todo-keyword) clist)
27787 (push (org-point-in-group p 4 :tags) clist))
27788 (goto-char p)
27789 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27790 (if (looking-at "\\[#[A-Z0-9]\\]")
27791 (push (org-point-in-group p 0 :priority) clist)))
27793 ((org-at-item-p)
27794 (push (org-point-in-group p 2 :item-bullet) clist)
27795 (push (list :item (point-at-bol)
27796 (save-excursion (org-end-of-item) (point)))
27797 clist)
27798 (and (org-at-item-checkbox-p)
27799 (push (org-point-in-group p 0 :checkbox) clist)))
27801 ((org-at-table-p)
27802 (push (list :table (org-table-begin) (org-table-end)) clist)
27803 (if (memq 'org-formula faces)
27804 (push (list :table-special
27805 (previous-single-property-change p 'face)
27806 (next-single-property-change p 'face)) clist)))
27807 ((org-at-table-p 'any)
27808 (push (list :table-table) clist)))
27809 (goto-char p)
27811 ;; Now the small context
27812 (cond
27813 ((org-at-timestamp-p)
27814 (push (org-point-in-group p 0 :timestamp) clist))
27815 ((memq 'org-link faces)
27816 (push (list :link
27817 (previous-single-property-change p 'face)
27818 (next-single-property-change p 'face)) clist))
27819 ((memq 'org-special-keyword faces)
27820 (push (list :keyword
27821 (previous-single-property-change p 'face)
27822 (next-single-property-change p 'face)) clist))
27823 ((org-on-target-p)
27824 (push (org-point-in-group p 0 :target) clist)
27825 (goto-char (1- (match-beginning 0)))
27826 (if (looking-at org-radio-target-regexp)
27827 (push (org-point-in-group p 0 :radio-target) clist))
27828 (goto-char p))
27829 ((setq o (car (delq nil
27830 (mapcar
27831 (lambda (x)
27832 (if (memq x org-latex-fragment-image-overlays) x))
27833 (org-overlays-at (point))))))
27834 (push (list :latex-fragment
27835 (org-overlay-start o) (org-overlay-end o)) clist)
27836 (push (list :latex-preview
27837 (org-overlay-start o) (org-overlay-end o)) clist))
27838 ((org-inside-LaTeX-fragment-p)
27839 ;; FIXME: positions wrong.
27840 (push (list :latex-fragment (point) (point)) clist)))
27842 (setq clist (nreverse (delq nil clist)))
27843 clist))
27845 ;; FIXME: Compare with at-regexp-p Do we need both?
27846 (defun org-in-regexp (re &optional nlines visually)
27847 "Check if point is inside a match of regexp.
27848 Normally only the current line is checked, but you can include NLINES extra
27849 lines both before and after point into the search.
27850 If VISUALLY is set, require that the cursor is not after the match but
27851 really on, so that the block visually is on the match."
27852 (catch 'exit
27853 (let ((pos (point))
27854 (eol (point-at-eol (+ 1 (or nlines 0))))
27855 (inc (if visually 1 0)))
27856 (save-excursion
27857 (beginning-of-line (- 1 (or nlines 0)))
27858 (while (re-search-forward re eol t)
27859 (if (and (<= (match-beginning 0) pos)
27860 (>= (+ inc (match-end 0)) pos))
27861 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27863 (defun org-at-regexp-p (regexp)
27864 "Is point inside a match of REGEXP in the current line?"
27865 (catch 'exit
27866 (save-excursion
27867 (let ((pos (point)) (end (point-at-eol)))
27868 (beginning-of-line 1)
27869 (while (re-search-forward regexp end t)
27870 (if (and (<= (match-beginning 0) pos)
27871 (>= (match-end 0) pos))
27872 (throw 'exit t)))
27873 nil))))
27875 (defun org-occur-in-agenda-files (regexp &optional nlines)
27876 "Call `multi-occur' with buffers for all agenda files."
27877 (interactive "sOrg-files matching: \np")
27878 (let* ((files (org-agenda-files))
27879 (tnames (mapcar 'file-truename files))
27880 (extra org-agenda-text-search-extra-files)
27882 (while (setq f (pop extra))
27883 (unless (member (file-truename f) tnames)
27884 (add-to-list 'files f 'append)
27885 (add-to-list 'tnames (file-truename f) 'append)))
27886 (multi-occur
27887 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27888 regexp)))
27890 (if (boundp 'occur-mode-find-occurrence-hook)
27891 ;; Emacs 23
27892 (add-hook 'occur-mode-find-occurrence-hook
27893 (lambda ()
27894 (when (org-mode-p)
27895 (org-reveal))))
27896 ;; Emacs 22
27897 (defadvice occur-mode-goto-occurrence
27898 (after org-occur-reveal activate)
27899 (and (org-mode-p) (org-reveal)))
27900 (defadvice occur-mode-goto-occurrence-other-window
27901 (after org-occur-reveal activate)
27902 (and (org-mode-p) (org-reveal)))
27903 (defadvice occur-mode-display-occurrence
27904 (after org-occur-reveal activate)
27905 (when (org-mode-p)
27906 (let ((pos (occur-mode-find-occurrence)))
27907 (with-current-buffer (marker-buffer pos)
27908 (save-excursion
27909 (goto-char pos)
27910 (org-reveal)))))))
27912 (defun org-uniquify (list)
27913 "Remove duplicate elements from LIST."
27914 (let (res)
27915 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27916 res))
27918 (defun org-delete-all (elts list)
27919 "Remove all elements in ELTS from LIST."
27920 (while elts
27921 (setq list (delete (pop elts) list)))
27922 list)
27924 (defun org-back-over-empty-lines ()
27925 "Move backwards over witespace, to the beginning of the first empty line.
27926 Returns the number o empty lines passed."
27927 (let ((pos (point)))
27928 (skip-chars-backward " \t\n\r")
27929 (beginning-of-line 2)
27930 (goto-char (min (point) pos))
27931 (count-lines (point) pos)))
27933 (defun org-skip-whitespace ()
27934 (skip-chars-forward " \t\n\r"))
27936 (defun org-point-in-group (point group &optional context)
27937 "Check if POINT is in match-group GROUP.
27938 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27939 match. If the match group does ot exist or point is not inside it,
27940 return nil."
27941 (and (match-beginning group)
27942 (>= point (match-beginning group))
27943 (<= point (match-end group))
27944 (if context
27945 (list context (match-beginning group) (match-end group))
27946 t)))
27948 (defun org-switch-to-buffer-other-window (&rest args)
27949 "Switch to buffer in a second window on the current frame.
27950 In particular, do not allow pop-up frames."
27951 (let (pop-up-frames special-display-buffer-names special-display-regexps
27952 special-display-function)
27953 (apply 'switch-to-buffer-other-window args)))
27955 (defun org-combine-plists (&rest plists)
27956 "Create a single property list from all plists in PLISTS.
27957 The process starts by copying the first list, and then setting properties
27958 from the other lists. Settings in the last list are the most significant
27959 ones and overrule settings in the other lists."
27960 (let ((rtn (copy-sequence (pop plists)))
27961 p v ls)
27962 (while plists
27963 (setq ls (pop plists))
27964 (while ls
27965 (setq p (pop ls) v (pop ls))
27966 (setq rtn (plist-put rtn p v))))
27967 rtn))
27969 (defun org-move-line-down (arg)
27970 "Move the current line down. With prefix argument, move it past ARG lines."
27971 (interactive "p")
27972 (let ((col (current-column))
27973 beg end pos)
27974 (beginning-of-line 1) (setq beg (point))
27975 (beginning-of-line 2) (setq end (point))
27976 (beginning-of-line (+ 1 arg))
27977 (setq pos (move-marker (make-marker) (point)))
27978 (insert (delete-and-extract-region beg end))
27979 (goto-char pos)
27980 (move-to-column col)))
27982 (defun org-move-line-up (arg)
27983 "Move the current line up. With prefix argument, move it past ARG lines."
27984 (interactive "p")
27985 (let ((col (current-column))
27986 beg end pos)
27987 (beginning-of-line 1) (setq beg (point))
27988 (beginning-of-line 2) (setq end (point))
27989 (beginning-of-line (- arg))
27990 (setq pos (move-marker (make-marker) (point)))
27991 (insert (delete-and-extract-region beg end))
27992 (goto-char pos)
27993 (move-to-column col)))
27995 (defun org-replace-escapes (string table)
27996 "Replace %-escapes in STRING with values in TABLE.
27997 TABLE is an association list with keys like \"%a\" and string values.
27998 The sequences in STRING may contain normal field width and padding information,
27999 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28000 so values can contain further %-escapes if they are define later in TABLE."
28001 (let ((case-fold-search nil)
28002 e re rpl)
28003 (while (setq e (pop table))
28004 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28005 (while (string-match re string)
28006 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28007 (cdr e)))
28008 (setq string (replace-match rpl t t string))))
28009 string))
28012 (defun org-sublist (list start end)
28013 "Return a section of LIST, from START to END.
28014 Counting starts at 1."
28015 (let (rtn (c start))
28016 (setq list (nthcdr (1- start) list))
28017 (while (and list (<= c end))
28018 (push (pop list) rtn)
28019 (setq c (1+ c)))
28020 (nreverse rtn)))
28022 (defun org-find-base-buffer-visiting (file)
28023 "Like `find-buffer-visiting' but alway return the base buffer and
28024 not an indirect buffer"
28025 (let ((buf (find-buffer-visiting file)))
28026 (if buf
28027 (or (buffer-base-buffer buf) buf)
28028 nil)))
28030 (defun org-image-file-name-regexp ()
28031 "Return regexp matching the file names of images."
28032 (if (fboundp 'image-file-name-regexp)
28033 (image-file-name-regexp)
28034 (let ((image-file-name-extensions
28035 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28036 "xbm" "xpm" "pbm" "pgm" "ppm")))
28037 (concat "\\."
28038 (regexp-opt (nconc (mapcar 'upcase
28039 image-file-name-extensions)
28040 image-file-name-extensions)
28042 "\\'"))))
28044 (defun org-file-image-p (file)
28045 "Return non-nil if FILE is an image."
28046 (save-match-data
28047 (string-match (org-image-file-name-regexp) file)))
28049 ;;; Paragraph filling stuff.
28050 ;; We want this to be just right, so use the full arsenal.
28052 (defun org-indent-line-function ()
28053 "Indent line like previous, but further if previous was headline or item."
28054 (interactive)
28055 (let* ((pos (point))
28056 (itemp (org-at-item-p))
28057 column bpos bcol tpos tcol bullet btype bullet-type)
28058 ;; Find the previous relevant line
28059 (beginning-of-line 1)
28060 (cond
28061 ((looking-at "#") (setq column 0))
28062 ((looking-at "\\*+ ") (setq column 0))
28064 (beginning-of-line 0)
28065 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28066 (beginning-of-line 0))
28067 (cond
28068 ((looking-at "\\*+[ \t]+")
28069 (goto-char (match-end 0))
28070 (setq column (current-column)))
28071 ((org-in-item-p)
28072 (org-beginning-of-item)
28073 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28074 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28075 (setq bpos (match-beginning 1) tpos (match-end 0)
28076 bcol (progn (goto-char bpos) (current-column))
28077 tcol (progn (goto-char tpos) (current-column))
28078 bullet (match-string 1)
28079 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28080 (if (not itemp)
28081 (setq column tcol)
28082 (goto-char pos)
28083 (beginning-of-line 1)
28084 (if (looking-at "\\S-")
28085 (progn
28086 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28087 (setq bullet (match-string 1)
28088 btype (if (string-match "[0-9]" bullet) "n" bullet))
28089 (setq column (if (equal btype bullet-type) bcol tcol)))
28090 (setq column (org-get-indentation)))))
28091 (t (setq column (org-get-indentation))))))
28092 (goto-char pos)
28093 (if (<= (current-column) (current-indentation))
28094 (indent-line-to column)
28095 (save-excursion (indent-line-to column)))
28096 (setq column (current-column))
28097 (beginning-of-line 1)
28098 (if (looking-at
28099 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28100 (replace-match (concat "\\1" (format org-property-format
28101 (match-string 2) (match-string 3)))
28102 t nil))
28103 (move-to-column column)))
28105 (defun org-set-autofill-regexps ()
28106 (interactive)
28107 ;; In the paragraph separator we include headlines, because filling
28108 ;; text in a line directly attached to a headline would otherwise
28109 ;; fill the headline as well.
28110 (org-set-local 'comment-start-skip "^#+[ \t]*")
28111 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28112 ;; The paragraph starter includes hand-formatted lists.
28113 (org-set-local 'paragraph-start
28114 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28115 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28116 ;; But only if the user has not turned off tables or fixed-width regions
28117 (org-set-local
28118 'auto-fill-inhibit-regexp
28119 (concat "\\*+ \\|#\\+"
28120 "\\|[ \t]*" org-keyword-time-regexp
28121 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28122 (concat
28123 "\\|[ \t]*["
28124 (if org-enable-table-editor "|" "")
28125 (if org-enable-fixed-width-editor ":" "")
28126 "]"))))
28127 ;; We use our own fill-paragraph function, to make sure that tables
28128 ;; and fixed-width regions are not wrapped. That function will pass
28129 ;; through to `fill-paragraph' when appropriate.
28130 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28131 ; Adaptive filling: To get full control, first make sure that
28132 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28133 (org-set-local 'adaptive-fill-regexp "\000")
28134 (org-set-local 'adaptive-fill-function
28135 'org-adaptive-fill-function)
28136 (org-set-local
28137 'align-mode-rules-list
28138 '((org-in-buffer-settings
28139 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28140 (modes . '(org-mode))))))
28142 (defun org-fill-paragraph (&optional justify)
28143 "Re-align a table, pass through to fill-paragraph if no table."
28144 (let ((table-p (org-at-table-p))
28145 (table.el-p (org-at-table.el-p)))
28146 (cond ((and (equal (char-after (point-at-bol)) ?*)
28147 (save-excursion (goto-char (point-at-bol))
28148 (looking-at outline-regexp)))
28149 t) ; skip headlines
28150 (table.el-p t) ; skip table.el tables
28151 (table-p (org-table-align) t) ; align org-mode tables
28152 (t nil)))) ; call paragraph-fill
28154 ;; For reference, this is the default value of adaptive-fill-regexp
28155 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28157 (defun org-adaptive-fill-function ()
28158 "Return a fill prefix for org-mode files.
28159 In particular, this makes sure hanging paragraphs for hand-formatted lists
28160 work correctly."
28161 (cond ((looking-at "#[ \t]+")
28162 (match-string 0))
28163 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28164 (save-excursion
28165 (goto-char (match-end 0))
28166 (make-string (current-column) ?\ )))
28167 (t nil)))
28169 ;;;; Functions extending outline functionality
28172 (defun org-beginning-of-line (&optional arg)
28173 "Go to the beginning of the current line. If that is invisible, continue
28174 to a visible line beginning. This makes the function of C-a more intuitive.
28175 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28176 first attempt, and only move to after the tags when the cursor is already
28177 beyond the end of the headline."
28178 (interactive "P")
28179 (let ((pos (point)))
28180 (beginning-of-line 1)
28181 (if (bobp)
28183 (backward-char 1)
28184 (if (org-invisible-p)
28185 (while (and (not (bobp)) (org-invisible-p))
28186 (backward-char 1)
28187 (beginning-of-line 1))
28188 (forward-char 1)))
28189 (when org-special-ctrl-a/e
28190 (cond
28191 ((and (looking-at org-todo-line-regexp)
28192 (= (char-after (match-end 1)) ?\ ))
28193 (goto-char
28194 (if (eq org-special-ctrl-a/e t)
28195 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28196 ((= pos (point)) (match-beginning 3))
28197 (t (point)))
28198 (cond ((> pos (point)) (point))
28199 ((not (eq last-command this-command)) (point))
28200 (t (match-beginning 3))))))
28201 ((org-at-item-p)
28202 (goto-char
28203 (if (eq org-special-ctrl-a/e t)
28204 (cond ((> pos (match-end 4)) (match-end 4))
28205 ((= pos (point)) (match-end 4))
28206 (t (point)))
28207 (cond ((> pos (point)) (point))
28208 ((not (eq last-command this-command)) (point))
28209 (t (match-end 4))))))))))
28211 (defun org-end-of-line (&optional arg)
28212 "Go to the end of the line.
28213 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28214 first attempt, and only move to after the tags when the cursor is already
28215 beyond the end of the headline."
28216 (interactive "P")
28217 (if (or (not org-special-ctrl-a/e)
28218 (not (org-on-heading-p)))
28219 (end-of-line arg)
28220 (let ((pos (point)))
28221 (beginning-of-line 1)
28222 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28223 (if (eq org-special-ctrl-a/e t)
28224 (if (or (< pos (match-beginning 1))
28225 (= pos (match-end 0)))
28226 (goto-char (match-beginning 1))
28227 (goto-char (match-end 0)))
28228 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28229 (goto-char (match-end 0))
28230 (goto-char (match-beginning 1))))
28231 (end-of-line arg)))))
28233 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28234 (define-key org-mode-map "\C-e" 'org-end-of-line)
28236 (defun org-kill-line (&optional arg)
28237 "Kill line, to tags or end of line."
28238 (interactive "P")
28239 (cond
28240 ((or (not org-special-ctrl-k)
28241 (bolp)
28242 (not (org-on-heading-p)))
28243 (call-interactively 'kill-line))
28244 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28245 (kill-region (point) (match-beginning 1))
28246 (org-set-tags nil t))
28247 (t (kill-region (point) (point-at-eol)))))
28249 (define-key org-mode-map "\C-k" 'org-kill-line)
28251 (defun org-invisible-p ()
28252 "Check if point is at a character currently not visible."
28253 ;; Early versions of noutline don't have `outline-invisible-p'.
28254 (if (fboundp 'outline-invisible-p)
28255 (outline-invisible-p)
28256 (get-char-property (point) 'invisible)))
28258 (defun org-invisible-p2 ()
28259 "Check if point is at a character currently not visible."
28260 (save-excursion
28261 (if (and (eolp) (not (bobp))) (backward-char 1))
28262 ;; Early versions of noutline don't have `outline-invisible-p'.
28263 (if (fboundp 'outline-invisible-p)
28264 (outline-invisible-p)
28265 (get-char-property (point) 'invisible))))
28267 (defalias 'org-back-to-heading 'outline-back-to-heading)
28268 (defalias 'org-on-heading-p 'outline-on-heading-p)
28269 (defalias 'org-at-heading-p 'outline-on-heading-p)
28270 (defun org-at-heading-or-item-p ()
28271 (or (org-on-heading-p) (org-at-item-p)))
28273 (defun org-on-target-p ()
28274 (or (org-in-regexp org-radio-target-regexp)
28275 (org-in-regexp org-target-regexp)))
28277 (defun org-up-heading-all (arg)
28278 "Move to the heading line of which the present line is a subheading.
28279 This function considers both visible and invisible heading lines.
28280 With argument, move up ARG levels."
28281 (if (fboundp 'outline-up-heading-all)
28282 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28283 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28285 (defun org-up-heading-safe ()
28286 "Move to the heading line of which the present line is a subheading.
28287 This version will not throw an error. It will return the level of the
28288 headline found, or nil if no higher level is found."
28289 (let ((pos (point)) start-level level
28290 (re (concat "^" outline-regexp)))
28291 (catch 'exit
28292 (outline-back-to-heading t)
28293 (setq start-level (funcall outline-level))
28294 (if (equal start-level 1) (throw 'exit nil))
28295 (while (re-search-backward re nil t)
28296 (setq level (funcall outline-level))
28297 (if (< level start-level) (throw 'exit level)))
28298 nil)))
28300 (defun org-first-sibling-p ()
28301 "Is this heading the first child of its parents?"
28302 (interactive)
28303 (let ((re (concat "^" outline-regexp))
28304 level l)
28305 (unless (org-at-heading-p t)
28306 (error "Not at a heading"))
28307 (setq level (funcall outline-level))
28308 (save-excursion
28309 (if (not (re-search-backward re nil t))
28311 (setq l (funcall outline-level))
28312 (< l level)))))
28314 (defun org-goto-sibling (&optional previous)
28315 "Goto the next sibling, even if it is invisible.
28316 When PREVIOUS is set, go to the previous sibling instead. Returns t
28317 when a sibling was found. When none is found, return nil and don't
28318 move point."
28319 (let ((fun (if previous 're-search-backward 're-search-forward))
28320 (pos (point))
28321 (re (concat "^" outline-regexp))
28322 level l)
28323 (when (condition-case nil (org-back-to-heading t) (error nil))
28324 (setq level (funcall outline-level))
28325 (catch 'exit
28326 (or previous (forward-char 1))
28327 (while (funcall fun re nil t)
28328 (setq l (funcall outline-level))
28329 (when (< l level) (goto-char pos) (throw 'exit nil))
28330 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28331 (goto-char pos)
28332 nil))))
28334 (defun org-show-siblings ()
28335 "Show all siblings of the current headline."
28336 (save-excursion
28337 (while (org-goto-sibling) (org-flag-heading nil)))
28338 (save-excursion
28339 (while (org-goto-sibling 'previous)
28340 (org-flag-heading nil))))
28342 (defun org-show-hidden-entry ()
28343 "Show an entry where even the heading is hidden."
28344 (save-excursion
28345 (org-show-entry)))
28347 (defun org-flag-heading (flag &optional entry)
28348 "Flag the current heading. FLAG non-nil means make invisible.
28349 When ENTRY is non-nil, show the entire entry."
28350 (save-excursion
28351 (org-back-to-heading t)
28352 ;; Check if we should show the entire entry
28353 (if entry
28354 (progn
28355 (org-show-entry)
28356 (save-excursion
28357 (and (outline-next-heading)
28358 (org-flag-heading nil))))
28359 (outline-flag-region (max (point-min) (1- (point)))
28360 (save-excursion (outline-end-of-heading) (point))
28361 flag))))
28363 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28364 ;; This is an exact copy of the original function, but it uses
28365 ;; `org-back-to-heading', to make it work also in invisible
28366 ;; trees. And is uses an invisible-OK argument.
28367 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28368 (org-back-to-heading invisible-OK)
28369 (let ((first t)
28370 (level (funcall outline-level)))
28371 (while (and (not (eobp))
28372 (or first (> (funcall outline-level) level)))
28373 (setq first nil)
28374 (outline-next-heading))
28375 (unless to-heading
28376 (if (memq (preceding-char) '(?\n ?\^M))
28377 (progn
28378 ;; Go to end of line before heading
28379 (forward-char -1)
28380 (if (memq (preceding-char) '(?\n ?\^M))
28381 ;; leave blank line before heading
28382 (forward-char -1))))))
28383 (point))
28385 (defun org-show-subtree ()
28386 "Show everything after this heading at deeper levels."
28387 (outline-flag-region
28388 (point)
28389 (save-excursion
28390 (outline-end-of-subtree) (outline-next-heading) (point))
28391 nil))
28393 (defun org-show-entry ()
28394 "Show the body directly following this heading.
28395 Show the heading too, if it is currently invisible."
28396 (interactive)
28397 (save-excursion
28398 (condition-case nil
28399 (progn
28400 (org-back-to-heading t)
28401 (outline-flag-region
28402 (max (point-min) (1- (point)))
28403 (save-excursion
28404 (re-search-forward
28405 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28406 (or (match-beginning 1) (point-max)))
28407 nil))
28408 (error nil))))
28410 (defun org-make-options-regexp (kwds)
28411 "Make a regular expression for keyword lines."
28412 (concat
28414 "#?[ \t]*\\+\\("
28415 (mapconcat 'regexp-quote kwds "\\|")
28416 "\\):[ \t]*"
28417 "\\(.+\\)"))
28419 ;; Make isearch reveal the necessary context
28420 (defun org-isearch-end ()
28421 "Reveal context after isearch exits."
28422 (when isearch-success ; only if search was successful
28423 (if (featurep 'xemacs)
28424 ;; Under XEmacs, the hook is run in the correct place,
28425 ;; we directly show the context.
28426 (org-show-context 'isearch)
28427 ;; In Emacs the hook runs *before* restoring the overlays.
28428 ;; So we have to use a one-time post-command-hook to do this.
28429 ;; (Emacs 22 has a special variable, see function `org-mode')
28430 (unless (and (boundp 'isearch-mode-end-hook-quit)
28431 isearch-mode-end-hook-quit)
28432 ;; Only when the isearch was not quitted.
28433 (org-add-hook 'post-command-hook 'org-isearch-post-command
28434 'append 'local)))))
28436 (defun org-isearch-post-command ()
28437 "Remove self from hook, and show context."
28438 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28439 (org-show-context 'isearch))
28442 ;;;; Integration with and fixes for other packages
28444 ;;; Imenu support
28446 (defvar org-imenu-markers nil
28447 "All markers currently used by Imenu.")
28448 (make-variable-buffer-local 'org-imenu-markers)
28450 (defun org-imenu-new-marker (&optional pos)
28451 "Return a new marker for use by Imenu, and remember the marker."
28452 (let ((m (make-marker)))
28453 (move-marker m (or pos (point)))
28454 (push m org-imenu-markers)
28457 (defun org-imenu-get-tree ()
28458 "Produce the index for Imenu."
28459 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28460 (setq org-imenu-markers nil)
28461 (let* ((n org-imenu-depth)
28462 (re (concat "^" outline-regexp))
28463 (subs (make-vector (1+ n) nil))
28464 (last-level 0)
28465 m tree level head)
28466 (save-excursion
28467 (save-restriction
28468 (widen)
28469 (goto-char (point-max))
28470 (while (re-search-backward re nil t)
28471 (setq level (org-reduced-level (funcall outline-level)))
28472 (when (<= level n)
28473 (looking-at org-complex-heading-regexp)
28474 (setq head (org-match-string-no-properties 4)
28475 m (org-imenu-new-marker))
28476 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28477 (if (>= level last-level)
28478 (push (cons head m) (aref subs level))
28479 (push (cons head (aref subs (1+ level))) (aref subs level))
28480 (loop for i from (1+ level) to n do (aset subs i nil)))
28481 (setq last-level level)))))
28482 (aref subs 1)))
28484 (eval-after-load "imenu"
28485 '(progn
28486 (add-hook 'imenu-after-jump-hook
28487 (lambda () (org-show-context 'org-goto)))))
28489 ;; Speedbar support
28491 (defun org-speedbar-set-agenda-restriction ()
28492 "Restrict future agenda commands to the location at point in speedbar.
28493 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28494 (interactive)
28495 (let (p m tp np dir txt w)
28496 (cond
28497 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28498 'org-imenu t))
28499 (setq m (get-text-property p 'org-imenu-marker))
28500 (save-excursion
28501 (save-restriction
28502 (set-buffer (marker-buffer m))
28503 (goto-char m)
28504 (org-agenda-set-restriction-lock 'subtree))))
28505 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28506 'speedbar-function 'speedbar-find-file))
28507 (setq tp (previous-single-property-change
28508 (1+ p) 'speedbar-function)
28509 np (next-single-property-change
28510 tp 'speedbar-function)
28511 dir (speedbar-line-directory)
28512 txt (buffer-substring-no-properties (or tp (point-min))
28513 (or np (point-max))))
28514 (save-excursion
28515 (save-restriction
28516 (set-buffer (find-file-noselect
28517 (let ((default-directory dir))
28518 (expand-file-name txt))))
28519 (unless (org-mode-p)
28520 (error "Cannot restrict to non-Org-mode file"))
28521 (org-agenda-set-restriction-lock 'file))))
28522 (t (error "Don't know how to restrict Org-mode's agenda")))
28523 (org-move-overlay org-speedbar-restriction-lock-overlay
28524 (point-at-bol) (point-at-eol))
28525 (setq current-prefix-arg nil)
28526 (org-agenda-maybe-redo)))
28528 (eval-after-load "speedbar"
28529 '(progn
28530 (speedbar-add-supported-extension ".org")
28531 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28532 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28533 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28534 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28535 (add-hook 'speedbar-visiting-tag-hook
28536 (lambda () (org-show-context 'org-goto)))))
28539 ;;; Fixes and Hacks
28541 ;; Make flyspell not check words in links, to not mess up our keymap
28542 (defun org-mode-flyspell-verify ()
28543 "Don't let flyspell put overlays at active buttons."
28544 (not (get-text-property (point) 'keymap)))
28546 ;; Make `bookmark-jump' show the jump location if it was hidden.
28547 (eval-after-load "bookmark"
28548 '(if (boundp 'bookmark-after-jump-hook)
28549 ;; We can use the hook
28550 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28551 ;; Hook not available, use advice
28552 (defadvice bookmark-jump (after org-make-visible activate)
28553 "Make the position visible."
28554 (org-bookmark-jump-unhide))))
28556 (defun org-bookmark-jump-unhide ()
28557 "Unhide the current position, to show the bookmark location."
28558 (and (org-mode-p)
28559 (or (org-invisible-p)
28560 (save-excursion (goto-char (max (point-min) (1- (point))))
28561 (org-invisible-p)))
28562 (org-show-context 'bookmark-jump)))
28564 ;; Fix a bug in htmlize where there are text properties (face nil)
28565 (eval-after-load "htmlize"
28566 '(progn
28567 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28568 "Make sure there are no nil faces"
28569 (setq ad-return-value (delq nil ad-return-value)))))
28571 ;; Make session.el ignore our circular variable
28572 (eval-after-load "session"
28573 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28575 ;;;; Experimental code
28577 (defun org-closed-in-range ()
28578 "Sparse tree of items closed in a certain time range.
28579 Still experimental, may disappear in the future."
28580 (interactive)
28581 ;; Get the time interval from the user.
28582 (let* ((time1 (time-to-seconds
28583 (org-read-date nil 'to-time nil "Starting date: ")))
28584 (time2 (time-to-seconds
28585 (org-read-date nil 'to-time nil "End date:")))
28586 ;; callback function
28587 (callback (lambda ()
28588 (let ((time
28589 (time-to-seconds
28590 (apply 'encode-time
28591 (org-parse-time-string
28592 (match-string 1))))))
28593 ;; check if time in interval
28594 (and (>= time time1) (<= time time2))))))
28595 ;; make tree, check each match with the callback
28596 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28598 ;;;; Finish up
28600 (provide 'org)
28602 (run-hooks 'org-load-hook)
28604 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28605 ;;; org.el ends here