Added support for :maxlevel and :skip-empty-rows parameters to columnview dblock.
[org-mode.git] / org.el
blob46f5dfc4c1d8fc47c6da4c668a4da65c6a84ec34
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, to 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 (if heading
8056 (progn
8057 (if (re-search-forward
8058 (concat "^" (regexp-quote heading)
8059 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8060 nil t)
8061 (goto-char (match-end 0))
8062 ;; Heading not found, just insert it at the end
8063 (goto-char (point-max))
8064 (or (bolp) (insert "\n"))
8065 (insert "\n" heading "\n")
8066 (end-of-line 0))
8067 ;; Make the subtree visible
8068 (show-subtree)
8069 (org-end-of-subtree t)
8070 (skip-chars-backward " \t\r\n")
8071 (and (looking-at "[ \t\r\n]*")
8072 (replace-match "\n\n")))
8073 ;; No specific heading, just go to end of file.
8074 (goto-char (point-max)) (insert "\n"))
8075 ;; Paste
8076 (org-paste-subtree (org-get-legal-level level 1))
8078 ;; Mark the entry as done
8079 (when (and org-archive-mark-done
8080 (looking-at org-todo-line-regexp)
8081 (or (not (match-end 2))
8082 (not (member (match-string 2) org-done-keywords))))
8083 (let (org-log-done org-todo-log-states)
8084 (org-todo
8085 (car (or (member org-archive-mark-done org-done-keywords)
8086 org-done-keywords)))))
8088 ;; Add the context info
8089 (when org-archive-save-context-info
8090 (let ((l org-archive-save-context-info) e n v)
8091 (while (setq e (pop l))
8092 (when (and (setq v (symbol-value e))
8093 (stringp v) (string-match "\\S-" v))
8094 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8095 (org-entry-put (point) n v)))))
8097 ;; Save the buffer, if it is not the same buffer.
8098 (if (not (eq this-buffer buffer)) (save-buffer))))
8099 ;; Here we are back in the original buffer. Everything seems to have
8100 ;; worked. So now cut the tree and finish up.
8101 (let (this-command) (org-cut-subtree))
8102 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8103 (message "Subtree archived %s"
8104 (if (eq this-buffer buffer)
8105 (concat "under heading: " heading)
8106 (concat "in file: " (abbreviate-file-name afile)))))))
8108 (defun org-refresh-category-properties ()
8109 "Refresh category text properties in teh buffer."
8110 (let ((def-cat (cond
8111 ((null org-category)
8112 (if buffer-file-name
8113 (file-name-sans-extension
8114 (file-name-nondirectory buffer-file-name))
8115 "???"))
8116 ((symbolp org-category) (symbol-name org-category))
8117 (t org-category)))
8118 beg end cat pos optionp)
8119 (org-unmodified
8120 (save-excursion
8121 (save-restriction
8122 (widen)
8123 (goto-char (point-min))
8124 (put-text-property (point) (point-max) 'org-category def-cat)
8125 (while (re-search-forward
8126 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8127 (setq pos (match-end 0)
8128 optionp (equal (char-after (match-beginning 0)) ?#)
8129 cat (org-trim (match-string 2)))
8130 (if optionp
8131 (setq beg (point-at-bol) end (point-max))
8132 (org-back-to-heading t)
8133 (setq beg (point) end (org-end-of-subtree t t)))
8134 (put-text-property beg end 'org-category cat)
8135 (goto-char pos)))))))
8137 (defun org-archive-all-done (&optional tag)
8138 "Archive sublevels of the current tree without open TODO items.
8139 If the cursor is not on a headline, try all level 1 trees. If
8140 it is on a headline, try all direct children.
8141 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8142 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8143 (rea (concat ".*:" org-archive-tag ":"))
8144 (begm (make-marker))
8145 (endm (make-marker))
8146 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8147 "Move subtree to archive (no open TODO items)? "))
8148 beg end (cntarch 0))
8149 (if (org-on-heading-p)
8150 (progn
8151 (setq re1 (concat "^" (regexp-quote
8152 (make-string
8153 (1+ (- (match-end 0) (match-beginning 0) 1))
8154 ?*))
8155 " "))
8156 (move-marker begm (point))
8157 (move-marker endm (org-end-of-subtree t)))
8158 (setq re1 "^* ")
8159 (move-marker begm (point-min))
8160 (move-marker endm (point-max)))
8161 (save-excursion
8162 (goto-char begm)
8163 (while (re-search-forward re1 endm t)
8164 (setq beg (match-beginning 0)
8165 end (save-excursion (org-end-of-subtree t) (point)))
8166 (goto-char beg)
8167 (if (re-search-forward re end t)
8168 (goto-char end)
8169 (goto-char beg)
8170 (if (and (or (not tag) (not (looking-at rea)))
8171 (y-or-n-p question))
8172 (progn
8173 (if tag
8174 (org-toggle-tag org-archive-tag 'on)
8175 (org-archive-subtree))
8176 (setq cntarch (1+ cntarch)))
8177 (goto-char end)))))
8178 (message "%d trees archived" cntarch)))
8180 (defun org-cycle-hide-drawers (state)
8181 "Re-hide all drawers after a visibility state change."
8182 (when (and (org-mode-p)
8183 (not (memq state '(overview folded))))
8184 (save-excursion
8185 (let* ((globalp (memq state '(contents all)))
8186 (beg (if globalp (point-min) (point)))
8187 (end (if globalp (point-max) (org-end-of-subtree t))))
8188 (goto-char beg)
8189 (while (re-search-forward org-drawer-regexp end t)
8190 (org-flag-drawer t))))))
8192 (defun org-flag-drawer (flag)
8193 (save-excursion
8194 (beginning-of-line 1)
8195 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8196 (let ((b (match-end 0))
8197 (outline-regexp org-outline-regexp))
8198 (if (re-search-forward
8199 "^[ \t]*:END:"
8200 (save-excursion (outline-next-heading) (point)) t)
8201 (outline-flag-region b (point-at-eol) flag)
8202 (error ":END: line missing"))))))
8204 (defun org-cycle-hide-archived-subtrees (state)
8205 "Re-hide all archived subtrees after a visibility state change."
8206 (when (and (not org-cycle-open-archived-trees)
8207 (not (memq state '(overview folded))))
8208 (save-excursion
8209 (let* ((globalp (memq state '(contents all)))
8210 (beg (if globalp (point-min) (point)))
8211 (end (if globalp (point-max) (org-end-of-subtree t))))
8212 (org-hide-archived-subtrees beg end)
8213 (goto-char beg)
8214 (if (looking-at (concat ".*:" org-archive-tag ":"))
8215 (message "%s" (substitute-command-keys
8216 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8218 (defun org-force-cycle-archived ()
8219 "Cycle subtree even if it is archived."
8220 (interactive)
8221 (setq this-command 'org-cycle)
8222 (let ((org-cycle-open-archived-trees t))
8223 (call-interactively 'org-cycle)))
8225 (defun org-hide-archived-subtrees (beg end)
8226 "Re-hide all archived subtrees after a visibility state change."
8227 (save-excursion
8228 (let* ((re (concat ":" org-archive-tag ":")))
8229 (goto-char beg)
8230 (while (re-search-forward re end t)
8231 (and (org-on-heading-p) (hide-subtree))
8232 (org-end-of-subtree t)))))
8234 (defun org-toggle-tag (tag &optional onoff)
8235 "Toggle the tag TAG for the current line.
8236 If ONOFF is `on' or `off', don't toggle but set to this state."
8237 (unless (org-on-heading-p t) (error "Not on headling"))
8238 (let (res current)
8239 (save-excursion
8240 (beginning-of-line)
8241 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8242 (point-at-eol) t)
8243 (progn
8244 (setq current (match-string 1))
8245 (replace-match ""))
8246 (setq current ""))
8247 (setq current (nreverse (org-split-string current ":")))
8248 (cond
8249 ((eq onoff 'on)
8250 (setq res t)
8251 (or (member tag current) (push tag current)))
8252 ((eq onoff 'off)
8253 (or (not (member tag current)) (setq current (delete tag current))))
8254 (t (if (member tag current)
8255 (setq current (delete tag current))
8256 (setq res t)
8257 (push tag current))))
8258 (end-of-line 1)
8259 (if current
8260 (progn
8261 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8262 (org-set-tags nil t))
8263 (delete-horizontal-space))
8264 (run-hooks 'org-after-tags-change-hook))
8265 res))
8267 (defun org-toggle-archive-tag (&optional arg)
8268 "Toggle the archive tag for the current headline.
8269 With prefix ARG, check all children of current headline and offer tagging
8270 the children that do not contain any open TODO items."
8271 (interactive "P")
8272 (if arg
8273 (org-archive-all-done 'tag)
8274 (let (set)
8275 (save-excursion
8276 (org-back-to-heading t)
8277 (setq set (org-toggle-tag org-archive-tag))
8278 (when set (hide-subtree)))
8279 (and set (beginning-of-line 1))
8280 (message "Subtree %s" (if set "archived" "unarchived")))))
8283 ;;;; Tables
8285 ;;; The table editor
8287 ;; Watch out: Here we are talking about two different kind of tables.
8288 ;; Most of the code is for the tables created with the Org-mode table editor.
8289 ;; Sometimes, we talk about tables created and edited with the table.el
8290 ;; Emacs package. We call the former org-type tables, and the latter
8291 ;; table.el-type tables.
8293 (defun org-before-change-function (beg end)
8294 "Every change indicates that a table might need an update."
8295 (setq org-table-may-need-update t))
8297 (defconst org-table-line-regexp "^[ \t]*|"
8298 "Detects an org-type table line.")
8299 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8300 "Detects an org-type table line.")
8301 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8302 "Detects a table line marked for automatic recalculation.")
8303 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8304 "Detects a table line marked for automatic recalculation.")
8305 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8306 "Detects a table line marked for automatic recalculation.")
8307 (defconst org-table-hline-regexp "^[ \t]*|-"
8308 "Detects an org-type table hline.")
8309 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8310 "Detects a table-type table hline.")
8311 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8312 "Detects an org-type or table-type table.")
8313 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8314 "Searching from within a table (any type) this finds the first line
8315 outside the table.")
8316 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8317 "Searching from within a table (any type) this finds the first line
8318 outside the table.")
8320 (defvar org-table-last-highlighted-reference nil)
8321 (defvar org-table-formula-history nil)
8323 (defvar org-table-column-names nil
8324 "Alist with column names, derived from the `!' line.")
8325 (defvar org-table-column-name-regexp nil
8326 "Regular expression matching the current column names.")
8327 (defvar org-table-local-parameters nil
8328 "Alist with parameter names, derived from the `$' line.")
8329 (defvar org-table-named-field-locations nil
8330 "Alist with locations of named fields.")
8332 (defvar org-table-current-line-types nil
8333 "Table row types, non-nil only for the duration of a comand.")
8334 (defvar org-table-current-begin-line nil
8335 "Table begin line, non-nil only for the duration of a comand.")
8336 (defvar org-table-current-begin-pos nil
8337 "Table begin position, non-nil only for the duration of a comand.")
8338 (defvar org-table-dlines nil
8339 "Vector of data line line numbers in the current table.")
8340 (defvar org-table-hlines nil
8341 "Vector of hline line numbers in the current table.")
8343 (defconst org-table-range-regexp
8344 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8345 ;; 1 2 3 4 5
8346 "Regular expression for matching ranges in formulas.")
8348 (defconst org-table-range-regexp2
8349 (concat
8350 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8351 "\\.\\."
8352 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8353 "Match a range for reference display.")
8355 (defconst org-table-translate-regexp
8356 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8357 "Match a reference that needs translation, for reference display.")
8359 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8361 (defun org-table-create-with-table.el ()
8362 "Use the table.el package to insert a new table.
8363 If there is already a table at point, convert between Org-mode tables
8364 and table.el tables."
8365 (interactive)
8366 (require 'table)
8367 (cond
8368 ((org-at-table.el-p)
8369 (if (y-or-n-p "Convert table to Org-mode table? ")
8370 (org-table-convert)))
8371 ((org-at-table-p)
8372 (if (y-or-n-p "Convert table to table.el table? ")
8373 (org-table-convert)))
8374 (t (call-interactively 'table-insert))))
8376 (defun org-table-create-or-convert-from-region (arg)
8377 "Convert region to table, or create an empty table.
8378 If there is an active region, convert it to a table, using the function
8379 `org-table-convert-region'. See the documentation of that function
8380 to learn how the prefix argument is interpreted to determine the field
8381 separator.
8382 If there is no such region, create an empty table with `org-table-create'."
8383 (interactive "P")
8384 (if (org-region-active-p)
8385 (org-table-convert-region (region-beginning) (region-end) arg)
8386 (org-table-create arg)))
8388 (defun org-table-create (&optional size)
8389 "Query for a size and insert a table skeleton.
8390 SIZE is a string Columns x Rows like for example \"3x2\"."
8391 (interactive "P")
8392 (unless size
8393 (setq size (read-string
8394 (concat "Table size Columns x Rows [e.g. "
8395 org-table-default-size "]: ")
8396 "" nil org-table-default-size)))
8398 (let* ((pos (point))
8399 (indent (make-string (current-column) ?\ ))
8400 (split (org-split-string size " *x *"))
8401 (rows (string-to-number (nth 1 split)))
8402 (columns (string-to-number (car split)))
8403 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8404 "\n")))
8405 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8406 (point-at-bol) (point)))
8407 (beginning-of-line 1)
8408 (newline))
8409 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8410 (dotimes (i rows) (insert line))
8411 (goto-char pos)
8412 (if (> rows 1)
8413 ;; Insert a hline after the first row.
8414 (progn
8415 (end-of-line 1)
8416 (insert "\n|-")
8417 (goto-char pos)))
8418 (org-table-align)))
8420 (defun org-table-convert-region (beg0 end0 &optional separator)
8421 "Convert region to a table.
8422 The region goes from BEG0 to END0, but these borders will be moved
8423 slightly, to make sure a beginning of line in the first line is included.
8425 SEPARATOR specifies the field separator in the lines. It can have the
8426 following values:
8428 '(4) Use the comma as a field separator
8429 '(16) Use a TAB as field separator
8430 integer When a number, use that many spaces as field separator
8431 nil When nil, the command tries to be smart and figure out the
8432 separator in the following way:
8433 - when each line contains a TAB, assume TAB-separated material
8434 - when each line contains a comme, assume CSV material
8435 - else, assume one or more SPACE charcters as separator."
8436 (interactive "rP")
8437 (let* ((beg (min beg0 end0))
8438 (end (max beg0 end0))
8440 (goto-char beg)
8441 (beginning-of-line 1)
8442 (setq beg (move-marker (make-marker) (point)))
8443 (goto-char end)
8444 (if (bolp) (backward-char 1) (end-of-line 1))
8445 (setq end (move-marker (make-marker) (point)))
8446 ;; Get the right field separator
8447 (unless separator
8448 (goto-char beg)
8449 (setq separator
8450 (cond
8451 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8452 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8453 (t 1))))
8454 (setq re (cond
8455 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8456 ((equal separator '(16)) "^\\|\t")
8457 ((integerp separator)
8458 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8459 (t (error "This should not happen"))))
8460 (goto-char beg)
8461 (while (re-search-forward re end t)
8462 (replace-match "| " t t))
8463 (goto-char beg)
8464 (insert " ")
8465 (org-table-align)))
8467 (defun org-table-import (file arg)
8468 "Import FILE as a table.
8469 The file is assumed to be tab-separated. Such files can be produced by most
8470 spreadsheet and database applications. If no tabs (at least one per line)
8471 are found, lines will be split on whitespace into fields."
8472 (interactive "f\nP")
8473 (or (bolp) (newline))
8474 (let ((beg (point))
8475 (pm (point-max)))
8476 (insert-file-contents file)
8477 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8479 (defun org-table-export ()
8480 "Export table as a tab-separated file.
8481 Such a file can be imported into a spreadsheet program like Excel."
8482 (interactive)
8483 (let* ((beg (org-table-begin))
8484 (end (org-table-end))
8485 (table (buffer-substring beg end))
8486 (file (read-file-name "Export table to: "))
8487 buf)
8488 (unless (or (not (file-exists-p file))
8489 (y-or-n-p (format "Overwrite file %s? " file)))
8490 (error "Abort"))
8491 (with-current-buffer (find-file-noselect file)
8492 (setq buf (current-buffer))
8493 (erase-buffer)
8494 (fundamental-mode)
8495 (insert table)
8496 (goto-char (point-min))
8497 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8498 (replace-match "" t t)
8499 (end-of-line 1))
8500 (goto-char (point-min))
8501 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8502 (replace-match "" t t)
8503 (goto-char (min (1+ (point)) (point-max))))
8504 (goto-char (point-min))
8505 (while (re-search-forward "^-[-+]*$" nil t)
8506 (replace-match "")
8507 (if (looking-at "\n")
8508 (delete-char 1)))
8509 (goto-char (point-min))
8510 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8511 (replace-match "\t" t t))
8512 (save-buffer))
8513 (kill-buffer buf)))
8515 (defvar org-table-aligned-begin-marker (make-marker)
8516 "Marker at the beginning of the table last aligned.
8517 Used to check if cursor still is in that table, to minimize realignment.")
8518 (defvar org-table-aligned-end-marker (make-marker)
8519 "Marker at the end of the table last aligned.
8520 Used to check if cursor still is in that table, to minimize realignment.")
8521 (defvar org-table-last-alignment nil
8522 "List of flags for flushright alignment, from the last re-alignment.
8523 This is being used to correctly align a single field after TAB or RET.")
8524 (defvar org-table-last-column-widths nil
8525 "List of max width of fields in each column.
8526 This is being used to correctly align a single field after TAB or RET.")
8527 (defvar org-table-overlay-coordinates nil
8528 "Overlay coordinates after each align of a table.")
8529 (make-variable-buffer-local 'org-table-overlay-coordinates)
8531 (defvar org-last-recalc-line nil)
8532 (defconst org-narrow-column-arrow "=>"
8533 "Used as display property in narrowed table columns.")
8535 (defun org-table-align ()
8536 "Align the table at point by aligning all vertical bars."
8537 (interactive)
8538 (let* (
8539 ;; Limits of table
8540 (beg (org-table-begin))
8541 (end (org-table-end))
8542 ;; Current cursor position
8543 (linepos (org-current-line))
8544 (colpos (org-table-current-column))
8545 (winstart (window-start))
8546 (winstartline (org-current-line (min winstart (1- (point-max)))))
8547 lines (new "") lengths l typenums ty fields maxfields i
8548 column
8549 (indent "") cnt frac
8550 rfmt hfmt
8551 (spaces '(1 . 1))
8552 (sp1 (car spaces))
8553 (sp2 (cdr spaces))
8554 (rfmt1 (concat
8555 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8556 (hfmt1 (concat
8557 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8558 emptystrings links dates emph narrow fmax f1 len c e)
8559 (untabify beg end)
8560 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8561 ;; Check if we have links or dates
8562 (goto-char beg)
8563 (setq links (re-search-forward org-bracket-link-regexp end t))
8564 (goto-char beg)
8565 (setq emph (and org-hide-emphasis-markers
8566 (re-search-forward org-emph-re end t)))
8567 (goto-char beg)
8568 (setq dates (and org-display-custom-times
8569 (re-search-forward org-ts-regexp-both end t)))
8570 ;; Make sure the link properties are right
8571 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8572 ;; Make sure the date properties are right
8573 (when dates (goto-char beg) (while (org-activate-dates end)))
8574 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8576 ;; Check if we are narrowing any columns
8577 (goto-char beg)
8578 (setq narrow (and org-format-transports-properties-p
8579 (re-search-forward "<[0-9]+>" end t)))
8580 ;; Get the rows
8581 (setq lines (org-split-string
8582 (buffer-substring beg end) "\n"))
8583 ;; Store the indentation of the first line
8584 (if (string-match "^ *" (car lines))
8585 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8586 ;; Mark the hlines by setting the corresponding element to nil
8587 ;; At the same time, we remove trailing space.
8588 (setq lines (mapcar (lambda (l)
8589 (if (string-match "^ *|-" l)
8591 (if (string-match "[ \t]+$" l)
8592 (substring l 0 (match-beginning 0))
8593 l)))
8594 lines))
8595 ;; Get the data fields by splitting the lines.
8596 (setq fields (mapcar
8597 (lambda (l)
8598 (org-split-string l " *| *"))
8599 (delq nil (copy-sequence lines))))
8600 ;; How many fields in the longest line?
8601 (condition-case nil
8602 (setq maxfields (apply 'max (mapcar 'length fields)))
8603 (error
8604 (kill-region beg end)
8605 (org-table-create org-table-default-size)
8606 (error "Empty table - created default table")))
8607 ;; A list of empty strings to fill any short rows on output
8608 (setq emptystrings (make-list maxfields ""))
8609 ;; Check for special formatting.
8610 (setq i -1)
8611 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8612 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8613 ;; Check if there is an explicit width specified
8614 (when narrow
8615 (setq c column fmax nil)
8616 (while c
8617 (setq e (pop c))
8618 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8619 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8620 ;; Find fields that are wider than fmax, and shorten them
8621 (when fmax
8622 (loop for xx in column do
8623 (when (and (stringp xx)
8624 (> (org-string-width xx) fmax))
8625 (org-add-props xx nil
8626 'help-echo
8627 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8628 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8629 (unless (> f1 1)
8630 (error "Cannot narrow field starting with wide link \"%s\""
8631 (match-string 0 xx)))
8632 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8633 (add-text-properties (- f1 2) f1
8634 (list 'display org-narrow-column-arrow)
8635 xx)))))
8636 ;; Get the maximum width for each column
8637 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8638 ;; Get the fraction of numbers, to decide about alignment of the column
8639 (setq cnt 0 frac 0.0)
8640 (loop for x in column do
8641 (if (equal x "")
8643 (setq frac ( / (+ (* frac cnt)
8644 (if (string-match org-table-number-regexp x) 1 0))
8645 (setq cnt (1+ cnt))))))
8646 (push (>= frac org-table-number-fraction) typenums))
8647 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8649 ;; Store the alignment of this table, for later editing of single fields
8650 (setq org-table-last-alignment typenums
8651 org-table-last-column-widths lengths)
8653 ;; With invisible characters, `format' does not get the field width right
8654 ;; So we need to make these fields wide by hand.
8655 (when (or links emph)
8656 (loop for i from 0 upto (1- maxfields) do
8657 (setq len (nth i lengths))
8658 (loop for j from 0 upto (1- (length fields)) do
8659 (setq c (nthcdr i (car (nthcdr j fields))))
8660 (if (and (stringp (car c))
8661 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8662 ; (string-match org-bracket-link-regexp (car c))
8663 (< (org-string-width (car c)) len))
8664 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8666 ;; Compute the formats needed for output of the table
8667 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8668 (while (setq l (pop lengths))
8669 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8670 (setq rfmt (concat rfmt (format rfmt1 ty l))
8671 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8672 (setq rfmt (concat rfmt "\n")
8673 hfmt (concat (substring hfmt 0 -1) "|\n"))
8675 (setq new (mapconcat
8676 (lambda (l)
8677 (if l (apply 'format rfmt
8678 (append (pop fields) emptystrings))
8679 hfmt))
8680 lines ""))
8681 ;; Replace the old one
8682 (delete-region beg end)
8683 (move-marker end nil)
8684 (move-marker org-table-aligned-begin-marker (point))
8685 (insert new)
8686 (move-marker org-table-aligned-end-marker (point))
8687 (when (and orgtbl-mode (not (org-mode-p)))
8688 (goto-char org-table-aligned-begin-marker)
8689 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8690 ;; Try to move to the old location
8691 (goto-line winstartline)
8692 (setq winstart (point-at-bol))
8693 (goto-line linepos)
8694 (set-window-start (selected-window) winstart 'noforce)
8695 (org-table-goto-column colpos)
8696 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8697 (setq org-table-may-need-update nil)
8700 (defun org-string-width (s)
8701 "Compute width of string, ignoring invisible characters.
8702 This ignores character with invisibility property `org-link', and also
8703 characters with property `org-cwidth', because these will become invisible
8704 upon the next fontification round."
8705 (let (b l)
8706 (when (or (eq t buffer-invisibility-spec)
8707 (assq 'org-link buffer-invisibility-spec))
8708 (while (setq b (text-property-any 0 (length s)
8709 'invisible 'org-link s))
8710 (setq s (concat (substring s 0 b)
8711 (substring s (or (next-single-property-change
8712 b 'invisible s) (length s)))))))
8713 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8714 (setq s (concat (substring s 0 b)
8715 (substring s (or (next-single-property-change
8716 b 'org-cwidth s) (length s))))))
8717 (setq l (string-width s) b -1)
8718 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8719 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8722 (defun org-table-begin (&optional table-type)
8723 "Find the beginning of the table and return its position.
8724 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8725 (save-excursion
8726 (if (not (re-search-backward
8727 (if table-type org-table-any-border-regexp
8728 org-table-border-regexp)
8729 nil t))
8730 (progn (goto-char (point-min)) (point))
8731 (goto-char (match-beginning 0))
8732 (beginning-of-line 2)
8733 (point))))
8735 (defun org-table-end (&optional table-type)
8736 "Find the end of the table and return its position.
8737 With argument TABLE-TYPE, go to the end of a table.el-type table."
8738 (save-excursion
8739 (if (not (re-search-forward
8740 (if table-type org-table-any-border-regexp
8741 org-table-border-regexp)
8742 nil t))
8743 (goto-char (point-max))
8744 (goto-char (match-beginning 0)))
8745 (point-marker)))
8747 (defun org-table-justify-field-maybe (&optional new)
8748 "Justify the current field, text to left, number to right.
8749 Optional argument NEW may specify text to replace the current field content."
8750 (cond
8751 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8752 ((org-at-table-hline-p))
8753 ((and (not new)
8754 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8755 (current-buffer)))
8756 (< (point) org-table-aligned-begin-marker)
8757 (>= (point) org-table-aligned-end-marker)))
8758 ;; This is not the same table, force a full re-align
8759 (setq org-table-may-need-update t))
8760 (t ;; realign the current field, based on previous full realign
8761 (let* ((pos (point)) s
8762 (col (org-table-current-column))
8763 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8764 l f n o e)
8765 (when (> col 0)
8766 (skip-chars-backward "^|\n")
8767 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8768 (progn
8769 (setq s (match-string 1)
8770 o (match-string 0)
8771 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8772 e (not (= (match-beginning 2) (match-end 2))))
8773 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8774 l (if e "|" (setq org-table-may-need-update t) ""))
8775 n (format f s))
8776 (if new
8777 (if (<= (length new) l) ;; FIXME: length -> str-width?
8778 (setq n (format f new))
8779 (setq n (concat new "|") org-table-may-need-update t)))
8780 (or (equal n o)
8781 (let (org-table-may-need-update)
8782 (replace-match n t t))))
8783 (setq org-table-may-need-update t))
8784 (goto-char pos))))))
8786 (defun org-table-next-field ()
8787 "Go to the next field in the current table, creating new lines as needed.
8788 Before doing so, re-align the table if necessary."
8789 (interactive)
8790 (org-table-maybe-eval-formula)
8791 (org-table-maybe-recalculate-line)
8792 (if (and org-table-automatic-realign
8793 org-table-may-need-update)
8794 (org-table-align))
8795 (let ((end (org-table-end)))
8796 (if (org-at-table-hline-p)
8797 (end-of-line 1))
8798 (condition-case nil
8799 (progn
8800 (re-search-forward "|" end)
8801 (if (looking-at "[ \t]*$")
8802 (re-search-forward "|" end))
8803 (if (and (looking-at "-")
8804 org-table-tab-jumps-over-hlines
8805 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8806 (goto-char (match-beginning 1)))
8807 (if (looking-at "-")
8808 (progn
8809 (beginning-of-line 0)
8810 (org-table-insert-row 'below))
8811 (if (looking-at " ") (forward-char 1))))
8812 (error
8813 (org-table-insert-row 'below)))))
8815 (defun org-table-previous-field ()
8816 "Go to the previous field in the table.
8817 Before doing so, re-align the table if necessary."
8818 (interactive)
8819 (org-table-justify-field-maybe)
8820 (org-table-maybe-recalculate-line)
8821 (if (and org-table-automatic-realign
8822 org-table-may-need-update)
8823 (org-table-align))
8824 (if (org-at-table-hline-p)
8825 (end-of-line 1))
8826 (re-search-backward "|" (org-table-begin))
8827 (re-search-backward "|" (org-table-begin))
8828 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8829 (re-search-backward "|" (org-table-begin)))
8830 (if (looking-at "| ?")
8831 (goto-char (match-end 0))))
8833 (defun org-table-next-row ()
8834 "Go to the next row (same column) in the current table.
8835 Before doing so, re-align the table if necessary."
8836 (interactive)
8837 (org-table-maybe-eval-formula)
8838 (org-table-maybe-recalculate-line)
8839 (if (or (looking-at "[ \t]*$")
8840 (save-excursion (skip-chars-backward " \t") (bolp)))
8841 (newline)
8842 (if (and org-table-automatic-realign
8843 org-table-may-need-update)
8844 (org-table-align))
8845 (let ((col (org-table-current-column)))
8846 (beginning-of-line 2)
8847 (if (or (not (org-at-table-p))
8848 (org-at-table-hline-p))
8849 (progn
8850 (beginning-of-line 0)
8851 (org-table-insert-row 'below)))
8852 (org-table-goto-column col)
8853 (skip-chars-backward "^|\n\r")
8854 (if (looking-at " ") (forward-char 1)))))
8856 (defun org-table-copy-down (n)
8857 "Copy a field down in the current column.
8858 If the field at the cursor is empty, copy into it the content of the nearest
8859 non-empty field above. With argument N, use the Nth non-empty field.
8860 If the current field is not empty, it is copied down to the next row, and
8861 the cursor is moved with it. Therefore, repeating this command causes the
8862 column to be filled row-by-row.
8863 If the variable `org-table-copy-increment' is non-nil and the field is an
8864 integer or a timestamp, it will be incremented while copying. In the case of
8865 a timestamp, if the cursor is on the year, change the year. If it is on the
8866 month or the day, change that. Point will stay on the current date field
8867 in order to easily repeat the interval."
8868 (interactive "p")
8869 (let* ((colpos (org-table-current-column))
8870 (col (current-column))
8871 (field (org-table-get-field))
8872 (non-empty (string-match "[^ \t]" field))
8873 (beg (org-table-begin))
8874 txt)
8875 (org-table-check-inside-data-field)
8876 (if non-empty
8877 (progn
8878 (setq txt (org-trim field))
8879 (org-table-next-row)
8880 (org-table-blank-field))
8881 (save-excursion
8882 (setq txt
8883 (catch 'exit
8884 (while (progn (beginning-of-line 1)
8885 (re-search-backward org-table-dataline-regexp
8886 beg t))
8887 (org-table-goto-column colpos t)
8888 (if (and (looking-at
8889 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8890 (= (setq n (1- n)) 0))
8891 (throw 'exit (match-string 1))))))))
8892 (if txt
8893 (progn
8894 (if (and org-table-copy-increment
8895 (string-match "^[0-9]+$" txt))
8896 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8897 (insert txt)
8898 (move-to-column col)
8899 (if (and org-table-copy-increment (org-at-timestamp-p t))
8900 (org-timestamp-up 1)
8901 (org-table-maybe-recalculate-line))
8902 (org-table-align)
8903 (move-to-column col))
8904 (error "No non-empty field found"))))
8906 (defun org-table-check-inside-data-field ()
8907 "Is point inside a table data field?
8908 I.e. not on a hline or before the first or after the last column?
8909 This actually throws an error, so it aborts the current command."
8910 (if (or (not (org-at-table-p))
8911 (= (org-table-current-column) 0)
8912 (org-at-table-hline-p)
8913 (looking-at "[ \t]*$"))
8914 (error "Not in table data field")))
8916 (defvar org-table-clip nil
8917 "Clipboard for table regions.")
8919 (defun org-table-blank-field ()
8920 "Blank the current table field or active region."
8921 (interactive)
8922 (org-table-check-inside-data-field)
8923 (if (and (interactive-p) (org-region-active-p))
8924 (let (org-table-clip)
8925 (org-table-cut-region (region-beginning) (region-end)))
8926 (skip-chars-backward "^|")
8927 (backward-char 1)
8928 (if (looking-at "|[^|\n]+")
8929 (let* ((pos (match-beginning 0))
8930 (match (match-string 0))
8931 (len (org-string-width match)))
8932 (replace-match (concat "|" (make-string (1- len) ?\ )))
8933 (goto-char (+ 2 pos))
8934 (substring match 1)))))
8936 (defun org-table-get-field (&optional n replace)
8937 "Return the value of the field in column N of current row.
8938 N defaults to current field.
8939 If REPLACE is a string, replace field with this value. The return value
8940 is always the old value."
8941 (and n (org-table-goto-column n))
8942 (skip-chars-backward "^|\n")
8943 (backward-char 1)
8944 (if (looking-at "|[^|\r\n]*")
8945 (let* ((pos (match-beginning 0))
8946 (val (buffer-substring (1+ pos) (match-end 0))))
8947 (if replace
8948 (replace-match (concat "|" replace) t t))
8949 (goto-char (min (point-at-eol) (+ 2 pos)))
8950 val)
8951 (forward-char 1) ""))
8953 (defun org-table-field-info (arg)
8954 "Show info about the current field, and highlight any reference at point."
8955 (interactive "P")
8956 (org-table-get-specials)
8957 (save-excursion
8958 (let* ((pos (point))
8959 (col (org-table-current-column))
8960 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8961 (name (car (rassoc (list (org-current-line) col)
8962 org-table-named-field-locations)))
8963 (eql (org-table-get-stored-formulas))
8964 (dline (org-table-current-dline))
8965 (ref (format "@%d$%d" dline col))
8966 (ref1 (org-table-convert-refs-to-an ref))
8967 (fequation (or (assoc name eql) (assoc ref eql)))
8968 (cequation (assoc (int-to-string col) eql))
8969 (eqn (or fequation cequation)))
8970 (goto-char pos)
8971 (condition-case nil
8972 (org-table-show-reference 'local)
8973 (error nil))
8974 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8975 dline col
8976 (if cname (concat " or $" cname) "")
8977 dline col ref1
8978 (if name (concat " or $" name) "")
8979 ;; FIXME: formula info not correct if special table line
8980 (if eqn
8981 (concat ", formula: "
8982 (org-table-formula-to-user
8983 (concat
8984 (if (string-match "^[$@]"(car eqn)) "" "$")
8985 (car eqn) "=" (cdr eqn))))
8986 "")))))
8988 (defun org-table-current-column ()
8989 "Find out which column we are in.
8990 When called interactively, column is also displayed in echo area."
8991 (interactive)
8992 (if (interactive-p) (org-table-check-inside-data-field))
8993 (save-excursion
8994 (let ((cnt 0) (pos (point)))
8995 (beginning-of-line 1)
8996 (while (search-forward "|" pos t)
8997 (setq cnt (1+ cnt)))
8998 (if (interactive-p) (message "This is table column %d" cnt))
8999 cnt)))
9001 (defun org-table-current-dline ()
9002 "Find out what table data line we are in.
9003 Only datalins count for this."
9004 (interactive)
9005 (if (interactive-p) (org-table-check-inside-data-field))
9006 (save-excursion
9007 (let ((cnt 0) (pos (point)))
9008 (goto-char (org-table-begin))
9009 (while (<= (point) pos)
9010 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9011 (beginning-of-line 2))
9012 (if (interactive-p) (message "This is table line %d" cnt))
9013 cnt)))
9015 (defun org-table-goto-column (n &optional on-delim force)
9016 "Move the cursor to the Nth column in the current table line.
9017 With optional argument ON-DELIM, stop with point before the left delimiter
9018 of the field.
9019 If there are less than N fields, just go to after the last delimiter.
9020 However, when FORCE is non-nil, create new columns if necessary."
9021 (interactive "p")
9022 (let ((pos (point-at-eol)))
9023 (beginning-of-line 1)
9024 (when (> n 0)
9025 (while (and (> (setq n (1- n)) -1)
9026 (or (search-forward "|" pos t)
9027 (and force
9028 (progn (end-of-line 1)
9029 (skip-chars-backward "^|")
9030 (insert " | "))))))
9031 ; (backward-char 2) t)))))
9032 (when (and force (not (looking-at ".*|")))
9033 (save-excursion (end-of-line 1) (insert " | ")))
9034 (if on-delim
9035 (backward-char 1)
9036 (if (looking-at " ") (forward-char 1))))))
9038 (defun org-at-table-p (&optional table-type)
9039 "Return t if the cursor is inside an org-type table.
9040 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9041 (if org-enable-table-editor
9042 (save-excursion
9043 (beginning-of-line 1)
9044 (looking-at (if table-type org-table-any-line-regexp
9045 org-table-line-regexp)))
9046 nil))
9048 (defun org-at-table.el-p ()
9049 "Return t if and only if we are at a table.el table."
9050 (and (org-at-table-p 'any)
9051 (save-excursion
9052 (goto-char (org-table-begin 'any))
9053 (looking-at org-table1-hline-regexp))))
9055 (defun org-table-recognize-table.el ()
9056 "If there is a table.el table nearby, recognize it and move into it."
9057 (if org-table-tab-recognizes-table.el
9058 (if (org-at-table.el-p)
9059 (progn
9060 (beginning-of-line 1)
9061 (if (looking-at org-table-dataline-regexp)
9063 (if (looking-at org-table1-hline-regexp)
9064 (progn
9065 (beginning-of-line 2)
9066 (if (looking-at org-table-any-border-regexp)
9067 (beginning-of-line -1)))))
9068 (if (re-search-forward "|" (org-table-end t) t)
9069 (progn
9070 (require 'table)
9071 (if (table--at-cell-p (point))
9073 (message "recognizing table.el table...")
9074 (table-recognize-table)
9075 (message "recognizing table.el table...done")))
9076 (error "This should not happen..."))
9078 nil)
9079 nil))
9081 (defun org-at-table-hline-p ()
9082 "Return t if the cursor is inside a hline in a table."
9083 (if org-enable-table-editor
9084 (save-excursion
9085 (beginning-of-line 1)
9086 (looking-at org-table-hline-regexp))
9087 nil))
9089 (defun org-table-insert-column ()
9090 "Insert a new column into the table."
9091 (interactive)
9092 (if (not (org-at-table-p))
9093 (error "Not at a table"))
9094 (org-table-find-dataline)
9095 (let* ((col (max 1 (org-table-current-column)))
9096 (beg (org-table-begin))
9097 (end (org-table-end))
9098 ;; Current cursor position
9099 (linepos (org-current-line))
9100 (colpos col))
9101 (goto-char beg)
9102 (while (< (point) end)
9103 (if (org-at-table-hline-p)
9105 (org-table-goto-column col t)
9106 (insert "| "))
9107 (beginning-of-line 2))
9108 (move-marker end nil)
9109 (goto-line linepos)
9110 (org-table-goto-column colpos)
9111 (org-table-align)
9112 (org-table-fix-formulas "$" nil (1- col) 1)))
9114 (defun org-table-find-dataline ()
9115 "Find a dataline in the current table, which is needed for column commands."
9116 (if (and (org-at-table-p)
9117 (not (org-at-table-hline-p)))
9119 (let ((col (current-column))
9120 (end (org-table-end)))
9121 (move-to-column col)
9122 (while (and (< (point) end)
9123 (or (not (= (current-column) col))
9124 (org-at-table-hline-p)))
9125 (beginning-of-line 2)
9126 (move-to-column col))
9127 (if (and (org-at-table-p)
9128 (not (org-at-table-hline-p)))
9130 (error
9131 "Please position cursor in a data line for column operations")))))
9133 (defun org-table-delete-column ()
9134 "Delete a column from the table."
9135 (interactive)
9136 (if (not (org-at-table-p))
9137 (error "Not at a table"))
9138 (org-table-find-dataline)
9139 (org-table-check-inside-data-field)
9140 (let* ((col (org-table-current-column))
9141 (beg (org-table-begin))
9142 (end (org-table-end))
9143 ;; Current cursor position
9144 (linepos (org-current-line))
9145 (colpos col))
9146 (goto-char beg)
9147 (while (< (point) end)
9148 (if (org-at-table-hline-p)
9150 (org-table-goto-column col t)
9151 (and (looking-at "|[^|\n]+|")
9152 (replace-match "|")))
9153 (beginning-of-line 2))
9154 (move-marker end nil)
9155 (goto-line linepos)
9156 (org-table-goto-column colpos)
9157 (org-table-align)
9158 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9159 col -1 col)))
9161 (defun org-table-move-column-right ()
9162 "Move column to the right."
9163 (interactive)
9164 (org-table-move-column nil))
9165 (defun org-table-move-column-left ()
9166 "Move column to the left."
9167 (interactive)
9168 (org-table-move-column 'left))
9170 (defun org-table-move-column (&optional left)
9171 "Move the current column to the right. With arg LEFT, move to the left."
9172 (interactive "P")
9173 (if (not (org-at-table-p))
9174 (error "Not at a table"))
9175 (org-table-find-dataline)
9176 (org-table-check-inside-data-field)
9177 (let* ((col (org-table-current-column))
9178 (col1 (if left (1- col) col))
9179 (beg (org-table-begin))
9180 (end (org-table-end))
9181 ;; Current cursor position
9182 (linepos (org-current-line))
9183 (colpos (if left (1- col) (1+ col))))
9184 (if (and left (= col 1))
9185 (error "Cannot move column further left"))
9186 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9187 (error "Cannot move column further right"))
9188 (goto-char beg)
9189 (while (< (point) end)
9190 (if (org-at-table-hline-p)
9192 (org-table-goto-column col1 t)
9193 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9194 (replace-match "|\\2|\\1|")))
9195 (beginning-of-line 2))
9196 (move-marker end nil)
9197 (goto-line linepos)
9198 (org-table-goto-column colpos)
9199 (org-table-align)
9200 (org-table-fix-formulas
9201 "$" (list (cons (number-to-string col) (number-to-string colpos))
9202 (cons (number-to-string colpos) (number-to-string col))))))
9204 (defun org-table-move-row-down ()
9205 "Move table row down."
9206 (interactive)
9207 (org-table-move-row nil))
9208 (defun org-table-move-row-up ()
9209 "Move table row up."
9210 (interactive)
9211 (org-table-move-row 'up))
9213 (defun org-table-move-row (&optional up)
9214 "Move the current table line down. With arg UP, move it up."
9215 (interactive "P")
9216 (let* ((col (current-column))
9217 (pos (point))
9218 (hline1p (save-excursion (beginning-of-line 1)
9219 (looking-at org-table-hline-regexp)))
9220 (dline1 (org-table-current-dline))
9221 (dline2 (+ dline1 (if up -1 1)))
9222 (tonew (if up 0 2))
9223 txt hline2p)
9224 (beginning-of-line tonew)
9225 (unless (org-at-table-p)
9226 (goto-char pos)
9227 (error "Cannot move row further"))
9228 (setq hline2p (looking-at org-table-hline-regexp))
9229 (goto-char pos)
9230 (beginning-of-line 1)
9231 (setq pos (point))
9232 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9233 (delete-region (point) (1+ (point-at-eol)))
9234 (beginning-of-line tonew)
9235 (insert txt)
9236 (beginning-of-line 0)
9237 (move-to-column col)
9238 (unless (or hline1p hline2p)
9239 (org-table-fix-formulas
9240 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9241 (cons (number-to-string dline2) (number-to-string dline1)))))))
9243 (defun org-table-insert-row (&optional arg)
9244 "Insert a new row above the current line into the table.
9245 With prefix ARG, insert below the current line."
9246 (interactive "P")
9247 (if (not (org-at-table-p))
9248 (error "Not at a table"))
9249 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9250 (new (org-table-clean-line line)))
9251 ;; Fix the first field if necessary
9252 (if (string-match "^[ \t]*| *[#$] *|" line)
9253 (setq new (replace-match (match-string 0 line) t t new)))
9254 (beginning-of-line (if arg 2 1))
9255 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9256 (beginning-of-line 0)
9257 (re-search-forward "| ?" (point-at-eol) t)
9258 (and (or org-table-may-need-update org-table-overlay-coordinates)
9259 (org-table-align))
9260 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9262 (defun org-table-insert-hline (&optional above)
9263 "Insert a horizontal-line below the current line into the table.
9264 With prefix ABOVE, insert above the current line."
9265 (interactive "P")
9266 (if (not (org-at-table-p))
9267 (error "Not at a table"))
9268 (let ((line (org-table-clean-line
9269 (buffer-substring (point-at-bol) (point-at-eol))))
9270 (col (current-column)))
9271 (while (string-match "|\\( +\\)|" line)
9272 (setq line (replace-match
9273 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9274 ?-) "|") t t line)))
9275 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9276 (beginning-of-line (if above 1 2))
9277 (insert line "\n")
9278 (beginning-of-line (if above 1 -1))
9279 (move-to-column col)
9280 (and org-table-overlay-coordinates (org-table-align))))
9282 (defun org-table-hline-and-move (&optional same-column)
9283 "Insert a hline and move to the row below that line."
9284 (interactive "P")
9285 (let ((col (org-table-current-column)))
9286 (org-table-maybe-eval-formula)
9287 (org-table-maybe-recalculate-line)
9288 (org-table-insert-hline)
9289 (end-of-line 2)
9290 (if (looking-at "\n[ \t]*|-")
9291 (progn (insert "\n|") (org-table-align))
9292 (org-table-next-field))
9293 (if same-column (org-table-goto-column col))))
9295 (defun org-table-clean-line (s)
9296 "Convert a table line S into a string with only \"|\" and space.
9297 In particular, this does handle wide and invisible characters."
9298 (if (string-match "^[ \t]*|-" s)
9299 ;; It's a hline, just map the characters
9300 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9301 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9302 (setq s (replace-match
9303 (concat "|" (make-string (org-string-width (match-string 1 s))
9304 ?\ ) "|")
9305 t t s)))
9308 (defun org-table-kill-row ()
9309 "Delete the current row or horizontal line from the table."
9310 (interactive)
9311 (if (not (org-at-table-p))
9312 (error "Not at a table"))
9313 (let ((col (current-column))
9314 (dline (org-table-current-dline)))
9315 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9316 (if (not (org-at-table-p)) (beginning-of-line 0))
9317 (move-to-column col)
9318 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9319 dline -1 dline)))
9321 (defun org-table-sort-lines (with-case &optional sorting-type)
9322 "Sort table lines according to the column at point.
9324 The position of point indicates the column to be used for
9325 sorting, and the range of lines is the range between the nearest
9326 horizontal separator lines, or the entire table of no such lines
9327 exist. If point is before the first column, you will be prompted
9328 for the sorting column. If there is an active region, the mark
9329 specifies the first line and the sorting column, while point
9330 should be in the last line to be included into the sorting.
9332 The command then prompts for the sorting type which can be
9333 alphabetically, numerically, or by time (as given in a time stamp
9334 in the field). Sorting in reverse order is also possible.
9336 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9338 If SORTING-TYPE is specified when this function is called from a Lisp
9339 program, no prompting will take place. SORTING-TYPE must be a character,
9340 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9341 should be done in reverse order."
9342 (interactive "P")
9343 (let* ((thisline (org-current-line))
9344 (thiscol (org-table-current-column))
9345 beg end bcol ecol tend tbeg column lns pos)
9346 (when (equal thiscol 0)
9347 (if (interactive-p)
9348 (setq thiscol
9349 (string-to-number
9350 (read-string "Use column N for sorting: ")))
9351 (setq thiscol 1))
9352 (org-table-goto-column thiscol))
9353 (org-table-check-inside-data-field)
9354 (if (org-region-active-p)
9355 (progn
9356 (setq beg (region-beginning) end (region-end))
9357 (goto-char beg)
9358 (setq column (org-table-current-column)
9359 beg (point-at-bol))
9360 (goto-char end)
9361 (setq end (point-at-bol 2)))
9362 (setq column (org-table-current-column)
9363 pos (point)
9364 tbeg (org-table-begin)
9365 tend (org-table-end))
9366 (if (re-search-backward org-table-hline-regexp tbeg t)
9367 (setq beg (point-at-bol 2))
9368 (goto-char tbeg)
9369 (setq beg (point-at-bol 1)))
9370 (goto-char pos)
9371 (if (re-search-forward org-table-hline-regexp tend t)
9372 (setq end (point-at-bol 1))
9373 (goto-char tend)
9374 (setq end (point-at-bol))))
9375 (setq beg (move-marker (make-marker) beg)
9376 end (move-marker (make-marker) end))
9377 (untabify beg end)
9378 (goto-char beg)
9379 (org-table-goto-column column)
9380 (skip-chars-backward "^|")
9381 (setq bcol (current-column))
9382 (org-table-goto-column (1+ column))
9383 (skip-chars-backward "^|")
9384 (setq ecol (1- (current-column)))
9385 (org-table-goto-column column)
9386 (setq lns (mapcar (lambda(x) (cons
9387 (org-sort-remove-invisible
9388 (nth (1- column)
9389 (org-split-string x "[ \t]*|[ \t]*")))
9391 (org-split-string (buffer-substring beg end) "\n")))
9392 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9393 (delete-region beg end)
9394 (move-marker beg nil)
9395 (move-marker end nil)
9396 (insert (mapconcat 'cdr lns "\n") "\n")
9397 (goto-line thisline)
9398 (org-table-goto-column thiscol)
9399 (message "%d lines sorted, based on column %d" (length lns) column)))
9401 ;; FIXME: maybe we will not need this? Table sorting is broken....
9402 (defun org-sort-remove-invisible (s)
9403 (remove-text-properties 0 (length s) org-rm-props s)
9404 (while (string-match org-bracket-link-regexp s)
9405 (setq s (replace-match (if (match-end 2)
9406 (match-string 3 s)
9407 (match-string 1 s)) t t s)))
9410 (defun org-table-cut-region (beg end)
9411 "Copy region in table to the clipboard and blank all relevant fields."
9412 (interactive "r")
9413 (org-table-copy-region beg end 'cut))
9415 (defun org-table-copy-region (beg end &optional cut)
9416 "Copy rectangular region in table to clipboard.
9417 A special clipboard is used which can only be accessed
9418 with `org-table-paste-rectangle'."
9419 (interactive "rP")
9420 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9421 region cols
9422 (rpl (if cut " " nil)))
9423 (goto-char beg)
9424 (org-table-check-inside-data-field)
9425 (setq l01 (org-current-line)
9426 c01 (org-table-current-column))
9427 (goto-char end)
9428 (org-table-check-inside-data-field)
9429 (setq l02 (org-current-line)
9430 c02 (org-table-current-column))
9431 (setq l1 (min l01 l02) l2 (max l01 l02)
9432 c1 (min c01 c02) c2 (max c01 c02))
9433 (catch 'exit
9434 (while t
9435 (catch 'nextline
9436 (if (> l1 l2) (throw 'exit t))
9437 (goto-line l1)
9438 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9439 (setq cols nil ic1 c1 ic2 c2)
9440 (while (< ic1 (1+ ic2))
9441 (push (org-table-get-field ic1 rpl) cols)
9442 (setq ic1 (1+ ic1)))
9443 (push (nreverse cols) region)
9444 (setq l1 (1+ l1)))))
9445 (setq org-table-clip (nreverse region))
9446 (if cut (org-table-align))
9447 org-table-clip))
9449 (defun org-table-paste-rectangle ()
9450 "Paste a rectangular region into a table.
9451 The upper right corner ends up in the current field. All involved fields
9452 will be overwritten. If the rectangle does not fit into the present table,
9453 the table is enlarged as needed. The process ignores horizontal separator
9454 lines."
9455 (interactive)
9456 (unless (and org-table-clip (listp org-table-clip))
9457 (error "First cut/copy a region to paste!"))
9458 (org-table-check-inside-data-field)
9459 (let* ((clip org-table-clip)
9460 (line (org-current-line))
9461 (col (org-table-current-column))
9462 (org-enable-table-editor t)
9463 (org-table-automatic-realign nil)
9464 c cols field)
9465 (while (setq cols (pop clip))
9466 (while (org-at-table-hline-p) (beginning-of-line 2))
9467 (if (not (org-at-table-p))
9468 (progn (end-of-line 0) (org-table-next-field)))
9469 (setq c col)
9470 (while (setq field (pop cols))
9471 (org-table-goto-column c nil 'force)
9472 (org-table-get-field nil field)
9473 (setq c (1+ c)))
9474 (beginning-of-line 2))
9475 (goto-line line)
9476 (org-table-goto-column col)
9477 (org-table-align)))
9479 (defun org-table-convert ()
9480 "Convert from `org-mode' table to table.el and back.
9481 Obviously, this only works within limits. When an Org-mode table is
9482 converted to table.el, all horizontal separator lines get lost, because
9483 table.el uses these as cell boundaries and has no notion of horizontal lines.
9484 A table.el table can be converted to an Org-mode table only if it does not
9485 do row or column spanning. Multiline cells will become multiple cells.
9486 Beware, Org-mode does not test if the table can be successfully converted - it
9487 blindly applies a recipe that works for simple tables."
9488 (interactive)
9489 (require 'table)
9490 (if (org-at-table.el-p)
9491 ;; convert to Org-mode table
9492 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9493 (end (move-marker (make-marker) (org-table-end t))))
9494 (table-unrecognize-region beg end)
9495 (goto-char beg)
9496 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9497 (replace-match ""))
9498 (goto-char beg))
9499 (if (org-at-table-p)
9500 ;; convert to table.el table
9501 (let ((beg (move-marker (make-marker) (org-table-begin)))
9502 (end (move-marker (make-marker) (org-table-end))))
9503 ;; first, get rid of all horizontal lines
9504 (goto-char beg)
9505 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9506 (replace-match ""))
9507 ;; insert a hline before first
9508 (goto-char beg)
9509 (org-table-insert-hline 'above)
9510 (beginning-of-line -1)
9511 ;; insert a hline after each line
9512 (while (progn (beginning-of-line 3) (< (point) end))
9513 (org-table-insert-hline))
9514 (goto-char beg)
9515 (setq end (move-marker end (org-table-end)))
9516 ;; replace "+" at beginning and ending of hlines
9517 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9518 (replace-match "\\1+-"))
9519 (goto-char beg)
9520 (while (re-search-forward "-|[ \t]*$" end t)
9521 (replace-match "-+"))
9522 (goto-char beg)))))
9524 (defun org-table-wrap-region (arg)
9525 "Wrap several fields in a column like a paragraph.
9526 This is useful if you'd like to spread the contents of a field over several
9527 lines, in order to keep the table compact.
9529 If there is an active region, and both point and mark are in the same column,
9530 the text in the column is wrapped to minimum width for the given number of
9531 lines. Generally, this makes the table more compact. A prefix ARG may be
9532 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9533 formats the selected text to two lines. If the region was longer than two
9534 lines, the remaining lines remain empty. A negative prefix argument reduces
9535 the current number of lines by that amount. The wrapped text is pasted back
9536 into the table. If you formatted it to more lines than it was before, fields
9537 further down in the table get overwritten - so you might need to make space in
9538 the table first.
9540 If there is no region, the current field is split at the cursor position and
9541 the text fragment to the right of the cursor is prepended to the field one
9542 line down.
9544 If there is no region, but you specify a prefix ARG, the current field gets
9545 blank, and the content is appended to the field above."
9546 (interactive "P")
9547 (org-table-check-inside-data-field)
9548 (if (org-region-active-p)
9549 ;; There is a region: fill as a paragraph
9550 (let* ((beg (region-beginning))
9551 (cline (save-excursion (goto-char beg) (org-current-line)))
9552 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9553 nlines)
9554 (org-table-cut-region (region-beginning) (region-end))
9555 (if (> (length (car org-table-clip)) 1)
9556 (error "Region must be limited to single column"))
9557 (setq nlines (if arg
9558 (if (< arg 1)
9559 (+ (length org-table-clip) arg)
9560 arg)
9561 (length org-table-clip)))
9562 (setq org-table-clip
9563 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9564 nil nlines)))
9565 (goto-line cline)
9566 (org-table-goto-column ccol)
9567 (org-table-paste-rectangle))
9568 ;; No region, split the current field at point
9569 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9570 (skip-chars-forward "^\r\n|"))
9571 (if arg
9572 ;; combine with field above
9573 (let ((s (org-table-blank-field))
9574 (col (org-table-current-column)))
9575 (beginning-of-line 0)
9576 (while (org-at-table-hline-p) (beginning-of-line 0))
9577 (org-table-goto-column col)
9578 (skip-chars-forward "^|")
9579 (skip-chars-backward " ")
9580 (insert " " (org-trim s))
9581 (org-table-align))
9582 ;; split field
9583 (if (looking-at "\\([^|]+\\)+|")
9584 (let ((s (match-string 1)))
9585 (replace-match " |")
9586 (goto-char (match-beginning 0))
9587 (org-table-next-row)
9588 (insert (org-trim s) " ")
9589 (org-table-align))
9590 (org-table-next-row)))))
9592 (defvar org-field-marker nil)
9594 (defun org-table-edit-field (arg)
9595 "Edit table field in a different window.
9596 This is mainly useful for fields that contain hidden parts.
9597 When called with a \\[universal-argument] prefix, just make the full field visible so that
9598 it can be edited in place."
9599 (interactive "P")
9600 (if arg
9601 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9602 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9603 (remove-text-properties b e '(org-cwidth t invisible t
9604 display t intangible t))
9605 (if (and (boundp 'font-lock-mode) font-lock-mode)
9606 (font-lock-fontify-block)))
9607 (let ((pos (move-marker (make-marker) (point)))
9608 (field (org-table-get-field))
9609 (cw (current-window-configuration))
9611 (org-switch-to-buffer-other-window "*Org tmp*")
9612 (erase-buffer)
9613 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9614 (let ((org-inhibit-startup t)) (org-mode))
9615 (goto-char (setq p (point-max)))
9616 (insert (org-trim field))
9617 (remove-text-properties p (point-max)
9618 '(invisible t org-cwidth t display t
9619 intangible t))
9620 (goto-char p)
9621 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9622 (org-set-local 'org-window-configuration cw)
9623 (org-set-local 'org-field-marker pos)
9624 (message "Edit and finish with C-c C-c"))))
9626 (defun org-table-finish-edit-field ()
9627 "Finish editing a table data field.
9628 Remove all newline characters, insert the result into the table, realign
9629 the table and kill the editing buffer."
9630 (let ((pos org-field-marker)
9631 (cw org-window-configuration)
9632 (cb (current-buffer))
9633 text)
9634 (goto-char (point-min))
9635 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9636 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9637 (replace-match " "))
9638 (setq text (org-trim (buffer-string)))
9639 (set-window-configuration cw)
9640 (kill-buffer cb)
9641 (select-window (get-buffer-window (marker-buffer pos)))
9642 (goto-char pos)
9643 (move-marker pos nil)
9644 (org-table-check-inside-data-field)
9645 (org-table-get-field nil text)
9646 (org-table-align)
9647 (message "New field value inserted")))
9649 (defun org-trim (s)
9650 "Remove whitespace at beginning and end of string."
9651 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9652 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9655 (defun org-wrap (string &optional width lines)
9656 "Wrap string to either a number of lines, or a width in characters.
9657 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9658 that costs. If there is a word longer than WIDTH, the text is actually
9659 wrapped to the length of that word.
9660 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9661 many lines, whatever width that takes.
9662 The return value is a list of lines, without newlines at the end."
9663 (let* ((words (org-split-string string "[ \t\n]+"))
9664 (maxword (apply 'max (mapcar 'org-string-width words)))
9665 w ll)
9666 (cond (width
9667 (org-do-wrap words (max maxword width)))
9668 (lines
9669 (setq w maxword)
9670 (setq ll (org-do-wrap words maxword))
9671 (if (<= (length ll) lines)
9673 (setq ll words)
9674 (while (> (length ll) lines)
9675 (setq w (1+ w))
9676 (setq ll (org-do-wrap words w)))
9677 ll))
9678 (t (error "Cannot wrap this")))))
9681 (defun org-do-wrap (words width)
9682 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9683 (let (lines line)
9684 (while words
9685 (setq line (pop words))
9686 (while (and words (< (+ (length line) (length (car words))) width))
9687 (setq line (concat line " " (pop words))))
9688 (setq lines (push line lines)))
9689 (nreverse lines)))
9691 (defun org-split-string (string &optional separators)
9692 "Splits STRING into substrings at SEPARATORS.
9693 No empty strings are returned if there are matches at the beginning
9694 and end of string."
9695 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9696 (start 0)
9697 notfirst
9698 (list nil))
9699 (while (and (string-match rexp string
9700 (if (and notfirst
9701 (= start (match-beginning 0))
9702 (< start (length string)))
9703 (1+ start) start))
9704 (< (match-beginning 0) (length string)))
9705 (setq notfirst t)
9706 (or (eq (match-beginning 0) 0)
9707 (and (eq (match-beginning 0) (match-end 0))
9708 (eq (match-beginning 0) start))
9709 (setq list
9710 (cons (substring string start (match-beginning 0))
9711 list)))
9712 (setq start (match-end 0)))
9713 (or (eq start (length string))
9714 (setq list
9715 (cons (substring string start)
9716 list)))
9717 (nreverse list)))
9719 (defun org-table-map-tables (function)
9720 "Apply FUNCTION to the start of all tables in the buffer."
9721 (save-excursion
9722 (save-restriction
9723 (widen)
9724 (goto-char (point-min))
9725 (while (re-search-forward org-table-any-line-regexp nil t)
9726 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9727 (beginning-of-line 1)
9728 (if (looking-at org-table-line-regexp)
9729 (save-excursion (funcall function)))
9730 (re-search-forward org-table-any-border-regexp nil 1))))
9731 (message "Mapping tables: done"))
9733 (defvar org-timecnt) ; dynamically scoped parameter
9735 (defun org-table-sum (&optional beg end nlast)
9736 "Sum numbers in region of current table column.
9737 The result will be displayed in the echo area, and will be available
9738 as kill to be inserted with \\[yank].
9740 If there is an active region, it is interpreted as a rectangle and all
9741 numbers in that rectangle will be summed. If there is no active
9742 region and point is located in a table column, sum all numbers in that
9743 column.
9745 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9746 numbers are assumed to be times as well (in decimal hours) and the
9747 numbers are added as such.
9749 If NLAST is a number, only the NLAST fields will actually be summed."
9750 (interactive)
9751 (save-excursion
9752 (let (col (org-timecnt 0) diff h m s org-table-clip)
9753 (cond
9754 ((and beg end)) ; beg and end given explicitly
9755 ((org-region-active-p)
9756 (setq beg (region-beginning) end (region-end)))
9758 (setq col (org-table-current-column))
9759 (goto-char (org-table-begin))
9760 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9761 (error "No table data"))
9762 (org-table-goto-column col)
9763 (setq beg (point))
9764 (goto-char (org-table-end))
9765 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9766 (error "No table data"))
9767 (org-table-goto-column col)
9768 (setq end (point))))
9769 (let* ((items (apply 'append (org-table-copy-region beg end)))
9770 (items1 (cond ((not nlast) items)
9771 ((>= nlast (length items)) items)
9772 (t (setq items (reverse items))
9773 (setcdr (nthcdr (1- nlast) items) nil)
9774 (nreverse items))))
9775 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9776 items1)))
9777 (res (apply '+ numbers))
9778 (sres (if (= org-timecnt 0)
9779 (format "%g" res)
9780 (setq diff (* 3600 res)
9781 h (floor (/ diff 3600)) diff (mod diff 3600)
9782 m (floor (/ diff 60)) diff (mod diff 60)
9783 s diff)
9784 (format "%d:%02d:%02d" h m s))))
9785 (kill-new sres)
9786 (if (interactive-p)
9787 (message "%s"
9788 (substitute-command-keys
9789 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9790 (length numbers) sres))))
9791 sres))))
9793 (defun org-table-get-number-for-summing (s)
9794 (let (n)
9795 (if (string-match "^ *|? *" s)
9796 (setq s (replace-match "" nil nil s)))
9797 (if (string-match " *|? *$" s)
9798 (setq s (replace-match "" nil nil s)))
9799 (setq n (string-to-number s))
9800 (cond
9801 ((and (string-match "0" s)
9802 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9803 ((string-match "\\`[ \t]+\\'" s) nil)
9804 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9805 (let ((h (string-to-number (or (match-string 1 s) "0")))
9806 (m (string-to-number (or (match-string 2 s) "0")))
9807 (s (string-to-number (or (match-string 4 s) "0"))))
9808 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9809 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9810 ((equal n 0) nil)
9811 (t n))))
9813 (defun org-table-current-field-formula (&optional key noerror)
9814 "Return the formula active for the current field.
9815 Assumes that specials are in place.
9816 If KEY is given, return the key to this formula.
9817 Otherwise return the formula preceeded with \"=\" or \":=\"."
9818 (let* ((name (car (rassoc (list (org-current-line)
9819 (org-table-current-column))
9820 org-table-named-field-locations)))
9821 (col (org-table-current-column))
9822 (scol (int-to-string col))
9823 (ref (format "@%d$%d" (org-table-current-dline) col))
9824 (stored-list (org-table-get-stored-formulas noerror))
9825 (ass (or (assoc name stored-list)
9826 (assoc ref stored-list)
9827 (assoc scol stored-list))))
9828 (if key
9829 (car ass)
9830 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9831 (cdr ass))))))
9833 (defun org-table-get-formula (&optional equation named)
9834 "Read a formula from the minibuffer, offer stored formula as default.
9835 When NAMED is non-nil, look for a named equation."
9836 (let* ((stored-list (org-table-get-stored-formulas))
9837 (name (car (rassoc (list (org-current-line)
9838 (org-table-current-column))
9839 org-table-named-field-locations)))
9840 (ref (format "@%d$%d" (org-table-current-dline)
9841 (org-table-current-column)))
9842 (refass (assoc ref stored-list))
9843 (scol (if named
9844 (if name name ref)
9845 (int-to-string (org-table-current-column))))
9846 (dummy (and (or name refass) (not named)
9847 (not (y-or-n-p "Replace field formula with column formula? " ))
9848 (error "Abort")))
9849 (name (or name ref))
9850 (org-table-may-need-update nil)
9851 (stored (cdr (assoc scol stored-list)))
9852 (eq (cond
9853 ((and stored equation (string-match "^ *=? *$" equation))
9854 stored)
9855 ((stringp equation)
9856 equation)
9857 (t (org-table-formula-from-user
9858 (read-string
9859 (org-table-formula-to-user
9860 (format "%s formula %s%s="
9861 (if named "Field" "Column")
9862 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9863 scol))
9864 (if stored (org-table-formula-to-user stored) "")
9865 'org-table-formula-history
9866 )))))
9867 mustsave)
9868 (when (not (string-match "\\S-" eq))
9869 ;; remove formula
9870 (setq stored-list (delq (assoc scol stored-list) stored-list))
9871 (org-table-store-formulas stored-list)
9872 (error "Formula removed"))
9873 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9874 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9875 (if (and name (not named))
9876 ;; We set the column equation, delete the named one.
9877 (setq stored-list (delq (assoc name stored-list) stored-list)
9878 mustsave t))
9879 (if stored
9880 (setcdr (assoc scol stored-list) eq)
9881 (setq stored-list (cons (cons scol eq) stored-list)))
9882 (if (or mustsave (not (equal stored eq)))
9883 (org-table-store-formulas stored-list))
9884 eq))
9886 (defun org-table-store-formulas (alist)
9887 "Store the list of formulas below the current table."
9888 (setq alist (sort alist 'org-table-formula-less-p))
9889 (save-excursion
9890 (goto-char (org-table-end))
9891 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9892 (progn
9893 ;; don't overwrite TBLFM, we might use text properties to store stuff
9894 (goto-char (match-beginning 2))
9895 (delete-region (match-beginning 2) (match-end 0)))
9896 (insert "#+TBLFM:"))
9897 (insert " "
9898 (mapconcat (lambda (x)
9899 (concat
9900 (if (equal (string-to-char (car x)) ?@) "" "$")
9901 (car x) "=" (cdr x)))
9902 alist "::")
9903 "\n")))
9905 (defsubst org-table-formula-make-cmp-string (a)
9906 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9907 (concat
9908 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9909 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9910 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9912 (defun org-table-formula-less-p (a b)
9913 "Compare two formulas for sorting."
9914 (let ((as (org-table-formula-make-cmp-string (car a)))
9915 (bs (org-table-formula-make-cmp-string (car b))))
9916 (and as bs (string< as bs))))
9918 (defun org-table-get-stored-formulas (&optional noerror)
9919 "Return an alist with the stored formulas directly after current table."
9920 (interactive)
9921 (let (scol eq eq-alist strings string seen)
9922 (save-excursion
9923 (goto-char (org-table-end))
9924 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9925 (setq strings (org-split-string (match-string 2) " *:: *"))
9926 (while (setq string (pop strings))
9927 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9928 (setq scol (if (match-end 2)
9929 (match-string 2 string)
9930 (match-string 1 string))
9931 eq (match-string 3 string)
9932 eq-alist (cons (cons scol eq) eq-alist))
9933 (if (member scol seen)
9934 (if noerror
9935 (progn
9936 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9937 (ding)
9938 (sit-for 2))
9939 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9940 (push scol seen))))))
9941 (nreverse eq-alist)))
9943 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9944 "Modify the equations after the table structure has been edited.
9945 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9946 For all numbers larger than LIMIT, shift them by DELTA."
9947 (save-excursion
9948 (goto-char (org-table-end))
9949 (when (looking-at "#\\+TBLFM:")
9950 (let ((re (concat key "\\([0-9]+\\)"))
9951 (re2
9952 (when remove
9953 (if (equal key "$")
9954 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9955 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9956 s n a)
9957 (when remove
9958 (while (re-search-forward re2 (point-at-eol) t)
9959 (replace-match "")))
9960 (while (re-search-forward re (point-at-eol) t)
9961 (setq s (match-string 1) n (string-to-number s))
9962 (cond
9963 ((setq a (assoc s replace))
9964 (replace-match (concat key (cdr a)) t t))
9965 ((and limit (> n limit))
9966 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9968 (defun org-table-get-specials ()
9969 "Get the column names and local parameters for this table."
9970 (save-excursion
9971 (let ((beg (org-table-begin)) (end (org-table-end))
9972 names name fields fields1 field cnt
9973 c v l line col types dlines hlines)
9974 (setq org-table-column-names nil
9975 org-table-local-parameters nil
9976 org-table-named-field-locations nil
9977 org-table-current-begin-line nil
9978 org-table-current-begin-pos nil
9979 org-table-current-line-types nil)
9980 (goto-char beg)
9981 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9982 (setq names (org-split-string (match-string 1) " *| *")
9983 cnt 1)
9984 (while (setq name (pop names))
9985 (setq cnt (1+ cnt))
9986 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9987 (push (cons name (int-to-string cnt)) org-table-column-names))))
9988 (setq org-table-column-names (nreverse org-table-column-names))
9989 (setq org-table-column-name-regexp
9990 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9991 (goto-char beg)
9992 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9993 (setq fields (org-split-string (match-string 1) " *| *"))
9994 (while (setq field (pop fields))
9995 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9996 (push (cons (match-string 1 field) (match-string 2 field))
9997 org-table-local-parameters))))
9998 (goto-char beg)
9999 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10000 (setq c (match-string 1)
10001 fields (org-split-string (match-string 2) " *| *"))
10002 (save-excursion
10003 (beginning-of-line (if (equal c "_") 2 0))
10004 (setq line (org-current-line) col 1)
10005 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10006 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10007 (while (and fields1 (setq field (pop fields)))
10008 (setq v (pop fields1) col (1+ col))
10009 (when (and (stringp field) (stringp v)
10010 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10011 (push (cons field v) org-table-local-parameters)
10012 (push (list field line col) org-table-named-field-locations))))
10013 ;; Analyse the line types
10014 (goto-char beg)
10015 (setq org-table-current-begin-line (org-current-line)
10016 org-table-current-begin-pos (point)
10017 l org-table-current-begin-line)
10018 (while (looking-at "[ \t]*|\\(-\\)?")
10019 (push (if (match-end 1) 'hline 'dline) types)
10020 (if (match-end 1) (push l hlines) (push l dlines))
10021 (beginning-of-line 2)
10022 (setq l (1+ l)))
10023 (setq org-table-current-line-types (apply 'vector (nreverse types))
10024 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10025 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10027 (defun org-table-maybe-eval-formula ()
10028 "Check if the current field starts with \"=\" or \":=\".
10029 If yes, store the formula and apply it."
10030 ;; We already know we are in a table. Get field will only return a formula
10031 ;; when appropriate. It might return a separator line, but no problem.
10032 (when org-table-formula-evaluate-inline
10033 (let* ((field (org-trim (or (org-table-get-field) "")))
10034 named eq)
10035 (when (string-match "^:?=\\(.*\\)" field)
10036 (setq named (equal (string-to-char field) ?:)
10037 eq (match-string 1 field))
10038 (if (or (fboundp 'calc-eval)
10039 (equal (substring eq 0 (min 2 (length eq))) "'("))
10040 (org-table-eval-formula (if named '(4) nil)
10041 (org-table-formula-from-user eq))
10042 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10044 (defvar org-recalc-commands nil
10045 "List of commands triggering the recalculation of a line.
10046 Will be filled automatically during use.")
10048 (defvar org-recalc-marks
10049 '((" " . "Unmarked: no special line, no automatic recalculation")
10050 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10051 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10052 ("!" . "Column name definition line. Reference in formula as $name.")
10053 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10054 ("_" . "Names for values in row below this one.")
10055 ("^" . "Names for values in row above this one.")))
10057 (defun org-table-rotate-recalc-marks (&optional newchar)
10058 "Rotate the recalculation mark in the first column.
10059 If in any row, the first field is not consistent with a mark,
10060 insert a new column for the markers.
10061 When there is an active region, change all the lines in the region,
10062 after prompting for the marking character.
10063 After each change, a message will be displayed indicating the meaning
10064 of the new mark."
10065 (interactive)
10066 (unless (org-at-table-p) (error "Not at a table"))
10067 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10068 (beg (org-table-begin))
10069 (end (org-table-end))
10070 (l (org-current-line))
10071 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10072 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10073 (have-col
10074 (save-excursion
10075 (goto-char beg)
10076 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10077 (col (org-table-current-column))
10078 (forcenew (car (assoc newchar org-recalc-marks)))
10079 epos new)
10080 (when l1
10081 (message "Change region to what mark? Type # * ! $ or SPC: ")
10082 (setq newchar (char-to-string (read-char-exclusive))
10083 forcenew (car (assoc newchar org-recalc-marks))))
10084 (if (and newchar (not forcenew))
10085 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10086 newchar))
10087 (if l1 (goto-line l1))
10088 (save-excursion
10089 (beginning-of-line 1)
10090 (unless (looking-at org-table-dataline-regexp)
10091 (error "Not at a table data line")))
10092 (unless have-col
10093 (org-table-goto-column 1)
10094 (org-table-insert-column)
10095 (org-table-goto-column (1+ col)))
10096 (setq epos (point-at-eol))
10097 (save-excursion
10098 (beginning-of-line 1)
10099 (org-table-get-field
10100 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10101 (concat " "
10102 (setq new (or forcenew
10103 (cadr (member (match-string 1) marks))))
10104 " ")
10105 " # ")))
10106 (if (and l1 l2)
10107 (progn
10108 (goto-line l1)
10109 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10110 (and (looking-at org-table-dataline-regexp)
10111 (org-table-get-field 1 (concat " " new " "))))
10112 (goto-line l1)))
10113 (if (not (= epos (point-at-eol))) (org-table-align))
10114 (goto-line l)
10115 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10117 (defun org-table-maybe-recalculate-line ()
10118 "Recompute the current line if marked for it, and if we haven't just done it."
10119 (interactive)
10120 (and org-table-allow-automatic-line-recalculation
10121 (not (and (memq last-command org-recalc-commands)
10122 (equal org-last-recalc-line (org-current-line))))
10123 (save-excursion (beginning-of-line 1)
10124 (looking-at org-table-auto-recalculate-regexp))
10125 (org-table-recalculate) t))
10127 (defvar org-table-formula-debug nil
10128 "Non-nil means, debug table formulas.
10129 When nil, simply write \"#ERROR\" in corrupted fields.")
10130 (make-variable-buffer-local 'org-table-formula-debug)
10132 (defvar modes)
10133 (defsubst org-set-calc-mode (var &optional value)
10134 (if (stringp var)
10135 (setq var (assoc var '(("D" calc-angle-mode deg)
10136 ("R" calc-angle-mode rad)
10137 ("F" calc-prefer-frac t)
10138 ("S" calc-symbolic-mode t)))
10139 value (nth 2 var) var (nth 1 var)))
10140 (if (memq var modes)
10141 (setcar (cdr (memq var modes)) value)
10142 (cons var (cons value modes)))
10143 modes)
10145 (defun org-table-eval-formula (&optional arg equation
10146 suppress-align suppress-const
10147 suppress-store suppress-analysis)
10148 "Replace the table field value at the cursor by the result of a calculation.
10150 This function makes use of Dave Gillespie's Calc package, in my view the
10151 most exciting program ever written for GNU Emacs. So you need to have Calc
10152 installed in order to use this function.
10154 In a table, this command replaces the value in the current field with the
10155 result of a formula. It also installs the formula as the \"current\" column
10156 formula, by storing it in a special line below the table. When called
10157 with a `C-u' prefix, the current field must ba a named field, and the
10158 formula is installed as valid in only this specific field.
10160 When called with two `C-u' prefixes, insert the active equation
10161 for the field back into the current field, so that it can be
10162 edited there. This is useful in order to use \\[org-table-show-reference]
10163 to check the referenced fields.
10165 When called, the command first prompts for a formula, which is read in
10166 the minibuffer. Previously entered formulas are available through the
10167 history list, and the last used formula is offered as a default.
10168 These stored formulas are adapted correctly when moving, inserting, or
10169 deleting columns with the corresponding commands.
10171 The formula can be any algebraic expression understood by the Calc package.
10172 For details, see the Org-mode manual.
10174 This function can also be called from Lisp programs and offers
10175 additional arguments: EQUATION can be the formula to apply. If this
10176 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10177 used to speed-up recursive calls by by-passing unnecessary aligns.
10178 SUPPRESS-CONST suppresses the interpretation of constants in the
10179 formula, assuming that this has been done already outside the function.
10180 SUPPRESS-STORE means the formula should not be stored, either because
10181 it is already stored, or because it is a modified equation that should
10182 not overwrite the stored one."
10183 (interactive "P")
10184 (org-table-check-inside-data-field)
10185 (or suppress-analysis (org-table-get-specials))
10186 (if (equal arg '(16))
10187 (let ((eq (org-table-current-field-formula)))
10188 (or eq (error "No equation active for current field"))
10189 (org-table-get-field nil eq)
10190 (org-table-align)
10191 (setq org-table-may-need-update t))
10192 (let* (fields
10193 (ndown (if (integerp arg) arg 1))
10194 (org-table-automatic-realign nil)
10195 (case-fold-search nil)
10196 (down (> ndown 1))
10197 (formula (if (and equation suppress-store)
10198 equation
10199 (org-table-get-formula equation (equal arg '(4)))))
10200 (n0 (org-table-current-column))
10201 (modes (copy-sequence org-calc-default-modes))
10202 (numbers nil) ; was a variable, now fixed default
10203 (keep-empty nil)
10204 n form form0 bw fmt x ev orig c lispp literal)
10205 ;; Parse the format string. Since we have a lot of modes, this is
10206 ;; a lot of work. However, I think calc still uses most of the time.
10207 (if (string-match ";" formula)
10208 (let ((tmp (org-split-string formula ";")))
10209 (setq formula (car tmp)
10210 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10211 (nth 1 tmp)))
10212 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10213 (setq c (string-to-char (match-string 1 fmt))
10214 n (string-to-number (match-string 2 fmt)))
10215 (if (= c ?p)
10216 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10217 (setq modes (org-set-calc-mode
10218 'calc-float-format
10219 (list (cdr (assoc c '((?n . float) (?f . fix)
10220 (?s . sci) (?e . eng))))
10221 n))))
10222 (setq fmt (replace-match "" t t fmt)))
10223 (if (string-match "[NT]" fmt)
10224 (setq numbers (equal (match-string 0 fmt) "N")
10225 fmt (replace-match "" t t fmt)))
10226 (if (string-match "L" fmt)
10227 (setq literal t
10228 fmt (replace-match "" t t fmt)))
10229 (if (string-match "E" fmt)
10230 (setq keep-empty t
10231 fmt (replace-match "" t t fmt)))
10232 (while (string-match "[DRFS]" fmt)
10233 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10234 (setq fmt (replace-match "" t t fmt)))
10235 (unless (string-match "\\S-" fmt)
10236 (setq fmt nil))))
10237 (if (and (not suppress-const) org-table-formula-use-constants)
10238 (setq formula (org-table-formula-substitute-names formula)))
10239 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10240 (while (> ndown 0)
10241 (setq fields (org-split-string
10242 (org-no-properties
10243 (buffer-substring (point-at-bol) (point-at-eol)))
10244 " *| *"))
10245 (if (eq numbers t)
10246 (setq fields (mapcar
10247 (lambda (x) (number-to-string (string-to-number x)))
10248 fields)))
10249 (setq ndown (1- ndown))
10250 (setq form (copy-sequence formula)
10251 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10252 (if (and lispp literal) (setq lispp 'literal))
10253 ;; Check for old vertical references
10254 (setq form (org-rewrite-old-row-references form))
10255 ;; Insert complex ranges
10256 (while (string-match org-table-range-regexp form)
10257 (setq form
10258 (replace-match
10259 (save-match-data
10260 (org-table-make-reference
10261 (org-table-get-range (match-string 0 form) nil n0)
10262 keep-empty numbers lispp))
10263 t t form)))
10264 ;; Insert simple ranges
10265 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10266 (setq form
10267 (replace-match
10268 (save-match-data
10269 (org-table-make-reference
10270 (org-sublist
10271 fields (string-to-number (match-string 1 form))
10272 (string-to-number (match-string 2 form)))
10273 keep-empty numbers lispp))
10274 t t form)))
10275 (setq form0 form)
10276 ;; Insert the references to fields in same row
10277 (while (string-match "\\$\\([0-9]+\\)" form)
10278 (setq n (string-to-number (match-string 1 form))
10279 x (nth (1- (if (= n 0) n0 n)) fields))
10280 (unless x (error "Invalid field specifier \"%s\""
10281 (match-string 0 form)))
10282 (setq form (replace-match
10283 (save-match-data
10284 (org-table-make-reference x nil numbers lispp))
10285 t t form)))
10287 (if lispp
10288 (setq ev (condition-case nil
10289 (eval (eval (read form)))
10290 (error "#ERROR"))
10291 ev (if (numberp ev) (number-to-string ev) ev))
10292 (or (fboundp 'calc-eval)
10293 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10294 (setq ev (calc-eval (cons form modes)
10295 (if numbers 'num))))
10297 (when org-table-formula-debug
10298 (with-output-to-temp-buffer "*Substitution History*"
10299 (princ (format "Substitution history of formula
10300 Orig: %s
10301 $xyz-> %s
10302 @r$c-> %s
10303 $1-> %s\n" orig formula form0 form))
10304 (if (listp ev)
10305 (princ (format " %s^\nError: %s"
10306 (make-string (car ev) ?\-) (nth 1 ev)))
10307 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10308 ev (or fmt "NONE")
10309 (if fmt (format fmt (string-to-number ev)) ev)))))
10310 (setq bw (get-buffer-window "*Substitution History*"))
10311 (shrink-window-if-larger-than-buffer bw)
10312 (unless (and (interactive-p) (not ndown))
10313 (unless (let (inhibit-redisplay)
10314 (y-or-n-p "Debugging Formula. Continue to next? "))
10315 (org-table-align)
10316 (error "Abort"))
10317 (delete-window bw)
10318 (message "")))
10319 (if (listp ev) (setq fmt nil ev "#ERROR"))
10320 (org-table-justify-field-maybe
10321 (if fmt (format fmt (string-to-number ev)) ev))
10322 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10323 (call-interactively 'org-return)
10324 (setq ndown 0)))
10325 (and down (org-table-maybe-recalculate-line))
10326 (or suppress-align (and org-table-may-need-update
10327 (org-table-align))))))
10329 (defun org-table-put-field-property (prop value)
10330 (save-excursion
10331 (put-text-property (progn (skip-chars-backward "^|") (point))
10332 (progn (skip-chars-forward "^|") (point))
10333 prop value)))
10335 (defun org-table-get-range (desc &optional tbeg col highlight)
10336 "Get a calc vector from a column, accorting to descriptor DESC.
10337 Optional arguments TBEG and COL can give the beginning of the table and
10338 the current column, to avoid unnecessary parsing.
10339 HIGHLIGHT means, just highlight the range."
10340 (if (not (equal (string-to-char desc) ?@))
10341 (setq desc (concat "@" desc)))
10342 (save-excursion
10343 (or tbeg (setq tbeg (org-table-begin)))
10344 (or col (setq col (org-table-current-column)))
10345 (let ((thisline (org-current-line))
10346 beg end c1 c2 r1 r2 rangep tmp)
10347 (unless (string-match org-table-range-regexp desc)
10348 (error "Invalid table range specifier `%s'" desc))
10349 (setq rangep (match-end 3)
10350 r1 (and (match-end 1) (match-string 1 desc))
10351 r2 (and (match-end 4) (match-string 4 desc))
10352 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10353 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10355 (and c1 (setq c1 (+ (string-to-number c1)
10356 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10357 (and c2 (setq c2 (+ (string-to-number c2)
10358 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10359 (if (equal r1 "") (setq r1 nil))
10360 (if (equal r2 "") (setq r2 nil))
10361 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10362 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10363 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10364 (if (not r1) (setq r1 thisline))
10365 (if (not r2) (setq r2 thisline))
10366 (if (not c1) (setq c1 col))
10367 (if (not c2) (setq c2 col))
10368 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10369 ;; just one field
10370 (progn
10371 (goto-line r1)
10372 (while (not (looking-at org-table-dataline-regexp))
10373 (beginning-of-line 2))
10374 (prog1 (org-trim (org-table-get-field c1))
10375 (if highlight (org-table-highlight-rectangle (point) (point)))))
10376 ;; A range, return a vector
10377 ;; First sort the numbers to get a regular ractangle
10378 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10379 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10380 (goto-line r1)
10381 (while (not (looking-at org-table-dataline-regexp))
10382 (beginning-of-line 2))
10383 (org-table-goto-column c1)
10384 (setq beg (point))
10385 (goto-line r2)
10386 (while (not (looking-at org-table-dataline-regexp))
10387 (beginning-of-line 0))
10388 (org-table-goto-column c2)
10389 (setq end (point))
10390 (if highlight
10391 (org-table-highlight-rectangle
10392 beg (progn (skip-chars-forward "^|\n") (point))))
10393 ;; return string representation of calc vector
10394 (mapcar 'org-trim
10395 (apply 'append (org-table-copy-region beg end)))))))
10397 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10398 "Analyze descriptor DESC and retrieve the corresponding line number.
10399 The cursor is currently in line CLINE, the table begins in line BLINE,
10400 and TABLE is a vector with line types."
10401 (if (string-match "^[0-9]+$" desc)
10402 (aref org-table-dlines (string-to-number desc))
10403 (setq cline (or cline (org-current-line))
10404 bline (or bline org-table-current-begin-line)
10405 table (or table org-table-current-line-types))
10406 (if (or
10407 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10408 ;; 1 2 3 4 5 6
10409 (and (not (match-end 3)) (not (match-end 6)))
10410 (and (match-end 3) (match-end 6) (not (match-end 5))))
10411 (error "invalid row descriptor `%s'" desc))
10412 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10413 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10414 (odir (and (match-end 5) (match-string 5 desc)))
10415 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10416 (i (- cline bline))
10417 (rel (and (match-end 6)
10418 (or (and (match-end 1) (not (match-end 3)))
10419 (match-end 5)))))
10420 (if (and hn (not hdir))
10421 (progn
10422 (setq i 0 hdir "+")
10423 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10424 (if (and (not hn) on (not odir))
10425 (error "should never happen");;(aref org-table-dlines on)
10426 (if (and hn (> hn 0))
10427 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10428 (if on
10429 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10430 (+ bline i)))))
10432 (defun org-find-row-type (table i type backwards relative n)
10433 (let ((l (length table)))
10434 (while (> n 0)
10435 (while (and (setq i (+ i (if backwards -1 1)))
10436 (>= i 0) (< i l)
10437 (not (eq (aref table i) type))
10438 (if (and relative (eq (aref table i) 'hline))
10439 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10440 t)))
10441 (setq n (1- n)))
10442 (if (or (< i 0) (>= i l))
10443 (error "Row descriptior leads outside table")
10444 i)))
10446 (defun org-rewrite-old-row-references (s)
10447 (if (string-match "&[-+0-9I]" s)
10448 (error "Formula contains old &row reference, please rewrite using @-syntax")
10451 (defun org-table-make-reference (elements keep-empty numbers lispp)
10452 "Convert list ELEMENTS to something appropriate to insert into formula.
10453 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10454 NUMBERS indicates that everything should be converted to numbers.
10455 LISPP means to return something appropriate for a Lisp list."
10456 (if (stringp elements) ; just a single val
10457 (if lispp
10458 (if (eq lispp 'literal)
10459 elements
10460 (prin1-to-string (if numbers (string-to-number elements) elements)))
10461 (if (equal elements "") (setq elements "0"))
10462 (if numbers (number-to-string (string-to-number elements)) elements))
10463 (unless keep-empty
10464 (setq elements
10465 (delq nil
10466 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10467 elements))))
10468 (setq elements (or elements '("0")))
10469 (if lispp
10470 (mapconcat
10471 (lambda (x)
10472 (if (eq lispp 'literal)
10474 (prin1-to-string (if numbers (string-to-number x) x))))
10475 elements " ")
10476 (concat "[" (mapconcat
10477 (lambda (x)
10478 (if numbers (number-to-string (string-to-number x)) x))
10479 elements
10480 ",") "]"))))
10482 (defun org-table-recalculate (&optional all noalign)
10483 "Recalculate the current table line by applying all stored formulas.
10484 With prefix arg ALL, do this for all lines in the table."
10485 (interactive "P")
10486 (or (memq this-command org-recalc-commands)
10487 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10488 (unless (org-at-table-p) (error "Not at a table"))
10489 (if (equal all '(16))
10490 (org-table-iterate)
10491 (org-table-get-specials)
10492 (let* ((eqlist (sort (org-table-get-stored-formulas)
10493 (lambda (a b) (string< (car a) (car b)))))
10494 (inhibit-redisplay (not debug-on-error))
10495 (line-re org-table-dataline-regexp)
10496 (thisline (org-current-line))
10497 (thiscol (org-table-current-column))
10498 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10499 ;; Insert constants in all formulas
10500 (setq eqlist
10501 (mapcar (lambda (x)
10502 (setcdr x (org-table-formula-substitute-names (cdr x)))
10504 eqlist))
10505 ;; Split the equation list
10506 (while (setq eq (pop eqlist))
10507 (if (<= (string-to-char (car eq)) ?9)
10508 (push eq eqlnum)
10509 (push eq eqlname)))
10510 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10511 (if all
10512 (progn
10513 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10514 (goto-char (setq beg (org-table-begin)))
10515 (if (re-search-forward org-table-calculate-mark-regexp end t)
10516 ;; This is a table with marked lines, compute selected lines
10517 (setq line-re org-table-recalculate-regexp)
10518 ;; Move forward to the first non-header line
10519 (if (and (re-search-forward org-table-dataline-regexp end t)
10520 (re-search-forward org-table-hline-regexp end t)
10521 (re-search-forward org-table-dataline-regexp end t))
10522 (setq beg (match-beginning 0))
10523 nil))) ;; just leave beg where it is
10524 (setq beg (point-at-bol)
10525 end (move-marker (make-marker) (1+ (point-at-eol)))))
10526 (goto-char beg)
10527 (and all (message "Re-applying formulas to full table..."))
10529 ;; First find the named fields, and mark them untouchanble
10530 (remove-text-properties beg end '(org-untouchable t))
10531 (while (setq eq (pop eqlname))
10532 (setq name (car eq)
10533 a (assoc name org-table-named-field-locations))
10534 (and (not a)
10535 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10536 (setq a (list name
10537 (aref org-table-dlines
10538 (string-to-number (match-string 1 name)))
10539 (string-to-number (match-string 2 name)))))
10540 (when (and a (or all (equal (nth 1 a) thisline)))
10541 (message "Re-applying formula to field: %s" name)
10542 (goto-line (nth 1 a))
10543 (org-table-goto-column (nth 2 a))
10544 (push (append a (list (cdr eq))) eqlname1)
10545 (org-table-put-field-property :org-untouchable t)))
10547 ;; Now evauluate the column formulas, but skip fields covered by
10548 ;; field formulas
10549 (goto-char beg)
10550 (while (re-search-forward line-re end t)
10551 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10552 ;; Unprotected line, recalculate
10553 (and all (message "Re-applying formulas to full table...(line %d)"
10554 (setq cnt (1+ cnt))))
10555 (setq org-last-recalc-line (org-current-line))
10556 (setq eql eqlnum)
10557 (while (setq entry (pop eql))
10558 (goto-line org-last-recalc-line)
10559 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10560 (unless (get-text-property (point) :org-untouchable)
10561 (org-table-eval-formula nil (cdr entry)
10562 'noalign 'nocst 'nostore 'noanalysis)))))
10564 ;; Now evaluate the field formulas
10565 (while (setq eq (pop eqlname1))
10566 (message "Re-applying formula to field: %s" (car eq))
10567 (goto-line (nth 1 eq))
10568 (org-table-goto-column (nth 2 eq))
10569 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10570 'nostore 'noanalysis))
10572 (goto-line thisline)
10573 (org-table-goto-column thiscol)
10574 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10575 (or noalign (and org-table-may-need-update (org-table-align))
10576 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10578 ;; back to initial position
10579 (message "Re-applying formulas...done")
10580 (goto-line thisline)
10581 (org-table-goto-column thiscol)
10582 (or noalign (and org-table-may-need-update (org-table-align))
10583 (and all (message "Re-applying formulas...done"))))))
10585 (defun org-table-iterate (&optional arg)
10586 "Recalculate the table until it does not change anymore."
10587 (interactive "P")
10588 (let ((imax (if arg (prefix-numeric-value arg) 10))
10589 (i 0)
10590 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10591 thistbl)
10592 (catch 'exit
10593 (while (< i imax)
10594 (setq i (1+ i))
10595 (org-table-recalculate 'all)
10596 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10597 (if (not (string= lasttbl thistbl))
10598 (setq lasttbl thistbl)
10599 (if (> i 1)
10600 (message "Convergence after %d iterations" i)
10601 (message "Table was already stable"))
10602 (throw 'exit t)))
10603 (error "No convergence after %d iterations" i))))
10605 (defun org-table-formula-substitute-names (f)
10606 "Replace $const with values in string F."
10607 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10608 ;; First, check for column names
10609 (while (setq start (string-match org-table-column-name-regexp f start))
10610 (setq start (1+ start))
10611 (setq a (assoc (match-string 1 f) org-table-column-names))
10612 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10613 ;; Parameters and constants
10614 (setq start 0)
10615 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10616 (setq start (1+ start))
10617 (if (setq a (save-match-data
10618 (org-table-get-constant (match-string 1 f))))
10619 (setq f (replace-match
10620 (concat (if pp "(") a (if pp ")")) t t f))))
10621 (if org-table-formula-debug
10622 (put-text-property 0 (length f) :orig-formula f1 f))
10625 (defun org-table-get-constant (const)
10626 "Find the value for a parameter or constant in a formula.
10627 Parameters get priority."
10628 (or (cdr (assoc const org-table-local-parameters))
10629 (cdr (assoc const org-table-formula-constants-local))
10630 (cdr (assoc const org-table-formula-constants))
10631 (and (fboundp 'constants-get) (constants-get const))
10632 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10633 (org-entry-get nil (substring const 5) 'inherit))
10634 "#UNDEFINED_NAME"))
10636 (defvar org-table-fedit-map
10637 (let ((map (make-sparse-keymap)))
10638 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10639 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10640 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10641 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10642 (org-defkey map "\C-c?" 'org-table-show-reference)
10643 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10644 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10645 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10646 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10647 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10648 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10649 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10650 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10651 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10652 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10653 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10654 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10655 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10656 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10657 map))
10659 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10660 '("Edit-Formulas"
10661 ["Finish and Install" org-table-fedit-finish t]
10662 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10663 ["Abort" org-table-fedit-abort t]
10664 "--"
10665 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10666 ["Complete Lisp Symbol" lisp-complete-symbol t]
10667 "--"
10668 "Shift Reference at Point"
10669 ["Up" org-table-fedit-ref-up t]
10670 ["Down" org-table-fedit-ref-down t]
10671 ["Left" org-table-fedit-ref-left t]
10672 ["Right" org-table-fedit-ref-right t]
10674 "Change Test Row for Column Formulas"
10675 ["Up" org-table-fedit-line-up t]
10676 ["Down" org-table-fedit-line-down t]
10677 "--"
10678 ["Scroll Table Window" org-table-fedit-scroll t]
10679 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10680 ["Show Table Grid" org-table-fedit-toggle-coordinates
10681 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10682 org-table-overlay-coordinates)]
10683 "--"
10684 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10685 :style toggle :selected org-table-buffer-is-an]))
10687 (defvar org-pos)
10689 (defun org-table-edit-formulas ()
10690 "Edit the formulas of the current table in a separate buffer."
10691 (interactive)
10692 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10693 (beginning-of-line 0))
10694 (unless (org-at-table-p) (error "Not at a table"))
10695 (org-table-get-specials)
10696 (let ((key (org-table-current-field-formula 'key 'noerror))
10697 (eql (sort (org-table-get-stored-formulas 'noerror)
10698 'org-table-formula-less-p))
10699 (pos (move-marker (make-marker) (point)))
10700 (startline 1)
10701 (wc (current-window-configuration))
10702 (titles '((column . "# Column Formulas\n")
10703 (field . "# Field Formulas\n")
10704 (named . "# Named Field Formulas\n")))
10705 entry s type title)
10706 (org-switch-to-buffer-other-window "*Edit Formulas*")
10707 (erase-buffer)
10708 ;; Keep global-font-lock-mode from turning on font-lock-mode
10709 (let ((font-lock-global-modes '(not fundamental-mode)))
10710 (fundamental-mode))
10711 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10712 (org-set-local 'org-pos pos)
10713 (org-set-local 'org-window-configuration wc)
10714 (use-local-map org-table-fedit-map)
10715 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10716 (easy-menu-add org-table-fedit-menu)
10717 (setq startline (org-current-line))
10718 (while (setq entry (pop eql))
10719 (setq type (cond
10720 ((equal (string-to-char (car entry)) ?@) 'field)
10721 ((string-match "^[0-9]" (car entry)) 'column)
10722 (t 'named)))
10723 (when (setq title (assq type titles))
10724 (or (bobp) (insert "\n"))
10725 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10726 (setq titles (delq title titles)))
10727 (if (equal key (car entry)) (setq startline (org-current-line)))
10728 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10729 (car entry) " = " (cdr entry) "\n"))
10730 (remove-text-properties 0 (length s) '(face nil) s)
10731 (insert s))
10732 (if (eq org-table-use-standard-references t)
10733 (org-table-fedit-toggle-ref-type))
10734 (goto-line startline)
10735 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10737 (defun org-table-fedit-post-command ()
10738 (when (not (memq this-command '(lisp-complete-symbol)))
10739 (let ((win (selected-window)))
10740 (save-excursion
10741 (condition-case nil
10742 (org-table-show-reference)
10743 (error nil))
10744 (select-window win)))))
10746 (defun org-table-formula-to-user (s)
10747 "Convert a formula from internal to user representation."
10748 (if (eq org-table-use-standard-references t)
10749 (org-table-convert-refs-to-an s)
10752 (defun org-table-formula-from-user (s)
10753 "Convert a formula from user to internal representation."
10754 (if org-table-use-standard-references
10755 (org-table-convert-refs-to-rc s)
10758 (defun org-table-convert-refs-to-rc (s)
10759 "Convert spreadsheet references from AB7 to @7$28.
10760 Works for single references, but also for entire formulas and even the
10761 full TBLFM line."
10762 (let ((start 0))
10763 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10764 (cond
10765 ((match-end 3)
10766 ;; format match, just advance
10767 (setq start (match-end 0)))
10768 ((and (> (match-beginning 0) 0)
10769 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10770 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10771 ;; 3.e5 or something like this.
10772 (setq start (match-end 0)))
10774 (setq start (match-beginning 0)
10775 s (replace-match
10776 (if (equal (match-string 2 s) "&")
10777 (format "$%d" (org-letters-to-number (match-string 1 s)))
10778 (format "@%d$%d"
10779 (string-to-number (match-string 2 s))
10780 (org-letters-to-number (match-string 1 s))))
10781 t t s)))))
10784 (defun org-table-convert-refs-to-an (s)
10785 "Convert spreadsheet references from to @7$28 to AB7.
10786 Works for single references, but also for entire formulas and even the
10787 full TBLFM line."
10788 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10789 (setq s (replace-match
10790 (format "%s%d"
10791 (org-number-to-letters
10792 (string-to-number (match-string 2 s)))
10793 (string-to-number (match-string 1 s)))
10794 t t s)))
10795 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10796 (setq s (replace-match (concat "\\1"
10797 (org-number-to-letters
10798 (string-to-number (match-string 2 s))) "&")
10799 t nil s)))
10802 (defun org-letters-to-number (s)
10803 "Convert a base 26 number represented by letters into an integer.
10804 For example: AB -> 28."
10805 (let ((n 0))
10806 (setq s (upcase s))
10807 (while (> (length s) 0)
10808 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10809 s (substring s 1)))
10812 (defun org-number-to-letters (n)
10813 "Convert an integer into a base 26 number represented by letters.
10814 For example: 28 -> AB."
10815 (let ((s ""))
10816 (while (> n 0)
10817 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10818 n (/ (1- n) 26)))
10821 (defun org-table-fedit-convert-buffer (function)
10822 "Convert all references in this buffer, using FUNTION."
10823 (let ((line (org-current-line)))
10824 (goto-char (point-min))
10825 (while (not (eobp))
10826 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10827 (delete-region (point) (point-at-eol))
10828 (or (eobp) (forward-char 1)))
10829 (goto-line line)))
10831 (defun org-table-fedit-toggle-ref-type ()
10832 "Convert all references in the buffer from B3 to @3$2 and back."
10833 (interactive)
10834 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10835 (org-table-fedit-convert-buffer
10836 (if org-table-buffer-is-an
10837 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10838 (message "Reference type switched to %s"
10839 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10841 (defun org-table-fedit-ref-up ()
10842 "Shift the reference at point one row/hline up."
10843 (interactive)
10844 (org-table-fedit-shift-reference 'up))
10845 (defun org-table-fedit-ref-down ()
10846 "Shift the reference at point one row/hline down."
10847 (interactive)
10848 (org-table-fedit-shift-reference 'down))
10849 (defun org-table-fedit-ref-left ()
10850 "Shift the reference at point one field to the left."
10851 (interactive)
10852 (org-table-fedit-shift-reference 'left))
10853 (defun org-table-fedit-ref-right ()
10854 "Shift the reference at point one field to the right."
10855 (interactive)
10856 (org-table-fedit-shift-reference 'right))
10858 (defun org-table-fedit-shift-reference (dir)
10859 (cond
10860 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10861 (if (memq dir '(left right))
10862 (org-rematch-and-replace 1 (eq dir 'left))
10863 (error "Cannot shift reference in this direction")))
10864 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10865 ;; A B3-like reference
10866 (if (memq dir '(up down))
10867 (org-rematch-and-replace 2 (eq dir 'up))
10868 (org-rematch-and-replace 1 (eq dir 'left))))
10869 ((org-at-regexp-p
10870 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10871 ;; An internal reference
10872 (if (memq dir '(up down))
10873 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10874 (org-rematch-and-replace 5 (eq dir 'left))))))
10876 (defun org-rematch-and-replace (n &optional decr hline)
10877 "Re-match the group N, and replace it with the shifted refrence."
10878 (or (match-end n) (error "Cannot shift reference in this direction"))
10879 (goto-char (match-beginning n))
10880 (and (looking-at (regexp-quote (match-string n)))
10881 (replace-match (org-shift-refpart (match-string 0) decr hline)
10882 t t)))
10884 (defun org-shift-refpart (ref &optional decr hline)
10885 "Shift a refrence part REF.
10886 If DECR is set, decrease the references row/column, else increase.
10887 If HLINE is set, this may be a hline reference, it certainly is not
10888 a translation reference."
10889 (save-match-data
10890 (let* ((sign (string-match "^[-+]" ref)) n)
10892 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10893 (cond
10894 ((and hline (string-match "^I+" ref))
10895 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10896 (setq n (+ n (if decr -1 1)))
10897 (if (= n 0) (setq n (+ n (if decr -1 1))))
10898 (if sign
10899 (setq sign (if (< n 0) "-" "+") n (abs n))
10900 (setq n (max 1 n)))
10901 (concat sign (make-string n ?I)))
10903 ((string-match "^[0-9]+" ref)
10904 (setq n (string-to-number (concat sign ref)))
10905 (setq n (+ n (if decr -1 1)))
10906 (if sign
10907 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10908 (number-to-string (max 1 n))))
10910 ((string-match "^[a-zA-Z]+" ref)
10911 (org-number-to-letters
10912 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10914 (t (error "Cannot shift reference"))))))
10916 (defun org-table-fedit-toggle-coordinates ()
10917 "Toggle the display of coordinates in the refrenced table."
10918 (interactive)
10919 (let ((pos (marker-position org-pos)))
10920 (with-current-buffer (marker-buffer org-pos)
10921 (save-excursion
10922 (goto-char pos)
10923 (org-table-toggle-coordinate-overlays)))))
10925 (defun org-table-fedit-finish (&optional arg)
10926 "Parse the buffer for formula definitions and install them.
10927 With prefix ARG, apply the new formulas to the table."
10928 (interactive "P")
10929 (org-table-remove-rectangle-highlight)
10930 (if org-table-use-standard-references
10931 (progn
10932 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10933 (setq org-table-buffer-is-an nil)))
10934 (let ((pos org-pos) eql var form)
10935 (goto-char (point-min))
10936 (while (re-search-forward
10937 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10938 nil t)
10939 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10940 form (match-string 3))
10941 (setq form (org-trim form))
10942 (when (not (equal form ""))
10943 (while (string-match "[ \t]*\n[ \t]*" form)
10944 (setq form (replace-match " " t t form)))
10945 (when (assoc var eql)
10946 (error "Double formulas for %s" var))
10947 (push (cons var form) eql)))
10948 (setq org-pos nil)
10949 (set-window-configuration org-window-configuration)
10950 (select-window (get-buffer-window (marker-buffer pos)))
10951 (goto-char pos)
10952 (unless (org-at-table-p)
10953 (error "Lost table position - cannot install formulae"))
10954 (org-table-store-formulas eql)
10955 (move-marker pos nil)
10956 (kill-buffer "*Edit Formulas*")
10957 (if arg
10958 (org-table-recalculate 'all)
10959 (message "New formulas installed - press C-u C-c C-c to apply."))))
10961 (defun org-table-fedit-abort ()
10962 "Abort editing formulas, without installing the changes."
10963 (interactive)
10964 (org-table-remove-rectangle-highlight)
10965 (let ((pos org-pos))
10966 (set-window-configuration org-window-configuration)
10967 (select-window (get-buffer-window (marker-buffer pos)))
10968 (goto-char pos)
10969 (move-marker pos nil)
10970 (message "Formula editing aborted without installing changes")))
10972 (defun org-table-fedit-lisp-indent ()
10973 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10974 (interactive)
10975 (let ((pos (point)) beg end ind)
10976 (beginning-of-line 1)
10977 (cond
10978 ((looking-at "[ \t]")
10979 (goto-char pos)
10980 (call-interactively 'lisp-indent-line))
10981 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10982 ((not (fboundp 'pp-buffer))
10983 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10984 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10985 (goto-char (- (match-end 0) 2))
10986 (setq beg (point))
10987 (setq ind (make-string (current-column) ?\ ))
10988 (condition-case nil (forward-sexp 1)
10989 (error
10990 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10991 (setq end (point))
10992 (save-restriction
10993 (narrow-to-region beg end)
10994 (if (eq last-command this-command)
10995 (progn
10996 (goto-char (point-min))
10997 (setq this-command nil)
10998 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10999 (replace-match " ")))
11000 (pp-buffer)
11001 (untabify (point-min) (point-max))
11002 (goto-char (1+ (point-min)))
11003 (while (re-search-forward "^." nil t)
11004 (beginning-of-line 1)
11005 (insert ind))
11006 (goto-char (point-max))
11007 (backward-delete-char 1)))
11008 (goto-char beg))
11009 (t nil))))
11011 (defvar org-show-positions nil)
11013 (defun org-table-show-reference (&optional local)
11014 "Show the location/value of the $ expression at point."
11015 (interactive)
11016 (org-table-remove-rectangle-highlight)
11017 (catch 'exit
11018 (let ((pos (if local (point) org-pos))
11019 (face2 'highlight)
11020 (org-inhibit-highlight-removal t)
11021 (win (selected-window))
11022 (org-show-positions nil)
11023 var name e what match dest)
11024 (if local (org-table-get-specials))
11025 (setq what (cond
11026 ((or (org-at-regexp-p org-table-range-regexp2)
11027 (org-at-regexp-p org-table-translate-regexp)
11028 (org-at-regexp-p org-table-range-regexp))
11029 (setq match
11030 (save-match-data
11031 (org-table-convert-refs-to-rc (match-string 0))))
11032 'range)
11033 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11034 ((org-at-regexp-p "\\$[0-9]+") 'column)
11035 ((not local) nil)
11036 (t (error "No reference at point")))
11037 match (and what (or match (match-string 0))))
11038 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11039 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11040 'secondary-selection))
11041 (org-add-hook 'before-change-functions
11042 'org-table-remove-rectangle-highlight)
11043 (if (eq what 'name) (setq var (substring match 1)))
11044 (when (eq what 'range)
11045 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11046 (setq match (org-table-formula-substitute-names match)))
11047 (unless local
11048 (save-excursion
11049 (end-of-line 1)
11050 (re-search-backward "^\\S-" nil t)
11051 (beginning-of-line 1)
11052 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11053 (setq dest
11054 (save-match-data
11055 (org-table-convert-refs-to-rc (match-string 1))))
11056 (org-table-add-rectangle-overlay
11057 (match-beginning 1) (match-end 1) face2))))
11058 (if (and (markerp pos) (marker-buffer pos))
11059 (if (get-buffer-window (marker-buffer pos))
11060 (select-window (get-buffer-window (marker-buffer pos)))
11061 (org-switch-to-buffer-other-window (get-buffer-window
11062 (marker-buffer pos)))))
11063 (goto-char pos)
11064 (org-table-force-dataline)
11065 (when dest
11066 (setq name (substring dest 1))
11067 (cond
11068 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11069 (setq e (assoc name org-table-named-field-locations))
11070 (goto-line (nth 1 e))
11071 (org-table-goto-column (nth 2 e)))
11072 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11073 (let ((l (string-to-number (match-string 1 dest)))
11074 (c (string-to-number (match-string 2 dest))))
11075 (goto-line (aref org-table-dlines l))
11076 (org-table-goto-column c)))
11077 (t (org-table-goto-column (string-to-number name))))
11078 (move-marker pos (point))
11079 (org-table-highlight-rectangle nil nil face2))
11080 (cond
11081 ((equal dest match))
11082 ((not match))
11083 ((eq what 'range)
11084 (condition-case nil
11085 (save-excursion
11086 (org-table-get-range match nil nil 'highlight))
11087 (error nil)))
11088 ((setq e (assoc var org-table-named-field-locations))
11089 (goto-line (nth 1 e))
11090 (org-table-goto-column (nth 2 e))
11091 (org-table-highlight-rectangle (point) (point))
11092 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11093 ((setq e (assoc var org-table-column-names))
11094 (org-table-goto-column (string-to-number (cdr e)))
11095 (org-table-highlight-rectangle (point) (point))
11096 (goto-char (org-table-begin))
11097 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11098 (org-table-end) t)
11099 (progn
11100 (goto-char (match-beginning 1))
11101 (org-table-highlight-rectangle)
11102 (message "Named column (column %s)" (cdr e)))
11103 (error "Column name not found")))
11104 ((eq what 'column)
11105 ;; column number
11106 (org-table-goto-column (string-to-number (substring match 1)))
11107 (org-table-highlight-rectangle (point) (point))
11108 (message "Column %s" (substring match 1)))
11109 ((setq e (assoc var org-table-local-parameters))
11110 (goto-char (org-table-begin))
11111 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11112 (progn
11113 (goto-char (match-beginning 1))
11114 (org-table-highlight-rectangle)
11115 (message "Local parameter."))
11116 (error "Parameter not found")))
11118 (cond
11119 ((not var) (error "No reference at point"))
11120 ((setq e (assoc var org-table-formula-constants-local))
11121 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11122 var (cdr e)))
11123 ((setq e (assoc var org-table-formula-constants))
11124 (message "Constant: $%s=%s in `org-table-formula-constants'."
11125 var (cdr e)))
11126 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11127 (message "Constant: $%s=%s, from `constants.el'%s."
11128 var e (format " (%s units)" constants-unit-system)))
11129 (t (error "Undefined name $%s" var)))))
11130 (goto-char pos)
11131 (when (and org-show-positions
11132 (not (memq this-command '(org-table-fedit-scroll
11133 org-table-fedit-scroll-down))))
11134 (push pos org-show-positions)
11135 (push org-table-current-begin-pos org-show-positions)
11136 (let ((min (apply 'min org-show-positions))
11137 (max (apply 'max org-show-positions)))
11138 (goto-char min) (recenter 0)
11139 (goto-char max)
11140 (or (pos-visible-in-window-p max) (recenter -1))))
11141 (select-window win))))
11143 (defun org-table-force-dataline ()
11144 "Make sure the cursor is in a dataline in a table."
11145 (unless (save-excursion
11146 (beginning-of-line 1)
11147 (looking-at org-table-dataline-regexp))
11148 (let* ((re org-table-dataline-regexp)
11149 (p1 (save-excursion (re-search-forward re nil 'move)))
11150 (p2 (save-excursion (re-search-backward re nil 'move))))
11151 (cond ((and p1 p2)
11152 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11153 p1 p2)))
11154 ((or p1 p2) (goto-char (or p1 p2)))
11155 (t (error "No table dataline around here"))))))
11157 (defun org-table-fedit-line-up ()
11158 "Move cursor one line up in the window showing the table."
11159 (interactive)
11160 (org-table-fedit-move 'previous-line))
11162 (defun org-table-fedit-line-down ()
11163 "Move cursor one line down in the window showing the table."
11164 (interactive)
11165 (org-table-fedit-move 'next-line))
11167 (defun org-table-fedit-move (command)
11168 "Move the cursor in the window shoinw the table.
11169 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11170 (let ((org-table-allow-automatic-line-recalculation nil)
11171 (pos org-pos) (win (selected-window)) p)
11172 (select-window (get-buffer-window (marker-buffer org-pos)))
11173 (setq p (point))
11174 (call-interactively command)
11175 (while (and (org-at-table-p)
11176 (org-at-table-hline-p))
11177 (call-interactively command))
11178 (or (org-at-table-p) (goto-char p))
11179 (move-marker pos (point))
11180 (select-window win)))
11182 (defun org-table-fedit-scroll (N)
11183 (interactive "p")
11184 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11185 (scroll-other-window N)))
11187 (defun org-table-fedit-scroll-down (N)
11188 (interactive "p")
11189 (org-table-fedit-scroll (- N)))
11191 (defvar org-table-rectangle-overlays nil)
11193 (defun org-table-add-rectangle-overlay (beg end &optional face)
11194 "Add a new overlay."
11195 (let ((ov (org-make-overlay beg end)))
11196 (org-overlay-put ov 'face (or face 'secondary-selection))
11197 (push ov org-table-rectangle-overlays)))
11199 (defun org-table-highlight-rectangle (&optional beg end face)
11200 "Highlight rectangular region in a table."
11201 (setq beg (or beg (point)) end (or end (point)))
11202 (let ((b (min beg end))
11203 (e (max beg end))
11204 l1 c1 l2 c2 tmp)
11205 (and (boundp 'org-show-positions)
11206 (setq org-show-positions (cons b (cons e org-show-positions))))
11207 (goto-char (min beg end))
11208 (setq l1 (org-current-line)
11209 c1 (org-table-current-column))
11210 (goto-char (max beg end))
11211 (setq l2 (org-current-line)
11212 c2 (org-table-current-column))
11213 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11214 (goto-line l1)
11215 (beginning-of-line 1)
11216 (loop for line from l1 to l2 do
11217 (when (looking-at org-table-dataline-regexp)
11218 (org-table-goto-column c1)
11219 (skip-chars-backward "^|\n") (setq beg (point))
11220 (org-table-goto-column c2)
11221 (skip-chars-forward "^|\n") (setq end (point))
11222 (org-table-add-rectangle-overlay beg end face))
11223 (beginning-of-line 2))
11224 (goto-char b))
11225 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11227 (defun org-table-remove-rectangle-highlight (&rest ignore)
11228 "Remove the rectangle overlays."
11229 (unless org-inhibit-highlight-removal
11230 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11231 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11232 (setq org-table-rectangle-overlays nil)))
11234 (defvar org-table-coordinate-overlays nil
11235 "Collects the cooordinate grid overlays, so that they can be removed.")
11236 (make-variable-buffer-local 'org-table-coordinate-overlays)
11238 (defun org-table-overlay-coordinates ()
11239 "Add overlays to the table at point, to show row/column coordinates."
11240 (interactive)
11241 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11242 (setq org-table-coordinate-overlays nil)
11243 (save-excursion
11244 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11245 (goto-char (org-table-begin))
11246 (while (org-at-table-p)
11247 (setq eol (point-at-eol))
11248 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11249 (push ov org-table-coordinate-overlays)
11250 (setq hline (looking-at org-table-hline-regexp))
11251 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11252 (format "%4d" (setq id (1+ id)))))
11253 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11254 (when hline
11255 (setq ic 0)
11256 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11257 (setq beg (1+ (match-beginning 0))
11258 ic (1+ ic)
11259 s1 (concat "$" (int-to-string ic))
11260 s2 (org-number-to-letters ic)
11261 str (if (eq org-table-use-standard-references t) s2 s1))
11262 (setq ov (org-make-overlay beg (+ beg (length str))))
11263 (push ov org-table-coordinate-overlays)
11264 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11265 (beginning-of-line 2)))))
11267 (defun org-table-toggle-coordinate-overlays ()
11268 "Toggle the display of Row/Column numbers in tables."
11269 (interactive)
11270 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11271 (message "Row/Column number display turned %s"
11272 (if org-table-overlay-coordinates "on" "off"))
11273 (if (and (org-at-table-p) org-table-overlay-coordinates)
11274 (org-table-align))
11275 (unless org-table-overlay-coordinates
11276 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11277 (setq org-table-coordinate-overlays nil)))
11279 (defun org-table-toggle-formula-debugger ()
11280 "Toggle the formula debugger in tables."
11281 (interactive)
11282 (setq org-table-formula-debug (not org-table-formula-debug))
11283 (message "Formula debugging has been turned %s"
11284 (if org-table-formula-debug "on" "off")))
11286 ;;; The orgtbl minor mode
11288 ;; Define a minor mode which can be used in other modes in order to
11289 ;; integrate the org-mode table editor.
11291 ;; This is really a hack, because the org-mode table editor uses several
11292 ;; keys which normally belong to the major mode, for example the TAB and
11293 ;; RET keys. Here is how it works: The minor mode defines all the keys
11294 ;; necessary to operate the table editor, but wraps the commands into a
11295 ;; function which tests if the cursor is currently inside a table. If that
11296 ;; is the case, the table editor command is executed. However, when any of
11297 ;; those keys is used outside a table, the function uses `key-binding' to
11298 ;; look up if the key has an associated command in another currently active
11299 ;; keymap (minor modes, major mode, global), and executes that command.
11300 ;; There might be problems if any of the keys used by the table editor is
11301 ;; otherwise used as a prefix key.
11303 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11304 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11305 ;; addresses this by checking explicitly for both bindings.
11307 ;; The optimized version (see variable `orgtbl-optimized') takes over
11308 ;; all keys which are bound to `self-insert-command' in the *global map*.
11309 ;; Some modes bind other commands to simple characters, for example
11310 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11311 ;; active, this binding is ignored inside tables and replaced with a
11312 ;; modified self-insert.
11314 (defvar orgtbl-mode nil
11315 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11316 table editor in arbitrary modes.")
11317 (make-variable-buffer-local 'orgtbl-mode)
11319 (defvar orgtbl-mode-map (make-keymap)
11320 "Keymap for `orgtbl-mode'.")
11322 ;;;###autoload
11323 (defun turn-on-orgtbl ()
11324 "Unconditionally turn on `orgtbl-mode'."
11325 (orgtbl-mode 1))
11327 (defvar org-old-auto-fill-inhibit-regexp nil
11328 "Local variable used by `orgtbl-mode'")
11330 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11331 "Matches a line belonging to an orgtbl.")
11333 (defconst orgtbl-extra-font-lock-keywords
11334 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11335 0 (quote 'org-table) 'prepend))
11336 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11338 ;;;###autoload
11339 (defun orgtbl-mode (&optional arg)
11340 "The `org-mode' table editor as a minor mode for use in other modes."
11341 (interactive)
11342 (if (org-mode-p)
11343 ;; Exit without error, in case some hook functions calls this
11344 ;; by accident in org-mode.
11345 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11346 (setq orgtbl-mode
11347 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11348 (if orgtbl-mode
11349 (progn
11350 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11351 ;; Make sure we are first in minor-mode-map-alist
11352 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11353 (and c (setq minor-mode-map-alist
11354 (cons c (delq c minor-mode-map-alist)))))
11355 (org-set-local (quote org-table-may-need-update) t)
11356 (org-add-hook 'before-change-functions 'org-before-change-function
11357 nil 'local)
11358 (org-set-local 'org-old-auto-fill-inhibit-regexp
11359 auto-fill-inhibit-regexp)
11360 (org-set-local 'auto-fill-inhibit-regexp
11361 (if auto-fill-inhibit-regexp
11362 (concat orgtbl-line-start-regexp "\\|"
11363 auto-fill-inhibit-regexp)
11364 orgtbl-line-start-regexp))
11365 (org-add-to-invisibility-spec '(org-cwidth))
11366 (when (fboundp 'font-lock-add-keywords)
11367 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11368 (org-restart-font-lock))
11369 (easy-menu-add orgtbl-mode-menu)
11370 (run-hooks 'orgtbl-mode-hook))
11371 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11372 (org-cleanup-narrow-column-properties)
11373 (org-remove-from-invisibility-spec '(org-cwidth))
11374 (remove-hook 'before-change-functions 'org-before-change-function t)
11375 (when (fboundp 'font-lock-remove-keywords)
11376 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11377 (org-restart-font-lock))
11378 (easy-menu-remove orgtbl-mode-menu)
11379 (force-mode-line-update 'all))))
11381 (defun org-cleanup-narrow-column-properties ()
11382 "Remove all properties related to narrow-column invisibility."
11383 (let ((s 1))
11384 (while (setq s (text-property-any s (point-max)
11385 'display org-narrow-column-arrow))
11386 (remove-text-properties s (1+ s) '(display t)))
11387 (setq s 1)
11388 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11389 (remove-text-properties s (1+ s) '(org-cwidth t)))
11390 (setq s 1)
11391 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11392 (remove-text-properties s (1+ s) '(invisible t)))))
11394 ;; Install it as a minor mode.
11395 (put 'orgtbl-mode :included t)
11396 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11397 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11399 (defun orgtbl-make-binding (fun n &rest keys)
11400 "Create a function for binding in the table minor mode.
11401 FUN is the command to call inside a table. N is used to create a unique
11402 command name. KEYS are keys that should be checked in for a command
11403 to execute outside of tables."
11404 (eval
11405 (list 'defun
11406 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11407 '(arg)
11408 (concat "In tables, run `" (symbol-name fun) "'.\n"
11409 "Outside of tables, run the binding of `"
11410 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11411 "'.")
11412 '(interactive "p")
11413 (list 'if
11414 '(org-at-table-p)
11415 (list 'call-interactively (list 'quote fun))
11416 (list 'let '(orgtbl-mode)
11417 (list 'call-interactively
11418 (append '(or)
11419 (mapcar (lambda (k)
11420 (list 'key-binding k))
11421 keys)
11422 '('orgtbl-error))))))))
11424 (defun orgtbl-error ()
11425 "Error when there is no default binding for a table key."
11426 (interactive)
11427 (error "This key has no function outside tables"))
11429 (defun orgtbl-setup ()
11430 "Setup orgtbl keymaps."
11431 (let ((nfunc 0)
11432 (bindings
11433 (list
11434 '([(meta shift left)] org-table-delete-column)
11435 '([(meta left)] org-table-move-column-left)
11436 '([(meta right)] org-table-move-column-right)
11437 '([(meta shift right)] org-table-insert-column)
11438 '([(meta shift up)] org-table-kill-row)
11439 '([(meta shift down)] org-table-insert-row)
11440 '([(meta up)] org-table-move-row-up)
11441 '([(meta down)] org-table-move-row-down)
11442 '("\C-c\C-w" org-table-cut-region)
11443 '("\C-c\M-w" org-table-copy-region)
11444 '("\C-c\C-y" org-table-paste-rectangle)
11445 '("\C-c-" org-table-insert-hline)
11446 '("\C-c}" org-table-toggle-coordinate-overlays)
11447 '("\C-c{" org-table-toggle-formula-debugger)
11448 '("\C-m" org-table-next-row)
11449 '([(shift return)] org-table-copy-down)
11450 '("\C-c\C-q" org-table-wrap-region)
11451 '("\C-c?" org-table-field-info)
11452 '("\C-c " org-table-blank-field)
11453 '("\C-c+" org-table-sum)
11454 '("\C-c=" org-table-eval-formula)
11455 '("\C-c'" org-table-edit-formulas)
11456 '("\C-c`" org-table-edit-field)
11457 '("\C-c*" org-table-recalculate)
11458 '("\C-c|" org-table-create-or-convert-from-region)
11459 '("\C-c^" org-table-sort-lines)
11460 '([(control ?#)] org-table-rotate-recalc-marks)))
11461 elt key fun cmd)
11462 (while (setq elt (pop bindings))
11463 (setq nfunc (1+ nfunc))
11464 (setq key (org-key (car elt))
11465 fun (nth 1 elt)
11466 cmd (orgtbl-make-binding fun nfunc key))
11467 (org-defkey orgtbl-mode-map key cmd))
11469 ;; Special treatment needed for TAB and RET
11470 (org-defkey orgtbl-mode-map [(return)]
11471 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11472 (org-defkey orgtbl-mode-map "\C-m"
11473 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11475 (org-defkey orgtbl-mode-map [(tab)]
11476 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11477 (org-defkey orgtbl-mode-map "\C-i"
11478 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11480 (org-defkey orgtbl-mode-map [(shift tab)]
11481 (orgtbl-make-binding 'org-table-previous-field 104
11482 [(shift tab)] [(tab)] "\C-i"))
11484 (org-defkey orgtbl-mode-map "\M-\C-m"
11485 (orgtbl-make-binding 'org-table-wrap-region 105
11486 "\M-\C-m" [(meta return)]))
11487 (org-defkey orgtbl-mode-map [(meta return)]
11488 (orgtbl-make-binding 'org-table-wrap-region 106
11489 [(meta return)] "\M-\C-m"))
11491 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11492 (when orgtbl-optimized
11493 ;; If the user wants maximum table support, we need to hijack
11494 ;; some standard editing functions
11495 (org-remap orgtbl-mode-map
11496 'self-insert-command 'orgtbl-self-insert-command
11497 'delete-char 'org-delete-char
11498 'delete-backward-char 'org-delete-backward-char)
11499 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11500 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11501 '("OrgTbl"
11502 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11503 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11504 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11505 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11506 "--"
11507 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11508 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11509 ["Copy Field from Above"
11510 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11511 "--"
11512 ("Column"
11513 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11514 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11515 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11516 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11517 ("Row"
11518 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11519 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11520 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11521 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11522 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11523 "--"
11524 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11525 ("Rectangle"
11526 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11527 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11528 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11529 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11530 "--"
11531 ("Radio tables"
11532 ["Insert table template" orgtbl-insert-radio-table
11533 (assq major-mode orgtbl-radio-table-templates)]
11534 ["Comment/uncomment table" orgtbl-toggle-comment t])
11535 "--"
11536 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11537 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11538 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11539 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11540 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11541 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11542 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11543 ["Sum Column/Rectangle" org-table-sum
11544 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11545 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11546 ["Debug Formulas"
11547 org-table-toggle-formula-debugger :active (org-at-table-p)
11548 :keys "C-c {"
11549 :style toggle :selected org-table-formula-debug]
11550 ["Show Col/Row Numbers"
11551 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11552 :keys "C-c }"
11553 :style toggle :selected org-table-overlay-coordinates]
11557 (defun orgtbl-ctrl-c-ctrl-c (arg)
11558 "If the cursor is inside a table, realign the table.
11559 It it is a table to be sent away to a receiver, do it.
11560 With prefix arg, also recompute table."
11561 (interactive "P")
11562 (let ((pos (point)) action)
11563 (save-excursion
11564 (beginning-of-line 1)
11565 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11566 ((looking-at "[ \t]*|") pos)
11567 ((looking-at "#\\+TBLFM:") 'recalc))))
11568 (cond
11569 ((integerp action)
11570 (goto-char action)
11571 (org-table-maybe-eval-formula)
11572 (if arg
11573 (call-interactively 'org-table-recalculate)
11574 (org-table-maybe-recalculate-line))
11575 (call-interactively 'org-table-align)
11576 (orgtbl-send-table 'maybe))
11577 ((eq action 'recalc)
11578 (save-excursion
11579 (beginning-of-line 1)
11580 (skip-chars-backward " \r\n\t")
11581 (if (org-at-table-p)
11582 (org-call-with-arg 'org-table-recalculate t))))
11583 (t (let (orgtbl-mode)
11584 (call-interactively (key-binding "\C-c\C-c")))))))
11586 (defun orgtbl-tab (arg)
11587 "Justification and field motion for `orgtbl-mode'."
11588 (interactive "P")
11589 (if arg (org-table-edit-field t)
11590 (org-table-justify-field-maybe)
11591 (org-table-next-field)))
11593 (defun orgtbl-ret ()
11594 "Justification and field motion for `orgtbl-mode'."
11595 (interactive)
11596 (org-table-justify-field-maybe)
11597 (org-table-next-row))
11599 (defun orgtbl-self-insert-command (N)
11600 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11601 If the cursor is in a table looking at whitespace, the whitespace is
11602 overwritten, and the table is not marked as requiring realignment."
11603 (interactive "p")
11604 (if (and (org-at-table-p)
11606 (and org-table-auto-blank-field
11607 (member last-command
11608 '(orgtbl-hijacker-command-100
11609 orgtbl-hijacker-command-101
11610 orgtbl-hijacker-command-102
11611 orgtbl-hijacker-command-103
11612 orgtbl-hijacker-command-104
11613 orgtbl-hijacker-command-105))
11614 (org-table-blank-field))
11616 (eq N 1)
11617 (looking-at "[^|\n]* +|"))
11618 (let (org-table-may-need-update)
11619 (goto-char (1- (match-end 0)))
11620 (delete-backward-char 1)
11621 (goto-char (match-beginning 0))
11622 (self-insert-command N))
11623 (setq org-table-may-need-update t)
11624 (let (orgtbl-mode)
11625 (call-interactively (key-binding (vector last-input-event))))))
11627 (defun org-force-self-insert (N)
11628 "Needed to enforce self-insert under remapping."
11629 (interactive "p")
11630 (self-insert-command N))
11632 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11633 "Regula expression matching exponentials as produced by calc.")
11635 (defvar org-table-clean-did-remove-column nil)
11637 (defun orgtbl-export (table target)
11638 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11639 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11640 org-table-last-alignment org-table-last-column-widths
11641 maxcol column)
11642 (if (not (fboundp func))
11643 (error "Cannot export orgtbl table to %s" target))
11644 (setq lines (org-table-clean-before-export lines))
11645 (setq table
11646 (mapcar
11647 (lambda (x)
11648 (if (string-match org-table-hline-regexp x)
11649 'hline
11650 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11651 lines))
11652 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11653 table)))
11654 (loop for i from (1- maxcol) downto 0 do
11655 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11656 (setq column (delq nil column))
11657 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11658 (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))
11659 (funcall func table nil)))
11661 (defun orgtbl-send-table (&optional maybe)
11662 "Send a tranformed version of this table to the receiver position.
11663 With argument MAYBE, fail quietly if no transformation is defined for
11664 this table."
11665 (interactive)
11666 (catch 'exit
11667 (unless (org-at-table-p) (error "Not at a table"))
11668 ;; when non-interactive, we assume align has just happened.
11669 (when (interactive-p) (org-table-align))
11670 (save-excursion
11671 (goto-char (org-table-begin))
11672 (beginning-of-line 0)
11673 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11674 (if maybe
11675 (throw 'exit nil)
11676 (error "Don't know how to transform this table."))))
11677 (let* ((name (match-string 1))
11679 (transform (intern (match-string 2)))
11680 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11681 (skip (plist-get params :skip))
11682 (skipcols (plist-get params :skipcols))
11683 (txt (buffer-substring-no-properties
11684 (org-table-begin) (org-table-end)))
11685 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11686 (lines (org-table-clean-before-export lines))
11687 (i0 (if org-table-clean-did-remove-column 2 1))
11688 (table (mapcar
11689 (lambda (x)
11690 (if (string-match org-table-hline-regexp x)
11691 'hline
11692 (org-remove-by-index
11693 (org-split-string (org-trim x) "\\s-*|\\s-*")
11694 skipcols i0)))
11695 lines))
11696 (fun (if (= i0 2) 'cdr 'identity))
11697 (org-table-last-alignment
11698 (org-remove-by-index (funcall fun org-table-last-alignment)
11699 skipcols i0))
11700 (org-table-last-column-widths
11701 (org-remove-by-index (funcall fun org-table-last-column-widths)
11702 skipcols i0)))
11704 (unless (fboundp transform)
11705 (error "No such transformation function %s" transform))
11706 (setq txt (funcall transform table params))
11707 ;; Find the insertion place
11708 (save-excursion
11709 (goto-char (point-min))
11710 (unless (re-search-forward
11711 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11712 (error "Don't know where to insert translated table"))
11713 (goto-char (match-beginning 0))
11714 (beginning-of-line 2)
11715 (setq beg (point))
11716 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11717 (error "Cannot find end of insertion region"))
11718 (beginning-of-line 1)
11719 (delete-region beg (point))
11720 (goto-char beg)
11721 (insert txt "\n"))
11722 (message "Table converted and installed at receiver location"))))
11724 (defun org-remove-by-index (list indices &optional i0)
11725 "Remove the elements in LIST with indices in INDICES.
11726 First element has index 0, or I0 if given."
11727 (if (not indices)
11728 list
11729 (if (integerp indices) (setq indices (list indices)))
11730 (setq i0 (1- (or i0 0)))
11731 (delq :rm (mapcar (lambda (x)
11732 (setq i0 (1+ i0))
11733 (if (memq i0 indices) :rm x))
11734 list))))
11736 (defun orgtbl-toggle-comment ()
11737 "Comment or uncomment the orgtbl at point."
11738 (interactive)
11739 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11740 (re2 (concat "^" orgtbl-line-start-regexp))
11741 (commented (save-excursion (beginning-of-line 1)
11742 (cond ((looking-at re1) t)
11743 ((looking-at re2) nil)
11744 (t (error "Not at an org table")))))
11745 (re (if commented re1 re2))
11746 beg end)
11747 (save-excursion
11748 (beginning-of-line 1)
11749 (while (looking-at re) (beginning-of-line 0))
11750 (beginning-of-line 2)
11751 (setq beg (point))
11752 (while (looking-at re) (beginning-of-line 2))
11753 (setq end (point)))
11754 (comment-region beg end (if commented '(4) nil))))
11756 (defun orgtbl-insert-radio-table ()
11757 "Insert a radio table template appropriate for this major mode."
11758 (interactive)
11759 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11760 (txt (nth 1 e))
11761 name pos)
11762 (unless e (error "No radio table setup defined for %s" major-mode))
11763 (setq name (read-string "Table name: "))
11764 (while (string-match "%n" txt)
11765 (setq txt (replace-match name t t txt)))
11766 (or (bolp) (insert "\n"))
11767 (setq pos (point))
11768 (insert txt)
11769 (goto-char pos)))
11771 (defun org-get-param (params header i sym &optional hsym)
11772 "Get parameter value for symbol SYM.
11773 If this is a header line, actually get the value for the symbol with an
11774 additional \"h\" inserted after the colon.
11775 If the value is a protperty list, get the element for the current column.
11776 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11777 (let ((val (plist-get params sym)))
11778 (and hsym header (setq val (or (plist-get params hsym) val)))
11779 (if (consp val) (plist-get val i) val)))
11781 (defun orgtbl-to-generic (table params)
11782 "Convert the orgtbl-mode TABLE to some other format.
11783 This generic routine can be used for many standard cases.
11784 TABLE is a list, each entry either the symbol `hline' for a horizontal
11785 separator line, or a list of fields for that line.
11786 PARAMS is a property list of parameters that can influence the conversion.
11787 For the generic converter, some parameters are obligatory: You need to
11788 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11789 :splice, you must have :tstart and :tend.
11791 Valid parameters are
11793 :tstart String to start the table. Ignored when :splice is t.
11794 :tend String to end the table. Ignored when :splice is t.
11796 :splice When set to t, return only table body lines, don't wrap
11797 them into :tstart and :tend. Default is nil.
11799 :hline String to be inserted on horizontal separation lines.
11800 May be nil to ignore hlines.
11802 :lstart String to start a new table line.
11803 :lend String to end a table line
11804 :sep Separator between two fields
11805 :lfmt Format for entire line, with enough %s to capture all fields.
11806 If this is present, :lstart, :lend, and :sep are ignored.
11807 :fmt A format to be used to wrap the field, should contain
11808 %s for the original field value. For example, to wrap
11809 everything in dollars, you could use :fmt \"$%s$\".
11810 This may also be a property list with column numbers and
11811 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11813 :hlstart :hlend :hlsep :hlfmt :hfmt
11814 Same as above, specific for the header lines in the table.
11815 All lines before the first hline are treated as header.
11816 If any of these is not present, the data line value is used.
11818 :efmt Use this format to print numbers with exponentials.
11819 The format should have %s twice for inserting mantissa
11820 and exponent, for example \"%s\\\\times10^{%s}\". This
11821 may also be a property list with column numbers and
11822 formats. :fmt will still be applied after :efmt.
11824 In addition to this, the parameters :skip and :skipcols are always handled
11825 directly by `orgtbl-send-table'. See manual."
11826 (interactive)
11827 (let* ((p params)
11828 (splicep (plist-get p :splice))
11829 (hline (plist-get p :hline))
11830 rtn line i fm efm lfmt h)
11832 ;; Do we have a header?
11833 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11834 (setq h t))
11836 ;; Put header
11837 (unless splicep
11838 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11840 ;; Now loop over all lines
11841 (while (setq line (pop table))
11842 (if (eq line 'hline)
11843 ;; A horizontal separator line
11844 (progn (if hline (push hline rtn))
11845 (setq h nil)) ; no longer in header
11846 ;; A normal line. Convert the fields, push line onto the result list
11847 (setq i 0)
11848 (setq line
11849 (mapcar
11850 (lambda (f)
11851 (setq i (1+ i)
11852 fm (org-get-param p h i :fmt :hfmt)
11853 efm (org-get-param p h i :efmt))
11854 (if (and efm (string-match orgtbl-exp-regexp f))
11855 (setq f (format
11856 efm (match-string 1 f) (match-string 2 f))))
11857 (if fm (setq f (format fm f)))
11859 line))
11860 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11861 (push (apply 'format lfmt line) rtn)
11862 (push (concat
11863 (org-get-param p h i :lstart :hlstart)
11864 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11865 (org-get-param p h i :lend :hlend))
11866 rtn))))
11868 (unless splicep
11869 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11871 (mapconcat 'identity (nreverse rtn) "\n")))
11873 (defun orgtbl-to-latex (table params)
11874 "Convert the orgtbl-mode TABLE to LaTeX.
11875 TABLE is a list, each entry either the symbol `hline' for a horizontal
11876 separator line, or a list of fields for that line.
11877 PARAMS is a property list of parameters that can influence the conversion.
11878 Supports all parameters from `orgtbl-to-generic'. Most important for
11879 LaTeX are:
11881 :splice When set to t, return only table body lines, don't wrap
11882 them into a tabular environment. Default is nil.
11884 :fmt A format to be used to wrap the field, should contain %s for the
11885 original field value. For example, to wrap everything in dollars,
11886 use :fmt \"$%s$\". This may also be a property list with column
11887 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11889 :efmt Format for transforming numbers with exponentials. The format
11890 should have %s twice for inserting mantissa and exponent, for
11891 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11892 This may also be a property list with column numbers and formats.
11894 The general parameters :skip and :skipcols have already been applied when
11895 this function is called."
11896 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11897 org-table-last-alignment ""))
11898 (params2
11899 (list
11900 :tstart (concat "\\begin{tabular}{" alignment "}")
11901 :tend "\\end{tabular}"
11902 :lstart "" :lend " \\\\" :sep " & "
11903 :efmt "%s\\,(%s)" :hline "\\hline")))
11904 (orgtbl-to-generic table (org-combine-plists params2 params))))
11906 (defun orgtbl-to-html (table params)
11907 "Convert the orgtbl-mode TABLE to LaTeX.
11908 TABLE is a list, each entry either the symbol `hline' for a horizontal
11909 separator line, or a list of fields for that line.
11910 PARAMS is a property list of parameters that can influence the conversion.
11911 Currently this function recognizes the following parameters:
11913 :splice When set to t, return only table body lines, don't wrap
11914 them into a <table> environment. Default is nil.
11916 The general parameters :skip and :skipcols have already been applied when
11917 this function is called. The function does *not* use `orgtbl-to-generic',
11918 so you cannot specify parameters for it."
11919 (let* ((splicep (plist-get params :splice))
11920 html)
11921 ;; Just call the formatter we already have
11922 ;; We need to make text lines for it, so put the fields back together.
11923 (setq html (org-format-org-table-html
11924 (mapcar
11925 (lambda (x)
11926 (if (eq x 'hline)
11927 "|----+----|"
11928 (concat "| " (mapconcat 'identity x " | ") " |")))
11929 table)
11930 splicep))
11931 (if (string-match "\n+\\'" html)
11932 (setq html (replace-match "" t t html)))
11933 html))
11935 (defun orgtbl-to-texinfo (table params)
11936 "Convert the orgtbl-mode TABLE to TeXInfo.
11937 TABLE is a list, each entry either the symbol `hline' for a horizontal
11938 separator line, or a list of fields for that line.
11939 PARAMS is a property list of parameters that can influence the conversion.
11940 Supports all parameters from `orgtbl-to-generic'. Most important for
11941 TeXInfo are:
11943 :splice nil/t When set to t, return only table body lines, don't wrap
11944 them into a multitable environment. Default is nil.
11946 :fmt fmt A format to be used to wrap the field, should contain
11947 %s for the original field value. For example, to wrap
11948 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11949 This may also be a property list with column numbers and
11950 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11952 :cf \"f1 f2..\" The column fractions for the table. By default these
11953 are computed automatically from the width of the columns
11954 under org-mode.
11956 The general parameters :skip and :skipcols have already been applied when
11957 this function is called."
11958 (let* ((total (float (apply '+ org-table-last-column-widths)))
11959 (colfrac (or (plist-get params :cf)
11960 (mapconcat
11961 (lambda (x) (format "%.3f" (/ (float x) total)))
11962 org-table-last-column-widths " ")))
11963 (params2
11964 (list
11965 :tstart (concat "@multitable @columnfractions " colfrac)
11966 :tend "@end multitable"
11967 :lstart "@item " :lend "" :sep " @tab "
11968 :hlstart "@headitem ")))
11969 (orgtbl-to-generic table (org-combine-plists params2 params))))
11971 ;;;; Link Stuff
11973 ;;; Link abbreviations
11975 (defun org-link-expand-abbrev (link)
11976 "Apply replacements as defined in `org-link-abbrev-alist."
11977 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11978 (let* ((key (match-string 1 link))
11979 (as (or (assoc key org-link-abbrev-alist-local)
11980 (assoc key org-link-abbrev-alist)))
11981 (tag (and (match-end 2) (match-string 3 link)))
11982 rpl)
11983 (if (not as)
11984 link
11985 (setq rpl (cdr as))
11986 (cond
11987 ((symbolp rpl) (funcall rpl tag))
11988 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11989 (t (concat rpl tag)))))
11990 link))
11992 ;;; Storing and inserting links
11994 (defvar org-insert-link-history nil
11995 "Minibuffer history for links inserted with `org-insert-link'.")
11997 (defvar org-stored-links nil
11998 "Contains the links stored with `org-store-link'.")
12000 (defvar org-store-link-plist nil
12001 "Plist with info about the most recently link created with `org-store-link'.")
12003 (defvar org-link-protocols nil
12004 "Link protocols added to Org-mode using `org-add-link-type'.")
12006 (defvar org-store-link-functions nil
12007 "List of functions that are called to create and store a link.
12008 Each function will be called in turn until one returns a non-nil
12009 value. Each function should check if it is responsible for creating
12010 this link (for example by looking at the major mode).
12011 If not, it must exit and return nil.
12012 If yes, it should return a non-nil value after a calling
12013 `org-store-link-props' with a list of properties and values.
12014 Special properties are:
12016 :type The link prefix. like \"http\". This must be given.
12017 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12018 This is obligatory as well.
12019 :description Optional default description for the second pair
12020 of brackets in an Org-mode link. The user can still change
12021 this when inserting this link into an Org-mode buffer.
12023 In addition to these, any additional properties can be specified
12024 and then used in remember templates.")
12026 (defun org-add-link-type (type &optional follow publish)
12027 "Add TYPE to the list of `org-link-types'.
12028 Re-compute all regular expressions depending on `org-link-types'
12029 FOLLOW and PUBLISH are two functions. Both take the link path as
12030 an argument.
12031 FOLLOW should do whatever is necessary to follow the link, for example
12032 to find a file or display a mail message.
12034 PUBLISH takes the path and retuns the string that should be used when
12035 this document is published. FIMXE: This is actually not yet implemented."
12036 (add-to-list 'org-link-types type t)
12037 (org-make-link-regexps)
12038 (add-to-list 'org-link-protocols
12039 (list type follow publish)))
12041 (defun org-add-agenda-custom-command (entry)
12042 "Replace or add a command in `org-agenda-custom-commands'.
12043 This is mostly for hacking and trying a new command - once the command
12044 works you probably want to add it to `org-agenda-custom-commands' for good."
12045 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12046 (if ass
12047 (setcdr ass (cdr entry))
12048 (push entry org-agenda-custom-commands))))
12050 ;;;###autoload
12051 (defun org-store-link (arg)
12052 "\\<org-mode-map>Store an org-link to the current location.
12053 This link is added to `org-stored-links' and can later be inserted
12054 into an org-buffer with \\[org-insert-link].
12056 For some link types, a prefix arg is interpreted:
12057 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12058 For file links, arg negates `org-context-in-file-links'."
12059 (interactive "P")
12060 (setq org-store-link-plist nil) ; reset
12061 (let (link cpltxt desc description search txt)
12062 (cond
12064 ((run-hook-with-args-until-success 'org-store-link-functions)
12065 (setq link (plist-get org-store-link-plist :link)
12066 desc (or (plist-get org-store-link-plist :description) link)))
12068 ((eq major-mode 'bbdb-mode)
12069 (let ((name (bbdb-record-name (bbdb-current-record)))
12070 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12071 (setq cpltxt (concat "bbdb:" (or name company))
12072 link (org-make-link cpltxt))
12073 (org-store-link-props :type "bbdb" :name name :company company)))
12075 ((eq major-mode 'Info-mode)
12076 (setq link (org-make-link "info:"
12077 (file-name-nondirectory Info-current-file)
12078 ":" Info-current-node))
12079 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12080 ":" Info-current-node))
12081 (org-store-link-props :type "info" :file Info-current-file
12082 :node Info-current-node))
12084 ((eq major-mode 'calendar-mode)
12085 (let ((cd (calendar-cursor-to-date)))
12086 (setq link
12087 (format-time-string
12088 (car org-time-stamp-formats)
12089 (apply 'encode-time
12090 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12091 nil nil nil))))
12092 (org-store-link-props :type "calendar" :date cd)))
12094 ((or (eq major-mode 'vm-summary-mode)
12095 (eq major-mode 'vm-presentation-mode))
12096 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12097 (vm-follow-summary-cursor)
12098 (save-excursion
12099 (vm-select-folder-buffer)
12100 (let* ((message (car vm-message-pointer))
12101 (folder buffer-file-name)
12102 (subject (vm-su-subject message))
12103 (to (vm-get-header-contents message "To"))
12104 (from (vm-get-header-contents message "From"))
12105 (message-id (vm-su-message-id message)))
12106 (org-store-link-props :type "vm" :from from :to to :subject subject
12107 :message-id message-id)
12108 (setq message-id (org-remove-angle-brackets message-id))
12109 (setq folder (abbreviate-file-name folder))
12110 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12111 folder)
12112 (setq folder (replace-match "" t t folder)))
12113 (setq cpltxt (org-email-link-description))
12114 (setq link (org-make-link "vm:" folder "#" message-id)))))
12116 ((eq major-mode 'wl-summary-mode)
12117 (let* ((msgnum (wl-summary-message-number))
12118 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12119 msgnum 'message-id))
12120 (wl-message-entity
12121 (if (fboundp 'elmo-message-entity)
12122 (elmo-message-entity
12123 wl-summary-buffer-elmo-folder msgnum)
12124 (elmo-msgdb-overview-get-entity
12125 msgnum (wl-summary-buffer-msgdb))))
12126 (from (wl-summary-line-from))
12127 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12128 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12129 (wl-summary-line-subject))))
12130 (org-store-link-props :type "wl" :from from :to to
12131 :subject subject :message-id message-id)
12132 (setq message-id (org-remove-angle-brackets message-id))
12133 (setq cpltxt (org-email-link-description))
12134 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12135 "#" message-id))))
12137 ((or (equal major-mode 'mh-folder-mode)
12138 (equal major-mode 'mh-show-mode))
12139 (let ((from (org-mhe-get-header "From:"))
12140 (to (org-mhe-get-header "To:"))
12141 (message-id (org-mhe-get-header "Message-Id:"))
12142 (subject (org-mhe-get-header "Subject:")))
12143 (org-store-link-props :type "mh" :from from :to to
12144 :subject subject :message-id message-id)
12145 (setq cpltxt (org-email-link-description))
12146 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12147 (org-remove-angle-brackets message-id)))))
12149 ((or (eq major-mode 'rmail-mode)
12150 (eq major-mode 'rmail-summary-mode))
12151 (save-window-excursion
12152 (save-restriction
12153 (when (eq major-mode 'rmail-summary-mode)
12154 (rmail-show-message rmail-current-message))
12155 (rmail-narrow-to-non-pruned-header)
12156 (let ((folder buffer-file-name)
12157 (message-id (mail-fetch-field "message-id"))
12158 (from (mail-fetch-field "from"))
12159 (to (mail-fetch-field "to"))
12160 (subject (mail-fetch-field "subject")))
12161 (org-store-link-props
12162 :type "rmail" :from from :to to
12163 :subject subject :message-id message-id)
12164 (setq message-id (org-remove-angle-brackets message-id))
12165 (setq cpltxt (org-email-link-description))
12166 (setq link (org-make-link "rmail:" folder "#" message-id)))
12167 (rmail-show-message rmail-current-message))))
12169 ((eq major-mode 'gnus-group-mode)
12170 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12171 (gnus-group-group-name)) ; version
12172 ((fboundp 'gnus-group-name)
12173 (gnus-group-name))
12174 (t "???"))))
12175 (unless group (error "Not on a group"))
12176 (org-store-link-props :type "gnus" :group group)
12177 (setq cpltxt (concat
12178 (if (org-xor arg org-usenet-links-prefer-google)
12179 "http://groups.google.com/groups?group="
12180 "gnus:")
12181 group)
12182 link (org-make-link cpltxt))))
12184 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12185 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12186 (let* ((group gnus-newsgroup-name)
12187 (article (gnus-summary-article-number))
12188 (header (gnus-summary-article-header article))
12189 (from (mail-header-from header))
12190 (message-id (mail-header-id header))
12191 (date (mail-header-date header))
12192 (subject (gnus-summary-subject-string)))
12193 (org-store-link-props :type "gnus" :from from :subject subject
12194 :message-id message-id :group group)
12195 (setq cpltxt (org-email-link-description))
12196 (if (org-xor arg org-usenet-links-prefer-google)
12197 (setq link
12198 (concat
12199 cpltxt "\n "
12200 (format "http://groups.google.com/groups?as_umsgid=%s"
12201 (org-fixup-message-id-for-http message-id))))
12202 (setq link (org-make-link "gnus:" group
12203 "#" (number-to-string article))))))
12205 ((eq major-mode 'w3-mode)
12206 (setq cpltxt (url-view-url t)
12207 link (org-make-link cpltxt))
12208 (org-store-link-props :type "w3" :url (url-view-url t)))
12210 ((eq major-mode 'w3m-mode)
12211 (setq cpltxt (or w3m-current-title w3m-current-url)
12212 link (org-make-link w3m-current-url))
12213 (org-store-link-props :type "w3m" :url (url-view-url t)))
12215 ((setq search (run-hook-with-args-until-success
12216 'org-create-file-search-functions))
12217 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12218 "::" search))
12219 (setq cpltxt (or description link)))
12221 ((eq major-mode 'image-mode)
12222 (setq cpltxt (concat "file:"
12223 (abbreviate-file-name buffer-file-name))
12224 link (org-make-link cpltxt))
12225 (org-store-link-props :type "image" :file buffer-file-name))
12227 ((eq major-mode 'dired-mode)
12228 ;; link to the file in the current line
12229 (setq cpltxt (concat "file:"
12230 (abbreviate-file-name
12231 (expand-file-name
12232 (dired-get-filename nil t))))
12233 link (org-make-link cpltxt)))
12235 ((and buffer-file-name (org-mode-p))
12236 ;; Just link to current headline
12237 (setq cpltxt (concat "file:"
12238 (abbreviate-file-name buffer-file-name)))
12239 ;; Add a context search string
12240 (when (org-xor org-context-in-file-links arg)
12241 ;; Check if we are on a target
12242 (if (org-in-regexp "<<\\(.*?\\)>>")
12243 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12244 (setq txt (cond
12245 ((org-on-heading-p) nil)
12246 ((org-region-active-p)
12247 (buffer-substring (region-beginning) (region-end)))
12248 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12249 (when (or (null txt) (string-match "\\S-" txt))
12250 (setq cpltxt
12251 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12252 desc "NONE"))))
12253 (if (string-match "::\\'" cpltxt)
12254 (setq cpltxt (substring cpltxt 0 -2)))
12255 (setq link (org-make-link cpltxt)))
12257 ((buffer-file-name (buffer-base-buffer))
12258 ;; Just link to this file here.
12259 (setq cpltxt (concat "file:"
12260 (abbreviate-file-name
12261 (buffer-file-name (buffer-base-buffer)))))
12262 ;; Add a context string
12263 (when (org-xor org-context-in-file-links arg)
12264 (setq txt (if (org-region-active-p)
12265 (buffer-substring (region-beginning) (region-end))
12266 (buffer-substring (point-at-bol) (point-at-eol))))
12267 ;; Only use search option if there is some text.
12268 (when (string-match "\\S-" txt)
12269 (setq cpltxt
12270 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12271 desc "NONE")))
12272 (setq link (org-make-link cpltxt)))
12274 ((interactive-p)
12275 (error "Cannot link to a buffer which is not visiting a file"))
12277 (t (setq link nil)))
12279 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12280 (setq link (or link cpltxt)
12281 desc (or desc cpltxt))
12282 (if (equal desc "NONE") (setq desc nil))
12284 (if (and (interactive-p) link)
12285 (progn
12286 (setq org-stored-links
12287 (cons (list link desc) org-stored-links))
12288 (message "Stored: %s" (or desc link)))
12289 (and link (org-make-link-string link desc)))))
12291 (defun org-store-link-props (&rest plist)
12292 "Store link properties, extract names and addresses."
12293 (let (x adr)
12294 (when (setq x (plist-get plist :from))
12295 (setq adr (mail-extract-address-components x))
12296 (plist-put plist :fromname (car adr))
12297 (plist-put plist :fromaddress (nth 1 adr)))
12298 (when (setq x (plist-get plist :to))
12299 (setq adr (mail-extract-address-components x))
12300 (plist-put plist :toname (car adr))
12301 (plist-put plist :toaddress (nth 1 adr))))
12302 (let ((from (plist-get plist :from))
12303 (to (plist-get plist :to)))
12304 (when (and from to org-from-is-user-regexp)
12305 (plist-put plist :fromto
12306 (if (string-match org-from-is-user-regexp from)
12307 (concat "to %t")
12308 (concat "from %f")))))
12309 (setq org-store-link-plist plist))
12311 (defun org-email-link-description (&optional fmt)
12312 "Return the description part of an email link.
12313 This takes information from `org-store-link-plist' and formats it
12314 according to FMT (default from `org-email-link-description-format')."
12315 (setq fmt (or fmt org-email-link-description-format))
12316 (let* ((p org-store-link-plist)
12317 (to (plist-get p :toaddress))
12318 (from (plist-get p :fromaddress))
12319 (table
12320 (list
12321 (cons "%c" (plist-get p :fromto))
12322 (cons "%F" (plist-get p :from))
12323 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12324 (cons "%T" (plist-get p :to))
12325 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12326 (cons "%s" (plist-get p :subject))
12327 (cons "%m" (plist-get p :message-id)))))
12328 (when (string-match "%c" fmt)
12329 ;; Check if the user wrote this message
12330 (if (and org-from-is-user-regexp from to
12331 (save-match-data (string-match org-from-is-user-regexp from)))
12332 (setq fmt (replace-match "to %t" t t fmt))
12333 (setq fmt (replace-match "from %f" t t fmt))))
12334 (org-replace-escapes fmt table)))
12336 (defun org-make-org-heading-search-string (&optional string heading)
12337 "Make search string for STRING or current headline."
12338 (interactive)
12339 (let ((s (or string (org-get-heading))))
12340 (unless (and string (not heading))
12341 ;; We are using a headline, clean up garbage in there.
12342 (if (string-match org-todo-regexp s)
12343 (setq s (replace-match "" t t s)))
12344 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12345 (setq s (replace-match "" t t s)))
12346 (setq s (org-trim s))
12347 (if (string-match (concat "^\\(" org-quote-string "\\|"
12348 org-comment-string "\\)") s)
12349 (setq s (replace-match "" t t s)))
12350 (while (string-match org-ts-regexp s)
12351 (setq s (replace-match "" t t s))))
12352 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12353 (setq s (replace-match " " t t s)))
12354 (or string (setq s (concat "*" s))) ; Add * for headlines
12355 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12357 (defun org-make-link (&rest strings)
12358 "Concatenate STRINGS."
12359 (apply 'concat strings))
12361 (defun org-make-link-string (link &optional description)
12362 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12363 (unless (string-match "\\S-" link)
12364 (error "Empty link"))
12365 (when (stringp description)
12366 ;; Remove brackets from the description, they are fatal.
12367 (while (string-match "\\[" description)
12368 (setq description (replace-match "{" t t description)))
12369 (while (string-match "\\]" description)
12370 (setq description (replace-match "}" t t description))))
12371 (when (equal (org-link-escape link) description)
12372 ;; No description needed, it is identical
12373 (setq description nil))
12374 (when (and (not description)
12375 (not (equal link (org-link-escape link))))
12376 (setq description link))
12377 (concat "[[" (org-link-escape link) "]"
12378 (if description (concat "[" description "]") "")
12379 "]"))
12381 (defconst org-link-escape-chars
12382 '((?\ . "%20")
12383 (?\[ . "%5B")
12384 (?\] . "%5D")
12385 (?\340 . "%E0") ; `a
12386 (?\342 . "%E2") ; ^a
12387 (?\347 . "%E7") ; ,c
12388 (?\350 . "%E8") ; `e
12389 (?\351 . "%E9") ; 'e
12390 (?\352 . "%EA") ; ^e
12391 (?\356 . "%EE") ; ^i
12392 (?\364 . "%F4") ; ^o
12393 (?\371 . "%F9") ; `u
12394 (?\373 . "%FB") ; ^u
12395 (?\; . "%3B")
12396 (?? . "%3F")
12397 (?= . "%3D")
12398 (?+ . "%2B")
12400 "Association list of escapes for some characters problematic in links.
12401 This is the list that is used for internal purposes.")
12403 (defconst org-link-escape-chars-browser
12404 '((?\ . "%20")) ; 32 for the SPC char
12405 "Association list of escapes for some characters problematic in links.
12406 This is the list that is used before handing over to the browser.")
12408 (defun org-link-escape (text &optional table)
12409 "Escape charaters in TEXT that are problematic for links."
12410 (setq table (or table org-link-escape-chars))
12411 (when text
12412 (let ((re (mapconcat (lambda (x) (regexp-quote
12413 (char-to-string (car x))))
12414 table "\\|")))
12415 (while (string-match re text)
12416 (setq text
12417 (replace-match
12418 (cdr (assoc (string-to-char (match-string 0 text))
12419 table))
12420 t t text)))
12421 text)))
12423 (defun org-link-unescape (text &optional table)
12424 "Reverse the action of `org-link-escape'."
12425 (setq table (or table org-link-escape-chars))
12426 (when text
12427 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12428 table "\\|")))
12429 (while (string-match re text)
12430 (setq text
12431 (replace-match
12432 (char-to-string (car (rassoc (match-string 0 text) table)))
12433 t t text)))
12434 text)))
12436 (defun org-xor (a b)
12437 "Exclusive or."
12438 (if a (not b) b))
12440 (defun org-get-header (header)
12441 "Find a header field in the current buffer."
12442 (save-excursion
12443 (goto-char (point-min))
12444 (let ((case-fold-search t) s)
12445 (cond
12446 ((eq header 'from)
12447 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12448 (setq s (match-string 1)))
12449 (while (string-match "\"" s)
12450 (setq s (replace-match "" t t s)))
12451 (if (string-match "[<(].*" s)
12452 (setq s (replace-match "" t t s))))
12453 ((eq header 'message-id)
12454 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12455 (setq s (match-string 1))))
12456 ((eq header 'subject)
12457 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12458 (setq s (match-string 1)))))
12459 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12460 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12461 s)))
12464 (defun org-fixup-message-id-for-http (s)
12465 "Replace special characters in a message id, so it can be used in an http query."
12466 (while (string-match "<" s)
12467 (setq s (replace-match "%3C" t t s)))
12468 (while (string-match ">" s)
12469 (setq s (replace-match "%3E" t t s)))
12470 (while (string-match "@" s)
12471 (setq s (replace-match "%40" t t s)))
12474 ;;;###autoload
12475 (defun org-insert-link-global ()
12476 "Insert a link like Org-mode does.
12477 This command can be called in any mode to insert a link in Org-mode syntax."
12478 (interactive)
12479 (org-run-like-in-org-mode 'org-insert-link))
12481 (defun org-insert-link (&optional complete-file)
12482 "Insert a link. At the prompt, enter the link.
12484 Completion can be used to select a link previously stored with
12485 `org-store-link'. When the empty string is entered (i.e. if you just
12486 press RET at the prompt), the link defaults to the most recently
12487 stored link. As SPC triggers completion in the minibuffer, you need to
12488 use M-SPC or C-q SPC to force the insertion of a space character.
12490 You will also be prompted for a description, and if one is given, it will
12491 be displayed in the buffer instead of the link.
12493 If there is already a link at point, this command will allow you to edit link
12494 and description parts.
12496 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12497 selected using completion. The path to the file will be relative to
12498 the current directory if the file is in the current directory or a
12499 subdirectory. Otherwise, the link will be the absolute path as
12500 completed in the minibuffer (i.e. normally ~/path/to/file).
12502 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12503 is in the current directory or below.
12504 With three \\[universal-argument] prefixes, negate the meaning of
12505 `org-keep-stored-link-after-insertion'."
12506 (interactive "P")
12507 (let* ((wcf (current-window-configuration))
12508 (region (if (org-region-active-p)
12509 (buffer-substring (region-beginning) (region-end))))
12510 (remove (and region (list (region-beginning) (region-end))))
12511 (desc region)
12512 tmphist ; byte-compile incorrectly complains about this
12513 link entry file)
12514 (cond
12515 ((org-in-regexp org-bracket-link-regexp 1)
12516 ;; We do have a link at point, and we are going to edit it.
12517 (setq remove (list (match-beginning 0) (match-end 0)))
12518 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12519 (setq link (read-string "Link: "
12520 (org-link-unescape
12521 (org-match-string-no-properties 1)))))
12522 ((or (org-in-regexp org-angle-link-re)
12523 (org-in-regexp org-plain-link-re))
12524 ;; Convert to bracket link
12525 (setq remove (list (match-beginning 0) (match-end 0))
12526 link (read-string "Link: "
12527 (org-remove-angle-brackets (match-string 0)))))
12528 ((equal complete-file '(4))
12529 ;; Completing read for file names.
12530 (setq file (read-file-name "File: "))
12531 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12532 (pwd1 (file-name-as-directory (abbreviate-file-name
12533 (expand-file-name ".")))))
12534 (cond
12535 ((equal complete-file '(16))
12536 (setq link (org-make-link
12537 "file:"
12538 (abbreviate-file-name (expand-file-name file)))))
12539 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12540 (setq link (org-make-link "file:" (match-string 1 file))))
12541 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12542 (expand-file-name file))
12543 (setq link (org-make-link
12544 "file:" (match-string 1 (expand-file-name file)))))
12545 (t (setq link (org-make-link "file:" file))))))
12547 ;; Read link, with completion for stored links.
12548 (with-output-to-temp-buffer "*Org Links*"
12549 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12550 (when org-stored-links
12551 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12552 (princ (mapconcat
12553 (lambda (x)
12554 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12555 (reverse org-stored-links) "\n"))))
12556 (let ((cw (selected-window)))
12557 (select-window (get-buffer-window "*Org Links*"))
12558 (shrink-window-if-larger-than-buffer)
12559 (setq truncate-lines t)
12560 (select-window cw))
12561 ;; Fake a link history, containing the stored links.
12562 (setq tmphist (append (mapcar 'car org-stored-links)
12563 org-insert-link-history))
12564 (unwind-protect
12565 (setq link (org-completing-read
12566 "Link: "
12567 (append
12568 (mapcar (lambda (x) (list (concat (car x) ":")))
12569 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12570 (mapcar (lambda (x) (list (concat x ":")))
12571 org-link-types))
12572 nil nil nil
12573 'tmphist
12574 (or (car (car org-stored-links)))))
12575 (set-window-configuration wcf)
12576 (kill-buffer "*Org Links*"))
12577 (setq entry (assoc link org-stored-links))
12578 (or entry (push link org-insert-link-history))
12579 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12580 (not org-keep-stored-link-after-insertion))
12581 (setq org-stored-links (delq (assoc link org-stored-links)
12582 org-stored-links)))
12583 (setq desc (or desc (nth 1 entry)))))
12585 (if (string-match org-plain-link-re link)
12586 ;; URL-like link, normalize the use of angular brackets.
12587 (setq link (org-make-link (org-remove-angle-brackets link))))
12589 ;; Check if we are linking to the current file with a search option
12590 ;; If yes, simplify the link by using only the search option.
12591 (when (and buffer-file-name
12592 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12593 (let* ((path (match-string 1 link))
12594 (case-fold-search nil)
12595 (search (match-string 2 link)))
12596 (save-match-data
12597 (if (equal (file-truename buffer-file-name) (file-truename path))
12598 ;; We are linking to this same file, with a search option
12599 (setq link search)))))
12601 ;; Check if we can/should use a relative path. If yes, simplify the link
12602 (when (string-match "\\<file:\\(.*\\)" link)
12603 (let* ((path (match-string 1 link))
12604 (origpath path)
12605 (case-fold-search nil))
12606 (cond
12607 ((eq org-link-file-path-type 'absolute)
12608 (setq path (abbreviate-file-name (expand-file-name path))))
12609 ((eq org-link-file-path-type 'noabbrev)
12610 (setq path (expand-file-name path)))
12611 ((eq org-link-file-path-type 'relative)
12612 (setq path (file-relative-name path)))
12614 (save-match-data
12615 (if (string-match (concat "^" (regexp-quote
12616 (file-name-as-directory
12617 (expand-file-name "."))))
12618 (expand-file-name path))
12619 ;; We are linking a file with relative path name.
12620 (setq path (substring (expand-file-name path)
12621 (match-end 0)))))))
12622 (setq link (concat "file:" path))
12623 (if (equal desc origpath)
12624 (setq desc path))))
12626 (setq desc (read-string "Description: " desc))
12627 (unless (string-match "\\S-" desc) (setq desc nil))
12628 (if remove (apply 'delete-region remove))
12629 (insert (org-make-link-string link desc))))
12631 (defun org-completing-read (&rest args)
12632 (let ((minibuffer-local-completion-map
12633 (copy-keymap minibuffer-local-completion-map)))
12634 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12635 (apply 'completing-read args)))
12637 ;;; Opening/following a link
12638 (defvar org-link-search-failed nil)
12640 (defun org-next-link ()
12641 "Move forward to the next link.
12642 If the link is in hidden text, expose it."
12643 (interactive)
12644 (when (and org-link-search-failed (eq this-command last-command))
12645 (goto-char (point-min))
12646 (message "Link search wrapped back to beginning of buffer"))
12647 (setq org-link-search-failed nil)
12648 (let* ((pos (point))
12649 (ct (org-context))
12650 (a (assoc :link ct)))
12651 (if a (goto-char (nth 2 a)))
12652 (if (re-search-forward org-any-link-re nil t)
12653 (progn
12654 (goto-char (match-beginning 0))
12655 (if (org-invisible-p) (org-show-context)))
12656 (goto-char pos)
12657 (setq org-link-search-failed t)
12658 (error "No further link found"))))
12660 (defun org-previous-link ()
12661 "Move backward to the previous link.
12662 If the link is in hidden text, expose it."
12663 (interactive)
12664 (when (and org-link-search-failed (eq this-command last-command))
12665 (goto-char (point-max))
12666 (message "Link search wrapped back to end of buffer"))
12667 (setq org-link-search-failed nil)
12668 (let* ((pos (point))
12669 (ct (org-context))
12670 (a (assoc :link ct)))
12671 (if a (goto-char (nth 1 a)))
12672 (if (re-search-backward org-any-link-re nil t)
12673 (progn
12674 (goto-char (match-beginning 0))
12675 (if (org-invisible-p) (org-show-context)))
12676 (goto-char pos)
12677 (setq org-link-search-failed t)
12678 (error "No further link found"))))
12680 (defun org-find-file-at-mouse (ev)
12681 "Open file link or URL at mouse."
12682 (interactive "e")
12683 (mouse-set-point ev)
12684 (org-open-at-point 'in-emacs))
12686 (defun org-open-at-mouse (ev)
12687 "Open file link or URL at mouse."
12688 (interactive "e")
12689 (mouse-set-point ev)
12690 (org-open-at-point))
12692 (defvar org-window-config-before-follow-link nil
12693 "The window configuration before following a link.
12694 This is saved in case the need arises to restore it.")
12696 (defvar org-open-link-marker (make-marker)
12697 "Marker pointing to the location where `org-open-at-point; was called.")
12699 ;;;###autoload
12700 (defun org-open-at-point-global ()
12701 "Follow a link like Org-mode does.
12702 This command can be called in any mode to follow a link that has
12703 Org-mode syntax."
12704 (interactive)
12705 (org-run-like-in-org-mode 'org-open-at-point))
12707 (defun org-open-at-point (&optional in-emacs)
12708 "Open link at or after point.
12709 If there is no link at point, this function will search forward up to
12710 the end of the current subtree.
12711 Normally, files will be opened by an appropriate application. If the
12712 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12713 (interactive "P")
12714 (move-marker org-open-link-marker (point))
12715 (setq org-window-config-before-follow-link (current-window-configuration))
12716 (org-remove-occur-highlights nil nil t)
12717 (if (org-at-timestamp-p t)
12718 (org-follow-timestamp-link)
12719 (let (type path link line search (pos (point)))
12720 (catch 'match
12721 (save-excursion
12722 (skip-chars-forward "^]\n\r")
12723 (when (org-in-regexp org-bracket-link-regexp)
12724 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12725 (while (string-match " *\n *" link)
12726 (setq link (replace-match " " t t link)))
12727 (setq link (org-link-expand-abbrev link))
12728 (if (string-match org-link-re-with-space2 link)
12729 (setq type (match-string 1 link) path (match-string 2 link))
12730 (setq type "thisfile" path link))
12731 (throw 'match t)))
12733 (when (get-text-property (point) 'org-linked-text)
12734 (setq type "thisfile"
12735 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12736 (1+ (point)) (point))
12737 path (buffer-substring
12738 (previous-single-property-change pos 'org-linked-text)
12739 (next-single-property-change pos 'org-linked-text)))
12740 (throw 'match t))
12742 (save-excursion
12743 (when (or (org-in-regexp org-angle-link-re)
12744 (org-in-regexp org-plain-link-re))
12745 (setq type (match-string 1) path (match-string 2))
12746 (throw 'match t)))
12747 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12748 (setq type "tree-match"
12749 path (match-string 1))
12750 (throw 'match t))
12751 (save-excursion
12752 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12753 (setq type "tags"
12754 path (match-string 1))
12755 (while (string-match ":" path)
12756 (setq path (replace-match "+" t t path)))
12757 (throw 'match t))))
12758 (unless path
12759 (error "No link found"))
12760 ;; Remove any trailing spaces in path
12761 (if (string-match " +\\'" path)
12762 (setq path (replace-match "" t t path)))
12764 (cond
12766 ((assoc type org-link-protocols)
12767 (funcall (nth 1 (assoc type org-link-protocols)) path))
12769 ((equal type "mailto")
12770 (let ((cmd (car org-link-mailto-program))
12771 (args (cdr org-link-mailto-program)) args1
12772 (address path) (subject "") a)
12773 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12774 (setq address (match-string 1 path)
12775 subject (org-link-escape (match-string 2 path))))
12776 (while args
12777 (cond
12778 ((not (stringp (car args))) (push (pop args) args1))
12779 (t (setq a (pop args))
12780 (if (string-match "%a" a)
12781 (setq a (replace-match address t t a)))
12782 (if (string-match "%s" a)
12783 (setq a (replace-match subject t t a)))
12784 (push a args1))))
12785 (apply cmd (nreverse args1))))
12787 ((member type '("http" "https" "ftp" "news"))
12788 (browse-url (concat type ":" (org-link-escape
12789 path org-link-escape-chars-browser))))
12791 ((member type '("message"))
12792 (browse-url (concat type ":" path)))
12794 ((string= type "tags")
12795 (org-tags-view in-emacs path))
12796 ((string= type "thisfile")
12797 (if in-emacs
12798 (switch-to-buffer-other-window
12799 (org-get-buffer-for-internal-link (current-buffer)))
12800 (org-mark-ring-push))
12801 (let ((cmd `(org-link-search
12802 ,path
12803 ,(cond ((equal in-emacs '(4)) 'occur)
12804 ((equal in-emacs '(16)) 'org-occur)
12805 (t nil))
12806 ,pos)))
12807 (condition-case nil (eval cmd)
12808 (error (progn (widen) (eval cmd))))))
12810 ((string= type "tree-match")
12811 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12813 ((string= type "file")
12814 (if (string-match "::\\([0-9]+\\)\\'" path)
12815 (setq line (string-to-number (match-string 1 path))
12816 path (substring path 0 (match-beginning 0)))
12817 (if (string-match "::\\(.+\\)\\'" path)
12818 (setq search (match-string 1 path)
12819 path (substring path 0 (match-beginning 0)))))
12820 (if (string-match "[*?{]" (file-name-nondirectory path))
12821 (dired path)
12822 (org-open-file path in-emacs line search)))
12824 ((string= type "news")
12825 (org-follow-gnus-link path))
12827 ((string= type "bbdb")
12828 (org-follow-bbdb-link path))
12830 ((string= type "info")
12831 (org-follow-info-link path))
12833 ((string= type "gnus")
12834 (let (group article)
12835 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12836 (error "Error in Gnus link"))
12837 (setq group (match-string 1 path)
12838 article (match-string 3 path))
12839 (org-follow-gnus-link group article)))
12841 ((string= type "vm")
12842 (let (folder article)
12843 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12844 (error "Error in VM link"))
12845 (setq folder (match-string 1 path)
12846 article (match-string 3 path))
12847 ;; in-emacs is the prefix arg, will be interpreted as read-only
12848 (org-follow-vm-link folder article in-emacs)))
12850 ((string= type "wl")
12851 (let (folder article)
12852 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12853 (error "Error in Wanderlust link"))
12854 (setq folder (match-string 1 path)
12855 article (match-string 3 path))
12856 (org-follow-wl-link folder article)))
12858 ((string= type "mhe")
12859 (let (folder article)
12860 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12861 (error "Error in MHE link"))
12862 (setq folder (match-string 1 path)
12863 article (match-string 3 path))
12864 (org-follow-mhe-link folder article)))
12866 ((string= type "rmail")
12867 (let (folder article)
12868 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12869 (error "Error in RMAIL link"))
12870 (setq folder (match-string 1 path)
12871 article (match-string 3 path))
12872 (org-follow-rmail-link folder article)))
12874 ((string= type "shell")
12875 (let ((cmd path))
12876 (if (or (not org-confirm-shell-link-function)
12877 (funcall org-confirm-shell-link-function
12878 (format "Execute \"%s\" in shell? "
12879 (org-add-props cmd nil
12880 'face 'org-warning))))
12881 (progn
12882 (message "Executing %s" cmd)
12883 (shell-command cmd))
12884 (error "Abort"))))
12886 ((string= type "elisp")
12887 (let ((cmd path))
12888 (if (or (not org-confirm-elisp-link-function)
12889 (funcall org-confirm-elisp-link-function
12890 (format "Execute \"%s\" as elisp? "
12891 (org-add-props cmd nil
12892 'face 'org-warning))))
12893 (message "%s => %s" cmd (eval (read cmd)))
12894 (error "Abort"))))
12897 (browse-url-at-point)))))
12898 (move-marker org-open-link-marker nil))
12900 ;;; File search
12902 (defvar org-create-file-search-functions nil
12903 "List of functions to construct the right search string for a file link.
12904 These functions are called in turn with point at the location to
12905 which the link should point.
12907 A function in the hook should first test if it would like to
12908 handle this file type, for example by checking the major-mode or
12909 the file extension. If it decides not to handle this file, it
12910 should just return nil to give other functions a chance. If it
12911 does handle the file, it must return the search string to be used
12912 when following the link. The search string will be part of the
12913 file link, given after a double colon, and `org-open-at-point'
12914 will automatically search for it. If special measures must be
12915 taken to make the search successful, another function should be
12916 added to the companion hook `org-execute-file-search-functions',
12917 which see.
12919 A function in this hook may also use `setq' to set the variable
12920 `description' to provide a suggestion for the descriptive text to
12921 be used for this link when it gets inserted into an Org-mode
12922 buffer with \\[org-insert-link].")
12924 (defvar org-execute-file-search-functions nil
12925 "List of functions to execute a file search triggered by a link.
12927 Functions added to this hook must accept a single argument, the
12928 search string that was part of the file link, the part after the
12929 double colon. The function must first check if it would like to
12930 handle this search, for example by checking the major-mode or the
12931 file extension. If it decides not to handle this search, it
12932 should just return nil to give other functions a chance. If it
12933 does handle the search, it must return a non-nil value to keep
12934 other functions from trying.
12936 Each function can access the current prefix argument through the
12937 variable `current-prefix-argument'. Note that a single prefix is
12938 used to force opening a link in Emacs, so it may be good to only
12939 use a numeric or double prefix to guide the search function.
12941 In case this is needed, a function in this hook can also restore
12942 the window configuration before `org-open-at-point' was called using:
12944 (set-window-configuration org-window-config-before-follow-link)")
12946 (defun org-link-search (s &optional type avoid-pos)
12947 "Search for a link search option.
12948 If S is surrounded by forward slashes, it is interpreted as a
12949 regular expression. In org-mode files, this will create an `org-occur'
12950 sparse tree. In ordinary files, `occur' will be used to list matches.
12951 If the current buffer is in `dired-mode', grep will be used to search
12952 in all files. If AVOID-POS is given, ignore matches near that position."
12953 (let ((case-fold-search t)
12954 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12955 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12956 (append '(("") (" ") ("\t") ("\n"))
12957 org-emphasis-alist)
12958 "\\|") "\\)"))
12959 (pos (point))
12960 (pre "") (post "")
12961 words re0 re1 re2 re3 re4 re5 re2a reall)
12962 (cond
12963 ;; First check if there are any special
12964 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12965 ;; Now try the builtin stuff
12966 ((save-excursion
12967 (goto-char (point-min))
12968 (and
12969 (re-search-forward
12970 (concat "<<" (regexp-quote s0) ">>") nil t)
12971 (setq pos (match-beginning 0))))
12972 ;; There is an exact target for this
12973 (goto-char pos))
12974 ((string-match "^/\\(.*\\)/$" s)
12975 ;; A regular expression
12976 (cond
12977 ((org-mode-p)
12978 (org-occur (match-string 1 s)))
12979 ;;((eq major-mode 'dired-mode)
12980 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12981 (t (org-do-occur (match-string 1 s)))))
12983 ;; A normal search strings
12984 (when (equal (string-to-char s) ?*)
12985 ;; Anchor on headlines, post may include tags.
12986 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12987 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12988 s (substring s 1)))
12989 (remove-text-properties
12990 0 (length s)
12991 '(face nil mouse-face nil keymap nil fontified nil) s)
12992 ;; Make a series of regular expressions to find a match
12993 (setq words (org-split-string s "[ \n\r\t]+")
12994 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12995 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12996 "\\)" markers)
12997 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12998 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12999 re1 (concat pre re2 post)
13000 re3 (concat pre re4 post)
13001 re5 (concat pre ".*" re4)
13002 re2 (concat pre re2)
13003 re2a (concat pre re2a)
13004 re4 (concat pre re4)
13005 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13006 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13007 re5 "\\)"
13009 (cond
13010 ((eq type 'org-occur) (org-occur reall))
13011 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13012 (t (goto-char (point-min))
13013 (if (or (org-search-not-self 1 re0 nil t)
13014 (org-search-not-self 1 re1 nil t)
13015 (org-search-not-self 1 re2 nil t)
13016 (org-search-not-self 1 re2a nil t)
13017 (org-search-not-self 1 re3 nil t)
13018 (org-search-not-self 1 re4 nil t)
13019 (org-search-not-self 1 re5 nil t)
13021 (goto-char (match-beginning 1))
13022 (goto-char pos)
13023 (error "No match")))))
13025 ;; Normal string-search
13026 (goto-char (point-min))
13027 (if (search-forward s nil t)
13028 (goto-char (match-beginning 0))
13029 (error "No match"))))
13030 (and (org-mode-p) (org-show-context 'link-search))))
13032 (defun org-search-not-self (group &rest args)
13033 "Execute `re-search-forward', but only accept matches that do not
13034 enclose the position of `org-open-link-marker'."
13035 (let ((m org-open-link-marker))
13036 (catch 'exit
13037 (while (apply 're-search-forward args)
13038 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13039 (goto-char (match-end group))
13040 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13041 (> (match-beginning 0) (marker-position m))
13042 (< (match-end 0) (marker-position m)))
13043 (save-match-data
13044 (or (not (org-in-regexp
13045 org-bracket-link-analytic-regexp 1))
13046 (not (match-end 4)) ; no description
13047 (and (<= (match-beginning 4) (point))
13048 (>= (match-end 4) (point))))))
13049 (throw 'exit (point))))))))
13051 (defun org-get-buffer-for-internal-link (buffer)
13052 "Return a buffer to be used for displaying the link target of internal links."
13053 (cond
13054 ((not org-display-internal-link-with-indirect-buffer)
13055 buffer)
13056 ((string-match "(Clone)$" (buffer-name buffer))
13057 (message "Buffer is already a clone, not making another one")
13058 ;; we also do not modify visibility in this case
13059 buffer)
13060 (t ; make a new indirect buffer for displaying the link
13061 (let* ((bn (buffer-name buffer))
13062 (ibn (concat bn "(Clone)"))
13063 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13064 (with-current-buffer ib (org-overview))
13065 ib))))
13067 (defun org-do-occur (regexp &optional cleanup)
13068 "Call the Emacs command `occur'.
13069 If CLEANUP is non-nil, remove the printout of the regular expression
13070 in the *Occur* buffer. This is useful if the regex is long and not useful
13071 to read."
13072 (occur regexp)
13073 (when cleanup
13074 (let ((cwin (selected-window)) win beg end)
13075 (when (setq win (get-buffer-window "*Occur*"))
13076 (select-window win))
13077 (goto-char (point-min))
13078 (when (re-search-forward "match[a-z]+" nil t)
13079 (setq beg (match-end 0))
13080 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13081 (setq end (1- (match-beginning 0)))))
13082 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13083 (goto-char (point-min))
13084 (select-window cwin))))
13086 ;;; The mark ring for links jumps
13088 (defvar org-mark-ring nil
13089 "Mark ring for positions before jumps in Org-mode.")
13090 (defvar org-mark-ring-last-goto nil
13091 "Last position in the mark ring used to go back.")
13092 ;; Fill and close the ring
13093 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13094 (loop for i from 1 to org-mark-ring-length do
13095 (push (make-marker) org-mark-ring))
13096 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13097 org-mark-ring)
13099 (defun org-mark-ring-push (&optional pos buffer)
13100 "Put the current position or POS into the mark ring and rotate it."
13101 (interactive)
13102 (setq pos (or pos (point)))
13103 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13104 (move-marker (car org-mark-ring)
13105 (or pos (point))
13106 (or buffer (current-buffer)))
13107 (message "%s"
13108 (substitute-command-keys
13109 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13111 (defun org-mark-ring-goto (&optional n)
13112 "Jump to the previous position in the mark ring.
13113 With prefix arg N, jump back that many stored positions. When
13114 called several times in succession, walk through the entire ring.
13115 Org-mode commands jumping to a different position in the current file,
13116 or to another Org-mode file, automatically push the old position
13117 onto the ring."
13118 (interactive "p")
13119 (let (p m)
13120 (if (eq last-command this-command)
13121 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13122 (setq p org-mark-ring))
13123 (setq org-mark-ring-last-goto p)
13124 (setq m (car p))
13125 (switch-to-buffer (marker-buffer m))
13126 (goto-char m)
13127 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13129 (defun org-remove-angle-brackets (s)
13130 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13131 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13133 (defun org-add-angle-brackets (s)
13134 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13135 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13138 ;;; Following specific links
13140 (defun org-follow-timestamp-link ()
13141 (cond
13142 ((org-at-date-range-p t)
13143 (let ((org-agenda-start-on-weekday)
13144 (t1 (match-string 1))
13145 (t2 (match-string 2)))
13146 (setq t1 (time-to-days (org-time-string-to-time t1))
13147 t2 (time-to-days (org-time-string-to-time t2)))
13148 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13149 ((org-at-timestamp-p t)
13150 (org-agenda-list nil (time-to-days (org-time-string-to-time
13151 (substring (match-string 1) 0 10)))
13153 (t (error "This should not happen"))))
13156 (defun org-follow-bbdb-link (name)
13157 "Follow a BBDB link to NAME."
13158 (require 'bbdb)
13159 (let ((inhibit-redisplay (not debug-on-error))
13160 (bbdb-electric-p nil))
13161 (catch 'exit
13162 ;; Exact match on name
13163 (bbdb-name (concat "\\`" name "\\'") nil)
13164 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13165 ;; Exact match on name
13166 (bbdb-company (concat "\\`" name "\\'") nil)
13167 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13168 ;; Partial match on name
13169 (bbdb-name name nil)
13170 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13171 ;; Partial match on company
13172 (bbdb-company name nil)
13173 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13174 ;; General match including network address and notes
13175 (bbdb name nil)
13176 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13177 (delete-window (get-buffer-window "*BBDB*"))
13178 (error "No matching BBDB record")))))
13180 (defun org-follow-info-link (name)
13181 "Follow an info file & node link to NAME."
13182 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13183 (string-match "\\(.*\\)" name))
13184 (progn
13185 (require 'info)
13186 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13187 (Info-find-node (match-string 1 name) (match-string 2 name))
13188 (Info-find-node (match-string 1 name) "Top")))
13189 (message "Could not open: %s" name)))
13191 (defun org-follow-gnus-link (&optional group article)
13192 "Follow a Gnus link to GROUP and ARTICLE."
13193 (require 'gnus)
13194 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13195 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13196 (cond ((and group article)
13197 (gnus-group-read-group 1 nil group)
13198 (gnus-summary-goto-article (string-to-number article) nil t))
13199 (group (gnus-group-jump-to-group group))))
13201 (defun org-follow-vm-link (&optional folder article readonly)
13202 "Follow a VM link to FOLDER and ARTICLE."
13203 (require 'vm)
13204 (setq article (org-add-angle-brackets article))
13205 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13206 ;; ange-ftp or efs or tramp access
13207 (let ((user (or (match-string 1 folder) (user-login-name)))
13208 (host (match-string 2 folder))
13209 (file (match-string 3 folder)))
13210 (cond
13211 ((featurep 'tramp)
13212 ;; use tramp to access the file
13213 (if (featurep 'xemacs)
13214 (setq folder (format "[%s@%s]%s" user host file))
13215 (setq folder (format "/%s@%s:%s" user host file))))
13217 ;; use ange-ftp or efs
13218 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13219 (setq folder (format "/%s@%s:%s" user host file))))))
13220 (when folder
13221 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13222 (sit-for 0.1)
13223 (when article
13224 (vm-select-folder-buffer)
13225 (widen)
13226 (let ((case-fold-search t))
13227 (goto-char (point-min))
13228 (if (not (re-search-forward
13229 (concat "^" "message-id: *" (regexp-quote article))))
13230 (error "Could not find the specified message in this folder"))
13231 (vm-isearch-update)
13232 (vm-isearch-narrow)
13233 (vm-beginning-of-message)
13234 (vm-summarize)))))
13236 (defun org-follow-wl-link (folder article)
13237 "Follow a Wanderlust link to FOLDER and ARTICLE."
13238 (if (and (string= folder "%")
13239 article
13240 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13241 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13242 ;; Thus, we recompose folder and article ids.
13243 (setq folder (format "%s#%s" folder (match-string 1 article))
13244 article (match-string 3 article)))
13245 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13246 (error "No such folder: %s" folder))
13247 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13248 (and article
13249 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13250 (wl-summary-redisplay)))
13252 (defun org-follow-rmail-link (folder article)
13253 "Follow an RMAIL link to FOLDER and ARTICLE."
13254 (setq article (org-add-angle-brackets article))
13255 (let (message-number)
13256 (save-excursion
13257 (save-window-excursion
13258 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13259 (setq message-number
13260 (save-restriction
13261 (widen)
13262 (goto-char (point-max))
13263 (if (re-search-backward
13264 (concat "^Message-ID:\\s-+" (regexp-quote
13265 (or article "")))
13266 nil t)
13267 (rmail-what-message))))))
13268 (if message-number
13269 (progn
13270 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13271 (rmail-show-message message-number)
13272 message-number)
13273 (error "Message not found"))))
13275 ;;; mh-e integration based on planner-mode
13276 (defun org-mhe-get-message-real-folder ()
13277 "Return the name of the current message real folder, so if you use
13278 sequences, it will now work."
13279 (save-excursion
13280 (let* ((folder
13281 (if (equal major-mode 'mh-folder-mode)
13282 mh-current-folder
13283 ;; Refer to the show buffer
13284 mh-show-folder-buffer))
13285 (end-index
13286 (if (boundp 'mh-index-folder)
13287 (min (length mh-index-folder) (length folder))))
13289 ;; a simple test on mh-index-data does not work, because
13290 ;; mh-index-data is always nil in a show buffer.
13291 (if (and (boundp 'mh-index-folder)
13292 (string= mh-index-folder (substring folder 0 end-index)))
13293 (if (equal major-mode 'mh-show-mode)
13294 (save-window-excursion
13295 (let (pop-up-frames)
13296 (when (buffer-live-p (get-buffer folder))
13297 (progn
13298 (pop-to-buffer folder)
13299 (org-mhe-get-message-folder-from-index)
13302 (org-mhe-get-message-folder-from-index)
13304 folder
13308 (defun org-mhe-get-message-folder-from-index ()
13309 "Returns the name of the message folder in a index folder buffer."
13310 (save-excursion
13311 (mh-index-previous-folder)
13312 (re-search-forward "^\\(+.*\\)$" nil t)
13313 (message "%s" (match-string 1))))
13315 (defun org-mhe-get-message-folder ()
13316 "Return the name of the current message folder. Be careful if you
13317 use sequences."
13318 (save-excursion
13319 (if (equal major-mode 'mh-folder-mode)
13320 mh-current-folder
13321 ;; Refer to the show buffer
13322 mh-show-folder-buffer)))
13324 (defun org-mhe-get-message-num ()
13325 "Return the number of the current message. Be careful if you
13326 use sequences."
13327 (save-excursion
13328 (if (equal major-mode 'mh-folder-mode)
13329 (mh-get-msg-num nil)
13330 ;; Refer to the show buffer
13331 (mh-show-buffer-message-number))))
13333 (defun org-mhe-get-header (header)
13334 "Return a header of the message in folder mode. This will create a
13335 show buffer for the corresponding message. If you have a more clever
13336 idea..."
13337 (let* ((folder (org-mhe-get-message-folder))
13338 (num (org-mhe-get-message-num))
13339 (buffer (get-buffer-create (concat "show-" folder)))
13340 (header-field))
13341 (with-current-buffer buffer
13342 (mh-display-msg num folder)
13343 (if (equal major-mode 'mh-folder-mode)
13344 (mh-header-display)
13345 (mh-show-header-display))
13346 (set-buffer buffer)
13347 (setq header-field (mh-get-header-field header))
13348 (if (equal major-mode 'mh-folder-mode)
13349 (mh-show)
13350 (mh-show-show))
13351 header-field)))
13353 (defun org-follow-mhe-link (folder article)
13354 "Follow an MHE link to FOLDER and ARTICLE.
13355 If ARTICLE is nil FOLDER is shown. If the configuration variable
13356 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13357 ARTICLE is searched in all folders. Indexed searches (swish++,
13358 namazu, and others supported by MH-E) will always search in all
13359 folders."
13360 (require 'mh-e)
13361 (require 'mh-search)
13362 (require 'mh-utils)
13363 (mh-find-path)
13364 (if (not article)
13365 (mh-visit-folder (mh-normalize-folder-name folder))
13366 (setq article (org-add-angle-brackets article))
13367 (mh-search-choose)
13368 (if (equal mh-searcher 'pick)
13369 (progn
13370 (mh-search folder (list "--message-id" article))
13371 (when (and org-mhe-search-all-folders
13372 (not (org-mhe-get-message-real-folder)))
13373 (kill-this-buffer)
13374 (mh-search "+" (list "--message-id" article))))
13375 (mh-search "+" article))
13376 (if (org-mhe-get-message-real-folder)
13377 (mh-show-msg 1)
13378 (kill-this-buffer)
13379 (error "Message not found"))))
13381 ;;; BibTeX links
13383 ;; Use the custom search meachnism to construct and use search strings for
13384 ;; file links to BibTeX database entries.
13386 (defun org-create-file-search-in-bibtex ()
13387 "Create the search string and description for a BibTeX database entry."
13388 (when (eq major-mode 'bibtex-mode)
13389 ;; yes, we want to construct this search string.
13390 ;; Make a good description for this entry, using names, year and the title
13391 ;; Put it into the `description' variable which is dynamically scoped.
13392 (let ((bibtex-autokey-names 1)
13393 (bibtex-autokey-names-stretch 1)
13394 (bibtex-autokey-name-case-convert-function 'identity)
13395 (bibtex-autokey-name-separator " & ")
13396 (bibtex-autokey-additional-names " et al.")
13397 (bibtex-autokey-year-length 4)
13398 (bibtex-autokey-name-year-separator " ")
13399 (bibtex-autokey-titlewords 3)
13400 (bibtex-autokey-titleword-separator " ")
13401 (bibtex-autokey-titleword-case-convert-function 'identity)
13402 (bibtex-autokey-titleword-length 'infty)
13403 (bibtex-autokey-year-title-separator ": "))
13404 (setq description (bibtex-generate-autokey)))
13405 ;; Now parse the entry, get the key and return it.
13406 (save-excursion
13407 (bibtex-beginning-of-entry)
13408 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13410 (defun org-execute-file-search-in-bibtex (s)
13411 "Find the link search string S as a key for a database entry."
13412 (when (eq major-mode 'bibtex-mode)
13413 ;; Yes, we want to do the search in this file.
13414 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13415 (goto-char (point-min))
13416 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13417 (regexp-quote s) "[ \t\n]*,") nil t)
13418 (goto-char (match-beginning 0)))
13419 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13420 ;; Use double prefix to indicate that any web link should be browsed
13421 (let ((b (current-buffer)) (p (point)))
13422 ;; Restore the window configuration because we just use the web link
13423 (set-window-configuration org-window-config-before-follow-link)
13424 (save-excursion (set-buffer b) (goto-char p)
13425 (bibtex-url)))
13426 (recenter 0)) ; Move entry start to beginning of window
13427 ;; return t to indicate that the search is done.
13430 ;; Finally add the functions to the right hooks.
13431 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13432 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13434 ;; end of Bibtex link setup
13436 ;;; Following file links
13438 (defun org-open-file (path &optional in-emacs line search)
13439 "Open the file at PATH.
13440 First, this expands any special file name abbreviations. Then the
13441 configuration variable `org-file-apps' is checked if it contains an
13442 entry for this file type, and if yes, the corresponding command is launched.
13443 If no application is found, Emacs simply visits the file.
13444 With optional argument IN-EMACS, Emacs will visit the file.
13445 Optional LINE specifies a line to go to, optional SEARCH a string to
13446 search for. If LINE or SEARCH is given, the file will always be
13447 opened in Emacs.
13448 If the file does not exist, an error is thrown."
13449 (setq in-emacs (or in-emacs line search))
13450 (let* ((file (if (equal path "")
13451 buffer-file-name
13452 (substitute-in-file-name (expand-file-name path))))
13453 (apps (append org-file-apps (org-default-apps)))
13454 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13455 (dirp (if remp nil (file-directory-p file)))
13456 (dfile (downcase file))
13457 (old-buffer (current-buffer))
13458 (old-pos (point))
13459 (old-mode major-mode)
13460 ext cmd)
13461 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13462 (setq ext (match-string 1 dfile))
13463 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13464 (setq ext (match-string 1 dfile))))
13465 (if in-emacs
13466 (setq cmd 'emacs)
13467 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13468 (and dirp (cdr (assoc 'directory apps)))
13469 (cdr (assoc ext apps))
13470 (cdr (assoc t apps)))))
13471 (when (eq cmd 'mailcap)
13472 (require 'mailcap)
13473 (mailcap-parse-mailcaps)
13474 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13475 (command (mailcap-mime-info mime-type)))
13476 (if (stringp command)
13477 (setq cmd command)
13478 (setq cmd 'emacs))))
13479 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13480 (not (file-exists-p file))
13481 (not org-open-non-existing-files))
13482 (error "No such file: %s" file))
13483 (cond
13484 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13485 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13486 (while (string-match "['\"]%s['\"]" cmd)
13487 (setq cmd (replace-match "%s" t t cmd)))
13488 (while (string-match "%s" cmd)
13489 (setq cmd (replace-match
13490 (save-match-data (shell-quote-argument file))
13491 t t cmd)))
13492 (save-window-excursion
13493 (start-process-shell-command cmd nil cmd)))
13494 ((or (stringp cmd)
13495 (eq cmd 'emacs))
13496 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13497 (widen)
13498 (if line (goto-line line)
13499 (if search (org-link-search search))))
13500 ((consp cmd)
13501 (eval cmd))
13502 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13503 (and (org-mode-p) (eq old-mode 'org-mode)
13504 (or (not (equal old-buffer (current-buffer)))
13505 (not (equal old-pos (point))))
13506 (org-mark-ring-push old-pos old-buffer))))
13508 (defun org-default-apps ()
13509 "Return the default applications for this operating system."
13510 (cond
13511 ((eq system-type 'darwin)
13512 org-file-apps-defaults-macosx)
13513 ((eq system-type 'windows-nt)
13514 org-file-apps-defaults-windowsnt)
13515 (t org-file-apps-defaults-gnu)))
13517 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13518 (defun org-file-remote-p (file)
13519 "Test whether FILE specifies a location on a remote system.
13520 Return non-nil if the location is indeed remote.
13522 For example, the filename \"/user@host:/foo\" specifies a location
13523 on the system \"/user@host:\"."
13524 (cond ((fboundp 'file-remote-p)
13525 (file-remote-p file))
13526 ((fboundp 'tramp-handle-file-remote-p)
13527 (tramp-handle-file-remote-p file))
13528 ((and (boundp 'ange-ftp-name-format)
13529 (string-match (car ange-ftp-name-format) file))
13531 (t nil)))
13534 ;;;; Hooks for remember.el, and refiling
13536 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13537 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13539 ;;;###autoload
13540 (defun org-remember-insinuate ()
13541 "Setup remember.el for use wiht Org-mode."
13542 (require 'remember)
13543 (setq remember-annotation-functions '(org-remember-annotation))
13544 (setq remember-handler-functions '(org-remember-handler))
13545 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13547 ;;;###autoload
13548 (defun org-remember-annotation ()
13549 "Return a link to the current location as an annotation for remember.el.
13550 If you are using Org-mode files as target for data storage with
13551 remember.el, then the annotations should include a link compatible with the
13552 conventions in Org-mode. This function returns such a link."
13553 (org-store-link nil))
13555 (defconst org-remember-help
13556 "Select a destination location for the note.
13557 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13558 RET on headline -> Store as sublevel entry to current headline
13559 RET at beg-of-buf -> Append to file as level 2 headline
13560 <left>/<right> -> before/after current headline, same headings level")
13562 (defvar org-remember-previous-location nil)
13563 (defvar org-force-remember-template-char) ;; dynamically scoped
13565 (defun org-select-remember-template (&optional use-char)
13566 (when org-remember-templates
13567 (let* ((templates (mapcar (lambda (x)
13568 (if (stringp (car x))
13569 (append (list (nth 1 x) (car x)) (cddr x))
13570 (append (list (car x) "") (cdr x))))
13571 org-remember-templates))
13572 (char (or use-char
13573 (cond
13574 ((= (length templates) 1)
13575 (caar templates))
13576 ((and (boundp 'org-force-remember-template-char)
13577 org-force-remember-template-char)
13578 (if (stringp org-force-remember-template-char)
13579 (string-to-char org-force-remember-template-char)
13580 org-force-remember-template-char))
13582 (message "Select template: %s"
13583 (mapconcat
13584 (lambda (x)
13585 (cond
13586 ((not (string-match "\\S-" (nth 1 x)))
13587 (format "[%c]" (car x)))
13588 ((equal (downcase (car x))
13589 (downcase (aref (nth 1 x) 0)))
13590 (format "[%c]%s" (car x)
13591 (substring (nth 1 x) 1)))
13592 (t (format "[%c]%s" (car x) (nth 1 x)))))
13593 templates " "))
13594 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13595 (when (equal char0 ?\C-g)
13596 (jump-to-register remember-register)
13597 (kill-buffer remember-buffer))
13598 char0))))))
13599 (cddr (assoc char templates)))))
13601 (defvar x-last-selected-text)
13602 (defvar x-last-selected-text-primary)
13604 ;;;###autoload
13605 (defun org-remember-apply-template (&optional use-char skip-interactive)
13606 "Initialize *remember* buffer with template, invoke `org-mode'.
13607 This function should be placed into `remember-mode-hook' and in fact requires
13608 to be run from that hook to function properly."
13609 (if org-remember-templates
13610 (let* ((entry (org-select-remember-template use-char))
13611 (tpl (car entry))
13612 (plist-p (if org-store-link-plist t nil))
13613 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13614 (string-match "\\S-" (nth 1 entry)))
13615 (nth 1 entry)
13616 org-default-notes-file))
13617 (headline (nth 2 entry))
13618 (v-c (or (and (eq window-system 'x)
13619 (fboundp 'x-cut-buffer-or-selection-value)
13620 (x-cut-buffer-or-selection-value))
13621 (org-bound-and-true-p x-last-selected-text)
13622 (org-bound-and-true-p x-last-selected-text-primary)
13623 (and (> (length kill-ring) 0) (current-kill 0))))
13624 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13625 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13626 (v-u (concat "[" (substring v-t 1 -1) "]"))
13627 (v-U (concat "[" (substring v-T 1 -1) "]"))
13628 ;; `initial' and `annotation' are bound in `remember'
13629 (v-i (if (boundp 'initial) initial))
13630 (v-a (if (and (boundp 'annotation) annotation)
13631 (if (equal annotation "[[]]") "" annotation)
13632 ""))
13633 (v-A (if (and v-a
13634 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13635 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13636 v-a))
13637 (v-n user-full-name)
13638 (org-startup-folded nil)
13639 org-time-was-given org-end-time-was-given x
13640 prompt completions char time pos default histvar)
13641 (setq org-store-link-plist
13642 (append (list :annotation v-a :initial v-i)
13643 org-store-link-plist))
13644 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13645 (erase-buffer)
13646 (insert (substitute-command-keys
13647 (format
13648 "## Filing location: Select interactively, default, or last used:
13649 ## %s to select file and header location interactively.
13650 ## %s \"%s\" -> \"* %s\"
13651 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13652 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13653 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13654 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13655 (abbreviate-file-name (or file org-default-notes-file))
13656 (or headline "")
13657 (or (car org-remember-previous-location) "???")
13658 (or (cdr org-remember-previous-location) "???"))))
13659 (insert tpl) (goto-char (point-min))
13660 ;; Simple %-escapes
13661 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13662 (when (and initial (equal (match-string 0) "%i"))
13663 (save-match-data
13664 (let* ((lead (buffer-substring
13665 (point-at-bol) (match-beginning 0))))
13666 (setq v-i (mapconcat 'identity
13667 (org-split-string initial "\n")
13668 (concat "\n" lead))))))
13669 (replace-match
13670 (or (eval (intern (concat "v-" (match-string 1)))) "")
13671 t t))
13673 ;; %[] Insert contents of a file.
13674 (goto-char (point-min))
13675 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13676 (let ((start (match-beginning 0))
13677 (end (match-end 0))
13678 (filename (expand-file-name (match-string 1))))
13679 (goto-char start)
13680 (delete-region start end)
13681 (condition-case error
13682 (insert-file-contents filename)
13683 (error (insert (format "%%![Couldn't insert %s: %s]"
13684 filename error))))))
13685 ;; %() embedded elisp
13686 (goto-char (point-min))
13687 (while (re-search-forward "%\\((.+)\\)" nil t)
13688 (goto-char (match-beginning 0))
13689 (let ((template-start (point)))
13690 (forward-char 1)
13691 (let ((result
13692 (condition-case error
13693 (eval (read (current-buffer)))
13694 (error (format "%%![Error: %s]" error)))))
13695 (delete-region template-start (point))
13696 (insert result))))
13698 ;; From the property list
13699 (when plist-p
13700 (goto-char (point-min))
13701 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13702 (and (setq x (or (plist-get org-store-link-plist
13703 (intern (match-string 1))) ""))
13704 (replace-match x t t))))
13706 ;; Turn on org-mode in the remember buffer, set local variables
13707 (org-mode)
13708 (org-set-local 'org-finish-function 'org-remember-finalize)
13709 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13710 (org-set-local 'org-default-notes-file file))
13711 (if (and headline (stringp headline) (string-match "\\S-" headline))
13712 (org-set-local 'org-remember-default-headline headline))
13713 ;; Interactive template entries
13714 (goto-char (point-min))
13715 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13716 (setq char (if (match-end 3) (match-string 3))
13717 prompt (if (match-end 2) (match-string 2)))
13718 (goto-char (match-beginning 0))
13719 (replace-match "")
13720 (setq completions nil default nil)
13721 (when prompt
13722 (setq completions (org-split-string prompt "|")
13723 prompt (pop completions)
13724 default (car completions)
13725 histvar (intern (concat
13726 "org-remember-template-prompt-history::"
13727 (or prompt "")))
13728 completions (mapcar 'list completions)))
13729 (cond
13730 ((member char '("G" "g"))
13731 (let* ((org-last-tags-completion-table
13732 (org-global-tags-completion-table
13733 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13734 (org-add-colon-after-tag-completion t)
13735 (ins (completing-read
13736 (if prompt (concat prompt ": ") "Tags: ")
13737 'org-tags-completion-function nil nil nil
13738 'org-tags-history)))
13739 (setq ins (mapconcat 'identity
13740 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13741 ":"))
13742 (when (string-match "\\S-" ins)
13743 (or (equal (char-before) ?:) (insert ":"))
13744 (insert ins)
13745 (or (equal (char-after) ?:) (insert ":")))))
13746 (char
13747 (setq org-time-was-given (equal (upcase char) char))
13748 (setq time (org-read-date (equal (upcase char) "U") t nil
13749 prompt))
13750 (org-insert-time-stamp time org-time-was-given
13751 (member char '("u" "U"))
13752 nil nil (list org-end-time-was-given)))
13754 (insert (org-completing-read
13755 (concat (if prompt prompt "Enter string")
13756 (if default (concat " [" default "]"))
13757 ": ")
13758 completions nil nil nil histvar default)))))
13759 (goto-char (point-min))
13760 (if (re-search-forward "%\\?" nil t)
13761 (replace-match "")
13762 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13763 (org-mode)
13764 (org-set-local 'org-finish-function 'org-remember-finalize))
13765 (when (save-excursion
13766 (goto-char (point-min))
13767 (re-search-forward "%!" nil t))
13768 (replace-match "")
13769 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13771 (defun org-remember-finish-immediately ()
13772 "File remember note immediately.
13773 This should be run in `post-command-hook' and will remove itself
13774 from that hook."
13775 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13776 (when org-finish-function
13777 (funcall org-finish-function)))
13779 (defvar org-clock-marker) ; Defined below
13780 (defun org-remember-finalize ()
13781 "Finalize the remember process."
13782 (unless (fboundp 'remember-finalize)
13783 (defalias 'remember-finalize 'remember-buffer))
13784 (when (and org-clock-marker
13785 (equal (marker-buffer org-clock-marker) (current-buffer)))
13786 ;; FIXME: test this, this is w/o notetaking!
13787 (let (org-log-note-clock-out) (org-clock-out)))
13788 (when buffer-file-name
13789 (save-buffer)
13790 (setq buffer-file-name nil))
13791 (remember-finalize))
13793 ;;;###autoload
13794 (defun org-remember (&optional goto org-force-remember-template-char)
13795 "Call `remember'. If this is already a remember buffer, re-apply template.
13796 If there is an active region, make sure remember uses it as initial content
13797 of the remember buffer.
13799 When called interactively with a `C-u' prefix argument GOTO, don't remember
13800 anything, just go to the file/headline where the selected template usually
13801 stores its notes. With a double prefix arg `C-u C-u', go to the last
13802 note stored by remember.
13804 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13805 associated with a template in `org-remember-templates'."
13806 (interactive "P")
13807 (cond
13808 ((equal goto '(4)) (org-go-to-remember-target))
13809 ((equal goto '(16)) (org-remember-goto-last-stored))
13811 (if (memq org-finish-function '(remember-buffer remember-finalize))
13812 (progn
13813 (when (< (length org-remember-templates) 2)
13814 (error "No other template available"))
13815 (erase-buffer)
13816 (let ((annotation (plist-get org-store-link-plist :annotation))
13817 (initial (plist-get org-store-link-plist :initial)))
13818 (org-remember-apply-template))
13819 (message "Press C-c C-c to remember data"))
13820 (if (org-region-active-p)
13821 (remember (buffer-substring (point) (mark)))
13822 (call-interactively 'remember))))))
13824 (defun org-remember-goto-last-stored ()
13825 "Go to the location where the last remember note was stored."
13826 (interactive)
13827 (bookmark-jump "org-remember-last-stored")
13828 (message "This is the last note stored by remember"))
13830 (defun org-go-to-remember-target (&optional template-key)
13831 "Go to the target location of a remember template.
13832 The user is queried for the template."
13833 (interactive)
13834 (let* ((entry (org-select-remember-template template-key))
13835 (file (nth 1 entry))
13836 (heading (nth 2 entry))
13837 visiting)
13838 (unless (and file (stringp file) (string-match "\\S-" file))
13839 (setq file org-default-notes-file))
13840 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13841 (setq heading org-remember-default-headline))
13842 (setq visiting (org-find-base-buffer-visiting file))
13843 (if (not visiting) (find-file-noselect file))
13844 (switch-to-buffer (or visiting (get-file-buffer file)))
13845 (widen)
13846 (goto-char (point-min))
13847 (if (re-search-forward
13848 (concat "^\\*+[ \t]+" (regexp-quote heading)
13849 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13850 nil t)
13851 (goto-char (match-beginning 0))
13852 (error "Target headline not found: %s" heading))))
13854 (defvar org-note-abort nil) ; dynamically scoped
13856 ;;;###autoload
13857 (defun org-remember-handler ()
13858 "Store stuff from remember.el into an org file.
13859 First prompts for an org file. If the user just presses return, the value
13860 of `org-default-notes-file' is used.
13861 Then the command offers the headings tree of the selected file in order to
13862 file the text at a specific location.
13863 You can either immediately press RET to get the note appended to the
13864 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13865 find a better place. Then press RET or <left> or <right> in insert the note.
13867 Key Cursor position Note gets inserted
13868 -----------------------------------------------------------------------------
13869 RET buffer-start as level 1 heading at end of file
13870 RET on headline as sublevel of the heading at cursor
13871 RET no heading at cursor position, level taken from context.
13872 Or use prefix arg to specify level manually.
13873 <left> on headline as same level, before current heading
13874 <right> on headline as same level, after current heading
13876 So the fastest way to store the note is to press RET RET to append it to
13877 the default file. This way your current train of thought is not
13878 interrupted, in accordance with the principles of remember.el.
13879 You can also get the fast execution without prompting by using
13880 C-u C-c C-c to exit the remember buffer. See also the variable
13881 `org-remember-store-without-prompt'.
13883 Before being stored away, the function ensures that the text has a
13884 headline, i.e. a first line that starts with a \"*\". If not, a headline
13885 is constructed from the current date and some additional data.
13887 If the variable `org-adapt-indentation' is non-nil, the entire text is
13888 also indented so that it starts in the same column as the headline
13889 \(i.e. after the stars).
13891 See also the variable `org-reverse-note-order'."
13892 (goto-char (point-min))
13893 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13894 (replace-match ""))
13895 (goto-char (point-max))
13896 (beginning-of-line 1)
13897 (while (looking-at "[ \t]*$\\|##.*")
13898 (delete-region (1- (point)) (point-max))
13899 (beginning-of-line 1))
13900 (catch 'quit
13901 (if org-note-abort (throw 'quit nil))
13902 (let* ((txt (buffer-substring (point-min) (point-max)))
13903 (fastp (org-xor (equal current-prefix-arg '(4))
13904 org-remember-store-without-prompt))
13905 (file (cond
13906 (fastp org-default-notes-file)
13907 ((and (eq org-remember-interactive-interface 'refile)
13908 org-refile-targets)
13909 org-default-notes-file)
13910 ((not (and (equal current-prefix-arg '(16))
13911 org-remember-previous-location))
13912 (org-get-org-file))))
13913 (heading org-remember-default-headline)
13914 (visiting (and file (org-find-base-buffer-visiting file)))
13915 (org-startup-folded nil)
13916 (org-startup-align-all-tables nil)
13917 (org-goto-start-pos 1)
13918 spos exitcmd level indent reversed)
13919 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13920 (setq file (car org-remember-previous-location)
13921 heading (cdr org-remember-previous-location)
13922 fastp t))
13923 (setq current-prefix-arg nil)
13924 (if (string-match "[ \t\n]+\\'" txt)
13925 (setq txt (replace-match "" t t txt)))
13926 ;; Modify text so that it becomes a nice subtree which can be inserted
13927 ;; into an org tree.
13928 (let* ((lines (split-string txt "\n"))
13929 first)
13930 (setq first (car lines) lines (cdr lines))
13931 (if (string-match "^\\*+ " first)
13932 ;; Is already a headline
13933 (setq indent nil)
13934 ;; We need to add a headline: Use time and first buffer line
13935 (setq lines (cons first lines)
13936 first (concat "* " (current-time-string)
13937 " (" (remember-buffer-desc) ")")
13938 indent " "))
13939 (if (and org-adapt-indentation indent)
13940 (setq lines (mapcar
13941 (lambda (x)
13942 (if (string-match "\\S-" x)
13943 (concat indent x) x))
13944 lines)))
13945 (setq txt (concat first "\n"
13946 (mapconcat 'identity lines "\n"))))
13947 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13948 (setq txt (replace-match "\n\n" t t txt))
13949 (if (string-match "[ \t\n]*\\'" txt)
13950 (setq txt (replace-match "\n" t t txt))))
13951 ;; Put the modified text back into the remember buffer, for refile.
13952 (erase-buffer)
13953 (insert txt)
13954 (goto-char (point-min))
13955 (when (and (eq org-remember-interactive-interface 'refile)
13956 (not fastp))
13957 (org-refile nil (or visiting (find-file-noselect file)))
13958 (throw 'quit t))
13959 ;; Find the file
13960 (if (not visiting) (find-file-noselect file))
13961 (with-current-buffer (or visiting (get-file-buffer file))
13962 (unless (org-mode-p)
13963 (error "Target files for remember notes must be in Org-mode"))
13964 (save-excursion
13965 (save-restriction
13966 (widen)
13967 (and (goto-char (point-min))
13968 (not (re-search-forward "^\\* " nil t))
13969 (insert "\n* " (or heading "Notes") "\n"))
13970 (setq reversed (org-notes-order-reversed-p))
13972 ;; Find the default location
13973 (when (and heading (stringp heading) (string-match "\\S-" heading))
13974 (goto-char (point-min))
13975 (if (re-search-forward
13976 (concat "^\\*+[ \t]+" (regexp-quote heading)
13977 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13978 nil t)
13979 (setq org-goto-start-pos (match-beginning 0))
13980 (when fastp
13981 (goto-char (point-max))
13982 (unless (bolp) (newline))
13983 (insert "* " heading "\n")
13984 (setq org-goto-start-pos (point-at-bol 0)))))
13986 ;; Ask the User for a location, using the appropriate interface
13987 (cond
13988 (fastp (setq spos org-goto-start-pos
13989 exitcmd 'return))
13990 ((eq org-remember-interactive-interface 'outline)
13991 (setq spos (org-get-location (current-buffer)
13992 org-remember-help)
13993 exitcmd (cdr spos)
13994 spos (car spos)))
13995 ((eq org-remember-interactive-interface 'outline-path-completion)
13996 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13997 (org-refile-use-outline-path t))
13998 (setq spos (org-refile-get-location "Heading: ")
13999 exitcmd 'return
14000 spos (nth 3 spos))))
14001 (t (error "this should not hapen")))
14002 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14003 ; not handle this note
14004 (goto-char spos)
14005 (cond ((org-on-heading-p t)
14006 (org-back-to-heading t)
14007 (setq level (funcall outline-level))
14008 (cond
14009 ((eq exitcmd 'return)
14010 ;; sublevel of current
14011 (setq org-remember-previous-location
14012 (cons (abbreviate-file-name file)
14013 (org-get-heading 'notags)))
14014 (if reversed
14015 (outline-next-heading)
14016 (org-end-of-subtree t)
14017 (if (not (bolp))
14018 (if (looking-at "[ \t]*\n")
14019 (beginning-of-line 2)
14020 (end-of-line 1)
14021 (insert "\n"))))
14022 (bookmark-set "org-remember-last-stored")
14023 (org-paste-subtree (org-get-legal-level level 1) txt))
14024 ((eq exitcmd 'left)
14025 ;; before current
14026 (bookmark-set "org-remember-last-stored")
14027 (org-paste-subtree level txt))
14028 ((eq exitcmd 'right)
14029 ;; after current
14030 (org-end-of-subtree t)
14031 (bookmark-set "org-remember-last-stored")
14032 (org-paste-subtree level txt))
14033 (t (error "This should not happen"))))
14035 ((and (bobp) (not reversed))
14036 ;; Put it at the end, one level below level 1
14037 (save-restriction
14038 (widen)
14039 (goto-char (point-max))
14040 (if (not (bolp)) (newline))
14041 (bookmark-set "org-remember-last-stored")
14042 (org-paste-subtree (org-get-legal-level 1 1) txt)))
14044 ((and (bobp) reversed)
14045 ;; Put it at the start, as level 1
14046 (save-restriction
14047 (widen)
14048 (goto-char (point-min))
14049 (re-search-forward "^\\*+ " nil t)
14050 (beginning-of-line 1)
14051 (bookmark-set "org-remember-last-stored")
14052 (org-paste-subtree 1 txt)))
14054 ;; Put it right there, with automatic level determined by
14055 ;; org-paste-subtree or from prefix arg
14056 (bookmark-set "org-remember-last-stored")
14057 (org-paste-subtree
14058 (if (numberp current-prefix-arg) current-prefix-arg)
14059 txt)))
14060 (when remember-save-after-remembering
14061 (save-buffer)
14062 (if (not visiting) (kill-buffer (current-buffer)))))))))
14064 t) ;; return t to indicate that we took care of this note.
14066 (defun org-get-org-file ()
14067 "Read a filename, with default directory `org-directory'."
14068 (let ((default (or org-default-notes-file remember-data-file)))
14069 (read-file-name (format "File name [%s]: " default)
14070 (file-name-as-directory org-directory)
14071 default)))
14073 (defun org-notes-order-reversed-p ()
14074 "Check if the current file should receive notes in reversed order."
14075 (cond
14076 ((not org-reverse-note-order) nil)
14077 ((eq t org-reverse-note-order) t)
14078 ((not (listp org-reverse-note-order)) nil)
14079 (t (catch 'exit
14080 (let ((all org-reverse-note-order)
14081 entry)
14082 (while (setq entry (pop all))
14083 (if (string-match (car entry) buffer-file-name)
14084 (throw 'exit (cdr entry))))
14085 nil)))))
14087 ;;; Refiling
14089 (defvar org-refile-target-table nil
14090 "The list of refile targets, created by `org-refile'.")
14092 (defvar org-agenda-new-buffers nil
14093 "Buffers created to visit agenda files.")
14095 (defun org-get-refile-targets (&optional default-buffer)
14096 "Produce a table with refile targets."
14097 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14098 targets txt re files f desc descre)
14099 (with-current-buffer (or default-buffer (current-buffer))
14100 (while (setq entry (pop entries))
14101 (setq files (car entry) desc (cdr entry))
14102 (cond
14103 ((null files) (setq files (list (current-buffer))))
14104 ((eq files 'org-agenda-files)
14105 (setq files (org-agenda-files 'unrestricted)))
14106 ((and (symbolp files) (fboundp files))
14107 (setq files (funcall files)))
14108 ((and (symbolp files) (boundp files))
14109 (setq files (symbol-value files))))
14110 (if (stringp files) (setq files (list files)))
14111 (cond
14112 ((eq (car desc) :tag)
14113 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14114 ((eq (car desc) :todo)
14115 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14116 ((eq (car desc) :regexp)
14117 (setq descre (cdr desc)))
14118 ((eq (car desc) :level)
14119 (setq descre (concat "^\\*\\{" (number-to-string
14120 (if org-odd-levels-only
14121 (1- (* 2 (cdr desc)))
14122 (cdr desc)))
14123 "\\}[ \t]")))
14124 ((eq (car desc) :maxlevel)
14125 (setq descre (concat "^\\*\\{1," (number-to-string
14126 (if org-odd-levels-only
14127 (1- (* 2 (cdr desc)))
14128 (cdr desc)))
14129 "\\}[ \t]")))
14130 (t (error "Bad refiling target description %s" desc)))
14131 (while (setq f (pop files))
14132 (save-excursion
14133 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14134 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14135 (save-excursion
14136 (save-restriction
14137 (widen)
14138 (goto-char (point-min))
14139 (while (re-search-forward descre nil t)
14140 (goto-char (point-at-bol))
14141 (when (looking-at org-complex-heading-regexp)
14142 (setq txt (match-string 4)
14143 re (concat "^" (regexp-quote
14144 (buffer-substring (match-beginning 1)
14145 (match-end 4)))))
14146 (if (match-end 5) (setq re (concat re "[ \t]+"
14147 (regexp-quote
14148 (match-string 5)))))
14149 (setq re (concat re "[ \t]*$"))
14150 (when org-refile-use-outline-path
14151 (setq txt (mapconcat 'identity
14152 (append
14153 (if (eq org-refile-use-outline-path 'file)
14154 (list (file-name-nondirectory
14155 (buffer-file-name (buffer-base-buffer))))
14156 (if (eq org-refile-use-outline-path 'full-file-path)
14157 (list (buffer-file-name (buffer-base-buffer)))))
14158 (org-get-outline-path)
14159 (list txt))
14160 "/")))
14161 (push (list txt f re (point)) targets))
14162 (goto-char (point-at-eol))))))))
14163 (nreverse targets))))
14165 (defun org-get-outline-path ()
14166 "Return the outline path to the current entry, as a list."
14167 (let (rtn)
14168 (save-excursion
14169 (while (org-up-heading-safe)
14170 (when (looking-at org-complex-heading-regexp)
14171 (push (org-match-string-no-properties 4) rtn)))
14172 rtn)))
14174 (defvar org-refile-history nil
14175 "History for refiling operations.")
14177 (defun org-refile (&optional goto default-buffer)
14178 "Move the entry at point to another heading.
14179 The list of target headings is compiled using the information in
14180 `org-refile-targets', which see. This list is created upon first use, and
14181 you can update it by calling this command with a double prefix (`C-u C-u').
14182 FIXME: Can we find a better way of updating?
14184 At the target location, the entry is filed as a subitem of the target heading.
14185 Depending on `org-reverse-note-order', the new subitem will either be the
14186 first of the last subitem.
14188 With prefix arg GOTO, the command will only visit the target location,
14189 not actually move anything.
14190 With a double prefix `C-c C-c', go to the location where the last refiling
14191 operation has put the subtree.
14193 With a double prefix argument, the command can be used to jump to any
14194 heading in the current buffer."
14195 (interactive "P")
14196 (let* ((cbuf (current-buffer))
14197 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14198 pos it nbuf file re level reversed)
14199 (if (equal goto '(16))
14200 (org-refile-goto-last-stored)
14201 (when (setq it (org-refile-get-location
14202 (if goto "Goto: " "Refile to: ") default-buffer))
14203 (setq file (nth 1 it)
14204 re (nth 2 it)
14205 pos (nth 3 it))
14206 (setq nbuf (or (find-buffer-visiting file)
14207 (find-file-noselect file)))
14208 (if goto
14209 (progn
14210 (switch-to-buffer nbuf)
14211 (goto-char pos)
14212 (org-show-context 'org-goto))
14213 (org-copy-special)
14214 (save-excursion
14215 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14216 (find-file-noselect file))))
14217 (setq reversed (org-notes-order-reversed-p))
14218 (save-excursion
14219 (save-restriction
14220 (widen)
14221 (goto-char pos)
14222 (looking-at outline-regexp)
14223 (setq level (org-get-legal-level (funcall outline-level) 1))
14224 (goto-char
14225 (if reversed
14226 (outline-next-heading)
14227 (or (save-excursion (outline-get-next-sibling))
14228 (org-end-of-subtree t t)
14229 (point-max))))
14230 (bookmark-set "org-refile-last-stored")
14231 (org-paste-subtree level))))
14232 (org-cut-special)
14233 (message "Entry refiled to \"%s\"" (car it)))))))
14235 (defun org-refile-goto-last-stored ()
14236 "Go to the location where the last refile was stored."
14237 (interactive)
14238 (bookmark-jump "org-refile-last-stored")
14239 (message "This is the location of the last refile"))
14241 (defun org-refile-get-location (&optional prompt default-buffer)
14242 "Prompt the user for a refile location, using PROMPT."
14243 (let ((org-refile-targets org-refile-targets)
14244 (org-refile-use-outline-path org-refile-use-outline-path))
14245 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14246 (unless org-refile-target-table
14247 (error "No refile targets"))
14248 (let* ((cbuf (current-buffer))
14249 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14250 (fname (and filename (file-truename filename)))
14251 (tbl (mapcar
14252 (lambda (x)
14253 (if (not (equal fname (file-truename (nth 1 x))))
14254 (cons (concat (car x) " (" (file-name-nondirectory
14255 (nth 1 x)) ")")
14256 (cdr x))
14258 org-refile-target-table))
14259 (completion-ignore-case t))
14260 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14261 tbl)))
14263 ;;;; Dynamic blocks
14265 (defun org-find-dblock (name)
14266 "Find the first dynamic block with name NAME in the buffer.
14267 If not found, stay at current position and return nil."
14268 (let (pos)
14269 (save-excursion
14270 (goto-char (point-min))
14271 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14272 nil t)
14273 (match-beginning 0))))
14274 (if pos (goto-char pos))
14275 pos))
14277 (defconst org-dblock-start-re
14278 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14279 "Matches the startline of a dynamic block, with parameters.")
14281 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14282 "Matches the end of a dyhamic block.")
14284 (defun org-create-dblock (plist)
14285 "Create a dynamic block section, with parameters taken from PLIST.
14286 PLIST must containe a :name entry which is used as name of the block."
14287 (unless (bolp) (newline))
14288 (let ((name (plist-get plist :name)))
14289 (insert "#+BEGIN: " name)
14290 (while plist
14291 (if (eq (car plist) :name)
14292 (setq plist (cddr plist))
14293 (insert " " (prin1-to-string (pop plist)))))
14294 (insert "\n\n#+END:\n")
14295 (beginning-of-line -2)))
14297 (defun org-prepare-dblock ()
14298 "Prepare dynamic block for refresh.
14299 This empties the block, puts the cursor at the insert position and returns
14300 the property list including an extra property :name with the block name."
14301 (unless (looking-at org-dblock-start-re)
14302 (error "Not at a dynamic block"))
14303 (let* ((begdel (1+ (match-end 0)))
14304 (name (org-no-properties (match-string 1)))
14305 (params (append (list :name name)
14306 (read (concat "(" (match-string 3) ")")))))
14307 (unless (re-search-forward org-dblock-end-re nil t)
14308 (error "Dynamic block not terminated"))
14309 (delete-region begdel (match-beginning 0))
14310 (goto-char begdel)
14311 (open-line 1)
14312 params))
14314 (defun org-map-dblocks (&optional command)
14315 "Apply COMMAND to all dynamic blocks in the current buffer.
14316 If COMMAND is not given, use `org-update-dblock'."
14317 (let ((cmd (or command 'org-update-dblock))
14318 pos)
14319 (save-excursion
14320 (goto-char (point-min))
14321 (while (re-search-forward org-dblock-start-re nil t)
14322 (goto-char (setq pos (match-beginning 0)))
14323 (condition-case nil
14324 (funcall cmd)
14325 (error (message "Error during update of dynamic block")))
14326 (goto-char pos)
14327 (unless (re-search-forward org-dblock-end-re nil t)
14328 (error "Dynamic block not terminated"))))))
14330 (defun org-dblock-update (&optional arg)
14331 "User command for updating dynamic blocks.
14332 Update the dynamic block at point. With prefix ARG, update all dynamic
14333 blocks in the buffer."
14334 (interactive "P")
14335 (if arg
14336 (org-update-all-dblocks)
14337 (or (looking-at org-dblock-start-re)
14338 (org-beginning-of-dblock))
14339 (org-update-dblock)))
14341 (defun org-update-dblock ()
14342 "Update the dynamic block at point
14343 This means to empty the block, parse for parameters and then call
14344 the correct writing function."
14345 (save-window-excursion
14346 (let* ((pos (point))
14347 (line (org-current-line))
14348 (params (org-prepare-dblock))
14349 (name (plist-get params :name))
14350 (cmd (intern (concat "org-dblock-write:" name))))
14351 (message "Updating dynamic block `%s' at line %d..." name line)
14352 (funcall cmd params)
14353 (message "Updating dynamic block `%s' at line %d...done" name line)
14354 (goto-char pos))))
14356 (defun org-beginning-of-dblock ()
14357 "Find the beginning of the dynamic block at point.
14358 Error if there is no scuh block at point."
14359 (let ((pos (point))
14360 beg)
14361 (end-of-line 1)
14362 (if (and (re-search-backward org-dblock-start-re nil t)
14363 (setq beg (match-beginning 0))
14364 (re-search-forward org-dblock-end-re nil t)
14365 (> (match-end 0) pos))
14366 (goto-char beg)
14367 (goto-char pos)
14368 (error "Not in a dynamic block"))))
14370 (defun org-update-all-dblocks ()
14371 "Update all dynamic blocks in the buffer.
14372 This function can be used in a hook."
14373 (when (org-mode-p)
14374 (org-map-dblocks 'org-update-dblock)))
14377 ;;;; Completion
14379 (defconst org-additional-option-like-keywords
14380 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14381 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14382 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14384 (defun org-complete (&optional arg)
14385 "Perform completion on word at point.
14386 At the beginning of a headline, this completes TODO keywords as given in
14387 `org-todo-keywords'.
14388 If the current word is preceded by a backslash, completes the TeX symbols
14389 that are supported for HTML support.
14390 If the current word is preceded by \"#+\", completes special words for
14391 setting file options.
14392 In the line after \"#+STARTUP:, complete valid keywords.\"
14393 At all other locations, this simply calls the value of
14394 `org-completion-fallback-command'."
14395 (interactive "P")
14396 (org-without-partial-completion
14397 (catch 'exit
14398 (let* ((end (point))
14399 (beg1 (save-excursion
14400 (skip-chars-backward (org-re "[:alnum:]_@"))
14401 (point)))
14402 (beg (save-excursion
14403 (skip-chars-backward "a-zA-Z0-9_:$")
14404 (point)))
14405 (confirm (lambda (x) (stringp (car x))))
14406 (searchhead (equal (char-before beg) ?*))
14407 (tag (and (equal (char-before beg1) ?:)
14408 (equal (char-after (point-at-bol)) ?*)))
14409 (prop (and (equal (char-before beg1) ?:)
14410 (not (equal (char-after (point-at-bol)) ?*))))
14411 (texp (equal (char-before beg) ?\\))
14412 (link (equal (char-before beg) ?\[))
14413 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14414 beg)
14415 "#+"))
14416 (startup (string-match "^#\\+STARTUP:.*"
14417 (buffer-substring (point-at-bol) (point))))
14418 (completion-ignore-case opt)
14419 (type nil)
14420 (tbl nil)
14421 (table (cond
14422 (opt
14423 (setq type :opt)
14424 (append
14425 (mapcar
14426 (lambda (x)
14427 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14428 (cons (match-string 2 x) (match-string 1 x)))
14429 (org-split-string (org-get-current-options) "\n"))
14430 (mapcar 'list org-additional-option-like-keywords)))
14431 (startup
14432 (setq type :startup)
14433 org-startup-options)
14434 (link (append org-link-abbrev-alist-local
14435 org-link-abbrev-alist))
14436 (texp
14437 (setq type :tex)
14438 org-html-entities)
14439 ((string-match "\\`\\*+[ \t]+\\'"
14440 (buffer-substring (point-at-bol) beg))
14441 (setq type :todo)
14442 (mapcar 'list org-todo-keywords-1))
14443 (searchhead
14444 (setq type :searchhead)
14445 (save-excursion
14446 (goto-char (point-min))
14447 (while (re-search-forward org-todo-line-regexp nil t)
14448 (push (list
14449 (org-make-org-heading-search-string
14450 (match-string 3) t))
14451 tbl)))
14452 tbl)
14453 (tag (setq type :tag beg beg1)
14454 (or org-tag-alist (org-get-buffer-tags)))
14455 (prop (setq type :prop beg beg1)
14456 (mapcar 'list (org-buffer-property-keys nil t t)))
14457 (t (progn
14458 (call-interactively org-completion-fallback-command)
14459 (throw 'exit nil)))))
14460 (pattern (buffer-substring-no-properties beg end))
14461 (completion (try-completion pattern table confirm)))
14462 (cond ((eq completion t)
14463 (if (not (assoc (upcase pattern) table))
14464 (message "Already complete")
14465 (if (equal type :opt)
14466 (insert (substring (cdr (assoc (upcase pattern) table))
14467 (length pattern)))
14468 (if (memq type '(:tag :prop)) (insert ":")))))
14469 ((null completion)
14470 (message "Can't find completion for \"%s\"" pattern)
14471 (ding))
14472 ((not (string= pattern completion))
14473 (delete-region beg end)
14474 (if (string-match " +$" completion)
14475 (setq completion (replace-match "" t t completion)))
14476 (insert completion)
14477 (if (get-buffer-window "*Completions*")
14478 (delete-window (get-buffer-window "*Completions*")))
14479 (if (assoc completion table)
14480 (if (eq type :todo) (insert " ")
14481 (if (memq type '(:tag :prop)) (insert ":"))))
14482 (if (and (equal type :opt) (assoc completion table))
14483 (message "%s" (substitute-command-keys
14484 "Press \\[org-complete] again to insert example settings"))))
14486 (message "Making completion list...")
14487 (let ((list (sort (all-completions pattern table confirm)
14488 'string<)))
14489 (with-output-to-temp-buffer "*Completions*"
14490 (condition-case nil
14491 ;; Protection needed for XEmacs and emacs 21
14492 (display-completion-list list pattern)
14493 (error (display-completion-list list)))))
14494 (message "Making completion list...%s" "done")))))))
14496 ;;;; TODO, DEADLINE, Comments
14498 (defun org-toggle-comment ()
14499 "Change the COMMENT state of an entry."
14500 (interactive)
14501 (save-excursion
14502 (org-back-to-heading)
14503 (let (case-fold-search)
14504 (if (looking-at (concat outline-regexp
14505 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14506 (replace-match "" t t nil 1)
14507 (if (looking-at outline-regexp)
14508 (progn
14509 (goto-char (match-end 0))
14510 (insert org-comment-string " ")))))))
14512 (defvar org-last-todo-state-is-todo nil
14513 "This is non-nil when the last TODO state change led to a TODO state.
14514 If the last change removed the TODO tag or switched to DONE, then
14515 this is nil.")
14517 (defvar org-setting-tags nil) ; dynamically skiped
14519 ;; FIXME: better place
14520 (defun org-property-or-variable-value (var &optional inherit)
14521 "Check if there is a property fixing the value of VAR.
14522 If yes, return this value. If not, return the current value of the variable."
14523 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14524 (if (and prop (stringp prop) (string-match "\\S-" prop))
14525 (read prop)
14526 (symbol-value var))))
14528 (defun org-parse-local-options (string var)
14529 "Parse STRING for startup setting relevant for variable VAR."
14530 (let ((rtn (symbol-value var))
14531 e opts)
14532 (save-match-data
14533 (if (or (not string) (not (string-match "\\S-" string)))
14535 (setq opts (delq nil (mapcar (lambda (x)
14536 (setq e (assoc x org-startup-options))
14537 (if (eq (nth 1 e) var) e nil))
14538 (org-split-string string "[ \t]+"))))
14539 (if (not opts)
14541 (setq rtn nil)
14542 (while (setq e (pop opts))
14543 (if (not (nth 3 e))
14544 (setq rtn (nth 2 e))
14545 (if (not (listp rtn)) (setq rtn nil))
14546 (push (nth 2 e) rtn)))
14547 rtn)))))
14549 (defvar org-blocker-hook nil
14550 "Hook for functions that are allowed to block a state change.
14552 Each function gets as its single argument a property list, see
14553 `org-trigger-hook' for more information about this list.
14555 If any of the functions in this hook returns nil, the state change
14556 is blocked.")
14558 (defvar org-trigger-hook nil
14559 "Hook for functions that are triggered by a state change.
14561 Each function gets as its single argument a property list with at least
14562 the following elements:
14564 (:type type-of-change :position pos-at-entry-start
14565 :from old-state :to new-state)
14567 Depending on the type, more properties may be present.
14569 This mechanism is currently implemented for:
14571 TODO state changes
14572 ------------------
14573 :type todo-state-change
14574 :from previous state (keyword as a string), or nil
14575 :to new state (keyword as a string), or nil")
14578 (defun org-todo (&optional arg)
14579 "Change the TODO state of an item.
14580 The state of an item is given by a keyword at the start of the heading,
14581 like
14582 *** TODO Write paper
14583 *** DONE Call mom
14585 The different keywords are specified in the variable `org-todo-keywords'.
14586 By default the available states are \"TODO\" and \"DONE\".
14587 So for this example: when the item starts with TODO, it is changed to DONE.
14588 When it starts with DONE, the DONE is removed. And when neither TODO nor
14589 DONE are present, add TODO at the beginning of the heading.
14591 With C-u prefix arg, use completion to determine the new state.
14592 With numeric prefix arg, switch to that state.
14594 For calling through lisp, arg is also interpreted in the following way:
14595 'none -> empty state
14596 \"\"(empty string) -> switch to empty state
14597 'done -> switch to DONE
14598 'nextset -> switch to the next set of keywords
14599 'previousset -> switch to the previous set of keywords
14600 \"WAITING\" -> switch to the specified keyword, but only if it
14601 really is a member of `org-todo-keywords'."
14602 (interactive "P")
14603 (save-excursion
14604 (catch 'exit
14605 (org-back-to-heading)
14606 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14607 (or (looking-at (concat " +" org-todo-regexp " *"))
14608 (looking-at " *"))
14609 (let* ((match-data (match-data))
14610 (startpos (point-at-bol))
14611 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14612 (org-log-done org-log-done)
14613 (org-log-repeat org-log-repeat)
14614 (org-todo-log-states org-todo-log-states)
14615 (this (match-string 1))
14616 (hl-pos (match-beginning 0))
14617 (head (org-get-todo-sequence-head this))
14618 (ass (assoc head org-todo-kwd-alist))
14619 (interpret (nth 1 ass))
14620 (done-word (nth 3 ass))
14621 (final-done-word (nth 4 ass))
14622 (last-state (or this ""))
14623 (completion-ignore-case t)
14624 (member (member this org-todo-keywords-1))
14625 (tail (cdr member))
14626 (state (cond
14627 ((and org-todo-key-trigger
14628 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14629 (and (not arg) org-use-fast-todo-selection
14630 (not (eq org-use-fast-todo-selection 'prefix)))))
14631 ;; Use fast selection
14632 (org-fast-todo-selection))
14633 ((and (equal arg '(4))
14634 (or (not org-use-fast-todo-selection)
14635 (not org-todo-key-trigger)))
14636 ;; Read a state with completion
14637 (completing-read "State: " (mapcar (lambda(x) (list x))
14638 org-todo-keywords-1)
14639 nil t))
14640 ((eq arg 'right)
14641 (if this
14642 (if tail (car tail) nil)
14643 (car org-todo-keywords-1)))
14644 ((eq arg 'left)
14645 (if (equal member org-todo-keywords-1)
14647 (if this
14648 (nth (- (length org-todo-keywords-1) (length tail) 2)
14649 org-todo-keywords-1)
14650 (org-last org-todo-keywords-1))))
14651 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14652 (setq arg nil))) ; hack to fall back to cycling
14653 (arg
14654 ;; user or caller requests a specific state
14655 (cond
14656 ((equal arg "") nil)
14657 ((eq arg 'none) nil)
14658 ((eq arg 'done) (or done-word (car org-done-keywords)))
14659 ((eq arg 'nextset)
14660 (or (car (cdr (member head org-todo-heads)))
14661 (car org-todo-heads)))
14662 ((eq arg 'previousset)
14663 (let ((org-todo-heads (reverse org-todo-heads)))
14664 (or (car (cdr (member head org-todo-heads)))
14665 (car org-todo-heads))))
14666 ((car (member arg org-todo-keywords-1)))
14667 ((nth (1- (prefix-numeric-value arg))
14668 org-todo-keywords-1))))
14669 ((null member) (or head (car org-todo-keywords-1)))
14670 ((equal this final-done-word) nil) ;; -> make empty
14671 ((null tail) nil) ;; -> first entry
14672 ((eq interpret 'sequence)
14673 (car tail))
14674 ((memq interpret '(type priority))
14675 (if (eq this-command last-command)
14676 (car tail)
14677 (if (> (length tail) 0)
14678 (or done-word (car org-done-keywords))
14679 nil)))
14680 (t nil)))
14681 (next (if state (concat " " state " ") " "))
14682 (change-plist (list :type 'todo-state-change :from this :to state
14683 :position startpos))
14684 dolog now-done-p)
14685 (when org-blocker-hook
14686 (unless (save-excursion
14687 (save-match-data
14688 (run-hook-with-args-until-failure
14689 'org-blocker-hook change-plist)))
14690 (if (interactive-p)
14691 (error "TODO state change from %s to %s blocked" this state)
14692 ;; fail silently
14693 (message "TODO state change from %s to %s blocked" this state)
14694 (throw 'exit nil))))
14695 (store-match-data match-data)
14696 (replace-match next t t)
14697 (unless (pos-visible-in-window-p hl-pos)
14698 (message "TODO state changed to %s" (org-trim next)))
14699 (unless head
14700 (setq head (org-get-todo-sequence-head state)
14701 ass (assoc head org-todo-kwd-alist)
14702 interpret (nth 1 ass)
14703 done-word (nth 3 ass)
14704 final-done-word (nth 4 ass)))
14705 (when (memq arg '(nextset previousset))
14706 (message "Keyword-Set %d/%d: %s"
14707 (- (length org-todo-sets) -1
14708 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14709 (length org-todo-sets)
14710 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14711 (setq org-last-todo-state-is-todo
14712 (not (member state org-done-keywords)))
14713 (setq now-done-p (and (member state org-done-keywords)
14714 (not (member this org-done-keywords))))
14715 (and logging (org-local-logging logging))
14716 (when (and (or org-todo-log-states org-log-done)
14717 (not (memq arg '(nextset previousset))))
14718 ;; we need to look at recording a time and note
14719 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14720 (nth 2 (assoc this org-todo-log-states))))
14721 (when (and state
14722 (member state org-not-done-keywords)
14723 (not (member this org-not-done-keywords)))
14724 ;; This is now a todo state and was not one before
14725 ;; If there was a CLOSED time stamp, get rid of it.
14726 (org-add-planning-info nil nil 'closed))
14727 (when (and now-done-p org-log-done)
14728 ;; It is now done, and it was not done before
14729 (org-add-planning-info 'closed (org-current-time))
14730 (if (and (not dolog) (eq 'note org-log-done))
14731 (org-add-log-maybe 'done state 'findpos 'note)))
14732 (when (and state dolog)
14733 ;; This is a non-nil state, and we need to log it
14734 (org-add-log-maybe 'state state 'findpos dolog)))
14735 ;; Fixup tag positioning
14736 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14737 (run-hooks 'org-after-todo-state-change-hook)
14738 (if (and arg (not (member state org-done-keywords)))
14739 (setq head (org-get-todo-sequence-head state)))
14740 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14741 ;; Do we need to trigger a repeat?
14742 (when now-done-p (org-auto-repeat-maybe state))
14743 ;; Fixup cursor location if close to the keyword
14744 (if (and (outline-on-heading-p)
14745 (not (bolp))
14746 (save-excursion (beginning-of-line 1)
14747 (looking-at org-todo-line-regexp))
14748 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14749 (progn
14750 (goto-char (or (match-end 2) (match-end 1)))
14751 (just-one-space)))
14752 (when org-trigger-hook
14753 (save-excursion
14754 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14756 (defun org-local-logging (value)
14757 "Get logging settings from a property VALUE."
14758 (let* (words w a)
14759 ;; directly set the variables, they are already local.
14760 (setq org-log-done nil
14761 org-log-repeat nil
14762 org-todo-log-states nil)
14763 (setq words (org-split-string value))
14764 (while (setq w (pop words))
14765 (cond
14766 ((setq a (assoc w org-startup-options))
14767 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14768 (set (nth 1 a) (nth 2 a))))
14769 ((setq a (org-extract-log-state-settings w))
14770 (and (member (car a) org-todo-keywords-1)
14771 (push a org-todo-log-states)))))))
14773 (defun org-get-todo-sequence-head (kwd)
14774 "Return the head of the TODO sequence to which KWD belongs.
14775 If KWD is not set, check if there is a text property remembering the
14776 right sequence."
14777 (let (p)
14778 (cond
14779 ((not kwd)
14780 (or (get-text-property (point-at-bol) 'org-todo-head)
14781 (progn
14782 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14783 nil (point-at-eol)))
14784 (get-text-property p 'org-todo-head))))
14785 ((not (member kwd org-todo-keywords-1))
14786 (car org-todo-keywords-1))
14787 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14789 (defun org-fast-todo-selection ()
14790 "Fast TODO keyword selection with single keys.
14791 Returns the new TODO keyword, or nil if no state change should occur."
14792 (let* ((fulltable org-todo-key-alist)
14793 (done-keywords org-done-keywords) ;; needed for the faces.
14794 (maxlen (apply 'max (mapcar
14795 (lambda (x)
14796 (if (stringp (car x)) (string-width (car x)) 0))
14797 fulltable)))
14798 (expert nil)
14799 (fwidth (+ maxlen 3 1 3))
14800 (ncol (/ (- (window-width) 4) fwidth))
14801 tg cnt e c tbl
14802 groups ingroup)
14803 (save-window-excursion
14804 (if expert
14805 (set-buffer (get-buffer-create " *Org todo*"))
14806 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14807 (erase-buffer)
14808 (org-set-local 'org-done-keywords done-keywords)
14809 (setq tbl fulltable cnt 0)
14810 (while (setq e (pop tbl))
14811 (cond
14812 ((equal e '(:startgroup))
14813 (push '() groups) (setq ingroup t)
14814 (when (not (= cnt 0))
14815 (setq cnt 0)
14816 (insert "\n"))
14817 (insert "{ "))
14818 ((equal e '(:endgroup))
14819 (setq ingroup nil cnt 0)
14820 (insert "}\n"))
14822 (setq tg (car e) c (cdr e))
14823 (if ingroup (push tg (car groups)))
14824 (setq tg (org-add-props tg nil 'face
14825 (org-get-todo-face tg)))
14826 (if (and (= cnt 0) (not ingroup)) (insert " "))
14827 (insert "[" c "] " tg (make-string
14828 (- fwidth 4 (length tg)) ?\ ))
14829 (when (= (setq cnt (1+ cnt)) ncol)
14830 (insert "\n")
14831 (if ingroup (insert " "))
14832 (setq cnt 0)))))
14833 (insert "\n")
14834 (goto-char (point-min))
14835 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14836 (fit-window-to-buffer))
14837 (message "[a-z..]:Set [SPC]:clear")
14838 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14839 (cond
14840 ((or (= c ?\C-g)
14841 (and (= c ?q) (not (rassoc c fulltable))))
14842 (setq quit-flag t))
14843 ((= c ?\ ) nil)
14844 ((setq e (rassoc c fulltable) tg (car e))
14846 (t (setq quit-flag t))))))
14848 (defun org-get-repeat ()
14849 "Check if tere is a deadline/schedule with repeater in this entry."
14850 (save-match-data
14851 (save-excursion
14852 (org-back-to-heading t)
14853 (if (re-search-forward
14854 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14855 (match-string 1)))))
14857 (defvar org-last-changed-timestamp)
14858 (defvar org-log-post-message)
14859 (defvar org-log-note-purpose)
14860 (defun org-auto-repeat-maybe (done-word)
14861 "Check if the current headline contains a repeated deadline/schedule.
14862 If yes, set TODO state back to what it was and change the base date
14863 of repeating deadline/scheduled time stamps to new date.
14864 This function is run automatically after each state change to a DONE state."
14865 ;; last-state is dynamically scoped into this function
14866 (let* ((repeat (org-get-repeat))
14867 (aa (assoc last-state org-todo-kwd-alist))
14868 (interpret (nth 1 aa))
14869 (head (nth 2 aa))
14870 (whata '(("d" . day) ("m" . month) ("y" . year)))
14871 (msg "Entry repeats: ")
14872 (org-log-done nil)
14873 (org-todo-log-states nil)
14874 re type n what ts)
14875 (when repeat
14876 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14877 (org-todo (if (eq interpret 'type) last-state head))
14878 (when (and org-log-repeat
14879 (or (not (memq 'org-add-log-note
14880 (default-value 'post-command-hook)))
14881 (eq org-log-note-purpose 'done)))
14882 ;; Make sure a note is taken;
14883 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14884 'findpos org-log-repeat))
14885 (org-back-to-heading t)
14886 (org-add-planning-info nil nil 'closed)
14887 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14888 org-deadline-time-regexp "\\)\\|\\("
14889 org-ts-regexp "\\)"))
14890 (while (re-search-forward
14891 re (save-excursion (outline-next-heading) (point)) t)
14892 (setq type (if (match-end 1) org-scheduled-string
14893 (if (match-end 3) org-deadline-string "Plain:"))
14894 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14895 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14896 (setq n (string-to-number (match-string 1 ts))
14897 what (match-string 2 ts))
14898 (if (equal what "w") (setq n (* n 7) what "d"))
14899 (org-timestamp-change n (cdr (assoc what whata)))
14900 (setq msg (concat msg type org-last-changed-timestamp " "))))
14901 (setq org-log-post-message msg)
14902 (message "%s" msg))))
14904 (defun org-show-todo-tree (arg)
14905 "Make a compact tree which shows all headlines marked with TODO.
14906 The tree will show the lines where the regexp matches, and all higher
14907 headlines above the match.
14908 With a \\[universal-argument] prefix, also show the DONE entries.
14909 With a numeric prefix N, construct a sparse tree for the Nth element
14910 of `org-todo-keywords-1'."
14911 (interactive "P")
14912 (let ((case-fold-search nil)
14913 (kwd-re
14914 (cond ((null arg) org-not-done-regexp)
14915 ((equal arg '(4))
14916 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14917 (mapcar 'list org-todo-keywords-1))))
14918 (concat "\\("
14919 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14920 "\\)\\>")))
14921 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14922 (regexp-quote (nth (1- (prefix-numeric-value arg))
14923 org-todo-keywords-1)))
14924 (t (error "Invalid prefix argument: %s" arg)))))
14925 (message "%d TODO entries found"
14926 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14928 (defun org-deadline (&optional remove)
14929 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14930 With argument REMOVE, remove any deadline from the item."
14931 (interactive "P")
14932 (if remove
14933 (progn
14934 (org-remove-timestamp-with-keyword org-deadline-string)
14935 (message "Item no longer has a deadline."))
14936 (org-add-planning-info 'deadline nil 'closed)))
14938 (defun org-schedule (&optional remove)
14939 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14940 With argument REMOVE, remove any scheduling date from the item."
14941 (interactive "P")
14942 (if remove
14943 (progn
14944 (org-remove-timestamp-with-keyword org-scheduled-string)
14945 (message "Item is no longer scheduled."))
14946 (org-add-planning-info 'scheduled nil 'closed)))
14948 (defun org-remove-timestamp-with-keyword (keyword)
14949 "Remove all time stamps with KEYWORD in the current entry."
14950 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14951 beg)
14952 (save-excursion
14953 (org-back-to-heading t)
14954 (setq beg (point))
14955 (org-end-of-subtree t t)
14956 (while (re-search-backward re beg t)
14957 (replace-match "")
14958 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14959 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14961 (defun org-add-planning-info (what &optional time &rest remove)
14962 "Insert new timestamp with keyword in the line directly after the headline.
14963 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14964 If non is given, the user is prompted for a date.
14965 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14966 be removed."
14967 (interactive)
14968 (let (org-time-was-given org-end-time-was-given)
14969 (when what (setq time (or time (org-read-date nil 'to-time))))
14970 (when (and org-insert-labeled-timestamps-at-point
14971 (member what '(scheduled deadline)))
14972 (insert
14973 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14974 (org-insert-time-stamp time org-time-was-given
14975 nil nil nil (list org-end-time-was-given))
14976 (setq what nil))
14977 (save-excursion
14978 (save-restriction
14979 (let (col list elt ts buffer-invisibility-spec)
14980 (org-back-to-heading t)
14981 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14982 (goto-char (match-end 1))
14983 (setq col (current-column))
14984 (goto-char (match-end 0))
14985 (if (eobp) (insert "\n") (forward-char 1))
14986 (if (and (not (looking-at outline-regexp))
14987 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14988 "[^\r\n]*"))
14989 (not (equal (match-string 1) org-clock-string)))
14990 (narrow-to-region (match-beginning 0) (match-end 0))
14991 (insert-before-markers "\n")
14992 (backward-char 1)
14993 (narrow-to-region (point) (point))
14994 (indent-to-column col))
14995 ;; Check if we have to remove something.
14996 (setq list (cons what remove))
14997 (while list
14998 (setq elt (pop list))
14999 (goto-char (point-min))
15000 (when (or (and (eq elt 'scheduled)
15001 (re-search-forward org-scheduled-time-regexp nil t))
15002 (and (eq elt 'deadline)
15003 (re-search-forward org-deadline-time-regexp nil t))
15004 (and (eq elt 'closed)
15005 (re-search-forward org-closed-time-regexp nil t)))
15006 (replace-match "")
15007 (if (looking-at "--+<[^>]+>") (replace-match ""))
15008 (if (looking-at " +") (replace-match ""))))
15009 (goto-char (point-max))
15010 (when what
15011 (insert
15012 (if (not (equal (char-before) ?\ )) " " "")
15013 (cond ((eq what 'scheduled) org-scheduled-string)
15014 ((eq what 'deadline) org-deadline-string)
15015 ((eq what 'closed) org-closed-string))
15016 " ")
15017 (setq ts (org-insert-time-stamp
15018 time
15019 (or org-time-was-given
15020 (and (eq what 'closed) org-log-done-with-time))
15021 (eq what 'closed)
15022 nil nil (list org-end-time-was-given)))
15023 (end-of-line 1))
15024 (goto-char (point-min))
15025 (widen)
15026 (if (looking-at "[ \t]+\r?\n")
15027 (replace-match ""))
15028 ts)))))
15030 (defvar org-log-note-marker (make-marker))
15031 (defvar org-log-note-purpose nil)
15032 (defvar org-log-note-state nil)
15033 (defvar org-log-note-how nil)
15034 (defvar org-log-note-window-configuration nil)
15035 (defvar org-log-note-return-to (make-marker))
15036 (defvar org-log-post-message nil
15037 "Message to be displayed after a log note has been stored.
15038 The auto-repeater uses this.")
15040 (defun org-add-log-maybe (&optional purpose state findpos how)
15041 "Set up the post command hook to take a note.
15042 If this is about to TODO state change, the new state is expected in STATE.
15043 When FINDPOS is non-nil, find the correct position for the note in
15044 the current entry. If not, assume that it can be inserted at point."
15045 (save-excursion
15046 (when findpos
15047 (org-back-to-heading t)
15048 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15049 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15050 "[^\r\n]*\\)?"))
15051 (goto-char (match-end 0))
15052 (unless org-log-states-order-reversed
15053 (and (= (char-after) ?\n) (forward-char 1))
15054 (org-skip-over-state-notes)
15055 (skip-chars-backward " \t\n\r")))
15056 (move-marker org-log-note-marker (point))
15057 (setq org-log-note-purpose purpose
15058 org-log-note-state state
15059 org-log-note-how how)
15060 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15062 (defun org-skip-over-state-notes ()
15063 "Skip past the list of State notes in an entry."
15064 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15065 (while (looking-at "[ \t]*- State")
15066 (condition-case nil
15067 (org-next-item)
15068 (error (org-end-of-item)))))
15070 (defun org-add-log-note (&optional purpose)
15071 "Pop up a window for taking a note, and add this note later at point."
15072 (remove-hook 'post-command-hook 'org-add-log-note)
15073 (setq org-log-note-window-configuration (current-window-configuration))
15074 (delete-other-windows)
15075 (move-marker org-log-note-return-to (point))
15076 (switch-to-buffer (marker-buffer org-log-note-marker))
15077 (goto-char org-log-note-marker)
15078 (org-switch-to-buffer-other-window "*Org Note*")
15079 (erase-buffer)
15080 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15081 (org-store-log-note)
15082 (let ((org-inhibit-startup t)) (org-mode))
15083 (insert (format "# Insert note for %s.
15084 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15085 (cond
15086 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15087 ((eq org-log-note-purpose 'done) "closed todo item")
15088 ((eq org-log-note-purpose 'state)
15089 (format "state change to \"%s\"" org-log-note-state))
15090 (t (error "This should not happen")))))
15091 (org-set-local 'org-finish-function 'org-store-log-note)))
15093 (defun org-store-log-note ()
15094 "Finish taking a log note, and insert it to where it belongs."
15095 (let ((txt (buffer-string))
15096 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15097 lines ind)
15098 (kill-buffer (current-buffer))
15099 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15100 (setq txt (replace-match "" t t txt)))
15101 (if (string-match "\\s-+\\'" txt)
15102 (setq txt (replace-match "" t t txt)))
15103 (setq lines (org-split-string txt "\n"))
15104 (when (and note (string-match "\\S-" note))
15105 (setq note
15106 (org-replace-escapes
15107 note
15108 (list (cons "%u" (user-login-name))
15109 (cons "%U" user-full-name)
15110 (cons "%t" (format-time-string
15111 (org-time-stamp-format 'long 'inactive)
15112 (current-time)))
15113 (cons "%s" (if org-log-note-state
15114 (concat "\"" org-log-note-state "\"")
15115 "")))))
15116 (if lines (setq note (concat note " \\\\")))
15117 (push note lines))
15118 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15119 (when lines
15120 (save-excursion
15121 (set-buffer (marker-buffer org-log-note-marker))
15122 (save-excursion
15123 (goto-char org-log-note-marker)
15124 (move-marker org-log-note-marker nil)
15125 (end-of-line 1)
15126 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15127 (indent-relative nil)
15128 (insert "- " (pop lines))
15129 (org-indent-line-function)
15130 (beginning-of-line 1)
15131 (looking-at "[ \t]*")
15132 (setq ind (concat (match-string 0) " "))
15133 (end-of-line 1)
15134 (while lines (insert "\n" ind (pop lines)))))))
15135 (set-window-configuration org-log-note-window-configuration)
15136 (with-current-buffer (marker-buffer org-log-note-return-to)
15137 (goto-char org-log-note-return-to))
15138 (move-marker org-log-note-return-to nil)
15139 (and org-log-post-message (message "%s" org-log-post-message)))
15141 ;; FIXME: what else would be useful?
15142 ;; - priority
15143 ;; - date
15145 (defun org-sparse-tree (&optional arg)
15146 "Create a sparse tree, prompt for the details.
15147 This command can create sparse trees. You first need to select the type
15148 of match used to create the tree:
15150 t Show entries with a specific TODO keyword.
15151 T Show entries selected by a tags match.
15152 p Enter a property name and its value (both with completion on existing
15153 names/values) and show entries with that property.
15154 r Show entries matching a regular expression
15155 d Show deadlines due within `org-deadline-warning-days'."
15156 (interactive "P")
15157 (let (ans kwd value)
15158 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15159 (setq ans (read-char-exclusive))
15160 (cond
15161 ((equal ans ?d)
15162 (call-interactively 'org-check-deadlines))
15163 ((equal ans ?b)
15164 (call-interactively 'org-check-before-date))
15165 ((equal ans ?t)
15166 (org-show-todo-tree '(4)))
15167 ((equal ans ?T)
15168 (call-interactively 'org-tags-sparse-tree))
15169 ((member ans '(?p ?P))
15170 (setq kwd (completing-read "Property: "
15171 (mapcar 'list (org-buffer-property-keys))))
15172 (setq value (completing-read "Value: "
15173 (mapcar 'list (org-property-values kwd))))
15174 (unless (string-match "\\`{.*}\\'" value)
15175 (setq value (concat "\"" value "\"")))
15176 (org-tags-sparse-tree arg (concat kwd "=" value)))
15177 ((member ans '(?r ?R ?/))
15178 (call-interactively 'org-occur))
15179 (t (error "No such sparse tree command \"%c\"" ans)))))
15181 (defvar org-occur-highlights nil)
15182 (make-variable-buffer-local 'org-occur-highlights)
15184 (defun org-occur (regexp &optional keep-previous callback)
15185 "Make a compact tree which shows all matches of REGEXP.
15186 The tree will show the lines where the regexp matches, and all higher
15187 headlines above the match. It will also show the heading after the match,
15188 to make sure editing the matching entry is easy.
15189 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15190 call to `org-occur' will be kept, to allow stacking of calls to this
15191 command.
15192 If CALLBACK is non-nil, it is a function which is called to confirm
15193 that the match should indeed be shown."
15194 (interactive "sRegexp: \nP")
15195 (or keep-previous (org-remove-occur-highlights nil nil t))
15196 (let ((cnt 0))
15197 (save-excursion
15198 (goto-char (point-min))
15199 (if (or (not keep-previous) ; do not want to keep
15200 (not org-occur-highlights)) ; no previous matches
15201 ;; hide everything
15202 (org-overview))
15203 (while (re-search-forward regexp nil t)
15204 (when (or (not callback)
15205 (save-match-data (funcall callback)))
15206 (setq cnt (1+ cnt))
15207 (when org-highlight-sparse-tree-matches
15208 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15209 (org-show-context 'occur-tree))))
15210 (when org-remove-highlights-with-change
15211 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15212 nil 'local))
15213 (unless org-sparse-tree-open-archived-trees
15214 (org-hide-archived-subtrees (point-min) (point-max)))
15215 (run-hooks 'org-occur-hook)
15216 (if (interactive-p)
15217 (message "%d match(es) for regexp %s" cnt regexp))
15218 cnt))
15220 (defun org-show-context (&optional key)
15221 "Make sure point and context and visible.
15222 How much context is shown depends upon the variables
15223 `org-show-hierarchy-above', `org-show-following-heading'. and
15224 `org-show-siblings'."
15225 (let ((heading-p (org-on-heading-p t))
15226 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15227 (following-p (org-get-alist-option org-show-following-heading key))
15228 (entry-p (org-get-alist-option org-show-entry-below key))
15229 (siblings-p (org-get-alist-option org-show-siblings key)))
15230 (catch 'exit
15231 ;; Show heading or entry text
15232 (if (and heading-p (not entry-p))
15233 (org-flag-heading nil) ; only show the heading
15234 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15235 (org-show-hidden-entry))) ; show entire entry
15236 (when following-p
15237 ;; Show next sibling, or heading below text
15238 (save-excursion
15239 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15240 (org-flag-heading nil))))
15241 (when siblings-p (org-show-siblings))
15242 (when hierarchy-p
15243 ;; show all higher headings, possibly with siblings
15244 (save-excursion
15245 (while (and (condition-case nil
15246 (progn (org-up-heading-all 1) t)
15247 (error nil))
15248 (not (bobp)))
15249 (org-flag-heading nil)
15250 (when siblings-p (org-show-siblings))))))))
15252 (defun org-reveal (&optional siblings)
15253 "Show current entry, hierarchy above it, and the following headline.
15254 This can be used to show a consistent set of context around locations
15255 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15256 not t for the search context.
15258 With optional argument SIBLINGS, on each level of the hierarchy all
15259 siblings are shown. This repairs the tree structure to what it would
15260 look like when opened with hierarchical calls to `org-cycle'."
15261 (interactive "P")
15262 (let ((org-show-hierarchy-above t)
15263 (org-show-following-heading t)
15264 (org-show-siblings (if siblings t org-show-siblings)))
15265 (org-show-context nil)))
15267 (defun org-highlight-new-match (beg end)
15268 "Highlight from BEG to END and mark the highlight is an occur headline."
15269 (let ((ov (org-make-overlay beg end)))
15270 (org-overlay-put ov 'face 'secondary-selection)
15271 (push ov org-occur-highlights)))
15273 (defun org-remove-occur-highlights (&optional beg end noremove)
15274 "Remove the occur highlights from the buffer.
15275 BEG and END are ignored. If NOREMOVE is nil, remove this function
15276 from the `before-change-functions' in the current buffer."
15277 (interactive)
15278 (unless org-inhibit-highlight-removal
15279 (mapc 'org-delete-overlay org-occur-highlights)
15280 (setq org-occur-highlights nil)
15281 (unless noremove
15282 (remove-hook 'before-change-functions
15283 'org-remove-occur-highlights 'local))))
15285 ;;;; Priorities
15287 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15288 "Regular expression matching the priority indicator.")
15290 (defvar org-remove-priority-next-time nil)
15292 (defun org-priority-up ()
15293 "Increase the priority of the current item."
15294 (interactive)
15295 (org-priority 'up))
15297 (defun org-priority-down ()
15298 "Decrease the priority of the current item."
15299 (interactive)
15300 (org-priority 'down))
15302 (defun org-priority (&optional action)
15303 "Change the priority of an item by ARG.
15304 ACTION can be `set', `up', `down', or a character."
15305 (interactive)
15306 (setq action (or action 'set))
15307 (let (current new news have remove)
15308 (save-excursion
15309 (org-back-to-heading)
15310 (if (looking-at org-priority-regexp)
15311 (setq current (string-to-char (match-string 2))
15312 have t)
15313 (setq current org-default-priority))
15314 (cond
15315 ((or (eq action 'set) (integerp action))
15316 (if (integerp action)
15317 (setq new action)
15318 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15319 (setq new (read-char-exclusive)))
15320 (if (and (= (upcase org-highest-priority) org-highest-priority)
15321 (= (upcase org-lowest-priority) org-lowest-priority))
15322 (setq new (upcase new)))
15323 (cond ((equal new ?\ ) (setq remove t))
15324 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15325 (error "Priority must be between `%c' and `%c'"
15326 org-highest-priority org-lowest-priority))))
15327 ((eq action 'up)
15328 (if (and (not have) (eq last-command this-command))
15329 (setq new org-lowest-priority)
15330 (setq new (if (and org-priority-start-cycle-with-default (not have))
15331 org-default-priority (1- current)))))
15332 ((eq action 'down)
15333 (if (and (not have) (eq last-command this-command))
15334 (setq new org-highest-priority)
15335 (setq new (if (and org-priority-start-cycle-with-default (not have))
15336 org-default-priority (1+ current)))))
15337 (t (error "Invalid action")))
15338 (if (or (< (upcase new) org-highest-priority)
15339 (> (upcase new) org-lowest-priority))
15340 (setq remove t))
15341 (setq news (format "%c" new))
15342 (if have
15343 (if remove
15344 (replace-match "" t t nil 1)
15345 (replace-match news t t nil 2))
15346 (if remove
15347 (error "No priority cookie found in line")
15348 (looking-at org-todo-line-regexp)
15349 (if (match-end 2)
15350 (progn
15351 (goto-char (match-end 2))
15352 (insert " [#" news "]"))
15353 (goto-char (match-beginning 3))
15354 (insert "[#" news "] ")))))
15355 (org-preserve-lc (org-set-tags nil 'align))
15356 (if remove
15357 (message "Priority removed")
15358 (message "Priority of current item set to %s" news))))
15361 (defun org-get-priority (s)
15362 "Find priority cookie and return priority."
15363 (save-match-data
15364 (if (not (string-match org-priority-regexp s))
15365 (* 1000 (- org-lowest-priority org-default-priority))
15366 (* 1000 (- org-lowest-priority
15367 (string-to-char (match-string 2 s)))))))
15369 ;;;; Tags
15371 (defun org-scan-tags (action matcher &optional todo-only)
15372 "Scan headline tags with inheritance and produce output ACTION.
15373 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15374 evaluated, testing if a given set of tags qualifies a headline for
15375 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15376 are included in the output."
15377 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15378 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15379 (org-re
15380 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15381 (props (list 'face nil
15382 'done-face 'org-done
15383 'undone-face nil
15384 'mouse-face 'highlight
15385 'org-not-done-regexp org-not-done-regexp
15386 'org-todo-regexp org-todo-regexp
15387 'keymap org-agenda-keymap
15388 'help-echo
15389 (format "mouse-2 or RET jump to org file %s"
15390 (abbreviate-file-name
15391 (or (buffer-file-name (buffer-base-buffer))
15392 (buffer-name (buffer-base-buffer)))))))
15393 (case-fold-search nil)
15394 lspos
15395 tags tags-list tags-alist (llast 0) rtn level category i txt
15396 todo marker entry priority)
15397 (save-excursion
15398 (goto-char (point-min))
15399 (when (eq action 'sparse-tree)
15400 (org-overview)
15401 (org-remove-occur-highlights))
15402 (while (re-search-forward re nil t)
15403 (catch :skip
15404 (setq todo (if (match-end 1) (match-string 2))
15405 tags (if (match-end 4) (match-string 4)))
15406 (goto-char (setq lspos (1+ (match-beginning 0))))
15407 (setq level (org-reduced-level (funcall outline-level))
15408 category (org-get-category))
15409 (setq i llast llast level)
15410 ;; remove tag lists from same and sublevels
15411 (while (>= i level)
15412 (when (setq entry (assoc i tags-alist))
15413 (setq tags-alist (delete entry tags-alist)))
15414 (setq i (1- i)))
15415 ;; add the nex tags
15416 (when tags
15417 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15418 tags-alist
15419 (cons (cons level tags) tags-alist)))
15420 ;; compile tags for current headline
15421 (setq tags-list
15422 (if org-use-tag-inheritance
15423 (apply 'append (mapcar 'cdr tags-alist))
15424 tags))
15425 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15426 (eval matcher)
15427 (or (not org-agenda-skip-archived-trees)
15428 (not (member org-archive-tag tags-list))))
15429 (and (eq action 'agenda) (org-agenda-skip))
15430 ;; list this headline
15432 (if (eq action 'sparse-tree)
15433 (progn
15434 (and org-highlight-sparse-tree-matches
15435 (org-get-heading) (match-end 0)
15436 (org-highlight-new-match
15437 (match-beginning 0) (match-beginning 1)))
15438 (org-show-context 'tags-tree))
15439 (setq txt (org-format-agenda-item
15441 (concat
15442 (if org-tags-match-list-sublevels
15443 (make-string (1- level) ?.) "")
15444 (org-get-heading))
15445 category tags-list)
15446 priority (org-get-priority txt))
15447 (goto-char lspos)
15448 (setq marker (org-agenda-new-marker))
15449 (org-add-props txt props
15450 'org-marker marker 'org-hd-marker marker 'org-category category
15451 'priority priority 'type "tagsmatch")
15452 (push txt rtn))
15453 ;; if we are to skip sublevels, jump to end of subtree
15454 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15455 (when (and (eq action 'sparse-tree)
15456 (not org-sparse-tree-open-archived-trees))
15457 (org-hide-archived-subtrees (point-min) (point-max)))
15458 (nreverse rtn)))
15460 (defvar todo-only) ;; dynamically scoped
15462 (defun org-tags-sparse-tree (&optional todo-only match)
15463 "Create a sparse tree according to tags string MATCH.
15464 MATCH can contain positive and negative selection of tags, like
15465 \"+WORK+URGENT-WITHBOSS\".
15466 If optional argument TODO_ONLY is non-nil, only select lines that are
15467 also TODO lines."
15468 (interactive "P")
15469 (org-prepare-agenda-buffers (list (current-buffer)))
15470 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15472 (defvar org-cached-props nil)
15473 (defun org-cached-entry-get (pom property)
15474 (if (or (eq t org-use-property-inheritance)
15475 (member property org-use-property-inheritance))
15476 ;; Caching is not possible, check it directly
15477 (org-entry-get pom property 'inherit)
15478 ;; Get all properties, so that we can do complicated checks easily
15479 (cdr (assoc property (or org-cached-props
15480 (setq org-cached-props
15481 (org-entry-properties pom)))))))
15483 (defun org-global-tags-completion-table (&optional files)
15484 "Return the list of all tags in all agenda buffer/files."
15485 (save-excursion
15486 (org-uniquify
15487 (delq nil
15488 (apply 'append
15489 (mapcar
15490 (lambda (file)
15491 (set-buffer (find-file-noselect file))
15492 (append (org-get-buffer-tags)
15493 (mapcar (lambda (x) (if (stringp (car-safe x))
15494 (list (car-safe x)) nil))
15495 org-tag-alist)))
15496 (if (and files (car files))
15497 files
15498 (org-agenda-files))))))))
15500 (defun org-make-tags-matcher (match)
15501 "Create the TAGS//TODO matcher form for the selection string MATCH."
15502 ;; todo-only is scoped dynamically into this function, and the function
15503 ;; may change it it the matcher asksk for it.
15504 (unless match
15505 ;; Get a new match request, with completion
15506 (let ((org-last-tags-completion-table
15507 (org-global-tags-completion-table)))
15508 (setq match (completing-read
15509 "Match: " 'org-tags-completion-function nil nil nil
15510 'org-tags-history))))
15512 ;; Parse the string and create a lisp form
15513 (let ((match0 match)
15514 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15515 minus tag mm
15516 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15517 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15518 (if (string-match "/+" match)
15519 ;; match contains also a todo-matching request
15520 (progn
15521 (setq tagsmatch (substring match 0 (match-beginning 0))
15522 todomatch (substring match (match-end 0)))
15523 (if (string-match "^!" todomatch)
15524 (setq todo-only t todomatch (substring todomatch 1)))
15525 (if (string-match "^\\s-*$" todomatch)
15526 (setq todomatch nil)))
15527 ;; only matching tags
15528 (setq tagsmatch match todomatch nil))
15530 ;; Make the tags matcher
15531 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15532 (setq tagsmatcher t)
15533 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15534 (while (setq term (pop orterms))
15535 (while (and (equal (substring term -1) "\\") orterms)
15536 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15537 (while (string-match re term)
15538 (setq minus (and (match-end 1)
15539 (equal (match-string 1 term) "-"))
15540 tag (match-string 2 term)
15541 re-p (equal (string-to-char tag) ?{)
15542 level-p (match-end 3)
15543 prop-p (match-end 4)
15544 mm (cond
15545 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15546 (level-p `(= level ,(string-to-number
15547 (match-string 3 term))))
15548 (prop-p
15549 (setq pn (match-string 4 term)
15550 pv (match-string 5 term)
15551 cat-p (equal pn "CATEGORY")
15552 re-p (equal (string-to-char pv) ?{)
15553 pv (substring pv 1 -1))
15554 (if (equal pn "CATEGORY")
15555 (setq gv '(get-text-property (point) 'org-category))
15556 (setq gv `(org-cached-entry-get nil ,pn)))
15557 (if re-p
15558 `(string-match ,pv (or ,gv ""))
15559 `(equal ,pv (or ,gv ""))))
15560 (t `(member ,(downcase tag) tags-list)))
15561 mm (if minus (list 'not mm) mm)
15562 term (substring term (match-end 0)))
15563 (push mm tagsmatcher))
15564 (push (if (> (length tagsmatcher) 1)
15565 (cons 'and tagsmatcher)
15566 (car tagsmatcher))
15567 orlist)
15568 (setq tagsmatcher nil))
15569 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15570 (setq tagsmatcher
15571 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15573 ;; Make the todo matcher
15574 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15575 (setq todomatcher t)
15576 (setq orterms (org-split-string todomatch "|") orlist nil)
15577 (while (setq term (pop orterms))
15578 (while (string-match re term)
15579 (setq minus (and (match-end 1)
15580 (equal (match-string 1 term) "-"))
15581 kwd (match-string 2 term)
15582 re-p (equal (string-to-char kwd) ?{)
15583 term (substring term (match-end 0))
15584 mm (if re-p
15585 `(string-match ,(substring kwd 1 -1) todo)
15586 (list 'equal 'todo kwd))
15587 mm (if minus (list 'not mm) mm))
15588 (push mm todomatcher))
15589 (push (if (> (length todomatcher) 1)
15590 (cons 'and todomatcher)
15591 (car todomatcher))
15592 orlist)
15593 (setq todomatcher nil))
15594 (setq todomatcher (if (> (length orlist) 1)
15595 (cons 'or orlist) (car orlist))))
15597 ;; Return the string and lisp forms of the matcher
15598 (setq matcher (if todomatcher
15599 (list 'and tagsmatcher todomatcher)
15600 tagsmatcher))
15601 (cons match0 matcher)))
15603 (defun org-match-any-p (re list)
15604 "Does re match any element of list?"
15605 (setq list (mapcar (lambda (x) (string-match re x)) list))
15606 (delq nil list))
15608 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15609 (defvar org-tags-overlay (org-make-overlay 1 1))
15610 (org-detach-overlay org-tags-overlay)
15612 (defun org-align-tags-here (to-col)
15613 ;; Assumes that this is a headline
15614 (let ((pos (point)) (col (current-column)) tags)
15615 (beginning-of-line 1)
15616 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15617 (< pos (match-beginning 2)))
15618 (progn
15619 (setq tags (match-string 2))
15620 (goto-char (match-beginning 1))
15621 (insert " ")
15622 (delete-region (point) (1+ (match-end 0)))
15623 (backward-char 1)
15624 (move-to-column
15625 (max (1+ (current-column))
15626 (1+ col)
15627 (if (> to-col 0)
15628 to-col
15629 (- (abs to-col) (length tags))))
15631 (insert tags)
15632 (move-to-column (min (current-column) col) t))
15633 (goto-char pos))))
15635 (defun org-set-tags (&optional arg just-align)
15636 "Set the tags for the current headline.
15637 With prefix ARG, realign all tags in headings in the current buffer."
15638 (interactive "P")
15639 (let* ((re (concat "^" outline-regexp))
15640 (current (org-get-tags-string))
15641 (col (current-column))
15642 (org-setting-tags t)
15643 table current-tags inherited-tags ; computed below when needed
15644 tags p0 c0 c1 rpl)
15645 (if arg
15646 (save-excursion
15647 (goto-char (point-min))
15648 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15649 (while (re-search-forward re nil t)
15650 (org-set-tags nil t)
15651 (end-of-line 1)))
15652 (message "All tags realigned to column %d" org-tags-column))
15653 (if just-align
15654 (setq tags current)
15655 ;; Get a new set of tags from the user
15656 (save-excursion
15657 (setq table (or org-tag-alist (org-get-buffer-tags))
15658 org-last-tags-completion-table table
15659 current-tags (org-split-string current ":")
15660 inherited-tags (nreverse
15661 (nthcdr (length current-tags)
15662 (nreverse (org-get-tags-at))))
15663 tags
15664 (if (or (eq t org-use-fast-tag-selection)
15665 (and org-use-fast-tag-selection
15666 (delq nil (mapcar 'cdr table))))
15667 (org-fast-tag-selection
15668 current-tags inherited-tags table
15669 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15670 (let ((org-add-colon-after-tag-completion t))
15671 (org-trim
15672 (org-without-partial-completion
15673 (completing-read "Tags: " 'org-tags-completion-function
15674 nil nil current 'org-tags-history)))))))
15675 (while (string-match "[-+&]+" tags)
15676 ;; No boolean logic, just a list
15677 (setq tags (replace-match ":" t t tags))))
15679 (if (string-match "\\`[\t ]*\\'" tags)
15680 (setq tags "")
15681 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15682 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15684 ;; Insert new tags at the correct column
15685 (beginning-of-line 1)
15686 (cond
15687 ((and (equal current "") (equal tags "")))
15688 ((re-search-forward
15689 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15690 (point-at-eol) t)
15691 (if (equal tags "")
15692 (setq rpl "")
15693 (goto-char (match-beginning 0))
15694 (setq c0 (current-column) p0 (point)
15695 c1 (max (1+ c0) (if (> org-tags-column 0)
15696 org-tags-column
15697 (- (- org-tags-column) (length tags))))
15698 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15699 (replace-match rpl t t)
15700 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15701 tags)
15702 (t (error "Tags alignment failed")))
15703 (move-to-column col)
15704 (unless just-align
15705 (run-hooks 'org-after-tags-change-hook)))))
15707 (defun org-change-tag-in-region (beg end tag off)
15708 "Add or remove TAG for each entry in the region.
15709 This works in the agenda, and also in an org-mode buffer."
15710 (interactive
15711 (list (region-beginning) (region-end)
15712 (let ((org-last-tags-completion-table
15713 (if (org-mode-p)
15714 (org-get-buffer-tags)
15715 (org-global-tags-completion-table))))
15716 (completing-read
15717 "Tag: " 'org-tags-completion-function nil nil nil
15718 'org-tags-history))
15719 (progn
15720 (message "[s]et or [r]emove? ")
15721 (equal (read-char-exclusive) ?r))))
15722 (if (fboundp 'deactivate-mark) (deactivate-mark))
15723 (let ((agendap (equal major-mode 'org-agenda-mode))
15724 l1 l2 m buf pos newhead (cnt 0))
15725 (goto-char end)
15726 (setq l2 (1- (org-current-line)))
15727 (goto-char beg)
15728 (setq l1 (org-current-line))
15729 (loop for l from l1 to l2 do
15730 (goto-line l)
15731 (setq m (get-text-property (point) 'org-hd-marker))
15732 (when (or (and (org-mode-p) (org-on-heading-p))
15733 (and agendap m))
15734 (setq buf (if agendap (marker-buffer m) (current-buffer))
15735 pos (if agendap m (point)))
15736 (with-current-buffer buf
15737 (save-excursion
15738 (save-restriction
15739 (goto-char pos)
15740 (setq cnt (1+ cnt))
15741 (org-toggle-tag tag (if off 'off 'on))
15742 (setq newhead (org-get-heading)))))
15743 (and agendap (org-agenda-change-all-lines newhead m))))
15744 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15746 (defun org-tags-completion-function (string predicate &optional flag)
15747 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15748 (confirm (lambda (x) (stringp (car x)))))
15749 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15750 (setq s1 (match-string 1 string)
15751 s2 (match-string 2 string))
15752 (setq s1 "" s2 string))
15753 (cond
15754 ((eq flag nil)
15755 ;; try completion
15756 (setq rtn (try-completion s2 ctable confirm))
15757 (if (stringp rtn)
15758 (setq rtn
15759 (concat s1 s2 (substring rtn (length s2))
15760 (if (and org-add-colon-after-tag-completion
15761 (assoc rtn ctable))
15762 ":" ""))))
15763 rtn)
15764 ((eq flag t)
15765 ;; all-completions
15766 (all-completions s2 ctable confirm)
15768 ((eq flag 'lambda)
15769 ;; exact match?
15770 (assoc s2 ctable)))
15773 (defun org-fast-tag-insert (kwd tags face &optional end)
15774 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15775 (insert (format "%-12s" (concat kwd ":"))
15776 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15777 (or end "")))
15779 (defun org-fast-tag-show-exit (flag)
15780 (save-excursion
15781 (goto-line 3)
15782 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15783 (replace-match ""))
15784 (when flag
15785 (end-of-line 1)
15786 (move-to-column (- (window-width) 19) t)
15787 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15789 (defun org-set-current-tags-overlay (current prefix)
15790 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15791 (if (featurep 'xemacs)
15792 (org-overlay-display org-tags-overlay (concat prefix s)
15793 'secondary-selection)
15794 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15795 (org-overlay-display org-tags-overlay (concat prefix s)))))
15797 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15798 "Fast tag selection with single keys.
15799 CURRENT is the current list of tags in the headline, INHERITED is the
15800 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15801 possibly with grouping information. TODO-TABLE is a similar table with
15802 TODO keywords, should these have keys assigned to them.
15803 If the keys are nil, a-z are automatically assigned.
15804 Returns the new tags string, or nil to not change the current settings."
15805 (let* ((fulltable (append table todo-table))
15806 (maxlen (apply 'max (mapcar
15807 (lambda (x)
15808 (if (stringp (car x)) (string-width (car x)) 0))
15809 fulltable)))
15810 (buf (current-buffer))
15811 (expert (eq org-fast-tag-selection-single-key 'expert))
15812 (buffer-tags nil)
15813 (fwidth (+ maxlen 3 1 3))
15814 (ncol (/ (- (window-width) 4) fwidth))
15815 (i-face 'org-done)
15816 (c-face 'org-todo)
15817 tg cnt e c char c1 c2 ntable tbl rtn
15818 ov-start ov-end ov-prefix
15819 (exit-after-next org-fast-tag-selection-single-key)
15820 (done-keywords org-done-keywords)
15821 groups ingroup)
15822 (save-excursion
15823 (beginning-of-line 1)
15824 (if (looking-at
15825 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15826 (setq ov-start (match-beginning 1)
15827 ov-end (match-end 1)
15828 ov-prefix "")
15829 (setq ov-start (1- (point-at-eol))
15830 ov-end (1+ ov-start))
15831 (skip-chars-forward "^\n\r")
15832 (setq ov-prefix
15833 (concat
15834 (buffer-substring (1- (point)) (point))
15835 (if (> (current-column) org-tags-column)
15837 (make-string (- org-tags-column (current-column)) ?\ ))))))
15838 (org-move-overlay org-tags-overlay ov-start ov-end)
15839 (save-window-excursion
15840 (if expert
15841 (set-buffer (get-buffer-create " *Org tags*"))
15842 (delete-other-windows)
15843 (split-window-vertically)
15844 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15845 (erase-buffer)
15846 (org-set-local 'org-done-keywords done-keywords)
15847 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15848 (org-fast-tag-insert "Current" current c-face "\n\n")
15849 (org-fast-tag-show-exit exit-after-next)
15850 (org-set-current-tags-overlay current ov-prefix)
15851 (setq tbl fulltable char ?a cnt 0)
15852 (while (setq e (pop tbl))
15853 (cond
15854 ((equal e '(:startgroup))
15855 (push '() groups) (setq ingroup t)
15856 (when (not (= cnt 0))
15857 (setq cnt 0)
15858 (insert "\n"))
15859 (insert "{ "))
15860 ((equal e '(:endgroup))
15861 (setq ingroup nil cnt 0)
15862 (insert "}\n"))
15864 (setq tg (car e) c2 nil)
15865 (if (cdr e)
15866 (setq c (cdr e))
15867 ;; automatically assign a character.
15868 (setq c1 (string-to-char
15869 (downcase (substring
15870 tg (if (= (string-to-char tg) ?@) 1 0)))))
15871 (if (or (rassoc c1 ntable) (rassoc c1 table))
15872 (while (or (rassoc char ntable) (rassoc char table))
15873 (setq char (1+ char)))
15874 (setq c2 c1))
15875 (setq c (or c2 char)))
15876 (if ingroup (push tg (car groups)))
15877 (setq tg (org-add-props tg nil 'face
15878 (cond
15879 ((not (assoc tg table))
15880 (org-get-todo-face tg))
15881 ((member tg current) c-face)
15882 ((member tg inherited) i-face)
15883 (t nil))))
15884 (if (and (= cnt 0) (not ingroup)) (insert " "))
15885 (insert "[" c "] " tg (make-string
15886 (- fwidth 4 (length tg)) ?\ ))
15887 (push (cons tg c) ntable)
15888 (when (= (setq cnt (1+ cnt)) ncol)
15889 (insert "\n")
15890 (if ingroup (insert " "))
15891 (setq cnt 0)))))
15892 (setq ntable (nreverse ntable))
15893 (insert "\n")
15894 (goto-char (point-min))
15895 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15896 (fit-window-to-buffer))
15897 (setq rtn
15898 (catch 'exit
15899 (while t
15900 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15901 (if groups " [!] no groups" " [!]groups")
15902 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15903 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15904 (cond
15905 ((= c ?\r) (throw 'exit t))
15906 ((= c ?!)
15907 (setq groups (not groups))
15908 (goto-char (point-min))
15909 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15910 ((= c ?\C-c)
15911 (if (not expert)
15912 (org-fast-tag-show-exit
15913 (setq exit-after-next (not exit-after-next)))
15914 (setq expert nil)
15915 (delete-other-windows)
15916 (split-window-vertically)
15917 (org-switch-to-buffer-other-window " *Org tags*")
15918 (and (fboundp 'fit-window-to-buffer)
15919 (fit-window-to-buffer))))
15920 ((or (= c ?\C-g)
15921 (and (= c ?q) (not (rassoc c ntable))))
15922 (org-detach-overlay org-tags-overlay)
15923 (setq quit-flag t))
15924 ((= c ?\ )
15925 (setq current nil)
15926 (if exit-after-next (setq exit-after-next 'now)))
15927 ((= c ?\t)
15928 (condition-case nil
15929 (setq tg (completing-read
15930 "Tag: "
15931 (or buffer-tags
15932 (with-current-buffer buf
15933 (org-get-buffer-tags)))))
15934 (quit (setq tg "")))
15935 (when (string-match "\\S-" tg)
15936 (add-to-list 'buffer-tags (list tg))
15937 (if (member tg current)
15938 (setq current (delete tg current))
15939 (push tg current)))
15940 (if exit-after-next (setq exit-after-next 'now)))
15941 ((setq e (rassoc c todo-table) tg (car e))
15942 (with-current-buffer buf
15943 (save-excursion (org-todo tg)))
15944 (if exit-after-next (setq exit-after-next 'now)))
15945 ((setq e (rassoc c ntable) tg (car e))
15946 (if (member tg current)
15947 (setq current (delete tg current))
15948 (loop for g in groups do
15949 (if (member tg g)
15950 (mapc (lambda (x)
15951 (setq current (delete x current)))
15952 g)))
15953 (push tg current))
15954 (if exit-after-next (setq exit-after-next 'now))))
15956 ;; Create a sorted list
15957 (setq current
15958 (sort current
15959 (lambda (a b)
15960 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15961 (if (eq exit-after-next 'now) (throw 'exit t))
15962 (goto-char (point-min))
15963 (beginning-of-line 2)
15964 (delete-region (point) (point-at-eol))
15965 (org-fast-tag-insert "Current" current c-face)
15966 (org-set-current-tags-overlay current ov-prefix)
15967 (while (re-search-forward
15968 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15969 (setq tg (match-string 1))
15970 (add-text-properties
15971 (match-beginning 1) (match-end 1)
15972 (list 'face
15973 (cond
15974 ((member tg current) c-face)
15975 ((member tg inherited) i-face)
15976 (t (get-text-property (match-beginning 1) 'face))))))
15977 (goto-char (point-min)))))
15978 (org-detach-overlay org-tags-overlay)
15979 (if rtn
15980 (mapconcat 'identity current ":")
15981 nil))))
15983 (defun org-get-tags-string ()
15984 "Get the TAGS string in the current headline."
15985 (unless (org-on-heading-p t)
15986 (error "Not on a heading"))
15987 (save-excursion
15988 (beginning-of-line 1)
15989 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15990 (org-match-string-no-properties 1)
15991 "")))
15993 (defun org-get-tags ()
15994 "Get the list of tags specified in the current headline."
15995 (org-split-string (org-get-tags-string) ":"))
15997 (defun org-get-buffer-tags ()
15998 "Get a table of all tags used in the buffer, for completion."
15999 (let (tags)
16000 (save-excursion
16001 (goto-char (point-min))
16002 (while (re-search-forward
16003 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16004 (when (equal (char-after (point-at-bol 0)) ?*)
16005 (mapc (lambda (x) (add-to-list 'tags x))
16006 (org-split-string (org-match-string-no-properties 1) ":")))))
16007 (mapcar 'list tags)))
16010 ;;;; Properties
16012 ;;; Setting and retrieving properties
16014 (defconst org-special-properties
16015 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16016 "TIMESTAMP" "TIMESTAMP_IA")
16017 "The special properties valid in Org-mode.
16019 These are properties that are not defined in the property drawer,
16020 but in some other way.")
16022 (defconst org-default-properties
16023 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16024 "LOCATION" "LOGGING" "COLUMNS")
16025 "Some properties that are used by Org-mode for various purposes.
16026 Being in this list makes sure that they are offered for completion.")
16028 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16029 "Regular expression matching the first line of a property drawer.")
16031 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16032 "Regular expression matching the first line of a property drawer.")
16034 (defun org-property-action ()
16035 "Do an action on properties."
16036 (interactive)
16037 (let (c)
16038 (org-at-property-p)
16039 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16040 (setq c (read-char-exclusive))
16041 (cond
16042 ((equal c ?s)
16043 (call-interactively 'org-set-property))
16044 ((equal c ?d)
16045 (call-interactively 'org-delete-property))
16046 ((equal c ?D)
16047 (call-interactively 'org-delete-property-globally))
16048 ((equal c ?c)
16049 (call-interactively 'org-compute-property-at-point))
16050 (t (error "No such property action %c" c)))))
16052 (defun org-at-property-p ()
16053 "Is the cursor in a property line?"
16054 ;; FIXME: Does not check if we are actually in the drawer.
16055 ;; FIXME: also returns true on any drawers.....
16056 ;; This is used by C-c C-c for property action.
16057 (save-excursion
16058 (beginning-of-line 1)
16059 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16061 (defmacro org-with-point-at (pom &rest body)
16062 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16063 (declare (indent 1) (debug t))
16064 `(save-excursion
16065 (if (markerp pom) (set-buffer (marker-buffer pom)))
16066 (save-excursion
16067 (goto-char (or pom (point)))
16068 ,@body)))
16070 (defun org-get-property-block (&optional beg end force)
16071 "Return the (beg . end) range of the body of the property drawer.
16072 BEG and END can be beginning and end of subtree, if not given
16073 they will be found.
16074 If the drawer does not exist and FORCE is non-nil, create the drawer."
16075 (catch 'exit
16076 (save-excursion
16077 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16078 (end (or end (progn (outline-next-heading) (point)))))
16079 (goto-char beg)
16080 (if (re-search-forward org-property-start-re end t)
16081 (setq beg (1+ (match-end 0)))
16082 (if force
16083 (save-excursion
16084 (org-insert-property-drawer)
16085 (setq end (progn (outline-next-heading) (point))))
16086 (throw 'exit nil))
16087 (goto-char beg)
16088 (if (re-search-forward org-property-start-re end t)
16089 (setq beg (1+ (match-end 0)))))
16090 (if (re-search-forward org-property-end-re end t)
16091 (setq end (match-beginning 0))
16092 (or force (throw 'exit nil))
16093 (goto-char beg)
16094 (setq end beg)
16095 (org-indent-line-function)
16096 (insert ":END:\n"))
16097 (cons beg end)))))
16099 (defun org-entry-properties (&optional pom which)
16100 "Get all properties of the entry at point-or-marker POM.
16101 This includes the TODO keyword, the tags, time strings for deadline,
16102 scheduled, and clocking, and any additional properties defined in the
16103 entry. The return value is an alist, keys may occur multiple times
16104 if the property key was used several times.
16105 POM may also be nil, in which case the current entry is used.
16106 If WHICH is nil or `all', get all properties. If WHICH is
16107 `special' or `standard', only get that subclass."
16108 (setq which (or which 'all))
16109 (org-with-point-at pom
16110 (let ((clockstr (substring org-clock-string 0 -1))
16111 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16112 beg end range props sum-props key value string clocksum)
16113 (save-excursion
16114 (when (condition-case nil (org-back-to-heading t) (error nil))
16115 (setq beg (point))
16116 (setq sum-props (get-text-property (point) 'org-summaries))
16117 (setq clocksum (get-text-property (point) :org-clock-minutes))
16118 (outline-next-heading)
16119 (setq end (point))
16120 (when (memq which '(all special))
16121 ;; Get the special properties, like TODO and tags
16122 (goto-char beg)
16123 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16124 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16125 (when (looking-at org-priority-regexp)
16126 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16127 (when (and (setq value (org-get-tags-string))
16128 (string-match "\\S-" value))
16129 (push (cons "TAGS" value) props))
16130 (when (setq value (org-get-tags-at))
16131 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16132 props))
16133 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16134 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16135 string (if (equal key clockstr)
16136 (org-no-properties
16137 (org-trim
16138 (buffer-substring
16139 (match-beginning 3) (goto-char (point-at-eol)))))
16140 (substring (org-match-string-no-properties 3) 1 -1)))
16141 (unless key
16142 (if (= (char-after (match-beginning 3)) ?\[)
16143 (setq key "TIMESTAMP_IA")
16144 (setq key "TIMESTAMP")))
16145 (when (or (equal key clockstr) (not (assoc key props)))
16146 (push (cons key string) props)))
16150 (when (memq which '(all standard))
16151 ;; Get the standard properties, like :PORP: ...
16152 (setq range (org-get-property-block beg end))
16153 (when range
16154 (goto-char (car range))
16155 (while (re-search-forward
16156 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16157 (cdr range) t)
16158 (setq key (org-match-string-no-properties 1)
16159 value (org-trim (or (org-match-string-no-properties 2) "")))
16160 (unless (member key excluded)
16161 (push (cons key (or value "")) props)))))
16162 (if clocksum
16163 (push (cons "CLOCKSUM"
16164 (org-column-number-to-string (/ (float clocksum) 60.)
16165 'add_times))
16166 props))
16167 (append sum-props (nreverse props)))))))
16169 (defun org-entry-get (pom property &optional inherit)
16170 "Get value of PROPERTY for entry at point-or-marker POM.
16171 If INHERIT is non-nil and the entry does not have the property,
16172 then also check higher levels of the hierarchy.
16173 If the property is present but empty, the return value is the empty string.
16174 If the property is not present at all, nil is returned."
16175 (org-with-point-at pom
16176 (if inherit
16177 (org-entry-get-with-inheritance property)
16178 (if (member property org-special-properties)
16179 ;; We need a special property. Use brute force, get all properties.
16180 (cdr (assoc property (org-entry-properties nil 'special)))
16181 (let ((range (org-get-property-block)))
16182 (if (and range
16183 (goto-char (car range))
16184 (re-search-forward
16185 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16186 (cdr range) t))
16187 ;; Found the property, return it.
16188 (if (match-end 1)
16189 (org-match-string-no-properties 1)
16190 "")))))))
16192 (defun org-entry-delete (pom property)
16193 "Delete the property PROPERTY from entry at point-or-marker POM."
16194 (org-with-point-at pom
16195 (if (member property org-special-properties)
16196 nil ; cannot delete these properties.
16197 (let ((range (org-get-property-block)))
16198 (if (and range
16199 (goto-char (car range))
16200 (re-search-forward
16201 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16202 (cdr range) t))
16203 (progn
16204 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16206 nil)))))
16208 ;; Multi-values properties are properties that contain multiple values
16209 ;; These values are assumed to be single words, separated by whitespace.
16210 (defun org-entry-add-to-multivalued-property (pom property value)
16211 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16212 (let* ((old (org-entry-get pom property))
16213 (values (and old (org-split-string old "[ \t]"))))
16214 (unless (member value values)
16215 (setq values (cons value values))
16216 (org-entry-put pom property
16217 (mapconcat 'identity values " ")))))
16219 (defun org-entry-remove-from-multivalued-property (pom property value)
16220 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16221 (let* ((old (org-entry-get pom property))
16222 (values (and old (org-split-string old "[ \t]"))))
16223 (when (member value values)
16224 (setq values (delete value values))
16225 (org-entry-put pom property
16226 (mapconcat 'identity values " ")))))
16228 (defun org-entry-member-in-multivalued-property (pom property value)
16229 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16230 (let* ((old (org-entry-get pom property))
16231 (values (and old (org-split-string old "[ \t]"))))
16232 (member value values)))
16234 (defvar org-entry-property-inherited-from (make-marker))
16236 (defun org-entry-get-with-inheritance (property)
16237 "Get entry property, and search higher levels if not present."
16238 (let (tmp)
16239 (save-excursion
16240 (save-restriction
16241 (widen)
16242 (catch 'ex
16243 (while t
16244 (when (setq tmp (org-entry-get nil property))
16245 (org-back-to-heading t)
16246 (move-marker org-entry-property-inherited-from (point))
16247 (throw 'ex tmp))
16248 (or (org-up-heading-safe) (throw 'ex nil)))))
16249 (or tmp (cdr (assoc property org-local-properties))
16250 (cdr (assoc property org-global-properties))))))
16252 (defun org-entry-put (pom property value)
16253 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16254 (org-with-point-at pom
16255 (org-back-to-heading t)
16256 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16257 range)
16258 (cond
16259 ((equal property "TODO")
16260 (when (and (stringp value) (string-match "\\S-" value)
16261 (not (member value org-todo-keywords-1)))
16262 (error "\"%s\" is not a valid TODO state" value))
16263 (if (or (not value)
16264 (not (string-match "\\S-" value)))
16265 (setq value 'none))
16266 (org-todo value)
16267 (org-set-tags nil 'align))
16268 ((equal property "PRIORITY")
16269 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16270 (string-to-char value) ?\ ))
16271 (org-set-tags nil 'align))
16272 ((equal property "SCHEDULED")
16273 (if (re-search-forward org-scheduled-time-regexp end t)
16274 (cond
16275 ((eq value 'earlier) (org-timestamp-change -1 'day))
16276 ((eq value 'later) (org-timestamp-change 1 'day))
16277 (t (call-interactively 'org-schedule)))
16278 (call-interactively 'org-schedule)))
16279 ((equal property "DEADLINE")
16280 (if (re-search-forward org-deadline-time-regexp end t)
16281 (cond
16282 ((eq value 'earlier) (org-timestamp-change -1 'day))
16283 ((eq value 'later) (org-timestamp-change 1 'day))
16284 (t (call-interactively 'org-deadline)))
16285 (call-interactively 'org-deadline)))
16286 ((member property org-special-properties)
16287 (error "The %s property can not yet be set with `org-entry-put'"
16288 property))
16289 (t ; a non-special property
16290 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16291 (setq range (org-get-property-block beg end 'force))
16292 (goto-char (car range))
16293 (if (re-search-forward
16294 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16295 (progn
16296 (delete-region (match-beginning 1) (match-end 1))
16297 (goto-char (match-beginning 1)))
16298 (goto-char (cdr range))
16299 (insert "\n")
16300 (backward-char 1)
16301 (org-indent-line-function)
16302 (insert ":" property ":"))
16303 (and value (insert " " value))
16304 (org-indent-line-function)))))))
16306 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16307 "Get all property keys in the current buffer.
16308 With INCLUDE-SPECIALS, also list the special properties that relect things
16309 like tags and TODO state.
16310 With INCLUDE-DEFAULTS, also include properties that has special meaning
16311 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16312 With INCLUDE-COLUMNS, also include property names given in COLUMN
16313 formats in the current buffer."
16314 (let (rtn range cfmt cols s p)
16315 (save-excursion
16316 (save-restriction
16317 (widen)
16318 (goto-char (point-min))
16319 (while (re-search-forward org-property-start-re nil t)
16320 (setq range (org-get-property-block))
16321 (goto-char (car range))
16322 (while (re-search-forward
16323 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16324 (cdr range) t)
16325 (add-to-list 'rtn (org-match-string-no-properties 1)))
16326 (outline-next-heading))))
16328 (when include-specials
16329 (setq rtn (append org-special-properties rtn)))
16331 (when include-defaults
16332 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16334 (when include-columns
16335 (save-excursion
16336 (save-restriction
16337 (widen)
16338 (goto-char (point-min))
16339 (while (re-search-forward
16340 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16341 nil t)
16342 (setq cfmt (match-string 2) s 0)
16343 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16344 cfmt s)
16345 (setq s (match-end 0)
16346 p (match-string 1 cfmt))
16347 (unless (or (equal p "ITEM")
16348 (member p org-special-properties))
16349 (add-to-list 'rtn (match-string 1 cfmt))))))))
16351 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16353 (defun org-property-values (key)
16354 "Return a list of all values of property KEY."
16355 (save-excursion
16356 (save-restriction
16357 (widen)
16358 (goto-char (point-min))
16359 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16360 values)
16361 (while (re-search-forward re nil t)
16362 (add-to-list 'values (org-trim (match-string 1))))
16363 (delete "" values)))))
16365 (defun org-insert-property-drawer ()
16366 "Insert a property drawer into the current entry."
16367 (interactive)
16368 (org-back-to-heading t)
16369 (looking-at outline-regexp)
16370 (let ((indent (- (match-end 0)(match-beginning 0)))
16371 (beg (point))
16372 (re (concat "^[ \t]*" org-keyword-time-regexp))
16373 end hiddenp)
16374 (outline-next-heading)
16375 (setq end (point))
16376 (goto-char beg)
16377 (while (re-search-forward re end t))
16378 (setq hiddenp (org-invisible-p))
16379 (end-of-line 1)
16380 (and (equal (char-after) ?\n) (forward-char 1))
16381 (org-skip-over-state-notes)
16382 (skip-chars-backward " \t\n\r")
16383 (if (eq (char-before) ?*) (forward-char 1))
16384 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16385 (beginning-of-line 0)
16386 (indent-to-column indent)
16387 (beginning-of-line 2)
16388 (indent-to-column indent)
16389 (beginning-of-line 0)
16390 (if hiddenp
16391 (save-excursion
16392 (org-back-to-heading t)
16393 (hide-entry))
16394 (org-flag-drawer t))))
16396 (defun org-set-property (property value)
16397 "In the current entry, set PROPERTY to VALUE.
16398 When called interactively, this will prompt for a property name, offering
16399 completion on existing and default properties. And then it will prompt
16400 for a value, offering competion either on allowed values (via an inherited
16401 xxx_ALL property) or on existing values in other instances of this property
16402 in the current file."
16403 (interactive
16404 (let* ((prop (completing-read
16405 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16406 (cur (org-entry-get nil prop))
16407 (allowed (org-property-get-allowed-values nil prop 'table))
16408 (existing (mapcar 'list (org-property-values prop)))
16409 (val (if allowed
16410 (completing-read "Value: " allowed nil 'req-match)
16411 (completing-read
16412 (concat "Value" (if (and cur (string-match "\\S-" cur))
16413 (concat "[" cur "]") "")
16414 ": ")
16415 existing nil nil "" nil cur))))
16416 (list prop (if (equal val "") cur val))))
16417 (unless (equal (org-entry-get nil property) value)
16418 (org-entry-put nil property value)))
16420 (defun org-delete-property (property)
16421 "In the current entry, delete PROPERTY."
16422 (interactive
16423 (let* ((prop (completing-read
16424 "Property: " (org-entry-properties nil 'standard))))
16425 (list prop)))
16426 (message "Property %s %s" property
16427 (if (org-entry-delete nil property)
16428 "deleted"
16429 "was not present in the entry")))
16431 (defun org-delete-property-globally (property)
16432 "Remove PROPERTY globally, from all entries."
16433 (interactive
16434 (let* ((prop (completing-read
16435 "Globally remove property: "
16436 (mapcar 'list (org-buffer-property-keys)))))
16437 (list prop)))
16438 (save-excursion
16439 (save-restriction
16440 (widen)
16441 (goto-char (point-min))
16442 (let ((cnt 0))
16443 (while (re-search-forward
16444 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16445 nil t)
16446 (setq cnt (1+ cnt))
16447 (replace-match ""))
16448 (message "Property \"%s\" removed from %d entries" property cnt)))))
16450 (defvar org-columns-current-fmt-compiled) ; defined below
16452 (defun org-compute-property-at-point ()
16453 "Compute the property at point.
16454 This looks for an enclosing column format, extracts the operator and
16455 then applies it to the proerty in the column format's scope."
16456 (interactive)
16457 (unless (org-at-property-p)
16458 (error "Not at a property"))
16459 (let ((prop (org-match-string-no-properties 2)))
16460 (org-columns-get-format-and-top-level)
16461 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16462 (error "No operator defined for property %s" prop))
16463 (org-columns-compute prop)))
16465 (defun org-property-get-allowed-values (pom property &optional table)
16466 "Get allowed values for the property PROPERTY.
16467 When TABLE is non-nil, return an alist that can directly be used for
16468 completion."
16469 (let (vals)
16470 (cond
16471 ((equal property "TODO")
16472 (setq vals (org-with-point-at pom
16473 (append org-todo-keywords-1 '("")))))
16474 ((equal property "PRIORITY")
16475 (let ((n org-lowest-priority))
16476 (while (>= n org-highest-priority)
16477 (push (char-to-string n) vals)
16478 (setq n (1- n)))))
16479 ((member property org-special-properties))
16481 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16483 (when (and vals (string-match "\\S-" vals))
16484 (setq vals (car (read-from-string (concat "(" vals ")"))))
16485 (setq vals (mapcar (lambda (x)
16486 (cond ((stringp x) x)
16487 ((numberp x) (number-to-string x))
16488 ((symbolp x) (symbol-name x))
16489 (t "???")))
16490 vals)))))
16491 (if table (mapcar 'list vals) vals)))
16493 (defun org-property-previous-allowed-value (&optional previous)
16494 "Switch to the next allowed value for this property."
16495 (interactive)
16496 (org-property-next-allowed-value t))
16498 (defun org-property-next-allowed-value (&optional previous)
16499 "Switch to the next allowed value for this property."
16500 (interactive)
16501 (unless (org-at-property-p)
16502 (error "Not at a property"))
16503 (let* ((key (match-string 2))
16504 (value (match-string 3))
16505 (allowed (or (org-property-get-allowed-values (point) key)
16506 (and (member value '("[ ]" "[-]" "[X]"))
16507 '("[ ]" "[X]"))))
16508 nval)
16509 (unless allowed
16510 (error "Allowed values for this property have not been defined"))
16511 (if previous (setq allowed (reverse allowed)))
16512 (if (member value allowed)
16513 (setq nval (car (cdr (member value allowed)))))
16514 (setq nval (or nval (car allowed)))
16515 (if (equal nval value)
16516 (error "Only one allowed value for this property"))
16517 (org-at-property-p)
16518 (replace-match (concat " :" key ": " nval) t t)
16519 (org-indent-line-function)
16520 (beginning-of-line 1)
16521 (skip-chars-forward " \t")))
16523 (defun org-find-entry-with-id (ident)
16524 "Locate the entry that contains the ID property with exact value IDENT.
16525 IDENT can be a string, a symbol or a number, this function will search for
16526 the string representation of it.
16527 Return the position where this entry starts, or nil if there is no such entry."
16528 (let ((id (cond
16529 ((stringp ident) ident)
16530 ((symbol-name ident) (symbol-name ident))
16531 ((numberp ident) (number-to-string ident))
16532 (t (error "IDENT %s must be a string, symbol or number" ident))))
16533 (case-fold-search nil))
16534 (save-excursion
16535 (save-restriction
16536 (widen)
16537 (goto-char (point-min))
16538 (when (re-search-forward
16539 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16540 nil t)
16541 (org-back-to-heading)
16542 (point))))))
16544 ;;; Column View
16546 (defvar org-columns-overlays nil
16547 "Holds the list of current column overlays.")
16549 (defvar org-columns-current-fmt nil
16550 "Local variable, holds the currently active column format.")
16551 (defvar org-columns-current-fmt-compiled nil
16552 "Local variable, holds the currently active column format.
16553 This is the compiled version of the format.")
16554 (defvar org-columns-current-widths nil
16555 "Loval variable, holds the currently widths of fields.")
16556 (defvar org-columns-current-maxwidths nil
16557 "Loval variable, holds the currently active maximum column widths.")
16558 (defvar org-columns-begin-marker (make-marker)
16559 "Points to the position where last a column creation command was called.")
16560 (defvar org-columns-top-level-marker (make-marker)
16561 "Points to the position where current columns region starts.")
16563 (defvar org-columns-map (make-sparse-keymap)
16564 "The keymap valid in column display.")
16566 (defun org-columns-content ()
16567 "Switch to contents view while in columns view."
16568 (interactive)
16569 (org-overview)
16570 (org-content))
16572 (org-defkey org-columns-map "c" 'org-columns-content)
16573 (org-defkey org-columns-map "o" 'org-overview)
16574 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16575 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16576 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16577 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16578 (org-defkey org-columns-map "v" 'org-columns-show-value)
16579 (org-defkey org-columns-map "q" 'org-columns-quit)
16580 (org-defkey org-columns-map "r" 'org-columns-redo)
16581 (org-defkey org-columns-map "g" 'org-columns-redo)
16582 (org-defkey org-columns-map [left] 'backward-char)
16583 (org-defkey org-columns-map "\M-b" 'backward-char)
16584 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16585 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16586 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16587 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16588 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16589 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16590 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16591 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16592 (org-defkey org-columns-map "<" 'org-columns-narrow)
16593 (org-defkey org-columns-map ">" 'org-columns-widen)
16594 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16595 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16596 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16597 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16599 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16600 '("Column"
16601 ["Edit property" org-columns-edit-value t]
16602 ["Next allowed value" org-columns-next-allowed-value t]
16603 ["Previous allowed value" org-columns-previous-allowed-value t]
16604 ["Show full value" org-columns-show-value t]
16605 ["Edit allowed values" org-columns-edit-allowed t]
16606 "--"
16607 ["Edit column attributes" org-columns-edit-attributes t]
16608 ["Increase column width" org-columns-widen t]
16609 ["Decrease column width" org-columns-narrow t]
16610 "--"
16611 ["Move column right" org-columns-move-right t]
16612 ["Move column left" org-columns-move-left t]
16613 ["Add column" org-columns-new t]
16614 ["Delete column" org-columns-delete t]
16615 "--"
16616 ["CONTENTS" org-columns-content t]
16617 ["OVERVIEW" org-overview t]
16618 ["Refresh columns display" org-columns-redo t]
16619 "--"
16620 ["Open link" org-columns-open-link t]
16621 "--"
16622 ["Quit" org-columns-quit t]))
16624 (defun org-columns-new-overlay (beg end &optional string face)
16625 "Create a new column overlay and add it to the list."
16626 (let ((ov (org-make-overlay beg end)))
16627 (org-overlay-put ov 'face (or face 'secondary-selection))
16628 (org-overlay-display ov string face)
16629 (push ov org-columns-overlays)
16630 ov))
16632 (defun org-columns-display-here (&optional props)
16633 "Overlay the current line with column display."
16634 (interactive)
16635 (let* ((fmt org-columns-current-fmt-compiled)
16636 (beg (point-at-bol))
16637 (level-face (save-excursion
16638 (beginning-of-line 1)
16639 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16640 (org-get-level-face 2))))
16641 (color (list :foreground
16642 (face-attribute (or level-face 'default) :foreground)))
16643 props pom property ass width f string ov column val modval)
16644 ;; Check if the entry is in another buffer.
16645 (unless props
16646 (if (eq major-mode 'org-agenda-mode)
16647 (setq pom (or (get-text-property (point) 'org-hd-marker)
16648 (get-text-property (point) 'org-marker))
16649 props (if pom (org-entry-properties pom) nil))
16650 (setq props (org-entry-properties nil))))
16651 ;; Walk the format
16652 (while (setq column (pop fmt))
16653 (setq property (car column)
16654 ass (if (equal property "ITEM")
16655 (cons "ITEM"
16656 (save-match-data
16657 (org-no-properties
16658 (org-remove-tabs
16659 (buffer-substring-no-properties
16660 (point-at-bol) (point-at-eol))))))
16661 (assoc property props))
16662 width (or (cdr (assoc property org-columns-current-maxwidths))
16663 (nth 2 column)
16664 (length property))
16665 f (format "%%-%d.%ds | " width width)
16666 val (or (cdr ass) "")
16667 modval (if (equal property "ITEM")
16668 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16669 string (format f (or modval val)))
16670 ;; Create the overlay
16671 (org-unmodified
16672 (setq ov (org-columns-new-overlay
16673 beg (setq beg (1+ beg)) string
16674 (list color 'org-column)))
16675 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16676 (org-overlay-put ov 'keymap org-columns-map)
16677 (org-overlay-put ov 'org-columns-key property)
16678 (org-overlay-put ov 'org-columns-value (cdr ass))
16679 (org-overlay-put ov 'org-columns-value-modified modval)
16680 (org-overlay-put ov 'org-columns-pom pom)
16681 (org-overlay-put ov 'org-columns-format f))
16682 (if (or (not (char-after beg))
16683 (equal (char-after beg) ?\n))
16684 (let ((inhibit-read-only t))
16685 (save-excursion
16686 (goto-char beg)
16687 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16688 ;; Make the rest of the line disappear.
16689 (org-unmodified
16690 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16691 (org-overlay-put ov 'invisible t)
16692 (org-overlay-put ov 'keymap org-columns-map)
16693 (org-overlay-put ov 'intangible t)
16694 (push ov org-columns-overlays)
16695 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16696 (org-overlay-put ov 'keymap org-columns-map)
16697 (push ov org-columns-overlays)
16698 (let ((inhibit-read-only t))
16699 (put-text-property (max (point-min) (1- (point-at-bol)))
16700 (min (point-max) (1+ (point-at-eol)))
16701 'read-only "Type `e' to edit property")))))
16703 (defvar org-previous-header-line-format nil
16704 "The header line format before column view was turned on.")
16705 (defvar org-columns-inhibit-recalculation nil
16706 "Inhibit recomputing of columns on column view startup.")
16709 (defvar header-line-format)
16710 (defun org-columns-display-here-title ()
16711 "Overlay the newline before the current line with the table title."
16712 (interactive)
16713 (let ((fmt org-columns-current-fmt-compiled)
16714 string (title "")
16715 property width f column str widths)
16716 (while (setq column (pop fmt))
16717 (setq property (car column)
16718 str (or (nth 1 column) property)
16719 width (or (cdr (assoc property org-columns-current-maxwidths))
16720 (nth 2 column)
16721 (length str))
16722 widths (push width widths)
16723 f (format "%%-%d.%ds | " width width)
16724 string (format f str)
16725 title (concat title string)))
16726 (setq title (concat
16727 (org-add-props " " nil 'display '(space :align-to 0))
16728 (org-add-props title nil 'face '(:weight bold :underline t))))
16729 (org-set-local 'org-previous-header-line-format header-line-format)
16730 (org-set-local 'org-columns-current-widths (nreverse widths))
16731 (setq header-line-format title)))
16733 (defun org-columns-remove-overlays ()
16734 "Remove all currently active column overlays."
16735 (interactive)
16736 (when (marker-buffer org-columns-begin-marker)
16737 (with-current-buffer (marker-buffer org-columns-begin-marker)
16738 (when (local-variable-p 'org-previous-header-line-format)
16739 (setq header-line-format org-previous-header-line-format)
16740 (kill-local-variable 'org-previous-header-line-format))
16741 (move-marker org-columns-begin-marker nil)
16742 (move-marker org-columns-top-level-marker nil)
16743 (org-unmodified
16744 (mapc 'org-delete-overlay org-columns-overlays)
16745 (setq org-columns-overlays nil)
16746 (let ((inhibit-read-only t))
16747 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16749 (defun org-columns-cleanup-item (item fmt)
16750 "Remove from ITEM what is a column in the format FMT."
16751 (if (not org-complex-heading-regexp)
16752 item
16753 (when (string-match org-complex-heading-regexp item)
16754 (concat
16755 (org-add-props (concat (match-string 1 item) " ") nil
16756 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16757 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16758 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16759 " " (match-string 4 item)
16760 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16762 (defun org-columns-show-value ()
16763 "Show the full value of the property."
16764 (interactive)
16765 (let ((value (get-char-property (point) 'org-columns-value)))
16766 (message "Value is: %s" (or value ""))))
16768 (defun org-columns-quit ()
16769 "Remove the column overlays and in this way exit column editing."
16770 (interactive)
16771 (org-unmodified
16772 (org-columns-remove-overlays)
16773 (let ((inhibit-read-only t))
16774 (remove-text-properties (point-min) (point-max) '(read-only t))))
16775 (when (eq major-mode 'org-agenda-mode)
16776 (message
16777 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16779 (defun org-columns-check-computed ()
16780 "Check if this column value is computed.
16781 If yes, throw an error indicating that changing it does not make sense."
16782 (let ((val (get-char-property (point) 'org-columns-value)))
16783 (when (and (stringp val)
16784 (get-char-property 0 'org-computed val))
16785 (error "This value is computed from the entry's children"))))
16787 (defun org-columns-todo (&optional arg)
16788 "Change the TODO state during column view."
16789 (interactive "P")
16790 (org-columns-edit-value "TODO"))
16792 (defun org-columns-set-tags-or-toggle (&optional arg)
16793 "Toggle checkbox at point, or set tags for current headline."
16794 (interactive "P")
16795 (if (string-match "\\`\\[[ xX-]\\]\\'"
16796 (get-char-property (point) 'org-columns-value))
16797 (org-columns-next-allowed-value)
16798 (org-columns-edit-value "TAGS")))
16800 (defun org-columns-edit-value (&optional key)
16801 "Edit the value of the property at point in column view.
16802 Where possible, use the standard interface for changing this line."
16803 (interactive)
16804 (org-columns-check-computed)
16805 (let* ((external-key key)
16806 (col (current-column))
16807 (key (or key (get-char-property (point) 'org-columns-key)))
16808 (value (get-char-property (point) 'org-columns-value))
16809 (bol (point-at-bol)) (eol (point-at-eol))
16810 (pom (or (get-text-property bol 'org-hd-marker)
16811 (point))) ; keep despite of compiler waring
16812 (line-overlays
16813 (delq nil (mapcar (lambda (x)
16814 (and (eq (overlay-buffer x) (current-buffer))
16815 (>= (overlay-start x) bol)
16816 (<= (overlay-start x) eol)
16818 org-columns-overlays)))
16819 nval eval allowed)
16820 (cond
16821 ((equal key "CLOCKSUM")
16822 (error "This special column cannot be edited"))
16823 ((equal key "ITEM")
16824 (setq eval '(org-with-point-at pom
16825 (org-edit-headline))))
16826 ((equal key "TODO")
16827 (setq eval '(org-with-point-at pom
16828 (let ((current-prefix-arg
16829 (if external-key current-prefix-arg '(4))))
16830 (call-interactively 'org-todo)))))
16831 ((equal key "PRIORITY")
16832 (setq eval '(org-with-point-at pom
16833 (call-interactively 'org-priority))))
16834 ((equal key "TAGS")
16835 (setq eval '(org-with-point-at pom
16836 (let ((org-fast-tag-selection-single-key
16837 (if (eq org-fast-tag-selection-single-key 'expert)
16838 t org-fast-tag-selection-single-key)))
16839 (call-interactively 'org-set-tags)))))
16840 ((equal key "DEADLINE")
16841 (setq eval '(org-with-point-at pom
16842 (call-interactively 'org-deadline))))
16843 ((equal key "SCHEDULED")
16844 (setq eval '(org-with-point-at pom
16845 (call-interactively 'org-schedule))))
16847 (setq allowed (org-property-get-allowed-values pom key 'table))
16848 (if allowed
16849 (setq nval (completing-read "Value: " allowed nil t))
16850 (setq nval (read-string "Edit: " value)))
16851 (setq nval (org-trim nval))
16852 (when (not (equal nval value))
16853 (setq eval '(org-entry-put pom key nval)))))
16854 (when eval
16855 (let ((inhibit-read-only t))
16856 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16857 (unwind-protect
16858 (progn
16859 (setq org-columns-overlays
16860 (org-delete-all line-overlays org-columns-overlays))
16861 (mapc 'org-delete-overlay line-overlays)
16862 (org-columns-eval eval))
16863 (org-columns-display-here))))
16864 (move-to-column col)
16865 (if (and (org-mode-p)
16866 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16867 (org-columns-update key))))
16869 (defun org-edit-headline () ; FIXME: this is not columns specific
16870 "Edit the current headline, the part without TODO keyword, TAGS."
16871 (org-back-to-heading)
16872 (when (looking-at org-todo-line-regexp)
16873 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16874 (txt (match-string 3))
16875 (post "")
16876 txt2)
16877 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16878 (setq post (match-string 0 txt)
16879 txt (substring txt 0 (match-beginning 0))))
16880 (setq txt2 (read-string "Edit: " txt))
16881 (when (not (equal txt txt2))
16882 (beginning-of-line 1)
16883 (insert pre txt2 post)
16884 (delete-region (point) (point-at-eol))
16885 (org-set-tags nil t)))))
16887 (defun org-columns-edit-allowed ()
16888 "Edit the list of allowed values for the current property."
16889 (interactive)
16890 (let* ((key (get-char-property (point) 'org-columns-key))
16891 (key1 (concat key "_ALL"))
16892 (allowed (org-entry-get (point) key1 t))
16893 nval)
16894 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16895 (setq nval (read-string "Allowed: " allowed))
16896 (org-entry-put
16897 (cond ((marker-position org-entry-property-inherited-from)
16898 org-entry-property-inherited-from)
16899 ((marker-position org-columns-top-level-marker)
16900 org-columns-top-level-marker))
16901 key1 nval)))
16903 (defmacro org-no-warnings (&rest body)
16904 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16906 (defun org-columns-eval (form)
16907 (let (hidep)
16908 (save-excursion
16909 (beginning-of-line 1)
16910 ;; `next-line' is needed here, because it skips invisible line.
16911 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16912 (setq hidep (org-on-heading-p 1)))
16913 (eval form)
16914 (and hidep (hide-entry))))
16916 (defun org-columns-previous-allowed-value ()
16917 "Switch to the previous allowed value for this column."
16918 (interactive)
16919 (org-columns-next-allowed-value t))
16921 (defun org-columns-next-allowed-value (&optional previous)
16922 "Switch to the next allowed value for this column."
16923 (interactive)
16924 (org-columns-check-computed)
16925 (let* ((col (current-column))
16926 (key (get-char-property (point) 'org-columns-key))
16927 (value (get-char-property (point) 'org-columns-value))
16928 (bol (point-at-bol)) (eol (point-at-eol))
16929 (pom (or (get-text-property bol 'org-hd-marker)
16930 (point))) ; keep despite of compiler waring
16931 (line-overlays
16932 (delq nil (mapcar (lambda (x)
16933 (and (eq (overlay-buffer x) (current-buffer))
16934 (>= (overlay-start x) bol)
16935 (<= (overlay-start x) eol)
16937 org-columns-overlays)))
16938 (allowed (or (org-property-get-allowed-values pom key)
16939 (and (memq
16940 (nth 4 (assoc key org-columns-current-fmt-compiled))
16941 '(checkbox checkbox-n-of-m checkbox-percent))
16942 '("[ ]" "[X]"))))
16943 nval)
16944 (when (equal key "ITEM")
16945 (error "Cannot edit item headline from here"))
16946 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16947 (error "Allowed values for this property have not been defined"))
16948 (if (member key '("SCHEDULED" "DEADLINE"))
16949 (setq nval (if previous 'earlier 'later))
16950 (if previous (setq allowed (reverse allowed)))
16951 (if (member value allowed)
16952 (setq nval (car (cdr (member value allowed)))))
16953 (setq nval (or nval (car allowed)))
16954 (if (equal nval value)
16955 (error "Only one allowed value for this property")))
16956 (let ((inhibit-read-only t))
16957 (remove-text-properties (1- bol) eol '(read-only t))
16958 (unwind-protect
16959 (progn
16960 (setq org-columns-overlays
16961 (org-delete-all line-overlays org-columns-overlays))
16962 (mapc 'org-delete-overlay line-overlays)
16963 (org-columns-eval '(org-entry-put pom key nval)))
16964 (org-columns-display-here)))
16965 (move-to-column col)
16966 (if (and (org-mode-p)
16967 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16968 (org-columns-update key))))
16970 (defun org-verify-version (task)
16971 (cond
16972 ((eq task 'columns)
16973 (if (or (featurep 'xemacs)
16974 (< emacs-major-version 22))
16975 (error "Emacs 22 is required for the columns feature")))))
16977 (defun org-columns-open-link (&optional arg)
16978 (interactive "P")
16979 (let ((value (get-char-property (point) 'org-columns-value)))
16980 (org-open-link-from-string value arg)))
16982 (defun org-open-link-from-string (s &optional arg)
16983 "Open a link in the string S, as if it was in Org-mode."
16984 (interactive)
16985 (with-temp-buffer
16986 (let ((org-inhibit-startup t))
16987 (org-mode)
16988 (insert s)
16989 (goto-char (point-min))
16990 (org-open-at-point arg))))
16992 (defun org-columns-get-format-and-top-level ()
16993 (let (fmt)
16994 (when (condition-case nil (org-back-to-heading) (error nil))
16995 (move-marker org-entry-property-inherited-from nil)
16996 (setq fmt (org-entry-get nil "COLUMNS" t)))
16997 (setq fmt (or fmt org-columns-default-format))
16998 (org-set-local 'org-columns-current-fmt fmt)
16999 (org-columns-compile-format fmt)
17000 (if (marker-position org-entry-property-inherited-from)
17001 (move-marker org-columns-top-level-marker
17002 org-entry-property-inherited-from)
17003 (move-marker org-columns-top-level-marker (point)))
17004 fmt))
17006 (defun org-columns ()
17007 "Turn on column view on an org-mode file."
17008 (interactive)
17009 (org-verify-version 'columns)
17010 (org-columns-remove-overlays)
17011 (move-marker org-columns-begin-marker (point))
17012 (let (beg end fmt cache maxwidths)
17013 (setq fmt (org-columns-get-format-and-top-level))
17014 (save-excursion
17015 (goto-char org-columns-top-level-marker)
17016 (setq beg (point))
17017 (unless org-columns-inhibit-recalculation
17018 (org-columns-compute-all))
17019 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17020 (point-max)))
17021 ;; Get and cache the properties
17022 (goto-char beg)
17023 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17024 (save-excursion
17025 (save-restriction
17026 (narrow-to-region beg end)
17027 (org-clock-sum))))
17028 (while (re-search-forward (concat "^" outline-regexp) end t)
17029 (push (cons (org-current-line) (org-entry-properties)) cache))
17030 (when cache
17031 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17032 (org-set-local 'org-columns-current-maxwidths maxwidths)
17033 (org-columns-display-here-title)
17034 (mapc (lambda (x)
17035 (goto-line (car x))
17036 (org-columns-display-here (cdr x)))
17037 cache)))))
17039 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17040 "Insert a new column, to the leeft o the current column."
17041 (interactive)
17042 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17043 cell)
17044 (setq prop (completing-read
17045 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17046 nil nil prop))
17047 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17048 (setq width (read-string "Column width: " (if width (number-to-string width))))
17049 (if (string-match "\\S-" width)
17050 (setq width (string-to-number width))
17051 (setq width nil))
17052 (setq fmt (completing-read "Summary [none]: "
17053 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17054 nil t))
17055 (if (string-match "\\S-" fmt)
17056 (setq fmt (intern fmt))
17057 (setq fmt nil))
17058 (if (eq fmt 'none) (setq fmt nil))
17059 (if editp
17060 (progn
17061 (setcar editp prop)
17062 (setcdr editp (list title width nil fmt)))
17063 (setq cell (nthcdr (1- (current-column))
17064 org-columns-current-fmt-compiled))
17065 (setcdr cell (cons (list prop title width nil fmt)
17066 (cdr cell))))
17067 (org-columns-store-format)
17068 (org-columns-redo)))
17070 (defun org-columns-delete ()
17071 "Delete the column at point from columns view."
17072 (interactive)
17073 (let* ((n (current-column))
17074 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17075 (when (y-or-n-p
17076 (format "Are you sure you want to remove column \"%s\"? " title))
17077 (setq org-columns-current-fmt-compiled
17078 (delq (nth n org-columns-current-fmt-compiled)
17079 org-columns-current-fmt-compiled))
17080 (org-columns-store-format)
17081 (org-columns-redo)
17082 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17083 (backward-char 1)))))
17085 (defun org-columns-edit-attributes ()
17086 "Edit the attributes of the current column."
17087 (interactive)
17088 (let* ((n (current-column))
17089 (info (nth n org-columns-current-fmt-compiled)))
17090 (apply 'org-columns-new info)))
17092 (defun org-columns-widen (arg)
17093 "Make the column wider by ARG characters."
17094 (interactive "p")
17095 (let* ((n (current-column))
17096 (entry (nth n org-columns-current-fmt-compiled))
17097 (width (or (nth 2 entry)
17098 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17099 (setq width (max 1 (+ width arg)))
17100 (setcar (nthcdr 2 entry) width)
17101 (org-columns-store-format)
17102 (org-columns-redo)))
17104 (defun org-columns-narrow (arg)
17105 "Make the column nrrower by ARG characters."
17106 (interactive "p")
17107 (org-columns-widen (- arg)))
17109 (defun org-columns-move-right ()
17110 "Swap this column with the one to the right."
17111 (interactive)
17112 (let* ((n (current-column))
17113 (cell (nthcdr n org-columns-current-fmt-compiled))
17115 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17116 (error "Cannot shift this column further to the right"))
17117 (setq e (car cell))
17118 (setcar cell (car (cdr cell)))
17119 (setcdr cell (cons e (cdr (cdr cell))))
17120 (org-columns-store-format)
17121 (org-columns-redo)
17122 (forward-char 1)))
17124 (defun org-columns-move-left ()
17125 "Swap this column with the one to the left."
17126 (interactive)
17127 (let* ((n (current-column)))
17128 (when (= n 0)
17129 (error "Cannot shift this column further to the left"))
17130 (backward-char 1)
17131 (org-columns-move-right)
17132 (backward-char 1)))
17134 (defun org-columns-store-format ()
17135 "Store the text version of the current columns format in appropriate place.
17136 This is either in the COLUMNS property of the node starting the current column
17137 display, or in the #+COLUMNS line of the current buffer."
17138 (let (fmt (cnt 0))
17139 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17140 (org-set-local 'org-columns-current-fmt fmt)
17141 (if (marker-position org-columns-top-level-marker)
17142 (save-excursion
17143 (goto-char org-columns-top-level-marker)
17144 (if (and (org-at-heading-p)
17145 (org-entry-get nil "COLUMNS"))
17146 (org-entry-put nil "COLUMNS" fmt)
17147 (goto-char (point-min))
17148 ;; Overwrite all #+COLUMNS lines....
17149 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17150 (setq cnt (1+ cnt))
17151 (replace-match (concat "#+COLUMNS: " fmt) t t))
17152 (unless (> cnt 0)
17153 (goto-char (point-min))
17154 (or (org-on-heading-p t) (outline-next-heading))
17155 (let ((inhibit-read-only t))
17156 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17157 (org-set-local 'org-columns-default-format fmt))))))
17159 (defvar org-overriding-columns-format nil
17160 "When set, overrides any other definition.")
17161 (defvar org-agenda-view-columns-initially nil
17162 "When set, switch to columns view immediately after creating the agenda.")
17164 (defun org-agenda-columns ()
17165 "Turn on column view in the agenda."
17166 (interactive)
17167 (org-verify-version 'columns)
17168 (org-columns-remove-overlays)
17169 (move-marker org-columns-begin-marker (point))
17170 (let (fmt cache maxwidths m)
17171 (cond
17172 ((and (local-variable-p 'org-overriding-columns-format)
17173 org-overriding-columns-format)
17174 (setq fmt org-overriding-columns-format))
17175 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17176 (setq fmt (org-entry-get m "COLUMNS" t)))
17177 ((and (boundp 'org-columns-current-fmt)
17178 (local-variable-p 'org-columns-current-fmt)
17179 org-columns-current-fmt)
17180 (setq fmt org-columns-current-fmt))
17181 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17182 (setq m (get-text-property m 'org-hd-marker))
17183 (setq fmt (org-entry-get m "COLUMNS" t))))
17184 (setq fmt (or fmt org-columns-default-format))
17185 (org-set-local 'org-columns-current-fmt fmt)
17186 (org-columns-compile-format fmt)
17187 (save-excursion
17188 ;; Get and cache the properties
17189 (goto-char (point-min))
17190 (while (not (eobp))
17191 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17192 (get-text-property (point) 'org-marker)))
17193 (push (cons (org-current-line) (org-entry-properties m)) cache))
17194 (beginning-of-line 2))
17195 (when cache
17196 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17197 (org-set-local 'org-columns-current-maxwidths maxwidths)
17198 (org-columns-display-here-title)
17199 (mapc (lambda (x)
17200 (goto-line (car x))
17201 (org-columns-display-here (cdr x)))
17202 cache)))))
17204 (defun org-columns-get-autowidth-alist (s cache)
17205 "Derive the maximum column widths from the format and the cache."
17206 (let ((start 0) rtn)
17207 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17208 (push (cons (match-string 1 s) 1) rtn)
17209 (setq start (match-end 0)))
17210 (mapc (lambda (x)
17211 (setcdr x (apply 'max
17212 (mapcar
17213 (lambda (y)
17214 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17215 cache))))
17216 rtn)
17217 rtn))
17219 (defun org-columns-compute-all ()
17220 "Compute all columns that have operators defined."
17221 (org-unmodified
17222 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17223 (let ((columns org-columns-current-fmt-compiled) col)
17224 (while (setq col (pop columns))
17225 (when (nth 3 col)
17226 (save-excursion
17227 (org-columns-compute (car col)))))))
17229 (defun org-columns-update (property)
17230 "Recompute PROPERTY, and update the columns display for it."
17231 (org-columns-compute property)
17232 (let (fmt val pos)
17233 (save-excursion
17234 (mapc (lambda (ov)
17235 (when (equal (org-overlay-get ov 'org-columns-key) property)
17236 (setq pos (org-overlay-start ov))
17237 (goto-char pos)
17238 (when (setq val (cdr (assoc property
17239 (get-text-property
17240 (point-at-bol) 'org-summaries))))
17241 (setq fmt (org-overlay-get ov 'org-columns-format))
17242 (org-overlay-put ov 'org-columns-value val)
17243 (org-overlay-put ov 'display (format fmt val)))))
17244 org-columns-overlays))))
17246 (defun org-columns-compute (property)
17247 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17248 (interactive)
17249 (let* ((re (concat "^" outline-regexp))
17250 (lmax 30) ; Does anyone use deeper levels???
17251 (lsum (make-vector lmax 0))
17252 (lflag (make-vector lmax nil))
17253 (level 0)
17254 (ass (assoc property org-columns-current-fmt-compiled))
17255 (format (nth 4 ass))
17256 (printf (nth 5 ass))
17257 (beg org-columns-top-level-marker)
17258 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17259 (save-excursion
17260 ;; Find the region to compute
17261 (goto-char beg)
17262 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17263 (goto-char end)
17264 ;; Walk the tree from the back and do the computations
17265 (while (re-search-backward re beg t)
17266 (setq sumpos (match-beginning 0)
17267 last-level level
17268 level (org-outline-level)
17269 val (org-entry-get nil property)
17270 valflag (and val (string-match "\\S-" val)))
17271 (cond
17272 ((< level last-level)
17273 ;; put the sum of lower levels here as a property
17274 (setq sum (aref lsum last-level) ; current sum
17275 flag (aref lflag last-level) ; any valid entries from children?
17276 str (org-column-number-to-string sum format printf)
17277 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17278 useval (if flag str1 (if valflag val ""))
17279 sum-alist (get-text-property sumpos 'org-summaries))
17280 (if (assoc property sum-alist)
17281 (setcdr (assoc property sum-alist) useval)
17282 (push (cons property useval) sum-alist)
17283 (org-unmodified
17284 (add-text-properties sumpos (1+ sumpos)
17285 (list 'org-summaries sum-alist))))
17286 (when val
17287 (org-entry-put nil property (if flag str val)))
17288 ;; add current to current level accumulator
17289 (when (or flag valflag)
17290 (aset lsum level (+ (aref lsum level)
17291 (if flag sum (org-column-string-to-number
17292 (if flag str val) format))))
17293 (aset lflag level t))
17294 ;; clear accumulators for deeper levels
17295 (loop for l from (1+ level) to (1- lmax) do
17296 (aset lsum l 0)
17297 (aset lflag l nil)))
17298 ((>= level last-level)
17299 ;; add what we have here to the accumulator for this level
17300 (aset lsum level (+ (aref lsum level)
17301 (org-column-string-to-number (or val "0") format)))
17302 (and valflag (aset lflag level t)))
17303 (t (error "This should not happen")))))))
17305 (defun org-columns-redo ()
17306 "Construct the column display again."
17307 (interactive)
17308 (message "Recomputing columns...")
17309 (save-excursion
17310 (if (marker-position org-columns-begin-marker)
17311 (goto-char org-columns-begin-marker))
17312 (org-columns-remove-overlays)
17313 (if (org-mode-p)
17314 (call-interactively 'org-columns)
17315 (call-interactively 'org-agenda-columns)))
17316 (message "Recomputing columns...done"))
17318 (defun org-columns-not-in-agenda ()
17319 (if (eq major-mode 'org-agenda-mode)
17320 (error "This command is only allowed in Org-mode buffers")))
17323 (defun org-string-to-number (s)
17324 "Convert string to number, and interpret hh:mm:ss."
17325 (if (not (string-match ":" s))
17326 (string-to-number s)
17327 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17328 (while l
17329 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17330 sum)))
17332 (defun org-column-number-to-string (n fmt &optional printf)
17333 "Convert a computed column number to a string value, according to FMT."
17334 (cond
17335 ((eq fmt 'add_times)
17336 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17337 (format "%d:%02d" h m)))
17338 ((eq fmt 'checkbox)
17339 (cond ((= n (floor n)) "[X]")
17340 ((> n 1.) "[-]")
17341 (t "[ ]")))
17342 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17343 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17344 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17345 (printf (format printf n))
17346 ((eq fmt 'currency)
17347 (format "%.2f" n))
17348 (t (number-to-string n))))
17350 (defun org-nofm-to-completion (n m &optional percent)
17351 (if (not percent)
17352 (format "[%d/%d]" n m)
17353 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17355 (defun org-column-string-to-number (s fmt)
17356 "Convert a column value to a number that can be used for column computing."
17357 (cond
17358 ((string-match ":" s)
17359 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17360 (while l
17361 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17362 sum))
17363 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17364 (if (equal s "[X]") 1. 0.000001))
17365 (t (string-to-number s))))
17367 (defun org-columns-uncompile-format (cfmt)
17368 "Turn the compiled columns format back into a string representation."
17369 (let ((rtn "") e s prop title op width fmt printf)
17370 (while (setq e (pop cfmt))
17371 (setq prop (car e)
17372 title (nth 1 e)
17373 width (nth 2 e)
17374 op (nth 3 e)
17375 fmt (nth 4 e)
17376 printf (nth 5 e))
17377 (cond
17378 ((eq fmt 'add_times) (setq op ":"))
17379 ((eq fmt 'checkbox) (setq op "X"))
17380 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17381 ((eq fmt 'checkbox-percent) (setq op "X%"))
17382 ((eq fmt 'add_numbers) (setq op "+"))
17383 ((eq fmt 'currency) (setq op "$")))
17384 (if (and op printf) (setq op (concat op ";" printf)))
17385 (if (equal title prop) (setq title nil))
17386 (setq s (concat "%" (if width (number-to-string width))
17387 prop
17388 (if title (concat "(" title ")"))
17389 (if op (concat "{" op "}"))))
17390 (setq rtn (concat rtn " " s)))
17391 (org-trim rtn)))
17393 (defun org-columns-compile-format (fmt)
17394 "Turn a column format string into an alist of specifications.
17395 The alist has one entry for each column in the format. The elements of
17396 that list are:
17397 property the property
17398 title the title field for the columns
17399 width the column width in characters, can be nil for automatic
17400 operator the operator if any
17401 format the output format for computed results, derived from operator
17402 printf a printf format for computed values"
17403 (let ((start 0) width prop title op f printf)
17404 (setq org-columns-current-fmt-compiled nil)
17405 (while (string-match
17406 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17407 fmt start)
17408 (setq start (match-end 0)
17409 width (match-string 1 fmt)
17410 prop (match-string 2 fmt)
17411 title (or (match-string 3 fmt) prop)
17412 op (match-string 4 fmt)
17413 f nil
17414 printf nil)
17415 (if width (setq width (string-to-number width)))
17416 (when (and op (string-match ";" op))
17417 (setq printf (substring op (match-end 0))
17418 op (substring op 0 (match-beginning 0))))
17419 (cond
17420 ((equal op "+") (setq f 'add_numbers))
17421 ((equal op "$") (setq f 'currency))
17422 ((equal op ":") (setq f 'add_times))
17423 ((equal op "X") (setq f 'checkbox))
17424 ((equal op "X/") (setq f 'checkbox-n-of-m))
17425 ((equal op "X%") (setq f 'checkbox-percent))
17427 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17428 (setq org-columns-current-fmt-compiled
17429 (nreverse org-columns-current-fmt-compiled))))
17432 ;;; Dynamic block for Column view
17434 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17435 "Get the column view of the current buffer or subtree.
17436 The first optional argument MAXLEVEL sets the level limit. A
17437 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17438 empty rows, an empty row being one where all the column view
17439 specifiers except ITEM are empty. This function returns a list
17440 containing the title row and all other rows. Each row is a list
17441 of fields."
17442 (save-excursion
17443 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17444 (n (length title)) row tbl)
17445 (goto-char (point-min))
17446 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17447 (or (null maxlevel)
17448 (>= maxlevel
17449 (if org-odd-levels-only
17450 (/ (1+ (length (match-string 1))) 2)
17451 (length (match-string 1))))))
17452 (when (get-char-property (match-beginning 0) 'org-columns-key)
17453 (setq row nil)
17454 (loop for i from 0 to (1- n) do
17455 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17456 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17458 row))
17459 (setq row (nreverse row))
17460 (unless (and skip-empty-rows
17461 (eq 1 (length (delete "" (delete-dups row)))))
17462 (push row tbl))))
17463 (append (list title 'hline) (nreverse tbl)))))
17465 (defun org-dblock-write:columnview (params)
17466 "Write the column view table.
17467 PARAMS is a property list of parameters:
17469 :width enforce same column widths with <N> specifiers.
17470 :id the :ID: property of the entry where the columns view
17471 should be built, as a string. When `local', call locally.
17472 When `global' call column view with the cursor at the beginning
17473 of the buffer (usually this means that the whole buffer switches
17474 to column view).
17475 :hlines When t, insert a hline before each item. When a number, insert
17476 a hline before each level <= that number.
17477 :vlines When t, make each column a colgroup to enforce vertical lines.
17478 :maxlevel When set to a number, don't capture headlines below this level.
17479 :skip-empty-rows
17480 When t, skip rows where all specifiers other than ITEM are empty."
17481 (let ((pos (move-marker (make-marker) (point)))
17482 (hlines (plist-get params :hlines))
17483 (vlines (plist-get params :vlines))
17484 (maxlevel (plist-get params :maxlevel))
17485 (skip-empty-rows (plist-get params :skip-empty-rows))
17486 tbl id idpos nfields tmp)
17487 (save-excursion
17488 (save-restriction
17489 (when (setq id (plist-get params :id))
17490 (cond ((not id) nil)
17491 ((eq id 'global) (goto-char (point-min)))
17492 ((eq id 'local) nil)
17493 ((setq idpos (org-find-entry-with-id id))
17494 (goto-char idpos))
17495 (t (error "Cannot find entry with :ID: %s" id))))
17496 (org-columns)
17497 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17498 (setq nfields (length (car tbl)))
17499 (org-columns-quit)))
17500 (goto-char pos)
17501 (move-marker pos nil)
17502 (when tbl
17503 (when (plist-get params :hlines)
17504 (setq tmp nil)
17505 (while tbl
17506 (if (eq (car tbl) 'hline)
17507 (push (pop tbl) tmp)
17508 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17509 (if (and (not (eq (car tmp) 'hline))
17510 (or (eq hlines t)
17511 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17512 (push 'hline tmp)))
17513 (push (pop tbl) tmp)))
17514 (setq tbl (nreverse tmp)))
17515 (when vlines
17516 (setq tbl (mapcar (lambda (x)
17517 (if (eq 'hline x) x (cons "" x)))
17518 tbl))
17519 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17520 (setq pos (point))
17521 (insert (org-listtable-to-string tbl))
17522 (when (plist-get params :width)
17523 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17524 org-columns-current-widths "|")))
17525 (goto-char pos)
17526 (org-table-align))))
17528 (defun org-listtable-to-string (tbl)
17529 "Convert a listtable TBL to a string that contains the Org-mode table.
17530 The table still need to be alligned. The resulting string has no leading
17531 and tailing newline characters."
17532 (mapconcat
17533 (lambda (x)
17534 (cond
17535 ((listp x)
17536 (concat "|" (mapconcat 'identity x "|") "|"))
17537 ((eq x 'hline) "|-|")
17538 (t (error "Garbage in listtable: %s" x))))
17539 tbl "\n"))
17541 (defun org-insert-columns-dblock ()
17542 "Create a dynamic block capturing a column view table."
17543 (interactive)
17544 (let ((defaults '(:name "columnview" :hlines 1))
17545 (id (completing-read
17546 "Capture columns (local, global, entry with :ID: property) [local]: "
17547 (append '(("global") ("local"))
17548 (mapcar 'list (org-property-values "ID"))))))
17549 (if (equal id "") (setq id 'local))
17550 (if (equal id "global") (setq id 'global))
17551 (setq defaults (append defaults (list :id id)))
17552 (org-create-dblock defaults)
17553 (org-update-dblock)))
17555 ;;;; Timestamps
17557 (defvar org-last-changed-timestamp nil)
17558 (defvar org-time-was-given) ; dynamically scoped parameter
17559 (defvar org-end-time-was-given) ; dynamically scoped parameter
17560 (defvar org-ts-what) ; dynamically scoped parameter
17562 (defun org-time-stamp (arg)
17563 "Prompt for a date/time and insert a time stamp.
17564 If the user specifies a time like HH:MM, or if this command is called
17565 with a prefix argument, the time stamp will contain date and time.
17566 Otherwise, only the date will be included. All parts of a date not
17567 specified by the user will be filled in from the current date/time.
17568 So if you press just return without typing anything, the time stamp
17569 will represent the current date/time. If there is already a timestamp
17570 at the cursor, it will be modified."
17571 (interactive "P")
17572 (let* ((ts nil)
17573 (default-time
17574 ;; Default time is either today, or, when entering a range,
17575 ;; the range start.
17576 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17577 (save-excursion
17578 (re-search-backward
17579 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17580 (- (point) 20) t)))
17581 (apply 'encode-time (org-parse-time-string (match-string 1)))
17582 (current-time)))
17583 (default-input (and ts (org-get-compact-tod ts)))
17584 org-time-was-given org-end-time-was-given time)
17585 (cond
17586 ((and (org-at-timestamp-p)
17587 (eq last-command 'org-time-stamp)
17588 (eq this-command 'org-time-stamp))
17589 (insert "--")
17590 (setq time (let ((this-command this-command))
17591 (org-read-date arg 'totime nil nil default-time default-input)))
17592 (org-insert-time-stamp time (or org-time-was-given arg)))
17593 ((org-at-timestamp-p)
17594 (setq time (let ((this-command this-command))
17595 (org-read-date arg 'totime nil nil default-time default-input)))
17596 (when (org-at-timestamp-p) ; just to get the match data
17597 (replace-match "")
17598 (setq org-last-changed-timestamp
17599 (org-insert-time-stamp
17600 time (or org-time-was-given arg)
17601 nil nil nil (list org-end-time-was-given))))
17602 (message "Timestamp updated"))
17604 (setq time (let ((this-command this-command))
17605 (org-read-date arg 'totime nil nil default-time default-input)))
17606 (org-insert-time-stamp time (or org-time-was-given arg)
17607 nil nil nil (list org-end-time-was-given))))))
17609 ;; FIXME: can we use this for something else????
17610 ;; like computing time differences?????
17611 (defun org-get-compact-tod (s)
17612 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17613 (let* ((t1 (match-string 1 s))
17614 (h1 (string-to-number (match-string 2 s)))
17615 (m1 (string-to-number (match-string 3 s)))
17616 (t2 (and (match-end 4) (match-string 5 s)))
17617 (h2 (and t2 (string-to-number (match-string 6 s))))
17618 (m2 (and t2 (string-to-number (match-string 7 s))))
17619 dh dm)
17620 (if (not t2)
17622 (setq dh (- h2 h1) dm (- m2 m1))
17623 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17624 (concat t1 "+" (number-to-string dh)
17625 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17627 (defun org-time-stamp-inactive (&optional arg)
17628 "Insert an inactive time stamp.
17629 An inactive time stamp is enclosed in square brackets instead of angle
17630 brackets. It is inactive in the sense that it does not trigger agenda entries,
17631 does not link to the calendar and cannot be changed with the S-cursor keys.
17632 So these are more for recording a certain time/date."
17633 (interactive "P")
17634 (let (org-time-was-given org-end-time-was-given time)
17635 (setq time (org-read-date arg 'totime))
17636 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17637 nil nil (list org-end-time-was-given))))
17639 (defvar org-date-ovl (org-make-overlay 1 1))
17640 (org-overlay-put org-date-ovl 'face 'org-warning)
17641 (org-detach-overlay org-date-ovl)
17643 (defvar org-ans1) ; dynamically scoped parameter
17644 (defvar org-ans2) ; dynamically scoped parameter
17646 (defvar org-plain-time-of-day-regexp) ; defined below
17648 (defvar org-read-date-overlay nil)
17649 (defvar org-dcst nil) ; dynamically scoped
17651 (defun org-read-date (&optional with-time to-time from-string prompt
17652 default-time default-input)
17653 "Read a date, possibly a time, and make things smooth for the user.
17654 The prompt will suggest to enter an ISO date, but you can also enter anything
17655 which will at least partially be understood by `parse-time-string'.
17656 Unrecognized parts of the date will default to the current day, month, year,
17657 hour and minute. If this command is called to replace a timestamp at point,
17658 of to enter the second timestamp of a range, the default time is taken from the
17659 existing stamp. For example,
17660 3-2-5 --> 2003-02-05
17661 feb 15 --> currentyear-02-15
17662 sep 12 9 --> 2009-09-12
17663 12:45 --> today 12:45
17664 22 sept 0:34 --> currentyear-09-22 0:34
17665 12 --> currentyear-currentmonth-12
17666 Fri --> nearest Friday (today or later)
17667 etc.
17669 Furthermore you can specify a relative date by giving, as the *first* thing
17670 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17671 change in days weeks, months, years.
17672 With a single plus or minus, the date is relative to today. With a double
17673 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17674 +4d --> four days from today
17675 +4 --> same as above
17676 +2w --> two weeks from today
17677 ++5 --> five days from default date
17679 The function understands only English month and weekday abbreviations,
17680 but this can be configured with the variables `parse-time-months' and
17681 `parse-time-weekdays'.
17683 While prompting, a calendar is popped up - you can also select the
17684 date with the mouse (button 1). The calendar shows a period of three
17685 months. To scroll it to other months, use the keys `>' and `<'.
17686 If you don't like the calendar, turn it off with
17687 \(setq org-read-date-popup-calendar nil)
17689 With optional argument TO-TIME, the date will immediately be converted
17690 to an internal time.
17691 With an optional argument WITH-TIME, the prompt will suggest to also
17692 insert a time. Note that when WITH-TIME is not set, you can still
17693 enter a time, and this function will inform the calling routine about
17694 this change. The calling routine may then choose to change the format
17695 used to insert the time stamp into the buffer to include the time.
17696 With optional argument FROM-STRING, read from this string instead from
17697 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17698 the time/date that is used for everything that is not specified by the
17699 user."
17700 (require 'parse-time)
17701 (let* ((org-time-stamp-rounding-minutes
17702 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17703 (org-dcst org-display-custom-times)
17704 (ct (org-current-time))
17705 (def (or default-time ct))
17706 (defdecode (decode-time def))
17707 (dummy (progn
17708 (when (< (nth 2 defdecode) org-extend-today-until)
17709 (setcar (nthcdr 2 defdecode) -1)
17710 (setcar (nthcdr 1 defdecode) 59)
17711 (setq def (apply 'encode-time defdecode)
17712 defdecode (decode-time def)))))
17713 (calendar-move-hook nil)
17714 (view-diary-entries-initially nil)
17715 (view-calendar-holidays-initially nil)
17716 (timestr (format-time-string
17717 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17718 (prompt (concat (if prompt (concat prompt " ") "")
17719 (format "Date+time [%s]: " timestr)))
17720 ans (org-ans0 "") org-ans1 org-ans2 final)
17722 (cond
17723 (from-string (setq ans from-string))
17724 (org-read-date-popup-calendar
17725 (save-excursion
17726 (save-window-excursion
17727 (calendar)
17728 (calendar-forward-day (- (time-to-days def)
17729 (calendar-absolute-from-gregorian
17730 (calendar-current-date))))
17731 (org-eval-in-calendar nil t)
17732 (let* ((old-map (current-local-map))
17733 (map (copy-keymap calendar-mode-map))
17734 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17735 (org-defkey map (kbd "RET") 'org-calendar-select)
17736 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17737 'org-calendar-select-mouse)
17738 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17739 'org-calendar-select-mouse)
17740 (org-defkey minibuffer-local-map [(meta shift left)]
17741 (lambda () (interactive)
17742 (org-eval-in-calendar '(calendar-backward-month 1))))
17743 (org-defkey minibuffer-local-map [(meta shift right)]
17744 (lambda () (interactive)
17745 (org-eval-in-calendar '(calendar-forward-month 1))))
17746 (org-defkey minibuffer-local-map [(meta shift up)]
17747 (lambda () (interactive)
17748 (org-eval-in-calendar '(calendar-backward-year 1))))
17749 (org-defkey minibuffer-local-map [(meta shift down)]
17750 (lambda () (interactive)
17751 (org-eval-in-calendar '(calendar-forward-year 1))))
17752 (org-defkey minibuffer-local-map [(shift up)]
17753 (lambda () (interactive)
17754 (org-eval-in-calendar '(calendar-backward-week 1))))
17755 (org-defkey minibuffer-local-map [(shift down)]
17756 (lambda () (interactive)
17757 (org-eval-in-calendar '(calendar-forward-week 1))))
17758 (org-defkey minibuffer-local-map [(shift left)]
17759 (lambda () (interactive)
17760 (org-eval-in-calendar '(calendar-backward-day 1))))
17761 (org-defkey minibuffer-local-map [(shift right)]
17762 (lambda () (interactive)
17763 (org-eval-in-calendar '(calendar-forward-day 1))))
17764 (org-defkey minibuffer-local-map ">"
17765 (lambda () (interactive)
17766 (org-eval-in-calendar '(scroll-calendar-left 1))))
17767 (org-defkey minibuffer-local-map "<"
17768 (lambda () (interactive)
17769 (org-eval-in-calendar '(scroll-calendar-right 1))))
17770 (unwind-protect
17771 (progn
17772 (use-local-map map)
17773 (add-hook 'post-command-hook 'org-read-date-display)
17774 (setq org-ans0 (read-string prompt default-input nil nil))
17775 ;; org-ans0: from prompt
17776 ;; org-ans1: from mouse click
17777 ;; org-ans2: from calendar motion
17778 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17779 (remove-hook 'post-command-hook 'org-read-date-display)
17780 (use-local-map old-map)
17781 (when org-read-date-overlay
17782 (org-delete-overlay org-read-date-overlay)
17783 (setq org-read-date-overlay nil)))))))
17785 (t ; Naked prompt only
17786 (unwind-protect
17787 (setq ans (read-string prompt default-input nil timestr))
17788 (when org-read-date-overlay
17789 (org-delete-overlay org-read-date-overlay)
17790 (setq org-read-date-overlay nil)))))
17792 (setq final (org-read-date-analyze ans def defdecode))
17794 (if to-time
17795 (apply 'encode-time final)
17796 (if (and (boundp 'org-time-was-given) org-time-was-given)
17797 (format "%04d-%02d-%02d %02d:%02d"
17798 (nth 5 final) (nth 4 final) (nth 3 final)
17799 (nth 2 final) (nth 1 final))
17800 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17801 (defvar def)
17802 (defvar defdecode)
17803 (defvar with-time)
17804 (defun org-read-date-display ()
17805 "Display the currrent date prompt interpretation in the minibuffer."
17806 (when org-read-date-display-live
17807 (when org-read-date-overlay
17808 (org-delete-overlay org-read-date-overlay))
17809 (let ((p (point)))
17810 (end-of-line 1)
17811 (while (not (equal (buffer-substring
17812 (max (point-min) (- (point) 4)) (point))
17813 " "))
17814 (insert " "))
17815 (goto-char p))
17816 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17817 " " (or org-ans1 org-ans2)))
17818 (org-end-time-was-given nil)
17819 (f (org-read-date-analyze ans def defdecode))
17820 (fmts (if org-dcst
17821 org-time-stamp-custom-formats
17822 org-time-stamp-formats))
17823 (fmt (if (or with-time
17824 (and (boundp 'org-time-was-given) org-time-was-given))
17825 (cdr fmts)
17826 (car fmts)))
17827 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17828 (when (and org-end-time-was-given
17829 (string-match org-plain-time-of-day-regexp txt))
17830 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17831 org-end-time-was-given
17832 (substring txt (match-end 0)))))
17833 (setq org-read-date-overlay
17834 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17835 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17837 (defun org-read-date-analyze (ans def defdecode)
17838 "Analyze the combined answer of the date prompt."
17839 ;; FIXME: cleanup and comment
17840 (let (delta deltan deltaw deltadef year month day
17841 hour minute second wday pm h2 m2 tl wday1)
17843 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17844 (setq ans (replace-match "" t t ans)
17845 deltan (car delta)
17846 deltaw (nth 1 delta)
17847 deltadef (nth 2 delta)))
17849 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17850 (when (string-match
17851 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17852 (setq year (if (match-end 2)
17853 (string-to-number (match-string 2 ans))
17854 (string-to-number (format-time-string "%Y")))
17855 month (string-to-number (match-string 3 ans))
17856 day (string-to-number (match-string 4 ans)))
17857 (if (< year 100) (setq year (+ 2000 year)))
17858 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17859 t nil ans)))
17860 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17861 ;; If there is a time with am/pm, and *no* time without it, we convert
17862 ;; so that matching will be successful.
17863 (loop for i from 1 to 2 do ; twice, for end time as well
17864 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17865 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17866 (setq hour (string-to-number (match-string 1 ans))
17867 minute (if (match-end 3)
17868 (string-to-number (match-string 3 ans))
17870 pm (equal ?p
17871 (string-to-char (downcase (match-string 4 ans)))))
17872 (if (and (= hour 12) (not pm))
17873 (setq hour 0)
17874 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17875 (setq ans (replace-match (format "%02d:%02d" hour minute)
17876 t t ans))))
17878 ;; Check if a time range is given as a duration
17879 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17880 (setq hour (string-to-number (match-string 1 ans))
17881 h2 (+ hour (string-to-number (match-string 3 ans)))
17882 minute (string-to-number (match-string 2 ans))
17883 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17884 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17885 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17887 ;; Check if there is a time range
17888 (when (boundp 'org-end-time-was-given)
17889 (setq org-time-was-given nil)
17890 (when (and (string-match org-plain-time-of-day-regexp ans)
17891 (match-end 8))
17892 (setq org-end-time-was-given (match-string 8 ans))
17893 (setq ans (concat (substring ans 0 (match-beginning 7))
17894 (substring ans (match-end 7))))))
17896 (setq tl (parse-time-string ans)
17897 day (or (nth 3 tl) (nth 3 defdecode))
17898 month (or (nth 4 tl)
17899 (if (and org-read-date-prefer-future
17900 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17901 (1+ (nth 4 defdecode))
17902 (nth 4 defdecode)))
17903 year (or (nth 5 tl)
17904 (if (and org-read-date-prefer-future
17905 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17906 (1+ (nth 5 defdecode))
17907 (nth 5 defdecode)))
17908 hour (or (nth 2 tl) (nth 2 defdecode))
17909 minute (or (nth 1 tl) (nth 1 defdecode))
17910 second (or (nth 0 tl) 0)
17911 wday (nth 6 tl))
17912 (when deltan
17913 (unless deltadef
17914 (let ((now (decode-time (current-time))))
17915 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17916 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17917 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17918 ((equal deltaw "m") (setq month (+ month deltan)))
17919 ((equal deltaw "y") (setq year (+ year deltan)))))
17920 (when (and wday (not (nth 3 tl)))
17921 ;; Weekday was given, but no day, so pick that day in the week
17922 ;; on or after the derived date.
17923 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17924 (unless (equal wday wday1)
17925 (setq day (+ day (% (- wday wday1 -7) 7)))))
17926 (if (and (boundp 'org-time-was-given)
17927 (nth 2 tl))
17928 (setq org-time-was-given t))
17929 (if (< year 100) (setq year (+ 2000 year)))
17930 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17931 (list second minute hour day month year)))
17933 (defvar parse-time-weekdays)
17935 (defun org-read-date-get-relative (s today default)
17936 "Check string S for special relative date string.
17937 TODAY and DEFAULT are internal times, for today and for a default.
17938 Return shift list (N what def-flag)
17939 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17940 N is the number of WHATs to shift.
17941 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17942 the DEFAULT date rather than TODAY."
17943 (when (string-match
17944 (concat
17945 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17946 "\\([0-9]+\\)?"
17947 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17948 "\\([ \t]\\|$\\)") s)
17949 (let* ((dir (if (match-end 1)
17950 (string-to-char (substring (match-string 1 s) -1))
17951 ?+))
17952 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17953 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17954 (what (if (match-end 3) (match-string 3 s) "d"))
17955 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17956 (date (if rel default today))
17957 (wday (nth 6 (decode-time date)))
17958 delta)
17959 (if wday1
17960 (progn
17961 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17962 (if (= dir ?-) (setq delta (- delta 7)))
17963 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17964 (list delta "d" rel))
17965 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17967 (defun org-eval-in-calendar (form &optional keepdate)
17968 "Eval FORM in the calendar window and return to current window.
17969 Also, store the cursor date in variable org-ans2."
17970 (let ((sw (selected-window)))
17971 (select-window (get-buffer-window "*Calendar*"))
17972 (eval form)
17973 (when (and (not keepdate) (calendar-cursor-to-date))
17974 (let* ((date (calendar-cursor-to-date))
17975 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17976 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17977 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17978 (select-window sw)))
17980 ; ;; Update the prompt to show new default date
17981 ; (save-excursion
17982 ; (goto-char (point-min))
17983 ; (when (and org-ans2
17984 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17985 ; (get-text-property (match-end 0) 'field))
17986 ; (let ((inhibit-read-only t))
17987 ; (replace-match (concat "[" org-ans2 "]") t t)
17988 ; (add-text-properties (point-min) (1+ (match-end 0))
17989 ; (text-properties-at (1+ (point-min)))))))))
17991 (defun org-calendar-select ()
17992 "Return to `org-read-date' with the date currently selected.
17993 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17994 (interactive)
17995 (when (calendar-cursor-to-date)
17996 (let* ((date (calendar-cursor-to-date))
17997 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17998 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17999 (if (active-minibuffer-window) (exit-minibuffer))))
18001 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18002 "Insert a date stamp for the date given by the internal TIME.
18003 WITH-HM means, use the stamp format that includes the time of the day.
18004 INACTIVE means use square brackets instead of angular ones, so that the
18005 stamp will not contribute to the agenda.
18006 PRE and POST are optional strings to be inserted before and after the
18007 stamp.
18008 The command returns the inserted time stamp."
18009 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18010 stamp)
18011 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18012 (insert-before-markers (or pre ""))
18013 (insert-before-markers (setq stamp (format-time-string fmt time)))
18014 (when (listp extra)
18015 (setq extra (car extra))
18016 (if (and (stringp extra)
18017 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18018 (setq extra (format "-%02d:%02d"
18019 (string-to-number (match-string 1 extra))
18020 (string-to-number (match-string 2 extra))))
18021 (setq extra nil)))
18022 (when extra
18023 (backward-char 1)
18024 (insert-before-markers extra)
18025 (forward-char 1))
18026 (insert-before-markers (or post ""))
18027 stamp))
18029 (defun org-toggle-time-stamp-overlays ()
18030 "Toggle the use of custom time stamp formats."
18031 (interactive)
18032 (setq org-display-custom-times (not org-display-custom-times))
18033 (unless org-display-custom-times
18034 (let ((p (point-min)) (bmp (buffer-modified-p)))
18035 (while (setq p (next-single-property-change p 'display))
18036 (if (and (get-text-property p 'display)
18037 (eq (get-text-property p 'face) 'org-date))
18038 (remove-text-properties
18039 p (setq p (next-single-property-change p 'display))
18040 '(display t))))
18041 (set-buffer-modified-p bmp)))
18042 (if (featurep 'xemacs)
18043 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18044 (org-restart-font-lock)
18045 (setq org-table-may-need-update t)
18046 (if org-display-custom-times
18047 (message "Time stamps are overlayed with custom format")
18048 (message "Time stamp overlays removed")))
18050 (defun org-display-custom-time (beg end)
18051 "Overlay modified time stamp format over timestamp between BED and END."
18052 (let* ((ts (buffer-substring beg end))
18053 t1 w1 with-hm tf time str w2 (off 0))
18054 (save-match-data
18055 (setq t1 (org-parse-time-string ts t))
18056 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
18057 (setq off (- (match-end 0) (match-beginning 0)))))
18058 (setq end (- end off))
18059 (setq w1 (- end beg)
18060 with-hm (and (nth 1 t1) (nth 2 t1))
18061 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18062 time (org-fix-decoded-time t1)
18063 str (org-add-props
18064 (format-time-string
18065 (substring tf 1 -1) (apply 'encode-time time))
18066 nil 'mouse-face 'highlight)
18067 w2 (length str))
18068 (if (not (= w2 w1))
18069 (add-text-properties (1+ beg) (+ 2 beg)
18070 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18071 (if (featurep 'xemacs)
18072 (progn
18073 (put-text-property beg end 'invisible t)
18074 (put-text-property beg end 'end-glyph (make-glyph str)))
18075 (put-text-property beg end 'display str))))
18077 (defun org-translate-time (string)
18078 "Translate all timestamps in STRING to custom format.
18079 But do this only if the variable `org-display-custom-times' is set."
18080 (when org-display-custom-times
18081 (save-match-data
18082 (let* ((start 0)
18083 (re org-ts-regexp-both)
18084 t1 with-hm inactive tf time str beg end)
18085 (while (setq start (string-match re string start))
18086 (setq beg (match-beginning 0)
18087 end (match-end 0)
18088 t1 (save-match-data
18089 (org-parse-time-string (substring string beg end) t))
18090 with-hm (and (nth 1 t1) (nth 2 t1))
18091 inactive (equal (substring string beg (1+ beg)) "[")
18092 tf (funcall (if with-hm 'cdr 'car)
18093 org-time-stamp-custom-formats)
18094 time (org-fix-decoded-time t1)
18095 str (format-time-string
18096 (concat
18097 (if inactive "[" "<") (substring tf 1 -1)
18098 (if inactive "]" ">"))
18099 (apply 'encode-time time))
18100 string (replace-match str t t string)
18101 start (+ start (length str)))))))
18102 string)
18104 (defun org-fix-decoded-time (time)
18105 "Set 0 instead of nil for the first 6 elements of time.
18106 Don't touch the rest."
18107 (let ((n 0))
18108 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18110 (defun org-days-to-time (timestamp-string)
18111 "Difference between TIMESTAMP-STRING and now in days."
18112 (- (time-to-days (org-time-string-to-time timestamp-string))
18113 (time-to-days (current-time))))
18115 (defun org-deadline-close (timestamp-string &optional ndays)
18116 "Is the time in TIMESTAMP-STRING close to the current date?"
18117 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18118 (and (< (org-days-to-time timestamp-string) ndays)
18119 (not (org-entry-is-done-p))))
18121 (defun org-get-wdays (ts)
18122 "Get the deadline lead time appropriate for timestring TS."
18123 (cond
18124 ((<= org-deadline-warning-days 0)
18125 ;; 0 or negative, enforce this value no matter what
18126 (- org-deadline-warning-days))
18127 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18128 ;; lead time is specified.
18129 (floor (* (string-to-number (match-string 1 ts))
18130 (cdr (assoc (match-string 2 ts)
18131 '(("d" . 1) ("w" . 7)
18132 ("m" . 30.4) ("y" . 365.25)))))))
18133 ;; go for the default.
18134 (t org-deadline-warning-days)))
18136 (defun org-calendar-select-mouse (ev)
18137 "Return to `org-read-date' with the date currently selected.
18138 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18139 (interactive "e")
18140 (mouse-set-point ev)
18141 (when (calendar-cursor-to-date)
18142 (let* ((date (calendar-cursor-to-date))
18143 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18144 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18145 (if (active-minibuffer-window) (exit-minibuffer))))
18147 (defun org-check-deadlines (ndays)
18148 "Check if there are any deadlines due or past due.
18149 A deadline is considered due if it happens within `org-deadline-warning-days'
18150 days from today's date. If the deadline appears in an entry marked DONE,
18151 it is not shown. The prefix arg NDAYS can be used to test that many
18152 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18153 (interactive "P")
18154 (let* ((org-warn-days
18155 (cond
18156 ((equal ndays '(4)) 100000)
18157 (ndays (prefix-numeric-value ndays))
18158 (t (abs org-deadline-warning-days))))
18159 (case-fold-search nil)
18160 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18161 (callback
18162 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18164 (message "%d deadlines past-due or due within %d days"
18165 (org-occur regexp nil callback)
18166 org-warn-days)))
18168 (defun org-check-before-date (date)
18169 "Check if there are deadlines or scheduled entries before DATE."
18170 (interactive (list (org-read-date)))
18171 (let ((case-fold-search nil)
18172 (regexp (concat "\\<\\(" org-deadline-string
18173 "\\|" org-scheduled-string
18174 "\\) *<\\([^>]+\\)>"))
18175 (callback
18176 (lambda () (time-less-p
18177 (org-time-string-to-time (match-string 2))
18178 (org-time-string-to-time date)))))
18179 (message "%d entries before %s"
18180 (org-occur regexp nil callback) date)))
18182 (defun org-evaluate-time-range (&optional to-buffer)
18183 "Evaluate a time range by computing the difference between start and end.
18184 Normally the result is just printed in the echo area, but with prefix arg
18185 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18186 If the time range is actually in a table, the result is inserted into the
18187 next column.
18188 For time difference computation, a year is assumed to be exactly 365
18189 days in order to avoid rounding problems."
18190 (interactive "P")
18192 (org-clock-update-time-maybe)
18193 (save-excursion
18194 (unless (org-at-date-range-p t)
18195 (goto-char (point-at-bol))
18196 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18197 (if (not (org-at-date-range-p t))
18198 (error "Not at a time-stamp range, and none found in current line")))
18199 (let* ((ts1 (match-string 1))
18200 (ts2 (match-string 2))
18201 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18202 (match-end (match-end 0))
18203 (time1 (org-time-string-to-time ts1))
18204 (time2 (org-time-string-to-time ts2))
18205 (t1 (time-to-seconds time1))
18206 (t2 (time-to-seconds time2))
18207 (diff (abs (- t2 t1)))
18208 (negative (< (- t2 t1) 0))
18209 ;; (ys (floor (* 365 24 60 60)))
18210 (ds (* 24 60 60))
18211 (hs (* 60 60))
18212 (fy "%dy %dd %02d:%02d")
18213 (fy1 "%dy %dd")
18214 (fd "%dd %02d:%02d")
18215 (fd1 "%dd")
18216 (fh "%02d:%02d")
18217 y d h m align)
18218 (if havetime
18219 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18221 d (floor (/ diff ds)) diff (mod diff ds)
18222 h (floor (/ diff hs)) diff (mod diff hs)
18223 m (floor (/ diff 60)))
18224 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18226 d (floor (+ (/ diff ds) 0.5))
18227 h 0 m 0))
18228 (if (not to-buffer)
18229 (message "%s" (org-make-tdiff-string y d h m))
18230 (if (org-at-table-p)
18231 (progn
18232 (goto-char match-end)
18233 (setq align t)
18234 (and (looking-at " *|") (goto-char (match-end 0))))
18235 (goto-char match-end))
18236 (if (looking-at
18237 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18238 (replace-match ""))
18239 (if negative (insert " -"))
18240 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18241 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18242 (insert " " (format fh h m))))
18243 (if align (org-table-align))
18244 (message "Time difference inserted")))))
18246 (defun org-make-tdiff-string (y d h m)
18247 (let ((fmt "")
18248 (l nil))
18249 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18250 l (push y l)))
18251 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18252 l (push d l)))
18253 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18254 l (push h l)))
18255 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18256 l (push m l)))
18257 (apply 'format fmt (nreverse l))))
18259 (defun org-time-string-to-time (s)
18260 (apply 'encode-time (org-parse-time-string s)))
18262 (defun org-time-string-to-absolute (s &optional daynr prefer)
18263 "Convert a time stamp to an absolute day number.
18264 If there is a specifyer for a cyclic time stamp, get the closest date to
18265 DAYNR."
18266 (cond
18267 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18268 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18269 daynr
18270 (+ daynr 1000)))
18271 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18272 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18273 (time-to-days (current-time))) (match-string 0 s)
18274 prefer))
18275 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18277 (defun org-time-from-absolute (d)
18278 "Return the time corresponding to date D.
18279 D may be an absolute day number, or a calendar-type list (month day year)."
18280 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18281 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18283 (defun org-calendar-holiday ()
18284 "List of holidays, for Diary display in Org-mode."
18285 (require 'holidays)
18286 (let ((hl (funcall
18287 (if (fboundp 'calendar-check-holidays)
18288 'calendar-check-holidays 'check-calendar-holidays) date)))
18289 (if hl (mapconcat 'identity hl "; "))))
18291 (defun org-diary-sexp-entry (sexp entry date)
18292 "Process a SEXP diary ENTRY for DATE."
18293 (require 'diary-lib)
18294 (let ((result (if calendar-debug-sexp
18295 (let ((stack-trace-on-error t))
18296 (eval (car (read-from-string sexp))))
18297 (condition-case nil
18298 (eval (car (read-from-string sexp)))
18299 (error
18300 (beep)
18301 (message "Bad sexp at line %d in %s: %s"
18302 (org-current-line)
18303 (buffer-file-name) sexp)
18304 (sleep-for 2))))))
18305 (cond ((stringp result) result)
18306 ((and (consp result)
18307 (stringp (cdr result))) (cdr result))
18308 (result entry)
18309 (t nil))))
18311 (defun org-diary-to-ical-string (frombuf)
18312 "Get iCalendar entries from diary entries in buffer FROMBUF.
18313 This uses the icalendar.el library."
18314 (let* ((tmpdir (if (featurep 'xemacs)
18315 (temp-directory)
18316 temporary-file-directory))
18317 (tmpfile (make-temp-name
18318 (expand-file-name "orgics" tmpdir)))
18319 buf rtn b e)
18320 (save-excursion
18321 (set-buffer frombuf)
18322 (icalendar-export-region (point-min) (point-max) tmpfile)
18323 (setq buf (find-buffer-visiting tmpfile))
18324 (set-buffer buf)
18325 (goto-char (point-min))
18326 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18327 (setq b (match-beginning 0)))
18328 (goto-char (point-max))
18329 (if (re-search-backward "^END:VEVENT" nil t)
18330 (setq e (match-end 0)))
18331 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18332 (kill-buffer buf)
18333 (kill-buffer frombuf)
18334 (delete-file tmpfile)
18335 rtn))
18337 (defun org-closest-date (start current change prefer)
18338 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18339 When PREFER is `past' return a date that is either CURRENT or past.
18340 When PREFER is `future', return a date that is either CURRENT or future."
18341 ;; Make the proper lists from the dates
18342 (catch 'exit
18343 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18344 dn dw sday cday n1 n2
18345 d m y y1 y2 date1 date2 nmonths nm ny m2)
18347 (setq start (org-date-to-gregorian start)
18348 current (org-date-to-gregorian
18349 (if org-agenda-repeating-timestamp-show-all
18350 current
18351 (time-to-days (current-time))))
18352 sday (calendar-absolute-from-gregorian start)
18353 cday (calendar-absolute-from-gregorian current))
18355 (if (<= cday sday) (throw 'exit sday))
18357 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18358 (setq dn (string-to-number (match-string 1 change))
18359 dw (cdr (assoc (match-string 2 change) a1)))
18360 (error "Invalid change specifyer: %s" change))
18361 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18362 (cond
18363 ((eq dw 'day)
18364 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18365 n2 (+ n1 dn)))
18366 ((eq dw 'year)
18367 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18368 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18369 (setq date1 (list m d y1)
18370 n1 (calendar-absolute-from-gregorian date1)
18371 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18372 n2 (calendar-absolute-from-gregorian date2)))
18373 ((eq dw 'month)
18374 ;; approx number of month between the tow dates
18375 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18376 ;; How often does dn fit in there?
18377 (setq d (nth 1 start) m (car start) y (nth 2 start)
18378 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18379 m (+ m nm)
18380 ny (floor (/ m 12))
18381 y (+ y ny)
18382 m (- m (* ny 12)))
18383 (while (> m 12) (setq m (- m 12) y (1+ y)))
18384 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18385 (setq m2 (+ m dn) y2 y)
18386 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18387 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18388 (while (< n2 cday)
18389 (setq n1 n2 m m2 y y2)
18390 (setq m2 (+ m dn) y2 y)
18391 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18392 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18394 (if org-agenda-repeating-timestamp-show-all
18395 (cond
18396 ((eq prefer 'past) n1)
18397 ((eq prefer 'future) (if (= cday n1) n1 n2))
18398 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18399 (cond
18400 ((eq prefer 'past) n1)
18401 ((eq prefer 'future) (if (= cday n1) n1 n2))
18402 (t (if (= cday n1) n1 n2)))))))
18404 (defun org-date-to-gregorian (date)
18405 "Turn any specification of DATE into a gregorian date for the calendar."
18406 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18407 ((and (listp date) (= (length date) 3)) date)
18408 ((stringp date)
18409 (setq date (org-parse-time-string date))
18410 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18411 ((listp date)
18412 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18414 (defun org-parse-time-string (s &optional nodefault)
18415 "Parse the standard Org-mode time string.
18416 This should be a lot faster than the normal `parse-time-string'.
18417 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18418 hour and minute fields will be nil if not given."
18419 (if (string-match org-ts-regexp0 s)
18420 (list 0
18421 (if (or (match-beginning 8) (not nodefault))
18422 (string-to-number (or (match-string 8 s) "0")))
18423 (if (or (match-beginning 7) (not nodefault))
18424 (string-to-number (or (match-string 7 s) "0")))
18425 (string-to-number (match-string 4 s))
18426 (string-to-number (match-string 3 s))
18427 (string-to-number (match-string 2 s))
18428 nil nil nil)
18429 (make-list 9 0)))
18431 (defun org-timestamp-up (&optional arg)
18432 "Increase the date item at the cursor by one.
18433 If the cursor is on the year, change the year. If it is on the month or
18434 the day, change that.
18435 With prefix ARG, change by that many units."
18436 (interactive "p")
18437 (org-timestamp-change (prefix-numeric-value arg)))
18439 (defun org-timestamp-down (&optional arg)
18440 "Decrease the date item at the cursor by one.
18441 If the cursor is on the year, change the year. If it is on the month or
18442 the day, change that.
18443 With prefix ARG, change by that many units."
18444 (interactive "p")
18445 (org-timestamp-change (- (prefix-numeric-value arg))))
18447 (defun org-timestamp-up-day (&optional arg)
18448 "Increase the date in the time stamp by one day.
18449 With prefix ARG, change that many days."
18450 (interactive "p")
18451 (if (and (not (org-at-timestamp-p t))
18452 (org-on-heading-p))
18453 (org-todo 'up)
18454 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18456 (defun org-timestamp-down-day (&optional arg)
18457 "Decrease the date in the time stamp by one day.
18458 With prefix ARG, change that many days."
18459 (interactive "p")
18460 (if (and (not (org-at-timestamp-p t))
18461 (org-on-heading-p))
18462 (org-todo 'down)
18463 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18465 (defsubst org-pos-in-match-range (pos n)
18466 (and (match-beginning n)
18467 (<= (match-beginning n) pos)
18468 (>= (match-end n) pos)))
18470 (defun org-at-timestamp-p (&optional inactive-ok)
18471 "Determine if the cursor is in or at a timestamp."
18472 (interactive)
18473 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18474 (pos (point))
18475 (ans (or (looking-at tsr)
18476 (save-excursion
18477 (skip-chars-backward "^[<\n\r\t")
18478 (if (> (point) (point-min)) (backward-char 1))
18479 (and (looking-at tsr)
18480 (> (- (match-end 0) pos) -1))))))
18481 (and ans
18482 (boundp 'org-ts-what)
18483 (setq org-ts-what
18484 (cond
18485 ((= pos (match-beginning 0)) 'bracket)
18486 ((= pos (1- (match-end 0))) 'bracket)
18487 ((org-pos-in-match-range pos 2) 'year)
18488 ((org-pos-in-match-range pos 3) 'month)
18489 ((org-pos-in-match-range pos 7) 'hour)
18490 ((org-pos-in-match-range pos 8) 'minute)
18491 ((or (org-pos-in-match-range pos 4)
18492 (org-pos-in-match-range pos 5)) 'day)
18493 ((and (> pos (or (match-end 8) (match-end 5)))
18494 (< pos (match-end 0)))
18495 (- pos (or (match-end 8) (match-end 5))))
18496 (t 'day))))
18497 ans))
18499 (defun org-toggle-timestamp-type ()
18501 (interactive)
18502 (when (org-at-timestamp-p t)
18503 (save-excursion
18504 (goto-char (match-beginning 0))
18505 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18506 (goto-char (1- (match-end 0)))
18507 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18508 (message "Timestamp is now %sactive"
18509 (if (equal (char-before) ?>) "in" ""))))
18511 (defun org-timestamp-change (n &optional what)
18512 "Change the date in the time stamp at point.
18513 The date will be changed by N times WHAT. WHAT can be `day', `month',
18514 `year', `minute', `second'. If WHAT is not given, the cursor position
18515 in the timestamp determines what will be changed."
18516 (let ((pos (point))
18517 with-hm inactive
18518 org-ts-what
18519 extra
18520 ts time time0)
18521 (if (not (org-at-timestamp-p t))
18522 (error "Not at a timestamp"))
18523 (if (and (not what) (eq org-ts-what 'bracket))
18524 (org-toggle-timestamp-type)
18525 (if (and (not what) (not (eq org-ts-what 'day))
18526 org-display-custom-times
18527 (get-text-property (point) 'display)
18528 (not (get-text-property (1- (point)) 'display)))
18529 (setq org-ts-what 'day))
18530 (setq org-ts-what (or what org-ts-what)
18531 inactive (= (char-after (match-beginning 0)) ?\[)
18532 ts (match-string 0))
18533 (replace-match "")
18534 (if (string-match
18535 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18537 (setq extra (match-string 1 ts)))
18538 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18539 (setq with-hm t))
18540 (setq time0 (org-parse-time-string ts))
18541 (setq time
18542 (encode-time (or (car time0) 0)
18543 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18544 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18545 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18546 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18547 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18548 (nthcdr 6 time0)))
18549 (when (integerp org-ts-what)
18550 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18551 (if (eq what 'calendar)
18552 (let ((cal-date (org-get-date-from-calendar)))
18553 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18554 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18555 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18556 (setcar time0 (or (car time0) 0))
18557 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18558 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18559 (setq time (apply 'encode-time time0))))
18560 (setq org-last-changed-timestamp
18561 (org-insert-time-stamp time with-hm inactive nil nil extra))
18562 (org-clock-update-time-maybe)
18563 (goto-char pos)
18564 ;; Try to recenter the calendar window, if any
18565 (if (and org-calendar-follow-timestamp-change
18566 (get-buffer-window "*Calendar*" t)
18567 (memq org-ts-what '(day month year)))
18568 (org-recenter-calendar (time-to-days time))))))
18570 ;; FIXME: does not yet work for lead times
18571 (defun org-modify-ts-extra (s pos n)
18572 "Change the different parts of the lead-time and repeat fields in timestamp."
18573 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18574 ng h m new)
18575 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18576 (cond
18577 ((or (org-pos-in-match-range pos 2)
18578 (org-pos-in-match-range pos 3))
18579 (setq m (string-to-number (match-string 3 s))
18580 h (string-to-number (match-string 2 s)))
18581 (if (org-pos-in-match-range pos 2)
18582 (setq h (+ h n))
18583 (setq m (+ m n)))
18584 (if (< m 0) (setq m (+ m 60) h (1- h)))
18585 (if (> m 59) (setq m (- m 60) h (1+ h)))
18586 (setq h (min 24 (max 0 h)))
18587 (setq ng 1 new (format "-%02d:%02d" h m)))
18588 ((org-pos-in-match-range pos 6)
18589 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18590 ((org-pos-in-match-range pos 5)
18591 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18593 (when ng
18594 (setq s (concat
18595 (substring s 0 (match-beginning ng))
18597 (substring s (match-end ng))))))
18600 (defun org-recenter-calendar (date)
18601 "If the calendar is visible, recenter it to DATE."
18602 (let* ((win (selected-window))
18603 (cwin (get-buffer-window "*Calendar*" t))
18604 (calendar-move-hook nil))
18605 (when cwin
18606 (select-window cwin)
18607 (calendar-goto-date (if (listp date) date
18608 (calendar-gregorian-from-absolute date)))
18609 (select-window win))))
18611 (defun org-goto-calendar (&optional arg)
18612 "Go to the Emacs calendar at the current date.
18613 If there is a time stamp in the current line, go to that date.
18614 A prefix ARG can be used to force the current date."
18615 (interactive "P")
18616 (let ((tsr org-ts-regexp) diff
18617 (calendar-move-hook nil)
18618 (view-calendar-holidays-initially nil)
18619 (view-diary-entries-initially nil))
18620 (if (or (org-at-timestamp-p)
18621 (save-excursion
18622 (beginning-of-line 1)
18623 (looking-at (concat ".*" tsr))))
18624 (let ((d1 (time-to-days (current-time)))
18625 (d2 (time-to-days
18626 (org-time-string-to-time (match-string 1)))))
18627 (setq diff (- d2 d1))))
18628 (calendar)
18629 (calendar-goto-today)
18630 (if (and diff (not arg)) (calendar-forward-day diff))))
18632 (defun org-get-date-from-calendar ()
18633 "Return a list (month day year) of date at point in calendar."
18634 (with-current-buffer "*Calendar*"
18635 (save-match-data
18636 (calendar-cursor-to-date))))
18638 (defun org-date-from-calendar ()
18639 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18640 If there is already a time stamp at the cursor position, update it."
18641 (interactive)
18642 (if (org-at-timestamp-p t)
18643 (org-timestamp-change 0 'calendar)
18644 (let ((cal-date (org-get-date-from-calendar)))
18645 (org-insert-time-stamp
18646 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18648 (defvar appt-time-msg-list)
18650 ;;;###autoload
18651 (defun org-agenda-to-appt (&optional refresh filter)
18652 "Activate appointments found in `org-agenda-files'.
18653 With a \\[universal-argument] prefix, refresh the list of
18654 appointements.
18656 If FILTER is t, interactively prompt the user for a regular
18657 expression, and filter out entries that don't match it.
18659 If FILTER is a string, use this string as a regular expression
18660 for filtering entries out.
18662 FILTER can also be an alist with the car of each cell being
18663 either 'headline or 'category. For example:
18665 '((headline \"IMPORTANT\")
18666 (category \"Work\"))
18668 will only add headlines containing IMPORTANT or headlines
18669 belonging to the \"Work\" category."
18670 (interactive "P")
18671 (require 'calendar)
18672 (if refresh (setq appt-time-msg-list nil))
18673 (if (eq filter t)
18674 (setq filter (read-from-minibuffer "Regexp filter: ")))
18675 (let* ((cnt 0) ; count added events
18676 (org-agenda-new-buffers nil)
18677 (org-deadline-warning-days 0)
18678 (today (org-date-to-gregorian
18679 (time-to-days (current-time))))
18680 (files (org-agenda-files)) entries file)
18681 ;; Get all entries which may contain an appt
18682 (while (setq file (pop files))
18683 (setq entries
18684 (append entries
18685 (org-agenda-get-day-entries
18686 file today :timestamp :scheduled :deadline))))
18687 (setq entries (delq nil entries))
18688 ;; Map thru entries and find if we should filter them out
18689 (mapc
18690 (lambda(x)
18691 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18692 (cat (get-text-property 1 'org-category x))
18693 (tod (get-text-property 1 'time-of-day x))
18694 (ok (or (null filter)
18695 (and (stringp filter) (string-match filter evt))
18696 (and (listp filter)
18697 (or (string-match
18698 (cadr (assoc 'category filter)) cat)
18699 (string-match
18700 (cadr (assoc 'headline filter)) evt))))))
18701 ;; FIXME: Shall we remove text-properties for the appt text?
18702 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18703 (when (and ok tod)
18704 (setq tod (number-to-string tod)
18705 tod (when (string-match
18706 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18707 (concat (match-string 1 tod) ":"
18708 (match-string 2 tod))))
18709 (appt-add tod evt)
18710 (setq cnt (1+ cnt))))) entries)
18711 (org-release-buffers org-agenda-new-buffers)
18712 (if (eq cnt 0)
18713 (message "No event to add")
18714 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18716 ;;; The clock for measuring work time.
18718 (defvar org-mode-line-string "")
18719 (put 'org-mode-line-string 'risky-local-variable t)
18721 (defvar org-mode-line-timer nil)
18722 (defvar org-clock-heading "")
18723 (defvar org-clock-start-time "")
18725 (defun org-update-mode-line ()
18726 (let* ((delta (- (time-to-seconds (current-time))
18727 (time-to-seconds org-clock-start-time)))
18728 (h (floor delta 3600))
18729 (m (floor (- delta (* 3600 h)) 60)))
18730 (setq org-mode-line-string
18731 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18732 'help-echo "Org-mode clock is running"))
18733 (force-mode-line-update)))
18735 (defvar org-clock-marker (make-marker)
18736 "Marker recording the last clock-in.")
18737 (defvar org-clock-mode-line-entry nil
18738 "Information for the modeline about the running clock.")
18740 (defun org-clock-in ()
18741 "Start the clock on the current item.
18742 If necessary, clock-out of the currently active clock."
18743 (interactive)
18744 (org-clock-out t)
18745 (let (ts)
18746 (save-excursion
18747 (org-back-to-heading t)
18748 (when (and org-clock-in-switch-to-state
18749 (not (looking-at (concat outline-regexp "[ \t]*"
18750 org-clock-in-switch-to-state
18751 "\\>"))))
18752 (org-todo org-clock-in-switch-to-state))
18753 (if (and org-clock-heading-function
18754 (functionp org-clock-heading-function))
18755 (setq org-clock-heading (funcall org-clock-heading-function))
18756 (if (looking-at org-complex-heading-regexp)
18757 (setq org-clock-heading (match-string 4))
18758 (setq org-clock-heading "???")))
18759 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18760 (org-clock-find-position)
18762 (insert "\n") (backward-char 1)
18763 (indent-relative)
18764 (insert org-clock-string " ")
18765 (setq org-clock-start-time (current-time))
18766 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18767 (move-marker org-clock-marker (point) (buffer-base-buffer))
18768 (or global-mode-string (setq global-mode-string '("")))
18769 (or (memq 'org-mode-line-string global-mode-string)
18770 (setq global-mode-string
18771 (append global-mode-string '(org-mode-line-string))))
18772 (org-update-mode-line)
18773 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18774 (message "Clock started at %s" ts))))
18776 (defun org-clock-find-position ()
18777 "Find the location where the next clock line should be inserted."
18778 (org-back-to-heading t)
18779 (catch 'exit
18780 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18781 (re (concat "^[ \t]*" org-clock-string))
18782 (cnt 0)
18783 first last)
18784 (goto-char beg)
18785 (when (eobp) (newline) (setq end (max (point) end)))
18786 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18787 ;; we seem to have a CLOCK drawer, so go there.
18788 (beginning-of-line 2)
18789 (throw 'exit t))
18790 ;; Lets count the CLOCK lines
18791 (goto-char beg)
18792 (while (re-search-forward re end t)
18793 (setq first (or first (match-beginning 0))
18794 last (match-beginning 0)
18795 cnt (1+ cnt)))
18796 (when (and (integerp org-clock-into-drawer)
18797 (>= (1+ cnt) org-clock-into-drawer))
18798 ;; Wrap current entries into a new drawer
18799 (goto-char last)
18800 (beginning-of-line 2)
18801 (if (org-at-item-p) (org-end-of-item))
18802 (insert ":END:\n")
18803 (beginning-of-line 0)
18804 (org-indent-line-function)
18805 (goto-char first)
18806 (insert ":CLOCK:\n")
18807 (beginning-of-line 0)
18808 (org-indent-line-function)
18809 (org-flag-drawer t)
18810 (beginning-of-line 2)
18811 (throw 'exit nil))
18813 (goto-char beg)
18814 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18815 (not (equal (match-string 1) org-clock-string)))
18816 ;; Planning info, skip to after it
18817 (beginning-of-line 2)
18818 (or (bolp) (newline)))
18819 (when (eq t org-clock-into-drawer)
18820 (insert ":CLOCK:\n:END:\n")
18821 (beginning-of-line -1)
18822 (org-indent-line-function)
18823 (org-flag-drawer t)
18824 (beginning-of-line 2)
18825 (org-indent-line-function)))))
18827 (defun org-clock-out (&optional fail-quietly)
18828 "Stop the currently running clock.
18829 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18830 (interactive)
18831 (catch 'exit
18832 (if (not (marker-buffer org-clock-marker))
18833 (if fail-quietly (throw 'exit t) (error "No active clock")))
18834 (let (ts te s h m)
18835 (save-excursion
18836 (set-buffer (marker-buffer org-clock-marker))
18837 (goto-char org-clock-marker)
18838 (beginning-of-line 1)
18839 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18840 (equal (match-string 1) org-clock-string))
18841 (setq ts (match-string 2))
18842 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18843 (goto-char (match-end 0))
18844 (delete-region (point) (point-at-eol))
18845 (insert "--")
18846 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18847 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18848 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18849 h (floor (/ s 3600))
18850 s (- s (* 3600 h))
18851 m (floor (/ s 60))
18852 s (- s (* 60 s)))
18853 (insert " => " (format "%2d:%02d" h m))
18854 (move-marker org-clock-marker nil)
18855 (when org-log-note-clock-out
18856 (org-add-log-maybe 'clock-out))
18857 (when org-mode-line-timer
18858 (cancel-timer org-mode-line-timer)
18859 (setq org-mode-line-timer nil))
18860 (setq global-mode-string
18861 (delq 'org-mode-line-string global-mode-string))
18862 (force-mode-line-update)
18863 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18865 (defun org-clock-cancel ()
18866 "Cancel the running clock be removing the start timestamp."
18867 (interactive)
18868 (if (not (marker-buffer org-clock-marker))
18869 (error "No active clock"))
18870 (save-excursion
18871 (set-buffer (marker-buffer org-clock-marker))
18872 (goto-char org-clock-marker)
18873 (delete-region (1- (point-at-bol)) (point-at-eol)))
18874 (setq global-mode-string
18875 (delq 'org-mode-line-string global-mode-string))
18876 (force-mode-line-update)
18877 (message "Clock canceled"))
18879 (defun org-clock-goto (&optional delete-windows)
18880 "Go to the currently clocked-in entry."
18881 (interactive "P")
18882 (if (not (marker-buffer org-clock-marker))
18883 (error "No active clock"))
18884 (switch-to-buffer-other-window
18885 (marker-buffer org-clock-marker))
18886 (if delete-windows (delete-other-windows))
18887 (goto-char org-clock-marker)
18888 (org-show-entry)
18889 (org-back-to-heading)
18890 (recenter))
18892 (defvar org-clock-file-total-minutes nil
18893 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18894 (make-variable-buffer-local 'org-clock-file-total-minutes)
18896 (defun org-clock-sum (&optional tstart tend)
18897 "Sum the times for each subtree.
18898 Puts the resulting times in minutes as a text property on each headline."
18899 (interactive)
18900 (let* ((bmp (buffer-modified-p))
18901 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18902 org-clock-string
18903 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18904 (lmax 30)
18905 (ltimes (make-vector lmax 0))
18906 (t1 0)
18907 (level 0)
18908 ts te dt
18909 time)
18910 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18911 (save-excursion
18912 (goto-char (point-max))
18913 (while (re-search-backward re nil t)
18914 (cond
18915 ((match-end 2)
18916 ;; Two time stamps
18917 (setq ts (match-string 2)
18918 te (match-string 3)
18919 ts (time-to-seconds
18920 (apply 'encode-time (org-parse-time-string ts)))
18921 te (time-to-seconds
18922 (apply 'encode-time (org-parse-time-string te)))
18923 ts (if tstart (max ts tstart) ts)
18924 te (if tend (min te tend) te)
18925 dt (- te ts)
18926 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18927 ((match-end 4)
18928 ;; A naket time
18929 (setq t1 (+ t1 (string-to-number (match-string 5))
18930 (* 60 (string-to-number (match-string 4))))))
18931 (t ;; A headline
18932 (setq level (- (match-end 1) (match-beginning 1)))
18933 (when (or (> t1 0) (> (aref ltimes level) 0))
18934 (loop for l from 0 to level do
18935 (aset ltimes l (+ (aref ltimes l) t1)))
18936 (setq t1 0 time (aref ltimes level))
18937 (loop for l from level to (1- lmax) do
18938 (aset ltimes l 0))
18939 (goto-char (match-beginning 0))
18940 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18941 (setq org-clock-file-total-minutes (aref ltimes 0)))
18942 (set-buffer-modified-p bmp)))
18944 (defun org-clock-display (&optional total-only)
18945 "Show subtree times in the entire buffer.
18946 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18947 in the echo area."
18948 (interactive)
18949 (org-remove-clock-overlays)
18950 (let (time h m p)
18951 (org-clock-sum)
18952 (unless total-only
18953 (save-excursion
18954 (goto-char (point-min))
18955 (while (or (and (equal (setq p (point)) (point-min))
18956 (get-text-property p :org-clock-minutes))
18957 (setq p (next-single-property-change
18958 (point) :org-clock-minutes)))
18959 (goto-char p)
18960 (when (setq time (get-text-property p :org-clock-minutes))
18961 (org-put-clock-overlay time (funcall outline-level))))
18962 (setq h (/ org-clock-file-total-minutes 60)
18963 m (- org-clock-file-total-minutes (* 60 h)))
18964 ;; Arrange to remove the overlays upon next change.
18965 (when org-remove-highlights-with-change
18966 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18967 nil 'local))))
18968 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18970 (defvar org-clock-overlays nil)
18971 (make-variable-buffer-local 'org-clock-overlays)
18973 (defun org-put-clock-overlay (time &optional level)
18974 "Put an overlays on the current line, displaying TIME.
18975 If LEVEL is given, prefix time with a corresponding number of stars.
18976 This creates a new overlay and stores it in `org-clock-overlays', so that it
18977 will be easy to remove."
18978 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18979 (l (if level (org-get-legal-level level 0) 0))
18980 (off 0)
18981 ov tx)
18982 (move-to-column c)
18983 (unless (eolp) (skip-chars-backward "^ \t"))
18984 (skip-chars-backward " \t")
18985 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18986 tx (concat (buffer-substring (1- (point)) (point))
18987 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18988 (org-add-props (format "%s %2d:%02d%s"
18989 (make-string l ?*) h m
18990 (make-string (- 16 l) ?\ ))
18991 '(face secondary-selection))
18992 ""))
18993 (if (not (featurep 'xemacs))
18994 (org-overlay-put ov 'display tx)
18995 (org-overlay-put ov 'invisible t)
18996 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18997 (push ov org-clock-overlays)))
18999 (defun org-remove-clock-overlays (&optional beg end noremove)
19000 "Remove the occur highlights from the buffer.
19001 BEG and END are ignored. If NOREMOVE is nil, remove this function
19002 from the `before-change-functions' in the current buffer."
19003 (interactive)
19004 (unless org-inhibit-highlight-removal
19005 (mapc 'org-delete-overlay org-clock-overlays)
19006 (setq org-clock-overlays nil)
19007 (unless noremove
19008 (remove-hook 'before-change-functions
19009 'org-remove-clock-overlays 'local))))
19011 (defun org-clock-out-if-current ()
19012 "Clock out if the current entry contains the running clock.
19013 This is used to stop the clock after a TODO entry is marked DONE,
19014 and is only done if the variable `org-clock-out-when-done' is not nil."
19015 (when (and org-clock-out-when-done
19016 (member state org-done-keywords)
19017 (equal (marker-buffer org-clock-marker) (current-buffer))
19018 (< (point) org-clock-marker)
19019 (> (save-excursion (outline-next-heading) (point))
19020 org-clock-marker))
19021 ;; Clock out, but don't accept a logging message for this.
19022 (let ((org-log-note-clock-out nil))
19023 (org-clock-out))))
19025 (add-hook 'org-after-todo-state-change-hook
19026 'org-clock-out-if-current)
19028 (defun org-check-running-clock ()
19029 "Check if the current buffer contains the running clock.
19030 If yes, offer to stop it and to save the buffer with the changes."
19031 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19032 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19033 (buffer-name))))
19034 (org-clock-out)
19035 (when (y-or-n-p "Save changed buffer?")
19036 (save-buffer))))
19038 (defun org-clock-report (&optional arg)
19039 "Create a table containing a report about clocked time.
19040 If the cursor is inside an existing clocktable block, then the table
19041 will be updated. If not, a new clocktable will be inserted.
19042 When called with a prefix argument, move to the first clock table in the
19043 buffer and update it."
19044 (interactive "P")
19045 (org-remove-clock-overlays)
19046 (when arg
19047 (org-find-dblock "clocktable")
19048 (org-show-entry))
19049 (if (org-in-clocktable-p)
19050 (goto-char (org-in-clocktable-p))
19051 (org-create-dblock (list :name "clocktable"
19052 :maxlevel 2 :scope 'file)))
19053 (org-update-dblock))
19055 (defun org-in-clocktable-p ()
19056 "Check if the cursor is in a clocktable."
19057 (let ((pos (point)) start)
19058 (save-excursion
19059 (end-of-line 1)
19060 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19061 (setq start (match-beginning 0))
19062 (re-search-forward "^#\\+END:.*" nil t)
19063 (>= (match-end 0) pos)
19064 start))))
19066 (defun org-clock-update-time-maybe ()
19067 "If this is a CLOCK line, update it and return t.
19068 Otherwise, return nil."
19069 (interactive)
19070 (save-excursion
19071 (beginning-of-line 1)
19072 (skip-chars-forward " \t")
19073 (when (looking-at org-clock-string)
19074 (let ((re (concat "[ \t]*" org-clock-string
19075 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19076 "\\([ \t]*=>.*\\)?"))
19077 ts te h m s)
19078 (if (not (looking-at re))
19080 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19081 (end-of-line 1)
19082 (setq ts (match-string 1)
19083 te (match-string 2))
19084 (setq s (- (time-to-seconds
19085 (apply 'encode-time (org-parse-time-string te)))
19086 (time-to-seconds
19087 (apply 'encode-time (org-parse-time-string ts))))
19088 h (floor (/ s 3600))
19089 s (- s (* 3600 h))
19090 m (floor (/ s 60))
19091 s (- s (* 60 s)))
19092 (insert " => " (format "%2d:%02d" h m))
19093 t)))))
19095 (defun org-clock-special-range (key &optional time as-strings)
19096 "Return two times bordering a special time range.
19097 Key is a symbol specifying the range and can be one of `today', `yesterday',
19098 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19099 A week starts Monday 0:00 and ends Sunday 24:00.
19100 The range is determined relative to TIME. TIME defaults to the current time.
19101 The return value is a cons cell with two internal times like the ones
19102 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19103 the returned times will be formatted strings."
19104 (let* ((tm (decode-time (or time (current-time))))
19105 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19106 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19107 (dow (nth 6 tm))
19108 s1 m1 h1 d1 month1 y1 diff ts te fm)
19109 (cond
19110 ((eq key 'today)
19111 (setq h 0 m 0 h1 24 m1 0))
19112 ((eq key 'yesterday)
19113 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19114 ((eq key 'thisweek)
19115 (setq diff (if (= dow 0) 6 (1- dow))
19116 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19117 ((eq key 'lastweek)
19118 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19119 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19120 ((eq key 'thismonth)
19121 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19122 ((eq key 'lastmonth)
19123 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19124 ((eq key 'thisyear)
19125 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19126 ((eq key 'lastyear)
19127 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19128 (t (error "No such time block %s" key)))
19129 (setq ts (encode-time s m h d month y)
19130 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19131 (or d1 d) (or month1 month) (or y1 y)))
19132 (setq fm (cdr org-time-stamp-formats))
19133 (if as-strings
19134 (cons (format-time-string fm ts) (format-time-string fm te))
19135 (cons ts te))))
19137 (defun org-dblock-write:clocktable (params)
19138 "Write the standard clocktable."
19139 (catch 'exit
19140 (let* ((hlchars '((1 . "*") (2 . "/")))
19141 (ins (make-marker))
19142 (total-time nil)
19143 (scope (plist-get params :scope))
19144 (tostring (plist-get params :tostring))
19145 (multifile (plist-get params :multifile))
19146 (header (plist-get params :header))
19147 (maxlevel (or (plist-get params :maxlevel) 3))
19148 (step (plist-get params :step))
19149 (emph (plist-get params :emphasize))
19150 (ts (plist-get params :tstart))
19151 (te (plist-get params :tend))
19152 (block (plist-get params :block))
19153 ipos time h m p level hlc hdl
19154 cc beg end pos tbl)
19155 (when step
19156 (org-clocktable-steps params)
19157 (throw 'exit nil))
19158 (when block
19159 (setq cc (org-clock-special-range block nil t)
19160 ts (car cc) te (cdr cc)))
19161 (if ts (setq ts (time-to-seconds
19162 (apply 'encode-time (org-parse-time-string ts)))))
19163 (if te (setq te (time-to-seconds
19164 (apply 'encode-time (org-parse-time-string te)))))
19165 (move-marker ins (point))
19166 (setq ipos (point))
19168 ;; Get the right scope
19169 (setq pos (point))
19170 (save-restriction
19171 (cond
19172 ((not scope))
19173 ((eq scope 'file) (widen))
19174 ((eq scope 'subtree) (org-narrow-to-subtree))
19175 ((eq scope 'tree)
19176 (while (org-up-heading-safe))
19177 (org-narrow-to-subtree))
19178 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19179 (symbol-name scope)))
19180 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19181 (catch 'exit
19182 (while (org-up-heading-safe)
19183 (looking-at outline-regexp)
19184 (if (<= (org-reduced-level (funcall outline-level)) level)
19185 (throw 'exit nil))))
19186 (org-narrow-to-subtree))
19187 ((or (listp scope) (eq scope 'agenda))
19188 (let* ((files (if (listp scope) scope (org-agenda-files)))
19189 (scope 'agenda)
19190 (p1 (copy-sequence params))
19191 file)
19192 (plist-put p1 :tostring t)
19193 (plist-put p1 :multifile t)
19194 (plist-put p1 :scope 'file)
19195 (org-prepare-agenda-buffers files)
19196 (while (setq file (pop files))
19197 (with-current-buffer (find-buffer-visiting file)
19198 (push (org-clocktable-add-file
19199 file (org-dblock-write:clocktable p1)) tbl)
19200 (setq total-time (+ (or total-time 0)
19201 org-clock-file-total-minutes)))))))
19202 (goto-char pos)
19204 (unless (eq scope 'agenda)
19205 (org-clock-sum ts te)
19206 (goto-char (point-min))
19207 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19208 (goto-char p)
19209 (when (setq time (get-text-property p :org-clock-minutes))
19210 (save-excursion
19211 (beginning-of-line 1)
19212 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19213 (setq level (org-reduced-level
19214 (- (match-end 1) (match-beginning 1))))
19215 (<= level maxlevel))
19216 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19217 hdl (match-string 2)
19218 h (/ time 60)
19219 m (- time (* 60 h)))
19220 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19221 (push (concat
19222 "| " (int-to-string level) "|" hlc hdl hlc " |"
19223 (make-string (1- level) ?|)
19224 hlc (format "%d:%02d" h m) hlc
19225 " |") tbl))))))
19226 (setq tbl (nreverse tbl))
19227 (if tostring
19228 (if tbl (mapconcat 'identity tbl "\n") nil)
19229 (goto-char ins)
19230 (insert-before-markers
19231 (or header
19232 (concat
19233 "Clock summary at ["
19234 (substring
19235 (format-time-string (cdr org-time-stamp-formats))
19236 1 -1)
19237 "]."
19238 (if block
19239 (format " Considered range is /%s/." block)
19241 "\n\n"))
19242 (if (eq scope 'agenda) "|File" "")
19243 "|L|Headline|Time|\n")
19244 (setq total-time (or total-time org-clock-file-total-minutes)
19245 h (/ total-time 60)
19246 m (- total-time (* 60 h)))
19247 (insert-before-markers
19248 "|-\n|"
19249 (if (eq scope 'agenda) "|" "")
19251 "*Total time*| "
19252 (format "*%d:%02d*" h m)
19253 "|\n|-\n")
19254 (setq tbl (delq nil tbl))
19255 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19256 (equal (substring (car tbl) 0 2) "|-"))
19257 (pop tbl))
19258 (insert-before-markers (mapconcat
19259 'identity (delq nil tbl)
19260 (if (eq scope 'agenda) "\n|-\n" "\n")))
19261 (backward-delete-char 1)
19262 (goto-char ipos)
19263 (skip-chars-forward "^|")
19264 (org-table-align))))))
19266 (defun org-clocktable-steps (params)
19267 (let* ((p1 (copy-sequence params))
19268 (ts (plist-get p1 :tstart))
19269 (te (plist-get p1 :tend))
19270 (step0 (plist-get p1 :step))
19271 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19272 (block (plist-get p1 :block))
19274 (when block
19275 (setq cc (org-clock-special-range block nil t)
19276 ts (car cc) te (cdr cc)))
19277 (if ts (setq ts (time-to-seconds
19278 (apply 'encode-time (org-parse-time-string ts)))))
19279 (if te (setq te (time-to-seconds
19280 (apply 'encode-time (org-parse-time-string te)))))
19281 (plist-put p1 :header "")
19282 (plist-put p1 :step nil)
19283 (plist-put p1 :block nil)
19284 (while (< ts te)
19285 (or (bolp) (insert "\n"))
19286 (plist-put p1 :tstart (format-time-string
19287 (car org-time-stamp-formats)
19288 (seconds-to-time ts)))
19289 (plist-put p1 :tend (format-time-string
19290 (car org-time-stamp-formats)
19291 (seconds-to-time (setq ts (+ ts step)))))
19292 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19293 (plist-get p1 :tstart) "\n")
19294 (org-dblock-write:clocktable p1)
19295 (re-search-forward "#\\+END:")
19296 (end-of-line 0))))
19299 (defun org-clocktable-add-file (file table)
19300 (if table
19301 (let ((lines (org-split-string table "\n"))
19302 (ff (file-name-nondirectory file)))
19303 (mapconcat 'identity
19304 (mapcar (lambda (x)
19305 (if (string-match org-table-dataline-regexp x)
19306 (concat "|" ff x)
19308 lines)
19309 "\n"))))
19311 ;; FIXME: I don't think anybody uses this, ask David
19312 (defun org-collect-clock-time-entries ()
19313 "Return an internal list with clocking information.
19314 This list has one entry for each CLOCK interval.
19315 FIXME: describe the elements."
19316 (interactive)
19317 (let ((re (concat "^[ \t]*" org-clock-string
19318 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19319 rtn beg end next cont level title total closedp leafp
19320 clockpos titlepos h m donep)
19321 (save-excursion
19322 (org-clock-sum)
19323 (goto-char (point-min))
19324 (while (re-search-forward re nil t)
19325 (setq clockpos (match-beginning 0)
19326 beg (match-string 1) end (match-string 2)
19327 cont (match-end 0))
19328 (setq beg (apply 'encode-time (org-parse-time-string beg))
19329 end (apply 'encode-time (org-parse-time-string end)))
19330 (org-back-to-heading t)
19331 (setq donep (org-entry-is-done-p))
19332 (setq titlepos (point)
19333 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19334 h (/ total 60) m (- total (* 60 h))
19335 total (cons h m))
19336 (looking-at "\\(\\*+\\) +\\(.*\\)")
19337 (setq level (- (match-end 1) (match-beginning 1))
19338 title (org-match-string-no-properties 2))
19339 (save-excursion (outline-next-heading) (setq next (point)))
19340 (setq closedp (re-search-forward org-closed-time-regexp next t))
19341 (goto-char next)
19342 (setq leafp (and (looking-at "^\\*+ ")
19343 (<= (- (match-end 0) (point)) level)))
19344 (push (list beg end clockpos closedp donep
19345 total title titlepos level leafp)
19346 rtn)
19347 (goto-char cont)))
19348 (nreverse rtn)))
19350 ;;;; Agenda, and Diary Integration
19352 ;;; Define the Org-agenda-mode
19354 (defvar org-agenda-mode-map (make-sparse-keymap)
19355 "Keymap for `org-agenda-mode'.")
19357 (defvar org-agenda-menu) ; defined later in this file.
19358 (defvar org-agenda-follow-mode nil)
19359 (defvar org-agenda-show-log nil)
19360 (defvar org-agenda-redo-command nil)
19361 (defvar org-agenda-query-string nil)
19362 (defvar org-agenda-mode-hook nil)
19363 (defvar org-agenda-type nil)
19364 (defvar org-agenda-force-single-file nil)
19366 (defun org-agenda-mode ()
19367 "Mode for time-sorted view on action items in Org-mode files.
19369 The following commands are available:
19371 \\{org-agenda-mode-map}"
19372 (interactive)
19373 (kill-all-local-variables)
19374 (setq org-agenda-undo-list nil
19375 org-agenda-pending-undo-list nil)
19376 (setq major-mode 'org-agenda-mode)
19377 ;; Keep global-font-lock-mode from turning on font-lock-mode
19378 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19379 (setq mode-name "Org-Agenda")
19380 (use-local-map org-agenda-mode-map)
19381 (easy-menu-add org-agenda-menu)
19382 (if org-startup-truncated (setq truncate-lines t))
19383 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19384 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19385 ;; Make sure properties are removed when copying text
19386 (when (boundp 'buffer-substring-filters)
19387 (org-set-local 'buffer-substring-filters
19388 (cons (lambda (x)
19389 (set-text-properties 0 (length x) nil x) x)
19390 buffer-substring-filters)))
19391 (unless org-agenda-keep-modes
19392 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19393 org-agenda-show-log nil))
19394 (easy-menu-change
19395 '("Agenda") "Agenda Files"
19396 (append
19397 (list
19398 (vector
19399 (if (get 'org-agenda-files 'org-restrict)
19400 "Restricted to single file"
19401 "Edit File List")
19402 '(org-edit-agenda-file-list)
19403 (not (get 'org-agenda-files 'org-restrict)))
19404 "--")
19405 (mapcar 'org-file-menu-entry (org-agenda-files))))
19406 (org-agenda-set-mode-name)
19407 (apply
19408 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19409 (list 'org-agenda-mode-hook)))
19411 (substitute-key-definition 'undo 'org-agenda-undo
19412 org-agenda-mode-map global-map)
19413 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19414 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19415 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19416 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19417 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19418 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19419 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19420 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19421 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19422 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19423 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19424 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19425 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19426 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19427 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19428 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19429 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19430 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19431 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19432 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19433 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19434 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19435 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19436 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19437 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19438 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19439 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19440 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19441 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19443 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19444 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19445 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19446 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19447 (while l (org-defkey org-agenda-mode-map
19448 (int-to-string (pop l)) 'digit-argument)))
19450 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19451 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19452 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19453 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19454 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19455 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19456 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19457 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19458 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19459 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19460 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19461 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19462 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19463 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19464 (org-defkey org-agenda-mode-map "n" 'next-line)
19465 (org-defkey org-agenda-mode-map "p" 'previous-line)
19466 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19467 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19468 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19469 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19470 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19471 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19472 (eval-after-load "calendar"
19473 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19474 'org-calendar-goto-agenda))
19475 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19476 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19477 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19478 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19479 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19480 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19481 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19482 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19483 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19484 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19485 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19486 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19487 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19488 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19489 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19490 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19491 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19492 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19493 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19494 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19495 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19496 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19498 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19499 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19500 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19501 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19503 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19504 "Local keymap for agenda entries from Org-mode.")
19506 (org-defkey org-agenda-keymap
19507 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19508 (org-defkey org-agenda-keymap
19509 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19510 (when org-agenda-mouse-1-follows-link
19511 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19512 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19513 '("Agenda"
19514 ("Agenda Files")
19515 "--"
19516 ["Show" org-agenda-show t]
19517 ["Go To (other window)" org-agenda-goto t]
19518 ["Go To (this window)" org-agenda-switch-to t]
19519 ["Follow Mode" org-agenda-follow-mode
19520 :style toggle :selected org-agenda-follow-mode :active t]
19521 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19522 "--"
19523 ["Cycle TODO" org-agenda-todo t]
19524 ["Archive subtree" org-agenda-archive t]
19525 ["Delete subtree" org-agenda-kill t]
19526 "--"
19527 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19528 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19529 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19530 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19531 "--"
19532 ("Tags and Properties"
19533 ["Show all Tags" org-agenda-show-tags t]
19534 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19535 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19536 "--"
19537 ["Column View" org-columns t])
19538 ("Date/Schedule"
19539 ["Schedule" org-agenda-schedule t]
19540 ["Set Deadline" org-agenda-deadline t]
19541 "--"
19542 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19543 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19544 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19545 ("Clock"
19546 ["Clock in" org-agenda-clock-in t]
19547 ["Clock out" org-agenda-clock-out t]
19548 ["Clock cancel" org-agenda-clock-cancel t]
19549 ["Goto running clock" org-clock-goto t])
19550 ("Priority"
19551 ["Set Priority" org-agenda-priority t]
19552 ["Increase Priority" org-agenda-priority-up t]
19553 ["Decrease Priority" org-agenda-priority-down t]
19554 ["Show Priority" org-agenda-show-priority t])
19555 ("Calendar/Diary"
19556 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19557 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19558 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19559 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19560 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19561 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19562 "--"
19563 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19564 "--"
19565 ("View"
19566 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19567 :style radio :selected (equal org-agenda-ndays 1)]
19568 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19569 :style radio :selected (equal org-agenda-ndays 7)]
19570 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19571 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19572 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19573 :style radio :selected (member org-agenda-ndays '(365 366))]
19574 "--"
19575 ["Show Logbook entries" org-agenda-log-mode
19576 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19577 ["Include Diary" org-agenda-toggle-diary
19578 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19579 ["Use Time Grid" org-agenda-toggle-time-grid
19580 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19581 ["Write view to file" org-write-agenda t]
19582 ["Rebuild buffer" org-agenda-redo t]
19583 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19584 "--"
19585 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19586 "--"
19587 ["Quit" org-agenda-quit t]
19588 ["Exit and Release Buffers" org-agenda-exit t]
19591 ;;; Agenda undo
19593 (defvar org-agenda-allow-remote-undo t
19594 "Non-nil means, allow remote undo from the agenda buffer.")
19595 (defvar org-agenda-undo-list nil
19596 "List of undoable operations in the agenda since last refresh.")
19597 (defvar org-agenda-undo-has-started-in nil
19598 "Buffers that have already seen `undo-start' in the current undo sequence.")
19599 (defvar org-agenda-pending-undo-list nil
19600 "In a series of undo commands, this is the list of remaning undo items.")
19602 (defmacro org-if-unprotected (&rest body)
19603 "Execute BODY if there is no `org-protected' text property at point."
19604 (declare (debug t))
19605 `(unless (get-text-property (point) 'org-protected)
19606 ,@body))
19608 (defmacro org-with-remote-undo (_buffer &rest _body)
19609 "Execute BODY while recording undo information in two buffers."
19610 (declare (indent 1) (debug t))
19611 `(let ((_cline (org-current-line))
19612 (_cmd this-command)
19613 (_buf1 (current-buffer))
19614 (_buf2 ,_buffer)
19615 (_undo1 buffer-undo-list)
19616 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19617 _c1 _c2)
19618 ,@_body
19619 (when org-agenda-allow-remote-undo
19620 (setq _c1 (org-verify-change-for-undo
19621 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19622 _c2 (org-verify-change-for-undo
19623 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19624 (when (or _c1 _c2)
19625 ;; make sure there are undo boundaries
19626 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19627 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19628 ;; remember which buffer to undo
19629 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19630 org-agenda-undo-list)))))
19632 (defun org-agenda-undo ()
19633 "Undo a remote editing step in the agenda.
19634 This undoes changes both in the agenda buffer and in the remote buffer
19635 that have been changed along."
19636 (interactive)
19637 (or org-agenda-allow-remote-undo
19638 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19639 (if (not (eq this-command last-command))
19640 (setq org-agenda-undo-has-started-in nil
19641 org-agenda-pending-undo-list org-agenda-undo-list))
19642 (if (not org-agenda-pending-undo-list)
19643 (error "No further undo information"))
19644 (let* ((entry (pop org-agenda-pending-undo-list))
19645 buf line cmd rembuf)
19646 (setq cmd (pop entry) line (pop entry))
19647 (setq rembuf (nth 2 entry))
19648 (org-with-remote-undo rembuf
19649 (while (bufferp (setq buf (pop entry)))
19650 (if (pop entry)
19651 (with-current-buffer buf
19652 (let ((last-undo-buffer buf)
19653 (inhibit-read-only t))
19654 (unless (memq buf org-agenda-undo-has-started-in)
19655 (push buf org-agenda-undo-has-started-in)
19656 (make-local-variable 'pending-undo-list)
19657 (undo-start))
19658 (while (and pending-undo-list
19659 (listp pending-undo-list)
19660 (not (car pending-undo-list)))
19661 (pop pending-undo-list))
19662 (undo-more 1))))))
19663 (goto-line line)
19664 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19666 (defun org-verify-change-for-undo (l1 l2)
19667 "Verify that a real change occurred between the undo lists L1 and L2."
19668 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19669 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19670 (not (eq l1 l2)))
19672 ;;; Agenda dispatch
19674 (defvar org-agenda-restrict nil)
19675 (defvar org-agenda-restrict-begin (make-marker))
19676 (defvar org-agenda-restrict-end (make-marker))
19677 (defvar org-agenda-last-dispatch-buffer nil)
19678 (defvar org-agenda-overriding-restriction nil)
19680 ;;;###autoload
19681 (defun org-agenda (arg &optional keys restriction)
19682 "Dispatch agenda commands to collect entries to the agenda buffer.
19683 Prompts for a command to execute. Any prefix arg will be passed
19684 on to the selected command. The default selections are:
19686 a Call `org-agenda-list' to display the agenda for current day or week.
19687 t Call `org-todo-list' to display the global todo list.
19688 T Call `org-todo-list' to display the global todo list, select only
19689 entries with a specific TODO keyword (the user gets a prompt).
19690 m Call `org-tags-view' to display headlines with tags matching
19691 a condition (the user is prompted for the condition).
19692 M Like `m', but select only TODO entries, no ordinary headlines.
19693 L Create a timeline for the current buffer.
19694 e Export views to associated files.
19696 More commands can be added by configuring the variable
19697 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19698 searches can be pre-defined in this way.
19700 If the current buffer is in Org-mode and visiting a file, you can also
19701 first press `<' once to indicate that the agenda should be temporarily
19702 \(until the next use of \\[org-agenda]) restricted to the current file.
19703 Pressing `<' twice means to restrict to the current subtree or region
19704 \(if active)."
19705 (interactive "P")
19706 (catch 'exit
19707 (let* ((prefix-descriptions nil)
19708 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19709 (org-agenda-custom-commands
19710 ;; normalize different versions
19711 (delq nil
19712 (mapcar
19713 (lambda (x)
19714 (cond ((stringp (cdr x))
19715 (push x prefix-descriptions)
19716 nil)
19717 ((stringp (nth 1 x)) x)
19718 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19719 (t (cons (car x) (cons "" (cdr x))))))
19720 org-agenda-custom-commands)))
19721 (buf (current-buffer))
19722 (bfn (buffer-file-name (buffer-base-buffer)))
19723 entry key type match lprops ans)
19724 ;; Turn off restriction unless there is an overriding one
19725 (unless org-agenda-overriding-restriction
19726 (put 'org-agenda-files 'org-restrict nil)
19727 (setq org-agenda-restrict nil)
19728 (move-marker org-agenda-restrict-begin nil)
19729 (move-marker org-agenda-restrict-end nil))
19730 ;; Delete old local properties
19731 (put 'org-agenda-redo-command 'org-lprops nil)
19732 ;; Remember where this call originated
19733 (setq org-agenda-last-dispatch-buffer (current-buffer))
19734 (unless keys
19735 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19736 keys (car ans)
19737 restriction (cdr ans)))
19738 ;; Estabish the restriction, if any
19739 (when (and (not org-agenda-overriding-restriction) restriction)
19740 (put 'org-agenda-files 'org-restrict (list bfn))
19741 (cond
19742 ((eq restriction 'region)
19743 (setq org-agenda-restrict t)
19744 (move-marker org-agenda-restrict-begin (region-beginning))
19745 (move-marker org-agenda-restrict-end (region-end)))
19746 ((eq restriction 'subtree)
19747 (save-excursion
19748 (setq org-agenda-restrict t)
19749 (org-back-to-heading t)
19750 (move-marker org-agenda-restrict-begin (point))
19751 (move-marker org-agenda-restrict-end
19752 (progn (org-end-of-subtree t)))))))
19754 (require 'calendar) ; FIXME: can we avoid this for some commands?
19755 ;; For example the todo list should not need it (but does...)
19756 (cond
19757 ((setq entry (assoc keys org-agenda-custom-commands))
19758 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19759 (progn
19760 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19761 (put 'org-agenda-redo-command 'org-lprops lprops)
19762 (cond
19763 ((eq type 'agenda)
19764 (org-let lprops '(org-agenda-list current-prefix-arg)))
19765 ((eq type 'alltodo)
19766 (org-let lprops '(org-todo-list current-prefix-arg)))
19767 ((eq type 'search)
19768 (org-let lprops '(org-search-view current-prefix-arg match)))
19769 ((eq type 'stuck)
19770 (org-let lprops '(org-agenda-list-stuck-projects
19771 current-prefix-arg)))
19772 ((eq type 'tags)
19773 (org-let lprops '(org-tags-view current-prefix-arg match)))
19774 ((eq type 'tags-todo)
19775 (org-let lprops '(org-tags-view '(4) match)))
19776 ((eq type 'todo)
19777 (org-let lprops '(org-todo-list match)))
19778 ((eq type 'tags-tree)
19779 (org-check-for-org-mode)
19780 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19781 ((eq type 'todo-tree)
19782 (org-check-for-org-mode)
19783 (org-let lprops
19784 '(org-occur (concat "^" outline-regexp "[ \t]*"
19785 (regexp-quote match) "\\>"))))
19786 ((eq type 'occur-tree)
19787 (org-check-for-org-mode)
19788 (org-let lprops '(org-occur match)))
19789 ((functionp type)
19790 (org-let lprops '(funcall type match)))
19791 ((fboundp type)
19792 (org-let lprops '(funcall type match)))
19793 (t (error "Invalid custom agenda command type %s" type))))
19794 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19795 ((equal keys "C")
19796 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19797 (customize-variable 'org-agenda-custom-commands))
19798 ((equal keys "a") (call-interactively 'org-agenda-list))
19799 ((equal keys "s") (call-interactively 'org-search-view))
19800 ((equal keys "t") (call-interactively 'org-todo-list))
19801 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19802 ((equal keys "m") (call-interactively 'org-tags-view))
19803 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19804 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19805 ((equal keys "L")
19806 (unless (org-mode-p)
19807 (error "This is not an Org-mode file"))
19808 (unless restriction
19809 (put 'org-agenda-files 'org-restrict (list bfn))
19810 (org-call-with-arg 'org-timeline arg)))
19811 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19812 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19813 ((equal keys "!") (customize-variable 'org-stuck-projects))
19814 (t (error "Invalid agenda key"))))))
19816 (defun org-agenda-normalize-custom-commands (cmds)
19817 (delq nil
19818 (mapcar
19819 (lambda (x)
19820 (cond ((stringp (cdr x)) nil)
19821 ((stringp (nth 1 x)) x)
19822 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19823 (t (cons (car x) (cons "" (cdr x))))))
19824 cmds)))
19826 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19827 "The user interface for selecting an agenda command."
19828 (catch 'exit
19829 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19830 (restrict-ok (and bfn (org-mode-p)))
19831 (region-p (org-region-active-p))
19832 (custom org-agenda-custom-commands)
19833 (selstring "")
19834 restriction second-time
19835 c entry key type match prefixes rmheader header-end custom1 desc)
19836 (save-window-excursion
19837 (delete-other-windows)
19838 (org-switch-to-buffer-other-window " *Agenda Commands*")
19839 (erase-buffer)
19840 (insert (eval-when-compile
19841 (let ((header
19843 Press key for an agenda command: < Buffer,subtree/region restriction
19844 -------------------------------- > Remove restriction
19845 a Agenda for current week or day e Export agenda views
19846 t List of all TODO entries T Entries with special TODO kwd
19847 m Match a TAGS query M Like m, but only TODO entries
19848 L Timeline for current buffer # List stuck projects (!=configure)
19849 s Search for keywords C Configure custom agenda commands
19850 / Multi-occur
19852 (start 0))
19853 (while (string-match
19854 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19855 header start)
19856 (setq start (match-end 0))
19857 (add-text-properties (match-beginning 2) (match-end 2)
19858 '(face bold) header))
19859 header)))
19860 (setq header-end (move-marker (make-marker) (point)))
19861 (while t
19862 (setq custom1 custom)
19863 (when (eq rmheader t)
19864 (goto-line 1)
19865 (re-search-forward ":" nil t)
19866 (delete-region (match-end 0) (point-at-eol))
19867 (forward-char 1)
19868 (looking-at "-+")
19869 (delete-region (match-end 0) (point-at-eol))
19870 (move-marker header-end (match-end 0)))
19871 (goto-char header-end)
19872 (delete-region (point) (point-max))
19873 (while (setq entry (pop custom1))
19874 (setq key (car entry) desc (nth 1 entry)
19875 type (nth 2 entry) match (nth 3 entry))
19876 (if (> (length key) 1)
19877 (add-to-list 'prefixes (string-to-char key))
19878 (insert
19879 (format
19880 "\n%-4s%-14s: %s"
19881 (org-add-props (copy-sequence key)
19882 '(face bold))
19883 (cond
19884 ((string-match "\\S-" desc) desc)
19885 ((eq type 'agenda) "Agenda for current week or day")
19886 ((eq type 'alltodo) "List of all TODO entries")
19887 ((eq type 'search) "Word search")
19888 ((eq type 'stuck) "List of stuck projects")
19889 ((eq type 'todo) "TODO keyword")
19890 ((eq type 'tags) "Tags query")
19891 ((eq type 'tags-todo) "Tags (TODO)")
19892 ((eq type 'tags-tree) "Tags tree")
19893 ((eq type 'todo-tree) "TODO kwd tree")
19894 ((eq type 'occur-tree) "Occur tree")
19895 ((functionp type) (if (symbolp type)
19896 (symbol-name type)
19897 "Lambda expression"))
19898 (t "???"))
19899 (cond
19900 ((stringp match)
19901 (org-add-props match nil 'face 'org-warning))
19902 (match
19903 (format "set of %d commands" (length match)))
19904 (t ""))))))
19905 (when prefixes
19906 (mapc (lambda (x)
19907 (insert
19908 (format "\n%s %s"
19909 (org-add-props (char-to-string x)
19910 nil 'face 'bold)
19911 (or (cdr (assoc (concat selstring (char-to-string x))
19912 prefix-descriptions))
19913 "Prefix key"))))
19914 prefixes))
19915 (goto-char (point-min))
19916 (when (fboundp 'fit-window-to-buffer)
19917 (if second-time
19918 (if (not (pos-visible-in-window-p (point-max)))
19919 (fit-window-to-buffer))
19920 (setq second-time t)
19921 (fit-window-to-buffer)))
19922 (message "Press key for agenda command%s:"
19923 (if (or restrict-ok org-agenda-overriding-restriction)
19924 (if org-agenda-overriding-restriction
19925 " (restriction lock active)"
19926 (if restriction
19927 (format " (restricted to %s)" restriction)
19928 " (unrestricted)"))
19929 ""))
19930 (setq c (read-char-exclusive))
19931 (message "")
19932 (cond
19933 ((assoc (char-to-string c) custom)
19934 (setq selstring (concat selstring (char-to-string c)))
19935 (throw 'exit (cons selstring restriction)))
19936 ((memq c prefixes)
19937 (setq selstring (concat selstring (char-to-string c))
19938 prefixes nil
19939 rmheader (or rmheader t)
19940 custom (delq nil (mapcar
19941 (lambda (x)
19942 (if (or (= (length (car x)) 1)
19943 (/= (string-to-char (car x)) c))
19945 (cons (substring (car x) 1) (cdr x))))
19946 custom))))
19947 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19948 (message "Restriction is only possible in Org-mode buffers")
19949 (ding) (sit-for 1))
19950 ((eq c ?1)
19951 (org-agenda-remove-restriction-lock 'noupdate)
19952 (setq restriction 'buffer))
19953 ((eq c ?0)
19954 (org-agenda-remove-restriction-lock 'noupdate)
19955 (setq restriction (if region-p 'region 'subtree)))
19956 ((eq c ?<)
19957 (org-agenda-remove-restriction-lock 'noupdate)
19958 (setq restriction
19959 (cond
19960 ((eq restriction 'buffer)
19961 (if region-p 'region 'subtree))
19962 ((memq restriction '(subtree region))
19963 nil)
19964 (t 'buffer))))
19965 ((eq c ?>)
19966 (org-agenda-remove-restriction-lock 'noupdate)
19967 (setq restriction nil))
19968 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19969 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19970 ((and (> (length selstring) 0) (eq c ?\d))
19971 (delete-window)
19972 (org-agenda-get-restriction-and-command prefix-descriptions))
19974 ((equal c ?q) (error "Abort"))
19975 (t (error "Invalid key %c" c))))))))
19977 (defun org-run-agenda-series (name series)
19978 (org-prepare-agenda name)
19979 (let* ((org-agenda-multi t)
19980 (redo (list 'org-run-agenda-series name (list 'quote series)))
19981 (cmds (car series))
19982 (gprops (nth 1 series))
19983 match ;; The byte compiler incorrectly complains about this. Keep it!
19984 cmd type lprops)
19985 (while (setq cmd (pop cmds))
19986 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19987 (cond
19988 ((eq type 'agenda)
19989 (org-let2 gprops lprops
19990 '(call-interactively 'org-agenda-list)))
19991 ((eq type 'alltodo)
19992 (org-let2 gprops lprops
19993 '(call-interactively 'org-todo-list)))
19994 ((eq type 'search)
19995 (org-let2 gprops lprops
19996 '(org-search-view current-prefix-arg match)))
19997 ((eq type 'stuck)
19998 (org-let2 gprops lprops
19999 '(call-interactively 'org-agenda-list-stuck-projects)))
20000 ((eq type 'tags)
20001 (org-let2 gprops lprops
20002 '(org-tags-view current-prefix-arg match)))
20003 ((eq type 'tags-todo)
20004 (org-let2 gprops lprops
20005 '(org-tags-view '(4) match)))
20006 ((eq type 'todo)
20007 (org-let2 gprops lprops
20008 '(org-todo-list match)))
20009 ((fboundp type)
20010 (org-let2 gprops lprops
20011 '(funcall type match)))
20012 (t (error "Invalid type in command series"))))
20013 (widen)
20014 (setq org-agenda-redo-command redo)
20015 (goto-char (point-min)))
20016 (org-finalize-agenda))
20018 ;;;###autoload
20019 (defmacro org-batch-agenda (cmd-key &rest parameters)
20020 "Run an agenda command in batch mode and send the result to STDOUT.
20021 If CMD-KEY is a string of length 1, it is used as a key in
20022 `org-agenda-custom-commands' and triggers this command. If it is a
20023 longer string it is used as a tags/todo match string.
20024 Paramters are alternating variable names and values that will be bound
20025 before running the agenda command."
20026 (let (pars)
20027 (while parameters
20028 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20029 (if (> (length cmd-key) 2)
20030 (eval (list 'let (nreverse pars)
20031 (list 'org-tags-view nil cmd-key)))
20032 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20033 (set-buffer org-agenda-buffer-name)
20034 (princ (org-encode-for-stdout (buffer-string)))))
20036 (defun org-encode-for-stdout (string)
20037 (if (fboundp 'encode-coding-string)
20038 (encode-coding-string string buffer-file-coding-system)
20039 string))
20041 (defvar org-agenda-info nil)
20043 ;;;###autoload
20044 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20045 "Run an agenda command in batch mode and send the result to STDOUT.
20046 If CMD-KEY is a string of length 1, it is used as a key in
20047 `org-agenda-custom-commands' and triggers this command. If it is a
20048 longer string it is used as a tags/todo match string.
20049 Paramters are alternating variable names and values that will be bound
20050 before running the agenda command.
20052 The output gives a line for each selected agenda item. Each
20053 item is a list of comma-separated values, like this:
20055 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20057 category The category of the item
20058 head The headline, without TODO kwd, TAGS and PRIORITY
20059 type The type of the agenda entry, can be
20060 todo selected in TODO match
20061 tagsmatch selected in tags match
20062 diary imported from diary
20063 deadline a deadline on given date
20064 scheduled scheduled on given date
20065 timestamp entry has timestamp on given date
20066 closed entry was closed on given date
20067 upcoming-deadline warning about deadline
20068 past-scheduled forwarded scheduled item
20069 block entry has date block including g. date
20070 todo The todo keyword, if any
20071 tags All tags including inherited ones, separated by colons
20072 date The relevant date, like 2007-2-14
20073 time The time, like 15:00-16:50
20074 extra Sting with extra planning info
20075 priority-l The priority letter if any was given
20076 priority-n The computed numerical priority
20077 agenda-day The day in the agenda where this is listed"
20079 (let (pars)
20080 (while parameters
20081 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20082 (push (list 'org-agenda-remove-tags t) pars)
20083 (if (> (length cmd-key) 2)
20084 (eval (list 'let (nreverse pars)
20085 (list 'org-tags-view nil cmd-key)))
20086 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20087 (set-buffer org-agenda-buffer-name)
20088 (let* ((lines (org-split-string (buffer-string) "\n"))
20089 line)
20090 (while (setq line (pop lines))
20091 (catch 'next
20092 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20093 (setq org-agenda-info
20094 (org-fix-agenda-info (text-properties-at 0 line)))
20095 (princ
20096 (org-encode-for-stdout
20097 (mapconcat 'org-agenda-export-csv-mapper
20098 '(org-category txt type todo tags date time-of-day extra
20099 priority-letter priority agenda-day)
20100 ",")))
20101 (princ "\n"))))))
20103 (defun org-fix-agenda-info (props)
20104 "Make sure all properties on an agenda item have a canonical form,
20105 so the export commands can easily use it."
20106 (let (tmp re)
20107 (when (setq tmp (plist-get props 'tags))
20108 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20109 (when (setq tmp (plist-get props 'date))
20110 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20111 (let ((calendar-date-display-form '(year "-" month "-" day)))
20112 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20114 (setq tmp (calendar-date-string tmp)))
20115 (setq props (plist-put props 'date tmp)))
20116 (when (setq tmp (plist-get props 'day))
20117 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20118 (let ((calendar-date-display-form '(year "-" month "-" day)))
20119 (setq tmp (calendar-date-string tmp)))
20120 (setq props (plist-put props 'day tmp))
20121 (setq props (plist-put props 'agenda-day tmp)))
20122 (when (setq tmp (plist-get props 'txt))
20123 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20124 (plist-put props 'priority-letter (match-string 1 tmp))
20125 (setq tmp (replace-match "" t t tmp)))
20126 (when (and (setq re (plist-get props 'org-todo-regexp))
20127 (setq re (concat "\\`\\.*" re " ?"))
20128 (string-match re tmp))
20129 (plist-put props 'todo (match-string 1 tmp))
20130 (setq tmp (replace-match "" t t tmp)))
20131 (plist-put props 'txt tmp)))
20132 props)
20134 (defun org-agenda-export-csv-mapper (prop)
20135 (let ((res (plist-get org-agenda-info prop)))
20136 (setq res
20137 (cond
20138 ((not res) "")
20139 ((stringp res) res)
20140 (t (prin1-to-string res))))
20141 (while (string-match "," res)
20142 (setq res (replace-match ";" t t res)))
20143 (org-trim res)))
20146 ;;;###autoload
20147 (defun org-store-agenda-views (&rest parameters)
20148 (interactive)
20149 (eval (list 'org-batch-store-agenda-views)))
20151 ;; FIXME, why is this a macro?????
20152 ;;;###autoload
20153 (defmacro org-batch-store-agenda-views (&rest parameters)
20154 "Run all custom agenda commands that have a file argument."
20155 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20156 (pop-up-frames nil)
20157 (dir default-directory)
20158 pars cmd thiscmdkey files opts)
20159 (while parameters
20160 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20161 (setq pars (reverse pars))
20162 (save-window-excursion
20163 (while cmds
20164 (setq cmd (pop cmds)
20165 thiscmdkey (car cmd)
20166 opts (nth 4 cmd)
20167 files (nth 5 cmd))
20168 (if (stringp files) (setq files (list files)))
20169 (when files
20170 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20171 (list 'org-agenda nil thiscmdkey)))
20172 (set-buffer org-agenda-buffer-name)
20173 (while files
20174 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20175 (list 'org-write-agenda
20176 (expand-file-name (pop files) dir) t))))
20177 (and (get-buffer org-agenda-buffer-name)
20178 (kill-buffer org-agenda-buffer-name)))))))
20180 (defun org-write-agenda (file &optional nosettings)
20181 "Write the current buffer (an agenda view) as a file.
20182 Depending on the extension of the file name, plain text (.txt),
20183 HTML (.html or .htm) or Postscript (.ps) is produced.
20184 If NOSETTINGS is given, do not scope the settings of
20185 `org-agenda-exporter-settings' into the export commands. This is used when
20186 the settings have already been scoped and we do not wish to overrule other,
20187 higher priority settings."
20188 (interactive "FWrite agenda to file: ")
20189 (if (not (file-writable-p file))
20190 (error "Cannot write agenda to file %s" file))
20191 (cond
20192 ((string-match "\\.html?\\'" file) (require 'htmlize))
20193 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20194 (org-let (if nosettings nil org-agenda-exporter-settings)
20195 '(save-excursion
20196 (save-window-excursion
20197 (cond
20198 ((string-match "\\.html?\\'" file)
20199 (set-buffer (htmlize-buffer (current-buffer)))
20201 (when (and org-agenda-export-html-style
20202 (string-match "<style>" org-agenda-export-html-style))
20203 ;; replace <style> section with org-agenda-export-html-style
20204 (goto-char (point-min))
20205 (kill-region (- (search-forward "<style") 6)
20206 (search-forward "</style>"))
20207 (insert org-agenda-export-html-style))
20208 (write-file file)
20209 (kill-buffer (current-buffer))
20210 (message "HTML written to %s" file))
20211 ((string-match "\\.ps\\'" file)
20212 (ps-print-buffer-with-faces file)
20213 (message "Postscript written to %s" file))
20215 (let ((bs (buffer-string)))
20216 (find-file file)
20217 (insert bs)
20218 (save-buffer 0)
20219 (kill-buffer (current-buffer))
20220 (message "Plain text written to %s" file))))))
20221 (set-buffer org-agenda-buffer-name)))
20223 (defmacro org-no-read-only (&rest body)
20224 "Inhibit read-only for BODY."
20225 `(let ((inhibit-read-only t)) ,@body))
20227 (defun org-check-for-org-mode ()
20228 "Make sure current buffer is in org-mode. Error if not."
20229 (or (org-mode-p)
20230 (error "Cannot execute org-mode agenda command on buffer in %s."
20231 major-mode)))
20233 (defun org-fit-agenda-window ()
20234 "Fit the window to the buffer size."
20235 (and (memq org-agenda-window-setup '(reorganize-frame))
20236 (fboundp 'fit-window-to-buffer)
20237 (fit-window-to-buffer
20239 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20240 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20242 ;;; Agenda file list
20244 (defun org-agenda-files (&optional unrestricted)
20245 "Get the list of agenda files.
20246 Optional UNRESTRICTED means return the full list even if a restriction
20247 is currently in place."
20248 (let ((files
20249 (cond
20250 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20251 ((stringp org-agenda-files) (org-read-agenda-file-list))
20252 ((listp org-agenda-files) org-agenda-files)
20253 (t (error "Invalid value of `org-agenda-files'")))))
20254 (setq files (apply 'append
20255 (mapcar (lambda (f)
20256 (if (file-directory-p f)
20257 (directory-files f t
20258 org-agenda-file-regexp)
20259 (list f)))
20260 files)))
20261 (if org-agenda-skip-unavailable-files
20262 (delq nil
20263 (mapcar (function
20264 (lambda (file)
20265 (and (file-readable-p file) file)))
20266 files))
20267 files))) ; `org-check-agenda-file' will remove them from the list
20269 (defun org-edit-agenda-file-list ()
20270 "Edit the list of agenda files.
20271 Depending on setup, this either uses customize to edit the variable
20272 `org-agenda-files', or it visits the file that is holding the list. In the
20273 latter case, the buffer is set up in a way that saving it automatically kills
20274 the buffer and restores the previous window configuration."
20275 (interactive)
20276 (if (stringp org-agenda-files)
20277 (let ((cw (current-window-configuration)))
20278 (find-file org-agenda-files)
20279 (org-set-local 'org-window-configuration cw)
20280 (org-add-hook 'after-save-hook
20281 (lambda ()
20282 (set-window-configuration
20283 (prog1 org-window-configuration
20284 (kill-buffer (current-buffer))))
20285 (org-install-agenda-files-menu)
20286 (message "New agenda file list installed"))
20287 nil 'local)
20288 (message "%s" (substitute-command-keys
20289 "Edit list and finish with \\[save-buffer]")))
20290 (customize-variable 'org-agenda-files)))
20292 (defun org-store-new-agenda-file-list (list)
20293 "Set new value for the agenda file list and save it correcly."
20294 (if (stringp org-agenda-files)
20295 (let ((f org-agenda-files) b)
20296 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20297 (with-temp-file f
20298 (insert (mapconcat 'identity list "\n") "\n")))
20299 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20300 (setq org-agenda-files list)
20301 (customize-save-variable 'org-agenda-files org-agenda-files))))
20303 (defun org-read-agenda-file-list ()
20304 "Read the list of agenda files from a file."
20305 (when (stringp org-agenda-files)
20306 (with-temp-buffer
20307 (insert-file-contents org-agenda-files)
20308 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20311 ;;;###autoload
20312 (defun org-cycle-agenda-files ()
20313 "Cycle through the files in `org-agenda-files'.
20314 If the current buffer visits an agenda file, find the next one in the list.
20315 If the current buffer does not, find the first agenda file."
20316 (interactive)
20317 (let* ((fs (org-agenda-files t))
20318 (files (append fs (list (car fs))))
20319 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20320 file)
20321 (unless files (error "No agenda files"))
20322 (catch 'exit
20323 (while (setq file (pop files))
20324 (if (equal (file-truename file) tcf)
20325 (when (car files)
20326 (find-file (car files))
20327 (throw 'exit t))))
20328 (find-file (car fs)))
20329 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20331 (defun org-agenda-file-to-front (&optional to-end)
20332 "Move/add the current file to the top of the agenda file list.
20333 If the file is not present in the list, it is added to the front. If it is
20334 present, it is moved there. With optional argument TO-END, add/move to the
20335 end of the list."
20336 (interactive "P")
20337 (let ((org-agenda-skip-unavailable-files nil)
20338 (file-alist (mapcar (lambda (x)
20339 (cons (file-truename x) x))
20340 (org-agenda-files t)))
20341 (ctf (file-truename buffer-file-name))
20342 x had)
20343 (setq x (assoc ctf file-alist) had x)
20345 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20346 (if to-end
20347 (setq file-alist (append (delq x file-alist) (list x)))
20348 (setq file-alist (cons x (delq x file-alist))))
20349 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20350 (org-install-agenda-files-menu)
20351 (message "File %s to %s of agenda file list"
20352 (if had "moved" "added") (if to-end "end" "front"))))
20354 (defun org-remove-file (&optional file)
20355 "Remove current file from the list of files in variable `org-agenda-files'.
20356 These are the files which are being checked for agenda entries.
20357 Optional argument FILE means, use this file instead of the current."
20358 (interactive)
20359 (let* ((org-agenda-skip-unavailable-files nil)
20360 (file (or file buffer-file-name))
20361 (true-file (file-truename file))
20362 (afile (abbreviate-file-name file))
20363 (files (delq nil (mapcar
20364 (lambda (x)
20365 (if (equal true-file
20366 (file-truename x))
20367 nil x))
20368 (org-agenda-files t)))))
20369 (if (not (= (length files) (length (org-agenda-files t))))
20370 (progn
20371 (org-store-new-agenda-file-list files)
20372 (org-install-agenda-files-menu)
20373 (message "Removed file: %s" afile))
20374 (message "File was not in list: %s (not removed)" afile))))
20376 (defun org-file-menu-entry (file)
20377 (vector file (list 'find-file file) t))
20379 (defun org-check-agenda-file (file)
20380 "Make sure FILE exists. If not, ask user what to do."
20381 (when (not (file-exists-p file))
20382 (message "non-existent file %s. [R]emove from list or [A]bort?"
20383 (abbreviate-file-name file))
20384 (let ((r (downcase (read-char-exclusive))))
20385 (cond
20386 ((equal r ?r)
20387 (org-remove-file file)
20388 (throw 'nextfile t))
20389 (t (error "Abort"))))))
20391 ;;; Agenda prepare and finalize
20393 (defvar org-agenda-multi nil) ; dynammically scoped
20394 (defvar org-agenda-buffer-name "*Org Agenda*")
20395 (defvar org-pre-agenda-window-conf nil)
20396 (defvar org-agenda-name nil)
20397 (defun org-prepare-agenda (&optional name)
20398 (setq org-todo-keywords-for-agenda nil)
20399 (setq org-done-keywords-for-agenda nil)
20400 (if org-agenda-multi
20401 (progn
20402 (setq buffer-read-only nil)
20403 (goto-char (point-max))
20404 (unless (or (bobp) org-agenda-compact-blocks)
20405 (insert "\n" (make-string (window-width) ?=) "\n"))
20406 (narrow-to-region (point) (point-max)))
20407 (org-agenda-reset-markers)
20408 (org-prepare-agenda-buffers (org-agenda-files))
20409 (setq org-todo-keywords-for-agenda
20410 (org-uniquify org-todo-keywords-for-agenda))
20411 (setq org-done-keywords-for-agenda
20412 (org-uniquify org-done-keywords-for-agenda))
20413 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20414 (awin (get-buffer-window abuf)))
20415 (cond
20416 ((equal (current-buffer) abuf) nil)
20417 (awin (select-window awin))
20418 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20419 ((equal org-agenda-window-setup 'current-window)
20420 (switch-to-buffer abuf))
20421 ((equal org-agenda-window-setup 'other-window)
20422 (org-switch-to-buffer-other-window abuf))
20423 ((equal org-agenda-window-setup 'other-frame)
20424 (switch-to-buffer-other-frame abuf))
20425 ((equal org-agenda-window-setup 'reorganize-frame)
20426 (delete-other-windows)
20427 (org-switch-to-buffer-other-window abuf))))
20428 (setq buffer-read-only nil)
20429 (erase-buffer)
20430 (org-agenda-mode)
20431 (and name (not org-agenda-name)
20432 (org-set-local 'org-agenda-name name)))
20433 (setq buffer-read-only nil))
20435 (defun org-finalize-agenda ()
20436 "Finishing touch for the agenda buffer, called just before displaying it."
20437 (unless org-agenda-multi
20438 (save-excursion
20439 (let ((inhibit-read-only t))
20440 (goto-char (point-min))
20441 (while (org-activate-bracket-links (point-max))
20442 (add-text-properties (match-beginning 0) (match-end 0)
20443 '(face org-link)))
20444 (org-agenda-align-tags)
20445 (unless org-agenda-with-colors
20446 (remove-text-properties (point-min) (point-max) '(face nil))))
20447 (if (and (boundp 'org-overriding-columns-format)
20448 org-overriding-columns-format)
20449 (org-set-local 'org-overriding-columns-format
20450 org-overriding-columns-format))
20451 (if (and (boundp 'org-agenda-view-columns-initially)
20452 org-agenda-view-columns-initially)
20453 (org-agenda-columns))
20454 (when org-agenda-fontify-priorities
20455 (org-fontify-priorities))
20456 (run-hooks 'org-finalize-agenda-hook)
20457 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20460 (defun org-fontify-priorities ()
20461 "Make highest priority lines bold, and lowest italic."
20462 (interactive)
20463 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20464 (org-delete-overlay o)))
20465 (org-overlays-in (point-min) (point-max)))
20466 (save-excursion
20467 (let ((inhibit-read-only t)
20468 b e p ov h l)
20469 (goto-char (point-min))
20470 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20471 (setq h (or (get-char-property (point) 'org-highest-priority)
20472 org-highest-priority)
20473 l (or (get-char-property (point) 'org-lowest-priority)
20474 org-lowest-priority)
20475 p (string-to-char (match-string 1))
20476 b (match-beginning 0) e (point-at-eol)
20477 ov (org-make-overlay b e))
20478 (org-overlay-put
20479 ov 'face
20480 (cond ((listp org-agenda-fontify-priorities)
20481 (cdr (assoc p org-agenda-fontify-priorities)))
20482 ((equal p l) 'italic)
20483 ((equal p h) 'bold)))
20484 (org-overlay-put ov 'org-type 'org-priority)))))
20486 (defun org-prepare-agenda-buffers (files)
20487 "Create buffers for all agenda files, protect archived trees and comments."
20488 (interactive)
20489 (let ((pa '(:org-archived t))
20490 (pc '(:org-comment t))
20491 (pall '(:org-archived t :org-comment t))
20492 (inhibit-read-only t)
20493 (rea (concat ":" org-archive-tag ":"))
20494 bmp file re)
20495 (save-excursion
20496 (save-restriction
20497 (while (setq file (pop files))
20498 (if (bufferp file)
20499 (set-buffer file)
20500 (org-check-agenda-file file)
20501 (set-buffer (org-get-agenda-file-buffer file)))
20502 (widen)
20503 (setq bmp (buffer-modified-p))
20504 (org-refresh-category-properties)
20505 (setq org-todo-keywords-for-agenda
20506 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20507 (setq org-done-keywords-for-agenda
20508 (append org-done-keywords-for-agenda org-done-keywords))
20509 (save-excursion
20510 (remove-text-properties (point-min) (point-max) pall)
20511 (when org-agenda-skip-archived-trees
20512 (goto-char (point-min))
20513 (while (re-search-forward rea nil t)
20514 (if (org-on-heading-p t)
20515 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20516 (goto-char (point-min))
20517 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20518 (while (re-search-forward re nil t)
20519 (add-text-properties
20520 (match-beginning 0) (org-end-of-subtree t) pc)))
20521 (set-buffer-modified-p bmp))))))
20523 (defvar org-agenda-skip-function nil
20524 "Function to be called at each match during agenda construction.
20525 If this function returns nil, the current match should not be skipped.
20526 Otherwise, the function must return a position from where the search
20527 should be continued.
20528 This may also be a Lisp form, it will be evaluated.
20529 Never set this variable using `setq' or so, because then it will apply
20530 to all future agenda commands. Instead, bind it with `let' to scope
20531 it dynamically into the agenda-constructing command. A good way to set
20532 it is through options in org-agenda-custom-commands.")
20534 (defun org-agenda-skip ()
20535 "Throw to `:skip' in places that should be skipped.
20536 Also moves point to the end of the skipped region, so that search can
20537 continue from there."
20538 (let ((p (point-at-bol)) to fp)
20539 (and org-agenda-skip-archived-trees
20540 (get-text-property p :org-archived)
20541 (org-end-of-subtree t)
20542 (throw :skip t))
20543 (and (get-text-property p :org-comment)
20544 (org-end-of-subtree t)
20545 (throw :skip t))
20546 (if (equal (char-after p) ?#) (throw :skip t))
20547 (when (and (or (setq fp (functionp org-agenda-skip-function))
20548 (consp org-agenda-skip-function))
20549 (setq to (save-excursion
20550 (save-match-data
20551 (if fp
20552 (funcall org-agenda-skip-function)
20553 (eval org-agenda-skip-function))))))
20554 (goto-char to)
20555 (throw :skip t))))
20557 (defvar org-agenda-markers nil
20558 "List of all currently active markers created by `org-agenda'.")
20559 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20560 "Creation time of the last agenda marker.")
20562 (defun org-agenda-new-marker (&optional pos)
20563 "Return a new agenda marker.
20564 Org-mode keeps a list of these markers and resets them when they are
20565 no longer in use."
20566 (let ((m (copy-marker (or pos (point)))))
20567 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20568 (push m org-agenda-markers)
20571 (defun org-agenda-reset-markers ()
20572 "Reset markers created by `org-agenda'."
20573 (while org-agenda-markers
20574 (move-marker (pop org-agenda-markers) nil)))
20576 (defun org-get-agenda-file-buffer (file)
20577 "Get a buffer visiting FILE. If the buffer needs to be created, add
20578 it to the list of buffers which might be released later."
20579 (let ((buf (org-find-base-buffer-visiting file)))
20580 (if buf
20581 buf ; just return it
20582 ;; Make a new buffer and remember it
20583 (setq buf (find-file-noselect file))
20584 (if buf (push buf org-agenda-new-buffers))
20585 buf)))
20587 (defun org-release-buffers (blist)
20588 "Release all buffers in list, asking the user for confirmation when needed.
20589 When a buffer is unmodified, it is just killed. When modified, it is saved
20590 \(if the user agrees) and then killed."
20591 (let (buf file)
20592 (while (setq buf (pop blist))
20593 (setq file (buffer-file-name buf))
20594 (when (and (buffer-modified-p buf)
20595 file
20596 (y-or-n-p (format "Save file %s? " file)))
20597 (with-current-buffer buf (save-buffer)))
20598 (kill-buffer buf))))
20600 (defun org-get-category (&optional pos)
20601 "Get the category applying to position POS."
20602 (get-text-property (or pos (point)) 'org-category))
20604 ;;; Agenda timeline
20606 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20608 (defun org-timeline (&optional include-all)
20609 "Show a time-sorted view of the entries in the current org file.
20610 Only entries with a time stamp of today or later will be listed. With
20611 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20612 under the current date.
20613 If the buffer contains an active region, only check the region for
20614 dates."
20615 (interactive "P")
20616 (require 'calendar)
20617 (org-compile-prefix-format 'timeline)
20618 (org-set-sorting-strategy 'timeline)
20619 (let* ((dopast t)
20620 (dotodo include-all)
20621 (doclosed org-agenda-show-log)
20622 (entry buffer-file-name)
20623 (date (calendar-current-date))
20624 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20625 (end (if (org-region-active-p) (region-end) (point-max)))
20626 (day-numbers (org-get-all-dates beg end 'no-ranges
20627 t doclosed ; always include today
20628 org-timeline-show-empty-dates))
20629 (org-deadline-warning-days 0)
20630 (org-agenda-only-exact-dates t)
20631 (today (time-to-days (current-time)))
20632 (past t)
20633 args
20634 s e rtn d emptyp)
20635 (setq org-agenda-redo-command
20636 (list 'progn
20637 (list 'org-switch-to-buffer-other-window (current-buffer))
20638 (list 'org-timeline (list 'quote include-all))))
20639 (if (not dopast)
20640 ;; Remove past dates from the list of dates.
20641 (setq day-numbers (delq nil (mapcar (lambda(x)
20642 (if (>= x today) x nil))
20643 day-numbers))))
20644 (org-prepare-agenda (concat "Timeline "
20645 (file-name-nondirectory buffer-file-name)))
20646 (if doclosed (push :closed args))
20647 (push :timestamp args)
20648 (push :deadline args)
20649 (push :scheduled args)
20650 (push :sexp args)
20651 (if dotodo (push :todo args))
20652 (while (setq d (pop day-numbers))
20653 (if (and (listp d) (eq (car d) :omitted))
20654 (progn
20655 (setq s (point))
20656 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20657 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20658 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20659 (if (and (>= d today)
20660 dopast
20661 past)
20662 (progn
20663 (setq past nil)
20664 (insert (make-string 79 ?-) "\n")))
20665 (setq date (calendar-gregorian-from-absolute d))
20666 (setq s (point))
20667 (setq rtn (and (not emptyp)
20668 (apply 'org-agenda-get-day-entries entry
20669 date args)))
20670 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20671 (progn
20672 (insert
20673 (if (stringp org-agenda-format-date)
20674 (format-time-string org-agenda-format-date
20675 (org-time-from-absolute date))
20676 (funcall org-agenda-format-date date))
20677 "\n")
20678 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20679 (put-text-property s (1- (point)) 'org-date-line t)
20680 (if (equal d today)
20681 (put-text-property s (1- (point)) 'org-today t))
20682 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20683 (put-text-property s (1- (point)) 'day d)))))
20684 (goto-char (point-min))
20685 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20686 (point-min)))
20687 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20688 (org-finalize-agenda)
20689 (setq buffer-read-only t)))
20691 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20692 "Return a list of all relevant day numbers from BEG to END buffer positions.
20693 If NO-RANGES is non-nil, include only the start and end dates of a range,
20694 not every single day in the range. If FORCE-TODAY is non-nil, make
20695 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20696 inactive time stamps (those in square brackets) are included.
20697 When EMPTY is non-nil, also include days without any entries."
20698 (let ((re (concat
20699 (if pre-re pre-re "")
20700 (if inactive org-ts-regexp-both org-ts-regexp)))
20701 dates dates1 date day day1 day2 ts1 ts2)
20702 (if force-today
20703 (setq dates (list (time-to-days (current-time)))))
20704 (save-excursion
20705 (goto-char beg)
20706 (while (re-search-forward re end t)
20707 (setq day (time-to-days (org-time-string-to-time
20708 (substring (match-string 1) 0 10))))
20709 (or (memq day dates) (push day dates)))
20710 (unless no-ranges
20711 (goto-char beg)
20712 (while (re-search-forward org-tr-regexp end t)
20713 (setq ts1 (substring (match-string 1) 0 10)
20714 ts2 (substring (match-string 2) 0 10)
20715 day1 (time-to-days (org-time-string-to-time ts1))
20716 day2 (time-to-days (org-time-string-to-time ts2)))
20717 (while (< (setq day1 (1+ day1)) day2)
20718 (or (memq day1 dates) (push day1 dates)))))
20719 (setq dates (sort dates '<))
20720 (when empty
20721 (while (setq day (pop dates))
20722 (setq day2 (car dates))
20723 (push day dates1)
20724 (when (and day2 empty)
20725 (if (or (eq empty t)
20726 (and (numberp empty) (<= (- day2 day) empty)))
20727 (while (< (setq day (1+ day)) day2)
20728 (push (list day) dates1))
20729 (push (cons :omitted (- day2 day)) dates1))))
20730 (setq dates (nreverse dates1)))
20731 dates)))
20733 ;;; Agenda Daily/Weekly
20735 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20736 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20737 (defvar org-agenda-last-arguments nil
20738 "The arguments of the previous call to org-agenda")
20739 (defvar org-starting-day nil) ; local variable in the agenda buffer
20740 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20741 (defvar org-include-all-loc nil) ; local variable
20742 (defvar org-agenda-remove-date nil) ; dynamically scoped
20744 ;;;###autoload
20745 (defun org-agenda-list (&optional include-all start-day ndays)
20746 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20747 The view will be for the current day or week, but from the overview buffer
20748 you will be able to go to other days/weeks.
20750 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20751 all unfinished TODO items will also be shown, before the agenda.
20752 This feature is considered obsolete, please use the TODO list or a block
20753 agenda instead.
20755 With a numeric prefix argument in an interactive call, the agenda will
20756 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20757 the number of days. NDAYS defaults to `org-agenda-ndays'.
20759 START-DAY defaults to TODAY, or to the most recent match for the weekday
20760 given in `org-agenda-start-on-weekday'."
20761 (interactive "P")
20762 (if (and (integerp include-all) (> include-all 0))
20763 (setq ndays include-all include-all nil))
20764 (setq ndays (or ndays org-agenda-ndays)
20765 start-day (or start-day org-agenda-start-day))
20766 (if org-agenda-overriding-arguments
20767 (setq include-all (car org-agenda-overriding-arguments)
20768 start-day (nth 1 org-agenda-overriding-arguments)
20769 ndays (nth 2 org-agenda-overriding-arguments)))
20770 (if (stringp start-day)
20771 ;; Convert to an absolute day number
20772 (setq start-day (time-to-days (org-read-date nil t start-day))))
20773 (setq org-agenda-last-arguments (list include-all start-day ndays))
20774 (org-compile-prefix-format 'agenda)
20775 (org-set-sorting-strategy 'agenda)
20776 (require 'calendar)
20777 (let* ((org-agenda-start-on-weekday
20778 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20779 org-agenda-start-on-weekday nil))
20780 (thefiles (org-agenda-files))
20781 (files thefiles)
20782 (today (time-to-days
20783 (time-subtract (current-time)
20784 (list 0 (* 3600 org-extend-today-until) 0))))
20785 (sd (or start-day today))
20786 (start (if (or (null org-agenda-start-on-weekday)
20787 (< org-agenda-ndays 7))
20789 (let* ((nt (calendar-day-of-week
20790 (calendar-gregorian-from-absolute sd)))
20791 (n1 org-agenda-start-on-weekday)
20792 (d (- nt n1)))
20793 (- sd (+ (if (< d 0) 7 0) d)))))
20794 (day-numbers (list start))
20795 (day-cnt 0)
20796 (inhibit-redisplay (not debug-on-error))
20797 s e rtn rtnall file date d start-pos end-pos todayp nd)
20798 (setq org-agenda-redo-command
20799 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20800 ;; Make the list of days
20801 (setq ndays (or ndays org-agenda-ndays)
20802 nd ndays)
20803 (while (> ndays 1)
20804 (push (1+ (car day-numbers)) day-numbers)
20805 (setq ndays (1- ndays)))
20806 (setq day-numbers (nreverse day-numbers))
20807 (org-prepare-agenda "Day/Week")
20808 (org-set-local 'org-starting-day (car day-numbers))
20809 (org-set-local 'org-include-all-loc include-all)
20810 (org-set-local 'org-agenda-span
20811 (org-agenda-ndays-to-span nd))
20812 (when (and (or include-all org-agenda-include-all-todo)
20813 (member today day-numbers))
20814 (setq files thefiles
20815 rtnall nil)
20816 (while (setq file (pop files))
20817 (catch 'nextfile
20818 (org-check-agenda-file file)
20819 (setq date (calendar-gregorian-from-absolute today)
20820 rtn (org-agenda-get-day-entries
20821 file date :todo))
20822 (setq rtnall (append rtnall rtn))))
20823 (when rtnall
20824 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20825 (add-text-properties (point-min) (1- (point))
20826 (list 'face 'org-agenda-structure))
20827 (insert (org-finalize-agenda-entries rtnall) "\n")))
20828 (unless org-agenda-compact-blocks
20829 (setq s (point))
20830 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20831 "-agenda:\n")
20832 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20833 'org-date-line t)))
20834 (while (setq d (pop day-numbers))
20835 (setq date (calendar-gregorian-from-absolute d)
20836 s (point))
20837 (if (or (setq todayp (= d today))
20838 (and (not start-pos) (= d sd)))
20839 (setq start-pos (point))
20840 (if (and start-pos (not end-pos))
20841 (setq end-pos (point))))
20842 (setq files thefiles
20843 rtnall nil)
20844 (while (setq file (pop files))
20845 (catch 'nextfile
20846 (org-check-agenda-file file)
20847 (if org-agenda-show-log
20848 (setq rtn (org-agenda-get-day-entries
20849 file date
20850 :deadline :scheduled :timestamp :sexp :closed))
20851 (setq rtn (org-agenda-get-day-entries
20852 file date
20853 :deadline :scheduled :sexp :timestamp)))
20854 (setq rtnall (append rtnall rtn))))
20855 (if org-agenda-include-diary
20856 (progn
20857 (require 'diary-lib)
20858 (setq rtn (org-get-entries-from-diary date))
20859 (setq rtnall (append rtnall rtn))))
20860 (if (or rtnall org-agenda-show-all-dates)
20861 (progn
20862 (setq day-cnt (1+ day-cnt))
20863 (insert
20864 (if (stringp org-agenda-format-date)
20865 (format-time-string org-agenda-format-date
20866 (org-time-from-absolute date))
20867 (funcall org-agenda-format-date date))
20868 "\n")
20869 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20870 (put-text-property s (1- (point)) 'org-date-line t)
20871 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20872 (if todayp (put-text-property s (1- (point)) 'org-today t))
20873 (if rtnall (insert
20874 (org-finalize-agenda-entries
20875 (org-agenda-add-time-grid-maybe
20876 rtnall nd todayp))
20877 "\n"))
20878 (put-text-property s (1- (point)) 'day d)
20879 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20880 (goto-char (point-min))
20881 (org-fit-agenda-window)
20882 (unless (and (pos-visible-in-window-p (point-min))
20883 (pos-visible-in-window-p (point-max)))
20884 (goto-char (1- (point-max)))
20885 (recenter -1)
20886 (if (not (pos-visible-in-window-p (or start-pos 1)))
20887 (progn
20888 (goto-char (or start-pos 1))
20889 (recenter 1))))
20890 (goto-char (or start-pos 1))
20891 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20892 (org-finalize-agenda)
20893 (setq buffer-read-only t)
20894 (message "")))
20896 (defun org-agenda-ndays-to-span (n)
20897 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20899 ;;; Agenda word search
20901 (defvar org-agenda-search-history nil)
20903 ;;;###autoload
20904 (defun org-search-view (&optional arg string)
20905 "Show all entries that contain words or regular expressions.
20906 If the first character of the search string is an asterisks,
20907 search only the headlines.
20909 The search string is broken into \"words\" by splitting at whitespace.
20910 The individual words are then interpreted as a boolean expression with
20911 logical AND. Words prefixed with a minus must not occur in the entry.
20912 Words without a prefix or prefixed with a plus must occur in the entry.
20913 Matching is case-insensitive and the words are enclosed by word delimiters.
20915 Words enclosed by curly braces are interpreted as regular expressions
20916 that must or must not match in the entry.
20918 This command searches the agenda files, and in addition the files listed
20919 in `org-agenda-text-search-extra-files'."
20920 (interactive "P")
20921 (org-compile-prefix-format 'search)
20922 (org-set-sorting-strategy 'search)
20923 (org-prepare-agenda "SEARCH")
20924 (let* ((props (list 'face nil
20925 'done-face 'org-done
20926 'org-not-done-regexp org-not-done-regexp
20927 'org-todo-regexp org-todo-regexp
20928 'mouse-face 'highlight
20929 'keymap org-agenda-keymap
20930 'help-echo (format "mouse-2 or RET jump to location")))
20931 regexp rtn rtnall files file pos
20932 marker priority category tags c neg re
20933 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
20934 (unless (and (not arg)
20935 (stringp string)
20936 (string-match "\\S-" string))
20937 (setq string (read-string "[+-]Word/{Regexp} ...: "
20938 (cond
20939 ((integerp arg) (cons string arg))
20940 (arg string))
20941 'org-agenda-search-history)))
20942 (setq org-agenda-redo-command
20943 (list 'org-search-view 'current-prefix-arg string))
20944 (setq org-agenda-query-string string)
20946 (if (equal (string-to-char string) ?*)
20947 (setq hdl-only t
20948 words (substring string 1))
20949 (setq words string))
20950 (setq words (org-split-string words))
20951 (mapc (lambda (w)
20952 (setq c (string-to-char w))
20953 (if (equal c ?-)
20954 (setq neg t w (substring w 1))
20955 (if (equal c ?+)
20956 (setq neg nil w (substring w 1))
20957 (setq neg nil)))
20958 (if (string-match "\\`{.*}\\'" w)
20959 (setq re (substring w 1 -1))
20960 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
20961 (if neg (push re regexps-) (push re regexps+)))
20962 words)
20963 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
20964 (if (not regexps+)
20965 (setq regexp (concat "^" org-outline-regexp))
20966 (setq regexp (pop regexps+))
20967 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
20968 regexp))))
20969 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
20970 rtnall nil)
20971 (while (setq file (pop files))
20972 (setq ee nil)
20973 (catch 'nextfile
20974 (org-check-agenda-file file)
20975 (setq buffer (if (file-exists-p file)
20976 (org-get-agenda-file-buffer file)
20977 (error "No such file %s" file)))
20978 (if (not buffer)
20979 ;; If file does not exist, make sure an error message is sent
20980 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
20981 file))))
20982 (with-current-buffer buffer
20983 (unless (org-mode-p)
20984 (error "Agenda file %s is not in `org-mode'" file))
20985 (let ((case-fold-search t))
20986 (save-excursion
20987 (save-restriction
20988 (if org-agenda-restrict
20989 (narrow-to-region org-agenda-restrict-begin
20990 org-agenda-restrict-end)
20991 (widen))
20992 (goto-char (point-min))
20993 (unless (or (org-on-heading-p)
20994 (outline-next-heading))
20995 (throw 'nextfile t))
20996 (goto-char (max (point-min) (1- (point))))
20997 (while (re-search-forward regexp nil t)
20998 (org-back-to-heading t)
20999 (skip-chars-forward "* ")
21000 (setq beg (point-at-bol)
21001 beg1 (point)
21002 end (progn (outline-next-heading) (point)))
21003 (catch :skip
21004 (goto-char beg)
21005 (org-agenda-skip)
21006 (setq str (buffer-substring-no-properties
21007 (point-at-bol)
21008 (if hdl-only (point-at-eol) end)))
21009 (mapc (lambda (wr) (when (string-match wr str)
21010 (goto-char (1- end))
21011 (throw :skip t)))
21012 regexps-)
21013 (mapc (lambda (wr) (unless (string-match wr str)
21014 (goto-char (1- end))
21015 (throw :skip t)))
21016 regexps+)
21017 (goto-char beg)
21018 (setq marker (org-agenda-new-marker (point))
21019 category (org-get-category)
21020 tags (org-get-tags-at (point))
21021 txt (org-format-agenda-item
21023 (buffer-substring-no-properties
21024 beg1 (point-at-eol))
21025 category tags))
21026 (org-add-props txt props
21027 'org-marker marker 'org-hd-marker marker
21028 'priority 1000 'org-category category
21029 'type "search")
21030 (push txt ee)
21031 (goto-char (1- end)))))))))
21032 (setq rtn (nreverse ee))
21033 (setq rtnall (append rtnall rtn)))
21034 (if org-agenda-overriding-header
21035 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21036 nil 'face 'org-agenda-structure) "\n")
21037 (insert "Search words: ")
21038 (add-text-properties (point-min) (1- (point))
21039 (list 'face 'org-agenda-structure))
21040 (setq pos (point))
21041 (insert string "\n")
21042 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21043 (setq pos (point))
21044 (unless org-agenda-multi
21045 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21046 (add-text-properties pos (1- (point))
21047 (list 'face 'org-agenda-structure))))
21048 (when rtnall
21049 (insert (org-finalize-agenda-entries rtnall) "\n"))
21050 (goto-char (point-min))
21051 (org-fit-agenda-window)
21052 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21053 (org-finalize-agenda)
21054 (setq buffer-read-only t)))
21056 ;;; Agenda TODO list
21058 (defvar org-select-this-todo-keyword nil)
21059 (defvar org-last-arg nil)
21061 ;;;###autoload
21062 (defun org-todo-list (arg)
21063 "Show all TODO entries from all agenda file in a single list.
21064 The prefix arg can be used to select a specific TODO keyword and limit
21065 the list to these. When using \\[universal-argument], you will be prompted
21066 for a keyword. A numeric prefix directly selects the Nth keyword in
21067 `org-todo-keywords-1'."
21068 (interactive "P")
21069 (require 'calendar)
21070 (org-compile-prefix-format 'todo)
21071 (org-set-sorting-strategy 'todo)
21072 (org-prepare-agenda "TODO")
21073 (let* ((today (time-to-days (current-time)))
21074 (date (calendar-gregorian-from-absolute today))
21075 (kwds org-todo-keywords-for-agenda)
21076 (completion-ignore-case t)
21077 (org-select-this-todo-keyword
21078 (if (stringp arg) arg
21079 (and arg (integerp arg) (> arg 0)
21080 (nth (1- arg) kwds))))
21081 rtn rtnall files file pos)
21082 (when (equal arg '(4))
21083 (setq org-select-this-todo-keyword
21084 (completing-read "Keyword (or KWD1|K2D2|...): "
21085 (mapcar 'list kwds) nil nil)))
21086 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21087 (org-set-local 'org-last-arg arg)
21088 (setq org-agenda-redo-command
21089 '(org-todo-list (or current-prefix-arg org-last-arg)))
21090 (setq files (org-agenda-files)
21091 rtnall nil)
21092 (while (setq file (pop files))
21093 (catch 'nextfile
21094 (org-check-agenda-file file)
21095 (setq rtn (org-agenda-get-day-entries file date :todo))
21096 (setq rtnall (append rtnall rtn))))
21097 (if org-agenda-overriding-header
21098 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21099 nil 'face 'org-agenda-structure) "\n")
21100 (insert "Global list of TODO items of type: ")
21101 (add-text-properties (point-min) (1- (point))
21102 (list 'face 'org-agenda-structure))
21103 (setq pos (point))
21104 (insert (or org-select-this-todo-keyword "ALL") "\n")
21105 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21106 (setq pos (point))
21107 (unless org-agenda-multi
21108 (insert "Available with `N r': (0)ALL")
21109 (let ((n 0) s)
21110 (mapc (lambda (x)
21111 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21112 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21113 (insert "\n "))
21114 (insert " " s))
21115 kwds))
21116 (insert "\n"))
21117 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21118 (when rtnall
21119 (insert (org-finalize-agenda-entries rtnall) "\n"))
21120 (goto-char (point-min))
21121 (org-fit-agenda-window)
21122 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21123 (org-finalize-agenda)
21124 (setq buffer-read-only t)))
21126 ;;; Agenda tags match
21128 ;;;###autoload
21129 (defun org-tags-view (&optional todo-only match)
21130 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21131 The prefix arg TODO-ONLY limits the search to TODO entries."
21132 (interactive "P")
21133 (org-compile-prefix-format 'tags)
21134 (org-set-sorting-strategy 'tags)
21135 (let* ((org-tags-match-list-sublevels
21136 (if todo-only t org-tags-match-list-sublevels))
21137 (completion-ignore-case t)
21138 rtn rtnall files file pos matcher
21139 buffer)
21140 (setq matcher (org-make-tags-matcher match)
21141 match (car matcher) matcher (cdr matcher))
21142 (org-prepare-agenda (concat "TAGS " match))
21143 (setq org-agenda-redo-command
21144 (list 'org-tags-view (list 'quote todo-only)
21145 (list 'if 'current-prefix-arg nil match)))
21146 (setq files (org-agenda-files)
21147 rtnall nil)
21148 (while (setq file (pop files))
21149 (catch 'nextfile
21150 (org-check-agenda-file file)
21151 (setq buffer (if (file-exists-p file)
21152 (org-get-agenda-file-buffer file)
21153 (error "No such file %s" file)))
21154 (if (not buffer)
21155 ;; If file does not exist, merror message to agenda
21156 (setq rtn (list
21157 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21158 rtnall (append rtnall rtn))
21159 (with-current-buffer buffer
21160 (unless (org-mode-p)
21161 (error "Agenda file %s is not in `org-mode'" file))
21162 (save-excursion
21163 (save-restriction
21164 (if org-agenda-restrict
21165 (narrow-to-region org-agenda-restrict-begin
21166 org-agenda-restrict-end)
21167 (widen))
21168 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21169 (setq rtnall (append rtnall rtn))))))))
21170 (if org-agenda-overriding-header
21171 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21172 nil 'face 'org-agenda-structure) "\n")
21173 (insert "Headlines with TAGS match: ")
21174 (add-text-properties (point-min) (1- (point))
21175 (list 'face 'org-agenda-structure))
21176 (setq pos (point))
21177 (insert match "\n")
21178 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21179 (setq pos (point))
21180 (unless org-agenda-multi
21181 (insert "Press `C-u r' to search again with new search string\n"))
21182 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21183 (when rtnall
21184 (insert (org-finalize-agenda-entries rtnall) "\n"))
21185 (goto-char (point-min))
21186 (org-fit-agenda-window)
21187 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21188 (org-finalize-agenda)
21189 (setq buffer-read-only t)))
21191 ;;; Agenda Finding stuck projects
21193 (defvar org-agenda-skip-regexp nil
21194 "Regular expression used in skipping subtrees for the agenda.
21195 This is basically a temporary global variable that can be set and then
21196 used by user-defined selections using `org-agenda-skip-function'.")
21198 (defvar org-agenda-overriding-header nil
21199 "When this is set during todo and tags searches, will replace header.")
21201 (defun org-agenda-skip-subtree-when-regexp-matches ()
21202 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21203 If yes, it returns the end position of this tree, causing agenda commands
21204 to skip this subtree. This is a function that can be put into
21205 `org-agenda-skip-function' for the duration of a command."
21206 (let ((end (save-excursion (org-end-of-subtree t)))
21207 skip)
21208 (save-excursion
21209 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21210 (and skip end)))
21212 (defun org-agenda-skip-entry-if (&rest conditions)
21213 "Skip entry if any of CONDITIONS is true.
21214 See `org-agenda-skip-if' for details."
21215 (org-agenda-skip-if nil conditions))
21217 (defun org-agenda-skip-subtree-if (&rest conditions)
21218 "Skip entry if any of CONDITIONS is true.
21219 See `org-agenda-skip-if' for details."
21220 (org-agenda-skip-if t conditions))
21222 (defun org-agenda-skip-if (subtree conditions)
21223 "Checks current entity for CONDITIONS.
21224 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21225 the entry, i.e. the text before the next heading is checked.
21227 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21228 from different tests. Valid conditions are:
21230 scheduled Check if there is a scheduled cookie
21231 notscheduled Check if there is no scheduled cookie
21232 deadline Check if there is a deadline
21233 notdeadline Check if there is no deadline
21234 regexp Check if regexp matches
21235 notregexp Check if regexp does not match.
21237 The regexp is taken from the conditions list, it must come right after
21238 the `regexp' or `notregexp' element.
21240 If any of these conditions is met, this function returns the end point of
21241 the entity, causing the search to continue from there. This is a function
21242 that can be put into `org-agenda-skip-function' for the duration of a command."
21243 (let (beg end m)
21244 (org-back-to-heading t)
21245 (setq beg (point)
21246 end (if subtree
21247 (progn (org-end-of-subtree t) (point))
21248 (progn (outline-next-heading) (1- (point)))))
21249 (goto-char beg)
21250 (and
21252 (and (memq 'scheduled conditions)
21253 (re-search-forward org-scheduled-time-regexp end t))
21254 (and (memq 'notscheduled conditions)
21255 (not (re-search-forward org-scheduled-time-regexp end t)))
21256 (and (memq 'deadline conditions)
21257 (re-search-forward org-deadline-time-regexp end t))
21258 (and (memq 'notdeadline conditions)
21259 (not (re-search-forward org-deadline-time-regexp end t)))
21260 (and (setq m (memq 'regexp conditions))
21261 (stringp (nth 1 m))
21262 (re-search-forward (nth 1 m) end t))
21263 (and (setq m (memq 'notregexp conditions))
21264 (stringp (nth 1 m))
21265 (not (re-search-forward (nth 1 m) end t))))
21266 end)))
21268 ;;;###autoload
21269 (defun org-agenda-list-stuck-projects (&rest ignore)
21270 "Create agenda view for projects that are stuck.
21271 Stuck projects are project that have no next actions. For the definitions
21272 of what a project is and how to check if it stuck, customize the variable
21273 `org-stuck-projects'.
21274 MATCH is being ignored."
21275 (interactive)
21276 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21277 ;; FIXME: we could have used org-agenda-skip-if here.
21278 (org-agenda-overriding-header "List of stuck projects: ")
21279 (matcher (nth 0 org-stuck-projects))
21280 (todo (nth 1 org-stuck-projects))
21281 (todo-wds (if (member "*" todo)
21282 (progn
21283 (org-prepare-agenda-buffers (org-agenda-files))
21284 (org-delete-all
21285 org-done-keywords-for-agenda
21286 (copy-sequence org-todo-keywords-for-agenda)))
21287 todo))
21288 (todo-re (concat "^\\*+[ \t]+\\("
21289 (mapconcat 'identity todo-wds "\\|")
21290 "\\)\\>"))
21291 (tags (nth 2 org-stuck-projects))
21292 (tags-re (if (member "*" tags)
21293 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21294 (concat "^\\*+ .*:\\("
21295 (mapconcat 'identity tags "\\|")
21296 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21297 (gen-re (nth 3 org-stuck-projects))
21298 (re-list
21299 (delq nil
21300 (list
21301 (if todo todo-re)
21302 (if tags tags-re)
21303 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21304 gen-re)))))
21305 (setq org-agenda-skip-regexp
21306 (if re-list
21307 (mapconcat 'identity re-list "\\|")
21308 (error "No information how to identify unstuck projects")))
21309 (org-tags-view nil matcher)
21310 (with-current-buffer org-agenda-buffer-name
21311 (setq org-agenda-redo-command
21312 '(org-agenda-list-stuck-projects
21313 (or current-prefix-arg org-last-arg))))))
21315 ;;; Diary integration
21317 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21319 (defun org-get-entries-from-diary (date)
21320 "Get the (Emacs Calendar) diary entries for DATE."
21321 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21322 (diary-display-hook '(fancy-diary-display))
21323 (pop-up-frames nil)
21324 (list-diary-entries-hook
21325 (cons 'org-diary-default-entry list-diary-entries-hook))
21326 (diary-file-name-prefix-function nil) ; turn this feature off
21327 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21328 entries
21329 (org-disable-agenda-to-diary t))
21330 (save-excursion
21331 (save-window-excursion
21332 (funcall (if (fboundp 'diary-list-entries)
21333 'diary-list-entries 'list-diary-entries)
21334 date 1)))
21335 (if (not (get-buffer fancy-diary-buffer))
21336 (setq entries nil)
21337 (with-current-buffer fancy-diary-buffer
21338 (setq buffer-read-only nil)
21339 (if (zerop (buffer-size))
21340 ;; No entries
21341 (setq entries nil)
21342 ;; Omit the date and other unnecessary stuff
21343 (org-agenda-cleanup-fancy-diary)
21344 ;; Add prefix to each line and extend the text properties
21345 (if (zerop (buffer-size))
21346 (setq entries nil)
21347 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21348 (set-buffer-modified-p nil)
21349 (kill-buffer fancy-diary-buffer)))
21350 (when entries
21351 (setq entries (org-split-string entries "\n"))
21352 (setq entries
21353 (mapcar
21354 (lambda (x)
21355 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21356 ;; Extend the text properties to the beginning of the line
21357 (org-add-props x (text-properties-at (1- (length x)) x)
21358 'type "diary" 'date date))
21359 entries)))))
21361 (defun org-agenda-cleanup-fancy-diary ()
21362 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21363 This gets rid of the date, the underline under the date, and
21364 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21365 date. It also removes lines that contain only whitespace."
21366 (goto-char (point-min))
21367 (if (looking-at ".*?:[ \t]*")
21368 (progn
21369 (replace-match "")
21370 (re-search-forward "\n=+$" nil t)
21371 (replace-match "")
21372 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21373 (re-search-forward "\n=+$" nil t)
21374 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21375 (goto-char (point-min))
21376 (while (re-search-forward "^ +\n" nil t)
21377 (replace-match ""))
21378 (goto-char (point-min))
21379 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21380 (replace-match "")))
21382 ;; Make sure entries from the diary have the right text properties.
21383 (eval-after-load "diary-lib"
21384 '(if (boundp 'diary-modify-entry-list-string-function)
21385 ;; We can rely on the hook, nothing to do
21387 ;; Hook not avaiable, must use advice to make this work
21388 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21389 "Make the position visible."
21390 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21391 (stringp string)
21392 buffer-file-name)
21393 (setq string (org-modify-diary-entry-string string))))))
21395 (defun org-modify-diary-entry-string (string)
21396 "Add text properties to string, allowing org-mode to act on it."
21397 (org-add-props string nil
21398 'mouse-face 'highlight
21399 'keymap org-agenda-keymap
21400 'help-echo (if buffer-file-name
21401 (format "mouse-2 or RET jump to diary file %s"
21402 (abbreviate-file-name buffer-file-name))
21404 'org-agenda-diary-link t
21405 'org-marker (org-agenda-new-marker (point-at-bol))))
21407 (defun org-diary-default-entry ()
21408 "Add a dummy entry to the diary.
21409 Needed to avoid empty dates which mess up holiday display."
21410 ;; Catch the error if dealing with the new add-to-diary-alist
21411 (when org-disable-agenda-to-diary
21412 (condition-case nil
21413 (add-to-diary-list original-date "Org-mode dummy" "")
21414 (error
21415 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21417 ;;;###autoload
21418 (defun org-diary (&rest args)
21419 "Return diary information from org-files.
21420 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21421 It accesses org files and extracts information from those files to be
21422 listed in the diary. The function accepts arguments specifying what
21423 items should be listed. The following arguments are allowed:
21425 :timestamp List the headlines of items containing a date stamp or
21426 date range matching the selected date. Deadlines will
21427 also be listed, on the expiration day.
21429 :sexp List entries resulting from diary-like sexps.
21431 :deadline List any deadlines past due, or due within
21432 `org-deadline-warning-days'. The listing occurs only
21433 in the diary for *today*, not at any other date. If
21434 an entry is marked DONE, it is no longer listed.
21436 :scheduled List all items which are scheduled for the given date.
21437 The diary for *today* also contains items which were
21438 scheduled earlier and are not yet marked DONE.
21440 :todo List all TODO items from the org-file. This may be a
21441 long list - so this is not turned on by default.
21442 Like deadlines, these entries only show up in the
21443 diary for *today*, not at any other date.
21445 The call in the diary file should look like this:
21447 &%%(org-diary) ~/path/to/some/orgfile.org
21449 Use a separate line for each org file to check. Or, if you omit the file name,
21450 all files listed in `org-agenda-files' will be checked automatically:
21452 &%%(org-diary)
21454 If you don't give any arguments (as in the example above), the default
21455 arguments (:deadline :scheduled :timestamp :sexp) are used.
21456 So the example above may also be written as
21458 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21460 The function expects the lisp variables `entry' and `date' to be provided
21461 by the caller, because this is how the calendar works. Don't use this
21462 function from a program - use `org-agenda-get-day-entries' instead."
21463 (when (> (- (time-to-seconds (current-time))
21464 org-agenda-last-marker-time)
21466 (org-agenda-reset-markers))
21467 (org-compile-prefix-format 'agenda)
21468 (org-set-sorting-strategy 'agenda)
21469 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21470 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21471 (list entry)
21472 (org-agenda-files t)))
21473 file rtn results)
21474 (org-prepare-agenda-buffers files)
21475 ;; If this is called during org-agenda, don't return any entries to
21476 ;; the calendar. Org Agenda will list these entries itself.
21477 (if org-disable-agenda-to-diary (setq files nil))
21478 (while (setq file (pop files))
21479 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21480 (setq results (append results rtn)))
21481 (if results
21482 (concat (org-finalize-agenda-entries results) "\n"))))
21484 ;;; Agenda entry finders
21486 (defun org-agenda-get-day-entries (file date &rest args)
21487 "Does the work for `org-diary' and `org-agenda'.
21488 FILE is the path to a file to be checked for entries. DATE is date like
21489 the one returned by `calendar-current-date'. ARGS are symbols indicating
21490 which kind of entries should be extracted. For details about these, see
21491 the documentation of `org-diary'."
21492 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21493 (let* ((org-startup-folded nil)
21494 (org-startup-align-all-tables nil)
21495 (buffer (if (file-exists-p file)
21496 (org-get-agenda-file-buffer file)
21497 (error "No such file %s" file)))
21498 arg results rtn)
21499 (if (not buffer)
21500 ;; If file does not exist, make sure an error message ends up in diary
21501 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21502 (with-current-buffer buffer
21503 (unless (org-mode-p)
21504 (error "Agenda file %s is not in `org-mode'" file))
21505 (let ((case-fold-search nil))
21506 (save-excursion
21507 (save-restriction
21508 (if org-agenda-restrict
21509 (narrow-to-region org-agenda-restrict-begin
21510 org-agenda-restrict-end)
21511 (widen))
21512 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21513 (while (setq arg (pop args))
21514 (cond
21515 ((and (eq arg :todo)
21516 (equal date (calendar-current-date)))
21517 (setq rtn (org-agenda-get-todos))
21518 (setq results (append results rtn)))
21519 ((eq arg :timestamp)
21520 (setq rtn (org-agenda-get-blocks))
21521 (setq results (append results rtn))
21522 (setq rtn (org-agenda-get-timestamps))
21523 (setq results (append results rtn)))
21524 ((eq arg :sexp)
21525 (setq rtn (org-agenda-get-sexps))
21526 (setq results (append results rtn)))
21527 ((eq arg :scheduled)
21528 (setq rtn (org-agenda-get-scheduled))
21529 (setq results (append results rtn)))
21530 ((eq arg :closed)
21531 (setq rtn (org-agenda-get-closed))
21532 (setq results (append results rtn)))
21533 ((eq arg :deadline)
21534 (setq rtn (org-agenda-get-deadlines))
21535 (setq results (append results rtn))))))))
21536 results))))
21538 (defun org-entry-is-todo-p ()
21539 (member (org-get-todo-state) org-not-done-keywords))
21541 (defun org-entry-is-done-p ()
21542 (member (org-get-todo-state) org-done-keywords))
21544 (defun org-get-todo-state ()
21545 (save-excursion
21546 (org-back-to-heading t)
21547 (and (looking-at org-todo-line-regexp)
21548 (match-end 2)
21549 (match-string 2))))
21551 (defun org-at-date-range-p (&optional inactive-ok)
21552 "Is the cursor inside a date range?"
21553 (interactive)
21554 (save-excursion
21555 (catch 'exit
21556 (let ((pos (point)))
21557 (skip-chars-backward "^[<\r\n")
21558 (skip-chars-backward "<[")
21559 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21560 (>= (match-end 0) pos)
21561 (throw 'exit t))
21562 (skip-chars-backward "^<[\r\n")
21563 (skip-chars-backward "<[")
21564 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21565 (>= (match-end 0) pos)
21566 (throw 'exit t)))
21567 nil)))
21569 (defun org-agenda-get-todos ()
21570 "Return the TODO information for agenda display."
21571 (let* ((props (list 'face nil
21572 'done-face 'org-done
21573 'org-not-done-regexp org-not-done-regexp
21574 'org-todo-regexp org-todo-regexp
21575 'mouse-face 'highlight
21576 'keymap org-agenda-keymap
21577 'help-echo
21578 (format "mouse-2 or RET jump to org file %s"
21579 (abbreviate-file-name buffer-file-name))))
21580 ;; FIXME: get rid of the \n at some point but watch out
21581 (regexp (concat "^\\*+[ \t]+\\("
21582 (if org-select-this-todo-keyword
21583 (if (equal org-select-this-todo-keyword "*")
21584 org-todo-regexp
21585 (concat "\\<\\("
21586 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21587 "\\)\\>"))
21588 org-not-done-regexp)
21589 "[^\n\r]*\\)"))
21590 marker priority category tags
21591 ee txt beg end)
21592 (goto-char (point-min))
21593 (while (re-search-forward regexp nil t)
21594 (catch :skip
21595 (save-match-data
21596 (beginning-of-line)
21597 (setq beg (point) end (progn (outline-next-heading) (point)))
21598 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21599 (re-search-forward org-ts-regexp end t))
21600 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21601 (re-search-forward org-scheduled-time-regexp end t))
21602 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21603 (re-search-forward org-deadline-time-regexp end t)
21604 (org-deadline-close (match-string 1))))
21605 (goto-char (1+ beg))
21606 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21607 (throw :skip nil)))
21608 (goto-char beg)
21609 (org-agenda-skip)
21610 (goto-char (match-beginning 1))
21611 (setq marker (org-agenda-new-marker (match-beginning 0))
21612 category (org-get-category)
21613 tags (org-get-tags-at (point))
21614 txt (org-format-agenda-item "" (match-string 1) category tags)
21615 priority (1+ (org-get-priority txt)))
21616 (org-add-props txt props
21617 'org-marker marker 'org-hd-marker marker
21618 'priority priority 'org-category category
21619 'type "todo")
21620 (push txt ee)
21621 (if org-agenda-todo-list-sublevels
21622 (goto-char (match-end 1))
21623 (org-end-of-subtree 'invisible))))
21624 (nreverse ee)))
21626 (defconst org-agenda-no-heading-message
21627 "No heading for this item in buffer or region.")
21629 (defun org-agenda-get-timestamps ()
21630 "Return the date stamp information for agenda display."
21631 (let* ((props (list 'face nil
21632 'org-not-done-regexp org-not-done-regexp
21633 'org-todo-regexp org-todo-regexp
21634 'mouse-face 'highlight
21635 'keymap org-agenda-keymap
21636 'help-echo
21637 (format "mouse-2 or RET jump to org file %s"
21638 (abbreviate-file-name buffer-file-name))))
21639 (d1 (calendar-absolute-from-gregorian date))
21640 (remove-re
21641 (concat
21642 (regexp-quote
21643 (format-time-string
21644 "<%Y-%m-%d"
21645 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21646 ".*?>"))
21647 (regexp
21648 (concat
21649 (regexp-quote
21650 (substring
21651 (format-time-string
21652 (car org-time-stamp-formats)
21653 (apply 'encode-time ; DATE bound by calendar
21654 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21655 0 11))
21656 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21657 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21658 marker hdmarker deadlinep scheduledp donep tmp priority category
21659 ee txt timestr tags b0 b3 e3 head)
21660 (goto-char (point-min))
21661 (while (re-search-forward regexp nil t)
21662 (setq b0 (match-beginning 0)
21663 b3 (match-beginning 3) e3 (match-end 3))
21664 (catch :skip
21665 (and (org-at-date-range-p) (throw :skip nil))
21666 (org-agenda-skip)
21667 (if (and (match-end 1)
21668 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21669 (throw :skip nil))
21670 (if (and e3
21671 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21672 (throw :skip nil))
21673 (setq marker (org-agenda-new-marker b0)
21674 category (org-get-category b0)
21675 tmp (buffer-substring (max (point-min)
21676 (- b0 org-ds-keyword-length))
21678 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21679 deadlinep (string-match org-deadline-regexp tmp)
21680 scheduledp (string-match org-scheduled-regexp tmp)
21681 donep (org-entry-is-done-p))
21682 (if (or scheduledp deadlinep) (throw :skip t))
21683 (if (string-match ">" timestr)
21684 ;; substring should only run to end of time stamp
21685 (setq timestr (substring timestr 0 (match-end 0))))
21686 (save-excursion
21687 (if (re-search-backward "^\\*+ " nil t)
21688 (progn
21689 (goto-char (match-beginning 0))
21690 (setq hdmarker (org-agenda-new-marker)
21691 tags (org-get-tags-at))
21692 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21693 (setq head (match-string 1))
21694 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21695 (setq txt (org-format-agenda-item
21696 nil head category tags timestr nil
21697 remove-re)))
21698 (setq txt org-agenda-no-heading-message))
21699 (setq priority (org-get-priority txt))
21700 (org-add-props txt props
21701 'org-marker marker 'org-hd-marker hdmarker)
21702 (org-add-props txt nil 'priority priority
21703 'org-category category 'date date
21704 'type "timestamp")
21705 (push txt ee))
21706 (outline-next-heading)))
21707 (nreverse ee)))
21709 (defun org-agenda-get-sexps ()
21710 "Return the sexp information for agenda display."
21711 (require 'diary-lib)
21712 (let* ((props (list 'face nil
21713 'mouse-face 'highlight
21714 'keymap org-agenda-keymap
21715 'help-echo
21716 (format "mouse-2 or RET jump to org file %s"
21717 (abbreviate-file-name buffer-file-name))))
21718 (regexp "^&?%%(")
21719 marker category ee txt tags entry result beg b sexp sexp-entry)
21720 (goto-char (point-min))
21721 (while (re-search-forward regexp nil t)
21722 (catch :skip
21723 (org-agenda-skip)
21724 (setq beg (match-beginning 0))
21725 (goto-char (1- (match-end 0)))
21726 (setq b (point))
21727 (forward-sexp 1)
21728 (setq sexp (buffer-substring b (point)))
21729 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21730 (org-trim (match-string 1))
21731 ""))
21732 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21733 (when result
21734 (setq marker (org-agenda-new-marker beg)
21735 category (org-get-category beg))
21737 (if (string-match "\\S-" result)
21738 (setq txt result)
21739 (setq txt "SEXP entry returned empty string"))
21741 (setq txt (org-format-agenda-item
21742 "" txt category tags 'time))
21743 (org-add-props txt props 'org-marker marker)
21744 (org-add-props txt nil
21745 'org-category category 'date date
21746 'type "sexp")
21747 (push txt ee))))
21748 (nreverse ee)))
21750 (defun org-agenda-get-closed ()
21751 "Return the logged TODO entries for agenda display."
21752 (let* ((props (list 'mouse-face 'highlight
21753 'org-not-done-regexp org-not-done-regexp
21754 'org-todo-regexp org-todo-regexp
21755 'keymap org-agenda-keymap
21756 'help-echo
21757 (format "mouse-2 or RET jump to org file %s"
21758 (abbreviate-file-name buffer-file-name))))
21759 (regexp (concat
21760 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21761 (regexp-quote
21762 (substring
21763 (format-time-string
21764 (car org-time-stamp-formats)
21765 (apply 'encode-time ; DATE bound by calendar
21766 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21767 1 11))))
21768 marker hdmarker priority category tags closedp
21769 ee txt timestr)
21770 (goto-char (point-min))
21771 (while (re-search-forward regexp nil t)
21772 (catch :skip
21773 (org-agenda-skip)
21774 (setq marker (org-agenda-new-marker (match-beginning 0))
21775 closedp (equal (match-string 1) org-closed-string)
21776 category (org-get-category (match-beginning 0))
21777 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21778 ;; donep (org-entry-is-done-p)
21780 (if (string-match "\\]" timestr)
21781 ;; substring should only run to end of time stamp
21782 (setq timestr (substring timestr 0 (match-end 0))))
21783 (save-excursion
21784 (if (re-search-backward "^\\*+ " nil t)
21785 (progn
21786 (goto-char (match-beginning 0))
21787 (setq hdmarker (org-agenda-new-marker)
21788 tags (org-get-tags-at))
21789 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21790 (setq txt (org-format-agenda-item
21791 (if closedp "Closed: " "Clocked: ")
21792 (match-string 1) category tags timestr)))
21793 (setq txt org-agenda-no-heading-message))
21794 (setq priority 100000)
21795 (org-add-props txt props
21796 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21797 'priority priority 'org-category category
21798 'type "closed" 'date date
21799 'undone-face 'org-warning 'done-face 'org-done)
21800 (push txt ee))
21801 (goto-char (point-at-eol))))
21802 (nreverse ee)))
21804 (defun org-agenda-get-deadlines ()
21805 "Return the deadline information for agenda display."
21806 (let* ((props (list 'mouse-face 'highlight
21807 'org-not-done-regexp org-not-done-regexp
21808 'org-todo-regexp org-todo-regexp
21809 'keymap org-agenda-keymap
21810 'help-echo
21811 (format "mouse-2 or RET jump to org file %s"
21812 (abbreviate-file-name buffer-file-name))))
21813 (regexp org-deadline-time-regexp)
21814 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21815 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21816 d2 diff dfrac wdays pos pos1 category tags
21817 ee txt head face s upcomingp donep timestr)
21818 (goto-char (point-min))
21819 (while (re-search-forward regexp nil t)
21820 (catch :skip
21821 (org-agenda-skip)
21822 (setq s (match-string 1)
21823 pos (1- (match-beginning 1))
21824 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21825 diff (- d2 d1)
21826 wdays (org-get-wdays s)
21827 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21828 upcomingp (and todayp (> diff 0)))
21829 ;; When to show a deadline in the calendar:
21830 ;; If the expiration is within wdays warning time.
21831 ;; Past-due deadlines are only shown on the current date
21832 (if (or (and (<= diff wdays)
21833 (and todayp (not org-agenda-only-exact-dates)))
21834 (= diff 0))
21835 (save-excursion
21836 (setq category (org-get-category))
21837 (if (re-search-backward "^\\*+[ \t]+" nil t)
21838 (progn
21839 (goto-char (match-end 0))
21840 (setq pos1 (match-beginning 0))
21841 (setq tags (org-get-tags-at pos1))
21842 (setq head (buffer-substring-no-properties
21843 (point)
21844 (progn (skip-chars-forward "^\r\n")
21845 (point))))
21846 (setq donep (string-match org-looking-at-done-regexp head))
21847 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21848 (setq timestr
21849 (concat (substring s (match-beginning 1)) " "))
21850 (setq timestr 'time))
21851 (if (and donep
21852 (or org-agenda-skip-deadline-if-done
21853 (not (= diff 0))))
21854 (setq txt nil)
21855 (setq txt (org-format-agenda-item
21856 (if (= diff 0)
21857 (car org-agenda-deadline-leaders)
21858 (format (nth 1 org-agenda-deadline-leaders)
21859 diff))
21860 head category tags timestr))))
21861 (setq txt org-agenda-no-heading-message))
21862 (when txt
21863 (setq face (org-agenda-deadline-face dfrac wdays))
21864 (org-add-props txt props
21865 'org-marker (org-agenda-new-marker pos)
21866 'org-hd-marker (org-agenda-new-marker pos1)
21867 'priority (+ (- diff)
21868 (org-get-priority txt))
21869 'org-category category
21870 'type (if upcomingp "upcoming-deadline" "deadline")
21871 'date (if upcomingp date d2)
21872 'face (if donep 'org-done face)
21873 'undone-face face 'done-face 'org-done)
21874 (push txt ee))))))
21875 (nreverse ee)))
21877 (defun org-agenda-deadline-face (fraction &optional wdays)
21878 "Return the face to displaying a deadline item.
21879 FRACTION is what fraction of the head-warning time has passed."
21880 (if (equal wdays 0) (setq fraction 1.))
21881 (let ((faces org-agenda-deadline-faces) f)
21882 (catch 'exit
21883 (while (setq f (pop faces))
21884 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21886 (defun org-agenda-get-scheduled ()
21887 "Return the scheduled information for agenda display."
21888 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21889 'org-todo-regexp org-todo-regexp
21890 'done-face 'org-done
21891 'mouse-face 'highlight
21892 'keymap org-agenda-keymap
21893 'help-echo
21894 (format "mouse-2 or RET jump to org file %s"
21895 (abbreviate-file-name buffer-file-name))))
21896 (regexp org-scheduled-time-regexp)
21897 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21898 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21899 d2 diff pos pos1 category tags
21900 ee txt head pastschedp donep face timestr s)
21901 (goto-char (point-min))
21902 (while (re-search-forward regexp nil t)
21903 (catch :skip
21904 (org-agenda-skip)
21905 (setq s (match-string 1)
21906 pos (1- (match-beginning 1))
21907 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21908 ;;; is this right?
21909 ;;; do we need to do this for deadleine too????
21910 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21911 diff (- d2 d1))
21912 (setq pastschedp (and todayp (< diff 0)))
21913 ;; When to show a scheduled item in the calendar:
21914 ;; If it is on or past the date.
21915 (if (or (and (< diff 0)
21916 (and todayp (not org-agenda-only-exact-dates)))
21917 (= diff 0))
21918 (save-excursion
21919 (setq category (org-get-category))
21920 (if (re-search-backward "^\\*+[ \t]+" nil t)
21921 (progn
21922 (goto-char (match-end 0))
21923 (setq pos1 (match-beginning 0))
21924 (setq tags (org-get-tags-at))
21925 (setq head (buffer-substring-no-properties
21926 (point)
21927 (progn (skip-chars-forward "^\r\n") (point))))
21928 (setq donep (string-match org-looking-at-done-regexp head))
21929 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21930 (setq timestr
21931 (concat (substring s (match-beginning 1)) " "))
21932 (setq timestr 'time))
21933 (if (and donep
21934 (or org-agenda-skip-scheduled-if-done
21935 (not (= diff 0))))
21936 (setq txt nil)
21937 (setq txt (org-format-agenda-item
21938 (if (= diff 0)
21939 (car org-agenda-scheduled-leaders)
21940 (format (nth 1 org-agenda-scheduled-leaders)
21941 (- 1 diff)))
21942 head category tags timestr))))
21943 (setq txt org-agenda-no-heading-message))
21944 (when txt
21945 (setq face (if pastschedp
21946 'org-scheduled-previously
21947 'org-scheduled-today))
21948 (org-add-props txt props
21949 'undone-face face
21950 'face (if donep 'org-done face)
21951 'org-marker (org-agenda-new-marker pos)
21952 'org-hd-marker (org-agenda-new-marker pos1)
21953 'type (if pastschedp "past-scheduled" "scheduled")
21954 'date (if pastschedp d2 date)
21955 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21956 'org-category category)
21957 (push txt ee))))))
21958 (nreverse ee)))
21960 (defun org-agenda-get-blocks ()
21961 "Return the date-range information for agenda display."
21962 (let* ((props (list 'face nil
21963 'org-not-done-regexp org-not-done-regexp
21964 'org-todo-regexp org-todo-regexp
21965 'mouse-face 'highlight
21966 'keymap org-agenda-keymap
21967 'help-echo
21968 (format "mouse-2 or RET jump to org file %s"
21969 (abbreviate-file-name buffer-file-name))))
21970 (regexp org-tr-regexp)
21971 (d0 (calendar-absolute-from-gregorian date))
21972 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21973 donep head)
21974 (goto-char (point-min))
21975 (while (re-search-forward regexp nil t)
21976 (catch :skip
21977 (org-agenda-skip)
21978 (setq pos (point))
21979 (setq timestr (match-string 0)
21980 s1 (match-string 1)
21981 s2 (match-string 2)
21982 d1 (time-to-days (org-time-string-to-time s1))
21983 d2 (time-to-days (org-time-string-to-time s2)))
21984 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21985 ;; Only allow days between the limits, because the normal
21986 ;; date stamps will catch the limits.
21987 (save-excursion
21988 (setq marker (org-agenda-new-marker (point)))
21989 (setq category (org-get-category))
21990 (if (re-search-backward "^\\*+ " nil t)
21991 (progn
21992 (goto-char (match-beginning 0))
21993 (setq hdmarker (org-agenda-new-marker (point)))
21994 (setq tags (org-get-tags-at))
21995 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21996 (setq head (match-string 1))
21997 (and org-agenda-skip-timestamp-if-done
21998 (org-entry-is-done-p)
21999 (throw :skip t))
22000 (setq txt (org-format-agenda-item
22001 (format (if (= d1 d2) "" "(%d/%d): ")
22002 (1+ (- d0 d1)) (1+ (- d2 d1)))
22003 head category tags
22004 (if (= d0 d1) timestr))))
22005 (setq txt org-agenda-no-heading-message))
22006 (org-add-props txt props
22007 'org-marker marker 'org-hd-marker hdmarker
22008 'type "block" 'date date
22009 'priority (org-get-priority txt) 'org-category category)
22010 (push txt ee)))
22011 (goto-char pos)))
22012 ;; Sort the entries by expiration date.
22013 (nreverse ee)))
22015 ;;; Agenda presentation and sorting
22017 (defconst org-plain-time-of-day-regexp
22018 (concat
22019 "\\(\\<[012]?[0-9]"
22020 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22021 "\\(--?"
22022 "\\(\\<[012]?[0-9]"
22023 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22024 "\\)?")
22025 "Regular expression to match a plain time or time range.
22026 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22027 groups carry important information:
22028 0 the full match
22029 1 the first time, range or not
22030 8 the second time, if it is a range.")
22032 (defconst org-plain-time-extension-regexp
22033 (concat
22034 "\\(\\<[012]?[0-9]"
22035 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22036 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22037 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22038 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22039 groups carry important information:
22040 0 the full match
22041 7 hours of duration
22042 9 minutes of duration")
22044 (defconst org-stamp-time-of-day-regexp
22045 (concat
22046 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22047 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22048 "\\(--?"
22049 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22050 "Regular expression to match a timestamp time or time range.
22051 After a match, the following groups carry important information:
22052 0 the full match
22053 1 date plus weekday, for backreferencing to make sure both times on same day
22054 2 the first time, range or not
22055 4 the second time, if it is a range.")
22057 (defvar org-prefix-has-time nil
22058 "A flag, set by `org-compile-prefix-format'.
22059 The flag is set if the currently compiled format contains a `%t'.")
22060 (defvar org-prefix-has-tag nil
22061 "A flag, set by `org-compile-prefix-format'.
22062 The flag is set if the currently compiled format contains a `%T'.")
22064 (defun org-format-agenda-item (extra txt &optional category tags dotime
22065 noprefix remove-re)
22066 "Format TXT to be inserted into the agenda buffer.
22067 In particular, it adds the prefix and corresponding text properties. EXTRA
22068 must be a string and replaces the `%s' specifier in the prefix format.
22069 CATEGORY (string, symbol or nil) may be used to overrule the default
22070 category taken from local variable or file name. It will replace the `%c'
22071 specifier in the format. DOTIME, when non-nil, indicates that a
22072 time-of-day should be extracted from TXT for sorting of this entry, and for
22073 the `%t' specifier in the format. When DOTIME is a string, this string is
22074 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22075 only the correctly processes TXT should be returned - this is used by
22076 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22077 Any match of REMOVE-RE will be removed from TXT."
22078 (save-match-data
22079 ;; Diary entries sometimes have extra whitespace at the beginning
22080 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22081 (let* ((category (or category
22082 org-category
22083 (if buffer-file-name
22084 (file-name-sans-extension
22085 (file-name-nondirectory buffer-file-name))
22086 "")))
22087 (tag (if tags (nth (1- (length tags)) tags) ""))
22088 time ; time and tag are needed for the eval of the prefix format
22089 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22090 (time-of-day (and dotime (org-get-time-of-day ts)))
22091 stamp plain s0 s1 s2 rtn srp)
22092 (when (and dotime time-of-day org-prefix-has-time)
22093 ;; Extract starting and ending time and move them to prefix
22094 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22095 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22096 (setq s0 (match-string 0 ts)
22097 srp (and stamp (match-end 3))
22098 s1 (match-string (if plain 1 2) ts)
22099 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22101 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22102 ;; them, we might want to remove them there to avoid duplication.
22103 ;; The user can turn this off with a variable.
22104 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22105 (string-match (concat (regexp-quote s0) " *") txt)
22106 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22107 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22108 (= (match-beginning 0) 0)
22110 (setq txt (replace-match "" nil nil txt))))
22111 ;; Normalize the time(s) to 24 hour
22112 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22113 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22115 (when (and s1 (not s2) org-agenda-default-appointment-duration
22116 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22117 (let ((m (+ (string-to-number (match-string 2 s1))
22118 (* 60 (string-to-number (match-string 1 s1)))
22119 org-agenda-default-appointment-duration))
22121 (setq h (/ m 60) m (- m (* h 60)))
22122 (setq s2 (format "%02d:%02d" h m))))
22124 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22125 txt)
22126 ;; Tags are in the string
22127 (if (or (eq org-agenda-remove-tags t)
22128 (and org-agenda-remove-tags
22129 org-prefix-has-tag))
22130 (setq txt (replace-match "" t t txt))
22131 (setq txt (replace-match
22132 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22133 (match-string 2 txt))
22134 t t txt))))
22136 (when remove-re
22137 (while (string-match remove-re txt)
22138 (setq txt (replace-match "" t t txt))))
22140 ;; Create the final string
22141 (if noprefix
22142 (setq rtn txt)
22143 ;; Prepare the variables needed in the eval of the compiled format
22144 (setq time (cond (s2 (concat s1 "-" s2))
22145 (s1 (concat s1 "......"))
22146 (t ""))
22147 extra (or extra "")
22148 category (if (symbolp category) (symbol-name category) category))
22149 ;; Evaluate the compiled format
22150 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22152 ;; And finally add the text properties
22153 (org-add-props rtn nil
22154 'org-category (downcase category) 'tags tags
22155 'org-highest-priority org-highest-priority
22156 'org-lowest-priority org-lowest-priority
22157 'prefix-length (- (length rtn) (length txt))
22158 'time-of-day time-of-day
22159 'txt txt
22160 'time time
22161 'extra extra
22162 'dotime dotime))))
22164 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22165 (defvar org-agenda-sorting-strategy-selected nil)
22167 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22168 (catch 'exit
22169 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22170 ((and todayp (member 'today (car org-agenda-time-grid))))
22171 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22172 ((member 'weekly (car org-agenda-time-grid)))
22173 (t (throw 'exit list)))
22174 (let* ((have (delq nil (mapcar
22175 (lambda (x) (get-text-property 1 'time-of-day x))
22176 list)))
22177 (string (nth 1 org-agenda-time-grid))
22178 (gridtimes (nth 2 org-agenda-time-grid))
22179 (req (car org-agenda-time-grid))
22180 (remove (member 'remove-match req))
22181 new time)
22182 (if (and (member 'require-timed req) (not have))
22183 ;; don't show empty grid
22184 (throw 'exit list))
22185 (while (setq time (pop gridtimes))
22186 (unless (and remove (member time have))
22187 (setq time (int-to-string time))
22188 (push (org-format-agenda-item
22189 nil string "" nil
22190 (concat (substring time 0 -2) ":" (substring time -2)))
22191 new)
22192 (put-text-property
22193 1 (length (car new)) 'face 'org-time-grid (car new))))
22194 (if (member 'time-up org-agenda-sorting-strategy-selected)
22195 (append new list)
22196 (append list new)))))
22198 (defun org-compile-prefix-format (key)
22199 "Compile the prefix format into a Lisp form that can be evaluated.
22200 The resulting form is returned and stored in the variable
22201 `org-prefix-format-compiled'."
22202 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22203 (let ((s (cond
22204 ((stringp org-agenda-prefix-format)
22205 org-agenda-prefix-format)
22206 ((assq key org-agenda-prefix-format)
22207 (cdr (assq key org-agenda-prefix-format)))
22208 (t " %-12:c%?-12t% s")))
22209 (start 0)
22210 varform vars var e c f opt)
22211 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22212 s start)
22213 (setq var (cdr (assoc (match-string 4 s)
22214 '(("c" . category) ("t" . time) ("s" . extra)
22215 ("T" . tag))))
22216 c (or (match-string 3 s) "")
22217 opt (match-beginning 1)
22218 start (1+ (match-beginning 0)))
22219 (if (equal var 'time) (setq org-prefix-has-time t))
22220 (if (equal var 'tag) (setq org-prefix-has-tag t))
22221 (setq f (concat "%" (match-string 2 s) "s"))
22222 (if opt
22223 (setq varform
22224 `(if (equal "" ,var)
22226 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22227 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22228 (setq s (replace-match "%s" t nil s))
22229 (push varform vars))
22230 (setq vars (nreverse vars))
22231 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22233 (defun org-set-sorting-strategy (key)
22234 (if (symbolp (car org-agenda-sorting-strategy))
22235 ;; the old format
22236 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22237 (setq org-agenda-sorting-strategy-selected
22238 (or (cdr (assq key org-agenda-sorting-strategy))
22239 (cdr (assq 'agenda org-agenda-sorting-strategy))
22240 '(time-up category-keep priority-down)))))
22242 (defun org-get-time-of-day (s &optional string mod24)
22243 "Check string S for a time of day.
22244 If found, return it as a military time number between 0 and 2400.
22245 If not found, return nil.
22246 The optional STRING argument forces conversion into a 5 character wide string
22247 HH:MM."
22248 (save-match-data
22249 (when
22250 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22251 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22252 (let* ((h (string-to-number (match-string 1 s)))
22253 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22254 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22255 (am-p (equal ampm "am"))
22256 (h1 (cond ((not ampm) h)
22257 ((= h 12) (if am-p 0 12))
22258 (t (+ h (if am-p 0 12)))))
22259 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22260 (mod h1 24) h1))
22261 (t0 (+ (* 100 h2) m))
22262 (t1 (concat (if (>= h1 24) "+" " ")
22263 (if (< t0 100) "0" "")
22264 (if (< t0 10) "0" "")
22265 (int-to-string t0))))
22266 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22268 (defun org-finalize-agenda-entries (list &optional nosort)
22269 "Sort and concatenate the agenda items."
22270 (setq list (mapcar 'org-agenda-highlight-todo list))
22271 (if nosort
22272 list
22273 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22275 (defun org-agenda-highlight-todo (x)
22276 (let (re pl)
22277 (if (eq x 'line)
22278 (save-excursion
22279 (beginning-of-line 1)
22280 (setq re (get-text-property (point) 'org-todo-regexp))
22281 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22282 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22283 (add-text-properties (match-beginning 0) (match-end 0)
22284 (list 'face (org-get-todo-face 0)))
22285 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22286 (delete-region (match-beginning 1) (1- (match-end 0)))
22287 (goto-char (match-beginning 1))
22288 (insert (format org-agenda-todo-keyword-format s)))))
22289 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22290 pl (get-text-property 0 'prefix-length x))
22291 (when (and re
22292 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22293 x (or pl 0)) pl))
22294 (add-text-properties
22295 (or (match-end 1) (match-end 0)) (match-end 0)
22296 (list 'face (org-get-todo-face (match-string 2 x)))
22298 (setq x (concat (substring x 0 (match-end 1))
22299 (format org-agenda-todo-keyword-format
22300 (match-string 2 x))
22302 (substring x (match-end 3)))))
22303 x)))
22305 (defsubst org-cmp-priority (a b)
22306 "Compare the priorities of string A and B."
22307 (let ((pa (or (get-text-property 1 'priority a) 0))
22308 (pb (or (get-text-property 1 'priority b) 0)))
22309 (cond ((> pa pb) +1)
22310 ((< pa pb) -1)
22311 (t nil))))
22313 (defsubst org-cmp-category (a b)
22314 "Compare the string values of categories of strings A and B."
22315 (let ((ca (or (get-text-property 1 'org-category a) ""))
22316 (cb (or (get-text-property 1 'org-category b) "")))
22317 (cond ((string-lessp ca cb) -1)
22318 ((string-lessp cb ca) +1)
22319 (t nil))))
22321 (defsubst org-cmp-tag (a b)
22322 "Compare the string values of categories of strings A and B."
22323 (let ((ta (car (last (get-text-property 1 'tags a))))
22324 (tb (car (last (get-text-property 1 'tags b)))))
22325 (cond ((not ta) +1)
22326 ((not tb) -1)
22327 ((string-lessp ta tb) -1)
22328 ((string-lessp tb ta) +1)
22329 (t nil))))
22331 (defsubst org-cmp-time (a b)
22332 "Compare the time-of-day values of strings A and B."
22333 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22334 (ta (or (get-text-property 1 'time-of-day a) def))
22335 (tb (or (get-text-property 1 'time-of-day b) def)))
22336 (cond ((< ta tb) -1)
22337 ((< tb ta) +1)
22338 (t nil))))
22340 (defun org-entries-lessp (a b)
22341 "Predicate for sorting agenda entries."
22342 ;; The following variables will be used when the form is evaluated.
22343 ;; So even though the compiler complains, keep them.
22344 (let* ((time-up (org-cmp-time a b))
22345 (time-down (if time-up (- time-up) nil))
22346 (priority-up (org-cmp-priority a b))
22347 (priority-down (if priority-up (- priority-up) nil))
22348 (category-up (org-cmp-category a b))
22349 (category-down (if category-up (- category-up) nil))
22350 (category-keep (if category-up +1 nil))
22351 (tag-up (org-cmp-tag a b))
22352 (tag-down (if tag-up (- tag-up) nil)))
22353 (cdr (assoc
22354 (eval (cons 'or org-agenda-sorting-strategy-selected))
22355 '((-1 . t) (1 . nil) (nil . nil))))))
22357 ;;; Agenda restriction lock
22359 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22360 "Overlay to mark the headline to which arenda commands are restricted.")
22361 (org-overlay-put org-agenda-restriction-lock-overlay
22362 'face 'org-agenda-restriction-lock)
22363 (org-overlay-put org-agenda-restriction-lock-overlay
22364 'help-echo "Agendas are currently limited to this subtree.")
22365 (org-detach-overlay org-agenda-restriction-lock-overlay)
22366 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22367 "Overlay marking the agenda restriction line in speedbar.")
22368 (org-overlay-put org-speedbar-restriction-lock-overlay
22369 'face 'org-agenda-restriction-lock)
22370 (org-overlay-put org-speedbar-restriction-lock-overlay
22371 'help-echo "Agendas are currently limited to this item.")
22372 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22374 (defun org-agenda-set-restriction-lock (&optional type)
22375 "Set restriction lock for agenda, to current subtree or file.
22376 Restriction will be the file if TYPE is `file', or if type is the
22377 universal prefix '(4), or if the cursor is before the first headline
22378 in the file. Otherwise, restriction will be to the current subtree."
22379 (interactive "P")
22380 (and (equal type '(4)) (setq type 'file))
22381 (setq type (cond
22382 (type type)
22383 ((org-at-heading-p) 'subtree)
22384 ((condition-case nil (org-back-to-heading t) (error nil))
22385 'subtree)
22386 (t 'file)))
22387 (if (eq type 'subtree)
22388 (progn
22389 (setq org-agenda-restrict t)
22390 (setq org-agenda-overriding-restriction 'subtree)
22391 (put 'org-agenda-files 'org-restrict
22392 (list (buffer-file-name (buffer-base-buffer))))
22393 (org-back-to-heading t)
22394 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22395 (move-marker org-agenda-restrict-begin (point))
22396 (move-marker org-agenda-restrict-end
22397 (save-excursion (org-end-of-subtree t)))
22398 (message "Locking agenda restriction to subtree"))
22399 (put 'org-agenda-files 'org-restrict
22400 (list (buffer-file-name (buffer-base-buffer))))
22401 (setq org-agenda-restrict nil)
22402 (setq org-agenda-overriding-restriction 'file)
22403 (move-marker org-agenda-restrict-begin nil)
22404 (move-marker org-agenda-restrict-end nil)
22405 (message "Locking agenda restriction to file"))
22406 (setq current-prefix-arg nil)
22407 (org-agenda-maybe-redo))
22409 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22410 "Remove the agenda restriction lock."
22411 (interactive "P")
22412 (org-detach-overlay org-agenda-restriction-lock-overlay)
22413 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22414 (setq org-agenda-overriding-restriction nil)
22415 (setq org-agenda-restrict nil)
22416 (put 'org-agenda-files 'org-restrict nil)
22417 (move-marker org-agenda-restrict-begin nil)
22418 (move-marker org-agenda-restrict-end nil)
22419 (setq current-prefix-arg nil)
22420 (message "Agenda restriction lock removed")
22421 (or noupdate (org-agenda-maybe-redo)))
22423 (defun org-agenda-maybe-redo ()
22424 "If there is any window showing the agenda view, update it."
22425 (let ((w (get-buffer-window org-agenda-buffer-name t))
22426 (w0 (selected-window)))
22427 (when w
22428 (select-window w)
22429 (org-agenda-redo)
22430 (select-window w0)
22431 (if org-agenda-overriding-restriction
22432 (message "Agenda view shifted to new %s restriction"
22433 org-agenda-overriding-restriction)
22434 (message "Agenda restriction lock removed")))))
22436 ;;; Agenda commands
22438 (defun org-agenda-check-type (error &rest types)
22439 "Check if agenda buffer is of allowed type.
22440 If ERROR is non-nil, throw an error, otherwise just return nil."
22441 (if (memq org-agenda-type types)
22443 (if error
22444 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22445 nil)))
22447 (defun org-agenda-quit ()
22448 "Exit agenda by removing the window or the buffer."
22449 (interactive)
22450 (let ((buf (current-buffer)))
22451 (if (not (one-window-p)) (delete-window))
22452 (kill-buffer buf)
22453 (org-agenda-reset-markers)
22454 (org-columns-remove-overlays))
22455 ;; Maybe restore the pre-agenda window configuration.
22456 (and org-agenda-restore-windows-after-quit
22457 (not (eq org-agenda-window-setup 'other-frame))
22458 org-pre-agenda-window-conf
22459 (set-window-configuration org-pre-agenda-window-conf)))
22461 (defun org-agenda-exit ()
22462 "Exit agenda by removing the window or the buffer.
22463 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22464 Org-mode buffers visited directly by the user will not be touched."
22465 (interactive)
22466 (org-release-buffers org-agenda-new-buffers)
22467 (setq org-agenda-new-buffers nil)
22468 (org-agenda-quit))
22470 (defun org-agenda-execute (arg)
22471 "Execute another agenda command, keeping same window.\\<global-map>
22472 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22473 (interactive "P")
22474 (let ((org-agenda-window-setup 'current-window))
22475 (org-agenda arg)))
22477 (defun org-save-all-org-buffers ()
22478 "Save all Org-mode buffers without user confirmation."
22479 (interactive)
22480 (message "Saving all Org-mode buffers...")
22481 (save-some-buffers t 'org-mode-p)
22482 (message "Saving all Org-mode buffers... done"))
22484 (defun org-agenda-redo ()
22485 "Rebuild Agenda.
22486 When this is the global TODO list, a prefix argument will be interpreted."
22487 (interactive)
22488 (let* ((org-agenda-keep-modes t)
22489 (line (org-current-line))
22490 (window-line (- line (org-current-line (window-start))))
22491 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22492 (message "Rebuilding agenda buffer...")
22493 (org-let lprops '(eval org-agenda-redo-command))
22494 (setq org-agenda-undo-list nil
22495 org-agenda-pending-undo-list nil)
22496 (message "Rebuilding agenda buffer...done")
22497 (goto-line line)
22498 (recenter window-line)))
22500 (defun org-agenda-manipulate-query-add ()
22501 "Manipulate the query by adding a search term with positive selection.
22502 Positive selection means, the term must be matched for selection of an entry."
22503 (interactive)
22504 (org-agenda-manipulate-query ?\[))
22505 (defun org-agenda-manipulate-query-subtract ()
22506 "Manipulate the query by adding a search term with negative selection.
22507 Negative selection means, term must not be matched for selection of an entry."
22508 (interactive)
22509 (org-agenda-manipulate-query ?\]))
22510 (defun org-agenda-manipulate-query-add-re ()
22511 "Manipulate the query by adding a search regexp with positive selection.
22512 Positive selection means, the regexp must match for selection of an entry."
22513 (interactive)
22514 (org-agenda-manipulate-query ?\{))
22515 (defun org-agenda-manipulate-query-subtract-re ()
22516 "Manipulate the query by adding a search regexp with negative selection.
22517 Negative selection means, regexp must not match for selection of an entry."
22518 (interactive)
22519 (org-agenda-manipulate-query ?\}))
22520 (defun org-agenda-manipulate-query (char)
22521 (cond
22522 ((eq org-agenda-type 'search)
22523 (org-add-to-string
22524 'org-agenda-query-string
22525 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22526 (?\{ . " +{}") (?\} . " -{}")))))
22527 (setq org-agenda-redo-command
22528 (list 'org-search-view
22529 (+ (length org-agenda-query-string)
22530 (if (member char '(?\{ ?\})) 0 1))
22531 org-agenda-query-string))
22532 (set-register org-agenda-query-register org-agenda-query-string)
22533 (org-agenda-redo))
22534 (t (error "Canot manipulate query for %s-type agenda buffers"
22535 org-agenda-type))))
22537 (defun org-add-to-string (var string)
22538 (set var (concat (symbol-value var) string)))
22540 (defun org-agenda-goto-date (date)
22541 "Jump to DATE in agenda."
22542 (interactive (list (org-read-date)))
22543 (org-agenda-list nil date))
22545 (defun org-agenda-goto-today ()
22546 "Go to today."
22547 (interactive)
22548 (org-agenda-check-type t 'timeline 'agenda)
22549 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22550 (cond
22551 (tdpos (goto-char tdpos))
22552 ((eq org-agenda-type 'agenda)
22553 (let* ((sd (time-to-days
22554 (time-subtract (current-time)
22555 (list 0 (* 3600 org-extend-today-until) 0))))
22556 (comp (org-agenda-compute-time-span sd org-agenda-span))
22557 (org-agenda-overriding-arguments org-agenda-last-arguments))
22558 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22559 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22560 (org-agenda-redo)
22561 (org-agenda-find-same-or-today-or-agenda)))
22562 (t (error "Cannot find today")))))
22564 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22565 (goto-char
22566 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22567 (text-property-any (point-min) (point-max) 'org-today t)
22568 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22569 (point-min))))
22571 (defun org-agenda-later (arg)
22572 "Go forward in time by thee current span.
22573 With prefix ARG, go forward that many times the current span."
22574 (interactive "p")
22575 (org-agenda-check-type t 'agenda)
22576 (let* ((span org-agenda-span)
22577 (sd org-starting-day)
22578 (greg (calendar-gregorian-from-absolute sd))
22579 (cnt (get-text-property (point) 'org-day-cnt))
22580 greg2 nd)
22581 (cond
22582 ((eq span 'day)
22583 (setq sd (+ arg sd) nd 1))
22584 ((eq span 'week)
22585 (setq sd (+ (* 7 arg) sd) nd 7))
22586 ((eq span 'month)
22587 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22588 sd (calendar-absolute-from-gregorian greg2))
22589 (setcar greg2 (1+ (car greg2)))
22590 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22591 ((eq span 'year)
22592 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22593 sd (calendar-absolute-from-gregorian greg2))
22594 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22595 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22596 (let ((org-agenda-overriding-arguments
22597 (list (car org-agenda-last-arguments) sd nd t)))
22598 (org-agenda-redo)
22599 (org-agenda-find-same-or-today-or-agenda cnt))))
22601 (defun org-agenda-earlier (arg)
22602 "Go backward in time by the current span.
22603 With prefix ARG, go backward that many times the current span."
22604 (interactive "p")
22605 (org-agenda-later (- arg)))
22607 (defun org-agenda-day-view ()
22608 "Switch to daily view for agenda."
22609 (interactive)
22610 (setq org-agenda-ndays 1)
22611 (org-agenda-change-time-span 'day))
22612 (defun org-agenda-week-view ()
22613 "Switch to daily view for agenda."
22614 (interactive)
22615 (setq org-agenda-ndays 7)
22616 (org-agenda-change-time-span 'week))
22617 (defun org-agenda-month-view ()
22618 "Switch to daily view for agenda."
22619 (interactive)
22620 (org-agenda-change-time-span 'month))
22621 (defun org-agenda-year-view ()
22622 "Switch to daily view for agenda."
22623 (interactive)
22624 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22625 (org-agenda-change-time-span 'year)
22626 (error "Abort")))
22628 (defun org-agenda-change-time-span (span)
22629 "Change the agenda view to SPAN.
22630 SPAN may be `day', `week', `month', `year'."
22631 (org-agenda-check-type t 'agenda)
22632 (if (equal org-agenda-span span)
22633 (error "Viewing span is already \"%s\"" span))
22634 (let* ((sd (or (get-text-property (point) 'day)
22635 org-starting-day))
22636 (computed (org-agenda-compute-time-span sd span))
22637 (org-agenda-overriding-arguments
22638 (list (car org-agenda-last-arguments)
22639 (car computed) (cdr computed) t)))
22640 (org-agenda-redo)
22641 (org-agenda-find-same-or-today-or-agenda))
22642 (org-agenda-set-mode-name)
22643 (message "Switched to %s view" span))
22645 (defun org-agenda-compute-time-span (sd span)
22646 "Compute starting date and number of days for agenda.
22647 SPAN may be `day', `week', `month', `year'. The return value
22648 is a cons cell with the starting date and the number of days,
22649 so that the date SD will be in that range."
22650 (let* ((greg (calendar-gregorian-from-absolute sd))
22652 (cond
22653 ((eq span 'day)
22654 (setq nd 1))
22655 ((eq span 'week)
22656 (let* ((nt (calendar-day-of-week
22657 (calendar-gregorian-from-absolute sd)))
22658 (d (if org-agenda-start-on-weekday
22659 (- nt org-agenda-start-on-weekday)
22660 0)))
22661 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22662 (setq nd 7)))
22663 ((eq span 'month)
22664 (setq sd (calendar-absolute-from-gregorian
22665 (list (car greg) 1 (nth 2 greg)))
22666 nd (- (calendar-absolute-from-gregorian
22667 (list (1+ (car greg)) 1 (nth 2 greg)))
22668 sd)))
22669 ((eq span 'year)
22670 (setq sd (calendar-absolute-from-gregorian
22671 (list 1 1 (nth 2 greg)))
22672 nd (- (calendar-absolute-from-gregorian
22673 (list 1 1 (1+ (nth 2 greg))))
22674 sd))))
22675 (cons sd nd)))
22677 ;; FIXME: does not work if user makes date format that starts with a blank
22678 (defun org-agenda-next-date-line (&optional arg)
22679 "Jump to the next line indicating a date in agenda buffer."
22680 (interactive "p")
22681 (org-agenda-check-type t 'agenda 'timeline)
22682 (beginning-of-line 1)
22683 (if (looking-at "^\\S-") (forward-char 1))
22684 (if (not (re-search-forward "^\\S-" nil t arg))
22685 (progn
22686 (backward-char 1)
22687 (error "No next date after this line in this buffer")))
22688 (goto-char (match-beginning 0)))
22690 (defun org-agenda-previous-date-line (&optional arg)
22691 "Jump to the previous line indicating a date in agenda buffer."
22692 (interactive "p")
22693 (org-agenda-check-type t 'agenda 'timeline)
22694 (beginning-of-line 1)
22695 (if (not (re-search-backward "^\\S-" nil t arg))
22696 (error "No previous date before this line in this buffer")))
22698 ;; Initialize the highlight
22699 (defvar org-hl (org-make-overlay 1 1))
22700 (org-overlay-put org-hl 'face 'highlight)
22702 (defun org-highlight (begin end &optional buffer)
22703 "Highlight a region with overlay."
22704 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22705 org-hl begin end (or buffer (current-buffer))))
22707 (defun org-unhighlight ()
22708 "Detach overlay INDEX."
22709 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22711 ;; FIXME this is currently not used.
22712 (defun org-highlight-until-next-command (beg end &optional buffer)
22713 (org-highlight beg end buffer)
22714 (add-hook 'pre-command-hook 'org-unhighlight-once))
22715 (defun org-unhighlight-once ()
22716 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22717 (org-unhighlight))
22719 (defun org-agenda-follow-mode ()
22720 "Toggle follow mode in an agenda buffer."
22721 (interactive)
22722 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22723 (org-agenda-set-mode-name)
22724 (message "Follow mode is %s"
22725 (if org-agenda-follow-mode "on" "off")))
22727 (defun org-agenda-log-mode ()
22728 "Toggle log mode in an agenda buffer."
22729 (interactive)
22730 (org-agenda-check-type t 'agenda 'timeline)
22731 (setq org-agenda-show-log (not org-agenda-show-log))
22732 (org-agenda-set-mode-name)
22733 (org-agenda-redo)
22734 (message "Log mode is %s"
22735 (if org-agenda-show-log "on" "off")))
22737 (defun org-agenda-toggle-diary ()
22738 "Toggle diary inclusion in an agenda buffer."
22739 (interactive)
22740 (org-agenda-check-type t 'agenda)
22741 (setq org-agenda-include-diary (not org-agenda-include-diary))
22742 (org-agenda-redo)
22743 (org-agenda-set-mode-name)
22744 (message "Diary inclusion turned %s"
22745 (if org-agenda-include-diary "on" "off")))
22747 (defun org-agenda-toggle-time-grid ()
22748 "Toggle time grid in an agenda buffer."
22749 (interactive)
22750 (org-agenda-check-type t 'agenda)
22751 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22752 (org-agenda-redo)
22753 (org-agenda-set-mode-name)
22754 (message "Time-grid turned %s"
22755 (if org-agenda-use-time-grid "on" "off")))
22757 (defun org-agenda-set-mode-name ()
22758 "Set the mode name to indicate all the small mode settings."
22759 (setq mode-name
22760 (concat "Org-Agenda"
22761 (if (equal org-agenda-ndays 1) " Day" "")
22762 (if (equal org-agenda-ndays 7) " Week" "")
22763 (if org-agenda-follow-mode " Follow" "")
22764 (if org-agenda-include-diary " Diary" "")
22765 (if org-agenda-use-time-grid " Grid" "")
22766 (if org-agenda-show-log " Log" "")))
22767 (force-mode-line-update))
22769 (defun org-agenda-post-command-hook ()
22770 (and (eolp) (not (bolp)) (backward-char 1))
22771 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22772 (if (and org-agenda-follow-mode
22773 (get-text-property (point) 'org-marker))
22774 (org-agenda-show)))
22776 (defun org-agenda-show-priority ()
22777 "Show the priority of the current item.
22778 This priority is composed of the main priority given with the [#A] cookies,
22779 and by additional input from the age of a schedules or deadline entry."
22780 (interactive)
22781 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22782 (message "Priority is %d" (if pri pri -1000))))
22784 (defun org-agenda-show-tags ()
22785 "Show the tags applicable to the current item."
22786 (interactive)
22787 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22788 (if tags
22789 (message "Tags are :%s:"
22790 (org-no-properties (mapconcat 'identity tags ":")))
22791 (message "No tags associated with this line"))))
22793 (defun org-agenda-goto (&optional highlight)
22794 "Go to the Org-mode file which contains the item at point."
22795 (interactive)
22796 (let* ((marker (or (get-text-property (point) 'org-marker)
22797 (org-agenda-error)))
22798 (buffer (marker-buffer marker))
22799 (pos (marker-position marker)))
22800 (switch-to-buffer-other-window buffer)
22801 (widen)
22802 (goto-char pos)
22803 (when (org-mode-p)
22804 (org-show-context 'agenda)
22805 (save-excursion
22806 (and (outline-next-heading)
22807 (org-flag-heading nil)))) ; show the next heading
22808 (recenter (/ (window-height) 2))
22809 (run-hooks 'org-agenda-after-show-hook)
22810 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22812 (defvar org-agenda-after-show-hook nil
22813 "Normal hook run after an item has been shown from the agenda.
22814 Point is in the buffer where the item originated.")
22816 (defun org-agenda-kill ()
22817 "Kill the entry or subtree belonging to the current agenda entry."
22818 (interactive)
22819 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22820 (let* ((marker (or (get-text-property (point) 'org-marker)
22821 (org-agenda-error)))
22822 (buffer (marker-buffer marker))
22823 (pos (marker-position marker))
22824 (type (get-text-property (point) 'type))
22825 dbeg dend (n 0) conf)
22826 (org-with-remote-undo buffer
22827 (with-current-buffer buffer
22828 (save-excursion
22829 (goto-char pos)
22830 (if (and (org-mode-p) (not (member type '("sexp"))))
22831 (setq dbeg (progn (org-back-to-heading t) (point))
22832 dend (org-end-of-subtree t t))
22833 (setq dbeg (point-at-bol)
22834 dend (min (point-max) (1+ (point-at-eol)))))
22835 (goto-char dbeg)
22836 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22837 (setq conf (or (eq t org-agenda-confirm-kill)
22838 (and (numberp org-agenda-confirm-kill)
22839 (> n org-agenda-confirm-kill))))
22840 (and conf
22841 (not (y-or-n-p
22842 (format "Delete entry with %d lines in buffer \"%s\"? "
22843 n (buffer-name buffer))))
22844 (error "Abort"))
22845 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22846 (with-current-buffer buffer (delete-region dbeg dend))
22847 (message "Agenda item and source killed"))))
22849 (defun org-agenda-archive ()
22850 "Kill the entry or subtree belonging to the current agenda entry."
22851 (interactive)
22852 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22853 (let* ((marker (or (get-text-property (point) 'org-marker)
22854 (org-agenda-error)))
22855 (buffer (marker-buffer marker))
22856 (pos (marker-position marker)))
22857 (org-with-remote-undo buffer
22858 (with-current-buffer buffer
22859 (if (org-mode-p)
22860 (save-excursion
22861 (goto-char pos)
22862 (org-remove-subtree-entries-from-agenda)
22863 (org-back-to-heading t)
22864 (org-archive-subtree))
22865 (error "Archiving works only in Org-mode files"))))))
22867 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22868 "Remove all lines in the agenda that correspond to a given subtree.
22869 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22870 If this information is not given, the function uses the tree at point."
22871 (let ((buf (or buf (current-buffer))) m p)
22872 (save-excursion
22873 (unless (and beg end)
22874 (org-back-to-heading t)
22875 (setq beg (point))
22876 (org-end-of-subtree t)
22877 (setq end (point)))
22878 (set-buffer (get-buffer org-agenda-buffer-name))
22879 (save-excursion
22880 (goto-char (point-max))
22881 (beginning-of-line 1)
22882 (while (not (bobp))
22883 (when (and (setq m (get-text-property (point) 'org-marker))
22884 (equal buf (marker-buffer m))
22885 (setq p (marker-position m))
22886 (>= p beg)
22887 (<= p end))
22888 (let ((inhibit-read-only t))
22889 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22890 (beginning-of-line 0))))))
22892 (defun org-agenda-open-link ()
22893 "Follow the link in the current line, if any."
22894 (interactive)
22895 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22896 (save-excursion
22897 (save-restriction
22898 (narrow-to-region (point-at-bol) (point-at-eol))
22899 (org-open-at-point))))
22901 (defun org-agenda-copy-local-variable (var)
22902 "Get a variable from a referenced buffer and install it here."
22903 (let ((m (get-text-property (point) 'org-marker)))
22904 (when (and m (buffer-live-p (marker-buffer m)))
22905 (org-set-local var (with-current-buffer (marker-buffer m)
22906 (symbol-value var))))))
22908 (defun org-agenda-switch-to (&optional delete-other-windows)
22909 "Go to the Org-mode file which contains the item at point."
22910 (interactive)
22911 (let* ((marker (or (get-text-property (point) 'org-marker)
22912 (org-agenda-error)))
22913 (buffer (marker-buffer marker))
22914 (pos (marker-position marker)))
22915 (switch-to-buffer buffer)
22916 (and delete-other-windows (delete-other-windows))
22917 (widen)
22918 (goto-char pos)
22919 (when (org-mode-p)
22920 (org-show-context 'agenda)
22921 (save-excursion
22922 (and (outline-next-heading)
22923 (org-flag-heading nil)))))) ; show the next heading
22925 (defun org-agenda-goto-mouse (ev)
22926 "Go to the Org-mode file which contains the item at the mouse click."
22927 (interactive "e")
22928 (mouse-set-point ev)
22929 (org-agenda-goto))
22931 (defun org-agenda-show ()
22932 "Display the Org-mode file which contains the item at point."
22933 (interactive)
22934 (let ((win (selected-window)))
22935 (org-agenda-goto t)
22936 (select-window win)))
22938 (defun org-agenda-recenter (arg)
22939 "Display the Org-mode file which contains the item at point and recenter."
22940 (interactive "P")
22941 (let ((win (selected-window)))
22942 (org-agenda-goto t)
22943 (recenter arg)
22944 (select-window win)))
22946 (defun org-agenda-show-mouse (ev)
22947 "Display the Org-mode file which contains the item at the mouse click."
22948 (interactive "e")
22949 (mouse-set-point ev)
22950 (org-agenda-show))
22952 (defun org-agenda-check-no-diary ()
22953 "Check if the entry is a diary link and abort if yes."
22954 (if (get-text-property (point) 'org-agenda-diary-link)
22955 (org-agenda-error)))
22957 (defun org-agenda-error ()
22958 (error "Command not allowed in this line"))
22960 (defun org-agenda-tree-to-indirect-buffer ()
22961 "Show the subtree corresponding to the current entry in an indirect buffer.
22962 This calls the command `org-tree-to-indirect-buffer' from the original
22963 Org-mode buffer.
22964 With numerical prefix arg ARG, go up to this level and then take that tree.
22965 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22966 dedicated frame)."
22967 (interactive)
22968 (org-agenda-check-no-diary)
22969 (let* ((marker (or (get-text-property (point) 'org-marker)
22970 (org-agenda-error)))
22971 (buffer (marker-buffer marker))
22972 (pos (marker-position marker)))
22973 (with-current-buffer buffer
22974 (save-excursion
22975 (goto-char pos)
22976 (call-interactively 'org-tree-to-indirect-buffer)))))
22978 (defvar org-last-heading-marker (make-marker)
22979 "Marker pointing to the headline that last changed its TODO state
22980 by a remote command from the agenda.")
22982 (defun org-agenda-todo-nextset ()
22983 "Switch TODO entry to next sequence."
22984 (interactive)
22985 (org-agenda-todo 'nextset))
22987 (defun org-agenda-todo-previousset ()
22988 "Switch TODO entry to previous sequence."
22989 (interactive)
22990 (org-agenda-todo 'previousset))
22992 (defun org-agenda-todo (&optional arg)
22993 "Cycle TODO state of line at point, also in Org-mode file.
22994 This changes the line at point, all other lines in the agenda referring to
22995 the same tree node, and the headline of the tree node in the Org-mode file."
22996 (interactive "P")
22997 (org-agenda-check-no-diary)
22998 (let* ((col (current-column))
22999 (marker (or (get-text-property (point) 'org-marker)
23000 (org-agenda-error)))
23001 (buffer (marker-buffer marker))
23002 (pos (marker-position marker))
23003 (hdmarker (get-text-property (point) 'org-hd-marker))
23004 (inhibit-read-only t)
23005 newhead)
23006 (org-with-remote-undo buffer
23007 (with-current-buffer buffer
23008 (widen)
23009 (goto-char pos)
23010 (org-show-context 'agenda)
23011 (save-excursion
23012 (and (outline-next-heading)
23013 (org-flag-heading nil))) ; show the next heading
23014 (org-todo arg)
23015 (and (bolp) (forward-char 1))
23016 (setq newhead (org-get-heading))
23017 (save-excursion
23018 (org-back-to-heading)
23019 (move-marker org-last-heading-marker (point))))
23020 (beginning-of-line 1)
23021 (save-excursion
23022 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23023 (move-to-column col))))
23025 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23026 "Change all lines in the agenda buffer which match HDMARKER.
23027 The new content of the line will be NEWHEAD (as modified by
23028 `org-format-agenda-item'). HDMARKER is checked with
23029 `equal' against all `org-hd-marker' text properties in the file.
23030 If FIXFACE is non-nil, the face of each item is modified acording to
23031 the new TODO state."
23032 (let* ((inhibit-read-only t)
23033 props m pl undone-face done-face finish new dotime cat tags)
23034 (save-excursion
23035 (goto-char (point-max))
23036 (beginning-of-line 1)
23037 (while (not finish)
23038 (setq finish (bobp))
23039 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23040 (equal m hdmarker))
23041 (setq props (text-properties-at (point))
23042 dotime (get-text-property (point) 'dotime)
23043 cat (get-text-property (point) 'org-category)
23044 tags (get-text-property (point) 'tags)
23045 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23046 pl (get-text-property (point) 'prefix-length)
23047 undone-face (get-text-property (point) 'undone-face)
23048 done-face (get-text-property (point) 'done-face))
23049 (move-to-column pl)
23050 (cond
23051 ((equal new "")
23052 (beginning-of-line 1)
23053 (and (looking-at ".*\n?") (replace-match "")))
23054 ((looking-at ".*")
23055 (replace-match new t t)
23056 (beginning-of-line 1)
23057 (add-text-properties (point-at-bol) (point-at-eol) props)
23058 (when fixface
23059 (add-text-properties
23060 (point-at-bol) (point-at-eol)
23061 (list 'face
23062 (if org-last-todo-state-is-todo
23063 undone-face done-face))))
23064 (org-agenda-highlight-todo 'line)
23065 (beginning-of-line 1))
23066 (t (error "Line update did not work"))))
23067 (beginning-of-line 0)))
23068 (org-finalize-agenda)))
23070 (defun org-agenda-align-tags (&optional line)
23071 "Align all tags in agenda items to `org-agenda-tags-column'."
23072 (let ((inhibit-read-only t) l c)
23073 (save-excursion
23074 (goto-char (if line (point-at-bol) (point-min)))
23075 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23076 (if line (point-at-eol) nil) t)
23077 (add-text-properties
23078 (match-beginning 2) (match-end 2)
23079 (list 'face (delq nil (list 'org-tag (get-text-property
23080 (match-beginning 2) 'face)))))
23081 (setq l (- (match-end 2) (match-beginning 2))
23082 c (if (< org-agenda-tags-column 0)
23083 (- (abs org-agenda-tags-column) l)
23084 org-agenda-tags-column))
23085 (delete-region (match-beginning 1) (match-end 1))
23086 (goto-char (match-beginning 1))
23087 (insert (org-add-props
23088 (make-string (max 1 (- c (current-column))) ?\ )
23089 (text-properties-at (point))))))))
23091 (defun org-agenda-priority-up ()
23092 "Increase the priority of line at point, also in Org-mode file."
23093 (interactive)
23094 (org-agenda-priority 'up))
23096 (defun org-agenda-priority-down ()
23097 "Decrease the priority of line at point, also in Org-mode file."
23098 (interactive)
23099 (org-agenda-priority 'down))
23101 (defun org-agenda-priority (&optional force-direction)
23102 "Set the priority of line at point, also in Org-mode file.
23103 This changes the line at point, all other lines in the agenda referring to
23104 the same tree node, and the headline of the tree node in the Org-mode file."
23105 (interactive)
23106 (org-agenda-check-no-diary)
23107 (let* ((marker (or (get-text-property (point) 'org-marker)
23108 (org-agenda-error)))
23109 (hdmarker (get-text-property (point) 'org-hd-marker))
23110 (buffer (marker-buffer hdmarker))
23111 (pos (marker-position hdmarker))
23112 (inhibit-read-only t)
23113 newhead)
23114 (org-with-remote-undo buffer
23115 (with-current-buffer buffer
23116 (widen)
23117 (goto-char pos)
23118 (org-show-context 'agenda)
23119 (save-excursion
23120 (and (outline-next-heading)
23121 (org-flag-heading nil))) ; show the next heading
23122 (funcall 'org-priority force-direction)
23123 (end-of-line 1)
23124 (setq newhead (org-get-heading)))
23125 (org-agenda-change-all-lines newhead hdmarker)
23126 (beginning-of-line 1))))
23128 (defun org-get-tags-at (&optional pos)
23129 "Get a list of all headline tags applicable at POS.
23130 POS defaults to point. If tags are inherited, the list contains
23131 the targets in the same sequence as the headlines appear, i.e.
23132 the tags of the current headline come last."
23133 (interactive)
23134 (let (tags lastpos)
23135 (save-excursion
23136 (save-restriction
23137 (widen)
23138 (goto-char (or pos (point)))
23139 (save-match-data
23140 (org-back-to-heading t)
23141 (condition-case nil
23142 (while (not (equal lastpos (point)))
23143 (setq lastpos (point))
23144 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23145 (setq tags (append (org-split-string
23146 (org-match-string-no-properties 1) ":")
23147 tags)))
23148 (or org-use-tag-inheritance (error ""))
23149 (org-up-heading-all 1))
23150 (error nil))))
23151 tags)))
23153 ;; FIXME: should fix the tags property of the agenda line.
23154 (defun org-agenda-set-tags ()
23155 "Set tags for the current headline."
23156 (interactive)
23157 (org-agenda-check-no-diary)
23158 (if (and (org-region-active-p) (interactive-p))
23159 (call-interactively 'org-change-tag-in-region)
23160 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23161 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23162 (org-agenda-error)))
23163 (buffer (marker-buffer hdmarker))
23164 (pos (marker-position hdmarker))
23165 (inhibit-read-only t)
23166 newhead)
23167 (org-with-remote-undo buffer
23168 (with-current-buffer buffer
23169 (widen)
23170 (goto-char pos)
23171 (save-excursion
23172 (org-show-context 'agenda))
23173 (save-excursion
23174 (and (outline-next-heading)
23175 (org-flag-heading nil))) ; show the next heading
23176 (goto-char pos)
23177 (call-interactively 'org-set-tags)
23178 (end-of-line 1)
23179 (setq newhead (org-get-heading)))
23180 (org-agenda-change-all-lines newhead hdmarker)
23181 (beginning-of-line 1)))))
23183 (defun org-agenda-toggle-archive-tag ()
23184 "Toggle the archive tag for the current entry."
23185 (interactive)
23186 (org-agenda-check-no-diary)
23187 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23188 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23189 (org-agenda-error)))
23190 (buffer (marker-buffer hdmarker))
23191 (pos (marker-position hdmarker))
23192 (inhibit-read-only t)
23193 newhead)
23194 (org-with-remote-undo buffer
23195 (with-current-buffer buffer
23196 (widen)
23197 (goto-char pos)
23198 (org-show-context 'agenda)
23199 (save-excursion
23200 (and (outline-next-heading)
23201 (org-flag-heading nil))) ; show the next heading
23202 (call-interactively 'org-toggle-archive-tag)
23203 (end-of-line 1)
23204 (setq newhead (org-get-heading)))
23205 (org-agenda-change-all-lines newhead hdmarker)
23206 (beginning-of-line 1))))
23208 (defun org-agenda-date-later (arg &optional what)
23209 "Change the date of this item to one day later."
23210 (interactive "p")
23211 (org-agenda-check-type t 'agenda 'timeline)
23212 (org-agenda-check-no-diary)
23213 (let* ((marker (or (get-text-property (point) 'org-marker)
23214 (org-agenda-error)))
23215 (buffer (marker-buffer marker))
23216 (pos (marker-position marker)))
23217 (org-with-remote-undo buffer
23218 (with-current-buffer buffer
23219 (widen)
23220 (goto-char pos)
23221 (if (not (org-at-timestamp-p))
23222 (error "Cannot find time stamp"))
23223 (org-timestamp-change arg (or what 'day)))
23224 (org-agenda-show-new-time marker org-last-changed-timestamp))
23225 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23227 (defun org-agenda-date-earlier (arg &optional what)
23228 "Change the date of this item to one day earlier."
23229 (interactive "p")
23230 (org-agenda-date-later (- arg) what))
23232 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23233 "Show new date stamp via text properties."
23234 ;; We use text properties to make this undoable
23235 (let ((inhibit-read-only t))
23236 (setq stamp (concat " " prefix " => " stamp))
23237 (save-excursion
23238 (goto-char (point-max))
23239 (while (not (bobp))
23240 (when (equal marker (get-text-property (point) 'org-marker))
23241 (move-to-column (- (window-width) (length stamp)) t)
23242 (if (featurep 'xemacs)
23243 ;; Use `duplicable' property to trigger undo recording
23244 (let ((ex (make-extent nil nil))
23245 (gl (make-glyph stamp)))
23246 (set-glyph-face gl 'secondary-selection)
23247 (set-extent-properties
23248 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23249 (insert-extent ex (1- (point)) (point-at-eol)))
23250 (add-text-properties
23251 (1- (point)) (point-at-eol)
23252 (list 'display (org-add-props stamp nil
23253 'face 'secondary-selection))))
23254 (beginning-of-line 1))
23255 (beginning-of-line 0)))))
23257 (defun org-agenda-date-prompt (arg)
23258 "Change the date of this item. Date is prompted for, with default today.
23259 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23260 be used to request time specification in the time stamp."
23261 (interactive "P")
23262 (org-agenda-check-type t 'agenda 'timeline)
23263 (org-agenda-check-no-diary)
23264 (let* ((marker (or (get-text-property (point) 'org-marker)
23265 (org-agenda-error)))
23266 (buffer (marker-buffer marker))
23267 (pos (marker-position marker)))
23268 (org-with-remote-undo buffer
23269 (with-current-buffer buffer
23270 (widen)
23271 (goto-char pos)
23272 (if (not (org-at-timestamp-p))
23273 (error "Cannot find time stamp"))
23274 (org-time-stamp arg)
23275 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23277 (defun org-agenda-schedule (arg)
23278 "Schedule the item at point."
23279 (interactive "P")
23280 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23281 (org-agenda-check-no-diary)
23282 (let* ((marker (or (get-text-property (point) 'org-marker)
23283 (org-agenda-error)))
23284 (buffer (marker-buffer marker))
23285 (pos (marker-position marker))
23286 (org-insert-labeled-timestamps-at-point nil)
23288 (message "%s" (marker-insertion-type marker)) (sit-for 3)
23289 (set-marker-insertion-type marker t)
23290 (org-with-remote-undo buffer
23291 (with-current-buffer buffer
23292 (widen)
23293 (goto-char pos)
23294 (setq ts (org-schedule arg)))
23295 (org-agenda-show-new-time marker ts "S"))
23296 (message "Item scheduled for %s" ts)))
23298 (defun org-agenda-deadline (arg)
23299 "Schedule the item at point."
23300 (interactive "P")
23301 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23302 (org-agenda-check-no-diary)
23303 (let* ((marker (or (get-text-property (point) 'org-marker)
23304 (org-agenda-error)))
23305 (buffer (marker-buffer marker))
23306 (pos (marker-position marker))
23307 (org-insert-labeled-timestamps-at-point nil)
23309 (org-with-remote-undo buffer
23310 (with-current-buffer buffer
23311 (widen)
23312 (goto-char pos)
23313 (setq ts (org-deadline arg)))
23314 (org-agenda-show-new-time marker ts "S"))
23315 (message "Deadline for this item set to %s" ts)))
23317 (defun org-get-heading (&optional no-tags)
23318 "Return the heading of the current entry, without the stars."
23319 (save-excursion
23320 (org-back-to-heading t)
23321 (if (looking-at
23322 (if no-tags
23323 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23324 "\\*+[ \t]+\\([^\r\n]*\\)"))
23325 (match-string 1) "")))
23327 (defun org-agenda-clock-in (&optional arg)
23328 "Start the clock on the currently selected item."
23329 (interactive "P")
23330 (org-agenda-check-no-diary)
23331 (let* ((marker (or (get-text-property (point) 'org-marker)
23332 (org-agenda-error)))
23333 (pos (marker-position marker)))
23334 (org-with-remote-undo (marker-buffer marker)
23335 (with-current-buffer (marker-buffer marker)
23336 (widen)
23337 (goto-char pos)
23338 (org-clock-in)))))
23340 (defun org-agenda-clock-out (&optional arg)
23341 "Stop the currently running clock."
23342 (interactive "P")
23343 (unless (marker-buffer org-clock-marker)
23344 (error "No running clock"))
23345 (org-with-remote-undo (marker-buffer org-clock-marker)
23346 (org-clock-out)))
23348 (defun org-agenda-clock-cancel (&optional arg)
23349 "Cancel the currently running clock."
23350 (interactive "P")
23351 (unless (marker-buffer org-clock-marker)
23352 (error "No running clock"))
23353 (org-with-remote-undo (marker-buffer org-clock-marker)
23354 (org-clock-cancel)))
23356 (defun org-agenda-diary-entry ()
23357 "Make a diary entry, like the `i' command from the calendar.
23358 All the standard commands work: block, weekly etc."
23359 (interactive)
23360 (org-agenda-check-type t 'agenda 'timeline)
23361 (require 'diary-lib)
23362 (let* ((char (progn
23363 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23364 (read-char-exclusive)))
23365 (cmd (cdr (assoc char
23366 '((?d . insert-diary-entry)
23367 (?w . insert-weekly-diary-entry)
23368 (?m . insert-monthly-diary-entry)
23369 (?y . insert-yearly-diary-entry)
23370 (?a . insert-anniversary-diary-entry)
23371 (?b . insert-block-diary-entry)
23372 (?c . insert-cyclic-diary-entry)))))
23373 (oldf (symbol-function 'calendar-cursor-to-date))
23374 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23375 (point (point))
23376 (mark (or (mark t) (point))))
23377 (unless cmd
23378 (error "No command associated with <%c>" char))
23379 (unless (and (get-text-property point 'day)
23380 (or (not (equal ?b char))
23381 (get-text-property mark 'day)))
23382 (error "Don't know which date to use for diary entry"))
23383 ;; We implement this by hacking the `calendar-cursor-to-date' function
23384 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23385 (let ((calendar-mark-ring
23386 (list (calendar-gregorian-from-absolute
23387 (or (get-text-property mark 'day)
23388 (get-text-property point 'day))))))
23389 (unwind-protect
23390 (progn
23391 (fset 'calendar-cursor-to-date
23392 (lambda (&optional error)
23393 (calendar-gregorian-from-absolute
23394 (get-text-property point 'day))))
23395 (call-interactively cmd))
23396 (fset 'calendar-cursor-to-date oldf)))))
23399 (defun org-agenda-execute-calendar-command (cmd)
23400 "Execute a calendar command from the agenda, with the date associated to
23401 the cursor position."
23402 (org-agenda-check-type t 'agenda 'timeline)
23403 (require 'diary-lib)
23404 (unless (get-text-property (point) 'day)
23405 (error "Don't know which date to use for calendar command"))
23406 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23407 (point (point))
23408 (date (calendar-gregorian-from-absolute
23409 (get-text-property point 'day)))
23410 ;; the following 3 vars are needed in the calendar
23411 (displayed-day (extract-calendar-day date))
23412 (displayed-month (extract-calendar-month date))
23413 (displayed-year (extract-calendar-year date)))
23414 (unwind-protect
23415 (progn
23416 (fset 'calendar-cursor-to-date
23417 (lambda (&optional error)
23418 (calendar-gregorian-from-absolute
23419 (get-text-property point 'day))))
23420 (call-interactively cmd))
23421 (fset 'calendar-cursor-to-date oldf))))
23423 (defun org-agenda-phases-of-moon ()
23424 "Display the phases of the moon for the 3 months around the cursor date."
23425 (interactive)
23426 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23428 (defun org-agenda-holidays ()
23429 "Display the holidays for the 3 months around the cursor date."
23430 (interactive)
23431 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23433 (defun org-agenda-sunrise-sunset (arg)
23434 "Display sunrise and sunset for the cursor date.
23435 Latitude and longitude can be specified with the variables
23436 `calendar-latitude' and `calendar-longitude'. When called with prefix
23437 argument, latitude and longitude will be prompted for."
23438 (interactive "P")
23439 (let ((calendar-longitude (if arg nil calendar-longitude))
23440 (calendar-latitude (if arg nil calendar-latitude))
23441 (calendar-location-name
23442 (if arg "the given coordinates" calendar-location-name)))
23443 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23445 (defun org-agenda-goto-calendar ()
23446 "Open the Emacs calendar with the date at the cursor."
23447 (interactive)
23448 (org-agenda-check-type t 'agenda 'timeline)
23449 (let* ((day (or (get-text-property (point) 'day)
23450 (error "Don't know which date to open in calendar")))
23451 (date (calendar-gregorian-from-absolute day))
23452 (calendar-move-hook nil)
23453 (view-calendar-holidays-initially nil)
23454 (view-diary-entries-initially nil))
23455 (calendar)
23456 (calendar-goto-date date)))
23458 (defun org-calendar-goto-agenda ()
23459 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23460 This is a command that has to be installed in `calendar-mode-map'."
23461 (interactive)
23462 (org-agenda-list nil (calendar-absolute-from-gregorian
23463 (calendar-cursor-to-date))
23464 nil))
23466 (defun org-agenda-convert-date ()
23467 (interactive)
23468 (org-agenda-check-type t 'agenda 'timeline)
23469 (let ((day (get-text-property (point) 'day))
23470 date s)
23471 (unless day
23472 (error "Don't know which date to convert"))
23473 (setq date (calendar-gregorian-from-absolute day))
23474 (setq s (concat
23475 "Gregorian: " (calendar-date-string date) "\n"
23476 "ISO: " (calendar-iso-date-string date) "\n"
23477 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23478 "Julian: " (calendar-julian-date-string date) "\n"
23479 "Astron. JD: " (calendar-astro-date-string date)
23480 " (Julian date number at noon UTC)\n"
23481 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23482 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23483 "French: " (calendar-french-date-string date) "\n"
23484 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23485 "Mayan: " (calendar-mayan-date-string date) "\n"
23486 "Coptic: " (calendar-coptic-date-string date) "\n"
23487 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23488 "Persian: " (calendar-persian-date-string date) "\n"
23489 "Chinese: " (calendar-chinese-date-string date) "\n"))
23490 (with-output-to-temp-buffer "*Dates*"
23491 (princ s))
23492 (if (fboundp 'fit-window-to-buffer)
23493 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23496 ;;;; Embedded LaTeX
23498 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23499 "Keymap for the minor `org-cdlatex-mode'.")
23501 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23502 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23503 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23504 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23505 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23507 (defvar org-cdlatex-texmathp-advice-is-done nil
23508 "Flag remembering if we have applied the advice to texmathp already.")
23510 (define-minor-mode org-cdlatex-mode
23511 "Toggle the minor `org-cdlatex-mode'.
23512 This mode supports entering LaTeX environment and math in LaTeX fragments
23513 in Org-mode.
23514 \\{org-cdlatex-mode-map}"
23515 nil " OCDL" nil
23516 (when org-cdlatex-mode (require 'cdlatex))
23517 (unless org-cdlatex-texmathp-advice-is-done
23518 (setq org-cdlatex-texmathp-advice-is-done t)
23519 (defadvice texmathp (around org-math-always-on activate)
23520 "Always return t in org-mode buffers.
23521 This is because we want to insert math symbols without dollars even outside
23522 the LaTeX math segments. If Orgmode thinks that point is actually inside
23523 en embedded LaTeX fragement, let texmathp do its job.
23524 \\[org-cdlatex-mode-map]"
23525 (interactive)
23526 (let (p)
23527 (cond
23528 ((not (org-mode-p)) ad-do-it)
23529 ((eq this-command 'cdlatex-math-symbol)
23530 (setq ad-return-value t
23531 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23533 (let ((p (org-inside-LaTeX-fragment-p)))
23534 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23535 (setq ad-return-value t
23536 texmathp-why '("Org-mode embedded math" . 0))
23537 (if p ad-do-it)))))))))
23539 (defun turn-on-org-cdlatex ()
23540 "Unconditionally turn on `org-cdlatex-mode'."
23541 (org-cdlatex-mode 1))
23543 (defun org-inside-LaTeX-fragment-p ()
23544 "Test if point is inside a LaTeX fragment.
23545 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23546 sequence appearing also before point.
23547 Even though the matchers for math are configurable, this function assumes
23548 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23549 delimiters are skipped when they have been removed by customization.
23550 The return value is nil, or a cons cell with the delimiter and
23551 and the position of this delimiter.
23553 This function does a reasonably good job, but can locally be fooled by
23554 for example currency specifications. For example it will assume being in
23555 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23556 fragments that are properly closed, but during editing, we have to live
23557 with the uncertainty caused by missing closing delimiters. This function
23558 looks only before point, not after."
23559 (catch 'exit
23560 (let ((pos (point))
23561 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23562 (lim (progn
23563 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23564 (point)))
23565 dd-on str (start 0) m re)
23566 (goto-char pos)
23567 (when dodollar
23568 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23569 re (nth 1 (assoc "$" org-latex-regexps)))
23570 (while (string-match re str start)
23571 (cond
23572 ((= (match-end 0) (length str))
23573 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23574 ((= (match-end 0) (- (length str) 5))
23575 (throw 'exit nil))
23576 (t (setq start (match-end 0))))))
23577 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23578 (goto-char pos)
23579 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23580 (and (match-beginning 2) (throw 'exit nil))
23581 ;; count $$
23582 (while (re-search-backward "\\$\\$" lim t)
23583 (setq dd-on (not dd-on)))
23584 (goto-char pos)
23585 (if dd-on (cons "$$" m))))))
23588 (defun org-try-cdlatex-tab ()
23589 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23590 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23591 - inside a LaTeX fragment, or
23592 - after the first word in a line, where an abbreviation expansion could
23593 insert a LaTeX environment."
23594 (when org-cdlatex-mode
23595 (cond
23596 ((save-excursion
23597 (skip-chars-backward "a-zA-Z0-9*")
23598 (skip-chars-backward " \t")
23599 (bolp))
23600 (cdlatex-tab) t)
23601 ((org-inside-LaTeX-fragment-p)
23602 (cdlatex-tab) t)
23603 (t nil))))
23605 (defun org-cdlatex-underscore-caret (&optional arg)
23606 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23607 Revert to the normal definition outside of these fragments."
23608 (interactive "P")
23609 (if (org-inside-LaTeX-fragment-p)
23610 (call-interactively 'cdlatex-sub-superscript)
23611 (let (org-cdlatex-mode)
23612 (call-interactively (key-binding (vector last-input-event))))))
23614 (defun org-cdlatex-math-modify (&optional arg)
23615 "Execute `cdlatex-math-modify' in LaTeX fragments.
23616 Revert to the normal definition outside of these fragments."
23617 (interactive "P")
23618 (if (org-inside-LaTeX-fragment-p)
23619 (call-interactively 'cdlatex-math-modify)
23620 (let (org-cdlatex-mode)
23621 (call-interactively (key-binding (vector last-input-event))))))
23623 (defvar org-latex-fragment-image-overlays nil
23624 "List of overlays carrying the images of latex fragments.")
23625 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23627 (defun org-remove-latex-fragment-image-overlays ()
23628 "Remove all overlays with LaTeX fragment images in current buffer."
23629 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23630 (setq org-latex-fragment-image-overlays nil))
23632 (defun org-preview-latex-fragment (&optional subtree)
23633 "Preview the LaTeX fragment at point, or all locally or globally.
23634 If the cursor is in a LaTeX fragment, create the image and overlay
23635 it over the source code. If there is no fragment at point, display
23636 all fragments in the current text, from one headline to the next. With
23637 prefix SUBTREE, display all fragments in the current subtree. With a
23638 double prefix `C-u C-u', or when the cursor is before the first headline,
23639 display all fragments in the buffer.
23640 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23641 (interactive "P")
23642 (org-remove-latex-fragment-image-overlays)
23643 (save-excursion
23644 (save-restriction
23645 (let (beg end at msg)
23646 (cond
23647 ((or (equal subtree '(16))
23648 (not (save-excursion
23649 (re-search-backward (concat "^" outline-regexp) nil t))))
23650 (setq beg (point-min) end (point-max)
23651 msg "Creating images for buffer...%s"))
23652 ((equal subtree '(4))
23653 (org-back-to-heading)
23654 (setq beg (point) end (org-end-of-subtree t)
23655 msg "Creating images for subtree...%s"))
23657 (if (setq at (org-inside-LaTeX-fragment-p))
23658 (goto-char (max (point-min) (- (cdr at) 2)))
23659 (org-back-to-heading))
23660 (setq beg (point) end (progn (outline-next-heading) (point))
23661 msg (if at "Creating image...%s"
23662 "Creating images for entry...%s"))))
23663 (message msg "")
23664 (narrow-to-region beg end)
23665 (goto-char beg)
23666 (org-format-latex
23667 (concat "ltxpng/" (file-name-sans-extension
23668 (file-name-nondirectory
23669 buffer-file-name)))
23670 default-directory 'overlays msg at 'forbuffer)
23671 (message msg "done. Use `C-c C-c' to remove images.")))))
23673 (defvar org-latex-regexps
23674 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23675 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23676 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23677 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23678 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23679 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23680 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23681 "Regular expressions for matching embedded LaTeX.")
23683 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23684 "Replace LaTeX fragments with links to an image, and produce images."
23685 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23686 (let* ((prefixnodir (file-name-nondirectory prefix))
23687 (absprefix (expand-file-name prefix dir))
23688 (todir (file-name-directory absprefix))
23689 (opt org-format-latex-options)
23690 (matchers (plist-get opt :matchers))
23691 (re-list org-latex-regexps)
23692 (cnt 0) txt link beg end re e checkdir
23693 m n block linkfile movefile ov)
23694 ;; Check if there are old images files with this prefix, and remove them
23695 (when (file-directory-p todir)
23696 (mapc 'delete-file
23697 (directory-files
23698 todir 'full
23699 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23700 ;; Check the different regular expressions
23701 (while (setq e (pop re-list))
23702 (setq m (car e) re (nth 1 e) n (nth 2 e)
23703 block (if (nth 3 e) "\n\n" ""))
23704 (when (member m matchers)
23705 (goto-char (point-min))
23706 (while (re-search-forward re nil t)
23707 (when (or (not at) (equal (cdr at) (match-beginning n)))
23708 (setq txt (match-string n)
23709 beg (match-beginning n) end (match-end n)
23710 cnt (1+ cnt)
23711 linkfile (format "%s_%04d.png" prefix cnt)
23712 movefile (format "%s_%04d.png" absprefix cnt)
23713 link (concat block "[[file:" linkfile "]]" block))
23714 (if msg (message msg cnt))
23715 (goto-char beg)
23716 (unless checkdir ; make sure the directory exists
23717 (setq checkdir t)
23718 (or (file-directory-p todir) (make-directory todir)))
23719 (org-create-formula-image
23720 txt movefile opt forbuffer)
23721 (if overlays
23722 (progn
23723 (setq ov (org-make-overlay beg end))
23724 (if (featurep 'xemacs)
23725 (progn
23726 (org-overlay-put ov 'invisible t)
23727 (org-overlay-put
23728 ov 'end-glyph
23729 (make-glyph (vector 'png :file movefile))))
23730 (org-overlay-put
23731 ov 'display
23732 (list 'image :type 'png :file movefile :ascent 'center)))
23733 (push ov org-latex-fragment-image-overlays)
23734 (goto-char end))
23735 (delete-region beg end)
23736 (insert link))))))))
23738 ;; This function borrows from Ganesh Swami's latex2png.el
23739 (defun org-create-formula-image (string tofile options buffer)
23740 (let* ((tmpdir (if (featurep 'xemacs)
23741 (temp-directory)
23742 temporary-file-directory))
23743 (texfilebase (make-temp-name
23744 (expand-file-name "orgtex" tmpdir)))
23745 (texfile (concat texfilebase ".tex"))
23746 (dvifile (concat texfilebase ".dvi"))
23747 (pngfile (concat texfilebase ".png"))
23748 (fnh (face-attribute 'default :height nil))
23749 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23750 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23751 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23752 "Black"))
23753 (bg (or (plist-get options (if buffer :background :html-background))
23754 "Transparent")))
23755 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23756 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23757 (with-temp-file texfile
23758 (insert org-format-latex-header
23759 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23760 (let ((dir default-directory))
23761 (condition-case nil
23762 (progn
23763 (cd tmpdir)
23764 (call-process "latex" nil nil nil texfile))
23765 (error nil))
23766 (cd dir))
23767 (if (not (file-exists-p dvifile))
23768 (progn (message "Failed to create dvi file from %s" texfile) nil)
23769 (call-process "dvipng" nil nil nil
23770 "-E" "-fg" fg "-bg" bg
23771 "-D" dpi
23772 ;;"-x" scale "-y" scale
23773 "-T" "tight"
23774 "-o" pngfile
23775 dvifile)
23776 (if (not (file-exists-p pngfile))
23777 (progn (message "Failed to create png file from %s" texfile) nil)
23778 ;; Use the requested file name and clean up
23779 (copy-file pngfile tofile 'replace)
23780 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23781 (delete-file (concat texfilebase e)))
23782 pngfile))))
23784 (defun org-dvipng-color (attr)
23785 "Return an rgb color specification for dvipng."
23786 (apply 'format "rgb %s %s %s"
23787 (mapcar 'org-normalize-color
23788 (color-values (face-attribute 'default attr nil)))))
23790 (defun org-normalize-color (value)
23791 "Return string to be used as color value for an RGB component."
23792 (format "%g" (/ value 65535.0)))
23794 ;;;; Exporting
23796 ;;; Variables, constants, and parameter plists
23798 (defconst org-level-max 20)
23800 (defvar org-export-html-preamble nil
23801 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23802 (defvar org-export-html-postamble nil
23803 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23804 (defvar org-export-html-auto-preamble t
23805 "Should default preamble be inserted? Set by publishing functions.")
23806 (defvar org-export-html-auto-postamble t
23807 "Should default postamble be inserted? Set by publishing functions.")
23808 (defvar org-current-export-file nil) ; dynamically scoped parameter
23809 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23812 (defconst org-export-plist-vars
23813 '((:language . org-export-default-language)
23814 (:customtime . org-display-custom-times)
23815 (:headline-levels . org-export-headline-levels)
23816 (:section-numbers . org-export-with-section-numbers)
23817 (:table-of-contents . org-export-with-toc)
23818 (:preserve-breaks . org-export-preserve-breaks)
23819 (:archived-trees . org-export-with-archived-trees)
23820 (:emphasize . org-export-with-emphasize)
23821 (:sub-superscript . org-export-with-sub-superscripts)
23822 (:special-strings . org-export-with-special-strings)
23823 (:footnotes . org-export-with-footnotes)
23824 (:drawers . org-export-with-drawers)
23825 (:tags . org-export-with-tags)
23826 (:TeX-macros . org-export-with-TeX-macros)
23827 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23828 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23829 (:fixed-width . org-export-with-fixed-width)
23830 (:timestamps . org-export-with-timestamps)
23831 (:author-info . org-export-author-info)
23832 (:time-stamp-file . org-export-time-stamp-file)
23833 (:tables . org-export-with-tables)
23834 (:table-auto-headline . org-export-highlight-first-table-line)
23835 (:style . org-export-html-style)
23836 (:agenda-style . org-agenda-export-html-style)
23837 (:convert-org-links . org-export-html-link-org-files-as-html)
23838 (:inline-images . org-export-html-inline-images)
23839 (:html-extension . org-export-html-extension)
23840 (:html-table-tag . org-export-html-table-tag)
23841 (:expand-quoted-html . org-export-html-expand)
23842 (:timestamp . org-export-html-with-timestamp)
23843 (:publishing-directory . org-export-publishing-directory)
23844 (:preamble . org-export-html-preamble)
23845 (:postamble . org-export-html-postamble)
23846 (:auto-preamble . org-export-html-auto-preamble)
23847 (:auto-postamble . org-export-html-auto-postamble)
23848 (:author . user-full-name)
23849 (:email . user-mail-address)))
23851 (defun org-default-export-plist ()
23852 "Return the property list with default settings for the export variables."
23853 (let ((l org-export-plist-vars) rtn e)
23854 (while (setq e (pop l))
23855 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23856 rtn))
23858 (defun org-infile-export-plist ()
23859 "Return the property list with file-local settings for export."
23860 (save-excursion
23861 (save-restriction
23862 (widen)
23863 (goto-char 0)
23864 (let ((re (org-make-options-regexp
23865 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23866 p key val text options)
23867 (while (re-search-forward re nil t)
23868 (setq key (org-match-string-no-properties 1)
23869 val (org-match-string-no-properties 2))
23870 (cond
23871 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23872 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23873 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23874 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23875 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23876 ((string-equal key "TEXT")
23877 (setq text (if text (concat text "\n" val) val)))
23878 ((string-equal key "OPTIONS") (setq options val))))
23879 (setq p (plist-put p :text text))
23880 (when options
23881 (let ((op '(("H" . :headline-levels)
23882 ("num" . :section-numbers)
23883 ("toc" . :table-of-contents)
23884 ("\\n" . :preserve-breaks)
23885 ("@" . :expand-quoted-html)
23886 (":" . :fixed-width)
23887 ("|" . :tables)
23888 ("^" . :sub-superscript)
23889 ("-" . :special-strings)
23890 ("f" . :footnotes)
23891 ("d" . :drawers)
23892 ("tags" . :tags)
23893 ("*" . :emphasize)
23894 ("TeX" . :TeX-macros)
23895 ("LaTeX" . :LaTeX-fragments)
23896 ("skip" . :skip-before-1st-heading)
23897 ("author" . :author-info)
23898 ("timestamp" . :time-stamp-file)))
23900 (while (setq o (pop op))
23901 (if (string-match (concat (regexp-quote (car o))
23902 ":\\([^ \t\n\r;,.]*\\)")
23903 options)
23904 (setq p (plist-put p (cdr o)
23905 (car (read-from-string
23906 (match-string 1 options)))))))))
23907 p))))
23909 (defun org-export-directory (type plist)
23910 (let* ((val (plist-get plist :publishing-directory))
23911 (dir (if (listp val)
23912 (or (cdr (assoc type val)) ".")
23913 val)))
23914 dir))
23916 (defun org-skip-comments (lines)
23917 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23918 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23919 (re2 "^\\(\\*+\\)[ \t\n\r]")
23920 (case-fold-search nil)
23921 rtn line level)
23922 (while (setq line (pop lines))
23923 (cond
23924 ((and (string-match re1 line)
23925 (setq level (- (match-end 1) (match-beginning 1))))
23926 ;; Beginning of a COMMENT subtree. Skip it.
23927 (while (and (setq line (pop lines))
23928 (or (not (string-match re2 line))
23929 (> (- (match-end 1) (match-beginning 1)) level))))
23930 (setq lines (cons line lines)))
23931 ((string-match "^#" line)
23932 ;; an ordinary comment line
23934 ((and org-export-table-remove-special-lines
23935 (string-match "^[ \t]*|" line)
23936 (or (string-match "^[ \t]*| *[!_^] *|" line)
23937 (and (string-match "| *<[0-9]+> *|" line)
23938 (not (string-match "| *[^ <|]" line)))))
23939 ;; a special table line that should be removed
23941 (t (setq rtn (cons line rtn)))))
23942 (nreverse rtn)))
23944 (defun org-export (&optional arg)
23945 (interactive)
23946 (let ((help "[t] insert the export option template
23947 \[v] limit export to visible part of outline tree
23949 \[a] export as ASCII
23951 \[h] export as HTML
23952 \[H] export as HTML to temporary buffer
23953 \[R] export region as HTML
23954 \[b] export as HTML and browse immediately
23955 \[x] export as XOXO
23957 \[l] export as LaTeX
23958 \[L] export as LaTeX to temporary buffer
23960 \[i] export current file as iCalendar file
23961 \[I] export all agenda files as iCalendar files
23962 \[c] export agenda files into combined iCalendar file
23964 \[F] publish current file
23965 \[P] publish current project
23966 \[X] publish... (project will be prompted for)
23967 \[A] publish all projects")
23968 (cmds
23969 '((?t . org-insert-export-options-template)
23970 (?v . org-export-visible)
23971 (?a . org-export-as-ascii)
23972 (?h . org-export-as-html)
23973 (?b . org-export-as-html-and-open)
23974 (?H . org-export-as-html-to-buffer)
23975 (?R . org-export-region-as-html)
23976 (?x . org-export-as-xoxo)
23977 (?l . org-export-as-latex)
23978 (?L . org-export-as-latex-to-buffer)
23979 (?i . org-export-icalendar-this-file)
23980 (?I . org-export-icalendar-all-agenda-files)
23981 (?c . org-export-icalendar-combine-agenda-files)
23982 (?F . org-publish-current-file)
23983 (?P . org-publish-current-project)
23984 (?X . org-publish)
23985 (?A . org-publish-all)))
23986 r1 r2 ass)
23987 (save-window-excursion
23988 (delete-other-windows)
23989 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23990 (princ help))
23991 (message "Select command: ")
23992 (setq r1 (read-char-exclusive)))
23993 (setq r2 (if (< r1 27) (+ r1 96) r1))
23994 (if (setq ass (assq r2 cmds))
23995 (call-interactively (cdr ass))
23996 (error "No command associated with key %c" r1))))
23998 (defconst org-html-entities
23999 '(("nbsp")
24000 ("iexcl")
24001 ("cent")
24002 ("pound")
24003 ("curren")
24004 ("yen")
24005 ("brvbar")
24006 ("vert" . "&#124;")
24007 ("sect")
24008 ("uml")
24009 ("copy")
24010 ("ordf")
24011 ("laquo")
24012 ("not")
24013 ("shy")
24014 ("reg")
24015 ("macr")
24016 ("deg")
24017 ("plusmn")
24018 ("sup2")
24019 ("sup3")
24020 ("acute")
24021 ("micro")
24022 ("para")
24023 ("middot")
24024 ("odot"."o")
24025 ("star"."*")
24026 ("cedil")
24027 ("sup1")
24028 ("ordm")
24029 ("raquo")
24030 ("frac14")
24031 ("frac12")
24032 ("frac34")
24033 ("iquest")
24034 ("Agrave")
24035 ("Aacute")
24036 ("Acirc")
24037 ("Atilde")
24038 ("Auml")
24039 ("Aring") ("AA"."&Aring;")
24040 ("AElig")
24041 ("Ccedil")
24042 ("Egrave")
24043 ("Eacute")
24044 ("Ecirc")
24045 ("Euml")
24046 ("Igrave")
24047 ("Iacute")
24048 ("Icirc")
24049 ("Iuml")
24050 ("ETH")
24051 ("Ntilde")
24052 ("Ograve")
24053 ("Oacute")
24054 ("Ocirc")
24055 ("Otilde")
24056 ("Ouml")
24057 ("times")
24058 ("Oslash")
24059 ("Ugrave")
24060 ("Uacute")
24061 ("Ucirc")
24062 ("Uuml")
24063 ("Yacute")
24064 ("THORN")
24065 ("szlig")
24066 ("agrave")
24067 ("aacute")
24068 ("acirc")
24069 ("atilde")
24070 ("auml")
24071 ("aring")
24072 ("aelig")
24073 ("ccedil")
24074 ("egrave")
24075 ("eacute")
24076 ("ecirc")
24077 ("euml")
24078 ("igrave")
24079 ("iacute")
24080 ("icirc")
24081 ("iuml")
24082 ("eth")
24083 ("ntilde")
24084 ("ograve")
24085 ("oacute")
24086 ("ocirc")
24087 ("otilde")
24088 ("ouml")
24089 ("divide")
24090 ("oslash")
24091 ("ugrave")
24092 ("uacute")
24093 ("ucirc")
24094 ("uuml")
24095 ("yacute")
24096 ("thorn")
24097 ("yuml")
24098 ("fnof")
24099 ("Alpha")
24100 ("Beta")
24101 ("Gamma")
24102 ("Delta")
24103 ("Epsilon")
24104 ("Zeta")
24105 ("Eta")
24106 ("Theta")
24107 ("Iota")
24108 ("Kappa")
24109 ("Lambda")
24110 ("Mu")
24111 ("Nu")
24112 ("Xi")
24113 ("Omicron")
24114 ("Pi")
24115 ("Rho")
24116 ("Sigma")
24117 ("Tau")
24118 ("Upsilon")
24119 ("Phi")
24120 ("Chi")
24121 ("Psi")
24122 ("Omega")
24123 ("alpha")
24124 ("beta")
24125 ("gamma")
24126 ("delta")
24127 ("epsilon")
24128 ("varepsilon"."&epsilon;")
24129 ("zeta")
24130 ("eta")
24131 ("theta")
24132 ("iota")
24133 ("kappa")
24134 ("lambda")
24135 ("mu")
24136 ("nu")
24137 ("xi")
24138 ("omicron")
24139 ("pi")
24140 ("rho")
24141 ("sigmaf") ("varsigma"."&sigmaf;")
24142 ("sigma")
24143 ("tau")
24144 ("upsilon")
24145 ("phi")
24146 ("chi")
24147 ("psi")
24148 ("omega")
24149 ("thetasym") ("vartheta"."&thetasym;")
24150 ("upsih")
24151 ("piv")
24152 ("bull") ("bullet"."&bull;")
24153 ("hellip") ("dots"."&hellip;")
24154 ("prime")
24155 ("Prime")
24156 ("oline")
24157 ("frasl")
24158 ("weierp")
24159 ("image")
24160 ("real")
24161 ("trade")
24162 ("alefsym")
24163 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24164 ("uarr") ("uparrow"."&uarr;")
24165 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24166 ("darr")("downarrow"."&darr;")
24167 ("harr") ("leftrightarrow"."&harr;")
24168 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24169 ("lArr") ("Leftarrow"."&lArr;")
24170 ("uArr") ("Uparrow"."&uArr;")
24171 ("rArr") ("Rightarrow"."&rArr;")
24172 ("dArr") ("Downarrow"."&dArr;")
24173 ("hArr") ("Leftrightarrow"."&hArr;")
24174 ("forall")
24175 ("part") ("partial"."&part;")
24176 ("exist") ("exists"."&exist;")
24177 ("empty") ("emptyset"."&empty;")
24178 ("nabla")
24179 ("isin") ("in"."&isin;")
24180 ("notin")
24181 ("ni")
24182 ("prod")
24183 ("sum")
24184 ("minus")
24185 ("lowast") ("ast"."&lowast;")
24186 ("radic")
24187 ("prop") ("proptp"."&prop;")
24188 ("infin") ("infty"."&infin;")
24189 ("ang") ("angle"."&ang;")
24190 ("and") ("wedge"."&and;")
24191 ("or") ("vee"."&or;")
24192 ("cap")
24193 ("cup")
24194 ("int")
24195 ("there4")
24196 ("sim")
24197 ("cong") ("simeq"."&cong;")
24198 ("asymp")("approx"."&asymp;")
24199 ("ne") ("neq"."&ne;")
24200 ("equiv")
24201 ("le")
24202 ("ge")
24203 ("sub") ("subset"."&sub;")
24204 ("sup") ("supset"."&sup;")
24205 ("nsub")
24206 ("sube")
24207 ("supe")
24208 ("oplus")
24209 ("otimes")
24210 ("perp")
24211 ("sdot") ("cdot"."&sdot;")
24212 ("lceil")
24213 ("rceil")
24214 ("lfloor")
24215 ("rfloor")
24216 ("lang")
24217 ("rang")
24218 ("loz") ("Diamond"."&loz;")
24219 ("spades") ("spadesuit"."&spades;")
24220 ("clubs") ("clubsuit"."&clubs;")
24221 ("hearts") ("diamondsuit"."&hearts;")
24222 ("diams") ("diamondsuit"."&diams;")
24223 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24224 ("quot")
24225 ("amp")
24226 ("lt")
24227 ("gt")
24228 ("OElig")
24229 ("oelig")
24230 ("Scaron")
24231 ("scaron")
24232 ("Yuml")
24233 ("circ")
24234 ("tilde")
24235 ("ensp")
24236 ("emsp")
24237 ("thinsp")
24238 ("zwnj")
24239 ("zwj")
24240 ("lrm")
24241 ("rlm")
24242 ("ndash")
24243 ("mdash")
24244 ("lsquo")
24245 ("rsquo")
24246 ("sbquo")
24247 ("ldquo")
24248 ("rdquo")
24249 ("bdquo")
24250 ("dagger")
24251 ("Dagger")
24252 ("permil")
24253 ("lsaquo")
24254 ("rsaquo")
24255 ("euro")
24257 ("arccos"."arccos")
24258 ("arcsin"."arcsin")
24259 ("arctan"."arctan")
24260 ("arg"."arg")
24261 ("cos"."cos")
24262 ("cosh"."cosh")
24263 ("cot"."cot")
24264 ("coth"."coth")
24265 ("csc"."csc")
24266 ("deg"."deg")
24267 ("det"."det")
24268 ("dim"."dim")
24269 ("exp"."exp")
24270 ("gcd"."gcd")
24271 ("hom"."hom")
24272 ("inf"."inf")
24273 ("ker"."ker")
24274 ("lg"."lg")
24275 ("lim"."lim")
24276 ("liminf"."liminf")
24277 ("limsup"."limsup")
24278 ("ln"."ln")
24279 ("log"."log")
24280 ("max"."max")
24281 ("min"."min")
24282 ("Pr"."Pr")
24283 ("sec"."sec")
24284 ("sin"."sin")
24285 ("sinh"."sinh")
24286 ("sup"."sup")
24287 ("tan"."tan")
24288 ("tanh"."tanh")
24290 "Entities for TeX->HTML translation.
24291 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24292 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24293 In that case, \"\\ent\" will be translated to \"&other;\".
24294 The list contains HTML entities for Latin-1, Greek and other symbols.
24295 It is supplemented by a number of commonly used TeX macros with appropriate
24296 translations. There is currently no way for users to extend this.")
24298 ;;; General functions for all backends
24300 (defun org-cleaned-string-for-export (string &rest parameters)
24301 "Cleanup a buffer STRING so that links can be created safely."
24302 (interactive)
24303 (let* ((re-radio (and org-target-link-regexp
24304 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24305 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24306 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24307 (re-archive (concat ":" org-archive-tag ":"))
24308 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24309 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24310 (htmlp (plist-get parameters :for-html))
24311 (asciip (plist-get parameters :for-ascii))
24312 (latexp (plist-get parameters :for-LaTeX))
24313 (commentsp (plist-get parameters :comments))
24314 (archived-trees (plist-get parameters :archived-trees))
24315 (inhibit-read-only t)
24316 (drawers org-drawers)
24317 (exp-drawers (plist-get parameters :drawers))
24318 (outline-regexp "\\*+ ")
24319 a b xx
24320 rtn p)
24321 (with-current-buffer (get-buffer-create " org-mode-tmp")
24322 (erase-buffer)
24323 (insert string)
24324 ;; Remove license-to-kill stuff
24325 (while (setq p (text-property-any (point-min) (point-max)
24326 :org-license-to-kill t))
24327 (delete-region p (next-single-property-change p :org-license-to-kill)))
24329 (let ((org-inhibit-startup t)) (org-mode))
24330 (untabify (point-min) (point-max))
24332 ;; Get rid of drawers
24333 (unless (eq t exp-drawers)
24334 (goto-char (point-min))
24335 (let ((re (concat "^[ \t]*:\\("
24336 (mapconcat
24337 'identity
24338 (org-delete-all exp-drawers
24339 (copy-sequence drawers))
24340 "\\|")
24341 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24342 (while (re-search-forward re nil t)
24343 (replace-match ""))))
24345 ;; Get the correct stuff before the first headline
24346 (when (plist-get parameters :skip-before-1st-heading)
24347 (goto-char (point-min))
24348 (when (re-search-forward "^\\*+[ \t]" nil t)
24349 (delete-region (point-min) (match-beginning 0))
24350 (goto-char (point-min))
24351 (insert "\n")))
24352 (when (plist-get parameters :add-text)
24353 (goto-char (point-min))
24354 (insert (plist-get parameters :add-text) "\n"))
24356 ;; Get rid of archived trees
24357 (when (not (eq archived-trees t))
24358 (goto-char (point-min))
24359 (while (re-search-forward re-archive nil t)
24360 (if (not (org-on-heading-p t))
24361 (org-end-of-subtree t)
24362 (beginning-of-line 1)
24363 (setq a (if archived-trees
24364 (1+ (point-at-eol)) (point))
24365 b (org-end-of-subtree t))
24366 (if (> b a) (delete-region a b)))))
24368 ;; Find targets in comments and move them out of comments,
24369 ;; but mark them as targets that should be invisible
24370 (goto-char (point-min))
24371 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24372 (replace-match "\\1(INVISIBLE)"))
24374 ;; Protect backend specific stuff, throw away the others.
24375 (let ((formatters
24376 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24377 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24378 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24379 fmt)
24380 (goto-char (point-min))
24381 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24382 (goto-char (match-end 0))
24383 (while (not (looking-at "#\\+END_EXAMPLE"))
24384 (insert ": ")
24385 (beginning-of-line 2)))
24386 (goto-char (point-min))
24387 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24388 (add-text-properties (match-beginning 0) (match-end 0)
24389 '(org-protected t)))
24390 (while formatters
24391 (setq fmt (pop formatters))
24392 (when (car fmt)
24393 (goto-char (point-min))
24394 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24395 ":[ \t]*\\(.*\\)") nil t)
24396 (replace-match "\\1" t)
24397 (add-text-properties
24398 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24399 '(org-protected t))))
24400 (goto-char (point-min))
24401 (while (re-search-forward
24402 (concat "^#\\+"
24403 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24404 (cadddr fmt) "\\>.*\n?") nil t)
24405 (if (car fmt)
24406 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24407 '(org-protected t))
24408 (delete-region (match-beginning 0) (match-end 0))))))
24410 ;; Protect quoted subtrees
24411 (goto-char (point-min))
24412 (while (re-search-forward re-quote nil t)
24413 (goto-char (match-beginning 0))
24414 (end-of-line 1)
24415 (add-text-properties (point) (org-end-of-subtree t)
24416 '(org-protected t)))
24418 ;; Protect verbatim elements
24419 (goto-char (point-min))
24420 (while (re-search-forward org-verbatim-re nil t)
24421 (add-text-properties (match-beginning 4) (match-end 4)
24422 '(org-protected t))
24423 (goto-char (1+ (match-end 4))))
24425 ;; Remove subtrees that are commented
24426 (goto-char (point-min))
24427 (while (re-search-forward re-commented nil t)
24428 (goto-char (match-beginning 0))
24429 (delete-region (point) (org-end-of-subtree t)))
24431 ;; Remove special table lines
24432 (when org-export-table-remove-special-lines
24433 (goto-char (point-min))
24434 (while (re-search-forward "^[ \t]*|" nil t)
24435 (beginning-of-line 1)
24436 (if (or (looking-at "[ \t]*| *[!_^] *|")
24437 (and (looking-at ".*?| *<[0-9]+> *|")
24438 (not (looking-at ".*?| *[^ <|]"))))
24439 (delete-region (max (point-min) (1- (point-at-bol)))
24440 (point-at-eol))
24441 (end-of-line 1))))
24443 ;; Specific LaTeX stuff
24444 (when latexp
24445 (require 'org-export-latex nil)
24446 (org-export-latex-cleaned-string))
24448 (when asciip
24449 (org-export-ascii-clean-string))
24451 ;; Specific HTML stuff
24452 (when htmlp
24453 ;; Convert LaTeX fragments to images
24454 (when (plist-get parameters :LaTeX-fragments)
24455 (org-format-latex
24456 (concat "ltxpng/" (file-name-sans-extension
24457 (file-name-nondirectory
24458 org-current-export-file)))
24459 org-current-export-dir nil "Creating LaTeX image %s"))
24460 (message "Exporting..."))
24462 ;; Remove or replace comments
24463 (goto-char (point-min))
24464 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24465 (if commentsp
24466 (progn (add-text-properties
24467 (match-beginning 0) (match-end 0) '(org-protected t))
24468 (replace-match (format commentsp (match-string 1)) t t))
24469 (replace-match "")))
24471 ;; Find matches for radio targets and turn them into internal links
24472 (goto-char (point-min))
24473 (when re-radio
24474 (while (re-search-forward re-radio nil t)
24475 (org-if-unprotected
24476 (replace-match "\\1[[\\2]]"))))
24478 ;; Find all links that contain a newline and put them into a single line
24479 (goto-char (point-min))
24480 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24481 (org-if-unprotected
24482 (replace-match "\\1 \\3")
24483 (goto-char (match-beginning 0))))
24486 ;; Normalize links: Convert angle and plain links into bracket links
24487 ;; Expand link abbreviations
24488 (goto-char (point-min))
24489 (while (re-search-forward re-plain-link nil t)
24490 (goto-char (1- (match-end 0)))
24491 (org-if-unprotected
24492 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24493 ":" (match-string 3) "]]")))
24494 ;; added 'org-link face to links
24495 (put-text-property 0 (length s) 'face 'org-link s)
24496 (replace-match s t t))))
24497 (goto-char (point-min))
24498 (while (re-search-forward re-angle-link nil t)
24499 (goto-char (1- (match-end 0)))
24500 (org-if-unprotected
24501 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24502 ":" (match-string 3) "]]")))
24503 (put-text-property 0 (length s) 'face 'org-link s)
24504 (replace-match s t t))))
24505 (goto-char (point-min))
24506 (while (re-search-forward org-bracket-link-regexp nil t)
24507 (org-if-unprotected
24508 (let* ((s (concat "[[" (setq xx (save-match-data
24509 (org-link-expand-abbrev (match-string 1))))
24511 (if (match-end 3)
24512 (match-string 2)
24513 (concat "[" xx "]"))
24514 "]")))
24515 (put-text-property 0 (length s) 'face 'org-link s)
24516 (replace-match s t t))))
24518 ;; Find multiline emphasis and put them into single line
24519 (when (plist-get parameters :emph-multiline)
24520 (goto-char (point-min))
24521 (while (re-search-forward org-emph-re nil t)
24522 (if (not (= (char-after (match-beginning 3))
24523 (char-after (match-beginning 4))))
24524 (org-if-unprotected
24525 (subst-char-in-region (match-beginning 0) (match-end 0)
24526 ?\n ?\ t)
24527 (goto-char (1- (match-end 0))))
24528 (goto-char (1+ (match-beginning 0))))))
24530 (setq rtn (buffer-string)))
24531 (kill-buffer " org-mode-tmp")
24532 rtn))
24534 (defun org-export-grab-title-from-buffer ()
24535 "Get a title for the current document, from looking at the buffer."
24536 (let ((inhibit-read-only t))
24537 (save-excursion
24538 (goto-char (point-min))
24539 (let ((end (save-excursion (outline-next-heading) (point))))
24540 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24541 ;; Mark the line so that it will not be exported as normal text.
24542 (org-unmodified
24543 (add-text-properties (match-beginning 0) (match-end 0)
24544 (list :org-license-to-kill t)))
24545 ;; Return the title string
24546 (org-trim (match-string 0)))))))
24548 (defun org-export-get-title-from-subtree ()
24549 "Return subtree title and exclude it from export."
24550 (let (title (m (mark)))
24551 (save-excursion
24552 (goto-char (region-beginning))
24553 (when (and (org-at-heading-p)
24554 (>= (org-end-of-subtree t t) (region-end)))
24555 ;; This is a subtree, we take the title from the first heading
24556 (goto-char (region-beginning))
24557 (looking-at org-todo-line-regexp)
24558 (setq title (match-string 3))
24559 (org-unmodified
24560 (add-text-properties (point) (1+ (point-at-eol))
24561 (list :org-license-to-kill t)))))
24562 title))
24564 (defun org-solidify-link-text (s &optional alist)
24565 "Take link text and make a safe target out of it."
24566 (save-match-data
24567 (let* ((rtn
24568 (mapconcat
24569 'identity
24570 (org-split-string s "[ \t\r\n]+") "--"))
24571 (a (assoc rtn alist)))
24572 (or (cdr a) rtn))))
24574 (defun org-get-min-level (lines)
24575 "Get the minimum level in LINES."
24576 (let ((re "^\\(\\*+\\) ") l min)
24577 (catch 'exit
24578 (while (setq l (pop lines))
24579 (if (string-match re l)
24580 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24581 1)))
24583 ;; Variable holding the vector with section numbers
24584 (defvar org-section-numbers (make-vector org-level-max 0))
24586 (defun org-init-section-numbers ()
24587 "Initialize the vector for the section numbers."
24588 (let* ((level -1)
24589 (numbers (nreverse (org-split-string "" "\\.")))
24590 (depth (1- (length org-section-numbers)))
24591 (i depth) number-string)
24592 (while (>= i 0)
24593 (if (> i level)
24594 (aset org-section-numbers i 0)
24595 (setq number-string (or (car numbers) "0"))
24596 (if (string-match "\\`[A-Z]\\'" number-string)
24597 (aset org-section-numbers i
24598 (- (string-to-char number-string) ?A -1))
24599 (aset org-section-numbers i (string-to-number number-string)))
24600 (pop numbers))
24601 (setq i (1- i)))))
24603 (defun org-section-number (&optional level)
24604 "Return a string with the current section number.
24605 When LEVEL is non-nil, increase section numbers on that level."
24606 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24607 (when level
24608 (when (> level -1)
24609 (aset org-section-numbers
24610 level (1+ (aref org-section-numbers level))))
24611 (setq idx (1+ level))
24612 (while (<= idx depth)
24613 (if (not (= idx 1))
24614 (aset org-section-numbers idx 0))
24615 (setq idx (1+ idx))))
24616 (setq idx 0)
24617 (while (<= idx depth)
24618 (setq n (aref org-section-numbers idx))
24619 (setq string (concat string (if (not (string= string "")) "." "")
24620 (int-to-string n)))
24621 (setq idx (1+ idx)))
24622 (save-match-data
24623 (if (string-match "\\`\\([@0]\\.\\)+" string)
24624 (setq string (replace-match "" t nil string)))
24625 (if (string-match "\\(\\.0\\)+\\'" string)
24626 (setq string (replace-match "" t nil string))))
24627 string))
24629 ;;; ASCII export
24631 (defvar org-last-level nil) ; dynamically scoped variable
24632 (defvar org-min-level nil) ; dynamically scoped variable
24633 (defvar org-levels-open nil) ; dynamically scoped parameter
24634 (defvar org-ascii-current-indentation nil) ; For communication
24636 (defun org-export-as-ascii (arg)
24637 "Export the outline as a pretty ASCII file.
24638 If there is an active region, export only the region.
24639 The prefix ARG specifies how many levels of the outline should become
24640 underlined headlines. The default is 3."
24641 (interactive "P")
24642 (setq-default org-todo-line-regexp org-todo-line-regexp)
24643 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24644 (org-infile-export-plist)))
24645 (region-p (org-region-active-p))
24646 (subtree-p
24647 (when region-p
24648 (save-excursion
24649 (goto-char (region-beginning))
24650 (and (org-at-heading-p)
24651 (>= (org-end-of-subtree t t) (region-end))))))
24652 (custom-times org-display-custom-times)
24653 (org-ascii-current-indentation '(0 . 0))
24654 (level 0) line txt
24655 (umax nil)
24656 (umax-toc nil)
24657 (case-fold-search nil)
24658 (filename (concat (file-name-as-directory
24659 (org-export-directory :ascii opt-plist))
24660 (file-name-sans-extension
24661 (or (and subtree-p
24662 (org-entry-get (region-beginning)
24663 "EXPORT_FILE_NAME" t))
24664 (file-name-nondirectory buffer-file-name)))
24665 ".txt"))
24666 (filename (if (equal (file-truename filename)
24667 (file-truename buffer-file-name))
24668 (concat filename ".txt")
24669 filename))
24670 (buffer (find-file-noselect filename))
24671 (org-levels-open (make-vector org-level-max nil))
24672 (odd org-odd-levels-only)
24673 (date (plist-get opt-plist :date))
24674 (author (plist-get opt-plist :author))
24675 (title (or (and subtree-p (org-export-get-title-from-subtree))
24676 (plist-get opt-plist :title)
24677 (and (not
24678 (plist-get opt-plist :skip-before-1st-heading))
24679 (org-export-grab-title-from-buffer))
24680 (file-name-sans-extension
24681 (file-name-nondirectory buffer-file-name))))
24682 (email (plist-get opt-plist :email))
24683 (language (plist-get opt-plist :language))
24684 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24685 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24686 (todo nil)
24687 (lang-words nil)
24688 (region
24689 (buffer-substring
24690 (if (org-region-active-p) (region-beginning) (point-min))
24691 (if (org-region-active-p) (region-end) (point-max))))
24692 (lines (org-split-string
24693 (org-cleaned-string-for-export
24694 region
24695 :for-ascii t
24696 :skip-before-1st-heading
24697 (plist-get opt-plist :skip-before-1st-heading)
24698 :drawers (plist-get opt-plist :drawers)
24699 :verbatim-multiline t
24700 :archived-trees
24701 (plist-get opt-plist :archived-trees)
24702 :add-text (plist-get opt-plist :text))
24703 "\n"))
24704 thetoc have-headings first-heading-pos
24705 table-open table-buffer)
24707 (let ((inhibit-read-only t))
24708 (org-unmodified
24709 (remove-text-properties (point-min) (point-max)
24710 '(:org-license-to-kill t))))
24712 (setq org-min-level (org-get-min-level lines))
24713 (setq org-last-level org-min-level)
24714 (org-init-section-numbers)
24716 (find-file-noselect filename)
24718 (setq lang-words (or (assoc language org-export-language-setup)
24719 (assoc "en" org-export-language-setup)))
24720 (switch-to-buffer-other-window buffer)
24721 (erase-buffer)
24722 (fundamental-mode)
24723 ;; create local variables for all options, to make sure all called
24724 ;; functions get the correct information
24725 (mapc (lambda (x)
24726 (set (make-local-variable (cdr x))
24727 (plist-get opt-plist (car x))))
24728 org-export-plist-vars)
24729 (org-set-local 'org-odd-levels-only odd)
24730 (setq umax (if arg (prefix-numeric-value arg)
24731 org-export-headline-levels))
24732 (setq umax-toc (if (integerp org-export-with-toc)
24733 (min org-export-with-toc umax)
24734 umax))
24736 ;; File header
24737 (if title (org-insert-centered title ?=))
24738 (insert "\n")
24739 (if (and (or author email)
24740 org-export-author-info)
24741 (insert (concat (nth 1 lang-words) ": " (or author "")
24742 (if email (concat " <" email ">") "")
24743 "\n")))
24745 (cond
24746 ((and date (string-match "%" date))
24747 (setq date (format-time-string date (current-time))))
24748 (date)
24749 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24751 (if (and date org-export-time-stamp-file)
24752 (insert (concat (nth 2 lang-words) ": " date"\n")))
24754 (insert "\n\n")
24756 (if org-export-with-toc
24757 (progn
24758 (push (concat (nth 3 lang-words) "\n") thetoc)
24759 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24760 (mapc '(lambda (line)
24761 (if (string-match org-todo-line-regexp
24762 line)
24763 ;; This is a headline
24764 (progn
24765 (setq have-headings t)
24766 (setq level (- (match-end 1) (match-beginning 1))
24767 level (org-tr-level level)
24768 txt (match-string 3 line)
24769 todo
24770 (or (and org-export-mark-todo-in-toc
24771 (match-beginning 2)
24772 (not (member (match-string 2 line)
24773 org-done-keywords)))
24774 ; TODO, not DONE
24775 (and org-export-mark-todo-in-toc
24776 (= level umax-toc)
24777 (org-search-todo-below
24778 line lines level))))
24779 (setq txt (org-html-expand-for-ascii txt))
24781 (while (string-match org-bracket-link-regexp txt)
24782 (setq txt
24783 (replace-match
24784 (match-string (if (match-end 2) 3 1) txt)
24785 t t txt)))
24787 (if (and (memq org-export-with-tags '(not-in-toc nil))
24788 (string-match
24789 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24790 txt))
24791 (setq txt (replace-match "" t t txt)))
24792 (if (string-match quote-re0 txt)
24793 (setq txt (replace-match "" t t txt)))
24795 (if org-export-with-section-numbers
24796 (setq txt (concat (org-section-number level)
24797 " " txt)))
24798 (if (<= level umax-toc)
24799 (progn
24800 (push
24801 (concat
24802 (make-string
24803 (* (max 0 (- level org-min-level)) 4) ?\ )
24804 (format (if todo "%s (*)\n" "%s\n") txt))
24805 thetoc)
24806 (setq org-last-level level))
24807 ))))
24808 lines)
24809 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24811 (org-init-section-numbers)
24812 (while (setq line (pop lines))
24813 ;; Remove the quoted HTML tags.
24814 (setq line (org-html-expand-for-ascii line))
24815 ;; Remove targets
24816 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24817 (setq line (replace-match "" t t line)))
24818 ;; Replace internal links
24819 (while (string-match org-bracket-link-regexp line)
24820 (setq line (replace-match
24821 (if (match-end 3) "[\\3]" "[\\1]")
24822 t nil line)))
24823 (when custom-times
24824 (setq line (org-translate-time line)))
24825 (cond
24826 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24827 ;; a Headline
24828 (setq first-heading-pos (or first-heading-pos (point)))
24829 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24830 txt (match-string 2 line))
24831 (org-ascii-level-start level txt umax lines))
24833 ((and org-export-with-tables
24834 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24835 (if (not table-open)
24836 ;; New table starts
24837 (setq table-open t table-buffer nil))
24838 ;; Accumulate lines
24839 (setq table-buffer (cons line table-buffer))
24840 (when (or (not lines)
24841 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24842 (car lines))))
24843 (setq table-open nil
24844 table-buffer (nreverse table-buffer))
24845 (insert (mapconcat
24846 (lambda (x)
24847 (org-fix-indentation x org-ascii-current-indentation))
24848 (org-format-table-ascii table-buffer)
24849 "\n") "\n")))
24851 (setq line (org-fix-indentation line org-ascii-current-indentation))
24852 (if (and org-export-with-fixed-width
24853 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24854 (setq line (replace-match "\\1" nil nil line)))
24855 (insert line "\n"))))
24857 (normal-mode)
24859 ;; insert the table of contents
24860 (when thetoc
24861 (goto-char (point-min))
24862 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24863 (progn
24864 (goto-char (match-beginning 0))
24865 (replace-match ""))
24866 (goto-char first-heading-pos))
24867 (mapc 'insert thetoc)
24868 (or (looking-at "[ \t]*\n[ \t]*\n")
24869 (insert "\n\n")))
24871 ;; Convert whitespace place holders
24872 (goto-char (point-min))
24873 (let (beg end)
24874 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24875 (setq end (next-single-property-change beg 'org-whitespace))
24876 (goto-char beg)
24877 (delete-region beg end)
24878 (insert (make-string (- end beg) ?\ ))))
24880 (save-buffer)
24881 ;; remove display and invisible chars
24882 (let (beg end)
24883 (goto-char (point-min))
24884 (while (setq beg (next-single-property-change (point) 'display))
24885 (setq end (next-single-property-change beg 'display))
24886 (delete-region beg end)
24887 (goto-char beg)
24888 (insert "=>"))
24889 (goto-char (point-min))
24890 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24891 (setq end (next-single-property-change beg 'org-cwidth))
24892 (delete-region beg end)
24893 (goto-char beg)))
24894 (goto-char (point-min))))
24896 (defun org-export-ascii-clean-string ()
24897 "Do extra work for ASCII export"
24898 (goto-char (point-min))
24899 (while (re-search-forward org-verbatim-re nil t)
24900 (goto-char (match-end 2))
24901 (backward-delete-char 1) (insert "'")
24902 (goto-char (match-beginning 2))
24903 (delete-char 1) (insert "`")
24904 (goto-char (match-end 2))))
24906 (defun org-search-todo-below (line lines level)
24907 "Search the subtree below LINE for any TODO entries."
24908 (let ((rest (cdr (memq line lines)))
24909 (re org-todo-line-regexp)
24910 line lv todo)
24911 (catch 'exit
24912 (while (setq line (pop rest))
24913 (if (string-match re line)
24914 (progn
24915 (setq lv (- (match-end 1) (match-beginning 1))
24916 todo (and (match-beginning 2)
24917 (not (member (match-string 2 line)
24918 org-done-keywords))))
24919 ; TODO, not DONE
24920 (if (<= lv level) (throw 'exit nil))
24921 (if todo (throw 'exit t))))))))
24923 (defun org-html-expand-for-ascii (line)
24924 "Handle quoted HTML for ASCII export."
24925 (if org-export-html-expand
24926 (while (string-match "@<[^<>\n]*>" line)
24927 ;; We just remove the tags for now.
24928 (setq line (replace-match "" nil nil line))))
24929 line)
24931 (defun org-insert-centered (s &optional underline)
24932 "Insert the string S centered and underline it with character UNDERLINE."
24933 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24934 (insert (make-string ind ?\ ) s "\n")
24935 (if underline
24936 (insert (make-string ind ?\ )
24937 (make-string (string-width s) underline)
24938 "\n"))))
24940 (defun org-ascii-level-start (level title umax &optional lines)
24941 "Insert a new level in ASCII export."
24942 (let (char (n (- level umax 1)) (ind 0))
24943 (if (> level umax)
24944 (progn
24945 (insert (make-string (* 2 n) ?\ )
24946 (char-to-string (nth (% n (length org-export-ascii-bullets))
24947 org-export-ascii-bullets))
24948 " " title "\n")
24949 ;; find the indentation of the next non-empty line
24950 (catch 'stop
24951 (while lines
24952 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24953 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24954 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24955 (pop lines)))
24956 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24957 (if (or (not (equal (char-before) ?\n))
24958 (not (equal (char-before (1- (point))) ?\n)))
24959 (insert "\n"))
24960 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24961 (unless org-export-with-tags
24962 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24963 (setq title (replace-match "" t t title))))
24964 (if org-export-with-section-numbers
24965 (setq title (concat (org-section-number level) " " title)))
24966 (insert title "\n" (make-string (string-width title) char) "\n")
24967 (setq org-ascii-current-indentation '(0 . 0)))))
24969 (defun org-export-visible (type arg)
24970 "Create a copy of the visible part of the current buffer, and export it.
24971 The copy is created in a temporary buffer and removed after use.
24972 TYPE is the final key (as a string) that also select the export command in
24973 the `C-c C-e' export dispatcher.
24974 As a special case, if the you type SPC at the prompt, the temporary
24975 org-mode file will not be removed but presented to you so that you can
24976 continue to use it. The prefix arg ARG is passed through to the exporting
24977 command."
24978 (interactive
24979 (list (progn
24980 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24981 (read-char-exclusive))
24982 current-prefix-arg))
24983 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24984 (error "Invalid export key"))
24985 (let* ((binding (cdr (assoc type
24986 '((?a . org-export-as-ascii)
24987 (?\C-a . org-export-as-ascii)
24988 (?b . org-export-as-html-and-open)
24989 (?\C-b . org-export-as-html-and-open)
24990 (?h . org-export-as-html)
24991 (?H . org-export-as-html-to-buffer)
24992 (?R . org-export-region-as-html)
24993 (?x . org-export-as-xoxo)))))
24994 (keepp (equal type ?\ ))
24995 (file buffer-file-name)
24996 (buffer (get-buffer-create "*Org Export Visible*"))
24997 s e)
24998 ;; Need to hack the drawers here.
24999 (save-excursion
25000 (goto-char (point-min))
25001 (while (re-search-forward org-drawer-regexp nil t)
25002 (goto-char (match-beginning 1))
25003 (or (org-invisible-p) (org-flag-drawer nil))))
25004 (with-current-buffer buffer (erase-buffer))
25005 (save-excursion
25006 (setq s (goto-char (point-min)))
25007 (while (not (= (point) (point-max)))
25008 (goto-char (org-find-invisible))
25009 (append-to-buffer buffer s (point))
25010 (setq s (goto-char (org-find-visible))))
25011 (org-cycle-hide-drawers 'all)
25012 (goto-char (point-min))
25013 (unless keepp
25014 ;; Copy all comment lines to the end, to make sure #+ settings are
25015 ;; still available for the second export step. Kind of a hack, but
25016 ;; does do the trick.
25017 (if (looking-at "#[^\r\n]*")
25018 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25019 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25020 (append-to-buffer buffer (1+ (match-beginning 0))
25021 (min (point-max) (1+ (match-end 0))))))
25022 (set-buffer buffer)
25023 (let ((buffer-file-name file)
25024 (org-inhibit-startup t))
25025 (org-mode)
25026 (show-all)
25027 (unless keepp (funcall binding arg))))
25028 (if (not keepp)
25029 (kill-buffer buffer)
25030 (switch-to-buffer-other-window buffer)
25031 (goto-char (point-min)))))
25033 (defun org-find-visible ()
25034 (let ((s (point)))
25035 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25036 (get-char-property s 'invisible)))
25038 (defun org-find-invisible ()
25039 (let ((s (point)))
25040 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25041 (not (get-char-property s 'invisible))))
25044 ;;; HTML export
25046 (defun org-get-current-options ()
25047 "Return a string with current options as keyword options.
25048 Does include HTML export options as well as TODO and CATEGORY stuff."
25049 (format
25050 "#+TITLE: %s
25051 #+AUTHOR: %s
25052 #+EMAIL: %s
25053 #+LANGUAGE: %s
25054 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25055 #+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
25056 #+CATEGORY: %s
25057 #+SEQ_TODO: %s
25058 #+TYP_TODO: %s
25059 #+PRIORITIES: %c %c %c
25060 #+DRAWERS: %s
25061 #+STARTUP: %s %s %s %s %s
25062 #+TAGS: %s
25063 #+ARCHIVE: %s
25064 #+LINK: %s
25066 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25067 org-export-headline-levels
25068 org-export-with-section-numbers
25069 org-export-with-toc
25070 org-export-preserve-breaks
25071 org-export-html-expand
25072 org-export-with-fixed-width
25073 org-export-with-tables
25074 org-export-with-sub-superscripts
25075 org-export-with-special-strings
25076 org-export-with-footnotes
25077 org-export-with-emphasize
25078 org-export-with-TeX-macros
25079 org-export-with-LaTeX-fragments
25080 org-export-skip-text-before-1st-heading
25081 org-export-with-drawers
25082 org-export-with-tags
25083 (file-name-nondirectory buffer-file-name)
25084 "TODO FEEDBACK VERIFY DONE"
25085 "Me Jason Marie DONE"
25086 org-highest-priority org-lowest-priority org-default-priority
25087 (mapconcat 'identity org-drawers " ")
25088 (cdr (assoc org-startup-folded
25089 '((nil . "showall") (t . "overview") (content . "content"))))
25090 (if org-odd-levels-only "odd" "oddeven")
25091 (if org-hide-leading-stars "hidestars" "showstars")
25092 (if org-startup-align-all-tables "align" "noalign")
25093 (cond ((eq org-log-done t) "logdone")
25094 ((equal org-log-done 'note) "lognotedone")
25095 ((not org-log-done) "nologdone"))
25096 (or (mapconcat (lambda (x)
25097 (cond
25098 ((equal '(:startgroup) x) "{")
25099 ((equal '(:endgroup) x) "}")
25100 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25101 (t (car x))))
25102 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25103 org-archive-location
25104 "org file:~/org/%s.org"
25107 (defun org-insert-export-options-template ()
25108 "Insert into the buffer a template with information for exporting."
25109 (interactive)
25110 (if (not (bolp)) (newline))
25111 (let ((s (org-get-current-options)))
25112 (and (string-match "#\\+CATEGORY" s)
25113 (setq s (substring s 0 (match-beginning 0))))
25114 (insert s)))
25116 (defun org-toggle-fixed-width-section (arg)
25117 "Toggle the fixed-width export.
25118 If there is no active region, the QUOTE keyword at the current headline is
25119 inserted or removed. When present, it causes the text between this headline
25120 and the next to be exported as fixed-width text, and unmodified.
25121 If there is an active region, this command adds or removes a colon as the
25122 first character of this line. If the first character of a line is a colon,
25123 this line is also exported in fixed-width font."
25124 (interactive "P")
25125 (let* ((cc 0)
25126 (regionp (org-region-active-p))
25127 (beg (if regionp (region-beginning) (point)))
25128 (end (if regionp (region-end)))
25129 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25130 (case-fold-search nil)
25131 (re "[ \t]*\\(:\\)")
25132 off)
25133 (if regionp
25134 (save-excursion
25135 (goto-char beg)
25136 (setq cc (current-column))
25137 (beginning-of-line 1)
25138 (setq off (looking-at re))
25139 (while (> nlines 0)
25140 (setq nlines (1- nlines))
25141 (beginning-of-line 1)
25142 (cond
25143 (arg
25144 (move-to-column cc t)
25145 (insert ":\n")
25146 (forward-line -1))
25147 ((and off (looking-at re))
25148 (replace-match "" t t nil 1))
25149 ((not off) (move-to-column cc t) (insert ":")))
25150 (forward-line 1)))
25151 (save-excursion
25152 (org-back-to-heading)
25153 (if (looking-at (concat outline-regexp
25154 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25155 (replace-match "" t t nil 1)
25156 (if (looking-at outline-regexp)
25157 (progn
25158 (goto-char (match-end 0))
25159 (insert org-quote-string " "))))))))
25161 (defun org-export-as-html-and-open (arg)
25162 "Export the outline as HTML and immediately open it with a browser.
25163 If there is an active region, export only the region.
25164 The prefix ARG specifies how many levels of the outline should become
25165 headlines. The default is 3. Lower levels will become bulleted lists."
25166 (interactive "P")
25167 (org-export-as-html arg 'hidden)
25168 (org-open-file buffer-file-name))
25170 (defun org-export-as-html-batch ()
25171 "Call `org-export-as-html', may be used in batch processing as
25172 emacs --batch
25173 --load=$HOME/lib/emacs/org.el
25174 --eval \"(setq org-export-headline-levels 2)\"
25175 --visit=MyFile --funcall org-export-as-html-batch"
25176 (org-export-as-html org-export-headline-levels 'hidden))
25178 (defun org-export-as-html-to-buffer (arg)
25179 "Call `org-exort-as-html` with output to a temporary buffer.
25180 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25181 (interactive "P")
25182 (org-export-as-html arg nil nil "*Org HTML Export*")
25183 (switch-to-buffer-other-window "*Org HTML Export*"))
25185 (defun org-replace-region-by-html (beg end)
25186 "Assume the current region has org-mode syntax, and convert it to HTML.
25187 This can be used in any buffer. For example, you could write an
25188 itemized list in org-mode syntax in an HTML buffer and then use this
25189 command to convert it."
25190 (interactive "r")
25191 (let (reg html buf pop-up-frames)
25192 (save-window-excursion
25193 (if (org-mode-p)
25194 (setq html (org-export-region-as-html
25195 beg end t 'string))
25196 (setq reg (buffer-substring beg end)
25197 buf (get-buffer-create "*Org tmp*"))
25198 (with-current-buffer buf
25199 (erase-buffer)
25200 (insert reg)
25201 (org-mode)
25202 (setq html (org-export-region-as-html
25203 (point-min) (point-max) t 'string)))
25204 (kill-buffer buf)))
25205 (delete-region beg end)
25206 (insert html)))
25208 (defun org-export-region-as-html (beg end &optional body-only buffer)
25209 "Convert region from BEG to END in org-mode buffer to HTML.
25210 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25211 contents, and only produce the region of converted text, useful for
25212 cut-and-paste operations.
25213 If BUFFER is a buffer or a string, use/create that buffer as a target
25214 of the converted HTML. If BUFFER is the symbol `string', return the
25215 produced HTML as a string and leave not buffer behind. For example,
25216 a Lisp program could call this function in the following way:
25218 (setq html (org-export-region-as-html beg end t 'string))
25220 When called interactively, the output buffer is selected, and shown
25221 in a window. A non-interactive call will only retunr the buffer."
25222 (interactive "r\nP")
25223 (when (interactive-p)
25224 (setq buffer "*Org HTML Export*"))
25225 (let ((transient-mark-mode t) (zmacs-regions t)
25226 rtn)
25227 (goto-char end)
25228 (set-mark (point)) ;; to activate the region
25229 (goto-char beg)
25230 (setq rtn (org-export-as-html
25231 nil nil nil
25232 buffer body-only))
25233 (if (fboundp 'deactivate-mark) (deactivate-mark))
25234 (if (and (interactive-p) (bufferp rtn))
25235 (switch-to-buffer-other-window rtn)
25236 rtn)))
25238 (defvar html-table-tag nil) ; dynamically scoped into this.
25239 (defun org-export-as-html (arg &optional hidden ext-plist
25240 to-buffer body-only)
25241 "Export the outline as a pretty HTML file.
25242 If there is an active region, export only the region. The prefix
25243 ARG specifies how many levels of the outline should become
25244 headlines. The default is 3. Lower levels will become bulleted
25245 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25246 EXT-PLIST is a property list with external parameters overriding
25247 org-mode's default settings, but still inferior to file-local
25248 settings. When TO-BUFFER is non-nil, create a buffer with that
25249 name and export to that buffer. If TO-BUFFER is the symbol `string',
25250 don't leave any buffer behind but just return the resulting HTML as
25251 a string. When BODY-ONLY is set, don't produce the file header and footer,
25252 simply return the content of <body>...</body>, without even
25253 the body tags themselves."
25254 (interactive "P")
25256 ;; Make sure we have a file name when we need it.
25257 (when (and (not (or to-buffer body-only))
25258 (not buffer-file-name))
25259 (if (buffer-base-buffer)
25260 (org-set-local 'buffer-file-name
25261 (with-current-buffer (buffer-base-buffer)
25262 buffer-file-name))
25263 (error "Need a file name to be able to export.")))
25265 (message "Exporting...")
25266 (setq-default org-todo-line-regexp org-todo-line-regexp)
25267 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25268 (setq-default org-done-keywords org-done-keywords)
25269 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25270 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25271 ext-plist
25272 (org-infile-export-plist)))
25274 (style (plist-get opt-plist :style))
25275 (html-extension (plist-get opt-plist :html-extension))
25276 (link-validate (plist-get opt-plist :link-validation-function))
25277 valid thetoc have-headings first-heading-pos
25278 (odd org-odd-levels-only)
25279 (region-p (org-region-active-p))
25280 (subtree-p
25281 (when region-p
25282 (save-excursion
25283 (goto-char (region-beginning))
25284 (and (org-at-heading-p)
25285 (>= (org-end-of-subtree t t) (region-end))))))
25286 ;; The following two are dynamically scoped into other
25287 ;; routines below.
25288 (org-current-export-dir (org-export-directory :html opt-plist))
25289 (org-current-export-file buffer-file-name)
25290 (level 0) (line "") (origline "") txt todo
25291 (umax nil)
25292 (umax-toc nil)
25293 (filename (if to-buffer nil
25294 (expand-file-name
25295 (concat
25296 (file-name-sans-extension
25297 (or (and subtree-p
25298 (org-entry-get (region-beginning)
25299 "EXPORT_FILE_NAME" t))
25300 (file-name-nondirectory buffer-file-name)))
25301 "." html-extension)
25302 (file-name-as-directory
25303 (org-export-directory :html opt-plist)))))
25304 (current-dir (if buffer-file-name
25305 (file-name-directory buffer-file-name)
25306 default-directory))
25307 (buffer (if to-buffer
25308 (cond
25309 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25310 (t (get-buffer-create to-buffer)))
25311 (find-file-noselect filename)))
25312 (org-levels-open (make-vector org-level-max nil))
25313 (date (plist-get opt-plist :date))
25314 (author (plist-get opt-plist :author))
25315 (title (or (and subtree-p (org-export-get-title-from-subtree))
25316 (plist-get opt-plist :title)
25317 (and (not
25318 (plist-get opt-plist :skip-before-1st-heading))
25319 (org-export-grab-title-from-buffer))
25320 (and buffer-file-name
25321 (file-name-sans-extension
25322 (file-name-nondirectory buffer-file-name)))
25323 "UNTITLED"))
25324 (html-table-tag (plist-get opt-plist :html-table-tag))
25325 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25326 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25327 (inquote nil)
25328 (infixed nil)
25329 (in-local-list nil)
25330 (local-list-num nil)
25331 (local-list-indent nil)
25332 (llt org-plain-list-ordered-item-terminator)
25333 (email (plist-get opt-plist :email))
25334 (language (plist-get opt-plist :language))
25335 (lang-words nil)
25336 (target-alist nil) tg
25337 (head-count 0) cnt
25338 (start 0)
25339 (coding-system (and (boundp 'buffer-file-coding-system)
25340 buffer-file-coding-system))
25341 (coding-system-for-write (or org-export-html-coding-system
25342 coding-system))
25343 (save-buffer-coding-system (or org-export-html-coding-system
25344 coding-system))
25345 (charset (and coding-system-for-write
25346 (fboundp 'coding-system-get)
25347 (coding-system-get coding-system-for-write
25348 'mime-charset)))
25349 (region
25350 (buffer-substring
25351 (if region-p (region-beginning) (point-min))
25352 (if region-p (region-end) (point-max))))
25353 (lines
25354 (org-split-string
25355 (org-cleaned-string-for-export
25356 region
25357 :emph-multiline t
25358 :for-html t
25359 :skip-before-1st-heading
25360 (plist-get opt-plist :skip-before-1st-heading)
25361 :drawers (plist-get opt-plist :drawers)
25362 :archived-trees
25363 (plist-get opt-plist :archived-trees)
25364 :add-text
25365 (plist-get opt-plist :text)
25366 :LaTeX-fragments
25367 (plist-get opt-plist :LaTeX-fragments))
25368 "[\r\n]"))
25369 table-open type
25370 table-buffer table-orig-buffer
25371 ind start-is-num starter didclose
25372 rpl path desc descp desc1 desc2 link
25375 (let ((inhibit-read-only t))
25376 (org-unmodified
25377 (remove-text-properties (point-min) (point-max)
25378 '(:org-license-to-kill t))))
25380 (message "Exporting...")
25382 (setq org-min-level (org-get-min-level lines))
25383 (setq org-last-level org-min-level)
25384 (org-init-section-numbers)
25386 (cond
25387 ((and date (string-match "%" date))
25388 (setq date (format-time-string date (current-time))))
25389 (date)
25390 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25392 ;; Get the language-dependent settings
25393 (setq lang-words (or (assoc language org-export-language-setup)
25394 (assoc "en" org-export-language-setup)))
25396 ;; Switch to the output buffer
25397 (set-buffer buffer)
25398 (let ((inhibit-read-only t)) (erase-buffer))
25399 (fundamental-mode)
25401 (and (fboundp 'set-buffer-file-coding-system)
25402 (set-buffer-file-coding-system coding-system-for-write))
25404 (let ((case-fold-search nil)
25405 (org-odd-levels-only odd))
25406 ;; create local variables for all options, to make sure all called
25407 ;; functions get the correct information
25408 (mapc (lambda (x)
25409 (set (make-local-variable (cdr x))
25410 (plist-get opt-plist (car x))))
25411 org-export-plist-vars)
25412 (setq umax (if arg (prefix-numeric-value arg)
25413 org-export-headline-levels))
25414 (setq umax-toc (if (integerp org-export-with-toc)
25415 (min org-export-with-toc umax)
25416 umax))
25417 (unless body-only
25418 ;; File header
25419 (insert (format
25420 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25421 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25422 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25423 lang=\"%s\" xml:lang=\"%s\">
25424 <head>
25425 <title>%s</title>
25426 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25427 <meta name=\"generator\" content=\"Org-mode\"/>
25428 <meta name=\"generated\" content=\"%s\"/>
25429 <meta name=\"author\" content=\"%s\"/>
25431 </head><body>
25433 language language (org-html-expand title)
25434 (or charset "iso-8859-1") date author style))
25436 (insert (or (plist-get opt-plist :preamble) ""))
25438 (when (plist-get opt-plist :auto-preamble)
25439 (if title (insert (format org-export-html-title-format
25440 (org-html-expand title))))))
25442 (if (and org-export-with-toc (not body-only))
25443 (progn
25444 (push (format "<h%d>%s</h%d>\n"
25445 org-export-html-toplevel-hlevel
25446 (nth 3 lang-words)
25447 org-export-html-toplevel-hlevel)
25448 thetoc)
25449 (push "<ul>\n<li>" thetoc)
25450 (setq lines
25451 (mapcar '(lambda (line)
25452 (if (string-match org-todo-line-regexp line)
25453 ;; This is a headline
25454 (progn
25455 (setq have-headings t)
25456 (setq level (- (match-end 1) (match-beginning 1))
25457 level (org-tr-level level)
25458 txt (save-match-data
25459 (org-html-expand
25460 (org-export-cleanup-toc-line
25461 (match-string 3 line))))
25462 todo
25463 (or (and org-export-mark-todo-in-toc
25464 (match-beginning 2)
25465 (not (member (match-string 2 line)
25466 org-done-keywords)))
25467 ; TODO, not DONE
25468 (and org-export-mark-todo-in-toc
25469 (= level umax-toc)
25470 (org-search-todo-below
25471 line lines level))))
25472 (if (string-match
25473 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25474 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25475 (if (string-match quote-re0 txt)
25476 (setq txt (replace-match "" t t txt)))
25477 (if org-export-with-section-numbers
25478 (setq txt (concat (org-section-number level)
25479 " " txt)))
25480 (if (<= level (max umax umax-toc))
25481 (setq head-count (+ head-count 1)))
25482 (if (<= level umax-toc)
25483 (progn
25484 (if (> level org-last-level)
25485 (progn
25486 (setq cnt (- level org-last-level))
25487 (while (>= (setq cnt (1- cnt)) 0)
25488 (push "\n<ul>\n<li>" thetoc))
25489 (push "\n" thetoc)))
25490 (if (< level org-last-level)
25491 (progn
25492 (setq cnt (- org-last-level level))
25493 (while (>= (setq cnt (1- cnt)) 0)
25494 (push "</li>\n</ul>" thetoc))
25495 (push "\n" thetoc)))
25496 ;; Check for targets
25497 (while (string-match org-target-regexp line)
25498 (setq tg (match-string 1 line)
25499 line (replace-match
25500 (concat "@<span class=\"target\">" tg "@</span> ")
25501 t t line))
25502 (push (cons (org-solidify-link-text tg)
25503 (format "sec-%d" head-count))
25504 target-alist))
25505 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25506 (setq txt (replace-match "" t t txt)))
25507 (push
25508 (format
25509 (if todo
25510 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25511 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25512 head-count txt) thetoc)
25514 (setq org-last-level level))
25516 line)
25517 lines))
25518 (while (> org-last-level (1- org-min-level))
25519 (setq org-last-level (1- org-last-level))
25520 (push "</li>\n</ul>\n" thetoc))
25521 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25523 (setq head-count 0)
25524 (org-init-section-numbers)
25526 (while (setq line (pop lines) origline line)
25527 (catch 'nextline
25529 ;; end of quote section?
25530 (when (and inquote (string-match "^\\*+ " line))
25531 (insert "</pre>\n")
25532 (setq inquote nil))
25533 ;; inside a quote section?
25534 (when inquote
25535 (insert (org-html-protect line) "\n")
25536 (throw 'nextline nil))
25538 ;; verbatim lines
25539 (when (and org-export-with-fixed-width
25540 (string-match "^[ \t]*:\\(.*\\)" line))
25541 (when (not infixed)
25542 (setq infixed t)
25543 (insert "<pre>\n"))
25544 (insert (org-html-protect (match-string 1 line)) "\n")
25545 (when (and lines
25546 (not (string-match "^[ \t]*\\(:.*\\)"
25547 (car lines))))
25548 (setq infixed nil)
25549 (insert "</pre>\n"))
25550 (throw 'nextline nil))
25552 ;; Protected HTML
25553 (when (get-text-property 0 'org-protected line)
25554 (let (par)
25555 (when (re-search-backward
25556 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25557 (setq par (match-string 1))
25558 (replace-match "\\2\n"))
25559 (insert line "\n")
25560 (while (and lines
25561 (or (= (length (car lines)) 0)
25562 (get-text-property 0 'org-protected (car lines))))
25563 (insert (pop lines) "\n"))
25564 (and par (insert "<p>\n")))
25565 (throw 'nextline nil))
25567 ;; Horizontal line
25568 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25569 (insert "\n<hr/>\n")
25570 (throw 'nextline nil))
25572 ;; make targets to anchors
25573 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25574 (cond
25575 ((match-end 2)
25576 (setq line (replace-match
25577 (concat "@<a name=\""
25578 (org-solidify-link-text (match-string 1 line))
25579 "\">\\nbsp@</a>")
25580 t t line)))
25581 ((and org-export-with-toc (equal (string-to-char line) ?*))
25582 (setq line (replace-match
25583 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25584 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25585 t t line)))
25587 (setq line (replace-match
25588 (concat "@<a name=\""
25589 (org-solidify-link-text (match-string 1 line))
25590 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25591 t t line)))))
25593 (setq line (org-html-handle-time-stamps line))
25595 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25596 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25597 ;; Also handle sub_superscripts and checkboxes
25598 (or (string-match org-table-hline-regexp line)
25599 (setq line (org-html-expand line)))
25601 ;; Format the links
25602 (setq start 0)
25603 (while (string-match org-bracket-link-analytic-regexp line start)
25604 (setq start (match-beginning 0))
25605 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25606 (setq path (match-string 3 line))
25607 (setq desc1 (if (match-end 5) (match-string 5 line))
25608 desc2 (if (match-end 2) (concat type ":" path) path)
25609 descp (and desc1 (not (equal desc1 desc2)))
25610 desc (or desc1 desc2))
25611 ;; Make an image out of the description if that is so wanted
25612 (when (and descp (org-file-image-p desc))
25613 (save-match-data
25614 (if (string-match "^file:" desc)
25615 (setq desc (substring desc (match-end 0)))))
25616 (setq desc (concat "<img src=\"" desc "\"/>")))
25617 ;; FIXME: do we need to unescape here somewhere?
25618 (cond
25619 ((equal type "internal")
25620 (setq rpl
25621 (concat
25622 "<a href=\"#"
25623 (org-solidify-link-text
25624 (save-match-data (org-link-unescape path)) target-alist)
25625 "\">" desc "</a>")))
25626 ((member type '("http" "https"))
25627 ;; standard URL, just check if we need to inline an image
25628 (if (and (or (eq t org-export-html-inline-images)
25629 (and org-export-html-inline-images (not descp)))
25630 (org-file-image-p path))
25631 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25632 (setq link (concat type ":" path))
25633 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25634 ((member type '("ftp" "mailto" "news"))
25635 ;; standard URL
25636 (setq link (concat type ":" path))
25637 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25638 ((string= type "file")
25639 ;; FILE link
25640 (let* ((filename path)
25641 (abs-p (file-name-absolute-p filename))
25642 thefile file-is-image-p search)
25643 (save-match-data
25644 (if (string-match "::\\(.*\\)" filename)
25645 (setq search (match-string 1 filename)
25646 filename (replace-match "" t nil filename)))
25647 (setq valid
25648 (if (functionp link-validate)
25649 (funcall link-validate filename current-dir)
25651 (setq file-is-image-p (org-file-image-p filename))
25652 (setq thefile (if abs-p (expand-file-name filename) filename))
25653 (when (and org-export-html-link-org-files-as-html
25654 (string-match "\\.org$" thefile))
25655 (setq thefile (concat (substring thefile 0
25656 (match-beginning 0))
25657 "." html-extension))
25658 (if (and search
25659 ;; make sure this is can be used as target search
25660 (not (string-match "^[0-9]*$" search))
25661 (not (string-match "^\\*" search))
25662 (not (string-match "^/.*/$" search)))
25663 (setq thefile (concat thefile "#"
25664 (org-solidify-link-text
25665 (org-link-unescape search)))))
25666 (when (string-match "^file:" desc)
25667 (setq desc (replace-match "" t t desc))
25668 (if (string-match "\\.org$" desc)
25669 (setq desc (replace-match "" t t desc))))))
25670 (setq rpl (if (and file-is-image-p
25671 (or (eq t org-export-html-inline-images)
25672 (and org-export-html-inline-images
25673 (not descp))))
25674 (concat "<img src=\"" thefile "\"/>")
25675 (concat "<a href=\"" thefile "\">" desc "</a>")))
25676 (if (not valid) (setq rpl desc))))
25677 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25678 (setq rpl (concat "<i>&lt;" type ":"
25679 (save-match-data (org-link-unescape path))
25680 "&gt;</i>"))))
25681 (setq line (replace-match rpl t t line)
25682 start (+ start (length rpl))))
25684 ;; TODO items
25685 (if (and (string-match org-todo-line-regexp line)
25686 (match-beginning 2))
25688 (setq line
25689 (concat (substring line 0 (match-beginning 2))
25690 "<span class=\""
25691 (if (member (match-string 2 line)
25692 org-done-keywords)
25693 "done" "todo")
25694 "\">" (match-string 2 line)
25695 "</span>" (substring line (match-end 2)))))
25697 ;; Does this contain a reference to a footnote?
25698 (when org-export-with-footnotes
25699 (setq start 0)
25700 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25701 (if (get-text-property (match-beginning 2) 'org-protected line)
25702 (setq start (match-end 2))
25703 (let ((n (match-string 2 line)))
25704 (setq line
25705 (replace-match
25706 (format
25707 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25708 (match-string 1 line) n n n)
25709 t t line))))))
25711 (cond
25712 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25713 ;; This is a headline
25714 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25715 txt (match-string 2 line))
25716 (if (string-match quote-re0 txt)
25717 (setq txt (replace-match "" t t txt)))
25718 (if (<= level (max umax umax-toc))
25719 (setq head-count (+ head-count 1)))
25720 (when in-local-list
25721 ;; Close any local lists before inserting a new header line
25722 (while local-list-num
25723 (org-close-li)
25724 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25725 (pop local-list-num))
25726 (setq local-list-indent nil
25727 in-local-list nil))
25728 (setq first-heading-pos (or first-heading-pos (point)))
25729 (org-html-level-start level txt umax
25730 (and org-export-with-toc (<= level umax))
25731 head-count)
25732 ;; QUOTES
25733 (when (string-match quote-re line)
25734 (insert "<pre>")
25735 (setq inquote t)))
25737 ((and org-export-with-tables
25738 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25739 (if (not table-open)
25740 ;; New table starts
25741 (setq table-open t table-buffer nil table-orig-buffer nil))
25742 ;; Accumulate lines
25743 (setq table-buffer (cons line table-buffer)
25744 table-orig-buffer (cons origline table-orig-buffer))
25745 (when (or (not lines)
25746 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25747 (car lines))))
25748 (setq table-open nil
25749 table-buffer (nreverse table-buffer)
25750 table-orig-buffer (nreverse table-orig-buffer))
25751 (org-close-par-maybe)
25752 (insert (org-format-table-html table-buffer table-orig-buffer))))
25754 ;; Normal lines
25755 (when (string-match
25756 (cond
25757 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25758 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25759 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25760 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25761 line)
25762 (setq ind (org-get-string-indentation line)
25763 start-is-num (match-beginning 4)
25764 starter (if (match-beginning 2)
25765 (substring (match-string 2 line) 0 -1))
25766 line (substring line (match-beginning 5)))
25767 (unless (string-match "[^ \t]" line)
25768 ;; empty line. Pretend indentation is large.
25769 (setq ind (if org-empty-line-terminates-plain-lists
25771 (1+ (or (car local-list-indent) 1)))))
25772 (setq didclose nil)
25773 (while (and in-local-list
25774 (or (and (= ind (car local-list-indent))
25775 (not starter))
25776 (< ind (car local-list-indent))))
25777 (setq didclose t)
25778 (org-close-li)
25779 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25780 (pop local-list-num) (pop local-list-indent)
25781 (setq in-local-list local-list-indent))
25782 (cond
25783 ((and starter
25784 (or (not in-local-list)
25785 (> ind (car local-list-indent))))
25786 ;; Start new (level of) list
25787 (org-close-par-maybe)
25788 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25789 (push start-is-num local-list-num)
25790 (push ind local-list-indent)
25791 (setq in-local-list t))
25792 (starter
25793 ;; continue current list
25794 (org-close-li)
25795 (insert "<li>\n"))
25796 (didclose
25797 ;; we did close a list, normal text follows: need <p>
25798 (org-open-par)))
25799 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25800 (setq line
25801 (replace-match
25802 (if (equal (match-string 1 line) "X")
25803 "<b>[X]</b>"
25804 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25805 t t line))))
25807 ;; Empty lines start a new paragraph. If hand-formatted lists
25808 ;; are not fully interpreted, lines starting with "-", "+", "*"
25809 ;; also start a new paragraph.
25810 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25812 ;; Is this the start of a footnote?
25813 (when org-export-with-footnotes
25814 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25815 (org-close-par-maybe)
25816 (let ((n (match-string 1 line)))
25817 (setq line (replace-match
25818 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25820 ;; Check if the line break needs to be conserved
25821 (cond
25822 ((string-match "\\\\\\\\[ \t]*$" line)
25823 (setq line (replace-match "<br/>" t t line)))
25824 (org-export-preserve-breaks
25825 (setq line (concat line "<br/>"))))
25827 (insert line "\n")))))
25829 ;; Properly close all local lists and other lists
25830 (when inquote (insert "</pre>\n"))
25831 (when in-local-list
25832 ;; Close any local lists before inserting a new header line
25833 (while local-list-num
25834 (org-close-li)
25835 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25836 (pop local-list-num))
25837 (setq local-list-indent nil
25838 in-local-list nil))
25839 (org-html-level-start 1 nil umax
25840 (and org-export-with-toc (<= level umax))
25841 head-count)
25843 (unless body-only
25844 (when (plist-get opt-plist :auto-postamble)
25845 (insert "<div id=\"postamble\">")
25846 (when (and org-export-author-info author)
25847 (insert "<p class=\"author\"> "
25848 (nth 1 lang-words) ": " author "\n")
25849 (when email
25850 (if (listp (split-string email ",+ *"))
25851 (mapc (lambda(e)
25852 (insert "<a href=\"mailto:" e "\">&lt;"
25853 e "&gt;</a>\n"))
25854 (split-string email ",+ *"))
25855 (insert "<a href=\"mailto:" email "\">&lt;"
25856 email "&gt;</a>\n")))
25857 (insert "</p>\n"))
25858 (when (and date org-export-time-stamp-file)
25859 (insert "<p class=\"date\"> "
25860 (nth 2 lang-words) ": "
25861 date "</p>\n"))
25862 (insert "</div>"))
25864 (if org-export-html-with-timestamp
25865 (insert org-export-html-html-helper-timestamp))
25866 (insert (or (plist-get opt-plist :postamble) ""))
25867 (insert "</body>\n</html>\n"))
25869 (normal-mode)
25870 (if (eq major-mode default-major-mode) (html-mode))
25872 ;; insert the table of contents
25873 (goto-char (point-min))
25874 (when thetoc
25875 (if (or (re-search-forward
25876 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25877 (re-search-forward
25878 "\\[TABLE-OF-CONTENTS\\]" nil t))
25879 (progn
25880 (goto-char (match-beginning 0))
25881 (replace-match ""))
25882 (goto-char first-heading-pos)
25883 (when (looking-at "\\s-*</p>")
25884 (goto-char (match-end 0))
25885 (insert "\n")))
25886 (insert "<div id=\"table-of-contents\">\n")
25887 (mapc 'insert thetoc)
25888 (insert "</div>\n"))
25889 ;; remove empty paragraphs and lists
25890 (goto-char (point-min))
25891 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25892 (replace-match ""))
25893 (goto-char (point-min))
25894 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25895 (replace-match ""))
25896 (goto-char (point-min))
25897 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25898 (replace-match ""))
25899 ;; Convert whitespace place holders
25900 (goto-char (point-min))
25901 (let (beg end n)
25902 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25903 (setq n (get-text-property beg 'org-whitespace)
25904 end (next-single-property-change beg 'org-whitespace))
25905 (goto-char beg)
25906 (delete-region beg end)
25907 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25908 (make-string n ?x)))))
25910 (or to-buffer (progn (save-buffer) (kill-buffer (current-buffer))))
25911 (goto-char (point-min))
25912 (message "Exporting... done")
25913 (if (eq to-buffer 'string)
25914 (prog1 (buffer-substring (point-min) (point-max))
25915 (kill-buffer (current-buffer)))
25916 (current-buffer)))))
25918 (defvar org-table-colgroup-info nil)
25919 (defun org-format-table-ascii (lines)
25920 "Format a table for ascii export."
25921 (if (stringp lines)
25922 (setq lines (org-split-string lines "\n")))
25923 (if (not (string-match "^[ \t]*|" (car lines)))
25924 ;; Table made by table.el - test for spanning
25925 lines
25927 ;; A normal org table
25928 ;; Get rid of hlines at beginning and end
25929 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25930 (setq lines (nreverse lines))
25931 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25932 (setq lines (nreverse lines))
25933 (when org-export-table-remove-special-lines
25934 ;; Check if the table has a marking column. If yes remove the
25935 ;; column and the special lines
25936 (setq lines (org-table-clean-before-export lines)))
25937 ;; Get rid of the vertical lines except for grouping
25938 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25939 rtn line vl1 start)
25940 (while (setq line (pop lines))
25941 (if (string-match org-table-hline-regexp line)
25942 (and (string-match "|\\(.*\\)|" line)
25943 (setq line (replace-match " \\1" t nil line)))
25944 (setq start 0 vl1 vl)
25945 (while (string-match "|" line start)
25946 (setq start (match-end 0))
25947 (or (pop vl1) (setq line (replace-match " " t t line)))))
25948 (push line rtn))
25949 (nreverse rtn))))
25951 (defun org-colgroup-info-to-vline-list (info)
25952 (let (vl new last)
25953 (while info
25954 (setq last new new (pop info))
25955 (if (or (memq last '(:end :startend))
25956 (memq new '(:start :startend)))
25957 (push t vl)
25958 (push nil vl)))
25959 (setq vl (nreverse vl))
25960 (and vl (setcar vl nil))
25961 vl))
25963 (defun org-format-table-html (lines olines)
25964 "Find out which HTML converter to use and return the HTML code."
25965 (if (stringp lines)
25966 (setq lines (org-split-string lines "\n")))
25967 (if (string-match "^[ \t]*|" (car lines))
25968 ;; A normal org table
25969 (org-format-org-table-html lines)
25970 ;; Table made by table.el - test for spanning
25971 (let* ((hlines (delq nil (mapcar
25972 (lambda (x)
25973 (if (string-match "^[ \t]*\\+-" x) x
25974 nil))
25975 lines)))
25976 (first (car hlines))
25977 (ll (and (string-match "\\S-+" first)
25978 (match-string 0 first)))
25979 (re (concat "^[ \t]*" (regexp-quote ll)))
25980 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25981 hlines))))
25982 (if (and (not spanning)
25983 (not org-export-prefer-native-exporter-for-tables))
25984 ;; We can use my own converter with HTML conversions
25985 (org-format-table-table-html lines)
25986 ;; Need to use the code generator in table.el, with the original text.
25987 (org-format-table-table-html-using-table-generate-source olines)))))
25989 (defun org-format-org-table-html (lines &optional splice)
25990 "Format a table into HTML."
25991 ;; Get rid of hlines at beginning and end
25992 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25993 (setq lines (nreverse lines))
25994 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25995 (setq lines (nreverse lines))
25996 (when org-export-table-remove-special-lines
25997 ;; Check if the table has a marking column. If yes remove the
25998 ;; column and the special lines
25999 (setq lines (org-table-clean-before-export lines)))
26001 (let ((head (and org-export-highlight-first-table-line
26002 (delq nil (mapcar
26003 (lambda (x) (string-match "^[ \t]*|-" x))
26004 (cdr lines)))))
26005 (nlines 0) fnum i
26006 tbopen line fields html gr colgropen)
26007 (if splice (setq head nil))
26008 (unless splice (push (if head "<thead>" "<tbody>") html))
26009 (setq tbopen t)
26010 (while (setq line (pop lines))
26011 (catch 'next-line
26012 (if (string-match "^[ \t]*|-" line)
26013 (progn
26014 (unless splice
26015 (push (if head "</thead>" "</tbody>") html)
26016 (if lines (push "<tbody>" html) (setq tbopen nil)))
26017 (setq head nil) ;; head ends here, first time around
26018 ;; ignore this line
26019 (throw 'next-line t)))
26020 ;; Break the line into fields
26021 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26022 (unless fnum (setq fnum (make-vector (length fields) 0)))
26023 (setq nlines (1+ nlines) i -1)
26024 (push (concat "<tr>"
26025 (mapconcat
26026 (lambda (x)
26027 (setq i (1+ i))
26028 (if (and (< i nlines)
26029 (string-match org-table-number-regexp x))
26030 (incf (aref fnum i)))
26031 (if head
26032 (concat (car org-export-table-header-tags) x
26033 (cdr org-export-table-header-tags))
26034 (concat (car org-export-table-data-tags) x
26035 (cdr org-export-table-data-tags))))
26036 fields "")
26037 "</tr>")
26038 html)))
26039 (unless splice (if tbopen (push "</tbody>" html)))
26040 (unless splice (push "</table>\n" html))
26041 (setq html (nreverse html))
26042 (unless splice
26043 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26044 (push (mapconcat
26045 (lambda (x)
26046 (setq gr (pop org-table-colgroup-info))
26047 (format "%s<col align=\"%s\"></col>%s"
26048 (if (memq gr '(:start :startend))
26049 (prog1
26050 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26051 (setq colgropen t))
26053 (if (> (/ (float x) nlines) org-table-number-fraction)
26054 "right" "left")
26055 (if (memq gr '(:end :startend))
26056 (progn (setq colgropen nil) "</colgroup>")
26057 "")))
26058 fnum "")
26059 html)
26060 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26061 (push html-table-tag html))
26062 (concat (mapconcat 'identity html "\n") "\n")))
26064 (defun org-table-clean-before-export (lines)
26065 "Check if the table has a marking column.
26066 If yes remove the column and the special lines."
26067 (setq org-table-colgroup-info nil)
26068 (if (memq nil
26069 (mapcar
26070 (lambda (x) (or (string-match "^[ \t]*|-" x)
26071 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26072 lines))
26073 (progn
26074 (setq org-table-clean-did-remove-column nil)
26075 (delq nil
26076 (mapcar
26077 (lambda (x)
26078 (cond
26079 ((string-match "^[ \t]*| */ *|" x)
26080 (setq org-table-colgroup-info
26081 (mapcar (lambda (x)
26082 (cond ((member x '("<" "&lt;")) :start)
26083 ((member x '(">" "&gt;")) :end)
26084 ((member x '("<>" "&lt;&gt;")) :startend)
26085 (t nil)))
26086 (org-split-string x "[ \t]*|[ \t]*")))
26087 nil)
26088 (t x)))
26089 lines)))
26090 (setq org-table-clean-did-remove-column t)
26091 (delq nil
26092 (mapcar
26093 (lambda (x)
26094 (cond
26095 ((string-match "^[ \t]*| */ *|" x)
26096 (setq org-table-colgroup-info
26097 (mapcar (lambda (x)
26098 (cond ((member x '("<" "&lt;")) :start)
26099 ((member x '(">" "&gt;")) :end)
26100 ((member x '("<>" "&lt;&gt;")) :startend)
26101 (t nil)))
26102 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26103 nil)
26104 ((string-match "^[ \t]*| *[!_^/] *|" x)
26105 nil) ; ignore this line
26106 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26107 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26108 ;; remove the first column
26109 (replace-match "\\1|" t nil x))))
26110 lines))))
26112 (defun org-format-table-table-html (lines)
26113 "Format a table generated by table.el into HTML.
26114 This conversion does *not* use `table-generate-source' from table.el.
26115 This has the advantage that Org-mode's HTML conversions can be used.
26116 But it has the disadvantage, that no cell- or row-spanning is allowed."
26117 (let (line field-buffer
26118 (head org-export-highlight-first-table-line)
26119 fields html empty)
26120 (setq html (concat html-table-tag "\n"))
26121 (while (setq line (pop lines))
26122 (setq empty "&nbsp;")
26123 (catch 'next-line
26124 (if (string-match "^[ \t]*\\+-" line)
26125 (progn
26126 (if field-buffer
26127 (progn
26128 (setq
26129 html
26130 (concat
26131 html
26132 "<tr>"
26133 (mapconcat
26134 (lambda (x)
26135 (if (equal x "") (setq x empty))
26136 (if head
26137 (concat (car org-export-table-header-tags) x
26138 (cdr org-export-table-header-tags))
26139 (concat (car org-export-table-data-tags) x
26140 (cdr org-export-table-data-tags))))
26141 field-buffer "\n")
26142 "</tr>\n"))
26143 (setq head nil)
26144 (setq field-buffer nil)))
26145 ;; Ignore this line
26146 (throw 'next-line t)))
26147 ;; Break the line into fields and store the fields
26148 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26149 (if field-buffer
26150 (setq field-buffer (mapcar
26151 (lambda (x)
26152 (concat x "<br/>" (pop fields)))
26153 field-buffer))
26154 (setq field-buffer fields))))
26155 (setq html (concat html "</table>\n"))
26156 html))
26158 (defun org-format-table-table-html-using-table-generate-source (lines)
26159 "Format a table into html, using `table-generate-source' from table.el.
26160 This has the advantage that cell- or row-spanning is allowed.
26161 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26162 (require 'table)
26163 (with-current-buffer (get-buffer-create " org-tmp1 ")
26164 (erase-buffer)
26165 (insert (mapconcat 'identity lines "\n"))
26166 (goto-char (point-min))
26167 (if (not (re-search-forward "|[^+]" nil t))
26168 (error "Error processing table"))
26169 (table-recognize-table)
26170 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26171 (table-generate-source 'html " org-tmp2 ")
26172 (set-buffer " org-tmp2 ")
26173 (buffer-substring (point-min) (point-max))))
26175 (defun org-html-handle-time-stamps (s)
26176 "Format time stamps in string S, or remove them."
26177 (catch 'exit
26178 (let (r b)
26179 (while (string-match org-maybe-keyword-time-regexp s)
26180 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26181 ;; never export CLOCK
26182 (throw 'exit ""))
26183 (or b (setq b (substring s 0 (match-beginning 0))))
26184 (if (not org-export-with-timestamps)
26185 (setq r (concat r (substring s 0 (match-beginning 0)))
26186 s (substring s (match-end 0)))
26187 (setq r (concat
26188 r (substring s 0 (match-beginning 0))
26189 (if (match-end 1)
26190 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26191 (match-string 1 s)))
26192 (format " @<span class=\"timestamp\">%s@</span>"
26193 (substring
26194 (org-translate-time (match-string 3 s)) 1 -1)))
26195 s (substring s (match-end 0)))))
26196 ;; Line break if line started and ended with time stamp stuff
26197 (if (not r)
26199 (setq r (concat r s))
26200 (unless (string-match "\\S-" (concat b s))
26201 (setq r (concat r "@<br/>")))
26202 r))))
26204 (defun org-html-protect (s)
26205 ;; convert & to &amp;, < to &lt; and > to &gt;
26206 (let ((start 0))
26207 (while (string-match "&" s start)
26208 (setq s (replace-match "&amp;" t t s)
26209 start (1+ (match-beginning 0))))
26210 (while (string-match "<" s)
26211 (setq s (replace-match "&lt;" t t s)))
26212 (while (string-match ">" s)
26213 (setq s (replace-match "&gt;" t t s))))
26216 (defun org-export-cleanup-toc-line (s)
26217 "Remove tags and time staps from lines going into the toc."
26218 (when (memq org-export-with-tags '(not-in-toc nil))
26219 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26220 (setq s (replace-match "" t t s))))
26221 (when org-export-remove-timestamps-from-toc
26222 (while (string-match org-maybe-keyword-time-regexp s)
26223 (setq s (replace-match "" t t s))))
26224 (while (string-match org-bracket-link-regexp s)
26225 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26226 t t s)))
26229 (defun org-html-expand (string)
26230 "Prepare STRING for HTML export. Applies all active conversions.
26231 If there are links in the string, don't modify these."
26232 (let* ((re (concat org-bracket-link-regexp "\\|"
26233 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26234 m s l res)
26235 (while (setq m (string-match re string))
26236 (setq s (substring string 0 m)
26237 l (match-string 0 string)
26238 string (substring string (match-end 0)))
26239 (push (org-html-do-expand s) res)
26240 (push l res))
26241 (push (org-html-do-expand string) res)
26242 (apply 'concat (nreverse res))))
26244 (defun org-html-do-expand (s)
26245 "Apply all active conversions to translate special ASCII to HTML."
26246 (setq s (org-html-protect s))
26247 (if org-export-html-expand
26248 (let ((start 0))
26249 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26250 (setq s (replace-match "<\\1>" t nil s)))))
26251 (if org-export-with-emphasize
26252 (setq s (org-export-html-convert-emphasize s)))
26253 (if org-export-with-special-strings
26254 (setq s (org-export-html-convert-special-strings s)))
26255 (if org-export-with-sub-superscripts
26256 (setq s (org-export-html-convert-sub-super s)))
26257 (if org-export-with-TeX-macros
26258 (let ((start 0) wd ass)
26259 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26260 (if (get-text-property (match-beginning 0) 'org-protected s)
26261 (setq start (match-end 0))
26262 (setq wd (match-string 1 s))
26263 (if (setq ass (assoc wd org-html-entities))
26264 (setq s (replace-match (or (cdr ass)
26265 (concat "&" (car ass) ";"))
26266 t t s))
26267 (setq start (+ start (length wd))))))))
26270 (defun org-create-multibrace-regexp (left right n)
26271 "Create a regular expression which will match a balanced sexp.
26272 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26273 as single character strings.
26274 The regexp returned will match the entire expression including the
26275 delimiters. It will also define a single group which contains the
26276 match except for the outermost delimiters. The maximum depth of
26277 stacked delimiters is N. Escaping delimiters is not possible."
26278 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26279 (or "\\|")
26280 (re nothing)
26281 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26282 (while (> n 1)
26283 (setq n (1- n)
26284 re (concat re or next)
26285 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26286 (concat left "\\(" re "\\)" right)))
26288 (defvar org-match-substring-regexp
26289 (concat
26290 "\\([^\\]\\)\\([_^]\\)\\("
26291 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26292 "\\|"
26293 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26294 "\\|"
26295 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26296 "The regular expression matching a sub- or superscript.")
26298 (defvar org-match-substring-with-braces-regexp
26299 (concat
26300 "\\([^\\]\\)\\([_^]\\)\\("
26301 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26302 "\\)")
26303 "The regular expression matching a sub- or superscript, forcing braces.")
26305 (defconst org-export-html-special-string-regexps
26306 '(("\\\\-" . "&shy;")
26307 ("---\\([^-]\\)" . "&mdash;\\1")
26308 ("--\\([^-]\\)" . "&ndash;\\1")
26309 ("\\.\\.\\." . "&hellip;"))
26310 "Regular expressions for special string conversion.")
26312 (defun org-export-html-convert-special-strings (string)
26313 "Convert special characters in STRING to HTML."
26314 (let ((all org-export-html-special-string-regexps)
26315 e a re rpl start)
26316 (while (setq a (pop all))
26317 (setq re (car a) rpl (cdr a) start 0)
26318 (while (string-match re string start)
26319 (if (get-text-property (match-beginning 0) 'org-protected string)
26320 (setq start (match-end 0))
26321 (setq string (replace-match rpl t nil string)))))
26322 string))
26324 (defun org-export-html-convert-sub-super (string)
26325 "Convert sub- and superscripts in STRING to HTML."
26326 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26327 (while (string-match org-match-substring-regexp string s)
26328 (cond
26329 ((and requireb (match-end 8)) (setq s (match-end 2)))
26330 ((get-text-property (match-beginning 2) 'org-protected string)
26331 (setq s (match-end 2)))
26333 (setq s (match-end 1)
26334 key (if (string= (match-string 2 string) "_") "sub" "sup")
26335 c (or (match-string 8 string)
26336 (match-string 6 string)
26337 (match-string 5 string))
26338 string (replace-match
26339 (concat (match-string 1 string)
26340 "<" key ">" c "</" key ">")
26341 t t string)))))
26342 (while (string-match "\\\\\\([_^]\\)" string)
26343 (setq string (replace-match (match-string 1 string) t t string)))
26344 string))
26346 (defun org-export-html-convert-emphasize (string)
26347 "Apply emphasis."
26348 (let ((s 0) rpl)
26349 (while (string-match org-emph-re string s)
26350 (if (not (equal
26351 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26352 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26353 (setq s (match-beginning 0)
26355 (concat
26356 (match-string 1 string)
26357 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26358 (match-string 4 string)
26359 (nth 3 (assoc (match-string 3 string)
26360 org-emphasis-alist))
26361 (match-string 5 string))
26362 string (replace-match rpl t t string)
26363 s (+ s (- (length rpl) 2)))
26364 (setq s (1+ s))))
26365 string))
26367 (defvar org-par-open nil)
26368 (defun org-open-par ()
26369 "Insert <p>, but first close previous paragraph if any."
26370 (org-close-par-maybe)
26371 (insert "\n<p>")
26372 (setq org-par-open t))
26373 (defun org-close-par-maybe ()
26374 "Close paragraph if there is one open."
26375 (when org-par-open
26376 (insert "</p>")
26377 (setq org-par-open nil)))
26378 (defun org-close-li ()
26379 "Close <li> if necessary."
26380 (org-close-par-maybe)
26381 (insert "</li>\n"))
26383 (defvar body-only) ; dynamically scoped into this.
26384 (defun org-html-level-start (level title umax with-toc head-count)
26385 "Insert a new level in HTML export.
26386 When TITLE is nil, just close all open levels."
26387 (org-close-par-maybe)
26388 (let ((l org-level-max))
26389 (while (>= l level)
26390 (if (aref org-levels-open (1- l))
26391 (progn
26392 (org-html-level-close l umax)
26393 (aset org-levels-open (1- l) nil)))
26394 (setq l (1- l)))
26395 (when title
26396 ;; If title is nil, this means this function is called to close
26397 ;; all levels, so the rest is done only if title is given
26398 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26399 (setq title (replace-match
26400 (if org-export-with-tags
26401 (save-match-data
26402 (concat
26403 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26404 (mapconcat 'identity (org-split-string
26405 (match-string 1 title) ":")
26406 "&nbsp;")
26407 "</span>"))
26409 t t title)))
26410 (if (> level umax)
26411 (progn
26412 (if (aref org-levels-open (1- level))
26413 (progn
26414 (org-close-li)
26415 (insert "<li>" title "<br/>\n"))
26416 (aset org-levels-open (1- level) t)
26417 (org-close-par-maybe)
26418 (insert "<ul>\n<li>" title "<br/>\n")))
26419 (aset org-levels-open (1- level) t)
26420 (if (and org-export-with-section-numbers (not body-only))
26421 (setq title (concat (org-section-number level) " " title)))
26422 (setq level (+ level org-export-html-toplevel-hlevel -1))
26423 (if with-toc
26424 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26425 level level head-count title level))
26426 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26427 (org-open-par)))))
26429 (defun org-html-level-close (level max-outline-level)
26430 "Terminate one level in HTML export."
26431 (if (<= level max-outline-level)
26432 (insert "</div>\n")
26433 (org-close-li)
26434 (insert "</ul>\n")))
26436 ;;; iCalendar export
26438 ;;;###autoload
26439 (defun org-export-icalendar-this-file ()
26440 "Export current file as an iCalendar file.
26441 The iCalendar file will be located in the same directory as the Org-mode
26442 file, but with extension `.ics'."
26443 (interactive)
26444 (org-export-icalendar nil buffer-file-name))
26446 ;;;###autoload
26447 (defun org-export-icalendar-all-agenda-files ()
26448 "Export all files in `org-agenda-files' to iCalendar .ics files.
26449 Each iCalendar file will be located in the same directory as the Org-mode
26450 file, but with extension `.ics'."
26451 (interactive)
26452 (apply 'org-export-icalendar nil (org-agenda-files t)))
26454 ;;;###autoload
26455 (defun org-export-icalendar-combine-agenda-files ()
26456 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26457 The file is stored under the name `org-combined-agenda-icalendar-file'."
26458 (interactive)
26459 (apply 'org-export-icalendar t (org-agenda-files t)))
26461 (defun org-export-icalendar (combine &rest files)
26462 "Create iCalendar files for all elements of FILES.
26463 If COMBINE is non-nil, combine all calendar entries into a single large
26464 file and store it under the name `org-combined-agenda-icalendar-file'."
26465 (save-excursion
26466 (org-prepare-agenda-buffers files)
26467 (let* ((dir (org-export-directory
26468 :ical (list :publishing-directory
26469 org-export-publishing-directory)))
26470 file ical-file ical-buffer category started org-agenda-new-buffers)
26472 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26473 (when combine
26474 (setq ical-file
26475 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26476 org-combined-agenda-icalendar-file
26477 (expand-file-name org-combined-agenda-icalendar-file dir))
26478 ical-buffer (org-get-agenda-file-buffer ical-file))
26479 (set-buffer ical-buffer) (erase-buffer))
26480 (while (setq file (pop files))
26481 (catch 'nextfile
26482 (org-check-agenda-file file)
26483 (set-buffer (org-get-agenda-file-buffer file))
26484 (unless combine
26485 (setq ical-file (concat (file-name-as-directory dir)
26486 (file-name-sans-extension
26487 (file-name-nondirectory buffer-file-name))
26488 ".ics"))
26489 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26490 (with-current-buffer ical-buffer (erase-buffer)))
26491 (setq category (or org-category
26492 (file-name-sans-extension
26493 (file-name-nondirectory buffer-file-name))))
26494 (if (symbolp category) (setq category (symbol-name category)))
26495 (let ((standard-output ical-buffer))
26496 (if combine
26497 (and (not started) (setq started t)
26498 (org-start-icalendar-file org-icalendar-combined-name))
26499 (org-start-icalendar-file category))
26500 (org-print-icalendar-entries combine)
26501 (when (or (and combine (not files)) (not combine))
26502 (org-finish-icalendar-file)
26503 (set-buffer ical-buffer)
26504 (save-buffer)
26505 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26506 (org-release-buffers org-agenda-new-buffers))))
26508 (defvar org-after-save-iCalendar-file-hook nil
26509 "Hook run after an iCalendar file has been saved.
26510 The iCalendar buffer is still current when this hook is run.
26511 A good way to use this is to tell a desktop calenndar application to re-read
26512 the iCalendar file.")
26514 (defun org-print-icalendar-entries (&optional combine)
26515 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26516 When COMBINE is non nil, add the category to each line."
26517 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26518 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26519 (dts (org-ical-ts-to-string
26520 (format-time-string (cdr org-time-stamp-formats) (current-time))
26521 "DTSTART"))
26522 hd ts ts2 state status (inc t) pos b sexp rrule
26523 scheduledp deadlinep tmp pri category entry location summary desc
26524 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26525 (org-refresh-category-properties)
26526 (save-excursion
26527 (goto-char (point-min))
26528 (while (re-search-forward re1 nil t)
26529 (catch :skip
26530 (org-agenda-skip)
26531 (setq pos (match-beginning 0)
26532 ts (match-string 0)
26533 inc t
26534 hd (org-get-heading)
26535 summary (org-icalendar-cleanup-string
26536 (org-entry-get nil "SUMMARY"))
26537 desc (org-icalendar-cleanup-string
26538 (or (org-entry-get nil "DESCRIPTION")
26539 (and org-icalendar-include-body (org-get-entry)))
26540 t org-icalendar-include-body)
26541 location (org-icalendar-cleanup-string
26542 (org-entry-get nil "LOCATION"))
26543 category (org-get-category))
26544 (if (looking-at re2)
26545 (progn
26546 (goto-char (match-end 0))
26547 (setq ts2 (match-string 1) inc nil))
26548 (setq tmp (buffer-substring (max (point-min)
26549 (- pos org-ds-keyword-length))
26550 pos)
26551 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26552 (progn
26553 (setq inc nil)
26554 (replace-match "\\1" t nil ts))
26556 deadlinep (string-match org-deadline-regexp tmp)
26557 scheduledp (string-match org-scheduled-regexp tmp)
26558 ;; donep (org-entry-is-done-p)
26560 (if (or (string-match org-tr-regexp hd)
26561 (string-match org-ts-regexp hd))
26562 (setq hd (replace-match "" t t hd)))
26563 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26564 (setq rrule
26565 (concat "\nRRULE:FREQ="
26566 (cdr (assoc
26567 (match-string 2 ts)
26568 '(("d" . "DAILY")("w" . "WEEKLY")
26569 ("m" . "MONTHLY")("y" . "YEARLY"))))
26570 ";INTERVAL=" (match-string 1 ts)))
26571 (setq rrule ""))
26572 (setq summary (or summary hd))
26573 (if (string-match org-bracket-link-regexp summary)
26574 (setq summary
26575 (replace-match (if (match-end 3)
26576 (match-string 3 summary)
26577 (match-string 1 summary))
26578 t t summary)))
26579 (if deadlinep (setq summary (concat "DL: " summary)))
26580 (if scheduledp (setq summary (concat "S: " summary)))
26581 (if (string-match "\\`<%%" ts)
26582 (with-current-buffer sexp-buffer
26583 (insert (substring ts 1 -1) " " summary "\n"))
26584 (princ (format "BEGIN:VEVENT
26586 %s%s
26587 SUMMARY:%s%s%s
26588 CATEGORIES:%s
26589 END:VEVENT\n"
26590 (org-ical-ts-to-string ts "DTSTART")
26591 (org-ical-ts-to-string ts2 "DTEND" inc)
26592 rrule summary
26593 (if (and desc (string-match "\\S-" desc))
26594 (concat "\nDESCRIPTION: " desc) "")
26595 (if (and location (string-match "\\S-" location))
26596 (concat "\nLOCATION: " location) "")
26597 category)))))
26599 (when (and org-icalendar-include-sexps
26600 (condition-case nil (require 'icalendar) (error nil))
26601 (fboundp 'icalendar-export-region))
26602 ;; Get all the literal sexps
26603 (goto-char (point-min))
26604 (while (re-search-forward "^&?%%(" nil t)
26605 (catch :skip
26606 (org-agenda-skip)
26607 (setq b (match-beginning 0))
26608 (goto-char (1- (match-end 0)))
26609 (forward-sexp 1)
26610 (end-of-line 1)
26611 (setq sexp (buffer-substring b (point)))
26612 (with-current-buffer sexp-buffer
26613 (insert sexp "\n"))
26614 (princ (org-diary-to-ical-string sexp-buffer)))))
26616 (when org-icalendar-include-todo
26617 (goto-char (point-min))
26618 (while (re-search-forward org-todo-line-regexp nil t)
26619 (catch :skip
26620 (org-agenda-skip)
26621 (setq state (match-string 2))
26622 (setq status (if (member state org-done-keywords)
26623 "COMPLETED" "NEEDS-ACTION"))
26624 (when (and state
26625 (or (not (member state org-done-keywords))
26626 (eq org-icalendar-include-todo 'all))
26627 (not (member org-archive-tag (org-get-tags-at)))
26629 (setq hd (match-string 3)
26630 summary (org-icalendar-cleanup-string
26631 (org-entry-get nil "SUMMARY"))
26632 desc (org-icalendar-cleanup-string
26633 (or (org-entry-get nil "DESCRIPTION")
26634 (and org-icalendar-include-body (org-get-entry)))
26635 t org-icalendar-include-body)
26636 location (org-icalendar-cleanup-string
26637 (org-entry-get nil "LOCATION")))
26638 (if (string-match org-bracket-link-regexp hd)
26639 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26640 (match-string 1 hd))
26641 t t hd)))
26642 (if (string-match org-priority-regexp hd)
26643 (setq pri (string-to-char (match-string 2 hd))
26644 hd (concat (substring hd 0 (match-beginning 1))
26645 (substring hd (match-end 1))))
26646 (setq pri org-default-priority))
26647 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26648 (- org-lowest-priority org-highest-priority))))))
26650 (princ (format "BEGIN:VTODO
26652 SUMMARY:%s%s%s
26653 CATEGORIES:%s
26654 SEQUENCE:1
26655 PRIORITY:%d
26656 STATUS:%s
26657 END:VTODO\n"
26659 (or summary hd)
26660 (if (and location (string-match "\\S-" location))
26661 (concat "\nLOCATION: " location) "")
26662 (if (and desc (string-match "\\S-" desc))
26663 (concat "\nDESCRIPTION: " desc) "")
26664 category pri status)))))))))
26666 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26667 "Take out stuff and quote what needs to be quoted.
26668 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26669 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26670 characters."
26671 (if (not s)
26673 (when is-body
26674 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26675 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26676 (while (string-match re s) (setq s (replace-match "" t t s)))
26677 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26678 (let ((start 0))
26679 (while (string-match "\\([,;\\]\\)" s start)
26680 (setq start (+ (match-beginning 0) 2)
26681 s (replace-match "\\\\\\1" nil nil s))))
26682 (when is-body
26683 (while (string-match "[ \t]*\n[ \t]*" s)
26684 (setq s (replace-match "\\n" t t s))))
26685 (setq s (org-trim s))
26686 (if is-body
26687 (if maxlength
26688 (if (and (numberp maxlength)
26689 (> (length s) maxlength))
26690 (setq s (substring s 0 maxlength)))))
26693 (defun org-get-entry ()
26694 "Clean-up description string."
26695 (save-excursion
26696 (org-back-to-heading t)
26697 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26699 (defun org-start-icalendar-file (name)
26700 "Start an iCalendar file by inserting the header."
26701 (let ((user user-full-name)
26702 (name (or name "unknown"))
26703 (timezone (cadr (current-time-zone))))
26704 (princ
26705 (format "BEGIN:VCALENDAR
26706 VERSION:2.0
26707 X-WR-CALNAME:%s
26708 PRODID:-//%s//Emacs with Org-mode//EN
26709 X-WR-TIMEZONE:%s
26710 CALSCALE:GREGORIAN\n" name user timezone))))
26712 (defun org-finish-icalendar-file ()
26713 "Finish an iCalendar file by inserting the END statement."
26714 (princ "END:VCALENDAR\n"))
26716 (defun org-ical-ts-to-string (s keyword &optional inc)
26717 "Take a time string S and convert it to iCalendar format.
26718 KEYWORD is added in front, to make a complete line like DTSTART....
26719 When INC is non-nil, increase the hour by two (if time string contains
26720 a time), or the day by one (if it does not contain a time)."
26721 (let ((t1 (org-parse-time-string s 'nodefault))
26722 t2 fmt have-time time)
26723 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26724 (setq t2 t1 have-time t)
26725 (setq t2 (org-parse-time-string s)))
26726 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26727 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26728 (when inc
26729 (if have-time
26730 (if org-agenda-default-appointment-duration
26731 (setq mi (+ org-agenda-default-appointment-duration mi))
26732 (setq h (+ 2 h)))
26733 (setq d (1+ d))))
26734 (setq time (encode-time s mi h d m y)))
26735 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26736 (concat keyword (format-time-string fmt time))))
26738 ;;; XOXO export
26740 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26741 (with-current-buffer buffer
26742 (apply 'insert output)))
26743 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26745 (defun org-export-as-xoxo (&optional buffer)
26746 "Export the org buffer as XOXO.
26747 The XOXO buffer is named *xoxo-<source buffer name>*"
26748 (interactive (list (current-buffer)))
26749 ;; A quickie abstraction
26751 ;; Output everything as XOXO
26752 (with-current-buffer (get-buffer buffer)
26753 (let* ((pos (point))
26754 (opt-plist (org-combine-plists (org-default-export-plist)
26755 (org-infile-export-plist)))
26756 (filename (concat (file-name-as-directory
26757 (org-export-directory :xoxo opt-plist))
26758 (file-name-sans-extension
26759 (file-name-nondirectory buffer-file-name))
26760 ".html"))
26761 (out (find-file-noselect filename))
26762 (last-level 1)
26763 (hanging-li nil))
26764 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26765 ;; Check the output buffer is empty.
26766 (with-current-buffer out (erase-buffer))
26767 ;; Kick off the output
26768 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26769 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26770 (let* ((hd (match-string-no-properties 1))
26771 (level (length hd))
26772 (text (concat
26773 (match-string-no-properties 2)
26774 (save-excursion
26775 (goto-char (match-end 0))
26776 (let ((str ""))
26777 (catch 'loop
26778 (while 't
26779 (forward-line)
26780 (if (looking-at "^[ \t]\\(.*\\)")
26781 (setq str (concat str (match-string-no-properties 1)))
26782 (throw 'loop str)))))))))
26784 ;; Handle level rendering
26785 (cond
26786 ((> level last-level)
26787 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26789 ((< level last-level)
26790 (dotimes (- (- last-level level) 1)
26791 (if hanging-li
26792 (org-export-as-xoxo-insert-into out "</li>\n"))
26793 (org-export-as-xoxo-insert-into out "</ol>\n"))
26794 (when hanging-li
26795 (org-export-as-xoxo-insert-into out "</li>\n")
26796 (setq hanging-li nil)))
26798 ((equal level last-level)
26799 (if hanging-li
26800 (org-export-as-xoxo-insert-into out "</li>\n")))
26803 (setq last-level level)
26805 ;; And output the new li
26806 (setq hanging-li 't)
26807 (if (equal ?+ (elt text 0))
26808 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26809 (org-export-as-xoxo-insert-into out "<li>" text))))
26811 ;; Finally finish off the ol
26812 (dotimes (- last-level 1)
26813 (if hanging-li
26814 (org-export-as-xoxo-insert-into out "</li>\n"))
26815 (org-export-as-xoxo-insert-into out "</ol>\n"))
26817 (goto-char pos)
26818 ;; Finish the buffer off and clean it up.
26819 (switch-to-buffer-other-window out)
26820 (indent-region (point-min) (point-max) nil)
26821 (save-buffer)
26822 (goto-char (point-min))
26826 ;;;; Key bindings
26828 ;; Make `C-c C-x' a prefix key
26829 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26831 ;; TAB key with modifiers
26832 (org-defkey org-mode-map "\C-i" 'org-cycle)
26833 (org-defkey org-mode-map [(tab)] 'org-cycle)
26834 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26835 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26836 (org-defkey org-mode-map "\M-\t" 'org-complete)
26837 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26838 ;; The following line is necessary under Suse GNU/Linux
26839 (unless (featurep 'xemacs)
26840 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26841 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26842 (define-key org-mode-map [backtab] 'org-shifttab)
26844 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26845 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26846 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26848 ;; Cursor keys with modifiers
26849 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26850 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26851 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26852 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26854 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26855 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26856 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26857 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26859 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26860 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26861 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26862 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26864 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26865 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26867 ;;; Extra keys for tty access.
26868 ;; We only set them when really needed because otherwise the
26869 ;; menus don't show the simple keys
26871 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26872 (not window-system))
26873 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26874 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26875 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26876 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26877 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26878 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26879 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26880 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26881 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26882 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26883 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26884 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26885 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26886 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26887 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26888 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26889 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26890 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26891 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26892 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26893 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26894 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26896 ;; All the other keys
26898 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26899 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26900 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26901 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26902 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26903 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26904 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26905 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26906 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26907 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26908 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26909 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26910 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26911 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26912 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26913 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26914 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26915 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26916 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26917 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26918 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26919 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26920 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26921 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26922 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26923 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26924 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26925 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26926 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26927 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26928 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26929 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26930 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26931 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26932 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26933 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26934 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26935 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26936 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26937 (org-defkey org-mode-map "\C-c^" 'org-sort)
26938 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26939 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26940 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26941 (org-defkey org-mode-map "\C-m" 'org-return)
26942 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26943 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26944 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26945 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26946 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26947 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26948 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26949 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26950 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26951 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26952 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26953 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26954 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26955 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26956 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26957 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26958 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26960 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26961 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26962 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26963 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26965 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26966 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26967 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26968 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26969 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26970 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26971 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26972 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26973 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26974 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26975 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26976 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26978 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26980 (when (featurep 'xemacs)
26981 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26983 (defsubst org-table-p () (org-at-table-p))
26985 (defun org-self-insert-command (N)
26986 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26987 If the cursor is in a table looking at whitespace, the whitespace is
26988 overwritten, and the table is not marked as requiring realignment."
26989 (interactive "p")
26990 (if (and (org-table-p)
26991 (progn
26992 ;; check if we blank the field, and if that triggers align
26993 (and org-table-auto-blank-field
26994 (member last-command
26995 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26996 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26997 ;; got extra space, this field does not determine column width
26998 (let (org-table-may-need-update) (org-table-blank-field))
26999 ;; no extra space, this field may determine column width
27000 (org-table-blank-field)))
27002 (eq N 1)
27003 (looking-at "[^|\n]* |"))
27004 (let (org-table-may-need-update)
27005 (goto-char (1- (match-end 0)))
27006 (delete-backward-char 1)
27007 (goto-char (match-beginning 0))
27008 (self-insert-command N))
27009 (setq org-table-may-need-update t)
27010 (self-insert-command N)
27011 (org-fix-tags-on-the-fly)))
27013 (defun org-fix-tags-on-the-fly ()
27014 (when (and (equal (char-after (point-at-bol)) ?*)
27015 (org-on-heading-p))
27016 (org-align-tags-here org-tags-column)))
27018 (defun org-delete-backward-char (N)
27019 "Like `delete-backward-char', insert whitespace at field end in tables.
27020 When deleting backwards, in tables this function will insert whitespace in
27021 front of the next \"|\" separator, to keep the table aligned. The table will
27022 still be marked for re-alignment if the field did fill the entire column,
27023 because, in this case the deletion might narrow the column."
27024 (interactive "p")
27025 (if (and (org-table-p)
27026 (eq N 1)
27027 (string-match "|" (buffer-substring (point-at-bol) (point)))
27028 (looking-at ".*?|"))
27029 (let ((pos (point))
27030 (noalign (looking-at "[^|\n\r]* |"))
27031 (c org-table-may-need-update))
27032 (backward-delete-char N)
27033 (skip-chars-forward "^|")
27034 (insert " ")
27035 (goto-char (1- pos))
27036 ;; noalign: if there were two spaces at the end, this field
27037 ;; does not determine the width of the column.
27038 (if noalign (setq org-table-may-need-update c)))
27039 (backward-delete-char N)
27040 (org-fix-tags-on-the-fly)))
27042 (defun org-delete-char (N)
27043 "Like `delete-char', but insert whitespace at field end in tables.
27044 When deleting characters, in tables this function will insert whitespace in
27045 front of the next \"|\" separator, to keep the table aligned. The table will
27046 still be marked for re-alignment if the field did fill the entire column,
27047 because, in this case the deletion might narrow the column."
27048 (interactive "p")
27049 (if (and (org-table-p)
27050 (not (bolp))
27051 (not (= (char-after) ?|))
27052 (eq N 1))
27053 (if (looking-at ".*?|")
27054 (let ((pos (point))
27055 (noalign (looking-at "[^|\n\r]* |"))
27056 (c org-table-may-need-update))
27057 (replace-match (concat
27058 (substring (match-string 0) 1 -1)
27059 " |"))
27060 (goto-char pos)
27061 ;; noalign: if there were two spaces at the end, this field
27062 ;; does not determine the width of the column.
27063 (if noalign (setq org-table-may-need-update c)))
27064 (delete-char N))
27065 (delete-char N)
27066 (org-fix-tags-on-the-fly)))
27068 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27069 (put 'org-self-insert-command 'delete-selection t)
27070 (put 'orgtbl-self-insert-command 'delete-selection t)
27071 (put 'org-delete-char 'delete-selection 'supersede)
27072 (put 'org-delete-backward-char 'delete-selection 'supersede)
27074 ;; Make `flyspell-mode' delay after some commands
27075 (put 'org-self-insert-command 'flyspell-delayed t)
27076 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27077 (put 'org-delete-char 'flyspell-delayed t)
27078 (put 'org-delete-backward-char 'flyspell-delayed t)
27080 ;; Make pabbrev-mode expand after org-mode commands
27081 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27082 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27084 ;; How to do this: Measure non-white length of current string
27085 ;; If equal to column width, we should realign.
27087 (defun org-remap (map &rest commands)
27088 "In MAP, remap the functions given in COMMANDS.
27089 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27090 (let (new old)
27091 (while commands
27092 (setq old (pop commands) new (pop commands))
27093 (if (fboundp 'command-remapping)
27094 (org-defkey map (vector 'remap old) new)
27095 (substitute-key-definition old new map global-map)))))
27097 (when (eq org-enable-table-editor 'optimized)
27098 ;; If the user wants maximum table support, we need to hijack
27099 ;; some standard editing functions
27100 (org-remap org-mode-map
27101 'self-insert-command 'org-self-insert-command
27102 'delete-char 'org-delete-char
27103 'delete-backward-char 'org-delete-backward-char)
27104 (org-defkey org-mode-map "|" 'org-force-self-insert))
27106 (defun org-shiftcursor-error ()
27107 "Throw an error because Shift-Cursor command was applied in wrong context."
27108 (error "This command is active in special context like tables, headlines or timestamps"))
27110 (defun org-shifttab (&optional arg)
27111 "Global visibility cycling or move to previous table field.
27112 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27113 on context.
27114 See the individual commands for more information."
27115 (interactive "P")
27116 (cond
27117 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27118 (arg (message "Content view to level: ")
27119 (org-content (prefix-numeric-value arg))
27120 (setq org-cycle-global-status 'overview))
27121 (t (call-interactively 'org-global-cycle))))
27123 (defun org-shiftmetaleft ()
27124 "Promote subtree or delete table column.
27125 Calls `org-promote-subtree', `org-outdent-item',
27126 or `org-table-delete-column', depending on context.
27127 See the individual commands for more information."
27128 (interactive)
27129 (cond
27130 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27131 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27132 ((org-at-item-p) (call-interactively 'org-outdent-item))
27133 (t (org-shiftcursor-error))))
27135 (defun org-shiftmetaright ()
27136 "Demote subtree or insert table column.
27137 Calls `org-demote-subtree', `org-indent-item',
27138 or `org-table-insert-column', depending on context.
27139 See the individual commands for more information."
27140 (interactive)
27141 (cond
27142 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27143 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27144 ((org-at-item-p) (call-interactively 'org-indent-item))
27145 (t (org-shiftcursor-error))))
27147 (defun org-shiftmetaup (&optional arg)
27148 "Move subtree up or kill table row.
27149 Calls `org-move-subtree-up' or `org-table-kill-row' or
27150 `org-move-item-up' depending on context. See the individual commands
27151 for more information."
27152 (interactive "P")
27153 (cond
27154 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27155 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27156 ((org-at-item-p) (call-interactively 'org-move-item-up))
27157 (t (org-shiftcursor-error))))
27158 (defun org-shiftmetadown (&optional arg)
27159 "Move subtree down or insert table row.
27160 Calls `org-move-subtree-down' or `org-table-insert-row' or
27161 `org-move-item-down', depending on context. See the individual
27162 commands for more information."
27163 (interactive "P")
27164 (cond
27165 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27166 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27167 ((org-at-item-p) (call-interactively 'org-move-item-down))
27168 (t (org-shiftcursor-error))))
27170 (defun org-metaleft (&optional arg)
27171 "Promote heading or move table column to left.
27172 Calls `org-do-promote' or `org-table-move-column', depending on context.
27173 With no specific context, calls the Emacs default `backward-word'.
27174 See the individual commands for more information."
27175 (interactive "P")
27176 (cond
27177 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27178 ((or (org-on-heading-p) (org-region-active-p))
27179 (call-interactively 'org-do-promote))
27180 ((org-at-item-p) (call-interactively 'org-outdent-item))
27181 (t (call-interactively 'backward-word))))
27183 (defun org-metaright (&optional arg)
27184 "Demote subtree or move table column to right.
27185 Calls `org-do-demote' or `org-table-move-column', depending on context.
27186 With no specific context, calls the Emacs default `forward-word'.
27187 See the individual commands for more information."
27188 (interactive "P")
27189 (cond
27190 ((org-at-table-p) (call-interactively 'org-table-move-column))
27191 ((or (org-on-heading-p) (org-region-active-p))
27192 (call-interactively 'org-do-demote))
27193 ((org-at-item-p) (call-interactively 'org-indent-item))
27194 (t (call-interactively 'forward-word))))
27196 (defun org-metaup (&optional arg)
27197 "Move subtree up or move table row up.
27198 Calls `org-move-subtree-up' or `org-table-move-row' or
27199 `org-move-item-up', depending on context. See the individual commands
27200 for more information."
27201 (interactive "P")
27202 (cond
27203 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27204 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27205 ((org-at-item-p) (call-interactively 'org-move-item-up))
27206 (t (transpose-lines 1) (beginning-of-line -1))))
27208 (defun org-metadown (&optional arg)
27209 "Move subtree down or move table row down.
27210 Calls `org-move-subtree-down' or `org-table-move-row' or
27211 `org-move-item-down', depending on context. See the individual
27212 commands for more information."
27213 (interactive "P")
27214 (cond
27215 ((org-at-table-p) (call-interactively 'org-table-move-row))
27216 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27217 ((org-at-item-p) (call-interactively 'org-move-item-down))
27218 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27220 (defun org-shiftup (&optional arg)
27221 "Increase item in timestamp or increase priority of current headline.
27222 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27223 depending on context. See the individual commands for more information."
27224 (interactive "P")
27225 (cond
27226 ((org-at-timestamp-p t)
27227 (call-interactively (if org-edit-timestamp-down-means-later
27228 'org-timestamp-down 'org-timestamp-up)))
27229 ((org-on-heading-p) (call-interactively 'org-priority-up))
27230 ((org-at-item-p) (call-interactively 'org-previous-item))
27231 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27233 (defun org-shiftdown (&optional arg)
27234 "Decrease item in timestamp or decrease priority of current headline.
27235 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27236 depending on context. See the individual commands for more information."
27237 (interactive "P")
27238 (cond
27239 ((org-at-timestamp-p t)
27240 (call-interactively (if org-edit-timestamp-down-means-later
27241 'org-timestamp-up 'org-timestamp-down)))
27242 ((org-on-heading-p) (call-interactively 'org-priority-down))
27243 (t (call-interactively 'org-next-item))))
27245 (defun org-shiftright ()
27246 "Next TODO keyword or timestamp one day later, depending on context."
27247 (interactive)
27248 (cond
27249 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27250 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27251 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27252 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27253 (t (org-shiftcursor-error))))
27255 (defun org-shiftleft ()
27256 "Previous TODO keyword or timestamp one day earlier, depending on context."
27257 (interactive)
27258 (cond
27259 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27260 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27261 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27262 ((org-at-property-p)
27263 (call-interactively 'org-property-previous-allowed-value))
27264 (t (org-shiftcursor-error))))
27266 (defun org-shiftcontrolright ()
27267 "Switch to next TODO set."
27268 (interactive)
27269 (cond
27270 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27271 (t (org-shiftcursor-error))))
27273 (defun org-shiftcontrolleft ()
27274 "Switch to previous TODO set."
27275 (interactive)
27276 (cond
27277 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27278 (t (org-shiftcursor-error))))
27280 (defun org-ctrl-c-ret ()
27281 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27282 (interactive)
27283 (cond
27284 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27285 (t (call-interactively 'org-insert-heading))))
27287 (defun org-copy-special ()
27288 "Copy region in table or copy current subtree.
27289 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27290 See the individual commands for more information."
27291 (interactive)
27292 (call-interactively
27293 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27295 (defun org-cut-special ()
27296 "Cut region in table or cut current subtree.
27297 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27298 See the individual commands for more information."
27299 (interactive)
27300 (call-interactively
27301 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27303 (defun org-paste-special (arg)
27304 "Paste rectangular region into table, or past subtree relative to level.
27305 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27306 See the individual commands for more information."
27307 (interactive "P")
27308 (if (org-at-table-p)
27309 (org-table-paste-rectangle)
27310 (org-paste-subtree arg)))
27312 (defun org-ctrl-c-ctrl-c (&optional arg)
27313 "Set tags in headline, or update according to changed information at point.
27315 This command does many different things, depending on context:
27317 - If the cursor is in a headline, prompt for tags and insert them
27318 into the current line, aligned to `org-tags-column'. When called
27319 with prefix arg, realign all tags in the current buffer.
27321 - If the cursor is in one of the special #+KEYWORD lines, this
27322 triggers scanning the buffer for these lines and updating the
27323 information.
27325 - If the cursor is inside a table, realign the table. This command
27326 works even if the automatic table editor has been turned off.
27328 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27329 the entire table.
27331 - If the cursor is a the beginning of a dynamic block, update it.
27333 - If the cursor is inside a table created by the table.el package,
27334 activate that table.
27336 - If the current buffer is a remember buffer, close note and file it.
27337 with a prefix argument, file it without further interaction to the default
27338 location.
27340 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27341 links in this buffer.
27343 - If the cursor is on a numbered item in a plain list, renumber the
27344 ordered list.
27346 - If the cursor is on a checkbox, toggle it."
27347 (interactive "P")
27348 (let ((org-enable-table-editor t))
27349 (cond
27350 ((or org-clock-overlays
27351 org-occur-highlights
27352 org-latex-fragment-image-overlays)
27353 (org-remove-clock-overlays)
27354 (org-remove-occur-highlights)
27355 (org-remove-latex-fragment-image-overlays)
27356 (message "Temporary highlights/overlays removed from current buffer"))
27357 ((and (local-variable-p 'org-finish-function (current-buffer))
27358 (fboundp org-finish-function))
27359 (funcall org-finish-function))
27360 ((org-at-property-p)
27361 (call-interactively 'org-property-action))
27362 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27363 ((org-on-heading-p) (call-interactively 'org-set-tags))
27364 ((org-at-table.el-p)
27365 (require 'table)
27366 (beginning-of-line 1)
27367 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27368 (call-interactively 'table-recognize-table))
27369 ((org-at-table-p)
27370 (org-table-maybe-eval-formula)
27371 (if arg
27372 (call-interactively 'org-table-recalculate)
27373 (org-table-maybe-recalculate-line))
27374 (call-interactively 'org-table-align))
27375 ((org-at-item-checkbox-p)
27376 (call-interactively 'org-toggle-checkbox))
27377 ((org-at-item-p)
27378 (call-interactively 'org-maybe-renumber-ordered-list))
27379 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27380 ;; Dynamic block
27381 (beginning-of-line 1)
27382 (org-update-dblock))
27383 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27384 (cond
27385 ((equal (match-string 1) "TBLFM")
27386 ;; Recalculate the table before this line
27387 (save-excursion
27388 (beginning-of-line 1)
27389 (skip-chars-backward " \r\n\t")
27390 (if (org-at-table-p)
27391 (org-call-with-arg 'org-table-recalculate t))))
27393 (call-interactively 'org-mode-restart))))
27394 (t (error "C-c C-c can do nothing useful at this location.")))))
27396 (defun org-mode-restart ()
27397 "Restart Org-mode, to scan again for special lines.
27398 Also updates the keyword regular expressions."
27399 (interactive)
27400 (let ((org-inhibit-startup t)) (org-mode))
27401 (message "Org-mode restarted to refresh keyword and special line setup"))
27403 (defun org-kill-note-or-show-branches ()
27404 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27405 (interactive)
27406 (if (not org-finish-function)
27407 (call-interactively 'show-branches)
27408 (let ((org-note-abort t))
27409 (funcall org-finish-function))))
27411 (defun org-return (&optional indent)
27412 "Goto next table row or insert a newline.
27413 Calls `org-table-next-row' or `newline', depending on context.
27414 See the individual commands for more information."
27415 (interactive)
27416 (cond
27417 ((bobp) (if indent (newline-and-indent) (newline)))
27418 ((and (org-at-heading-p)
27419 (looking-at
27420 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27421 (org-show-entry)
27422 (end-of-line 1)
27423 (newline))
27424 ((org-at-table-p)
27425 (org-table-justify-field-maybe)
27426 (call-interactively 'org-table-next-row))
27427 (t (if indent (newline-and-indent) (newline)))))
27429 (defun org-return-indent ()
27430 (interactive)
27431 "Goto next table row or insert a newline and indent.
27432 Calls `org-table-next-row' or `newline-and-indent', depending on
27433 context. See the individual commands for more information."
27434 (org-return t))
27436 (defun org-ctrl-c-minus ()
27437 "Insert separator line in table or modify bullet type in list.
27438 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
27439 depending on context."
27440 (interactive)
27441 (cond
27442 ((org-at-table-p)
27443 (call-interactively 'org-table-insert-hline))
27444 ((org-on-heading-p)
27445 ;; Convert to item
27446 (save-excursion
27447 (beginning-of-line 1)
27448 (if (looking-at "\\*+ ")
27449 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27450 ((org-in-item-p)
27451 (call-interactively 'org-cycle-list-bullet))
27452 (t (error "`C-c -' does have no function here."))))
27454 (defun org-meta-return (&optional arg)
27455 "Insert a new heading or wrap a region in a table.
27456 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27457 See the individual commands for more information."
27458 (interactive "P")
27459 (cond
27460 ((org-at-table-p)
27461 (call-interactively 'org-table-wrap-region))
27462 (t (call-interactively 'org-insert-heading))))
27464 ;;; Menu entries
27466 ;; Define the Org-mode menus
27467 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27468 '("Tbl"
27469 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27470 ["Next Field" org-cycle (org-at-table-p)]
27471 ["Previous Field" org-shifttab (org-at-table-p)]
27472 ["Next Row" org-return (org-at-table-p)]
27473 "--"
27474 ["Blank Field" org-table-blank-field (org-at-table-p)]
27475 ["Edit Field" org-table-edit-field (org-at-table-p)]
27476 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27477 "--"
27478 ("Column"
27479 ["Move Column Left" org-metaleft (org-at-table-p)]
27480 ["Move Column Right" org-metaright (org-at-table-p)]
27481 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27482 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27483 ("Row"
27484 ["Move Row Up" org-metaup (org-at-table-p)]
27485 ["Move Row Down" org-metadown (org-at-table-p)]
27486 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27487 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27488 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27489 "--"
27490 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27491 ("Rectangle"
27492 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27493 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27494 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27495 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27496 "--"
27497 ("Calculate"
27498 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27499 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27500 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27501 "--"
27502 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27503 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27504 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27505 "--"
27506 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27507 "--"
27508 ["Sum Column/Rectangle" org-table-sum
27509 (or (org-at-table-p) (org-region-active-p))]
27510 ["Which Column?" org-table-current-column (org-at-table-p)])
27511 ["Debug Formulas"
27512 org-table-toggle-formula-debugger
27513 :style toggle :selected org-table-formula-debug]
27514 ["Show Col/Row Numbers"
27515 org-table-toggle-coordinate-overlays
27516 :style toggle :selected org-table-overlay-coordinates]
27517 "--"
27518 ["Create" org-table-create (and (not (org-at-table-p))
27519 org-enable-table-editor)]
27520 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27521 ["Import from File" org-table-import (not (org-at-table-p))]
27522 ["Export to File" org-table-export (org-at-table-p)]
27523 "--"
27524 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27526 (easy-menu-define org-org-menu org-mode-map "Org menu"
27527 '("Org"
27528 ("Show/Hide"
27529 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27530 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27531 ["Sparse Tree" org-occur t]
27532 ["Reveal Context" org-reveal t]
27533 ["Show All" show-all t]
27534 "--"
27535 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27536 "--"
27537 ["New Heading" org-insert-heading t]
27538 ("Navigate Headings"
27539 ["Up" outline-up-heading t]
27540 ["Next" outline-next-visible-heading t]
27541 ["Previous" outline-previous-visible-heading t]
27542 ["Next Same Level" outline-forward-same-level t]
27543 ["Previous Same Level" outline-backward-same-level t]
27544 "--"
27545 ["Jump" org-goto t])
27546 ("Edit Structure"
27547 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27548 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27549 "--"
27550 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27551 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27552 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27553 "--"
27554 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27555 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27556 ["Demote Heading" org-metaright (not (org-at-table-p))]
27557 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27558 "--"
27559 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27560 "--"
27561 ["Convert to odd levels" org-convert-to-odd-levels t]
27562 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27563 ("Editing"
27564 ["Emphasis..." org-emphasize t])
27565 ("Archive"
27566 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27567 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27568 ; :active t :keys "C-u C-c C-x C-a"]
27569 ["Sparse trees open ARCHIVE trees"
27570 (setq org-sparse-tree-open-archived-trees
27571 (not org-sparse-tree-open-archived-trees))
27572 :style toggle :selected org-sparse-tree-open-archived-trees]
27573 ["Cycling opens ARCHIVE trees"
27574 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27575 :style toggle :selected org-cycle-open-archived-trees]
27576 ["Agenda includes ARCHIVE trees"
27577 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27578 :style toggle :selected (not org-agenda-skip-archived-trees)]
27579 "--"
27580 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27581 ; ["Check and Move Children" (org-archive-subtree '(4))
27582 ; :active t :keys "C-u C-c C-x C-s"]
27584 "--"
27585 ("TODO Lists"
27586 ["TODO/DONE/-" org-todo t]
27587 ("Select keyword"
27588 ["Next keyword" org-shiftright (org-on-heading-p)]
27589 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27590 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27591 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27592 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27593 ["Show TODO Tree" org-show-todo-tree t]
27594 ["Global TODO list" org-todo-list t]
27595 "--"
27596 ["Set Priority" org-priority t]
27597 ["Priority Up" org-shiftup t]
27598 ["Priority Down" org-shiftdown t])
27599 ("TAGS and Properties"
27600 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27601 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27602 "--"
27603 ["Set property" 'org-set-property t]
27604 ["Column view of properties" org-columns t]
27605 ["Insert Column View DBlock" org-insert-columns-dblock t])
27606 ("Dates and Scheduling"
27607 ["Timestamp" org-time-stamp t]
27608 ["Timestamp (inactive)" org-time-stamp-inactive t]
27609 ("Change Date"
27610 ["1 Day Later" org-shiftright t]
27611 ["1 Day Earlier" org-shiftleft t]
27612 ["1 ... Later" org-shiftup t]
27613 ["1 ... Earlier" org-shiftdown t])
27614 ["Compute Time Range" org-evaluate-time-range t]
27615 ["Schedule Item" org-schedule t]
27616 ["Deadline" org-deadline t]
27617 "--"
27618 ["Custom time format" org-toggle-time-stamp-overlays
27619 :style radio :selected org-display-custom-times]
27620 "--"
27621 ["Goto Calendar" org-goto-calendar t]
27622 ["Date from Calendar" org-date-from-calendar t])
27623 ("Logging work"
27624 ["Clock in" org-clock-in t]
27625 ["Clock out" org-clock-out t]
27626 ["Clock cancel" org-clock-cancel t]
27627 ["Goto running clock" org-clock-goto t]
27628 ["Display times" org-clock-display t]
27629 ["Create clock table" org-clock-report t]
27630 "--"
27631 ["Record DONE time"
27632 (progn (setq org-log-done (not org-log-done))
27633 (message "Switching to %s will %s record a timestamp"
27634 (car org-done-keywords)
27635 (if org-log-done "automatically" "not")))
27636 :style toggle :selected org-log-done])
27637 "--"
27638 ["Agenda Command..." org-agenda t]
27639 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27640 ("File List for Agenda")
27641 ("Special views current file"
27642 ["TODO Tree" org-show-todo-tree t]
27643 ["Check Deadlines" org-check-deadlines t]
27644 ["Timeline" org-timeline t]
27645 ["Tags Tree" org-tags-sparse-tree t])
27646 "--"
27647 ("Hyperlinks"
27648 ["Store Link (Global)" org-store-link t]
27649 ["Insert Link" org-insert-link t]
27650 ["Follow Link" org-open-at-point t]
27651 "--"
27652 ["Next link" org-next-link t]
27653 ["Previous link" org-previous-link t]
27654 "--"
27655 ["Descriptive Links"
27656 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27657 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27658 ["Literal Links"
27659 (progn
27660 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27661 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27662 "--"
27663 ["Export/Publish..." org-export t]
27664 ("LaTeX"
27665 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27666 :selected org-cdlatex-mode]
27667 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27668 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27669 ["Modify math symbol" org-cdlatex-math-modify
27670 (org-inside-LaTeX-fragment-p)]
27671 ["Export LaTeX fragments as images"
27672 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27673 :style toggle :selected org-export-with-LaTeX-fragments])
27674 "--"
27675 ("Documentation"
27676 ["Show Version" org-version t]
27677 ["Info Documentation" org-info t])
27678 ("Customize"
27679 ["Browse Org Group" org-customize t]
27680 "--"
27681 ["Expand This Menu" org-create-customize-menu
27682 (fboundp 'customize-menu-create)])
27683 "--"
27684 ["Refresh setup" org-mode-restart t]
27687 (defun org-info (&optional node)
27688 "Read documentation for Org-mode in the info system.
27689 With optional NODE, go directly to that node."
27690 (interactive)
27691 (require 'info)
27692 (info (format "(org)%s" (or node ""))))
27694 (defun org-install-agenda-files-menu ()
27695 (let ((bl (buffer-list)))
27696 (save-excursion
27697 (while bl
27698 (set-buffer (pop bl))
27699 (if (org-mode-p) (setq bl nil)))
27700 (when (org-mode-p)
27701 (easy-menu-change
27702 '("Org") "File List for Agenda"
27703 (append
27704 (list
27705 ["Edit File List" (org-edit-agenda-file-list) t]
27706 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27707 ["Remove Current File from List" org-remove-file t]
27708 ["Cycle through agenda files" org-cycle-agenda-files t]
27709 ["Occur in all agenda files" org-occur-in-agenda-files t]
27710 "--")
27711 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27713 ;;;; Documentation
27715 (defun org-customize ()
27716 "Call the customize function with org as argument."
27717 (interactive)
27718 (customize-browse 'org))
27720 (defun org-create-customize-menu ()
27721 "Create a full customization menu for Org-mode, insert it into the menu."
27722 (interactive)
27723 (if (fboundp 'customize-menu-create)
27724 (progn
27725 (easy-menu-change
27726 '("Org") "Customize"
27727 `(["Browse Org group" org-customize t]
27728 "--"
27729 ,(customize-menu-create 'org)
27730 ["Set" Custom-set t]
27731 ["Save" Custom-save t]
27732 ["Reset to Current" Custom-reset-current t]
27733 ["Reset to Saved" Custom-reset-saved t]
27734 ["Reset to Standard Settings" Custom-reset-standard t]))
27735 (message "\"Org\"-menu now contains full customization menu"))
27736 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27738 ;;;; Miscellaneous stuff
27741 ;;; Generally useful functions
27743 (defun org-context ()
27744 "Return a list of contexts of the current cursor position.
27745 If several contexts apply, all are returned.
27746 Each context entry is a list with a symbol naming the context, and
27747 two positions indicating start and end of the context. Possible
27748 contexts are:
27750 :headline anywhere in a headline
27751 :headline-stars on the leading stars in a headline
27752 :todo-keyword on a TODO keyword (including DONE) in a headline
27753 :tags on the TAGS in a headline
27754 :priority on the priority cookie in a headline
27755 :item on the first line of a plain list item
27756 :item-bullet on the bullet/number of a plain list item
27757 :checkbox on the checkbox in a plain list item
27758 :table in an org-mode table
27759 :table-special on a special filed in a table
27760 :table-table in a table.el table
27761 :link on a hyperlink
27762 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27763 :target on a <<target>>
27764 :radio-target on a <<<radio-target>>>
27765 :latex-fragment on a LaTeX fragment
27766 :latex-preview on a LaTeX fragment with overlayed preview image
27768 This function expects the position to be visible because it uses font-lock
27769 faces as a help to recognize the following contexts: :table-special, :link,
27770 and :keyword."
27771 (let* ((f (get-text-property (point) 'face))
27772 (faces (if (listp f) f (list f)))
27773 (p (point)) clist o)
27774 ;; First the large context
27775 (cond
27776 ((org-on-heading-p t)
27777 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27778 (when (progn
27779 (beginning-of-line 1)
27780 (looking-at org-todo-line-tags-regexp))
27781 (push (org-point-in-group p 1 :headline-stars) clist)
27782 (push (org-point-in-group p 2 :todo-keyword) clist)
27783 (push (org-point-in-group p 4 :tags) clist))
27784 (goto-char p)
27785 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27786 (if (looking-at "\\[#[A-Z0-9]\\]")
27787 (push (org-point-in-group p 0 :priority) clist)))
27789 ((org-at-item-p)
27790 (push (org-point-in-group p 2 :item-bullet) clist)
27791 (push (list :item (point-at-bol)
27792 (save-excursion (org-end-of-item) (point)))
27793 clist)
27794 (and (org-at-item-checkbox-p)
27795 (push (org-point-in-group p 0 :checkbox) clist)))
27797 ((org-at-table-p)
27798 (push (list :table (org-table-begin) (org-table-end)) clist)
27799 (if (memq 'org-formula faces)
27800 (push (list :table-special
27801 (previous-single-property-change p 'face)
27802 (next-single-property-change p 'face)) clist)))
27803 ((org-at-table-p 'any)
27804 (push (list :table-table) clist)))
27805 (goto-char p)
27807 ;; Now the small context
27808 (cond
27809 ((org-at-timestamp-p)
27810 (push (org-point-in-group p 0 :timestamp) clist))
27811 ((memq 'org-link faces)
27812 (push (list :link
27813 (previous-single-property-change p 'face)
27814 (next-single-property-change p 'face)) clist))
27815 ((memq 'org-special-keyword faces)
27816 (push (list :keyword
27817 (previous-single-property-change p 'face)
27818 (next-single-property-change p 'face)) clist))
27819 ((org-on-target-p)
27820 (push (org-point-in-group p 0 :target) clist)
27821 (goto-char (1- (match-beginning 0)))
27822 (if (looking-at org-radio-target-regexp)
27823 (push (org-point-in-group p 0 :radio-target) clist))
27824 (goto-char p))
27825 ((setq o (car (delq nil
27826 (mapcar
27827 (lambda (x)
27828 (if (memq x org-latex-fragment-image-overlays) x))
27829 (org-overlays-at (point))))))
27830 (push (list :latex-fragment
27831 (org-overlay-start o) (org-overlay-end o)) clist)
27832 (push (list :latex-preview
27833 (org-overlay-start o) (org-overlay-end o)) clist))
27834 ((org-inside-LaTeX-fragment-p)
27835 ;; FIXME: positions wrong.
27836 (push (list :latex-fragment (point) (point)) clist)))
27838 (setq clist (nreverse (delq nil clist)))
27839 clist))
27841 ;; FIXME: Compare with at-regexp-p Do we need both?
27842 (defun org-in-regexp (re &optional nlines visually)
27843 "Check if point is inside a match of regexp.
27844 Normally only the current line is checked, but you can include NLINES extra
27845 lines both before and after point into the search.
27846 If VISUALLY is set, require that the cursor is not after the match but
27847 really on, so that the block visually is on the match."
27848 (catch 'exit
27849 (let ((pos (point))
27850 (eol (point-at-eol (+ 1 (or nlines 0))))
27851 (inc (if visually 1 0)))
27852 (save-excursion
27853 (beginning-of-line (- 1 (or nlines 0)))
27854 (while (re-search-forward re eol t)
27855 (if (and (<= (match-beginning 0) pos)
27856 (>= (+ inc (match-end 0)) pos))
27857 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27859 (defun org-at-regexp-p (regexp)
27860 "Is point inside a match of REGEXP in the current line?"
27861 (catch 'exit
27862 (save-excursion
27863 (let ((pos (point)) (end (point-at-eol)))
27864 (beginning-of-line 1)
27865 (while (re-search-forward regexp end t)
27866 (if (and (<= (match-beginning 0) pos)
27867 (>= (match-end 0) pos))
27868 (throw 'exit t)))
27869 nil))))
27871 (defun org-occur-in-agenda-files (regexp &optional nlines)
27872 "Call `multi-occur' with buffers for all agenda files."
27873 (interactive "sOrg-files matching: \np")
27874 (let* ((files (org-agenda-files))
27875 (tnames (mapcar 'file-truename files))
27876 (extra org-agenda-text-search-extra-files)
27878 (while (setq f (pop extra))
27879 (unless (member (file-truename f) tnames)
27880 (add-to-list 'files f 'append)
27881 (add-to-list 'tnames (file-truename f) 'append)))
27882 (multi-occur
27883 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27884 regexp)))
27886 (if (boundp 'occur-mode-find-occurrence-hook)
27887 ;; Emacs 23
27888 (add-hook 'occur-mode-find-occurrence-hook
27889 (lambda ()
27890 (when (org-mode-p)
27891 (org-reveal))))
27892 ;; Emacs 22
27893 (defadvice occur-mode-goto-occurrence
27894 (after org-occur-reveal activate)
27895 (and (org-mode-p) (org-reveal)))
27896 (defadvice occur-mode-goto-occurrence-other-window
27897 (after org-occur-reveal activate)
27898 (and (org-mode-p) (org-reveal)))
27899 (defadvice occur-mode-display-occurrence
27900 (after org-occur-reveal activate)
27901 (when (org-mode-p)
27902 (let ((pos (occur-mode-find-occurrence)))
27903 (with-current-buffer (marker-buffer pos)
27904 (save-excursion
27905 (goto-char pos)
27906 (org-reveal)))))))
27908 (defun org-uniquify (list)
27909 "Remove duplicate elements from LIST."
27910 (let (res)
27911 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27912 res))
27914 (defun org-delete-all (elts list)
27915 "Remove all elements in ELTS from LIST."
27916 (while elts
27917 (setq list (delete (pop elts) list)))
27918 list)
27920 (defun org-back-over-empty-lines ()
27921 "Move backwards over witespace, to the beginning of the first empty line.
27922 Returns the number o empty lines passed."
27923 (let ((pos (point)))
27924 (skip-chars-backward " \t\n\r")
27925 (beginning-of-line 2)
27926 (goto-char (min (point) pos))
27927 (count-lines (point) pos)))
27929 (defun org-skip-whitespace ()
27930 (skip-chars-forward " \t\n\r"))
27932 (defun org-point-in-group (point group &optional context)
27933 "Check if POINT is in match-group GROUP.
27934 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27935 match. If the match group does ot exist or point is not inside it,
27936 return nil."
27937 (and (match-beginning group)
27938 (>= point (match-beginning group))
27939 (<= point (match-end group))
27940 (if context
27941 (list context (match-beginning group) (match-end group))
27942 t)))
27944 (defun org-switch-to-buffer-other-window (&rest args)
27945 "Switch to buffer in a second window on the current frame.
27946 In particular, do not allow pop-up frames."
27947 (let (pop-up-frames special-display-buffer-names special-display-regexps
27948 special-display-function)
27949 (apply 'switch-to-buffer-other-window args)))
27951 (defun org-combine-plists (&rest plists)
27952 "Create a single property list from all plists in PLISTS.
27953 The process starts by copying the first list, and then setting properties
27954 from the other lists. Settings in the last list are the most significant
27955 ones and overrule settings in the other lists."
27956 (let ((rtn (copy-sequence (pop plists)))
27957 p v ls)
27958 (while plists
27959 (setq ls (pop plists))
27960 (while ls
27961 (setq p (pop ls) v (pop ls))
27962 (setq rtn (plist-put rtn p v))))
27963 rtn))
27965 (defun org-move-line-down (arg)
27966 "Move the current line down. With prefix argument, move it past ARG lines."
27967 (interactive "p")
27968 (let ((col (current-column))
27969 beg end pos)
27970 (beginning-of-line 1) (setq beg (point))
27971 (beginning-of-line 2) (setq end (point))
27972 (beginning-of-line (+ 1 arg))
27973 (setq pos (move-marker (make-marker) (point)))
27974 (insert (delete-and-extract-region beg end))
27975 (goto-char pos)
27976 (move-to-column col)))
27978 (defun org-move-line-up (arg)
27979 "Move the current line up. With prefix argument, move it past ARG lines."
27980 (interactive "p")
27981 (let ((col (current-column))
27982 beg end pos)
27983 (beginning-of-line 1) (setq beg (point))
27984 (beginning-of-line 2) (setq end (point))
27985 (beginning-of-line (- arg))
27986 (setq pos (move-marker (make-marker) (point)))
27987 (insert (delete-and-extract-region beg end))
27988 (goto-char pos)
27989 (move-to-column col)))
27991 (defun org-replace-escapes (string table)
27992 "Replace %-escapes in STRING with values in TABLE.
27993 TABLE is an association list with keys like \"%a\" and string values.
27994 The sequences in STRING may contain normal field width and padding information,
27995 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27996 so values can contain further %-escapes if they are define later in TABLE."
27997 (let ((case-fold-search nil)
27998 e re rpl)
27999 (while (setq e (pop table))
28000 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28001 (while (string-match re string)
28002 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28003 (cdr e)))
28004 (setq string (replace-match rpl t t string))))
28005 string))
28008 (defun org-sublist (list start end)
28009 "Return a section of LIST, from START to END.
28010 Counting starts at 1."
28011 (let (rtn (c start))
28012 (setq list (nthcdr (1- start) list))
28013 (while (and list (<= c end))
28014 (push (pop list) rtn)
28015 (setq c (1+ c)))
28016 (nreverse rtn)))
28018 (defun org-find-base-buffer-visiting (file)
28019 "Like `find-buffer-visiting' but alway return the base buffer and
28020 not an indirect buffer"
28021 (let ((buf (find-buffer-visiting file)))
28022 (if buf
28023 (or (buffer-base-buffer buf) buf)
28024 nil)))
28026 (defun org-image-file-name-regexp ()
28027 "Return regexp matching the file names of images."
28028 (if (fboundp 'image-file-name-regexp)
28029 (image-file-name-regexp)
28030 (let ((image-file-name-extensions
28031 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28032 "xbm" "xpm" "pbm" "pgm" "ppm")))
28033 (concat "\\."
28034 (regexp-opt (nconc (mapcar 'upcase
28035 image-file-name-extensions)
28036 image-file-name-extensions)
28038 "\\'"))))
28040 (defun org-file-image-p (file)
28041 "Return non-nil if FILE is an image."
28042 (save-match-data
28043 (string-match (org-image-file-name-regexp) file)))
28045 ;;; Paragraph filling stuff.
28046 ;; We want this to be just right, so use the full arsenal.
28048 (defun org-indent-line-function ()
28049 "Indent line like previous, but further if previous was headline or item."
28050 (interactive)
28051 (let* ((pos (point))
28052 (itemp (org-at-item-p))
28053 column bpos bcol tpos tcol bullet btype bullet-type)
28054 ;; Find the previous relevant line
28055 (beginning-of-line 1)
28056 (cond
28057 ((looking-at "#") (setq column 0))
28058 ((looking-at "\\*+ ") (setq column 0))
28060 (beginning-of-line 0)
28061 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28062 (beginning-of-line 0))
28063 (cond
28064 ((looking-at "\\*+[ \t]+")
28065 (goto-char (match-end 0))
28066 (setq column (current-column)))
28067 ((org-in-item-p)
28068 (org-beginning-of-item)
28069 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28070 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28071 (setq bpos (match-beginning 1) tpos (match-end 0)
28072 bcol (progn (goto-char bpos) (current-column))
28073 tcol (progn (goto-char tpos) (current-column))
28074 bullet (match-string 1)
28075 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28076 (if (not itemp)
28077 (setq column tcol)
28078 (goto-char pos)
28079 (beginning-of-line 1)
28080 (if (looking-at "\\S-")
28081 (progn
28082 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28083 (setq bullet (match-string 1)
28084 btype (if (string-match "[0-9]" bullet) "n" bullet))
28085 (setq column (if (equal btype bullet-type) bcol tcol)))
28086 (setq column (org-get-indentation)))))
28087 (t (setq column (org-get-indentation))))))
28088 (goto-char pos)
28089 (if (<= (current-column) (current-indentation))
28090 (indent-line-to column)
28091 (save-excursion (indent-line-to column)))
28092 (setq column (current-column))
28093 (beginning-of-line 1)
28094 (if (looking-at
28095 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28096 (replace-match (concat "\\1" (format org-property-format
28097 (match-string 2) (match-string 3)))
28098 t nil))
28099 (move-to-column column)))
28101 (defun org-set-autofill-regexps ()
28102 (interactive)
28103 ;; In the paragraph separator we include headlines, because filling
28104 ;; text in a line directly attached to a headline would otherwise
28105 ;; fill the headline as well.
28106 (org-set-local 'comment-start-skip "^#+[ \t]*")
28107 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28108 ;; The paragraph starter includes hand-formatted lists.
28109 (org-set-local 'paragraph-start
28110 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28111 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28112 ;; But only if the user has not turned off tables or fixed-width regions
28113 (org-set-local
28114 'auto-fill-inhibit-regexp
28115 (concat "\\*+ \\|#\\+"
28116 "\\|[ \t]*" org-keyword-time-regexp
28117 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28118 (concat
28119 "\\|[ \t]*["
28120 (if org-enable-table-editor "|" "")
28121 (if org-enable-fixed-width-editor ":" "")
28122 "]"))))
28123 ;; We use our own fill-paragraph function, to make sure that tables
28124 ;; and fixed-width regions are not wrapped. That function will pass
28125 ;; through to `fill-paragraph' when appropriate.
28126 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28127 ; Adaptive filling: To get full control, first make sure that
28128 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28129 (org-set-local 'adaptive-fill-regexp "\000")
28130 (org-set-local 'adaptive-fill-function
28131 'org-adaptive-fill-function)
28132 (org-set-local
28133 'align-mode-rules-list
28134 '((org-in-buffer-settings
28135 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28136 (modes . '(org-mode))))))
28138 (defun org-fill-paragraph (&optional justify)
28139 "Re-align a table, pass through to fill-paragraph if no table."
28140 (let ((table-p (org-at-table-p))
28141 (table.el-p (org-at-table.el-p)))
28142 (cond ((and (equal (char-after (point-at-bol)) ?*)
28143 (save-excursion (goto-char (point-at-bol))
28144 (looking-at outline-regexp)))
28145 t) ; skip headlines
28146 (table.el-p t) ; skip table.el tables
28147 (table-p (org-table-align) t) ; align org-mode tables
28148 (t nil)))) ; call paragraph-fill
28150 ;; For reference, this is the default value of adaptive-fill-regexp
28151 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28153 (defun org-adaptive-fill-function ()
28154 "Return a fill prefix for org-mode files.
28155 In particular, this makes sure hanging paragraphs for hand-formatted lists
28156 work correctly."
28157 (cond ((looking-at "#[ \t]+")
28158 (match-string 0))
28159 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28160 (save-excursion
28161 (goto-char (match-end 0))
28162 (make-string (current-column) ?\ )))
28163 (t nil)))
28165 ;;;; Functions extending outline functionality
28168 (defun org-beginning-of-line (&optional arg)
28169 "Go to the beginning of the current line. If that is invisible, continue
28170 to a visible line beginning. This makes the function of C-a more intuitive.
28171 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28172 first attempt, and only move to after the tags when the cursor is already
28173 beyond the end of the headline."
28174 (interactive "P")
28175 (let ((pos (point)))
28176 (beginning-of-line 1)
28177 (if (bobp)
28179 (backward-char 1)
28180 (if (org-invisible-p)
28181 (while (and (not (bobp)) (org-invisible-p))
28182 (backward-char 1)
28183 (beginning-of-line 1))
28184 (forward-char 1)))
28185 (when org-special-ctrl-a/e
28186 (cond
28187 ((and (looking-at org-todo-line-regexp)
28188 (= (char-after (match-end 1)) ?\ ))
28189 (goto-char
28190 (if (eq org-special-ctrl-a/e t)
28191 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28192 ((= pos (point)) (match-beginning 3))
28193 (t (point)))
28194 (cond ((> pos (point)) (point))
28195 ((not (eq last-command this-command)) (point))
28196 (t (match-beginning 3))))))
28197 ((org-at-item-p)
28198 (goto-char
28199 (if (eq org-special-ctrl-a/e t)
28200 (cond ((> pos (match-end 4)) (match-end 4))
28201 ((= pos (point)) (match-end 4))
28202 (t (point)))
28203 (cond ((> pos (point)) (point))
28204 ((not (eq last-command this-command)) (point))
28205 (t (match-end 4))))))))))
28207 (defun org-end-of-line (&optional arg)
28208 "Go to the end of the line.
28209 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28210 first attempt, and only move to after the tags when the cursor is already
28211 beyond the end of the headline."
28212 (interactive "P")
28213 (if (or (not org-special-ctrl-a/e)
28214 (not (org-on-heading-p)))
28215 (end-of-line arg)
28216 (let ((pos (point)))
28217 (beginning-of-line 1)
28218 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28219 (if (eq org-special-ctrl-a/e t)
28220 (if (or (< pos (match-beginning 1))
28221 (= pos (match-end 0)))
28222 (goto-char (match-beginning 1))
28223 (goto-char (match-end 0)))
28224 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28225 (goto-char (match-end 0))
28226 (goto-char (match-beginning 1))))
28227 (end-of-line arg)))))
28229 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28230 (define-key org-mode-map "\C-e" 'org-end-of-line)
28232 (defun org-kill-line (&optional arg)
28233 "Kill line, to tags or end of line."
28234 (interactive "P")
28235 (cond
28236 ((or (not org-special-ctrl-k)
28237 (bolp)
28238 (not (org-on-heading-p)))
28239 (call-interactively 'kill-line))
28240 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28241 (kill-region (point) (match-beginning 1))
28242 (org-set-tags nil t))
28243 (t (kill-region (point) (point-at-eol)))))
28245 (define-key org-mode-map "\C-k" 'org-kill-line)
28247 (defun org-invisible-p ()
28248 "Check if point is at a character currently not visible."
28249 ;; Early versions of noutline don't have `outline-invisible-p'.
28250 (if (fboundp 'outline-invisible-p)
28251 (outline-invisible-p)
28252 (get-char-property (point) 'invisible)))
28254 (defun org-invisible-p2 ()
28255 "Check if point is at a character currently not visible."
28256 (save-excursion
28257 (if (and (eolp) (not (bobp))) (backward-char 1))
28258 ;; Early versions of noutline don't have `outline-invisible-p'.
28259 (if (fboundp 'outline-invisible-p)
28260 (outline-invisible-p)
28261 (get-char-property (point) 'invisible))))
28263 (defalias 'org-back-to-heading 'outline-back-to-heading)
28264 (defalias 'org-on-heading-p 'outline-on-heading-p)
28265 (defalias 'org-at-heading-p 'outline-on-heading-p)
28266 (defun org-at-heading-or-item-p ()
28267 (or (org-on-heading-p) (org-at-item-p)))
28269 (defun org-on-target-p ()
28270 (or (org-in-regexp org-radio-target-regexp)
28271 (org-in-regexp org-target-regexp)))
28273 (defun org-up-heading-all (arg)
28274 "Move to the heading line of which the present line is a subheading.
28275 This function considers both visible and invisible heading lines.
28276 With argument, move up ARG levels."
28277 (if (fboundp 'outline-up-heading-all)
28278 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28279 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28281 (defun org-up-heading-safe ()
28282 "Move to the heading line of which the present line is a subheading.
28283 This version will not throw an error. It will return the level of the
28284 headline found, or nil if no higher level is found."
28285 (let ((pos (point)) start-level level
28286 (re (concat "^" outline-regexp)))
28287 (catch 'exit
28288 (outline-back-to-heading t)
28289 (setq start-level (funcall outline-level))
28290 (if (equal start-level 1) (throw 'exit nil))
28291 (while (re-search-backward re nil t)
28292 (setq level (funcall outline-level))
28293 (if (< level start-level) (throw 'exit level)))
28294 nil)))
28296 (defun org-first-sibling-p ()
28297 "Is this heading the first child of its parents?"
28298 (interactive)
28299 (let ((re (concat "^" outline-regexp))
28300 level l)
28301 (unless (org-at-heading-p t)
28302 (error "Not at a heading"))
28303 (setq level (funcall outline-level))
28304 (save-excursion
28305 (if (not (re-search-backward re nil t))
28307 (setq l (funcall outline-level))
28308 (< l level)))))
28310 (defun org-goto-sibling (&optional previous)
28311 "Goto the next sibling, even if it is invisible.
28312 When PREVIOUS is set, go to the previous sibling instead. Returns t
28313 when a sibling was found. When none is found, return nil and don't
28314 move point."
28315 (let ((fun (if previous 're-search-backward 're-search-forward))
28316 (pos (point))
28317 (re (concat "^" outline-regexp))
28318 level l)
28319 (when (condition-case nil (org-back-to-heading t) (error nil))
28320 (setq level (funcall outline-level))
28321 (catch 'exit
28322 (or previous (forward-char 1))
28323 (while (funcall fun re nil t)
28324 (setq l (funcall outline-level))
28325 (when (< l level) (goto-char pos) (throw 'exit nil))
28326 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28327 (goto-char pos)
28328 nil))))
28330 (defun org-show-siblings ()
28331 "Show all siblings of the current headline."
28332 (save-excursion
28333 (while (org-goto-sibling) (org-flag-heading nil)))
28334 (save-excursion
28335 (while (org-goto-sibling 'previous)
28336 (org-flag-heading nil))))
28338 (defun org-show-hidden-entry ()
28339 "Show an entry where even the heading is hidden."
28340 (save-excursion
28341 (org-show-entry)))
28343 (defun org-flag-heading (flag &optional entry)
28344 "Flag the current heading. FLAG non-nil means make invisible.
28345 When ENTRY is non-nil, show the entire entry."
28346 (save-excursion
28347 (org-back-to-heading t)
28348 ;; Check if we should show the entire entry
28349 (if entry
28350 (progn
28351 (org-show-entry)
28352 (save-excursion
28353 (and (outline-next-heading)
28354 (org-flag-heading nil))))
28355 (outline-flag-region (max (point-min) (1- (point)))
28356 (save-excursion (outline-end-of-heading) (point))
28357 flag))))
28359 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28360 ;; This is an exact copy of the original function, but it uses
28361 ;; `org-back-to-heading', to make it work also in invisible
28362 ;; trees. And is uses an invisible-OK argument.
28363 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28364 (org-back-to-heading invisible-OK)
28365 (let ((first t)
28366 (level (funcall outline-level)))
28367 (while (and (not (eobp))
28368 (or first (> (funcall outline-level) level)))
28369 (setq first nil)
28370 (outline-next-heading))
28371 (unless to-heading
28372 (if (memq (preceding-char) '(?\n ?\^M))
28373 (progn
28374 ;; Go to end of line before heading
28375 (forward-char -1)
28376 (if (memq (preceding-char) '(?\n ?\^M))
28377 ;; leave blank line before heading
28378 (forward-char -1))))))
28379 (point))
28381 (defun org-show-subtree ()
28382 "Show everything after this heading at deeper levels."
28383 (outline-flag-region
28384 (point)
28385 (save-excursion
28386 (outline-end-of-subtree) (outline-next-heading) (point))
28387 nil))
28389 (defun org-show-entry ()
28390 "Show the body directly following this heading.
28391 Show the heading too, if it is currently invisible."
28392 (interactive)
28393 (save-excursion
28394 (condition-case nil
28395 (progn
28396 (org-back-to-heading t)
28397 (outline-flag-region
28398 (max (point-min) (1- (point)))
28399 (save-excursion
28400 (re-search-forward
28401 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28402 (or (match-beginning 1) (point-max)))
28403 nil))
28404 (error nil))))
28406 (defun org-make-options-regexp (kwds)
28407 "Make a regular expression for keyword lines."
28408 (concat
28410 "#?[ \t]*\\+\\("
28411 (mapconcat 'regexp-quote kwds "\\|")
28412 "\\):[ \t]*"
28413 "\\(.+\\)"))
28415 ;; Make isearch reveal the necessary context
28416 (defun org-isearch-end ()
28417 "Reveal context after isearch exits."
28418 (when isearch-success ; only if search was successful
28419 (if (featurep 'xemacs)
28420 ;; Under XEmacs, the hook is run in the correct place,
28421 ;; we directly show the context.
28422 (org-show-context 'isearch)
28423 ;; In Emacs the hook runs *before* restoring the overlays.
28424 ;; So we have to use a one-time post-command-hook to do this.
28425 ;; (Emacs 22 has a special variable, see function `org-mode')
28426 (unless (and (boundp 'isearch-mode-end-hook-quit)
28427 isearch-mode-end-hook-quit)
28428 ;; Only when the isearch was not quitted.
28429 (org-add-hook 'post-command-hook 'org-isearch-post-command
28430 'append 'local)))))
28432 (defun org-isearch-post-command ()
28433 "Remove self from hook, and show context."
28434 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28435 (org-show-context 'isearch))
28438 ;;;; Integration with and fixes for other packages
28440 ;;; Imenu support
28442 (defvar org-imenu-markers nil
28443 "All markers currently used by Imenu.")
28444 (make-variable-buffer-local 'org-imenu-markers)
28446 (defun org-imenu-new-marker (&optional pos)
28447 "Return a new marker for use by Imenu, and remember the marker."
28448 (let ((m (make-marker)))
28449 (move-marker m (or pos (point)))
28450 (push m org-imenu-markers)
28453 (defun org-imenu-get-tree ()
28454 "Produce the index for Imenu."
28455 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28456 (setq org-imenu-markers nil)
28457 (let* ((n org-imenu-depth)
28458 (re (concat "^" outline-regexp))
28459 (subs (make-vector (1+ n) nil))
28460 (last-level 0)
28461 m tree level head)
28462 (save-excursion
28463 (save-restriction
28464 (widen)
28465 (goto-char (point-max))
28466 (while (re-search-backward re nil t)
28467 (setq level (org-reduced-level (funcall outline-level)))
28468 (when (<= level n)
28469 (looking-at org-complex-heading-regexp)
28470 (setq head (org-match-string-no-properties 4)
28471 m (org-imenu-new-marker))
28472 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28473 (if (>= level last-level)
28474 (push (cons head m) (aref subs level))
28475 (push (cons head (aref subs (1+ level))) (aref subs level))
28476 (loop for i from (1+ level) to n do (aset subs i nil)))
28477 (setq last-level level)))))
28478 (aref subs 1)))
28480 (eval-after-load "imenu"
28481 '(progn
28482 (add-hook 'imenu-after-jump-hook
28483 (lambda () (org-show-context 'org-goto)))))
28485 ;; Speedbar support
28487 (defun org-speedbar-set-agenda-restriction ()
28488 "Restrict future agenda commands to the location at point in speedbar.
28489 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28490 (interactive)
28491 (let (p m tp np dir txt w)
28492 (cond
28493 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28494 'org-imenu t))
28495 (setq m (get-text-property p 'org-imenu-marker))
28496 (save-excursion
28497 (save-restriction
28498 (set-buffer (marker-buffer m))
28499 (goto-char m)
28500 (org-agenda-set-restriction-lock 'subtree))))
28501 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28502 'speedbar-function 'speedbar-find-file))
28503 (setq tp (previous-single-property-change
28504 (1+ p) 'speedbar-function)
28505 np (next-single-property-change
28506 tp 'speedbar-function)
28507 dir (speedbar-line-directory)
28508 txt (buffer-substring-no-properties (or tp (point-min))
28509 (or np (point-max))))
28510 (save-excursion
28511 (save-restriction
28512 (set-buffer (find-file-noselect
28513 (let ((default-directory dir))
28514 (expand-file-name txt))))
28515 (unless (org-mode-p)
28516 (error "Cannot restrict to non-Org-mode file"))
28517 (org-agenda-set-restriction-lock 'file))))
28518 (t (error "Don't know how to restrict Org-mode's agenda")))
28519 (org-move-overlay org-speedbar-restriction-lock-overlay
28520 (point-at-bol) (point-at-eol))
28521 (setq current-prefix-arg nil)
28522 (org-agenda-maybe-redo)))
28524 (eval-after-load "speedbar"
28525 '(progn
28526 (speedbar-add-supported-extension ".org")
28527 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28528 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28529 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28530 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28531 (add-hook 'speedbar-visiting-tag-hook
28532 (lambda () (org-show-context 'org-goto)))))
28535 ;;; Fixes and Hacks
28537 ;; Make flyspell not check words in links, to not mess up our keymap
28538 (defun org-mode-flyspell-verify ()
28539 "Don't let flyspell put overlays at active buttons."
28540 (not (get-text-property (point) 'keymap)))
28542 ;; Make `bookmark-jump' show the jump location if it was hidden.
28543 (eval-after-load "bookmark"
28544 '(if (boundp 'bookmark-after-jump-hook)
28545 ;; We can use the hook
28546 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28547 ;; Hook not available, use advice
28548 (defadvice bookmark-jump (after org-make-visible activate)
28549 "Make the position visible."
28550 (org-bookmark-jump-unhide))))
28552 (defun org-bookmark-jump-unhide ()
28553 "Unhide the current position, to show the bookmark location."
28554 (and (org-mode-p)
28555 (or (org-invisible-p)
28556 (save-excursion (goto-char (max (point-min) (1- (point))))
28557 (org-invisible-p)))
28558 (org-show-context 'bookmark-jump)))
28560 ;; Fix a bug in htmlize where there are text properties (face nil)
28561 (eval-after-load "htmlize"
28562 '(progn
28563 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28564 "Make sure there are no nil faces"
28565 (setq ad-return-value (delq nil ad-return-value)))))
28567 ;; Make session.el ignore our circular variable
28568 (eval-after-load "session"
28569 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28571 ;;;; Experimental code
28573 (defun org-closed-in-range ()
28574 "Sparse tree of items closed in a certain time range.
28575 Still experimental, may disappear in the future."
28576 (interactive)
28577 ;; Get the time interval from the user.
28578 (let* ((time1 (time-to-seconds
28579 (org-read-date nil 'to-time nil "Starting date: ")))
28580 (time2 (time-to-seconds
28581 (org-read-date nil 'to-time nil "End date:")))
28582 ;; callback function
28583 (callback (lambda ()
28584 (let ((time
28585 (time-to-seconds
28586 (apply 'encode-time
28587 (org-parse-time-string
28588 (match-string 1))))))
28589 ;; check if time in interval
28590 (and (>= time time1) (<= time time2))))))
28591 ;; make tree, check each match with the callback
28592 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28594 ;;;; Finish up
28596 (provide 'org)
28598 (run-hooks 'org-load-hook)
28600 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28601 ;;; org.el ends here