Merge branch 'master' of git+ssh://repo.or.cz/srv/git/org-mode
[org-mode.git] / org.el
blob722adc65b51f0e379837890e12ab1fefde23e895
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 nil
155 "Hook that is run after org.el has been loaded."
156 :group 'org
157 :type 'hook)
159 (defcustom org-default-extensions '(org-irc)
160 "Extensions that should always be loaded together with org.el.
161 If the description starts with <A>, this means the extension
162 will be autoloaded when needed, preloading is not necessary."
163 :group 'org
164 :type
165 '(set :greedy t
166 (const :tag " Mouse support (org-mouse.el)" org-mouse)
167 (const :tag "<A> Publishing (org-publish.el)" org-publish)
168 (const :tag "<A> LaTeX export (org-export-latex.el)" org-export-latex)
169 (const :tag " IRC/ERC links (org-irc.el)" org-irc)
170 (const :tag " Apple Mail message links under OS X (org-mac-message.el)" org-mac-message)))
172 (defun org-load-default-extensions ()
173 "Load all extensions listed in `org-default-extensions'."
174 (mapc (lambda (ext)
175 (condition-case nil (require ext)
176 (error (message "Problems while trying to load feature `%s'" ext))))
177 org-default-extensions))
179 (eval-after-load "org" '(org-load-default-extensions))
181 ;; FIXME: Needs a separate group...
182 (defcustom org-completion-fallback-command 'hippie-expand
183 "The expansion command called by \\[org-complete] in normal context.
184 Normal means, no org-mode-specific context."
185 :group 'org
186 :type 'function)
188 (defgroup org-startup nil
189 "Options concerning startup of Org-mode."
190 :tag "Org Startup"
191 :group 'org)
193 (defcustom org-startup-folded t
194 "Non-nil means, entering Org-mode will switch to OVERVIEW.
195 This can also be configured on a per-file basis by adding one of
196 the following lines anywhere in the buffer:
198 #+STARTUP: fold
199 #+STARTUP: nofold
200 #+STARTUP: content"
201 :group 'org-startup
202 :type '(choice
203 (const :tag "nofold: show all" nil)
204 (const :tag "fold: overview" t)
205 (const :tag "content: all headlines" content)))
207 (defcustom org-startup-truncated t
208 "Non-nil means, entering Org-mode will set `truncate-lines'.
209 This is useful since some lines containing links can be very long and
210 uninteresting. Also tables look terrible when wrapped."
211 :group 'org-startup
212 :type 'boolean)
214 (defcustom org-startup-align-all-tables nil
215 "Non-nil means, align all tables when visiting a file.
216 This is useful when the column width in tables is forced with <N> cookies
217 in table fields. Such tables will look correct only after the first re-align.
218 This can also be configured on a per-file basis by adding one of
219 the following lines anywhere in the buffer:
220 #+STARTUP: align
221 #+STARTUP: noalign"
222 :group 'org-startup
223 :type 'boolean)
225 (defcustom org-insert-mode-line-in-empty-file nil
226 "Non-nil means insert the first line setting Org-mode in empty files.
227 When the function `org-mode' is called interactively in an empty file, this
228 normally means that the file name does not automatically trigger Org-mode.
229 To ensure that the file will always be in Org-mode in the future, a
230 line enforcing Org-mode will be inserted into the buffer, if this option
231 has been set."
232 :group 'org-startup
233 :type 'boolean)
235 (defcustom org-replace-disputed-keys nil
236 "Non-nil means use alternative key bindings for some keys.
237 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
238 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
239 If you want to use Org-mode together with one of these other modes,
240 or more generally if you would like to move some Org-mode commands to
241 other keys, set this variable and configure the keys with the variable
242 `org-disputed-keys'.
244 This option is only relevant at load-time of Org-mode, and must be set
245 *before* org.el is loaded. Changing it requires a restart of Emacs to
246 become effective."
247 :group 'org-startup
248 :type 'boolean)
250 (if (fboundp 'defvaralias)
251 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
253 (defcustom org-disputed-keys
254 '(([(shift up)] . [(meta p)])
255 ([(shift down)] . [(meta n)])
256 ([(shift left)] . [(meta -)])
257 ([(shift right)] . [(meta +)])
258 ([(control shift right)] . [(meta shift +)])
259 ([(control shift left)] . [(meta shift -)]))
260 "Keys for which Org-mode and other modes compete.
261 This is an alist, cars are the default keys, second element specifies
262 the alternative to use when `org-replace-disputed-keys' is t.
264 Keys can be specified in any syntax supported by `define-key'.
265 The value of this option takes effect only at Org-mode's startup,
266 therefore you'll have to restart Emacs to apply it after changing."
267 :group 'org-startup
268 :type 'alist)
270 (defun org-key (key)
271 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
272 Or return the original if not disputed."
273 (if org-replace-disputed-keys
274 (let* ((nkey (key-description key))
275 (x (org-find-if (lambda (x)
276 (equal (key-description (car x)) nkey))
277 org-disputed-keys)))
278 (if x (cdr x) key))
279 key))
281 (defun org-find-if (predicate seq)
282 (catch 'exit
283 (while seq
284 (if (funcall predicate (car seq))
285 (throw 'exit (car seq))
286 (pop seq)))))
288 (defun org-defkey (keymap key def)
289 "Define a key, possibly translated, as returned by `org-key'."
290 (define-key keymap (org-key key) def))
292 (defcustom org-ellipsis nil
293 "The ellipsis to use in the Org-mode outline.
294 When nil, just use the standard three dots. When a string, use that instead,
295 When a face, use the standart 3 dots, but with the specified face.
296 The change affects only Org-mode (which will then use its own display table).
297 Changing this requires executing `M-x org-mode' in a buffer to become
298 effective."
299 :group 'org-startup
300 :type '(choice (const :tag "Default" nil)
301 (face :tag "Face" :value org-warning)
302 (string :tag "String" :value "...#")))
304 (defvar org-display-table nil
305 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
307 (defgroup org-keywords nil
308 "Keywords in Org-mode."
309 :tag "Org Keywords"
310 :group 'org)
312 (defcustom org-deadline-string "DEADLINE:"
313 "String to mark deadline entries.
314 A deadline is this string, followed by a time stamp. Should be a word,
315 terminated by a colon. You can insert a schedule keyword and
316 a timestamp with \\[org-deadline].
317 Changes become only effective after restarting Emacs."
318 :group 'org-keywords
319 :type 'string)
321 (defcustom org-scheduled-string "SCHEDULED:"
322 "String to mark scheduled TODO entries.
323 A schedule is this string, followed by a time stamp. Should be a word,
324 terminated by a colon. You can insert a schedule keyword and
325 a timestamp with \\[org-schedule].
326 Changes become only effective after restarting Emacs."
327 :group 'org-keywords
328 :type 'string)
330 (defcustom org-closed-string "CLOSED:"
331 "String used as the prefix for timestamps logging closing a TODO entry."
332 :group 'org-keywords
333 :type 'string)
335 (defcustom org-clock-string "CLOCK:"
336 "String used as prefix for timestamps clocking work hours on an item."
337 :group 'org-keywords
338 :type 'string)
340 (defcustom org-comment-string "COMMENT"
341 "Entries starting with this keyword will never be exported.
342 An entry can be toggled between COMMENT and normal with
343 \\[org-toggle-comment].
344 Changes become only effective after restarting Emacs."
345 :group 'org-keywords
346 :type 'string)
348 (defcustom org-quote-string "QUOTE"
349 "Entries starting with this keyword will be exported in fixed-width font.
350 Quoting applies only to the text in the entry following the headline, and does
351 not extend beyond the next headline, even if that is lower level.
352 An entry can be toggled between QUOTE and normal with
353 \\[org-toggle-fixed-width-section]."
354 :group 'org-keywords
355 :type 'string)
357 (defconst org-repeat-re
358 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
359 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
360 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
361 "Regular expression for specifying repeated events.
362 After a match, group 1 contains the repeat expression.")
364 (defgroup org-structure nil
365 "Options concerning the general structure of Org-mode files."
366 :tag "Org Structure"
367 :group 'org)
369 (defgroup org-reveal-location nil
370 "Options about how to make context of a location visible."
371 :tag "Org Reveal Location"
372 :group 'org-structure)
374 (defconst org-context-choice
375 '(choice
376 (const :tag "Always" t)
377 (const :tag "Never" nil)
378 (repeat :greedy t :tag "Individual contexts"
379 (cons
380 (choice :tag "Context"
381 (const agenda)
382 (const org-goto)
383 (const occur-tree)
384 (const tags-tree)
385 (const link-search)
386 (const mark-goto)
387 (const bookmark-jump)
388 (const isearch)
389 (const default))
390 (boolean))))
391 "Contexts for the reveal options.")
393 (defcustom org-show-hierarchy-above '((default . t))
394 "Non-nil means, show full hierarchy when revealing a location.
395 Org-mode often shows locations in an org-mode file which might have
396 been invisible before. When this is set, the hierarchy of headings
397 above the exposed location is shown.
398 Turning this off for example for sparse trees makes them very compact.
399 Instead of t, this can also be an alist specifying this option for different
400 contexts. Valid contexts are
401 agenda when exposing an entry from the agenda
402 org-goto when using the command `org-goto' on key C-c C-j
403 occur-tree when using the command `org-occur' on key C-c /
404 tags-tree when constructing a sparse tree based on tags matches
405 link-search when exposing search matches associated with a link
406 mark-goto when exposing the jump goal of a mark
407 bookmark-jump when exposing a bookmark location
408 isearch when exiting from an incremental search
409 default default for all contexts not set explicitly"
410 :group 'org-reveal-location
411 :type org-context-choice)
413 (defcustom org-show-following-heading '((default . nil))
414 "Non-nil means, show following heading when revealing a location.
415 Org-mode often shows locations in an org-mode file which might have
416 been invisible before. When this is set, the heading following the
417 match is shown.
418 Turning this off for example for sparse trees makes them very compact,
419 but makes it harder to edit the location of the match. In such a case,
420 use the command \\[org-reveal] to show more context.
421 Instead of t, this can also be an alist specifying this option for different
422 contexts. See `org-show-hierarchy-above' for valid contexts."
423 :group 'org-reveal-location
424 :type org-context-choice)
426 (defcustom org-show-siblings '((default . nil) (isearch t))
427 "Non-nil means, show all sibling heading when revealing a location.
428 Org-mode often shows locations in an org-mode file which might have
429 been invisible before. When this is set, the sibling of the current entry
430 heading are all made visible. If `org-show-hierarchy-above' is t,
431 the same happens on each level of the hierarchy above the current entry.
433 By default this is on for the isearch context, off for all other contexts.
434 Turning this off for example for sparse trees makes them very compact,
435 but makes it harder to edit the location of the match. In such a case,
436 use the command \\[org-reveal] to show more context.
437 Instead of t, this can also be an alist specifying this option for different
438 contexts. See `org-show-hierarchy-above' for valid contexts."
439 :group 'org-reveal-location
440 :type org-context-choice)
442 (defcustom org-show-entry-below '((default . nil))
443 "Non-nil means, show the entry below a headline when revealing a location.
444 Org-mode often shows locations in an org-mode file which might have
445 been invisible before. When this is set, the text below the headline that is
446 exposed is also shown.
448 By default this is off for all contexts.
449 Instead of t, this can also be an alist specifying this option for different
450 contexts. See `org-show-hierarchy-above' for valid contexts."
451 :group 'org-reveal-location
452 :type org-context-choice)
454 (defgroup org-cycle nil
455 "Options concerning visibility cycling in Org-mode."
456 :tag "Org Cycle"
457 :group 'org-structure)
459 (defcustom org-drawers '("PROPERTIES" "CLOCK")
460 "Names of drawers. Drawers are not opened by cycling on the headline above.
461 Drawers only open with a TAB on the drawer line itself. A drawer looks like
462 this:
463 :DRAWERNAME:
464 .....
465 :END:
466 The drawer \"PROPERTIES\" is special for capturing properties through
467 the property API.
469 Drawers can be defined on the per-file basis with a line like:
471 #+DRAWERS: HIDDEN STATE PROPERTIES"
472 :group 'org-structure
473 :type '(repeat (string :tag "Drawer Name")))
475 (defcustom org-cycle-global-at-bob nil
476 "Cycle globally if cursor is at beginning of buffer and not at a headline.
477 This makes it possible to do global cycling without having to use S-TAB or
478 C-u TAB. For this special case to work, the first line of the buffer
479 must not be a headline - it may be empty ot some other text. When used in
480 this way, `org-cycle-hook' is disables temporarily, to make sure the
481 cursor stays at the beginning of the buffer.
482 When this option is nil, don't do anything special at the beginning
483 of the buffer."
484 :group 'org-cycle
485 :type 'boolean)
487 (defcustom org-cycle-emulate-tab t
488 "Where should `org-cycle' emulate TAB.
489 nil Never
490 white Only in completely white lines
491 whitestart Only at the beginning of lines, before the first non-white char
492 t Everywhere except in headlines
493 exc-hl-bol Everywhere except at the start of a headline
494 If TAB is used in a place where it does not emulate TAB, the current subtree
495 visibility is cycled."
496 :group 'org-cycle
497 :type '(choice (const :tag "Never" nil)
498 (const :tag "Only in completely white lines" white)
499 (const :tag "Before first char in a line" whitestart)
500 (const :tag "Everywhere except in headlines" t)
501 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
504 (defcustom org-cycle-separator-lines 2
505 "Number of empty lines needed to keep an empty line between collapsed trees.
506 If you leave an empty line between the end of a subtree and the following
507 headline, this empty line is hidden when the subtree is folded.
508 Org-mode will leave (exactly) one empty line visible if the number of
509 empty lines is equal or larger to the number given in this variable.
510 So the default 2 means, at least 2 empty lines after the end of a subtree
511 are needed to produce free space between a collapsed subtree and the
512 following headline.
514 Special case: when 0, never leave empty lines in collapsed view."
515 :group 'org-cycle
516 :type 'integer)
518 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
519 org-cycle-hide-drawers
520 org-cycle-show-empty-lines
521 org-optimize-window-after-visibility-change)
522 "Hook that is run after `org-cycle' has changed the buffer visibility.
523 The function(s) in this hook must accept a single argument which indicates
524 the new state that was set by the most recent `org-cycle' command. The
525 argument is a symbol. After a global state change, it can have the values
526 `overview', `content', or `all'. After a local state change, it can have
527 the values `folded', `children', or `subtree'."
528 :group 'org-cycle
529 :type 'hook)
531 (defgroup org-edit-structure nil
532 "Options concerning structure editing in Org-mode."
533 :tag "Org Edit Structure"
534 :group 'org-structure)
536 (defcustom org-odd-levels-only nil
537 "Non-nil means, skip even levels and only use odd levels for the outline.
538 This has the effect that two stars are being added/taken away in
539 promotion/demotion commands. It also influences how levels are
540 handled by the exporters.
541 Changing it requires restart of `font-lock-mode' to become effective
542 for fontification also in regions already fontified.
543 You may also set this on a per-file basis by adding one of the following
544 lines to the buffer:
546 #+STARTUP: odd
547 #+STARTUP: oddeven"
548 :group 'org-edit-structure
549 :group 'org-font-lock
550 :type 'boolean)
552 (defcustom org-adapt-indentation t
553 "Non-nil means, adapt indentation when promoting and demoting.
554 When this is set and the *entire* text in an entry is indented, the
555 indentation is increased by one space in a demotion command, and
556 decreased by one in a promotion command. If any line in the entry
557 body starts at column 0, indentation is not changed at all."
558 :group 'org-edit-structure
559 :type 'boolean)
561 (defcustom org-special-ctrl-a/e nil
562 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
563 When t, `C-a' will bring back the cursor to the beginning of the
564 headline text, i.e. after the stars and after a possible TODO keyword.
565 In an item, this will be the position after the bullet.
566 When the cursor is already at that position, another `C-a' will bring
567 it to the beginning of the line.
568 `C-e' will jump to the end of the headline, ignoring the presence of tags
569 in the headline. A second `C-e' will then jump to the true end of the
570 line, after any tags.
571 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
572 and only a directly following, identical keypress will bring the cursor
573 to the special positions."
574 :group 'org-edit-structure
575 :type '(choice
576 (const :tag "off" nil)
577 (const :tag "after bullet first" t)
578 (const :tag "border first" reversed)))
580 (if (fboundp 'defvaralias)
581 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
583 (defcustom org-special-ctrl-k nil
584 "Non-nil means `C-k' will behave specially in headlines.
585 When nil, `C-k' will call the default `kill-line' command.
586 When t, the following will happen while the cursor is in the headline:
588 - When the cursor is at the beginning of a headline, kill the entire
589 line and possible the folded subtree below the line.
590 - When in the middle of the headline text, kill the headline up to the tags.
591 - When after the headline text, kill the tags."
592 :group 'org-edit-structure
593 :type 'boolean)
595 (defcustom org-M-RET-may-split-line '((default . t))
596 "Non-nil means, M-RET will split the line at the cursor position.
597 When nil, it will go to the end of the line before making a
598 new line.
599 You may also set this option in a different way for different
600 contexts. Valid contexts are:
602 headline when creating a new headline
603 item when creating a new item
604 table in a table field
605 default the value to be used for all contexts not explicitly
606 customized"
607 :group 'org-structure
608 :group 'org-table
609 :type '(choice
610 (const :tag "Always" t)
611 (const :tag "Never" nil)
612 (repeat :greedy t :tag "Individual contexts"
613 (cons
614 (choice :tag "Context"
615 (const headline)
616 (const item)
617 (const table)
618 (const default))
619 (boolean)))))
622 (defcustom org-blank-before-new-entry '((heading . nil)
623 (plain-list-item . nil))
624 "Should `org-insert-heading' leave a blank line before new heading/item?
625 The value is an alist, with `heading' and `plain-list-item' as car,
626 and a boolean flag as cdr."
627 :group 'org-edit-structure
628 :type '(list
629 (cons (const heading) (boolean))
630 (cons (const plain-list-item) (boolean))))
632 (defcustom org-insert-heading-hook nil
633 "Hook being run after inserting a new heading."
634 :group 'org-edit-structure
635 :type 'hook)
637 (defcustom org-enable-fixed-width-editor t
638 "Non-nil means, lines starting with \":\" are treated as fixed-width.
639 This currently only means, they are never auto-wrapped.
640 When nil, such lines will be treated like ordinary lines.
641 See also the QUOTE keyword."
642 :group 'org-edit-structure
643 :type 'boolean)
645 (defcustom org-goto-auto-isearch t
646 "Non-nil means, typing characters in org-goto starts incremental search."
647 :group 'org-edit-structure
648 :type 'boolean)
650 (defgroup org-sparse-trees nil
651 "Options concerning sparse trees in Org-mode."
652 :tag "Org Sparse Trees"
653 :group 'org-structure)
655 (defcustom org-highlight-sparse-tree-matches t
656 "Non-nil means, highlight all matches that define a sparse tree.
657 The highlights will automatically disappear the next time the buffer is
658 changed by an edit command."
659 :group 'org-sparse-trees
660 :type 'boolean)
662 (defcustom org-remove-highlights-with-change t
663 "Non-nil means, any change to the buffer will remove temporary highlights.
664 Such highlights are created by `org-occur' and `org-clock-display'.
665 When nil, `C-c C-c needs to be used to get rid of the highlights.
666 The highlights created by `org-preview-latex-fragment' always need
667 `C-c C-c' to be removed."
668 :group 'org-sparse-trees
669 :group 'org-time
670 :type 'boolean)
673 (defcustom org-occur-hook '(org-first-headline-recenter)
674 "Hook that is run after `org-occur' has constructed a sparse tree.
675 This can be used to recenter the window to show as much of the structure
676 as possible."
677 :group 'org-sparse-trees
678 :type 'hook)
680 (defgroup org-plain-lists nil
681 "Options concerning plain lists in Org-mode."
682 :tag "Org Plain lists"
683 :group 'org-structure)
685 (defcustom org-cycle-include-plain-lists nil
686 "Non-nil means, include plain lists into visibility cycling.
687 This means that during cycling, plain list items will *temporarily* be
688 interpreted as outline headlines with a level given by 1000+i where i is the
689 indentation of the bullet. In all other operations, plain list items are
690 not seen as headlines. For example, you cannot assign a TODO keyword to
691 such an item."
692 :group 'org-plain-lists
693 :type 'boolean)
695 (defcustom org-plain-list-ordered-item-terminator t
696 "The character that makes a line with leading number an ordered list item.
697 Valid values are ?. and ?\). To get both terminators, use t. While
698 ?. may look nicer, it creates the danger that a line with leading
699 number may be incorrectly interpreted as an item. ?\) therefore is
700 the safe choice."
701 :group 'org-plain-lists
702 :type '(choice (const :tag "dot like in \"2.\"" ?.)
703 (const :tag "paren like in \"2)\"" ?\))
704 (const :tab "both" t)))
706 (defcustom org-auto-renumber-ordered-lists t
707 "Non-nil means, automatically renumber ordered plain lists.
708 Renumbering happens when the sequence have been changed with
709 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
710 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
711 :group 'org-plain-lists
712 :type 'boolean)
714 (defcustom org-provide-checkbox-statistics t
715 "Non-nil means, update checkbox statistics after insert and toggle.
716 When this is set, checkbox statistics is updated each time you either insert
717 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
718 with \\[org-ctrl-c-ctrl-c\\]."
719 :group 'org-plain-lists
720 :type 'boolean)
722 (defgroup org-archive nil
723 "Options concerning archiving in Org-mode."
724 :tag "Org Archive"
725 :group 'org-structure)
727 (defcustom org-archive-tag "ARCHIVE"
728 "The tag that marks a subtree as archived.
729 An archived subtree does not open during visibility cycling, and does
730 not contribute to the agenda listings.
731 After changing this, font-lock must be restarted in the relevant buffers to
732 get the proper fontification."
733 :group 'org-archive
734 :group 'org-keywords
735 :type 'string)
737 (defcustom org-agenda-skip-archived-trees t
738 "Non-nil means, the agenda will skip any items located in archived trees.
739 An archived tree is a tree marked with the tag ARCHIVE."
740 :group 'org-archive
741 :group 'org-agenda-skip
742 :type 'boolean)
744 (defcustom org-cycle-open-archived-trees nil
745 "Non-nil means, `org-cycle' will open archived trees.
746 An archived tree is a tree marked with the tag ARCHIVE.
747 When nil, archived trees will stay folded. You can still open them with
748 normal outline commands like `show-all', but not with the cycling commands."
749 :group 'org-archive
750 :group 'org-cycle
751 :type 'boolean)
753 (defcustom org-sparse-tree-open-archived-trees nil
754 "Non-nil means sparse tree construction shows matches in archived trees.
755 When nil, matches in these trees are highlighted, but the trees are kept in
756 collapsed state."
757 :group 'org-archive
758 :group 'org-sparse-trees
759 :type 'boolean)
761 (defcustom org-archive-location "%s_archive::"
762 "The location where subtrees should be archived.
763 This string consists of two parts, separated by a double-colon.
765 The first part is a file name - when omitted, archiving happens in the same
766 file. %s will be replaced by the current file name (without directory part).
767 Archiving to a different file is useful to keep archived entries from
768 contributing to the Org-mode Agenda.
770 The part after the double colon is a headline. The archived entries will be
771 filed under that headline. When omitted, the subtrees are simply filed away
772 at the end of the file, as top-level entries.
774 Here are a few examples:
775 \"%s_archive::\"
776 If the current file is Projects.org, archive in file
777 Projects.org_archive, as top-level trees. This is the default.
779 \"::* Archived Tasks\"
780 Archive in the current file, under the top-level headline
781 \"* Archived Tasks\".
783 \"~/org/archive.org::\"
784 Archive in file ~/org/archive.org (absolute path), as top-level trees.
786 \"basement::** Finished Tasks\"
787 Archive in file ./basement (relative path), as level 3 trees
788 below the level 2 heading \"** Finished Tasks\".
790 You may set this option on a per-file basis by adding to the buffer a
791 line like
793 #+ARCHIVE: basement::** Finished Tasks"
794 :group 'org-archive
795 :type 'string)
797 (defcustom org-archive-mark-done t
798 "Non-nil means, mark entries as DONE when they are moved to the archive file.
799 This can be a string to set the keyword to use. When t, Org-mode will
800 use the first keyword in its list that means done."
801 :group 'org-archive
802 :type '(choice
803 (const :tag "No" nil)
804 (const :tag "Yes" t)
805 (string :tag "Use this keyword")))
807 (defcustom org-archive-stamp-time t
808 "Non-nil means, add a time stamp to entries moved to an archive file.
809 This variable is obsolete and has no effect anymore, instead add ot remove
810 `time' from the variablle `org-archive-save-context-info'."
811 :group 'org-archive
812 :type 'boolean)
814 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
815 "Parts of context info that should be stored as properties when archiving.
816 When a subtree is moved to an archive file, it looses information given by
817 context, like inherited tags, the category, and possibly also the TODO
818 state (depending on the variable `org-archive-mark-done').
819 This variable can be a list of any of the following symbols:
821 time The time of archiving.
822 file The file where the entry originates.
823 itags The local tags, in the headline of the subtree.
824 ltags The tags the subtree inherits from further up the hierarchy.
825 todo The pre-archive TODO state.
826 category The category, taken from file name or #+CATEGORY lines.
827 olpath The outline path to the item. These are all headlines above
828 the current item, separated by /, like a file path.
830 For each symbol present in the list, a property will be created in
831 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
832 information."
833 :group 'org-archive
834 :type '(set :greedy t
835 (const :tag "Time" time)
836 (const :tag "File" file)
837 (const :tag "Category" category)
838 (const :tag "TODO state" todo)
839 (const :tag "TODO state" priority)
840 (const :tag "Inherited tags" itags)
841 (const :tag "Outline path" olpath)
842 (const :tag "Local tags" ltags)))
844 (defgroup org-imenu-and-speedbar nil
845 "Options concerning imenu and speedbar in Org-mode."
846 :tag "Org Imenu and Speedbar"
847 :group 'org-structure)
849 (defcustom org-imenu-depth 2
850 "The maximum level for Imenu access to Org-mode headlines.
851 This also applied for speedbar access."
852 :group 'org-imenu-and-speedbar
853 :type 'number)
855 (defgroup org-table nil
856 "Options concerning tables in Org-mode."
857 :tag "Org Table"
858 :group 'org)
860 (defcustom org-enable-table-editor 'optimized
861 "Non-nil means, lines starting with \"|\" are handled by the table editor.
862 When nil, such lines will be treated like ordinary lines.
864 When equal to the symbol `optimized', the table editor will be optimized to
865 do the following:
866 - Automatic overwrite mode in front of whitespace in table fields.
867 This makes the structure of the table stay in tact as long as the edited
868 field does not exceed the column width.
869 - Minimize the number of realigns. Normally, the table is aligned each time
870 TAB or RET are pressed to move to another field. With optimization this
871 happens only if changes to a field might have changed the column width.
872 Optimization requires replacing the functions `self-insert-command',
873 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
874 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
875 very good at guessing when a re-align will be necessary, but you can always
876 force one with \\[org-ctrl-c-ctrl-c].
878 If you would like to use the optimized version in Org-mode, but the
879 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
881 This variable can be used to turn on and off the table editor during a session,
882 but in order to toggle optimization, a restart is required.
884 See also the variable `org-table-auto-blank-field'."
885 :group 'org-table
886 :type '(choice
887 (const :tag "off" nil)
888 (const :tag "on" t)
889 (const :tag "on, optimized" optimized)))
891 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
892 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
893 In the optimized version, the table editor takes over all simple keys that
894 normally just insert a character. In tables, the characters are inserted
895 in a way to minimize disturbing the table structure (i.e. in overwrite mode
896 for empty fields). Outside tables, the correct binding of the keys is
897 restored.
899 The default for this option is t if the optimized version is also used in
900 Org-mode. See the variable `org-enable-table-editor' for details. Changing
901 this variable requires a restart of Emacs to become effective."
902 :group 'org-table
903 :type 'boolean)
905 (defcustom orgtbl-radio-table-templates
906 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
907 % END RECEIVE ORGTBL %n
908 \\begin{comment}
909 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
910 | | |
911 \\end{comment}\n")
912 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
913 @c END RECEIVE ORGTBL %n
914 @ignore
915 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
916 | | |
917 @end ignore\n")
918 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
919 <!-- END RECEIVE ORGTBL %n -->
920 <!--
921 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
922 | | |
923 -->\n"))
924 "Templates for radio tables in different major modes.
925 All occurrences of %n in a template will be replaced with the name of the
926 table, obtained by prompting the user."
927 :group 'org-table
928 :type '(repeat
929 (list (symbol :tag "Major mode")
930 (string :tag "Format"))))
932 (defgroup org-table-settings nil
933 "Settings for tables in Org-mode."
934 :tag "Org Table Settings"
935 :group 'org-table)
937 (defcustom org-table-default-size "5x2"
938 "The default size for newly created tables, Columns x Rows."
939 :group 'org-table-settings
940 :type 'string)
942 (defcustom org-table-number-regexp
943 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
944 "Regular expression for recognizing numbers in table columns.
945 If a table column contains mostly numbers, it will be aligned to the
946 right. If not, it will be aligned to the left.
948 The default value of this option is a regular expression which allows
949 anything which looks remotely like a number as used in scientific
950 context. For example, all of the following will be considered a
951 number:
952 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
954 Other options offered by the customize interface are more restrictive."
955 :group 'org-table-settings
956 :type '(choice
957 (const :tag "Positive Integers"
958 "^[0-9]+$")
959 (const :tag "Integers"
960 "^[-+]?[0-9]+$")
961 (const :tag "Floating Point Numbers"
962 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
963 (const :tag "Floating Point Number or Integer"
964 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
965 (const :tag "Exponential, Floating point, Integer"
966 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
967 (const :tag "Very General Number-Like, including hex"
968 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
969 (string :tag "Regexp:")))
971 (defcustom org-table-number-fraction 0.5
972 "Fraction of numbers in a column required to make the column align right.
973 In a column all non-white fields are considered. If at least this
974 fraction of fields is matched by `org-table-number-fraction',
975 alignment to the right border applies."
976 :group 'org-table-settings
977 :type 'number)
979 (defgroup org-table-editing nil
980 "Behavior of tables during editing in Org-mode."
981 :tag "Org Table Editing"
982 :group 'org-table)
984 (defcustom org-table-automatic-realign t
985 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
986 When nil, aligning is only done with \\[org-table-align], or after column
987 removal/insertion."
988 :group 'org-table-editing
989 :type 'boolean)
991 (defcustom org-table-auto-blank-field t
992 "Non-nil means, automatically blank table field when starting to type into it.
993 This only happens when typing immediately after a field motion
994 command (TAB, S-TAB or RET).
995 Only relevant when `org-enable-table-editor' is equal to `optimized'."
996 :group 'org-table-editing
997 :type 'boolean)
999 (defcustom org-table-tab-jumps-over-hlines t
1000 "Non-nil means, tab in the last column of a table with jump over a hline.
1001 If a horizontal separator line is following the current line,
1002 `org-table-next-field' can either create a new row before that line, or jump
1003 over the line. When this option is nil, a new line will be created before
1004 this line."
1005 :group 'org-table-editing
1006 :type 'boolean)
1008 (defcustom org-table-tab-recognizes-table.el t
1009 "Non-nil means, TAB will automatically notice a table.el table.
1010 When it sees such a table, it moves point into it and - if necessary -
1011 calls `table-recognize-table'."
1012 :group 'org-table-editing
1013 :type 'boolean)
1015 (defgroup org-table-calculation nil
1016 "Options concerning tables in Org-mode."
1017 :tag "Org Table Calculation"
1018 :group 'org-table)
1020 (defcustom org-table-use-standard-references t
1021 "Should org-mode work with table refrences like B3 instead of @3$2?
1022 Possible values are:
1023 nil never use them
1024 from accept as input, do not present for editing
1025 t: accept as input and present for editing"
1026 :group 'org-table-calculation
1027 :type '(choice
1028 (const :tag "Never, don't even check unser input for them" nil)
1029 (const :tag "Always, both as user input, and when editing" t)
1030 (const :tag "Convert user input, don't offer during editing" 'from)))
1032 (defcustom org-table-copy-increment t
1033 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1034 :group 'org-table-calculation
1035 :type 'boolean)
1037 (defcustom org-calc-default-modes
1038 '(calc-internal-prec 12
1039 calc-float-format (float 5)
1040 calc-angle-mode deg
1041 calc-prefer-frac nil
1042 calc-symbolic-mode nil
1043 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1044 calc-display-working-message t
1046 "List with Calc mode settings for use in calc-eval for table formulas.
1047 The list must contain alternating symbols (Calc modes variables and values).
1048 Don't remove any of the default settings, just change the values. Org-mode
1049 relies on the variables to be present in the list."
1050 :group 'org-table-calculation
1051 :type 'plist)
1053 (defcustom org-table-formula-evaluate-inline t
1054 "Non-nil means, TAB and RET evaluate a formula in current table field.
1055 If the current field starts with an equal sign, it is assumed to be a formula
1056 which should be evaluated as described in the manual and in the documentation
1057 string of the command `org-table-eval-formula'. This feature requires the
1058 Emacs calc package.
1059 When this variable is nil, formula calculation is only available through
1060 the command \\[org-table-eval-formula]."
1061 :group 'org-table-calculation
1062 :type 'boolean)
1064 (defcustom org-table-formula-use-constants t
1065 "Non-nil means, interpret constants in formulas in tables.
1066 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1067 by the value given in `org-table-formula-constants', or by a value obtained
1068 from the `constants.el' package."
1069 :group 'org-table-calculation
1070 :type 'boolean)
1072 (defcustom org-table-formula-constants nil
1073 "Alist with constant names and values, for use in table formulas.
1074 The car of each element is a name of a constant, without the `$' before it.
1075 The cdr is the value as a string. For example, if you'd like to use the
1076 speed of light in a formula, you would configure
1078 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1080 and then use it in an equation like `$1*$c'.
1082 Constants can also be defined on a per-file basis using a line like
1084 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1085 :group 'org-table-calculation
1086 :type '(repeat
1087 (cons (string :tag "name")
1088 (string :tag "value"))))
1090 (defvar org-table-formula-constants-local nil
1091 "Local version of `org-table-formula-constants'.")
1092 (make-variable-buffer-local 'org-table-formula-constants-local)
1094 (defcustom org-table-allow-automatic-line-recalculation t
1095 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1096 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1097 :group 'org-table-calculation
1098 :type 'boolean)
1100 (defgroup org-link nil
1101 "Options concerning links in Org-mode."
1102 :tag "Org Link"
1103 :group 'org)
1105 (defvar org-link-abbrev-alist-local nil
1106 "Buffer-local version of `org-link-abbrev-alist', which see.
1107 The value of this is taken from the #+LINK lines.")
1108 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1110 (defcustom org-link-abbrev-alist nil
1111 "Alist of link abbreviations.
1112 The car of each element is a string, to be replaced at the start of a link.
1113 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1114 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1116 [[linkkey:tag][description]]
1118 If REPLACE is a string, the tag will simply be appended to create the link.
1119 If the string contains \"%s\", the tag will be inserted there.
1121 REPLACE may also be a function that will be called with the tag as the
1122 only argument to create the link, which should be returned as a string.
1124 See the manual for examples."
1125 :group 'org-link
1126 :type 'alist)
1128 (defcustom org-descriptive-links t
1129 "Non-nil means, hide link part and only show description of bracket links.
1130 Bracket links are like [[link][descritpion]]. This variable sets the initial
1131 state in new org-mode buffers. The setting can then be toggled on a
1132 per-buffer basis from the Org->Hyperlinks menu."
1133 :group 'org-link
1134 :type 'boolean)
1136 (defcustom org-link-file-path-type 'adaptive
1137 "How the path name in file links should be stored.
1138 Valid values are:
1140 relative Relative to the current directory, i.e. the directory of the file
1141 into which the link is being inserted.
1142 absolute Absolute path, if possible with ~ for home directory.
1143 noabbrev Absolute path, no abbreviation of home directory.
1144 adaptive Use relative path for files in the current directory and sub-
1145 directories of it. For other files, use an absolute path."
1146 :group 'org-link
1147 :type '(choice
1148 (const relative)
1149 (const absolute)
1150 (const noabbrev)
1151 (const adaptive)))
1153 (defcustom org-activate-links '(bracket angle plain radio tag date)
1154 "Types of links that should be activated in Org-mode files.
1155 This is a list of symbols, each leading to the activation of a certain link
1156 type. In principle, it does not hurt to turn on most link types - there may
1157 be a small gain when turning off unused link types. The types are:
1159 bracket The recommended [[link][description]] or [[link]] links with hiding.
1160 angular Links in angular brackes that may contain whitespace like
1161 <bbdb:Carsten Dominik>.
1162 plain Plain links in normal text, no whitespace, like http://google.com.
1163 radio Text that is matched by a radio target, see manual for details.
1164 tag Tag settings in a headline (link to tag search).
1165 date Time stamps (link to calendar).
1167 Changing this variable requires a restart of Emacs to become effective."
1168 :group 'org-link
1169 :type '(set (const :tag "Double bracket links (new style)" bracket)
1170 (const :tag "Angular bracket links (old style)" angular)
1171 (const :tag "Plain text links" plain)
1172 (const :tag "Radio target matches" radio)
1173 (const :tag "Tags" tag)
1174 (const :tag "Timestamps" date)))
1176 (defgroup org-link-store nil
1177 "Options concerning storing links in Org-mode"
1178 :tag "Org Store Link"
1179 :group 'org-link)
1181 (defcustom org-email-link-description-format "Email %c: %.30s"
1182 "Format of the description part of a link to an email or usenet message.
1183 The following %-excapes will be replaced by corresponding information:
1185 %F full \"From\" field
1186 %f name, taken from \"From\" field, address if no name
1187 %T full \"To\" field
1188 %t first name in \"To\" field, address if no name
1189 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1190 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1191 %s subject
1192 %m message-id.
1194 You may use normal field width specification between the % and the letter.
1195 This is for example useful to limit the length of the subject.
1197 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1198 :group 'org-link-store
1199 :type 'string)
1201 (defcustom org-from-is-user-regexp
1202 (let (r1 r2)
1203 (when (and user-mail-address (not (string= user-mail-address "")))
1204 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1205 (when (and user-full-name (not (string= user-full-name "")))
1206 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1207 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1208 "Regexp mached against the \"From:\" header of an email or usenet message.
1209 It should match if the message is from the user him/herself."
1210 :group 'org-link-store
1211 :type 'regexp)
1213 (defcustom org-context-in-file-links t
1214 "Non-nil means, file links from `org-store-link' contain context.
1215 A search string will be added to the file name with :: as separator and
1216 used to find the context when the link is activated by the command
1217 `org-open-at-point'.
1218 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1219 negates this setting for the duration of the command."
1220 :group 'org-link-store
1221 :type 'boolean)
1223 (defcustom org-keep-stored-link-after-insertion nil
1224 "Non-nil means, keep link in list for entire session.
1226 The command `org-store-link' adds a link pointing to the current
1227 location to an internal list. These links accumulate during a session.
1228 The command `org-insert-link' can be used to insert links into any
1229 Org-mode file (offering completion for all stored links). When this
1230 option is nil, every link which has been inserted once using \\[org-insert-link]
1231 will be removed from the list, to make completing the unused links
1232 more efficient."
1233 :group 'org-link-store
1234 :type 'boolean)
1236 (defcustom org-usenet-links-prefer-google nil
1237 "Non-nil means, `org-store-link' will create web links to Google groups.
1238 When nil, Gnus will be used for such links.
1239 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1240 negates this setting for the duration of the command."
1241 :group 'org-link-store
1242 :type 'boolean)
1244 (defgroup org-link-follow nil
1245 "Options concerning following links in Org-mode"
1246 :tag "Org Follow Link"
1247 :group 'org-link)
1249 (defcustom org-follow-link-hook nil
1250 "Hook that is run after a link has been followed."
1251 :group 'org-link-follow
1252 :type 'hook)
1254 (defcustom org-tab-follows-link nil
1255 "Non-nil means, on links TAB will follow the link.
1256 Needs to be set before org.el is loaded."
1257 :group 'org-link-follow
1258 :type 'boolean)
1260 (defcustom org-return-follows-link nil
1261 "Non-nil means, on links RET will follow the link.
1262 Needs to be set before org.el is loaded."
1263 :group 'org-link-follow
1264 :type 'boolean)
1266 (defcustom org-mouse-1-follows-link
1267 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1268 "Non-nil means, mouse-1 on a link will follow the link.
1269 A longer mouse click will still set point. Does not work on XEmacs.
1270 Needs to be set before org.el is loaded."
1271 :group 'org-link-follow
1272 :type 'boolean)
1274 (defcustom org-mark-ring-length 4
1275 "Number of different positions to be recorded in the ring
1276 Changing this requires a restart of Emacs to work correctly."
1277 :group 'org-link-follow
1278 :type 'interger)
1280 (defcustom org-link-frame-setup
1281 '((vm . vm-visit-folder-other-frame)
1282 (gnus . gnus-other-frame)
1283 (file . find-file-other-window))
1284 "Setup the frame configuration for following links.
1285 When following a link with Emacs, it may often be useful to display
1286 this link in another window or frame. This variable can be used to
1287 set this up for the different types of links.
1288 For VM, use any of
1289 `vm-visit-folder'
1290 `vm-visit-folder-other-frame'
1291 For Gnus, use any of
1292 `gnus'
1293 `gnus-other-frame'
1294 For FILE, use any of
1295 `find-file'
1296 `find-file-other-window'
1297 `find-file-other-frame'
1298 For the calendar, use the variable `calendar-setup'.
1299 For BBDB, it is currently only possible to display the matches in
1300 another window."
1301 :group 'org-link-follow
1302 :type '(list
1303 (cons (const vm)
1304 (choice
1305 (const vm-visit-folder)
1306 (const vm-visit-folder-other-window)
1307 (const vm-visit-folder-other-frame)))
1308 (cons (const gnus)
1309 (choice
1310 (const gnus)
1311 (const gnus-other-frame)))
1312 (cons (const file)
1313 (choice
1314 (const find-file)
1315 (const find-file-other-window)
1316 (const find-file-other-frame)))))
1318 (defcustom org-display-internal-link-with-indirect-buffer nil
1319 "Non-nil means, use indirect buffer to display infile links.
1320 Activating internal links (from one location in a file to another location
1321 in the same file) normally just jumps to the location. When the link is
1322 activated with a C-u prefix (or with mouse-3), the link is displayed in
1323 another window. When this option is set, the other window actually displays
1324 an indirect buffer clone of the current buffer, to avoid any visibility
1325 changes to the current buffer."
1326 :group 'org-link-follow
1327 :type 'boolean)
1329 (defcustom org-open-non-existing-files nil
1330 "Non-nil means, `org-open-file' will open non-existing files.
1331 When nil, an error will be generated."
1332 :group 'org-link-follow
1333 :type 'boolean)
1335 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1336 "Function and arguments to call for following mailto links.
1337 This is a list with the first element being a lisp function, and the
1338 remaining elements being arguments to the function. In string arguments,
1339 %a will be replaced by the address, and %s will be replaced by the subject
1340 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1341 :group 'org-link-follow
1342 :type '(choice
1343 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1344 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1345 (const :tag "message-mail" (message-mail "%a" "%s"))
1346 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1348 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1349 "Non-nil means, ask for confirmation before executing shell links.
1350 Shell links can be dangerous: just think about a link
1352 [[shell:rm -rf ~/*][Google Search]]
1354 This link would show up in your Org-mode document as \"Google Search\",
1355 but really it would remove your entire home directory.
1356 Therefore we advise against setting this variable to nil.
1357 Just change it to `y-or-n-p' of you want to confirm with a
1358 single keystroke rather than having to type \"yes\"."
1359 :group 'org-link-follow
1360 :type '(choice
1361 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1362 (const :tag "with y-or-n (faster)" y-or-n-p)
1363 (const :tag "no confirmation (dangerous)" nil)))
1365 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1366 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1367 Elisp links can be dangerous: just think about a link
1369 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1371 This link would show up in your Org-mode document as \"Google Search\",
1372 but really it would remove your entire home directory.
1373 Therefore we advise against setting this variable to nil.
1374 Just change it to `y-or-n-p' of you want to confirm with a
1375 single keystroke rather than having to type \"yes\"."
1376 :group 'org-link-follow
1377 :type '(choice
1378 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1379 (const :tag "with y-or-n (faster)" y-or-n-p)
1380 (const :tag "no confirmation (dangerous)" nil)))
1382 (defconst org-file-apps-defaults-gnu
1383 '((remote . emacs)
1384 (t . mailcap))
1385 "Default file applications on a UNIX or GNU/Linux system.
1386 See `org-file-apps'.")
1388 (defconst org-file-apps-defaults-macosx
1389 '((remote . emacs)
1390 (t . "open %s")
1391 ("ps" . "gv %s")
1392 ("ps.gz" . "gv %s")
1393 ("eps" . "gv %s")
1394 ("eps.gz" . "gv %s")
1395 ("dvi" . "xdvi %s")
1396 ("fig" . "xfig %s"))
1397 "Default file applications on a MacOS X system.
1398 The system \"open\" is known as a default, but we use X11 applications
1399 for some files for which the OS does not have a good default.
1400 See `org-file-apps'.")
1402 (defconst org-file-apps-defaults-windowsnt
1403 (list
1404 '(remote . emacs)
1405 (cons t
1406 (list (if (featurep 'xemacs)
1407 'mswindows-shell-execute
1408 'w32-shell-execute)
1409 "open" 'file)))
1410 "Default file applications on a Windows NT system.
1411 The system \"open\" is used for most files.
1412 See `org-file-apps'.")
1414 (defcustom org-file-apps
1416 ("txt" . emacs)
1417 ("tex" . emacs)
1418 ("ltx" . emacs)
1419 ("org" . emacs)
1420 ("el" . emacs)
1421 ("bib" . emacs)
1423 "External applications for opening `file:path' items in a document.
1424 Org-mode uses system defaults for different file types, but
1425 you can use this variable to set the application for a given file
1426 extension. The entries in this list are cons cells where the car identifies
1427 files and the cdr the corresponding command. Possible values for the
1428 file identifier are
1429 \"ext\" A string identifying an extension
1430 `directory' Matches a directory
1431 `remote' Matches a remote file, accessible through tramp or efs.
1432 Remote files most likely should be visited through Emacs
1433 because external applications cannot handle such paths.
1434 t Default for all remaining files
1436 Possible values for the command are:
1437 `emacs' The file will be visited by the current Emacs process.
1438 `default' Use the default application for this file type.
1439 string A command to be executed by a shell; %s will be replaced
1440 by the path to the file.
1441 sexp A Lisp form which will be evaluated. The file path will
1442 be available in the Lisp variable `file'.
1443 For more examples, see the system specific constants
1444 `org-file-apps-defaults-macosx'
1445 `org-file-apps-defaults-windowsnt'
1446 `org-file-apps-defaults-gnu'."
1447 :group 'org-link-follow
1448 :type '(repeat
1449 (cons (choice :value ""
1450 (string :tag "Extension")
1451 (const :tag "Default for unrecognized files" t)
1452 (const :tag "Remote file" remote)
1453 (const :tag "Links to a directory" directory))
1454 (choice :value ""
1455 (const :tag "Visit with Emacs" emacs)
1456 (const :tag "Use system default" default)
1457 (string :tag "Command")
1458 (sexp :tag "Lisp form")))))
1460 (defcustom org-mhe-search-all-folders nil
1461 "Non-nil means, that the search for the mh-message will be extended to
1462 all folders if the message cannot be found in the folder given in the link.
1463 Searching all folders is very efficient with one of the search engines
1464 supported by MH-E, but will be slow with pick."
1465 :group 'org-link-follow
1466 :type 'boolean)
1468 (defgroup org-remember nil
1469 "Options concerning interaction with remember.el."
1470 :tag "Org Remember"
1471 :group 'org)
1473 (defcustom org-directory "~/org"
1474 "Directory with org files.
1475 This directory will be used as default to prompt for org files.
1476 Used by the hooks for remember.el."
1477 :group 'org-remember
1478 :type 'directory)
1480 (defcustom org-default-notes-file "~/.notes"
1481 "Default target for storing notes.
1482 Used by the hooks for remember.el. This can be a string, or nil to mean
1483 the value of `remember-data-file'.
1484 You can set this on a per-template basis with the variable
1485 `org-remember-templates'."
1486 :group 'org-remember
1487 :type '(choice
1488 (const :tag "Default from remember-data-file" nil)
1489 file))
1491 (defcustom org-remember-store-without-prompt t
1492 "Non-nil means, `C-c C-c' stores remember note without further promts.
1493 In this case, you need `C-u C-c C-c' to get the prompts for
1494 note file and headline.
1495 When this variable is nil, `C-c C-c' give you the prompts, and
1496 `C-u C-c C-c' trigger the fasttrack."
1497 :group 'org-remember
1498 :type 'boolean)
1500 (defcustom org-remember-interactive-interface 'refile
1501 "The interface to be used for interactive filing of remember notes.
1502 This is only used when the interactive mode for selecting a filing
1503 location is used (see the variable `org-remember-store-without-prompt').
1504 Allowed vaues are:
1505 outline The interface shows an outline of the relevant file
1506 and the correct heading is found by moving through
1507 the outline or by searching with incremental search.
1508 outline-path-completion Headlines in the current buffer are offered via
1509 completion.
1510 refile Use the refile interface, and offer headlines,
1511 possibly from different buffers."
1512 :group 'org-remember
1513 :type '(choice
1514 (const :tag "Refile" refile)
1515 (const :tag "Outline" outline)
1516 (const :tag "Outline-path-completion" outline-path-completion)))
1518 (defcustom org-goto-interface 'outline
1519 "The default interface to be used for `org-goto'.
1520 Allowed vaues are:
1521 outline The interface shows an outline of the relevant file
1522 and the correct heading is found by moving through
1523 the outline or by searching with incremental search.
1524 outline-path-completion Headlines in the current buffer are offered via
1525 completion."
1526 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1527 :type '(choice
1528 (const :tag "Outline" outline)
1529 (const :tag "Outline-path-completion" outline-path-completion)))
1531 (defcustom org-remember-default-headline ""
1532 "The headline that should be the default location in the notes file.
1533 When filing remember notes, the cursor will start at that position.
1534 You can set this on a per-template basis with the variable
1535 `org-remember-templates'."
1536 :group 'org-remember
1537 :type 'string)
1539 (defcustom org-remember-templates nil
1540 "Templates for the creation of remember buffers.
1541 When nil, just let remember make the buffer.
1542 When not nil, this is a list of 5-element lists. In each entry, the first
1543 element is the name of the template, which should be a single short word.
1544 The second element is a character, a unique key to select this template.
1545 The third element is the template. The fourth element is optional and can
1546 specify a destination file for remember items created with this template.
1547 The default file is given by `org-default-notes-file'. An optional fifth
1548 element can specify the headline in that file that should be offered
1549 first when the user is asked to file the entry. The default headline is
1550 given in the variable `org-remember-default-headline'.
1552 An optional sixth element can specify the context in which the user should
1553 be able to select this template. If this element is a list of major modes,
1554 the template will only be available while invoking `org-remember' from a
1555 buffer in one of these modes. If it is a function, the template will only
1556 be selected if the function returns `t'. A value of `t' means select
1557 this template in any context. When the element is `nil', the template
1558 will be selected by default, i.e. when all contextual checks failed.
1560 The template specifies the structure of the remember buffer. It should have
1561 a first line starting with a star, to act as the org-mode headline.
1562 Furthermore, the following %-escapes will be replaced with content:
1564 %^{prompt} Prompt the user for a string and replace this sequence with it.
1565 A default value and a completion table ca be specified like this:
1566 %^{prompt|default|completion2|completion3|...}
1567 %t time stamp, date only
1568 %T time stamp with date and time
1569 %u, %U like the above, but inactive time stamps
1570 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1571 You may define a prompt like %^{Please specify birthday}t
1572 %n user name (taken from `user-full-name')
1573 %a annotation, normally the link created with org-store-link
1574 %i initial content, the region active. If %i is indented,
1575 the entire inserted text will be indented as well.
1576 %c content of the clipboard, or current kill ring head
1577 %^g prompt for tags, with completion on tags in target file
1578 %^G prompt for tags, with completion all tags in all agenda files
1579 %:keyword specific information for certain link types, see below
1580 %[pathname] insert the contents of the file given by `pathname'
1581 %(sexp) evaluate elisp `(sexp)' and replace with the result
1582 %! Store this note immediately after filling the template
1584 %? After completing the template, position cursor here.
1586 Apart from these general escapes, you can access information specific to the
1587 link type that is created. For example, calling `remember' in emails or gnus
1588 will record the author and the subject of the message, which you can access
1589 with %:author and %:subject, respectively. Here is a complete list of what
1590 is recorded for each link type.
1592 Link type | Available information
1593 -------------------+------------------------------------------------------
1594 bbdb | %:type %:name %:company
1595 vm, wl, mh, rmail | %:type %:subject %:message-id
1596 | %:from %:fromname %:fromaddress
1597 | %:to %:toname %:toaddress
1598 | %:fromto (either \"to NAME\" or \"from NAME\")
1599 gnus | %:group, for messages also all email fields
1600 w3, w3m | %:type %:url
1601 info | %:type %:file %:node
1602 calendar | %:type %:date"
1603 :group 'org-remember
1604 :get (lambda (var) ; Make sure all entries have at least 5 elements
1605 (mapcar (lambda (x)
1606 (if (not (stringp (car x))) (setq x (cons "" x)))
1607 (cond ((= (length x) 4) (append x '("")))
1608 ((= (length x) 3) (append x '("" "")))
1609 (t x)))
1610 (default-value var)))
1611 :type '(repeat
1612 :tag "enabled"
1613 (list :value ("" ?a "\n" nil nil nil)
1614 (string :tag "Name")
1615 (character :tag "Selection Key")
1616 (string :tag "Template")
1617 (choice
1618 (file :tag "Destination file")
1619 (const :tag "Prompt for file" nil))
1620 (choice
1621 (string :tag "Destination headline")
1622 (const :tag "Selection interface for heading"))
1623 (choice
1624 (const :tag "Use by default" nil)
1625 (const :tag "Use in all contexts" t)
1626 (repeat :tag "Use only if in major mode"
1627 (symbol :tag "Major mode"))
1628 (function :tag "Perform a check against function")))))
1630 (defcustom org-reverse-note-order nil
1631 "Non-nil means, store new notes at the beginning of a file or entry.
1632 When nil, new notes will be filed to the end of a file or entry.
1633 This can also be a list with cons cells of regular expressions that
1634 are matched against file names, and values."
1635 :group 'org-remember
1636 :type '(choice
1637 (const :tag "Reverse always" t)
1638 (const :tag "Reverse never" nil)
1639 (repeat :tag "By file name regexp"
1640 (cons regexp boolean))))
1642 (defcustom org-refile-targets nil
1643 "Targets for refiling entries with \\[org-refile].
1644 This is list of cons cells. Each cell contains:
1645 - a specification of the files to be considered, either a list of files,
1646 or a symbol whose function or value fields will be used to retrieve
1647 a file name or a list of file names. Nil means, refile to a different
1648 heading in the current buffer.
1649 - A specification of how to find candidate refile targets. This may be
1650 any of
1651 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1652 This tag has to be present in all target headlines, inheritance will
1653 not be considered.
1654 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1655 todo keyword.
1656 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1657 headlines that are refiling targets.
1658 - a cons cell (:level . N). Any headline of level N is considered a target.
1659 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1660 ;; FIXME: what if there are a var and func with same name???
1661 :group 'org-remember
1662 :type '(repeat
1663 (cons
1664 (choice :value org-agenda-files
1665 (const :tag "All agenda files" org-agenda-files)
1666 (const :tag "Current buffer" nil)
1667 (function) (variable) (file))
1668 (choice :tag "Identify target headline by"
1669 (cons :tag "Specific tag" (const :tag) (string))
1670 (cons :tag "TODO keyword" (const :todo) (string))
1671 (cons :tag "Regular expression" (const :regexp) (regexp))
1672 (cons :tag "Level number" (const :level) (integer))
1673 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1675 (defcustom org-refile-use-outline-path nil
1676 "Non-nil means, provide refile targets as paths.
1677 So a level 3 headline will be available as level1/level2/level3.
1678 When the value is `file', also include the file name (without directory)
1679 into the path. When `full-file-path', include the full file path."
1680 :group 'org-remember
1681 :type '(choice
1682 (const :tag "Not" nil)
1683 (const :tag "Yes" t)
1684 (const :tag "Start with file name" file)
1685 (const :tag "Start with full file path" full-file-path)))
1687 (defgroup org-todo nil
1688 "Options concerning TODO items in Org-mode."
1689 :tag "Org TODO"
1690 :group 'org)
1692 (defgroup org-progress nil
1693 "Options concerning Progress logging in Org-mode."
1694 :tag "Org Progress"
1695 :group 'org-time)
1697 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1698 "List of TODO entry keyword sequences and their interpretation.
1699 \\<org-mode-map>This is a list of sequences.
1701 Each sequence starts with a symbol, either `sequence' or `type',
1702 indicating if the keywords should be interpreted as a sequence of
1703 action steps, or as different types of TODO items. The first
1704 keywords are states requiring action - these states will select a headline
1705 for inclusion into the global TODO list Org-mode produces. If one of
1706 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1707 signify that no further action is necessary. If \"|\" is not found,
1708 the last keyword is treated as the only DONE state of the sequence.
1710 The command \\[org-todo] cycles an entry through these states, and one
1711 additional state where no keyword is present. For details about this
1712 cycling, see the manual.
1714 TODO keywords and interpretation can also be set on a per-file basis with
1715 the special #+SEQ_TODO and #+TYP_TODO lines.
1717 Each keyword can optionally specify a character for fast state selection
1718 \(in combination with the variable `org-use-fast-todo-selection')
1719 and specifiers for state change logging, using the same syntax
1720 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1721 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1722 indicates to record a time stamp each time this state is selected.
1724 Each keyword may also specify if a timestamp or a note should be
1725 recorded when entering or leaving the state, by adding additional
1726 characters in the parenthesis after the keyword. This looks like this:
1727 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1728 record only the time of the state change. With X and Y being either
1729 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1730 Y when leaving the state if and only if the *target* state does not
1731 define X. You may omit any of the fast-selection key or X or /Y,
1732 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1734 For backward compatibility, this variable may also be just a list
1735 of keywords - in this case the interptetation (sequence or type) will be
1736 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1737 :group 'org-todo
1738 :group 'org-keywords
1739 :type '(choice
1740 (repeat :tag "Old syntax, just keywords"
1741 (string :tag "Keyword"))
1742 (repeat :tag "New syntax"
1743 (cons
1744 (choice
1745 :tag "Interpretation"
1746 (const :tag "Sequence (cycling hits every state)" sequence)
1747 (const :tag "Type (cycling directly to DONE)" type))
1748 (repeat
1749 (string :tag "Keyword"))))))
1751 (defvar org-todo-keywords-1 nil
1752 "All TODO and DONE keywords active in a buffer.")
1753 (make-variable-buffer-local 'org-todo-keywords-1)
1754 (defvar org-todo-keywords-for-agenda nil)
1755 (defvar org-done-keywords-for-agenda nil)
1756 (defvar org-not-done-keywords nil)
1757 (make-variable-buffer-local 'org-not-done-keywords)
1758 (defvar org-done-keywords nil)
1759 (make-variable-buffer-local 'org-done-keywords)
1760 (defvar org-todo-heads nil)
1761 (make-variable-buffer-local 'org-todo-heads)
1762 (defvar org-todo-sets nil)
1763 (make-variable-buffer-local 'org-todo-sets)
1764 (defvar org-todo-log-states nil)
1765 (make-variable-buffer-local 'org-todo-log-states)
1766 (defvar org-todo-kwd-alist nil)
1767 (make-variable-buffer-local 'org-todo-kwd-alist)
1768 (defvar org-todo-key-alist nil)
1769 (make-variable-buffer-local 'org-todo-key-alist)
1770 (defvar org-todo-key-trigger nil)
1771 (make-variable-buffer-local 'org-todo-key-trigger)
1773 (defcustom org-todo-interpretation 'sequence
1774 "Controls how TODO keywords are interpreted.
1775 This variable is in principle obsolete and is only used for
1776 backward compatibility, if the interpretation of todo keywords is
1777 not given already in `org-todo-keywords'. See that variable for
1778 more information."
1779 :group 'org-todo
1780 :group 'org-keywords
1781 :type '(choice (const sequence)
1782 (const type)))
1784 (defcustom org-use-fast-todo-selection 'prefix
1785 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1786 This variable describes if and under what circumstances the cycling
1787 mechanism for TODO keywords will be replaced by a single-key, direct
1788 selection scheme.
1790 When nil, fast selection is never used.
1792 When the symbol `prefix', it will be used when `org-todo' is called with
1793 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1794 in an agenda buffer.
1796 When t, fast selection is used by default. In this case, the prefix
1797 argument forces cycling instead.
1799 In all cases, the special interface is only used if access keys have actually
1800 been assigned by the user, i.e. if keywords in the configuration are followed
1801 by a letter in parenthesis, like TODO(t)."
1802 :group 'org-todo
1803 :type '(choice
1804 (const :tag "Never" nil)
1805 (const :tag "By default" t)
1806 (const :tag "Only with C-u C-c C-t" prefix)))
1808 (defcustom org-after-todo-state-change-hook nil
1809 "Hook which is run after the state of a TODO item was changed.
1810 The new state (a string with a TODO keyword, or nil) is available in the
1811 Lisp variable `state'."
1812 :group 'org-todo
1813 :type 'hook)
1815 (defcustom org-log-done nil
1816 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1817 When equal to the list (done), also prompt for a closing note.
1818 This can also be configured on a per-file basis by adding one of
1819 the following lines anywhere in the buffer:
1821 #+STARTUP: logdone
1822 #+STARTUP: lognotedone
1823 #+STARTUP: nologdone"
1824 :group 'org-todo
1825 :group 'org-progress
1826 :type '(choice
1827 (const :tag "No logging" nil)
1828 (const :tag "Record CLOSED timestamp" time)
1829 (const :tag "Record CLOSED timestamp with closing note." note)))
1831 ;; Normalize old uses of org-log-done.
1832 (cond
1833 ((eq org-log-done t) (setq org-log-done 'time))
1834 ((and (listp org-log-done) (memq 'done org-log-done))
1835 (setq org-log-done 'note)))
1837 ;; FIXME: document
1838 (defcustom org-log-note-clock-out nil
1839 "Non-nil means, recored a note when clocking out of an item.
1840 This can also be configured on a per-file basis by adding one of
1841 the following lines anywhere in the buffer:
1843 #+STARTUP: lognoteclock-out
1844 #+STARTUP: nolognoteclock-out"
1845 :group 'org-todo
1846 :group 'org-progress
1847 :type 'boolean)
1849 (defcustom org-log-done-with-time t
1850 "Non-nil means, the CLOSED time stamp will contain date and time.
1851 When nil, only the date will be recorded."
1852 :group 'org-progress
1853 :type 'boolean)
1855 (defcustom org-log-note-headings
1856 '((done . "CLOSING NOTE %t")
1857 (state . "State %-12s %t")
1858 (clock-out . ""))
1859 "Headings for notes added when clocking out or closing TODO items.
1860 The value is an alist, with the car being a symbol indicating the note
1861 context, and the cdr is the heading to be used. The heading may also be the
1862 empty string.
1863 %t in the heading will be replaced by a time stamp.
1864 %s will be replaced by the new TODO state, in double quotes.
1865 %u will be replaced by the user name.
1866 %U will be replaced by the full user name."
1867 :group 'org-todo
1868 :group 'org-progress
1869 :type '(list :greedy t
1870 (cons (const :tag "Heading when closing an item" done) string)
1871 (cons (const :tag
1872 "Heading when changing todo state (todo sequence only)"
1873 state) string)
1874 (cons (const :tag "Heading when clocking out" clock-out) string)))
1876 (defcustom org-log-states-order-reversed t
1877 "Non-nil means, the latest state change note will be directly after heading.
1878 When nil, the notes will be orderer according to time."
1879 :group 'org-todo
1880 :group 'org-progress
1881 :type 'boolean)
1883 (defcustom org-log-repeat 'time
1884 "Non-nil means, record moving through the DONE state when triggering repeat.
1885 An auto-repeating tasks is immediately switched back to TODO when marked
1886 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1887 the TODO keyword definition, or recording a cloing note by setting
1888 `org-log-done', there will be no record of the task moving trhough DONE.
1889 This variable forces taking a note anyway. Possible values are:
1891 nil Don't force a record
1892 time Record a time stamp
1893 note Record a note
1895 This option can also be set with on a per-file-basis with
1897 #+STARTUP: logrepeat
1898 #+STARTUP: lognoterepeat
1899 #+STARTUP: nologrepeat
1901 You can have local logging settings for a subtree by setting the LOGGING
1902 property to one or more of these keywords."
1903 :group 'org-todo
1904 :group 'org-progress
1905 :type '(choice
1906 (const :tag "Don't force a record" nil)
1907 (const :tag "Force recording the DONE state" time)
1908 (const :tag "Force recording a note with the DONE state" note)))
1910 (defcustom org-clock-into-drawer 2
1911 "Should clocking info be wrapped into a drawer?
1912 When t, clocking info will always be inserted into a :CLOCK: drawer.
1913 If necessary, the drawer will be created.
1914 When nil, the drawer will not be created, but used when present.
1915 When an integer and the number of clocking entries in an item
1916 reaches or exceeds this number, a drawer will be created."
1917 :group 'org-todo
1918 :group 'org-progress
1919 :type '(choice
1920 (const :tag "Always" t)
1921 (const :tag "Only when drawer exists" nil)
1922 (integer :tag "When at least N clock entries")))
1924 (defcustom org-clock-out-when-done t
1925 "When t, the clock will be stopped when the relevant entry is marked DONE.
1926 Nil means, clock will keep running until stopped explicitly with
1927 `C-c C-x C-o', or until the clock is started in a different item."
1928 :group 'org-progress
1929 :type 'boolean)
1931 (defcustom org-clock-in-switch-to-state nil
1932 "Set task to a special todo state while clocking it.
1933 The value should be the state to which the entry should be switched."
1934 :group 'org-progress
1935 :group 'org-todo
1936 :type '(choice
1937 (const :tag "Don't force a state" nil)
1938 (string :tag "State")))
1940 (defgroup org-priorities nil
1941 "Priorities in Org-mode."
1942 :tag "Org Priorities"
1943 :group 'org-todo)
1945 (defcustom org-highest-priority ?A
1946 "The highest priority of TODO items. A character like ?A, ?B etc.
1947 Must have a smaller ASCII number than `org-lowest-priority'."
1948 :group 'org-priorities
1949 :type 'character)
1951 (defcustom org-lowest-priority ?C
1952 "The lowest priority of TODO items. A character like ?A, ?B etc.
1953 Must have a larger ASCII number than `org-highest-priority'."
1954 :group 'org-priorities
1955 :type 'character)
1957 (defcustom org-default-priority ?B
1958 "The default priority of TODO items.
1959 This is the priority an item get if no explicit priority is given."
1960 :group 'org-priorities
1961 :type 'character)
1963 (defcustom org-priority-start-cycle-with-default t
1964 "Non-nil means, start with default priority when starting to cycle.
1965 When this is nil, the first step in the cycle will be (depending on the
1966 command used) one higher or lower that the default priority."
1967 :group 'org-priorities
1968 :type 'boolean)
1970 (defgroup org-time nil
1971 "Options concerning time stamps and deadlines in Org-mode."
1972 :tag "Org Time"
1973 :group 'org)
1975 (defcustom org-insert-labeled-timestamps-at-point nil
1976 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1977 When nil, these labeled time stamps are forces into the second line of an
1978 entry, just after the headline. When scheduling from the global TODO list,
1979 the time stamp will always be forced into the second line."
1980 :group 'org-time
1981 :type 'boolean)
1983 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1984 "Formats for `format-time-string' which are used for time stamps.
1985 It is not recommended to change this constant.")
1987 (defcustom org-time-stamp-rounding-minutes '(0 5)
1988 "Number of minutes to round time stamps to.
1989 These are two values, the first applies when first creating a time stamp.
1990 The second applies when changing it with the commands `S-up' and `S-down'.
1991 When changing the time stamp, this means that it will change in steps
1992 of N minues, as given by the second value.
1994 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1995 numbers should be factors of 60, so for example 5, 10, 15.
1997 When this is larger than 1, you can still force an exact time-stamp by using
1998 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1999 and by using a prefix arg to `S-up/down' to specify the exact number
2000 of minutes to shift."
2001 :group 'org-time
2002 :get '(lambda (var) ; Make sure all entries have 5 elements
2003 (if (integerp (default-value var))
2004 (list (default-value var) 5)
2005 (default-value var)))
2006 :type '(list
2007 (integer :tag "when inserting times")
2008 (integer :tag "when modifying times")))
2010 (defcustom org-display-custom-times nil
2011 "Non-nil means, overlay custom formats over all time stamps.
2012 The formats are defined through the variable `org-time-stamp-custom-formats'.
2013 To turn this on on a per-file basis, insert anywhere in the file:
2014 #+STARTUP: customtime"
2015 :group 'org-time
2016 :set 'set-default
2017 :type 'sexp)
2018 (make-variable-buffer-local 'org-display-custom-times)
2020 (defcustom org-time-stamp-custom-formats
2021 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2022 "Custom formats for time stamps. See `format-time-string' for the syntax.
2023 These are overlayed over the default ISO format if the variable
2024 `org-display-custom-times' is set. Time like %H:%M should be at the
2025 end of the second format."
2026 :group 'org-time
2027 :type 'sexp)
2029 (defun org-time-stamp-format (&optional long inactive)
2030 "Get the right format for a time string."
2031 (let ((f (if long (cdr org-time-stamp-formats)
2032 (car org-time-stamp-formats))))
2033 (if inactive
2034 (concat "[" (substring f 1 -1) "]")
2035 f)))
2037 (defcustom org-read-date-prefer-future t
2038 "Non-nil means, assume future for incomplete date input from user.
2039 This affects the following situations:
2040 1. The user gives a day, but no month.
2041 For example, if today is the 15th, and you enter \"3\", Org-mode will
2042 read this as the third of *next* month. However, if you enter \"17\",
2043 it will be considered as *this* month.
2044 2. The user gives a month but not a year.
2045 For example, if it is april and you enter \"feb 2\", this will be read
2046 as feb 2, *next* year. \"May 5\", however, will be this year.
2048 When this option is nil, the current month and year will always be used
2049 as defaults."
2050 :group 'org-time
2051 :type 'boolean)
2053 (defcustom org-read-date-display-live t
2054 "Non-nil means, display current interpretation of date prompt live.
2055 This display will be in an overlay, in the minibuffer."
2056 :group 'org-time
2057 :type 'boolean)
2059 (defcustom org-read-date-popup-calendar t
2060 "Non-nil means, pop up a calendar when prompting for a date.
2061 In the calendar, the date can be selected with mouse-1. However, the
2062 minibuffer will also be active, and you can simply enter the date as well.
2063 When nil, only the minibuffer will be available."
2064 :group 'org-time
2065 :type 'boolean)
2066 (if (fboundp 'defvaralias)
2067 (defvaralias 'org-popup-calendar-for-date-prompt
2068 'org-read-date-popup-calendar))
2070 (defcustom org-extend-today-until 0
2071 "The hour when your day really ends.
2072 This has influence for the following applications:
2073 - When switching the agenda to \"today\". It it is still earlier than
2074 the time given here, the day recognized as TODAY is actually yesterday.
2075 - When a date is read from the user and it is still before the time given
2076 here, the current date and time will be assumed to be yesterday, 23:59.
2078 FIXME:
2079 IMPORTANT: This is still a very experimental feature, it may disappear
2080 again or it may be extended to mean more things."
2081 :group 'org-time
2082 :type 'number)
2084 (defcustom org-edit-timestamp-down-means-later nil
2085 "Non-nil means, S-down will increase the time in a time stamp.
2086 When nil, S-up will increase."
2087 :group 'org-time
2088 :type 'boolean)
2090 (defcustom org-calendar-follow-timestamp-change t
2091 "Non-nil means, make the calendar window follow timestamp changes.
2092 When a timestamp is modified and the calendar window is visible, it will be
2093 moved to the new date."
2094 :group 'org-time
2095 :type 'boolean)
2097 (defcustom org-clock-heading-function nil
2098 "When non-nil, should be a function to create `org-clock-heading'.
2099 This is the string shown in the mode line when a clock is running.
2100 The function is called with point at the beginning of the headline."
2101 :group 'org-time ; FIXME: Should we have a separate group????
2102 :type 'function)
2104 (defgroup org-tags nil
2105 "Options concerning tags in Org-mode."
2106 :tag "Org Tags"
2107 :group 'org)
2109 (defcustom org-tag-alist nil
2110 "List of tags allowed in Org-mode files.
2111 When this list is nil, Org-mode will base TAG input on what is already in the
2112 buffer.
2113 The value of this variable is an alist, the car of each entry must be a
2114 keyword as a string, the cdr may be a character that is used to select
2115 that tag through the fast-tag-selection interface.
2116 See the manual for details."
2117 :group 'org-tags
2118 :type '(repeat
2119 (choice
2120 (cons (string :tag "Tag name")
2121 (character :tag "Access char"))
2122 (const :tag "Start radio group" (:startgroup))
2123 (const :tag "End radio group" (:endgroup)))))
2125 (defcustom org-use-fast-tag-selection 'auto
2126 "Non-nil means, use fast tag selection scheme.
2127 This is a special interface to select and deselect tags with single keys.
2128 When nil, fast selection is never used.
2129 When the symbol `auto', fast selection is used if and only if selection
2130 characters for tags have been configured, either through the variable
2131 `org-tag-alist' or through a #+TAGS line in the buffer.
2132 When t, fast selection is always used and selection keys are assigned
2133 automatically if necessary."
2134 :group 'org-tags
2135 :type '(choice
2136 (const :tag "Always" t)
2137 (const :tag "Never" nil)
2138 (const :tag "When selection characters are configured" 'auto)))
2140 (defcustom org-fast-tag-selection-single-key nil
2141 "Non-nil means, fast tag selection exits after first change.
2142 When nil, you have to press RET to exit it.
2143 During fast tag selection, you can toggle this flag with `C-c'.
2144 This variable can also have the value `expert'. In this case, the window
2145 displaying the tags menu is not even shown, until you press C-c again."
2146 :group 'org-tags
2147 :type '(choice
2148 (const :tag "No" nil)
2149 (const :tag "Yes" t)
2150 (const :tag "Expert" expert)))
2152 (defvar org-fast-tag-selection-include-todo nil
2153 "Non-nil means, fast tags selection interface will also offer TODO states.
2154 This is an undocumented feature, you should not rely on it.")
2156 (defcustom org-tags-column -80
2157 "The column to which tags should be indented in a headline.
2158 If this number is positive, it specifies the column. If it is negative,
2159 it means that the tags should be flushright to that column. For example,
2160 -80 works well for a normal 80 character screen."
2161 :group 'org-tags
2162 :type 'integer)
2164 (defcustom org-auto-align-tags t
2165 "Non-nil means, realign tags after pro/demotion of TODO state change.
2166 These operations change the length of a headline and therefore shift
2167 the tags around. With this options turned on, after each such operation
2168 the tags are again aligned to `org-tags-column'."
2169 :group 'org-tags
2170 :type 'boolean)
2172 (defcustom org-use-tag-inheritance t
2173 "Non-nil means, tags in levels apply also for sublevels.
2174 When nil, only the tags directly given in a specific line apply there.
2175 If you turn off this option, you very likely want to turn on the
2176 companion option `org-tags-match-list-sublevels'."
2177 :group 'org-tags
2178 :type 'boolean)
2180 (defcustom org-tags-match-list-sublevels nil
2181 "Non-nil means list also sublevels of headlines matching tag search.
2182 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2183 the sublevels of a headline matching a tag search often also match
2184 the same search. Listing all of them can create very long lists.
2185 Setting this variable to nil causes subtrees of a match to be skipped.
2186 This option is off by default, because inheritance in on. If you turn
2187 inheritance off, you very likely want to turn this option on.
2189 As a special case, if the tag search is restricted to TODO items, the
2190 value of this variable is ignored and sublevels are always checked, to
2191 make sure all corresponding TODO items find their way into the list."
2192 :group 'org-tags
2193 :type 'boolean)
2195 (defvar org-tags-history nil
2196 "History of minibuffer reads for tags.")
2197 (defvar org-last-tags-completion-table nil
2198 "The last used completion table for tags.")
2199 (defvar org-after-tags-change-hook nil
2200 "Hook that is run after the tags in a line have changed.")
2202 (defgroup org-properties nil
2203 "Options concerning properties in Org-mode."
2204 :tag "Org Properties"
2205 :group 'org)
2207 (defcustom org-property-format "%-10s %s"
2208 "How property key/value pairs should be formatted by `indent-line'.
2209 When `indent-line' hits a property definition, it will format the line
2210 according to this format, mainly to make sure that the values are
2211 lined-up with respect to each other."
2212 :group 'org-properties
2213 :type 'string)
2215 (defcustom org-use-property-inheritance nil
2216 "Non-nil means, properties apply also for sublevels.
2217 This setting is only relevant during property searches, not when querying
2218 an entry with `org-entry-get'. To retrieve a property with inheritance,
2219 you need to call `org-entry-get' with the inheritance flag.
2220 Turning this on can cause significant overhead when doing a search, so
2221 this is turned off by default.
2222 When nil, only the properties directly given in the current entry count.
2223 The value may also be a list of properties that shouldhave inheritance.
2225 However, note that some special properties use inheritance under special
2226 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2227 and the properties ending in \"_ALL\" when they are used as descriptor
2228 for valid values of a property."
2229 :group 'org-properties
2230 :type '(choice
2231 (const :tag "Not" nil)
2232 (const :tag "Always" nil)
2233 (repeat :tag "Specific properties" (string :tag "Property"))))
2235 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2236 "The default column format, if no other format has been defined.
2237 This variable can be set on the per-file basis by inserting a line
2239 #+COLUMNS: %25ITEM ....."
2240 :group 'org-properties
2241 :type 'string)
2243 (defcustom org-global-properties nil
2244 "List of property/value pairs that can be inherited by any entry.
2245 You can set buffer-local values for this by adding lines like
2247 #+PROPERTY: NAME VALUE"
2248 :group 'org-properties
2249 :type '(repeat
2250 (cons (string :tag "Property")
2251 (string :tag "Value"))))
2253 (defvar org-local-properties nil
2254 "List of property/value pairs that can be inherited by any entry.
2255 Valid for the current buffer.
2256 This variable is populated from #+PROPERTY lines.")
2258 (defgroup org-agenda nil
2259 "Options concerning agenda views in Org-mode."
2260 :tag "Org Agenda"
2261 :group 'org)
2263 (defvar org-category nil
2264 "Variable used by org files to set a category for agenda display.
2265 Such files should use a file variable to set it, for example
2267 # -*- mode: org; org-category: \"ELisp\"
2269 or contain a special line
2271 #+CATEGORY: ELisp
2273 If the file does not specify a category, then file's base name
2274 is used instead.")
2275 (make-variable-buffer-local 'org-category)
2277 (defcustom org-agenda-files nil
2278 "The files to be used for agenda display.
2279 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2280 \\[org-remove-file]. You can also use customize to edit the list.
2282 If an entry is a directory, all files in that directory that are matched by
2283 `org-agenda-file-regexp' will be part of the file list.
2285 If the value of the variable is not a list but a single file name, then
2286 the list of agenda files is actually stored and maintained in that file, one
2287 agenda file per line."
2288 :group 'org-agenda
2289 :type '(choice
2290 (repeat :tag "List of files and directories" file)
2291 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2293 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2294 "Regular expression to match files for `org-agenda-files'.
2295 If any element in the list in that variable contains a directory instead
2296 of a normal file, all files in that directory that are matched by this
2297 regular expression will be included."
2298 :group 'org-agenda
2299 :type 'regexp)
2301 (defcustom org-agenda-skip-unavailable-files nil
2302 "t means to just skip non-reachable files in `org-agenda-files'.
2303 Nil means to remove them, after a query, from the list."
2304 :group 'org-agenda
2305 :type 'boolean)
2307 (defcustom org-agenda-text-search-extra-files nil
2308 "List of extra files to be searched by text search commands.
2309 These files will be search in addition to the agenda files bu the
2310 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2311 Note that these files will only be searched for text search commands,
2312 not for the other agenda views like todo lists, tag earches or the weekly
2313 agenda. This variable is intended to list notes and possibly archive files
2314 that should also be searched by these two commands."
2315 :group 'org-agenda
2316 :type '(repeat file))
2318 (if (fboundp 'defvaralias)
2319 (defvaralias 'org-agenda-multi-occur-extra-files
2320 'org-agenda-text-search-extra-files))
2322 (defcustom org-agenda-confirm-kill 1
2323 "When set, remote killing from the agenda buffer needs confirmation.
2324 When t, a confirmation is always needed. When a number N, confirmation is
2325 only needed when the text to be killed contains more than N non-white lines."
2326 :group 'org-agenda
2327 :type '(choice
2328 (const :tag "Never" nil)
2329 (const :tag "Always" t)
2330 (number :tag "When more than N lines")))
2332 (defcustom org-calendar-to-agenda-key [?c]
2333 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2334 The command `org-calendar-goto-agenda' will be bound to this key. The
2335 default is the character `c' because then `c' can be used to switch back and
2336 forth between agenda and calendar."
2337 :group 'org-agenda
2338 :type 'sexp)
2340 (defcustom org-agenda-compact-blocks nil
2341 "Non-nil means, make the block agenda more compact.
2342 This is done by leaving out unnecessary lines."
2343 :group 'org-agenda
2344 :type nil)
2346 (defgroup org-agenda-export nil
2347 "Options concerning exporting agenda views in Org-mode."
2348 :tag "Org Agenda Export"
2349 :group 'org-agenda)
2351 (defcustom org-agenda-with-colors t
2352 "Non-nil means, use colors in agenda views."
2353 :group 'org-agenda-export
2354 :type 'boolean)
2356 (defcustom org-agenda-exporter-settings nil
2357 "Alist of variable/value pairs that should be active during agenda export.
2358 This is a good place to set uptions for ps-print and for htmlize."
2359 :group 'org-agenda-export
2360 :type '(repeat
2361 (list
2362 (variable)
2363 (sexp :tag "Value"))))
2365 (defcustom org-agenda-export-html-style ""
2366 "The style specification for exported HTML Agenda files.
2367 If this variable contains a string, it will replace the default <style>
2368 section as produced by `htmlize'.
2369 Since there are different ways of setting style information, this variable
2370 needs to contain the full HTML structure to provide a style, including the
2371 surrounding HTML tags. The style specifications should include definitions
2372 the fonts used by the agenda, here is an example:
2374 <style type=\"text/css\">
2375 p { font-weight: normal; color: gray; }
2376 .org-agenda-structure {
2377 font-size: 110%;
2378 color: #003399;
2379 font-weight: 600;
2381 .org-todo {
2382 color: #cc6666;Week-agenda:
2383 font-weight: bold;
2385 .org-done {
2386 color: #339933;
2388 .title { text-align: center; }
2389 .todo, .deadline { color: red; }
2390 .done { color: green; }
2391 </style>
2393 or, if you want to keep the style in a file,
2395 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2397 As the value of this option simply gets inserted into the HTML <head> header,
2398 you can \"misuse\" it to also add other text to the header. However,
2399 <style>...</style> is required, if not present the variable will be ignored."
2400 :group 'org-agenda-export
2401 :group 'org-export-html
2402 :type 'string)
2404 (defgroup org-agenda-custom-commands nil
2405 "Options concerning agenda views in Org-mode."
2406 :tag "Org Agenda Custom Commands"
2407 :group 'org-agenda)
2409 (defcustom org-agenda-custom-commands nil
2410 "Custom commands for the agenda.
2411 These commands will be offered on the splash screen displayed by the
2412 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2414 (key desc type match options files)
2416 key The key (one or more characters as a string) to be associated
2417 with the command.
2418 desc A description of the commend, when omitted or nil, a default
2419 description is built using MATCH.
2420 type The command type, any of the following symbols:
2421 agenda The daily/weekly agenda.
2422 todo Entries with a specific TODO keyword, in all agenda files.
2423 search Entries containing search words entry or headline.
2424 tags Tags/Property/TODO match in all agenda files.
2425 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2426 todo-tree Sparse tree of specific TODO keyword in *current* file.
2427 tags-tree Sparse tree with all tags matches in *current* file.
2428 occur-tree Occur sparse tree for *current* file.
2429 ... A user-defined function.
2430 match What to search for:
2431 - a single keyword for TODO keyword searches
2432 - a tags match expression for tags searches
2433 - a regular expression for occur searches
2434 options A list of option settings, similar to that in a let form, so like
2435 this: ((opt1 val1) (opt2 val2) ...)
2436 files A list of files file to write the produced agenda buffer to
2437 with the command `org-store-agenda-views'.
2438 If a file name ends in \".html\", an HTML version of the buffer
2439 is written out. If it ends in \".ps\", a postscript version is
2440 produced. Otherwide, only the plain text is written to the file.
2442 You can also define a set of commands, to create a composite agenda buffer.
2443 In this case, an entry looks like this:
2445 (key desc (cmd1 cmd2 ...) general-options file)
2447 where
2449 desc A description string to be displayed in the dispatcher menu.
2450 cmd An agenda command, similar to the above. However, tree commands
2451 are no allowed, but instead you can get agenda and global todo list.
2452 So valid commands for a set are:
2453 (agenda)
2454 (alltodo)
2455 (stuck)
2456 (todo \"match\" options files)
2457 (search \"match\" options files)
2458 (tags \"match\" options files)
2459 (tags-todo \"match\" options files)
2461 Each command can carry a list of options, and another set of options can be
2462 given for the whole set of commands. Individual command options take
2463 precedence over the general options.
2465 When using several characters as key to a command, the first characters
2466 are prefix commands. For the dispatcher to display useful information, you
2467 should provide a description for the prefix, like
2469 (setq org-agenda-custom-commands
2470 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2471 (\"hl\" tags \"+HOME+Lisa\")
2472 (\"hp\" tags \"+HOME+Peter\")
2473 (\"hk\" tags \"+HOME+Kim\")))"
2474 :group 'org-agenda-custom-commands
2475 :type '(repeat
2476 (choice :value ("a" "" tags "" nil)
2477 (list :tag "Single command"
2478 (string :tag "Access Key(s) ")
2479 (option (string :tag "Description"))
2480 (choice
2481 (const :tag "Agenda" agenda)
2482 (const :tag "TODO list" alltodo)
2483 (const :tag "Search words" search)
2484 (const :tag "Stuck projects" stuck)
2485 (const :tag "Tags search (all agenda files)" tags)
2486 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2487 (const :tag "TODO keyword search (all agenda files)" todo)
2488 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2489 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2490 (const :tag "Occur tree (current buffer)" occur-tree)
2491 (sexp :tag "Other, user-defined function"))
2492 (string :tag "Match")
2493 (repeat :tag "Local options"
2494 (list (variable :tag "Option") (sexp :tag "Value")))
2495 (option (repeat :tag "Export" (file :tag "Export to"))))
2496 (list :tag "Command series, all agenda files"
2497 (string :tag "Access Key(s)")
2498 (string :tag "Description ")
2499 (repeat :tag "Component"
2500 (choice
2501 (const :tag "Agenda" (agenda))
2502 (const :tag "TODO list" (alltodo))
2503 (list :tag "Search words"
2504 (const :format "" search)
2505 (string :tag "Match")
2506 (repeat :tag "Local options"
2507 (list (variable :tag "Option")
2508 (sexp :tag "Value"))))
2509 (const :tag "Stuck projects" (stuck))
2510 (list :tag "Tags search"
2511 (const :format "" tags)
2512 (string :tag "Match")
2513 (repeat :tag "Local options"
2514 (list (variable :tag "Option")
2515 (sexp :tag "Value"))))
2517 (list :tag "Tags search, TODO entries only"
2518 (const :format "" tags-todo)
2519 (string :tag "Match")
2520 (repeat :tag "Local options"
2521 (list (variable :tag "Option")
2522 (sexp :tag "Value"))))
2524 (list :tag "TODO keyword search"
2525 (const :format "" todo)
2526 (string :tag "Match")
2527 (repeat :tag "Local options"
2528 (list (variable :tag "Option")
2529 (sexp :tag "Value"))))
2531 (list :tag "Other, user-defined function"
2532 (symbol :tag "function")
2533 (string :tag "Match")
2534 (repeat :tag "Local options"
2535 (list (variable :tag "Option")
2536 (sexp :tag "Value"))))))
2538 (repeat :tag "General options"
2539 (list (variable :tag "Option")
2540 (sexp :tag "Value")))
2541 (option (repeat :tag "Export" (file :tag "Export to"))))
2542 (cons :tag "Prefix key documentation"
2543 (string :tag "Access Key(s)")
2544 (string :tag "Description ")))))
2546 (defcustom org-agenda-query-register ?o
2547 "The register holding the current query string.
2548 The prupose of this is that if you construct a query string interactively,
2549 you can then use it to define a custom command."
2550 :group 'org-agenda-custom-commands
2551 :type 'character)
2553 (defcustom org-stuck-projects
2554 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2555 "How to identify stuck projects.
2556 This is a list of four items:
2557 1. A tags/todo matcher string that is used to identify a project.
2558 The entire tree below a headline matched by this is considered one project.
2559 2. A list of TODO keywords identifying non-stuck projects.
2560 If the project subtree contains any headline with one of these todo
2561 keywords, the project is considered to be not stuck. If you specify
2562 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2563 3. A list of tags identifying non-stuck projects.
2564 If the project subtree contains any headline with one of these tags,
2565 the project is considered to be not stuck. If you specify \"*\" as
2566 a tag, any tag will mark the project unstuck.
2567 4. An arbitrary regular expression matching non-stuck projects.
2569 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2570 or `C-c a #' to produce the list."
2571 :group 'org-agenda-custom-commands
2572 :type '(list
2573 (string :tag "Tags/TODO match to identify a project")
2574 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2575 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2576 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2579 (defgroup org-agenda-skip nil
2580 "Options concerning skipping parts of agenda files."
2581 :tag "Org Agenda Skip"
2582 :group 'org-agenda)
2584 (defcustom org-agenda-todo-list-sublevels t
2585 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2586 When nil, the sublevels of a TODO entry are not checked, resulting in
2587 potentially much shorter TODO lists."
2588 :group 'org-agenda-skip
2589 :group 'org-todo
2590 :type 'boolean)
2592 (defcustom org-agenda-todo-ignore-with-date nil
2593 "Non-nil means, don't show entries with a date in the global todo list.
2594 You can use this if you prefer to mark mere appointments with a TODO keyword,
2595 but don't want them to show up in the TODO list.
2596 When this is set, it also covers deadlines and scheduled items, the settings
2597 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2598 will be ignored."
2599 :group 'org-agenda-skip
2600 :group 'org-todo
2601 :type 'boolean)
2603 (defcustom org-agenda-todo-ignore-scheduled nil
2604 "Non-nil means, don't show scheduled entries in the global todo list.
2605 The idea behind this is that by scheduling it, you have already taken care
2606 of this item.
2607 See also `org-agenda-todo-ignore-with-date'."
2608 :group 'org-agenda-skip
2609 :group 'org-todo
2610 :type 'boolean)
2612 (defcustom org-agenda-todo-ignore-deadlines nil
2613 "Non-nil means, don't show near deadline entries in the global todo list.
2614 Near means closer than `org-deadline-warning-days' days.
2615 The idea behind this is that such items will appear in the agenda anyway.
2616 See also `org-agenda-todo-ignore-with-date'."
2617 :group 'org-agenda-skip
2618 :group 'org-todo
2619 :type 'boolean)
2621 (defcustom org-agenda-skip-scheduled-if-done nil
2622 "Non-nil means don't show scheduled items in agenda when they are done.
2623 This is relevant for the daily/weekly agenda, not for the TODO list. And
2624 it applies only to the actual date of the scheduling. Warnings about
2625 an item with a past scheduling dates are always turned off when the item
2626 is DONE."
2627 :group 'org-agenda-skip
2628 :type 'boolean)
2630 (defcustom org-agenda-skip-deadline-if-done nil
2631 "Non-nil means don't show deadines when the corresponding item is done.
2632 When nil, the deadline is still shown and should give you a happy feeling.
2633 This is relevant for the daily/weekly agenda. And it applied only to the
2634 actualy date of the deadline. Warnings about approching and past-due
2635 deadlines are always turned off when the item is DONE."
2636 :group 'org-agenda-skip
2637 :type 'boolean)
2639 (defcustom org-agenda-skip-timestamp-if-done nil
2640 "Non-nil means don't select item by timestamp or -range if it is DONE."
2641 :group 'org-agenda-skip
2642 :type 'boolean)
2644 (defcustom org-timeline-show-empty-dates 3
2645 "Non-nil means, `org-timeline' also shows dates without an entry.
2646 When nil, only the days which actually have entries are shown.
2647 When t, all days between the first and the last date are shown.
2648 When an integer, show also empty dates, but if there is a gap of more than
2649 N days, just insert a special line indicating the size of the gap."
2650 :group 'org-agenda-skip
2651 :type '(choice
2652 (const :tag "None" nil)
2653 (const :tag "All" t)
2654 (number :tag "at most")))
2657 (defgroup org-agenda-startup nil
2658 "Options concerning initial settings in the Agenda in Org Mode."
2659 :tag "Org Agenda Startup"
2660 :group 'org-agenda)
2662 (defcustom org-finalize-agenda-hook nil
2663 "Hook run just before displaying an agenda buffer."
2664 :group 'org-agenda-startup
2665 :type 'hook)
2667 (defcustom org-agenda-mouse-1-follows-link nil
2668 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2669 A longer mouse click will still set point. Does not work on XEmacs.
2670 Needs to be set before org.el is loaded."
2671 :group 'org-agenda-startup
2672 :type 'boolean)
2674 (defcustom org-agenda-start-with-follow-mode nil
2675 "The initial value of follow-mode in a newly created agenda window."
2676 :group 'org-agenda-startup
2677 :type 'boolean)
2679 (defgroup org-agenda-windows nil
2680 "Options concerning the windows used by the Agenda in Org Mode."
2681 :tag "Org Agenda Windows"
2682 :group 'org-agenda)
2684 (defcustom org-agenda-window-setup 'reorganize-frame
2685 "How the agenda buffer should be displayed.
2686 Possible values for this option are:
2688 current-window Show agenda in the current window, keeping all other windows.
2689 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2690 other-window Use `switch-to-buffer-other-window' to display agenda.
2691 reorganize-frame Show only two windows on the current frame, the current
2692 window and the agenda.
2693 See also the variable `org-agenda-restore-windows-after-quit'."
2694 :group 'org-agenda-windows
2695 :type '(choice
2696 (const current-window)
2697 (const other-frame)
2698 (const other-window)
2699 (const reorganize-frame)))
2701 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2702 "The min and max height of the agenda window as a fraction of frame height.
2703 The value of the variable is a cons cell with two numbers between 0 and 1.
2704 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2705 :group 'org-agenda-windows
2706 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2708 (defcustom org-agenda-restore-windows-after-quit nil
2709 "Non-nil means, restore window configuration open exiting agenda.
2710 Before the window configuration is changed for displaying the agenda,
2711 the current status is recorded. When the agenda is exited with
2712 `q' or `x' and this option is set, the old state is restored. If
2713 `org-agenda-window-setup' is `other-frame', the value of this
2714 option will be ignored.."
2715 :group 'org-agenda-windows
2716 :type 'boolean)
2718 (defcustom org-indirect-buffer-display 'other-window
2719 "How should indirect tree buffers be displayed?
2720 This applies to indirect buffers created with the commands
2721 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2722 Valid values are:
2723 current-window Display in the current window
2724 other-window Just display in another window.
2725 dedicated-frame Create one new frame, and re-use it each time.
2726 new-frame Make a new frame each time. Note that in this case
2727 previously-made indirect buffers are kept, and you need to
2728 kill these buffers yourself."
2729 :group 'org-structure
2730 :group 'org-agenda-windows
2731 :type '(choice
2732 (const :tag "In current window" current-window)
2733 (const :tag "In current frame, other window" other-window)
2734 (const :tag "Each time a new frame" new-frame)
2735 (const :tag "One dedicated frame" dedicated-frame)))
2737 (defgroup org-agenda-daily/weekly nil
2738 "Options concerning the daily/weekly agenda."
2739 :tag "Org Agenda Daily/Weekly"
2740 :group 'org-agenda)
2742 (defcustom org-agenda-ndays 7
2743 "Number of days to include in overview display.
2744 Should be 1 or 7."
2745 :group 'org-agenda-daily/weekly
2746 :type 'number)
2748 (defcustom org-agenda-start-on-weekday 1
2749 "Non-nil means, start the overview always on the specified weekday.
2750 0 denotes Sunday, 1 denotes Monday etc.
2751 When nil, always start on the current day."
2752 :group 'org-agenda-daily/weekly
2753 :type '(choice (const :tag "Today" nil)
2754 (number :tag "Weekday No.")))
2756 (defcustom org-agenda-show-all-dates t
2757 "Non-nil means, `org-agenda' shows every day in the selected range.
2758 When nil, only the days which actually have entries are shown."
2759 :group 'org-agenda-daily/weekly
2760 :type 'boolean)
2762 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2763 "Format string for displaying dates in the agenda.
2764 Used by the daily/weekly agenda and by the timeline. This should be
2765 a format string understood by `format-time-string', or a function returning
2766 the formatted date as a string. The function must take a single argument,
2767 a calendar-style date list like (month day year)."
2768 :group 'org-agenda-daily/weekly
2769 :type '(choice
2770 (string :tag "Format string")
2771 (function :tag "Function")))
2773 (defun org-agenda-format-date-aligned (date)
2774 "Format a date string for display in the daily/weekly agenda, or timeline.
2775 This function makes sure that dates are aligned for easy reading."
2776 (format "%-9s %2d %s %4d"
2777 (calendar-day-name date)
2778 (extract-calendar-day date)
2779 (calendar-month-name (extract-calendar-month date))
2780 (extract-calendar-year date)))
2782 (defcustom org-agenda-include-diary nil
2783 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2784 :group 'org-agenda-daily/weekly
2785 :type 'boolean)
2787 (defcustom org-agenda-include-all-todo nil
2788 "Set means weekly/daily agenda will always contain all TODO entries.
2789 The TODO entries will be listed at the top of the agenda, before
2790 the entries for specific days."
2791 :group 'org-agenda-daily/weekly
2792 :type 'boolean)
2794 (defcustom org-agenda-repeating-timestamp-show-all t
2795 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2796 When nil, only one occurence is shown, either today or the
2797 nearest into the future."
2798 :group 'org-agenda-daily/weekly
2799 :type 'boolean)
2801 (defcustom org-deadline-warning-days 14
2802 "No. of days before expiration during which a deadline becomes active.
2803 This variable governs the display in sparse trees and in the agenda.
2804 When 0 or negative, it means use this number (the absolute value of it)
2805 even if a deadline has a different individual lead time specified."
2806 :group 'org-time
2807 :group 'org-agenda-daily/weekly
2808 :type 'number)
2810 (defcustom org-scheduled-past-days 10000
2811 "No. of days to continue listing scheduled items that are not marked DONE.
2812 When an item is scheduled on a date, it shows up in the agenda on this
2813 day and will be listed until it is marked done for the number of days
2814 given here."
2815 :group 'org-agenda-daily/weekly
2816 :type 'number)
2818 (defgroup org-agenda-time-grid nil
2819 "Options concerning the time grid in the Org-mode Agenda."
2820 :tag "Org Agenda Time Grid"
2821 :group 'org-agenda)
2823 (defcustom org-agenda-use-time-grid t
2824 "Non-nil means, show a time grid in the agenda schedule.
2825 A time grid is a set of lines for specific times (like every two hours between
2826 8:00 and 20:00). The items scheduled for a day at specific times are
2827 sorted in between these lines.
2828 For details about when the grid will be shown, and what it will look like, see
2829 the variable `org-agenda-time-grid'."
2830 :group 'org-agenda-time-grid
2831 :type 'boolean)
2833 (defcustom org-agenda-time-grid
2834 '((daily today require-timed)
2835 "----------------"
2836 (800 1000 1200 1400 1600 1800 2000))
2838 "The settings for time grid for agenda display.
2839 This is a list of three items. The first item is again a list. It contains
2840 symbols specifying conditions when the grid should be displayed:
2842 daily if the agenda shows a single day
2843 weekly if the agenda shows an entire week
2844 today show grid on current date, independent of daily/weekly display
2845 require-timed show grid only if at least one item has a time specification
2847 The second item is a string which will be places behing the grid time.
2849 The third item is a list of integers, indicating the times that should have
2850 a grid line."
2851 :group 'org-agenda-time-grid
2852 :type
2853 '(list
2854 (set :greedy t :tag "Grid Display Options"
2855 (const :tag "Show grid in single day agenda display" daily)
2856 (const :tag "Show grid in weekly agenda display" weekly)
2857 (const :tag "Always show grid for today" today)
2858 (const :tag "Show grid only if any timed entries are present"
2859 require-timed)
2860 (const :tag "Skip grid times already present in an entry"
2861 remove-match))
2862 (string :tag "Grid String")
2863 (repeat :tag "Grid Times" (integer :tag "Time"))))
2865 (defgroup org-agenda-sorting nil
2866 "Options concerning sorting in the Org-mode Agenda."
2867 :tag "Org Agenda Sorting"
2868 :group 'org-agenda)
2870 (defconst org-sorting-choice
2871 '(choice
2872 (const time-up) (const time-down)
2873 (const category-keep) (const category-up) (const category-down)
2874 (const tag-down) (const tag-up)
2875 (const priority-up) (const priority-down))
2876 "Sorting choices.")
2878 (defcustom org-agenda-sorting-strategy
2879 '((agenda time-up category-keep priority-down)
2880 (todo category-keep priority-down)
2881 (tags category-keep priority-down)
2882 (search category-keep))
2883 "Sorting structure for the agenda items of a single day.
2884 This is a list of symbols which will be used in sequence to determine
2885 if an entry should be listed before another entry. The following
2886 symbols are recognized:
2888 time-up Put entries with time-of-day indications first, early first
2889 time-down Put entries with time-of-day indications first, late first
2890 category-keep Keep the default order of categories, corresponding to the
2891 sequence in `org-agenda-files'.
2892 category-up Sort alphabetically by category, A-Z.
2893 category-down Sort alphabetically by category, Z-A.
2894 tag-up Sort alphabetically by last tag, A-Z.
2895 tag-down Sort alphabetically by last tag, Z-A.
2896 priority-up Sort numerically by priority, high priority last.
2897 priority-down Sort numerically by priority, high priority first.
2899 The different possibilities will be tried in sequence, and testing stops
2900 if one comparison returns a \"not-equal\". For example, the default
2901 '(time-up category-keep priority-down)
2902 means: Pull out all entries having a specified time of day and sort them,
2903 in order to make a time schedule for the current day the first thing in the
2904 agenda listing for the day. Of the entries without a time indication, keep
2905 the grouped in categories, don't sort the categories, but keep them in
2906 the sequence given in `org-agenda-files'. Within each category sort by
2907 priority.
2909 Leaving out `category-keep' would mean that items will be sorted across
2910 categories by priority.
2912 Instead of a single list, this can also be a set of list for specific
2913 contents, with a context symbol in the car of the list, any of
2914 `agenda', `todo', `tags' for the corresponding agenda views."
2915 :group 'org-agenda-sorting
2916 :type `(choice
2917 (repeat :tag "General" ,org-sorting-choice)
2918 (list :tag "Individually"
2919 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2920 (repeat ,org-sorting-choice))
2921 (cons (const :tag "Strategy for TODO lists" todo)
2922 (repeat ,org-sorting-choice))
2923 (cons (const :tag "Strategy for Tags matches" tags)
2924 (repeat ,org-sorting-choice)))))
2926 (defcustom org-sort-agenda-notime-is-late t
2927 "Non-nil means, items without time are considered late.
2928 This is only relevant for sorting. When t, items which have no explicit
2929 time like 15:30 will be considered as 99:01, i.e. later than any items which
2930 do have a time. When nil, the default time is before 0:00. You can use this
2931 option to decide if the schedule for today should come before or after timeless
2932 agenda entries."
2933 :group 'org-agenda-sorting
2934 :type 'boolean)
2936 (defgroup org-agenda-line-format nil
2937 "Options concerning the entry prefix in the Org-mode agenda display."
2938 :tag "Org Agenda Line Format"
2939 :group 'org-agenda)
2941 (defcustom org-agenda-prefix-format
2942 '((agenda . " %-12:c%?-12t% s")
2943 (timeline . " % s")
2944 (todo . " %-12:c")
2945 (tags . " %-12:c")
2946 (search . " %-12:c"))
2947 "Format specifications for the prefix of items in the agenda views.
2948 An alist with four entries, for the different agenda types. The keys to the
2949 sublists are `agenda', `timeline', `todo', and `tags'. The values
2950 are format strings.
2951 This format works similar to a printf format, with the following meaning:
2953 %c the category of the item, \"Diary\" for entries from the diary, or
2954 as given by the CATEGORY keyword or derived from the file name.
2955 %T the *last* tag of the item. Last because inherited tags come
2956 first in the list.
2957 %t the time-of-day specification if one applies to the entry, in the
2958 format HH:MM
2959 %s Scheduling/Deadline information, a short string
2961 All specifiers work basically like the standard `%s' of printf, but may
2962 contain two additional characters: A question mark just after the `%' and
2963 a whitespace/punctuation character just before the final letter.
2965 If the first character after `%' is a question mark, the entire field
2966 will only be included if the corresponding value applies to the
2967 current entry. This is useful for fields which should have fixed
2968 width when present, but zero width when absent. For example,
2969 \"%?-12t\" will result in a 12 character time field if a time of the
2970 day is specified, but will completely disappear in entries which do
2971 not contain a time.
2973 If there is punctuation or whitespace character just before the final
2974 format letter, this character will be appended to the field value if
2975 the value is not empty. For example, the format \"%-12:c\" leads to
2976 \"Diary: \" if the category is \"Diary\". If the category were be
2977 empty, no additional colon would be interted.
2979 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2980 - Indent the line with two space characters
2981 - Give the category in a 12 chars wide field, padded with whitespace on
2982 the right (because of `-'). Append a colon if there is a category
2983 (because of `:').
2984 - If there is a time-of-day, put it into a 12 chars wide field. If no
2985 time, don't put in an empty field, just skip it (because of '?').
2986 - Finally, put the scheduling information and append a whitespace.
2988 As another example, if you don't want the time-of-day of entries in
2989 the prefix, you could use:
2991 (setq org-agenda-prefix-format \" %-11:c% s\")
2993 See also the variables `org-agenda-remove-times-when-in-prefix' and
2994 `org-agenda-remove-tags'."
2995 :type '(choice
2996 (string :tag "General format")
2997 (list :greedy t :tag "View dependent"
2998 (cons (const agenda) (string :tag "Format"))
2999 (cons (const timeline) (string :tag "Format"))
3000 (cons (const todo) (string :tag "Format"))
3001 (cons (const tags) (string :tag "Format"))
3002 (cons (const search) (string :tag "Format"))))
3003 :group 'org-agenda-line-format)
3005 (defvar org-prefix-format-compiled nil
3006 "The compiled version of the most recently used prefix format.
3007 See the variable `org-agenda-prefix-format'.")
3009 (defcustom org-agenda-todo-keyword-format "%-1s"
3010 "Format for the TODO keyword in agenda lines.
3011 Set this to something like \"%-12s\" if you want all TODO keywords
3012 to occupy a fixed space in the agenda display."
3013 :group 'org-agenda-line-format
3014 :type 'string)
3016 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
3017 "Text preceeding scheduled items in the agenda view.
3018 This is a list with two strings. The first applies when the item is
3019 scheduled on the current day. The second applies when it has been scheduled
3020 previously, it may contain a %d to capture how many days ago the item was
3021 scheduled."
3022 :group 'org-agenda-line-format
3023 :type '(list
3024 (string :tag "Scheduled today ")
3025 (string :tag "Scheduled previously")))
3027 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
3028 "Text preceeding deadline items in the agenda view.
3029 This is a list with two strings. The first applies when the item has its
3030 deadline on the current day. The second applies when it is in the past or
3031 in the future, it may contain %d to capture how many days away the deadline
3032 is (was)."
3033 :group 'org-agenda-line-format
3034 :type '(list
3035 (string :tag "Deadline today ")
3036 (string :tag "Deadline relative")))
3038 (defcustom org-agenda-remove-times-when-in-prefix t
3039 "Non-nil means, remove duplicate time specifications in agenda items.
3040 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3041 time-of-day specification in a headline or diary entry is extracted and
3042 placed into the prefix. If this option is non-nil, the original specification
3043 \(a timestamp or -range, or just a plain time(range) specification like
3044 11:30-4pm) will be removed for agenda display. This makes the agenda less
3045 cluttered.
3046 The option can be t or nil. It may also be the symbol `beg', indicating
3047 that the time should only be removed what it is located at the beginning of
3048 the headline/diary entry."
3049 :group 'org-agenda-line-format
3050 :type '(choice
3051 (const :tag "Always" t)
3052 (const :tag "Never" nil)
3053 (const :tag "When at beginning of entry" beg)))
3056 (defcustom org-agenda-default-appointment-duration nil
3057 "Default duration for appointments that only have a starting time.
3058 When nil, no duration is specified in such cases.
3059 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3060 :group 'org-agenda-line-format
3061 :type '(choice
3062 (integer :tag "Minutes")
3063 (const :tag "No default duration")))
3066 (defcustom org-agenda-remove-tags nil
3067 "Non-nil means, remove the tags from the headline copy in the agenda.
3068 When this is the symbol `prefix', only remove tags when
3069 `org-agenda-prefix-format' contains a `%T' specifier."
3070 :group 'org-agenda-line-format
3071 :type '(choice
3072 (const :tag "Always" t)
3073 (const :tag "Never" nil)
3074 (const :tag "When prefix format contains %T" prefix)))
3076 (if (fboundp 'defvaralias)
3077 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3078 'org-agenda-remove-tags))
3080 (defcustom org-agenda-tags-column -80
3081 "Shift tags in agenda items to this column.
3082 If this number is positive, it specifies the column. If it is negative,
3083 it means that the tags should be flushright to that column. For example,
3084 -80 works well for a normal 80 character screen."
3085 :group 'org-agenda-line-format
3086 :type 'integer)
3088 (if (fboundp 'defvaralias)
3089 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3091 (defcustom org-agenda-fontify-priorities t
3092 "Non-nil means, highlight low and high priorities in agenda.
3093 When t, the highest priority entries are bold, lowest priority italic.
3094 This may also be an association list of priority faces. The face may be
3095 a names face, or a list like `(:background \"Red\")'."
3096 :group 'org-agenda-line-format
3097 :type '(choice
3098 (const :tag "Never" nil)
3099 (const :tag "Defaults" t)
3100 (repeat :tag "Specify"
3101 (list (character :tag "Priority" :value ?A)
3102 (sexp :tag "face")))))
3104 (defgroup org-latex nil
3105 "Options for embedding LaTeX code into Org-mode"
3106 :tag "Org LaTeX"
3107 :group 'org)
3109 (defcustom org-format-latex-options
3110 '(:foreground default :background default :scale 1.0
3111 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3112 :matchers ("begin" "$" "$$" "\\(" "\\["))
3113 "Options for creating images from LaTeX fragments.
3114 This is a property list with the following properties:
3115 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3116 `default' means use the forground of the default face.
3117 :background the background color, or \"Transparent\".
3118 `default' means use the background of the default face.
3119 :scale a scaling factor for the size of the images
3120 :html-foreground, :html-background, :html-scale
3121 The same numbers for HTML export.
3122 :matchers a list indicating which matchers should be used to
3123 find LaTeX fragments. Valid members of this list are:
3124 \"begin\" find environments
3125 \"$\" find math expressions surrounded by $...$
3126 \"$$\" find math expressions surrounded by $$....$$
3127 \"\\(\" find math expressions surrounded by \\(...\\)
3128 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3129 :group 'org-latex
3130 :type 'plist)
3132 (defcustom org-format-latex-header "\\documentclass{article}
3133 \\usepackage{fullpage} % do not remove
3134 \\usepackage{amssymb}
3135 \\usepackage[usenames]{color}
3136 \\usepackage{amsmath}
3137 \\usepackage{latexsym}
3138 \\usepackage[mathscr]{eucal}
3139 \\pagestyle{empty} % do not remove"
3140 "The document header used for processing LaTeX fragments."
3141 :group 'org-latex
3142 :type 'string)
3144 (defgroup org-export nil
3145 "Options for exporting org-listings."
3146 :tag "Org Export"
3147 :group 'org)
3149 (defgroup org-export-general nil
3150 "General options for exporting Org-mode files."
3151 :tag "Org Export General"
3152 :group 'org-export)
3154 ;; FIXME
3155 (defvar org-export-publishing-directory nil)
3157 (defcustom org-export-with-special-strings t
3158 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3159 When this option is turned on, these strings will be exported as:
3161 Org HTML LaTeX
3162 -----+----------+--------
3163 \\- &shy; \\-
3164 -- &ndash; --
3165 --- &mdash; ---
3166 ... &hellip; \ldots
3168 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3169 :group 'org-export-translation
3170 :type 'boolean)
3172 (defcustom org-export-language-setup
3173 '(("en" "Author" "Date" "Table of Contents")
3174 ("cs" "Autor" "Datum" "Obsah")
3175 ("da" "Ophavsmand" "Dato" "Indhold")
3176 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3177 ("es" "Autor" "Fecha" "\xcdndice")
3178 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3179 ("it" "Autore" "Data" "Indice")
3180 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3181 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3182 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3183 "Terms used in export text, translated to different languages.
3184 Use the variable `org-export-default-language' to set the language,
3185 or use the +OPTION lines for a per-file setting."
3186 :group 'org-export-general
3187 :type '(repeat
3188 (list
3189 (string :tag "HTML language tag")
3190 (string :tag "Author")
3191 (string :tag "Date")
3192 (string :tag "Table of Contents"))))
3194 (defcustom org-export-default-language "en"
3195 "The default language of HTML export, as a string.
3196 This should have an association in `org-export-language-setup'."
3197 :group 'org-export-general
3198 :type 'string)
3200 (defcustom org-export-skip-text-before-1st-heading t
3201 "Non-nil means, skip all text before the first headline when exporting.
3202 When nil, that text is exported as well."
3203 :group 'org-export-general
3204 :type 'boolean)
3206 (defcustom org-export-headline-levels 3
3207 "The last level which is still exported as a headline.
3208 Inferior levels will produce itemize lists when exported.
3209 Note that a numeric prefix argument to an exporter function overrides
3210 this setting.
3212 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3213 :group 'org-export-general
3214 :type 'number)
3216 (defcustom org-export-with-section-numbers t
3217 "Non-nil means, add section numbers to headlines when exporting.
3219 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3220 :group 'org-export-general
3221 :type 'boolean)
3223 (defcustom org-export-with-toc t
3224 "Non-nil means, create a table of contents in exported files.
3225 The TOC contains headlines with levels up to`org-export-headline-levels'.
3226 When an integer, include levels up to N in the toc, this may then be
3227 different from `org-export-headline-levels', but it will not be allowed
3228 to be larger than the number of headline levels.
3229 When nil, no table of contents is made.
3231 Headlines which contain any TODO items will be marked with \"(*)\" in
3232 ASCII export, and with red color in HTML output, if the option
3233 `org-export-mark-todo-in-toc' is set.
3235 In HTML output, the TOC will be clickable.
3237 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3238 or \"toc:3\"."
3239 :group 'org-export-general
3240 :type '(choice
3241 (const :tag "No Table of Contents" nil)
3242 (const :tag "Full Table of Contents" t)
3243 (integer :tag "TOC to level")))
3245 (defcustom org-export-mark-todo-in-toc nil
3246 "Non-nil means, mark TOC lines that contain any open TODO items."
3247 :group 'org-export-general
3248 :type 'boolean)
3250 (defcustom org-export-preserve-breaks nil
3251 "Non-nil means, preserve all line breaks when exporting.
3252 Normally, in HTML output paragraphs will be reformatted. In ASCII
3253 export, line breaks will always be preserved, regardless of this variable.
3255 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3256 :group 'org-export-general
3257 :type 'boolean)
3259 (defcustom org-export-with-archived-trees 'headline
3260 "Whether subtrees with the ARCHIVE tag should be exported.
3261 This can have three different values
3262 nil Do not export, pretend this tree is not present
3263 t Do export the entire tree
3264 headline Only export the headline, but skip the tree below it."
3265 :group 'org-export-general
3266 :group 'org-archive
3267 :type '(choice
3268 (const :tag "not at all" nil)
3269 (const :tag "headline only" 'headline)
3270 (const :tag "entirely" t)))
3272 (defcustom org-export-author-info t
3273 "Non-nil means, insert author name and email into the exported file.
3275 This option can also be set with the +OPTIONS line,
3276 e.g. \"author-info:nil\"."
3277 :group 'org-export-general
3278 :type 'boolean)
3280 (defcustom org-export-time-stamp-file t
3281 "Non-nil means, insert a time stamp into the exported file.
3282 The time stamp shows when the file was created.
3284 This option can also be set with the +OPTIONS line,
3285 e.g. \"timestamp:nil\"."
3286 :group 'org-export-general
3287 :type 'boolean)
3289 (defcustom org-export-with-timestamps t
3290 "If nil, do not export time stamps and associated keywords."
3291 :group 'org-export-general
3292 :type 'boolean)
3294 (defcustom org-export-remove-timestamps-from-toc t
3295 "If nil, remove timestamps from the table of contents entries."
3296 :group 'org-export-general
3297 :type 'boolean)
3299 (defcustom org-export-with-tags 'not-in-toc
3300 "If nil, do not export tags, just remove them from headlines.
3301 If this is the symbol `not-in-toc', tags will be removed from table of
3302 contents entries, but still be shown in the headlines of the document.
3304 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3305 :group 'org-export-general
3306 :type '(choice
3307 (const :tag "Off" nil)
3308 (const :tag "Not in TOC" not-in-toc)
3309 (const :tag "On" t)))
3311 (defcustom org-export-with-drawers nil
3312 "Non-nil means, export with drawers like the property drawer.
3313 When t, all drawers are exported. This may also be a list of
3314 drawer names to export."
3315 :group 'org-export-general
3316 :type '(choice
3317 (const :tag "All drawers" t)
3318 (const :tag "None" nil)
3319 (repeat :tag "Selected drawers"
3320 (string :tag "Drawer name"))))
3322 (defgroup org-export-translation nil
3323 "Options for translating special ascii sequences for the export backends."
3324 :tag "Org Export Translation"
3325 :group 'org-export)
3327 (defcustom org-export-with-emphasize t
3328 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3329 If the export target supports emphasizing text, the word will be
3330 typeset in bold, italic, or underlined, respectively. Works only for
3331 single words, but you can say: I *really* *mean* *this*.
3332 Not all export backends support this.
3334 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3335 :group 'org-export-translation
3336 :type 'boolean)
3338 (defcustom org-export-with-footnotes t
3339 "If nil, export [1] as a footnote marker.
3340 Lines starting with [1] will be formatted as footnotes.
3342 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3343 :group 'org-export-translation
3344 :type 'boolean)
3346 (defcustom org-export-with-sub-superscripts t
3347 "Non-nil means, interpret \"_\" and \"^\" for export.
3348 When this option is turned on, you can use TeX-like syntax for sub- and
3349 superscripts. Several characters after \"_\" or \"^\" will be
3350 considered as a single item - so grouping with {} is normally not
3351 needed. For example, the following things will be parsed as single
3352 sub- or superscripts.
3354 10^24 or 10^tau several digits will be considered 1 item.
3355 10^-12 or 10^-tau a leading sign with digits or a word
3356 x^2-y^3 will be read as x^2 - y^3, because items are
3357 terminated by almost any nonword/nondigit char.
3358 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3360 Still, ambiguity is possible - so when in doubt use {} to enclose the
3361 sub/superscript. If you set this variable to the symbol `{}',
3362 the braces are *required* in order to trigger interpretations as
3363 sub/superscript. This can be helpful in documents that need \"_\"
3364 frequently in plain text.
3366 Not all export backends support this, but HTML does.
3368 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3369 :group 'org-export-translation
3370 :type '(choice
3371 (const :tag "Always interpret" t)
3372 (const :tag "Only with braces" {})
3373 (const :tag "Never interpret" nil)))
3375 (defcustom org-export-with-special-strings t
3376 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3377 When this option is turned on, these strings will be exported as:
3379 \\- : &shy;
3380 -- : &ndash;
3381 --- : &mdash;
3383 Not all export backends support this, but HTML does.
3385 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3386 :group 'org-export-translation
3387 :type 'boolean)
3389 (defcustom org-export-with-TeX-macros t
3390 "Non-nil means, interpret simple TeX-like macros when exporting.
3391 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3392 No only real TeX macros will work here, but the standard HTML entities
3393 for math can be used as macro names as well. For a list of supported
3394 names in HTML export, see the constant `org-html-entities'.
3395 Not all export backends support this.
3397 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3398 :group 'org-export-translation
3399 :group 'org-export-latex
3400 :type 'boolean)
3402 (defcustom org-export-with-LaTeX-fragments nil
3403 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3404 When set, the exporter will find LaTeX environments if the \\begin line is
3405 the first non-white thing on a line. It will also find the math delimiters
3406 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3407 display math.
3409 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3410 :group 'org-export-translation
3411 :group 'org-export-latex
3412 :type 'boolean)
3414 (defcustom org-export-with-fixed-width t
3415 "Non-nil means, lines starting with \":\" will be in fixed width font.
3416 This can be used to have pre-formatted text, fragments of code etc. For
3417 example:
3418 : ;; Some Lisp examples
3419 : (while (defc cnt)
3420 : (ding))
3421 will be looking just like this in also HTML. See also the QUOTE keyword.
3422 Not all export backends support this.
3424 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3425 :group 'org-export-translation
3426 :type 'boolean)
3428 (defcustom org-match-sexp-depth 3
3429 "Number of stacked braces for sub/superscript matching.
3430 This has to be set before loading org.el to be effective."
3431 :group 'org-export-translation
3432 :type 'integer)
3434 (defgroup org-export-tables nil
3435 "Options for exporting tables in Org-mode."
3436 :tag "Org Export Tables"
3437 :group 'org-export)
3439 (defcustom org-export-with-tables t
3440 "If non-nil, lines starting with \"|\" define a table.
3441 For example:
3443 | Name | Address | Birthday |
3444 |-------------+----------+-----------|
3445 | Arthur Dent | England | 29.2.2100 |
3447 Not all export backends support this.
3449 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3450 :group 'org-export-tables
3451 :type 'boolean)
3453 (defcustom org-export-highlight-first-table-line t
3454 "Non-nil means, highlight the first table line.
3455 In HTML export, this means use <th> instead of <td>.
3456 In tables created with table.el, this applies to the first table line.
3457 In Org-mode tables, all lines before the first horizontal separator
3458 line will be formatted with <th> tags."
3459 :group 'org-export-tables
3460 :type 'boolean)
3462 (defcustom org-export-table-remove-special-lines t
3463 "Remove special lines and marking characters in calculating tables.
3464 This removes the special marking character column from tables that are set
3465 up for spreadsheet calculations. It also removes the entire lines
3466 marked with `!', `_', or `^'. The lines with `$' are kept, because
3467 the values of constants may be useful to have."
3468 :group 'org-export-tables
3469 :type 'boolean)
3471 (defcustom org-export-prefer-native-exporter-for-tables nil
3472 "Non-nil means, always export tables created with table.el natively.
3473 Natively means, use the HTML code generator in table.el.
3474 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3475 the table does not use row- or column-spanning). This has the
3476 advantage, that the automatic HTML conversions for math symbols and
3477 sub/superscripts can be applied. Org-mode's HTML generator is also
3478 much faster."
3479 :group 'org-export-tables
3480 :type 'boolean)
3482 (defgroup org-export-ascii nil
3483 "Options specific for ASCII export of Org-mode files."
3484 :tag "Org Export ASCII"
3485 :group 'org-export)
3487 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3488 "Characters for underlining headings in ASCII export.
3489 In the given sequence, these characters will be used for level 1, 2, ..."
3490 :group 'org-export-ascii
3491 :type '(repeat character))
3493 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3494 "Bullet characters for headlines converted to lists in ASCII export.
3495 The first character is used for the first lest level generated in this
3496 way, and so on. If there are more levels than characters given here,
3497 the list will be repeated.
3498 Note that plain lists will keep the same bullets as the have in the
3499 Org-mode file."
3500 :group 'org-export-ascii
3501 :type '(repeat character))
3503 (defgroup org-export-xml nil
3504 "Options specific for XML export of Org-mode files."
3505 :tag "Org Export XML"
3506 :group 'org-export)
3508 (defgroup org-export-html nil
3509 "Options specific for HTML export of Org-mode files."
3510 :tag "Org Export HTML"
3511 :group 'org-export)
3513 (defcustom org-export-html-coding-system nil
3515 :group 'org-export-html
3516 :type 'coding-system)
3518 (defcustom org-export-html-extension "html"
3519 "The extension for exported HTML files."
3520 :group 'org-export-html
3521 :type 'string)
3523 (defcustom org-export-html-style
3524 "<style type=\"text/css\">
3525 html {
3526 font-family: Times, serif;
3527 font-size: 12pt;
3529 .title { text-align: center; }
3530 .todo { color: red; }
3531 .done { color: green; }
3532 .timestamp { color: grey }
3533 .timestamp-kwd { color: CadetBlue }
3534 .tag { background-color:lightblue; font-weight:normal }
3535 .target { background-color: lavender; }
3536 pre {
3537 border: 1pt solid #AEBDCC;
3538 background-color: #F3F5F7;
3539 padding: 5pt;
3540 font-family: courier, monospace;
3542 table { border-collapse: collapse; }
3543 td, th {
3544 vertical-align: top;
3545 <!--border: 1pt solid #ADB9CC;-->
3547 </style>"
3548 "The default style specification for exported HTML files.
3549 Since there are different ways of setting style information, this variable
3550 needs to contain the full HTML structure to provide a style, including the
3551 surrounding HTML tags. The style specifications should include definitions
3552 for new classes todo, done, title, and deadline. For example, legal values
3553 would be:
3555 <style type=\"text/css\">
3556 p { font-weight: normal; color: gray; }
3557 h1 { color: black; }
3558 .title { text-align: center; }
3559 .todo, .deadline { color: red; }
3560 .done { color: green; }
3561 </style>
3563 or, if you want to keep the style in a file,
3565 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3567 As the value of this option simply gets inserted into the HTML <head> header,
3568 you can \"misuse\" it to add arbitrary text to the header."
3569 :group 'org-export-html
3570 :type 'string)
3573 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3574 "Format for typesetting the document title in HTML export."
3575 :group 'org-export-html
3576 :type 'string)
3578 (defcustom org-export-html-toplevel-hlevel 2
3579 "The <H> level for level 1 headings in HTML export."
3580 :group 'org-export-html
3581 :type 'string)
3583 (defcustom org-export-html-link-org-files-as-html t
3584 "Non-nil means, make file links to `file.org' point to `file.html'.
3585 When org-mode is exporting an org-mode file to HTML, links to
3586 non-html files are directly put into a href tag in HTML.
3587 However, links to other Org-mode files (recognized by the
3588 extension `.org.) should become links to the corresponding html
3589 file, assuming that the linked org-mode file will also be
3590 converted to HTML.
3591 When nil, the links still point to the plain `.org' file."
3592 :group 'org-export-html
3593 :type 'boolean)
3595 (defcustom org-export-html-inline-images 'maybe
3596 "Non-nil means, inline images into exported HTML pages.
3597 This is done using an <img> tag. When nil, an anchor with href is used to
3598 link to the image. If this option is `maybe', then images in links with
3599 an empty description will be inlined, while images with a description will
3600 be linked only."
3601 :group 'org-export-html
3602 :type '(choice (const :tag "Never" nil)
3603 (const :tag "Always" t)
3604 (const :tag "When there is no description" maybe)))
3606 ;; FIXME: rename
3607 (defcustom org-export-html-expand t
3608 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3609 When nil, these tags will be exported as plain text and therefore
3610 not be interpreted by a browser.
3612 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3613 :group 'org-export-html
3614 :type 'boolean)
3616 (defcustom org-export-html-table-tag
3617 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3618 "The HTML tag that is used to start a table.
3619 This must be a <table> tag, but you may change the options like
3620 borders and spacing."
3621 :group 'org-export-html
3622 :type 'string)
3624 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3625 "The opening tag for table header fields.
3626 This is customizable so that alignment options can be specified."
3627 :group 'org-export-tables
3628 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3630 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3631 "The opening tag for table data fields.
3632 This is customizable so that alignment options can be specified."
3633 :group 'org-export-tables
3634 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3636 (defcustom org-export-html-with-timestamp nil
3637 "If non-nil, write `org-export-html-html-helper-timestamp'
3638 into the exported HTML text. Otherwise, the buffer will just be saved
3639 to a file."
3640 :group 'org-export-html
3641 :type 'boolean)
3643 (defcustom org-export-html-html-helper-timestamp
3644 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3645 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3646 :group 'org-export-html
3647 :type 'string)
3649 (defgroup org-export-icalendar nil
3650 "Options specific for iCalendar export of Org-mode files."
3651 :tag "Org Export iCalendar"
3652 :group 'org-export)
3654 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3655 "The file name for the iCalendar file covering all agenda files.
3656 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3657 The file name should be absolute, the file will be overwritten without warning."
3658 :group 'org-export-icalendar
3659 :type 'file)
3661 (defcustom org-icalendar-include-todo nil
3662 "Non-nil means, export to iCalendar files should also cover TODO items."
3663 :group 'org-export-icalendar
3664 :type '(choice
3665 (const :tag "None" nil)
3666 (const :tag "Unfinished" t)
3667 (const :tag "All" all)))
3669 (defcustom org-icalendar-include-sexps t
3670 "Non-nil means, export to iCalendar files should also cover sexp entries.
3671 These are entries like in the diary, but directly in an Org-mode file."
3672 :group 'org-export-icalendar
3673 :type 'boolean)
3675 (defcustom org-icalendar-include-body 100
3676 "Amount of text below headline to be included in iCalendar export.
3677 This is a number of characters that should maximally be included.
3678 Properties, scheduling and clocking lines will always be removed.
3679 The text will be inserted into the DESCRIPTION field."
3680 :group 'org-export-icalendar
3681 :type '(choice
3682 (const :tag "Nothing" nil)
3683 (const :tag "Everything" t)
3684 (integer :tag "Max characters")))
3686 (defcustom org-icalendar-combined-name "OrgMode"
3687 "Calendar name for the combined iCalendar representing all agenda files."
3688 :group 'org-export-icalendar
3689 :type 'string)
3691 (defgroup org-font-lock nil
3692 "Font-lock settings for highlighting in Org-mode."
3693 :tag "Org Font Lock"
3694 :group 'org)
3696 (defcustom org-level-color-stars-only nil
3697 "Non-nil means fontify only the stars in each headline.
3698 When nil, the entire headline is fontified.
3699 Changing it requires restart of `font-lock-mode' to become effective
3700 also in regions already fontified."
3701 :group 'org-font-lock
3702 :type 'boolean)
3704 (defcustom org-hide-leading-stars nil
3705 "Non-nil means, hide the first N-1 stars in a headline.
3706 This works by using the face `org-hide' for these stars. This
3707 face is white for a light background, and black for a dark
3708 background. You may have to customize the face `org-hide' to
3709 make this work.
3710 Changing it requires restart of `font-lock-mode' to become effective
3711 also in regions already fontified.
3712 You may also set this on a per-file basis by adding one of the following
3713 lines to the buffer:
3715 #+STARTUP: hidestars
3716 #+STARTUP: showstars"
3717 :group 'org-font-lock
3718 :type 'boolean)
3720 (defcustom org-fontify-done-headline nil
3721 "Non-nil means, change the face of a headline if it is marked DONE.
3722 Normally, only the TODO/DONE keyword indicates the state of a headline.
3723 When this is non-nil, the headline after the keyword is set to the
3724 `org-headline-done' as an additional indication."
3725 :group 'org-font-lock
3726 :type 'boolean)
3728 (defcustom org-fontify-emphasized-text t
3729 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3730 Changing this variable requires a restart of Emacs to take effect."
3731 :group 'org-font-lock
3732 :type 'boolean)
3734 (defcustom org-highlight-latex-fragments-and-specials nil
3735 "Non-nil means, fontify what is treated specially by the exporters."
3736 :group 'org-font-lock
3737 :type 'boolean)
3739 (defcustom org-hide-emphasis-markers nil
3740 "Non-nil mean font-lock should hide the emphasis marker characters."
3741 :group 'org-font-lock
3742 :type 'boolean)
3744 (defvar org-emph-re nil
3745 "Regular expression for matching emphasis.")
3746 (defvar org-verbatim-re nil
3747 "Regular expression for matching verbatim text.")
3748 (defvar org-emphasis-regexp-components) ; defined just below
3749 (defvar org-emphasis-alist) ; defined just below
3750 (defun org-set-emph-re (var val)
3751 "Set variable and compute the emphasis regular expression."
3752 (set var val)
3753 (when (and (boundp 'org-emphasis-alist)
3754 (boundp 'org-emphasis-regexp-components)
3755 org-emphasis-alist org-emphasis-regexp-components)
3756 (let* ((e org-emphasis-regexp-components)
3757 (pre (car e))
3758 (post (nth 1 e))
3759 (border (nth 2 e))
3760 (body (nth 3 e))
3761 (nl (nth 4 e))
3762 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3763 (body1 (concat body "*?"))
3764 (markers (mapconcat 'car org-emphasis-alist ""))
3765 (vmarkers (mapconcat
3766 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3767 org-emphasis-alist "")))
3768 ;; make sure special characters appear at the right position in the class
3769 (if (string-match "\\^" markers)
3770 (setq markers (concat (replace-match "" t t markers) "^")))
3771 (if (string-match "-" markers)
3772 (setq markers (concat (replace-match "" t t markers) "-")))
3773 (if (string-match "\\^" vmarkers)
3774 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3775 (if (string-match "-" vmarkers)
3776 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3777 (if (> nl 0)
3778 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3779 (int-to-string nl) "\\}")))
3780 ;; Make the regexp
3781 (setq org-emph-re
3782 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3783 "\\("
3784 "\\([" markers "]\\)"
3785 "\\("
3786 "[^" border "]\\|"
3787 "[^" border (if (and nil stacked) markers) "]"
3788 body1
3789 "[^" border (if (and nil stacked) markers) "]"
3790 "\\)"
3791 "\\3\\)"
3792 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3793 (setq org-verbatim-re
3794 (concat "\\([" pre "]\\|^\\)"
3795 "\\("
3796 "\\([" vmarkers "]\\)"
3797 "\\("
3798 "[^" border "]\\|"
3799 "[^" border "]"
3800 body1
3801 "[^" border "]"
3802 "\\)"
3803 "\\3\\)"
3804 "\\([" post "]\\|$\\)")))))
3806 (defcustom org-emphasis-regexp-components
3807 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3808 "Components used to build the regular expression for emphasis.
3809 This is a list with 6 entries. Terminology: In an emphasis string
3810 like \" *strong word* \", we call the initial space PREMATCH, the final
3811 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3812 and \"trong wor\" is the body. The different components in this variable
3813 specify what is allowed/forbidden in each part:
3815 pre Chars allowed as prematch. Beginning of line will be allowed too.
3816 post Chars allowed as postmatch. End of line will be allowed too.
3817 border The chars *forbidden* as border characters.
3818 body-regexp A regexp like \".\" to match a body character. Don't use
3819 non-shy groups here, and don't allow newline here.
3820 newline The maximum number of newlines allowed in an emphasis exp.
3822 Use customize to modify this, or restart Emacs after changing it."
3823 :group 'org-font-lock
3824 :set 'org-set-emph-re
3825 :type '(list
3826 (sexp :tag "Allowed chars in pre ")
3827 (sexp :tag "Allowed chars in post ")
3828 (sexp :tag "Forbidden chars in border ")
3829 (sexp :tag "Regexp for body ")
3830 (integer :tag "number of newlines allowed")
3831 (option (boolean :tag "Stacking (DISABLED) "))))
3833 (defcustom org-emphasis-alist
3834 '(("*" bold "<b>" "</b>")
3835 ("/" italic "<i>" "</i>")
3836 ("_" underline "<u>" "</u>")
3837 ("=" org-code "<code>" "</code>" verbatim)
3838 ("~" org-verbatim "" "" verbatim)
3839 ("+" (:strike-through t) "<del>" "</del>")
3841 "Special syntax for emphasized text.
3842 Text starting and ending with a special character will be emphasized, for
3843 example *bold*, _underlined_ and /italic/. This variable sets the marker
3844 characters, the face to be used by font-lock for highlighting in Org-mode
3845 Emacs buffers, and the HTML tags to be used for this.
3846 Use customize to modify this, or restart Emacs after changing it."
3847 :group 'org-font-lock
3848 :set 'org-set-emph-re
3849 :type '(repeat
3850 (list
3851 (string :tag "Marker character")
3852 (choice
3853 (face :tag "Font-lock-face")
3854 (plist :tag "Face property list"))
3855 (string :tag "HTML start tag")
3856 (string :tag "HTML end tag")
3857 (option (const verbatim)))))
3859 ;;; The faces
3861 (defgroup org-faces nil
3862 "Faces in Org-mode."
3863 :tag "Org Faces"
3864 :group 'org-font-lock)
3866 (defun org-compatible-face (inherits specs)
3867 "Make a compatible face specification.
3868 If INHERITS is an existing face and if the Emacs version supports it,
3869 just inherit the face. If not, use SPECS to define the face.
3870 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3871 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3872 to the top of the list. The `min-colors' attribute will be removed from
3873 any other entries, and any resulting duplicates will be removed entirely."
3874 (cond
3875 ((and inherits (facep inherits)
3876 (not (featurep 'xemacs)) (> emacs-major-version 22))
3877 ;; In Emacs 23, we use inheritance where possible.
3878 ;; We only do this in Emacs 23, because only there the outline
3879 ;; faces have been changed to the original org-mode-level-faces.
3880 (list (list t :inherit inherits)))
3881 ((or (featurep 'xemacs) (< emacs-major-version 22))
3882 ;; These do not understand the `min-colors' attribute.
3883 (let (r e a)
3884 (while (setq e (pop specs))
3885 (cond
3886 ((memq (car e) '(t default)) (push e r))
3887 ((setq a (member '(min-colors 8) (car e)))
3888 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3889 (cdr e)))))
3890 ((setq a (assq 'min-colors (car e)))
3891 (setq e (cons (delq a (car e)) (cdr e)))
3892 (or (assoc (car e) r) (push e r)))
3893 (t (or (assoc (car e) r) (push e r)))))
3894 (nreverse r)))
3895 (t specs)))
3896 (put 'org-compatible-face 'lisp-indent-function 1)
3898 (defface org-hide
3899 '((((background light)) (:foreground "white"))
3900 (((background dark)) (:foreground "black")))
3901 "Face used to hide leading stars in headlines.
3902 The forground color of this face should be equal to the background
3903 color of the frame."
3904 :group 'org-faces)
3906 (defface org-level-1 ;; font-lock-function-name-face
3907 (org-compatible-face 'outline-1
3908 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3909 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3910 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3911 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3912 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3913 (t (:bold t))))
3914 "Face used for level 1 headlines."
3915 :group 'org-faces)
3917 (defface org-level-2 ;; font-lock-variable-name-face
3918 (org-compatible-face 'outline-2
3919 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3920 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3921 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3922 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3923 (t (:bold t))))
3924 "Face used for level 2 headlines."
3925 :group 'org-faces)
3927 (defface org-level-3 ;; font-lock-keyword-face
3928 (org-compatible-face 'outline-3
3929 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3930 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3931 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3932 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3933 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3934 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3935 (t (:bold t))))
3936 "Face used for level 3 headlines."
3937 :group 'org-faces)
3939 (defface org-level-4 ;; font-lock-comment-face
3940 (org-compatible-face 'outline-4
3941 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3942 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3943 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3944 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3945 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3946 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3947 (t (:bold t))))
3948 "Face used for level 4 headlines."
3949 :group 'org-faces)
3951 (defface org-level-5 ;; font-lock-type-face
3952 (org-compatible-face 'outline-5
3953 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3954 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3955 (((class color) (min-colors 8)) (:foreground "green"))))
3956 "Face used for level 5 headlines."
3957 :group 'org-faces)
3959 (defface org-level-6 ;; font-lock-constant-face
3960 (org-compatible-face 'outline-6
3961 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3962 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3963 (((class color) (min-colors 8)) (:foreground "magenta"))))
3964 "Face used for level 6 headlines."
3965 :group 'org-faces)
3967 (defface org-level-7 ;; font-lock-builtin-face
3968 (org-compatible-face 'outline-7
3969 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3970 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3971 (((class color) (min-colors 8)) (:foreground "blue"))))
3972 "Face used for level 7 headlines."
3973 :group 'org-faces)
3975 (defface org-level-8 ;; font-lock-string-face
3976 (org-compatible-face 'outline-8
3977 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3978 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3979 (((class color) (min-colors 8)) (:foreground "green"))))
3980 "Face used for level 8 headlines."
3981 :group 'org-faces)
3983 (defface org-special-keyword ;; font-lock-string-face
3984 (org-compatible-face nil
3985 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3986 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3987 (t (:italic t))))
3988 "Face used for special keywords."
3989 :group 'org-faces)
3991 (defface org-drawer ;; font-lock-function-name-face
3992 (org-compatible-face nil
3993 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3994 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3995 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3996 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3997 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3998 (t (:bold t))))
3999 "Face used for drawers."
4000 :group 'org-faces)
4002 (defface org-property-value nil
4003 "Face used for the value of a property."
4004 :group 'org-faces)
4006 (defface org-column
4007 (org-compatible-face nil
4008 '((((class color) (min-colors 16) (background light))
4009 (:background "grey90"))
4010 (((class color) (min-colors 16) (background dark))
4011 (:background "grey30"))
4012 (((class color) (min-colors 8))
4013 (:background "cyan" :foreground "black"))
4014 (t (:inverse-video t))))
4015 "Face for column display of entry properties."
4016 :group 'org-faces)
4018 (when (fboundp 'set-face-attribute)
4019 ;; Make sure that a fixed-width face is used when we have a column table.
4020 (set-face-attribute 'org-column nil
4021 :height (face-attribute 'default :height)
4022 :family (face-attribute 'default :family)))
4024 (defface org-warning
4025 (org-compatible-face 'font-lock-warning-face
4026 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4027 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4028 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4029 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4030 (t (:bold t))))
4031 "Face for deadlines and TODO keywords."
4032 :group 'org-faces)
4034 (defface org-archived ; similar to shadow
4035 (org-compatible-face 'shadow
4036 '((((class color grayscale) (min-colors 88) (background light))
4037 (:foreground "grey50"))
4038 (((class color grayscale) (min-colors 88) (background dark))
4039 (:foreground "grey70"))
4040 (((class color) (min-colors 8) (background light))
4041 (:foreground "green"))
4042 (((class color) (min-colors 8) (background dark))
4043 (:foreground "yellow"))))
4044 "Face for headline with the ARCHIVE tag."
4045 :group 'org-faces)
4047 (defface org-link
4048 '((((class color) (background light)) (:foreground "Purple" :underline t))
4049 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4050 (t (:underline t)))
4051 "Face for links."
4052 :group 'org-faces)
4054 (defface org-ellipsis
4055 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4056 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4057 (t (:strike-through t)))
4058 "Face for the ellipsis in folded text."
4059 :group 'org-faces)
4061 (defface org-target
4062 '((((class color) (background light)) (:underline t))
4063 (((class color) (background dark)) (:underline t))
4064 (t (:underline t)))
4065 "Face for links."
4066 :group 'org-faces)
4068 (defface org-date
4069 '((((class color) (background light)) (:foreground "Purple" :underline t))
4070 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4071 (t (:underline t)))
4072 "Face for links."
4073 :group 'org-faces)
4075 (defface org-sexp-date
4076 '((((class color) (background light)) (:foreground "Purple"))
4077 (((class color) (background dark)) (:foreground "Cyan"))
4078 (t (:underline t)))
4079 "Face for links."
4080 :group 'org-faces)
4082 (defface org-tag
4083 '((t (:bold t)))
4084 "Face for tags."
4085 :group 'org-faces)
4087 (defface org-todo ; font-lock-warning-face
4088 (org-compatible-face nil
4089 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4090 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4091 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4092 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4093 (t (:inverse-video t :bold t))))
4094 "Face for TODO keywords."
4095 :group 'org-faces)
4097 (defface org-done ;; font-lock-type-face
4098 (org-compatible-face nil
4099 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4100 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4101 (((class color) (min-colors 8)) (:foreground "green"))
4102 (t (:bold t))))
4103 "Face used for todo keywords that indicate DONE items."
4104 :group 'org-faces)
4106 (defface org-headline-done ;; font-lock-string-face
4107 (org-compatible-face nil
4108 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4109 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4110 (((class color) (min-colors 8) (background light)) (:bold nil))))
4111 "Face used to indicate that a headline is DONE.
4112 This face is only used if `org-fontify-done-headline' is set. If applies
4113 to the part of the headline after the DONE keyword."
4114 :group 'org-faces)
4116 (defcustom org-todo-keyword-faces nil
4117 "Faces for specific TODO keywords.
4118 This is a list of cons cells, with TODO keywords in the car
4119 and faces in the cdr. The face can be a symbol, or a property
4120 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4121 :group 'org-faces
4122 :group 'org-todo
4123 :type '(repeat
4124 (cons
4125 (string :tag "keyword")
4126 (sexp :tag "face"))))
4128 (defface org-table ;; font-lock-function-name-face
4129 (org-compatible-face nil
4130 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4131 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4132 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4133 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4134 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4135 (((class color) (min-colors 8) (background dark)))))
4136 "Face used for tables."
4137 :group 'org-faces)
4139 (defface org-formula
4140 (org-compatible-face nil
4141 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4142 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4143 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4144 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4145 (t (:bold t :italic t))))
4146 "Face for formulas."
4147 :group 'org-faces)
4149 (defface org-code
4150 (org-compatible-face nil
4151 '((((class color grayscale) (min-colors 88) (background light))
4152 (:foreground "grey50"))
4153 (((class color grayscale) (min-colors 88) (background dark))
4154 (:foreground "grey70"))
4155 (((class color) (min-colors 8) (background light))
4156 (:foreground "green"))
4157 (((class color) (min-colors 8) (background dark))
4158 (:foreground "yellow"))))
4159 "Face for fixed-with text like code snippets."
4160 :group 'org-faces
4161 :version "22.1")
4163 (defface org-verbatim
4164 (org-compatible-face nil
4165 '((((class color grayscale) (min-colors 88) (background light))
4166 (:foreground "grey50" :underline t))
4167 (((class color grayscale) (min-colors 88) (background dark))
4168 (:foreground "grey70" :underline t))
4169 (((class color) (min-colors 8) (background light))
4170 (:foreground "green" :underline t))
4171 (((class color) (min-colors 8) (background dark))
4172 (:foreground "yellow" :underline t))))
4173 "Face for fixed-with text like code snippets."
4174 :group 'org-faces
4175 :version "22.1")
4177 (defface org-agenda-structure ;; font-lock-function-name-face
4178 (org-compatible-face nil
4179 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4180 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4181 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4182 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4183 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4184 (t (:bold t))))
4185 "Face used in agenda for captions and dates."
4186 :group 'org-faces)
4188 (defface org-scheduled-today
4189 (org-compatible-face nil
4190 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4191 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4192 (((class color) (min-colors 8)) (:foreground "green"))
4193 (t (:bold t :italic t))))
4194 "Face for items scheduled for a certain day."
4195 :group 'org-faces)
4197 (defface org-scheduled-previously
4198 (org-compatible-face nil
4199 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4200 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4201 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4202 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4203 (t (:bold t))))
4204 "Face for items scheduled previously, and not yet done."
4205 :group 'org-faces)
4207 (defface org-upcoming-deadline
4208 (org-compatible-face nil
4209 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4210 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4211 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4212 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4213 (t (:bold t))))
4214 "Face for items scheduled previously, and not yet done."
4215 :group 'org-faces)
4217 (defcustom org-agenda-deadline-faces
4218 '((1.0 . org-warning)
4219 (0.5 . org-upcoming-deadline)
4220 (0.0 . default))
4221 "Faces for showing deadlines in the agenda.
4222 This is a list of cons cells. The cdr of each cell is a face to be used,
4223 and it can also just be like '(:foreground \"yellow\").
4224 Each car is a fraction of the head-warning time that must have passed for
4225 this the face in the cdr to be used for display. The numbers must be
4226 given in descending order. The head-warning time is normally taken
4227 from `org-deadline-warning-days', but can also be specified in the deadline
4228 timestamp itself, like this:
4230 DEADLINE: <2007-08-13 Mon -8d>
4232 You may use d for days, w for weeks, m for months and y for years. Months
4233 and years will only be treated in an approximate fashion (30.4 days for a
4234 month and 365.24 days for a year)."
4235 :group 'org-faces
4236 :group 'org-agenda-daily/weekly
4237 :type '(repeat
4238 (cons
4239 (number :tag "Fraction of head-warning time passed")
4240 (sexp :tag "Face"))))
4242 ;; FIXME: this is not a good face yet.
4243 (defface org-agenda-restriction-lock
4244 (org-compatible-face nil
4245 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4246 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4247 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4248 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4249 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4250 (t (:inverse-video t))))
4251 "Face for showing the agenda restriction lock."
4252 :group 'org-faces)
4254 (defface org-time-grid ;; font-lock-variable-name-face
4255 (org-compatible-face nil
4256 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4257 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4258 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4259 "Face used for time grids."
4260 :group 'org-faces)
4262 (defconst org-level-faces
4263 '(org-level-1 org-level-2 org-level-3 org-level-4
4264 org-level-5 org-level-6 org-level-7 org-level-8
4267 (defcustom org-n-level-faces (length org-level-faces)
4268 "The number of different faces to be used for headlines.
4269 Org-mode defines 8 different headline faces, so this can be at most 8.
4270 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4271 :type 'number
4272 :group 'org-faces)
4274 ;;; Functions and variables from ther packages
4275 ;; Declared here to avoid compiler warnings
4277 (eval-and-compile
4278 (unless (fboundp 'declare-function)
4279 (defmacro declare-function (fn file &optional arglist fileonly))))
4281 ;; XEmacs only
4282 (defvar outline-mode-menu-heading)
4283 (defvar outline-mode-menu-show)
4284 (defvar outline-mode-menu-hide)
4285 (defvar zmacs-regions) ; XEmacs regions
4287 ;; Emacs only
4288 (defvar mark-active)
4290 ;; Various packages
4291 ;; FIXME: get the argument lists for the UNKNOWN stuff
4292 (declare-function add-to-diary-list "diary-lib"
4293 (date string specifier &optional marker globcolor literal))
4294 (declare-function table--at-cell-p "table" (position &optional object at-column))
4295 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4296 (declare-function bbdb "ext:bbdb-com" (string elidep))
4297 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4298 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4299 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4300 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4301 (declare-function bbdb-record-name "ext:bbdb" (record))
4302 (declare-function bibtex-beginning-of-entry "bibtex" ())
4303 (declare-function bibtex-generate-autokey "bibtex" ())
4304 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4305 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4306 (defvar calc-embedded-close-formula)
4307 (defvar calc-embedded-open-formula)
4308 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4309 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4310 (declare-function calendar-check-holidays "holidays" (date))
4311 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4312 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4313 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4314 (declare-function calendar-forward-day "cal-move" (arg))
4315 (declare-function calendar-french-date-string "cal-french" (&optional date))
4316 (declare-function calendar-goto-date "cal-move" (date))
4317 (declare-function calendar-goto-today "cal-move" ())
4318 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4319 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4320 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4321 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4322 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4323 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4324 (defvar calendar-mode-map)
4325 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4326 (declare-function cdlatex-tab "ext:cdlatex" ())
4327 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4328 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4329 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4330 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4331 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4332 (defvar font-lock-unfontify-region-function)
4333 (declare-function gnus-article-show-summary "gnus-art" ())
4334 (declare-function gnus-summary-last-subject "gnus-sum" ())
4335 (defvar gnus-other-frame-object)
4336 (defvar gnus-group-name)
4337 (defvar gnus-article-current)
4338 (defvar Info-current-file)
4339 (defvar Info-current-node)
4340 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4341 (declare-function mh-find-path "mh-utils" ())
4342 (declare-function mh-get-header-field "mh-utils" (field))
4343 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4344 (declare-function mh-header-display "mh-show" ())
4345 (declare-function mh-index-previous-folder "mh-search" ())
4346 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4347 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4348 (declare-function mh-search-choose "mh-search" (&optional searcher))
4349 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4350 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4351 (declare-function mh-show-header-display "mh-show" t t)
4352 (declare-function mh-show-msg "mh-show" (msg))
4353 (declare-function mh-show-show "mh-show" t t)
4354 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4355 (defvar mh-progs)
4356 (defvar mh-current-folder)
4357 (defvar mh-show-folder-buffer)
4358 (defvar mh-index-folder)
4359 (defvar mh-searcher)
4360 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4361 (declare-function parse-time-string "parse-time" (string))
4362 (declare-function remember "remember" (&optional initial))
4363 (declare-function remember-buffer-desc "remember" ())
4364 (declare-function remember-finalize "remember" ())
4365 (defvar remember-save-after-remembering)
4366 (defvar remember-data-file)
4367 (defvar remember-register)
4368 (defvar remember-buffer)
4369 (defvar remember-handler-functions)
4370 (defvar remember-annotation-functions)
4371 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4372 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4373 (declare-function rmail-what-message "rmail" ())
4374 (defvar rmail-current-message)
4375 (defvar texmathp-why)
4376 (declare-function vm-beginning-of-message "ext:vm-page" ())
4377 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4378 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4379 (declare-function vm-isearch-narrow "ext:vm-search" ())
4380 (declare-function vm-isearch-update "ext:vm-search" ())
4381 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4382 (declare-function vm-su-message-id "ext:vm-summary" (m))
4383 (declare-function vm-su-subject "ext:vm-summary" (m))
4384 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4385 (defvar vm-message-pointer)
4386 (defvar vm-folder-directory)
4387 (defvar w3m-current-url)
4388 (defvar w3m-current-title)
4389 ;; backward compatibility to old version of wl
4390 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4391 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4392 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4393 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4394 (declare-function wl-summary-line-from "ext:wl-summary" ())
4395 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4396 (declare-function wl-summary-message-number "ext:wl-summary" ())
4397 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4398 (defvar wl-summary-buffer-elmo-folder)
4399 (defvar wl-summary-buffer-folder-name)
4400 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4402 (defvar org-latex-regexps)
4403 (defvar constants-unit-system)
4405 ;;; Variables for pre-computed regular expressions, all buffer local
4407 (defvar org-drawer-regexp nil
4408 "Matches first line of a hidden block.")
4409 (make-variable-buffer-local 'org-drawer-regexp)
4410 (defvar org-todo-regexp nil
4411 "Matches any of the TODO state keywords.")
4412 (make-variable-buffer-local 'org-todo-regexp)
4413 (defvar org-not-done-regexp nil
4414 "Matches any of the TODO state keywords except the last one.")
4415 (make-variable-buffer-local 'org-not-done-regexp)
4416 (defvar org-todo-line-regexp nil
4417 "Matches a headline and puts TODO state into group 2 if present.")
4418 (make-variable-buffer-local 'org-todo-line-regexp)
4419 (defvar org-complex-heading-regexp nil
4420 "Matches a headline and puts everything into groups:
4421 group 1: the stars
4422 group 2: The todo keyword, maybe
4423 group 3: Priority cookie
4424 group 4: True headline
4425 group 5: Tags")
4426 (make-variable-buffer-local 'org-complex-heading-regexp)
4427 (defvar org-todo-line-tags-regexp nil
4428 "Matches a headline and puts TODO state into group 2 if present.
4429 Also put tags into group 4 if tags are present.")
4430 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4431 (defvar org-nl-done-regexp nil
4432 "Matches newline followed by a headline with the DONE keyword.")
4433 (make-variable-buffer-local 'org-nl-done-regexp)
4434 (defvar org-looking-at-done-regexp nil
4435 "Matches the DONE keyword a point.")
4436 (make-variable-buffer-local 'org-looking-at-done-regexp)
4437 (defvar org-ds-keyword-length 12
4438 "Maximum length of the Deadline and SCHEDULED keywords.")
4439 (make-variable-buffer-local 'org-ds-keyword-length)
4440 (defvar org-deadline-regexp nil
4441 "Matches the DEADLINE keyword.")
4442 (make-variable-buffer-local 'org-deadline-regexp)
4443 (defvar org-deadline-time-regexp nil
4444 "Matches the DEADLINE keyword together with a time stamp.")
4445 (make-variable-buffer-local 'org-deadline-time-regexp)
4446 (defvar org-deadline-line-regexp nil
4447 "Matches the DEADLINE keyword and the rest of the line.")
4448 (make-variable-buffer-local 'org-deadline-line-regexp)
4449 (defvar org-scheduled-regexp nil
4450 "Matches the SCHEDULED keyword.")
4451 (make-variable-buffer-local 'org-scheduled-regexp)
4452 (defvar org-scheduled-time-regexp nil
4453 "Matches the SCHEDULED keyword together with a time stamp.")
4454 (make-variable-buffer-local 'org-scheduled-time-regexp)
4455 (defvar org-closed-time-regexp nil
4456 "Matches the CLOSED keyword together with a time stamp.")
4457 (make-variable-buffer-local 'org-closed-time-regexp)
4459 (defvar org-keyword-time-regexp nil
4460 "Matches any of the 4 keywords, together with the time stamp.")
4461 (make-variable-buffer-local 'org-keyword-time-regexp)
4462 (defvar org-keyword-time-not-clock-regexp nil
4463 "Matches any of the 3 keywords, together with the time stamp.")
4464 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4465 (defvar org-maybe-keyword-time-regexp nil
4466 "Matches a timestamp, possibly preceeded by a keyword.")
4467 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4468 (defvar org-planning-or-clock-line-re nil
4469 "Matches a line with planning or clock info.")
4470 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4472 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4473 rear-nonsticky t mouse-map t fontified t)
4474 "Properties to remove when a string without properties is wanted.")
4476 (defsubst org-match-string-no-properties (num &optional string)
4477 (if (featurep 'xemacs)
4478 (let ((s (match-string num string)))
4479 (remove-text-properties 0 (length s) org-rm-props s)
4481 (match-string-no-properties num string)))
4483 (defsubst org-no-properties (s)
4484 (if (fboundp 'set-text-properties)
4485 (set-text-properties 0 (length s) nil s)
4486 (remove-text-properties 0 (length s) org-rm-props s))
4489 (defsubst org-get-alist-option (option key)
4490 (cond ((eq key t) t)
4491 ((eq option t) t)
4492 ((assoc key option) (cdr (assoc key option)))
4493 (t (cdr (assq 'default option)))))
4495 (defsubst org-inhibit-invisibility ()
4496 "Modified `buffer-invisibility-spec' for Emacs 21.
4497 Some ops with invisible text do not work correctly on Emacs 21. For these
4498 we turn off invisibility temporarily. Use this in a `let' form."
4499 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4501 (defsubst org-set-local (var value)
4502 "Make VAR local in current buffer and set it to VALUE."
4503 (set (make-variable-buffer-local var) value))
4505 (defsubst org-mode-p ()
4506 "Check if the current buffer is in Org-mode."
4507 (eq major-mode 'org-mode))
4509 (defsubst org-last (list)
4510 "Return the last element of LIST."
4511 (car (last list)))
4513 (defun org-let (list &rest body)
4514 (eval (cons 'let (cons list body))))
4515 (put 'org-let 'lisp-indent-function 1)
4517 (defun org-let2 (list1 list2 &rest body)
4518 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4519 (put 'org-let2 'lisp-indent-function 2)
4520 (defconst org-startup-options
4521 '(("fold" org-startup-folded t)
4522 ("overview" org-startup-folded t)
4523 ("nofold" org-startup-folded nil)
4524 ("showall" org-startup-folded nil)
4525 ("content" org-startup-folded content)
4526 ("hidestars" org-hide-leading-stars t)
4527 ("showstars" org-hide-leading-stars nil)
4528 ("odd" org-odd-levels-only t)
4529 ("oddeven" org-odd-levels-only nil)
4530 ("align" org-startup-align-all-tables t)
4531 ("noalign" org-startup-align-all-tables nil)
4532 ("customtime" org-display-custom-times t)
4533 ("logdone" org-log-done time)
4534 ("lognotedone" org-log-done note)
4535 ("nologdone" org-log-done nil)
4536 ("lognoteclock-out" org-log-note-clock-out t)
4537 ("nolognoteclock-out" org-log-note-clock-out nil)
4538 ("logrepeat" org-log-repeat state)
4539 ("lognoterepeat" org-log-repeat note)
4540 ("nologrepeat" org-log-repeat nil)
4541 ("constcgs" constants-unit-system cgs)
4542 ("constSI" constants-unit-system SI))
4543 "Variable associated with STARTUP options for org-mode.
4544 Each element is a list of three items: The startup options as written
4545 in the #+STARTUP line, the corresponding variable, and the value to
4546 set this variable to if the option is found. An optional forth element PUSH
4547 means to push this value onto the list in the variable.")
4549 (defun org-set-regexps-and-options ()
4550 "Precompute regular expressions for current buffer."
4551 (when (org-mode-p)
4552 (org-set-local 'org-todo-kwd-alist nil)
4553 (org-set-local 'org-todo-key-alist nil)
4554 (org-set-local 'org-todo-key-trigger nil)
4555 (org-set-local 'org-todo-keywords-1 nil)
4556 (org-set-local 'org-done-keywords nil)
4557 (org-set-local 'org-todo-heads nil)
4558 (org-set-local 'org-todo-sets nil)
4559 (org-set-local 'org-todo-log-states nil)
4560 (let ((re (org-make-options-regexp
4561 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4562 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4563 "CONSTANTS" "PROPERTY" "DRAWERS")))
4564 (splitre "[ \t]+")
4565 kwds kws0 kwsa key log value cat arch tags const links hw dws
4566 tail sep kws1 prio props drawers)
4567 (save-excursion
4568 (save-restriction
4569 (widen)
4570 (goto-char (point-min))
4571 (while (re-search-forward re nil t)
4572 (setq key (match-string 1) value (org-match-string-no-properties 2))
4573 (cond
4574 ((equal key "CATEGORY")
4575 (if (string-match "[ \t]+$" value)
4576 (setq value (replace-match "" t t value)))
4577 (setq cat value))
4578 ((member key '("SEQ_TODO" "TODO"))
4579 (push (cons 'sequence (org-split-string value splitre)) kwds))
4580 ((equal key "TYP_TODO")
4581 (push (cons 'type (org-split-string value splitre)) kwds))
4582 ((equal key "TAGS")
4583 (setq tags (append tags (org-split-string value splitre))))
4584 ((equal key "COLUMNS")
4585 (org-set-local 'org-columns-default-format value))
4586 ((equal key "LINK")
4587 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4588 (push (cons (match-string 1 value)
4589 (org-trim (match-string 2 value)))
4590 links)))
4591 ((equal key "PRIORITIES")
4592 (setq prio (org-split-string value " +")))
4593 ((equal key "PROPERTY")
4594 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4595 (push (cons (match-string 1 value) (match-string 2 value))
4596 props)))
4597 ((equal key "DRAWERS")
4598 (setq drawers (org-split-string value splitre)))
4599 ((equal key "CONSTANTS")
4600 (setq const (append const (org-split-string value splitre))))
4601 ((equal key "STARTUP")
4602 (let ((opts (org-split-string value splitre))
4603 l var val)
4604 (while (setq l (pop opts))
4605 (when (setq l (assoc l org-startup-options))
4606 (setq var (nth 1 l) val (nth 2 l))
4607 (if (not (nth 3 l))
4608 (set (make-local-variable var) val)
4609 (if (not (listp (symbol-value var)))
4610 (set (make-local-variable var) nil))
4611 (set (make-local-variable var) (symbol-value var))
4612 (add-to-list var val))))))
4613 ((equal key "ARCHIVE")
4614 (string-match " *$" value)
4615 (setq arch (replace-match "" t t value))
4616 (remove-text-properties 0 (length arch)
4617 '(face t fontified t) arch)))
4619 (when cat
4620 (org-set-local 'org-category (intern cat))
4621 (push (cons "CATEGORY" cat) props))
4622 (when prio
4623 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4624 (setq prio (mapcar 'string-to-char prio))
4625 (org-set-local 'org-highest-priority (nth 0 prio))
4626 (org-set-local 'org-lowest-priority (nth 1 prio))
4627 (org-set-local 'org-default-priority (nth 2 prio)))
4628 (and props (org-set-local 'org-local-properties (nreverse props)))
4629 (and drawers (org-set-local 'org-drawers drawers))
4630 (and arch (org-set-local 'org-archive-location arch))
4631 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4632 ;; Process the TODO keywords
4633 (unless kwds
4634 ;; Use the global values as if they had been given locally.
4635 (setq kwds (default-value 'org-todo-keywords))
4636 (if (stringp (car kwds))
4637 (setq kwds (list (cons org-todo-interpretation
4638 (default-value 'org-todo-keywords)))))
4639 (setq kwds (reverse kwds)))
4640 (setq kwds (nreverse kwds))
4641 (let (inter kws kw)
4642 (while (setq kws (pop kwds))
4643 (setq inter (pop kws) sep (member "|" kws)
4644 kws0 (delete "|" (copy-sequence kws))
4645 kwsa nil
4646 kws1 (mapcar
4647 (lambda (x)
4648 ;; 1 2
4649 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4650 (progn
4651 (setq kw (match-string 1 x)
4652 key (and (match-end 2) (match-string 2 x))
4653 log (org-extract-log-state-settings x))
4654 (push (cons kw (and key (string-to-char key))) kwsa)
4655 (and log (push log org-todo-log-states))
4657 (error "Invalid TODO keyword %s" x)))
4658 kws0)
4659 kwsa (if kwsa (append '((:startgroup))
4660 (nreverse kwsa)
4661 '((:endgroup))))
4662 hw (car kws1)
4663 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4664 tail (list inter hw (car dws) (org-last dws)))
4665 (add-to-list 'org-todo-heads hw 'append)
4666 (push kws1 org-todo-sets)
4667 (setq org-done-keywords (append org-done-keywords dws nil))
4668 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4669 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4670 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4671 (setq org-todo-sets (nreverse org-todo-sets)
4672 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4673 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4674 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4675 ;; Process the constants
4676 (when const
4677 (let (e cst)
4678 (while (setq e (pop const))
4679 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4680 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4681 (setq org-table-formula-constants-local cst)))
4683 ;; Process the tags.
4684 (when tags
4685 (let (e tgs)
4686 (while (setq e (pop tags))
4687 (cond
4688 ((equal e "{") (push '(:startgroup) tgs))
4689 ((equal e "}") (push '(:endgroup) tgs))
4690 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4691 (push (cons (match-string 1 e)
4692 (string-to-char (match-string 2 e)))
4693 tgs))
4694 (t (push (list e) tgs))))
4695 (org-set-local 'org-tag-alist nil)
4696 (while (setq e (pop tgs))
4697 (or (and (stringp (car e))
4698 (assoc (car e) org-tag-alist))
4699 (push e org-tag-alist))))))
4701 ;; Compute the regular expressions and other local variables
4702 (if (not org-done-keywords)
4703 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4704 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4705 (length org-scheduled-string)))
4706 org-drawer-regexp
4707 (concat "^[ \t]*:\\("
4708 (mapconcat 'regexp-quote org-drawers "\\|")
4709 "\\):[ \t]*$")
4710 org-not-done-keywords
4711 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4712 org-todo-regexp
4713 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4714 "\\|") "\\)\\>")
4715 org-not-done-regexp
4716 (concat "\\<\\("
4717 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4718 "\\)\\>")
4719 org-todo-line-regexp
4720 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4721 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4722 "\\)\\>\\)?[ \t]*\\(.*\\)")
4723 org-complex-heading-regexp
4724 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4725 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4726 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4727 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4728 org-nl-done-regexp
4729 (concat "\n\\*+[ \t]+"
4730 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4731 "\\)" "\\>")
4732 org-todo-line-tags-regexp
4733 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4734 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4735 (org-re
4736 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4737 org-looking-at-done-regexp
4738 (concat "^" "\\(?:"
4739 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4740 "\\>")
4741 org-deadline-regexp (concat "\\<" org-deadline-string)
4742 org-deadline-time-regexp
4743 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4744 org-deadline-line-regexp
4745 (concat "\\<\\(" org-deadline-string "\\).*")
4746 org-scheduled-regexp
4747 (concat "\\<" org-scheduled-string)
4748 org-scheduled-time-regexp
4749 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4750 org-closed-time-regexp
4751 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4752 org-keyword-time-regexp
4753 (concat "\\<\\(" org-scheduled-string
4754 "\\|" org-deadline-string
4755 "\\|" org-closed-string
4756 "\\|" org-clock-string "\\)"
4757 " *[[<]\\([^]>]+\\)[]>]")
4758 org-keyword-time-not-clock-regexp
4759 (concat "\\<\\(" org-scheduled-string
4760 "\\|" org-deadline-string
4761 "\\|" org-closed-string
4762 "\\)"
4763 " *[[<]\\([^]>]+\\)[]>]")
4764 org-maybe-keyword-time-regexp
4765 (concat "\\(\\<\\(" org-scheduled-string
4766 "\\|" org-deadline-string
4767 "\\|" org-closed-string
4768 "\\|" org-clock-string "\\)\\)?"
4769 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4770 org-planning-or-clock-line-re
4771 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4772 "\\|" org-deadline-string
4773 "\\|" org-closed-string "\\|" org-clock-string
4774 "\\)\\>\\)")
4776 (org-compute-latex-and-specials-regexp)
4777 (org-set-font-lock-defaults)))
4779 (defun org-extract-log-state-settings (x)
4780 "Extract the log state setting from a TODO keyword string.
4781 This will extract info from a string like \"WAIT(w@/!)\"."
4782 (let (kw key log1 log2)
4783 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4784 (setq kw (match-string 1 x)
4785 key (and (match-end 2) (match-string 2 x))
4786 log1 (and (match-end 3) (match-string 3 x))
4787 log2 (and (match-end 4) (match-string 4 x)))
4788 (and (or log1 log2)
4789 (list kw
4790 (and log1 (if (equal log1 "!") 'time 'note))
4791 (and log2 (if (equal log2 "!") 'time 'note)))))))
4793 (defun org-remove-keyword-keys (list)
4794 "Remove a pair of parenthesis at the end of each string in LIST."
4795 (mapcar (lambda (x)
4796 (if (string-match "(.*)$" x)
4797 (substring x 0 (match-beginning 0))
4799 list))
4801 ;; FIXME: this could be done much better, using second characters etc.
4802 (defun org-assign-fast-keys (alist)
4803 "Assign fast keys to a keyword-key alist.
4804 Respect keys that are already there."
4805 (let (new e k c c1 c2 (char ?a))
4806 (while (setq e (pop alist))
4807 (cond
4808 ((equal e '(:startgroup)) (push e new))
4809 ((equal e '(:endgroup)) (push e new))
4811 (setq k (car e) c2 nil)
4812 (if (cdr e)
4813 (setq c (cdr e))
4814 ;; automatically assign a character.
4815 (setq c1 (string-to-char
4816 (downcase (substring
4817 k (if (= (string-to-char k) ?@) 1 0)))))
4818 (if (or (rassoc c1 new) (rassoc c1 alist))
4819 (while (or (rassoc char new) (rassoc char alist))
4820 (setq char (1+ char)))
4821 (setq c2 c1))
4822 (setq c (or c2 char)))
4823 (push (cons k c) new))))
4824 (nreverse new)))
4826 ;;; Some variables ujsed in various places
4828 (defvar org-window-configuration nil
4829 "Used in various places to store a window configuration.")
4830 (defvar org-finish-function nil
4831 "Function to be called when `C-c C-c' is used.
4832 This is for getting out of special buffers like remember.")
4835 ;; FIXME: Occasionally check by commenting these, to make sure
4836 ;; no other functions uses these, forgetting to let-bind them.
4837 (defvar entry)
4838 (defvar state)
4839 (defvar last-state)
4840 (defvar date)
4841 (defvar description)
4843 ;; Defined somewhere in this file, but used before definition.
4844 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4845 (defvar org-agenda-buffer-name)
4846 (defvar org-agenda-undo-list)
4847 (defvar org-agenda-pending-undo-list)
4848 (defvar org-agenda-overriding-header)
4849 (defvar orgtbl-mode)
4850 (defvar org-html-entities)
4851 (defvar org-struct-menu)
4852 (defvar org-org-menu)
4853 (defvar org-tbl-menu)
4854 (defvar org-agenda-keymap)
4856 ;;;; Emacs/XEmacs compatibility
4858 ;; Overlay compatibility functions
4859 (defun org-make-overlay (beg end &optional buffer)
4860 (if (featurep 'xemacs)
4861 (make-extent beg end buffer)
4862 (make-overlay beg end buffer)))
4863 (defun org-delete-overlay (ovl)
4864 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4865 (defun org-detach-overlay (ovl)
4866 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4867 (defun org-move-overlay (ovl beg end &optional buffer)
4868 (if (featurep 'xemacs)
4869 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4870 (move-overlay ovl beg end buffer)))
4871 (defun org-overlay-put (ovl prop value)
4872 (if (featurep 'xemacs)
4873 (set-extent-property ovl prop value)
4874 (overlay-put ovl prop value)))
4875 (defun org-overlay-display (ovl text &optional face evap)
4876 "Make overlay OVL display TEXT with face FACE."
4877 (if (featurep 'xemacs)
4878 (let ((gl (make-glyph text)))
4879 (and face (set-glyph-face gl face))
4880 (set-extent-property ovl 'invisible t)
4881 (set-extent-property ovl 'end-glyph gl))
4882 (overlay-put ovl 'display text)
4883 (if face (overlay-put ovl 'face face))
4884 (if evap (overlay-put ovl 'evaporate t))))
4885 (defun org-overlay-before-string (ovl text &optional face evap)
4886 "Make overlay OVL display TEXT with face FACE."
4887 (if (featurep 'xemacs)
4888 (let ((gl (make-glyph text)))
4889 (and face (set-glyph-face gl face))
4890 (set-extent-property ovl 'begin-glyph gl))
4891 (if face (org-add-props text nil 'face face))
4892 (overlay-put ovl 'before-string text)
4893 (if evap (overlay-put ovl 'evaporate t))))
4894 (defun org-overlay-get (ovl prop)
4895 (if (featurep 'xemacs)
4896 (extent-property ovl prop)
4897 (overlay-get ovl prop)))
4898 (defun org-overlays-at (pos)
4899 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4900 (defun org-overlays-in (&optional start end)
4901 (if (featurep 'xemacs)
4902 (extent-list nil start end)
4903 (overlays-in start end)))
4904 (defun org-overlay-start (o)
4905 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4906 (defun org-overlay-end (o)
4907 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4908 (defun org-find-overlays (prop &optional pos delete)
4909 "Find all overlays specifying PROP at POS or point.
4910 If DELETE is non-nil, delete all those overlays."
4911 (let ((overlays (org-overlays-at (or pos (point))))
4912 ov found)
4913 (while (setq ov (pop overlays))
4914 (if (org-overlay-get ov prop)
4915 (if delete (org-delete-overlay ov) (push ov found))))
4916 found))
4918 ;; Region compatibility
4920 (defun org-add-hook (hook function &optional append local)
4921 "Add-hook, compatible with both Emacsen."
4922 (if (and local (featurep 'xemacs))
4923 (add-local-hook hook function append)
4924 (add-hook hook function append local)))
4926 (defvar org-ignore-region nil
4927 "To temporarily disable the active region.")
4929 (defun org-region-active-p ()
4930 "Is `transient-mark-mode' on and the region active?
4931 Works on both Emacs and XEmacs."
4932 (if org-ignore-region
4934 (if (featurep 'xemacs)
4935 (and zmacs-regions (region-active-p))
4936 (if (fboundp 'use-region-p)
4937 (use-region-p)
4938 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4940 ;; Invisibility compatibility
4942 (defun org-add-to-invisibility-spec (arg)
4943 "Add elements to `buffer-invisibility-spec'.
4944 See documentation for `buffer-invisibility-spec' for the kind of elements
4945 that can be added."
4946 (cond
4947 ((fboundp 'add-to-invisibility-spec)
4948 (add-to-invisibility-spec arg))
4949 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4950 (setq buffer-invisibility-spec (list arg)))
4952 (setq buffer-invisibility-spec
4953 (cons arg buffer-invisibility-spec)))))
4955 (defun org-remove-from-invisibility-spec (arg)
4956 "Remove elements from `buffer-invisibility-spec'."
4957 (if (fboundp 'remove-from-invisibility-spec)
4958 (remove-from-invisibility-spec arg)
4959 (if (consp buffer-invisibility-spec)
4960 (setq buffer-invisibility-spec
4961 (delete arg buffer-invisibility-spec)))))
4963 (defun org-in-invisibility-spec-p (arg)
4964 "Is ARG a member of `buffer-invisibility-spec'?"
4965 (if (consp buffer-invisibility-spec)
4966 (member arg buffer-invisibility-spec)
4967 nil))
4969 ;;;; Define the Org-mode
4971 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4972 (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."))
4975 ;; We use a before-change function to check if a table might need
4976 ;; an update.
4977 (defvar org-table-may-need-update t
4978 "Indicates that a table might need an update.
4979 This variable is set by `org-before-change-function'.
4980 `org-table-align' sets it back to nil.")
4981 (defvar org-mode-map)
4982 (defvar org-mode-hook nil)
4983 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4984 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4985 (defvar org-table-buffer-is-an nil)
4986 (defconst org-outline-regexp "\\*+ ")
4988 ;;;###autoload
4989 (define-derived-mode org-mode outline-mode "Org"
4990 "Outline-based notes management and organizer, alias
4991 \"Carsten's outline-mode for keeping track of everything.\"
4993 Org-mode develops organizational tasks around a NOTES file which
4994 contains information about projects as plain text. Org-mode is
4995 implemented on top of outline-mode, which is ideal to keep the content
4996 of large files well structured. It supports ToDo items, deadlines and
4997 time stamps, which magically appear in the diary listing of the Emacs
4998 calendar. Tables are easily created with a built-in table editor.
4999 Plain text URL-like links connect to websites, emails (VM), Usenet
5000 messages (Gnus), BBDB entries, and any files related to the project.
5001 For printing and sharing of notes, an Org-mode file (or a part of it)
5002 can be exported as a structured ASCII or HTML file.
5004 The following commands are available:
5006 \\{org-mode-map}"
5008 ;; Get rid of Outline menus, they are not needed
5009 ;; Need to do this here because define-derived-mode sets up
5010 ;; the keymap so late. Still, it is a waste to call this each time
5011 ;; we switch another buffer into org-mode.
5012 (if (featurep 'xemacs)
5013 (when (boundp 'outline-mode-menu-heading)
5014 ;; Assume this is Greg's port, it used easymenu
5015 (easy-menu-remove outline-mode-menu-heading)
5016 (easy-menu-remove outline-mode-menu-show)
5017 (easy-menu-remove outline-mode-menu-hide))
5018 (define-key org-mode-map [menu-bar headings] 'undefined)
5019 (define-key org-mode-map [menu-bar hide] 'undefined)
5020 (define-key org-mode-map [menu-bar show] 'undefined))
5022 (easy-menu-add org-org-menu)
5023 (easy-menu-add org-tbl-menu)
5024 (org-install-agenda-files-menu)
5025 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
5026 (org-add-to-invisibility-spec '(org-cwidth))
5027 (when (featurep 'xemacs)
5028 (org-set-local 'line-move-ignore-invisible t))
5029 (org-set-local 'outline-regexp org-outline-regexp)
5030 (org-set-local 'outline-level 'org-outline-level)
5031 (when (and org-ellipsis
5032 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5033 (fboundp 'make-glyph-code))
5034 (unless org-display-table
5035 (setq org-display-table (make-display-table)))
5036 (set-display-table-slot
5037 org-display-table 4
5038 (vconcat (mapcar
5039 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5040 org-ellipsis)))
5041 (if (stringp org-ellipsis) org-ellipsis "..."))))
5042 (setq buffer-display-table org-display-table))
5043 (org-set-regexps-and-options)
5044 ;; Calc embedded
5045 (org-set-local 'calc-embedded-open-mode "# ")
5046 (modify-syntax-entry ?# "<")
5047 (modify-syntax-entry ?@ "w")
5048 (if org-startup-truncated (setq truncate-lines t))
5049 (org-set-local 'font-lock-unfontify-region-function
5050 'org-unfontify-region)
5051 ;; Activate before-change-function
5052 (org-set-local 'org-table-may-need-update t)
5053 (org-add-hook 'before-change-functions 'org-before-change-function nil
5054 'local)
5055 ;; Check for running clock before killing a buffer
5056 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5057 ;; Paragraphs and auto-filling
5058 (org-set-autofill-regexps)
5059 (setq indent-line-function 'org-indent-line-function)
5060 (org-update-radio-target-regexp)
5062 ;; Comment characters
5063 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5064 (org-set-local 'comment-padding " ")
5066 ;; Align options lines
5067 (org-set-local
5068 'align-mode-rules-list
5069 '((org-in-buffer-settings
5070 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5071 (modes . '(org-mode)))))
5073 ;; Imenu
5074 (org-set-local 'imenu-create-index-function
5075 'org-imenu-get-tree)
5077 ;; Make isearch reveal context
5078 (if (or (featurep 'xemacs)
5079 (not (boundp 'outline-isearch-open-invisible-function)))
5080 ;; Emacs 21 and XEmacs make use of the hook
5081 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5082 ;; Emacs 22 deals with this through a special variable
5083 (org-set-local 'outline-isearch-open-invisible-function
5084 (lambda (&rest ignore) (org-show-context 'isearch))))
5086 ;; If empty file that did not turn on org-mode automatically, make it to.
5087 (if (and org-insert-mode-line-in-empty-file
5088 (interactive-p)
5089 (= (point-min) (point-max)))
5090 (insert "# -*- mode: org -*-\n\n"))
5092 (unless org-inhibit-startup
5093 (when org-startup-align-all-tables
5094 (let ((bmp (buffer-modified-p)))
5095 (org-table-map-tables 'org-table-align)
5096 (set-buffer-modified-p bmp)))
5097 (org-cycle-hide-drawers 'all)
5098 (cond
5099 ((eq org-startup-folded t)
5100 (org-cycle '(4)))
5101 ((eq org-startup-folded 'content)
5102 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5103 (org-cycle '(4)) (org-cycle '(4)))))))
5105 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5107 (defsubst org-call-with-arg (command arg)
5108 "Call COMMAND interactively, but pretend prefix are was ARG."
5109 (let ((current-prefix-arg arg)) (call-interactively command)))
5111 (defsubst org-current-line (&optional pos)
5112 (save-excursion
5113 (and pos (goto-char pos))
5114 ;; works also in narrowed buffer, because we start at 1, not point-min
5115 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5117 (defun org-current-time ()
5118 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5119 (if (> (car org-time-stamp-rounding-minutes) 1)
5120 (let ((r (car org-time-stamp-rounding-minutes))
5121 (time (decode-time)))
5122 (apply 'encode-time
5123 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5124 (nthcdr 2 time))))
5125 (current-time)))
5127 (defun org-add-props (string plist &rest props)
5128 "Add text properties to entire string, from beginning to end.
5129 PLIST may be a list of properties, PROPS are individual properties and values
5130 that will be added to PLIST. Returns the string that was modified."
5131 (add-text-properties
5132 0 (length string) (if props (append plist props) plist) string)
5133 string)
5134 (put 'org-add-props 'lisp-indent-function 2)
5137 ;;;; Font-Lock stuff, including the activators
5139 (defvar org-mouse-map (make-sparse-keymap))
5140 (org-defkey org-mouse-map
5141 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5142 (org-defkey org-mouse-map
5143 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5144 (when org-mouse-1-follows-link
5145 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5146 (when org-tab-follows-link
5147 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5148 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5149 (when org-return-follows-link
5150 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5151 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5153 (require 'font-lock)
5155 (defconst org-non-link-chars "]\t\n\r<>")
5156 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5157 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5158 (defvar org-link-re-with-space nil
5159 "Matches a link with spaces, optional angular brackets around it.")
5160 (defvar org-link-re-with-space2 nil
5161 "Matches a link with spaces, optional angular brackets around it.")
5162 (defvar org-angle-link-re nil
5163 "Matches link with angular brackets, spaces are allowed.")
5164 (defvar org-plain-link-re nil
5165 "Matches plain link, without spaces.")
5166 (defvar org-bracket-link-regexp nil
5167 "Matches a link in double brackets.")
5168 (defvar org-bracket-link-analytic-regexp nil
5169 "Regular expression used to analyze links.
5170 Here is what the match groups contain after a match:
5171 1: http:
5172 2: http
5173 3: path
5174 4: [desc]
5175 5: desc")
5176 (defvar org-any-link-re nil
5177 "Regular expression matching any link.")
5179 (defun org-make-link-regexps ()
5180 "Update the link regular expressions.
5181 This should be called after the variable `org-link-types' has changed."
5182 (setq org-link-re-with-space
5183 (concat
5184 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5185 "\\([^" org-non-link-chars " ]"
5186 "[^" org-non-link-chars "]*"
5187 "[^" org-non-link-chars " ]\\)>?")
5188 org-link-re-with-space2
5189 (concat
5190 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5191 "\\([^" org-non-link-chars " ]"
5192 "[^]\t\n\r]*"
5193 "[^" org-non-link-chars " ]\\)>?")
5194 org-angle-link-re
5195 (concat
5196 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5197 "\\([^" org-non-link-chars " ]"
5198 "[^" org-non-link-chars "]*"
5199 "\\)>")
5200 org-plain-link-re
5201 (concat
5202 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5203 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5204 org-bracket-link-regexp
5205 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5206 org-bracket-link-analytic-regexp
5207 (concat
5208 "\\[\\["
5209 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5210 "\\([^]]+\\)"
5211 "\\]"
5212 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5213 "\\]")
5214 org-any-link-re
5215 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5216 org-angle-link-re "\\)\\|\\("
5217 org-plain-link-re "\\)")))
5219 (org-make-link-regexps)
5221 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5222 "Regular expression for fast time stamp matching.")
5223 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5224 "Regular expression for fast time stamp matching.")
5225 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5226 "Regular expression matching time strings for analysis.
5227 This one does not require the space after the date.")
5228 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5229 "Regular expression matching time strings for analysis.")
5230 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5231 "Regular expression matching time stamps, with groups.")
5232 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5233 "Regular expression matching time stamps (also [..]), with groups.")
5234 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5235 "Regular expression matching a time stamp range.")
5236 (defconst org-tr-regexp-both
5237 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5238 "Regular expression matching a time stamp range.")
5239 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5240 org-ts-regexp "\\)?")
5241 "Regular expression matching a time stamp or time stamp range.")
5242 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5243 org-ts-regexp-both "\\)?")
5244 "Regular expression matching a time stamp or time stamp range.
5245 The time stamps may be either active or inactive.")
5247 (defvar org-emph-face nil)
5249 (defun org-do-emphasis-faces (limit)
5250 "Run through the buffer and add overlays to links."
5251 (let (rtn)
5252 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5253 (if (not (= (char-after (match-beginning 3))
5254 (char-after (match-beginning 4))))
5255 (progn
5256 (setq rtn t)
5257 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5258 'face
5259 (nth 1 (assoc (match-string 3)
5260 org-emphasis-alist)))
5261 (add-text-properties (match-beginning 2) (match-end 2)
5262 '(font-lock-multiline t))
5263 (when org-hide-emphasis-markers
5264 (add-text-properties (match-end 4) (match-beginning 5)
5265 '(invisible org-link))
5266 (add-text-properties (match-beginning 3) (match-end 3)
5267 '(invisible org-link)))))
5268 (backward-char 1))
5269 rtn))
5271 (defun org-emphasize (&optional char)
5272 "Insert or change an emphasis, i.e. a font like bold or italic.
5273 If there is an active region, change that region to a new emphasis.
5274 If there is no region, just insert the marker characters and position
5275 the cursor between them.
5276 CHAR should be either the marker character, or the first character of the
5277 HTML tag associated with that emphasis. If CHAR is a space, the means
5278 to remove the emphasis of the selected region.
5279 If char is not given (for example in an interactive call) it
5280 will be prompted for."
5281 (interactive)
5282 (let ((eal org-emphasis-alist) e det
5283 (erc org-emphasis-regexp-components)
5284 (prompt "")
5285 (string "") beg end move tag c s)
5286 (if (org-region-active-p)
5287 (setq beg (region-beginning) end (region-end)
5288 string (buffer-substring beg end))
5289 (setq move t))
5291 (while (setq e (pop eal))
5292 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5293 c (aref tag 0))
5294 (push (cons c (string-to-char (car e))) det)
5295 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5296 (substring tag 1)))))
5297 (unless char
5298 (message "%s" (concat "Emphasis marker or tag:" prompt))
5299 (setq char (read-char-exclusive)))
5300 (setq char (or (cdr (assoc char det)) char))
5301 (if (equal char ?\ )
5302 (setq s "" move nil)
5303 (unless (assoc (char-to-string char) org-emphasis-alist)
5304 (error "No such emphasis marker: \"%c\"" char))
5305 (setq s (char-to-string char)))
5306 (while (and (> (length string) 1)
5307 (equal (substring string 0 1) (substring string -1))
5308 (assoc (substring string 0 1) org-emphasis-alist))
5309 (setq string (substring string 1 -1)))
5310 (setq string (concat s string s))
5311 (if beg (delete-region beg end))
5312 (unless (or (bolp)
5313 (string-match (concat "[" (nth 0 erc) "\n]")
5314 (char-to-string (char-before (point)))))
5315 (insert " "))
5316 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5317 (char-to-string (char-after (point))))
5318 (insert " ") (backward-char 1))
5319 (insert string)
5320 (and move (backward-char 1))))
5322 (defconst org-nonsticky-props
5323 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5326 (defun org-activate-plain-links (limit)
5327 "Run through the buffer and add overlays to links."
5328 (catch 'exit
5329 (let (f)
5330 (while (re-search-forward org-plain-link-re limit t)
5331 (setq f (get-text-property (match-beginning 0) 'face))
5332 (if (or (eq f 'org-tag)
5333 (and (listp f) (memq 'org-tag f)))
5335 (add-text-properties (match-beginning 0) (match-end 0)
5336 (list 'mouse-face 'highlight
5337 'rear-nonsticky org-nonsticky-props
5338 'keymap org-mouse-map
5340 (throw 'exit t))))))
5342 (defun org-activate-code (limit)
5343 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5344 (unless (get-text-property (match-beginning 1) 'face)
5345 (remove-text-properties (match-beginning 0) (match-end 0)
5346 '(display t invisible t intangible t))
5347 t)))
5349 (defun org-activate-angle-links (limit)
5350 "Run through the buffer and add overlays to links."
5351 (if (re-search-forward org-angle-link-re limit t)
5352 (progn
5353 (add-text-properties (match-beginning 0) (match-end 0)
5354 (list 'mouse-face 'highlight
5355 'rear-nonsticky org-nonsticky-props
5356 'keymap org-mouse-map
5358 t)))
5360 (defmacro org-maybe-intangible (props)
5361 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5362 In emacs 21, invisible text is not avoided by the command loop, so the
5363 intangible property is needed to make sure point skips this text.
5364 In Emacs 22, this is not necessary. The intangible text property has
5365 led to problems with flyspell. These problems are fixed in flyspell.el,
5366 but we still avoid setting the property in Emacs 22 and later.
5367 We use a macro so that the test can happen at compilation time."
5368 (if (< emacs-major-version 22)
5369 `(append '(intangible t) ,props)
5370 props))
5372 (defun org-activate-bracket-links (limit)
5373 "Run through the buffer and add overlays to bracketed links."
5374 (if (re-search-forward org-bracket-link-regexp limit t)
5375 (let* ((help (concat "LINK: "
5376 (org-match-string-no-properties 1)))
5377 ;; FIXME: above we should remove the escapes.
5378 ;; but that requires another match, protecting match data,
5379 ;; a lot of overhead for font-lock.
5380 (ip (org-maybe-intangible
5381 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5382 'keymap org-mouse-map 'mouse-face 'highlight
5383 'font-lock-multiline t 'help-echo help)))
5384 (vp (list 'rear-nonsticky org-nonsticky-props
5385 'keymap org-mouse-map 'mouse-face 'highlight
5386 ' font-lock-multiline t 'help-echo help)))
5387 ;; We need to remove the invisible property here. Table narrowing
5388 ;; may have made some of this invisible.
5389 (remove-text-properties (match-beginning 0) (match-end 0)
5390 '(invisible nil))
5391 (if (match-end 3)
5392 (progn
5393 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5394 (add-text-properties (match-beginning 3) (match-end 3) vp)
5395 (add-text-properties (match-end 3) (match-end 0) ip))
5396 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5397 (add-text-properties (match-beginning 1) (match-end 1) vp)
5398 (add-text-properties (match-end 1) (match-end 0) ip))
5399 t)))
5401 (defun org-activate-dates (limit)
5402 "Run through the buffer and add overlays to dates."
5403 (if (re-search-forward org-tsr-regexp-both limit t)
5404 (progn
5405 (add-text-properties (match-beginning 0) (match-end 0)
5406 (list 'mouse-face 'highlight
5407 'rear-nonsticky org-nonsticky-props
5408 'keymap org-mouse-map))
5409 (when org-display-custom-times
5410 (if (match-end 3)
5411 (org-display-custom-time (match-beginning 3) (match-end 3)))
5412 (org-display-custom-time (match-beginning 1) (match-end 1)))
5413 t)))
5415 (defvar org-target-link-regexp nil
5416 "Regular expression matching radio targets in plain text.")
5417 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5418 "Regular expression matching a link target.")
5419 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5420 "Regular expression matching a radio target.")
5421 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5422 "Regular expression matching any target.")
5424 (defun org-activate-target-links (limit)
5425 "Run through the buffer and add overlays to target matches."
5426 (when org-target-link-regexp
5427 (let ((case-fold-search t))
5428 (if (re-search-forward org-target-link-regexp limit t)
5429 (progn
5430 (add-text-properties (match-beginning 0) (match-end 0)
5431 (list 'mouse-face 'highlight
5432 'rear-nonsticky org-nonsticky-props
5433 'keymap org-mouse-map
5434 'help-echo "Radio target link"
5435 'org-linked-text t))
5436 t)))))
5438 (defun org-update-radio-target-regexp ()
5439 "Find all radio targets in this file and update the regular expression."
5440 (interactive)
5441 (when (memq 'radio org-activate-links)
5442 (setq org-target-link-regexp
5443 (org-make-target-link-regexp (org-all-targets 'radio)))
5444 (org-restart-font-lock)))
5446 (defun org-hide-wide-columns (limit)
5447 (let (s e)
5448 (setq s (text-property-any (point) (or limit (point-max))
5449 'org-cwidth t))
5450 (when s
5451 (setq e (next-single-property-change s 'org-cwidth))
5452 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5453 (goto-char e)
5454 t)))
5456 (defvar org-latex-and-specials-regexp nil
5457 "Regular expression for highlighting export special stuff.")
5458 (defvar org-match-substring-regexp)
5459 (defvar org-match-substring-with-braces-regexp)
5460 (defvar org-export-html-special-string-regexps)
5462 (defun org-compute-latex-and-specials-regexp ()
5463 "Compute regular expression for stuff treated specially by exporters."
5464 (if (not org-highlight-latex-fragments-and-specials)
5465 (org-set-local 'org-latex-and-specials-regexp nil)
5466 (let*
5467 ((matchers (plist-get org-format-latex-options :matchers))
5468 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5469 org-latex-regexps)))
5470 (options (org-combine-plists (org-default-export-plist)
5471 (org-infile-export-plist)))
5472 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5473 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5474 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5475 (org-export-html-expand (plist-get options :expand-quoted-html))
5476 (org-export-with-special-strings (plist-get options :special-strings))
5477 (re-sub
5478 (cond
5479 ((equal org-export-with-sub-superscripts '{})
5480 (list org-match-substring-with-braces-regexp))
5481 (org-export-with-sub-superscripts
5482 (list org-match-substring-regexp))
5483 (t nil)))
5484 (re-latex
5485 (if org-export-with-LaTeX-fragments
5486 (mapcar (lambda (x) (nth 1 x)) latexs)))
5487 (re-macros
5488 (if org-export-with-TeX-macros
5489 (list (concat "\\\\"
5490 (regexp-opt
5491 (append (mapcar 'car org-html-entities)
5492 (if (boundp 'org-latex-entities)
5493 org-latex-entities nil))
5494 'words))) ; FIXME
5496 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5497 (re-special (if org-export-with-special-strings
5498 (mapcar (lambda (x) (car x))
5499 org-export-html-special-string-regexps)))
5500 (re-rest
5501 (delq nil
5502 (list
5503 (if org-export-html-expand "@<[^>\n]+>")
5504 ))))
5505 (org-set-local
5506 'org-latex-and-specials-regexp
5507 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5508 re-rest) "\\|")))))
5510 (defface org-latex-and-export-specials
5511 (let ((font (cond ((assq :inherit custom-face-attributes)
5512 '(:inherit underline))
5513 (t '(:underline t)))))
5514 `((((class grayscale) (background light))
5515 (:foreground "DimGray" ,@font))
5516 (((class grayscale) (background dark))
5517 (:foreground "LightGray" ,@font))
5518 (((class color) (background light))
5519 (:foreground "SaddleBrown"))
5520 (((class color) (background dark))
5521 (:foreground "burlywood"))
5522 (t (,@font))))
5523 "Face used to highlight math latex and other special exporter stuff."
5524 :group 'org-faces)
5526 (defun org-do-latex-and-special-faces (limit)
5527 "Run through the buffer and add overlays to links."
5528 (when org-latex-and-specials-regexp
5529 (let (rtn d)
5530 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5531 limit t))
5532 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5533 'face))
5534 '(org-code org-verbatim underline)))
5535 (progn
5536 (setq rtn t
5537 d (cond ((member (char-after (1+ (match-beginning 0)))
5538 '(?_ ?^)) 1)
5539 (t 0)))
5540 (font-lock-prepend-text-property
5541 (+ d (match-beginning 0)) (match-end 0)
5542 'face 'org-latex-and-export-specials)
5543 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5544 '(font-lock-multiline t)))))
5545 rtn)))
5547 (defun org-restart-font-lock ()
5548 "Restart font-lock-mode, to force refontification."
5549 (when (and (boundp 'font-lock-mode) font-lock-mode)
5550 (font-lock-mode -1)
5551 (font-lock-mode 1)))
5553 (defun org-all-targets (&optional radio)
5554 "Return a list of all targets in this file.
5555 With optional argument RADIO, only find radio targets."
5556 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5557 rtn)
5558 (save-excursion
5559 (goto-char (point-min))
5560 (while (re-search-forward re nil t)
5561 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5562 rtn)))
5564 (defun org-make-target-link-regexp (targets)
5565 "Make regular expression matching all strings in TARGETS.
5566 The regular expression finds the targets also if there is a line break
5567 between words."
5568 (and targets
5569 (concat
5570 "\\<\\("
5571 (mapconcat
5572 (lambda (x)
5573 (while (string-match " +" x)
5574 (setq x (replace-match "\\s-+" t t x)))
5576 targets
5577 "\\|")
5578 "\\)\\>")))
5580 (defun org-activate-tags (limit)
5581 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5582 (progn
5583 (add-text-properties (match-beginning 1) (match-end 1)
5584 (list 'mouse-face 'highlight
5585 'rear-nonsticky org-nonsticky-props
5586 'keymap org-mouse-map))
5587 t)))
5589 (defun org-outline-level ()
5590 (save-excursion
5591 (looking-at outline-regexp)
5592 (if (match-beginning 1)
5593 (+ (org-get-string-indentation (match-string 1)) 1000)
5594 (1- (- (match-end 0) (match-beginning 0))))))
5596 (defvar org-font-lock-keywords nil)
5598 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5599 "Regular expression matching a property line.")
5601 (defun org-set-font-lock-defaults ()
5602 (let* ((em org-fontify-emphasized-text)
5603 (lk org-activate-links)
5604 (org-font-lock-extra-keywords
5605 (list
5606 ;; Headlines
5607 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5608 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5609 ;; Table lines
5610 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5611 (1 'org-table t))
5612 ;; Table internals
5613 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5614 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5615 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5616 ;; Drawers
5617 (list org-drawer-regexp '(0 'org-special-keyword t))
5618 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5619 ;; Properties
5620 (list org-property-re
5621 '(1 'org-special-keyword t)
5622 '(3 'org-property-value t))
5623 (if org-format-transports-properties-p
5624 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5625 ;; Links
5626 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5627 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5628 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5629 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5630 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5631 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5632 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5633 '(org-hide-wide-columns (0 nil append))
5634 ;; TODO lines
5635 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5636 '(1 (org-get-todo-face 1) t))
5637 ;; DONE
5638 (if org-fontify-done-headline
5639 (list (concat "^[*]+ +\\<\\("
5640 (mapconcat 'regexp-quote org-done-keywords "\\|")
5641 "\\)\\(.*\\)")
5642 '(2 'org-headline-done t))
5643 nil)
5644 ;; Priorities
5645 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5646 ;; Special keywords
5647 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5648 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5649 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5650 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5651 ;; Emphasis
5652 (if em
5653 (if (featurep 'xemacs)
5654 '(org-do-emphasis-faces (0 nil append))
5655 '(org-do-emphasis-faces)))
5656 ;; Checkboxes
5657 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5658 2 'bold prepend)
5659 (if org-provide-checkbox-statistics
5660 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5661 (0 (org-get-checkbox-statistics-face) t)))
5662 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5663 '(1 'org-archived prepend))
5664 ;; Specials
5665 '(org-do-latex-and-special-faces)
5666 ;; Code
5667 '(org-activate-code (1 'org-code t))
5668 ;; COMMENT
5669 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5670 "\\|" org-quote-string "\\)\\>")
5671 '(1 'org-special-keyword t))
5672 '("^#.*" (0 'font-lock-comment-face t))
5674 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5675 ;; Now set the full font-lock-keywords
5676 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5677 (org-set-local 'font-lock-defaults
5678 '(org-font-lock-keywords t nil nil backward-paragraph))
5679 (kill-local-variable 'font-lock-keywords) nil))
5681 (defvar org-m nil)
5682 (defvar org-l nil)
5683 (defvar org-f nil)
5684 (defun org-get-level-face (n)
5685 "Get the right face for match N in font-lock matching of healdines."
5686 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5687 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5688 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5689 (cond
5690 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5691 ((eq n 2) org-f)
5692 (t (if org-level-color-stars-only nil org-f))))
5694 (defun org-get-todo-face (kwd)
5695 "Get the right face for a TODO keyword KWD.
5696 If KWD is a number, get the corresponding match group."
5697 (if (numberp kwd) (setq kwd (match-string kwd)))
5698 (or (cdr (assoc kwd org-todo-keyword-faces))
5699 (and (member kwd org-done-keywords) 'org-done)
5700 'org-todo))
5702 (defun org-unfontify-region (beg end &optional maybe_loudly)
5703 "Remove fontification and activation overlays from links."
5704 (font-lock-default-unfontify-region beg end)
5705 (let* ((buffer-undo-list t)
5706 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5707 (inhibit-modification-hooks t)
5708 deactivate-mark buffer-file-name buffer-file-truename)
5709 (remove-text-properties beg end
5710 '(mouse-face t keymap t org-linked-text t
5711 invisible t intangible t))))
5713 ;;;; Visibility cycling, including org-goto and indirect buffer
5715 ;;; Cycling
5717 (defvar org-cycle-global-status nil)
5718 (make-variable-buffer-local 'org-cycle-global-status)
5719 (defvar org-cycle-subtree-status nil)
5720 (make-variable-buffer-local 'org-cycle-subtree-status)
5722 ;;;###autoload
5723 (defun org-cycle (&optional arg)
5724 "Visibility cycling for Org-mode.
5726 - When this function is called with a prefix argument, rotate the entire
5727 buffer through 3 states (global cycling)
5728 1. OVERVIEW: Show only top-level headlines.
5729 2. CONTENTS: Show all headlines of all levels, but no body text.
5730 3. SHOW ALL: Show everything.
5732 - When point is at the beginning of a headline, rotate the subtree started
5733 by this line through 3 different states (local cycling)
5734 1. FOLDED: Only the main headline is shown.
5735 2. CHILDREN: The main headline and the direct children are shown.
5736 From this state, you can move to one of the children
5737 and zoom in further.
5738 3. SUBTREE: Show the entire subtree, including body text.
5740 - When there is a numeric prefix, go up to a heading with level ARG, do
5741 a `show-subtree' and return to the previous cursor position. If ARG
5742 is negative, go up that many levels.
5744 - When point is not at the beginning of a headline, execute
5745 `indent-relative', like TAB normally does. See the option
5746 `org-cycle-emulate-tab' for details.
5748 - Special case: if point is at the beginning of the buffer and there is
5749 no headline in line 1, this function will act as if called with prefix arg.
5750 But only if also the variable `org-cycle-global-at-bob' is t."
5751 (interactive "P")
5752 (let* ((outline-regexp
5753 (if (and (org-mode-p) org-cycle-include-plain-lists)
5754 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5755 outline-regexp))
5756 (bob-special (and org-cycle-global-at-bob (bobp)
5757 (not (looking-at outline-regexp))))
5758 (org-cycle-hook
5759 (if bob-special
5760 (delq 'org-optimize-window-after-visibility-change
5761 (copy-sequence org-cycle-hook))
5762 org-cycle-hook))
5763 (pos (point)))
5765 (if (or bob-special (equal arg '(4)))
5766 ;; special case: use global cycling
5767 (setq arg t))
5769 (cond
5771 ((org-at-table-p 'any)
5772 ;; Enter the table or move to the next field in the table
5773 (or (org-table-recognize-table.el)
5774 (progn
5775 (if arg (org-table-edit-field t)
5776 (org-table-justify-field-maybe)
5777 (call-interactively 'org-table-next-field)))))
5779 ((eq arg t) ;; Global cycling
5781 (cond
5782 ((and (eq last-command this-command)
5783 (eq org-cycle-global-status 'overview))
5784 ;; We just created the overview - now do table of contents
5785 ;; This can be slow in very large buffers, so indicate action
5786 (message "CONTENTS...")
5787 (org-content)
5788 (message "CONTENTS...done")
5789 (setq org-cycle-global-status 'contents)
5790 (run-hook-with-args 'org-cycle-hook 'contents))
5792 ((and (eq last-command this-command)
5793 (eq org-cycle-global-status 'contents))
5794 ;; We just showed the table of contents - now show everything
5795 (show-all)
5796 (message "SHOW ALL")
5797 (setq org-cycle-global-status 'all)
5798 (run-hook-with-args 'org-cycle-hook 'all))
5801 ;; Default action: go to overview
5802 (org-overview)
5803 (message "OVERVIEW")
5804 (setq org-cycle-global-status 'overview)
5805 (run-hook-with-args 'org-cycle-hook 'overview))))
5807 ((and org-drawers org-drawer-regexp
5808 (save-excursion
5809 (beginning-of-line 1)
5810 (looking-at org-drawer-regexp)))
5811 ;; Toggle block visibility
5812 (org-flag-drawer
5813 (not (get-char-property (match-end 0) 'invisible))))
5815 ((integerp arg)
5816 ;; Show-subtree, ARG levels up from here.
5817 (save-excursion
5818 (org-back-to-heading)
5819 (outline-up-heading (if (< arg 0) (- arg)
5820 (- (funcall outline-level) arg)))
5821 (org-show-subtree)))
5823 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5824 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5825 ;; At a heading: rotate between three different views
5826 (org-back-to-heading)
5827 (let ((goal-column 0) eoh eol eos)
5828 ;; First, some boundaries
5829 (save-excursion
5830 (org-back-to-heading)
5831 (save-excursion
5832 (beginning-of-line 2)
5833 (while (and (not (eobp)) ;; this is like `next-line'
5834 (get-char-property (1- (point)) 'invisible))
5835 (beginning-of-line 2)) (setq eol (point)))
5836 (outline-end-of-heading) (setq eoh (point))
5837 (org-end-of-subtree t)
5838 (unless (eobp)
5839 (skip-chars-forward " \t\n")
5840 (beginning-of-line 1) ; in case this is an item
5842 (setq eos (1- (point))))
5843 ;; Find out what to do next and set `this-command'
5844 (cond
5845 ((= eos eoh)
5846 ;; Nothing is hidden behind this heading
5847 (message "EMPTY ENTRY")
5848 (setq org-cycle-subtree-status nil)
5849 (save-excursion
5850 (goto-char eos)
5851 (outline-next-heading)
5852 (if (org-invisible-p) (org-flag-heading nil))))
5853 ((or (>= eol eos)
5854 (not (string-match "\\S-" (buffer-substring eol eos))))
5855 ;; Entire subtree is hidden in one line: open it
5856 (org-show-entry)
5857 (show-children)
5858 (message "CHILDREN")
5859 (save-excursion
5860 (goto-char eos)
5861 (outline-next-heading)
5862 (if (org-invisible-p) (org-flag-heading nil)))
5863 (setq org-cycle-subtree-status 'children)
5864 (run-hook-with-args 'org-cycle-hook 'children))
5865 ((and (eq last-command this-command)
5866 (eq org-cycle-subtree-status 'children))
5867 ;; We just showed the children, now show everything.
5868 (org-show-subtree)
5869 (message "SUBTREE")
5870 (setq org-cycle-subtree-status 'subtree)
5871 (run-hook-with-args 'org-cycle-hook 'subtree))
5873 ;; Default action: hide the subtree.
5874 (hide-subtree)
5875 (message "FOLDED")
5876 (setq org-cycle-subtree-status 'folded)
5877 (run-hook-with-args 'org-cycle-hook 'folded)))))
5879 ;; TAB emulation
5880 (buffer-read-only (org-back-to-heading))
5882 ((org-try-cdlatex-tab))
5884 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5885 (or (not (bolp))
5886 (not (looking-at outline-regexp))))
5887 (call-interactively (global-key-binding "\t")))
5889 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5890 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5891 (or (and (eq org-cycle-emulate-tab 'white)
5892 (= (match-end 0) (point-at-eol)))
5893 (and (eq org-cycle-emulate-tab 'whitestart)
5894 (>= (match-end 0) pos))))
5896 (eq org-cycle-emulate-tab t))
5897 ; (if (and (looking-at "[ \n\r\t]")
5898 ; (string-match "^[ \t]*$" (buffer-substring
5899 ; (point-at-bol) (point))))
5900 ; (progn
5901 ; (beginning-of-line 1)
5902 ; (and (looking-at "[ \t]+") (replace-match ""))))
5903 (call-interactively (global-key-binding "\t")))
5905 (t (save-excursion
5906 (org-back-to-heading)
5907 (org-cycle))))))
5909 ;;;###autoload
5910 (defun org-global-cycle (&optional arg)
5911 "Cycle the global visibility. For details see `org-cycle'."
5912 (interactive "P")
5913 (let ((org-cycle-include-plain-lists
5914 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5915 (if (integerp arg)
5916 (progn
5917 (show-all)
5918 (hide-sublevels arg)
5919 (setq org-cycle-global-status 'contents))
5920 (org-cycle '(4)))))
5922 (defun org-overview ()
5923 "Switch to overview mode, shoing only top-level headlines.
5924 Really, this shows all headlines with level equal or greater than the level
5925 of the first headline in the buffer. This is important, because if the
5926 first headline is not level one, then (hide-sublevels 1) gives confusing
5927 results."
5928 (interactive)
5929 (let ((level (save-excursion
5930 (goto-char (point-min))
5931 (if (re-search-forward (concat "^" outline-regexp) nil t)
5932 (progn
5933 (goto-char (match-beginning 0))
5934 (funcall outline-level))))))
5935 (and level (hide-sublevels level))))
5937 (defun org-content (&optional arg)
5938 "Show all headlines in the buffer, like a table of contents.
5939 With numerical argument N, show content up to level N."
5940 (interactive "P")
5941 (save-excursion
5942 ;; Visit all headings and show their offspring
5943 (and (integerp arg) (org-overview))
5944 (goto-char (point-max))
5945 (catch 'exit
5946 (while (and (progn (condition-case nil
5947 (outline-previous-visible-heading 1)
5948 (error (goto-char (point-min))))
5950 (looking-at outline-regexp))
5951 (if (integerp arg)
5952 (show-children (1- arg))
5953 (show-branches))
5954 (if (bobp) (throw 'exit nil))))))
5957 (defun org-optimize-window-after-visibility-change (state)
5958 "Adjust the window after a change in outline visibility.
5959 This function is the default value of the hook `org-cycle-hook'."
5960 (when (get-buffer-window (current-buffer))
5961 (cond
5962 ; ((eq state 'overview) (org-first-headline-recenter 1))
5963 ; ((eq state 'overview) (org-beginning-of-line))
5964 ((eq state 'content) nil)
5965 ((eq state 'all) nil)
5966 ((eq state 'folded) nil)
5967 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5968 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5970 (defun org-compact-display-after-subtree-move ()
5971 (let (beg end)
5972 (save-excursion
5973 (if (org-up-heading-safe)
5974 (progn
5975 (hide-subtree)
5976 (show-entry)
5977 (show-children)
5978 (org-cycle-show-empty-lines 'children)
5979 (org-cycle-hide-drawers 'children))
5980 (org-overview)))))
5982 (defun org-cycle-show-empty-lines (state)
5983 "Show empty lines above all visible headlines.
5984 The region to be covered depends on STATE when called through
5985 `org-cycle-hook'. Lisp program can use t for STATE to get the
5986 entire buffer covered. Note that an empty line is only shown if there
5987 are at least `org-cycle-separator-lines' empty lines before the headeline."
5988 (when (> org-cycle-separator-lines 0)
5989 (save-excursion
5990 (let* ((n org-cycle-separator-lines)
5991 (re (cond
5992 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5993 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5994 (t (let ((ns (number-to-string (- n 2))))
5995 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5996 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5997 beg end)
5998 (cond
5999 ((memq state '(overview contents t))
6000 (setq beg (point-min) end (point-max)))
6001 ((memq state '(children folded))
6002 (setq beg (point) end (progn (org-end-of-subtree t t)
6003 (beginning-of-line 2)
6004 (point)))))
6005 (when beg
6006 (goto-char beg)
6007 (while (re-search-forward re end t)
6008 (if (not (get-char-property (match-end 1) 'invisible))
6009 (outline-flag-region
6010 (match-beginning 1) (match-end 1) nil)))))))
6011 ;; Never hide empty lines at the end of the file.
6012 (save-excursion
6013 (goto-char (point-max))
6014 (outline-previous-heading)
6015 (outline-end-of-heading)
6016 (if (and (looking-at "[ \t\n]+")
6017 (= (match-end 0) (point-max)))
6018 (outline-flag-region (point) (match-end 0) nil))))
6020 (defun org-subtree-end-visible-p ()
6021 "Is the end of the current subtree visible?"
6022 (pos-visible-in-window-p
6023 (save-excursion (org-end-of-subtree t) (point))))
6025 (defun org-first-headline-recenter (&optional N)
6026 "Move cursor to the first headline and recenter the headline.
6027 Optional argument N means, put the headline into the Nth line of the window."
6028 (goto-char (point-min))
6029 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6030 (beginning-of-line)
6031 (recenter (prefix-numeric-value N))))
6033 ;;; Org-goto
6035 (defvar org-goto-window-configuration nil)
6036 (defvar org-goto-marker nil)
6037 (defvar org-goto-map
6038 (let ((map (make-sparse-keymap)))
6039 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6040 (while (setq cmd (pop cmds))
6041 (substitute-key-definition cmd cmd map global-map)))
6042 (suppress-keymap map)
6043 (org-defkey map "\C-m" 'org-goto-ret)
6044 (org-defkey map [(return)] 'org-goto-ret)
6045 (org-defkey map [(left)] 'org-goto-left)
6046 (org-defkey map [(right)] 'org-goto-right)
6047 (org-defkey map [(control ?g)] 'org-goto-quit)
6048 (org-defkey map "\C-i" 'org-cycle)
6049 (org-defkey map [(tab)] 'org-cycle)
6050 (org-defkey map [(down)] 'outline-next-visible-heading)
6051 (org-defkey map [(up)] 'outline-previous-visible-heading)
6052 (if org-goto-auto-isearch
6053 (if (fboundp 'define-key-after)
6054 (define-key-after map [t] 'org-goto-local-auto-isearch)
6055 nil)
6056 (org-defkey map "q" 'org-goto-quit)
6057 (org-defkey map "n" 'outline-next-visible-heading)
6058 (org-defkey map "p" 'outline-previous-visible-heading)
6059 (org-defkey map "f" 'outline-forward-same-level)
6060 (org-defkey map "b" 'outline-backward-same-level)
6061 (org-defkey map "u" 'outline-up-heading))
6062 (org-defkey map "/" 'org-occur)
6063 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6064 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6065 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6066 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6067 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6068 map))
6070 (defconst org-goto-help
6071 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6072 RET=jump to location [Q]uit and return to previous location
6073 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6075 (defvar org-goto-start-pos) ; dynamically scoped parameter
6077 (defun org-goto (&optional alternative-interface)
6078 "Look up a different location in the current file, keeping current visibility.
6080 When you want look-up or go to a different location in a document, the
6081 fastest way is often to fold the entire buffer and then dive into the tree.
6082 This method has the disadvantage, that the previous location will be folded,
6083 which may not be what you want.
6085 This command works around this by showing a copy of the current buffer
6086 in an indirect buffer, in overview mode. You can dive into the tree in
6087 that copy, use org-occur and incremental search to find a location.
6088 When pressing RET or `Q', the command returns to the original buffer in
6089 which the visibility is still unchanged. After RET is will also jump to
6090 the location selected in the indirect buffer and expose the
6091 the headline hierarchy above."
6092 (interactive "P")
6093 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6094 (org-refile-use-outline-path t)
6095 (interface
6096 (if (not alternative-interface)
6097 org-goto-interface
6098 (if (eq org-goto-interface 'outline)
6099 'outline-path-completion
6100 'outline)))
6101 (org-goto-start-pos (point))
6102 (selected-point
6103 (if (eq interface 'outline)
6104 (car (org-get-location (current-buffer) org-goto-help))
6105 (nth 3 (org-refile-get-location "Goto: ")))))
6106 (if selected-point
6107 (progn
6108 (org-mark-ring-push org-goto-start-pos)
6109 (goto-char selected-point)
6110 (if (or (org-invisible-p) (org-invisible-p2))
6111 (org-show-context 'org-goto)))
6112 (message "Quit"))))
6114 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6115 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6116 (defvar org-goto-local-auto-isearch-map) ; defined below
6118 (defun org-get-location (buf help)
6119 "Let the user select a location in the Org-mode buffer BUF.
6120 This function uses a recursive edit. It returns the selected position
6121 or nil."
6122 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6123 (isearch-hide-immediately nil)
6124 (isearch-search-fun-function
6125 (lambda () 'org-goto-local-search-forward-headings))
6126 (org-goto-selected-point org-goto-exit-command))
6127 (save-excursion
6128 (save-window-excursion
6129 (delete-other-windows)
6130 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6131 (switch-to-buffer
6132 (condition-case nil
6133 (make-indirect-buffer (current-buffer) "*org-goto*")
6134 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6135 (with-output-to-temp-buffer "*Help*"
6136 (princ help))
6137 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6138 (setq buffer-read-only nil)
6139 (let ((org-startup-truncated t)
6140 (org-startup-folded nil)
6141 (org-startup-align-all-tables nil))
6142 (org-mode)
6143 (org-overview))
6144 (setq buffer-read-only t)
6145 (if (and (boundp 'org-goto-start-pos)
6146 (integer-or-marker-p org-goto-start-pos))
6147 (let ((org-show-hierarchy-above t)
6148 (org-show-siblings t)
6149 (org-show-following-heading t))
6150 (goto-char org-goto-start-pos)
6151 (and (org-invisible-p) (org-show-context)))
6152 (goto-char (point-min)))
6153 (org-beginning-of-line)
6154 (message "Select location and press RET")
6155 (use-local-map org-goto-map)
6156 (recursive-edit)
6158 (kill-buffer "*org-goto*")
6159 (cons org-goto-selected-point org-goto-exit-command)))
6161 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6162 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6163 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6164 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6166 (defun org-goto-local-search-forward-headings (string bound noerror)
6167 "Search and make sure that anu matches are in headlines."
6168 (catch 'return
6169 (while (search-forward string bound noerror)
6170 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6171 (and (member :headline context)
6172 (not (member :tags context))))
6173 (throw 'return (point))))))
6175 (defun org-goto-local-auto-isearch ()
6176 "Start isearch."
6177 (interactive)
6178 (goto-char (point-min))
6179 (let ((keys (this-command-keys)))
6180 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6181 (isearch-mode t)
6182 (isearch-process-search-char (string-to-char keys)))))
6184 (defun org-goto-ret (&optional arg)
6185 "Finish `org-goto' by going to the new location."
6186 (interactive "P")
6187 (setq org-goto-selected-point (point)
6188 org-goto-exit-command 'return)
6189 (throw 'exit nil))
6191 (defun org-goto-left ()
6192 "Finish `org-goto' by going to the new location."
6193 (interactive)
6194 (if (org-on-heading-p)
6195 (progn
6196 (beginning-of-line 1)
6197 (setq org-goto-selected-point (point)
6198 org-goto-exit-command 'left)
6199 (throw 'exit nil))
6200 (error "Not on a heading")))
6202 (defun org-goto-right ()
6203 "Finish `org-goto' by going to the new location."
6204 (interactive)
6205 (if (org-on-heading-p)
6206 (progn
6207 (setq org-goto-selected-point (point)
6208 org-goto-exit-command 'right)
6209 (throw 'exit nil))
6210 (error "Not on a heading")))
6212 (defun org-goto-quit ()
6213 "Finish `org-goto' without cursor motion."
6214 (interactive)
6215 (setq org-goto-selected-point nil)
6216 (setq org-goto-exit-command 'quit)
6217 (throw 'exit nil))
6219 ;;; Indirect buffer display of subtrees
6221 (defvar org-indirect-dedicated-frame nil
6222 "This is the frame being used for indirect tree display.")
6223 (defvar org-last-indirect-buffer nil)
6225 (defun org-tree-to-indirect-buffer (&optional arg)
6226 "Create indirect buffer and narrow it to current subtree.
6227 With numerical prefix ARG, go up to this level and then take that tree.
6228 If ARG is negative, go up that many levels.
6229 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6230 indirect buffer previously made with this command, to avoid proliferation of
6231 indirect buffers. However, when you call the command with a `C-u' prefix, or
6232 when `org-indirect-buffer-display' is `new-frame', the last buffer
6233 is kept so that you can work with several indirect buffers at the same time.
6234 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6235 requests that a new frame be made for the new buffer, so that the dedicated
6236 frame is not changed."
6237 (interactive "P")
6238 (let ((cbuf (current-buffer))
6239 (cwin (selected-window))
6240 (pos (point))
6241 beg end level heading ibuf)
6242 (save-excursion
6243 (org-back-to-heading t)
6244 (when (numberp arg)
6245 (setq level (org-outline-level))
6246 (if (< arg 0) (setq arg (+ level arg)))
6247 (while (> (setq level (org-outline-level)) arg)
6248 (outline-up-heading 1 t)))
6249 (setq beg (point)
6250 heading (org-get-heading))
6251 (org-end-of-subtree t) (setq end (point)))
6252 (if (and (buffer-live-p org-last-indirect-buffer)
6253 (not (eq org-indirect-buffer-display 'new-frame))
6254 (not arg))
6255 (kill-buffer org-last-indirect-buffer))
6256 (setq ibuf (org-get-indirect-buffer cbuf)
6257 org-last-indirect-buffer ibuf)
6258 (cond
6259 ((or (eq org-indirect-buffer-display 'new-frame)
6260 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6261 (select-frame (make-frame))
6262 (delete-other-windows)
6263 (switch-to-buffer ibuf)
6264 (org-set-frame-title heading))
6265 ((eq org-indirect-buffer-display 'dedicated-frame)
6266 (raise-frame
6267 (select-frame (or (and org-indirect-dedicated-frame
6268 (frame-live-p org-indirect-dedicated-frame)
6269 org-indirect-dedicated-frame)
6270 (setq org-indirect-dedicated-frame (make-frame)))))
6271 (delete-other-windows)
6272 (switch-to-buffer ibuf)
6273 (org-set-frame-title (concat "Indirect: " heading)))
6274 ((eq org-indirect-buffer-display 'current-window)
6275 (switch-to-buffer ibuf))
6276 ((eq org-indirect-buffer-display 'other-window)
6277 (pop-to-buffer ibuf))
6278 (t (error "Invalid value.")))
6279 (if (featurep 'xemacs)
6280 (save-excursion (org-mode) (turn-on-font-lock)))
6281 (narrow-to-region beg end)
6282 (show-all)
6283 (goto-char pos)
6284 (and (window-live-p cwin) (select-window cwin))))
6286 (defun org-get-indirect-buffer (&optional buffer)
6287 (setq buffer (or buffer (current-buffer)))
6288 (let ((n 1) (base (buffer-name buffer)) bname)
6289 (while (buffer-live-p
6290 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6291 (setq n (1+ n)))
6292 (condition-case nil
6293 (make-indirect-buffer buffer bname 'clone)
6294 (error (make-indirect-buffer buffer bname)))))
6296 (defun org-set-frame-title (title)
6297 "Set the title of the current frame to the string TITLE."
6298 ;; FIXME: how to name a single frame in XEmacs???
6299 (unless (featurep 'xemacs)
6300 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6302 ;;;; Structure editing
6304 ;;; Inserting headlines
6306 (defun org-insert-heading (&optional force-heading)
6307 "Insert a new heading or item with same depth at point.
6308 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6309 If point is at the beginning of a headline, insert a sibling before the
6310 current headline. If point is not at the beginning, do not split the line,
6311 but create the new hedline after the current line."
6312 (interactive "P")
6313 (if (= (buffer-size) 0)
6314 (insert "\n* ")
6315 (when (or force-heading (not (org-insert-item)))
6316 (let* ((head (save-excursion
6317 (condition-case nil
6318 (progn
6319 (org-back-to-heading)
6320 (match-string 0))
6321 (error "*"))))
6322 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6323 pos)
6324 (cond
6325 ((and (org-on-heading-p) (bolp)
6326 (or (bobp)
6327 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6328 ;; insert before the current line
6329 (open-line (if blank 2 1)))
6330 ((and (bolp)
6331 (or (bobp)
6332 (save-excursion
6333 (backward-char 1) (not (org-invisible-p)))))
6334 ;; insert right here
6335 nil)
6337 ; ;; in the middle of the line
6338 ; (org-show-entry)
6339 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6340 ; (if (and
6341 ; (org-on-heading-p)
6342 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6343 ; ;; protect the tags
6344 ;; (let ((tags (match-string 2)) pos)
6345 ; (delete-region (match-beginning 1) (match-end 1))
6346 ; (setq pos (point-at-bol))
6347 ; (newline (if blank 2 1))
6348 ; (save-excursion
6349 ; (goto-char pos)
6350 ; (end-of-line 1)
6351 ; (insert " " tags)
6352 ; (org-set-tags nil 'align)))
6353 ; (newline (if blank 2 1)))
6354 ; (newline (if blank 2 1))))
6357 ;; in the middle of the line
6358 (org-show-entry)
6359 (let ((split
6360 (org-get-alist-option org-M-RET-may-split-line 'headline))
6361 tags pos)
6362 (if (org-on-heading-p)
6363 (progn
6364 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6365 (setq tags (and (match-end 2) (match-string 2)))
6366 (and (match-end 1)
6367 (delete-region (match-beginning 1) (match-end 1)))
6368 (setq pos (point-at-bol))
6369 (or split (end-of-line 1))
6370 (delete-horizontal-space)
6371 (newline (if blank 2 1))
6372 (when tags
6373 (save-excursion
6374 (goto-char pos)
6375 (end-of-line 1)
6376 (insert " " tags)
6377 (org-set-tags nil 'align))))
6378 (or split (end-of-line 1))
6379 (newline (if blank 2 1))))))
6380 (insert head) (just-one-space)
6381 (setq pos (point))
6382 (end-of-line 1)
6383 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6384 (run-hooks 'org-insert-heading-hook)))))
6386 (defun org-insert-heading-after-current ()
6387 "Insert a new heading with same level as current, after current subtree."
6388 (interactive)
6389 (org-back-to-heading)
6390 (org-insert-heading)
6391 (org-move-subtree-down)
6392 (end-of-line 1))
6394 (defun org-insert-todo-heading (arg)
6395 "Insert a new heading with the same level and TODO state as current heading.
6396 If the heading has no TODO state, or if the state is DONE, use the first
6397 state (TODO by default). Also with prefix arg, force first state."
6398 (interactive "P")
6399 (when (not (org-insert-item 'checkbox))
6400 (org-insert-heading)
6401 (save-excursion
6402 (org-back-to-heading)
6403 (outline-previous-heading)
6404 (looking-at org-todo-line-regexp))
6405 (if (or arg
6406 (not (match-beginning 2))
6407 (member (match-string 2) org-done-keywords))
6408 (insert (car org-todo-keywords-1) " ")
6409 (insert (match-string 2) " "))))
6411 (defun org-insert-subheading (arg)
6412 "Insert a new subheading and demote it.
6413 Works for outline headings and for plain lists alike."
6414 (interactive "P")
6415 (org-insert-heading arg)
6416 (cond
6417 ((org-on-heading-p) (org-do-demote))
6418 ((org-at-item-p) (org-indent-item 1))))
6420 (defun org-insert-todo-subheading (arg)
6421 "Insert a new subheading with TODO keyword or checkbox and demote it.
6422 Works for outline headings and for plain lists alike."
6423 (interactive "P")
6424 (org-insert-todo-heading arg)
6425 (cond
6426 ((org-on-heading-p) (org-do-demote))
6427 ((org-at-item-p) (org-indent-item 1))))
6429 ;;; Promotion and Demotion
6431 (defun org-promote-subtree ()
6432 "Promote the entire subtree.
6433 See also `org-promote'."
6434 (interactive)
6435 (save-excursion
6436 (org-map-tree 'org-promote))
6437 (org-fix-position-after-promote))
6439 (defun org-demote-subtree ()
6440 "Demote the entire subtree. See `org-demote'.
6441 See also `org-promote'."
6442 (interactive)
6443 (save-excursion
6444 (org-map-tree 'org-demote))
6445 (org-fix-position-after-promote))
6448 (defun org-do-promote ()
6449 "Promote the current heading higher up the tree.
6450 If the region is active in `transient-mark-mode', promote all headings
6451 in the region."
6452 (interactive)
6453 (save-excursion
6454 (if (org-region-active-p)
6455 (org-map-region 'org-promote (region-beginning) (region-end))
6456 (org-promote)))
6457 (org-fix-position-after-promote))
6459 (defun org-do-demote ()
6460 "Demote the current heading lower down the tree.
6461 If the region is active in `transient-mark-mode', demote all headings
6462 in the region."
6463 (interactive)
6464 (save-excursion
6465 (if (org-region-active-p)
6466 (org-map-region 'org-demote (region-beginning) (region-end))
6467 (org-demote)))
6468 (org-fix-position-after-promote))
6470 (defun org-fix-position-after-promote ()
6471 "Make sure that after pro/demotion cursor position is right."
6472 (let ((pos (point)))
6473 (when (save-excursion
6474 (beginning-of-line 1)
6475 (looking-at org-todo-line-regexp)
6476 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6477 (cond ((eobp) (insert " "))
6478 ((eolp) (insert " "))
6479 ((equal (char-after) ?\ ) (forward-char 1))))))
6481 (defun org-reduced-level (l)
6482 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6484 (defun org-get-legal-level (level &optional change)
6485 "Rectify a level change under the influence of `org-odd-levels-only'
6486 LEVEL is a current level, CHANGE is by how much the level should be
6487 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6488 even level numbers will become the next higher odd number."
6489 (if org-odd-levels-only
6490 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6491 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6492 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6493 (max 1 (+ level change))))
6495 (defun org-promote ()
6496 "Promote the current heading higher up the tree.
6497 If the region is active in `transient-mark-mode', promote all headings
6498 in the region."
6499 (org-back-to-heading t)
6500 (let* ((level (save-match-data (funcall outline-level)))
6501 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6502 (diff (abs (- level (length up-head) -1))))
6503 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6504 (replace-match up-head nil t)
6505 ;; Fixup tag positioning
6506 (and org-auto-align-tags (org-set-tags nil t))
6507 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6509 (defun org-demote ()
6510 "Demote the current heading lower down the tree.
6511 If the region is active in `transient-mark-mode', demote all headings
6512 in the region."
6513 (org-back-to-heading t)
6514 (let* ((level (save-match-data (funcall outline-level)))
6515 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6516 (diff (abs (- level (length down-head) -1))))
6517 (replace-match down-head nil t)
6518 ;; Fixup tag positioning
6519 (and org-auto-align-tags (org-set-tags nil t))
6520 (if org-adapt-indentation (org-fixup-indentation diff))))
6522 (defun org-map-tree (fun)
6523 "Call FUN for every heading underneath the current one."
6524 (org-back-to-heading)
6525 (let ((level (funcall outline-level)))
6526 (save-excursion
6527 (funcall fun)
6528 (while (and (progn
6529 (outline-next-heading)
6530 (> (funcall outline-level) level))
6531 (not (eobp)))
6532 (funcall fun)))))
6534 (defun org-map-region (fun beg end)
6535 "Call FUN for every heading between BEG and END."
6536 (let ((org-ignore-region t))
6537 (save-excursion
6538 (setq end (copy-marker end))
6539 (goto-char beg)
6540 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6541 (< (point) end))
6542 (funcall fun))
6543 (while (and (progn
6544 (outline-next-heading)
6545 (< (point) end))
6546 (not (eobp)))
6547 (funcall fun)))))
6549 (defun org-fixup-indentation (diff)
6550 "Change the indentation in the current entry by DIFF
6551 However, if any line in the current entry has no indentation, or if it
6552 would end up with no indentation after the change, nothing at all is done."
6553 (save-excursion
6554 (let ((end (save-excursion (outline-next-heading)
6555 (point-marker)))
6556 (prohibit (if (> diff 0)
6557 "^\\S-"
6558 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6559 col)
6560 (unless (save-excursion (end-of-line 1)
6561 (re-search-forward prohibit end t))
6562 (while (and (< (point) end)
6563 (re-search-forward "^[ \t]+" end t))
6564 (goto-char (match-end 0))
6565 (setq col (current-column))
6566 (if (< diff 0) (replace-match ""))
6567 (indent-to (+ diff col))))
6568 (move-marker end nil))))
6570 (defun org-convert-to-odd-levels ()
6571 "Convert an org-mode file with all levels allowed to one with odd levels.
6572 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6573 level 5 etc."
6574 (interactive)
6575 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6576 (let ((org-odd-levels-only nil) n)
6577 (save-excursion
6578 (goto-char (point-min))
6579 (while (re-search-forward "^\\*\\*+ " nil t)
6580 (setq n (- (length (match-string 0)) 2))
6581 (while (>= (setq n (1- n)) 0)
6582 (org-demote))
6583 (end-of-line 1))))))
6586 (defun org-convert-to-oddeven-levels ()
6587 "Convert an org-mode file with only odd levels to one with odd and even levels.
6588 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6589 section with an even level, conversion would destroy the structure of the file. An error
6590 is signaled in this case."
6591 (interactive)
6592 (goto-char (point-min))
6593 ;; First check if there are no even levels
6594 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6595 (org-show-context t)
6596 (error "Not all levels are odd in this file. Conversion not possible."))
6597 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6598 (let ((org-odd-levels-only nil) n)
6599 (save-excursion
6600 (goto-char (point-min))
6601 (while (re-search-forward "^\\*\\*+ " nil t)
6602 (setq n (/ (1- (length (match-string 0))) 2))
6603 (while (>= (setq n (1- n)) 0)
6604 (org-promote))
6605 (end-of-line 1))))))
6607 (defun org-tr-level (n)
6608 "Make N odd if required."
6609 (if org-odd-levels-only (1+ (/ n 2)) n))
6611 ;;; Vertical tree motion, cutting and pasting of subtrees
6613 (defun org-move-subtree-up (&optional arg)
6614 "Move the current subtree up past ARG headlines of the same level."
6615 (interactive "p")
6616 (org-move-subtree-down (- (prefix-numeric-value arg))))
6618 (defun org-move-subtree-down (&optional arg)
6619 "Move the current subtree down past ARG headlines of the same level."
6620 (interactive "p")
6621 (setq arg (prefix-numeric-value arg))
6622 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6623 'outline-get-last-sibling))
6624 (ins-point (make-marker))
6625 (cnt (abs arg))
6626 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6627 ;; Select the tree
6628 (org-back-to-heading)
6629 (setq beg0 (point))
6630 (save-excursion
6631 (setq ne-beg (org-back-over-empty-lines))
6632 (setq beg (point)))
6633 (save-match-data
6634 (save-excursion (outline-end-of-heading)
6635 (setq folded (org-invisible-p)))
6636 (outline-end-of-subtree))
6637 (outline-next-heading)
6638 (setq ne-end (org-back-over-empty-lines))
6639 (setq end (point))
6640 (goto-char beg0)
6641 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6642 ;; include less whitespace
6643 (save-excursion
6644 (goto-char beg)
6645 (forward-line (- ne-beg ne-end))
6646 (setq beg (point))))
6647 ;; Find insertion point, with error handling
6648 (while (> cnt 0)
6649 (or (and (funcall movfunc) (looking-at outline-regexp))
6650 (progn (goto-char beg0)
6651 (error "Cannot move past superior level or buffer limit")))
6652 (setq cnt (1- cnt)))
6653 (if (> arg 0)
6654 ;; Moving forward - still need to move over subtree
6655 (progn (org-end-of-subtree t t)
6656 (save-excursion
6657 (org-back-over-empty-lines)
6658 (or (bolp) (newline)))))
6659 (setq ne-ins (org-back-over-empty-lines))
6660 (move-marker ins-point (point))
6661 (setq txt (buffer-substring beg end))
6662 (delete-region beg end)
6663 (outline-flag-region (1- beg) beg nil)
6664 (outline-flag-region (1- (point)) (point) nil)
6665 (insert txt)
6666 (or (bolp) (insert "\n"))
6667 (setq ins-end (point))
6668 (goto-char ins-point)
6669 (org-skip-whitespace)
6670 (when (and (< arg 0)
6671 (org-first-sibling-p)
6672 (> ne-ins ne-beg))
6673 ;; Move whitespace back to beginning
6674 (save-excursion
6675 (goto-char ins-end)
6676 (let ((kill-whole-line t))
6677 (kill-line (- ne-ins ne-beg)) (point)))
6678 (insert (make-string (- ne-ins ne-beg) ?\n)))
6679 (move-marker ins-point nil)
6680 (org-compact-display-after-subtree-move)
6681 (unless folded
6682 (org-show-entry)
6683 (show-children)
6684 (org-cycle-hide-drawers 'children))))
6686 (defvar org-subtree-clip ""
6687 "Clipboard for cut and paste of subtrees.
6688 This is actually only a copy of the kill, because we use the normal kill
6689 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6691 (defvar org-subtree-clip-folded nil
6692 "Was the last copied subtree folded?
6693 This is used to fold the tree back after pasting.")
6695 (defun org-cut-subtree (&optional n)
6696 "Cut the current subtree into the clipboard.
6697 With prefix arg N, cut this many sequential subtrees.
6698 This is a short-hand for marking the subtree and then cutting it."
6699 (interactive "p")
6700 (org-copy-subtree n 'cut))
6702 (defun org-copy-subtree (&optional n cut)
6703 "Cut the current subtree into the clipboard.
6704 With prefix arg N, cut this many sequential subtrees.
6705 This is a short-hand for marking the subtree and then copying it.
6706 If CUT is non-nil, actually cut the subtree."
6707 (interactive "p")
6708 (let (beg end folded (beg0 (point)))
6709 (if (interactive-p)
6710 (org-back-to-heading nil) ; take what looks like a subtree
6711 (org-back-to-heading t)) ; take what is really there
6712 (org-back-over-empty-lines)
6713 (setq beg (point))
6714 (skip-chars-forward " \t\r\n")
6715 (save-match-data
6716 (save-excursion (outline-end-of-heading)
6717 (setq folded (org-invisible-p)))
6718 (condition-case nil
6719 (outline-forward-same-level (1- n))
6720 (error nil))
6721 (org-end-of-subtree t t))
6722 (org-back-over-empty-lines)
6723 (setq end (point))
6724 (goto-char beg0)
6725 (when (> end beg)
6726 (setq org-subtree-clip-folded folded)
6727 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6728 (setq org-subtree-clip (current-kill 0))
6729 (message "%s: Subtree(s) with %d characters"
6730 (if cut "Cut" "Copied")
6731 (length org-subtree-clip)))))
6733 (defun org-paste-subtree (&optional level tree)
6734 "Paste the clipboard as a subtree, with modification of headline level.
6735 The entire subtree is promoted or demoted in order to match a new headline
6736 level. By default, the new level is derived from the visible headings
6737 before and after the insertion point, and taken to be the inferior headline
6738 level of the two. So if the previous visible heading is level 3 and the
6739 next is level 4 (or vice versa), level 4 will be used for insertion.
6740 This makes sure that the subtree remains an independent subtree and does
6741 not swallow low level entries.
6743 You can also force a different level, either by using a numeric prefix
6744 argument, or by inserting the heading marker by hand. For example, if the
6745 cursor is after \"*****\", then the tree will be shifted to level 5.
6747 If you want to insert the tree as is, just use \\[yank].
6749 If optional TREE is given, use this text instead of the kill ring."
6750 (interactive "P")
6751 (unless (org-kill-is-subtree-p tree)
6752 (error "%s"
6753 (substitute-command-keys
6754 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6755 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6756 (^re (concat "^\\(" outline-regexp "\\)"))
6757 (re (concat "\\(" outline-regexp "\\)"))
6758 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6760 (old-level (if (string-match ^re txt)
6761 (- (match-end 0) (match-beginning 0) 1)
6762 -1))
6763 (force-level (cond (level (prefix-numeric-value level))
6764 ((string-match
6765 ^re_ (buffer-substring (point-at-bol) (point)))
6766 (- (match-end 1) (match-beginning 1)))
6767 (t nil)))
6768 (previous-level (save-excursion
6769 (condition-case nil
6770 (progn
6771 (outline-previous-visible-heading 1)
6772 (if (looking-at re)
6773 (- (match-end 0) (match-beginning 0) 1)
6775 (error 1))))
6776 (next-level (save-excursion
6777 (condition-case nil
6778 (progn
6779 (or (looking-at outline-regexp)
6780 (outline-next-visible-heading 1))
6781 (if (looking-at re)
6782 (- (match-end 0) (match-beginning 0) 1)
6784 (error 1))))
6785 (new-level (or force-level (max previous-level next-level)))
6786 (shift (if (or (= old-level -1)
6787 (= new-level -1)
6788 (= old-level new-level))
6790 (- new-level old-level)))
6791 (delta (if (> shift 0) -1 1))
6792 (func (if (> shift 0) 'org-demote 'org-promote))
6793 (org-odd-levels-only nil)
6794 beg end)
6795 ;; Remove the forced level indicator
6796 (if force-level
6797 (delete-region (point-at-bol) (point)))
6798 ;; Paste
6799 (beginning-of-line 1)
6800 (org-back-over-empty-lines) ;; FIXME: correct fix????
6801 (setq beg (point))
6802 (insert-before-markers txt) ;; FIXME: correct fix????
6803 (unless (string-match "\n\\'" txt) (insert "\n"))
6804 (setq end (point))
6805 (goto-char beg)
6806 (skip-chars-forward " \t\n\r")
6807 (setq beg (point))
6808 ;; Shift if necessary
6809 (unless (= shift 0)
6810 (save-restriction
6811 (narrow-to-region beg end)
6812 (while (not (= shift 0))
6813 (org-map-region func (point-min) (point-max))
6814 (setq shift (+ delta shift)))
6815 (goto-char (point-min))))
6816 (when (interactive-p)
6817 (message "Clipboard pasted as level %d subtree" new-level))
6818 (if (and kill-ring
6819 (eq org-subtree-clip (current-kill 0))
6820 org-subtree-clip-folded)
6821 ;; The tree was folded before it was killed/copied
6822 (hide-subtree))))
6824 (defun org-kill-is-subtree-p (&optional txt)
6825 "Check if the current kill is an outline subtree, or a set of trees.
6826 Returns nil if kill does not start with a headline, or if the first
6827 headline level is not the largest headline level in the tree.
6828 So this will actually accept several entries of equal levels as well,
6829 which is OK for `org-paste-subtree'.
6830 If optional TXT is given, check this string instead of the current kill."
6831 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6832 (start-level (and kill
6833 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6834 org-outline-regexp "\\)")
6835 kill)
6836 (- (match-end 2) (match-beginning 2) 1)))
6837 (re (concat "^" org-outline-regexp))
6838 (start (1+ (match-beginning 2))))
6839 (if (not start-level)
6840 (progn
6841 nil) ;; does not even start with a heading
6842 (catch 'exit
6843 (while (setq start (string-match re kill (1+ start)))
6844 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6845 (throw 'exit nil)))
6846 t))))
6848 (defun org-narrow-to-subtree ()
6849 "Narrow buffer to the current subtree."
6850 (interactive)
6851 (save-excursion
6852 (save-match-data
6853 (narrow-to-region
6854 (progn (org-back-to-heading) (point))
6855 (progn (org-end-of-subtree t t) (point))))))
6858 ;;; Outline Sorting
6860 (defun org-sort (with-case)
6861 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6862 Optional argument WITH-CASE means sort case-sensitively."
6863 (interactive "P")
6864 (if (org-at-table-p)
6865 (org-call-with-arg 'org-table-sort-lines with-case)
6866 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6868 (defvar org-priority-regexp) ; defined later in the file
6870 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6871 "Sort entries on a certain level of an outline tree.
6872 If there is an active region, the entries in the region are sorted.
6873 Else, if the cursor is before the first entry, sort the top-level items.
6874 Else, the children of the entry at point are sorted.
6876 Sorting can be alphabetically, numerically, and by date/time as given by
6877 the first time stamp in the entry. The command prompts for the sorting
6878 type unless it has been given to the function through the SORTING-TYPE
6879 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6880 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6881 called with point at the beginning of the record. It must return either
6882 a string or a number that should serve as the sorting key for that record.
6884 Comparing entries ignores case by default. However, with an optional argument
6885 WITH-CASE, the sorting considers case as well."
6886 (interactive "P")
6887 (let ((case-func (if with-case 'identity 'downcase))
6888 start beg end stars re re2
6889 txt what tmp plain-list-p)
6890 ;; Find beginning and end of region to sort
6891 (cond
6892 ((org-region-active-p)
6893 ;; we will sort the region
6894 (setq end (region-end)
6895 what "region")
6896 (goto-char (region-beginning))
6897 (if (not (org-on-heading-p)) (outline-next-heading))
6898 (setq start (point)))
6899 ((org-at-item-p)
6900 ;; we will sort this plain list
6901 (org-beginning-of-item-list) (setq start (point))
6902 (org-end-of-item-list) (setq end (point))
6903 (goto-char start)
6904 (setq plain-list-p t
6905 what "plain list"))
6906 ((or (org-on-heading-p)
6907 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6908 ;; we will sort the children of the current headline
6909 (org-back-to-heading)
6910 (setq start (point)
6911 end (progn (org-end-of-subtree t t)
6912 (org-back-over-empty-lines)
6913 (point))
6914 what "children")
6915 (goto-char start)
6916 (show-subtree)
6917 (outline-next-heading))
6919 ;; we will sort the top-level entries in this file
6920 (goto-char (point-min))
6921 (or (org-on-heading-p) (outline-next-heading))
6922 (setq start (point) end (point-max) what "top-level")
6923 (goto-char start)
6924 (show-all)))
6926 (setq beg (point))
6927 (if (>= beg end) (error "Nothing to sort"))
6929 (unless plain-list-p
6930 (looking-at "\\(\\*+\\)")
6931 (setq stars (match-string 1)
6932 re (concat "^" (regexp-quote stars) " +")
6933 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6934 txt (buffer-substring beg end))
6935 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6936 (if (and (not (equal stars "*")) (string-match re2 txt))
6937 (error "Region to sort contains a level above the first entry")))
6939 (unless sorting-type
6940 (message
6941 (if plain-list-p
6942 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6943 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6944 what)
6945 (setq sorting-type (read-char-exclusive))
6947 (and (= (downcase sorting-type) ?f)
6948 (setq getkey-func
6949 (completing-read "Sort using function: "
6950 obarray 'fboundp t nil nil))
6951 (setq getkey-func (intern getkey-func)))
6953 (and (= (downcase sorting-type) ?r)
6954 (setq property
6955 (completing-read "Property: "
6956 (mapcar 'list (org-buffer-property-keys t))
6957 nil t))))
6959 (message "Sorting entries...")
6961 (save-restriction
6962 (narrow-to-region start end)
6964 (let ((dcst (downcase sorting-type))
6965 (now (current-time)))
6966 (sort-subr
6967 (/= dcst sorting-type)
6968 ;; This function moves to the beginning character of the "record" to
6969 ;; be sorted.
6970 (if plain-list-p
6971 (lambda nil
6972 (if (org-at-item-p) t (goto-char (point-max))))
6973 (lambda nil
6974 (if (re-search-forward re nil t)
6975 (goto-char (match-beginning 0))
6976 (goto-char (point-max)))))
6977 ;; This function moves to the last character of the "record" being
6978 ;; sorted.
6979 (if plain-list-p
6980 'org-end-of-item
6981 (lambda nil
6982 (save-match-data
6983 (condition-case nil
6984 (outline-forward-same-level 1)
6985 (error
6986 (goto-char (point-max)))))))
6988 ;; This function returns the value that gets sorted against.
6989 (if plain-list-p
6990 (lambda nil
6991 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6992 (cond
6993 ((= dcst ?n)
6994 (string-to-number (buffer-substring (match-end 0)
6995 (point-at-eol))))
6996 ((= dcst ?a)
6997 (buffer-substring (match-end 0) (point-at-eol)))
6998 ((= dcst ?t)
6999 (if (re-search-forward org-ts-regexp
7000 (point-at-eol) t)
7001 (org-time-string-to-time (match-string 0))
7002 now))
7003 ((= dcst ?f)
7004 (if getkey-func
7005 (progn
7006 (setq tmp (funcall getkey-func))
7007 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7008 tmp)
7009 (error "Invalid key function `%s'" getkey-func)))
7010 (t (error "Invalid sorting type `%c'" sorting-type)))))
7011 (lambda nil
7012 (cond
7013 ((= dcst ?n)
7014 (if (looking-at outline-regexp)
7015 (string-to-number (buffer-substring (match-end 0)
7016 (point-at-eol)))
7017 nil))
7018 ((= dcst ?a)
7019 (funcall case-func (buffer-substring (point-at-bol)
7020 (point-at-eol))))
7021 ((= dcst ?t)
7022 (if (re-search-forward org-ts-regexp
7023 (save-excursion
7024 (forward-line 2)
7025 (point)) t)
7026 (org-time-string-to-time (match-string 0))
7027 now))
7028 ((= dcst ?p)
7029 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7030 (string-to-char (match-string 2))
7031 org-default-priority))
7032 ((= dcst ?r)
7033 (or (org-entry-get nil property) ""))
7034 ((= dcst ?f)
7035 (if getkey-func
7036 (progn
7037 (setq tmp (funcall getkey-func))
7038 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7039 tmp)
7040 (error "Invalid key function `%s'" getkey-func)))
7041 (t (error "Invalid sorting type `%c'" sorting-type)))))
7043 (cond
7044 ((= dcst ?a) 'string<)
7045 ((= dcst ?t) 'time-less-p)
7046 (t nil)))))
7047 (message "Sorting entries...done")))
7049 (defun org-do-sort (table what &optional with-case sorting-type)
7050 "Sort TABLE of WHAT according to SORTING-TYPE.
7051 The user will be prompted for the SORTING-TYPE if the call to this
7052 function does not specify it. WHAT is only for the prompt, to indicate
7053 what is being sorted. The sorting key will be extracted from
7054 the car of the elements of the table.
7055 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7056 (unless sorting-type
7057 (message
7058 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7059 what)
7060 (setq sorting-type (read-char-exclusive)))
7061 (let ((dcst (downcase sorting-type))
7062 extractfun comparefun)
7063 ;; Define the appropriate functions
7064 (cond
7065 ((= dcst ?n)
7066 (setq extractfun 'string-to-number
7067 comparefun (if (= dcst sorting-type) '< '>)))
7068 ((= dcst ?a)
7069 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7070 (lambda(x) (downcase (org-sort-remove-invisible x))))
7071 comparefun (if (= dcst sorting-type)
7072 'string<
7073 (lambda (a b) (and (not (string< a b))
7074 (not (string= a b)))))))
7075 ((= dcst ?t)
7076 (setq extractfun
7077 (lambda (x)
7078 (if (string-match org-ts-regexp x)
7079 (time-to-seconds
7080 (org-time-string-to-time (match-string 0 x)))
7082 comparefun (if (= dcst sorting-type) '< '>)))
7083 (t (error "Invalid sorting type `%c'" sorting-type)))
7085 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7086 table)
7087 (lambda (a b) (funcall comparefun (car a) (car b))))))
7089 ;;;; Plain list items, including checkboxes
7091 ;;; Plain list items
7093 (defun org-at-item-p ()
7094 "Is point in a line starting a hand-formatted item?"
7095 (let ((llt org-plain-list-ordered-item-terminator))
7096 (save-excursion
7097 (goto-char (point-at-bol))
7098 (looking-at
7099 (cond
7100 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7101 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7102 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7103 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7105 (defun org-in-item-p ()
7106 "It the cursor inside a plain list item.
7107 Does not have to be the first line."
7108 (save-excursion
7109 (condition-case nil
7110 (progn
7111 (org-beginning-of-item)
7112 (org-at-item-p)
7114 (error nil))))
7116 (defun org-insert-item (&optional checkbox)
7117 "Insert a new item at the current level.
7118 Return t when things worked, nil when we are not in an item."
7119 (when (save-excursion
7120 (condition-case nil
7121 (progn
7122 (org-beginning-of-item)
7123 (org-at-item-p)
7124 (if (org-invisible-p) (error "Invisible item"))
7126 (error nil)))
7127 (let* ((bul (match-string 0))
7128 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7129 (match-end 0)))
7130 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7131 pos)
7132 (cond
7133 ((and (org-at-item-p) (<= (point) eow))
7134 ;; before the bullet
7135 (beginning-of-line 1)
7136 (open-line (if blank 2 1)))
7137 ((<= (point) eow)
7138 (beginning-of-line 1))
7140 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7141 (end-of-line 1)
7142 (delete-horizontal-space))
7143 (newline (if blank 2 1))))
7144 (insert bul (if checkbox "[ ]" ""))
7145 (just-one-space)
7146 (setq pos (point))
7147 (end-of-line 1)
7148 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7149 (org-maybe-renumber-ordered-list)
7150 (and checkbox (org-update-checkbox-count-maybe))
7153 ;;; Checkboxes
7155 (defun org-at-item-checkbox-p ()
7156 "Is point at a line starting a plain-list item with a checklet?"
7157 (and (org-at-item-p)
7158 (save-excursion
7159 (goto-char (match-end 0))
7160 (skip-chars-forward " \t")
7161 (looking-at "\\[[- X]\\]"))))
7163 (defun org-toggle-checkbox (&optional arg)
7164 "Toggle the checkbox in the current line."
7165 (interactive "P")
7166 (catch 'exit
7167 (let (beg end status (firstnew 'unknown))
7168 (cond
7169 ((org-region-active-p)
7170 (setq beg (region-beginning) end (region-end)))
7171 ((org-on-heading-p)
7172 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7173 ((org-at-item-checkbox-p)
7174 (let ((pos (point)))
7175 (replace-match
7176 (cond (arg "[-]")
7177 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7178 (t "[ ]"))
7179 t t)
7180 (goto-char pos))
7181 (throw 'exit t))
7182 (t (error "Not at a checkbox or heading, and no active region")))
7183 (save-excursion
7184 (goto-char beg)
7185 (while (< (point) end)
7186 (when (org-at-item-checkbox-p)
7187 (setq status (equal (match-string 0) "[X]"))
7188 (when (eq firstnew 'unknown)
7189 (setq firstnew (not status)))
7190 (replace-match
7191 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7192 (beginning-of-line 2)))))
7193 (org-update-checkbox-count-maybe))
7195 (defun org-update-checkbox-count-maybe ()
7196 "Update checkbox statistics unless turned off by user."
7197 (when org-provide-checkbox-statistics
7198 (org-update-checkbox-count)))
7200 (defun org-update-checkbox-count (&optional all)
7201 "Update the checkbox statistics in the current section.
7202 This will find all statistic cookies like [57%] and [6/12] and update them
7203 with the current numbers. With optional prefix argument ALL, do this for
7204 the whole buffer."
7205 (interactive "P")
7206 (save-excursion
7207 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7208 (beg (condition-case nil
7209 (progn (outline-back-to-heading) (point))
7210 (error (point-min))))
7211 (end (move-marker (make-marker)
7212 (progn (outline-next-heading) (point))))
7213 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7214 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7215 (re-find (concat re "\\|" re-box))
7216 beg-cookie end-cookie is-percent c-on c-off lim
7217 eline curr-ind next-ind continue-from startsearch
7218 (cstat 0)
7220 (when all
7221 (goto-char (point-min))
7222 (outline-next-heading)
7223 (setq beg (point) end (point-max)))
7224 (goto-char end)
7225 ;; find each statistic cookie
7226 (while (re-search-backward re-find beg t)
7227 (setq beg-cookie (match-beginning 1)
7228 end-cookie (match-end 1)
7229 cstat (+ cstat (if end-cookie 1 0))
7230 startsearch (point-at-eol)
7231 continue-from (point-at-bol)
7232 is-percent (match-beginning 2)
7233 lim (cond
7234 ((org-on-heading-p) (outline-next-heading) (point))
7235 ((org-at-item-p) (org-end-of-item) (point))
7236 (t nil))
7237 c-on 0
7238 c-off 0)
7239 (when lim
7240 ;; find first checkbox for this cookie and gather
7241 ;; statistics from all that are at this indentation level
7242 (goto-char startsearch)
7243 (if (re-search-forward re-box lim t)
7244 (progn
7245 (org-beginning-of-item)
7246 (setq curr-ind (org-get-indentation))
7247 (setq next-ind curr-ind)
7248 (while (= curr-ind next-ind)
7249 (save-excursion (end-of-line) (setq eline (point)))
7250 (if (re-search-forward re-box eline t)
7251 (if (member (match-string 2) '("[ ]" "[-]"))
7252 (setq c-off (1+ c-off))
7253 (setq c-on (1+ c-on))
7256 (org-end-of-item)
7257 (setq next-ind (org-get-indentation))
7259 (goto-char continue-from)
7260 ;; update cookie
7261 (when end-cookie
7262 (delete-region beg-cookie end-cookie)
7263 (goto-char beg-cookie)
7264 (insert
7265 (if is-percent
7266 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7267 (format "[%d/%d]" c-on (+ c-on c-off)))))
7268 ;; update items checkbox if it has one
7269 (when (org-at-item-p)
7270 (org-beginning-of-item)
7271 (when (and (> (+ c-on c-off) 0)
7272 (re-search-forward re-box (point-at-eol) t))
7273 (setq beg-cookie (match-beginning 2)
7274 end-cookie (match-end 2))
7275 (delete-region beg-cookie end-cookie)
7276 (goto-char beg-cookie)
7277 (cond ((= c-off 0) (insert "[X]"))
7278 ((= c-on 0) (insert "[ ]"))
7279 (t (insert "[-]")))
7281 (goto-char continue-from))
7282 (when (interactive-p)
7283 (message "Checkbox satistics updated %s (%d places)"
7284 (if all "in entire file" "in current outline entry") cstat)))))
7286 (defun org-get-checkbox-statistics-face ()
7287 "Select the face for checkbox statistics.
7288 The face will be `org-done' when all relevant boxes are checked. Otherwise
7289 it will be `org-todo'."
7290 (if (match-end 1)
7291 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7292 (if (and (> (match-end 2) (match-beginning 2))
7293 (equal (match-string 2) (match-string 3)))
7294 'org-done
7295 'org-todo)))
7297 (defun org-get-indentation (&optional line)
7298 "Get the indentation of the current line, interpreting tabs.
7299 When LINE is given, assume it represents a line and compute its indentation."
7300 (if line
7301 (if (string-match "^ *" (org-remove-tabs line))
7302 (match-end 0))
7303 (save-excursion
7304 (beginning-of-line 1)
7305 (skip-chars-forward " \t")
7306 (current-column))))
7308 (defun org-remove-tabs (s &optional width)
7309 "Replace tabulators in S with spaces.
7310 Assumes that s is a single line, starting in column 0."
7311 (setq width (or width tab-width))
7312 (while (string-match "\t" s)
7313 (setq s (replace-match
7314 (make-string
7315 (- (* width (/ (+ (match-beginning 0) width) width))
7316 (match-beginning 0)) ?\ )
7317 t t s)))
7320 (defun org-fix-indentation (line ind)
7321 "Fix indentation in LINE.
7322 IND is a cons cell with target and minimum indentation.
7323 If the current indenation in LINE is smaller than the minimum,
7324 leave it alone. If it is larger than ind, set it to the target."
7325 (let* ((l (org-remove-tabs line))
7326 (i (org-get-indentation l))
7327 (i1 (car ind)) (i2 (cdr ind)))
7328 (if (>= i i2) (setq l (substring line i2)))
7329 (if (> i1 0)
7330 (concat (make-string i1 ?\ ) l)
7331 l)))
7333 (defcustom org-empty-line-terminates-plain-lists nil
7334 "Non-nil means, an empty line ends all plain list levels.
7335 When nil, empty lines are part of the preceeding item."
7336 :group 'org-plain-lists
7337 :type 'boolean)
7339 (defun org-beginning-of-item ()
7340 "Go to the beginning of the current hand-formatted item.
7341 If the cursor is not in an item, throw an error."
7342 (interactive)
7343 (let ((pos (point))
7344 (limit (save-excursion
7345 (condition-case nil
7346 (progn
7347 (org-back-to-heading)
7348 (beginning-of-line 2) (point))
7349 (error (point-min)))))
7350 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7351 ind ind1)
7352 (if (org-at-item-p)
7353 (beginning-of-line 1)
7354 (beginning-of-line 1)
7355 (skip-chars-forward " \t")
7356 (setq ind (current-column))
7357 (if (catch 'exit
7358 (while t
7359 (beginning-of-line 0)
7360 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7362 (if (looking-at "[ \t]*$")
7363 (setq ind1 ind-empty)
7364 (skip-chars-forward " \t")
7365 (setq ind1 (current-column)))
7366 (if (< ind1 ind)
7367 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7369 (goto-char pos)
7370 (error "Not in an item")))))
7372 (defun org-end-of-item ()
7373 "Go to the end of the current hand-formatted item.
7374 If the cursor is not in an item, throw an error."
7375 (interactive)
7376 (let* ((pos (point))
7377 ind1
7378 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7379 (limit (save-excursion (outline-next-heading) (point)))
7380 (ind (save-excursion
7381 (org-beginning-of-item)
7382 (skip-chars-forward " \t")
7383 (current-column)))
7384 (end (catch 'exit
7385 (while t
7386 (beginning-of-line 2)
7387 (if (eobp) (throw 'exit (point)))
7388 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7389 (if (looking-at "[ \t]*$")
7390 (setq ind1 ind-empty)
7391 (skip-chars-forward " \t")
7392 (setq ind1 (current-column)))
7393 (if (<= ind1 ind)
7394 (throw 'exit (point-at-bol)))))))
7395 (if end
7396 (goto-char end)
7397 (goto-char pos)
7398 (error "Not in an item"))))
7400 (defun org-next-item ()
7401 "Move to the beginning of the next item in the current plain list.
7402 Error if not at a plain list, or if this is the last item in the list."
7403 (interactive)
7404 (let (ind ind1 (pos (point)))
7405 (org-beginning-of-item)
7406 (setq ind (org-get-indentation))
7407 (org-end-of-item)
7408 (setq ind1 (org-get-indentation))
7409 (unless (and (org-at-item-p) (= ind ind1))
7410 (goto-char pos)
7411 (error "On last item"))))
7413 (defun org-previous-item ()
7414 "Move to the beginning of the previous item in the current plain list.
7415 Error if not at a plain list, or if this is the first item in the list."
7416 (interactive)
7417 (let (beg ind ind1 (pos (point)))
7418 (org-beginning-of-item)
7419 (setq beg (point))
7420 (setq ind (org-get-indentation))
7421 (goto-char beg)
7422 (catch 'exit
7423 (while t
7424 (beginning-of-line 0)
7425 (if (looking-at "[ \t]*$")
7427 (if (<= (setq ind1 (org-get-indentation)) ind)
7428 (throw 'exit t)))))
7429 (condition-case nil
7430 (if (or (not (org-at-item-p))
7431 (< ind1 (1- ind)))
7432 (error "")
7433 (org-beginning-of-item))
7434 (error (goto-char pos)
7435 (error "On first item")))))
7437 (defun org-first-list-item-p ()
7438 "Is this heading the item in a plain list?"
7439 (unless (org-at-item-p)
7440 (error "Not at a plain list item"))
7441 (org-beginning-of-item)
7442 (= (point) (save-excursion (org-beginning-of-item-list))))
7444 (defun org-move-item-down ()
7445 "Move the plain list item at point down, i.e. swap with following item.
7446 Subitems (items with larger indentation) are considered part of the item,
7447 so this really moves item trees."
7448 (interactive)
7449 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7450 (org-beginning-of-item)
7451 (setq beg0 (point))
7452 (save-excursion
7453 (setq ne-beg (org-back-over-empty-lines))
7454 (setq beg (point)))
7455 (goto-char beg0)
7456 (setq ind (org-get-indentation))
7457 (org-end-of-item)
7458 (setq end0 (point))
7459 (setq ind1 (org-get-indentation))
7460 (setq ne-end (org-back-over-empty-lines))
7461 (setq end (point))
7462 (goto-char beg0)
7463 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7464 ;; include less whitespace
7465 (save-excursion
7466 (goto-char beg)
7467 (forward-line (- ne-beg ne-end))
7468 (setq beg (point))))
7469 (goto-char end0)
7470 (if (and (org-at-item-p) (= ind ind1))
7471 (progn
7472 (org-end-of-item)
7473 (org-back-over-empty-lines)
7474 (setq txt (buffer-substring beg end))
7475 (save-excursion
7476 (delete-region beg end))
7477 (setq pos (point))
7478 (insert txt)
7479 (goto-char pos) (org-skip-whitespace)
7480 (org-maybe-renumber-ordered-list))
7481 (goto-char pos)
7482 (error "Cannot move this item further down"))))
7484 (defun org-move-item-up (arg)
7485 "Move the plain list item at point up, i.e. swap with previous item.
7486 Subitems (items with larger indentation) are considered part of the item,
7487 so this really moves item trees."
7488 (interactive "p")
7489 (let (beg beg0 end ind ind1 (pos (point)) txt
7490 ne-beg ne-ins ins-end)
7491 (org-beginning-of-item)
7492 (setq beg0 (point))
7493 (setq ind (org-get-indentation))
7494 (save-excursion
7495 (setq ne-beg (org-back-over-empty-lines))
7496 (setq beg (point)))
7497 (goto-char beg0)
7498 (org-end-of-item)
7499 (setq end (point))
7500 (goto-char beg0)
7501 (catch 'exit
7502 (while t
7503 (beginning-of-line 0)
7504 (if (looking-at "[ \t]*$")
7505 (if org-empty-line-terminates-plain-lists
7506 (progn
7507 (goto-char pos)
7508 (error "Cannot move this item further up"))
7509 nil)
7510 (if (<= (setq ind1 (org-get-indentation)) ind)
7511 (throw 'exit t)))))
7512 (condition-case nil
7513 (org-beginning-of-item)
7514 (error (goto-char beg)
7515 (error "Cannot move this item further up")))
7516 (setq ind1 (org-get-indentation))
7517 (if (and (org-at-item-p) (= ind ind1))
7518 (progn
7519 (setq ne-ins (org-back-over-empty-lines))
7520 (setq txt (buffer-substring beg end))
7521 (save-excursion
7522 (delete-region beg end))
7523 (setq pos (point))
7524 (insert txt)
7525 (setq ins-end (point))
7526 (goto-char pos) (org-skip-whitespace)
7528 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7529 ;; Move whitespace back to beginning
7530 (save-excursion
7531 (goto-char ins-end)
7532 (let ((kill-whole-line t))
7533 (kill-line (- ne-ins ne-beg)) (point)))
7534 (insert (make-string (- ne-ins ne-beg) ?\n)))
7536 (org-maybe-renumber-ordered-list))
7537 (goto-char pos)
7538 (error "Cannot move this item further up"))))
7540 (defun org-maybe-renumber-ordered-list ()
7541 "Renumber the ordered list at point if setup allows it.
7542 This tests the user option `org-auto-renumber-ordered-lists' before
7543 doing the renumbering."
7544 (interactive)
7545 (when (and org-auto-renumber-ordered-lists
7546 (org-at-item-p))
7547 (if (match-beginning 3)
7548 (org-renumber-ordered-list 1)
7549 (org-fix-bullet-type))))
7551 (defun org-maybe-renumber-ordered-list-safe ()
7552 (condition-case nil
7553 (save-excursion
7554 (org-maybe-renumber-ordered-list))
7555 (error nil)))
7557 (defun org-cycle-list-bullet (&optional which)
7558 "Cycle through the different itemize/enumerate bullets.
7559 This cycle the entire list level through the sequence:
7561 `-' -> `+' -> `*' -> `1.' -> `1)'
7563 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7564 0 meand `-', 1 means `+' etc."
7565 (interactive "P")
7566 (org-preserve-lc
7567 (org-beginning-of-item-list)
7568 (org-at-item-p)
7569 (beginning-of-line 1)
7570 (let ((current (match-string 0))
7571 (prevp (eq which 'previous))
7572 new)
7573 (setq new (cond
7574 ((and (numberp which)
7575 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7576 ((string-match "-" current) (if prevp "1)" "+"))
7577 ((string-match "\\+" current)
7578 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7579 ((string-match "\\*" current) (if prevp "+" "1."))
7580 ((string-match "\\." current) (if prevp "*" "1)"))
7581 ((string-match ")" current) (if prevp "1." "-"))
7582 (t (error "This should not happen"))))
7583 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7584 (org-fix-bullet-type)
7585 (org-maybe-renumber-ordered-list))))
7587 (defun org-get-string-indentation (s)
7588 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7589 (let ((n -1) (i 0) (w tab-width) c)
7590 (catch 'exit
7591 (while (< (setq n (1+ n)) (length s))
7592 (setq c (aref s n))
7593 (cond ((= c ?\ ) (setq i (1+ i)))
7594 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7595 (t (throw 'exit t)))))
7598 (defun org-renumber-ordered-list (arg)
7599 "Renumber an ordered plain list.
7600 Cursor needs to be in the first line of an item, the line that starts
7601 with something like \"1.\" or \"2)\"."
7602 (interactive "p")
7603 (unless (and (org-at-item-p)
7604 (match-beginning 3))
7605 (error "This is not an ordered list"))
7606 (let ((line (org-current-line))
7607 (col (current-column))
7608 (ind (org-get-string-indentation
7609 (buffer-substring (point-at-bol) (match-beginning 3))))
7610 ;; (term (substring (match-string 3) -1))
7611 ind1 (n (1- arg))
7612 fmt)
7613 ;; find where this list begins
7614 (org-beginning-of-item-list)
7615 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7616 (setq fmt (concat "%d" (match-string 1)))
7617 (beginning-of-line 0)
7618 ;; walk forward and replace these numbers
7619 (catch 'exit
7620 (while t
7621 (catch 'next
7622 (beginning-of-line 2)
7623 (if (eobp) (throw 'exit nil))
7624 (if (looking-at "[ \t]*$") (throw 'next nil))
7625 (skip-chars-forward " \t") (setq ind1 (current-column))
7626 (if (> ind1 ind) (throw 'next t))
7627 (if (< ind1 ind) (throw 'exit t))
7628 (if (not (org-at-item-p)) (throw 'exit nil))
7629 (delete-region (match-beginning 2) (match-end 2))
7630 (goto-char (match-beginning 2))
7631 (insert (format fmt (setq n (1+ n)))))))
7632 (goto-line line)
7633 (move-to-column col)))
7635 (defun org-fix-bullet-type ()
7636 "Make sure all items in this list have the same bullet as the firsst item."
7637 (interactive)
7638 (unless (org-at-item-p) (error "This is not a list"))
7639 (let ((line (org-current-line))
7640 (col (current-column))
7641 (ind (current-indentation))
7642 ind1 bullet)
7643 ;; find where this list begins
7644 (org-beginning-of-item-list)
7645 (beginning-of-line 1)
7646 ;; find out what the bullet type is
7647 (looking-at "[ \t]*\\(\\S-+\\)")
7648 (setq bullet (match-string 1))
7649 ;; walk forward and replace these numbers
7650 (beginning-of-line 0)
7651 (catch 'exit
7652 (while t
7653 (catch 'next
7654 (beginning-of-line 2)
7655 (if (eobp) (throw 'exit nil))
7656 (if (looking-at "[ \t]*$") (throw 'next nil))
7657 (skip-chars-forward " \t") (setq ind1 (current-column))
7658 (if (> ind1 ind) (throw 'next t))
7659 (if (< ind1 ind) (throw 'exit t))
7660 (if (not (org-at-item-p)) (throw 'exit nil))
7661 (skip-chars-forward " \t")
7662 (looking-at "\\S-+")
7663 (replace-match bullet))))
7664 (goto-line line)
7665 (move-to-column col)
7666 (if (string-match "[0-9]" bullet)
7667 (org-renumber-ordered-list 1))))
7669 (defun org-beginning-of-item-list ()
7670 "Go to the beginning of the current item list.
7671 I.e. to the first item in this list."
7672 (interactive)
7673 (org-beginning-of-item)
7674 (let ((pos (point-at-bol))
7675 (ind (org-get-indentation))
7676 ind1)
7677 ;; find where this list begins
7678 (catch 'exit
7679 (while t
7680 (catch 'next
7681 (beginning-of-line 0)
7682 (if (looking-at "[ \t]*$")
7683 (throw (if (bobp) 'exit 'next) t))
7684 (skip-chars-forward " \t") (setq ind1 (current-column))
7685 (if (or (< ind1 ind)
7686 (and (= ind1 ind)
7687 (not (org-at-item-p)))
7688 (bobp))
7689 (throw 'exit t)
7690 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7691 (goto-char pos)))
7694 (defun org-end-of-item-list ()
7695 "Go to the end of the current item list.
7696 I.e. to the text after the last item."
7697 (interactive)
7698 (org-beginning-of-item)
7699 (let ((pos (point-at-bol))
7700 (ind (org-get-indentation))
7701 ind1)
7702 ;; find where this list begins
7703 (catch 'exit
7704 (while t
7705 (catch 'next
7706 (beginning-of-line 2)
7707 (if (looking-at "[ \t]*$")
7708 (throw (if (eobp) 'exit 'next) t))
7709 (skip-chars-forward " \t") (setq ind1 (current-column))
7710 (if (or (< ind1 ind)
7711 (and (= ind1 ind)
7712 (not (org-at-item-p)))
7713 (eobp))
7714 (progn
7715 (setq pos (point-at-bol))
7716 (throw 'exit t))))))
7717 (goto-char pos)))
7720 (defvar org-last-indent-begin-marker (make-marker))
7721 (defvar org-last-indent-end-marker (make-marker))
7723 (defun org-outdent-item (arg)
7724 "Outdent a local list item."
7725 (interactive "p")
7726 (org-indent-item (- arg)))
7728 (defun org-indent-item (arg)
7729 "Indent a local list item."
7730 (interactive "p")
7731 (unless (org-at-item-p)
7732 (error "Not on an item"))
7733 (save-excursion
7734 (let (beg end ind ind1 tmp delta ind-down ind-up)
7735 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7736 (setq beg org-last-indent-begin-marker
7737 end org-last-indent-end-marker)
7738 (org-beginning-of-item)
7739 (setq beg (move-marker org-last-indent-begin-marker (point)))
7740 (org-end-of-item)
7741 (setq end (move-marker org-last-indent-end-marker (point))))
7742 (goto-char beg)
7743 (setq tmp (org-item-indent-positions)
7744 ind (car tmp)
7745 ind-down (nth 2 tmp)
7746 ind-up (nth 1 tmp)
7747 delta (if (> arg 0)
7748 (if ind-down (- ind-down ind) 2)
7749 (if ind-up (- ind-up ind) -2)))
7750 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7751 (while (< (point) end)
7752 (beginning-of-line 1)
7753 (skip-chars-forward " \t") (setq ind1 (current-column))
7754 (delete-region (point-at-bol) (point))
7755 (or (eolp) (indent-to-column (+ ind1 delta)))
7756 (beginning-of-line 2))))
7757 (org-fix-bullet-type)
7758 (org-maybe-renumber-ordered-list-safe)
7759 (save-excursion
7760 (beginning-of-line 0)
7761 (condition-case nil (org-beginning-of-item) (error nil))
7762 (org-maybe-renumber-ordered-list-safe)))
7764 (defun org-item-indent-positions ()
7765 "Return indentation for plain list items.
7766 This returns a list with three values: The current indentation, the
7767 parent indentation and the indentation a child should habe.
7768 Assumes cursor in item line."
7769 (let* ((bolpos (point-at-bol))
7770 (ind (org-get-indentation))
7771 ind-down ind-up pos)
7772 (save-excursion
7773 (org-beginning-of-item-list)
7774 (skip-chars-backward "\n\r \t")
7775 (when (org-in-item-p)
7776 (org-beginning-of-item)
7777 (setq ind-up (org-get-indentation))))
7778 (setq pos (point))
7779 (save-excursion
7780 (cond
7781 ((and (condition-case nil (progn (org-previous-item) t)
7782 (error nil))
7783 (or (forward-char 1) t)
7784 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7785 (setq ind-down (org-get-indentation)))
7786 ((and (goto-char pos)
7787 (org-at-item-p))
7788 (goto-char (match-end 0))
7789 (skip-chars-forward " \t")
7790 (setq ind-down (current-column)))))
7791 (list ind ind-up ind-down)))
7793 ;;; The orgstruct minor mode
7795 ;; Define a minor mode which can be used in other modes in order to
7796 ;; integrate the org-mode structure editing commands.
7798 ;; This is really a hack, because the org-mode structure commands use
7799 ;; keys which normally belong to the major mode. Here is how it
7800 ;; works: The minor mode defines all the keys necessary to operate the
7801 ;; structure commands, but wraps the commands into a function which
7802 ;; tests if the cursor is currently at a headline or a plain list
7803 ;; item. If that is the case, the structure command is used,
7804 ;; temporarily setting many Org-mode variables like regular
7805 ;; expressions for filling etc. However, when any of those keys is
7806 ;; used at a different location, function uses `key-binding' to look
7807 ;; up if the key has an associated command in another currently active
7808 ;; keymap (minor modes, major mode, global), and executes that
7809 ;; command. There might be problems if any of the keys is otherwise
7810 ;; used as a prefix key.
7812 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7813 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7814 ;; addresses this by checking explicitly for both bindings.
7816 (defvar orgstruct-mode-map (make-sparse-keymap)
7817 "Keymap for the minor `orgstruct-mode'.")
7819 (defvar org-local-vars nil
7820 "List of local variables, for use by `orgstruct-mode'")
7822 ;;;###autoload
7823 (define-minor-mode orgstruct-mode
7824 "Toggle the minor more `orgstruct-mode'.
7825 This mode is for using Org-mode structure commands in other modes.
7826 The following key behave as if Org-mode was active, if the cursor
7827 is on a headline, or on a plain list item (both in the definition
7828 of Org-mode).
7830 M-up Move entry/item up
7831 M-down Move entry/item down
7832 M-left Promote
7833 M-right Demote
7834 M-S-up Move entry/item up
7835 M-S-down Move entry/item down
7836 M-S-left Promote subtree
7837 M-S-right Demote subtree
7838 M-q Fill paragraph and items like in Org-mode
7839 C-c ^ Sort entries
7840 C-c - Cycle list bullet
7841 TAB Cycle item visibility
7842 M-RET Insert new heading/item
7843 S-M-RET Insert new TODO heading / Chekbox item
7844 C-c C-c Set tags / toggle checkbox"
7845 nil " OrgStruct" nil
7846 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7848 ;;;###autoload
7849 (defun turn-on-orgstruct ()
7850 "Unconditionally turn on `orgstruct-mode'."
7851 (orgstruct-mode 1))
7853 ;;;###autoload
7854 (defun turn-on-orgstruct++ ()
7855 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7856 In addition to setting orgstruct-mode, this also exports all indentation and
7857 autofilling variables from org-mode into the buffer. Note that turning
7858 off orgstruct-mode will *not* remove these additional settings."
7859 (orgstruct-mode 1)
7860 (let (var val)
7861 (mapc
7862 (lambda (x)
7863 (when (string-match
7864 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7865 (symbol-name (car x)))
7866 (setq var (car x) val (nth 1 x))
7867 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7868 org-local-vars)))
7870 (defun orgstruct-error ()
7871 "Error when there is no default binding for a structure key."
7872 (interactive)
7873 (error "This key has no function outside structure elements"))
7875 (defun orgstruct-setup ()
7876 "Setup orgstruct keymaps."
7877 (let ((nfunc 0)
7878 (bindings
7879 (list
7880 '([(meta up)] org-metaup)
7881 '([(meta down)] org-metadown)
7882 '([(meta left)] org-metaleft)
7883 '([(meta right)] org-metaright)
7884 '([(meta shift up)] org-shiftmetaup)
7885 '([(meta shift down)] org-shiftmetadown)
7886 '([(meta shift left)] org-shiftmetaleft)
7887 '([(meta shift right)] org-shiftmetaright)
7888 '([(shift up)] org-shiftup)
7889 '([(shift down)] org-shiftdown)
7890 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7891 '("\M-q" fill-paragraph)
7892 '("\C-c^" org-sort)
7893 '("\C-c-" org-cycle-list-bullet)))
7894 elt key fun cmd)
7895 (while (setq elt (pop bindings))
7896 (setq nfunc (1+ nfunc))
7897 (setq key (org-key (car elt))
7898 fun (nth 1 elt)
7899 cmd (orgstruct-make-binding fun nfunc key))
7900 (org-defkey orgstruct-mode-map key cmd))
7902 ;; Special treatment needed for TAB and RET
7903 (org-defkey orgstruct-mode-map [(tab)]
7904 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7905 (org-defkey orgstruct-mode-map "\C-i"
7906 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7908 (org-defkey orgstruct-mode-map "\M-\C-m"
7909 (orgstruct-make-binding 'org-insert-heading 105
7910 "\M-\C-m" [(meta return)]))
7911 (org-defkey orgstruct-mode-map [(meta return)]
7912 (orgstruct-make-binding 'org-insert-heading 106
7913 [(meta return)] "\M-\C-m"))
7915 (org-defkey orgstruct-mode-map [(shift meta return)]
7916 (orgstruct-make-binding 'org-insert-todo-heading 107
7917 [(meta return)] "\M-\C-m"))
7919 (unless org-local-vars
7920 (setq org-local-vars (org-get-local-variables)))
7924 (defun orgstruct-make-binding (fun n &rest keys)
7925 "Create a function for binding in the structure minor mode.
7926 FUN is the command to call inside a table. N is used to create a unique
7927 command name. KEYS are keys that should be checked in for a command
7928 to execute outside of tables."
7929 (eval
7930 (list 'defun
7931 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7932 '(arg)
7933 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7934 "Outside of structure, run the binding of `"
7935 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7936 "'.")
7937 '(interactive "p")
7938 (list 'if
7939 '(org-context-p 'headline 'item)
7940 (list 'org-run-like-in-org-mode (list 'quote fun))
7941 (list 'let '(orgstruct-mode)
7942 (list 'call-interactively
7943 (append '(or)
7944 (mapcar (lambda (k)
7945 (list 'key-binding k))
7946 keys)
7947 '('orgstruct-error))))))))
7949 (defun org-context-p (&rest contexts)
7950 "Check if local context is and of CONTEXTS.
7951 Possible values in the list of contexts are `table', `headline', and `item'."
7952 (let ((pos (point)))
7953 (goto-char (point-at-bol))
7954 (prog1 (or (and (memq 'table contexts)
7955 (looking-at "[ \t]*|"))
7956 (and (memq 'headline contexts)
7957 (looking-at "\\*+"))
7958 (and (memq 'item contexts)
7959 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7960 (goto-char pos))))
7962 (defun org-get-local-variables ()
7963 "Return a list of all local variables in an org-mode buffer."
7964 (let (varlist)
7965 (with-current-buffer (get-buffer-create "*Org tmp*")
7966 (erase-buffer)
7967 (org-mode)
7968 (setq varlist (buffer-local-variables)))
7969 (kill-buffer "*Org tmp*")
7970 (delq nil
7971 (mapcar
7972 (lambda (x)
7973 (setq x
7974 (if (symbolp x)
7975 (list x)
7976 (list (car x) (list 'quote (cdr x)))))
7977 (if (string-match
7978 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7979 (symbol-name (car x)))
7980 x nil))
7981 varlist))))
7983 ;;;###autoload
7984 (defun org-run-like-in-org-mode (cmd)
7985 (unless org-local-vars
7986 (setq org-local-vars (org-get-local-variables)))
7987 (eval (list 'let org-local-vars
7988 (list 'call-interactively (list 'quote cmd)))))
7990 ;;;; Archiving
7992 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7994 (defun org-archive-subtree (&optional find-done)
7995 "Move the current subtree to the archive.
7996 The archive can be a certain top-level heading in the current file, or in
7997 a different file. The tree will be moved to that location, the subtree
7998 heading be marked DONE, and the current time will be added.
8000 When called with prefix argument FIND-DONE, find whole trees without any
8001 open TODO items and archive them (after getting confirmation from the user).
8002 If the cursor is not at a headline when this comand is called, try all level
8003 1 trees. If the cursor is on a headline, only try the direct children of
8004 this heading."
8005 (interactive "P")
8006 (if find-done
8007 (org-archive-all-done)
8008 ;; Save all relevant TODO keyword-relatex variables
8010 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
8011 (tr-org-todo-keywords-1 org-todo-keywords-1)
8012 (tr-org-todo-kwd-alist org-todo-kwd-alist)
8013 (tr-org-done-keywords org-done-keywords)
8014 (tr-org-todo-regexp org-todo-regexp)
8015 (tr-org-todo-line-regexp org-todo-line-regexp)
8016 (tr-org-odd-levels-only org-odd-levels-only)
8017 (this-buffer (current-buffer))
8018 (org-archive-location org-archive-location)
8019 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
8020 ;; start of variables that will be used for saving context
8021 ;; The compiler complains about them - keep them anyway!
8022 (file (abbreviate-file-name (buffer-file-name)))
8023 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
8024 (time (format-time-string
8025 (substring (cdr org-time-stamp-formats) 1 -1)
8026 (current-time)))
8027 afile heading buffer level newfile-p
8028 category todo priority
8029 ;; start of variables that will be used for savind context
8030 ltags itags prop)
8032 ;; Try to find a local archive location
8033 (save-excursion
8034 (save-restriction
8035 (widen)
8036 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8037 (if (and prop (string-match "\\S-" prop))
8038 (setq org-archive-location prop)
8039 (if (or (re-search-backward re nil t)
8040 (re-search-forward re nil t))
8041 (setq org-archive-location (match-string 1))))))
8043 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8044 (progn
8045 (setq afile (format (match-string 1 org-archive-location)
8046 (file-name-nondirectory buffer-file-name))
8047 heading (match-string 2 org-archive-location)))
8048 (error "Invalid `org-archive-location'"))
8049 (if (> (length afile) 0)
8050 (setq newfile-p (not (file-exists-p afile))
8051 buffer (find-file-noselect afile))
8052 (setq buffer (current-buffer)))
8053 (unless buffer
8054 (error "Cannot access file \"%s\"" afile))
8055 (if (and (> (length heading) 0)
8056 (string-match "^\\*+" heading))
8057 (setq level (match-end 0))
8058 (setq heading nil level 0))
8059 (save-excursion
8060 (org-back-to-heading t)
8061 ;; Get context information that will be lost by moving the tree
8062 (org-refresh-category-properties)
8063 (setq category (org-get-category)
8064 todo (and (looking-at org-todo-line-regexp)
8065 (match-string 2))
8066 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8067 ltags (org-get-tags)
8068 itags (org-delete-all ltags (org-get-tags-at)))
8069 (setq ltags (mapconcat 'identity ltags " ")
8070 itags (mapconcat 'identity itags " "))
8071 ;; We first only copy, in case something goes wrong
8072 ;; we need to protect this-command, to avoid kill-region sets it,
8073 ;; which would lead to duplication of subtrees
8074 (let (this-command) (org-copy-subtree))
8075 (set-buffer buffer)
8076 ;; Enforce org-mode for the archive buffer
8077 (if (not (org-mode-p))
8078 ;; Force the mode for future visits.
8079 (let ((org-insert-mode-line-in-empty-file t)
8080 (org-inhibit-startup t))
8081 (call-interactively 'org-mode)))
8082 (when newfile-p
8083 (goto-char (point-max))
8084 (insert (format "\nArchived entries from file %s\n\n"
8085 (buffer-file-name this-buffer))))
8086 ;; Force the TODO keywords of the original buffer
8087 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8088 (org-todo-keywords-1 tr-org-todo-keywords-1)
8089 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8090 (org-done-keywords tr-org-done-keywords)
8091 (org-todo-regexp tr-org-todo-regexp)
8092 (org-todo-line-regexp tr-org-todo-line-regexp)
8093 (org-odd-levels-only
8094 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8095 org-odd-levels-only
8096 tr-org-odd-levels-only)))
8097 (goto-char (point-min))
8098 (show-all)
8099 (if heading
8100 (progn
8101 (if (re-search-forward
8102 (concat "^" (regexp-quote heading)
8103 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8104 nil t)
8105 (goto-char (match-end 0))
8106 ;; Heading not found, just insert it at the end
8107 (goto-char (point-max))
8108 (or (bolp) (insert "\n"))
8109 (insert "\n" heading "\n")
8110 (end-of-line 0))
8111 ;; Make the subtree visible
8112 (show-subtree)
8113 (org-end-of-subtree t)
8114 (skip-chars-backward " \t\r\n")
8115 (and (looking-at "[ \t\r\n]*")
8116 (replace-match "\n\n")))
8117 ;; No specific heading, just go to end of file.
8118 (goto-char (point-max)) (insert "\n"))
8119 ;; Paste
8120 (org-paste-subtree (org-get-legal-level level 1))
8122 ;; Mark the entry as done
8123 (when (and org-archive-mark-done
8124 (looking-at org-todo-line-regexp)
8125 (or (not (match-end 2))
8126 (not (member (match-string 2) org-done-keywords))))
8127 (let (org-log-done org-todo-log-states)
8128 (org-todo
8129 (car (or (member org-archive-mark-done org-done-keywords)
8130 org-done-keywords)))))
8132 ;; Add the context info
8133 (when org-archive-save-context-info
8134 (let ((l org-archive-save-context-info) e n v)
8135 (while (setq e (pop l))
8136 (when (and (setq v (symbol-value e))
8137 (stringp v) (string-match "\\S-" v))
8138 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8139 (org-entry-put (point) n v)))))
8141 ;; Save and kill the buffer, if it is not the same buffer.
8142 (if (not (eq this-buffer buffer))
8143 (progn (save-buffer) (kill-buffer buffer)))))
8144 ;; Here we are back in the original buffer. Everything seems to have
8145 ;; worked. So now cut the tree and finish up.
8146 (let (this-command) (org-cut-subtree))
8147 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8148 (message "Subtree archived %s"
8149 (if (eq this-buffer buffer)
8150 (concat "under heading: " heading)
8151 (concat "in file: " (abbreviate-file-name afile)))))))
8153 (defun org-refresh-category-properties ()
8154 "Refresh category text properties in teh buffer."
8155 (let ((def-cat (cond
8156 ((null org-category)
8157 (if buffer-file-name
8158 (file-name-sans-extension
8159 (file-name-nondirectory buffer-file-name))
8160 "???"))
8161 ((symbolp org-category) (symbol-name org-category))
8162 (t org-category)))
8163 beg end cat pos optionp)
8164 (org-unmodified
8165 (save-excursion
8166 (save-restriction
8167 (widen)
8168 (goto-char (point-min))
8169 (put-text-property (point) (point-max) 'org-category def-cat)
8170 (while (re-search-forward
8171 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8172 (setq pos (match-end 0)
8173 optionp (equal (char-after (match-beginning 0)) ?#)
8174 cat (org-trim (match-string 2)))
8175 (if optionp
8176 (setq beg (point-at-bol) end (point-max))
8177 (org-back-to-heading t)
8178 (setq beg (point) end (org-end-of-subtree t t)))
8179 (put-text-property beg end 'org-category cat)
8180 (goto-char pos)))))))
8182 (defun org-archive-all-done (&optional tag)
8183 "Archive sublevels of the current tree without open TODO items.
8184 If the cursor is not on a headline, try all level 1 trees. If
8185 it is on a headline, try all direct children.
8186 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8187 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8188 (rea (concat ".*:" org-archive-tag ":"))
8189 (begm (make-marker))
8190 (endm (make-marker))
8191 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8192 "Move subtree to archive (no open TODO items)? "))
8193 beg end (cntarch 0))
8194 (if (org-on-heading-p)
8195 (progn
8196 (setq re1 (concat "^" (regexp-quote
8197 (make-string
8198 (1+ (- (match-end 0) (match-beginning 0) 1))
8199 ?*))
8200 " "))
8201 (move-marker begm (point))
8202 (move-marker endm (org-end-of-subtree t)))
8203 (setq re1 "^* ")
8204 (move-marker begm (point-min))
8205 (move-marker endm (point-max)))
8206 (save-excursion
8207 (goto-char begm)
8208 (while (re-search-forward re1 endm t)
8209 (setq beg (match-beginning 0)
8210 end (save-excursion (org-end-of-subtree t) (point)))
8211 (goto-char beg)
8212 (if (re-search-forward re end t)
8213 (goto-char end)
8214 (goto-char beg)
8215 (if (and (or (not tag) (not (looking-at rea)))
8216 (y-or-n-p question))
8217 (progn
8218 (if tag
8219 (org-toggle-tag org-archive-tag 'on)
8220 (org-archive-subtree))
8221 (setq cntarch (1+ cntarch)))
8222 (goto-char end)))))
8223 (message "%d trees archived" cntarch)))
8225 (defun org-cycle-hide-drawers (state)
8226 "Re-hide all drawers after a visibility state change."
8227 (when (and (org-mode-p)
8228 (not (memq state '(overview folded))))
8229 (save-excursion
8230 (let* ((globalp (memq state '(contents all)))
8231 (beg (if globalp (point-min) (point)))
8232 (end (if globalp (point-max) (org-end-of-subtree t))))
8233 (goto-char beg)
8234 (while (re-search-forward org-drawer-regexp end t)
8235 (org-flag-drawer t))))))
8237 (defun org-flag-drawer (flag)
8238 (save-excursion
8239 (beginning-of-line 1)
8240 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8241 (let ((b (match-end 0))
8242 (outline-regexp org-outline-regexp))
8243 (if (re-search-forward
8244 "^[ \t]*:END:"
8245 (save-excursion (outline-next-heading) (point)) t)
8246 (outline-flag-region b (point-at-eol) flag)
8247 (error ":END: line missing"))))))
8249 (defun org-cycle-hide-archived-subtrees (state)
8250 "Re-hide all archived subtrees after a visibility state change."
8251 (when (and (not org-cycle-open-archived-trees)
8252 (not (memq state '(overview folded))))
8253 (save-excursion
8254 (let* ((globalp (memq state '(contents all)))
8255 (beg (if globalp (point-min) (point)))
8256 (end (if globalp (point-max) (org-end-of-subtree t))))
8257 (org-hide-archived-subtrees beg end)
8258 (goto-char beg)
8259 (if (looking-at (concat ".*:" org-archive-tag ":"))
8260 (message "%s" (substitute-command-keys
8261 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8263 (defun org-force-cycle-archived ()
8264 "Cycle subtree even if it is archived."
8265 (interactive)
8266 (setq this-command 'org-cycle)
8267 (let ((org-cycle-open-archived-trees t))
8268 (call-interactively 'org-cycle)))
8270 (defun org-hide-archived-subtrees (beg end)
8271 "Re-hide all archived subtrees after a visibility state change."
8272 (save-excursion
8273 (let* ((re (concat ":" org-archive-tag ":")))
8274 (goto-char beg)
8275 (while (re-search-forward re end t)
8276 (and (org-on-heading-p) (hide-subtree))
8277 (org-end-of-subtree t)))))
8279 (defun org-toggle-tag (tag &optional onoff)
8280 "Toggle the tag TAG for the current line.
8281 If ONOFF is `on' or `off', don't toggle but set to this state."
8282 (unless (org-on-heading-p t) (error "Not on headling"))
8283 (let (res current)
8284 (save-excursion
8285 (beginning-of-line)
8286 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8287 (point-at-eol) t)
8288 (progn
8289 (setq current (match-string 1))
8290 (replace-match ""))
8291 (setq current ""))
8292 (setq current (nreverse (org-split-string current ":")))
8293 (cond
8294 ((eq onoff 'on)
8295 (setq res t)
8296 (or (member tag current) (push tag current)))
8297 ((eq onoff 'off)
8298 (or (not (member tag current)) (setq current (delete tag current))))
8299 (t (if (member tag current)
8300 (setq current (delete tag current))
8301 (setq res t)
8302 (push tag current))))
8303 (end-of-line 1)
8304 (if current
8305 (progn
8306 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8307 (org-set-tags nil t))
8308 (delete-horizontal-space))
8309 (run-hooks 'org-after-tags-change-hook))
8310 res))
8312 (defun org-toggle-archive-tag (&optional arg)
8313 "Toggle the archive tag for the current headline.
8314 With prefix ARG, check all children of current headline and offer tagging
8315 the children that do not contain any open TODO items."
8316 (interactive "P")
8317 (if arg
8318 (org-archive-all-done 'tag)
8319 (let (set)
8320 (save-excursion
8321 (org-back-to-heading t)
8322 (setq set (org-toggle-tag org-archive-tag))
8323 (when set (hide-subtree)))
8324 (and set (beginning-of-line 1))
8325 (message "Subtree %s" (if set "archived" "unarchived")))))
8328 ;;;; Tables
8330 ;;; The table editor
8332 ;; Watch out: Here we are talking about two different kind of tables.
8333 ;; Most of the code is for the tables created with the Org-mode table editor.
8334 ;; Sometimes, we talk about tables created and edited with the table.el
8335 ;; Emacs package. We call the former org-type tables, and the latter
8336 ;; table.el-type tables.
8338 (defun org-before-change-function (beg end)
8339 "Every change indicates that a table might need an update."
8340 (setq org-table-may-need-update t))
8342 (defconst org-table-line-regexp "^[ \t]*|"
8343 "Detects an org-type table line.")
8344 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8345 "Detects an org-type table line.")
8346 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8347 "Detects a table line marked for automatic recalculation.")
8348 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8349 "Detects a table line marked for automatic recalculation.")
8350 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8351 "Detects a table line marked for automatic recalculation.")
8352 (defconst org-table-hline-regexp "^[ \t]*|-"
8353 "Detects an org-type table hline.")
8354 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8355 "Detects a table-type table hline.")
8356 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8357 "Detects an org-type or table-type table.")
8358 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8359 "Searching from within a table (any type) this finds the first line
8360 outside the table.")
8361 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8362 "Searching from within a table (any type) this finds the first line
8363 outside the table.")
8365 (defvar org-table-last-highlighted-reference nil)
8366 (defvar org-table-formula-history nil)
8368 (defvar org-table-column-names nil
8369 "Alist with column names, derived from the `!' line.")
8370 (defvar org-table-column-name-regexp nil
8371 "Regular expression matching the current column names.")
8372 (defvar org-table-local-parameters nil
8373 "Alist with parameter names, derived from the `$' line.")
8374 (defvar org-table-named-field-locations nil
8375 "Alist with locations of named fields.")
8377 (defvar org-table-current-line-types nil
8378 "Table row types, non-nil only for the duration of a comand.")
8379 (defvar org-table-current-begin-line nil
8380 "Table begin line, non-nil only for the duration of a comand.")
8381 (defvar org-table-current-begin-pos nil
8382 "Table begin position, non-nil only for the duration of a comand.")
8383 (defvar org-table-dlines nil
8384 "Vector of data line line numbers in the current table.")
8385 (defvar org-table-hlines nil
8386 "Vector of hline line numbers in the current table.")
8388 (defconst org-table-range-regexp
8389 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8390 ;; 1 2 3 4 5
8391 "Regular expression for matching ranges in formulas.")
8393 (defconst org-table-range-regexp2
8394 (concat
8395 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8396 "\\.\\."
8397 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8398 "Match a range for reference display.")
8400 (defconst org-table-translate-regexp
8401 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8402 "Match a reference that needs translation, for reference display.")
8404 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8406 (defun org-table-create-with-table.el ()
8407 "Use the table.el package to insert a new table.
8408 If there is already a table at point, convert between Org-mode tables
8409 and table.el tables."
8410 (interactive)
8411 (require 'table)
8412 (cond
8413 ((org-at-table.el-p)
8414 (if (y-or-n-p "Convert table to Org-mode table? ")
8415 (org-table-convert)))
8416 ((org-at-table-p)
8417 (if (y-or-n-p "Convert table to table.el table? ")
8418 (org-table-convert)))
8419 (t (call-interactively 'table-insert))))
8421 (defun org-table-create-or-convert-from-region (arg)
8422 "Convert region to table, or create an empty table.
8423 If there is an active region, convert it to a table, using the function
8424 `org-table-convert-region'. See the documentation of that function
8425 to learn how the prefix argument is interpreted to determine the field
8426 separator.
8427 If there is no such region, create an empty table with `org-table-create'."
8428 (interactive "P")
8429 (if (org-region-active-p)
8430 (org-table-convert-region (region-beginning) (region-end) arg)
8431 (org-table-create arg)))
8433 (defun org-table-create (&optional size)
8434 "Query for a size and insert a table skeleton.
8435 SIZE is a string Columns x Rows like for example \"3x2\"."
8436 (interactive "P")
8437 (unless size
8438 (setq size (read-string
8439 (concat "Table size Columns x Rows [e.g. "
8440 org-table-default-size "]: ")
8441 "" nil org-table-default-size)))
8443 (let* ((pos (point))
8444 (indent (make-string (current-column) ?\ ))
8445 (split (org-split-string size " *x *"))
8446 (rows (string-to-number (nth 1 split)))
8447 (columns (string-to-number (car split)))
8448 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8449 "\n")))
8450 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8451 (point-at-bol) (point)))
8452 (beginning-of-line 1)
8453 (newline))
8454 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8455 (dotimes (i rows) (insert line))
8456 (goto-char pos)
8457 (if (> rows 1)
8458 ;; Insert a hline after the first row.
8459 (progn
8460 (end-of-line 1)
8461 (insert "\n|-")
8462 (goto-char pos)))
8463 (org-table-align)))
8465 (defun org-table-convert-region (beg0 end0 &optional separator)
8466 "Convert region to a table.
8467 The region goes from BEG0 to END0, but these borders will be moved
8468 slightly, to make sure a beginning of line in the first line is included.
8470 SEPARATOR specifies the field separator in the lines. It can have the
8471 following values:
8473 '(4) Use the comma as a field separator
8474 '(16) Use a TAB as field separator
8475 integer When a number, use that many spaces as field separator
8476 nil When nil, the command tries to be smart and figure out the
8477 separator in the following way:
8478 - when each line contains a TAB, assume TAB-separated material
8479 - when each line contains a comme, assume CSV material
8480 - else, assume one or more SPACE charcters as separator."
8481 (interactive "rP")
8482 (let* ((beg (min beg0 end0))
8483 (end (max beg0 end0))
8485 (goto-char beg)
8486 (beginning-of-line 1)
8487 (setq beg (move-marker (make-marker) (point)))
8488 (goto-char end)
8489 (if (bolp) (backward-char 1) (end-of-line 1))
8490 (setq end (move-marker (make-marker) (point)))
8491 ;; Get the right field separator
8492 (unless separator
8493 (goto-char beg)
8494 (setq separator
8495 (cond
8496 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8497 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8498 (t 1))))
8499 (setq re (cond
8500 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8501 ((equal separator '(16)) "^\\|\t")
8502 ((integerp separator)
8503 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8504 (t (error "This should not happen"))))
8505 (goto-char beg)
8506 (while (re-search-forward re end t)
8507 (replace-match "| " t t))
8508 (goto-char beg)
8509 (insert " ")
8510 (org-table-align)))
8512 (defun org-table-import (file arg)
8513 "Import FILE as a table.
8514 The file is assumed to be tab-separated. Such files can be produced by most
8515 spreadsheet and database applications. If no tabs (at least one per line)
8516 are found, lines will be split on whitespace into fields."
8517 (interactive "f\nP")
8518 (or (bolp) (newline))
8519 (let ((beg (point))
8520 (pm (point-max)))
8521 (insert-file-contents file)
8522 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8524 (defun org-table-export ()
8525 "Export table as a tab-separated file.
8526 Such a file can be imported into a spreadsheet program like Excel."
8527 (interactive)
8528 (let* ((beg (org-table-begin))
8529 (end (org-table-end))
8530 (table (buffer-substring beg end))
8531 (file (read-file-name "Export table to: "))
8532 buf)
8533 (unless (or (not (file-exists-p file))
8534 (y-or-n-p (format "Overwrite file %s? " file)))
8535 (error "Abort"))
8536 (with-current-buffer (find-file-noselect file)
8537 (setq buf (current-buffer))
8538 (erase-buffer)
8539 (fundamental-mode)
8540 (insert table)
8541 (goto-char (point-min))
8542 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8543 (replace-match "" t t)
8544 (end-of-line 1))
8545 (goto-char (point-min))
8546 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8547 (replace-match "" t t)
8548 (goto-char (min (1+ (point)) (point-max))))
8549 (goto-char (point-min))
8550 (while (re-search-forward "^-[-+]*$" nil t)
8551 (replace-match "")
8552 (if (looking-at "\n")
8553 (delete-char 1)))
8554 (goto-char (point-min))
8555 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8556 (replace-match "\t" t t))
8557 (save-buffer))
8558 (kill-buffer buf)))
8560 (defvar org-table-aligned-begin-marker (make-marker)
8561 "Marker at the beginning of the table last aligned.
8562 Used to check if cursor still is in that table, to minimize realignment.")
8563 (defvar org-table-aligned-end-marker (make-marker)
8564 "Marker at the end of the table last aligned.
8565 Used to check if cursor still is in that table, to minimize realignment.")
8566 (defvar org-table-last-alignment nil
8567 "List of flags for flushright alignment, from the last re-alignment.
8568 This is being used to correctly align a single field after TAB or RET.")
8569 (defvar org-table-last-column-widths nil
8570 "List of max width of fields in each column.
8571 This is being used to correctly align a single field after TAB or RET.")
8572 (defvar org-table-overlay-coordinates nil
8573 "Overlay coordinates after each align of a table.")
8574 (make-variable-buffer-local 'org-table-overlay-coordinates)
8576 (defvar org-last-recalc-line nil)
8577 (defconst org-narrow-column-arrow "=>"
8578 "Used as display property in narrowed table columns.")
8580 (defun org-table-align ()
8581 "Align the table at point by aligning all vertical bars."
8582 (interactive)
8583 (let* (
8584 ;; Limits of table
8585 (beg (org-table-begin))
8586 (end (org-table-end))
8587 ;; Current cursor position
8588 (linepos (org-current-line))
8589 (colpos (org-table-current-column))
8590 (winstart (window-start))
8591 (winstartline (org-current-line (min winstart (1- (point-max)))))
8592 lines (new "") lengths l typenums ty fields maxfields i
8593 column
8594 (indent "") cnt frac
8595 rfmt hfmt
8596 (spaces '(1 . 1))
8597 (sp1 (car spaces))
8598 (sp2 (cdr spaces))
8599 (rfmt1 (concat
8600 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8601 (hfmt1 (concat
8602 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8603 emptystrings links dates emph narrow fmax f1 len c e)
8604 (untabify beg end)
8605 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8606 ;; Check if we have links or dates
8607 (goto-char beg)
8608 (setq links (re-search-forward org-bracket-link-regexp end t))
8609 (goto-char beg)
8610 (setq emph (and org-hide-emphasis-markers
8611 (re-search-forward org-emph-re end t)))
8612 (goto-char beg)
8613 (setq dates (and org-display-custom-times
8614 (re-search-forward org-ts-regexp-both end t)))
8615 ;; Make sure the link properties are right
8616 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8617 ;; Make sure the date properties are right
8618 (when dates (goto-char beg) (while (org-activate-dates end)))
8619 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8621 ;; Check if we are narrowing any columns
8622 (goto-char beg)
8623 (setq narrow (and org-format-transports-properties-p
8624 (re-search-forward "<[0-9]+>" end t)))
8625 ;; Get the rows
8626 (setq lines (org-split-string
8627 (buffer-substring beg end) "\n"))
8628 ;; Store the indentation of the first line
8629 (if (string-match "^ *" (car lines))
8630 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8631 ;; Mark the hlines by setting the corresponding element to nil
8632 ;; At the same time, we remove trailing space.
8633 (setq lines (mapcar (lambda (l)
8634 (if (string-match "^ *|-" l)
8636 (if (string-match "[ \t]+$" l)
8637 (substring l 0 (match-beginning 0))
8638 l)))
8639 lines))
8640 ;; Get the data fields by splitting the lines.
8641 (setq fields (mapcar
8642 (lambda (l)
8643 (org-split-string l " *| *"))
8644 (delq nil (copy-sequence lines))))
8645 ;; How many fields in the longest line?
8646 (condition-case nil
8647 (setq maxfields (apply 'max (mapcar 'length fields)))
8648 (error
8649 (kill-region beg end)
8650 (org-table-create org-table-default-size)
8651 (error "Empty table - created default table")))
8652 ;; A list of empty strings to fill any short rows on output
8653 (setq emptystrings (make-list maxfields ""))
8654 ;; Check for special formatting.
8655 (setq i -1)
8656 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8657 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8658 ;; Check if there is an explicit width specified
8659 (when narrow
8660 (setq c column fmax nil)
8661 (while c
8662 (setq e (pop c))
8663 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8664 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8665 ;; Find fields that are wider than fmax, and shorten them
8666 (when fmax
8667 (loop for xx in column do
8668 (when (and (stringp xx)
8669 (> (org-string-width xx) fmax))
8670 (org-add-props xx nil
8671 'help-echo
8672 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8673 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8674 (unless (> f1 1)
8675 (error "Cannot narrow field starting with wide link \"%s\""
8676 (match-string 0 xx)))
8677 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8678 (add-text-properties (- f1 2) f1
8679 (list 'display org-narrow-column-arrow)
8680 xx)))))
8681 ;; Get the maximum width for each column
8682 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8683 ;; Get the fraction of numbers, to decide about alignment of the column
8684 (setq cnt 0 frac 0.0)
8685 (loop for x in column do
8686 (if (equal x "")
8688 (setq frac ( / (+ (* frac cnt)
8689 (if (string-match org-table-number-regexp x) 1 0))
8690 (setq cnt (1+ cnt))))))
8691 (push (>= frac org-table-number-fraction) typenums))
8692 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8694 ;; Store the alignment of this table, for later editing of single fields
8695 (setq org-table-last-alignment typenums
8696 org-table-last-column-widths lengths)
8698 ;; With invisible characters, `format' does not get the field width right
8699 ;; So we need to make these fields wide by hand.
8700 (when (or links emph)
8701 (loop for i from 0 upto (1- maxfields) do
8702 (setq len (nth i lengths))
8703 (loop for j from 0 upto (1- (length fields)) do
8704 (setq c (nthcdr i (car (nthcdr j fields))))
8705 (if (and (stringp (car c))
8706 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8707 ; (string-match org-bracket-link-regexp (car c))
8708 (< (org-string-width (car c)) len))
8709 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8711 ;; Compute the formats needed for output of the table
8712 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8713 (while (setq l (pop lengths))
8714 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8715 (setq rfmt (concat rfmt (format rfmt1 ty l))
8716 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8717 (setq rfmt (concat rfmt "\n")
8718 hfmt (concat (substring hfmt 0 -1) "|\n"))
8720 (setq new (mapconcat
8721 (lambda (l)
8722 (if l (apply 'format rfmt
8723 (append (pop fields) emptystrings))
8724 hfmt))
8725 lines ""))
8726 ;; Replace the old one
8727 (delete-region beg end)
8728 (move-marker end nil)
8729 (move-marker org-table-aligned-begin-marker (point))
8730 (insert new)
8731 (move-marker org-table-aligned-end-marker (point))
8732 (when (and orgtbl-mode (not (org-mode-p)))
8733 (goto-char org-table-aligned-begin-marker)
8734 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8735 ;; Try to move to the old location
8736 (goto-line winstartline)
8737 (setq winstart (point-at-bol))
8738 (goto-line linepos)
8739 (set-window-start (selected-window) winstart 'noforce)
8740 (org-table-goto-column colpos)
8741 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8742 (setq org-table-may-need-update nil)
8745 (defun org-string-width (s)
8746 "Compute width of string, ignoring invisible characters.
8747 This ignores character with invisibility property `org-link', and also
8748 characters with property `org-cwidth', because these will become invisible
8749 upon the next fontification round."
8750 (let (b l)
8751 (when (or (eq t buffer-invisibility-spec)
8752 (assq 'org-link buffer-invisibility-spec))
8753 (while (setq b (text-property-any 0 (length s)
8754 'invisible 'org-link s))
8755 (setq s (concat (substring s 0 b)
8756 (substring s (or (next-single-property-change
8757 b 'invisible s) (length s)))))))
8758 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8759 (setq s (concat (substring s 0 b)
8760 (substring s (or (next-single-property-change
8761 b 'org-cwidth s) (length s))))))
8762 (setq l (string-width s) b -1)
8763 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8764 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8767 (defun org-table-begin (&optional table-type)
8768 "Find the beginning of the table and return its position.
8769 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8770 (save-excursion
8771 (if (not (re-search-backward
8772 (if table-type org-table-any-border-regexp
8773 org-table-border-regexp)
8774 nil t))
8775 (progn (goto-char (point-min)) (point))
8776 (goto-char (match-beginning 0))
8777 (beginning-of-line 2)
8778 (point))))
8780 (defun org-table-end (&optional table-type)
8781 "Find the end of the table and return its position.
8782 With argument TABLE-TYPE, go to the end of a table.el-type table."
8783 (save-excursion
8784 (if (not (re-search-forward
8785 (if table-type org-table-any-border-regexp
8786 org-table-border-regexp)
8787 nil t))
8788 (goto-char (point-max))
8789 (goto-char (match-beginning 0)))
8790 (point-marker)))
8792 (defun org-table-justify-field-maybe (&optional new)
8793 "Justify the current field, text to left, number to right.
8794 Optional argument NEW may specify text to replace the current field content."
8795 (cond
8796 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8797 ((org-at-table-hline-p))
8798 ((and (not new)
8799 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8800 (current-buffer)))
8801 (< (point) org-table-aligned-begin-marker)
8802 (>= (point) org-table-aligned-end-marker)))
8803 ;; This is not the same table, force a full re-align
8804 (setq org-table-may-need-update t))
8805 (t ;; realign the current field, based on previous full realign
8806 (let* ((pos (point)) s
8807 (col (org-table-current-column))
8808 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8809 l f n o e)
8810 (when (> col 0)
8811 (skip-chars-backward "^|\n")
8812 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8813 (progn
8814 (setq s (match-string 1)
8815 o (match-string 0)
8816 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8817 e (not (= (match-beginning 2) (match-end 2))))
8818 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8819 l (if e "|" (setq org-table-may-need-update t) ""))
8820 n (format f s))
8821 (if new
8822 (if (<= (length new) l) ;; FIXME: length -> str-width?
8823 (setq n (format f new))
8824 (setq n (concat new "|") org-table-may-need-update t)))
8825 (or (equal n o)
8826 (let (org-table-may-need-update)
8827 (replace-match n t t))))
8828 (setq org-table-may-need-update t))
8829 (goto-char pos))))))
8831 (defun org-table-next-field ()
8832 "Go to the next field in the current table, creating new lines as needed.
8833 Before doing so, re-align the table if necessary."
8834 (interactive)
8835 (org-table-maybe-eval-formula)
8836 (org-table-maybe-recalculate-line)
8837 (if (and org-table-automatic-realign
8838 org-table-may-need-update)
8839 (org-table-align))
8840 (let ((end (org-table-end)))
8841 (if (org-at-table-hline-p)
8842 (end-of-line 1))
8843 (condition-case nil
8844 (progn
8845 (re-search-forward "|" end)
8846 (if (looking-at "[ \t]*$")
8847 (re-search-forward "|" end))
8848 (if (and (looking-at "-")
8849 org-table-tab-jumps-over-hlines
8850 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8851 (goto-char (match-beginning 1)))
8852 (if (looking-at "-")
8853 (progn
8854 (beginning-of-line 0)
8855 (org-table-insert-row 'below))
8856 (if (looking-at " ") (forward-char 1))))
8857 (error
8858 (org-table-insert-row 'below)))))
8860 (defun org-table-previous-field ()
8861 "Go to the previous field in the table.
8862 Before doing so, re-align the table if necessary."
8863 (interactive)
8864 (org-table-justify-field-maybe)
8865 (org-table-maybe-recalculate-line)
8866 (if (and org-table-automatic-realign
8867 org-table-may-need-update)
8868 (org-table-align))
8869 (if (org-at-table-hline-p)
8870 (end-of-line 1))
8871 (re-search-backward "|" (org-table-begin))
8872 (re-search-backward "|" (org-table-begin))
8873 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8874 (re-search-backward "|" (org-table-begin)))
8875 (if (looking-at "| ?")
8876 (goto-char (match-end 0))))
8878 (defun org-table-next-row ()
8879 "Go to the next row (same column) in the current table.
8880 Before doing so, re-align the table if necessary."
8881 (interactive)
8882 (org-table-maybe-eval-formula)
8883 (org-table-maybe-recalculate-line)
8884 (if (or (looking-at "[ \t]*$")
8885 (save-excursion (skip-chars-backward " \t") (bolp)))
8886 (newline)
8887 (if (and org-table-automatic-realign
8888 org-table-may-need-update)
8889 (org-table-align))
8890 (let ((col (org-table-current-column)))
8891 (beginning-of-line 2)
8892 (if (or (not (org-at-table-p))
8893 (org-at-table-hline-p))
8894 (progn
8895 (beginning-of-line 0)
8896 (org-table-insert-row 'below)))
8897 (org-table-goto-column col)
8898 (skip-chars-backward "^|\n\r")
8899 (if (looking-at " ") (forward-char 1)))))
8901 (defun org-table-copy-down (n)
8902 "Copy a field down in the current column.
8903 If the field at the cursor is empty, copy into it the content of the nearest
8904 non-empty field above. With argument N, use the Nth non-empty field.
8905 If the current field is not empty, it is copied down to the next row, and
8906 the cursor is moved with it. Therefore, repeating this command causes the
8907 column to be filled row-by-row.
8908 If the variable `org-table-copy-increment' is non-nil and the field is an
8909 integer or a timestamp, it will be incremented while copying. In the case of
8910 a timestamp, if the cursor is on the year, change the year. If it is on the
8911 month or the day, change that. Point will stay on the current date field
8912 in order to easily repeat the interval."
8913 (interactive "p")
8914 (let* ((colpos (org-table-current-column))
8915 (col (current-column))
8916 (field (org-table-get-field))
8917 (non-empty (string-match "[^ \t]" field))
8918 (beg (org-table-begin))
8919 txt)
8920 (org-table-check-inside-data-field)
8921 (if non-empty
8922 (progn
8923 (setq txt (org-trim field))
8924 (org-table-next-row)
8925 (org-table-blank-field))
8926 (save-excursion
8927 (setq txt
8928 (catch 'exit
8929 (while (progn (beginning-of-line 1)
8930 (re-search-backward org-table-dataline-regexp
8931 beg t))
8932 (org-table-goto-column colpos t)
8933 (if (and (looking-at
8934 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8935 (= (setq n (1- n)) 0))
8936 (throw 'exit (match-string 1))))))))
8937 (if txt
8938 (progn
8939 (if (and org-table-copy-increment
8940 (string-match "^[0-9]+$" txt))
8941 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8942 (insert txt)
8943 (move-to-column col)
8944 (if (and org-table-copy-increment (org-at-timestamp-p t))
8945 (org-timestamp-up 1)
8946 (org-table-maybe-recalculate-line))
8947 (org-table-align)
8948 (move-to-column col))
8949 (error "No non-empty field found"))))
8951 (defun org-table-check-inside-data-field ()
8952 "Is point inside a table data field?
8953 I.e. not on a hline or before the first or after the last column?
8954 This actually throws an error, so it aborts the current command."
8955 (if (or (not (org-at-table-p))
8956 (= (org-table-current-column) 0)
8957 (org-at-table-hline-p)
8958 (looking-at "[ \t]*$"))
8959 (error "Not in table data field")))
8961 (defvar org-table-clip nil
8962 "Clipboard for table regions.")
8964 (defun org-table-blank-field ()
8965 "Blank the current table field or active region."
8966 (interactive)
8967 (org-table-check-inside-data-field)
8968 (if (and (interactive-p) (org-region-active-p))
8969 (let (org-table-clip)
8970 (org-table-cut-region (region-beginning) (region-end)))
8971 (skip-chars-backward "^|")
8972 (backward-char 1)
8973 (if (looking-at "|[^|\n]+")
8974 (let* ((pos (match-beginning 0))
8975 (match (match-string 0))
8976 (len (org-string-width match)))
8977 (replace-match (concat "|" (make-string (1- len) ?\ )))
8978 (goto-char (+ 2 pos))
8979 (substring match 1)))))
8981 (defun org-table-get-field (&optional n replace)
8982 "Return the value of the field in column N of current row.
8983 N defaults to current field.
8984 If REPLACE is a string, replace field with this value. The return value
8985 is always the old value."
8986 (and n (org-table-goto-column n))
8987 (skip-chars-backward "^|\n")
8988 (backward-char 1)
8989 (if (looking-at "|[^|\r\n]*")
8990 (let* ((pos (match-beginning 0))
8991 (val (buffer-substring (1+ pos) (match-end 0))))
8992 (if replace
8993 (replace-match (concat "|" replace) t t))
8994 (goto-char (min (point-at-eol) (+ 2 pos)))
8995 val)
8996 (forward-char 1) ""))
8998 (defun org-table-field-info (arg)
8999 "Show info about the current field, and highlight any reference at point."
9000 (interactive "P")
9001 (org-table-get-specials)
9002 (save-excursion
9003 (let* ((pos (point))
9004 (col (org-table-current-column))
9005 (cname (car (rassoc (int-to-string col) org-table-column-names)))
9006 (name (car (rassoc (list (org-current-line) col)
9007 org-table-named-field-locations)))
9008 (eql (org-table-get-stored-formulas))
9009 (dline (org-table-current-dline))
9010 (ref (format "@%d$%d" dline col))
9011 (ref1 (org-table-convert-refs-to-an ref))
9012 (fequation (or (assoc name eql) (assoc ref eql)))
9013 (cequation (assoc (int-to-string col) eql))
9014 (eqn (or fequation cequation)))
9015 (goto-char pos)
9016 (condition-case nil
9017 (org-table-show-reference 'local)
9018 (error nil))
9019 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
9020 dline col
9021 (if cname (concat " or $" cname) "")
9022 dline col ref1
9023 (if name (concat " or $" name) "")
9024 ;; FIXME: formula info not correct if special table line
9025 (if eqn
9026 (concat ", formula: "
9027 (org-table-formula-to-user
9028 (concat
9029 (if (string-match "^[$@]"(car eqn)) "" "$")
9030 (car eqn) "=" (cdr eqn))))
9031 "")))))
9033 (defun org-table-current-column ()
9034 "Find out which column we are in.
9035 When called interactively, column is also displayed in echo area."
9036 (interactive)
9037 (if (interactive-p) (org-table-check-inside-data-field))
9038 (save-excursion
9039 (let ((cnt 0) (pos (point)))
9040 (beginning-of-line 1)
9041 (while (search-forward "|" pos t)
9042 (setq cnt (1+ cnt)))
9043 (if (interactive-p) (message "This is table column %d" cnt))
9044 cnt)))
9046 (defun org-table-current-dline ()
9047 "Find out what table data line we are in.
9048 Only datalins count for this."
9049 (interactive)
9050 (if (interactive-p) (org-table-check-inside-data-field))
9051 (save-excursion
9052 (let ((cnt 0) (pos (point)))
9053 (goto-char (org-table-begin))
9054 (while (<= (point) pos)
9055 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9056 (beginning-of-line 2))
9057 (if (interactive-p) (message "This is table line %d" cnt))
9058 cnt)))
9060 (defun org-table-goto-column (n &optional on-delim force)
9061 "Move the cursor to the Nth column in the current table line.
9062 With optional argument ON-DELIM, stop with point before the left delimiter
9063 of the field.
9064 If there are less than N fields, just go to after the last delimiter.
9065 However, when FORCE is non-nil, create new columns if necessary."
9066 (interactive "p")
9067 (let ((pos (point-at-eol)))
9068 (beginning-of-line 1)
9069 (when (> n 0)
9070 (while (and (> (setq n (1- n)) -1)
9071 (or (search-forward "|" pos t)
9072 (and force
9073 (progn (end-of-line 1)
9074 (skip-chars-backward "^|")
9075 (insert " | "))))))
9076 ; (backward-char 2) t)))))
9077 (when (and force (not (looking-at ".*|")))
9078 (save-excursion (end-of-line 1) (insert " | ")))
9079 (if on-delim
9080 (backward-char 1)
9081 (if (looking-at " ") (forward-char 1))))))
9083 (defun org-at-table-p (&optional table-type)
9084 "Return t if the cursor is inside an org-type table.
9085 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9086 (if org-enable-table-editor
9087 (save-excursion
9088 (beginning-of-line 1)
9089 (looking-at (if table-type org-table-any-line-regexp
9090 org-table-line-regexp)))
9091 nil))
9093 (defun org-at-table.el-p ()
9094 "Return t if and only if we are at a table.el table."
9095 (and (org-at-table-p 'any)
9096 (save-excursion
9097 (goto-char (org-table-begin 'any))
9098 (looking-at org-table1-hline-regexp))))
9100 (defun org-table-recognize-table.el ()
9101 "If there is a table.el table nearby, recognize it and move into it."
9102 (if org-table-tab-recognizes-table.el
9103 (if (org-at-table.el-p)
9104 (progn
9105 (beginning-of-line 1)
9106 (if (looking-at org-table-dataline-regexp)
9108 (if (looking-at org-table1-hline-regexp)
9109 (progn
9110 (beginning-of-line 2)
9111 (if (looking-at org-table-any-border-regexp)
9112 (beginning-of-line -1)))))
9113 (if (re-search-forward "|" (org-table-end t) t)
9114 (progn
9115 (require 'table)
9116 (if (table--at-cell-p (point))
9118 (message "recognizing table.el table...")
9119 (table-recognize-table)
9120 (message "recognizing table.el table...done")))
9121 (error "This should not happen..."))
9123 nil)
9124 nil))
9126 (defun org-at-table-hline-p ()
9127 "Return t if the cursor is inside a hline in a table."
9128 (if org-enable-table-editor
9129 (save-excursion
9130 (beginning-of-line 1)
9131 (looking-at org-table-hline-regexp))
9132 nil))
9134 (defun org-table-insert-column ()
9135 "Insert a new column into the table."
9136 (interactive)
9137 (if (not (org-at-table-p))
9138 (error "Not at a table"))
9139 (org-table-find-dataline)
9140 (let* ((col (max 1 (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 (insert "| "))
9152 (beginning-of-line 2))
9153 (move-marker end nil)
9154 (goto-line linepos)
9155 (org-table-goto-column colpos)
9156 (org-table-align)
9157 (org-table-fix-formulas "$" nil (1- col) 1)))
9159 (defun org-table-find-dataline ()
9160 "Find a dataline in the current table, which is needed for column commands."
9161 (if (and (org-at-table-p)
9162 (not (org-at-table-hline-p)))
9164 (let ((col (current-column))
9165 (end (org-table-end)))
9166 (move-to-column col)
9167 (while (and (< (point) end)
9168 (or (not (= (current-column) col))
9169 (org-at-table-hline-p)))
9170 (beginning-of-line 2)
9171 (move-to-column col))
9172 (if (and (org-at-table-p)
9173 (not (org-at-table-hline-p)))
9175 (error
9176 "Please position cursor in a data line for column operations")))))
9178 (defun org-table-delete-column ()
9179 "Delete a column from the table."
9180 (interactive)
9181 (if (not (org-at-table-p))
9182 (error "Not at a table"))
9183 (org-table-find-dataline)
9184 (org-table-check-inside-data-field)
9185 (let* ((col (org-table-current-column))
9186 (beg (org-table-begin))
9187 (end (org-table-end))
9188 ;; Current cursor position
9189 (linepos (org-current-line))
9190 (colpos col))
9191 (goto-char beg)
9192 (while (< (point) end)
9193 (if (org-at-table-hline-p)
9195 (org-table-goto-column col t)
9196 (and (looking-at "|[^|\n]+|")
9197 (replace-match "|")))
9198 (beginning-of-line 2))
9199 (move-marker end nil)
9200 (goto-line linepos)
9201 (org-table-goto-column colpos)
9202 (org-table-align)
9203 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9204 col -1 col)))
9206 (defun org-table-move-column-right ()
9207 "Move column to the right."
9208 (interactive)
9209 (org-table-move-column nil))
9210 (defun org-table-move-column-left ()
9211 "Move column to the left."
9212 (interactive)
9213 (org-table-move-column 'left))
9215 (defun org-table-move-column (&optional left)
9216 "Move the current column to the right. With arg LEFT, move to the left."
9217 (interactive "P")
9218 (if (not (org-at-table-p))
9219 (error "Not at a table"))
9220 (org-table-find-dataline)
9221 (org-table-check-inside-data-field)
9222 (let* ((col (org-table-current-column))
9223 (col1 (if left (1- col) col))
9224 (beg (org-table-begin))
9225 (end (org-table-end))
9226 ;; Current cursor position
9227 (linepos (org-current-line))
9228 (colpos (if left (1- col) (1+ col))))
9229 (if (and left (= col 1))
9230 (error "Cannot move column further left"))
9231 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9232 (error "Cannot move column further right"))
9233 (goto-char beg)
9234 (while (< (point) end)
9235 (if (org-at-table-hline-p)
9237 (org-table-goto-column col1 t)
9238 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9239 (replace-match "|\\2|\\1|")))
9240 (beginning-of-line 2))
9241 (move-marker end nil)
9242 (goto-line linepos)
9243 (org-table-goto-column colpos)
9244 (org-table-align)
9245 (org-table-fix-formulas
9246 "$" (list (cons (number-to-string col) (number-to-string colpos))
9247 (cons (number-to-string colpos) (number-to-string col))))))
9249 (defun org-table-move-row-down ()
9250 "Move table row down."
9251 (interactive)
9252 (org-table-move-row nil))
9253 (defun org-table-move-row-up ()
9254 "Move table row up."
9255 (interactive)
9256 (org-table-move-row 'up))
9258 (defun org-table-move-row (&optional up)
9259 "Move the current table line down. With arg UP, move it up."
9260 (interactive "P")
9261 (let* ((col (current-column))
9262 (pos (point))
9263 (hline1p (save-excursion (beginning-of-line 1)
9264 (looking-at org-table-hline-regexp)))
9265 (dline1 (org-table-current-dline))
9266 (dline2 (+ dline1 (if up -1 1)))
9267 (tonew (if up 0 2))
9268 txt hline2p)
9269 (beginning-of-line tonew)
9270 (unless (org-at-table-p)
9271 (goto-char pos)
9272 (error "Cannot move row further"))
9273 (setq hline2p (looking-at org-table-hline-regexp))
9274 (goto-char pos)
9275 (beginning-of-line 1)
9276 (setq pos (point))
9277 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9278 (delete-region (point) (1+ (point-at-eol)))
9279 (beginning-of-line tonew)
9280 (insert txt)
9281 (beginning-of-line 0)
9282 (move-to-column col)
9283 (unless (or hline1p hline2p)
9284 (org-table-fix-formulas
9285 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9286 (cons (number-to-string dline2) (number-to-string dline1)))))))
9288 (defun org-table-insert-row (&optional arg)
9289 "Insert a new row above the current line into the table.
9290 With prefix ARG, insert below the current line."
9291 (interactive "P")
9292 (if (not (org-at-table-p))
9293 (error "Not at a table"))
9294 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9295 (new (org-table-clean-line line)))
9296 ;; Fix the first field if necessary
9297 (if (string-match "^[ \t]*| *[#$] *|" line)
9298 (setq new (replace-match (match-string 0 line) t t new)))
9299 (beginning-of-line (if arg 2 1))
9300 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9301 (beginning-of-line 0)
9302 (re-search-forward "| ?" (point-at-eol) t)
9303 (and (or org-table-may-need-update org-table-overlay-coordinates)
9304 (org-table-align))
9305 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9307 (defun org-table-insert-hline (&optional above)
9308 "Insert a horizontal-line below the current line into the table.
9309 With prefix ABOVE, insert above the current line."
9310 (interactive "P")
9311 (if (not (org-at-table-p))
9312 (error "Not at a table"))
9313 (let ((line (org-table-clean-line
9314 (buffer-substring (point-at-bol) (point-at-eol))))
9315 (col (current-column)))
9316 (while (string-match "|\\( +\\)|" line)
9317 (setq line (replace-match
9318 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9319 ?-) "|") t t line)))
9320 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9321 (beginning-of-line (if above 1 2))
9322 (insert line "\n")
9323 (beginning-of-line (if above 1 -1))
9324 (move-to-column col)
9325 (and org-table-overlay-coordinates (org-table-align))))
9327 (defun org-table-hline-and-move (&optional same-column)
9328 "Insert a hline and move to the row below that line."
9329 (interactive "P")
9330 (let ((col (org-table-current-column)))
9331 (org-table-maybe-eval-formula)
9332 (org-table-maybe-recalculate-line)
9333 (org-table-insert-hline)
9334 (end-of-line 2)
9335 (if (looking-at "\n[ \t]*|-")
9336 (progn (insert "\n|") (org-table-align))
9337 (org-table-next-field))
9338 (if same-column (org-table-goto-column col))))
9340 (defun org-table-clean-line (s)
9341 "Convert a table line S into a string with only \"|\" and space.
9342 In particular, this does handle wide and invisible characters."
9343 (if (string-match "^[ \t]*|-" s)
9344 ;; It's a hline, just map the characters
9345 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9346 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9347 (setq s (replace-match
9348 (concat "|" (make-string (org-string-width (match-string 1 s))
9349 ?\ ) "|")
9350 t t s)))
9353 (defun org-table-kill-row ()
9354 "Delete the current row or horizontal line from the table."
9355 (interactive)
9356 (if (not (org-at-table-p))
9357 (error "Not at a table"))
9358 (let ((col (current-column))
9359 (dline (org-table-current-dline)))
9360 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9361 (if (not (org-at-table-p)) (beginning-of-line 0))
9362 (move-to-column col)
9363 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9364 dline -1 dline)))
9366 (defun org-table-sort-lines (with-case &optional sorting-type)
9367 "Sort table lines according to the column at point.
9369 The position of point indicates the column to be used for
9370 sorting, and the range of lines is the range between the nearest
9371 horizontal separator lines, or the entire table of no such lines
9372 exist. If point is before the first column, you will be prompted
9373 for the sorting column. If there is an active region, the mark
9374 specifies the first line and the sorting column, while point
9375 should be in the last line to be included into the sorting.
9377 The command then prompts for the sorting type which can be
9378 alphabetically, numerically, or by time (as given in a time stamp
9379 in the field). Sorting in reverse order is also possible.
9381 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9383 If SORTING-TYPE is specified when this function is called from a Lisp
9384 program, no prompting will take place. SORTING-TYPE must be a character,
9385 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9386 should be done in reverse order."
9387 (interactive "P")
9388 (let* ((thisline (org-current-line))
9389 (thiscol (org-table-current-column))
9390 beg end bcol ecol tend tbeg column lns pos)
9391 (when (equal thiscol 0)
9392 (if (interactive-p)
9393 (setq thiscol
9394 (string-to-number
9395 (read-string "Use column N for sorting: ")))
9396 (setq thiscol 1))
9397 (org-table-goto-column thiscol))
9398 (org-table-check-inside-data-field)
9399 (if (org-region-active-p)
9400 (progn
9401 (setq beg (region-beginning) end (region-end))
9402 (goto-char beg)
9403 (setq column (org-table-current-column)
9404 beg (point-at-bol))
9405 (goto-char end)
9406 (setq end (point-at-bol 2)))
9407 (setq column (org-table-current-column)
9408 pos (point)
9409 tbeg (org-table-begin)
9410 tend (org-table-end))
9411 (if (re-search-backward org-table-hline-regexp tbeg t)
9412 (setq beg (point-at-bol 2))
9413 (goto-char tbeg)
9414 (setq beg (point-at-bol 1)))
9415 (goto-char pos)
9416 (if (re-search-forward org-table-hline-regexp tend t)
9417 (setq end (point-at-bol 1))
9418 (goto-char tend)
9419 (setq end (point-at-bol))))
9420 (setq beg (move-marker (make-marker) beg)
9421 end (move-marker (make-marker) end))
9422 (untabify beg end)
9423 (goto-char beg)
9424 (org-table-goto-column column)
9425 (skip-chars-backward "^|")
9426 (setq bcol (current-column))
9427 (org-table-goto-column (1+ column))
9428 (skip-chars-backward "^|")
9429 (setq ecol (1- (current-column)))
9430 (org-table-goto-column column)
9431 (setq lns (mapcar (lambda(x) (cons
9432 (org-sort-remove-invisible
9433 (nth (1- column)
9434 (org-split-string x "[ \t]*|[ \t]*")))
9436 (org-split-string (buffer-substring beg end) "\n")))
9437 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9438 (delete-region beg end)
9439 (move-marker beg nil)
9440 (move-marker end nil)
9441 (insert (mapconcat 'cdr lns "\n") "\n")
9442 (goto-line thisline)
9443 (org-table-goto-column thiscol)
9444 (message "%d lines sorted, based on column %d" (length lns) column)))
9446 ;; FIXME: maybe we will not need this? Table sorting is broken....
9447 (defun org-sort-remove-invisible (s)
9448 (remove-text-properties 0 (length s) org-rm-props s)
9449 (while (string-match org-bracket-link-regexp s)
9450 (setq s (replace-match (if (match-end 2)
9451 (match-string 3 s)
9452 (match-string 1 s)) t t s)))
9455 (defun org-table-cut-region (beg end)
9456 "Copy region in table to the clipboard and blank all relevant fields."
9457 (interactive "r")
9458 (org-table-copy-region beg end 'cut))
9460 (defun org-table-copy-region (beg end &optional cut)
9461 "Copy rectangular region in table to clipboard.
9462 A special clipboard is used which can only be accessed
9463 with `org-table-paste-rectangle'."
9464 (interactive "rP")
9465 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9466 region cols
9467 (rpl (if cut " " nil)))
9468 (goto-char beg)
9469 (org-table-check-inside-data-field)
9470 (setq l01 (org-current-line)
9471 c01 (org-table-current-column))
9472 (goto-char end)
9473 (org-table-check-inside-data-field)
9474 (setq l02 (org-current-line)
9475 c02 (org-table-current-column))
9476 (setq l1 (min l01 l02) l2 (max l01 l02)
9477 c1 (min c01 c02) c2 (max c01 c02))
9478 (catch 'exit
9479 (while t
9480 (catch 'nextline
9481 (if (> l1 l2) (throw 'exit t))
9482 (goto-line l1)
9483 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9484 (setq cols nil ic1 c1 ic2 c2)
9485 (while (< ic1 (1+ ic2))
9486 (push (org-table-get-field ic1 rpl) cols)
9487 (setq ic1 (1+ ic1)))
9488 (push (nreverse cols) region)
9489 (setq l1 (1+ l1)))))
9490 (setq org-table-clip (nreverse region))
9491 (if cut (org-table-align))
9492 org-table-clip))
9494 (defun org-table-paste-rectangle ()
9495 "Paste a rectangular region into a table.
9496 The upper right corner ends up in the current field. All involved fields
9497 will be overwritten. If the rectangle does not fit into the present table,
9498 the table is enlarged as needed. The process ignores horizontal separator
9499 lines."
9500 (interactive)
9501 (unless (and org-table-clip (listp org-table-clip))
9502 (error "First cut/copy a region to paste!"))
9503 (org-table-check-inside-data-field)
9504 (let* ((clip org-table-clip)
9505 (line (org-current-line))
9506 (col (org-table-current-column))
9507 (org-enable-table-editor t)
9508 (org-table-automatic-realign nil)
9509 c cols field)
9510 (while (setq cols (pop clip))
9511 (while (org-at-table-hline-p) (beginning-of-line 2))
9512 (if (not (org-at-table-p))
9513 (progn (end-of-line 0) (org-table-next-field)))
9514 (setq c col)
9515 (while (setq field (pop cols))
9516 (org-table-goto-column c nil 'force)
9517 (org-table-get-field nil field)
9518 (setq c (1+ c)))
9519 (beginning-of-line 2))
9520 (goto-line line)
9521 (org-table-goto-column col)
9522 (org-table-align)))
9524 (defun org-table-convert ()
9525 "Convert from `org-mode' table to table.el and back.
9526 Obviously, this only works within limits. When an Org-mode table is
9527 converted to table.el, all horizontal separator lines get lost, because
9528 table.el uses these as cell boundaries and has no notion of horizontal lines.
9529 A table.el table can be converted to an Org-mode table only if it does not
9530 do row or column spanning. Multiline cells will become multiple cells.
9531 Beware, Org-mode does not test if the table can be successfully converted - it
9532 blindly applies a recipe that works for simple tables."
9533 (interactive)
9534 (require 'table)
9535 (if (org-at-table.el-p)
9536 ;; convert to Org-mode table
9537 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9538 (end (move-marker (make-marker) (org-table-end t))))
9539 (table-unrecognize-region beg end)
9540 (goto-char beg)
9541 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9542 (replace-match ""))
9543 (goto-char beg))
9544 (if (org-at-table-p)
9545 ;; convert to table.el table
9546 (let ((beg (move-marker (make-marker) (org-table-begin)))
9547 (end (move-marker (make-marker) (org-table-end))))
9548 ;; first, get rid of all horizontal lines
9549 (goto-char beg)
9550 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9551 (replace-match ""))
9552 ;; insert a hline before first
9553 (goto-char beg)
9554 (org-table-insert-hline 'above)
9555 (beginning-of-line -1)
9556 ;; insert a hline after each line
9557 (while (progn (beginning-of-line 3) (< (point) end))
9558 (org-table-insert-hline))
9559 (goto-char beg)
9560 (setq end (move-marker end (org-table-end)))
9561 ;; replace "+" at beginning and ending of hlines
9562 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9563 (replace-match "\\1+-"))
9564 (goto-char beg)
9565 (while (re-search-forward "-|[ \t]*$" end t)
9566 (replace-match "-+"))
9567 (goto-char beg)))))
9569 (defun org-table-wrap-region (arg)
9570 "Wrap several fields in a column like a paragraph.
9571 This is useful if you'd like to spread the contents of a field over several
9572 lines, in order to keep the table compact.
9574 If there is an active region, and both point and mark are in the same column,
9575 the text in the column is wrapped to minimum width for the given number of
9576 lines. Generally, this makes the table more compact. A prefix ARG may be
9577 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9578 formats the selected text to two lines. If the region was longer than two
9579 lines, the remaining lines remain empty. A negative prefix argument reduces
9580 the current number of lines by that amount. The wrapped text is pasted back
9581 into the table. If you formatted it to more lines than it was before, fields
9582 further down in the table get overwritten - so you might need to make space in
9583 the table first.
9585 If there is no region, the current field is split at the cursor position and
9586 the text fragment to the right of the cursor is prepended to the field one
9587 line down.
9589 If there is no region, but you specify a prefix ARG, the current field gets
9590 blank, and the content is appended to the field above."
9591 (interactive "P")
9592 (org-table-check-inside-data-field)
9593 (if (org-region-active-p)
9594 ;; There is a region: fill as a paragraph
9595 (let* ((beg (region-beginning))
9596 (cline (save-excursion (goto-char beg) (org-current-line)))
9597 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9598 nlines)
9599 (org-table-cut-region (region-beginning) (region-end))
9600 (if (> (length (car org-table-clip)) 1)
9601 (error "Region must be limited to single column"))
9602 (setq nlines (if arg
9603 (if (< arg 1)
9604 (+ (length org-table-clip) arg)
9605 arg)
9606 (length org-table-clip)))
9607 (setq org-table-clip
9608 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9609 nil nlines)))
9610 (goto-line cline)
9611 (org-table-goto-column ccol)
9612 (org-table-paste-rectangle))
9613 ;; No region, split the current field at point
9614 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9615 (skip-chars-forward "^\r\n|"))
9616 (if arg
9617 ;; combine with field above
9618 (let ((s (org-table-blank-field))
9619 (col (org-table-current-column)))
9620 (beginning-of-line 0)
9621 (while (org-at-table-hline-p) (beginning-of-line 0))
9622 (org-table-goto-column col)
9623 (skip-chars-forward "^|")
9624 (skip-chars-backward " ")
9625 (insert " " (org-trim s))
9626 (org-table-align))
9627 ;; split field
9628 (if (looking-at "\\([^|]+\\)+|")
9629 (let ((s (match-string 1)))
9630 (replace-match " |")
9631 (goto-char (match-beginning 0))
9632 (org-table-next-row)
9633 (insert (org-trim s) " ")
9634 (org-table-align))
9635 (org-table-next-row)))))
9637 (defvar org-field-marker nil)
9639 (defun org-table-edit-field (arg)
9640 "Edit table field in a different window.
9641 This is mainly useful for fields that contain hidden parts.
9642 When called with a \\[universal-argument] prefix, just make the full field visible so that
9643 it can be edited in place."
9644 (interactive "P")
9645 (if arg
9646 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9647 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9648 (remove-text-properties b e '(org-cwidth t invisible t
9649 display t intangible t))
9650 (if (and (boundp 'font-lock-mode) font-lock-mode)
9651 (font-lock-fontify-block)))
9652 (let ((pos (move-marker (make-marker) (point)))
9653 (field (org-table-get-field))
9654 (cw (current-window-configuration))
9656 (org-switch-to-buffer-other-window "*Org tmp*")
9657 (erase-buffer)
9658 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9659 (let ((org-inhibit-startup t)) (org-mode))
9660 (goto-char (setq p (point-max)))
9661 (insert (org-trim field))
9662 (remove-text-properties p (point-max)
9663 '(invisible t org-cwidth t display t
9664 intangible t))
9665 (goto-char p)
9666 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9667 (org-set-local 'org-window-configuration cw)
9668 (org-set-local 'org-field-marker pos)
9669 (message "Edit and finish with C-c C-c"))))
9671 (defun org-table-finish-edit-field ()
9672 "Finish editing a table data field.
9673 Remove all newline characters, insert the result into the table, realign
9674 the table and kill the editing buffer."
9675 (let ((pos org-field-marker)
9676 (cw org-window-configuration)
9677 (cb (current-buffer))
9678 text)
9679 (goto-char (point-min))
9680 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9681 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9682 (replace-match " "))
9683 (setq text (org-trim (buffer-string)))
9684 (set-window-configuration cw)
9685 (kill-buffer cb)
9686 (select-window (get-buffer-window (marker-buffer pos)))
9687 (goto-char pos)
9688 (move-marker pos nil)
9689 (org-table-check-inside-data-field)
9690 (org-table-get-field nil text)
9691 (org-table-align)
9692 (message "New field value inserted")))
9694 (defun org-trim (s)
9695 "Remove whitespace at beginning and end of string."
9696 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9697 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9700 (defun org-wrap (string &optional width lines)
9701 "Wrap string to either a number of lines, or a width in characters.
9702 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9703 that costs. If there is a word longer than WIDTH, the text is actually
9704 wrapped to the length of that word.
9705 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9706 many lines, whatever width that takes.
9707 The return value is a list of lines, without newlines at the end."
9708 (let* ((words (org-split-string string "[ \t\n]+"))
9709 (maxword (apply 'max (mapcar 'org-string-width words)))
9710 w ll)
9711 (cond (width
9712 (org-do-wrap words (max maxword width)))
9713 (lines
9714 (setq w maxword)
9715 (setq ll (org-do-wrap words maxword))
9716 (if (<= (length ll) lines)
9718 (setq ll words)
9719 (while (> (length ll) lines)
9720 (setq w (1+ w))
9721 (setq ll (org-do-wrap words w)))
9722 ll))
9723 (t (error "Cannot wrap this")))))
9726 (defun org-do-wrap (words width)
9727 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9728 (let (lines line)
9729 (while words
9730 (setq line (pop words))
9731 (while (and words (< (+ (length line) (length (car words))) width))
9732 (setq line (concat line " " (pop words))))
9733 (setq lines (push line lines)))
9734 (nreverse lines)))
9736 (defun org-split-string (string &optional separators)
9737 "Splits STRING into substrings at SEPARATORS.
9738 No empty strings are returned if there are matches at the beginning
9739 and end of string."
9740 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9741 (start 0)
9742 notfirst
9743 (list nil))
9744 (while (and (string-match rexp string
9745 (if (and notfirst
9746 (= start (match-beginning 0))
9747 (< start (length string)))
9748 (1+ start) start))
9749 (< (match-beginning 0) (length string)))
9750 (setq notfirst t)
9751 (or (eq (match-beginning 0) 0)
9752 (and (eq (match-beginning 0) (match-end 0))
9753 (eq (match-beginning 0) start))
9754 (setq list
9755 (cons (substring string start (match-beginning 0))
9756 list)))
9757 (setq start (match-end 0)))
9758 (or (eq start (length string))
9759 (setq list
9760 (cons (substring string start)
9761 list)))
9762 (nreverse list)))
9764 (defun org-table-map-tables (function)
9765 "Apply FUNCTION to the start of all tables in the buffer."
9766 (save-excursion
9767 (save-restriction
9768 (widen)
9769 (goto-char (point-min))
9770 (while (re-search-forward org-table-any-line-regexp nil t)
9771 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9772 (beginning-of-line 1)
9773 (if (looking-at org-table-line-regexp)
9774 (save-excursion (funcall function)))
9775 (re-search-forward org-table-any-border-regexp nil 1))))
9776 (message "Mapping tables: done"))
9778 (defvar org-timecnt) ; dynamically scoped parameter
9780 (defun org-table-sum (&optional beg end nlast)
9781 "Sum numbers in region of current table column.
9782 The result will be displayed in the echo area, and will be available
9783 as kill to be inserted with \\[yank].
9785 If there is an active region, it is interpreted as a rectangle and all
9786 numbers in that rectangle will be summed. If there is no active
9787 region and point is located in a table column, sum all numbers in that
9788 column.
9790 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9791 numbers are assumed to be times as well (in decimal hours) and the
9792 numbers are added as such.
9794 If NLAST is a number, only the NLAST fields will actually be summed."
9795 (interactive)
9796 (save-excursion
9797 (let (col (org-timecnt 0) diff h m s org-table-clip)
9798 (cond
9799 ((and beg end)) ; beg and end given explicitly
9800 ((org-region-active-p)
9801 (setq beg (region-beginning) end (region-end)))
9803 (setq col (org-table-current-column))
9804 (goto-char (org-table-begin))
9805 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9806 (error "No table data"))
9807 (org-table-goto-column col)
9808 (setq beg (point))
9809 (goto-char (org-table-end))
9810 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9811 (error "No table data"))
9812 (org-table-goto-column col)
9813 (setq end (point))))
9814 (let* ((items (apply 'append (org-table-copy-region beg end)))
9815 (items1 (cond ((not nlast) items)
9816 ((>= nlast (length items)) items)
9817 (t (setq items (reverse items))
9818 (setcdr (nthcdr (1- nlast) items) nil)
9819 (nreverse items))))
9820 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9821 items1)))
9822 (res (apply '+ numbers))
9823 (sres (if (= org-timecnt 0)
9824 (format "%g" res)
9825 (setq diff (* 3600 res)
9826 h (floor (/ diff 3600)) diff (mod diff 3600)
9827 m (floor (/ diff 60)) diff (mod diff 60)
9828 s diff)
9829 (format "%d:%02d:%02d" h m s))))
9830 (kill-new sres)
9831 (if (interactive-p)
9832 (message "%s"
9833 (substitute-command-keys
9834 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9835 (length numbers) sres))))
9836 sres))))
9838 (defun org-table-get-number-for-summing (s)
9839 (let (n)
9840 (if (string-match "^ *|? *" s)
9841 (setq s (replace-match "" nil nil s)))
9842 (if (string-match " *|? *$" s)
9843 (setq s (replace-match "" nil nil s)))
9844 (setq n (string-to-number s))
9845 (cond
9846 ((and (string-match "0" s)
9847 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9848 ((string-match "\\`[ \t]+\\'" s) nil)
9849 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9850 (let ((h (string-to-number (or (match-string 1 s) "0")))
9851 (m (string-to-number (or (match-string 2 s) "0")))
9852 (s (string-to-number (or (match-string 4 s) "0"))))
9853 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9854 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9855 ((equal n 0) nil)
9856 (t n))))
9858 (defun org-table-current-field-formula (&optional key noerror)
9859 "Return the formula active for the current field.
9860 Assumes that specials are in place.
9861 If KEY is given, return the key to this formula.
9862 Otherwise return the formula preceeded with \"=\" or \":=\"."
9863 (let* ((name (car (rassoc (list (org-current-line)
9864 (org-table-current-column))
9865 org-table-named-field-locations)))
9866 (col (org-table-current-column))
9867 (scol (int-to-string col))
9868 (ref (format "@%d$%d" (org-table-current-dline) col))
9869 (stored-list (org-table-get-stored-formulas noerror))
9870 (ass (or (assoc name stored-list)
9871 (assoc ref stored-list)
9872 (assoc scol stored-list))))
9873 (if key
9874 (car ass)
9875 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9876 (cdr ass))))))
9878 (defun org-table-get-formula (&optional equation named)
9879 "Read a formula from the minibuffer, offer stored formula as default.
9880 When NAMED is non-nil, look for a named equation."
9881 (let* ((stored-list (org-table-get-stored-formulas))
9882 (name (car (rassoc (list (org-current-line)
9883 (org-table-current-column))
9884 org-table-named-field-locations)))
9885 (ref (format "@%d$%d" (org-table-current-dline)
9886 (org-table-current-column)))
9887 (refass (assoc ref stored-list))
9888 (scol (if named
9889 (if name name ref)
9890 (int-to-string (org-table-current-column))))
9891 (dummy (and (or name refass) (not named)
9892 (not (y-or-n-p "Replace field formula with column formula? " ))
9893 (error "Abort")))
9894 (name (or name ref))
9895 (org-table-may-need-update nil)
9896 (stored (cdr (assoc scol stored-list)))
9897 (eq (cond
9898 ((and stored equation (string-match "^ *=? *$" equation))
9899 stored)
9900 ((stringp equation)
9901 equation)
9902 (t (org-table-formula-from-user
9903 (read-string
9904 (org-table-formula-to-user
9905 (format "%s formula %s%s="
9906 (if named "Field" "Column")
9907 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9908 scol))
9909 (if stored (org-table-formula-to-user stored) "")
9910 'org-table-formula-history
9911 )))))
9912 mustsave)
9913 (when (not (string-match "\\S-" eq))
9914 ;; remove formula
9915 (setq stored-list (delq (assoc scol stored-list) stored-list))
9916 (org-table-store-formulas stored-list)
9917 (error "Formula removed"))
9918 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9919 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9920 (if (and name (not named))
9921 ;; We set the column equation, delete the named one.
9922 (setq stored-list (delq (assoc name stored-list) stored-list)
9923 mustsave t))
9924 (if stored
9925 (setcdr (assoc scol stored-list) eq)
9926 (setq stored-list (cons (cons scol eq) stored-list)))
9927 (if (or mustsave (not (equal stored eq)))
9928 (org-table-store-formulas stored-list))
9929 eq))
9931 (defun org-table-store-formulas (alist)
9932 "Store the list of formulas below the current table."
9933 (setq alist (sort alist 'org-table-formula-less-p))
9934 (save-excursion
9935 (goto-char (org-table-end))
9936 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9937 (progn
9938 ;; don't overwrite TBLFM, we might use text properties to store stuff
9939 (goto-char (match-beginning 2))
9940 (delete-region (match-beginning 2) (match-end 0)))
9941 (insert "#+TBLFM:"))
9942 (insert " "
9943 (mapconcat (lambda (x)
9944 (concat
9945 (if (equal (string-to-char (car x)) ?@) "" "$")
9946 (car x) "=" (cdr x)))
9947 alist "::")
9948 "\n")))
9950 (defsubst org-table-formula-make-cmp-string (a)
9951 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9952 (concat
9953 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9954 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9955 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9957 (defun org-table-formula-less-p (a b)
9958 "Compare two formulas for sorting."
9959 (let ((as (org-table-formula-make-cmp-string (car a)))
9960 (bs (org-table-formula-make-cmp-string (car b))))
9961 (and as bs (string< as bs))))
9963 (defun org-table-get-stored-formulas (&optional noerror)
9964 "Return an alist with the stored formulas directly after current table."
9965 (interactive)
9966 (let (scol eq eq-alist strings string seen)
9967 (save-excursion
9968 (goto-char (org-table-end))
9969 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9970 (setq strings (org-split-string (match-string 2) " *:: *"))
9971 (while (setq string (pop strings))
9972 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9973 (setq scol (if (match-end 2)
9974 (match-string 2 string)
9975 (match-string 1 string))
9976 eq (match-string 3 string)
9977 eq-alist (cons (cons scol eq) eq-alist))
9978 (if (member scol seen)
9979 (if noerror
9980 (progn
9981 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9982 (ding)
9983 (sit-for 2))
9984 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9985 (push scol seen))))))
9986 (nreverse eq-alist)))
9988 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9989 "Modify the equations after the table structure has been edited.
9990 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9991 For all numbers larger than LIMIT, shift them by DELTA."
9992 (save-excursion
9993 (goto-char (org-table-end))
9994 (when (looking-at "#\\+TBLFM:")
9995 (let ((re (concat key "\\([0-9]+\\)"))
9996 (re2
9997 (when remove
9998 (if (equal key "$")
9999 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
10000 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
10001 s n a)
10002 (when remove
10003 (while (re-search-forward re2 (point-at-eol) t)
10004 (replace-match "")))
10005 (while (re-search-forward re (point-at-eol) t)
10006 (setq s (match-string 1) n (string-to-number s))
10007 (cond
10008 ((setq a (assoc s replace))
10009 (replace-match (concat key (cdr a)) t t))
10010 ((and limit (> n limit))
10011 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
10013 (defun org-table-get-specials ()
10014 "Get the column names and local parameters for this table."
10015 (save-excursion
10016 (let ((beg (org-table-begin)) (end (org-table-end))
10017 names name fields fields1 field cnt
10018 c v l line col types dlines hlines)
10019 (setq org-table-column-names nil
10020 org-table-local-parameters nil
10021 org-table-named-field-locations nil
10022 org-table-current-begin-line nil
10023 org-table-current-begin-pos nil
10024 org-table-current-line-types nil)
10025 (goto-char beg)
10026 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10027 (setq names (org-split-string (match-string 1) " *| *")
10028 cnt 1)
10029 (while (setq name (pop names))
10030 (setq cnt (1+ cnt))
10031 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10032 (push (cons name (int-to-string cnt)) org-table-column-names))))
10033 (setq org-table-column-names (nreverse org-table-column-names))
10034 (setq org-table-column-name-regexp
10035 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10036 (goto-char beg)
10037 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10038 (setq fields (org-split-string (match-string 1) " *| *"))
10039 (while (setq field (pop fields))
10040 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10041 (push (cons (match-string 1 field) (match-string 2 field))
10042 org-table-local-parameters))))
10043 (goto-char beg)
10044 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10045 (setq c (match-string 1)
10046 fields (org-split-string (match-string 2) " *| *"))
10047 (save-excursion
10048 (beginning-of-line (if (equal c "_") 2 0))
10049 (setq line (org-current-line) col 1)
10050 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10051 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10052 (while (and fields1 (setq field (pop fields)))
10053 (setq v (pop fields1) col (1+ col))
10054 (when (and (stringp field) (stringp v)
10055 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10056 (push (cons field v) org-table-local-parameters)
10057 (push (list field line col) org-table-named-field-locations))))
10058 ;; Analyse the line types
10059 (goto-char beg)
10060 (setq org-table-current-begin-line (org-current-line)
10061 org-table-current-begin-pos (point)
10062 l org-table-current-begin-line)
10063 (while (looking-at "[ \t]*|\\(-\\)?")
10064 (push (if (match-end 1) 'hline 'dline) types)
10065 (if (match-end 1) (push l hlines) (push l dlines))
10066 (beginning-of-line 2)
10067 (setq l (1+ l)))
10068 (setq org-table-current-line-types (apply 'vector (nreverse types))
10069 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10070 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10072 (defun org-table-maybe-eval-formula ()
10073 "Check if the current field starts with \"=\" or \":=\".
10074 If yes, store the formula and apply it."
10075 ;; We already know we are in a table. Get field will only return a formula
10076 ;; when appropriate. It might return a separator line, but no problem.
10077 (when org-table-formula-evaluate-inline
10078 (let* ((field (org-trim (or (org-table-get-field) "")))
10079 named eq)
10080 (when (string-match "^:?=\\(.*\\)" field)
10081 (setq named (equal (string-to-char field) ?:)
10082 eq (match-string 1 field))
10083 (if (or (fboundp 'calc-eval)
10084 (equal (substring eq 0 (min 2 (length eq))) "'("))
10085 (org-table-eval-formula (if named '(4) nil)
10086 (org-table-formula-from-user eq))
10087 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10089 (defvar org-recalc-commands nil
10090 "List of commands triggering the recalculation of a line.
10091 Will be filled automatically during use.")
10093 (defvar org-recalc-marks
10094 '((" " . "Unmarked: no special line, no automatic recalculation")
10095 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10096 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10097 ("!" . "Column name definition line. Reference in formula as $name.")
10098 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10099 ("_" . "Names for values in row below this one.")
10100 ("^" . "Names for values in row above this one.")))
10102 (defun org-table-rotate-recalc-marks (&optional newchar)
10103 "Rotate the recalculation mark in the first column.
10104 If in any row, the first field is not consistent with a mark,
10105 insert a new column for the markers.
10106 When there is an active region, change all the lines in the region,
10107 after prompting for the marking character.
10108 After each change, a message will be displayed indicating the meaning
10109 of the new mark."
10110 (interactive)
10111 (unless (org-at-table-p) (error "Not at a table"))
10112 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10113 (beg (org-table-begin))
10114 (end (org-table-end))
10115 (l (org-current-line))
10116 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10117 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10118 (have-col
10119 (save-excursion
10120 (goto-char beg)
10121 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10122 (col (org-table-current-column))
10123 (forcenew (car (assoc newchar org-recalc-marks)))
10124 epos new)
10125 (when l1
10126 (message "Change region to what mark? Type # * ! $ or SPC: ")
10127 (setq newchar (char-to-string (read-char-exclusive))
10128 forcenew (car (assoc newchar org-recalc-marks))))
10129 (if (and newchar (not forcenew))
10130 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10131 newchar))
10132 (if l1 (goto-line l1))
10133 (save-excursion
10134 (beginning-of-line 1)
10135 (unless (looking-at org-table-dataline-regexp)
10136 (error "Not at a table data line")))
10137 (unless have-col
10138 (org-table-goto-column 1)
10139 (org-table-insert-column)
10140 (org-table-goto-column (1+ col)))
10141 (setq epos (point-at-eol))
10142 (save-excursion
10143 (beginning-of-line 1)
10144 (org-table-get-field
10145 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10146 (concat " "
10147 (setq new (or forcenew
10148 (cadr (member (match-string 1) marks))))
10149 " ")
10150 " # ")))
10151 (if (and l1 l2)
10152 (progn
10153 (goto-line l1)
10154 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10155 (and (looking-at org-table-dataline-regexp)
10156 (org-table-get-field 1 (concat " " new " "))))
10157 (goto-line l1)))
10158 (if (not (= epos (point-at-eol))) (org-table-align))
10159 (goto-line l)
10160 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10162 (defun org-table-maybe-recalculate-line ()
10163 "Recompute the current line if marked for it, and if we haven't just done it."
10164 (interactive)
10165 (and org-table-allow-automatic-line-recalculation
10166 (not (and (memq last-command org-recalc-commands)
10167 (equal org-last-recalc-line (org-current-line))))
10168 (save-excursion (beginning-of-line 1)
10169 (looking-at org-table-auto-recalculate-regexp))
10170 (org-table-recalculate) t))
10172 (defvar org-table-formula-debug nil
10173 "Non-nil means, debug table formulas.
10174 When nil, simply write \"#ERROR\" in corrupted fields.")
10175 (make-variable-buffer-local 'org-table-formula-debug)
10177 (defvar modes)
10178 (defsubst org-set-calc-mode (var &optional value)
10179 (if (stringp var)
10180 (setq var (assoc var '(("D" calc-angle-mode deg)
10181 ("R" calc-angle-mode rad)
10182 ("F" calc-prefer-frac t)
10183 ("S" calc-symbolic-mode t)))
10184 value (nth 2 var) var (nth 1 var)))
10185 (if (memq var modes)
10186 (setcar (cdr (memq var modes)) value)
10187 (cons var (cons value modes)))
10188 modes)
10190 (defun org-table-eval-formula (&optional arg equation
10191 suppress-align suppress-const
10192 suppress-store suppress-analysis)
10193 "Replace the table field value at the cursor by the result of a calculation.
10195 This function makes use of Dave Gillespie's Calc package, in my view the
10196 most exciting program ever written for GNU Emacs. So you need to have Calc
10197 installed in order to use this function.
10199 In a table, this command replaces the value in the current field with the
10200 result of a formula. It also installs the formula as the \"current\" column
10201 formula, by storing it in a special line below the table. When called
10202 with a `C-u' prefix, the current field must ba a named field, and the
10203 formula is installed as valid in only this specific field.
10205 When called with two `C-u' prefixes, insert the active equation
10206 for the field back into the current field, so that it can be
10207 edited there. This is useful in order to use \\[org-table-show-reference]
10208 to check the referenced fields.
10210 When called, the command first prompts for a formula, which is read in
10211 the minibuffer. Previously entered formulas are available through the
10212 history list, and the last used formula is offered as a default.
10213 These stored formulas are adapted correctly when moving, inserting, or
10214 deleting columns with the corresponding commands.
10216 The formula can be any algebraic expression understood by the Calc package.
10217 For details, see the Org-mode manual.
10219 This function can also be called from Lisp programs and offers
10220 additional arguments: EQUATION can be the formula to apply. If this
10221 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10222 used to speed-up recursive calls by by-passing unnecessary aligns.
10223 SUPPRESS-CONST suppresses the interpretation of constants in the
10224 formula, assuming that this has been done already outside the function.
10225 SUPPRESS-STORE means the formula should not be stored, either because
10226 it is already stored, or because it is a modified equation that should
10227 not overwrite the stored one."
10228 (interactive "P")
10229 (org-table-check-inside-data-field)
10230 (or suppress-analysis (org-table-get-specials))
10231 (if (equal arg '(16))
10232 (let ((eq (org-table-current-field-formula)))
10233 (or eq (error "No equation active for current field"))
10234 (org-table-get-field nil eq)
10235 (org-table-align)
10236 (setq org-table-may-need-update t))
10237 (let* (fields
10238 (ndown (if (integerp arg) arg 1))
10239 (org-table-automatic-realign nil)
10240 (case-fold-search nil)
10241 (down (> ndown 1))
10242 (formula (if (and equation suppress-store)
10243 equation
10244 (org-table-get-formula equation (equal arg '(4)))))
10245 (n0 (org-table-current-column))
10246 (modes (copy-sequence org-calc-default-modes))
10247 (numbers nil) ; was a variable, now fixed default
10248 (keep-empty nil)
10249 n form form0 bw fmt x ev orig c lispp literal)
10250 ;; Parse the format string. Since we have a lot of modes, this is
10251 ;; a lot of work. However, I think calc still uses most of the time.
10252 (if (string-match ";" formula)
10253 (let ((tmp (org-split-string formula ";")))
10254 (setq formula (car tmp)
10255 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10256 (nth 1 tmp)))
10257 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10258 (setq c (string-to-char (match-string 1 fmt))
10259 n (string-to-number (match-string 2 fmt)))
10260 (if (= c ?p)
10261 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10262 (setq modes (org-set-calc-mode
10263 'calc-float-format
10264 (list (cdr (assoc c '((?n . float) (?f . fix)
10265 (?s . sci) (?e . eng))))
10266 n))))
10267 (setq fmt (replace-match "" t t fmt)))
10268 (if (string-match "[NT]" fmt)
10269 (setq numbers (equal (match-string 0 fmt) "N")
10270 fmt (replace-match "" t t fmt)))
10271 (if (string-match "L" fmt)
10272 (setq literal t
10273 fmt (replace-match "" t t fmt)))
10274 (if (string-match "E" fmt)
10275 (setq keep-empty t
10276 fmt (replace-match "" t t fmt)))
10277 (while (string-match "[DRFS]" fmt)
10278 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10279 (setq fmt (replace-match "" t t fmt)))
10280 (unless (string-match "\\S-" fmt)
10281 (setq fmt nil))))
10282 (if (and (not suppress-const) org-table-formula-use-constants)
10283 (setq formula (org-table-formula-substitute-names formula)))
10284 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10285 (while (> ndown 0)
10286 (setq fields (org-split-string
10287 (org-no-properties
10288 (buffer-substring (point-at-bol) (point-at-eol)))
10289 " *| *"))
10290 (if (eq numbers t)
10291 (setq fields (mapcar
10292 (lambda (x) (number-to-string (string-to-number x)))
10293 fields)))
10294 (setq ndown (1- ndown))
10295 (setq form (copy-sequence formula)
10296 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10297 (if (and lispp literal) (setq lispp 'literal))
10298 ;; Check for old vertical references
10299 (setq form (org-rewrite-old-row-references form))
10300 ;; Insert complex ranges
10301 (while (string-match org-table-range-regexp form)
10302 (setq form
10303 (replace-match
10304 (save-match-data
10305 (org-table-make-reference
10306 (org-table-get-range (match-string 0 form) nil n0)
10307 keep-empty numbers lispp))
10308 t t form)))
10309 ;; Insert simple ranges
10310 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10311 (setq form
10312 (replace-match
10313 (save-match-data
10314 (org-table-make-reference
10315 (org-sublist
10316 fields (string-to-number (match-string 1 form))
10317 (string-to-number (match-string 2 form)))
10318 keep-empty numbers lispp))
10319 t t form)))
10320 (setq form0 form)
10321 ;; Insert the references to fields in same row
10322 (while (string-match "\\$\\([0-9]+\\)" form)
10323 (setq n (string-to-number (match-string 1 form))
10324 x (nth (1- (if (= n 0) n0 n)) fields))
10325 (unless x (error "Invalid field specifier \"%s\""
10326 (match-string 0 form)))
10327 (setq form (replace-match
10328 (save-match-data
10329 (org-table-make-reference x nil numbers lispp))
10330 t t form)))
10332 (if lispp
10333 (setq ev (condition-case nil
10334 (eval (eval (read form)))
10335 (error "#ERROR"))
10336 ev (if (numberp ev) (number-to-string ev) ev))
10337 (or (fboundp 'calc-eval)
10338 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10339 (setq ev (calc-eval (cons form modes)
10340 (if numbers 'num))))
10342 (when org-table-formula-debug
10343 (with-output-to-temp-buffer "*Substitution History*"
10344 (princ (format "Substitution history of formula
10345 Orig: %s
10346 $xyz-> %s
10347 @r$c-> %s
10348 $1-> %s\n" orig formula form0 form))
10349 (if (listp ev)
10350 (princ (format " %s^\nError: %s"
10351 (make-string (car ev) ?\-) (nth 1 ev)))
10352 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10353 ev (or fmt "NONE")
10354 (if fmt (format fmt (string-to-number ev)) ev)))))
10355 (setq bw (get-buffer-window "*Substitution History*"))
10356 (shrink-window-if-larger-than-buffer bw)
10357 (unless (and (interactive-p) (not ndown))
10358 (unless (let (inhibit-redisplay)
10359 (y-or-n-p "Debugging Formula. Continue to next? "))
10360 (org-table-align)
10361 (error "Abort"))
10362 (delete-window bw)
10363 (message "")))
10364 (if (listp ev) (setq fmt nil ev "#ERROR"))
10365 (org-table-justify-field-maybe
10366 (if fmt (format fmt (string-to-number ev)) ev))
10367 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10368 (call-interactively 'org-return)
10369 (setq ndown 0)))
10370 (and down (org-table-maybe-recalculate-line))
10371 (or suppress-align (and org-table-may-need-update
10372 (org-table-align))))))
10374 (defun org-table-put-field-property (prop value)
10375 (save-excursion
10376 (put-text-property (progn (skip-chars-backward "^|") (point))
10377 (progn (skip-chars-forward "^|") (point))
10378 prop value)))
10380 (defun org-table-get-range (desc &optional tbeg col highlight)
10381 "Get a calc vector from a column, accorting to descriptor DESC.
10382 Optional arguments TBEG and COL can give the beginning of the table and
10383 the current column, to avoid unnecessary parsing.
10384 HIGHLIGHT means, just highlight the range."
10385 (if (not (equal (string-to-char desc) ?@))
10386 (setq desc (concat "@" desc)))
10387 (save-excursion
10388 (or tbeg (setq tbeg (org-table-begin)))
10389 (or col (setq col (org-table-current-column)))
10390 (let ((thisline (org-current-line))
10391 beg end c1 c2 r1 r2 rangep tmp)
10392 (unless (string-match org-table-range-regexp desc)
10393 (error "Invalid table range specifier `%s'" desc))
10394 (setq rangep (match-end 3)
10395 r1 (and (match-end 1) (match-string 1 desc))
10396 r2 (and (match-end 4) (match-string 4 desc))
10397 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10398 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10400 (and c1 (setq c1 (+ (string-to-number c1)
10401 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10402 (and c2 (setq c2 (+ (string-to-number c2)
10403 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10404 (if (equal r1 "") (setq r1 nil))
10405 (if (equal r2 "") (setq r2 nil))
10406 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10407 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10408 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10409 (if (not r1) (setq r1 thisline))
10410 (if (not r2) (setq r2 thisline))
10411 (if (not c1) (setq c1 col))
10412 (if (not c2) (setq c2 col))
10413 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10414 ;; just one field
10415 (progn
10416 (goto-line r1)
10417 (while (not (looking-at org-table-dataline-regexp))
10418 (beginning-of-line 2))
10419 (prog1 (org-trim (org-table-get-field c1))
10420 (if highlight (org-table-highlight-rectangle (point) (point)))))
10421 ;; A range, return a vector
10422 ;; First sort the numbers to get a regular ractangle
10423 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10424 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10425 (goto-line r1)
10426 (while (not (looking-at org-table-dataline-regexp))
10427 (beginning-of-line 2))
10428 (org-table-goto-column c1)
10429 (setq beg (point))
10430 (goto-line r2)
10431 (while (not (looking-at org-table-dataline-regexp))
10432 (beginning-of-line 0))
10433 (org-table-goto-column c2)
10434 (setq end (point))
10435 (if highlight
10436 (org-table-highlight-rectangle
10437 beg (progn (skip-chars-forward "^|\n") (point))))
10438 ;; return string representation of calc vector
10439 (mapcar 'org-trim
10440 (apply 'append (org-table-copy-region beg end)))))))
10442 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10443 "Analyze descriptor DESC and retrieve the corresponding line number.
10444 The cursor is currently in line CLINE, the table begins in line BLINE,
10445 and TABLE is a vector with line types."
10446 (if (string-match "^[0-9]+$" desc)
10447 (aref org-table-dlines (string-to-number desc))
10448 (setq cline (or cline (org-current-line))
10449 bline (or bline org-table-current-begin-line)
10450 table (or table org-table-current-line-types))
10451 (if (or
10452 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10453 ;; 1 2 3 4 5 6
10454 (and (not (match-end 3)) (not (match-end 6)))
10455 (and (match-end 3) (match-end 6) (not (match-end 5))))
10456 (error "invalid row descriptor `%s'" desc))
10457 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10458 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10459 (odir (and (match-end 5) (match-string 5 desc)))
10460 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10461 (i (- cline bline))
10462 (rel (and (match-end 6)
10463 (or (and (match-end 1) (not (match-end 3)))
10464 (match-end 5)))))
10465 (if (and hn (not hdir))
10466 (progn
10467 (setq i 0 hdir "+")
10468 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10469 (if (and (not hn) on (not odir))
10470 (error "should never happen");;(aref org-table-dlines on)
10471 (if (and hn (> hn 0))
10472 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10473 (if on
10474 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10475 (+ bline i)))))
10477 (defun org-find-row-type (table i type backwards relative n)
10478 (let ((l (length table)))
10479 (while (> n 0)
10480 (while (and (setq i (+ i (if backwards -1 1)))
10481 (>= i 0) (< i l)
10482 (not (eq (aref table i) type))
10483 (if (and relative (eq (aref table i) 'hline))
10484 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10485 t)))
10486 (setq n (1- n)))
10487 (if (or (< i 0) (>= i l))
10488 (error "Row descriptior leads outside table")
10489 i)))
10491 (defun org-rewrite-old-row-references (s)
10492 (if (string-match "&[-+0-9I]" s)
10493 (error "Formula contains old &row reference, please rewrite using @-syntax")
10496 (defun org-table-make-reference (elements keep-empty numbers lispp)
10497 "Convert list ELEMENTS to something appropriate to insert into formula.
10498 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10499 NUMBERS indicates that everything should be converted to numbers.
10500 LISPP means to return something appropriate for a Lisp list."
10501 (if (stringp elements) ; just a single val
10502 (if lispp
10503 (if (eq lispp 'literal)
10504 elements
10505 (prin1-to-string (if numbers (string-to-number elements) elements)))
10506 (if (equal elements "") (setq elements "0"))
10507 (if numbers (number-to-string (string-to-number elements)) elements))
10508 (unless keep-empty
10509 (setq elements
10510 (delq nil
10511 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10512 elements))))
10513 (setq elements (or elements '("0")))
10514 (if lispp
10515 (mapconcat
10516 (lambda (x)
10517 (if (eq lispp 'literal)
10519 (prin1-to-string (if numbers (string-to-number x) x))))
10520 elements " ")
10521 (concat "[" (mapconcat
10522 (lambda (x)
10523 (if numbers (number-to-string (string-to-number x)) x))
10524 elements
10525 ",") "]"))))
10527 (defun org-table-recalculate (&optional all noalign)
10528 "Recalculate the current table line by applying all stored formulas.
10529 With prefix arg ALL, do this for all lines in the table."
10530 (interactive "P")
10531 (or (memq this-command org-recalc-commands)
10532 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10533 (unless (org-at-table-p) (error "Not at a table"))
10534 (if (equal all '(16))
10535 (org-table-iterate)
10536 (org-table-get-specials)
10537 (let* ((eqlist (sort (org-table-get-stored-formulas)
10538 (lambda (a b) (string< (car a) (car b)))))
10539 (inhibit-redisplay (not debug-on-error))
10540 (line-re org-table-dataline-regexp)
10541 (thisline (org-current-line))
10542 (thiscol (org-table-current-column))
10543 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10544 ;; Insert constants in all formulas
10545 (setq eqlist
10546 (mapcar (lambda (x)
10547 (setcdr x (org-table-formula-substitute-names (cdr x)))
10549 eqlist))
10550 ;; Split the equation list
10551 (while (setq eq (pop eqlist))
10552 (if (<= (string-to-char (car eq)) ?9)
10553 (push eq eqlnum)
10554 (push eq eqlname)))
10555 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10556 (if all
10557 (progn
10558 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10559 (goto-char (setq beg (org-table-begin)))
10560 (if (re-search-forward org-table-calculate-mark-regexp end t)
10561 ;; This is a table with marked lines, compute selected lines
10562 (setq line-re org-table-recalculate-regexp)
10563 ;; Move forward to the first non-header line
10564 (if (and (re-search-forward org-table-dataline-regexp end t)
10565 (re-search-forward org-table-hline-regexp end t)
10566 (re-search-forward org-table-dataline-regexp end t))
10567 (setq beg (match-beginning 0))
10568 nil))) ;; just leave beg where it is
10569 (setq beg (point-at-bol)
10570 end (move-marker (make-marker) (1+ (point-at-eol)))))
10571 (goto-char beg)
10572 (and all (message "Re-applying formulas to full table..."))
10574 ;; First find the named fields, and mark them untouchanble
10575 (remove-text-properties beg end '(org-untouchable t))
10576 (while (setq eq (pop eqlname))
10577 (setq name (car eq)
10578 a (assoc name org-table-named-field-locations))
10579 (and (not a)
10580 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10581 (setq a (list name
10582 (aref org-table-dlines
10583 (string-to-number (match-string 1 name)))
10584 (string-to-number (match-string 2 name)))))
10585 (when (and a (or all (equal (nth 1 a) thisline)))
10586 (message "Re-applying formula to field: %s" name)
10587 (goto-line (nth 1 a))
10588 (org-table-goto-column (nth 2 a))
10589 (push (append a (list (cdr eq))) eqlname1)
10590 (org-table-put-field-property :org-untouchable t)))
10592 ;; Now evauluate the column formulas, but skip fields covered by
10593 ;; field formulas
10594 (goto-char beg)
10595 (while (re-search-forward line-re end t)
10596 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10597 ;; Unprotected line, recalculate
10598 (and all (message "Re-applying formulas to full table...(line %d)"
10599 (setq cnt (1+ cnt))))
10600 (setq org-last-recalc-line (org-current-line))
10601 (setq eql eqlnum)
10602 (while (setq entry (pop eql))
10603 (goto-line org-last-recalc-line)
10604 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10605 (unless (get-text-property (point) :org-untouchable)
10606 (org-table-eval-formula nil (cdr entry)
10607 'noalign 'nocst 'nostore 'noanalysis)))))
10609 ;; Now evaluate the field formulas
10610 (while (setq eq (pop eqlname1))
10611 (message "Re-applying formula to field: %s" (car eq))
10612 (goto-line (nth 1 eq))
10613 (org-table-goto-column (nth 2 eq))
10614 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10615 'nostore 'noanalysis))
10617 (goto-line thisline)
10618 (org-table-goto-column thiscol)
10619 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10620 (or noalign (and org-table-may-need-update (org-table-align))
10621 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10623 ;; back to initial position
10624 (message "Re-applying formulas...done")
10625 (goto-line thisline)
10626 (org-table-goto-column thiscol)
10627 (or noalign (and org-table-may-need-update (org-table-align))
10628 (and all (message "Re-applying formulas...done"))))))
10630 (defun org-table-iterate (&optional arg)
10631 "Recalculate the table until it does not change anymore."
10632 (interactive "P")
10633 (let ((imax (if arg (prefix-numeric-value arg) 10))
10634 (i 0)
10635 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10636 thistbl)
10637 (catch 'exit
10638 (while (< i imax)
10639 (setq i (1+ i))
10640 (org-table-recalculate 'all)
10641 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10642 (if (not (string= lasttbl thistbl))
10643 (setq lasttbl thistbl)
10644 (if (> i 1)
10645 (message "Convergence after %d iterations" i)
10646 (message "Table was already stable"))
10647 (throw 'exit t)))
10648 (error "No convergence after %d iterations" i))))
10650 (defun org-table-formula-substitute-names (f)
10651 "Replace $const with values in string F."
10652 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10653 ;; First, check for column names
10654 (while (setq start (string-match org-table-column-name-regexp f start))
10655 (setq start (1+ start))
10656 (setq a (assoc (match-string 1 f) org-table-column-names))
10657 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10658 ;; Parameters and constants
10659 (setq start 0)
10660 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10661 (setq start (1+ start))
10662 (if (setq a (save-match-data
10663 (org-table-get-constant (match-string 1 f))))
10664 (setq f (replace-match
10665 (concat (if pp "(") a (if pp ")")) t t f))))
10666 (if org-table-formula-debug
10667 (put-text-property 0 (length f) :orig-formula f1 f))
10670 (defun org-table-get-constant (const)
10671 "Find the value for a parameter or constant in a formula.
10672 Parameters get priority."
10673 (or (cdr (assoc const org-table-local-parameters))
10674 (cdr (assoc const org-table-formula-constants-local))
10675 (cdr (assoc const org-table-formula-constants))
10676 (and (fboundp 'constants-get) (constants-get const))
10677 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10678 (org-entry-get nil (substring const 5) 'inherit))
10679 "#UNDEFINED_NAME"))
10681 (defvar org-table-fedit-map
10682 (let ((map (make-sparse-keymap)))
10683 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10684 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10685 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10686 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10687 (org-defkey map "\C-c?" 'org-table-show-reference)
10688 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10689 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10690 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10691 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10692 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10693 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10694 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10695 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10696 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10697 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10698 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10699 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10700 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10701 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10702 map))
10704 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10705 '("Edit-Formulas"
10706 ["Finish and Install" org-table-fedit-finish t]
10707 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10708 ["Abort" org-table-fedit-abort t]
10709 "--"
10710 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10711 ["Complete Lisp Symbol" lisp-complete-symbol t]
10712 "--"
10713 "Shift Reference at Point"
10714 ["Up" org-table-fedit-ref-up t]
10715 ["Down" org-table-fedit-ref-down t]
10716 ["Left" org-table-fedit-ref-left t]
10717 ["Right" org-table-fedit-ref-right t]
10719 "Change Test Row for Column Formulas"
10720 ["Up" org-table-fedit-line-up t]
10721 ["Down" org-table-fedit-line-down t]
10722 "--"
10723 ["Scroll Table Window" org-table-fedit-scroll t]
10724 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10725 ["Show Table Grid" org-table-fedit-toggle-coordinates
10726 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10727 org-table-overlay-coordinates)]
10728 "--"
10729 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10730 :style toggle :selected org-table-buffer-is-an]))
10732 (defvar org-pos)
10734 (defun org-table-edit-formulas ()
10735 "Edit the formulas of the current table in a separate buffer."
10736 (interactive)
10737 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10738 (beginning-of-line 0))
10739 (unless (org-at-table-p) (error "Not at a table"))
10740 (org-table-get-specials)
10741 (let ((key (org-table-current-field-formula 'key 'noerror))
10742 (eql (sort (org-table-get-stored-formulas 'noerror)
10743 'org-table-formula-less-p))
10744 (pos (move-marker (make-marker) (point)))
10745 (startline 1)
10746 (wc (current-window-configuration))
10747 (titles '((column . "# Column Formulas\n")
10748 (field . "# Field Formulas\n")
10749 (named . "# Named Field Formulas\n")))
10750 entry s type title)
10751 (org-switch-to-buffer-other-window "*Edit Formulas*")
10752 (erase-buffer)
10753 ;; Keep global-font-lock-mode from turning on font-lock-mode
10754 (let ((font-lock-global-modes '(not fundamental-mode)))
10755 (fundamental-mode))
10756 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10757 (org-set-local 'org-pos pos)
10758 (org-set-local 'org-window-configuration wc)
10759 (use-local-map org-table-fedit-map)
10760 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10761 (easy-menu-add org-table-fedit-menu)
10762 (setq startline (org-current-line))
10763 (while (setq entry (pop eql))
10764 (setq type (cond
10765 ((equal (string-to-char (car entry)) ?@) 'field)
10766 ((string-match "^[0-9]" (car entry)) 'column)
10767 (t 'named)))
10768 (when (setq title (assq type titles))
10769 (or (bobp) (insert "\n"))
10770 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10771 (setq titles (delq title titles)))
10772 (if (equal key (car entry)) (setq startline (org-current-line)))
10773 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10774 (car entry) " = " (cdr entry) "\n"))
10775 (remove-text-properties 0 (length s) '(face nil) s)
10776 (insert s))
10777 (if (eq org-table-use-standard-references t)
10778 (org-table-fedit-toggle-ref-type))
10779 (goto-line startline)
10780 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10782 (defun org-table-fedit-post-command ()
10783 (when (not (memq this-command '(lisp-complete-symbol)))
10784 (let ((win (selected-window)))
10785 (save-excursion
10786 (condition-case nil
10787 (org-table-show-reference)
10788 (error nil))
10789 (select-window win)))))
10791 (defun org-table-formula-to-user (s)
10792 "Convert a formula from internal to user representation."
10793 (if (eq org-table-use-standard-references t)
10794 (org-table-convert-refs-to-an s)
10797 (defun org-table-formula-from-user (s)
10798 "Convert a formula from user to internal representation."
10799 (if org-table-use-standard-references
10800 (org-table-convert-refs-to-rc s)
10803 (defun org-table-convert-refs-to-rc (s)
10804 "Convert spreadsheet references from AB7 to @7$28.
10805 Works for single references, but also for entire formulas and even the
10806 full TBLFM line."
10807 (let ((start 0))
10808 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10809 (cond
10810 ((match-end 3)
10811 ;; format match, just advance
10812 (setq start (match-end 0)))
10813 ((and (> (match-beginning 0) 0)
10814 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10815 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10816 ;; 3.e5 or something like this.
10817 (setq start (match-end 0)))
10819 (setq start (match-beginning 0)
10820 s (replace-match
10821 (if (equal (match-string 2 s) "&")
10822 (format "$%d" (org-letters-to-number (match-string 1 s)))
10823 (format "@%d$%d"
10824 (string-to-number (match-string 2 s))
10825 (org-letters-to-number (match-string 1 s))))
10826 t t s)))))
10829 (defun org-table-convert-refs-to-an (s)
10830 "Convert spreadsheet references from to @7$28 to AB7.
10831 Works for single references, but also for entire formulas and even the
10832 full TBLFM line."
10833 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10834 (setq s (replace-match
10835 (format "%s%d"
10836 (org-number-to-letters
10837 (string-to-number (match-string 2 s)))
10838 (string-to-number (match-string 1 s)))
10839 t t s)))
10840 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10841 (setq s (replace-match (concat "\\1"
10842 (org-number-to-letters
10843 (string-to-number (match-string 2 s))) "&")
10844 t nil s)))
10847 (defun org-letters-to-number (s)
10848 "Convert a base 26 number represented by letters into an integer.
10849 For example: AB -> 28."
10850 (let ((n 0))
10851 (setq s (upcase s))
10852 (while (> (length s) 0)
10853 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10854 s (substring s 1)))
10857 (defun org-number-to-letters (n)
10858 "Convert an integer into a base 26 number represented by letters.
10859 For example: 28 -> AB."
10860 (let ((s ""))
10861 (while (> n 0)
10862 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10863 n (/ (1- n) 26)))
10866 (defun org-table-fedit-convert-buffer (function)
10867 "Convert all references in this buffer, using FUNTION."
10868 (let ((line (org-current-line)))
10869 (goto-char (point-min))
10870 (while (not (eobp))
10871 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10872 (delete-region (point) (point-at-eol))
10873 (or (eobp) (forward-char 1)))
10874 (goto-line line)))
10876 (defun org-table-fedit-toggle-ref-type ()
10877 "Convert all references in the buffer from B3 to @3$2 and back."
10878 (interactive)
10879 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10880 (org-table-fedit-convert-buffer
10881 (if org-table-buffer-is-an
10882 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10883 (message "Reference type switched to %s"
10884 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10886 (defun org-table-fedit-ref-up ()
10887 "Shift the reference at point one row/hline up."
10888 (interactive)
10889 (org-table-fedit-shift-reference 'up))
10890 (defun org-table-fedit-ref-down ()
10891 "Shift the reference at point one row/hline down."
10892 (interactive)
10893 (org-table-fedit-shift-reference 'down))
10894 (defun org-table-fedit-ref-left ()
10895 "Shift the reference at point one field to the left."
10896 (interactive)
10897 (org-table-fedit-shift-reference 'left))
10898 (defun org-table-fedit-ref-right ()
10899 "Shift the reference at point one field to the right."
10900 (interactive)
10901 (org-table-fedit-shift-reference 'right))
10903 (defun org-table-fedit-shift-reference (dir)
10904 (cond
10905 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10906 (if (memq dir '(left right))
10907 (org-rematch-and-replace 1 (eq dir 'left))
10908 (error "Cannot shift reference in this direction")))
10909 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10910 ;; A B3-like reference
10911 (if (memq dir '(up down))
10912 (org-rematch-and-replace 2 (eq dir 'up))
10913 (org-rematch-and-replace 1 (eq dir 'left))))
10914 ((org-at-regexp-p
10915 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10916 ;; An internal reference
10917 (if (memq dir '(up down))
10918 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10919 (org-rematch-and-replace 5 (eq dir 'left))))))
10921 (defun org-rematch-and-replace (n &optional decr hline)
10922 "Re-match the group N, and replace it with the shifted refrence."
10923 (or (match-end n) (error "Cannot shift reference in this direction"))
10924 (goto-char (match-beginning n))
10925 (and (looking-at (regexp-quote (match-string n)))
10926 (replace-match (org-shift-refpart (match-string 0) decr hline)
10927 t t)))
10929 (defun org-shift-refpart (ref &optional decr hline)
10930 "Shift a refrence part REF.
10931 If DECR is set, decrease the references row/column, else increase.
10932 If HLINE is set, this may be a hline reference, it certainly is not
10933 a translation reference."
10934 (save-match-data
10935 (let* ((sign (string-match "^[-+]" ref)) n)
10937 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10938 (cond
10939 ((and hline (string-match "^I+" ref))
10940 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10941 (setq n (+ n (if decr -1 1)))
10942 (if (= n 0) (setq n (+ n (if decr -1 1))))
10943 (if sign
10944 (setq sign (if (< n 0) "-" "+") n (abs n))
10945 (setq n (max 1 n)))
10946 (concat sign (make-string n ?I)))
10948 ((string-match "^[0-9]+" ref)
10949 (setq n (string-to-number (concat sign ref)))
10950 (setq n (+ n (if decr -1 1)))
10951 (if sign
10952 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10953 (number-to-string (max 1 n))))
10955 ((string-match "^[a-zA-Z]+" ref)
10956 (org-number-to-letters
10957 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10959 (t (error "Cannot shift reference"))))))
10961 (defun org-table-fedit-toggle-coordinates ()
10962 "Toggle the display of coordinates in the refrenced table."
10963 (interactive)
10964 (let ((pos (marker-position org-pos)))
10965 (with-current-buffer (marker-buffer org-pos)
10966 (save-excursion
10967 (goto-char pos)
10968 (org-table-toggle-coordinate-overlays)))))
10970 (defun org-table-fedit-finish (&optional arg)
10971 "Parse the buffer for formula definitions and install them.
10972 With prefix ARG, apply the new formulas to the table."
10973 (interactive "P")
10974 (org-table-remove-rectangle-highlight)
10975 (if org-table-use-standard-references
10976 (progn
10977 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10978 (setq org-table-buffer-is-an nil)))
10979 (let ((pos org-pos) eql var form)
10980 (goto-char (point-min))
10981 (while (re-search-forward
10982 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10983 nil t)
10984 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10985 form (match-string 3))
10986 (setq form (org-trim form))
10987 (when (not (equal form ""))
10988 (while (string-match "[ \t]*\n[ \t]*" form)
10989 (setq form (replace-match " " t t form)))
10990 (when (assoc var eql)
10991 (error "Double formulas for %s" var))
10992 (push (cons var form) eql)))
10993 (setq org-pos nil)
10994 (set-window-configuration org-window-configuration)
10995 (select-window (get-buffer-window (marker-buffer pos)))
10996 (goto-char pos)
10997 (unless (org-at-table-p)
10998 (error "Lost table position - cannot install formulae"))
10999 (org-table-store-formulas eql)
11000 (move-marker pos nil)
11001 (kill-buffer "*Edit Formulas*")
11002 (if arg
11003 (org-table-recalculate 'all)
11004 (message "New formulas installed - press C-u C-c C-c to apply."))))
11006 (defun org-table-fedit-abort ()
11007 "Abort editing formulas, without installing the changes."
11008 (interactive)
11009 (org-table-remove-rectangle-highlight)
11010 (let ((pos org-pos))
11011 (set-window-configuration org-window-configuration)
11012 (select-window (get-buffer-window (marker-buffer pos)))
11013 (goto-char pos)
11014 (move-marker pos nil)
11015 (message "Formula editing aborted without installing changes")))
11017 (defun org-table-fedit-lisp-indent ()
11018 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
11019 (interactive)
11020 (let ((pos (point)) beg end ind)
11021 (beginning-of-line 1)
11022 (cond
11023 ((looking-at "[ \t]")
11024 (goto-char pos)
11025 (call-interactively 'lisp-indent-line))
11026 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11027 ((not (fboundp 'pp-buffer))
11028 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11029 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11030 (goto-char (- (match-end 0) 2))
11031 (setq beg (point))
11032 (setq ind (make-string (current-column) ?\ ))
11033 (condition-case nil (forward-sexp 1)
11034 (error
11035 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11036 (setq end (point))
11037 (save-restriction
11038 (narrow-to-region beg end)
11039 (if (eq last-command this-command)
11040 (progn
11041 (goto-char (point-min))
11042 (setq this-command nil)
11043 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11044 (replace-match " ")))
11045 (pp-buffer)
11046 (untabify (point-min) (point-max))
11047 (goto-char (1+ (point-min)))
11048 (while (re-search-forward "^." nil t)
11049 (beginning-of-line 1)
11050 (insert ind))
11051 (goto-char (point-max))
11052 (backward-delete-char 1)))
11053 (goto-char beg))
11054 (t nil))))
11056 (defvar org-show-positions nil)
11058 (defun org-table-show-reference (&optional local)
11059 "Show the location/value of the $ expression at point."
11060 (interactive)
11061 (org-table-remove-rectangle-highlight)
11062 (catch 'exit
11063 (let ((pos (if local (point) org-pos))
11064 (face2 'highlight)
11065 (org-inhibit-highlight-removal t)
11066 (win (selected-window))
11067 (org-show-positions nil)
11068 var name e what match dest)
11069 (if local (org-table-get-specials))
11070 (setq what (cond
11071 ((or (org-at-regexp-p org-table-range-regexp2)
11072 (org-at-regexp-p org-table-translate-regexp)
11073 (org-at-regexp-p org-table-range-regexp))
11074 (setq match
11075 (save-match-data
11076 (org-table-convert-refs-to-rc (match-string 0))))
11077 'range)
11078 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11079 ((org-at-regexp-p "\\$[0-9]+") 'column)
11080 ((not local) nil)
11081 (t (error "No reference at point")))
11082 match (and what (or match (match-string 0))))
11083 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11084 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11085 'secondary-selection))
11086 (org-add-hook 'before-change-functions
11087 'org-table-remove-rectangle-highlight)
11088 (if (eq what 'name) (setq var (substring match 1)))
11089 (when (eq what 'range)
11090 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11091 (setq match (org-table-formula-substitute-names match)))
11092 (unless local
11093 (save-excursion
11094 (end-of-line 1)
11095 (re-search-backward "^\\S-" nil t)
11096 (beginning-of-line 1)
11097 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11098 (setq dest
11099 (save-match-data
11100 (org-table-convert-refs-to-rc (match-string 1))))
11101 (org-table-add-rectangle-overlay
11102 (match-beginning 1) (match-end 1) face2))))
11103 (if (and (markerp pos) (marker-buffer pos))
11104 (if (get-buffer-window (marker-buffer pos))
11105 (select-window (get-buffer-window (marker-buffer pos)))
11106 (org-switch-to-buffer-other-window (get-buffer-window
11107 (marker-buffer pos)))))
11108 (goto-char pos)
11109 (org-table-force-dataline)
11110 (when dest
11111 (setq name (substring dest 1))
11112 (cond
11113 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11114 (setq e (assoc name org-table-named-field-locations))
11115 (goto-line (nth 1 e))
11116 (org-table-goto-column (nth 2 e)))
11117 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11118 (let ((l (string-to-number (match-string 1 dest)))
11119 (c (string-to-number (match-string 2 dest))))
11120 (goto-line (aref org-table-dlines l))
11121 (org-table-goto-column c)))
11122 (t (org-table-goto-column (string-to-number name))))
11123 (move-marker pos (point))
11124 (org-table-highlight-rectangle nil nil face2))
11125 (cond
11126 ((equal dest match))
11127 ((not match))
11128 ((eq what 'range)
11129 (condition-case nil
11130 (save-excursion
11131 (org-table-get-range match nil nil 'highlight))
11132 (error nil)))
11133 ((setq e (assoc var org-table-named-field-locations))
11134 (goto-line (nth 1 e))
11135 (org-table-goto-column (nth 2 e))
11136 (org-table-highlight-rectangle (point) (point))
11137 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11138 ((setq e (assoc var org-table-column-names))
11139 (org-table-goto-column (string-to-number (cdr e)))
11140 (org-table-highlight-rectangle (point) (point))
11141 (goto-char (org-table-begin))
11142 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11143 (org-table-end) t)
11144 (progn
11145 (goto-char (match-beginning 1))
11146 (org-table-highlight-rectangle)
11147 (message "Named column (column %s)" (cdr e)))
11148 (error "Column name not found")))
11149 ((eq what 'column)
11150 ;; column number
11151 (org-table-goto-column (string-to-number (substring match 1)))
11152 (org-table-highlight-rectangle (point) (point))
11153 (message "Column %s" (substring match 1)))
11154 ((setq e (assoc var org-table-local-parameters))
11155 (goto-char (org-table-begin))
11156 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11157 (progn
11158 (goto-char (match-beginning 1))
11159 (org-table-highlight-rectangle)
11160 (message "Local parameter."))
11161 (error "Parameter not found")))
11163 (cond
11164 ((not var) (error "No reference at point"))
11165 ((setq e (assoc var org-table-formula-constants-local))
11166 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11167 var (cdr e)))
11168 ((setq e (assoc var org-table-formula-constants))
11169 (message "Constant: $%s=%s in `org-table-formula-constants'."
11170 var (cdr e)))
11171 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11172 (message "Constant: $%s=%s, from `constants.el'%s."
11173 var e (format " (%s units)" constants-unit-system)))
11174 (t (error "Undefined name $%s" var)))))
11175 (goto-char pos)
11176 (when (and org-show-positions
11177 (not (memq this-command '(org-table-fedit-scroll
11178 org-table-fedit-scroll-down))))
11179 (push pos org-show-positions)
11180 (push org-table-current-begin-pos org-show-positions)
11181 (let ((min (apply 'min org-show-positions))
11182 (max (apply 'max org-show-positions)))
11183 (goto-char min) (recenter 0)
11184 (goto-char max)
11185 (or (pos-visible-in-window-p max) (recenter -1))))
11186 (select-window win))))
11188 (defun org-table-force-dataline ()
11189 "Make sure the cursor is in a dataline in a table."
11190 (unless (save-excursion
11191 (beginning-of-line 1)
11192 (looking-at org-table-dataline-regexp))
11193 (let* ((re org-table-dataline-regexp)
11194 (p1 (save-excursion (re-search-forward re nil 'move)))
11195 (p2 (save-excursion (re-search-backward re nil 'move))))
11196 (cond ((and p1 p2)
11197 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11198 p1 p2)))
11199 ((or p1 p2) (goto-char (or p1 p2)))
11200 (t (error "No table dataline around here"))))))
11202 (defun org-table-fedit-line-up ()
11203 "Move cursor one line up in the window showing the table."
11204 (interactive)
11205 (org-table-fedit-move 'previous-line))
11207 (defun org-table-fedit-line-down ()
11208 "Move cursor one line down in the window showing the table."
11209 (interactive)
11210 (org-table-fedit-move 'next-line))
11212 (defun org-table-fedit-move (command)
11213 "Move the cursor in the window shoinw the table.
11214 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11215 (let ((org-table-allow-automatic-line-recalculation nil)
11216 (pos org-pos) (win (selected-window)) p)
11217 (select-window (get-buffer-window (marker-buffer org-pos)))
11218 (setq p (point))
11219 (call-interactively command)
11220 (while (and (org-at-table-p)
11221 (org-at-table-hline-p))
11222 (call-interactively command))
11223 (or (org-at-table-p) (goto-char p))
11224 (move-marker pos (point))
11225 (select-window win)))
11227 (defun org-table-fedit-scroll (N)
11228 (interactive "p")
11229 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11230 (scroll-other-window N)))
11232 (defun org-table-fedit-scroll-down (N)
11233 (interactive "p")
11234 (org-table-fedit-scroll (- N)))
11236 (defvar org-table-rectangle-overlays nil)
11238 (defun org-table-add-rectangle-overlay (beg end &optional face)
11239 "Add a new overlay."
11240 (let ((ov (org-make-overlay beg end)))
11241 (org-overlay-put ov 'face (or face 'secondary-selection))
11242 (push ov org-table-rectangle-overlays)))
11244 (defun org-table-highlight-rectangle (&optional beg end face)
11245 "Highlight rectangular region in a table."
11246 (setq beg (or beg (point)) end (or end (point)))
11247 (let ((b (min beg end))
11248 (e (max beg end))
11249 l1 c1 l2 c2 tmp)
11250 (and (boundp 'org-show-positions)
11251 (setq org-show-positions (cons b (cons e org-show-positions))))
11252 (goto-char (min beg end))
11253 (setq l1 (org-current-line)
11254 c1 (org-table-current-column))
11255 (goto-char (max beg end))
11256 (setq l2 (org-current-line)
11257 c2 (org-table-current-column))
11258 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11259 (goto-line l1)
11260 (beginning-of-line 1)
11261 (loop for line from l1 to l2 do
11262 (when (looking-at org-table-dataline-regexp)
11263 (org-table-goto-column c1)
11264 (skip-chars-backward "^|\n") (setq beg (point))
11265 (org-table-goto-column c2)
11266 (skip-chars-forward "^|\n") (setq end (point))
11267 (org-table-add-rectangle-overlay beg end face))
11268 (beginning-of-line 2))
11269 (goto-char b))
11270 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11272 (defun org-table-remove-rectangle-highlight (&rest ignore)
11273 "Remove the rectangle overlays."
11274 (unless org-inhibit-highlight-removal
11275 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11276 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11277 (setq org-table-rectangle-overlays nil)))
11279 (defvar org-table-coordinate-overlays nil
11280 "Collects the cooordinate grid overlays, so that they can be removed.")
11281 (make-variable-buffer-local 'org-table-coordinate-overlays)
11283 (defun org-table-overlay-coordinates ()
11284 "Add overlays to the table at point, to show row/column coordinates."
11285 (interactive)
11286 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11287 (setq org-table-coordinate-overlays nil)
11288 (save-excursion
11289 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11290 (goto-char (org-table-begin))
11291 (while (org-at-table-p)
11292 (setq eol (point-at-eol))
11293 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11294 (push ov org-table-coordinate-overlays)
11295 (setq hline (looking-at org-table-hline-regexp))
11296 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11297 (format "%4d" (setq id (1+ id)))))
11298 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11299 (when hline
11300 (setq ic 0)
11301 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11302 (setq beg (1+ (match-beginning 0))
11303 ic (1+ ic)
11304 s1 (concat "$" (int-to-string ic))
11305 s2 (org-number-to-letters ic)
11306 str (if (eq org-table-use-standard-references t) s2 s1))
11307 (setq ov (org-make-overlay beg (+ beg (length str))))
11308 (push ov org-table-coordinate-overlays)
11309 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11310 (beginning-of-line 2)))))
11312 (defun org-table-toggle-coordinate-overlays ()
11313 "Toggle the display of Row/Column numbers in tables."
11314 (interactive)
11315 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11316 (message "Row/Column number display turned %s"
11317 (if org-table-overlay-coordinates "on" "off"))
11318 (if (and (org-at-table-p) org-table-overlay-coordinates)
11319 (org-table-align))
11320 (unless org-table-overlay-coordinates
11321 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11322 (setq org-table-coordinate-overlays nil)))
11324 (defun org-table-toggle-formula-debugger ()
11325 "Toggle the formula debugger in tables."
11326 (interactive)
11327 (setq org-table-formula-debug (not org-table-formula-debug))
11328 (message "Formula debugging has been turned %s"
11329 (if org-table-formula-debug "on" "off")))
11331 ;;; The orgtbl minor mode
11333 ;; Define a minor mode which can be used in other modes in order to
11334 ;; integrate the org-mode table editor.
11336 ;; This is really a hack, because the org-mode table editor uses several
11337 ;; keys which normally belong to the major mode, for example the TAB and
11338 ;; RET keys. Here is how it works: The minor mode defines all the keys
11339 ;; necessary to operate the table editor, but wraps the commands into a
11340 ;; function which tests if the cursor is currently inside a table. If that
11341 ;; is the case, the table editor command is executed. However, when any of
11342 ;; those keys is used outside a table, the function uses `key-binding' to
11343 ;; look up if the key has an associated command in another currently active
11344 ;; keymap (minor modes, major mode, global), and executes that command.
11345 ;; There might be problems if any of the keys used by the table editor is
11346 ;; otherwise used as a prefix key.
11348 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11349 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11350 ;; addresses this by checking explicitly for both bindings.
11352 ;; The optimized version (see variable `orgtbl-optimized') takes over
11353 ;; all keys which are bound to `self-insert-command' in the *global map*.
11354 ;; Some modes bind other commands to simple characters, for example
11355 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11356 ;; active, this binding is ignored inside tables and replaced with a
11357 ;; modified self-insert.
11359 (defvar orgtbl-mode nil
11360 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11361 table editor in arbitrary modes.")
11362 (make-variable-buffer-local 'orgtbl-mode)
11364 (defvar orgtbl-mode-map (make-keymap)
11365 "Keymap for `orgtbl-mode'.")
11367 ;;;###autoload
11368 (defun turn-on-orgtbl ()
11369 "Unconditionally turn on `orgtbl-mode'."
11370 (orgtbl-mode 1))
11372 (defvar org-old-auto-fill-inhibit-regexp nil
11373 "Local variable used by `orgtbl-mode'")
11375 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11376 "Matches a line belonging to an orgtbl.")
11378 (defconst orgtbl-extra-font-lock-keywords
11379 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11380 0 (quote 'org-table) 'prepend))
11381 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11383 ;;;###autoload
11384 (defun orgtbl-mode (&optional arg)
11385 "The `org-mode' table editor as a minor mode for use in other modes."
11386 (interactive)
11387 (if (org-mode-p)
11388 ;; Exit without error, in case some hook functions calls this
11389 ;; by accident in org-mode.
11390 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11391 (setq orgtbl-mode
11392 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11393 (if orgtbl-mode
11394 (progn
11395 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11396 ;; Make sure we are first in minor-mode-map-alist
11397 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11398 (and c (setq minor-mode-map-alist
11399 (cons c (delq c minor-mode-map-alist)))))
11400 (org-set-local (quote org-table-may-need-update) t)
11401 (org-add-hook 'before-change-functions 'org-before-change-function
11402 nil 'local)
11403 (org-set-local 'org-old-auto-fill-inhibit-regexp
11404 auto-fill-inhibit-regexp)
11405 (org-set-local 'auto-fill-inhibit-regexp
11406 (if auto-fill-inhibit-regexp
11407 (concat orgtbl-line-start-regexp "\\|"
11408 auto-fill-inhibit-regexp)
11409 orgtbl-line-start-regexp))
11410 (org-add-to-invisibility-spec '(org-cwidth))
11411 (when (fboundp 'font-lock-add-keywords)
11412 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11413 (org-restart-font-lock))
11414 (easy-menu-add orgtbl-mode-menu)
11415 (run-hooks 'orgtbl-mode-hook))
11416 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11417 (org-cleanup-narrow-column-properties)
11418 (org-remove-from-invisibility-spec '(org-cwidth))
11419 (remove-hook 'before-change-functions 'org-before-change-function t)
11420 (when (fboundp 'font-lock-remove-keywords)
11421 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11422 (org-restart-font-lock))
11423 (easy-menu-remove orgtbl-mode-menu)
11424 (force-mode-line-update 'all))))
11426 (defun org-cleanup-narrow-column-properties ()
11427 "Remove all properties related to narrow-column invisibility."
11428 (let ((s 1))
11429 (while (setq s (text-property-any s (point-max)
11430 'display org-narrow-column-arrow))
11431 (remove-text-properties s (1+ s) '(display t)))
11432 (setq s 1)
11433 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11434 (remove-text-properties s (1+ s) '(org-cwidth t)))
11435 (setq s 1)
11436 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11437 (remove-text-properties s (1+ s) '(invisible t)))))
11439 ;; Install it as a minor mode.
11440 (put 'orgtbl-mode :included t)
11441 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11442 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11444 (defun orgtbl-make-binding (fun n &rest keys)
11445 "Create a function for binding in the table minor mode.
11446 FUN is the command to call inside a table. N is used to create a unique
11447 command name. KEYS are keys that should be checked in for a command
11448 to execute outside of tables."
11449 (eval
11450 (list 'defun
11451 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11452 '(arg)
11453 (concat "In tables, run `" (symbol-name fun) "'.\n"
11454 "Outside of tables, run the binding of `"
11455 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11456 "'.")
11457 '(interactive "p")
11458 (list 'if
11459 '(org-at-table-p)
11460 (list 'call-interactively (list 'quote fun))
11461 (list 'let '(orgtbl-mode)
11462 (list 'call-interactively
11463 (append '(or)
11464 (mapcar (lambda (k)
11465 (list 'key-binding k))
11466 keys)
11467 '('orgtbl-error))))))))
11469 (defun orgtbl-error ()
11470 "Error when there is no default binding for a table key."
11471 (interactive)
11472 (error "This key has no function outside tables"))
11474 (defun orgtbl-setup ()
11475 "Setup orgtbl keymaps."
11476 (let ((nfunc 0)
11477 (bindings
11478 (list
11479 '([(meta shift left)] org-table-delete-column)
11480 '([(meta left)] org-table-move-column-left)
11481 '([(meta right)] org-table-move-column-right)
11482 '([(meta shift right)] org-table-insert-column)
11483 '([(meta shift up)] org-table-kill-row)
11484 '([(meta shift down)] org-table-insert-row)
11485 '([(meta up)] org-table-move-row-up)
11486 '([(meta down)] org-table-move-row-down)
11487 '("\C-c\C-w" org-table-cut-region)
11488 '("\C-c\M-w" org-table-copy-region)
11489 '("\C-c\C-y" org-table-paste-rectangle)
11490 '("\C-c-" org-table-insert-hline)
11491 '("\C-c}" org-table-toggle-coordinate-overlays)
11492 '("\C-c{" org-table-toggle-formula-debugger)
11493 '("\C-m" org-table-next-row)
11494 '([(shift return)] org-table-copy-down)
11495 '("\C-c\C-q" org-table-wrap-region)
11496 '("\C-c?" org-table-field-info)
11497 '("\C-c " org-table-blank-field)
11498 '("\C-c+" org-table-sum)
11499 '("\C-c=" org-table-eval-formula)
11500 '("\C-c'" org-table-edit-formulas)
11501 '("\C-c`" org-table-edit-field)
11502 '("\C-c*" org-table-recalculate)
11503 '("\C-c|" org-table-create-or-convert-from-region)
11504 '("\C-c^" org-table-sort-lines)
11505 '([(control ?#)] org-table-rotate-recalc-marks)))
11506 elt key fun cmd)
11507 (while (setq elt (pop bindings))
11508 (setq nfunc (1+ nfunc))
11509 (setq key (org-key (car elt))
11510 fun (nth 1 elt)
11511 cmd (orgtbl-make-binding fun nfunc key))
11512 (org-defkey orgtbl-mode-map key cmd))
11514 ;; Special treatment needed for TAB and RET
11515 (org-defkey orgtbl-mode-map [(return)]
11516 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11517 (org-defkey orgtbl-mode-map "\C-m"
11518 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11520 (org-defkey orgtbl-mode-map [(tab)]
11521 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11522 (org-defkey orgtbl-mode-map "\C-i"
11523 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11525 (org-defkey orgtbl-mode-map [(shift tab)]
11526 (orgtbl-make-binding 'org-table-previous-field 104
11527 [(shift tab)] [(tab)] "\C-i"))
11529 (org-defkey orgtbl-mode-map "\M-\C-m"
11530 (orgtbl-make-binding 'org-table-wrap-region 105
11531 "\M-\C-m" [(meta return)]))
11532 (org-defkey orgtbl-mode-map [(meta return)]
11533 (orgtbl-make-binding 'org-table-wrap-region 106
11534 [(meta return)] "\M-\C-m"))
11536 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11537 (when orgtbl-optimized
11538 ;; If the user wants maximum table support, we need to hijack
11539 ;; some standard editing functions
11540 (org-remap orgtbl-mode-map
11541 'self-insert-command 'orgtbl-self-insert-command
11542 'delete-char 'org-delete-char
11543 'delete-backward-char 'org-delete-backward-char)
11544 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11545 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11546 '("OrgTbl"
11547 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11548 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11549 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11550 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11551 "--"
11552 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11553 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11554 ["Copy Field from Above"
11555 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11556 "--"
11557 ("Column"
11558 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11559 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11560 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11561 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11562 ("Row"
11563 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11564 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11565 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11566 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11567 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11568 "--"
11569 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11570 ("Rectangle"
11571 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11572 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11573 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11574 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11575 "--"
11576 ("Radio tables"
11577 ["Insert table template" orgtbl-insert-radio-table
11578 (assq major-mode orgtbl-radio-table-templates)]
11579 ["Comment/uncomment table" orgtbl-toggle-comment t])
11580 "--"
11581 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11582 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11583 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11584 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11585 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11586 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11587 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11588 ["Sum Column/Rectangle" org-table-sum
11589 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11590 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11591 ["Debug Formulas"
11592 org-table-toggle-formula-debugger :active (org-at-table-p)
11593 :keys "C-c {"
11594 :style toggle :selected org-table-formula-debug]
11595 ["Show Col/Row Numbers"
11596 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11597 :keys "C-c }"
11598 :style toggle :selected org-table-overlay-coordinates]
11602 (defun orgtbl-ctrl-c-ctrl-c (arg)
11603 "If the cursor is inside a table, realign the table.
11604 It it is a table to be sent away to a receiver, do it.
11605 With prefix arg, also recompute table."
11606 (interactive "P")
11607 (let ((pos (point)) action)
11608 (save-excursion
11609 (beginning-of-line 1)
11610 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11611 ((looking-at "[ \t]*|") pos)
11612 ((looking-at "#\\+TBLFM:") 'recalc))))
11613 (cond
11614 ((integerp action)
11615 (goto-char action)
11616 (org-table-maybe-eval-formula)
11617 (if arg
11618 (call-interactively 'org-table-recalculate)
11619 (org-table-maybe-recalculate-line))
11620 (call-interactively 'org-table-align)
11621 (orgtbl-send-table 'maybe))
11622 ((eq action 'recalc)
11623 (save-excursion
11624 (beginning-of-line 1)
11625 (skip-chars-backward " \r\n\t")
11626 (if (org-at-table-p)
11627 (org-call-with-arg 'org-table-recalculate t))))
11628 (t (let (orgtbl-mode)
11629 (call-interactively (key-binding "\C-c\C-c")))))))
11631 (defun orgtbl-tab (arg)
11632 "Justification and field motion for `orgtbl-mode'."
11633 (interactive "P")
11634 (if arg (org-table-edit-field t)
11635 (org-table-justify-field-maybe)
11636 (org-table-next-field)))
11638 (defun orgtbl-ret ()
11639 "Justification and field motion for `orgtbl-mode'."
11640 (interactive)
11641 (org-table-justify-field-maybe)
11642 (org-table-next-row))
11644 (defun orgtbl-self-insert-command (N)
11645 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11646 If the cursor is in a table looking at whitespace, the whitespace is
11647 overwritten, and the table is not marked as requiring realignment."
11648 (interactive "p")
11649 (if (and (org-at-table-p)
11651 (and org-table-auto-blank-field
11652 (member last-command
11653 '(orgtbl-hijacker-command-100
11654 orgtbl-hijacker-command-101
11655 orgtbl-hijacker-command-102
11656 orgtbl-hijacker-command-103
11657 orgtbl-hijacker-command-104
11658 orgtbl-hijacker-command-105))
11659 (org-table-blank-field))
11661 (eq N 1)
11662 (looking-at "[^|\n]* +|"))
11663 (let (org-table-may-need-update)
11664 (goto-char (1- (match-end 0)))
11665 (delete-backward-char 1)
11666 (goto-char (match-beginning 0))
11667 (self-insert-command N))
11668 (setq org-table-may-need-update t)
11669 (let (orgtbl-mode)
11670 (call-interactively (key-binding (vector last-input-event))))))
11672 (defun org-force-self-insert (N)
11673 "Needed to enforce self-insert under remapping."
11674 (interactive "p")
11675 (self-insert-command N))
11677 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11678 "Regula expression matching exponentials as produced by calc.")
11680 (defvar org-table-clean-did-remove-column nil)
11682 (defun orgtbl-export (table target)
11683 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11684 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11685 org-table-last-alignment org-table-last-column-widths
11686 maxcol column)
11687 (if (not (fboundp func))
11688 (error "Cannot export orgtbl table to %s" target))
11689 (setq lines (org-table-clean-before-export lines))
11690 (setq table
11691 (mapcar
11692 (lambda (x)
11693 (if (string-match org-table-hline-regexp x)
11694 'hline
11695 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11696 lines))
11697 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11698 table)))
11699 (loop for i from (1- maxcol) downto 0 do
11700 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11701 (setq column (delq nil column))
11702 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11703 (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))
11704 (funcall func table nil)))
11706 (defun orgtbl-send-table (&optional maybe)
11707 "Send a tranformed version of this table to the receiver position.
11708 With argument MAYBE, fail quietly if no transformation is defined for
11709 this table."
11710 (interactive)
11711 (catch 'exit
11712 (unless (org-at-table-p) (error "Not at a table"))
11713 ;; when non-interactive, we assume align has just happened.
11714 (when (interactive-p) (org-table-align))
11715 (save-excursion
11716 (goto-char (org-table-begin))
11717 (beginning-of-line 0)
11718 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11719 (if maybe
11720 (throw 'exit nil)
11721 (error "Don't know how to transform this table."))))
11722 (let* ((name (match-string 1))
11724 (transform (intern (match-string 2)))
11725 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11726 (skip (plist-get params :skip))
11727 (skipcols (plist-get params :skipcols))
11728 (txt (buffer-substring-no-properties
11729 (org-table-begin) (org-table-end)))
11730 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11731 (lines (org-table-clean-before-export lines))
11732 (i0 (if org-table-clean-did-remove-column 2 1))
11733 (table (mapcar
11734 (lambda (x)
11735 (if (string-match org-table-hline-regexp x)
11736 'hline
11737 (org-remove-by-index
11738 (org-split-string (org-trim x) "\\s-*|\\s-*")
11739 skipcols i0)))
11740 lines))
11741 (fun (if (= i0 2) 'cdr 'identity))
11742 (org-table-last-alignment
11743 (org-remove-by-index (funcall fun org-table-last-alignment)
11744 skipcols i0))
11745 (org-table-last-column-widths
11746 (org-remove-by-index (funcall fun org-table-last-column-widths)
11747 skipcols i0)))
11749 (unless (fboundp transform)
11750 (error "No such transformation function %s" transform))
11751 (setq txt (funcall transform table params))
11752 ;; Find the insertion place
11753 (save-excursion
11754 (goto-char (point-min))
11755 (unless (re-search-forward
11756 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11757 (error "Don't know where to insert translated table"))
11758 (goto-char (match-beginning 0))
11759 (beginning-of-line 2)
11760 (setq beg (point))
11761 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11762 (error "Cannot find end of insertion region"))
11763 (beginning-of-line 1)
11764 (delete-region beg (point))
11765 (goto-char beg)
11766 (insert txt "\n"))
11767 (message "Table converted and installed at receiver location"))))
11769 (defun org-remove-by-index (list indices &optional i0)
11770 "Remove the elements in LIST with indices in INDICES.
11771 First element has index 0, or I0 if given."
11772 (if (not indices)
11773 list
11774 (if (integerp indices) (setq indices (list indices)))
11775 (setq i0 (1- (or i0 0)))
11776 (delq :rm (mapcar (lambda (x)
11777 (setq i0 (1+ i0))
11778 (if (memq i0 indices) :rm x))
11779 list))))
11781 (defun orgtbl-toggle-comment ()
11782 "Comment or uncomment the orgtbl at point."
11783 (interactive)
11784 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11785 (re2 (concat "^" orgtbl-line-start-regexp))
11786 (commented (save-excursion (beginning-of-line 1)
11787 (cond ((looking-at re1) t)
11788 ((looking-at re2) nil)
11789 (t (error "Not at an org table")))))
11790 (re (if commented re1 re2))
11791 beg end)
11792 (save-excursion
11793 (beginning-of-line 1)
11794 (while (looking-at re) (beginning-of-line 0))
11795 (beginning-of-line 2)
11796 (setq beg (point))
11797 (while (looking-at re) (beginning-of-line 2))
11798 (setq end (point)))
11799 (comment-region beg end (if commented '(4) nil))))
11801 (defun orgtbl-insert-radio-table ()
11802 "Insert a radio table template appropriate for this major mode."
11803 (interactive)
11804 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11805 (txt (nth 1 e))
11806 name pos)
11807 (unless e (error "No radio table setup defined for %s" major-mode))
11808 (setq name (read-string "Table name: "))
11809 (while (string-match "%n" txt)
11810 (setq txt (replace-match name t t txt)))
11811 (or (bolp) (insert "\n"))
11812 (setq pos (point))
11813 (insert txt)
11814 (goto-char pos)))
11816 (defun org-get-param (params header i sym &optional hsym)
11817 "Get parameter value for symbol SYM.
11818 If this is a header line, actually get the value for the symbol with an
11819 additional \"h\" inserted after the colon.
11820 If the value is a protperty list, get the element for the current column.
11821 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11822 (let ((val (plist-get params sym)))
11823 (and hsym header (setq val (or (plist-get params hsym) val)))
11824 (if (consp val) (plist-get val i) val)))
11826 (defun orgtbl-to-generic (table params)
11827 "Convert the orgtbl-mode TABLE to some other format.
11828 This generic routine can be used for many standard cases.
11829 TABLE is a list, each entry either the symbol `hline' for a horizontal
11830 separator line, or a list of fields for that line.
11831 PARAMS is a property list of parameters that can influence the conversion.
11832 For the generic converter, some parameters are obligatory: You need to
11833 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11834 :splice, you must have :tstart and :tend.
11836 Valid parameters are
11838 :tstart String to start the table. Ignored when :splice is t.
11839 :tend String to end the table. Ignored when :splice is t.
11841 :splice When set to t, return only table body lines, don't wrap
11842 them into :tstart and :tend. Default is nil.
11844 :hline String to be inserted on horizontal separation lines.
11845 May be nil to ignore hlines.
11847 :lstart String to start a new table line.
11848 :lend String to end a table line
11849 :sep Separator between two fields
11850 :lfmt Format for entire line, with enough %s to capture all fields.
11851 If this is present, :lstart, :lend, and :sep are ignored.
11852 :fmt A format to be used to wrap the field, should contain
11853 %s for the original field value. For example, to wrap
11854 everything in dollars, you could use :fmt \"$%s$\".
11855 This may also be a property list with column numbers and
11856 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11858 :hlstart :hlend :hlsep :hlfmt :hfmt
11859 Same as above, specific for the header lines in the table.
11860 All lines before the first hline are treated as header.
11861 If any of these is not present, the data line value is used.
11863 :efmt Use this format to print numbers with exponentials.
11864 The format should have %s twice for inserting mantissa
11865 and exponent, for example \"%s\\\\times10^{%s}\". This
11866 may also be a property list with column numbers and
11867 formats. :fmt will still be applied after :efmt.
11869 In addition to this, the parameters :skip and :skipcols are always handled
11870 directly by `orgtbl-send-table'. See manual."
11871 (interactive)
11872 (let* ((p params)
11873 (splicep (plist-get p :splice))
11874 (hline (plist-get p :hline))
11875 rtn line i fm efm lfmt h)
11877 ;; Do we have a header?
11878 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11879 (setq h t))
11881 ;; Put header
11882 (unless splicep
11883 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11885 ;; Now loop over all lines
11886 (while (setq line (pop table))
11887 (if (eq line 'hline)
11888 ;; A horizontal separator line
11889 (progn (if hline (push hline rtn))
11890 (setq h nil)) ; no longer in header
11891 ;; A normal line. Convert the fields, push line onto the result list
11892 (setq i 0)
11893 (setq line
11894 (mapcar
11895 (lambda (f)
11896 (setq i (1+ i)
11897 fm (org-get-param p h i :fmt :hfmt)
11898 efm (org-get-param p h i :efmt))
11899 (if (and efm (string-match orgtbl-exp-regexp f))
11900 (setq f (format
11901 efm (match-string 1 f) (match-string 2 f))))
11902 (if fm (setq f (format fm f)))
11904 line))
11905 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11906 (push (apply 'format lfmt line) rtn)
11907 (push (concat
11908 (org-get-param p h i :lstart :hlstart)
11909 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11910 (org-get-param p h i :lend :hlend))
11911 rtn))))
11913 (unless splicep
11914 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11916 (mapconcat 'identity (nreverse rtn) "\n")))
11918 (defun orgtbl-to-latex (table params)
11919 "Convert the orgtbl-mode TABLE to LaTeX.
11920 TABLE is a list, each entry either the symbol `hline' for a horizontal
11921 separator line, or a list of fields for that line.
11922 PARAMS is a property list of parameters that can influence the conversion.
11923 Supports all parameters from `orgtbl-to-generic'. Most important for
11924 LaTeX are:
11926 :splice When set to t, return only table body lines, don't wrap
11927 them into a tabular environment. Default is nil.
11929 :fmt A format to be used to wrap the field, should contain %s for the
11930 original field value. For example, to wrap everything in dollars,
11931 use :fmt \"$%s$\". This may also be a property list with column
11932 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11934 :efmt Format for transforming numbers with exponentials. The format
11935 should have %s twice for inserting mantissa and exponent, for
11936 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11937 This may also be a property list with column numbers and formats.
11939 The general parameters :skip and :skipcols have already been applied when
11940 this function is called."
11941 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11942 org-table-last-alignment ""))
11943 (params2
11944 (list
11945 :tstart (concat "\\begin{tabular}{" alignment "}")
11946 :tend "\\end{tabular}"
11947 :lstart "" :lend " \\\\" :sep " & "
11948 :efmt "%s\\,(%s)" :hline "\\hline")))
11949 (orgtbl-to-generic table (org-combine-plists params2 params))))
11951 (defun orgtbl-to-html (table params)
11952 "Convert the orgtbl-mode TABLE to LaTeX.
11953 TABLE is a list, each entry either the symbol `hline' for a horizontal
11954 separator line, or a list of fields for that line.
11955 PARAMS is a property list of parameters that can influence the conversion.
11956 Currently this function recognizes the following parameters:
11958 :splice When set to t, return only table body lines, don't wrap
11959 them into a <table> environment. Default is nil.
11961 The general parameters :skip and :skipcols have already been applied when
11962 this function is called. The function does *not* use `orgtbl-to-generic',
11963 so you cannot specify parameters for it."
11964 (let* ((splicep (plist-get params :splice))
11965 html)
11966 ;; Just call the formatter we already have
11967 ;; We need to make text lines for it, so put the fields back together.
11968 (setq html (org-format-org-table-html
11969 (mapcar
11970 (lambda (x)
11971 (if (eq x 'hline)
11972 "|----+----|"
11973 (concat "| " (mapconcat 'identity x " | ") " |")))
11974 table)
11975 splicep))
11976 (if (string-match "\n+\\'" html)
11977 (setq html (replace-match "" t t html)))
11978 html))
11980 (defun orgtbl-to-texinfo (table params)
11981 "Convert the orgtbl-mode TABLE to TeXInfo.
11982 TABLE is a list, each entry either the symbol `hline' for a horizontal
11983 separator line, or a list of fields for that line.
11984 PARAMS is a property list of parameters that can influence the conversion.
11985 Supports all parameters from `orgtbl-to-generic'. Most important for
11986 TeXInfo are:
11988 :splice nil/t When set to t, return only table body lines, don't wrap
11989 them into a multitable environment. Default is nil.
11991 :fmt fmt A format to be used to wrap the field, should contain
11992 %s for the original field value. For example, to wrap
11993 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11994 This may also be a property list with column numbers and
11995 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11997 :cf \"f1 f2..\" The column fractions for the table. By default these
11998 are computed automatically from the width of the columns
11999 under org-mode.
12001 The general parameters :skip and :skipcols have already been applied when
12002 this function is called."
12003 (let* ((total (float (apply '+ org-table-last-column-widths)))
12004 (colfrac (or (plist-get params :cf)
12005 (mapconcat
12006 (lambda (x) (format "%.3f" (/ (float x) total)))
12007 org-table-last-column-widths " ")))
12008 (params2
12009 (list
12010 :tstart (concat "@multitable @columnfractions " colfrac)
12011 :tend "@end multitable"
12012 :lstart "@item " :lend "" :sep " @tab "
12013 :hlstart "@headitem ")))
12014 (orgtbl-to-generic table (org-combine-plists params2 params))))
12016 ;;;; Link Stuff
12018 ;;; Link abbreviations
12020 (defun org-link-expand-abbrev (link)
12021 "Apply replacements as defined in `org-link-abbrev-alist."
12022 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
12023 (let* ((key (match-string 1 link))
12024 (as (or (assoc key org-link-abbrev-alist-local)
12025 (assoc key org-link-abbrev-alist)))
12026 (tag (and (match-end 2) (match-string 3 link)))
12027 rpl)
12028 (if (not as)
12029 link
12030 (setq rpl (cdr as))
12031 (cond
12032 ((symbolp rpl) (funcall rpl tag))
12033 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12034 (t (concat rpl tag)))))
12035 link))
12037 ;;; Storing and inserting links
12039 (defvar org-insert-link-history nil
12040 "Minibuffer history for links inserted with `org-insert-link'.")
12042 (defvar org-stored-links nil
12043 "Contains the links stored with `org-store-link'.")
12045 (defvar org-store-link-plist nil
12046 "Plist with info about the most recently link created with `org-store-link'.")
12048 (defvar org-link-protocols nil
12049 "Link protocols added to Org-mode using `org-add-link-type'.")
12051 (defvar org-store-link-functions nil
12052 "List of functions that are called to create and store a link.
12053 Each function will be called in turn until one returns a non-nil
12054 value. Each function should check if it is responsible for creating
12055 this link (for example by looking at the major mode).
12056 If not, it must exit and return nil.
12057 If yes, it should return a non-nil value after a calling
12058 `org-store-link-props' with a list of properties and values.
12059 Special properties are:
12061 :type The link prefix. like \"http\". This must be given.
12062 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12063 This is obligatory as well.
12064 :description Optional default description for the second pair
12065 of brackets in an Org-mode link. The user can still change
12066 this when inserting this link into an Org-mode buffer.
12068 In addition to these, any additional properties can be specified
12069 and then used in remember templates.")
12071 (defun org-add-link-type (type &optional follow publish)
12072 "Add TYPE to the list of `org-link-types'.
12073 Re-compute all regular expressions depending on `org-link-types'
12074 FOLLOW and PUBLISH are two functions. Both take the link path as
12075 an argument.
12076 FOLLOW should do whatever is necessary to follow the link, for example
12077 to find a file or display a mail message.
12079 PUBLISH takes the path and retuns the string that should be used when
12080 this document is published. FIMXE: This is actually not yet implemented."
12081 (add-to-list 'org-link-types type t)
12082 (org-make-link-regexps)
12083 (add-to-list 'org-link-protocols
12084 (list type follow publish)))
12086 (defun org-add-agenda-custom-command (entry)
12087 "Replace or add a command in `org-agenda-custom-commands'.
12088 This is mostly for hacking and trying a new command - once the command
12089 works you probably want to add it to `org-agenda-custom-commands' for good."
12090 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12091 (if ass
12092 (setcdr ass (cdr entry))
12093 (push entry org-agenda-custom-commands))))
12095 ;;;###autoload
12096 (defun org-store-link (arg)
12097 "\\<org-mode-map>Store an org-link to the current location.
12098 This link is added to `org-stored-links' and can later be inserted
12099 into an org-buffer with \\[org-insert-link].
12101 For some link types, a prefix arg is interpreted:
12102 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12103 For file links, arg negates `org-context-in-file-links'."
12104 (interactive "P")
12105 (setq org-store-link-plist nil) ; reset
12106 (let (link cpltxt desc description search txt)
12107 (cond
12109 ((run-hook-with-args-until-success 'org-store-link-functions)
12110 (setq link (plist-get org-store-link-plist :link)
12111 desc (or (plist-get org-store-link-plist :description) link)))
12113 ((eq major-mode 'bbdb-mode)
12114 (let ((name (bbdb-record-name (bbdb-current-record)))
12115 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12116 (setq cpltxt (concat "bbdb:" (or name company))
12117 link (org-make-link cpltxt))
12118 (org-store-link-props :type "bbdb" :name name :company company)))
12120 ((eq major-mode 'Info-mode)
12121 (setq link (org-make-link "info:"
12122 (file-name-nondirectory Info-current-file)
12123 ":" Info-current-node))
12124 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12125 ":" Info-current-node))
12126 (org-store-link-props :type "info" :file Info-current-file
12127 :node Info-current-node))
12129 ((eq major-mode 'calendar-mode)
12130 (let ((cd (calendar-cursor-to-date)))
12131 (setq link
12132 (format-time-string
12133 (car org-time-stamp-formats)
12134 (apply 'encode-time
12135 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12136 nil nil nil))))
12137 (org-store-link-props :type "calendar" :date cd)))
12139 ((or (eq major-mode 'vm-summary-mode)
12140 (eq major-mode 'vm-presentation-mode))
12141 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12142 (vm-follow-summary-cursor)
12143 (save-excursion
12144 (vm-select-folder-buffer)
12145 (let* ((message (car vm-message-pointer))
12146 (folder buffer-file-name)
12147 (subject (vm-su-subject message))
12148 (to (vm-get-header-contents message "To"))
12149 (from (vm-get-header-contents message "From"))
12150 (message-id (vm-su-message-id message)))
12151 (org-store-link-props :type "vm" :from from :to to :subject subject
12152 :message-id message-id)
12153 (setq message-id (org-remove-angle-brackets message-id))
12154 (setq folder (abbreviate-file-name folder))
12155 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12156 folder)
12157 (setq folder (replace-match "" t t folder)))
12158 (setq cpltxt (org-email-link-description))
12159 (setq link (org-make-link "vm:" folder "#" message-id)))))
12161 ((eq major-mode 'wl-summary-mode)
12162 (let* ((msgnum (wl-summary-message-number))
12163 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12164 msgnum 'message-id))
12165 (wl-message-entity
12166 (if (fboundp 'elmo-message-entity)
12167 (elmo-message-entity
12168 wl-summary-buffer-elmo-folder msgnum)
12169 (elmo-msgdb-overview-get-entity
12170 msgnum (wl-summary-buffer-msgdb))))
12171 (from (wl-summary-line-from))
12172 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12173 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12174 (wl-summary-line-subject))))
12175 (org-store-link-props :type "wl" :from from :to to
12176 :subject subject :message-id message-id)
12177 (setq message-id (org-remove-angle-brackets message-id))
12178 (setq cpltxt (org-email-link-description))
12179 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12180 "#" message-id))))
12182 ((or (equal major-mode 'mh-folder-mode)
12183 (equal major-mode 'mh-show-mode))
12184 (let ((from (org-mhe-get-header "From:"))
12185 (to (org-mhe-get-header "To:"))
12186 (message-id (org-mhe-get-header "Message-Id:"))
12187 (subject (org-mhe-get-header "Subject:")))
12188 (org-store-link-props :type "mh" :from from :to to
12189 :subject subject :message-id message-id)
12190 (setq cpltxt (org-email-link-description))
12191 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12192 (org-remove-angle-brackets message-id)))))
12194 ((or (eq major-mode 'rmail-mode)
12195 (eq major-mode 'rmail-summary-mode))
12196 (save-window-excursion
12197 (save-restriction
12198 (when (eq major-mode 'rmail-summary-mode)
12199 (rmail-show-message rmail-current-message))
12200 (rmail-narrow-to-non-pruned-header)
12201 (let ((folder buffer-file-name)
12202 (message-id (mail-fetch-field "message-id"))
12203 (from (mail-fetch-field "from"))
12204 (to (mail-fetch-field "to"))
12205 (subject (mail-fetch-field "subject")))
12206 (org-store-link-props
12207 :type "rmail" :from from :to to
12208 :subject subject :message-id message-id)
12209 (setq message-id (org-remove-angle-brackets message-id))
12210 (setq cpltxt (org-email-link-description))
12211 (setq link (org-make-link "rmail:" folder "#" message-id)))
12212 (rmail-show-message rmail-current-message))))
12214 ((eq major-mode 'gnus-group-mode)
12215 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12216 (gnus-group-group-name)) ; version
12217 ((fboundp 'gnus-group-name)
12218 (gnus-group-name))
12219 (t "???"))))
12220 (unless group (error "Not on a group"))
12221 (org-store-link-props :type "gnus" :group group)
12222 (setq cpltxt (concat
12223 (if (org-xor arg org-usenet-links-prefer-google)
12224 "http://groups.google.com/groups?group="
12225 "gnus:")
12226 group)
12227 link (org-make-link cpltxt))))
12229 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12230 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12231 (let* ((group gnus-newsgroup-name)
12232 (article (gnus-summary-article-number))
12233 (header (gnus-summary-article-header article))
12234 (from (mail-header-from header))
12235 (message-id (mail-header-id header))
12236 (date (mail-header-date header))
12237 (subject (gnus-summary-subject-string)))
12238 (org-store-link-props :type "gnus" :from from :subject subject
12239 :message-id message-id :group group)
12240 (setq cpltxt (org-email-link-description))
12241 (if (org-xor arg org-usenet-links-prefer-google)
12242 (setq link
12243 (concat
12244 cpltxt "\n "
12245 (format "http://groups.google.com/groups?as_umsgid=%s"
12246 (org-fixup-message-id-for-http message-id))))
12247 (setq link (org-make-link "gnus:" group
12248 "#" (number-to-string article))))))
12250 ((eq major-mode 'w3-mode)
12251 (setq cpltxt (url-view-url t)
12252 link (org-make-link cpltxt))
12253 (org-store-link-props :type "w3" :url (url-view-url t)))
12255 ((eq major-mode 'w3m-mode)
12256 (setq cpltxt (or w3m-current-title w3m-current-url)
12257 link (org-make-link w3m-current-url))
12258 (org-store-link-props :type "w3m" :url (url-view-url t)))
12260 ((setq search (run-hook-with-args-until-success
12261 'org-create-file-search-functions))
12262 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12263 "::" search))
12264 (setq cpltxt (or description link)))
12266 ((eq major-mode 'image-mode)
12267 (setq cpltxt (concat "file:"
12268 (abbreviate-file-name buffer-file-name))
12269 link (org-make-link cpltxt))
12270 (org-store-link-props :type "image" :file buffer-file-name))
12272 ((eq major-mode 'dired-mode)
12273 ;; link to the file in the current line
12274 (setq cpltxt (concat "file:"
12275 (abbreviate-file-name
12276 (expand-file-name
12277 (dired-get-filename nil t))))
12278 link (org-make-link cpltxt)))
12280 ((and buffer-file-name (org-mode-p))
12281 ;; Just link to current headline
12282 (setq cpltxt (concat "file:"
12283 (abbreviate-file-name buffer-file-name)))
12284 ;; Add a context search string
12285 (when (org-xor org-context-in-file-links arg)
12286 ;; Check if we are on a target
12287 (if (org-in-regexp "<<\\(.*?\\)>>")
12288 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12289 (setq txt (cond
12290 ((org-on-heading-p) nil)
12291 ((org-region-active-p)
12292 (buffer-substring (region-beginning) (region-end)))
12293 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12294 (when (or (null txt) (string-match "\\S-" txt))
12295 (setq cpltxt
12296 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12297 desc "NONE"))))
12298 (if (string-match "::\\'" cpltxt)
12299 (setq cpltxt (substring cpltxt 0 -2)))
12300 (setq link (org-make-link cpltxt)))
12302 ((buffer-file-name (buffer-base-buffer))
12303 ;; Just link to this file here.
12304 (setq cpltxt (concat "file:"
12305 (abbreviate-file-name
12306 (buffer-file-name (buffer-base-buffer)))))
12307 ;; Add a context string
12308 (when (org-xor org-context-in-file-links arg)
12309 (setq txt (if (org-region-active-p)
12310 (buffer-substring (region-beginning) (region-end))
12311 (buffer-substring (point-at-bol) (point-at-eol))))
12312 ;; Only use search option if there is some text.
12313 (when (string-match "\\S-" txt)
12314 (setq cpltxt
12315 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12316 desc "NONE")))
12317 (setq link (org-make-link cpltxt)))
12319 ((interactive-p)
12320 (error "Cannot link to a buffer which is not visiting a file"))
12322 (t (setq link nil)))
12324 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12325 (setq link (or link cpltxt)
12326 desc (or desc cpltxt))
12327 (if (equal desc "NONE") (setq desc nil))
12329 (if (and (interactive-p) link)
12330 (progn
12331 (setq org-stored-links
12332 (cons (list link desc) org-stored-links))
12333 (message "Stored: %s" (or desc link)))
12334 (and link (org-make-link-string link desc)))))
12336 (defun org-store-link-props (&rest plist)
12337 "Store link properties, extract names and addresses."
12338 (let (x adr)
12339 (when (setq x (plist-get plist :from))
12340 (setq adr (mail-extract-address-components x))
12341 (plist-put plist :fromname (car adr))
12342 (plist-put plist :fromaddress (nth 1 adr)))
12343 (when (setq x (plist-get plist :to))
12344 (setq adr (mail-extract-address-components x))
12345 (plist-put plist :toname (car adr))
12346 (plist-put plist :toaddress (nth 1 adr))))
12347 (let ((from (plist-get plist :from))
12348 (to (plist-get plist :to)))
12349 (when (and from to org-from-is-user-regexp)
12350 (plist-put plist :fromto
12351 (if (string-match org-from-is-user-regexp from)
12352 (concat "to %t")
12353 (concat "from %f")))))
12354 (setq org-store-link-plist plist))
12356 (defun org-email-link-description (&optional fmt)
12357 "Return the description part of an email link.
12358 This takes information from `org-store-link-plist' and formats it
12359 according to FMT (default from `org-email-link-description-format')."
12360 (setq fmt (or fmt org-email-link-description-format))
12361 (let* ((p org-store-link-plist)
12362 (to (plist-get p :toaddress))
12363 (from (plist-get p :fromaddress))
12364 (table
12365 (list
12366 (cons "%c" (plist-get p :fromto))
12367 (cons "%F" (plist-get p :from))
12368 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12369 (cons "%T" (plist-get p :to))
12370 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12371 (cons "%s" (plist-get p :subject))
12372 (cons "%m" (plist-get p :message-id)))))
12373 (when (string-match "%c" fmt)
12374 ;; Check if the user wrote this message
12375 (if (and org-from-is-user-regexp from to
12376 (save-match-data (string-match org-from-is-user-regexp from)))
12377 (setq fmt (replace-match "to %t" t t fmt))
12378 (setq fmt (replace-match "from %f" t t fmt))))
12379 (org-replace-escapes fmt table)))
12381 (defun org-make-org-heading-search-string (&optional string heading)
12382 "Make search string for STRING or current headline."
12383 (interactive)
12384 (let ((s (or string (org-get-heading))))
12385 (unless (and string (not heading))
12386 ;; We are using a headline, clean up garbage in there.
12387 (if (string-match org-todo-regexp s)
12388 (setq s (replace-match "" t t s)))
12389 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12390 (setq s (replace-match "" t t s)))
12391 (setq s (org-trim s))
12392 (if (string-match (concat "^\\(" org-quote-string "\\|"
12393 org-comment-string "\\)") s)
12394 (setq s (replace-match "" t t s)))
12395 (while (string-match org-ts-regexp s)
12396 (setq s (replace-match "" t t s))))
12397 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12398 (setq s (replace-match " " t t s)))
12399 (or string (setq s (concat "*" s))) ; Add * for headlines
12400 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12402 (defun org-make-link (&rest strings)
12403 "Concatenate STRINGS."
12404 (apply 'concat strings))
12406 (defun org-make-link-string (link &optional description)
12407 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12408 (unless (string-match "\\S-" link)
12409 (error "Empty link"))
12410 (when (stringp description)
12411 ;; Remove brackets from the description, they are fatal.
12412 (while (string-match "\\[" description)
12413 (setq description (replace-match "{" t t description)))
12414 (while (string-match "\\]" description)
12415 (setq description (replace-match "}" t t description))))
12416 (when (equal (org-link-escape link) description)
12417 ;; No description needed, it is identical
12418 (setq description nil))
12419 (when (and (not description)
12420 (not (equal link (org-link-escape link))))
12421 (setq description link))
12422 (concat "[[" (org-link-escape link) "]"
12423 (if description (concat "[" description "]") "")
12424 "]"))
12426 (defconst org-link-escape-chars
12427 '((?\ . "%20")
12428 (?\[ . "%5B")
12429 (?\] . "%5D")
12430 (?\340 . "%E0") ; `a
12431 (?\342 . "%E2") ; ^a
12432 (?\347 . "%E7") ; ,c
12433 (?\350 . "%E8") ; `e
12434 (?\351 . "%E9") ; 'e
12435 (?\352 . "%EA") ; ^e
12436 (?\356 . "%EE") ; ^i
12437 (?\364 . "%F4") ; ^o
12438 (?\371 . "%F9") ; `u
12439 (?\373 . "%FB") ; ^u
12440 (?\; . "%3B")
12441 (?? . "%3F")
12442 (?= . "%3D")
12443 (?+ . "%2B")
12445 "Association list of escapes for some characters problematic in links.
12446 This is the list that is used for internal purposes.")
12448 (defconst org-link-escape-chars-browser
12449 '((?\ . "%20")) ; 32 for the SPC char
12450 "Association list of escapes for some characters problematic in links.
12451 This is the list that is used before handing over to the browser.")
12453 (defun org-link-escape (text &optional table)
12454 "Escape charaters in TEXT that are problematic for links."
12455 (setq table (or table org-link-escape-chars))
12456 (when text
12457 (let ((re (mapconcat (lambda (x) (regexp-quote
12458 (char-to-string (car x))))
12459 table "\\|")))
12460 (while (string-match re text)
12461 (setq text
12462 (replace-match
12463 (cdr (assoc (string-to-char (match-string 0 text))
12464 table))
12465 t t text)))
12466 text)))
12468 (defun org-link-unescape (text &optional table)
12469 "Reverse the action of `org-link-escape'."
12470 (setq table (or table org-link-escape-chars))
12471 (when text
12472 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12473 table "\\|")))
12474 (while (string-match re text)
12475 (setq text
12476 (replace-match
12477 (char-to-string (car (rassoc (match-string 0 text) table)))
12478 t t text)))
12479 text)))
12481 (defun org-xor (a b)
12482 "Exclusive or."
12483 (if a (not b) b))
12485 (defun org-get-header (header)
12486 "Find a header field in the current buffer."
12487 (save-excursion
12488 (goto-char (point-min))
12489 (let ((case-fold-search t) s)
12490 (cond
12491 ((eq header 'from)
12492 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12493 (setq s (match-string 1)))
12494 (while (string-match "\"" s)
12495 (setq s (replace-match "" t t s)))
12496 (if (string-match "[<(].*" s)
12497 (setq s (replace-match "" t t s))))
12498 ((eq header 'message-id)
12499 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12500 (setq s (match-string 1))))
12501 ((eq header 'subject)
12502 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12503 (setq s (match-string 1)))))
12504 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12505 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12506 s)))
12509 (defun org-fixup-message-id-for-http (s)
12510 "Replace special characters in a message id, so it can be used in an http query."
12511 (while (string-match "<" s)
12512 (setq s (replace-match "%3C" t t s)))
12513 (while (string-match ">" s)
12514 (setq s (replace-match "%3E" t t s)))
12515 (while (string-match "@" s)
12516 (setq s (replace-match "%40" t t s)))
12519 ;;;###autoload
12520 (defun org-insert-link-global ()
12521 "Insert a link like Org-mode does.
12522 This command can be called in any mode to insert a link in Org-mode syntax."
12523 (interactive)
12524 (org-run-like-in-org-mode 'org-insert-link))
12526 (defun org-insert-link (&optional complete-file)
12527 "Insert a link. At the prompt, enter the link.
12529 Completion can be used to select a link previously stored with
12530 `org-store-link'. When the empty string is entered (i.e. if you just
12531 press RET at the prompt), the link defaults to the most recently
12532 stored link. As SPC triggers completion in the minibuffer, you need to
12533 use M-SPC or C-q SPC to force the insertion of a space character.
12535 You will also be prompted for a description, and if one is given, it will
12536 be displayed in the buffer instead of the link.
12538 If there is already a link at point, this command will allow you to edit link
12539 and description parts.
12541 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12542 selected using completion. The path to the file will be relative to
12543 the current directory if the file is in the current directory or a
12544 subdirectory. Otherwise, the link will be the absolute path as
12545 completed in the minibuffer (i.e. normally ~/path/to/file).
12547 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12548 is in the current directory or below.
12549 With three \\[universal-argument] prefixes, negate the meaning of
12550 `org-keep-stored-link-after-insertion'."
12551 (interactive "P")
12552 (let* ((wcf (current-window-configuration))
12553 (region (if (org-region-active-p)
12554 (buffer-substring (region-beginning) (region-end))))
12555 (remove (and region (list (region-beginning) (region-end))))
12556 (desc region)
12557 tmphist ; byte-compile incorrectly complains about this
12558 link entry file)
12559 (cond
12560 ((org-in-regexp org-bracket-link-regexp 1)
12561 ;; We do have a link at point, and we are going to edit it.
12562 (setq remove (list (match-beginning 0) (match-end 0)))
12563 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12564 (setq link (read-string "Link: "
12565 (org-link-unescape
12566 (org-match-string-no-properties 1)))))
12567 ((or (org-in-regexp org-angle-link-re)
12568 (org-in-regexp org-plain-link-re))
12569 ;; Convert to bracket link
12570 (setq remove (list (match-beginning 0) (match-end 0))
12571 link (read-string "Link: "
12572 (org-remove-angle-brackets (match-string 0)))))
12573 ((equal complete-file '(4))
12574 ;; Completing read for file names.
12575 (setq file (read-file-name "File: "))
12576 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12577 (pwd1 (file-name-as-directory (abbreviate-file-name
12578 (expand-file-name ".")))))
12579 (cond
12580 ((equal complete-file '(16))
12581 (setq link (org-make-link
12582 "file:"
12583 (abbreviate-file-name (expand-file-name file)))))
12584 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12585 (setq link (org-make-link "file:" (match-string 1 file))))
12586 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12587 (expand-file-name file))
12588 (setq link (org-make-link
12589 "file:" (match-string 1 (expand-file-name file)))))
12590 (t (setq link (org-make-link "file:" file))))))
12592 ;; Read link, with completion for stored links.
12593 (with-output-to-temp-buffer "*Org Links*"
12594 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12595 (when org-stored-links
12596 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12597 (princ (mapconcat
12598 (lambda (x)
12599 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12600 (reverse org-stored-links) "\n"))))
12601 (let ((cw (selected-window)))
12602 (select-window (get-buffer-window "*Org Links*"))
12603 (shrink-window-if-larger-than-buffer)
12604 (setq truncate-lines t)
12605 (select-window cw))
12606 ;; Fake a link history, containing the stored links.
12607 (setq tmphist (append (mapcar 'car org-stored-links)
12608 org-insert-link-history))
12609 (unwind-protect
12610 (setq link (org-completing-read
12611 "Link: "
12612 (append
12613 (mapcar (lambda (x) (list (concat (car x) ":")))
12614 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12615 (mapcar (lambda (x) (list (concat x ":")))
12616 org-link-types))
12617 nil nil nil
12618 'tmphist
12619 (or (car (car org-stored-links)))))
12620 (set-window-configuration wcf)
12621 (kill-buffer "*Org Links*"))
12622 (setq entry (assoc link org-stored-links))
12623 (or entry (push link org-insert-link-history))
12624 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12625 (not org-keep-stored-link-after-insertion))
12626 (setq org-stored-links (delq (assoc link org-stored-links)
12627 org-stored-links)))
12628 (setq desc (or desc (nth 1 entry)))))
12630 (if (string-match org-plain-link-re link)
12631 ;; URL-like link, normalize the use of angular brackets.
12632 (setq link (org-make-link (org-remove-angle-brackets link))))
12634 ;; Check if we are linking to the current file with a search option
12635 ;; If yes, simplify the link by using only the search option.
12636 (when (and buffer-file-name
12637 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12638 (let* ((path (match-string 1 link))
12639 (case-fold-search nil)
12640 (search (match-string 2 link)))
12641 (save-match-data
12642 (if (equal (file-truename buffer-file-name) (file-truename path))
12643 ;; We are linking to this same file, with a search option
12644 (setq link search)))))
12646 ;; Check if we can/should use a relative path. If yes, simplify the link
12647 (when (string-match "\\<file:\\(.*\\)" link)
12648 (let* ((path (match-string 1 link))
12649 (origpath path)
12650 (case-fold-search nil))
12651 (cond
12652 ((eq org-link-file-path-type 'absolute)
12653 (setq path (abbreviate-file-name (expand-file-name path))))
12654 ((eq org-link-file-path-type 'noabbrev)
12655 (setq path (expand-file-name path)))
12656 ((eq org-link-file-path-type 'relative)
12657 (setq path (file-relative-name path)))
12659 (save-match-data
12660 (if (string-match (concat "^" (regexp-quote
12661 (file-name-as-directory
12662 (expand-file-name "."))))
12663 (expand-file-name path))
12664 ;; We are linking a file with relative path name.
12665 (setq path (substring (expand-file-name path)
12666 (match-end 0)))))))
12667 (setq link (concat "file:" path))
12668 (if (equal desc origpath)
12669 (setq desc path))))
12671 (setq desc (read-string "Description: " desc))
12672 (unless (string-match "\\S-" desc) (setq desc nil))
12673 (if remove (apply 'delete-region remove))
12674 (insert (org-make-link-string link desc))))
12676 (defun org-completing-read (&rest args)
12677 (let ((minibuffer-local-completion-map
12678 (copy-keymap minibuffer-local-completion-map)))
12679 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12680 (apply 'completing-read args)))
12682 ;;; Opening/following a link
12683 (defvar org-link-search-failed nil)
12685 (defun org-next-link ()
12686 "Move forward to the next link.
12687 If the link is in hidden text, expose it."
12688 (interactive)
12689 (when (and org-link-search-failed (eq this-command last-command))
12690 (goto-char (point-min))
12691 (message "Link search wrapped back to beginning of buffer"))
12692 (setq org-link-search-failed nil)
12693 (let* ((pos (point))
12694 (ct (org-context))
12695 (a (assoc :link ct)))
12696 (if a (goto-char (nth 2 a)))
12697 (if (re-search-forward org-any-link-re nil t)
12698 (progn
12699 (goto-char (match-beginning 0))
12700 (if (org-invisible-p) (org-show-context)))
12701 (goto-char pos)
12702 (setq org-link-search-failed t)
12703 (error "No further link found"))))
12705 (defun org-previous-link ()
12706 "Move backward to the previous link.
12707 If the link is in hidden text, expose it."
12708 (interactive)
12709 (when (and org-link-search-failed (eq this-command last-command))
12710 (goto-char (point-max))
12711 (message "Link search wrapped back to end of buffer"))
12712 (setq org-link-search-failed nil)
12713 (let* ((pos (point))
12714 (ct (org-context))
12715 (a (assoc :link ct)))
12716 (if a (goto-char (nth 1 a)))
12717 (if (re-search-backward org-any-link-re nil t)
12718 (progn
12719 (goto-char (match-beginning 0))
12720 (if (org-invisible-p) (org-show-context)))
12721 (goto-char pos)
12722 (setq org-link-search-failed t)
12723 (error "No further link found"))))
12725 (defun org-find-file-at-mouse (ev)
12726 "Open file link or URL at mouse."
12727 (interactive "e")
12728 (mouse-set-point ev)
12729 (org-open-at-point 'in-emacs))
12731 (defun org-open-at-mouse (ev)
12732 "Open file link or URL at mouse."
12733 (interactive "e")
12734 (mouse-set-point ev)
12735 (org-open-at-point))
12737 (defvar org-window-config-before-follow-link nil
12738 "The window configuration before following a link.
12739 This is saved in case the need arises to restore it.")
12741 (defvar org-open-link-marker (make-marker)
12742 "Marker pointing to the location where `org-open-at-point; was called.")
12744 ;;;###autoload
12745 (defun org-open-at-point-global ()
12746 "Follow a link like Org-mode does.
12747 This command can be called in any mode to follow a link that has
12748 Org-mode syntax."
12749 (interactive)
12750 (org-run-like-in-org-mode 'org-open-at-point))
12752 (defun org-open-at-point (&optional in-emacs)
12753 "Open link at or after point.
12754 If there is no link at point, this function will search forward up to
12755 the end of the current subtree.
12756 Normally, files will be opened by an appropriate application. If the
12757 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12758 (interactive "P")
12759 (move-marker org-open-link-marker (point))
12760 (setq org-window-config-before-follow-link (current-window-configuration))
12761 (org-remove-occur-highlights nil nil t)
12762 (if (org-at-timestamp-p t)
12763 (org-follow-timestamp-link)
12764 (let (type path link line search (pos (point)))
12765 (catch 'match
12766 (save-excursion
12767 (skip-chars-forward "^]\n\r")
12768 (when (org-in-regexp org-bracket-link-regexp)
12769 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12770 (while (string-match " *\n *" link)
12771 (setq link (replace-match " " t t link)))
12772 (setq link (org-link-expand-abbrev link))
12773 (if (string-match org-link-re-with-space2 link)
12774 (setq type (match-string 1 link) path (match-string 2 link))
12775 (setq type "thisfile" path link))
12776 (throw 'match t)))
12778 (when (get-text-property (point) 'org-linked-text)
12779 (setq type "thisfile"
12780 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12781 (1+ (point)) (point))
12782 path (buffer-substring
12783 (previous-single-property-change pos 'org-linked-text)
12784 (next-single-property-change pos 'org-linked-text)))
12785 (throw 'match t))
12787 (save-excursion
12788 (when (or (org-in-regexp org-angle-link-re)
12789 (org-in-regexp org-plain-link-re))
12790 (setq type (match-string 1) path (match-string 2))
12791 (throw 'match t)))
12792 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12793 (setq type "tree-match"
12794 path (match-string 1))
12795 (throw 'match t))
12796 (save-excursion
12797 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12798 (setq type "tags"
12799 path (match-string 1))
12800 (while (string-match ":" path)
12801 (setq path (replace-match "+" t t path)))
12802 (throw 'match t))))
12803 (unless path
12804 (error "No link found"))
12805 ;; Remove any trailing spaces in path
12806 (if (string-match " +\\'" path)
12807 (setq path (replace-match "" t t path)))
12809 (cond
12811 ((assoc type org-link-protocols)
12812 (funcall (nth 1 (assoc type org-link-protocols)) path))
12814 ((equal type "mailto")
12815 (let ((cmd (car org-link-mailto-program))
12816 (args (cdr org-link-mailto-program)) args1
12817 (address path) (subject "") a)
12818 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12819 (setq address (match-string 1 path)
12820 subject (org-link-escape (match-string 2 path))))
12821 (while args
12822 (cond
12823 ((not (stringp (car args))) (push (pop args) args1))
12824 (t (setq a (pop args))
12825 (if (string-match "%a" a)
12826 (setq a (replace-match address t t a)))
12827 (if (string-match "%s" a)
12828 (setq a (replace-match subject t t a)))
12829 (push a args1))))
12830 (apply cmd (nreverse args1))))
12832 ((member type '("http" "https" "ftp" "news"))
12833 (browse-url (concat type ":" (org-link-escape
12834 path org-link-escape-chars-browser))))
12836 ((member type '("message"))
12837 (browse-url (concat type ":" path)))
12839 ((string= type "tags")
12840 (org-tags-view in-emacs path))
12841 ((string= type "thisfile")
12842 (if in-emacs
12843 (switch-to-buffer-other-window
12844 (org-get-buffer-for-internal-link (current-buffer)))
12845 (org-mark-ring-push))
12846 (let ((cmd `(org-link-search
12847 ,path
12848 ,(cond ((equal in-emacs '(4)) 'occur)
12849 ((equal in-emacs '(16)) 'org-occur)
12850 (t nil))
12851 ,pos)))
12852 (condition-case nil (eval cmd)
12853 (error (progn (widen) (eval cmd))))))
12855 ((string= type "tree-match")
12856 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12858 ((string= type "file")
12859 (if (string-match "::\\([0-9]+\\)\\'" path)
12860 (setq line (string-to-number (match-string 1 path))
12861 path (substring path 0 (match-beginning 0)))
12862 (if (string-match "::\\(.+\\)\\'" path)
12863 (setq search (match-string 1 path)
12864 path (substring path 0 (match-beginning 0)))))
12865 (if (string-match "[*?{]" (file-name-nondirectory path))
12866 (dired path)
12867 (org-open-file path in-emacs line search)))
12869 ((string= type "news")
12870 (org-follow-gnus-link path))
12872 ((string= type "bbdb")
12873 (org-follow-bbdb-link path))
12875 ((string= type "info")
12876 (org-follow-info-link path))
12878 ((string= type "gnus")
12879 (let (group article)
12880 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12881 (error "Error in Gnus link"))
12882 (setq group (match-string 1 path)
12883 article (match-string 3 path))
12884 (org-follow-gnus-link group article)))
12886 ((string= type "vm")
12887 (let (folder article)
12888 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12889 (error "Error in VM link"))
12890 (setq folder (match-string 1 path)
12891 article (match-string 3 path))
12892 ;; in-emacs is the prefix arg, will be interpreted as read-only
12893 (org-follow-vm-link folder article in-emacs)))
12895 ((string= type "wl")
12896 (let (folder article)
12897 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12898 (error "Error in Wanderlust link"))
12899 (setq folder (match-string 1 path)
12900 article (match-string 3 path))
12901 (org-follow-wl-link folder article)))
12903 ((string= type "mhe")
12904 (let (folder article)
12905 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12906 (error "Error in MHE link"))
12907 (setq folder (match-string 1 path)
12908 article (match-string 3 path))
12909 (org-follow-mhe-link folder article)))
12911 ((string= type "rmail")
12912 (let (folder article)
12913 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12914 (error "Error in RMAIL link"))
12915 (setq folder (match-string 1 path)
12916 article (match-string 3 path))
12917 (org-follow-rmail-link folder article)))
12919 ((string= type "shell")
12920 (let ((cmd path))
12921 (if (or (not org-confirm-shell-link-function)
12922 (funcall org-confirm-shell-link-function
12923 (format "Execute \"%s\" in shell? "
12924 (org-add-props cmd nil
12925 'face 'org-warning))))
12926 (progn
12927 (message "Executing %s" cmd)
12928 (shell-command cmd))
12929 (error "Abort"))))
12931 ((string= type "elisp")
12932 (let ((cmd path))
12933 (if (or (not org-confirm-elisp-link-function)
12934 (funcall org-confirm-elisp-link-function
12935 (format "Execute \"%s\" as elisp? "
12936 (org-add-props cmd nil
12937 'face 'org-warning))))
12938 (message "%s => %s" cmd (eval (read cmd)))
12939 (error "Abort"))))
12942 (browse-url-at-point)))))
12943 (move-marker org-open-link-marker nil)
12944 (run-hook-with-args 'org-follow-link-hook))
12946 ;;; File search
12948 (defvar org-create-file-search-functions nil
12949 "List of functions to construct the right search string for a file link.
12950 These functions are called in turn with point at the location to
12951 which the link should point.
12953 A function in the hook should first test if it would like to
12954 handle this file type, for example by checking the major-mode or
12955 the file extension. If it decides not to handle this file, it
12956 should just return nil to give other functions a chance. If it
12957 does handle the file, it must return the search string to be used
12958 when following the link. The search string will be part of the
12959 file link, given after a double colon, and `org-open-at-point'
12960 will automatically search for it. If special measures must be
12961 taken to make the search successful, another function should be
12962 added to the companion hook `org-execute-file-search-functions',
12963 which see.
12965 A function in this hook may also use `setq' to set the variable
12966 `description' to provide a suggestion for the descriptive text to
12967 be used for this link when it gets inserted into an Org-mode
12968 buffer with \\[org-insert-link].")
12970 (defvar org-execute-file-search-functions nil
12971 "List of functions to execute a file search triggered by a link.
12973 Functions added to this hook must accept a single argument, the
12974 search string that was part of the file link, the part after the
12975 double colon. The function must first check if it would like to
12976 handle this search, for example by checking the major-mode or the
12977 file extension. If it decides not to handle this search, it
12978 should just return nil to give other functions a chance. If it
12979 does handle the search, it must return a non-nil value to keep
12980 other functions from trying.
12982 Each function can access the current prefix argument through the
12983 variable `current-prefix-argument'. Note that a single prefix is
12984 used to force opening a link in Emacs, so it may be good to only
12985 use a numeric or double prefix to guide the search function.
12987 In case this is needed, a function in this hook can also restore
12988 the window configuration before `org-open-at-point' was called using:
12990 (set-window-configuration org-window-config-before-follow-link)")
12992 (defun org-link-search (s &optional type avoid-pos)
12993 "Search for a link search option.
12994 If S is surrounded by forward slashes, it is interpreted as a
12995 regular expression. In org-mode files, this will create an `org-occur'
12996 sparse tree. In ordinary files, `occur' will be used to list matches.
12997 If the current buffer is in `dired-mode', grep will be used to search
12998 in all files. If AVOID-POS is given, ignore matches near that position."
12999 (let ((case-fold-search t)
13000 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
13001 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
13002 (append '(("") (" ") ("\t") ("\n"))
13003 org-emphasis-alist)
13004 "\\|") "\\)"))
13005 (pos (point))
13006 (pre "") (post "")
13007 words re0 re1 re2 re3 re4 re5 re2a reall)
13008 (cond
13009 ;; First check if there are any special
13010 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
13011 ;; Now try the builtin stuff
13012 ((save-excursion
13013 (goto-char (point-min))
13014 (and
13015 (re-search-forward
13016 (concat "<<" (regexp-quote s0) ">>") nil t)
13017 (setq pos (match-beginning 0))))
13018 ;; There is an exact target for this
13019 (goto-char pos))
13020 ((string-match "^/\\(.*\\)/$" s)
13021 ;; A regular expression
13022 (cond
13023 ((org-mode-p)
13024 (org-occur (match-string 1 s)))
13025 ;;((eq major-mode 'dired-mode)
13026 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
13027 (t (org-do-occur (match-string 1 s)))))
13029 ;; A normal search strings
13030 (when (equal (string-to-char s) ?*)
13031 ;; Anchor on headlines, post may include tags.
13032 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
13033 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
13034 s (substring s 1)))
13035 (remove-text-properties
13036 0 (length s)
13037 '(face nil mouse-face nil keymap nil fontified nil) s)
13038 ;; Make a series of regular expressions to find a match
13039 (setq words (org-split-string s "[ \n\r\t]+")
13040 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
13041 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
13042 "\\)" markers)
13043 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13044 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13045 re1 (concat pre re2 post)
13046 re3 (concat pre re4 post)
13047 re5 (concat pre ".*" re4)
13048 re2 (concat pre re2)
13049 re2a (concat pre re2a)
13050 re4 (concat pre re4)
13051 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13052 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13053 re5 "\\)"
13055 (cond
13056 ((eq type 'org-occur) (org-occur reall))
13057 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13058 (t (goto-char (point-min))
13059 (if (or (org-search-not-self 1 re0 nil t)
13060 (org-search-not-self 1 re1 nil t)
13061 (org-search-not-self 1 re2 nil t)
13062 (org-search-not-self 1 re2a nil t)
13063 (org-search-not-self 1 re3 nil t)
13064 (org-search-not-self 1 re4 nil t)
13065 (org-search-not-self 1 re5 nil t)
13067 (goto-char (match-beginning 1))
13068 (goto-char pos)
13069 (error "No match")))))
13071 ;; Normal string-search
13072 (goto-char (point-min))
13073 (if (search-forward s nil t)
13074 (goto-char (match-beginning 0))
13075 (error "No match"))))
13076 (and (org-mode-p) (org-show-context 'link-search))))
13078 (defun org-search-not-self (group &rest args)
13079 "Execute `re-search-forward', but only accept matches that do not
13080 enclose the position of `org-open-link-marker'."
13081 (let ((m org-open-link-marker))
13082 (catch 'exit
13083 (while (apply 're-search-forward args)
13084 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13085 (goto-char (match-end group))
13086 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13087 (> (match-beginning 0) (marker-position m))
13088 (< (match-end 0) (marker-position m)))
13089 (save-match-data
13090 (or (not (org-in-regexp
13091 org-bracket-link-analytic-regexp 1))
13092 (not (match-end 4)) ; no description
13093 (and (<= (match-beginning 4) (point))
13094 (>= (match-end 4) (point))))))
13095 (throw 'exit (point))))))))
13097 (defun org-get-buffer-for-internal-link (buffer)
13098 "Return a buffer to be used for displaying the link target of internal links."
13099 (cond
13100 ((not org-display-internal-link-with-indirect-buffer)
13101 buffer)
13102 ((string-match "(Clone)$" (buffer-name buffer))
13103 (message "Buffer is already a clone, not making another one")
13104 ;; we also do not modify visibility in this case
13105 buffer)
13106 (t ; make a new indirect buffer for displaying the link
13107 (let* ((bn (buffer-name buffer))
13108 (ibn (concat bn "(Clone)"))
13109 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13110 (with-current-buffer ib (org-overview))
13111 ib))))
13113 (defun org-do-occur (regexp &optional cleanup)
13114 "Call the Emacs command `occur'.
13115 If CLEANUP is non-nil, remove the printout of the regular expression
13116 in the *Occur* buffer. This is useful if the regex is long and not useful
13117 to read."
13118 (occur regexp)
13119 (when cleanup
13120 (let ((cwin (selected-window)) win beg end)
13121 (when (setq win (get-buffer-window "*Occur*"))
13122 (select-window win))
13123 (goto-char (point-min))
13124 (when (re-search-forward "match[a-z]+" nil t)
13125 (setq beg (match-end 0))
13126 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13127 (setq end (1- (match-beginning 0)))))
13128 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13129 (goto-char (point-min))
13130 (select-window cwin))))
13132 ;;; The mark ring for links jumps
13134 (defvar org-mark-ring nil
13135 "Mark ring for positions before jumps in Org-mode.")
13136 (defvar org-mark-ring-last-goto nil
13137 "Last position in the mark ring used to go back.")
13138 ;; Fill and close the ring
13139 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13140 (loop for i from 1 to org-mark-ring-length do
13141 (push (make-marker) org-mark-ring))
13142 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13143 org-mark-ring)
13145 (defun org-mark-ring-push (&optional pos buffer)
13146 "Put the current position or POS into the mark ring and rotate it."
13147 (interactive)
13148 (setq pos (or pos (point)))
13149 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13150 (move-marker (car org-mark-ring)
13151 (or pos (point))
13152 (or buffer (current-buffer)))
13153 (message "%s"
13154 (substitute-command-keys
13155 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13157 (defun org-mark-ring-goto (&optional n)
13158 "Jump to the previous position in the mark ring.
13159 With prefix arg N, jump back that many stored positions. When
13160 called several times in succession, walk through the entire ring.
13161 Org-mode commands jumping to a different position in the current file,
13162 or to another Org-mode file, automatically push the old position
13163 onto the ring."
13164 (interactive "p")
13165 (let (p m)
13166 (if (eq last-command this-command)
13167 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13168 (setq p org-mark-ring))
13169 (setq org-mark-ring-last-goto p)
13170 (setq m (car p))
13171 (switch-to-buffer (marker-buffer m))
13172 (goto-char m)
13173 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13175 (defun org-remove-angle-brackets (s)
13176 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13177 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13179 (defun org-add-angle-brackets (s)
13180 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13181 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13184 ;;; Following specific links
13186 (defun org-follow-timestamp-link ()
13187 (cond
13188 ((org-at-date-range-p t)
13189 (let ((org-agenda-start-on-weekday)
13190 (t1 (match-string 1))
13191 (t2 (match-string 2)))
13192 (setq t1 (time-to-days (org-time-string-to-time t1))
13193 t2 (time-to-days (org-time-string-to-time t2)))
13194 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13195 ((org-at-timestamp-p t)
13196 (org-agenda-list nil (time-to-days (org-time-string-to-time
13197 (substring (match-string 1) 0 10)))
13199 (t (error "This should not happen"))))
13202 (defun org-follow-bbdb-link (name)
13203 "Follow a BBDB link to NAME."
13204 (require 'bbdb)
13205 (let ((inhibit-redisplay (not debug-on-error))
13206 (bbdb-electric-p nil))
13207 (catch 'exit
13208 ;; Exact match on name
13209 (bbdb-name (concat "\\`" name "\\'") nil)
13210 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13211 ;; Exact match on name
13212 (bbdb-company (concat "\\`" name "\\'") nil)
13213 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13214 ;; Partial match on name
13215 (bbdb-name name nil)
13216 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13217 ;; Partial match on company
13218 (bbdb-company name nil)
13219 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13220 ;; General match including network address and notes
13221 (bbdb name nil)
13222 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13223 (delete-window (get-buffer-window "*BBDB*"))
13224 (error "No matching BBDB record")))))
13226 (defun org-follow-info-link (name)
13227 "Follow an info file & node link to NAME."
13228 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13229 (string-match "\\(.*\\)" name))
13230 (progn
13231 (require 'info)
13232 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13233 (Info-find-node (match-string 1 name) (match-string 2 name))
13234 (Info-find-node (match-string 1 name) "Top")))
13235 (message "Could not open: %s" name)))
13237 (defun org-follow-gnus-link (&optional group article)
13238 "Follow a Gnus link to GROUP and ARTICLE."
13239 (require 'gnus)
13240 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13241 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13242 (cond ((and group article)
13243 (gnus-group-read-group 1 nil group)
13244 (gnus-summary-goto-article (string-to-number article) nil t))
13245 (group (gnus-group-jump-to-group group))))
13247 (defun org-follow-vm-link (&optional folder article readonly)
13248 "Follow a VM link to FOLDER and ARTICLE."
13249 (require 'vm)
13250 (setq article (org-add-angle-brackets article))
13251 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13252 ;; ange-ftp or efs or tramp access
13253 (let ((user (or (match-string 1 folder) (user-login-name)))
13254 (host (match-string 2 folder))
13255 (file (match-string 3 folder)))
13256 (cond
13257 ((featurep 'tramp)
13258 ;; use tramp to access the file
13259 (if (featurep 'xemacs)
13260 (setq folder (format "[%s@%s]%s" user host file))
13261 (setq folder (format "/%s@%s:%s" user host file))))
13263 ;; use ange-ftp or efs
13264 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13265 (setq folder (format "/%s@%s:%s" user host file))))))
13266 (when folder
13267 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13268 (sit-for 0.1)
13269 (when article
13270 (vm-select-folder-buffer)
13271 (widen)
13272 (let ((case-fold-search t))
13273 (goto-char (point-min))
13274 (if (not (re-search-forward
13275 (concat "^" "message-id: *" (regexp-quote article))))
13276 (error "Could not find the specified message in this folder"))
13277 (vm-isearch-update)
13278 (vm-isearch-narrow)
13279 (vm-beginning-of-message)
13280 (vm-summarize)))))
13282 (defun org-follow-wl-link (folder article)
13283 "Follow a Wanderlust link to FOLDER and ARTICLE."
13284 (if (and (string= folder "%")
13285 article
13286 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13287 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13288 ;; Thus, we recompose folder and article ids.
13289 (setq folder (format "%s#%s" folder (match-string 1 article))
13290 article (match-string 3 article)))
13291 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13292 (error "No such folder: %s" folder))
13293 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13294 (and article
13295 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13296 (wl-summary-redisplay)))
13298 (defun org-follow-rmail-link (folder article)
13299 "Follow an RMAIL link to FOLDER and ARTICLE."
13300 (setq article (org-add-angle-brackets article))
13301 (let (message-number)
13302 (save-excursion
13303 (save-window-excursion
13304 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13305 (setq message-number
13306 (save-restriction
13307 (widen)
13308 (goto-char (point-max))
13309 (if (re-search-backward
13310 (concat "^Message-ID:\\s-+" (regexp-quote
13311 (or article "")))
13312 nil t)
13313 (rmail-what-message))))))
13314 (if message-number
13315 (progn
13316 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13317 (rmail-show-message message-number)
13318 message-number)
13319 (error "Message not found"))))
13321 ;;; mh-e integration based on planner-mode
13322 (defun org-mhe-get-message-real-folder ()
13323 "Return the name of the current message real folder, so if you use
13324 sequences, it will now work."
13325 (save-excursion
13326 (let* ((folder
13327 (if (equal major-mode 'mh-folder-mode)
13328 mh-current-folder
13329 ;; Refer to the show buffer
13330 mh-show-folder-buffer))
13331 (end-index
13332 (if (boundp 'mh-index-folder)
13333 (min (length mh-index-folder) (length folder))))
13335 ;; a simple test on mh-index-data does not work, because
13336 ;; mh-index-data is always nil in a show buffer.
13337 (if (and (boundp 'mh-index-folder)
13338 (string= mh-index-folder (substring folder 0 end-index)))
13339 (if (equal major-mode 'mh-show-mode)
13340 (save-window-excursion
13341 (let (pop-up-frames)
13342 (when (buffer-live-p (get-buffer folder))
13343 (progn
13344 (pop-to-buffer folder)
13345 (org-mhe-get-message-folder-from-index)
13348 (org-mhe-get-message-folder-from-index)
13350 folder
13354 (defun org-mhe-get-message-folder-from-index ()
13355 "Returns the name of the message folder in a index folder buffer."
13356 (save-excursion
13357 (mh-index-previous-folder)
13358 (re-search-forward "^\\(+.*\\)$" nil t)
13359 (message "%s" (match-string 1))))
13361 (defun org-mhe-get-message-folder ()
13362 "Return the name of the current message folder. Be careful if you
13363 use sequences."
13364 (save-excursion
13365 (if (equal major-mode 'mh-folder-mode)
13366 mh-current-folder
13367 ;; Refer to the show buffer
13368 mh-show-folder-buffer)))
13370 (defun org-mhe-get-message-num ()
13371 "Return the number of the current message. Be careful if you
13372 use sequences."
13373 (save-excursion
13374 (if (equal major-mode 'mh-folder-mode)
13375 (mh-get-msg-num nil)
13376 ;; Refer to the show buffer
13377 (mh-show-buffer-message-number))))
13379 (defun org-mhe-get-header (header)
13380 "Return a header of the message in folder mode. This will create a
13381 show buffer for the corresponding message. If you have a more clever
13382 idea..."
13383 (let* ((folder (org-mhe-get-message-folder))
13384 (num (org-mhe-get-message-num))
13385 (buffer (get-buffer-create (concat "show-" folder)))
13386 (header-field))
13387 (with-current-buffer buffer
13388 (mh-display-msg num folder)
13389 (if (equal major-mode 'mh-folder-mode)
13390 (mh-header-display)
13391 (mh-show-header-display))
13392 (set-buffer buffer)
13393 (setq header-field (mh-get-header-field header))
13394 (if (equal major-mode 'mh-folder-mode)
13395 (mh-show)
13396 (mh-show-show))
13397 header-field)))
13399 (defun org-follow-mhe-link (folder article)
13400 "Follow an MHE link to FOLDER and ARTICLE.
13401 If ARTICLE is nil FOLDER is shown. If the configuration variable
13402 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13403 ARTICLE is searched in all folders. Indexed searches (swish++,
13404 namazu, and others supported by MH-E) will always search in all
13405 folders."
13406 (require 'mh-e)
13407 (require 'mh-search)
13408 (require 'mh-utils)
13409 (mh-find-path)
13410 (if (not article)
13411 (mh-visit-folder (mh-normalize-folder-name folder))
13412 (setq article (org-add-angle-brackets article))
13413 (mh-search-choose)
13414 (if (equal mh-searcher 'pick)
13415 (progn
13416 (mh-search folder (list "--message-id" article))
13417 (when (and org-mhe-search-all-folders
13418 (not (org-mhe-get-message-real-folder)))
13419 (kill-this-buffer)
13420 (mh-search "+" (list "--message-id" article))))
13421 (mh-search "+" article))
13422 (if (org-mhe-get-message-real-folder)
13423 (mh-show-msg 1)
13424 (kill-this-buffer)
13425 (error "Message not found"))))
13427 ;;; BibTeX links
13429 ;; Use the custom search meachnism to construct and use search strings for
13430 ;; file links to BibTeX database entries.
13432 (defun org-create-file-search-in-bibtex ()
13433 "Create the search string and description for a BibTeX database entry."
13434 (when (eq major-mode 'bibtex-mode)
13435 ;; yes, we want to construct this search string.
13436 ;; Make a good description for this entry, using names, year and the title
13437 ;; Put it into the `description' variable which is dynamically scoped.
13438 (let ((bibtex-autokey-names 1)
13439 (bibtex-autokey-names-stretch 1)
13440 (bibtex-autokey-name-case-convert-function 'identity)
13441 (bibtex-autokey-name-separator " & ")
13442 (bibtex-autokey-additional-names " et al.")
13443 (bibtex-autokey-year-length 4)
13444 (bibtex-autokey-name-year-separator " ")
13445 (bibtex-autokey-titlewords 3)
13446 (bibtex-autokey-titleword-separator " ")
13447 (bibtex-autokey-titleword-case-convert-function 'identity)
13448 (bibtex-autokey-titleword-length 'infty)
13449 (bibtex-autokey-year-title-separator ": "))
13450 (setq description (bibtex-generate-autokey)))
13451 ;; Now parse the entry, get the key and return it.
13452 (save-excursion
13453 (bibtex-beginning-of-entry)
13454 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13456 (defun org-execute-file-search-in-bibtex (s)
13457 "Find the link search string S as a key for a database entry."
13458 (when (eq major-mode 'bibtex-mode)
13459 ;; Yes, we want to do the search in this file.
13460 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13461 (goto-char (point-min))
13462 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13463 (regexp-quote s) "[ \t\n]*,") nil t)
13464 (goto-char (match-beginning 0)))
13465 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13466 ;; Use double prefix to indicate that any web link should be browsed
13467 (let ((b (current-buffer)) (p (point)))
13468 ;; Restore the window configuration because we just use the web link
13469 (set-window-configuration org-window-config-before-follow-link)
13470 (save-excursion (set-buffer b) (goto-char p)
13471 (bibtex-url)))
13472 (recenter 0)) ; Move entry start to beginning of window
13473 ;; return t to indicate that the search is done.
13476 ;; Finally add the functions to the right hooks.
13477 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13478 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13480 ;; end of Bibtex link setup
13482 ;;; Following file links
13484 (defun org-open-file (path &optional in-emacs line search)
13485 "Open the file at PATH.
13486 First, this expands any special file name abbreviations. Then the
13487 configuration variable `org-file-apps' is checked if it contains an
13488 entry for this file type, and if yes, the corresponding command is launched.
13489 If no application is found, Emacs simply visits the file.
13490 With optional argument IN-EMACS, Emacs will visit the file.
13491 Optional LINE specifies a line to go to, optional SEARCH a string to
13492 search for. If LINE or SEARCH is given, the file will always be
13493 opened in Emacs.
13494 If the file does not exist, an error is thrown."
13495 (setq in-emacs (or in-emacs line search))
13496 (let* ((file (if (equal path "")
13497 buffer-file-name
13498 (substitute-in-file-name (expand-file-name path))))
13499 (apps (append org-file-apps (org-default-apps)))
13500 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13501 (dirp (if remp nil (file-directory-p file)))
13502 (dfile (downcase file))
13503 (old-buffer (current-buffer))
13504 (old-pos (point))
13505 (old-mode major-mode)
13506 ext cmd)
13507 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13508 (setq ext (match-string 1 dfile))
13509 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13510 (setq ext (match-string 1 dfile))))
13511 (if in-emacs
13512 (setq cmd 'emacs)
13513 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13514 (and dirp (cdr (assoc 'directory apps)))
13515 (cdr (assoc ext apps))
13516 (cdr (assoc t apps)))))
13517 (when (eq cmd 'mailcap)
13518 (require 'mailcap)
13519 (mailcap-parse-mailcaps)
13520 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13521 (command (mailcap-mime-info mime-type)))
13522 (if (stringp command)
13523 (setq cmd command)
13524 (setq cmd 'emacs))))
13525 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13526 (not (file-exists-p file))
13527 (not org-open-non-existing-files))
13528 (error "No such file: %s" file))
13529 (cond
13530 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13531 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13532 (while (string-match "['\"]%s['\"]" cmd)
13533 (setq cmd (replace-match "%s" t t cmd)))
13534 (while (string-match "%s" cmd)
13535 (setq cmd (replace-match
13536 (save-match-data (shell-quote-argument file))
13537 t t cmd)))
13538 (save-window-excursion
13539 (start-process-shell-command cmd nil cmd)))
13540 ((or (stringp cmd)
13541 (eq cmd 'emacs))
13542 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13543 (widen)
13544 (if line (goto-line line)
13545 (if search (org-link-search search))))
13546 ((consp cmd)
13547 (eval cmd))
13548 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13549 (and (org-mode-p) (eq old-mode 'org-mode)
13550 (or (not (equal old-buffer (current-buffer)))
13551 (not (equal old-pos (point))))
13552 (org-mark-ring-push old-pos old-buffer))))
13554 (defun org-default-apps ()
13555 "Return the default applications for this operating system."
13556 (cond
13557 ((eq system-type 'darwin)
13558 org-file-apps-defaults-macosx)
13559 ((eq system-type 'windows-nt)
13560 org-file-apps-defaults-windowsnt)
13561 (t org-file-apps-defaults-gnu)))
13563 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13564 (defun org-file-remote-p (file)
13565 "Test whether FILE specifies a location on a remote system.
13566 Return non-nil if the location is indeed remote.
13568 For example, the filename \"/user@host:/foo\" specifies a location
13569 on the system \"/user@host:\"."
13570 (cond ((fboundp 'file-remote-p)
13571 (file-remote-p file))
13572 ((fboundp 'tramp-handle-file-remote-p)
13573 (tramp-handle-file-remote-p file))
13574 ((and (boundp 'ange-ftp-name-format)
13575 (string-match (car ange-ftp-name-format) file))
13577 (t nil)))
13580 ;;;; Hooks for remember.el, and refiling
13582 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13583 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13585 ;;;###autoload
13586 (defun org-remember-insinuate ()
13587 "Setup remember.el for use wiht Org-mode."
13588 (require 'remember)
13589 (setq remember-annotation-functions '(org-remember-annotation))
13590 (setq remember-handler-functions '(org-remember-handler))
13591 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13593 ;;;###autoload
13594 (defun org-remember-annotation ()
13595 "Return a link to the current location as an annotation for remember.el.
13596 If you are using Org-mode files as target for data storage with
13597 remember.el, then the annotations should include a link compatible with the
13598 conventions in Org-mode. This function returns such a link."
13599 (org-store-link nil))
13601 (defconst org-remember-help
13602 "Select a destination location for the note.
13603 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13604 RET on headline -> Store as sublevel entry to current headline
13605 RET at beg-of-buf -> Append to file as level 2 headline
13606 <left>/<right> -> before/after current headline, same headings level")
13608 (defvar org-remember-previous-location nil)
13609 (defvar org-force-remember-template-char) ;; dynamically scoped
13611 ;; Save the major mode of the buffer we called remember from
13612 (defvar org-select-template-temp-major-mode nil)
13614 ;; Temporary store the buffer where remember was called from
13615 (defvar org-select-template-original-buffer nil)
13617 (defun org-select-remember-template (&optional use-char)
13618 (when org-remember-templates
13619 (let* ((pre-selected-templates
13620 (mapcar
13621 (lambda (tpl)
13622 (let ((ctxt (nth 5 tpl))
13623 (mode org-select-template-temp-major-mode)
13624 (buf org-select-template-original-buffer))
13625 (if (or (and (functionp ctxt)
13626 (save-excursion
13627 (set-buffer buf)
13628 ;; Protect the user-defined function from error
13629 (condition-case nil (funcall ctxt) (error nil))))
13630 (and ctxt (listp ctxt)
13631 (delq nil (mapcar (lambda(x) (eq mode x)) ctxt))))
13632 tpl)))
13633 org-remember-templates))
13634 ;; If no template at this point, add the default templates:
13635 (pre-selected-templates1
13636 (if (not (delq nil pre-selected-templates))
13637 (mapcar (lambda(x) (if (not (nth 5 x)) x))
13638 org-remember-templates)
13639 pre-selected-templates))
13640 ;; Then unconditionnally add template for any contexts
13641 (pre-selected-templates2
13642 (append (mapcar (lambda(x) (if (eq (nth 5 x) t) x))
13643 org-remember-templates)
13644 (delq nil pre-selected-templates1)))
13645 (templates (mapcar (lambda (x)
13646 (if (stringp (car x))
13647 (append (list (nth 1 x) (car x)) (cddr x))
13648 (append (list (car x) "") (cdr x))))
13649 (delq nil pre-selected-templates2)))
13650 (char (or use-char
13651 (cond
13652 ((= (length templates) 1)
13653 (caar templates))
13654 ((and (boundp 'org-force-remember-template-char)
13655 org-force-remember-template-char)
13656 (if (stringp org-force-remember-template-char)
13657 (string-to-char org-force-remember-template-char)
13658 org-force-remember-template-char))
13660 (message "Select template: %s"
13661 (mapconcat
13662 (lambda (x)
13663 (cond
13664 ((not (string-match "\\S-" (nth 1 x)))
13665 (format "[%c]" (car x)))
13666 ((equal (downcase (car x))
13667 (downcase (aref (nth 1 x) 0)))
13668 (format "[%c]%s" (car x)
13669 (substring (nth 1 x) 1)))
13670 (t (format "[%c]%s" (car x) (nth 1 x)))))
13671 templates " "))
13672 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13673 (when (equal char0 ?\C-g)
13674 (jump-to-register remember-register)
13675 (kill-buffer remember-buffer))
13676 char0))))))
13677 (cddr (assoc char templates)))))
13679 (defvar x-last-selected-text)
13680 (defvar x-last-selected-text-primary)
13682 ;;;###autoload
13683 (defun org-remember-apply-template (&optional use-char skip-interactive)
13684 "Initialize *remember* buffer with template, invoke `org-mode'.
13685 This function should be placed into `remember-mode-hook' and in fact requires
13686 to be run from that hook to function properly."
13687 (if org-remember-templates
13688 (let* ((entry (org-select-remember-template use-char))
13689 (tpl (car entry))
13690 (plist-p (if org-store-link-plist t nil))
13691 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13692 (string-match "\\S-" (nth 1 entry)))
13693 (nth 1 entry)
13694 org-default-notes-file))
13695 (headline (nth 2 entry))
13696 (v-c (or (and (eq window-system 'x)
13697 (fboundp 'x-cut-buffer-or-selection-value)
13698 (x-cut-buffer-or-selection-value))
13699 (org-bound-and-true-p x-last-selected-text)
13700 (org-bound-and-true-p x-last-selected-text-primary)
13701 (and (> (length kill-ring) 0) (current-kill 0))))
13702 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13703 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13704 (v-u (concat "[" (substring v-t 1 -1) "]"))
13705 (v-U (concat "[" (substring v-T 1 -1) "]"))
13706 ;; `initial' and `annotation' are bound in `remember'
13707 (v-i (if (boundp 'initial) initial))
13708 (v-a (if (and (boundp 'annotation) annotation)
13709 (if (equal annotation "[[]]") "" annotation)
13710 ""))
13711 (v-A (if (and v-a
13712 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13713 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13714 v-a))
13715 (v-n user-full-name)
13716 (org-startup-folded nil)
13717 org-time-was-given org-end-time-was-given x
13718 prompt completions char time pos default histvar)
13719 (setq org-store-link-plist
13720 (append (list :annotation v-a :initial v-i)
13721 org-store-link-plist))
13722 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13723 (erase-buffer)
13724 (insert (substitute-command-keys
13725 (format
13726 "## Filing location: Select interactively, default, or last used:
13727 ## %s to select file and header location interactively.
13728 ## %s \"%s\" -> \"* %s\"
13729 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13730 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13731 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13732 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13733 (abbreviate-file-name (or file org-default-notes-file))
13734 (or headline "")
13735 (or (car org-remember-previous-location) "???")
13736 (or (cdr org-remember-previous-location) "???"))))
13737 (insert tpl) (goto-char (point-min))
13738 ;; Simple %-escapes
13739 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13740 (when (and initial (equal (match-string 0) "%i"))
13741 (save-match-data
13742 (let* ((lead (buffer-substring
13743 (point-at-bol) (match-beginning 0))))
13744 (setq v-i (mapconcat 'identity
13745 (org-split-string initial "\n")
13746 (concat "\n" lead))))))
13747 (replace-match
13748 (or (eval (intern (concat "v-" (match-string 1)))) "")
13749 t t))
13751 ;; %[] Insert contents of a file.
13752 (goto-char (point-min))
13753 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13754 (let ((start (match-beginning 0))
13755 (end (match-end 0))
13756 (filename (expand-file-name (match-string 1))))
13757 (goto-char start)
13758 (delete-region start end)
13759 (condition-case error
13760 (insert-file-contents filename)
13761 (error (insert (format "%%![Couldn't insert %s: %s]"
13762 filename error))))))
13763 ;; %() embedded elisp
13764 (goto-char (point-min))
13765 (while (re-search-forward "%\\((.+)\\)" nil t)
13766 (goto-char (match-beginning 0))
13767 (let ((template-start (point)))
13768 (forward-char 1)
13769 (let ((result
13770 (condition-case error
13771 (eval (read (current-buffer)))
13772 (error (format "%%![Error: %s]" error)))))
13773 (delete-region template-start (point))
13774 (insert result))))
13776 ;; From the property list
13777 (when plist-p
13778 (goto-char (point-min))
13779 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13780 (and (setq x (or (plist-get org-store-link-plist
13781 (intern (match-string 1))) ""))
13782 (replace-match x t t))))
13784 ;; Turn on org-mode in the remember buffer, set local variables
13785 (org-mode)
13786 (org-set-local 'org-finish-function 'org-remember-finalize)
13787 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13788 (org-set-local 'org-default-notes-file file))
13789 (if (and headline (stringp headline) (string-match "\\S-" headline))
13790 (org-set-local 'org-remember-default-headline headline))
13791 ;; Interactive template entries
13792 (goto-char (point-min))
13793 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13794 (setq char (if (match-end 3) (match-string 3))
13795 prompt (if (match-end 2) (match-string 2)))
13796 (goto-char (match-beginning 0))
13797 (replace-match "")
13798 (setq completions nil default nil)
13799 (when prompt
13800 (setq completions (org-split-string prompt "|")
13801 prompt (pop completions)
13802 default (car completions)
13803 histvar (intern (concat
13804 "org-remember-template-prompt-history::"
13805 (or prompt "")))
13806 completions (mapcar 'list completions)))
13807 (cond
13808 ((member char '("G" "g"))
13809 (let* ((org-last-tags-completion-table
13810 (org-global-tags-completion-table
13811 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13812 (org-add-colon-after-tag-completion t)
13813 (ins (completing-read
13814 (if prompt (concat prompt ": ") "Tags: ")
13815 'org-tags-completion-function nil nil nil
13816 'org-tags-history)))
13817 (setq ins (mapconcat 'identity
13818 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13819 ":"))
13820 (when (string-match "\\S-" ins)
13821 (or (equal (char-before) ?:) (insert ":"))
13822 (insert ins)
13823 (or (equal (char-after) ?:) (insert ":")))))
13824 (char
13825 (setq org-time-was-given (equal (upcase char) char))
13826 (setq time (org-read-date (equal (upcase char) "U") t nil
13827 prompt))
13828 (org-insert-time-stamp time org-time-was-given
13829 (member char '("u" "U"))
13830 nil nil (list org-end-time-was-given)))
13832 (insert (org-completing-read
13833 (concat (if prompt prompt "Enter string")
13834 (if default (concat " [" default "]"))
13835 ": ")
13836 completions nil nil nil histvar default)))))
13837 (goto-char (point-min))
13838 (if (re-search-forward "%\\?" nil t)
13839 (replace-match "")
13840 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13841 (org-mode)
13842 (org-set-local 'org-finish-function 'org-remember-finalize))
13843 (when (save-excursion
13844 (goto-char (point-min))
13845 (re-search-forward "%!" nil t))
13846 (replace-match "")
13847 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13849 (defun org-remember-finish-immediately ()
13850 "File remember note immediately.
13851 This should be run in `post-command-hook' and will remove itself
13852 from that hook."
13853 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13854 (when org-finish-function
13855 (funcall org-finish-function)))
13857 (defvar org-clock-marker) ; Defined below
13858 (defun org-remember-finalize ()
13859 "Finalize the remember process."
13860 (unless (fboundp 'remember-finalize)
13861 (defalias 'remember-finalize 'remember-buffer))
13862 (when (and org-clock-marker
13863 (equal (marker-buffer org-clock-marker) (current-buffer)))
13864 ;; FIXME: test this, this is w/o notetaking!
13865 (let (org-log-note-clock-out) (org-clock-out)))
13866 (when buffer-file-name
13867 (save-buffer)
13868 (setq buffer-file-name nil))
13869 (remember-finalize))
13871 ;;;###autoload
13872 (defun org-remember (&optional goto org-force-remember-template-char)
13873 "Call `remember'. If this is already a remember buffer, re-apply template.
13874 If there is an active region, make sure remember uses it as initial content
13875 of the remember buffer.
13877 When called interactively with a `C-u' prefix argument GOTO, don't remember
13878 anything, just go to the file/headline where the selected template usually
13879 stores its notes. With a double prefix arg `C-u C-u', go to the last
13880 note stored by remember.
13882 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13883 associated with a template in `org-remember-templates'."
13884 (interactive "P")
13885 (cond
13886 ((equal goto '(4)) (org-go-to-remember-target))
13887 ((equal goto '(16)) (org-remember-goto-last-stored))
13889 ;; set temporary variables that will be needed in
13890 ;; `org-select-remember-template'
13891 (setq org-select-template-temp-major-mode major-mode)
13892 (setq org-select-template-original-buffer (current-buffer))
13893 (if (memq org-finish-function '(remember-buffer remember-finalize))
13894 (progn
13895 (when (< (length org-remember-templates) 2)
13896 (error "No other template available"))
13897 (erase-buffer)
13898 (let ((annotation (plist-get org-store-link-plist :annotation))
13899 (initial (plist-get org-store-link-plist :initial)))
13900 (org-remember-apply-template))
13901 (message "Press C-c C-c to remember data"))
13902 (if (org-region-active-p)
13903 (remember (buffer-substring (point) (mark)))
13904 (call-interactively 'remember))))))
13906 (defun org-remember-goto-last-stored ()
13907 "Go to the location where the last remember note was stored."
13908 (interactive)
13909 (bookmark-jump "org-remember-last-stored")
13910 (message "This is the last note stored by remember"))
13912 (defun org-go-to-remember-target (&optional template-key)
13913 "Go to the target location of a remember template.
13914 The user is queried for the template."
13915 (interactive)
13916 (let* (org-select-template-temp-major-mode
13917 (entry (org-select-remember-template template-key))
13918 (file (nth 1 entry))
13919 (heading (nth 2 entry))
13920 visiting)
13921 (unless (and file (stringp file) (string-match "\\S-" file))
13922 (setq file org-default-notes-file))
13923 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13924 (setq heading org-remember-default-headline))
13925 (setq visiting (org-find-base-buffer-visiting file))
13926 (if (not visiting) (find-file-noselect file))
13927 (switch-to-buffer (or visiting (get-file-buffer file)))
13928 (widen)
13929 (goto-char (point-min))
13930 (if (re-search-forward
13931 (concat "^\\*+[ \t]+" (regexp-quote heading)
13932 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13933 nil t)
13934 (goto-char (match-beginning 0))
13935 (error "Target headline not found: %s" heading))))
13937 (defvar org-note-abort nil) ; dynamically scoped
13939 ;;;###autoload
13940 (defun org-remember-handler ()
13941 "Store stuff from remember.el into an org file.
13942 First prompts for an org file. If the user just presses return, the value
13943 of `org-default-notes-file' is used.
13944 Then the command offers the headings tree of the selected file in order to
13945 file the text at a specific location.
13946 You can either immediately press RET to get the note appended to the
13947 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13948 find a better place. Then press RET or <left> or <right> in insert the note.
13950 Key Cursor position Note gets inserted
13951 -----------------------------------------------------------------------------
13952 RET buffer-start as level 1 heading at end of file
13953 RET on headline as sublevel of the heading at cursor
13954 RET no heading at cursor position, level taken from context.
13955 Or use prefix arg to specify level manually.
13956 <left> on headline as same level, before current heading
13957 <right> on headline as same level, after current heading
13959 So the fastest way to store the note is to press RET RET to append it to
13960 the default file. This way your current train of thought is not
13961 interrupted, in accordance with the principles of remember.el.
13962 You can also get the fast execution without prompting by using
13963 C-u C-c C-c to exit the remember buffer. See also the variable
13964 `org-remember-store-without-prompt'.
13966 Before being stored away, the function ensures that the text has a
13967 headline, i.e. a first line that starts with a \"*\". If not, a headline
13968 is constructed from the current date and some additional data.
13970 If the variable `org-adapt-indentation' is non-nil, the entire text is
13971 also indented so that it starts in the same column as the headline
13972 \(i.e. after the stars).
13974 See also the variable `org-reverse-note-order'."
13975 (goto-char (point-min))
13976 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13977 (replace-match ""))
13978 (goto-char (point-max))
13979 (beginning-of-line 1)
13980 (while (looking-at "[ \t]*$\\|##.*")
13981 (delete-region (1- (point)) (point-max))
13982 (beginning-of-line 1))
13983 (catch 'quit
13984 (if org-note-abort (throw 'quit nil))
13985 (let* ((txt (buffer-substring (point-min) (point-max)))
13986 (fastp (org-xor (equal current-prefix-arg '(4))
13987 org-remember-store-without-prompt))
13988 (file (cond
13989 (fastp org-default-notes-file)
13990 ((and (eq org-remember-interactive-interface 'refile)
13991 org-refile-targets)
13992 org-default-notes-file)
13993 ((not (and (equal current-prefix-arg '(16))
13994 org-remember-previous-location))
13995 (org-get-org-file))))
13996 (heading org-remember-default-headline)
13997 (visiting (and file (org-find-base-buffer-visiting file)))
13998 (org-startup-folded nil)
13999 (org-startup-align-all-tables nil)
14000 (org-goto-start-pos 1)
14001 spos exitcmd level indent reversed)
14002 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
14003 (setq file (car org-remember-previous-location)
14004 heading (cdr org-remember-previous-location)
14005 fastp t))
14006 (setq current-prefix-arg nil)
14007 (if (string-match "[ \t\n]+\\'" txt)
14008 (setq txt (replace-match "" t t txt)))
14009 ;; Modify text so that it becomes a nice subtree which can be inserted
14010 ;; into an org tree.
14011 (let* ((lines (split-string txt "\n"))
14012 first)
14013 (setq first (car lines) lines (cdr lines))
14014 (if (string-match "^\\*+ " first)
14015 ;; Is already a headline
14016 (setq indent nil)
14017 ;; We need to add a headline: Use time and first buffer line
14018 (setq lines (cons first lines)
14019 first (concat "* " (current-time-string)
14020 " (" (remember-buffer-desc) ")")
14021 indent " "))
14022 (if (and org-adapt-indentation indent)
14023 (setq lines (mapcar
14024 (lambda (x)
14025 (if (string-match "\\S-" x)
14026 (concat indent x) x))
14027 lines)))
14028 (setq txt (concat first "\n"
14029 (mapconcat 'identity lines "\n"))))
14030 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
14031 (setq txt (replace-match "\n\n" t t txt))
14032 (if (string-match "[ \t\n]*\\'" txt)
14033 (setq txt (replace-match "\n" t t txt))))
14034 ;; Put the modified text back into the remember buffer, for refile.
14035 (erase-buffer)
14036 (insert txt)
14037 (goto-char (point-min))
14038 (when (and (eq org-remember-interactive-interface 'refile)
14039 (not fastp))
14040 (org-refile nil (or visiting (find-file-noselect file)))
14041 (throw 'quit t))
14042 ;; Find the file
14043 (if (not visiting) (find-file-noselect file))
14044 (with-current-buffer (or visiting (get-file-buffer file))
14045 (unless (org-mode-p)
14046 (error "Target files for remember notes must be in Org-mode"))
14047 (save-excursion
14048 (save-restriction
14049 (widen)
14050 (and (goto-char (point-min))
14051 (not (re-search-forward "^\\* " nil t))
14052 (insert "\n* " (or heading "Notes") "\n"))
14053 (setq reversed (org-notes-order-reversed-p))
14055 ;; Find the default location
14056 (when (and heading (stringp heading) (string-match "\\S-" heading))
14057 (goto-char (point-min))
14058 (if (re-search-forward
14059 (concat "^\\*+[ \t]+" (regexp-quote heading)
14060 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14061 nil t)
14062 (setq org-goto-start-pos (match-beginning 0))
14063 (when fastp
14064 (goto-char (point-max))
14065 (unless (bolp) (newline))
14066 (insert "* " heading "\n")
14067 (setq org-goto-start-pos (point-at-bol 0)))))
14069 ;; Ask the User for a location, using the appropriate interface
14070 (cond
14071 (fastp (setq spos org-goto-start-pos
14072 exitcmd 'return))
14073 ((eq org-remember-interactive-interface 'outline)
14074 (setq spos (org-get-location (current-buffer)
14075 org-remember-help)
14076 exitcmd (cdr spos)
14077 spos (car spos)))
14078 ((eq org-remember-interactive-interface 'outline-path-completion)
14079 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
14080 (org-refile-use-outline-path t))
14081 (setq spos (org-refile-get-location "Heading: ")
14082 exitcmd 'return
14083 spos (nth 3 spos))))
14084 (t (error "this should not hapen")))
14085 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14086 ; not handle this note
14087 (goto-char spos)
14088 (cond ((org-on-heading-p t)
14089 (org-back-to-heading t)
14090 (setq level (funcall outline-level))
14091 (cond
14092 ((eq exitcmd 'return)
14093 ;; sublevel of current
14094 (setq org-remember-previous-location
14095 (cons (abbreviate-file-name file)
14096 (org-get-heading 'notags)))
14097 (if reversed
14098 (outline-next-heading)
14099 (org-end-of-subtree t)
14100 (if (not (bolp))
14101 (if (looking-at "[ \t]*\n")
14102 (beginning-of-line 2)
14103 (end-of-line 1)
14104 (insert "\n"))))
14105 (bookmark-set "org-remember-last-stored")
14106 (org-paste-subtree (org-get-legal-level level 1) txt))
14107 ((eq exitcmd 'left)
14108 ;; before current
14109 (bookmark-set "org-remember-last-stored")
14110 (org-paste-subtree level txt))
14111 ((eq exitcmd 'right)
14112 ;; after current
14113 (org-end-of-subtree t)
14114 (bookmark-set "org-remember-last-stored")
14115 (org-paste-subtree level txt))
14116 (t (error "This should not happen"))))
14118 ((and (bobp) (not reversed))
14119 ;; Put it at the end, one level below level 1
14120 (save-restriction
14121 (widen)
14122 (goto-char (point-max))
14123 (if (not (bolp)) (newline))
14124 (bookmark-set "org-remember-last-stored")
14125 (org-paste-subtree (org-get-legal-level 1 1) txt)))
14127 ((and (bobp) reversed)
14128 ;; Put it at the start, as level 1
14129 (save-restriction
14130 (widen)
14131 (goto-char (point-min))
14132 (re-search-forward "^\\*+ " nil t)
14133 (beginning-of-line 1)
14134 (bookmark-set "org-remember-last-stored")
14135 (org-paste-subtree 1 txt)))
14137 ;; Put it right there, with automatic level determined by
14138 ;; org-paste-subtree or from prefix arg
14139 (bookmark-set "org-remember-last-stored")
14140 (org-paste-subtree
14141 (if (numberp current-prefix-arg) current-prefix-arg)
14142 txt)))
14143 (when remember-save-after-remembering
14144 (save-buffer)
14145 (if (not visiting) (kill-buffer (current-buffer)))))))))
14147 t) ;; return t to indicate that we took care of this note.
14149 (defun org-get-org-file ()
14150 "Read a filename, with default directory `org-directory'."
14151 (let ((default (or org-default-notes-file remember-data-file)))
14152 (read-file-name (format "File name [%s]: " default)
14153 (file-name-as-directory org-directory)
14154 default)))
14156 (defun org-notes-order-reversed-p ()
14157 "Check if the current file should receive notes in reversed order."
14158 (cond
14159 ((not org-reverse-note-order) nil)
14160 ((eq t org-reverse-note-order) t)
14161 ((not (listp org-reverse-note-order)) nil)
14162 (t (catch 'exit
14163 (let ((all org-reverse-note-order)
14164 entry)
14165 (while (setq entry (pop all))
14166 (if (string-match (car entry) buffer-file-name)
14167 (throw 'exit (cdr entry))))
14168 nil)))))
14170 ;;; Refiling
14172 (defvar org-refile-target-table nil
14173 "The list of refile targets, created by `org-refile'.")
14175 (defvar org-agenda-new-buffers nil
14176 "Buffers created to visit agenda files.")
14178 (defun org-get-refile-targets (&optional default-buffer)
14179 "Produce a table with refile targets."
14180 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14181 targets txt re files f desc descre)
14182 (with-current-buffer (or default-buffer (current-buffer))
14183 (while (setq entry (pop entries))
14184 (setq files (car entry) desc (cdr entry))
14185 (cond
14186 ((null files) (setq files (list (current-buffer))))
14187 ((eq files 'org-agenda-files)
14188 (setq files (org-agenda-files 'unrestricted)))
14189 ((and (symbolp files) (fboundp files))
14190 (setq files (funcall files)))
14191 ((and (symbolp files) (boundp files))
14192 (setq files (symbol-value files))))
14193 (if (stringp files) (setq files (list files)))
14194 (cond
14195 ((eq (car desc) :tag)
14196 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14197 ((eq (car desc) :todo)
14198 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14199 ((eq (car desc) :regexp)
14200 (setq descre (cdr desc)))
14201 ((eq (car desc) :level)
14202 (setq descre (concat "^\\*\\{" (number-to-string
14203 (if org-odd-levels-only
14204 (1- (* 2 (cdr desc)))
14205 (cdr desc)))
14206 "\\}[ \t]")))
14207 ((eq (car desc) :maxlevel)
14208 (setq descre (concat "^\\*\\{1," (number-to-string
14209 (if org-odd-levels-only
14210 (1- (* 2 (cdr desc)))
14211 (cdr desc)))
14212 "\\}[ \t]")))
14213 (t (error "Bad refiling target description %s" desc)))
14214 (while (setq f (pop files))
14215 (save-excursion
14216 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14217 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14218 (save-excursion
14219 (save-restriction
14220 (widen)
14221 (goto-char (point-min))
14222 (while (re-search-forward descre nil t)
14223 (goto-char (point-at-bol))
14224 (when (looking-at org-complex-heading-regexp)
14225 (setq txt (match-string 4)
14226 re (concat "^" (regexp-quote
14227 (buffer-substring (match-beginning 1)
14228 (match-end 4)))))
14229 (if (match-end 5) (setq re (concat re "[ \t]+"
14230 (regexp-quote
14231 (match-string 5)))))
14232 (setq re (concat re "[ \t]*$"))
14233 (when org-refile-use-outline-path
14234 (setq txt (mapconcat 'identity
14235 (append
14236 (if (eq org-refile-use-outline-path 'file)
14237 (list (file-name-nondirectory
14238 (buffer-file-name (buffer-base-buffer))))
14239 (if (eq org-refile-use-outline-path 'full-file-path)
14240 (list (buffer-file-name (buffer-base-buffer)))))
14241 (org-get-outline-path)
14242 (list txt))
14243 "/")))
14244 (push (list txt f re (point)) targets))
14245 (goto-char (point-at-eol))))))))
14246 (nreverse targets))))
14248 (defun org-get-outline-path ()
14249 "Return the outline path to the current entry, as a list."
14250 (let (rtn)
14251 (save-excursion
14252 (while (org-up-heading-safe)
14253 (when (looking-at org-complex-heading-regexp)
14254 (push (org-match-string-no-properties 4) rtn)))
14255 rtn)))
14257 (defvar org-refile-history nil
14258 "History for refiling operations.")
14260 (defun org-refile (&optional goto default-buffer)
14261 "Move the entry at point to another heading.
14262 The list of target headings is compiled using the information in
14263 `org-refile-targets', which see. This list is created upon first use, and
14264 you can update it by calling this command with a double prefix (`C-u C-u').
14265 FIXME: Can we find a better way of updating?
14267 At the target location, the entry is filed as a subitem of the target heading.
14268 Depending on `org-reverse-note-order', the new subitem will either be the
14269 first of the last subitem.
14271 With prefix arg GOTO, the command will only visit the target location,
14272 not actually move anything.
14273 With a double prefix `C-c C-c', go to the location where the last refiling
14274 operation has put the subtree.
14276 With a double prefix argument, the command can be used to jump to any
14277 heading in the current buffer."
14278 (interactive "P")
14279 (let* ((cbuf (current-buffer))
14280 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14281 pos it nbuf file re level reversed)
14282 (if (equal goto '(16))
14283 (org-refile-goto-last-stored)
14284 (when (setq it (org-refile-get-location
14285 (if goto "Goto: " "Refile to: ") default-buffer))
14286 (setq file (nth 1 it)
14287 re (nth 2 it)
14288 pos (nth 3 it))
14289 (setq nbuf (or (find-buffer-visiting file)
14290 (find-file-noselect file)))
14291 (if goto
14292 (progn
14293 (switch-to-buffer nbuf)
14294 (goto-char pos)
14295 (org-show-context 'org-goto))
14296 (org-copy-special)
14297 (save-excursion
14298 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14299 (find-file-noselect file))))
14300 (setq reversed (org-notes-order-reversed-p))
14301 (save-excursion
14302 (save-restriction
14303 (widen)
14304 (goto-char pos)
14305 (looking-at outline-regexp)
14306 (setq level (org-get-legal-level (funcall outline-level) 1))
14307 (goto-char
14308 (if reversed
14309 (outline-next-heading)
14310 (or (save-excursion (outline-get-next-sibling))
14311 (org-end-of-subtree t t)
14312 (point-max))))
14313 (bookmark-set "org-refile-last-stored")
14314 (org-paste-subtree level))))
14315 (org-cut-special)
14316 (message "Entry refiled to \"%s\"" (car it)))))))
14318 (defun org-refile-goto-last-stored ()
14319 "Go to the location where the last refile was stored."
14320 (interactive)
14321 (bookmark-jump "org-refile-last-stored")
14322 (message "This is the location of the last refile"))
14324 (defun org-refile-get-location (&optional prompt default-buffer)
14325 "Prompt the user for a refile location, using PROMPT."
14326 (let ((org-refile-targets org-refile-targets)
14327 (org-refile-use-outline-path org-refile-use-outline-path))
14328 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14329 (unless org-refile-target-table
14330 (error "No refile targets"))
14331 (let* ((cbuf (current-buffer))
14332 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14333 (fname (and filename (file-truename filename)))
14334 (tbl (mapcar
14335 (lambda (x)
14336 (if (not (equal fname (file-truename (nth 1 x))))
14337 (cons (concat (car x) " (" (file-name-nondirectory
14338 (nth 1 x)) ")")
14339 (cdr x))
14341 org-refile-target-table))
14342 (completion-ignore-case t))
14343 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14344 tbl)))
14346 ;;;; Dynamic blocks
14348 (defun org-find-dblock (name)
14349 "Find the first dynamic block with name NAME in the buffer.
14350 If not found, stay at current position and return nil."
14351 (let (pos)
14352 (save-excursion
14353 (goto-char (point-min))
14354 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14355 nil t)
14356 (match-beginning 0))))
14357 (if pos (goto-char pos))
14358 pos))
14360 (defconst org-dblock-start-re
14361 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14362 "Matches the startline of a dynamic block, with parameters.")
14364 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14365 "Matches the end of a dyhamic block.")
14367 (defun org-create-dblock (plist)
14368 "Create a dynamic block section, with parameters taken from PLIST.
14369 PLIST must containe a :name entry which is used as name of the block."
14370 (unless (bolp) (newline))
14371 (let ((name (plist-get plist :name)))
14372 (insert "#+BEGIN: " name)
14373 (while plist
14374 (if (eq (car plist) :name)
14375 (setq plist (cddr plist))
14376 (insert " " (prin1-to-string (pop plist)))))
14377 (insert "\n\n#+END:\n")
14378 (beginning-of-line -2)))
14380 (defun org-prepare-dblock ()
14381 "Prepare dynamic block for refresh.
14382 This empties the block, puts the cursor at the insert position and returns
14383 the property list including an extra property :name with the block name."
14384 (unless (looking-at org-dblock-start-re)
14385 (error "Not at a dynamic block"))
14386 (let* ((begdel (1+ (match-end 0)))
14387 (name (org-no-properties (match-string 1)))
14388 (params (append (list :name name)
14389 (read (concat "(" (match-string 3) ")")))))
14390 (unless (re-search-forward org-dblock-end-re nil t)
14391 (error "Dynamic block not terminated"))
14392 (delete-region begdel (match-beginning 0))
14393 (goto-char begdel)
14394 (open-line 1)
14395 params))
14397 (defun org-map-dblocks (&optional command)
14398 "Apply COMMAND to all dynamic blocks in the current buffer.
14399 If COMMAND is not given, use `org-update-dblock'."
14400 (let ((cmd (or command 'org-update-dblock))
14401 pos)
14402 (save-excursion
14403 (goto-char (point-min))
14404 (while (re-search-forward org-dblock-start-re nil t)
14405 (goto-char (setq pos (match-beginning 0)))
14406 (condition-case nil
14407 (funcall cmd)
14408 (error (message "Error during update of dynamic block")))
14409 (goto-char pos)
14410 (unless (re-search-forward org-dblock-end-re nil t)
14411 (error "Dynamic block not terminated"))))))
14413 (defun org-dblock-update (&optional arg)
14414 "User command for updating dynamic blocks.
14415 Update the dynamic block at point. With prefix ARG, update all dynamic
14416 blocks in the buffer."
14417 (interactive "P")
14418 (if arg
14419 (org-update-all-dblocks)
14420 (or (looking-at org-dblock-start-re)
14421 (org-beginning-of-dblock))
14422 (org-update-dblock)))
14424 (defun org-update-dblock ()
14425 "Update the dynamic block at point
14426 This means to empty the block, parse for parameters and then call
14427 the correct writing function."
14428 (save-window-excursion
14429 (let* ((pos (point))
14430 (line (org-current-line))
14431 (params (org-prepare-dblock))
14432 (name (plist-get params :name))
14433 (cmd (intern (concat "org-dblock-write:" name))))
14434 (message "Updating dynamic block `%s' at line %d..." name line)
14435 (funcall cmd params)
14436 (message "Updating dynamic block `%s' at line %d...done" name line)
14437 (goto-char pos))))
14439 (defun org-beginning-of-dblock ()
14440 "Find the beginning of the dynamic block at point.
14441 Error if there is no scuh block at point."
14442 (let ((pos (point))
14443 beg)
14444 (end-of-line 1)
14445 (if (and (re-search-backward org-dblock-start-re nil t)
14446 (setq beg (match-beginning 0))
14447 (re-search-forward org-dblock-end-re nil t)
14448 (> (match-end 0) pos))
14449 (goto-char beg)
14450 (goto-char pos)
14451 (error "Not in a dynamic block"))))
14453 (defun org-update-all-dblocks ()
14454 "Update all dynamic blocks in the buffer.
14455 This function can be used in a hook."
14456 (when (org-mode-p)
14457 (org-map-dblocks 'org-update-dblock)))
14460 ;;;; Completion
14462 (defconst org-additional-option-like-keywords
14463 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14464 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14465 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14467 (defun org-complete (&optional arg)
14468 "Perform completion on word at point.
14469 At the beginning of a headline, this completes TODO keywords as given in
14470 `org-todo-keywords'.
14471 If the current word is preceded by a backslash, completes the TeX symbols
14472 that are supported for HTML support.
14473 If the current word is preceded by \"#+\", completes special words for
14474 setting file options.
14475 In the line after \"#+STARTUP:, complete valid keywords.\"
14476 At all other locations, this simply calls the value of
14477 `org-completion-fallback-command'."
14478 (interactive "P")
14479 (org-without-partial-completion
14480 (catch 'exit
14481 (let* ((end (point))
14482 (beg1 (save-excursion
14483 (skip-chars-backward (org-re "[:alnum:]_@"))
14484 (point)))
14485 (beg (save-excursion
14486 (skip-chars-backward "a-zA-Z0-9_:$")
14487 (point)))
14488 (confirm (lambda (x) (stringp (car x))))
14489 (searchhead (equal (char-before beg) ?*))
14490 (tag (and (equal (char-before beg1) ?:)
14491 (equal (char-after (point-at-bol)) ?*)))
14492 (prop (and (equal (char-before beg1) ?:)
14493 (not (equal (char-after (point-at-bol)) ?*))))
14494 (texp (equal (char-before beg) ?\\))
14495 (link (equal (char-before beg) ?\[))
14496 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14497 beg)
14498 "#+"))
14499 (startup (string-match "^#\\+STARTUP:.*"
14500 (buffer-substring (point-at-bol) (point))))
14501 (completion-ignore-case opt)
14502 (type nil)
14503 (tbl nil)
14504 (table (cond
14505 (opt
14506 (setq type :opt)
14507 (append
14508 (mapcar
14509 (lambda (x)
14510 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14511 (cons (match-string 2 x) (match-string 1 x)))
14512 (org-split-string (org-get-current-options) "\n"))
14513 (mapcar 'list org-additional-option-like-keywords)))
14514 (startup
14515 (setq type :startup)
14516 org-startup-options)
14517 (link (append org-link-abbrev-alist-local
14518 org-link-abbrev-alist))
14519 (texp
14520 (setq type :tex)
14521 org-html-entities)
14522 ((string-match "\\`\\*+[ \t]+\\'"
14523 (buffer-substring (point-at-bol) beg))
14524 (setq type :todo)
14525 (mapcar 'list org-todo-keywords-1))
14526 (searchhead
14527 (setq type :searchhead)
14528 (save-excursion
14529 (goto-char (point-min))
14530 (while (re-search-forward org-todo-line-regexp nil t)
14531 (push (list
14532 (org-make-org-heading-search-string
14533 (match-string 3) t))
14534 tbl)))
14535 tbl)
14536 (tag (setq type :tag beg beg1)
14537 (or org-tag-alist (org-get-buffer-tags)))
14538 (prop (setq type :prop beg beg1)
14539 (mapcar 'list (org-buffer-property-keys nil t t)))
14540 (t (progn
14541 (call-interactively org-completion-fallback-command)
14542 (throw 'exit nil)))))
14543 (pattern (buffer-substring-no-properties beg end))
14544 (completion (try-completion pattern table confirm)))
14545 (cond ((eq completion t)
14546 (if (not (assoc (upcase pattern) table))
14547 (message "Already complete")
14548 (if (equal type :opt)
14549 (insert (substring (cdr (assoc (upcase pattern) table))
14550 (length pattern)))
14551 (if (memq type '(:tag :prop)) (insert ":")))))
14552 ((null completion)
14553 (message "Can't find completion for \"%s\"" pattern)
14554 (ding))
14555 ((not (string= pattern completion))
14556 (delete-region beg end)
14557 (if (string-match " +$" completion)
14558 (setq completion (replace-match "" t t completion)))
14559 (insert completion)
14560 (if (get-buffer-window "*Completions*")
14561 (delete-window (get-buffer-window "*Completions*")))
14562 (if (assoc completion table)
14563 (if (eq type :todo) (insert " ")
14564 (if (memq type '(:tag :prop)) (insert ":"))))
14565 (if (and (equal type :opt) (assoc completion table))
14566 (message "%s" (substitute-command-keys
14567 "Press \\[org-complete] again to insert example settings"))))
14569 (message "Making completion list...")
14570 (let ((list (sort (all-completions pattern table confirm)
14571 'string<)))
14572 (with-output-to-temp-buffer "*Completions*"
14573 (condition-case nil
14574 ;; Protection needed for XEmacs and emacs 21
14575 (display-completion-list list pattern)
14576 (error (display-completion-list list)))))
14577 (message "Making completion list...%s" "done")))))))
14579 ;;;; TODO, DEADLINE, Comments
14581 (defun org-toggle-comment ()
14582 "Change the COMMENT state of an entry."
14583 (interactive)
14584 (save-excursion
14585 (org-back-to-heading)
14586 (let (case-fold-search)
14587 (if (looking-at (concat outline-regexp
14588 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14589 (replace-match "" t t nil 1)
14590 (if (looking-at outline-regexp)
14591 (progn
14592 (goto-char (match-end 0))
14593 (insert org-comment-string " ")))))))
14595 (defvar org-last-todo-state-is-todo nil
14596 "This is non-nil when the last TODO state change led to a TODO state.
14597 If the last change removed the TODO tag or switched to DONE, then
14598 this is nil.")
14600 (defvar org-setting-tags nil) ; dynamically skiped
14602 ;; FIXME: better place
14603 (defun org-property-or-variable-value (var &optional inherit)
14604 "Check if there is a property fixing the value of VAR.
14605 If yes, return this value. If not, return the current value of the variable."
14606 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14607 (if (and prop (stringp prop) (string-match "\\S-" prop))
14608 (read prop)
14609 (symbol-value var))))
14611 (defun org-parse-local-options (string var)
14612 "Parse STRING for startup setting relevant for variable VAR."
14613 (let ((rtn (symbol-value var))
14614 e opts)
14615 (save-match-data
14616 (if (or (not string) (not (string-match "\\S-" string)))
14618 (setq opts (delq nil (mapcar (lambda (x)
14619 (setq e (assoc x org-startup-options))
14620 (if (eq (nth 1 e) var) e nil))
14621 (org-split-string string "[ \t]+"))))
14622 (if (not opts)
14624 (setq rtn nil)
14625 (while (setq e (pop opts))
14626 (if (not (nth 3 e))
14627 (setq rtn (nth 2 e))
14628 (if (not (listp rtn)) (setq rtn nil))
14629 (push (nth 2 e) rtn)))
14630 rtn)))))
14632 (defvar org-blocker-hook nil
14633 "Hook for functions that are allowed to block a state change.
14635 Each function gets as its single argument a property list, see
14636 `org-trigger-hook' for more information about this list.
14638 If any of the functions in this hook returns nil, the state change
14639 is blocked.")
14641 (defvar org-trigger-hook nil
14642 "Hook for functions that are triggered by a state change.
14644 Each function gets as its single argument a property list with at least
14645 the following elements:
14647 (:type type-of-change :position pos-at-entry-start
14648 :from old-state :to new-state)
14650 Depending on the type, more properties may be present.
14652 This mechanism is currently implemented for:
14654 TODO state changes
14655 ------------------
14656 :type todo-state-change
14657 :from previous state (keyword as a string), or nil
14658 :to new state (keyword as a string), or nil")
14661 (defun org-todo (&optional arg)
14662 "Change the TODO state of an item.
14663 The state of an item is given by a keyword at the start of the heading,
14664 like
14665 *** TODO Write paper
14666 *** DONE Call mom
14668 The different keywords are specified in the variable `org-todo-keywords'.
14669 By default the available states are \"TODO\" and \"DONE\".
14670 So for this example: when the item starts with TODO, it is changed to DONE.
14671 When it starts with DONE, the DONE is removed. And when neither TODO nor
14672 DONE are present, add TODO at the beginning of the heading.
14674 With C-u prefix arg, use completion to determine the new state.
14675 With numeric prefix arg, switch to that state.
14677 For calling through lisp, arg is also interpreted in the following way:
14678 'none -> empty state
14679 \"\"(empty string) -> switch to empty state
14680 'done -> switch to DONE
14681 'nextset -> switch to the next set of keywords
14682 'previousset -> switch to the previous set of keywords
14683 \"WAITING\" -> switch to the specified keyword, but only if it
14684 really is a member of `org-todo-keywords'."
14685 (interactive "P")
14686 (save-excursion
14687 (catch 'exit
14688 (org-back-to-heading)
14689 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14690 (or (looking-at (concat " +" org-todo-regexp " *"))
14691 (looking-at " *"))
14692 (let* ((match-data (match-data))
14693 (startpos (point-at-bol))
14694 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14695 (org-log-done org-log-done)
14696 (org-log-repeat org-log-repeat)
14697 (org-todo-log-states org-todo-log-states)
14698 (this (match-string 1))
14699 (hl-pos (match-beginning 0))
14700 (head (org-get-todo-sequence-head this))
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 (last-state (or this ""))
14706 (completion-ignore-case t)
14707 (member (member this org-todo-keywords-1))
14708 (tail (cdr member))
14709 (state (cond
14710 ((and org-todo-key-trigger
14711 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14712 (and (not arg) org-use-fast-todo-selection
14713 (not (eq org-use-fast-todo-selection 'prefix)))))
14714 ;; Use fast selection
14715 (org-fast-todo-selection))
14716 ((and (equal arg '(4))
14717 (or (not org-use-fast-todo-selection)
14718 (not org-todo-key-trigger)))
14719 ;; Read a state with completion
14720 (completing-read "State: " (mapcar (lambda(x) (list x))
14721 org-todo-keywords-1)
14722 nil t))
14723 ((eq arg 'right)
14724 (if this
14725 (if tail (car tail) nil)
14726 (car org-todo-keywords-1)))
14727 ((eq arg 'left)
14728 (if (equal member org-todo-keywords-1)
14730 (if this
14731 (nth (- (length org-todo-keywords-1) (length tail) 2)
14732 org-todo-keywords-1)
14733 (org-last org-todo-keywords-1))))
14734 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14735 (setq arg nil))) ; hack to fall back to cycling
14736 (arg
14737 ;; user or caller requests a specific state
14738 (cond
14739 ((equal arg "") nil)
14740 ((eq arg 'none) nil)
14741 ((eq arg 'done) (or done-word (car org-done-keywords)))
14742 ((eq arg 'nextset)
14743 (or (car (cdr (member head org-todo-heads)))
14744 (car org-todo-heads)))
14745 ((eq arg 'previousset)
14746 (let ((org-todo-heads (reverse org-todo-heads)))
14747 (or (car (cdr (member head org-todo-heads)))
14748 (car org-todo-heads))))
14749 ((car (member arg org-todo-keywords-1)))
14750 ((nth (1- (prefix-numeric-value arg))
14751 org-todo-keywords-1))))
14752 ((null member) (or head (car org-todo-keywords-1)))
14753 ((equal this final-done-word) nil) ;; -> make empty
14754 ((null tail) nil) ;; -> first entry
14755 ((eq interpret 'sequence)
14756 (car tail))
14757 ((memq interpret '(type priority))
14758 (if (eq this-command last-command)
14759 (car tail)
14760 (if (> (length tail) 0)
14761 (or done-word (car org-done-keywords))
14762 nil)))
14763 (t nil)))
14764 (next (if state (concat " " state " ") " "))
14765 (change-plist (list :type 'todo-state-change :from this :to state
14766 :position startpos))
14767 dolog now-done-p)
14768 (when org-blocker-hook
14769 (unless (save-excursion
14770 (save-match-data
14771 (run-hook-with-args-until-failure
14772 'org-blocker-hook change-plist)))
14773 (if (interactive-p)
14774 (error "TODO state change from %s to %s blocked" this state)
14775 ;; fail silently
14776 (message "TODO state change from %s to %s blocked" this state)
14777 (throw 'exit nil))))
14778 (store-match-data match-data)
14779 (replace-match next t t)
14780 (unless (pos-visible-in-window-p hl-pos)
14781 (message "TODO state changed to %s" (org-trim next)))
14782 (unless head
14783 (setq head (org-get-todo-sequence-head state)
14784 ass (assoc head org-todo-kwd-alist)
14785 interpret (nth 1 ass)
14786 done-word (nth 3 ass)
14787 final-done-word (nth 4 ass)))
14788 (when (memq arg '(nextset previousset))
14789 (message "Keyword-Set %d/%d: %s"
14790 (- (length org-todo-sets) -1
14791 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14792 (length org-todo-sets)
14793 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14794 (setq org-last-todo-state-is-todo
14795 (not (member state org-done-keywords)))
14796 (setq now-done-p (and (member state org-done-keywords)
14797 (not (member this org-done-keywords))))
14798 (and logging (org-local-logging logging))
14799 (when (and (or org-todo-log-states org-log-done)
14800 (not (memq arg '(nextset previousset))))
14801 ;; we need to look at recording a time and note
14802 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14803 (nth 2 (assoc this org-todo-log-states))))
14804 (when (and state
14805 (member state org-not-done-keywords)
14806 (not (member this org-not-done-keywords)))
14807 ;; This is now a todo state and was not one before
14808 ;; If there was a CLOSED time stamp, get rid of it.
14809 (org-add-planning-info nil nil 'closed))
14810 (when (and now-done-p org-log-done)
14811 ;; It is now done, and it was not done before
14812 (org-add-planning-info 'closed (org-current-time))
14813 (if (and (not dolog) (eq 'note org-log-done))
14814 (org-add-log-maybe 'done state 'findpos 'note)))
14815 (when (and state dolog)
14816 ;; This is a non-nil state, and we need to log it
14817 (org-add-log-maybe 'state state 'findpos dolog)))
14818 ;; Fixup tag positioning
14819 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14820 (run-hooks 'org-after-todo-state-change-hook)
14821 (if (and arg (not (member state org-done-keywords)))
14822 (setq head (org-get-todo-sequence-head state)))
14823 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14824 ;; Do we need to trigger a repeat?
14825 (when now-done-p (org-auto-repeat-maybe state))
14826 ;; Fixup cursor location if close to the keyword
14827 (if (and (outline-on-heading-p)
14828 (not (bolp))
14829 (save-excursion (beginning-of-line 1)
14830 (looking-at org-todo-line-regexp))
14831 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14832 (progn
14833 (goto-char (or (match-end 2) (match-end 1)))
14834 (just-one-space)))
14835 (when org-trigger-hook
14836 (save-excursion
14837 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14839 (defun org-local-logging (value)
14840 "Get logging settings from a property VALUE."
14841 (let* (words w a)
14842 ;; directly set the variables, they are already local.
14843 (setq org-log-done nil
14844 org-log-repeat nil
14845 org-todo-log-states nil)
14846 (setq words (org-split-string value))
14847 (while (setq w (pop words))
14848 (cond
14849 ((setq a (assoc w org-startup-options))
14850 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14851 (set (nth 1 a) (nth 2 a))))
14852 ((setq a (org-extract-log-state-settings w))
14853 (and (member (car a) org-todo-keywords-1)
14854 (push a org-todo-log-states)))))))
14856 (defun org-get-todo-sequence-head (kwd)
14857 "Return the head of the TODO sequence to which KWD belongs.
14858 If KWD is not set, check if there is a text property remembering the
14859 right sequence."
14860 (let (p)
14861 (cond
14862 ((not kwd)
14863 (or (get-text-property (point-at-bol) 'org-todo-head)
14864 (progn
14865 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14866 nil (point-at-eol)))
14867 (get-text-property p 'org-todo-head))))
14868 ((not (member kwd org-todo-keywords-1))
14869 (car org-todo-keywords-1))
14870 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14872 (defun org-fast-todo-selection ()
14873 "Fast TODO keyword selection with single keys.
14874 Returns the new TODO keyword, or nil if no state change should occur."
14875 (let* ((fulltable org-todo-key-alist)
14876 (done-keywords org-done-keywords) ;; needed for the faces.
14877 (maxlen (apply 'max (mapcar
14878 (lambda (x)
14879 (if (stringp (car x)) (string-width (car x)) 0))
14880 fulltable)))
14881 (expert nil)
14882 (fwidth (+ maxlen 3 1 3))
14883 (ncol (/ (- (window-width) 4) fwidth))
14884 tg cnt e c tbl
14885 groups ingroup)
14886 (save-window-excursion
14887 (if expert
14888 (set-buffer (get-buffer-create " *Org todo*"))
14889 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14890 (erase-buffer)
14891 (org-set-local 'org-done-keywords done-keywords)
14892 (setq tbl fulltable cnt 0)
14893 (while (setq e (pop tbl))
14894 (cond
14895 ((equal e '(:startgroup))
14896 (push '() groups) (setq ingroup t)
14897 (when (not (= cnt 0))
14898 (setq cnt 0)
14899 (insert "\n"))
14900 (insert "{ "))
14901 ((equal e '(:endgroup))
14902 (setq ingroup nil cnt 0)
14903 (insert "}\n"))
14905 (setq tg (car e) c (cdr e))
14906 (if ingroup (push tg (car groups)))
14907 (setq tg (org-add-props tg nil 'face
14908 (org-get-todo-face tg)))
14909 (if (and (= cnt 0) (not ingroup)) (insert " "))
14910 (insert "[" c "] " tg (make-string
14911 (- fwidth 4 (length tg)) ?\ ))
14912 (when (= (setq cnt (1+ cnt)) ncol)
14913 (insert "\n")
14914 (if ingroup (insert " "))
14915 (setq cnt 0)))))
14916 (insert "\n")
14917 (goto-char (point-min))
14918 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14919 (fit-window-to-buffer))
14920 (message "[a-z..]:Set [SPC]:clear")
14921 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14922 (cond
14923 ((or (= c ?\C-g)
14924 (and (= c ?q) (not (rassoc c fulltable))))
14925 (setq quit-flag t))
14926 ((= c ?\ ) nil)
14927 ((setq e (rassoc c fulltable) tg (car e))
14929 (t (setq quit-flag t))))))
14931 (defun org-get-repeat ()
14932 "Check if tere is a deadline/schedule with repeater in this entry."
14933 (save-match-data
14934 (save-excursion
14935 (org-back-to-heading t)
14936 (if (re-search-forward
14937 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14938 (match-string 1)))))
14940 (defvar org-last-changed-timestamp)
14941 (defvar org-log-post-message)
14942 (defvar org-log-note-purpose)
14943 (defun org-auto-repeat-maybe (done-word)
14944 "Check if the current headline contains a repeated deadline/schedule.
14945 If yes, set TODO state back to what it was and change the base date
14946 of repeating deadline/scheduled time stamps to new date.
14947 This function is run automatically after each state change to a DONE state."
14948 ;; last-state is dynamically scoped into this function
14949 (let* ((repeat (org-get-repeat))
14950 (aa (assoc last-state org-todo-kwd-alist))
14951 (interpret (nth 1 aa))
14952 (head (nth 2 aa))
14953 (whata '(("d" . day) ("m" . month) ("y" . year)))
14954 (msg "Entry repeats: ")
14955 (org-log-done nil)
14956 (org-todo-log-states nil)
14957 re type n what ts)
14958 (when repeat
14959 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14960 (org-todo (if (eq interpret 'type) last-state head))
14961 (when (and org-log-repeat
14962 (or (not (memq 'org-add-log-note
14963 (default-value 'post-command-hook)))
14964 (eq org-log-note-purpose 'done)))
14965 ;; Make sure a note is taken;
14966 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14967 'findpos org-log-repeat))
14968 (org-back-to-heading t)
14969 (org-add-planning-info nil nil 'closed)
14970 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14971 org-deadline-time-regexp "\\)\\|\\("
14972 org-ts-regexp "\\)"))
14973 (while (re-search-forward
14974 re (save-excursion (outline-next-heading) (point)) t)
14975 (setq type (if (match-end 1) org-scheduled-string
14976 (if (match-end 3) org-deadline-string "Plain:"))
14977 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14978 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14979 (setq n (string-to-number (match-string 1 ts))
14980 what (match-string 2 ts))
14981 (if (equal what "w") (setq n (* n 7) what "d"))
14982 (org-timestamp-change n (cdr (assoc what whata)))
14983 (setq msg (concat msg type org-last-changed-timestamp " "))))
14984 (setq org-log-post-message msg)
14985 (message "%s" msg))))
14987 (defun org-show-todo-tree (arg)
14988 "Make a compact tree which shows all headlines marked with TODO.
14989 The tree will show the lines where the regexp matches, and all higher
14990 headlines above the match.
14991 With a \\[universal-argument] prefix, also show the DONE entries.
14992 With a numeric prefix N, construct a sparse tree for the Nth element
14993 of `org-todo-keywords-1'."
14994 (interactive "P")
14995 (let ((case-fold-search nil)
14996 (kwd-re
14997 (cond ((null arg) org-not-done-regexp)
14998 ((equal arg '(4))
14999 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
15000 (mapcar 'list org-todo-keywords-1))))
15001 (concat "\\("
15002 (mapconcat 'identity (org-split-string kwd "|") "\\|")
15003 "\\)\\>")))
15004 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
15005 (regexp-quote (nth (1- (prefix-numeric-value arg))
15006 org-todo-keywords-1)))
15007 (t (error "Invalid prefix argument: %s" arg)))))
15008 (message "%d TODO entries found"
15009 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
15011 (defun org-deadline (&optional remove)
15012 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
15013 With argument REMOVE, remove any deadline from the item."
15014 (interactive "P")
15015 (if remove
15016 (progn
15017 (org-remove-timestamp-with-keyword org-deadline-string)
15018 (message "Item no longer has a deadline."))
15019 (org-add-planning-info 'deadline nil 'closed)))
15021 (defun org-schedule (&optional remove)
15022 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
15023 With argument REMOVE, remove any scheduling date from the item."
15024 (interactive "P")
15025 (if remove
15026 (progn
15027 (org-remove-timestamp-with-keyword org-scheduled-string)
15028 (message "Item is no longer scheduled."))
15029 (org-add-planning-info 'scheduled nil 'closed)))
15031 (defun org-remove-timestamp-with-keyword (keyword)
15032 "Remove all time stamps with KEYWORD in the current entry."
15033 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
15034 beg)
15035 (save-excursion
15036 (org-back-to-heading t)
15037 (setq beg (point))
15038 (org-end-of-subtree t t)
15039 (while (re-search-backward re beg t)
15040 (replace-match "")
15041 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
15042 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
15044 (defun org-add-planning-info (what &optional time &rest remove)
15045 "Insert new timestamp with keyword in the line directly after the headline.
15046 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
15047 If non is given, the user is prompted for a date.
15048 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
15049 be removed."
15050 (interactive)
15051 (let (org-time-was-given org-end-time-was-given)
15052 (when what (setq time (or time (org-read-date nil 'to-time))))
15053 (when (and org-insert-labeled-timestamps-at-point
15054 (member what '(scheduled deadline)))
15055 (insert
15056 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
15057 (org-insert-time-stamp time org-time-was-given
15058 nil nil nil (list org-end-time-was-given))
15059 (setq what nil))
15060 (save-excursion
15061 (save-restriction
15062 (let (col list elt ts buffer-invisibility-spec)
15063 (org-back-to-heading t)
15064 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
15065 (goto-char (match-end 1))
15066 (setq col (current-column))
15067 (goto-char (match-end 0))
15068 (if (eobp) (insert "\n") (forward-char 1))
15069 (if (and (not (looking-at outline-regexp))
15070 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
15071 "[^\r\n]*"))
15072 (not (equal (match-string 1) org-clock-string)))
15073 (narrow-to-region (match-beginning 0) (match-end 0))
15074 (insert-before-markers "\n")
15075 (backward-char 1)
15076 (narrow-to-region (point) (point))
15077 (indent-to-column col))
15078 ;; Check if we have to remove something.
15079 (setq list (cons what remove))
15080 (while list
15081 (setq elt (pop list))
15082 (goto-char (point-min))
15083 (when (or (and (eq elt 'scheduled)
15084 (re-search-forward org-scheduled-time-regexp nil t))
15085 (and (eq elt 'deadline)
15086 (re-search-forward org-deadline-time-regexp nil t))
15087 (and (eq elt 'closed)
15088 (re-search-forward org-closed-time-regexp nil t)))
15089 (replace-match "")
15090 (if (looking-at "--+<[^>]+>") (replace-match ""))
15091 (if (looking-at " +") (replace-match ""))))
15092 (goto-char (point-max))
15093 (when what
15094 (insert
15095 (if (not (equal (char-before) ?\ )) " " "")
15096 (cond ((eq what 'scheduled) org-scheduled-string)
15097 ((eq what 'deadline) org-deadline-string)
15098 ((eq what 'closed) org-closed-string))
15099 " ")
15100 (setq ts (org-insert-time-stamp
15101 time
15102 (or org-time-was-given
15103 (and (eq what 'closed) org-log-done-with-time))
15104 (eq what 'closed)
15105 nil nil (list org-end-time-was-given)))
15106 (end-of-line 1))
15107 (goto-char (point-min))
15108 (widen)
15109 (if (looking-at "[ \t]+\r?\n")
15110 (replace-match ""))
15111 ts)))))
15113 (defvar org-log-note-marker (make-marker))
15114 (defvar org-log-note-purpose nil)
15115 (defvar org-log-note-state nil)
15116 (defvar org-log-note-how nil)
15117 (defvar org-log-note-window-configuration nil)
15118 (defvar org-log-note-return-to (make-marker))
15119 (defvar org-log-post-message nil
15120 "Message to be displayed after a log note has been stored.
15121 The auto-repeater uses this.")
15123 (defun org-add-log-maybe (&optional purpose state findpos how)
15124 "Set up the post command hook to take a note.
15125 If this is about to TODO state change, the new state is expected in STATE.
15126 When FINDPOS is non-nil, find the correct position for the note in
15127 the current entry. If not, assume that it can be inserted at point."
15128 (save-excursion
15129 (when findpos
15130 (org-back-to-heading t)
15131 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15132 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15133 "[^\r\n]*\\)?"))
15134 (goto-char (match-end 0))
15135 (unless org-log-states-order-reversed
15136 (and (= (char-after) ?\n) (forward-char 1))
15137 (org-skip-over-state-notes)
15138 (skip-chars-backward " \t\n\r")))
15139 (move-marker org-log-note-marker (point))
15140 (setq org-log-note-purpose purpose
15141 org-log-note-state state
15142 org-log-note-how how)
15143 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15145 (defun org-skip-over-state-notes ()
15146 "Skip past the list of State notes in an entry."
15147 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15148 (while (looking-at "[ \t]*- State")
15149 (condition-case nil
15150 (org-next-item)
15151 (error (org-end-of-item)))))
15153 (defun org-add-log-note (&optional purpose)
15154 "Pop up a window for taking a note, and add this note later at point."
15155 (remove-hook 'post-command-hook 'org-add-log-note)
15156 (setq org-log-note-window-configuration (current-window-configuration))
15157 (delete-other-windows)
15158 (move-marker org-log-note-return-to (point))
15159 (switch-to-buffer (marker-buffer org-log-note-marker))
15160 (goto-char org-log-note-marker)
15161 (org-switch-to-buffer-other-window "*Org Note*")
15162 (erase-buffer)
15163 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15164 (org-store-log-note)
15165 (let ((org-inhibit-startup t)) (org-mode))
15166 (insert (format "# Insert note for %s.
15167 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15168 (cond
15169 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15170 ((eq org-log-note-purpose 'done) "closed todo item")
15171 ((eq org-log-note-purpose 'state)
15172 (format "state change to \"%s\"" org-log-note-state))
15173 (t (error "This should not happen")))))
15174 (org-set-local 'org-finish-function 'org-store-log-note)))
15176 (defun org-store-log-note ()
15177 "Finish taking a log note, and insert it to where it belongs."
15178 (let ((txt (buffer-string))
15179 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15180 lines ind)
15181 (kill-buffer (current-buffer))
15182 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15183 (setq txt (replace-match "" t t txt)))
15184 (if (string-match "\\s-+\\'" txt)
15185 (setq txt (replace-match "" t t txt)))
15186 (setq lines (org-split-string txt "\n"))
15187 (when (and note (string-match "\\S-" note))
15188 (setq note
15189 (org-replace-escapes
15190 note
15191 (list (cons "%u" (user-login-name))
15192 (cons "%U" user-full-name)
15193 (cons "%t" (format-time-string
15194 (org-time-stamp-format 'long 'inactive)
15195 (current-time)))
15196 (cons "%s" (if org-log-note-state
15197 (concat "\"" org-log-note-state "\"")
15198 "")))))
15199 (if lines (setq note (concat note " \\\\")))
15200 (push note lines))
15201 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15202 (when lines
15203 (save-excursion
15204 (set-buffer (marker-buffer org-log-note-marker))
15205 (save-excursion
15206 (goto-char org-log-note-marker)
15207 (move-marker org-log-note-marker nil)
15208 (end-of-line 1)
15209 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15210 (indent-relative nil)
15211 (insert "- " (pop lines))
15212 (org-indent-line-function)
15213 (beginning-of-line 1)
15214 (looking-at "[ \t]*")
15215 (setq ind (concat (match-string 0) " "))
15216 (end-of-line 1)
15217 (while lines (insert "\n" ind (pop lines)))))))
15218 (set-window-configuration org-log-note-window-configuration)
15219 (with-current-buffer (marker-buffer org-log-note-return-to)
15220 (goto-char org-log-note-return-to))
15221 (move-marker org-log-note-return-to nil)
15222 (and org-log-post-message (message "%s" org-log-post-message)))
15224 ;; FIXME: what else would be useful?
15225 ;; - priority
15226 ;; - date
15228 (defun org-sparse-tree (&optional arg)
15229 "Create a sparse tree, prompt for the details.
15230 This command can create sparse trees. You first need to select the type
15231 of match used to create the tree:
15233 t Show entries with a specific TODO keyword.
15234 T Show entries selected by a tags match.
15235 p Enter a property name and its value (both with completion on existing
15236 names/values) and show entries with that property.
15237 r Show entries matching a regular expression
15238 d Show deadlines due within `org-deadline-warning-days'."
15239 (interactive "P")
15240 (let (ans kwd value)
15241 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15242 (setq ans (read-char-exclusive))
15243 (cond
15244 ((equal ans ?d)
15245 (call-interactively 'org-check-deadlines))
15246 ((equal ans ?b)
15247 (call-interactively 'org-check-before-date))
15248 ((equal ans ?t)
15249 (org-show-todo-tree '(4)))
15250 ((equal ans ?T)
15251 (call-interactively 'org-tags-sparse-tree))
15252 ((member ans '(?p ?P))
15253 (setq kwd (completing-read "Property: "
15254 (mapcar 'list (org-buffer-property-keys))))
15255 (setq value (completing-read "Value: "
15256 (mapcar 'list (org-property-values kwd))))
15257 (unless (string-match "\\`{.*}\\'" value)
15258 (setq value (concat "\"" value "\"")))
15259 (org-tags-sparse-tree arg (concat kwd "=" value)))
15260 ((member ans '(?r ?R ?/))
15261 (call-interactively 'org-occur))
15262 (t (error "No such sparse tree command \"%c\"" ans)))))
15264 (defvar org-occur-highlights nil
15265 "List of overlays used for occur matches.")
15266 (make-variable-buffer-local 'org-occur-highlights)
15267 (defvar org-occur-parameters nil
15268 "Parameters of the active org-occur calls.
15269 This is a list, each call to org-occur pushes as cons cell,
15270 containing the regular expression and the callback, onto the list.
15271 The list can contain several entries if `org-occur' has been called
15272 several time with the KEEP-PREVIOUS argument. Otherwise, this list
15273 will only contain one set of parameters. When the highlights are
15274 removed (for example with `C-c C-c', or with the next edit (depending
15275 on `org-remove-highlights-with-change'), this variable is emptied
15276 as well.")
15277 (make-variable-buffer-local 'org-occur-parameters)
15279 (defun org-occur (regexp &optional keep-previous callback)
15280 "Make a compact tree which shows all matches of REGEXP.
15281 The tree will show the lines where the regexp matches, and all higher
15282 headlines above the match. It will also show the heading after the match,
15283 to make sure editing the matching entry is easy.
15284 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15285 call to `org-occur' will be kept, to allow stacking of calls to this
15286 command.
15287 If CALLBACK is non-nil, it is a function which is called to confirm
15288 that the match should indeed be shown."
15289 (interactive "sRegexp: \nP")
15290 (unless keep-previous
15291 (org-remove-occur-highlights nil nil t))
15292 (push (cons regexp callback) org-occur-parameters)
15293 (let ((cnt 0))
15294 (save-excursion
15295 (goto-char (point-min))
15296 (if (or (not keep-previous) ; do not want to keep
15297 (not org-occur-highlights)) ; no previous matches
15298 ;; hide everything
15299 (org-overview))
15300 (while (re-search-forward regexp nil t)
15301 (when (or (not callback)
15302 (save-match-data (funcall callback)))
15303 (setq cnt (1+ cnt))
15304 (when org-highlight-sparse-tree-matches
15305 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15306 (org-show-context 'occur-tree))))
15307 (when org-remove-highlights-with-change
15308 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15309 nil 'local))
15310 (unless org-sparse-tree-open-archived-trees
15311 (org-hide-archived-subtrees (point-min) (point-max)))
15312 (run-hooks 'org-occur-hook)
15313 (if (interactive-p)
15314 (message "%d match(es) for regexp %s" cnt regexp))
15315 cnt))
15317 (defun org-show-context (&optional key)
15318 "Make sure point and context and visible.
15319 How much context is shown depends upon the variables
15320 `org-show-hierarchy-above', `org-show-following-heading'. and
15321 `org-show-siblings'."
15322 (let ((heading-p (org-on-heading-p t))
15323 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15324 (following-p (org-get-alist-option org-show-following-heading key))
15325 (entry-p (org-get-alist-option org-show-entry-below key))
15326 (siblings-p (org-get-alist-option org-show-siblings key)))
15327 (catch 'exit
15328 ;; Show heading or entry text
15329 (if (and heading-p (not entry-p))
15330 (org-flag-heading nil) ; only show the heading
15331 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15332 (org-show-hidden-entry))) ; show entire entry
15333 (when following-p
15334 ;; Show next sibling, or heading below text
15335 (save-excursion
15336 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15337 (org-flag-heading nil))))
15338 (when siblings-p (org-show-siblings))
15339 (when hierarchy-p
15340 ;; show all higher headings, possibly with siblings
15341 (save-excursion
15342 (while (and (condition-case nil
15343 (progn (org-up-heading-all 1) t)
15344 (error nil))
15345 (not (bobp)))
15346 (org-flag-heading nil)
15347 (when siblings-p (org-show-siblings))))))))
15349 (defun org-reveal (&optional siblings)
15350 "Show current entry, hierarchy above it, and the following headline.
15351 This can be used to show a consistent set of context around locations
15352 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15353 not t for the search context.
15355 With optional argument SIBLINGS, on each level of the hierarchy all
15356 siblings are shown. This repairs the tree structure to what it would
15357 look like when opened with hierarchical calls to `org-cycle'."
15358 (interactive "P")
15359 (let ((org-show-hierarchy-above t)
15360 (org-show-following-heading t)
15361 (org-show-siblings (if siblings t org-show-siblings)))
15362 (org-show-context nil)))
15364 (defun org-highlight-new-match (beg end)
15365 "Highlight from BEG to END and mark the highlight is an occur headline."
15366 (let ((ov (org-make-overlay beg end)))
15367 (org-overlay-put ov 'face 'secondary-selection)
15368 (push ov org-occur-highlights)))
15370 (defun org-remove-occur-highlights (&optional beg end noremove)
15371 "Remove the occur highlights from the buffer.
15372 BEG and END are ignored. If NOREMOVE is nil, remove this function
15373 from the `before-change-functions' in the current buffer."
15374 (interactive)
15375 (unless org-inhibit-highlight-removal
15376 (mapc 'org-delete-overlay org-occur-highlights)
15377 (setq org-occur-highlights nil)
15378 (setq org-occur-parameters nil)
15379 (unless noremove
15380 (remove-hook 'before-change-functions
15381 'org-remove-occur-highlights 'local))))
15383 ;;;; Priorities
15385 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15386 "Regular expression matching the priority indicator.")
15388 (defvar org-remove-priority-next-time nil)
15390 (defun org-priority-up ()
15391 "Increase the priority of the current item."
15392 (interactive)
15393 (org-priority 'up))
15395 (defun org-priority-down ()
15396 "Decrease the priority of the current item."
15397 (interactive)
15398 (org-priority 'down))
15400 (defun org-priority (&optional action)
15401 "Change the priority of an item by ARG.
15402 ACTION can be `set', `up', `down', or a character."
15403 (interactive)
15404 (setq action (or action 'set))
15405 (let (current new news have remove)
15406 (save-excursion
15407 (org-back-to-heading)
15408 (if (looking-at org-priority-regexp)
15409 (setq current (string-to-char (match-string 2))
15410 have t)
15411 (setq current org-default-priority))
15412 (cond
15413 ((or (eq action 'set) (integerp action))
15414 (if (integerp action)
15415 (setq new action)
15416 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15417 (setq new (read-char-exclusive)))
15418 (if (and (= (upcase org-highest-priority) org-highest-priority)
15419 (= (upcase org-lowest-priority) org-lowest-priority))
15420 (setq new (upcase new)))
15421 (cond ((equal new ?\ ) (setq remove t))
15422 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15423 (error "Priority must be between `%c' and `%c'"
15424 org-highest-priority org-lowest-priority))))
15425 ((eq action 'up)
15426 (if (and (not have) (eq last-command this-command))
15427 (setq new org-lowest-priority)
15428 (setq new (if (and org-priority-start-cycle-with-default (not have))
15429 org-default-priority (1- current)))))
15430 ((eq action 'down)
15431 (if (and (not have) (eq last-command this-command))
15432 (setq new org-highest-priority)
15433 (setq new (if (and org-priority-start-cycle-with-default (not have))
15434 org-default-priority (1+ current)))))
15435 (t (error "Invalid action")))
15436 (if (or (< (upcase new) org-highest-priority)
15437 (> (upcase new) org-lowest-priority))
15438 (setq remove t))
15439 (setq news (format "%c" new))
15440 (if have
15441 (if remove
15442 (replace-match "" t t nil 1)
15443 (replace-match news t t nil 2))
15444 (if remove
15445 (error "No priority cookie found in line")
15446 (looking-at org-todo-line-regexp)
15447 (if (match-end 2)
15448 (progn
15449 (goto-char (match-end 2))
15450 (insert " [#" news "]"))
15451 (goto-char (match-beginning 3))
15452 (insert "[#" news "] ")))))
15453 (org-preserve-lc (org-set-tags nil 'align))
15454 (if remove
15455 (message "Priority removed")
15456 (message "Priority of current item set to %s" news))))
15459 (defun org-get-priority (s)
15460 "Find priority cookie and return priority."
15461 (save-match-data
15462 (if (not (string-match org-priority-regexp s))
15463 (* 1000 (- org-lowest-priority org-default-priority))
15464 (* 1000 (- org-lowest-priority
15465 (string-to-char (match-string 2 s)))))))
15467 ;;;; Tags
15469 (defun org-scan-tags (action matcher &optional todo-only)
15470 "Scan headline tags with inheritance and produce output ACTION.
15471 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15472 evaluated, testing if a given set of tags qualifies a headline for
15473 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15474 are included in the output."
15475 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15476 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15477 (org-re
15478 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15479 (props (list 'face nil
15480 'done-face 'org-done
15481 'undone-face nil
15482 'mouse-face 'highlight
15483 'org-not-done-regexp org-not-done-regexp
15484 'org-todo-regexp org-todo-regexp
15485 'keymap org-agenda-keymap
15486 'help-echo
15487 (format "mouse-2 or RET jump to org file %s"
15488 (abbreviate-file-name
15489 (or (buffer-file-name (buffer-base-buffer))
15490 (buffer-name (buffer-base-buffer)))))))
15491 (case-fold-search nil)
15492 lspos
15493 tags tags-list tags-alist (llast 0) rtn level category i txt
15494 todo marker entry priority)
15495 (save-excursion
15496 (goto-char (point-min))
15497 (when (eq action 'sparse-tree)
15498 (org-overview)
15499 (org-remove-occur-highlights))
15500 (while (re-search-forward re nil t)
15501 (catch :skip
15502 (setq todo (if (match-end 1) (match-string 2))
15503 tags (if (match-end 4) (match-string 4)))
15504 (goto-char (setq lspos (1+ (match-beginning 0))))
15505 (setq level (org-reduced-level (funcall outline-level))
15506 category (org-get-category))
15507 (setq i llast llast level)
15508 ;; remove tag lists from same and sublevels
15509 (while (>= i level)
15510 (when (setq entry (assoc i tags-alist))
15511 (setq tags-alist (delete entry tags-alist)))
15512 (setq i (1- i)))
15513 ;; add the nex tags
15514 (when tags
15515 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15516 tags-alist
15517 (cons (cons level tags) tags-alist)))
15518 ;; compile tags for current headline
15519 (setq tags-list
15520 (if org-use-tag-inheritance
15521 (apply 'append (mapcar 'cdr tags-alist))
15522 tags))
15523 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15524 (eval matcher)
15525 (or (not org-agenda-skip-archived-trees)
15526 (not (member org-archive-tag tags-list))))
15527 (and (eq action 'agenda) (org-agenda-skip))
15528 ;; list this headline
15530 (if (eq action 'sparse-tree)
15531 (progn
15532 (and org-highlight-sparse-tree-matches
15533 (org-get-heading) (match-end 0)
15534 (org-highlight-new-match
15535 (match-beginning 0) (match-beginning 1)))
15536 (org-show-context 'tags-tree))
15537 (setq txt (org-format-agenda-item
15539 (concat
15540 (if org-tags-match-list-sublevels
15541 (make-string (1- level) ?.) "")
15542 (org-get-heading))
15543 category tags-list)
15544 priority (org-get-priority txt))
15545 (goto-char lspos)
15546 (setq marker (org-agenda-new-marker))
15547 (org-add-props txt props
15548 'org-marker marker 'org-hd-marker marker 'org-category category
15549 'priority priority 'type "tagsmatch")
15550 (push txt rtn))
15551 ;; if we are to skip sublevels, jump to end of subtree
15552 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15553 (when (and (eq action 'sparse-tree)
15554 (not org-sparse-tree-open-archived-trees))
15555 (org-hide-archived-subtrees (point-min) (point-max)))
15556 (nreverse rtn)))
15558 (defvar todo-only) ;; dynamically scoped
15560 (defun org-tags-sparse-tree (&optional todo-only match)
15561 "Create a sparse tree according to tags string MATCH.
15562 MATCH can contain positive and negative selection of tags, like
15563 \"+WORK+URGENT-WITHBOSS\".
15564 If optional argument TODO_ONLY is non-nil, only select lines that are
15565 also TODO lines."
15566 (interactive "P")
15567 (org-prepare-agenda-buffers (list (current-buffer)))
15568 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15570 (defvar org-cached-props nil)
15571 (defun org-cached-entry-get (pom property)
15572 (if (or (eq t org-use-property-inheritance)
15573 (member property org-use-property-inheritance))
15574 ;; Caching is not possible, check it directly
15575 (org-entry-get pom property 'inherit)
15576 ;; Get all properties, so that we can do complicated checks easily
15577 (cdr (assoc property (or org-cached-props
15578 (setq org-cached-props
15579 (org-entry-properties pom)))))))
15581 (defun org-global-tags-completion-table (&optional files)
15582 "Return the list of all tags in all agenda buffer/files."
15583 (save-excursion
15584 (org-uniquify
15585 (delq nil
15586 (apply 'append
15587 (mapcar
15588 (lambda (file)
15589 (set-buffer (find-file-noselect file))
15590 (append (org-get-buffer-tags)
15591 (mapcar (lambda (x) (if (stringp (car-safe x))
15592 (list (car-safe x)) nil))
15593 org-tag-alist)))
15594 (if (and files (car files))
15595 files
15596 (org-agenda-files))))))))
15598 (defun org-make-tags-matcher (match)
15599 "Create the TAGS//TODO matcher form for the selection string MATCH."
15600 ;; todo-only is scoped dynamically into this function, and the function
15601 ;; may change it it the matcher asksk for it.
15602 (unless match
15603 ;; Get a new match request, with completion
15604 (let ((org-last-tags-completion-table
15605 (org-global-tags-completion-table)))
15606 (setq match (completing-read
15607 "Match: " 'org-tags-completion-function nil nil nil
15608 'org-tags-history))))
15610 ;; Parse the string and create a lisp form
15611 (let ((match0 match)
15612 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15613 minus tag mm
15614 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15615 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15616 (if (string-match "/+" match)
15617 ;; match contains also a todo-matching request
15618 (progn
15619 (setq tagsmatch (substring match 0 (match-beginning 0))
15620 todomatch (substring match (match-end 0)))
15621 (if (string-match "^!" todomatch)
15622 (setq todo-only t todomatch (substring todomatch 1)))
15623 (if (string-match "^\\s-*$" todomatch)
15624 (setq todomatch nil)))
15625 ;; only matching tags
15626 (setq tagsmatch match todomatch nil))
15628 ;; Make the tags matcher
15629 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15630 (setq tagsmatcher t)
15631 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15632 (while (setq term (pop orterms))
15633 (while (and (equal (substring term -1) "\\") orterms)
15634 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15635 (while (string-match re term)
15636 (setq minus (and (match-end 1)
15637 (equal (match-string 1 term) "-"))
15638 tag (match-string 2 term)
15639 re-p (equal (string-to-char tag) ?{)
15640 level-p (match-end 3)
15641 prop-p (match-end 4)
15642 mm (cond
15643 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15644 (level-p `(= level ,(string-to-number
15645 (match-string 3 term))))
15646 (prop-p
15647 (setq pn (match-string 4 term)
15648 pv (match-string 5 term)
15649 cat-p (equal pn "CATEGORY")
15650 re-p (equal (string-to-char pv) ?{)
15651 pv (substring pv 1 -1))
15652 (if (equal pn "CATEGORY")
15653 (setq gv '(get-text-property (point) 'org-category))
15654 (setq gv `(org-cached-entry-get nil ,pn)))
15655 (if re-p
15656 `(string-match ,pv (or ,gv ""))
15657 `(equal ,pv (or ,gv ""))))
15658 (t `(member ,(downcase tag) tags-list)))
15659 mm (if minus (list 'not mm) mm)
15660 term (substring term (match-end 0)))
15661 (push mm tagsmatcher))
15662 (push (if (> (length tagsmatcher) 1)
15663 (cons 'and tagsmatcher)
15664 (car tagsmatcher))
15665 orlist)
15666 (setq tagsmatcher nil))
15667 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15668 (setq tagsmatcher
15669 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15671 ;; Make the todo matcher
15672 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15673 (setq todomatcher t)
15674 (setq orterms (org-split-string todomatch "|") orlist nil)
15675 (while (setq term (pop orterms))
15676 (while (string-match re term)
15677 (setq minus (and (match-end 1)
15678 (equal (match-string 1 term) "-"))
15679 kwd (match-string 2 term)
15680 re-p (equal (string-to-char kwd) ?{)
15681 term (substring term (match-end 0))
15682 mm (if re-p
15683 `(string-match ,(substring kwd 1 -1) todo)
15684 (list 'equal 'todo kwd))
15685 mm (if minus (list 'not mm) mm))
15686 (push mm todomatcher))
15687 (push (if (> (length todomatcher) 1)
15688 (cons 'and todomatcher)
15689 (car todomatcher))
15690 orlist)
15691 (setq todomatcher nil))
15692 (setq todomatcher (if (> (length orlist) 1)
15693 (cons 'or orlist) (car orlist))))
15695 ;; Return the string and lisp forms of the matcher
15696 (setq matcher (if todomatcher
15697 (list 'and tagsmatcher todomatcher)
15698 tagsmatcher))
15699 (cons match0 matcher)))
15701 (defun org-match-any-p (re list)
15702 "Does re match any element of list?"
15703 (setq list (mapcar (lambda (x) (string-match re x)) list))
15704 (delq nil list))
15706 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15707 (defvar org-tags-overlay (org-make-overlay 1 1))
15708 (org-detach-overlay org-tags-overlay)
15710 (defun org-align-tags-here (to-col)
15711 ;; Assumes that this is a headline
15712 (let ((pos (point)) (col (current-column)) tags)
15713 (beginning-of-line 1)
15714 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15715 (< pos (match-beginning 2)))
15716 (progn
15717 (setq tags (match-string 2))
15718 (goto-char (match-beginning 1))
15719 (insert " ")
15720 (delete-region (point) (1+ (match-end 0)))
15721 (backward-char 1)
15722 (move-to-column
15723 (max (1+ (current-column))
15724 (1+ col)
15725 (if (> to-col 0)
15726 to-col
15727 (- (abs to-col) (length tags))))
15729 (insert tags)
15730 (move-to-column (min (current-column) col) t))
15731 (goto-char pos))))
15733 (defun org-set-tags (&optional arg just-align)
15734 "Set the tags for the current headline.
15735 With prefix ARG, realign all tags in headings in the current buffer."
15736 (interactive "P")
15737 (let* ((re (concat "^" outline-regexp))
15738 (current (org-get-tags-string))
15739 (col (current-column))
15740 (org-setting-tags t)
15741 table current-tags inherited-tags ; computed below when needed
15742 tags p0 c0 c1 rpl)
15743 (if arg
15744 (save-excursion
15745 (goto-char (point-min))
15746 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15747 (while (re-search-forward re nil t)
15748 (org-set-tags nil t)
15749 (end-of-line 1)))
15750 (message "All tags realigned to column %d" org-tags-column))
15751 (if just-align
15752 (setq tags current)
15753 ;; Get a new set of tags from the user
15754 (save-excursion
15755 (setq table (or org-tag-alist (org-get-buffer-tags))
15756 org-last-tags-completion-table table
15757 current-tags (org-split-string current ":")
15758 inherited-tags (nreverse
15759 (nthcdr (length current-tags)
15760 (nreverse (org-get-tags-at))))
15761 tags
15762 (if (or (eq t org-use-fast-tag-selection)
15763 (and org-use-fast-tag-selection
15764 (delq nil (mapcar 'cdr table))))
15765 (org-fast-tag-selection
15766 current-tags inherited-tags table
15767 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15768 (let ((org-add-colon-after-tag-completion t))
15769 (org-trim
15770 (org-without-partial-completion
15771 (completing-read "Tags: " 'org-tags-completion-function
15772 nil nil current 'org-tags-history)))))))
15773 (while (string-match "[-+&]+" tags)
15774 ;; No boolean logic, just a list
15775 (setq tags (replace-match ":" t t tags))))
15777 (if (string-match "\\`[\t ]*\\'" tags)
15778 (setq tags "")
15779 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15780 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15782 ;; Insert new tags at the correct column
15783 (beginning-of-line 1)
15784 (cond
15785 ((and (equal current "") (equal tags "")))
15786 ((re-search-forward
15787 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15788 (point-at-eol) t)
15789 (if (equal tags "")
15790 (setq rpl "")
15791 (goto-char (match-beginning 0))
15792 (setq c0 (current-column) p0 (point)
15793 c1 (max (1+ c0) (if (> org-tags-column 0)
15794 org-tags-column
15795 (- (- org-tags-column) (length tags))))
15796 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15797 (replace-match rpl t t)
15798 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15799 tags)
15800 (t (error "Tags alignment failed")))
15801 (move-to-column col)
15802 (unless just-align
15803 (run-hooks 'org-after-tags-change-hook)))))
15805 (defun org-change-tag-in-region (beg end tag off)
15806 "Add or remove TAG for each entry in the region.
15807 This works in the agenda, and also in an org-mode buffer."
15808 (interactive
15809 (list (region-beginning) (region-end)
15810 (let ((org-last-tags-completion-table
15811 (if (org-mode-p)
15812 (org-get-buffer-tags)
15813 (org-global-tags-completion-table))))
15814 (completing-read
15815 "Tag: " 'org-tags-completion-function nil nil nil
15816 'org-tags-history))
15817 (progn
15818 (message "[s]et or [r]emove? ")
15819 (equal (read-char-exclusive) ?r))))
15820 (if (fboundp 'deactivate-mark) (deactivate-mark))
15821 (let ((agendap (equal major-mode 'org-agenda-mode))
15822 l1 l2 m buf pos newhead (cnt 0))
15823 (goto-char end)
15824 (setq l2 (1- (org-current-line)))
15825 (goto-char beg)
15826 (setq l1 (org-current-line))
15827 (loop for l from l1 to l2 do
15828 (goto-line l)
15829 (setq m (get-text-property (point) 'org-hd-marker))
15830 (when (or (and (org-mode-p) (org-on-heading-p))
15831 (and agendap m))
15832 (setq buf (if agendap (marker-buffer m) (current-buffer))
15833 pos (if agendap m (point)))
15834 (with-current-buffer buf
15835 (save-excursion
15836 (save-restriction
15837 (goto-char pos)
15838 (setq cnt (1+ cnt))
15839 (org-toggle-tag tag (if off 'off 'on))
15840 (setq newhead (org-get-heading)))))
15841 (and agendap (org-agenda-change-all-lines newhead m))))
15842 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15844 (defun org-tags-completion-function (string predicate &optional flag)
15845 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15846 (confirm (lambda (x) (stringp (car x)))))
15847 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15848 (setq s1 (match-string 1 string)
15849 s2 (match-string 2 string))
15850 (setq s1 "" s2 string))
15851 (cond
15852 ((eq flag nil)
15853 ;; try completion
15854 (setq rtn (try-completion s2 ctable confirm))
15855 (if (stringp rtn)
15856 (setq rtn
15857 (concat s1 s2 (substring rtn (length s2))
15858 (if (and org-add-colon-after-tag-completion
15859 (assoc rtn ctable))
15860 ":" ""))))
15861 rtn)
15862 ((eq flag t)
15863 ;; all-completions
15864 (all-completions s2 ctable confirm)
15866 ((eq flag 'lambda)
15867 ;; exact match?
15868 (assoc s2 ctable)))
15871 (defun org-fast-tag-insert (kwd tags face &optional end)
15872 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15873 (insert (format "%-12s" (concat kwd ":"))
15874 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15875 (or end "")))
15877 (defun org-fast-tag-show-exit (flag)
15878 (save-excursion
15879 (goto-line 3)
15880 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15881 (replace-match ""))
15882 (when flag
15883 (end-of-line 1)
15884 (move-to-column (- (window-width) 19) t)
15885 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15887 (defun org-set-current-tags-overlay (current prefix)
15888 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15889 (if (featurep 'xemacs)
15890 (org-overlay-display org-tags-overlay (concat prefix s)
15891 'secondary-selection)
15892 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15893 (org-overlay-display org-tags-overlay (concat prefix s)))))
15895 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15896 "Fast tag selection with single keys.
15897 CURRENT is the current list of tags in the headline, INHERITED is the
15898 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15899 possibly with grouping information. TODO-TABLE is a similar table with
15900 TODO keywords, should these have keys assigned to them.
15901 If the keys are nil, a-z are automatically assigned.
15902 Returns the new tags string, or nil to not change the current settings."
15903 (let* ((fulltable (append table todo-table))
15904 (maxlen (apply 'max (mapcar
15905 (lambda (x)
15906 (if (stringp (car x)) (string-width (car x)) 0))
15907 fulltable)))
15908 (buf (current-buffer))
15909 (expert (eq org-fast-tag-selection-single-key 'expert))
15910 (buffer-tags nil)
15911 (fwidth (+ maxlen 3 1 3))
15912 (ncol (/ (- (window-width) 4) fwidth))
15913 (i-face 'org-done)
15914 (c-face 'org-todo)
15915 tg cnt e c char c1 c2 ntable tbl rtn
15916 ov-start ov-end ov-prefix
15917 (exit-after-next org-fast-tag-selection-single-key)
15918 (done-keywords org-done-keywords)
15919 groups ingroup)
15920 (save-excursion
15921 (beginning-of-line 1)
15922 (if (looking-at
15923 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15924 (setq ov-start (match-beginning 1)
15925 ov-end (match-end 1)
15926 ov-prefix "")
15927 (setq ov-start (1- (point-at-eol))
15928 ov-end (1+ ov-start))
15929 (skip-chars-forward "^\n\r")
15930 (setq ov-prefix
15931 (concat
15932 (buffer-substring (1- (point)) (point))
15933 (if (> (current-column) org-tags-column)
15935 (make-string (- org-tags-column (current-column)) ?\ ))))))
15936 (org-move-overlay org-tags-overlay ov-start ov-end)
15937 (save-window-excursion
15938 (if expert
15939 (set-buffer (get-buffer-create " *Org tags*"))
15940 (delete-other-windows)
15941 (split-window-vertically)
15942 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15943 (erase-buffer)
15944 (org-set-local 'org-done-keywords done-keywords)
15945 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15946 (org-fast-tag-insert "Current" current c-face "\n\n")
15947 (org-fast-tag-show-exit exit-after-next)
15948 (org-set-current-tags-overlay current ov-prefix)
15949 (setq tbl fulltable char ?a cnt 0)
15950 (while (setq e (pop tbl))
15951 (cond
15952 ((equal e '(:startgroup))
15953 (push '() groups) (setq ingroup t)
15954 (when (not (= cnt 0))
15955 (setq cnt 0)
15956 (insert "\n"))
15957 (insert "{ "))
15958 ((equal e '(:endgroup))
15959 (setq ingroup nil cnt 0)
15960 (insert "}\n"))
15962 (setq tg (car e) c2 nil)
15963 (if (cdr e)
15964 (setq c (cdr e))
15965 ;; automatically assign a character.
15966 (setq c1 (string-to-char
15967 (downcase (substring
15968 tg (if (= (string-to-char tg) ?@) 1 0)))))
15969 (if (or (rassoc c1 ntable) (rassoc c1 table))
15970 (while (or (rassoc char ntable) (rassoc char table))
15971 (setq char (1+ char)))
15972 (setq c2 c1))
15973 (setq c (or c2 char)))
15974 (if ingroup (push tg (car groups)))
15975 (setq tg (org-add-props tg nil 'face
15976 (cond
15977 ((not (assoc tg table))
15978 (org-get-todo-face tg))
15979 ((member tg current) c-face)
15980 ((member tg inherited) i-face)
15981 (t nil))))
15982 (if (and (= cnt 0) (not ingroup)) (insert " "))
15983 (insert "[" c "] " tg (make-string
15984 (- fwidth 4 (length tg)) ?\ ))
15985 (push (cons tg c) ntable)
15986 (when (= (setq cnt (1+ cnt)) ncol)
15987 (insert "\n")
15988 (if ingroup (insert " "))
15989 (setq cnt 0)))))
15990 (setq ntable (nreverse ntable))
15991 (insert "\n")
15992 (goto-char (point-min))
15993 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15994 (fit-window-to-buffer))
15995 (setq rtn
15996 (catch 'exit
15997 (while t
15998 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15999 (if groups " [!] no groups" " [!]groups")
16000 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
16001 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
16002 (cond
16003 ((= c ?\r) (throw 'exit t))
16004 ((= c ?!)
16005 (setq groups (not groups))
16006 (goto-char (point-min))
16007 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
16008 ((= c ?\C-c)
16009 (if (not expert)
16010 (org-fast-tag-show-exit
16011 (setq exit-after-next (not exit-after-next)))
16012 (setq expert nil)
16013 (delete-other-windows)
16014 (split-window-vertically)
16015 (org-switch-to-buffer-other-window " *Org tags*")
16016 (and (fboundp 'fit-window-to-buffer)
16017 (fit-window-to-buffer))))
16018 ((or (= c ?\C-g)
16019 (and (= c ?q) (not (rassoc c ntable))))
16020 (org-detach-overlay org-tags-overlay)
16021 (setq quit-flag t))
16022 ((= c ?\ )
16023 (setq current nil)
16024 (if exit-after-next (setq exit-after-next 'now)))
16025 ((= c ?\t)
16026 (condition-case nil
16027 (setq tg (completing-read
16028 "Tag: "
16029 (or buffer-tags
16030 (with-current-buffer buf
16031 (org-get-buffer-tags)))))
16032 (quit (setq tg "")))
16033 (when (string-match "\\S-" tg)
16034 (add-to-list 'buffer-tags (list tg))
16035 (if (member tg current)
16036 (setq current (delete tg current))
16037 (push tg current)))
16038 (if exit-after-next (setq exit-after-next 'now)))
16039 ((setq e (rassoc c todo-table) tg (car e))
16040 (with-current-buffer buf
16041 (save-excursion (org-todo tg)))
16042 (if exit-after-next (setq exit-after-next 'now)))
16043 ((setq e (rassoc c ntable) tg (car e))
16044 (if (member tg current)
16045 (setq current (delete tg current))
16046 (loop for g in groups do
16047 (if (member tg g)
16048 (mapc (lambda (x)
16049 (setq current (delete x current)))
16050 g)))
16051 (push tg current))
16052 (if exit-after-next (setq exit-after-next 'now))))
16054 ;; Create a sorted list
16055 (setq current
16056 (sort current
16057 (lambda (a b)
16058 (assoc b (cdr (memq (assoc a ntable) ntable))))))
16059 (if (eq exit-after-next 'now) (throw 'exit t))
16060 (goto-char (point-min))
16061 (beginning-of-line 2)
16062 (delete-region (point) (point-at-eol))
16063 (org-fast-tag-insert "Current" current c-face)
16064 (org-set-current-tags-overlay current ov-prefix)
16065 (while (re-search-forward
16066 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
16067 (setq tg (match-string 1))
16068 (add-text-properties
16069 (match-beginning 1) (match-end 1)
16070 (list 'face
16071 (cond
16072 ((member tg current) c-face)
16073 ((member tg inherited) i-face)
16074 (t (get-text-property (match-beginning 1) 'face))))))
16075 (goto-char (point-min)))))
16076 (org-detach-overlay org-tags-overlay)
16077 (if rtn
16078 (mapconcat 'identity current ":")
16079 nil))))
16081 (defun org-get-tags-string ()
16082 "Get the TAGS string in the current headline."
16083 (unless (org-on-heading-p t)
16084 (error "Not on a heading"))
16085 (save-excursion
16086 (beginning-of-line 1)
16087 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16088 (org-match-string-no-properties 1)
16089 "")))
16091 (defun org-get-tags ()
16092 "Get the list of tags specified in the current headline."
16093 (org-split-string (org-get-tags-string) ":"))
16095 (defun org-get-buffer-tags ()
16096 "Get a table of all tags used in the buffer, for completion."
16097 (let (tags)
16098 (save-excursion
16099 (goto-char (point-min))
16100 (while (re-search-forward
16101 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16102 (when (equal (char-after (point-at-bol 0)) ?*)
16103 (mapc (lambda (x) (add-to-list 'tags x))
16104 (org-split-string (org-match-string-no-properties 1) ":")))))
16105 (mapcar 'list tags)))
16108 ;;;; Properties
16110 ;;; Setting and retrieving properties
16112 (defconst org-special-properties
16113 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16114 "TIMESTAMP" "TIMESTAMP_IA")
16115 "The special properties valid in Org-mode.
16117 These are properties that are not defined in the property drawer,
16118 but in some other way.")
16120 (defconst org-default-properties
16121 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16122 "LOCATION" "LOGGING" "COLUMNS")
16123 "Some properties that are used by Org-mode for various purposes.
16124 Being in this list makes sure that they are offered for completion.")
16126 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16127 "Regular expression matching the first line of a property drawer.")
16129 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16130 "Regular expression matching the first line of a property drawer.")
16132 (defun org-property-action ()
16133 "Do an action on properties."
16134 (interactive)
16135 (let (c)
16136 (org-at-property-p)
16137 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16138 (setq c (read-char-exclusive))
16139 (cond
16140 ((equal c ?s)
16141 (call-interactively 'org-set-property))
16142 ((equal c ?d)
16143 (call-interactively 'org-delete-property))
16144 ((equal c ?D)
16145 (call-interactively 'org-delete-property-globally))
16146 ((equal c ?c)
16147 (call-interactively 'org-compute-property-at-point))
16148 (t (error "No such property action %c" c)))))
16150 (defun org-at-property-p ()
16151 "Is the cursor in a property line?"
16152 ;; FIXME: Does not check if we are actually in the drawer.
16153 ;; FIXME: also returns true on any drawers.....
16154 ;; This is used by C-c C-c for property action.
16155 (save-excursion
16156 (beginning-of-line 1)
16157 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16159 (defmacro org-with-point-at (pom &rest body)
16160 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16161 (declare (indent 1) (debug t))
16162 `(save-excursion
16163 (if (markerp pom) (set-buffer (marker-buffer pom)))
16164 (save-excursion
16165 (goto-char (or pom (point)))
16166 ,@body)))
16168 (defun org-get-property-block (&optional beg end force)
16169 "Return the (beg . end) range of the body of the property drawer.
16170 BEG and END can be beginning and end of subtree, if not given
16171 they will be found.
16172 If the drawer does not exist and FORCE is non-nil, create the drawer."
16173 (catch 'exit
16174 (save-excursion
16175 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16176 (end (or end (progn (outline-next-heading) (point)))))
16177 (goto-char beg)
16178 (if (re-search-forward org-property-start-re end t)
16179 (setq beg (1+ (match-end 0)))
16180 (if force
16181 (save-excursion
16182 (org-insert-property-drawer)
16183 (setq end (progn (outline-next-heading) (point))))
16184 (throw 'exit nil))
16185 (goto-char beg)
16186 (if (re-search-forward org-property-start-re end t)
16187 (setq beg (1+ (match-end 0)))))
16188 (if (re-search-forward org-property-end-re end t)
16189 (setq end (match-beginning 0))
16190 (or force (throw 'exit nil))
16191 (goto-char beg)
16192 (setq end beg)
16193 (org-indent-line-function)
16194 (insert ":END:\n"))
16195 (cons beg end)))))
16197 (defun org-entry-properties (&optional pom which)
16198 "Get all properties of the entry at point-or-marker POM.
16199 This includes the TODO keyword, the tags, time strings for deadline,
16200 scheduled, and clocking, and any additional properties defined in the
16201 entry. The return value is an alist, keys may occur multiple times
16202 if the property key was used several times.
16203 POM may also be nil, in which case the current entry is used.
16204 If WHICH is nil or `all', get all properties. If WHICH is
16205 `special' or `standard', only get that subclass."
16206 (setq which (or which 'all))
16207 (org-with-point-at pom
16208 (let ((clockstr (substring org-clock-string 0 -1))
16209 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16210 beg end range props sum-props key value string clocksum)
16211 (save-excursion
16212 (when (condition-case nil (org-back-to-heading t) (error nil))
16213 (setq beg (point))
16214 (setq sum-props (get-text-property (point) 'org-summaries))
16215 (setq clocksum (get-text-property (point) :org-clock-minutes))
16216 (outline-next-heading)
16217 (setq end (point))
16218 (when (memq which '(all special))
16219 ;; Get the special properties, like TODO and tags
16220 (goto-char beg)
16221 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16222 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16223 (when (looking-at org-priority-regexp)
16224 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16225 (when (and (setq value (org-get-tags-string))
16226 (string-match "\\S-" value))
16227 (push (cons "TAGS" value) props))
16228 (when (setq value (org-get-tags-at))
16229 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16230 props))
16231 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16232 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16233 string (if (equal key clockstr)
16234 (org-no-properties
16235 (org-trim
16236 (buffer-substring
16237 (match-beginning 3) (goto-char (point-at-eol)))))
16238 (substring (org-match-string-no-properties 3) 1 -1)))
16239 (unless key
16240 (if (= (char-after (match-beginning 3)) ?\[)
16241 (setq key "TIMESTAMP_IA")
16242 (setq key "TIMESTAMP")))
16243 (when (or (equal key clockstr) (not (assoc key props)))
16244 (push (cons key string) props)))
16248 (when (memq which '(all standard))
16249 ;; Get the standard properties, like :PORP: ...
16250 (setq range (org-get-property-block beg end))
16251 (when range
16252 (goto-char (car range))
16253 (while (re-search-forward
16254 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16255 (cdr range) t)
16256 (setq key (org-match-string-no-properties 1)
16257 value (org-trim (or (org-match-string-no-properties 2) "")))
16258 (unless (member key excluded)
16259 (push (cons key (or value "")) props)))))
16260 (if clocksum
16261 (push (cons "CLOCKSUM"
16262 (org-column-number-to-string (/ (float clocksum) 60.)
16263 'add_times))
16264 props))
16265 (append sum-props (nreverse props)))))))
16267 (defun org-entry-get (pom property &optional inherit)
16268 "Get value of PROPERTY for entry at point-or-marker POM.
16269 If INHERIT is non-nil and the entry does not have the property,
16270 then also check higher levels of the hierarchy.
16271 If the property is present but empty, the return value is the empty string.
16272 If the property is not present at all, nil is returned."
16273 (org-with-point-at pom
16274 (if inherit
16275 (org-entry-get-with-inheritance property)
16276 (if (member property org-special-properties)
16277 ;; We need a special property. Use brute force, get all properties.
16278 (cdr (assoc property (org-entry-properties nil 'special)))
16279 (let ((range (org-get-property-block)))
16280 (if (and range
16281 (goto-char (car range))
16282 (re-search-forward
16283 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16284 (cdr range) t))
16285 ;; Found the property, return it.
16286 (if (match-end 1)
16287 (org-match-string-no-properties 1)
16288 "")))))))
16290 (defun org-entry-delete (pom property)
16291 "Delete the property PROPERTY from entry at point-or-marker POM."
16292 (org-with-point-at pom
16293 (if (member property org-special-properties)
16294 nil ; cannot delete these properties.
16295 (let ((range (org-get-property-block)))
16296 (if (and range
16297 (goto-char (car range))
16298 (re-search-forward
16299 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16300 (cdr range) t))
16301 (progn
16302 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16304 nil)))))
16306 ;; Multi-values properties are properties that contain multiple values
16307 ;; These values are assumed to be single words, separated by whitespace.
16308 (defun org-entry-add-to-multivalued-property (pom property value)
16309 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16310 (let* ((old (org-entry-get pom property))
16311 (values (and old (org-split-string old "[ \t]"))))
16312 (unless (member value values)
16313 (setq values (cons value values))
16314 (org-entry-put pom property
16315 (mapconcat 'identity values " ")))))
16317 (defun org-entry-remove-from-multivalued-property (pom property value)
16318 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16319 (let* ((old (org-entry-get pom property))
16320 (values (and old (org-split-string old "[ \t]"))))
16321 (when (member value values)
16322 (setq values (delete value values))
16323 (org-entry-put pom property
16324 (mapconcat 'identity values " ")))))
16326 (defun org-entry-member-in-multivalued-property (pom property value)
16327 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16328 (let* ((old (org-entry-get pom property))
16329 (values (and old (org-split-string old "[ \t]"))))
16330 (member value values)))
16332 (defvar org-entry-property-inherited-from (make-marker))
16334 (defun org-entry-get-with-inheritance (property)
16335 "Get entry property, and search higher levels if not present."
16336 (let (tmp)
16337 (save-excursion
16338 (save-restriction
16339 (widen)
16340 (catch 'ex
16341 (while t
16342 (when (setq tmp (org-entry-get nil property))
16343 (org-back-to-heading t)
16344 (move-marker org-entry-property-inherited-from (point))
16345 (throw 'ex tmp))
16346 (or (org-up-heading-safe) (throw 'ex nil)))))
16347 (or tmp (cdr (assoc property org-local-properties))
16348 (cdr (assoc property org-global-properties))))))
16350 (defun org-entry-put (pom property value)
16351 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16352 (org-with-point-at pom
16353 (org-back-to-heading t)
16354 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16355 range)
16356 (cond
16357 ((equal property "TODO")
16358 (when (and (stringp value) (string-match "\\S-" value)
16359 (not (member value org-todo-keywords-1)))
16360 (error "\"%s\" is not a valid TODO state" value))
16361 (if (or (not value)
16362 (not (string-match "\\S-" value)))
16363 (setq value 'none))
16364 (org-todo value)
16365 (org-set-tags nil 'align))
16366 ((equal property "PRIORITY")
16367 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16368 (string-to-char value) ?\ ))
16369 (org-set-tags nil 'align))
16370 ((equal property "SCHEDULED")
16371 (if (re-search-forward org-scheduled-time-regexp end t)
16372 (cond
16373 ((eq value 'earlier) (org-timestamp-change -1 'day))
16374 ((eq value 'later) (org-timestamp-change 1 'day))
16375 (t (call-interactively 'org-schedule)))
16376 (call-interactively 'org-schedule)))
16377 ((equal property "DEADLINE")
16378 (if (re-search-forward org-deadline-time-regexp end t)
16379 (cond
16380 ((eq value 'earlier) (org-timestamp-change -1 'day))
16381 ((eq value 'later) (org-timestamp-change 1 'day))
16382 (t (call-interactively 'org-deadline)))
16383 (call-interactively 'org-deadline)))
16384 ((member property org-special-properties)
16385 (error "The %s property can not yet be set with `org-entry-put'"
16386 property))
16387 (t ; a non-special property
16388 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16389 (setq range (org-get-property-block beg end 'force))
16390 (goto-char (car range))
16391 (if (re-search-forward
16392 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16393 (progn
16394 (delete-region (match-beginning 1) (match-end 1))
16395 (goto-char (match-beginning 1)))
16396 (goto-char (cdr range))
16397 (insert "\n")
16398 (backward-char 1)
16399 (org-indent-line-function)
16400 (insert ":" property ":"))
16401 (and value (insert " " value))
16402 (org-indent-line-function)))))))
16404 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16405 "Get all property keys in the current buffer.
16406 With INCLUDE-SPECIALS, also list the special properties that relect things
16407 like tags and TODO state.
16408 With INCLUDE-DEFAULTS, also include properties that has special meaning
16409 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16410 With INCLUDE-COLUMNS, also include property names given in COLUMN
16411 formats in the current buffer."
16412 (let (rtn range cfmt cols s p)
16413 (save-excursion
16414 (save-restriction
16415 (widen)
16416 (goto-char (point-min))
16417 (while (re-search-forward org-property-start-re nil t)
16418 (setq range (org-get-property-block))
16419 (goto-char (car range))
16420 (while (re-search-forward
16421 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16422 (cdr range) t)
16423 (add-to-list 'rtn (org-match-string-no-properties 1)))
16424 (outline-next-heading))))
16426 (when include-specials
16427 (setq rtn (append org-special-properties rtn)))
16429 (when include-defaults
16430 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16432 (when include-columns
16433 (save-excursion
16434 (save-restriction
16435 (widen)
16436 (goto-char (point-min))
16437 (while (re-search-forward
16438 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16439 nil t)
16440 (setq cfmt (match-string 2) s 0)
16441 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16442 cfmt s)
16443 (setq s (match-end 0)
16444 p (match-string 1 cfmt))
16445 (unless (or (equal p "ITEM")
16446 (member p org-special-properties))
16447 (add-to-list 'rtn (match-string 1 cfmt))))))))
16449 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16451 (defun org-property-values (key)
16452 "Return a list of all values of property KEY."
16453 (save-excursion
16454 (save-restriction
16455 (widen)
16456 (goto-char (point-min))
16457 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16458 values)
16459 (while (re-search-forward re nil t)
16460 (add-to-list 'values (org-trim (match-string 1))))
16461 (delete "" values)))))
16463 (defun org-insert-property-drawer ()
16464 "Insert a property drawer into the current entry."
16465 (interactive)
16466 (org-back-to-heading t)
16467 (looking-at outline-regexp)
16468 (let ((indent (- (match-end 0)(match-beginning 0)))
16469 (beg (point))
16470 (re (concat "^[ \t]*" org-keyword-time-regexp))
16471 end hiddenp)
16472 (outline-next-heading)
16473 (setq end (point))
16474 (goto-char beg)
16475 (while (re-search-forward re end t))
16476 (setq hiddenp (org-invisible-p))
16477 (end-of-line 1)
16478 (and (equal (char-after) ?\n) (forward-char 1))
16479 (org-skip-over-state-notes)
16480 (skip-chars-backward " \t\n\r")
16481 (if (eq (char-before) ?*) (forward-char 1))
16482 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16483 (beginning-of-line 0)
16484 (indent-to-column indent)
16485 (beginning-of-line 2)
16486 (indent-to-column indent)
16487 (beginning-of-line 0)
16488 (if hiddenp
16489 (save-excursion
16490 (org-back-to-heading t)
16491 (hide-entry))
16492 (org-flag-drawer t))))
16494 (defun org-set-property (property value)
16495 "In the current entry, set PROPERTY to VALUE.
16496 When called interactively, this will prompt for a property name, offering
16497 completion on existing and default properties. And then it will prompt
16498 for a value, offering competion either on allowed values (via an inherited
16499 xxx_ALL property) or on existing values in other instances of this property
16500 in the current file."
16501 (interactive
16502 (let* ((prop (completing-read
16503 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16504 (cur (org-entry-get nil prop))
16505 (allowed (org-property-get-allowed-values nil prop 'table))
16506 (existing (mapcar 'list (org-property-values prop)))
16507 (val (if allowed
16508 (completing-read "Value: " allowed nil 'req-match)
16509 (completing-read
16510 (concat "Value" (if (and cur (string-match "\\S-" cur))
16511 (concat "[" cur "]") "")
16512 ": ")
16513 existing nil nil "" nil cur))))
16514 (list prop (if (equal val "") cur val))))
16515 (unless (equal (org-entry-get nil property) value)
16516 (org-entry-put nil property value)))
16518 (defun org-delete-property (property)
16519 "In the current entry, delete PROPERTY."
16520 (interactive
16521 (let* ((prop (completing-read
16522 "Property: " (org-entry-properties nil 'standard))))
16523 (list prop)))
16524 (message "Property %s %s" property
16525 (if (org-entry-delete nil property)
16526 "deleted"
16527 "was not present in the entry")))
16529 (defun org-delete-property-globally (property)
16530 "Remove PROPERTY globally, from all entries."
16531 (interactive
16532 (let* ((prop (completing-read
16533 "Globally remove property: "
16534 (mapcar 'list (org-buffer-property-keys)))))
16535 (list prop)))
16536 (save-excursion
16537 (save-restriction
16538 (widen)
16539 (goto-char (point-min))
16540 (let ((cnt 0))
16541 (while (re-search-forward
16542 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16543 nil t)
16544 (setq cnt (1+ cnt))
16545 (replace-match ""))
16546 (message "Property \"%s\" removed from %d entries" property cnt)))))
16548 (defvar org-columns-current-fmt-compiled) ; defined below
16550 (defun org-compute-property-at-point ()
16551 "Compute the property at point.
16552 This looks for an enclosing column format, extracts the operator and
16553 then applies it to the proerty in the column format's scope."
16554 (interactive)
16555 (unless (org-at-property-p)
16556 (error "Not at a property"))
16557 (let ((prop (org-match-string-no-properties 2)))
16558 (org-columns-get-format-and-top-level)
16559 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16560 (error "No operator defined for property %s" prop))
16561 (org-columns-compute prop)))
16563 (defun org-property-get-allowed-values (pom property &optional table)
16564 "Get allowed values for the property PROPERTY.
16565 When TABLE is non-nil, return an alist that can directly be used for
16566 completion."
16567 (let (vals)
16568 (cond
16569 ((equal property "TODO")
16570 (setq vals (org-with-point-at pom
16571 (append org-todo-keywords-1 '("")))))
16572 ((equal property "PRIORITY")
16573 (let ((n org-lowest-priority))
16574 (while (>= n org-highest-priority)
16575 (push (char-to-string n) vals)
16576 (setq n (1- n)))))
16577 ((member property org-special-properties))
16579 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16581 (when (and vals (string-match "\\S-" vals))
16582 (setq vals (car (read-from-string (concat "(" vals ")"))))
16583 (setq vals (mapcar (lambda (x)
16584 (cond ((stringp x) x)
16585 ((numberp x) (number-to-string x))
16586 ((symbolp x) (symbol-name x))
16587 (t "???")))
16588 vals)))))
16589 (if table (mapcar 'list vals) vals)))
16591 (defun org-property-previous-allowed-value (&optional previous)
16592 "Switch to the next allowed value for this property."
16593 (interactive)
16594 (org-property-next-allowed-value t))
16596 (defun org-property-next-allowed-value (&optional previous)
16597 "Switch to the next allowed value for this property."
16598 (interactive)
16599 (unless (org-at-property-p)
16600 (error "Not at a property"))
16601 (let* ((key (match-string 2))
16602 (value (match-string 3))
16603 (allowed (or (org-property-get-allowed-values (point) key)
16604 (and (member value '("[ ]" "[-]" "[X]"))
16605 '("[ ]" "[X]"))))
16606 nval)
16607 (unless allowed
16608 (error "Allowed values for this property have not been defined"))
16609 (if previous (setq allowed (reverse allowed)))
16610 (if (member value allowed)
16611 (setq nval (car (cdr (member value allowed)))))
16612 (setq nval (or nval (car allowed)))
16613 (if (equal nval value)
16614 (error "Only one allowed value for this property"))
16615 (org-at-property-p)
16616 (replace-match (concat " :" key ": " nval) t t)
16617 (org-indent-line-function)
16618 (beginning-of-line 1)
16619 (skip-chars-forward " \t")))
16621 (defun org-find-entry-with-id (ident)
16622 "Locate the entry that contains the ID property with exact value IDENT.
16623 IDENT can be a string, a symbol or a number, this function will search for
16624 the string representation of it.
16625 Return the position where this entry starts, or nil if there is no such entry."
16626 (let ((id (cond
16627 ((stringp ident) ident)
16628 ((symbol-name ident) (symbol-name ident))
16629 ((numberp ident) (number-to-string ident))
16630 (t (error "IDENT %s must be a string, symbol or number" ident))))
16631 (case-fold-search nil))
16632 (save-excursion
16633 (save-restriction
16634 (widen)
16635 (goto-char (point-min))
16636 (when (re-search-forward
16637 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16638 nil t)
16639 (org-back-to-heading)
16640 (point))))))
16642 ;;; Column View
16644 (defvar org-columns-overlays nil
16645 "Holds the list of current column overlays.")
16647 (defvar org-columns-current-fmt nil
16648 "Local variable, holds the currently active column format.")
16649 (defvar org-columns-current-fmt-compiled nil
16650 "Local variable, holds the currently active column format.
16651 This is the compiled version of the format.")
16652 (defvar org-columns-current-widths nil
16653 "Loval variable, holds the currently widths of fields.")
16654 (defvar org-columns-current-maxwidths nil
16655 "Loval variable, holds the currently active maximum column widths.")
16656 (defvar org-columns-begin-marker (make-marker)
16657 "Points to the position where last a column creation command was called.")
16658 (defvar org-columns-top-level-marker (make-marker)
16659 "Points to the position where current columns region starts.")
16661 (defvar org-columns-map (make-sparse-keymap)
16662 "The keymap valid in column display.")
16664 (defun org-columns-content ()
16665 "Switch to contents view while in columns view."
16666 (interactive)
16667 (org-overview)
16668 (org-content))
16670 (org-defkey org-columns-map "c" 'org-columns-content)
16671 (org-defkey org-columns-map "o" 'org-overview)
16672 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16673 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16674 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16675 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16676 (org-defkey org-columns-map "v" 'org-columns-show-value)
16677 (org-defkey org-columns-map "q" 'org-columns-quit)
16678 (org-defkey org-columns-map "r" 'org-columns-redo)
16679 (org-defkey org-columns-map "g" 'org-columns-redo)
16680 (org-defkey org-columns-map [left] 'backward-char)
16681 (org-defkey org-columns-map "\M-b" 'backward-char)
16682 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16683 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16684 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16685 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16686 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16687 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16688 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16689 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16690 (org-defkey org-columns-map "<" 'org-columns-narrow)
16691 (org-defkey org-columns-map ">" 'org-columns-widen)
16692 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16693 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16694 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16695 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16697 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16698 '("Column"
16699 ["Edit property" org-columns-edit-value t]
16700 ["Next allowed value" org-columns-next-allowed-value t]
16701 ["Previous allowed value" org-columns-previous-allowed-value t]
16702 ["Show full value" org-columns-show-value t]
16703 ["Edit allowed values" org-columns-edit-allowed t]
16704 "--"
16705 ["Edit column attributes" org-columns-edit-attributes t]
16706 ["Increase column width" org-columns-widen t]
16707 ["Decrease column width" org-columns-narrow t]
16708 "--"
16709 ["Move column right" org-columns-move-right t]
16710 ["Move column left" org-columns-move-left t]
16711 ["Add column" org-columns-new t]
16712 ["Delete column" org-columns-delete t]
16713 "--"
16714 ["CONTENTS" org-columns-content t]
16715 ["OVERVIEW" org-overview t]
16716 ["Refresh columns display" org-columns-redo t]
16717 "--"
16718 ["Open link" org-columns-open-link t]
16719 "--"
16720 ["Quit" org-columns-quit t]))
16722 (defun org-columns-new-overlay (beg end &optional string face)
16723 "Create a new column overlay and add it to the list."
16724 (let ((ov (org-make-overlay beg end)))
16725 (org-overlay-put ov 'face (or face 'secondary-selection))
16726 (org-overlay-display ov string face)
16727 (push ov org-columns-overlays)
16728 ov))
16730 (defun org-columns-display-here (&optional props)
16731 "Overlay the current line with column display."
16732 (interactive)
16733 (let* ((fmt org-columns-current-fmt-compiled)
16734 (beg (point-at-bol))
16735 (level-face (save-excursion
16736 (beginning-of-line 1)
16737 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16738 (org-get-level-face 2))))
16739 (color (list :foreground
16740 (face-attribute (or level-face 'default) :foreground)))
16741 props pom property ass width f string ov column val modval)
16742 ;; Check if the entry is in another buffer.
16743 (unless props
16744 (if (eq major-mode 'org-agenda-mode)
16745 (setq pom (or (get-text-property (point) 'org-hd-marker)
16746 (get-text-property (point) 'org-marker))
16747 props (if pom (org-entry-properties pom) nil))
16748 (setq props (org-entry-properties nil))))
16749 ;; Walk the format
16750 (while (setq column (pop fmt))
16751 (setq property (car column)
16752 ass (if (equal property "ITEM")
16753 (cons "ITEM"
16754 (save-match-data
16755 (org-no-properties
16756 (org-remove-tabs
16757 (buffer-substring-no-properties
16758 (point-at-bol) (point-at-eol))))))
16759 (assoc property props))
16760 width (or (cdr (assoc property org-columns-current-maxwidths))
16761 (nth 2 column)
16762 (length property))
16763 f (format "%%-%d.%ds | " width width)
16764 val (or (cdr ass) "")
16765 modval (if (equal property "ITEM")
16766 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16767 string (format f (or modval val)))
16768 ;; Create the overlay
16769 (org-unmodified
16770 (setq ov (org-columns-new-overlay
16771 beg (setq beg (1+ beg)) string
16772 (list color 'org-column)))
16773 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16774 (org-overlay-put ov 'keymap org-columns-map)
16775 (org-overlay-put ov 'org-columns-key property)
16776 (org-overlay-put ov 'org-columns-value (cdr ass))
16777 (org-overlay-put ov 'org-columns-value-modified modval)
16778 (org-overlay-put ov 'org-columns-pom pom)
16779 (org-overlay-put ov 'org-columns-format f))
16780 (if (or (not (char-after beg))
16781 (equal (char-after beg) ?\n))
16782 (let ((inhibit-read-only t))
16783 (save-excursion
16784 (goto-char beg)
16785 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16786 ;; Make the rest of the line disappear.
16787 (org-unmodified
16788 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16789 (org-overlay-put ov 'invisible t)
16790 (org-overlay-put ov 'keymap org-columns-map)
16791 (org-overlay-put ov 'intangible t)
16792 (push ov org-columns-overlays)
16793 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16794 (org-overlay-put ov 'keymap org-columns-map)
16795 (push ov org-columns-overlays)
16796 (let ((inhibit-read-only t))
16797 (put-text-property (max (point-min) (1- (point-at-bol)))
16798 (min (point-max) (1+ (point-at-eol)))
16799 'read-only "Type `e' to edit property")))))
16801 (defvar org-previous-header-line-format nil
16802 "The header line format before column view was turned on.")
16803 (defvar org-columns-inhibit-recalculation nil
16804 "Inhibit recomputing of columns on column view startup.")
16807 (defvar header-line-format)
16808 (defun org-columns-display-here-title ()
16809 "Overlay the newline before the current line with the table title."
16810 (interactive)
16811 (let ((fmt org-columns-current-fmt-compiled)
16812 string (title "")
16813 property width f column str widths)
16814 (while (setq column (pop fmt))
16815 (setq property (car column)
16816 str (or (nth 1 column) property)
16817 width (or (cdr (assoc property org-columns-current-maxwidths))
16818 (nth 2 column)
16819 (length str))
16820 widths (push width widths)
16821 f (format "%%-%d.%ds | " width width)
16822 string (format f str)
16823 title (concat title string)))
16824 (setq title (concat
16825 (org-add-props " " nil 'display '(space :align-to 0))
16826 (org-add-props title nil 'face '(:weight bold :underline t))))
16827 (org-set-local 'org-previous-header-line-format header-line-format)
16828 (org-set-local 'org-columns-current-widths (nreverse widths))
16829 (setq header-line-format title)))
16831 (defun org-columns-remove-overlays ()
16832 "Remove all currently active column overlays."
16833 (interactive)
16834 (when (marker-buffer org-columns-begin-marker)
16835 (with-current-buffer (marker-buffer org-columns-begin-marker)
16836 (when (local-variable-p 'org-previous-header-line-format)
16837 (setq header-line-format org-previous-header-line-format)
16838 (kill-local-variable 'org-previous-header-line-format))
16839 (move-marker org-columns-begin-marker nil)
16840 (move-marker org-columns-top-level-marker nil)
16841 (org-unmodified
16842 (mapc 'org-delete-overlay org-columns-overlays)
16843 (setq org-columns-overlays nil)
16844 (let ((inhibit-read-only t))
16845 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16847 (defun org-columns-cleanup-item (item fmt)
16848 "Remove from ITEM what is a column in the format FMT."
16849 (if (not org-complex-heading-regexp)
16850 item
16851 (when (string-match org-complex-heading-regexp item)
16852 (concat
16853 (org-add-props (concat (match-string 1 item) " ") nil
16854 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16855 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16856 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16857 " " (match-string 4 item)
16858 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16860 (defun org-columns-show-value ()
16861 "Show the full value of the property."
16862 (interactive)
16863 (let ((value (get-char-property (point) 'org-columns-value)))
16864 (message "Value is: %s" (or value ""))))
16866 (defun org-columns-quit ()
16867 "Remove the column overlays and in this way exit column editing."
16868 (interactive)
16869 (org-unmodified
16870 (org-columns-remove-overlays)
16871 (let ((inhibit-read-only t))
16872 (remove-text-properties (point-min) (point-max) '(read-only t))))
16873 (when (eq major-mode 'org-agenda-mode)
16874 (message
16875 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16877 (defun org-columns-check-computed ()
16878 "Check if this column value is computed.
16879 If yes, throw an error indicating that changing it does not make sense."
16880 (let ((val (get-char-property (point) 'org-columns-value)))
16881 (when (and (stringp val)
16882 (get-char-property 0 'org-computed val))
16883 (error "This value is computed from the entry's children"))))
16885 (defun org-columns-todo (&optional arg)
16886 "Change the TODO state during column view."
16887 (interactive "P")
16888 (org-columns-edit-value "TODO"))
16890 (defun org-columns-set-tags-or-toggle (&optional arg)
16891 "Toggle checkbox at point, or set tags for current headline."
16892 (interactive "P")
16893 (if (string-match "\\`\\[[ xX-]\\]\\'"
16894 (get-char-property (point) 'org-columns-value))
16895 (org-columns-next-allowed-value)
16896 (org-columns-edit-value "TAGS")))
16898 (defun org-columns-edit-value (&optional key)
16899 "Edit the value of the property at point in column view.
16900 Where possible, use the standard interface for changing this line."
16901 (interactive)
16902 (org-columns-check-computed)
16903 (let* ((external-key key)
16904 (col (current-column))
16905 (key (or key (get-char-property (point) 'org-columns-key)))
16906 (value (get-char-property (point) 'org-columns-value))
16907 (bol (point-at-bol)) (eol (point-at-eol))
16908 (pom (or (get-text-property bol 'org-hd-marker)
16909 (point))) ; keep despite of compiler waring
16910 (line-overlays
16911 (delq nil (mapcar (lambda (x)
16912 (and (eq (overlay-buffer x) (current-buffer))
16913 (>= (overlay-start x) bol)
16914 (<= (overlay-start x) eol)
16916 org-columns-overlays)))
16917 nval eval allowed)
16918 (cond
16919 ((equal key "CLOCKSUM")
16920 (error "This special column cannot be edited"))
16921 ((equal key "ITEM")
16922 (setq eval '(org-with-point-at pom
16923 (org-edit-headline))))
16924 ((equal key "TODO")
16925 (setq eval '(org-with-point-at pom
16926 (let ((current-prefix-arg
16927 (if external-key current-prefix-arg '(4))))
16928 (call-interactively 'org-todo)))))
16929 ((equal key "PRIORITY")
16930 (setq eval '(org-with-point-at pom
16931 (call-interactively 'org-priority))))
16932 ((equal key "TAGS")
16933 (setq eval '(org-with-point-at pom
16934 (let ((org-fast-tag-selection-single-key
16935 (if (eq org-fast-tag-selection-single-key 'expert)
16936 t org-fast-tag-selection-single-key)))
16937 (call-interactively 'org-set-tags)))))
16938 ((equal key "DEADLINE")
16939 (setq eval '(org-with-point-at pom
16940 (call-interactively 'org-deadline))))
16941 ((equal key "SCHEDULED")
16942 (setq eval '(org-with-point-at pom
16943 (call-interactively 'org-schedule))))
16945 (setq allowed (org-property-get-allowed-values pom key 'table))
16946 (if allowed
16947 (setq nval (completing-read "Value: " allowed nil t))
16948 (setq nval (read-string "Edit: " value)))
16949 (setq nval (org-trim nval))
16950 (when (not (equal nval value))
16951 (setq eval '(org-entry-put pom key nval)))))
16952 (when eval
16953 (let ((inhibit-read-only t))
16954 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16955 (unwind-protect
16956 (progn
16957 (setq org-columns-overlays
16958 (org-delete-all line-overlays org-columns-overlays))
16959 (mapc 'org-delete-overlay line-overlays)
16960 (org-columns-eval eval))
16961 (org-columns-display-here))))
16962 (move-to-column col)
16963 (if (and (org-mode-p)
16964 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16965 (org-columns-update key))))
16967 (defun org-edit-headline () ; FIXME: this is not columns specific
16968 "Edit the current headline, the part without TODO keyword, TAGS."
16969 (org-back-to-heading)
16970 (when (looking-at org-todo-line-regexp)
16971 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16972 (txt (match-string 3))
16973 (post "")
16974 txt2)
16975 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16976 (setq post (match-string 0 txt)
16977 txt (substring txt 0 (match-beginning 0))))
16978 (setq txt2 (read-string "Edit: " txt))
16979 (when (not (equal txt txt2))
16980 (beginning-of-line 1)
16981 (insert pre txt2 post)
16982 (delete-region (point) (point-at-eol))
16983 (org-set-tags nil t)))))
16985 (defun org-columns-edit-allowed ()
16986 "Edit the list of allowed values for the current property."
16987 (interactive)
16988 (let* ((key (get-char-property (point) 'org-columns-key))
16989 (key1 (concat key "_ALL"))
16990 (allowed (org-entry-get (point) key1 t))
16991 nval)
16992 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16993 (setq nval (read-string "Allowed: " allowed))
16994 (org-entry-put
16995 (cond ((marker-position org-entry-property-inherited-from)
16996 org-entry-property-inherited-from)
16997 ((marker-position org-columns-top-level-marker)
16998 org-columns-top-level-marker))
16999 key1 nval)))
17001 (defmacro org-no-warnings (&rest body)
17002 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
17004 (defun org-columns-eval (form)
17005 (let (hidep)
17006 (save-excursion
17007 (beginning-of-line 1)
17008 ;; `next-line' is needed here, because it skips invisible line.
17009 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
17010 (setq hidep (org-on-heading-p 1)))
17011 (eval form)
17012 (and hidep (hide-entry))))
17014 (defun org-columns-previous-allowed-value ()
17015 "Switch to the previous allowed value for this column."
17016 (interactive)
17017 (org-columns-next-allowed-value t))
17019 (defun org-columns-next-allowed-value (&optional previous)
17020 "Switch to the next allowed value for this column."
17021 (interactive)
17022 (org-columns-check-computed)
17023 (let* ((col (current-column))
17024 (key (get-char-property (point) 'org-columns-key))
17025 (value (get-char-property (point) 'org-columns-value))
17026 (bol (point-at-bol)) (eol (point-at-eol))
17027 (pom (or (get-text-property bol 'org-hd-marker)
17028 (point))) ; keep despite of compiler waring
17029 (line-overlays
17030 (delq nil (mapcar (lambda (x)
17031 (and (eq (overlay-buffer x) (current-buffer))
17032 (>= (overlay-start x) bol)
17033 (<= (overlay-start x) eol)
17035 org-columns-overlays)))
17036 (allowed (or (org-property-get-allowed-values pom key)
17037 (and (memq
17038 (nth 4 (assoc key org-columns-current-fmt-compiled))
17039 '(checkbox checkbox-n-of-m checkbox-percent))
17040 '("[ ]" "[X]"))))
17041 nval)
17042 (when (equal key "ITEM")
17043 (error "Cannot edit item headline from here"))
17044 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
17045 (error "Allowed values for this property have not been defined"))
17046 (if (member key '("SCHEDULED" "DEADLINE"))
17047 (setq nval (if previous 'earlier 'later))
17048 (if previous (setq allowed (reverse allowed)))
17049 (if (member value allowed)
17050 (setq nval (car (cdr (member value allowed)))))
17051 (setq nval (or nval (car allowed)))
17052 (if (equal nval value)
17053 (error "Only one allowed value for this property")))
17054 (let ((inhibit-read-only t))
17055 (remove-text-properties (1- bol) eol '(read-only t))
17056 (unwind-protect
17057 (progn
17058 (setq org-columns-overlays
17059 (org-delete-all line-overlays org-columns-overlays))
17060 (mapc 'org-delete-overlay line-overlays)
17061 (org-columns-eval '(org-entry-put pom key nval)))
17062 (org-columns-display-here)))
17063 (move-to-column col)
17064 (if (and (org-mode-p)
17065 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17066 (org-columns-update key))))
17068 (defun org-verify-version (task)
17069 (cond
17070 ((eq task 'columns)
17071 (if (or (featurep 'xemacs)
17072 (< emacs-major-version 22))
17073 (error "Emacs 22 is required for the columns feature")))))
17075 (defun org-columns-open-link (&optional arg)
17076 (interactive "P")
17077 (let ((value (get-char-property (point) 'org-columns-value)))
17078 (org-open-link-from-string value arg)))
17080 (defun org-open-link-from-string (s &optional arg)
17081 "Open a link in the string S, as if it was in Org-mode."
17082 (interactive)
17083 (with-temp-buffer
17084 (let ((org-inhibit-startup t))
17085 (org-mode)
17086 (insert s)
17087 (goto-char (point-min))
17088 (org-open-at-point arg))))
17090 (defun org-columns-get-format-and-top-level ()
17091 (let (fmt)
17092 (when (condition-case nil (org-back-to-heading) (error nil))
17093 (move-marker org-entry-property-inherited-from nil)
17094 (setq fmt (org-entry-get nil "COLUMNS" t)))
17095 (setq fmt (or fmt org-columns-default-format))
17096 (org-set-local 'org-columns-current-fmt fmt)
17097 (org-columns-compile-format fmt)
17098 (if (marker-position org-entry-property-inherited-from)
17099 (move-marker org-columns-top-level-marker
17100 org-entry-property-inherited-from)
17101 (move-marker org-columns-top-level-marker (point)))
17102 fmt))
17104 (defun org-columns ()
17105 "Turn on column view on an org-mode file."
17106 (interactive)
17107 (org-verify-version 'columns)
17108 (org-columns-remove-overlays)
17109 (move-marker org-columns-begin-marker (point))
17110 (let (beg end fmt cache maxwidths)
17111 (setq fmt (org-columns-get-format-and-top-level))
17112 (save-excursion
17113 (goto-char org-columns-top-level-marker)
17114 (setq beg (point))
17115 (unless org-columns-inhibit-recalculation
17116 (org-columns-compute-all))
17117 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17118 (point-max)))
17119 ;; Get and cache the properties
17120 (goto-char beg)
17121 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17122 (save-excursion
17123 (save-restriction
17124 (narrow-to-region beg end)
17125 (org-clock-sum))))
17126 (while (re-search-forward (concat "^" outline-regexp) end t)
17127 (push (cons (org-current-line) (org-entry-properties)) cache))
17128 (when cache
17129 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17130 (org-set-local 'org-columns-current-maxwidths maxwidths)
17131 (org-columns-display-here-title)
17132 (mapc (lambda (x)
17133 (goto-line (car x))
17134 (org-columns-display-here (cdr x)))
17135 cache)))))
17137 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17138 "Insert a new column, to the leeft o the current column."
17139 (interactive)
17140 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17141 cell)
17142 (setq prop (completing-read
17143 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17144 nil nil prop))
17145 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17146 (setq width (read-string "Column width: " (if width (number-to-string width))))
17147 (if (string-match "\\S-" width)
17148 (setq width (string-to-number width))
17149 (setq width nil))
17150 (setq fmt (completing-read "Summary [none]: "
17151 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17152 nil t))
17153 (if (string-match "\\S-" fmt)
17154 (setq fmt (intern fmt))
17155 (setq fmt nil))
17156 (if (eq fmt 'none) (setq fmt nil))
17157 (if editp
17158 (progn
17159 (setcar editp prop)
17160 (setcdr editp (list title width nil fmt)))
17161 (setq cell (nthcdr (1- (current-column))
17162 org-columns-current-fmt-compiled))
17163 (setcdr cell (cons (list prop title width nil fmt)
17164 (cdr cell))))
17165 (org-columns-store-format)
17166 (org-columns-redo)))
17168 (defun org-columns-delete ()
17169 "Delete the column at point from columns view."
17170 (interactive)
17171 (let* ((n (current-column))
17172 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17173 (when (y-or-n-p
17174 (format "Are you sure you want to remove column \"%s\"? " title))
17175 (setq org-columns-current-fmt-compiled
17176 (delq (nth n org-columns-current-fmt-compiled)
17177 org-columns-current-fmt-compiled))
17178 (org-columns-store-format)
17179 (org-columns-redo)
17180 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17181 (backward-char 1)))))
17183 (defun org-columns-edit-attributes ()
17184 "Edit the attributes of the current column."
17185 (interactive)
17186 (let* ((n (current-column))
17187 (info (nth n org-columns-current-fmt-compiled)))
17188 (apply 'org-columns-new info)))
17190 (defun org-columns-widen (arg)
17191 "Make the column wider by ARG characters."
17192 (interactive "p")
17193 (let* ((n (current-column))
17194 (entry (nth n org-columns-current-fmt-compiled))
17195 (width (or (nth 2 entry)
17196 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17197 (setq width (max 1 (+ width arg)))
17198 (setcar (nthcdr 2 entry) width)
17199 (org-columns-store-format)
17200 (org-columns-redo)))
17202 (defun org-columns-narrow (arg)
17203 "Make the column nrrower by ARG characters."
17204 (interactive "p")
17205 (org-columns-widen (- arg)))
17207 (defun org-columns-move-right ()
17208 "Swap this column with the one to the right."
17209 (interactive)
17210 (let* ((n (current-column))
17211 (cell (nthcdr n org-columns-current-fmt-compiled))
17213 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17214 (error "Cannot shift this column further to the right"))
17215 (setq e (car cell))
17216 (setcar cell (car (cdr cell)))
17217 (setcdr cell (cons e (cdr (cdr cell))))
17218 (org-columns-store-format)
17219 (org-columns-redo)
17220 (forward-char 1)))
17222 (defun org-columns-move-left ()
17223 "Swap this column with the one to the left."
17224 (interactive)
17225 (let* ((n (current-column)))
17226 (when (= n 0)
17227 (error "Cannot shift this column further to the left"))
17228 (backward-char 1)
17229 (org-columns-move-right)
17230 (backward-char 1)))
17232 (defun org-columns-store-format ()
17233 "Store the text version of the current columns format in appropriate place.
17234 This is either in the COLUMNS property of the node starting the current column
17235 display, or in the #+COLUMNS line of the current buffer."
17236 (let (fmt (cnt 0))
17237 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17238 (org-set-local 'org-columns-current-fmt fmt)
17239 (if (marker-position org-columns-top-level-marker)
17240 (save-excursion
17241 (goto-char org-columns-top-level-marker)
17242 (if (and (org-at-heading-p)
17243 (org-entry-get nil "COLUMNS"))
17244 (org-entry-put nil "COLUMNS" fmt)
17245 (goto-char (point-min))
17246 ;; Overwrite all #+COLUMNS lines....
17247 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17248 (setq cnt (1+ cnt))
17249 (replace-match (concat "#+COLUMNS: " fmt) t t))
17250 (unless (> cnt 0)
17251 (goto-char (point-min))
17252 (or (org-on-heading-p t) (outline-next-heading))
17253 (let ((inhibit-read-only t))
17254 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17255 (org-set-local 'org-columns-default-format fmt))))))
17257 (defvar org-overriding-columns-format nil
17258 "When set, overrides any other definition.")
17259 (defvar org-agenda-view-columns-initially nil
17260 "When set, switch to columns view immediately after creating the agenda.")
17262 (defun org-agenda-columns ()
17263 "Turn on column view in the agenda."
17264 (interactive)
17265 (org-verify-version 'columns)
17266 (org-columns-remove-overlays)
17267 (move-marker org-columns-begin-marker (point))
17268 (let (fmt cache maxwidths m)
17269 (cond
17270 ((and (local-variable-p 'org-overriding-columns-format)
17271 org-overriding-columns-format)
17272 (setq fmt org-overriding-columns-format))
17273 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17274 (setq fmt (org-entry-get m "COLUMNS" t)))
17275 ((and (boundp 'org-columns-current-fmt)
17276 (local-variable-p 'org-columns-current-fmt)
17277 org-columns-current-fmt)
17278 (setq fmt org-columns-current-fmt))
17279 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17280 (setq m (get-text-property m 'org-hd-marker))
17281 (setq fmt (org-entry-get m "COLUMNS" t))))
17282 (setq fmt (or fmt org-columns-default-format))
17283 (org-set-local 'org-columns-current-fmt fmt)
17284 (org-columns-compile-format fmt)
17285 (save-excursion
17286 ;; Get and cache the properties
17287 (goto-char (point-min))
17288 (while (not (eobp))
17289 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17290 (get-text-property (point) 'org-marker)))
17291 (push (cons (org-current-line) (org-entry-properties m)) cache))
17292 (beginning-of-line 2))
17293 (when cache
17294 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17295 (org-set-local 'org-columns-current-maxwidths maxwidths)
17296 (org-columns-display-here-title)
17297 (mapc (lambda (x)
17298 (goto-line (car x))
17299 (org-columns-display-here (cdr x)))
17300 cache)))))
17302 (defun org-columns-get-autowidth-alist (s cache)
17303 "Derive the maximum column widths from the format and the cache."
17304 (let ((start 0) rtn)
17305 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17306 (push (cons (match-string 1 s) 1) rtn)
17307 (setq start (match-end 0)))
17308 (mapc (lambda (x)
17309 (setcdr x (apply 'max
17310 (mapcar
17311 (lambda (y)
17312 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17313 cache))))
17314 rtn)
17315 rtn))
17317 (defun org-columns-compute-all ()
17318 "Compute all columns that have operators defined."
17319 (org-unmodified
17320 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17321 (let ((columns org-columns-current-fmt-compiled) col)
17322 (while (setq col (pop columns))
17323 (when (nth 3 col)
17324 (save-excursion
17325 (org-columns-compute (car col)))))))
17327 (defun org-columns-update (property)
17328 "Recompute PROPERTY, and update the columns display for it."
17329 (org-columns-compute property)
17330 (let (fmt val pos)
17331 (save-excursion
17332 (mapc (lambda (ov)
17333 (when (equal (org-overlay-get ov 'org-columns-key) property)
17334 (setq pos (org-overlay-start ov))
17335 (goto-char pos)
17336 (when (setq val (cdr (assoc property
17337 (get-text-property
17338 (point-at-bol) 'org-summaries))))
17339 (setq fmt (org-overlay-get ov 'org-columns-format))
17340 (org-overlay-put ov 'org-columns-value val)
17341 (org-overlay-put ov 'display (format fmt val)))))
17342 org-columns-overlays))))
17344 (defun org-columns-compute (property)
17345 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17346 (interactive)
17347 (let* ((re (concat "^" outline-regexp))
17348 (lmax 30) ; Does anyone use deeper levels???
17349 (lsum (make-vector lmax 0))
17350 (lflag (make-vector lmax nil))
17351 (level 0)
17352 (ass (assoc property org-columns-current-fmt-compiled))
17353 (format (nth 4 ass))
17354 (printf (nth 5 ass))
17355 (beg org-columns-top-level-marker)
17356 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17357 (save-excursion
17358 ;; Find the region to compute
17359 (goto-char beg)
17360 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17361 (goto-char end)
17362 ;; Walk the tree from the back and do the computations
17363 (while (re-search-backward re beg t)
17364 (setq sumpos (match-beginning 0)
17365 last-level level
17366 level (org-outline-level)
17367 val (org-entry-get nil property)
17368 valflag (and val (string-match "\\S-" val)))
17369 (cond
17370 ((< level last-level)
17371 ;; put the sum of lower levels here as a property
17372 (setq sum (aref lsum last-level) ; current sum
17373 flag (aref lflag last-level) ; any valid entries from children?
17374 str (org-column-number-to-string sum format printf)
17375 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17376 useval (if flag str1 (if valflag val ""))
17377 sum-alist (get-text-property sumpos 'org-summaries))
17378 (if (assoc property sum-alist)
17379 (setcdr (assoc property sum-alist) useval)
17380 (push (cons property useval) sum-alist)
17381 (org-unmodified
17382 (add-text-properties sumpos (1+ sumpos)
17383 (list 'org-summaries sum-alist))))
17384 (when val
17385 (org-entry-put nil property (if flag str val)))
17386 ;; add current to current level accumulator
17387 (when (or flag valflag)
17388 (aset lsum level (+ (aref lsum level)
17389 (if flag sum (org-column-string-to-number
17390 (if flag str val) format))))
17391 (aset lflag level t))
17392 ;; clear accumulators for deeper levels
17393 (loop for l from (1+ level) to (1- lmax) do
17394 (aset lsum l 0)
17395 (aset lflag l nil)))
17396 ((>= level last-level)
17397 ;; add what we have here to the accumulator for this level
17398 (aset lsum level (+ (aref lsum level)
17399 (org-column-string-to-number (or val "0") format)))
17400 (and valflag (aset lflag level t)))
17401 (t (error "This should not happen")))))))
17403 (defun org-columns-redo ()
17404 "Construct the column display again."
17405 (interactive)
17406 (message "Recomputing columns...")
17407 (save-excursion
17408 (if (marker-position org-columns-begin-marker)
17409 (goto-char org-columns-begin-marker))
17410 (org-columns-remove-overlays)
17411 (if (org-mode-p)
17412 (call-interactively 'org-columns)
17413 (call-interactively 'org-agenda-columns)))
17414 (message "Recomputing columns...done"))
17416 (defun org-columns-not-in-agenda ()
17417 (if (eq major-mode 'org-agenda-mode)
17418 (error "This command is only allowed in Org-mode buffers")))
17421 (defun org-string-to-number (s)
17422 "Convert string to number, and interpret hh:mm:ss."
17423 (if (not (string-match ":" s))
17424 (string-to-number s)
17425 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17426 (while l
17427 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17428 sum)))
17430 (defun org-column-number-to-string (n fmt &optional printf)
17431 "Convert a computed column number to a string value, according to FMT."
17432 (cond
17433 ((eq fmt 'add_times)
17434 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17435 (format "%d:%02d" h m)))
17436 ((eq fmt 'checkbox)
17437 (cond ((= n (floor n)) "[X]")
17438 ((> n 1.) "[-]")
17439 (t "[ ]")))
17440 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17441 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17442 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17443 (printf (format printf n))
17444 ((eq fmt 'currency)
17445 (format "%.2f" n))
17446 (t (number-to-string n))))
17448 (defun org-nofm-to-completion (n m &optional percent)
17449 (if (not percent)
17450 (format "[%d/%d]" n m)
17451 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17453 (defun org-column-string-to-number (s fmt)
17454 "Convert a column value to a number that can be used for column computing."
17455 (cond
17456 ((string-match ":" s)
17457 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17458 (while l
17459 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17460 sum))
17461 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17462 (if (equal s "[X]") 1. 0.000001))
17463 (t (string-to-number s))))
17465 (defun org-columns-uncompile-format (cfmt)
17466 "Turn the compiled columns format back into a string representation."
17467 (let ((rtn "") e s prop title op width fmt printf)
17468 (while (setq e (pop cfmt))
17469 (setq prop (car e)
17470 title (nth 1 e)
17471 width (nth 2 e)
17472 op (nth 3 e)
17473 fmt (nth 4 e)
17474 printf (nth 5 e))
17475 (cond
17476 ((eq fmt 'add_times) (setq op ":"))
17477 ((eq fmt 'checkbox) (setq op "X"))
17478 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17479 ((eq fmt 'checkbox-percent) (setq op "X%"))
17480 ((eq fmt 'add_numbers) (setq op "+"))
17481 ((eq fmt 'currency) (setq op "$")))
17482 (if (and op printf) (setq op (concat op ";" printf)))
17483 (if (equal title prop) (setq title nil))
17484 (setq s (concat "%" (if width (number-to-string width))
17485 prop
17486 (if title (concat "(" title ")"))
17487 (if op (concat "{" op "}"))))
17488 (setq rtn (concat rtn " " s)))
17489 (org-trim rtn)))
17491 (defun org-columns-compile-format (fmt)
17492 "Turn a column format string into an alist of specifications.
17493 The alist has one entry for each column in the format. The elements of
17494 that list are:
17495 property the property
17496 title the title field for the columns
17497 width the column width in characters, can be nil for automatic
17498 operator the operator if any
17499 format the output format for computed results, derived from operator
17500 printf a printf format for computed values"
17501 (let ((start 0) width prop title op f printf)
17502 (setq org-columns-current-fmt-compiled nil)
17503 (while (string-match
17504 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17505 fmt start)
17506 (setq start (match-end 0)
17507 width (match-string 1 fmt)
17508 prop (match-string 2 fmt)
17509 title (or (match-string 3 fmt) prop)
17510 op (match-string 4 fmt)
17511 f nil
17512 printf nil)
17513 (if width (setq width (string-to-number width)))
17514 (when (and op (string-match ";" op))
17515 (setq printf (substring op (match-end 0))
17516 op (substring op 0 (match-beginning 0))))
17517 (cond
17518 ((equal op "+") (setq f 'add_numbers))
17519 ((equal op "$") (setq f 'currency))
17520 ((equal op ":") (setq f 'add_times))
17521 ((equal op "X") (setq f 'checkbox))
17522 ((equal op "X/") (setq f 'checkbox-n-of-m))
17523 ((equal op "X%") (setq f 'checkbox-percent))
17525 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17526 (setq org-columns-current-fmt-compiled
17527 (nreverse org-columns-current-fmt-compiled))))
17530 ;;; Dynamic block for Column view
17532 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17533 "Get the column view of the current buffer or subtree.
17534 The first optional argument MAXLEVEL sets the level limit. A
17535 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17536 empty rows, an empty row being one where all the column view
17537 specifiers except ITEM are empty. This function returns a list
17538 containing the title row and all other rows. Each row is a list
17539 of fields."
17540 (save-excursion
17541 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17542 (n (length title)) row tbl)
17543 (goto-char (point-min))
17544 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17545 (or (null maxlevel)
17546 (>= maxlevel
17547 (if org-odd-levels-only
17548 (/ (1+ (length (match-string 1))) 2)
17549 (length (match-string 1))))))
17550 (when (get-char-property (match-beginning 0) 'org-columns-key)
17551 (setq row nil)
17552 (loop for i from 0 to (1- n) do
17553 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17554 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17556 row))
17557 (setq row (nreverse row))
17558 (unless (and skip-empty-rows
17559 (eq 1 (length (delete "" (delete-dups row)))))
17560 (push row tbl))))
17561 (append (list title 'hline) (nreverse tbl)))))
17563 (defun org-dblock-write:columnview (params)
17564 "Write the column view table.
17565 PARAMS is a property list of parameters:
17567 :width enforce same column widths with <N> specifiers.
17568 :id the :ID: property of the entry where the columns view
17569 should be built, as a string. When `local', call locally.
17570 When `global' call column view with the cursor at the beginning
17571 of the buffer (usually this means that the whole buffer switches
17572 to column view).
17573 :hlines When t, insert a hline before each item. When a number, insert
17574 a hline before each level <= that number.
17575 :vlines When t, make each column a colgroup to enforce vertical lines.
17576 :maxlevel When set to a number, don't capture headlines below this level.
17577 :skip-empty-rows
17578 When t, skip rows where all specifiers other than ITEM are empty."
17579 (let ((pos (move-marker (make-marker) (point)))
17580 (hlines (plist-get params :hlines))
17581 (vlines (plist-get params :vlines))
17582 (maxlevel (plist-get params :maxlevel))
17583 (skip-empty-rows (plist-get params :skip-empty-rows))
17584 tbl id idpos nfields tmp)
17585 (save-excursion
17586 (save-restriction
17587 (when (setq id (plist-get params :id))
17588 (cond ((not id) nil)
17589 ((eq id 'global) (goto-char (point-min)))
17590 ((eq id 'local) nil)
17591 ((setq idpos (org-find-entry-with-id id))
17592 (goto-char idpos))
17593 (t (error "Cannot find entry with :ID: %s" id))))
17594 (org-columns)
17595 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17596 (setq nfields (length (car tbl)))
17597 (org-columns-quit)))
17598 (goto-char pos)
17599 (move-marker pos nil)
17600 (when tbl
17601 (when (plist-get params :hlines)
17602 (setq tmp nil)
17603 (while tbl
17604 (if (eq (car tbl) 'hline)
17605 (push (pop tbl) tmp)
17606 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17607 (if (and (not (eq (car tmp) 'hline))
17608 (or (eq hlines t)
17609 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17610 (push 'hline tmp)))
17611 (push (pop tbl) tmp)))
17612 (setq tbl (nreverse tmp)))
17613 (when vlines
17614 (setq tbl (mapcar (lambda (x)
17615 (if (eq 'hline x) x (cons "" x)))
17616 tbl))
17617 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17618 (setq pos (point))
17619 (insert (org-listtable-to-string tbl))
17620 (when (plist-get params :width)
17621 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17622 org-columns-current-widths "|")))
17623 (goto-char pos)
17624 (org-table-align))))
17626 (defun org-listtable-to-string (tbl)
17627 "Convert a listtable TBL to a string that contains the Org-mode table.
17628 The table still need to be alligned. The resulting string has no leading
17629 and tailing newline characters."
17630 (mapconcat
17631 (lambda (x)
17632 (cond
17633 ((listp x)
17634 (concat "|" (mapconcat 'identity x "|") "|"))
17635 ((eq x 'hline) "|-|")
17636 (t (error "Garbage in listtable: %s" x))))
17637 tbl "\n"))
17639 (defun org-insert-columns-dblock ()
17640 "Create a dynamic block capturing a column view table."
17641 (interactive)
17642 (let ((defaults '(:name "columnview" :hlines 1))
17643 (id (completing-read
17644 "Capture columns (local, global, entry with :ID: property) [local]: "
17645 (append '(("global") ("local"))
17646 (mapcar 'list (org-property-values "ID"))))))
17647 (if (equal id "") (setq id 'local))
17648 (if (equal id "global") (setq id 'global))
17649 (setq defaults (append defaults (list :id id)))
17650 (org-create-dblock defaults)
17651 (org-update-dblock)))
17653 ;;;; Timestamps
17655 (defvar org-last-changed-timestamp nil)
17656 (defvar org-time-was-given) ; dynamically scoped parameter
17657 (defvar org-end-time-was-given) ; dynamically scoped parameter
17658 (defvar org-ts-what) ; dynamically scoped parameter
17660 (defun org-time-stamp (arg)
17661 "Prompt for a date/time and insert a time stamp.
17662 If the user specifies a time like HH:MM, or if this command is called
17663 with a prefix argument, the time stamp will contain date and time.
17664 Otherwise, only the date will be included. All parts of a date not
17665 specified by the user will be filled in from the current date/time.
17666 So if you press just return without typing anything, the time stamp
17667 will represent the current date/time. If there is already a timestamp
17668 at the cursor, it will be modified."
17669 (interactive "P")
17670 (let* ((ts nil)
17671 (default-time
17672 ;; Default time is either today, or, when entering a range,
17673 ;; the range start.
17674 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17675 (save-excursion
17676 (re-search-backward
17677 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17678 (- (point) 20) t)))
17679 (apply 'encode-time (org-parse-time-string (match-string 1)))
17680 (current-time)))
17681 (default-input (and ts (org-get-compact-tod ts)))
17682 org-time-was-given org-end-time-was-given time)
17683 (cond
17684 ((and (org-at-timestamp-p)
17685 (eq last-command 'org-time-stamp)
17686 (eq this-command 'org-time-stamp))
17687 (insert "--")
17688 (setq time (let ((this-command this-command))
17689 (org-read-date arg 'totime nil nil default-time default-input)))
17690 (org-insert-time-stamp time (or org-time-was-given arg)))
17691 ((org-at-timestamp-p)
17692 (setq time (let ((this-command this-command))
17693 (org-read-date arg 'totime nil nil default-time default-input)))
17694 (when (org-at-timestamp-p) ; just to get the match data
17695 (replace-match "")
17696 (setq org-last-changed-timestamp
17697 (org-insert-time-stamp
17698 time (or org-time-was-given arg)
17699 nil nil nil (list org-end-time-was-given))))
17700 (message "Timestamp updated"))
17702 (setq time (let ((this-command this-command))
17703 (org-read-date arg 'totime nil nil default-time default-input)))
17704 (org-insert-time-stamp time (or org-time-was-given arg)
17705 nil nil nil (list org-end-time-was-given))))))
17707 ;; FIXME: can we use this for something else????
17708 ;; like computing time differences?????
17709 (defun org-get-compact-tod (s)
17710 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17711 (let* ((t1 (match-string 1 s))
17712 (h1 (string-to-number (match-string 2 s)))
17713 (m1 (string-to-number (match-string 3 s)))
17714 (t2 (and (match-end 4) (match-string 5 s)))
17715 (h2 (and t2 (string-to-number (match-string 6 s))))
17716 (m2 (and t2 (string-to-number (match-string 7 s))))
17717 dh dm)
17718 (if (not t2)
17720 (setq dh (- h2 h1) dm (- m2 m1))
17721 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17722 (concat t1 "+" (number-to-string dh)
17723 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17725 (defun org-time-stamp-inactive (&optional arg)
17726 "Insert an inactive time stamp.
17727 An inactive time stamp is enclosed in square brackets instead of angle
17728 brackets. It is inactive in the sense that it does not trigger agenda entries,
17729 does not link to the calendar and cannot be changed with the S-cursor keys.
17730 So these are more for recording a certain time/date."
17731 (interactive "P")
17732 (let (org-time-was-given org-end-time-was-given time)
17733 (setq time (org-read-date arg 'totime))
17734 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17735 nil nil (list org-end-time-was-given))))
17737 (defvar org-date-ovl (org-make-overlay 1 1))
17738 (org-overlay-put org-date-ovl 'face 'org-warning)
17739 (org-detach-overlay org-date-ovl)
17741 (defvar org-ans1) ; dynamically scoped parameter
17742 (defvar org-ans2) ; dynamically scoped parameter
17744 (defvar org-plain-time-of-day-regexp) ; defined below
17746 (defvar org-read-date-overlay nil)
17747 (defvar org-dcst nil) ; dynamically scoped
17749 (defun org-read-date (&optional with-time to-time from-string prompt
17750 default-time default-input)
17751 "Read a date, possibly a time, and make things smooth for the user.
17752 The prompt will suggest to enter an ISO date, but you can also enter anything
17753 which will at least partially be understood by `parse-time-string'.
17754 Unrecognized parts of the date will default to the current day, month, year,
17755 hour and minute. If this command is called to replace a timestamp at point,
17756 of to enter the second timestamp of a range, the default time is taken from the
17757 existing stamp. For example,
17758 3-2-5 --> 2003-02-05
17759 feb 15 --> currentyear-02-15
17760 sep 12 9 --> 2009-09-12
17761 12:45 --> today 12:45
17762 22 sept 0:34 --> currentyear-09-22 0:34
17763 12 --> currentyear-currentmonth-12
17764 Fri --> nearest Friday (today or later)
17765 etc.
17767 Furthermore you can specify a relative date by giving, as the *first* thing
17768 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17769 change in days weeks, months, years.
17770 With a single plus or minus, the date is relative to today. With a double
17771 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17772 +4d --> four days from today
17773 +4 --> same as above
17774 +2w --> two weeks from today
17775 ++5 --> five days from default date
17777 The function understands only English month and weekday abbreviations,
17778 but this can be configured with the variables `parse-time-months' and
17779 `parse-time-weekdays'.
17781 While prompting, a calendar is popped up - you can also select the
17782 date with the mouse (button 1). The calendar shows a period of three
17783 months. To scroll it to other months, use the keys `>' and `<'.
17784 If you don't like the calendar, turn it off with
17785 \(setq org-read-date-popup-calendar nil)
17787 With optional argument TO-TIME, the date will immediately be converted
17788 to an internal time.
17789 With an optional argument WITH-TIME, the prompt will suggest to also
17790 insert a time. Note that when WITH-TIME is not set, you can still
17791 enter a time, and this function will inform the calling routine about
17792 this change. The calling routine may then choose to change the format
17793 used to insert the time stamp into the buffer to include the time.
17794 With optional argument FROM-STRING, read from this string instead from
17795 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17796 the time/date that is used for everything that is not specified by the
17797 user."
17798 (require 'parse-time)
17799 (let* ((org-time-stamp-rounding-minutes
17800 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17801 (org-dcst org-display-custom-times)
17802 (ct (org-current-time))
17803 (def (or default-time ct))
17804 (defdecode (decode-time def))
17805 (dummy (progn
17806 (when (< (nth 2 defdecode) org-extend-today-until)
17807 (setcar (nthcdr 2 defdecode) -1)
17808 (setcar (nthcdr 1 defdecode) 59)
17809 (setq def (apply 'encode-time defdecode)
17810 defdecode (decode-time def)))))
17811 (calendar-move-hook nil)
17812 (view-diary-entries-initially nil)
17813 (view-calendar-holidays-initially nil)
17814 (timestr (format-time-string
17815 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17816 (prompt (concat (if prompt (concat prompt " ") "")
17817 (format "Date+time [%s]: " timestr)))
17818 ans (org-ans0 "") org-ans1 org-ans2 final)
17820 (cond
17821 (from-string (setq ans from-string))
17822 (org-read-date-popup-calendar
17823 (save-excursion
17824 (save-window-excursion
17825 (calendar)
17826 (calendar-forward-day (- (time-to-days def)
17827 (calendar-absolute-from-gregorian
17828 (calendar-current-date))))
17829 (org-eval-in-calendar nil t)
17830 (let* ((old-map (current-local-map))
17831 (map (copy-keymap calendar-mode-map))
17832 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17833 (org-defkey map (kbd "RET") 'org-calendar-select)
17834 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17835 'org-calendar-select-mouse)
17836 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17837 'org-calendar-select-mouse)
17838 (org-defkey minibuffer-local-map [(meta shift left)]
17839 (lambda () (interactive)
17840 (org-eval-in-calendar '(calendar-backward-month 1))))
17841 (org-defkey minibuffer-local-map [(meta shift right)]
17842 (lambda () (interactive)
17843 (org-eval-in-calendar '(calendar-forward-month 1))))
17844 (org-defkey minibuffer-local-map [(meta shift up)]
17845 (lambda () (interactive)
17846 (org-eval-in-calendar '(calendar-backward-year 1))))
17847 (org-defkey minibuffer-local-map [(meta shift down)]
17848 (lambda () (interactive)
17849 (org-eval-in-calendar '(calendar-forward-year 1))))
17850 (org-defkey minibuffer-local-map [(shift up)]
17851 (lambda () (interactive)
17852 (org-eval-in-calendar '(calendar-backward-week 1))))
17853 (org-defkey minibuffer-local-map [(shift down)]
17854 (lambda () (interactive)
17855 (org-eval-in-calendar '(calendar-forward-week 1))))
17856 (org-defkey minibuffer-local-map [(shift left)]
17857 (lambda () (interactive)
17858 (org-eval-in-calendar '(calendar-backward-day 1))))
17859 (org-defkey minibuffer-local-map [(shift right)]
17860 (lambda () (interactive)
17861 (org-eval-in-calendar '(calendar-forward-day 1))))
17862 (org-defkey minibuffer-local-map ">"
17863 (lambda () (interactive)
17864 (org-eval-in-calendar '(scroll-calendar-left 1))))
17865 (org-defkey minibuffer-local-map "<"
17866 (lambda () (interactive)
17867 (org-eval-in-calendar '(scroll-calendar-right 1))))
17868 (unwind-protect
17869 (progn
17870 (use-local-map map)
17871 (add-hook 'post-command-hook 'org-read-date-display)
17872 (setq org-ans0 (read-string prompt default-input nil nil))
17873 ;; org-ans0: from prompt
17874 ;; org-ans1: from mouse click
17875 ;; org-ans2: from calendar motion
17876 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17877 (remove-hook 'post-command-hook 'org-read-date-display)
17878 (use-local-map old-map)
17879 (when org-read-date-overlay
17880 (org-delete-overlay org-read-date-overlay)
17881 (setq org-read-date-overlay nil)))))))
17883 (t ; Naked prompt only
17884 (unwind-protect
17885 (setq ans (read-string prompt default-input nil timestr))
17886 (when org-read-date-overlay
17887 (org-delete-overlay org-read-date-overlay)
17888 (setq org-read-date-overlay nil)))))
17890 (setq final (org-read-date-analyze ans def defdecode))
17892 (if to-time
17893 (apply 'encode-time final)
17894 (if (and (boundp 'org-time-was-given) org-time-was-given)
17895 (format "%04d-%02d-%02d %02d:%02d"
17896 (nth 5 final) (nth 4 final) (nth 3 final)
17897 (nth 2 final) (nth 1 final))
17898 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17899 (defvar def)
17900 (defvar defdecode)
17901 (defvar with-time)
17902 (defun org-read-date-display ()
17903 "Display the currrent date prompt interpretation in the minibuffer."
17904 (when org-read-date-display-live
17905 (when org-read-date-overlay
17906 (org-delete-overlay org-read-date-overlay))
17907 (let ((p (point)))
17908 (end-of-line 1)
17909 (while (not (equal (buffer-substring
17910 (max (point-min) (- (point) 4)) (point))
17911 " "))
17912 (insert " "))
17913 (goto-char p))
17914 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17915 " " (or org-ans1 org-ans2)))
17916 (org-end-time-was-given nil)
17917 (f (org-read-date-analyze ans def defdecode))
17918 (fmts (if org-dcst
17919 org-time-stamp-custom-formats
17920 org-time-stamp-formats))
17921 (fmt (if (or with-time
17922 (and (boundp 'org-time-was-given) org-time-was-given))
17923 (cdr fmts)
17924 (car fmts)))
17925 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17926 (when (and org-end-time-was-given
17927 (string-match org-plain-time-of-day-regexp txt))
17928 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17929 org-end-time-was-given
17930 (substring txt (match-end 0)))))
17931 (setq org-read-date-overlay
17932 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17933 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17935 (defun org-read-date-analyze (ans def defdecode)
17936 "Analyze the combined answer of the date prompt."
17937 ;; FIXME: cleanup and comment
17938 (let (delta deltan deltaw deltadef year month day
17939 hour minute second wday pm h2 m2 tl wday1)
17941 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17942 (setq ans (replace-match "" t t ans)
17943 deltan (car delta)
17944 deltaw (nth 1 delta)
17945 deltadef (nth 2 delta)))
17947 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17948 (when (string-match
17949 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17950 (setq year (if (match-end 2)
17951 (string-to-number (match-string 2 ans))
17952 (string-to-number (format-time-string "%Y")))
17953 month (string-to-number (match-string 3 ans))
17954 day (string-to-number (match-string 4 ans)))
17955 (if (< year 100) (setq year (+ 2000 year)))
17956 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17957 t nil ans)))
17958 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17959 ;; If there is a time with am/pm, and *no* time without it, we convert
17960 ;; so that matching will be successful.
17961 (loop for i from 1 to 2 do ; twice, for end time as well
17962 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17963 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17964 (setq hour (string-to-number (match-string 1 ans))
17965 minute (if (match-end 3)
17966 (string-to-number (match-string 3 ans))
17968 pm (equal ?p
17969 (string-to-char (downcase (match-string 4 ans)))))
17970 (if (and (= hour 12) (not pm))
17971 (setq hour 0)
17972 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17973 (setq ans (replace-match (format "%02d:%02d" hour minute)
17974 t t ans))))
17976 ;; Check if a time range is given as a duration
17977 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17978 (setq hour (string-to-number (match-string 1 ans))
17979 h2 (+ hour (string-to-number (match-string 3 ans)))
17980 minute (string-to-number (match-string 2 ans))
17981 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17982 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17983 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17985 ;; Check if there is a time range
17986 (when (boundp 'org-end-time-was-given)
17987 (setq org-time-was-given nil)
17988 (when (and (string-match org-plain-time-of-day-regexp ans)
17989 (match-end 8))
17990 (setq org-end-time-was-given (match-string 8 ans))
17991 (setq ans (concat (substring ans 0 (match-beginning 7))
17992 (substring ans (match-end 7))))))
17994 (setq tl (parse-time-string ans)
17995 day (or (nth 3 tl) (nth 3 defdecode))
17996 month (or (nth 4 tl)
17997 (if (and org-read-date-prefer-future
17998 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17999 (1+ (nth 4 defdecode))
18000 (nth 4 defdecode)))
18001 year (or (nth 5 tl)
18002 (if (and org-read-date-prefer-future
18003 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
18004 (1+ (nth 5 defdecode))
18005 (nth 5 defdecode)))
18006 hour (or (nth 2 tl) (nth 2 defdecode))
18007 minute (or (nth 1 tl) (nth 1 defdecode))
18008 second (or (nth 0 tl) 0)
18009 wday (nth 6 tl))
18010 (when deltan
18011 (unless deltadef
18012 (let ((now (decode-time (current-time))))
18013 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
18014 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
18015 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
18016 ((equal deltaw "m") (setq month (+ month deltan)))
18017 ((equal deltaw "y") (setq year (+ year deltan)))))
18018 (when (and wday (not (nth 3 tl)))
18019 ;; Weekday was given, but no day, so pick that day in the week
18020 ;; on or after the derived date.
18021 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
18022 (unless (equal wday wday1)
18023 (setq day (+ day (% (- wday wday1 -7) 7)))))
18024 (if (and (boundp 'org-time-was-given)
18025 (nth 2 tl))
18026 (setq org-time-was-given t))
18027 (if (< year 100) (setq year (+ 2000 year)))
18028 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
18029 (list second minute hour day month year)))
18031 (defvar parse-time-weekdays)
18033 (defun org-read-date-get-relative (s today default)
18034 "Check string S for special relative date string.
18035 TODAY and DEFAULT are internal times, for today and for a default.
18036 Return shift list (N what def-flag)
18037 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
18038 N is the number of WHATs to shift.
18039 DEF-FLAG is t when a double ++ or -- indicates shift relative to
18040 the DEFAULT date rather than TODAY."
18041 (when (string-match
18042 (concat
18043 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
18044 "\\([0-9]+\\)?"
18045 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
18046 "\\([ \t]\\|$\\)") s)
18047 (let* ((dir (if (match-end 1)
18048 (string-to-char (substring (match-string 1 s) -1))
18049 ?+))
18050 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
18051 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
18052 (what (if (match-end 3) (match-string 3 s) "d"))
18053 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
18054 (date (if rel default today))
18055 (wday (nth 6 (decode-time date)))
18056 delta)
18057 (if wday1
18058 (progn
18059 (setq delta (mod (+ 7 (- wday1 wday)) 7))
18060 (if (= dir ?-) (setq delta (- delta 7)))
18061 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
18062 (list delta "d" rel))
18063 (list (* n (if (= dir ?-) -1 1)) what rel)))))
18065 (defun org-eval-in-calendar (form &optional keepdate)
18066 "Eval FORM in the calendar window and return to current window.
18067 Also, store the cursor date in variable org-ans2."
18068 (let ((sw (selected-window)))
18069 (select-window (get-buffer-window "*Calendar*"))
18070 (eval form)
18071 (when (and (not keepdate) (calendar-cursor-to-date))
18072 (let* ((date (calendar-cursor-to-date))
18073 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18074 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
18075 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
18076 (select-window sw)))
18078 ; ;; Update the prompt to show new default date
18079 ; (save-excursion
18080 ; (goto-char (point-min))
18081 ; (when (and org-ans2
18082 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
18083 ; (get-text-property (match-end 0) 'field))
18084 ; (let ((inhibit-read-only t))
18085 ; (replace-match (concat "[" org-ans2 "]") t t)
18086 ; (add-text-properties (point-min) (1+ (match-end 0))
18087 ; (text-properties-at (1+ (point-min)))))))))
18089 (defun org-calendar-select ()
18090 "Return to `org-read-date' with the date currently selected.
18091 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18092 (interactive)
18093 (when (calendar-cursor-to-date)
18094 (let* ((date (calendar-cursor-to-date))
18095 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18096 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18097 (if (active-minibuffer-window) (exit-minibuffer))))
18099 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18100 "Insert a date stamp for the date given by the internal TIME.
18101 WITH-HM means, use the stamp format that includes the time of the day.
18102 INACTIVE means use square brackets instead of angular ones, so that the
18103 stamp will not contribute to the agenda.
18104 PRE and POST are optional strings to be inserted before and after the
18105 stamp.
18106 The command returns the inserted time stamp."
18107 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18108 stamp)
18109 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18110 (insert-before-markers (or pre ""))
18111 (insert-before-markers (setq stamp (format-time-string fmt time)))
18112 (when (listp extra)
18113 (setq extra (car extra))
18114 (if (and (stringp extra)
18115 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18116 (setq extra (format "-%02d:%02d"
18117 (string-to-number (match-string 1 extra))
18118 (string-to-number (match-string 2 extra))))
18119 (setq extra nil)))
18120 (when extra
18121 (backward-char 1)
18122 (insert-before-markers extra)
18123 (forward-char 1))
18124 (insert-before-markers (or post ""))
18125 stamp))
18127 (defun org-toggle-time-stamp-overlays ()
18128 "Toggle the use of custom time stamp formats."
18129 (interactive)
18130 (setq org-display-custom-times (not org-display-custom-times))
18131 (unless org-display-custom-times
18132 (let ((p (point-min)) (bmp (buffer-modified-p)))
18133 (while (setq p (next-single-property-change p 'display))
18134 (if (and (get-text-property p 'display)
18135 (eq (get-text-property p 'face) 'org-date))
18136 (remove-text-properties
18137 p (setq p (next-single-property-change p 'display))
18138 '(display t))))
18139 (set-buffer-modified-p bmp)))
18140 (if (featurep 'xemacs)
18141 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18142 (org-restart-font-lock)
18143 (setq org-table-may-need-update t)
18144 (if org-display-custom-times
18145 (message "Time stamps are overlayed with custom format")
18146 (message "Time stamp overlays removed")))
18148 (defun org-display-custom-time (beg end)
18149 "Overlay modified time stamp format over timestamp between BED and END."
18150 (let* ((ts (buffer-substring beg end))
18151 t1 w1 with-hm tf time str w2 (off 0))
18152 (save-match-data
18153 (setq t1 (org-parse-time-string ts t))
18154 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
18155 (setq off (- (match-end 0) (match-beginning 0)))))
18156 (setq end (- end off))
18157 (setq w1 (- end beg)
18158 with-hm (and (nth 1 t1) (nth 2 t1))
18159 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18160 time (org-fix-decoded-time t1)
18161 str (org-add-props
18162 (format-time-string
18163 (substring tf 1 -1) (apply 'encode-time time))
18164 nil 'mouse-face 'highlight)
18165 w2 (length str))
18166 (if (not (= w2 w1))
18167 (add-text-properties (1+ beg) (+ 2 beg)
18168 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18169 (if (featurep 'xemacs)
18170 (progn
18171 (put-text-property beg end 'invisible t)
18172 (put-text-property beg end 'end-glyph (make-glyph str)))
18173 (put-text-property beg end 'display str))))
18175 (defun org-translate-time (string)
18176 "Translate all timestamps in STRING to custom format.
18177 But do this only if the variable `org-display-custom-times' is set."
18178 (when org-display-custom-times
18179 (save-match-data
18180 (let* ((start 0)
18181 (re org-ts-regexp-both)
18182 t1 with-hm inactive tf time str beg end)
18183 (while (setq start (string-match re string start))
18184 (setq beg (match-beginning 0)
18185 end (match-end 0)
18186 t1 (save-match-data
18187 (org-parse-time-string (substring string beg end) t))
18188 with-hm (and (nth 1 t1) (nth 2 t1))
18189 inactive (equal (substring string beg (1+ beg)) "[")
18190 tf (funcall (if with-hm 'cdr 'car)
18191 org-time-stamp-custom-formats)
18192 time (org-fix-decoded-time t1)
18193 str (format-time-string
18194 (concat
18195 (if inactive "[" "<") (substring tf 1 -1)
18196 (if inactive "]" ">"))
18197 (apply 'encode-time time))
18198 string (replace-match str t t string)
18199 start (+ start (length str)))))))
18200 string)
18202 (defun org-fix-decoded-time (time)
18203 "Set 0 instead of nil for the first 6 elements of time.
18204 Don't touch the rest."
18205 (let ((n 0))
18206 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18208 (defun org-days-to-time (timestamp-string)
18209 "Difference between TIMESTAMP-STRING and now in days."
18210 (- (time-to-days (org-time-string-to-time timestamp-string))
18211 (time-to-days (current-time))))
18213 (defun org-deadline-close (timestamp-string &optional ndays)
18214 "Is the time in TIMESTAMP-STRING close to the current date?"
18215 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18216 (and (< (org-days-to-time timestamp-string) ndays)
18217 (not (org-entry-is-done-p))))
18219 (defun org-get-wdays (ts)
18220 "Get the deadline lead time appropriate for timestring TS."
18221 (cond
18222 ((<= org-deadline-warning-days 0)
18223 ;; 0 or negative, enforce this value no matter what
18224 (- org-deadline-warning-days))
18225 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18226 ;; lead time is specified.
18227 (floor (* (string-to-number (match-string 1 ts))
18228 (cdr (assoc (match-string 2 ts)
18229 '(("d" . 1) ("w" . 7)
18230 ("m" . 30.4) ("y" . 365.25)))))))
18231 ;; go for the default.
18232 (t org-deadline-warning-days)))
18234 (defun org-calendar-select-mouse (ev)
18235 "Return to `org-read-date' with the date currently selected.
18236 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18237 (interactive "e")
18238 (mouse-set-point ev)
18239 (when (calendar-cursor-to-date)
18240 (let* ((date (calendar-cursor-to-date))
18241 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18242 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18243 (if (active-minibuffer-window) (exit-minibuffer))))
18245 (defun org-check-deadlines (ndays)
18246 "Check if there are any deadlines due or past due.
18247 A deadline is considered due if it happens within `org-deadline-warning-days'
18248 days from today's date. If the deadline appears in an entry marked DONE,
18249 it is not shown. The prefix arg NDAYS can be used to test that many
18250 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18251 (interactive "P")
18252 (let* ((org-warn-days
18253 (cond
18254 ((equal ndays '(4)) 100000)
18255 (ndays (prefix-numeric-value ndays))
18256 (t (abs org-deadline-warning-days))))
18257 (case-fold-search nil)
18258 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18259 (callback
18260 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18262 (message "%d deadlines past-due or due within %d days"
18263 (org-occur regexp nil callback)
18264 org-warn-days)))
18266 (defun org-check-before-date (date)
18267 "Check if there are deadlines or scheduled entries before DATE."
18268 (interactive (list (org-read-date)))
18269 (let ((case-fold-search nil)
18270 (regexp (concat "\\<\\(" org-deadline-string
18271 "\\|" org-scheduled-string
18272 "\\) *<\\([^>]+\\)>"))
18273 (callback
18274 (lambda () (time-less-p
18275 (org-time-string-to-time (match-string 2))
18276 (org-time-string-to-time date)))))
18277 (message "%d entries before %s"
18278 (org-occur regexp nil callback) date)))
18280 (defun org-evaluate-time-range (&optional to-buffer)
18281 "Evaluate a time range by computing the difference between start and end.
18282 Normally the result is just printed in the echo area, but with prefix arg
18283 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18284 If the time range is actually in a table, the result is inserted into the
18285 next column.
18286 For time difference computation, a year is assumed to be exactly 365
18287 days in order to avoid rounding problems."
18288 (interactive "P")
18290 (org-clock-update-time-maybe)
18291 (save-excursion
18292 (unless (org-at-date-range-p t)
18293 (goto-char (point-at-bol))
18294 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18295 (if (not (org-at-date-range-p t))
18296 (error "Not at a time-stamp range, and none found in current line")))
18297 (let* ((ts1 (match-string 1))
18298 (ts2 (match-string 2))
18299 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18300 (match-end (match-end 0))
18301 (time1 (org-time-string-to-time ts1))
18302 (time2 (org-time-string-to-time ts2))
18303 (t1 (time-to-seconds time1))
18304 (t2 (time-to-seconds time2))
18305 (diff (abs (- t2 t1)))
18306 (negative (< (- t2 t1) 0))
18307 ;; (ys (floor (* 365 24 60 60)))
18308 (ds (* 24 60 60))
18309 (hs (* 60 60))
18310 (fy "%dy %dd %02d:%02d")
18311 (fy1 "%dy %dd")
18312 (fd "%dd %02d:%02d")
18313 (fd1 "%dd")
18314 (fh "%02d:%02d")
18315 y d h m align)
18316 (if havetime
18317 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18319 d (floor (/ diff ds)) diff (mod diff ds)
18320 h (floor (/ diff hs)) diff (mod diff hs)
18321 m (floor (/ diff 60)))
18322 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18324 d (floor (+ (/ diff ds) 0.5))
18325 h 0 m 0))
18326 (if (not to-buffer)
18327 (message "%s" (org-make-tdiff-string y d h m))
18328 (if (org-at-table-p)
18329 (progn
18330 (goto-char match-end)
18331 (setq align t)
18332 (and (looking-at " *|") (goto-char (match-end 0))))
18333 (goto-char match-end))
18334 (if (looking-at
18335 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18336 (replace-match ""))
18337 (if negative (insert " -"))
18338 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18339 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18340 (insert " " (format fh h m))))
18341 (if align (org-table-align))
18342 (message "Time difference inserted")))))
18344 (defun org-make-tdiff-string (y d h m)
18345 (let ((fmt "")
18346 (l nil))
18347 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18348 l (push y l)))
18349 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18350 l (push d l)))
18351 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18352 l (push h l)))
18353 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18354 l (push m l)))
18355 (apply 'format fmt (nreverse l))))
18357 (defun org-time-string-to-time (s)
18358 (apply 'encode-time (org-parse-time-string s)))
18360 (defun org-time-string-to-absolute (s &optional daynr prefer)
18361 "Convert a time stamp to an absolute day number.
18362 If there is a specifyer for a cyclic time stamp, get the closest date to
18363 DAYNR."
18364 (cond
18365 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18366 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18367 daynr
18368 (+ daynr 1000)))
18369 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18370 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18371 (time-to-days (current-time))) (match-string 0 s)
18372 prefer))
18373 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18375 (defun org-time-from-absolute (d)
18376 "Return the time corresponding to date D.
18377 D may be an absolute day number, or a calendar-type list (month day year)."
18378 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18379 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18381 (defun org-calendar-holiday ()
18382 "List of holidays, for Diary display in Org-mode."
18383 (require 'holidays)
18384 (let ((hl (funcall
18385 (if (fboundp 'calendar-check-holidays)
18386 'calendar-check-holidays 'check-calendar-holidays) date)))
18387 (if hl (mapconcat 'identity hl "; "))))
18389 (defun org-diary-sexp-entry (sexp entry date)
18390 "Process a SEXP diary ENTRY for DATE."
18391 (require 'diary-lib)
18392 (let ((result (if calendar-debug-sexp
18393 (let ((stack-trace-on-error t))
18394 (eval (car (read-from-string sexp))))
18395 (condition-case nil
18396 (eval (car (read-from-string sexp)))
18397 (error
18398 (beep)
18399 (message "Bad sexp at line %d in %s: %s"
18400 (org-current-line)
18401 (buffer-file-name) sexp)
18402 (sleep-for 2))))))
18403 (cond ((stringp result) result)
18404 ((and (consp result)
18405 (stringp (cdr result))) (cdr result))
18406 (result entry)
18407 (t nil))))
18409 (defun org-diary-to-ical-string (frombuf)
18410 "Get iCalendar entries from diary entries in buffer FROMBUF.
18411 This uses the icalendar.el library."
18412 (let* ((tmpdir (if (featurep 'xemacs)
18413 (temp-directory)
18414 temporary-file-directory))
18415 (tmpfile (make-temp-name
18416 (expand-file-name "orgics" tmpdir)))
18417 buf rtn b e)
18418 (save-excursion
18419 (set-buffer frombuf)
18420 (icalendar-export-region (point-min) (point-max) tmpfile)
18421 (setq buf (find-buffer-visiting tmpfile))
18422 (set-buffer buf)
18423 (goto-char (point-min))
18424 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18425 (setq b (match-beginning 0)))
18426 (goto-char (point-max))
18427 (if (re-search-backward "^END:VEVENT" nil t)
18428 (setq e (match-end 0)))
18429 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18430 (kill-buffer buf)
18431 (kill-buffer frombuf)
18432 (delete-file tmpfile)
18433 rtn))
18435 (defun org-closest-date (start current change prefer)
18436 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18437 When PREFER is `past' return a date that is either CURRENT or past.
18438 When PREFER is `future', return a date that is either CURRENT or future."
18439 ;; Make the proper lists from the dates
18440 (catch 'exit
18441 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18442 dn dw sday cday n1 n2
18443 d m y y1 y2 date1 date2 nmonths nm ny m2)
18445 (setq start (org-date-to-gregorian start)
18446 current (org-date-to-gregorian
18447 (if org-agenda-repeating-timestamp-show-all
18448 current
18449 (time-to-days (current-time))))
18450 sday (calendar-absolute-from-gregorian start)
18451 cday (calendar-absolute-from-gregorian current))
18453 (if (<= cday sday) (throw 'exit sday))
18455 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18456 (setq dn (string-to-number (match-string 1 change))
18457 dw (cdr (assoc (match-string 2 change) a1)))
18458 (error "Invalid change specifyer: %s" change))
18459 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18460 (cond
18461 ((eq dw 'day)
18462 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18463 n2 (+ n1 dn)))
18464 ((eq dw 'year)
18465 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18466 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18467 (setq date1 (list m d y1)
18468 n1 (calendar-absolute-from-gregorian date1)
18469 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18470 n2 (calendar-absolute-from-gregorian date2)))
18471 ((eq dw 'month)
18472 ;; approx number of month between the tow dates
18473 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18474 ;; How often does dn fit in there?
18475 (setq d (nth 1 start) m (car start) y (nth 2 start)
18476 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18477 m (+ m nm)
18478 ny (floor (/ m 12))
18479 y (+ y ny)
18480 m (- m (* ny 12)))
18481 (while (> m 12) (setq m (- m 12) y (1+ y)))
18482 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18483 (setq m2 (+ m dn) y2 y)
18484 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18485 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18486 (while (< n2 cday)
18487 (setq n1 n2 m m2 y y2)
18488 (setq m2 (+ m dn) y2 y)
18489 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18490 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18492 (if org-agenda-repeating-timestamp-show-all
18493 (cond
18494 ((eq prefer 'past) n1)
18495 ((eq prefer 'future) (if (= cday n1) n1 n2))
18496 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18497 (cond
18498 ((eq prefer 'past) n1)
18499 ((eq prefer 'future) (if (= cday n1) n1 n2))
18500 (t (if (= cday n1) n1 n2)))))))
18502 (defun org-date-to-gregorian (date)
18503 "Turn any specification of DATE into a gregorian date for the calendar."
18504 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18505 ((and (listp date) (= (length date) 3)) date)
18506 ((stringp date)
18507 (setq date (org-parse-time-string date))
18508 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18509 ((listp date)
18510 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18512 (defun org-parse-time-string (s &optional nodefault)
18513 "Parse the standard Org-mode time string.
18514 This should be a lot faster than the normal `parse-time-string'.
18515 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18516 hour and minute fields will be nil if not given."
18517 (if (string-match org-ts-regexp0 s)
18518 (list 0
18519 (if (or (match-beginning 8) (not nodefault))
18520 (string-to-number (or (match-string 8 s) "0")))
18521 (if (or (match-beginning 7) (not nodefault))
18522 (string-to-number (or (match-string 7 s) "0")))
18523 (string-to-number (match-string 4 s))
18524 (string-to-number (match-string 3 s))
18525 (string-to-number (match-string 2 s))
18526 nil nil nil)
18527 (make-list 9 0)))
18529 (defun org-timestamp-up (&optional arg)
18530 "Increase the date item at the cursor by one.
18531 If the cursor is on the year, change the year. If it is on the month or
18532 the day, change that.
18533 With prefix ARG, change by that many units."
18534 (interactive "p")
18535 (org-timestamp-change (prefix-numeric-value arg)))
18537 (defun org-timestamp-down (&optional arg)
18538 "Decrease the date item at the cursor by one.
18539 If the cursor is on the year, change the year. If it is on the month or
18540 the day, change that.
18541 With prefix ARG, change by that many units."
18542 (interactive "p")
18543 (org-timestamp-change (- (prefix-numeric-value arg))))
18545 (defun org-timestamp-up-day (&optional arg)
18546 "Increase the date in the time stamp by one day.
18547 With prefix ARG, change that many days."
18548 (interactive "p")
18549 (if (and (not (org-at-timestamp-p t))
18550 (org-on-heading-p))
18551 (org-todo 'up)
18552 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18554 (defun org-timestamp-down-day (&optional arg)
18555 "Decrease the date in the time stamp by one day.
18556 With prefix ARG, change that many days."
18557 (interactive "p")
18558 (if (and (not (org-at-timestamp-p t))
18559 (org-on-heading-p))
18560 (org-todo 'down)
18561 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18563 (defsubst org-pos-in-match-range (pos n)
18564 (and (match-beginning n)
18565 (<= (match-beginning n) pos)
18566 (>= (match-end n) pos)))
18568 (defun org-at-timestamp-p (&optional inactive-ok)
18569 "Determine if the cursor is in or at a timestamp."
18570 (interactive)
18571 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18572 (pos (point))
18573 (ans (or (looking-at tsr)
18574 (save-excursion
18575 (skip-chars-backward "^[<\n\r\t")
18576 (if (> (point) (point-min)) (backward-char 1))
18577 (and (looking-at tsr)
18578 (> (- (match-end 0) pos) -1))))))
18579 (and ans
18580 (boundp 'org-ts-what)
18581 (setq org-ts-what
18582 (cond
18583 ((= pos (match-beginning 0)) 'bracket)
18584 ((= pos (1- (match-end 0))) 'bracket)
18585 ((org-pos-in-match-range pos 2) 'year)
18586 ((org-pos-in-match-range pos 3) 'month)
18587 ((org-pos-in-match-range pos 7) 'hour)
18588 ((org-pos-in-match-range pos 8) 'minute)
18589 ((or (org-pos-in-match-range pos 4)
18590 (org-pos-in-match-range pos 5)) 'day)
18591 ((and (> pos (or (match-end 8) (match-end 5)))
18592 (< pos (match-end 0)))
18593 (- pos (or (match-end 8) (match-end 5))))
18594 (t 'day))))
18595 ans))
18597 (defun org-toggle-timestamp-type ()
18598 "Toggle the type (<active> or [inactive]) of a time stamp."
18599 (interactive)
18600 (when (org-at-timestamp-p t)
18601 (save-excursion
18602 (goto-char (match-beginning 0))
18603 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18604 (goto-char (1- (match-end 0)))
18605 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18606 (message "Timestamp is now %sactive"
18607 (if (equal (char-before) ?>) "in" ""))))
18609 (defun org-timestamp-change (n &optional what)
18610 "Change the date in the time stamp at point.
18611 The date will be changed by N times WHAT. WHAT can be `day', `month',
18612 `year', `minute', `second'. If WHAT is not given, the cursor position
18613 in the timestamp determines what will be changed."
18614 (let ((pos (point))
18615 with-hm inactive
18616 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18617 org-ts-what
18618 extra rem
18619 ts time time0)
18620 (if (not (org-at-timestamp-p t))
18621 (error "Not at a timestamp"))
18622 (if (and (not what) (eq org-ts-what 'bracket))
18623 (org-toggle-timestamp-type)
18624 (if (and (not what) (not (eq org-ts-what 'day))
18625 org-display-custom-times
18626 (get-text-property (point) 'display)
18627 (not (get-text-property (1- (point)) 'display)))
18628 (setq org-ts-what 'day))
18629 (setq org-ts-what (or what org-ts-what)
18630 inactive (= (char-after (match-beginning 0)) ?\[)
18631 ts (match-string 0))
18632 (replace-match "")
18633 (if (string-match
18634 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18636 (setq extra (match-string 1 ts)))
18637 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18638 (setq with-hm t))
18639 (setq time0 (org-parse-time-string ts))
18640 (when (and (eq org-ts-what 'minute)
18641 (eq current-prefix-arg nil))
18642 (setq n (* dm (org-no-warnings (signum n))))
18643 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18644 (setcar (cdr time0) (+ (nth 1 time0)
18645 (if (> n 0) (- rem) (- dm rem))))))
18646 (setq time
18647 (encode-time (or (car time0) 0)
18648 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18649 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18650 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18651 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18652 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18653 (nthcdr 6 time0)))
18654 (when (integerp org-ts-what)
18655 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18656 (if (eq what 'calendar)
18657 (let ((cal-date (org-get-date-from-calendar)))
18658 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18659 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18660 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18661 (setcar time0 (or (car time0) 0))
18662 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18663 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18664 (setq time (apply 'encode-time time0))))
18665 (setq org-last-changed-timestamp
18666 (org-insert-time-stamp time with-hm inactive nil nil extra))
18667 (org-clock-update-time-maybe)
18668 (goto-char pos)
18669 ;; Try to recenter the calendar window, if any
18670 (if (and org-calendar-follow-timestamp-change
18671 (get-buffer-window "*Calendar*" t)
18672 (memq org-ts-what '(day month year)))
18673 (org-recenter-calendar (time-to-days time))))))
18675 ;; FIXME: does not yet work for lead times
18676 (defun org-modify-ts-extra (s pos n)
18677 "Change the different parts of the lead-time and repeat fields in timestamp."
18678 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18679 ng h m new)
18680 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18681 (cond
18682 ((or (org-pos-in-match-range pos 2)
18683 (org-pos-in-match-range pos 3))
18684 (setq m (string-to-number (match-string 3 s))
18685 h (string-to-number (match-string 2 s)))
18686 (if (org-pos-in-match-range pos 2)
18687 (setq h (+ h n))
18688 (setq m (+ m n)))
18689 (if (< m 0) (setq m (+ m 60) h (1- h)))
18690 (if (> m 59) (setq m (- m 60) h (1+ h)))
18691 (setq h (min 24 (max 0 h)))
18692 (setq ng 1 new (format "-%02d:%02d" h m)))
18693 ((org-pos-in-match-range pos 6)
18694 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18695 ((org-pos-in-match-range pos 5)
18696 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18698 (when ng
18699 (setq s (concat
18700 (substring s 0 (match-beginning ng))
18702 (substring s (match-end ng))))))
18705 (defun org-recenter-calendar (date)
18706 "If the calendar is visible, recenter it to DATE."
18707 (let* ((win (selected-window))
18708 (cwin (get-buffer-window "*Calendar*" t))
18709 (calendar-move-hook nil))
18710 (when cwin
18711 (select-window cwin)
18712 (calendar-goto-date (if (listp date) date
18713 (calendar-gregorian-from-absolute date)))
18714 (select-window win))))
18716 (defun org-goto-calendar (&optional arg)
18717 "Go to the Emacs calendar at the current date.
18718 If there is a time stamp in the current line, go to that date.
18719 A prefix ARG can be used to force the current date."
18720 (interactive "P")
18721 (let ((tsr org-ts-regexp) diff
18722 (calendar-move-hook nil)
18723 (view-calendar-holidays-initially nil)
18724 (view-diary-entries-initially nil))
18725 (if (or (org-at-timestamp-p)
18726 (save-excursion
18727 (beginning-of-line 1)
18728 (looking-at (concat ".*" tsr))))
18729 (let ((d1 (time-to-days (current-time)))
18730 (d2 (time-to-days
18731 (org-time-string-to-time (match-string 1)))))
18732 (setq diff (- d2 d1))))
18733 (calendar)
18734 (calendar-goto-today)
18735 (if (and diff (not arg)) (calendar-forward-day diff))))
18737 (defun org-get-date-from-calendar ()
18738 "Return a list (month day year) of date at point in calendar."
18739 (with-current-buffer "*Calendar*"
18740 (save-match-data
18741 (calendar-cursor-to-date))))
18743 (defun org-date-from-calendar ()
18744 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18745 If there is already a time stamp at the cursor position, update it."
18746 (interactive)
18747 (if (org-at-timestamp-p t)
18748 (org-timestamp-change 0 'calendar)
18749 (let ((cal-date (org-get-date-from-calendar)))
18750 (org-insert-time-stamp
18751 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18753 (defvar appt-time-msg-list)
18755 ;;;###autoload
18756 (defun org-agenda-to-appt (&optional refresh filter)
18757 "Activate appointments found in `org-agenda-files'.
18758 With a \\[universal-argument] prefix, refresh the list of
18759 appointements.
18761 If FILTER is t, interactively prompt the user for a regular
18762 expression, and filter out entries that don't match it.
18764 If FILTER is a string, use this string as a regular expression
18765 for filtering entries out.
18767 FILTER can also be an alist with the car of each cell being
18768 either 'headline or 'category. For example:
18770 '((headline \"IMPORTANT\")
18771 (category \"Work\"))
18773 will only add headlines containing IMPORTANT or headlines
18774 belonging to the \"Work\" category."
18775 (interactive "P")
18776 (require 'calendar)
18777 (if refresh (setq appt-time-msg-list nil))
18778 (if (eq filter t)
18779 (setq filter (read-from-minibuffer "Regexp filter: ")))
18780 (let* ((cnt 0) ; count added events
18781 (org-agenda-new-buffers nil)
18782 (org-deadline-warning-days 0)
18783 (today (org-date-to-gregorian
18784 (time-to-days (current-time))))
18785 (files (org-agenda-files)) entries file)
18786 ;; Get all entries which may contain an appt
18787 (while (setq file (pop files))
18788 (setq entries
18789 (append entries
18790 (org-agenda-get-day-entries
18791 file today :timestamp :scheduled :deadline))))
18792 (setq entries (delq nil entries))
18793 ;; Map thru entries and find if we should filter them out
18794 (mapc
18795 (lambda(x)
18796 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18797 (cat (get-text-property 1 'org-category x))
18798 (tod (get-text-property 1 'time-of-day x))
18799 (ok (or (null filter)
18800 (and (stringp filter) (string-match filter evt))
18801 (and (listp filter)
18802 (or (string-match
18803 (cadr (assoc 'category filter)) cat)
18804 (string-match
18805 (cadr (assoc 'headline filter)) evt))))))
18806 ;; FIXME: Shall we remove text-properties for the appt text?
18807 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18808 (when (and ok tod)
18809 (setq tod (number-to-string tod)
18810 tod (when (string-match
18811 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18812 (concat (match-string 1 tod) ":"
18813 (match-string 2 tod))))
18814 (appt-add tod evt)
18815 (setq cnt (1+ cnt))))) entries)
18816 (org-release-buffers org-agenda-new-buffers)
18817 (if (eq cnt 0)
18818 (message "No event to add")
18819 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18821 ;;; The clock for measuring work time.
18823 (defvar org-mode-line-string "")
18824 (put 'org-mode-line-string 'risky-local-variable t)
18826 (defvar org-mode-line-timer nil)
18827 (defvar org-clock-heading "")
18828 (defvar org-clock-start-time "")
18830 (defun org-update-mode-line ()
18831 (let* ((delta (- (time-to-seconds (current-time))
18832 (time-to-seconds org-clock-start-time)))
18833 (h (floor delta 3600))
18834 (m (floor (- delta (* 3600 h)) 60)))
18835 (setq org-mode-line-string
18836 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18837 'help-echo "Org-mode clock is running"))
18838 (force-mode-line-update)))
18840 (defvar org-clock-marker (make-marker)
18841 "Marker recording the last clock-in.")
18842 (defvar org-clock-mode-line-entry nil
18843 "Information for the modeline about the running clock.")
18845 (defun org-clock-in ()
18846 "Start the clock on the current item.
18847 If necessary, clock-out of the currently active clock."
18848 (interactive)
18849 (org-clock-out t)
18850 (let (ts)
18851 (save-excursion
18852 (org-back-to-heading t)
18853 (when (and org-clock-in-switch-to-state
18854 (not (looking-at (concat outline-regexp "[ \t]*"
18855 org-clock-in-switch-to-state
18856 "\\>"))))
18857 (org-todo org-clock-in-switch-to-state))
18858 (if (and org-clock-heading-function
18859 (functionp org-clock-heading-function))
18860 (setq org-clock-heading (funcall org-clock-heading-function))
18861 (if (looking-at org-complex-heading-regexp)
18862 (setq org-clock-heading (match-string 4))
18863 (setq org-clock-heading "???")))
18864 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18865 (org-clock-find-position)
18867 (insert "\n") (backward-char 1)
18868 (indent-relative)
18869 (insert org-clock-string " ")
18870 (setq org-clock-start-time (current-time))
18871 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18872 (move-marker org-clock-marker (point) (buffer-base-buffer))
18873 (or global-mode-string (setq global-mode-string '("")))
18874 (or (memq 'org-mode-line-string global-mode-string)
18875 (setq global-mode-string
18876 (append global-mode-string '(org-mode-line-string))))
18877 (org-update-mode-line)
18878 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18879 (message "Clock started at %s" ts))))
18881 (defun org-clock-find-position ()
18882 "Find the location where the next clock line should be inserted."
18883 (org-back-to-heading t)
18884 (catch 'exit
18885 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18886 (re (concat "^[ \t]*" org-clock-string))
18887 (cnt 0)
18888 first last)
18889 (goto-char beg)
18890 (when (eobp) (newline) (setq end (max (point) end)))
18891 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18892 ;; we seem to have a CLOCK drawer, so go there.
18893 (beginning-of-line 2)
18894 (throw 'exit t))
18895 ;; Lets count the CLOCK lines
18896 (goto-char beg)
18897 (while (re-search-forward re end t)
18898 (setq first (or first (match-beginning 0))
18899 last (match-beginning 0)
18900 cnt (1+ cnt)))
18901 (when (and (integerp org-clock-into-drawer)
18902 (>= (1+ cnt) org-clock-into-drawer))
18903 ;; Wrap current entries into a new drawer
18904 (goto-char last)
18905 (beginning-of-line 2)
18906 (if (org-at-item-p) (org-end-of-item))
18907 (insert ":END:\n")
18908 (beginning-of-line 0)
18909 (org-indent-line-function)
18910 (goto-char first)
18911 (insert ":CLOCK:\n")
18912 (beginning-of-line 0)
18913 (org-indent-line-function)
18914 (org-flag-drawer t)
18915 (beginning-of-line 2)
18916 (throw 'exit nil))
18918 (goto-char beg)
18919 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18920 (not (equal (match-string 1) org-clock-string)))
18921 ;; Planning info, skip to after it
18922 (beginning-of-line 2)
18923 (or (bolp) (newline)))
18924 (when (eq t org-clock-into-drawer)
18925 (insert ":CLOCK:\n:END:\n")
18926 (beginning-of-line -1)
18927 (org-indent-line-function)
18928 (org-flag-drawer t)
18929 (beginning-of-line 2)
18930 (org-indent-line-function)))))
18932 (defun org-clock-out (&optional fail-quietly)
18933 "Stop the currently running clock.
18934 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18935 (interactive)
18936 (catch 'exit
18937 (if (not (marker-buffer org-clock-marker))
18938 (if fail-quietly (throw 'exit t) (error "No active clock")))
18939 (let (ts te s h m)
18940 (save-excursion
18941 (set-buffer (marker-buffer org-clock-marker))
18942 (goto-char org-clock-marker)
18943 (beginning-of-line 1)
18944 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18945 (equal (match-string 1) org-clock-string))
18946 (setq ts (match-string 2))
18947 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18948 (goto-char (match-end 0))
18949 (delete-region (point) (point-at-eol))
18950 (insert "--")
18951 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18952 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18953 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18954 h (floor (/ s 3600))
18955 s (- s (* 3600 h))
18956 m (floor (/ s 60))
18957 s (- s (* 60 s)))
18958 (insert " => " (format "%2d:%02d" h m))
18959 (move-marker org-clock-marker nil)
18960 (when org-log-note-clock-out
18961 (org-add-log-maybe 'clock-out))
18962 (when org-mode-line-timer
18963 (cancel-timer org-mode-line-timer)
18964 (setq org-mode-line-timer nil))
18965 (setq global-mode-string
18966 (delq 'org-mode-line-string global-mode-string))
18967 (force-mode-line-update)
18968 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18970 (defun org-clock-cancel ()
18971 "Cancel the running clock be removing the start timestamp."
18972 (interactive)
18973 (if (not (marker-buffer org-clock-marker))
18974 (error "No active clock"))
18975 (save-excursion
18976 (set-buffer (marker-buffer org-clock-marker))
18977 (goto-char org-clock-marker)
18978 (delete-region (1- (point-at-bol)) (point-at-eol)))
18979 (setq global-mode-string
18980 (delq 'org-mode-line-string global-mode-string))
18981 (force-mode-line-update)
18982 (message "Clock canceled"))
18984 (defun org-clock-goto (&optional delete-windows)
18985 "Go to the currently clocked-in entry."
18986 (interactive "P")
18987 (if (not (marker-buffer org-clock-marker))
18988 (error "No active clock"))
18989 (switch-to-buffer-other-window
18990 (marker-buffer org-clock-marker))
18991 (if delete-windows (delete-other-windows))
18992 (goto-char org-clock-marker)
18993 (org-show-entry)
18994 (org-back-to-heading)
18995 (recenter))
18997 (defvar org-clock-file-total-minutes nil
18998 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18999 (make-variable-buffer-local 'org-clock-file-total-minutes)
19001 (defun org-clock-sum (&optional tstart tend)
19002 "Sum the times for each subtree.
19003 Puts the resulting times in minutes as a text property on each headline."
19004 (interactive)
19005 (let* ((bmp (buffer-modified-p))
19006 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
19007 org-clock-string
19008 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
19009 (lmax 30)
19010 (ltimes (make-vector lmax 0))
19011 (t1 0)
19012 (level 0)
19013 ts te dt
19014 time)
19015 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
19016 (save-excursion
19017 (goto-char (point-max))
19018 (while (re-search-backward re nil t)
19019 (cond
19020 ((match-end 2)
19021 ;; Two time stamps
19022 (setq ts (match-string 2)
19023 te (match-string 3)
19024 ts (time-to-seconds
19025 (apply 'encode-time (org-parse-time-string ts)))
19026 te (time-to-seconds
19027 (apply 'encode-time (org-parse-time-string te)))
19028 ts (if tstart (max ts tstart) ts)
19029 te (if tend (min te tend) te)
19030 dt (- te ts)
19031 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
19032 ((match-end 4)
19033 ;; A naket time
19034 (setq t1 (+ t1 (string-to-number (match-string 5))
19035 (* 60 (string-to-number (match-string 4))))))
19036 (t ;; A headline
19037 (setq level (- (match-end 1) (match-beginning 1)))
19038 (when (or (> t1 0) (> (aref ltimes level) 0))
19039 (loop for l from 0 to level do
19040 (aset ltimes l (+ (aref ltimes l) t1)))
19041 (setq t1 0 time (aref ltimes level))
19042 (loop for l from level to (1- lmax) do
19043 (aset ltimes l 0))
19044 (goto-char (match-beginning 0))
19045 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
19046 (setq org-clock-file-total-minutes (aref ltimes 0)))
19047 (set-buffer-modified-p bmp)))
19049 (defun org-clock-display (&optional total-only)
19050 "Show subtree times in the entire buffer.
19051 If TOTAL-ONLY is non-nil, only show the total time for the entire file
19052 in the echo area."
19053 (interactive)
19054 (org-remove-clock-overlays)
19055 (let (time h m p)
19056 (org-clock-sum)
19057 (unless total-only
19058 (save-excursion
19059 (goto-char (point-min))
19060 (while (or (and (equal (setq p (point)) (point-min))
19061 (get-text-property p :org-clock-minutes))
19062 (setq p (next-single-property-change
19063 (point) :org-clock-minutes)))
19064 (goto-char p)
19065 (when (setq time (get-text-property p :org-clock-minutes))
19066 (org-put-clock-overlay time (funcall outline-level))))
19067 (setq h (/ org-clock-file-total-minutes 60)
19068 m (- org-clock-file-total-minutes (* 60 h)))
19069 ;; Arrange to remove the overlays upon next change.
19070 (when org-remove-highlights-with-change
19071 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
19072 nil 'local))))
19073 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
19075 (defvar org-clock-overlays nil)
19076 (make-variable-buffer-local 'org-clock-overlays)
19078 (defun org-put-clock-overlay (time &optional level)
19079 "Put an overlays on the current line, displaying TIME.
19080 If LEVEL is given, prefix time with a corresponding number of stars.
19081 This creates a new overlay and stores it in `org-clock-overlays', so that it
19082 will be easy to remove."
19083 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
19084 (l (if level (org-get-legal-level level 0) 0))
19085 (off 0)
19086 ov tx)
19087 (move-to-column c)
19088 (unless (eolp) (skip-chars-backward "^ \t"))
19089 (skip-chars-backward " \t")
19090 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
19091 tx (concat (buffer-substring (1- (point)) (point))
19092 (make-string (+ off (max 0 (- c (current-column)))) ?.)
19093 (org-add-props (format "%s %2d:%02d%s"
19094 (make-string l ?*) h m
19095 (make-string (- 16 l) ?\ ))
19096 '(face secondary-selection))
19097 ""))
19098 (if (not (featurep 'xemacs))
19099 (org-overlay-put ov 'display tx)
19100 (org-overlay-put ov 'invisible t)
19101 (org-overlay-put ov 'end-glyph (make-glyph tx)))
19102 (push ov org-clock-overlays)))
19104 (defun org-remove-clock-overlays (&optional beg end noremove)
19105 "Remove the occur highlights from the buffer.
19106 BEG and END are ignored. If NOREMOVE is nil, remove this function
19107 from the `before-change-functions' in the current buffer."
19108 (interactive)
19109 (unless org-inhibit-highlight-removal
19110 (mapc 'org-delete-overlay org-clock-overlays)
19111 (setq org-clock-overlays nil)
19112 (unless noremove
19113 (remove-hook 'before-change-functions
19114 'org-remove-clock-overlays 'local))))
19116 (defun org-clock-out-if-current ()
19117 "Clock out if the current entry contains the running clock.
19118 This is used to stop the clock after a TODO entry is marked DONE,
19119 and is only done if the variable `org-clock-out-when-done' is not nil."
19120 (when (and org-clock-out-when-done
19121 (member state org-done-keywords)
19122 (equal (marker-buffer org-clock-marker) (current-buffer))
19123 (< (point) org-clock-marker)
19124 (> (save-excursion (outline-next-heading) (point))
19125 org-clock-marker))
19126 ;; Clock out, but don't accept a logging message for this.
19127 (let ((org-log-note-clock-out nil))
19128 (org-clock-out))))
19130 (add-hook 'org-after-todo-state-change-hook
19131 'org-clock-out-if-current)
19133 (defun org-check-running-clock ()
19134 "Check if the current buffer contains the running clock.
19135 If yes, offer to stop it and to save the buffer with the changes."
19136 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19137 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19138 (buffer-name))))
19139 (org-clock-out)
19140 (when (y-or-n-p "Save changed buffer?")
19141 (save-buffer))))
19143 (defun org-clock-report (&optional arg)
19144 "Create a table containing a report about clocked time.
19145 If the cursor is inside an existing clocktable block, then the table
19146 will be updated. If not, a new clocktable will be inserted.
19147 When called with a prefix argument, move to the first clock table in the
19148 buffer and update it."
19149 (interactive "P")
19150 (org-remove-clock-overlays)
19151 (when arg
19152 (org-find-dblock "clocktable")
19153 (org-show-entry))
19154 (if (org-in-clocktable-p)
19155 (goto-char (org-in-clocktable-p))
19156 (org-create-dblock (list :name "clocktable"
19157 :maxlevel 2 :scope 'file)))
19158 (org-update-dblock))
19160 (defun org-in-clocktable-p ()
19161 "Check if the cursor is in a clocktable."
19162 (let ((pos (point)) start)
19163 (save-excursion
19164 (end-of-line 1)
19165 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19166 (setq start (match-beginning 0))
19167 (re-search-forward "^#\\+END:.*" nil t)
19168 (>= (match-end 0) pos)
19169 start))))
19171 (defun org-clock-update-time-maybe ()
19172 "If this is a CLOCK line, update it and return t.
19173 Otherwise, return nil."
19174 (interactive)
19175 (save-excursion
19176 (beginning-of-line 1)
19177 (skip-chars-forward " \t")
19178 (when (looking-at org-clock-string)
19179 (let ((re (concat "[ \t]*" org-clock-string
19180 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19181 "\\([ \t]*=>.*\\)?"))
19182 ts te h m s)
19183 (if (not (looking-at re))
19185 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19186 (end-of-line 1)
19187 (setq ts (match-string 1)
19188 te (match-string 2))
19189 (setq s (- (time-to-seconds
19190 (apply 'encode-time (org-parse-time-string te)))
19191 (time-to-seconds
19192 (apply 'encode-time (org-parse-time-string ts))))
19193 h (floor (/ s 3600))
19194 s (- s (* 3600 h))
19195 m (floor (/ s 60))
19196 s (- s (* 60 s)))
19197 (insert " => " (format "%2d:%02d" h m))
19198 t)))))
19200 (defun org-clock-special-range (key &optional time as-strings)
19201 "Return two times bordering a special time range.
19202 Key is a symbol specifying the range and can be one of `today', `yesterday',
19203 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19204 A week starts Monday 0:00 and ends Sunday 24:00.
19205 The range is determined relative to TIME. TIME defaults to the current time.
19206 The return value is a cons cell with two internal times like the ones
19207 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19208 the returned times will be formatted strings."
19209 (let* ((tm (decode-time (or time (current-time))))
19210 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19211 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19212 (dow (nth 6 tm))
19213 s1 m1 h1 d1 month1 y1 diff ts te fm)
19214 (cond
19215 ((eq key 'today)
19216 (setq h 0 m 0 h1 24 m1 0))
19217 ((eq key 'yesterday)
19218 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19219 ((eq key 'thisweek)
19220 (setq diff (if (= dow 0) 6 (1- dow))
19221 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19222 ((eq key 'lastweek)
19223 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19224 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19225 ((eq key 'thismonth)
19226 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19227 ((eq key 'lastmonth)
19228 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19229 ((eq key 'thisyear)
19230 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19231 ((eq key 'lastyear)
19232 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19233 (t (error "No such time block %s" key)))
19234 (setq ts (encode-time s m h d month y)
19235 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19236 (or d1 d) (or month1 month) (or y1 y)))
19237 (setq fm (cdr org-time-stamp-formats))
19238 (if as-strings
19239 (cons (format-time-string fm ts) (format-time-string fm te))
19240 (cons ts te))))
19242 (defun org-dblock-write:clocktable (params)
19243 "Write the standard clocktable."
19244 (catch 'exit
19245 (let* ((hlchars '((1 . "*") (2 . "/")))
19246 (ins (make-marker))
19247 (total-time nil)
19248 (scope (plist-get params :scope))
19249 (tostring (plist-get params :tostring))
19250 (multifile (plist-get params :multifile))
19251 (header (plist-get params :header))
19252 (maxlevel (or (plist-get params :maxlevel) 3))
19253 (step (plist-get params :step))
19254 (emph (plist-get params :emphasize))
19255 (ts (plist-get params :tstart))
19256 (te (plist-get params :tend))
19257 (block (plist-get params :block))
19258 ipos time h m p level hlc hdl
19259 cc beg end pos tbl)
19260 (when step
19261 (org-clocktable-steps params)
19262 (throw 'exit nil))
19263 (when block
19264 (setq cc (org-clock-special-range block nil t)
19265 ts (car cc) te (cdr cc)))
19266 (if ts (setq ts (time-to-seconds
19267 (apply 'encode-time (org-parse-time-string ts)))))
19268 (if te (setq te (time-to-seconds
19269 (apply 'encode-time (org-parse-time-string te)))))
19270 (move-marker ins (point))
19271 (setq ipos (point))
19273 ;; Get the right scope
19274 (setq pos (point))
19275 (save-restriction
19276 (cond
19277 ((not scope))
19278 ((eq scope 'file) (widen))
19279 ((eq scope 'subtree) (org-narrow-to-subtree))
19280 ((eq scope 'tree)
19281 (while (org-up-heading-safe))
19282 (org-narrow-to-subtree))
19283 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19284 (symbol-name scope)))
19285 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19286 (catch 'exit
19287 (while (org-up-heading-safe)
19288 (looking-at outline-regexp)
19289 (if (<= (org-reduced-level (funcall outline-level)) level)
19290 (throw 'exit nil))))
19291 (org-narrow-to-subtree))
19292 ((or (listp scope) (eq scope 'agenda))
19293 (let* ((files (if (listp scope) scope (org-agenda-files)))
19294 (scope 'agenda)
19295 (p1 (copy-sequence params))
19296 file)
19297 (plist-put p1 :tostring t)
19298 (plist-put p1 :multifile t)
19299 (plist-put p1 :scope 'file)
19300 (org-prepare-agenda-buffers files)
19301 (while (setq file (pop files))
19302 (with-current-buffer (find-buffer-visiting file)
19303 (push (org-clocktable-add-file
19304 file (org-dblock-write:clocktable p1)) tbl)
19305 (setq total-time (+ (or total-time 0)
19306 org-clock-file-total-minutes)))))))
19307 (goto-char pos)
19309 (unless (eq scope 'agenda)
19310 (org-clock-sum ts te)
19311 (goto-char (point-min))
19312 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19313 (goto-char p)
19314 (when (setq time (get-text-property p :org-clock-minutes))
19315 (save-excursion
19316 (beginning-of-line 1)
19317 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19318 (setq level (org-reduced-level
19319 (- (match-end 1) (match-beginning 1))))
19320 (<= level maxlevel))
19321 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19322 hdl (match-string 2)
19323 h (/ time 60)
19324 m (- time (* 60 h)))
19325 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19326 (push (concat
19327 "| " (int-to-string level) "|" hlc hdl hlc " |"
19328 (make-string (1- level) ?|)
19329 hlc (format "%d:%02d" h m) hlc
19330 " |") tbl))))))
19331 (setq tbl (nreverse tbl))
19332 (if tostring
19333 (if tbl (mapconcat 'identity tbl "\n") nil)
19334 (goto-char ins)
19335 (insert-before-markers
19336 (or header
19337 (concat
19338 "Clock summary at ["
19339 (substring
19340 (format-time-string (cdr org-time-stamp-formats))
19341 1 -1)
19342 "]."
19343 (if block
19344 (format " Considered range is /%s/." block)
19346 "\n\n"))
19347 (if (eq scope 'agenda) "|File" "")
19348 "|L|Headline|Time|\n")
19349 (setq total-time (or total-time org-clock-file-total-minutes)
19350 h (/ total-time 60)
19351 m (- total-time (* 60 h)))
19352 (insert-before-markers
19353 "|-\n|"
19354 (if (eq scope 'agenda) "|" "")
19356 "*Total time*| "
19357 (format "*%d:%02d*" h m)
19358 "|\n|-\n")
19359 (setq tbl (delq nil tbl))
19360 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19361 (equal (substring (car tbl) 0 2) "|-"))
19362 (pop tbl))
19363 (insert-before-markers (mapconcat
19364 'identity (delq nil tbl)
19365 (if (eq scope 'agenda) "\n|-\n" "\n")))
19366 (backward-delete-char 1)
19367 (goto-char ipos)
19368 (skip-chars-forward "^|")
19369 (org-table-align))))))
19371 (defun org-clocktable-steps (params)
19372 (let* ((p1 (copy-sequence params))
19373 (ts (plist-get p1 :tstart))
19374 (te (plist-get p1 :tend))
19375 (step0 (plist-get p1 :step))
19376 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19377 (block (plist-get p1 :block))
19379 (when block
19380 (setq cc (org-clock-special-range block nil t)
19381 ts (car cc) te (cdr cc)))
19382 (if ts (setq ts (time-to-seconds
19383 (apply 'encode-time (org-parse-time-string ts)))))
19384 (if te (setq te (time-to-seconds
19385 (apply 'encode-time (org-parse-time-string te)))))
19386 (plist-put p1 :header "")
19387 (plist-put p1 :step nil)
19388 (plist-put p1 :block nil)
19389 (while (< ts te)
19390 (or (bolp) (insert "\n"))
19391 (plist-put p1 :tstart (format-time-string
19392 (car org-time-stamp-formats)
19393 (seconds-to-time ts)))
19394 (plist-put p1 :tend (format-time-string
19395 (car org-time-stamp-formats)
19396 (seconds-to-time (setq ts (+ ts step)))))
19397 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19398 (plist-get p1 :tstart) "\n")
19399 (org-dblock-write:clocktable p1)
19400 (re-search-forward "#\\+END:")
19401 (end-of-line 0))))
19404 (defun org-clocktable-add-file (file table)
19405 (if table
19406 (let ((lines (org-split-string table "\n"))
19407 (ff (file-name-nondirectory file)))
19408 (mapconcat 'identity
19409 (mapcar (lambda (x)
19410 (if (string-match org-table-dataline-regexp x)
19411 (concat "|" ff x)
19413 lines)
19414 "\n"))))
19416 ;; FIXME: I don't think anybody uses this, ask David
19417 (defun org-collect-clock-time-entries ()
19418 "Return an internal list with clocking information.
19419 This list has one entry for each CLOCK interval.
19420 FIXME: describe the elements."
19421 (interactive)
19422 (let ((re (concat "^[ \t]*" org-clock-string
19423 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19424 rtn beg end next cont level title total closedp leafp
19425 clockpos titlepos h m donep)
19426 (save-excursion
19427 (org-clock-sum)
19428 (goto-char (point-min))
19429 (while (re-search-forward re nil t)
19430 (setq clockpos (match-beginning 0)
19431 beg (match-string 1) end (match-string 2)
19432 cont (match-end 0))
19433 (setq beg (apply 'encode-time (org-parse-time-string beg))
19434 end (apply 'encode-time (org-parse-time-string end)))
19435 (org-back-to-heading t)
19436 (setq donep (org-entry-is-done-p))
19437 (setq titlepos (point)
19438 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19439 h (/ total 60) m (- total (* 60 h))
19440 total (cons h m))
19441 (looking-at "\\(\\*+\\) +\\(.*\\)")
19442 (setq level (- (match-end 1) (match-beginning 1))
19443 title (org-match-string-no-properties 2))
19444 (save-excursion (outline-next-heading) (setq next (point)))
19445 (setq closedp (re-search-forward org-closed-time-regexp next t))
19446 (goto-char next)
19447 (setq leafp (and (looking-at "^\\*+ ")
19448 (<= (- (match-end 0) (point)) level)))
19449 (push (list beg end clockpos closedp donep
19450 total title titlepos level leafp)
19451 rtn)
19452 (goto-char cont)))
19453 (nreverse rtn)))
19455 ;;;; Agenda, and Diary Integration
19457 ;;; Define the Org-agenda-mode
19459 (defvar org-agenda-mode-map (make-sparse-keymap)
19460 "Keymap for `org-agenda-mode'.")
19462 (defvar org-agenda-menu) ; defined later in this file.
19463 (defvar org-agenda-follow-mode nil)
19464 (defvar org-agenda-show-log nil)
19465 (defvar org-agenda-redo-command nil)
19466 (defvar org-agenda-query-string nil)
19467 (defvar org-agenda-mode-hook nil)
19468 (defvar org-agenda-type nil)
19469 (defvar org-agenda-force-single-file nil)
19471 (defun org-agenda-mode ()
19472 "Mode for time-sorted view on action items in Org-mode files.
19474 The following commands are available:
19476 \\{org-agenda-mode-map}"
19477 (interactive)
19478 (kill-all-local-variables)
19479 (setq org-agenda-undo-list nil
19480 org-agenda-pending-undo-list nil)
19481 (setq major-mode 'org-agenda-mode)
19482 ;; Keep global-font-lock-mode from turning on font-lock-mode
19483 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19484 (setq mode-name "Org-Agenda")
19485 (use-local-map org-agenda-mode-map)
19486 (easy-menu-add org-agenda-menu)
19487 (if org-startup-truncated (setq truncate-lines t))
19488 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19489 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19490 ;; Make sure properties are removed when copying text
19491 (when (boundp 'buffer-substring-filters)
19492 (org-set-local 'buffer-substring-filters
19493 (cons (lambda (x)
19494 (set-text-properties 0 (length x) nil x) x)
19495 buffer-substring-filters)))
19496 (unless org-agenda-keep-modes
19497 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19498 org-agenda-show-log nil))
19499 (easy-menu-change
19500 '("Agenda") "Agenda Files"
19501 (append
19502 (list
19503 (vector
19504 (if (get 'org-agenda-files 'org-restrict)
19505 "Restricted to single file"
19506 "Edit File List")
19507 '(org-edit-agenda-file-list)
19508 (not (get 'org-agenda-files 'org-restrict)))
19509 "--")
19510 (mapcar 'org-file-menu-entry (org-agenda-files))))
19511 (org-agenda-set-mode-name)
19512 (apply
19513 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19514 (list 'org-agenda-mode-hook)))
19516 (substitute-key-definition 'undo 'org-agenda-undo
19517 org-agenda-mode-map global-map)
19518 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19519 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19520 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19521 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19522 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19523 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19524 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19525 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19526 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19527 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19528 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19529 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19530 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19531 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19532 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19533 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19534 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19535 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19536 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19537 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19538 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19539 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19540 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19541 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19542 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19543 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19544 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19545 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19546 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19548 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19549 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19550 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19551 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19552 (while l (org-defkey org-agenda-mode-map
19553 (int-to-string (pop l)) 'digit-argument)))
19555 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19556 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19557 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19558 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19559 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19560 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19561 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19562 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19563 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19564 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19565 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19566 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19567 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19568 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19569 (org-defkey org-agenda-mode-map "n" 'next-line)
19570 (org-defkey org-agenda-mode-map "p" 'previous-line)
19571 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19572 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19573 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19574 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19575 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19576 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19577 (eval-after-load "calendar"
19578 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19579 'org-calendar-goto-agenda))
19580 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19581 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19582 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19583 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19584 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19585 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19586 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19587 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19588 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19589 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19590 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19591 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19592 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19593 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19594 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19595 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19596 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19597 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19598 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19599 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19600 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19601 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19603 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19604 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19605 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19606 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19608 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19609 "Local keymap for agenda entries from Org-mode.")
19611 (org-defkey org-agenda-keymap
19612 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19613 (org-defkey org-agenda-keymap
19614 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19615 (when org-agenda-mouse-1-follows-link
19616 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19617 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19618 '("Agenda"
19619 ("Agenda Files")
19620 "--"
19621 ["Show" org-agenda-show t]
19622 ["Go To (other window)" org-agenda-goto t]
19623 ["Go To (this window)" org-agenda-switch-to t]
19624 ["Follow Mode" org-agenda-follow-mode
19625 :style toggle :selected org-agenda-follow-mode :active t]
19626 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19627 "--"
19628 ["Cycle TODO" org-agenda-todo t]
19629 ["Archive subtree" org-agenda-archive t]
19630 ["Delete subtree" org-agenda-kill t]
19631 "--"
19632 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19633 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19634 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19635 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19636 "--"
19637 ("Tags and Properties"
19638 ["Show all Tags" org-agenda-show-tags t]
19639 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19640 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19641 "--"
19642 ["Column View" org-columns t])
19643 ("Date/Schedule"
19644 ["Schedule" org-agenda-schedule t]
19645 ["Set Deadline" org-agenda-deadline t]
19646 "--"
19647 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19648 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19649 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19650 ("Clock"
19651 ["Clock in" org-agenda-clock-in t]
19652 ["Clock out" org-agenda-clock-out t]
19653 ["Clock cancel" org-agenda-clock-cancel t]
19654 ["Goto running clock" org-clock-goto t])
19655 ("Priority"
19656 ["Set Priority" org-agenda-priority t]
19657 ["Increase Priority" org-agenda-priority-up t]
19658 ["Decrease Priority" org-agenda-priority-down t]
19659 ["Show Priority" org-agenda-show-priority t])
19660 ("Calendar/Diary"
19661 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19662 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19663 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19664 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19665 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19666 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19667 "--"
19668 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19669 "--"
19670 ("View"
19671 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19672 :style radio :selected (equal org-agenda-ndays 1)]
19673 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19674 :style radio :selected (equal org-agenda-ndays 7)]
19675 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19676 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19677 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19678 :style radio :selected (member org-agenda-ndays '(365 366))]
19679 "--"
19680 ["Show Logbook entries" org-agenda-log-mode
19681 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19682 ["Include Diary" org-agenda-toggle-diary
19683 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19684 ["Use Time Grid" org-agenda-toggle-time-grid
19685 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19686 ["Write view to file" org-write-agenda t]
19687 ["Rebuild buffer" org-agenda-redo t]
19688 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19689 "--"
19690 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19691 "--"
19692 ["Quit" org-agenda-quit t]
19693 ["Exit and Release Buffers" org-agenda-exit t]
19696 ;;; Agenda undo
19698 (defvar org-agenda-allow-remote-undo t
19699 "Non-nil means, allow remote undo from the agenda buffer.")
19700 (defvar org-agenda-undo-list nil
19701 "List of undoable operations in the agenda since last refresh.")
19702 (defvar org-agenda-undo-has-started-in nil
19703 "Buffers that have already seen `undo-start' in the current undo sequence.")
19704 (defvar org-agenda-pending-undo-list nil
19705 "In a series of undo commands, this is the list of remaning undo items.")
19707 (defmacro org-if-unprotected (&rest body)
19708 "Execute BODY if there is no `org-protected' text property at point."
19709 (declare (debug t))
19710 `(unless (get-text-property (point) 'org-protected)
19711 ,@body))
19713 (defmacro org-with-remote-undo (_buffer &rest _body)
19714 "Execute BODY while recording undo information in two buffers."
19715 (declare (indent 1) (debug t))
19716 `(let ((_cline (org-current-line))
19717 (_cmd this-command)
19718 (_buf1 (current-buffer))
19719 (_buf2 ,_buffer)
19720 (_undo1 buffer-undo-list)
19721 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19722 _c1 _c2)
19723 ,@_body
19724 (when org-agenda-allow-remote-undo
19725 (setq _c1 (org-verify-change-for-undo
19726 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19727 _c2 (org-verify-change-for-undo
19728 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19729 (when (or _c1 _c2)
19730 ;; make sure there are undo boundaries
19731 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19732 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19733 ;; remember which buffer to undo
19734 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19735 org-agenda-undo-list)))))
19737 (defun org-agenda-undo ()
19738 "Undo a remote editing step in the agenda.
19739 This undoes changes both in the agenda buffer and in the remote buffer
19740 that have been changed along."
19741 (interactive)
19742 (or org-agenda-allow-remote-undo
19743 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19744 (if (not (eq this-command last-command))
19745 (setq org-agenda-undo-has-started-in nil
19746 org-agenda-pending-undo-list org-agenda-undo-list))
19747 (if (not org-agenda-pending-undo-list)
19748 (error "No further undo information"))
19749 (let* ((entry (pop org-agenda-pending-undo-list))
19750 buf line cmd rembuf)
19751 (setq cmd (pop entry) line (pop entry))
19752 (setq rembuf (nth 2 entry))
19753 (org-with-remote-undo rembuf
19754 (while (bufferp (setq buf (pop entry)))
19755 (if (pop entry)
19756 (with-current-buffer buf
19757 (let ((last-undo-buffer buf)
19758 (inhibit-read-only t))
19759 (unless (memq buf org-agenda-undo-has-started-in)
19760 (push buf org-agenda-undo-has-started-in)
19761 (make-local-variable 'pending-undo-list)
19762 (undo-start))
19763 (while (and pending-undo-list
19764 (listp pending-undo-list)
19765 (not (car pending-undo-list)))
19766 (pop pending-undo-list))
19767 (undo-more 1))))))
19768 (goto-line line)
19769 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19771 (defun org-verify-change-for-undo (l1 l2)
19772 "Verify that a real change occurred between the undo lists L1 and L2."
19773 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19774 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19775 (not (eq l1 l2)))
19777 ;;; Agenda dispatch
19779 (defvar org-agenda-restrict nil)
19780 (defvar org-agenda-restrict-begin (make-marker))
19781 (defvar org-agenda-restrict-end (make-marker))
19782 (defvar org-agenda-last-dispatch-buffer nil)
19783 (defvar org-agenda-overriding-restriction nil)
19785 ;;;###autoload
19786 (defun org-agenda (arg &optional keys restriction)
19787 "Dispatch agenda commands to collect entries to the agenda buffer.
19788 Prompts for a command to execute. Any prefix arg will be passed
19789 on to the selected command. The default selections are:
19791 a Call `org-agenda-list' to display the agenda for current day or week.
19792 t Call `org-todo-list' to display the global todo list.
19793 T Call `org-todo-list' to display the global todo list, select only
19794 entries with a specific TODO keyword (the user gets a prompt).
19795 m Call `org-tags-view' to display headlines with tags matching
19796 a condition (the user is prompted for the condition).
19797 M Like `m', but select only TODO entries, no ordinary headlines.
19798 L Create a timeline for the current buffer.
19799 e Export views to associated files.
19801 More commands can be added by configuring the variable
19802 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19803 searches can be pre-defined in this way.
19805 If the current buffer is in Org-mode and visiting a file, you can also
19806 first press `<' once to indicate that the agenda should be temporarily
19807 \(until the next use of \\[org-agenda]) restricted to the current file.
19808 Pressing `<' twice means to restrict to the current subtree or region
19809 \(if active)."
19810 (interactive "P")
19811 (catch 'exit
19812 (let* ((prefix-descriptions nil)
19813 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19814 (org-agenda-custom-commands
19815 ;; normalize different versions
19816 (delq nil
19817 (mapcar
19818 (lambda (x)
19819 (cond ((stringp (cdr x))
19820 (push x prefix-descriptions)
19821 nil)
19822 ((stringp (nth 1 x)) x)
19823 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19824 (t (cons (car x) (cons "" (cdr x))))))
19825 org-agenda-custom-commands)))
19826 (buf (current-buffer))
19827 (bfn (buffer-file-name (buffer-base-buffer)))
19828 entry key type match lprops ans)
19829 ;; Turn off restriction unless there is an overriding one
19830 (unless org-agenda-overriding-restriction
19831 (put 'org-agenda-files 'org-restrict nil)
19832 (setq org-agenda-restrict nil)
19833 (move-marker org-agenda-restrict-begin nil)
19834 (move-marker org-agenda-restrict-end nil))
19835 ;; Delete old local properties
19836 (put 'org-agenda-redo-command 'org-lprops nil)
19837 ;; Remember where this call originated
19838 (setq org-agenda-last-dispatch-buffer (current-buffer))
19839 (unless keys
19840 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19841 keys (car ans)
19842 restriction (cdr ans)))
19843 ;; Estabish the restriction, if any
19844 (when (and (not org-agenda-overriding-restriction) restriction)
19845 (put 'org-agenda-files 'org-restrict (list bfn))
19846 (cond
19847 ((eq restriction 'region)
19848 (setq org-agenda-restrict t)
19849 (move-marker org-agenda-restrict-begin (region-beginning))
19850 (move-marker org-agenda-restrict-end (region-end)))
19851 ((eq restriction 'subtree)
19852 (save-excursion
19853 (setq org-agenda-restrict t)
19854 (org-back-to-heading t)
19855 (move-marker org-agenda-restrict-begin (point))
19856 (move-marker org-agenda-restrict-end
19857 (progn (org-end-of-subtree t)))))))
19859 (require 'calendar) ; FIXME: can we avoid this for some commands?
19860 ;; For example the todo list should not need it (but does...)
19861 (cond
19862 ((setq entry (assoc keys org-agenda-custom-commands))
19863 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19864 (progn
19865 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19866 (put 'org-agenda-redo-command 'org-lprops lprops)
19867 (cond
19868 ((eq type 'agenda)
19869 (org-let lprops '(org-agenda-list current-prefix-arg)))
19870 ((eq type 'alltodo)
19871 (org-let lprops '(org-todo-list current-prefix-arg)))
19872 ((eq type 'search)
19873 (org-let lprops '(org-search-view current-prefix-arg match)))
19874 ((eq type 'stuck)
19875 (org-let lprops '(org-agenda-list-stuck-projects
19876 current-prefix-arg)))
19877 ((eq type 'tags)
19878 (org-let lprops '(org-tags-view current-prefix-arg match)))
19879 ((eq type 'tags-todo)
19880 (org-let lprops '(org-tags-view '(4) match)))
19881 ((eq type 'todo)
19882 (org-let lprops '(org-todo-list match)))
19883 ((eq type 'tags-tree)
19884 (org-check-for-org-mode)
19885 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19886 ((eq type 'todo-tree)
19887 (org-check-for-org-mode)
19888 (org-let lprops
19889 '(org-occur (concat "^" outline-regexp "[ \t]*"
19890 (regexp-quote match) "\\>"))))
19891 ((eq type 'occur-tree)
19892 (org-check-for-org-mode)
19893 (org-let lprops '(org-occur match)))
19894 ((functionp type)
19895 (org-let lprops '(funcall type match)))
19896 ((fboundp type)
19897 (org-let lprops '(funcall type match)))
19898 (t (error "Invalid custom agenda command type %s" type))))
19899 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19900 ((equal keys "C")
19901 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19902 (customize-variable 'org-agenda-custom-commands))
19903 ((equal keys "a") (call-interactively 'org-agenda-list))
19904 ((equal keys "s") (call-interactively 'org-search-view))
19905 ((equal keys "t") (call-interactively 'org-todo-list))
19906 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19907 ((equal keys "m") (call-interactively 'org-tags-view))
19908 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19909 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19910 ((equal keys "L")
19911 (unless (org-mode-p)
19912 (error "This is not an Org-mode file"))
19913 (unless restriction
19914 (put 'org-agenda-files 'org-restrict (list bfn))
19915 (org-call-with-arg 'org-timeline arg)))
19916 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19917 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19918 ((equal keys "!") (customize-variable 'org-stuck-projects))
19919 (t (error "Invalid agenda key"))))))
19921 (defun org-agenda-normalize-custom-commands (cmds)
19922 (delq nil
19923 (mapcar
19924 (lambda (x)
19925 (cond ((stringp (cdr x)) nil)
19926 ((stringp (nth 1 x)) x)
19927 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19928 (t (cons (car x) (cons "" (cdr x))))))
19929 cmds)))
19931 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19932 "The user interface for selecting an agenda command."
19933 (catch 'exit
19934 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19935 (restrict-ok (and bfn (org-mode-p)))
19936 (region-p (org-region-active-p))
19937 (custom org-agenda-custom-commands)
19938 (selstring "")
19939 restriction second-time
19940 c entry key type match prefixes rmheader header-end custom1 desc)
19941 (save-window-excursion
19942 (delete-other-windows)
19943 (org-switch-to-buffer-other-window " *Agenda Commands*")
19944 (erase-buffer)
19945 (insert (eval-when-compile
19946 (let ((header
19948 Press key for an agenda command: < Buffer,subtree/region restriction
19949 -------------------------------- > Remove restriction
19950 a Agenda for current week or day e Export agenda views
19951 t List of all TODO entries T Entries with special TODO kwd
19952 m Match a TAGS query M Like m, but only TODO entries
19953 L Timeline for current buffer # List stuck projects (!=configure)
19954 s Search for keywords C Configure custom agenda commands
19955 / Multi-occur
19957 (start 0))
19958 (while (string-match
19959 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19960 header start)
19961 (setq start (match-end 0))
19962 (add-text-properties (match-beginning 2) (match-end 2)
19963 '(face bold) header))
19964 header)))
19965 (setq header-end (move-marker (make-marker) (point)))
19966 (while t
19967 (setq custom1 custom)
19968 (when (eq rmheader t)
19969 (goto-line 1)
19970 (re-search-forward ":" nil t)
19971 (delete-region (match-end 0) (point-at-eol))
19972 (forward-char 1)
19973 (looking-at "-+")
19974 (delete-region (match-end 0) (point-at-eol))
19975 (move-marker header-end (match-end 0)))
19976 (goto-char header-end)
19977 (delete-region (point) (point-max))
19978 (while (setq entry (pop custom1))
19979 (setq key (car entry) desc (nth 1 entry)
19980 type (nth 2 entry) match (nth 3 entry))
19981 (if (> (length key) 1)
19982 (add-to-list 'prefixes (string-to-char key))
19983 (insert
19984 (format
19985 "\n%-4s%-14s: %s"
19986 (org-add-props (copy-sequence key)
19987 '(face bold))
19988 (cond
19989 ((string-match "\\S-" desc) desc)
19990 ((eq type 'agenda) "Agenda for current week or day")
19991 ((eq type 'alltodo) "List of all TODO entries")
19992 ((eq type 'search) "Word search")
19993 ((eq type 'stuck) "List of stuck projects")
19994 ((eq type 'todo) "TODO keyword")
19995 ((eq type 'tags) "Tags query")
19996 ((eq type 'tags-todo) "Tags (TODO)")
19997 ((eq type 'tags-tree) "Tags tree")
19998 ((eq type 'todo-tree) "TODO kwd tree")
19999 ((eq type 'occur-tree) "Occur tree")
20000 ((functionp type) (if (symbolp type)
20001 (symbol-name type)
20002 "Lambda expression"))
20003 (t "???"))
20004 (cond
20005 ((stringp match)
20006 (org-add-props match nil 'face 'org-warning))
20007 (match
20008 (format "set of %d commands" (length match)))
20009 (t ""))))))
20010 (when prefixes
20011 (mapc (lambda (x)
20012 (insert
20013 (format "\n%s %s"
20014 (org-add-props (char-to-string x)
20015 nil 'face 'bold)
20016 (or (cdr (assoc (concat selstring (char-to-string x))
20017 prefix-descriptions))
20018 "Prefix key"))))
20019 prefixes))
20020 (goto-char (point-min))
20021 (when (fboundp 'fit-window-to-buffer)
20022 (if second-time
20023 (if (not (pos-visible-in-window-p (point-max)))
20024 (fit-window-to-buffer))
20025 (setq second-time t)
20026 (fit-window-to-buffer)))
20027 (message "Press key for agenda command%s:"
20028 (if (or restrict-ok org-agenda-overriding-restriction)
20029 (if org-agenda-overriding-restriction
20030 " (restriction lock active)"
20031 (if restriction
20032 (format " (restricted to %s)" restriction)
20033 " (unrestricted)"))
20034 ""))
20035 (setq c (read-char-exclusive))
20036 (message "")
20037 (cond
20038 ((assoc (char-to-string c) custom)
20039 (setq selstring (concat selstring (char-to-string c)))
20040 (throw 'exit (cons selstring restriction)))
20041 ((memq c prefixes)
20042 (setq selstring (concat selstring (char-to-string c))
20043 prefixes nil
20044 rmheader (or rmheader t)
20045 custom (delq nil (mapcar
20046 (lambda (x)
20047 (if (or (= (length (car x)) 1)
20048 (/= (string-to-char (car x)) c))
20050 (cons (substring (car x) 1) (cdr x))))
20051 custom))))
20052 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
20053 (message "Restriction is only possible in Org-mode buffers")
20054 (ding) (sit-for 1))
20055 ((eq c ?1)
20056 (org-agenda-remove-restriction-lock 'noupdate)
20057 (setq restriction 'buffer))
20058 ((eq c ?0)
20059 (org-agenda-remove-restriction-lock 'noupdate)
20060 (setq restriction (if region-p 'region 'subtree)))
20061 ((eq c ?<)
20062 (org-agenda-remove-restriction-lock 'noupdate)
20063 (setq restriction
20064 (cond
20065 ((eq restriction 'buffer)
20066 (if region-p 'region 'subtree))
20067 ((memq restriction '(subtree region))
20068 nil)
20069 (t 'buffer))))
20070 ((eq c ?>)
20071 (org-agenda-remove-restriction-lock 'noupdate)
20072 (setq restriction nil))
20073 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
20074 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
20075 ((and (> (length selstring) 0) (eq c ?\d))
20076 (delete-window)
20077 (org-agenda-get-restriction-and-command prefix-descriptions))
20079 ((equal c ?q) (error "Abort"))
20080 (t (error "Invalid key %c" c))))))))
20082 (defun org-run-agenda-series (name series)
20083 (org-prepare-agenda name)
20084 (let* ((org-agenda-multi t)
20085 (redo (list 'org-run-agenda-series name (list 'quote series)))
20086 (cmds (car series))
20087 (gprops (nth 1 series))
20088 match ;; The byte compiler incorrectly complains about this. Keep it!
20089 cmd type lprops)
20090 (while (setq cmd (pop cmds))
20091 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
20092 (cond
20093 ((eq type 'agenda)
20094 (org-let2 gprops lprops
20095 '(call-interactively 'org-agenda-list)))
20096 ((eq type 'alltodo)
20097 (org-let2 gprops lprops
20098 '(call-interactively 'org-todo-list)))
20099 ((eq type 'search)
20100 (org-let2 gprops lprops
20101 '(org-search-view current-prefix-arg match)))
20102 ((eq type 'stuck)
20103 (org-let2 gprops lprops
20104 '(call-interactively 'org-agenda-list-stuck-projects)))
20105 ((eq type 'tags)
20106 (org-let2 gprops lprops
20107 '(org-tags-view current-prefix-arg match)))
20108 ((eq type 'tags-todo)
20109 (org-let2 gprops lprops
20110 '(org-tags-view '(4) match)))
20111 ((eq type 'todo)
20112 (org-let2 gprops lprops
20113 '(org-todo-list match)))
20114 ((fboundp type)
20115 (org-let2 gprops lprops
20116 '(funcall type match)))
20117 (t (error "Invalid type in command series"))))
20118 (widen)
20119 (setq org-agenda-redo-command redo)
20120 (goto-char (point-min)))
20121 (org-finalize-agenda))
20123 ;;;###autoload
20124 (defmacro org-batch-agenda (cmd-key &rest parameters)
20125 "Run an agenda command in batch mode and send the result to STDOUT.
20126 If CMD-KEY is a string of length 1, it is used as a key in
20127 `org-agenda-custom-commands' and triggers this command. If it is a
20128 longer string it is used as a tags/todo match string.
20129 Paramters are alternating variable names and values that will be bound
20130 before running the agenda command."
20131 (let (pars)
20132 (while parameters
20133 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20134 (if (> (length cmd-key) 2)
20135 (eval (list 'let (nreverse pars)
20136 (list 'org-tags-view nil cmd-key)))
20137 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20138 (set-buffer org-agenda-buffer-name)
20139 (princ (org-encode-for-stdout (buffer-string)))))
20141 (defun org-encode-for-stdout (string)
20142 (if (fboundp 'encode-coding-string)
20143 (encode-coding-string string buffer-file-coding-system)
20144 string))
20146 (defvar org-agenda-info nil)
20148 ;;;###autoload
20149 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20150 "Run an agenda command in batch mode and send the result to STDOUT.
20151 If CMD-KEY is a string of length 1, it is used as a key in
20152 `org-agenda-custom-commands' and triggers this command. If it is a
20153 longer string it is used as a tags/todo match string.
20154 Paramters are alternating variable names and values that will be bound
20155 before running the agenda command.
20157 The output gives a line for each selected agenda item. Each
20158 item is a list of comma-separated values, like this:
20160 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20162 category The category of the item
20163 head The headline, without TODO kwd, TAGS and PRIORITY
20164 type The type of the agenda entry, can be
20165 todo selected in TODO match
20166 tagsmatch selected in tags match
20167 diary imported from diary
20168 deadline a deadline on given date
20169 scheduled scheduled on given date
20170 timestamp entry has timestamp on given date
20171 closed entry was closed on given date
20172 upcoming-deadline warning about deadline
20173 past-scheduled forwarded scheduled item
20174 block entry has date block including g. date
20175 todo The todo keyword, if any
20176 tags All tags including inherited ones, separated by colons
20177 date The relevant date, like 2007-2-14
20178 time The time, like 15:00-16:50
20179 extra Sting with extra planning info
20180 priority-l The priority letter if any was given
20181 priority-n The computed numerical priority
20182 agenda-day The day in the agenda where this is listed"
20184 (let (pars)
20185 (while parameters
20186 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20187 (push (list 'org-agenda-remove-tags t) pars)
20188 (if (> (length cmd-key) 2)
20189 (eval (list 'let (nreverse pars)
20190 (list 'org-tags-view nil cmd-key)))
20191 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20192 (set-buffer org-agenda-buffer-name)
20193 (let* ((lines (org-split-string (buffer-string) "\n"))
20194 line)
20195 (while (setq line (pop lines))
20196 (catch 'next
20197 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20198 (setq org-agenda-info
20199 (org-fix-agenda-info (text-properties-at 0 line)))
20200 (princ
20201 (org-encode-for-stdout
20202 (mapconcat 'org-agenda-export-csv-mapper
20203 '(org-category txt type todo tags date time-of-day extra
20204 priority-letter priority agenda-day)
20205 ",")))
20206 (princ "\n"))))))
20208 (defun org-fix-agenda-info (props)
20209 "Make sure all properties on an agenda item have a canonical form,
20210 so the export commands can easily use it."
20211 (let (tmp re)
20212 (when (setq tmp (plist-get props 'tags))
20213 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20214 (when (setq tmp (plist-get props 'date))
20215 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20216 (let ((calendar-date-display-form '(year "-" month "-" day)))
20217 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20219 (setq tmp (calendar-date-string tmp)))
20220 (setq props (plist-put props 'date tmp)))
20221 (when (setq tmp (plist-get props 'day))
20222 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20223 (let ((calendar-date-display-form '(year "-" month "-" day)))
20224 (setq tmp (calendar-date-string tmp)))
20225 (setq props (plist-put props 'day tmp))
20226 (setq props (plist-put props 'agenda-day tmp)))
20227 (when (setq tmp (plist-get props 'txt))
20228 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20229 (plist-put props 'priority-letter (match-string 1 tmp))
20230 (setq tmp (replace-match "" t t tmp)))
20231 (when (and (setq re (plist-get props 'org-todo-regexp))
20232 (setq re (concat "\\`\\.*" re " ?"))
20233 (string-match re tmp))
20234 (plist-put props 'todo (match-string 1 tmp))
20235 (setq tmp (replace-match "" t t tmp)))
20236 (plist-put props 'txt tmp)))
20237 props)
20239 (defun org-agenda-export-csv-mapper (prop)
20240 (let ((res (plist-get org-agenda-info prop)))
20241 (setq res
20242 (cond
20243 ((not res) "")
20244 ((stringp res) res)
20245 (t (prin1-to-string res))))
20246 (while (string-match "," res)
20247 (setq res (replace-match ";" t t res)))
20248 (org-trim res)))
20251 ;;;###autoload
20252 (defun org-store-agenda-views (&rest parameters)
20253 (interactive)
20254 (eval (list 'org-batch-store-agenda-views)))
20256 ;; FIXME, why is this a macro?????
20257 ;;;###autoload
20258 (defmacro org-batch-store-agenda-views (&rest parameters)
20259 "Run all custom agenda commands that have a file argument."
20260 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20261 (pop-up-frames nil)
20262 (dir default-directory)
20263 pars cmd thiscmdkey files opts)
20264 (while parameters
20265 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20266 (setq pars (reverse pars))
20267 (save-window-excursion
20268 (while cmds
20269 (setq cmd (pop cmds)
20270 thiscmdkey (car cmd)
20271 opts (nth 4 cmd)
20272 files (nth 5 cmd))
20273 (if (stringp files) (setq files (list files)))
20274 (when files
20275 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20276 (list 'org-agenda nil thiscmdkey)))
20277 (set-buffer org-agenda-buffer-name)
20278 (while files
20279 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20280 (list 'org-write-agenda
20281 (expand-file-name (pop files) dir) t))))
20282 (and (get-buffer org-agenda-buffer-name)
20283 (kill-buffer org-agenda-buffer-name)))))))
20285 (defun org-write-agenda (file &optional nosettings)
20286 "Write the current buffer (an agenda view) as a file.
20287 Depending on the extension of the file name, plain text (.txt),
20288 HTML (.html or .htm) or Postscript (.ps) is produced.
20289 If NOSETTINGS is given, do not scope the settings of
20290 `org-agenda-exporter-settings' into the export commands. This is used when
20291 the settings have already been scoped and we do not wish to overrule other,
20292 higher priority settings."
20293 (interactive "FWrite agenda to file: ")
20294 (if (not (file-writable-p file))
20295 (error "Cannot write agenda to file %s" file))
20296 (cond
20297 ((string-match "\\.html?\\'" file) (require 'htmlize))
20298 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20299 (org-let (if nosettings nil org-agenda-exporter-settings)
20300 '(save-excursion
20301 (save-window-excursion
20302 (cond
20303 ((string-match "\\.html?\\'" file)
20304 (set-buffer (htmlize-buffer (current-buffer)))
20306 (when (and org-agenda-export-html-style
20307 (string-match "<style>" org-agenda-export-html-style))
20308 ;; replace <style> section with org-agenda-export-html-style
20309 (goto-char (point-min))
20310 (kill-region (- (search-forward "<style") 6)
20311 (search-forward "</style>"))
20312 (insert org-agenda-export-html-style))
20313 (write-file file)
20314 (kill-buffer (current-buffer))
20315 (message "HTML written to %s" file))
20316 ((string-match "\\.ps\\'" file)
20317 (ps-print-buffer-with-faces file)
20318 (message "Postscript written to %s" file))
20320 (let ((bs (buffer-string)))
20321 (find-file file)
20322 (insert bs)
20323 (save-buffer 0)
20324 (kill-buffer (current-buffer))
20325 (message "Plain text written to %s" file))))))
20326 (set-buffer org-agenda-buffer-name)))
20328 (defmacro org-no-read-only (&rest body)
20329 "Inhibit read-only for BODY."
20330 `(let ((inhibit-read-only t)) ,@body))
20332 (defun org-check-for-org-mode ()
20333 "Make sure current buffer is in org-mode. Error if not."
20334 (or (org-mode-p)
20335 (error "Cannot execute org-mode agenda command on buffer in %s."
20336 major-mode)))
20338 (defun org-fit-agenda-window ()
20339 "Fit the window to the buffer size."
20340 (and (memq org-agenda-window-setup '(reorganize-frame))
20341 (fboundp 'fit-window-to-buffer)
20342 (fit-window-to-buffer
20344 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20345 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20347 ;;; Agenda file list
20349 (defun org-agenda-files (&optional unrestricted)
20350 "Get the list of agenda files.
20351 Optional UNRESTRICTED means return the full list even if a restriction
20352 is currently in place."
20353 (let ((files
20354 (cond
20355 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20356 ((stringp org-agenda-files) (org-read-agenda-file-list))
20357 ((listp org-agenda-files) org-agenda-files)
20358 (t (error "Invalid value of `org-agenda-files'")))))
20359 (setq files (apply 'append
20360 (mapcar (lambda (f)
20361 (if (file-directory-p f)
20362 (directory-files f t
20363 org-agenda-file-regexp)
20364 (list f)))
20365 files)))
20366 (if org-agenda-skip-unavailable-files
20367 (delq nil
20368 (mapcar (function
20369 (lambda (file)
20370 (and (file-readable-p file) file)))
20371 files))
20372 files))) ; `org-check-agenda-file' will remove them from the list
20374 (defun org-edit-agenda-file-list ()
20375 "Edit the list of agenda files.
20376 Depending on setup, this either uses customize to edit the variable
20377 `org-agenda-files', or it visits the file that is holding the list. In the
20378 latter case, the buffer is set up in a way that saving it automatically kills
20379 the buffer and restores the previous window configuration."
20380 (interactive)
20381 (if (stringp org-agenda-files)
20382 (let ((cw (current-window-configuration)))
20383 (find-file org-agenda-files)
20384 (org-set-local 'org-window-configuration cw)
20385 (org-add-hook 'after-save-hook
20386 (lambda ()
20387 (set-window-configuration
20388 (prog1 org-window-configuration
20389 (kill-buffer (current-buffer))))
20390 (org-install-agenda-files-menu)
20391 (message "New agenda file list installed"))
20392 nil 'local)
20393 (message "%s" (substitute-command-keys
20394 "Edit list and finish with \\[save-buffer]")))
20395 (customize-variable 'org-agenda-files)))
20397 (defun org-store-new-agenda-file-list (list)
20398 "Set new value for the agenda file list and save it correcly."
20399 (if (stringp org-agenda-files)
20400 (let ((f org-agenda-files) b)
20401 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20402 (with-temp-file f
20403 (insert (mapconcat 'identity list "\n") "\n")))
20404 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20405 (setq org-agenda-files list)
20406 (customize-save-variable 'org-agenda-files org-agenda-files))))
20408 (defun org-read-agenda-file-list ()
20409 "Read the list of agenda files from a file."
20410 (when (stringp org-agenda-files)
20411 (with-temp-buffer
20412 (insert-file-contents org-agenda-files)
20413 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20416 ;;;###autoload
20417 (defun org-cycle-agenda-files ()
20418 "Cycle through the files in `org-agenda-files'.
20419 If the current buffer visits an agenda file, find the next one in the list.
20420 If the current buffer does not, find the first agenda file."
20421 (interactive)
20422 (let* ((fs (org-agenda-files t))
20423 (files (append fs (list (car fs))))
20424 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20425 file)
20426 (unless files (error "No agenda files"))
20427 (catch 'exit
20428 (while (setq file (pop files))
20429 (if (equal (file-truename file) tcf)
20430 (when (car files)
20431 (find-file (car files))
20432 (throw 'exit t))))
20433 (find-file (car fs)))
20434 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20436 (defun org-agenda-file-to-front (&optional to-end)
20437 "Move/add the current file to the top of the agenda file list.
20438 If the file is not present in the list, it is added to the front. If it is
20439 present, it is moved there. With optional argument TO-END, add/move to the
20440 end of the list."
20441 (interactive "P")
20442 (let ((org-agenda-skip-unavailable-files nil)
20443 (file-alist (mapcar (lambda (x)
20444 (cons (file-truename x) x))
20445 (org-agenda-files t)))
20446 (ctf (file-truename buffer-file-name))
20447 x had)
20448 (setq x (assoc ctf file-alist) had x)
20450 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20451 (if to-end
20452 (setq file-alist (append (delq x file-alist) (list x)))
20453 (setq file-alist (cons x (delq x file-alist))))
20454 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20455 (org-install-agenda-files-menu)
20456 (message "File %s to %s of agenda file list"
20457 (if had "moved" "added") (if to-end "end" "front"))))
20459 (defun org-remove-file (&optional file)
20460 "Remove current file from the list of files in variable `org-agenda-files'.
20461 These are the files which are being checked for agenda entries.
20462 Optional argument FILE means, use this file instead of the current."
20463 (interactive)
20464 (let* ((org-agenda-skip-unavailable-files nil)
20465 (file (or file buffer-file-name))
20466 (true-file (file-truename file))
20467 (afile (abbreviate-file-name file))
20468 (files (delq nil (mapcar
20469 (lambda (x)
20470 (if (equal true-file
20471 (file-truename x))
20472 nil x))
20473 (org-agenda-files t)))))
20474 (if (not (= (length files) (length (org-agenda-files t))))
20475 (progn
20476 (org-store-new-agenda-file-list files)
20477 (org-install-agenda-files-menu)
20478 (message "Removed file: %s" afile))
20479 (message "File was not in list: %s (not removed)" afile))))
20481 (defun org-file-menu-entry (file)
20482 (vector file (list 'find-file file) t))
20484 (defun org-check-agenda-file (file)
20485 "Make sure FILE exists. If not, ask user what to do."
20486 (when (not (file-exists-p file))
20487 (message "non-existent file %s. [R]emove from list or [A]bort?"
20488 (abbreviate-file-name file))
20489 (let ((r (downcase (read-char-exclusive))))
20490 (cond
20491 ((equal r ?r)
20492 (org-remove-file file)
20493 (throw 'nextfile t))
20494 (t (error "Abort"))))))
20496 ;;; Agenda prepare and finalize
20498 (defvar org-agenda-multi nil) ; dynammically scoped
20499 (defvar org-agenda-buffer-name "*Org Agenda*")
20500 (defvar org-pre-agenda-window-conf nil)
20501 (defvar org-agenda-name nil)
20502 (defun org-prepare-agenda (&optional name)
20503 (setq org-todo-keywords-for-agenda nil)
20504 (setq org-done-keywords-for-agenda nil)
20505 (if org-agenda-multi
20506 (progn
20507 (setq buffer-read-only nil)
20508 (goto-char (point-max))
20509 (unless (or (bobp) org-agenda-compact-blocks)
20510 (insert "\n" (make-string (window-width) ?=) "\n"))
20511 (narrow-to-region (point) (point-max)))
20512 (org-agenda-reset-markers)
20513 (org-prepare-agenda-buffers (org-agenda-files))
20514 (setq org-todo-keywords-for-agenda
20515 (org-uniquify org-todo-keywords-for-agenda))
20516 (setq org-done-keywords-for-agenda
20517 (org-uniquify org-done-keywords-for-agenda))
20518 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20519 (awin (get-buffer-window abuf)))
20520 (cond
20521 ((equal (current-buffer) abuf) nil)
20522 (awin (select-window awin))
20523 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20524 ((equal org-agenda-window-setup 'current-window)
20525 (switch-to-buffer abuf))
20526 ((equal org-agenda-window-setup 'other-window)
20527 (org-switch-to-buffer-other-window abuf))
20528 ((equal org-agenda-window-setup 'other-frame)
20529 (switch-to-buffer-other-frame abuf))
20530 ((equal org-agenda-window-setup 'reorganize-frame)
20531 (delete-other-windows)
20532 (org-switch-to-buffer-other-window abuf))))
20533 (setq buffer-read-only nil)
20534 (erase-buffer)
20535 (org-agenda-mode)
20536 (and name (not org-agenda-name)
20537 (org-set-local 'org-agenda-name name)))
20538 (setq buffer-read-only nil))
20540 (defun org-finalize-agenda ()
20541 "Finishing touch for the agenda buffer, called just before displaying it."
20542 (unless org-agenda-multi
20543 (save-excursion
20544 (let ((inhibit-read-only t))
20545 (goto-char (point-min))
20546 (while (org-activate-bracket-links (point-max))
20547 (add-text-properties (match-beginning 0) (match-end 0)
20548 '(face org-link)))
20549 (org-agenda-align-tags)
20550 (unless org-agenda-with-colors
20551 (remove-text-properties (point-min) (point-max) '(face nil))))
20552 (if (and (boundp 'org-overriding-columns-format)
20553 org-overriding-columns-format)
20554 (org-set-local 'org-overriding-columns-format
20555 org-overriding-columns-format))
20556 (if (and (boundp 'org-agenda-view-columns-initially)
20557 org-agenda-view-columns-initially)
20558 (org-agenda-columns))
20559 (when org-agenda-fontify-priorities
20560 (org-fontify-priorities))
20561 (run-hooks 'org-finalize-agenda-hook)
20562 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20565 (defun org-fontify-priorities ()
20566 "Make highest priority lines bold, and lowest italic."
20567 (interactive)
20568 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20569 (org-delete-overlay o)))
20570 (org-overlays-in (point-min) (point-max)))
20571 (save-excursion
20572 (let ((inhibit-read-only t)
20573 b e p ov h l)
20574 (goto-char (point-min))
20575 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20576 (setq h (or (get-char-property (point) 'org-highest-priority)
20577 org-highest-priority)
20578 l (or (get-char-property (point) 'org-lowest-priority)
20579 org-lowest-priority)
20580 p (string-to-char (match-string 1))
20581 b (match-beginning 0) e (point-at-eol)
20582 ov (org-make-overlay b e))
20583 (org-overlay-put
20584 ov 'face
20585 (cond ((listp org-agenda-fontify-priorities)
20586 (cdr (assoc p org-agenda-fontify-priorities)))
20587 ((equal p l) 'italic)
20588 ((equal p h) 'bold)))
20589 (org-overlay-put ov 'org-type 'org-priority)))))
20591 (defun org-prepare-agenda-buffers (files)
20592 "Create buffers for all agenda files, protect archived trees and comments."
20593 (interactive)
20594 (let ((pa '(:org-archived t))
20595 (pc '(:org-comment t))
20596 (pall '(:org-archived t :org-comment t))
20597 (inhibit-read-only t)
20598 (rea (concat ":" org-archive-tag ":"))
20599 bmp file re)
20600 (save-excursion
20601 (save-restriction
20602 (while (setq file (pop files))
20603 (if (bufferp file)
20604 (set-buffer file)
20605 (org-check-agenda-file file)
20606 (set-buffer (org-get-agenda-file-buffer file)))
20607 (widen)
20608 (setq bmp (buffer-modified-p))
20609 (org-refresh-category-properties)
20610 (setq org-todo-keywords-for-agenda
20611 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20612 (setq org-done-keywords-for-agenda
20613 (append org-done-keywords-for-agenda org-done-keywords))
20614 (save-excursion
20615 (remove-text-properties (point-min) (point-max) pall)
20616 (when org-agenda-skip-archived-trees
20617 (goto-char (point-min))
20618 (while (re-search-forward rea nil t)
20619 (if (org-on-heading-p t)
20620 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20621 (goto-char (point-min))
20622 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20623 (while (re-search-forward re nil t)
20624 (add-text-properties
20625 (match-beginning 0) (org-end-of-subtree t) pc)))
20626 (set-buffer-modified-p bmp))))))
20628 (defvar org-agenda-skip-function nil
20629 "Function to be called at each match during agenda construction.
20630 If this function returns nil, the current match should not be skipped.
20631 Otherwise, the function must return a position from where the search
20632 should be continued.
20633 This may also be a Lisp form, it will be evaluated.
20634 Never set this variable using `setq' or so, because then it will apply
20635 to all future agenda commands. Instead, bind it with `let' to scope
20636 it dynamically into the agenda-constructing command. A good way to set
20637 it is through options in org-agenda-custom-commands.")
20639 (defun org-agenda-skip ()
20640 "Throw to `:skip' in places that should be skipped.
20641 Also moves point to the end of the skipped region, so that search can
20642 continue from there."
20643 (let ((p (point-at-bol)) to fp)
20644 (and org-agenda-skip-archived-trees
20645 (get-text-property p :org-archived)
20646 (org-end-of-subtree t)
20647 (throw :skip t))
20648 (and (get-text-property p :org-comment)
20649 (org-end-of-subtree t)
20650 (throw :skip t))
20651 (if (equal (char-after p) ?#) (throw :skip t))
20652 (when (and (or (setq fp (functionp org-agenda-skip-function))
20653 (consp org-agenda-skip-function))
20654 (setq to (save-excursion
20655 (save-match-data
20656 (if fp
20657 (funcall org-agenda-skip-function)
20658 (eval org-agenda-skip-function))))))
20659 (goto-char to)
20660 (throw :skip t))))
20662 (defvar org-agenda-markers nil
20663 "List of all currently active markers created by `org-agenda'.")
20664 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20665 "Creation time of the last agenda marker.")
20667 (defun org-agenda-new-marker (&optional pos)
20668 "Return a new agenda marker.
20669 Org-mode keeps a list of these markers and resets them when they are
20670 no longer in use."
20671 (let ((m (copy-marker (or pos (point)))))
20672 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20673 (push m org-agenda-markers)
20676 (defun org-agenda-reset-markers ()
20677 "Reset markers created by `org-agenda'."
20678 (while org-agenda-markers
20679 (move-marker (pop org-agenda-markers) nil)))
20681 (defun org-get-agenda-file-buffer (file)
20682 "Get a buffer visiting FILE. If the buffer needs to be created, add
20683 it to the list of buffers which might be released later."
20684 (let ((buf (org-find-base-buffer-visiting file)))
20685 (if buf
20686 buf ; just return it
20687 ;; Make a new buffer and remember it
20688 (setq buf (find-file-noselect file))
20689 (if buf (push buf org-agenda-new-buffers))
20690 buf)))
20692 (defun org-release-buffers (blist)
20693 "Release all buffers in list, asking the user for confirmation when needed.
20694 When a buffer is unmodified, it is just killed. When modified, it is saved
20695 \(if the user agrees) and then killed."
20696 (let (buf file)
20697 (while (setq buf (pop blist))
20698 (setq file (buffer-file-name buf))
20699 (when (and (buffer-modified-p buf)
20700 file
20701 (y-or-n-p (format "Save file %s? " file)))
20702 (with-current-buffer buf (save-buffer)))
20703 (kill-buffer buf))))
20705 (defun org-get-category (&optional pos)
20706 "Get the category applying to position POS."
20707 (get-text-property (or pos (point)) 'org-category))
20709 ;;; Agenda timeline
20711 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20713 (defun org-timeline (&optional include-all)
20714 "Show a time-sorted view of the entries in the current org file.
20715 Only entries with a time stamp of today or later will be listed. With
20716 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20717 under the current date.
20718 If the buffer contains an active region, only check the region for
20719 dates."
20720 (interactive "P")
20721 (require 'calendar)
20722 (org-compile-prefix-format 'timeline)
20723 (org-set-sorting-strategy 'timeline)
20724 (let* ((dopast t)
20725 (dotodo include-all)
20726 (doclosed org-agenda-show-log)
20727 (entry buffer-file-name)
20728 (date (calendar-current-date))
20729 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20730 (end (if (org-region-active-p) (region-end) (point-max)))
20731 (day-numbers (org-get-all-dates beg end 'no-ranges
20732 t doclosed ; always include today
20733 org-timeline-show-empty-dates))
20734 (org-deadline-warning-days 0)
20735 (org-agenda-only-exact-dates t)
20736 (today (time-to-days (current-time)))
20737 (past t)
20738 args
20739 s e rtn d emptyp)
20740 (setq org-agenda-redo-command
20741 (list 'progn
20742 (list 'org-switch-to-buffer-other-window (current-buffer))
20743 (list 'org-timeline (list 'quote include-all))))
20744 (if (not dopast)
20745 ;; Remove past dates from the list of dates.
20746 (setq day-numbers (delq nil (mapcar (lambda(x)
20747 (if (>= x today) x nil))
20748 day-numbers))))
20749 (org-prepare-agenda (concat "Timeline "
20750 (file-name-nondirectory buffer-file-name)))
20751 (if doclosed (push :closed args))
20752 (push :timestamp args)
20753 (push :deadline args)
20754 (push :scheduled args)
20755 (push :sexp args)
20756 (if dotodo (push :todo args))
20757 (while (setq d (pop day-numbers))
20758 (if (and (listp d) (eq (car d) :omitted))
20759 (progn
20760 (setq s (point))
20761 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20762 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20763 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20764 (if (and (>= d today)
20765 dopast
20766 past)
20767 (progn
20768 (setq past nil)
20769 (insert (make-string 79 ?-) "\n")))
20770 (setq date (calendar-gregorian-from-absolute d))
20771 (setq s (point))
20772 (setq rtn (and (not emptyp)
20773 (apply 'org-agenda-get-day-entries entry
20774 date args)))
20775 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20776 (progn
20777 (insert
20778 (if (stringp org-agenda-format-date)
20779 (format-time-string org-agenda-format-date
20780 (org-time-from-absolute date))
20781 (funcall org-agenda-format-date date))
20782 "\n")
20783 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20784 (put-text-property s (1- (point)) 'org-date-line t)
20785 (if (equal d today)
20786 (put-text-property s (1- (point)) 'org-today t))
20787 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20788 (put-text-property s (1- (point)) 'day d)))))
20789 (goto-char (point-min))
20790 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20791 (point-min)))
20792 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20793 (org-finalize-agenda)
20794 (setq buffer-read-only t)))
20796 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20797 "Return a list of all relevant day numbers from BEG to END buffer positions.
20798 If NO-RANGES is non-nil, include only the start and end dates of a range,
20799 not every single day in the range. If FORCE-TODAY is non-nil, make
20800 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20801 inactive time stamps (those in square brackets) are included.
20802 When EMPTY is non-nil, also include days without any entries."
20803 (let ((re (concat
20804 (if pre-re pre-re "")
20805 (if inactive org-ts-regexp-both org-ts-regexp)))
20806 dates dates1 date day day1 day2 ts1 ts2)
20807 (if force-today
20808 (setq dates (list (time-to-days (current-time)))))
20809 (save-excursion
20810 (goto-char beg)
20811 (while (re-search-forward re end t)
20812 (setq day (time-to-days (org-time-string-to-time
20813 (substring (match-string 1) 0 10))))
20814 (or (memq day dates) (push day dates)))
20815 (unless no-ranges
20816 (goto-char beg)
20817 (while (re-search-forward org-tr-regexp end t)
20818 (setq ts1 (substring (match-string 1) 0 10)
20819 ts2 (substring (match-string 2) 0 10)
20820 day1 (time-to-days (org-time-string-to-time ts1))
20821 day2 (time-to-days (org-time-string-to-time ts2)))
20822 (while (< (setq day1 (1+ day1)) day2)
20823 (or (memq day1 dates) (push day1 dates)))))
20824 (setq dates (sort dates '<))
20825 (when empty
20826 (while (setq day (pop dates))
20827 (setq day2 (car dates))
20828 (push day dates1)
20829 (when (and day2 empty)
20830 (if (or (eq empty t)
20831 (and (numberp empty) (<= (- day2 day) empty)))
20832 (while (< (setq day (1+ day)) day2)
20833 (push (list day) dates1))
20834 (push (cons :omitted (- day2 day)) dates1))))
20835 (setq dates (nreverse dates1)))
20836 dates)))
20838 ;;; Agenda Daily/Weekly
20840 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20841 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20842 (defvar org-agenda-last-arguments nil
20843 "The arguments of the previous call to org-agenda")
20844 (defvar org-starting-day nil) ; local variable in the agenda buffer
20845 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20846 (defvar org-include-all-loc nil) ; local variable
20847 (defvar org-agenda-remove-date nil) ; dynamically scoped
20849 ;;;###autoload
20850 (defun org-agenda-list (&optional include-all start-day ndays)
20851 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20852 The view will be for the current day or week, but from the overview buffer
20853 you will be able to go to other days/weeks.
20855 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20856 all unfinished TODO items will also be shown, before the agenda.
20857 This feature is considered obsolete, please use the TODO list or a block
20858 agenda instead.
20860 With a numeric prefix argument in an interactive call, the agenda will
20861 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20862 the number of days. NDAYS defaults to `org-agenda-ndays'.
20864 START-DAY defaults to TODAY, or to the most recent match for the weekday
20865 given in `org-agenda-start-on-weekday'."
20866 (interactive "P")
20867 (if (and (integerp include-all) (> include-all 0))
20868 (setq ndays include-all include-all nil))
20869 (setq ndays (or ndays org-agenda-ndays)
20870 start-day (or start-day org-agenda-start-day))
20871 (if org-agenda-overriding-arguments
20872 (setq include-all (car org-agenda-overriding-arguments)
20873 start-day (nth 1 org-agenda-overriding-arguments)
20874 ndays (nth 2 org-agenda-overriding-arguments)))
20875 (if (stringp start-day)
20876 ;; Convert to an absolute day number
20877 (setq start-day (time-to-days (org-read-date nil t start-day))))
20878 (setq org-agenda-last-arguments (list include-all start-day ndays))
20879 (org-compile-prefix-format 'agenda)
20880 (org-set-sorting-strategy 'agenda)
20881 (require 'calendar)
20882 (let* ((org-agenda-start-on-weekday
20883 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20884 org-agenda-start-on-weekday nil))
20885 (thefiles (org-agenda-files))
20886 (files thefiles)
20887 (today (time-to-days
20888 (time-subtract (current-time)
20889 (list 0 (* 3600 org-extend-today-until) 0))))
20890 (sd (or start-day today))
20891 (start (if (or (null org-agenda-start-on-weekday)
20892 (< org-agenda-ndays 7))
20894 (let* ((nt (calendar-day-of-week
20895 (calendar-gregorian-from-absolute sd)))
20896 (n1 org-agenda-start-on-weekday)
20897 (d (- nt n1)))
20898 (- sd (+ (if (< d 0) 7 0) d)))))
20899 (day-numbers (list start))
20900 (day-cnt 0)
20901 (inhibit-redisplay (not debug-on-error))
20902 s e rtn rtnall file date d start-pos end-pos todayp nd)
20903 (setq org-agenda-redo-command
20904 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20905 ;; Make the list of days
20906 (setq ndays (or ndays org-agenda-ndays)
20907 nd ndays)
20908 (while (> ndays 1)
20909 (push (1+ (car day-numbers)) day-numbers)
20910 (setq ndays (1- ndays)))
20911 (setq day-numbers (nreverse day-numbers))
20912 (org-prepare-agenda "Day/Week")
20913 (org-set-local 'org-starting-day (car day-numbers))
20914 (org-set-local 'org-include-all-loc include-all)
20915 (org-set-local 'org-agenda-span
20916 (org-agenda-ndays-to-span nd))
20917 (when (and (or include-all org-agenda-include-all-todo)
20918 (member today day-numbers))
20919 (setq files thefiles
20920 rtnall nil)
20921 (while (setq file (pop files))
20922 (catch 'nextfile
20923 (org-check-agenda-file file)
20924 (setq date (calendar-gregorian-from-absolute today)
20925 rtn (org-agenda-get-day-entries
20926 file date :todo))
20927 (setq rtnall (append rtnall rtn))))
20928 (when rtnall
20929 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20930 (add-text-properties (point-min) (1- (point))
20931 (list 'face 'org-agenda-structure))
20932 (insert (org-finalize-agenda-entries rtnall) "\n")))
20933 (unless org-agenda-compact-blocks
20934 (setq s (point))
20935 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20936 "-agenda:\n")
20937 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20938 'org-date-line t)))
20939 (while (setq d (pop day-numbers))
20940 (setq date (calendar-gregorian-from-absolute d)
20941 s (point))
20942 (if (or (setq todayp (= d today))
20943 (and (not start-pos) (= d sd)))
20944 (setq start-pos (point))
20945 (if (and start-pos (not end-pos))
20946 (setq end-pos (point))))
20947 (setq files thefiles
20948 rtnall nil)
20949 (while (setq file (pop files))
20950 (catch 'nextfile
20951 (org-check-agenda-file file)
20952 (if org-agenda-show-log
20953 (setq rtn (org-agenda-get-day-entries
20954 file date
20955 :deadline :scheduled :timestamp :sexp :closed))
20956 (setq rtn (org-agenda-get-day-entries
20957 file date
20958 :deadline :scheduled :sexp :timestamp)))
20959 (setq rtnall (append rtnall rtn))))
20960 (if org-agenda-include-diary
20961 (progn
20962 (require 'diary-lib)
20963 (setq rtn (org-get-entries-from-diary date))
20964 (setq rtnall (append rtnall rtn))))
20965 (if (or rtnall org-agenda-show-all-dates)
20966 (progn
20967 (setq day-cnt (1+ day-cnt))
20968 (insert
20969 (if (stringp org-agenda-format-date)
20970 (format-time-string org-agenda-format-date
20971 (org-time-from-absolute date))
20972 (funcall org-agenda-format-date date))
20973 "\n")
20974 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20975 (put-text-property s (1- (point)) 'org-date-line t)
20976 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20977 (if todayp (put-text-property s (1- (point)) 'org-today t))
20978 (if rtnall (insert
20979 (org-finalize-agenda-entries
20980 (org-agenda-add-time-grid-maybe
20981 rtnall nd todayp))
20982 "\n"))
20983 (put-text-property s (1- (point)) 'day d)
20984 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20985 (goto-char (point-min))
20986 (org-fit-agenda-window)
20987 (unless (and (pos-visible-in-window-p (point-min))
20988 (pos-visible-in-window-p (point-max)))
20989 (goto-char (1- (point-max)))
20990 (recenter -1)
20991 (if (not (pos-visible-in-window-p (or start-pos 1)))
20992 (progn
20993 (goto-char (or start-pos 1))
20994 (recenter 1))))
20995 (goto-char (or start-pos 1))
20996 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20997 (org-finalize-agenda)
20998 (setq buffer-read-only t)
20999 (message "")))
21001 (defun org-agenda-ndays-to-span (n)
21002 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
21004 ;;; Agenda word search
21006 (defvar org-agenda-search-history nil)
21008 ;;;###autoload
21009 (defun org-search-view (&optional arg string)
21010 "Show all entries that contain words or regular expressions.
21011 If the first character of the search string is an asterisks,
21012 search only the headlines.
21014 The search string is broken into \"words\" by splitting at whitespace.
21015 The individual words are then interpreted as a boolean expression with
21016 logical AND. Words prefixed with a minus must not occur in the entry.
21017 Words without a prefix or prefixed with a plus must occur in the entry.
21018 Matching is case-insensitive and the words are enclosed by word delimiters.
21020 Words enclosed by curly braces are interpreted as regular expressions
21021 that must or must not match in the entry.
21023 This command searches the agenda files, and in addition the files listed
21024 in `org-agenda-text-search-extra-files'."
21025 (interactive "P")
21026 (org-compile-prefix-format 'search)
21027 (org-set-sorting-strategy 'search)
21028 (org-prepare-agenda "SEARCH")
21029 (let* ((props (list 'face nil
21030 'done-face 'org-done
21031 'org-not-done-regexp org-not-done-regexp
21032 'org-todo-regexp org-todo-regexp
21033 'mouse-face 'highlight
21034 'keymap org-agenda-keymap
21035 'help-echo (format "mouse-2 or RET jump to location")))
21036 regexp rtn rtnall files file pos
21037 marker priority category tags c neg re
21038 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
21039 (unless (and (not arg)
21040 (stringp string)
21041 (string-match "\\S-" string))
21042 (setq string (read-string "[+-]Word/{Regexp} ...: "
21043 (cond
21044 ((integerp arg) (cons string arg))
21045 (arg string))
21046 'org-agenda-search-history)))
21047 (setq org-agenda-redo-command
21048 (list 'org-search-view 'current-prefix-arg string))
21049 (setq org-agenda-query-string string)
21051 (if (equal (string-to-char string) ?*)
21052 (setq hdl-only t
21053 words (substring string 1))
21054 (setq words string))
21055 (setq words (org-split-string words))
21056 (mapc (lambda (w)
21057 (setq c (string-to-char w))
21058 (if (equal c ?-)
21059 (setq neg t w (substring w 1))
21060 (if (equal c ?+)
21061 (setq neg nil w (substring w 1))
21062 (setq neg nil)))
21063 (if (string-match "\\`{.*}\\'" w)
21064 (setq re (substring w 1 -1))
21065 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
21066 (if neg (push re regexps-) (push re regexps+)))
21067 words)
21068 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
21069 (if (not regexps+)
21070 (setq regexp (concat "^" org-outline-regexp))
21071 (setq regexp (pop regexps+))
21072 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
21073 regexp))))
21074 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
21075 rtnall nil)
21076 (while (setq file (pop files))
21077 (setq ee nil)
21078 (catch 'nextfile
21079 (org-check-agenda-file file)
21080 (setq buffer (if (file-exists-p file)
21081 (org-get-agenda-file-buffer file)
21082 (error "No such file %s" file)))
21083 (if (not buffer)
21084 ;; If file does not exist, make sure an error message is sent
21085 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
21086 file))))
21087 (with-current-buffer buffer
21088 (unless (org-mode-p)
21089 (error "Agenda file %s is not in `org-mode'" file))
21090 (let ((case-fold-search t))
21091 (save-excursion
21092 (save-restriction
21093 (if org-agenda-restrict
21094 (narrow-to-region org-agenda-restrict-begin
21095 org-agenda-restrict-end)
21096 (widen))
21097 (goto-char (point-min))
21098 (unless (or (org-on-heading-p)
21099 (outline-next-heading))
21100 (throw 'nextfile t))
21101 (goto-char (max (point-min) (1- (point))))
21102 (while (re-search-forward regexp nil t)
21103 (org-back-to-heading t)
21104 (skip-chars-forward "* ")
21105 (setq beg (point-at-bol)
21106 beg1 (point)
21107 end (progn (outline-next-heading) (point)))
21108 (catch :skip
21109 (goto-char beg)
21110 (org-agenda-skip)
21111 (setq str (buffer-substring-no-properties
21112 (point-at-bol)
21113 (if hdl-only (point-at-eol) end)))
21114 (mapc (lambda (wr) (when (string-match wr str)
21115 (goto-char (1- end))
21116 (throw :skip t)))
21117 regexps-)
21118 (mapc (lambda (wr) (unless (string-match wr str)
21119 (goto-char (1- end))
21120 (throw :skip t)))
21121 regexps+)
21122 (goto-char beg)
21123 (setq marker (org-agenda-new-marker (point))
21124 category (org-get-category)
21125 tags (org-get-tags-at (point))
21126 txt (org-format-agenda-item
21128 (buffer-substring-no-properties
21129 beg1 (point-at-eol))
21130 category tags))
21131 (org-add-props txt props
21132 'org-marker marker 'org-hd-marker marker
21133 'priority 1000 'org-category category
21134 'type "search")
21135 (push txt ee)
21136 (goto-char (1- end)))))))))
21137 (setq rtn (nreverse ee))
21138 (setq rtnall (append rtnall rtn)))
21139 (if org-agenda-overriding-header
21140 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21141 nil 'face 'org-agenda-structure) "\n")
21142 (insert "Search words: ")
21143 (add-text-properties (point-min) (1- (point))
21144 (list 'face 'org-agenda-structure))
21145 (setq pos (point))
21146 (insert string "\n")
21147 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21148 (setq pos (point))
21149 (unless org-agenda-multi
21150 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21151 (add-text-properties pos (1- (point))
21152 (list 'face 'org-agenda-structure))))
21153 (when rtnall
21154 (insert (org-finalize-agenda-entries rtnall) "\n"))
21155 (goto-char (point-min))
21156 (org-fit-agenda-window)
21157 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21158 (org-finalize-agenda)
21159 (setq buffer-read-only t)))
21161 ;;; Agenda TODO list
21163 (defvar org-select-this-todo-keyword nil)
21164 (defvar org-last-arg nil)
21166 ;;;###autoload
21167 (defun org-todo-list (arg)
21168 "Show all TODO entries from all agenda file in a single list.
21169 The prefix arg can be used to select a specific TODO keyword and limit
21170 the list to these. When using \\[universal-argument], you will be prompted
21171 for a keyword. A numeric prefix directly selects the Nth keyword in
21172 `org-todo-keywords-1'."
21173 (interactive "P")
21174 (require 'calendar)
21175 (org-compile-prefix-format 'todo)
21176 (org-set-sorting-strategy 'todo)
21177 (org-prepare-agenda "TODO")
21178 (let* ((today (time-to-days (current-time)))
21179 (date (calendar-gregorian-from-absolute today))
21180 (kwds org-todo-keywords-for-agenda)
21181 (completion-ignore-case t)
21182 (org-select-this-todo-keyword
21183 (if (stringp arg) arg
21184 (and arg (integerp arg) (> arg 0)
21185 (nth (1- arg) kwds))))
21186 rtn rtnall files file pos)
21187 (when (equal arg '(4))
21188 (setq org-select-this-todo-keyword
21189 (completing-read "Keyword (or KWD1|K2D2|...): "
21190 (mapcar 'list kwds) nil nil)))
21191 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21192 (org-set-local 'org-last-arg arg)
21193 (setq org-agenda-redo-command
21194 '(org-todo-list (or current-prefix-arg org-last-arg)))
21195 (setq files (org-agenda-files)
21196 rtnall nil)
21197 (while (setq file (pop files))
21198 (catch 'nextfile
21199 (org-check-agenda-file file)
21200 (setq rtn (org-agenda-get-day-entries file date :todo))
21201 (setq rtnall (append rtnall rtn))))
21202 (if org-agenda-overriding-header
21203 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21204 nil 'face 'org-agenda-structure) "\n")
21205 (insert "Global list of TODO items of type: ")
21206 (add-text-properties (point-min) (1- (point))
21207 (list 'face 'org-agenda-structure))
21208 (setq pos (point))
21209 (insert (or org-select-this-todo-keyword "ALL") "\n")
21210 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21211 (setq pos (point))
21212 (unless org-agenda-multi
21213 (insert "Available with `N r': (0)ALL")
21214 (let ((n 0) s)
21215 (mapc (lambda (x)
21216 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21217 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21218 (insert "\n "))
21219 (insert " " s))
21220 kwds))
21221 (insert "\n"))
21222 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21223 (when rtnall
21224 (insert (org-finalize-agenda-entries rtnall) "\n"))
21225 (goto-char (point-min))
21226 (org-fit-agenda-window)
21227 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21228 (org-finalize-agenda)
21229 (setq buffer-read-only t)))
21231 ;;; Agenda tags match
21233 ;;;###autoload
21234 (defun org-tags-view (&optional todo-only match)
21235 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21236 The prefix arg TODO-ONLY limits the search to TODO entries."
21237 (interactive "P")
21238 (org-compile-prefix-format 'tags)
21239 (org-set-sorting-strategy 'tags)
21240 (let* ((org-tags-match-list-sublevels
21241 (if todo-only t org-tags-match-list-sublevels))
21242 (completion-ignore-case t)
21243 rtn rtnall files file pos matcher
21244 buffer)
21245 (setq matcher (org-make-tags-matcher match)
21246 match (car matcher) matcher (cdr matcher))
21247 (org-prepare-agenda (concat "TAGS " match))
21248 (setq org-agenda-redo-command
21249 (list 'org-tags-view (list 'quote todo-only)
21250 (list 'if 'current-prefix-arg nil match)))
21251 (setq files (org-agenda-files)
21252 rtnall nil)
21253 (while (setq file (pop files))
21254 (catch 'nextfile
21255 (org-check-agenda-file file)
21256 (setq buffer (if (file-exists-p file)
21257 (org-get-agenda-file-buffer file)
21258 (error "No such file %s" file)))
21259 (if (not buffer)
21260 ;; If file does not exist, merror message to agenda
21261 (setq rtn (list
21262 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21263 rtnall (append rtnall rtn))
21264 (with-current-buffer buffer
21265 (unless (org-mode-p)
21266 (error "Agenda file %s is not in `org-mode'" file))
21267 (save-excursion
21268 (save-restriction
21269 (if org-agenda-restrict
21270 (narrow-to-region org-agenda-restrict-begin
21271 org-agenda-restrict-end)
21272 (widen))
21273 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21274 (setq rtnall (append rtnall rtn))))))))
21275 (if org-agenda-overriding-header
21276 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21277 nil 'face 'org-agenda-structure) "\n")
21278 (insert "Headlines with TAGS match: ")
21279 (add-text-properties (point-min) (1- (point))
21280 (list 'face 'org-agenda-structure))
21281 (setq pos (point))
21282 (insert match "\n")
21283 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21284 (setq pos (point))
21285 (unless org-agenda-multi
21286 (insert "Press `C-u r' to search again with new search string\n"))
21287 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21288 (when rtnall
21289 (insert (org-finalize-agenda-entries rtnall) "\n"))
21290 (goto-char (point-min))
21291 (org-fit-agenda-window)
21292 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21293 (org-finalize-agenda)
21294 (setq buffer-read-only t)))
21296 ;;; Agenda Finding stuck projects
21298 (defvar org-agenda-skip-regexp nil
21299 "Regular expression used in skipping subtrees for the agenda.
21300 This is basically a temporary global variable that can be set and then
21301 used by user-defined selections using `org-agenda-skip-function'.")
21303 (defvar org-agenda-overriding-header nil
21304 "When this is set during todo and tags searches, will replace header.")
21306 (defun org-agenda-skip-subtree-when-regexp-matches ()
21307 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21308 If yes, it returns the end position of this tree, causing agenda commands
21309 to skip this subtree. This is a function that can be put into
21310 `org-agenda-skip-function' for the duration of a command."
21311 (let ((end (save-excursion (org-end-of-subtree t)))
21312 skip)
21313 (save-excursion
21314 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21315 (and skip end)))
21317 (defun org-agenda-skip-entry-if (&rest conditions)
21318 "Skip entry if any of CONDITIONS is true.
21319 See `org-agenda-skip-if' for details."
21320 (org-agenda-skip-if nil conditions))
21322 (defun org-agenda-skip-subtree-if (&rest conditions)
21323 "Skip entry if any of CONDITIONS is true.
21324 See `org-agenda-skip-if' for details."
21325 (org-agenda-skip-if t conditions))
21327 (defun org-agenda-skip-if (subtree conditions)
21328 "Checks current entity for CONDITIONS.
21329 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21330 the entry, i.e. the text before the next heading is checked.
21332 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21333 from different tests. Valid conditions are:
21335 scheduled Check if there is a scheduled cookie
21336 notscheduled Check if there is no scheduled cookie
21337 deadline Check if there is a deadline
21338 notdeadline Check if there is no deadline
21339 regexp Check if regexp matches
21340 notregexp Check if regexp does not match.
21342 The regexp is taken from the conditions list, it must come right after
21343 the `regexp' or `notregexp' element.
21345 If any of these conditions is met, this function returns the end point of
21346 the entity, causing the search to continue from there. This is a function
21347 that can be put into `org-agenda-skip-function' for the duration of a command."
21348 (let (beg end m)
21349 (org-back-to-heading t)
21350 (setq beg (point)
21351 end (if subtree
21352 (progn (org-end-of-subtree t) (point))
21353 (progn (outline-next-heading) (1- (point)))))
21354 (goto-char beg)
21355 (and
21357 (and (memq 'scheduled conditions)
21358 (re-search-forward org-scheduled-time-regexp end t))
21359 (and (memq 'notscheduled conditions)
21360 (not (re-search-forward org-scheduled-time-regexp end t)))
21361 (and (memq 'deadline conditions)
21362 (re-search-forward org-deadline-time-regexp end t))
21363 (and (memq 'notdeadline conditions)
21364 (not (re-search-forward org-deadline-time-regexp end t)))
21365 (and (setq m (memq 'regexp conditions))
21366 (stringp (nth 1 m))
21367 (re-search-forward (nth 1 m) end t))
21368 (and (setq m (memq 'notregexp conditions))
21369 (stringp (nth 1 m))
21370 (not (re-search-forward (nth 1 m) end t))))
21371 end)))
21373 ;;;###autoload
21374 (defun org-agenda-list-stuck-projects (&rest ignore)
21375 "Create agenda view for projects that are stuck.
21376 Stuck projects are project that have no next actions. For the definitions
21377 of what a project is and how to check if it stuck, customize the variable
21378 `org-stuck-projects'.
21379 MATCH is being ignored."
21380 (interactive)
21381 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21382 ;; FIXME: we could have used org-agenda-skip-if here.
21383 (org-agenda-overriding-header "List of stuck projects: ")
21384 (matcher (nth 0 org-stuck-projects))
21385 (todo (nth 1 org-stuck-projects))
21386 (todo-wds (if (member "*" todo)
21387 (progn
21388 (org-prepare-agenda-buffers (org-agenda-files))
21389 (org-delete-all
21390 org-done-keywords-for-agenda
21391 (copy-sequence org-todo-keywords-for-agenda)))
21392 todo))
21393 (todo-re (concat "^\\*+[ \t]+\\("
21394 (mapconcat 'identity todo-wds "\\|")
21395 "\\)\\>"))
21396 (tags (nth 2 org-stuck-projects))
21397 (tags-re (if (member "*" tags)
21398 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21399 (concat "^\\*+ .*:\\("
21400 (mapconcat 'identity tags "\\|")
21401 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21402 (gen-re (nth 3 org-stuck-projects))
21403 (re-list
21404 (delq nil
21405 (list
21406 (if todo todo-re)
21407 (if tags tags-re)
21408 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21409 gen-re)))))
21410 (setq org-agenda-skip-regexp
21411 (if re-list
21412 (mapconcat 'identity re-list "\\|")
21413 (error "No information how to identify unstuck projects")))
21414 (org-tags-view nil matcher)
21415 (with-current-buffer org-agenda-buffer-name
21416 (setq org-agenda-redo-command
21417 '(org-agenda-list-stuck-projects
21418 (or current-prefix-arg org-last-arg))))))
21420 ;;; Diary integration
21422 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21424 (defun org-get-entries-from-diary (date)
21425 "Get the (Emacs Calendar) diary entries for DATE."
21426 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21427 (diary-display-hook '(fancy-diary-display))
21428 (pop-up-frames nil)
21429 (list-diary-entries-hook
21430 (cons 'org-diary-default-entry list-diary-entries-hook))
21431 (diary-file-name-prefix-function nil) ; turn this feature off
21432 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21433 entries
21434 (org-disable-agenda-to-diary t))
21435 (save-excursion
21436 (save-window-excursion
21437 (funcall (if (fboundp 'diary-list-entries)
21438 'diary-list-entries 'list-diary-entries)
21439 date 1)))
21440 (if (not (get-buffer fancy-diary-buffer))
21441 (setq entries nil)
21442 (with-current-buffer fancy-diary-buffer
21443 (setq buffer-read-only nil)
21444 (if (zerop (buffer-size))
21445 ;; No entries
21446 (setq entries nil)
21447 ;; Omit the date and other unnecessary stuff
21448 (org-agenda-cleanup-fancy-diary)
21449 ;; Add prefix to each line and extend the text properties
21450 (if (zerop (buffer-size))
21451 (setq entries nil)
21452 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21453 (set-buffer-modified-p nil)
21454 (kill-buffer fancy-diary-buffer)))
21455 (when entries
21456 (setq entries (org-split-string entries "\n"))
21457 (setq entries
21458 (mapcar
21459 (lambda (x)
21460 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21461 ;; Extend the text properties to the beginning of the line
21462 (org-add-props x (text-properties-at (1- (length x)) x)
21463 'type "diary" 'date date))
21464 entries)))))
21466 (defun org-agenda-cleanup-fancy-diary ()
21467 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21468 This gets rid of the date, the underline under the date, and
21469 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21470 date. It also removes lines that contain only whitespace."
21471 (goto-char (point-min))
21472 (if (looking-at ".*?:[ \t]*")
21473 (progn
21474 (replace-match "")
21475 (re-search-forward "\n=+$" nil t)
21476 (replace-match "")
21477 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21478 (re-search-forward "\n=+$" nil t)
21479 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21480 (goto-char (point-min))
21481 (while (re-search-forward "^ +\n" nil t)
21482 (replace-match ""))
21483 (goto-char (point-min))
21484 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21485 (replace-match "")))
21487 ;; Make sure entries from the diary have the right text properties.
21488 (eval-after-load "diary-lib"
21489 '(if (boundp 'diary-modify-entry-list-string-function)
21490 ;; We can rely on the hook, nothing to do
21492 ;; Hook not avaiable, must use advice to make this work
21493 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21494 "Make the position visible."
21495 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21496 (stringp string)
21497 buffer-file-name)
21498 (setq string (org-modify-diary-entry-string string))))))
21500 (defun org-modify-diary-entry-string (string)
21501 "Add text properties to string, allowing org-mode to act on it."
21502 (org-add-props string nil
21503 'mouse-face 'highlight
21504 'keymap org-agenda-keymap
21505 'help-echo (if buffer-file-name
21506 (format "mouse-2 or RET jump to diary file %s"
21507 (abbreviate-file-name buffer-file-name))
21509 'org-agenda-diary-link t
21510 'org-marker (org-agenda-new-marker (point-at-bol))))
21512 (defun org-diary-default-entry ()
21513 "Add a dummy entry to the diary.
21514 Needed to avoid empty dates which mess up holiday display."
21515 ;; Catch the error if dealing with the new add-to-diary-alist
21516 (when org-disable-agenda-to-diary
21517 (condition-case nil
21518 (add-to-diary-list original-date "Org-mode dummy" "")
21519 (error
21520 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21522 ;;;###autoload
21523 (defun org-diary (&rest args)
21524 "Return diary information from org-files.
21525 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21526 It accesses org files and extracts information from those files to be
21527 listed in the diary. The function accepts arguments specifying what
21528 items should be listed. The following arguments are allowed:
21530 :timestamp List the headlines of items containing a date stamp or
21531 date range matching the selected date. Deadlines will
21532 also be listed, on the expiration day.
21534 :sexp List entries resulting from diary-like sexps.
21536 :deadline List any deadlines past due, or due within
21537 `org-deadline-warning-days'. The listing occurs only
21538 in the diary for *today*, not at any other date. If
21539 an entry is marked DONE, it is no longer listed.
21541 :scheduled List all items which are scheduled for the given date.
21542 The diary for *today* also contains items which were
21543 scheduled earlier and are not yet marked DONE.
21545 :todo List all TODO items from the org-file. This may be a
21546 long list - so this is not turned on by default.
21547 Like deadlines, these entries only show up in the
21548 diary for *today*, not at any other date.
21550 The call in the diary file should look like this:
21552 &%%(org-diary) ~/path/to/some/orgfile.org
21554 Use a separate line for each org file to check. Or, if you omit the file name,
21555 all files listed in `org-agenda-files' will be checked automatically:
21557 &%%(org-diary)
21559 If you don't give any arguments (as in the example above), the default
21560 arguments (:deadline :scheduled :timestamp :sexp) are used.
21561 So the example above may also be written as
21563 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21565 The function expects the lisp variables `entry' and `date' to be provided
21566 by the caller, because this is how the calendar works. Don't use this
21567 function from a program - use `org-agenda-get-day-entries' instead."
21568 (when (> (- (time-to-seconds (current-time))
21569 org-agenda-last-marker-time)
21571 (org-agenda-reset-markers))
21572 (org-compile-prefix-format 'agenda)
21573 (org-set-sorting-strategy 'agenda)
21574 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21575 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21576 (list entry)
21577 (org-agenda-files t)))
21578 file rtn results)
21579 (org-prepare-agenda-buffers files)
21580 ;; If this is called during org-agenda, don't return any entries to
21581 ;; the calendar. Org Agenda will list these entries itself.
21582 (if org-disable-agenda-to-diary (setq files nil))
21583 (while (setq file (pop files))
21584 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21585 (setq results (append results rtn)))
21586 (if results
21587 (concat (org-finalize-agenda-entries results) "\n"))))
21589 ;;; Agenda entry finders
21591 (defun org-agenda-get-day-entries (file date &rest args)
21592 "Does the work for `org-diary' and `org-agenda'.
21593 FILE is the path to a file to be checked for entries. DATE is date like
21594 the one returned by `calendar-current-date'. ARGS are symbols indicating
21595 which kind of entries should be extracted. For details about these, see
21596 the documentation of `org-diary'."
21597 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21598 (let* ((org-startup-folded nil)
21599 (org-startup-align-all-tables nil)
21600 (buffer (if (file-exists-p file)
21601 (org-get-agenda-file-buffer file)
21602 (error "No such file %s" file)))
21603 arg results rtn)
21604 (if (not buffer)
21605 ;; If file does not exist, make sure an error message ends up in diary
21606 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21607 (with-current-buffer buffer
21608 (unless (org-mode-p)
21609 (error "Agenda file %s is not in `org-mode'" file))
21610 (let ((case-fold-search nil))
21611 (save-excursion
21612 (save-restriction
21613 (if org-agenda-restrict
21614 (narrow-to-region org-agenda-restrict-begin
21615 org-agenda-restrict-end)
21616 (widen))
21617 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21618 (while (setq arg (pop args))
21619 (cond
21620 ((and (eq arg :todo)
21621 (equal date (calendar-current-date)))
21622 (setq rtn (org-agenda-get-todos))
21623 (setq results (append results rtn)))
21624 ((eq arg :timestamp)
21625 (setq rtn (org-agenda-get-blocks))
21626 (setq results (append results rtn))
21627 (setq rtn (org-agenda-get-timestamps))
21628 (setq results (append results rtn)))
21629 ((eq arg :sexp)
21630 (setq rtn (org-agenda-get-sexps))
21631 (setq results (append results rtn)))
21632 ((eq arg :scheduled)
21633 (setq rtn (org-agenda-get-scheduled))
21634 (setq results (append results rtn)))
21635 ((eq arg :closed)
21636 (setq rtn (org-agenda-get-closed))
21637 (setq results (append results rtn)))
21638 ((eq arg :deadline)
21639 (setq rtn (org-agenda-get-deadlines))
21640 (setq results (append results rtn))))))))
21641 results))))
21643 (defun org-entry-is-todo-p ()
21644 (member (org-get-todo-state) org-not-done-keywords))
21646 (defun org-entry-is-done-p ()
21647 (member (org-get-todo-state) org-done-keywords))
21649 (defun org-get-todo-state ()
21650 (save-excursion
21651 (org-back-to-heading t)
21652 (and (looking-at org-todo-line-regexp)
21653 (match-end 2)
21654 (match-string 2))))
21656 (defun org-at-date-range-p (&optional inactive-ok)
21657 "Is the cursor inside a date range?"
21658 (interactive)
21659 (save-excursion
21660 (catch 'exit
21661 (let ((pos (point)))
21662 (skip-chars-backward "^[<\r\n")
21663 (skip-chars-backward "<[")
21664 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21665 (>= (match-end 0) pos)
21666 (throw 'exit t))
21667 (skip-chars-backward "^<[\r\n")
21668 (skip-chars-backward "<[")
21669 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21670 (>= (match-end 0) pos)
21671 (throw 'exit t)))
21672 nil)))
21674 (defun org-agenda-get-todos ()
21675 "Return the TODO information for agenda display."
21676 (let* ((props (list 'face nil
21677 'done-face 'org-done
21678 'org-not-done-regexp org-not-done-regexp
21679 'org-todo-regexp org-todo-regexp
21680 'mouse-face 'highlight
21681 'keymap org-agenda-keymap
21682 'help-echo
21683 (format "mouse-2 or RET jump to org file %s"
21684 (abbreviate-file-name buffer-file-name))))
21685 ;; FIXME: get rid of the \n at some point but watch out
21686 (regexp (concat "^\\*+[ \t]+\\("
21687 (if org-select-this-todo-keyword
21688 (if (equal org-select-this-todo-keyword "*")
21689 org-todo-regexp
21690 (concat "\\<\\("
21691 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21692 "\\)\\>"))
21693 org-not-done-regexp)
21694 "[^\n\r]*\\)"))
21695 marker priority category tags
21696 ee txt beg end)
21697 (goto-char (point-min))
21698 (while (re-search-forward regexp nil t)
21699 (catch :skip
21700 (save-match-data
21701 (beginning-of-line)
21702 (setq beg (point) end (progn (outline-next-heading) (point)))
21703 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21704 (re-search-forward org-ts-regexp end t))
21705 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21706 (re-search-forward org-scheduled-time-regexp end t))
21707 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21708 (re-search-forward org-deadline-time-regexp end t)
21709 (org-deadline-close (match-string 1))))
21710 (goto-char (1+ beg))
21711 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21712 (throw :skip nil)))
21713 (goto-char beg)
21714 (org-agenda-skip)
21715 (goto-char (match-beginning 1))
21716 (setq marker (org-agenda-new-marker (match-beginning 0))
21717 category (org-get-category)
21718 tags (org-get-tags-at (point))
21719 txt (org-format-agenda-item "" (match-string 1) category tags)
21720 priority (1+ (org-get-priority txt)))
21721 (org-add-props txt props
21722 'org-marker marker 'org-hd-marker marker
21723 'priority priority 'org-category category
21724 'type "todo")
21725 (push txt ee)
21726 (if org-agenda-todo-list-sublevels
21727 (goto-char (match-end 1))
21728 (org-end-of-subtree 'invisible))))
21729 (nreverse ee)))
21731 (defconst org-agenda-no-heading-message
21732 "No heading for this item in buffer or region.")
21734 (defun org-agenda-get-timestamps ()
21735 "Return the date stamp information for agenda display."
21736 (let* ((props (list 'face nil
21737 'org-not-done-regexp org-not-done-regexp
21738 'org-todo-regexp org-todo-regexp
21739 'mouse-face 'highlight
21740 'keymap org-agenda-keymap
21741 'help-echo
21742 (format "mouse-2 or RET jump to org file %s"
21743 (abbreviate-file-name buffer-file-name))))
21744 (d1 (calendar-absolute-from-gregorian date))
21745 (remove-re
21746 (concat
21747 (regexp-quote
21748 (format-time-string
21749 "<%Y-%m-%d"
21750 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21751 ".*?>"))
21752 (regexp
21753 (concat
21754 (regexp-quote
21755 (substring
21756 (format-time-string
21757 (car org-time-stamp-formats)
21758 (apply 'encode-time ; DATE bound by calendar
21759 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21760 0 11))
21761 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21762 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21763 marker hdmarker deadlinep scheduledp donep tmp priority category
21764 ee txt timestr tags b0 b3 e3 head)
21765 (goto-char (point-min))
21766 (while (re-search-forward regexp nil t)
21767 (setq b0 (match-beginning 0)
21768 b3 (match-beginning 3) e3 (match-end 3))
21769 (catch :skip
21770 (and (org-at-date-range-p) (throw :skip nil))
21771 (org-agenda-skip)
21772 (if (and (match-end 1)
21773 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21774 (throw :skip nil))
21775 (if (and e3
21776 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21777 (throw :skip nil))
21778 (setq marker (org-agenda-new-marker b0)
21779 category (org-get-category b0)
21780 tmp (buffer-substring (max (point-min)
21781 (- b0 org-ds-keyword-length))
21783 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21784 deadlinep (string-match org-deadline-regexp tmp)
21785 scheduledp (string-match org-scheduled-regexp tmp)
21786 donep (org-entry-is-done-p))
21787 (if (or scheduledp deadlinep) (throw :skip t))
21788 (if (string-match ">" timestr)
21789 ;; substring should only run to end of time stamp
21790 (setq timestr (substring timestr 0 (match-end 0))))
21791 (save-excursion
21792 (if (re-search-backward "^\\*+ " nil t)
21793 (progn
21794 (goto-char (match-beginning 0))
21795 (setq hdmarker (org-agenda-new-marker)
21796 tags (org-get-tags-at))
21797 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21798 (setq head (match-string 1))
21799 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21800 (setq txt (org-format-agenda-item
21801 nil head category tags timestr nil
21802 remove-re)))
21803 (setq txt org-agenda-no-heading-message))
21804 (setq priority (org-get-priority txt))
21805 (org-add-props txt props
21806 'org-marker marker 'org-hd-marker hdmarker)
21807 (org-add-props txt nil 'priority priority
21808 'org-category category 'date date
21809 'type "timestamp")
21810 (push txt ee))
21811 (outline-next-heading)))
21812 (nreverse ee)))
21814 (defun org-agenda-get-sexps ()
21815 "Return the sexp information for agenda display."
21816 (require 'diary-lib)
21817 (let* ((props (list 'face nil
21818 'mouse-face 'highlight
21819 'keymap org-agenda-keymap
21820 'help-echo
21821 (format "mouse-2 or RET jump to org file %s"
21822 (abbreviate-file-name buffer-file-name))))
21823 (regexp "^&?%%(")
21824 marker category ee txt tags entry result beg b sexp sexp-entry)
21825 (goto-char (point-min))
21826 (while (re-search-forward regexp nil t)
21827 (catch :skip
21828 (org-agenda-skip)
21829 (setq beg (match-beginning 0))
21830 (goto-char (1- (match-end 0)))
21831 (setq b (point))
21832 (forward-sexp 1)
21833 (setq sexp (buffer-substring b (point)))
21834 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21835 (org-trim (match-string 1))
21836 ""))
21837 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21838 (when result
21839 (setq marker (org-agenda-new-marker beg)
21840 category (org-get-category beg))
21842 (if (string-match "\\S-" result)
21843 (setq txt result)
21844 (setq txt "SEXP entry returned empty string"))
21846 (setq txt (org-format-agenda-item
21847 "" txt category tags 'time))
21848 (org-add-props txt props 'org-marker marker)
21849 (org-add-props txt nil
21850 'org-category category 'date date
21851 'type "sexp")
21852 (push txt ee))))
21853 (nreverse ee)))
21855 (defun org-agenda-get-closed ()
21856 "Return the logged TODO entries for agenda display."
21857 (let* ((props (list 'mouse-face 'highlight
21858 'org-not-done-regexp org-not-done-regexp
21859 'org-todo-regexp org-todo-regexp
21860 'keymap org-agenda-keymap
21861 'help-echo
21862 (format "mouse-2 or RET jump to org file %s"
21863 (abbreviate-file-name buffer-file-name))))
21864 (regexp (concat
21865 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21866 (regexp-quote
21867 (substring
21868 (format-time-string
21869 (car org-time-stamp-formats)
21870 (apply 'encode-time ; DATE bound by calendar
21871 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21872 1 11))))
21873 marker hdmarker priority category tags closedp
21874 ee txt timestr)
21875 (goto-char (point-min))
21876 (while (re-search-forward regexp nil t)
21877 (catch :skip
21878 (org-agenda-skip)
21879 (setq marker (org-agenda-new-marker (match-beginning 0))
21880 closedp (equal (match-string 1) org-closed-string)
21881 category (org-get-category (match-beginning 0))
21882 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21883 ;; donep (org-entry-is-done-p)
21885 (if (string-match "\\]" timestr)
21886 ;; substring should only run to end of time stamp
21887 (setq timestr (substring timestr 0 (match-end 0))))
21888 (save-excursion
21889 (if (re-search-backward "^\\*+ " nil t)
21890 (progn
21891 (goto-char (match-beginning 0))
21892 (setq hdmarker (org-agenda-new-marker)
21893 tags (org-get-tags-at))
21894 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21895 (setq txt (org-format-agenda-item
21896 (if closedp "Closed: " "Clocked: ")
21897 (match-string 1) category tags timestr)))
21898 (setq txt org-agenda-no-heading-message))
21899 (setq priority 100000)
21900 (org-add-props txt props
21901 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21902 'priority priority 'org-category category
21903 'type "closed" 'date date
21904 'undone-face 'org-warning 'done-face 'org-done)
21905 (push txt ee))
21906 (goto-char (point-at-eol))))
21907 (nreverse ee)))
21909 (defun org-agenda-get-deadlines ()
21910 "Return the deadline information for agenda display."
21911 (let* ((props (list 'mouse-face 'highlight
21912 'org-not-done-regexp org-not-done-regexp
21913 'org-todo-regexp org-todo-regexp
21914 'keymap org-agenda-keymap
21915 'help-echo
21916 (format "mouse-2 or RET jump to org file %s"
21917 (abbreviate-file-name buffer-file-name))))
21918 (regexp org-deadline-time-regexp)
21919 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21920 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21921 d2 diff dfrac wdays pos pos1 category tags
21922 ee txt head face s upcomingp donep timestr)
21923 (goto-char (point-min))
21924 (while (re-search-forward regexp nil t)
21925 (catch :skip
21926 (org-agenda-skip)
21927 (setq s (match-string 1)
21928 pos (1- (match-beginning 1))
21929 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21930 diff (- d2 d1)
21931 wdays (org-get-wdays s)
21932 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21933 upcomingp (and todayp (> diff 0)))
21934 ;; When to show a deadline in the calendar:
21935 ;; If the expiration is within wdays warning time.
21936 ;; Past-due deadlines are only shown on the current date
21937 (if (or (and (<= diff wdays)
21938 (and todayp (not org-agenda-only-exact-dates)))
21939 (= diff 0))
21940 (save-excursion
21941 (setq category (org-get-category))
21942 (if (re-search-backward "^\\*+[ \t]+" nil t)
21943 (progn
21944 (goto-char (match-end 0))
21945 (setq pos1 (match-beginning 0))
21946 (setq tags (org-get-tags-at pos1))
21947 (setq head (buffer-substring-no-properties
21948 (point)
21949 (progn (skip-chars-forward "^\r\n")
21950 (point))))
21951 (setq donep (string-match org-looking-at-done-regexp head))
21952 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21953 (setq timestr
21954 (concat (substring s (match-beginning 1)) " "))
21955 (setq timestr 'time))
21956 (if (and donep
21957 (or org-agenda-skip-deadline-if-done
21958 (not (= diff 0))))
21959 (setq txt nil)
21960 (setq txt (org-format-agenda-item
21961 (if (= diff 0)
21962 (car org-agenda-deadline-leaders)
21963 (format (nth 1 org-agenda-deadline-leaders)
21964 diff))
21965 head category tags timestr))))
21966 (setq txt org-agenda-no-heading-message))
21967 (when txt
21968 (setq face (org-agenda-deadline-face dfrac wdays))
21969 (org-add-props txt props
21970 'org-marker (org-agenda-new-marker pos)
21971 'org-hd-marker (org-agenda-new-marker pos1)
21972 'priority (+ (- diff)
21973 (org-get-priority txt))
21974 'org-category category
21975 'type (if upcomingp "upcoming-deadline" "deadline")
21976 'date (if upcomingp date d2)
21977 'face (if donep 'org-done face)
21978 'undone-face face 'done-face 'org-done)
21979 (push txt ee))))))
21980 (nreverse ee)))
21982 (defun org-agenda-deadline-face (fraction &optional wdays)
21983 "Return the face to displaying a deadline item.
21984 FRACTION is what fraction of the head-warning time has passed."
21985 (if (equal wdays 0) (setq fraction 1.))
21986 (let ((faces org-agenda-deadline-faces) f)
21987 (catch 'exit
21988 (while (setq f (pop faces))
21989 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21991 (defun org-agenda-get-scheduled ()
21992 "Return the scheduled information for agenda display."
21993 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21994 'org-todo-regexp org-todo-regexp
21995 'done-face 'org-done
21996 'mouse-face 'highlight
21997 'keymap org-agenda-keymap
21998 'help-echo
21999 (format "mouse-2 or RET jump to org file %s"
22000 (abbreviate-file-name buffer-file-name))))
22001 (regexp org-scheduled-time-regexp)
22002 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22003 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22004 d2 diff pos pos1 category tags
22005 ee txt head pastschedp donep face timestr s)
22006 (goto-char (point-min))
22007 (while (re-search-forward regexp nil t)
22008 (catch :skip
22009 (org-agenda-skip)
22010 (setq s (match-string 1)
22011 pos (1- (match-beginning 1))
22012 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22013 ;;; is this right?
22014 ;;; do we need to do this for deadleine too????
22015 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
22016 diff (- d2 d1))
22017 (setq pastschedp (and todayp (< diff 0)))
22018 ;; When to show a scheduled item in the calendar:
22019 ;; If it is on or past the date.
22020 (if (or (and (< diff 0)
22021 (and todayp (not org-agenda-only-exact-dates)))
22022 (= diff 0))
22023 (save-excursion
22024 (setq category (org-get-category))
22025 (if (re-search-backward "^\\*+[ \t]+" nil t)
22026 (progn
22027 (goto-char (match-end 0))
22028 (setq pos1 (match-beginning 0))
22029 (setq tags (org-get-tags-at))
22030 (setq head (buffer-substring-no-properties
22031 (point)
22032 (progn (skip-chars-forward "^\r\n") (point))))
22033 (setq donep (string-match org-looking-at-done-regexp head))
22034 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22035 (setq timestr
22036 (concat (substring s (match-beginning 1)) " "))
22037 (setq timestr 'time))
22038 (if (and donep
22039 (or org-agenda-skip-scheduled-if-done
22040 (not (= diff 0))))
22041 (setq txt nil)
22042 (setq txt (org-format-agenda-item
22043 (if (= diff 0)
22044 (car org-agenda-scheduled-leaders)
22045 (format (nth 1 org-agenda-scheduled-leaders)
22046 (- 1 diff)))
22047 head category tags timestr))))
22048 (setq txt org-agenda-no-heading-message))
22049 (when txt
22050 (setq face (if pastschedp
22051 'org-scheduled-previously
22052 'org-scheduled-today))
22053 (org-add-props txt props
22054 'undone-face face
22055 'face (if donep 'org-done face)
22056 'org-marker (org-agenda-new-marker pos)
22057 'org-hd-marker (org-agenda-new-marker pos1)
22058 'type (if pastschedp "past-scheduled" "scheduled")
22059 'date (if pastschedp d2 date)
22060 'priority (+ 94 (- 5 diff) (org-get-priority txt))
22061 'org-category category)
22062 (push txt ee))))))
22063 (nreverse ee)))
22065 (defun org-agenda-get-blocks ()
22066 "Return the date-range information for agenda display."
22067 (let* ((props (list 'face nil
22068 'org-not-done-regexp org-not-done-regexp
22069 'org-todo-regexp org-todo-regexp
22070 'mouse-face 'highlight
22071 'keymap org-agenda-keymap
22072 'help-echo
22073 (format "mouse-2 or RET jump to org file %s"
22074 (abbreviate-file-name buffer-file-name))))
22075 (regexp org-tr-regexp)
22076 (d0 (calendar-absolute-from-gregorian date))
22077 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
22078 donep head)
22079 (goto-char (point-min))
22080 (while (re-search-forward regexp nil t)
22081 (catch :skip
22082 (org-agenda-skip)
22083 (setq pos (point))
22084 (setq timestr (match-string 0)
22085 s1 (match-string 1)
22086 s2 (match-string 2)
22087 d1 (time-to-days (org-time-string-to-time s1))
22088 d2 (time-to-days (org-time-string-to-time s2)))
22089 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
22090 ;; Only allow days between the limits, because the normal
22091 ;; date stamps will catch the limits.
22092 (save-excursion
22093 (setq marker (org-agenda-new-marker (point)))
22094 (setq category (org-get-category))
22095 (if (re-search-backward "^\\*+ " nil t)
22096 (progn
22097 (goto-char (match-beginning 0))
22098 (setq hdmarker (org-agenda-new-marker (point)))
22099 (setq tags (org-get-tags-at))
22100 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22101 (setq head (match-string 1))
22102 (and org-agenda-skip-timestamp-if-done
22103 (org-entry-is-done-p)
22104 (throw :skip t))
22105 (setq txt (org-format-agenda-item
22106 (format (if (= d1 d2) "" "(%d/%d): ")
22107 (1+ (- d0 d1)) (1+ (- d2 d1)))
22108 head category tags
22109 (if (= d0 d1) timestr))))
22110 (setq txt org-agenda-no-heading-message))
22111 (org-add-props txt props
22112 'org-marker marker 'org-hd-marker hdmarker
22113 'type "block" 'date date
22114 'priority (org-get-priority txt) 'org-category category)
22115 (push txt ee)))
22116 (goto-char pos)))
22117 ;; Sort the entries by expiration date.
22118 (nreverse ee)))
22120 ;;; Agenda presentation and sorting
22122 (defconst org-plain-time-of-day-regexp
22123 (concat
22124 "\\(\\<[012]?[0-9]"
22125 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22126 "\\(--?"
22127 "\\(\\<[012]?[0-9]"
22128 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22129 "\\)?")
22130 "Regular expression to match a plain time or time range.
22131 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22132 groups carry important information:
22133 0 the full match
22134 1 the first time, range or not
22135 8 the second time, if it is a range.")
22137 (defconst org-plain-time-extension-regexp
22138 (concat
22139 "\\(\\<[012]?[0-9]"
22140 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22141 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22142 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22143 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22144 groups carry important information:
22145 0 the full match
22146 7 hours of duration
22147 9 minutes of duration")
22149 (defconst org-stamp-time-of-day-regexp
22150 (concat
22151 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22152 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22153 "\\(--?"
22154 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22155 "Regular expression to match a timestamp time or time range.
22156 After a match, the following groups carry important information:
22157 0 the full match
22158 1 date plus weekday, for backreferencing to make sure both times on same day
22159 2 the first time, range or not
22160 4 the second time, if it is a range.")
22162 (defvar org-prefix-has-time nil
22163 "A flag, set by `org-compile-prefix-format'.
22164 The flag is set if the currently compiled format contains a `%t'.")
22165 (defvar org-prefix-has-tag nil
22166 "A flag, set by `org-compile-prefix-format'.
22167 The flag is set if the currently compiled format contains a `%T'.")
22169 (defun org-format-agenda-item (extra txt &optional category tags dotime
22170 noprefix remove-re)
22171 "Format TXT to be inserted into the agenda buffer.
22172 In particular, it adds the prefix and corresponding text properties. EXTRA
22173 must be a string and replaces the `%s' specifier in the prefix format.
22174 CATEGORY (string, symbol or nil) may be used to overrule the default
22175 category taken from local variable or file name. It will replace the `%c'
22176 specifier in the format. DOTIME, when non-nil, indicates that a
22177 time-of-day should be extracted from TXT for sorting of this entry, and for
22178 the `%t' specifier in the format. When DOTIME is a string, this string is
22179 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22180 only the correctly processes TXT should be returned - this is used by
22181 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22182 Any match of REMOVE-RE will be removed from TXT."
22183 (save-match-data
22184 ;; Diary entries sometimes have extra whitespace at the beginning
22185 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22186 (let* ((category (or category
22187 org-category
22188 (if buffer-file-name
22189 (file-name-sans-extension
22190 (file-name-nondirectory buffer-file-name))
22191 "")))
22192 (tag (if tags (nth (1- (length tags)) tags) ""))
22193 time ; time and tag are needed for the eval of the prefix format
22194 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22195 (time-of-day (and dotime (org-get-time-of-day ts)))
22196 stamp plain s0 s1 s2 rtn srp)
22197 (when (and dotime time-of-day org-prefix-has-time)
22198 ;; Extract starting and ending time and move them to prefix
22199 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22200 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22201 (setq s0 (match-string 0 ts)
22202 srp (and stamp (match-end 3))
22203 s1 (match-string (if plain 1 2) ts)
22204 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22206 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22207 ;; them, we might want to remove them there to avoid duplication.
22208 ;; The user can turn this off with a variable.
22209 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22210 (string-match (concat (regexp-quote s0) " *") txt)
22211 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22212 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22213 (= (match-beginning 0) 0)
22215 (setq txt (replace-match "" nil nil txt))))
22216 ;; Normalize the time(s) to 24 hour
22217 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22218 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22220 (when (and s1 (not s2) org-agenda-default-appointment-duration
22221 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22222 (let ((m (+ (string-to-number (match-string 2 s1))
22223 (* 60 (string-to-number (match-string 1 s1)))
22224 org-agenda-default-appointment-duration))
22226 (setq h (/ m 60) m (- m (* h 60)))
22227 (setq s2 (format "%02d:%02d" h m))))
22229 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22230 txt)
22231 ;; Tags are in the string
22232 (if (or (eq org-agenda-remove-tags t)
22233 (and org-agenda-remove-tags
22234 org-prefix-has-tag))
22235 (setq txt (replace-match "" t t txt))
22236 (setq txt (replace-match
22237 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22238 (match-string 2 txt))
22239 t t txt))))
22241 (when remove-re
22242 (while (string-match remove-re txt)
22243 (setq txt (replace-match "" t t txt))))
22245 ;; Create the final string
22246 (if noprefix
22247 (setq rtn txt)
22248 ;; Prepare the variables needed in the eval of the compiled format
22249 (setq time (cond (s2 (concat s1 "-" s2))
22250 (s1 (concat s1 "......"))
22251 (t ""))
22252 extra (or extra "")
22253 category (if (symbolp category) (symbol-name category) category))
22254 ;; Evaluate the compiled format
22255 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22257 ;; And finally add the text properties
22258 (org-add-props rtn nil
22259 'org-category (downcase category) 'tags tags
22260 'org-highest-priority org-highest-priority
22261 'org-lowest-priority org-lowest-priority
22262 'prefix-length (- (length rtn) (length txt))
22263 'time-of-day time-of-day
22264 'txt txt
22265 'time time
22266 'extra extra
22267 'dotime dotime))))
22269 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22270 (defvar org-agenda-sorting-strategy-selected nil)
22272 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22273 (catch 'exit
22274 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22275 ((and todayp (member 'today (car org-agenda-time-grid))))
22276 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22277 ((member 'weekly (car org-agenda-time-grid)))
22278 (t (throw 'exit list)))
22279 (let* ((have (delq nil (mapcar
22280 (lambda (x) (get-text-property 1 'time-of-day x))
22281 list)))
22282 (string (nth 1 org-agenda-time-grid))
22283 (gridtimes (nth 2 org-agenda-time-grid))
22284 (req (car org-agenda-time-grid))
22285 (remove (member 'remove-match req))
22286 new time)
22287 (if (and (member 'require-timed req) (not have))
22288 ;; don't show empty grid
22289 (throw 'exit list))
22290 (while (setq time (pop gridtimes))
22291 (unless (and remove (member time have))
22292 (setq time (int-to-string time))
22293 (push (org-format-agenda-item
22294 nil string "" nil
22295 (concat (substring time 0 -2) ":" (substring time -2)))
22296 new)
22297 (put-text-property
22298 1 (length (car new)) 'face 'org-time-grid (car new))))
22299 (if (member 'time-up org-agenda-sorting-strategy-selected)
22300 (append new list)
22301 (append list new)))))
22303 (defun org-compile-prefix-format (key)
22304 "Compile the prefix format into a Lisp form that can be evaluated.
22305 The resulting form is returned and stored in the variable
22306 `org-prefix-format-compiled'."
22307 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22308 (let ((s (cond
22309 ((stringp org-agenda-prefix-format)
22310 org-agenda-prefix-format)
22311 ((assq key org-agenda-prefix-format)
22312 (cdr (assq key org-agenda-prefix-format)))
22313 (t " %-12:c%?-12t% s")))
22314 (start 0)
22315 varform vars var e c f opt)
22316 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22317 s start)
22318 (setq var (cdr (assoc (match-string 4 s)
22319 '(("c" . category) ("t" . time) ("s" . extra)
22320 ("T" . tag))))
22321 c (or (match-string 3 s) "")
22322 opt (match-beginning 1)
22323 start (1+ (match-beginning 0)))
22324 (if (equal var 'time) (setq org-prefix-has-time t))
22325 (if (equal var 'tag) (setq org-prefix-has-tag t))
22326 (setq f (concat "%" (match-string 2 s) "s"))
22327 (if opt
22328 (setq varform
22329 `(if (equal "" ,var)
22331 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22332 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22333 (setq s (replace-match "%s" t nil s))
22334 (push varform vars))
22335 (setq vars (nreverse vars))
22336 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22338 (defun org-set-sorting-strategy (key)
22339 (if (symbolp (car org-agenda-sorting-strategy))
22340 ;; the old format
22341 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22342 (setq org-agenda-sorting-strategy-selected
22343 (or (cdr (assq key org-agenda-sorting-strategy))
22344 (cdr (assq 'agenda org-agenda-sorting-strategy))
22345 '(time-up category-keep priority-down)))))
22347 (defun org-get-time-of-day (s &optional string mod24)
22348 "Check string S for a time of day.
22349 If found, return it as a military time number between 0 and 2400.
22350 If not found, return nil.
22351 The optional STRING argument forces conversion into a 5 character wide string
22352 HH:MM."
22353 (save-match-data
22354 (when
22355 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22356 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22357 (let* ((h (string-to-number (match-string 1 s)))
22358 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22359 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22360 (am-p (equal ampm "am"))
22361 (h1 (cond ((not ampm) h)
22362 ((= h 12) (if am-p 0 12))
22363 (t (+ h (if am-p 0 12)))))
22364 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22365 (mod h1 24) h1))
22366 (t0 (+ (* 100 h2) m))
22367 (t1 (concat (if (>= h1 24) "+" " ")
22368 (if (< t0 100) "0" "")
22369 (if (< t0 10) "0" "")
22370 (int-to-string t0))))
22371 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22373 (defun org-finalize-agenda-entries (list &optional nosort)
22374 "Sort and concatenate the agenda items."
22375 (setq list (mapcar 'org-agenda-highlight-todo list))
22376 (if nosort
22377 list
22378 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22380 (defun org-agenda-highlight-todo (x)
22381 (let (re pl)
22382 (if (eq x 'line)
22383 (save-excursion
22384 (beginning-of-line 1)
22385 (setq re (get-text-property (point) 'org-todo-regexp))
22386 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22387 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22388 (add-text-properties (match-beginning 0) (match-end 0)
22389 (list 'face (org-get-todo-face 0)))
22390 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22391 (delete-region (match-beginning 1) (1- (match-end 0)))
22392 (goto-char (match-beginning 1))
22393 (insert (format org-agenda-todo-keyword-format s)))))
22394 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22395 pl (get-text-property 0 'prefix-length x))
22396 (when (and re
22397 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22398 x (or pl 0)) pl))
22399 (add-text-properties
22400 (or (match-end 1) (match-end 0)) (match-end 0)
22401 (list 'face (org-get-todo-face (match-string 2 x)))
22403 (setq x (concat (substring x 0 (match-end 1))
22404 (format org-agenda-todo-keyword-format
22405 (match-string 2 x))
22407 (substring x (match-end 3)))))
22408 x)))
22410 (defsubst org-cmp-priority (a b)
22411 "Compare the priorities of string A and B."
22412 (let ((pa (or (get-text-property 1 'priority a) 0))
22413 (pb (or (get-text-property 1 'priority b) 0)))
22414 (cond ((> pa pb) +1)
22415 ((< pa pb) -1)
22416 (t nil))))
22418 (defsubst org-cmp-category (a b)
22419 "Compare the string values of categories of strings A and B."
22420 (let ((ca (or (get-text-property 1 'org-category a) ""))
22421 (cb (or (get-text-property 1 'org-category b) "")))
22422 (cond ((string-lessp ca cb) -1)
22423 ((string-lessp cb ca) +1)
22424 (t nil))))
22426 (defsubst org-cmp-tag (a b)
22427 "Compare the string values of categories of strings A and B."
22428 (let ((ta (car (last (get-text-property 1 'tags a))))
22429 (tb (car (last (get-text-property 1 'tags b)))))
22430 (cond ((not ta) +1)
22431 ((not tb) -1)
22432 ((string-lessp ta tb) -1)
22433 ((string-lessp tb ta) +1)
22434 (t nil))))
22436 (defsubst org-cmp-time (a b)
22437 "Compare the time-of-day values of strings A and B."
22438 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22439 (ta (or (get-text-property 1 'time-of-day a) def))
22440 (tb (or (get-text-property 1 'time-of-day b) def)))
22441 (cond ((< ta tb) -1)
22442 ((< tb ta) +1)
22443 (t nil))))
22445 (defun org-entries-lessp (a b)
22446 "Predicate for sorting agenda entries."
22447 ;; The following variables will be used when the form is evaluated.
22448 ;; So even though the compiler complains, keep them.
22449 (let* ((time-up (org-cmp-time a b))
22450 (time-down (if time-up (- time-up) nil))
22451 (priority-up (org-cmp-priority a b))
22452 (priority-down (if priority-up (- priority-up) nil))
22453 (category-up (org-cmp-category a b))
22454 (category-down (if category-up (- category-up) nil))
22455 (category-keep (if category-up +1 nil))
22456 (tag-up (org-cmp-tag a b))
22457 (tag-down (if tag-up (- tag-up) nil)))
22458 (cdr (assoc
22459 (eval (cons 'or org-agenda-sorting-strategy-selected))
22460 '((-1 . t) (1 . nil) (nil . nil))))))
22462 ;;; Agenda restriction lock
22464 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22465 "Overlay to mark the headline to which arenda commands are restricted.")
22466 (org-overlay-put org-agenda-restriction-lock-overlay
22467 'face 'org-agenda-restriction-lock)
22468 (org-overlay-put org-agenda-restriction-lock-overlay
22469 'help-echo "Agendas are currently limited to this subtree.")
22470 (org-detach-overlay org-agenda-restriction-lock-overlay)
22471 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22472 "Overlay marking the agenda restriction line in speedbar.")
22473 (org-overlay-put org-speedbar-restriction-lock-overlay
22474 'face 'org-agenda-restriction-lock)
22475 (org-overlay-put org-speedbar-restriction-lock-overlay
22476 'help-echo "Agendas are currently limited to this item.")
22477 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22479 (defun org-agenda-set-restriction-lock (&optional type)
22480 "Set restriction lock for agenda, to current subtree or file.
22481 Restriction will be the file if TYPE is `file', or if type is the
22482 universal prefix '(4), or if the cursor is before the first headline
22483 in the file. Otherwise, restriction will be to the current subtree."
22484 (interactive "P")
22485 (and (equal type '(4)) (setq type 'file))
22486 (setq type (cond
22487 (type type)
22488 ((org-at-heading-p) 'subtree)
22489 ((condition-case nil (org-back-to-heading t) (error nil))
22490 'subtree)
22491 (t 'file)))
22492 (if (eq type 'subtree)
22493 (progn
22494 (setq org-agenda-restrict t)
22495 (setq org-agenda-overriding-restriction 'subtree)
22496 (put 'org-agenda-files 'org-restrict
22497 (list (buffer-file-name (buffer-base-buffer))))
22498 (org-back-to-heading t)
22499 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22500 (move-marker org-agenda-restrict-begin (point))
22501 (move-marker org-agenda-restrict-end
22502 (save-excursion (org-end-of-subtree t)))
22503 (message "Locking agenda restriction to subtree"))
22504 (put 'org-agenda-files 'org-restrict
22505 (list (buffer-file-name (buffer-base-buffer))))
22506 (setq org-agenda-restrict nil)
22507 (setq org-agenda-overriding-restriction 'file)
22508 (move-marker org-agenda-restrict-begin nil)
22509 (move-marker org-agenda-restrict-end nil)
22510 (message "Locking agenda restriction to file"))
22511 (setq current-prefix-arg nil)
22512 (org-agenda-maybe-redo))
22514 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22515 "Remove the agenda restriction lock."
22516 (interactive "P")
22517 (org-detach-overlay org-agenda-restriction-lock-overlay)
22518 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22519 (setq org-agenda-overriding-restriction nil)
22520 (setq org-agenda-restrict nil)
22521 (put 'org-agenda-files 'org-restrict nil)
22522 (move-marker org-agenda-restrict-begin nil)
22523 (move-marker org-agenda-restrict-end nil)
22524 (setq current-prefix-arg nil)
22525 (message "Agenda restriction lock removed")
22526 (or noupdate (org-agenda-maybe-redo)))
22528 (defun org-agenda-maybe-redo ()
22529 "If there is any window showing the agenda view, update it."
22530 (let ((w (get-buffer-window org-agenda-buffer-name t))
22531 (w0 (selected-window)))
22532 (when w
22533 (select-window w)
22534 (org-agenda-redo)
22535 (select-window w0)
22536 (if org-agenda-overriding-restriction
22537 (message "Agenda view shifted to new %s restriction"
22538 org-agenda-overriding-restriction)
22539 (message "Agenda restriction lock removed")))))
22541 ;;; Agenda commands
22543 (defun org-agenda-check-type (error &rest types)
22544 "Check if agenda buffer is of allowed type.
22545 If ERROR is non-nil, throw an error, otherwise just return nil."
22546 (if (memq org-agenda-type types)
22548 (if error
22549 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22550 nil)))
22552 (defun org-agenda-quit ()
22553 "Exit agenda by removing the window or the buffer."
22554 (interactive)
22555 (let ((buf (current-buffer)))
22556 (if (not (one-window-p)) (delete-window))
22557 (kill-buffer buf)
22558 (org-agenda-reset-markers)
22559 (org-columns-remove-overlays))
22560 ;; Maybe restore the pre-agenda window configuration.
22561 (and org-agenda-restore-windows-after-quit
22562 (not (eq org-agenda-window-setup 'other-frame))
22563 org-pre-agenda-window-conf
22564 (set-window-configuration org-pre-agenda-window-conf)))
22566 (defun org-agenda-exit ()
22567 "Exit agenda by removing the window or the buffer.
22568 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22569 Org-mode buffers visited directly by the user will not be touched."
22570 (interactive)
22571 (org-release-buffers org-agenda-new-buffers)
22572 (setq org-agenda-new-buffers nil)
22573 (org-agenda-quit))
22575 (defun org-agenda-execute (arg)
22576 "Execute another agenda command, keeping same window.\\<global-map>
22577 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22578 (interactive "P")
22579 (let ((org-agenda-window-setup 'current-window))
22580 (org-agenda arg)))
22582 (defun org-save-all-org-buffers ()
22583 "Save all Org-mode buffers without user confirmation."
22584 (interactive)
22585 (message "Saving all Org-mode buffers...")
22586 (save-some-buffers t 'org-mode-p)
22587 (message "Saving all Org-mode buffers... done"))
22589 (defun org-agenda-redo ()
22590 "Rebuild Agenda.
22591 When this is the global TODO list, a prefix argument will be interpreted."
22592 (interactive)
22593 (let* ((org-agenda-keep-modes t)
22594 (line (org-current-line))
22595 (window-line (- line (org-current-line (window-start))))
22596 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22597 (message "Rebuilding agenda buffer...")
22598 (org-let lprops '(eval org-agenda-redo-command))
22599 (setq org-agenda-undo-list nil
22600 org-agenda-pending-undo-list nil)
22601 (message "Rebuilding agenda buffer...done")
22602 (goto-line line)
22603 (recenter window-line)))
22605 (defun org-agenda-manipulate-query-add ()
22606 "Manipulate the query by adding a search term with positive selection.
22607 Positive selection means, the term must be matched for selection of an entry."
22608 (interactive)
22609 (org-agenda-manipulate-query ?\[))
22610 (defun org-agenda-manipulate-query-subtract ()
22611 "Manipulate the query by adding a search term with negative selection.
22612 Negative selection means, term must not be matched for selection of an entry."
22613 (interactive)
22614 (org-agenda-manipulate-query ?\]))
22615 (defun org-agenda-manipulate-query-add-re ()
22616 "Manipulate the query by adding a search regexp with positive selection.
22617 Positive selection means, the regexp must match for selection of an entry."
22618 (interactive)
22619 (org-agenda-manipulate-query ?\{))
22620 (defun org-agenda-manipulate-query-subtract-re ()
22621 "Manipulate the query by adding a search regexp with negative selection.
22622 Negative selection means, regexp must not match for selection of an entry."
22623 (interactive)
22624 (org-agenda-manipulate-query ?\}))
22625 (defun org-agenda-manipulate-query (char)
22626 (cond
22627 ((eq org-agenda-type 'search)
22628 (org-add-to-string
22629 'org-agenda-query-string
22630 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22631 (?\{ . " +{}") (?\} . " -{}")))))
22632 (setq org-agenda-redo-command
22633 (list 'org-search-view
22634 (+ (length org-agenda-query-string)
22635 (if (member char '(?\{ ?\})) 0 1))
22636 org-agenda-query-string))
22637 (set-register org-agenda-query-register org-agenda-query-string)
22638 (org-agenda-redo))
22639 (t (error "Canot manipulate query for %s-type agenda buffers"
22640 org-agenda-type))))
22642 (defun org-add-to-string (var string)
22643 (set var (concat (symbol-value var) string)))
22645 (defun org-agenda-goto-date (date)
22646 "Jump to DATE in agenda."
22647 (interactive (list (org-read-date)))
22648 (org-agenda-list nil date))
22650 (defun org-agenda-goto-today ()
22651 "Go to today."
22652 (interactive)
22653 (org-agenda-check-type t 'timeline 'agenda)
22654 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22655 (cond
22656 (tdpos (goto-char tdpos))
22657 ((eq org-agenda-type 'agenda)
22658 (let* ((sd (time-to-days
22659 (time-subtract (current-time)
22660 (list 0 (* 3600 org-extend-today-until) 0))))
22661 (comp (org-agenda-compute-time-span sd org-agenda-span))
22662 (org-agenda-overriding-arguments org-agenda-last-arguments))
22663 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22664 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22665 (org-agenda-redo)
22666 (org-agenda-find-same-or-today-or-agenda)))
22667 (t (error "Cannot find today")))))
22669 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22670 (goto-char
22671 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22672 (text-property-any (point-min) (point-max) 'org-today t)
22673 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22674 (point-min))))
22676 (defun org-agenda-later (arg)
22677 "Go forward in time by thee current span.
22678 With prefix ARG, go forward that many times the current span."
22679 (interactive "p")
22680 (org-agenda-check-type t 'agenda)
22681 (let* ((span org-agenda-span)
22682 (sd org-starting-day)
22683 (greg (calendar-gregorian-from-absolute sd))
22684 (cnt (get-text-property (point) 'org-day-cnt))
22685 greg2 nd)
22686 (cond
22687 ((eq span 'day)
22688 (setq sd (+ arg sd) nd 1))
22689 ((eq span 'week)
22690 (setq sd (+ (* 7 arg) sd) nd 7))
22691 ((eq span 'month)
22692 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22693 sd (calendar-absolute-from-gregorian greg2))
22694 (setcar greg2 (1+ (car greg2)))
22695 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22696 ((eq span 'year)
22697 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22698 sd (calendar-absolute-from-gregorian greg2))
22699 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22700 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22701 (let ((org-agenda-overriding-arguments
22702 (list (car org-agenda-last-arguments) sd nd t)))
22703 (org-agenda-redo)
22704 (org-agenda-find-same-or-today-or-agenda cnt))))
22706 (defun org-agenda-earlier (arg)
22707 "Go backward in time by the current span.
22708 With prefix ARG, go backward that many times the current span."
22709 (interactive "p")
22710 (org-agenda-later (- arg)))
22712 (defun org-agenda-day-view ()
22713 "Switch to daily view for agenda."
22714 (interactive)
22715 (setq org-agenda-ndays 1)
22716 (org-agenda-change-time-span 'day))
22717 (defun org-agenda-week-view ()
22718 "Switch to daily view for agenda."
22719 (interactive)
22720 (setq org-agenda-ndays 7)
22721 (org-agenda-change-time-span 'week))
22722 (defun org-agenda-month-view ()
22723 "Switch to daily view for agenda."
22724 (interactive)
22725 (org-agenda-change-time-span 'month))
22726 (defun org-agenda-year-view ()
22727 "Switch to daily view for agenda."
22728 (interactive)
22729 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22730 (org-agenda-change-time-span 'year)
22731 (error "Abort")))
22733 (defun org-agenda-change-time-span (span)
22734 "Change the agenda view to SPAN.
22735 SPAN may be `day', `week', `month', `year'."
22736 (org-agenda-check-type t 'agenda)
22737 (if (equal org-agenda-span span)
22738 (error "Viewing span is already \"%s\"" span))
22739 (let* ((sd (or (get-text-property (point) 'day)
22740 org-starting-day))
22741 (computed (org-agenda-compute-time-span sd span))
22742 (org-agenda-overriding-arguments
22743 (list (car org-agenda-last-arguments)
22744 (car computed) (cdr computed) t)))
22745 (org-agenda-redo)
22746 (org-agenda-find-same-or-today-or-agenda))
22747 (org-agenda-set-mode-name)
22748 (message "Switched to %s view" span))
22750 (defun org-agenda-compute-time-span (sd span)
22751 "Compute starting date and number of days for agenda.
22752 SPAN may be `day', `week', `month', `year'. The return value
22753 is a cons cell with the starting date and the number of days,
22754 so that the date SD will be in that range."
22755 (let* ((greg (calendar-gregorian-from-absolute sd))
22757 (cond
22758 ((eq span 'day)
22759 (setq nd 1))
22760 ((eq span 'week)
22761 (let* ((nt (calendar-day-of-week
22762 (calendar-gregorian-from-absolute sd)))
22763 (d (if org-agenda-start-on-weekday
22764 (- nt org-agenda-start-on-weekday)
22765 0)))
22766 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22767 (setq nd 7)))
22768 ((eq span 'month)
22769 (setq sd (calendar-absolute-from-gregorian
22770 (list (car greg) 1 (nth 2 greg)))
22771 nd (- (calendar-absolute-from-gregorian
22772 (list (1+ (car greg)) 1 (nth 2 greg)))
22773 sd)))
22774 ((eq span 'year)
22775 (setq sd (calendar-absolute-from-gregorian
22776 (list 1 1 (nth 2 greg)))
22777 nd (- (calendar-absolute-from-gregorian
22778 (list 1 1 (1+ (nth 2 greg))))
22779 sd))))
22780 (cons sd nd)))
22782 ;; FIXME: does not work if user makes date format that starts with a blank
22783 (defun org-agenda-next-date-line (&optional arg)
22784 "Jump to the next line indicating a date in agenda buffer."
22785 (interactive "p")
22786 (org-agenda-check-type t 'agenda 'timeline)
22787 (beginning-of-line 1)
22788 (if (looking-at "^\\S-") (forward-char 1))
22789 (if (not (re-search-forward "^\\S-" nil t arg))
22790 (progn
22791 (backward-char 1)
22792 (error "No next date after this line in this buffer")))
22793 (goto-char (match-beginning 0)))
22795 (defun org-agenda-previous-date-line (&optional arg)
22796 "Jump to the previous line indicating a date in agenda buffer."
22797 (interactive "p")
22798 (org-agenda-check-type t 'agenda 'timeline)
22799 (beginning-of-line 1)
22800 (if (not (re-search-backward "^\\S-" nil t arg))
22801 (error "No previous date before this line in this buffer")))
22803 ;; Initialize the highlight
22804 (defvar org-hl (org-make-overlay 1 1))
22805 (org-overlay-put org-hl 'face 'highlight)
22807 (defun org-highlight (begin end &optional buffer)
22808 "Highlight a region with overlay."
22809 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22810 org-hl begin end (or buffer (current-buffer))))
22812 (defun org-unhighlight ()
22813 "Detach overlay INDEX."
22814 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22816 ;; FIXME this is currently not used.
22817 (defun org-highlight-until-next-command (beg end &optional buffer)
22818 (org-highlight beg end buffer)
22819 (add-hook 'pre-command-hook 'org-unhighlight-once))
22820 (defun org-unhighlight-once ()
22821 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22822 (org-unhighlight))
22824 (defun org-agenda-follow-mode ()
22825 "Toggle follow mode in an agenda buffer."
22826 (interactive)
22827 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22828 (org-agenda-set-mode-name)
22829 (message "Follow mode is %s"
22830 (if org-agenda-follow-mode "on" "off")))
22832 (defun org-agenda-log-mode ()
22833 "Toggle log mode in an agenda buffer."
22834 (interactive)
22835 (org-agenda-check-type t 'agenda 'timeline)
22836 (setq org-agenda-show-log (not org-agenda-show-log))
22837 (org-agenda-set-mode-name)
22838 (org-agenda-redo)
22839 (message "Log mode is %s"
22840 (if org-agenda-show-log "on" "off")))
22842 (defun org-agenda-toggle-diary ()
22843 "Toggle diary inclusion in an agenda buffer."
22844 (interactive)
22845 (org-agenda-check-type t 'agenda)
22846 (setq org-agenda-include-diary (not org-agenda-include-diary))
22847 (org-agenda-redo)
22848 (org-agenda-set-mode-name)
22849 (message "Diary inclusion turned %s"
22850 (if org-agenda-include-diary "on" "off")))
22852 (defun org-agenda-toggle-time-grid ()
22853 "Toggle time grid in an agenda buffer."
22854 (interactive)
22855 (org-agenda-check-type t 'agenda)
22856 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22857 (org-agenda-redo)
22858 (org-agenda-set-mode-name)
22859 (message "Time-grid turned %s"
22860 (if org-agenda-use-time-grid "on" "off")))
22862 (defun org-agenda-set-mode-name ()
22863 "Set the mode name to indicate all the small mode settings."
22864 (setq mode-name
22865 (concat "Org-Agenda"
22866 (if (equal org-agenda-ndays 1) " Day" "")
22867 (if (equal org-agenda-ndays 7) " Week" "")
22868 (if org-agenda-follow-mode " Follow" "")
22869 (if org-agenda-include-diary " Diary" "")
22870 (if org-agenda-use-time-grid " Grid" "")
22871 (if org-agenda-show-log " Log" "")))
22872 (force-mode-line-update))
22874 (defun org-agenda-post-command-hook ()
22875 (and (eolp) (not (bolp)) (backward-char 1))
22876 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22877 (if (and org-agenda-follow-mode
22878 (get-text-property (point) 'org-marker))
22879 (org-agenda-show)))
22881 (defun org-agenda-show-priority ()
22882 "Show the priority of the current item.
22883 This priority is composed of the main priority given with the [#A] cookies,
22884 and by additional input from the age of a schedules or deadline entry."
22885 (interactive)
22886 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22887 (message "Priority is %d" (if pri pri -1000))))
22889 (defun org-agenda-show-tags ()
22890 "Show the tags applicable to the current item."
22891 (interactive)
22892 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22893 (if tags
22894 (message "Tags are :%s:"
22895 (org-no-properties (mapconcat 'identity tags ":")))
22896 (message "No tags associated with this line"))))
22898 (defun org-agenda-goto (&optional highlight)
22899 "Go to the Org-mode file which contains the item at point."
22900 (interactive)
22901 (let* ((marker (or (get-text-property (point) 'org-marker)
22902 (org-agenda-error)))
22903 (buffer (marker-buffer marker))
22904 (pos (marker-position marker)))
22905 (switch-to-buffer-other-window buffer)
22906 (widen)
22907 (goto-char pos)
22908 (when (org-mode-p)
22909 (org-show-context 'agenda)
22910 (save-excursion
22911 (and (outline-next-heading)
22912 (org-flag-heading nil)))) ; show the next heading
22913 (recenter (/ (window-height) 2))
22914 (run-hooks 'org-agenda-after-show-hook)
22915 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22917 (defvar org-agenda-after-show-hook nil
22918 "Normal hook run after an item has been shown from the agenda.
22919 Point is in the buffer where the item originated.")
22921 (defun org-agenda-kill ()
22922 "Kill the entry or subtree belonging to the current agenda entry."
22923 (interactive)
22924 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22925 (let* ((marker (or (get-text-property (point) 'org-marker)
22926 (org-agenda-error)))
22927 (buffer (marker-buffer marker))
22928 (pos (marker-position marker))
22929 (type (get-text-property (point) 'type))
22930 dbeg dend (n 0) conf)
22931 (org-with-remote-undo buffer
22932 (with-current-buffer buffer
22933 (save-excursion
22934 (goto-char pos)
22935 (if (and (org-mode-p) (not (member type '("sexp"))))
22936 (setq dbeg (progn (org-back-to-heading t) (point))
22937 dend (org-end-of-subtree t t))
22938 (setq dbeg (point-at-bol)
22939 dend (min (point-max) (1+ (point-at-eol)))))
22940 (goto-char dbeg)
22941 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22942 (setq conf (or (eq t org-agenda-confirm-kill)
22943 (and (numberp org-agenda-confirm-kill)
22944 (> n org-agenda-confirm-kill))))
22945 (and conf
22946 (not (y-or-n-p
22947 (format "Delete entry with %d lines in buffer \"%s\"? "
22948 n (buffer-name buffer))))
22949 (error "Abort"))
22950 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22951 (with-current-buffer buffer (delete-region dbeg dend))
22952 (message "Agenda item and source killed"))))
22954 (defun org-agenda-archive ()
22955 "Kill the entry or subtree belonging to the current agenda entry."
22956 (interactive)
22957 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22958 (let* ((marker (or (get-text-property (point) 'org-marker)
22959 (org-agenda-error)))
22960 (buffer (marker-buffer marker))
22961 (pos (marker-position marker)))
22962 (org-with-remote-undo buffer
22963 (with-current-buffer buffer
22964 (if (org-mode-p)
22965 (save-excursion
22966 (goto-char pos)
22967 (org-remove-subtree-entries-from-agenda)
22968 (org-back-to-heading t)
22969 (org-archive-subtree))
22970 (error "Archiving works only in Org-mode files"))))))
22972 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22973 "Remove all lines in the agenda that correspond to a given subtree.
22974 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22975 If this information is not given, the function uses the tree at point."
22976 (let ((buf (or buf (current-buffer))) m p)
22977 (save-excursion
22978 (unless (and beg end)
22979 (org-back-to-heading t)
22980 (setq beg (point))
22981 (org-end-of-subtree t)
22982 (setq end (point)))
22983 (set-buffer (get-buffer org-agenda-buffer-name))
22984 (save-excursion
22985 (goto-char (point-max))
22986 (beginning-of-line 1)
22987 (while (not (bobp))
22988 (when (and (setq m (get-text-property (point) 'org-marker))
22989 (equal buf (marker-buffer m))
22990 (setq p (marker-position m))
22991 (>= p beg)
22992 (<= p end))
22993 (let ((inhibit-read-only t))
22994 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22995 (beginning-of-line 0))))))
22997 (defun org-agenda-open-link ()
22998 "Follow the link in the current line, if any."
22999 (interactive)
23000 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
23001 (save-excursion
23002 (save-restriction
23003 (narrow-to-region (point-at-bol) (point-at-eol))
23004 (org-open-at-point))))
23006 (defun org-agenda-copy-local-variable (var)
23007 "Get a variable from a referenced buffer and install it here."
23008 (let ((m (get-text-property (point) 'org-marker)))
23009 (when (and m (buffer-live-p (marker-buffer m)))
23010 (org-set-local var (with-current-buffer (marker-buffer m)
23011 (symbol-value var))))))
23013 (defun org-agenda-switch-to (&optional delete-other-windows)
23014 "Go to the Org-mode file which contains the item at point."
23015 (interactive)
23016 (let* ((marker (or (get-text-property (point) 'org-marker)
23017 (org-agenda-error)))
23018 (buffer (marker-buffer marker))
23019 (pos (marker-position marker)))
23020 (switch-to-buffer buffer)
23021 (and delete-other-windows (delete-other-windows))
23022 (widen)
23023 (goto-char pos)
23024 (when (org-mode-p)
23025 (org-show-context 'agenda)
23026 (save-excursion
23027 (and (outline-next-heading)
23028 (org-flag-heading nil)))))) ; show the next heading
23030 (defun org-agenda-goto-mouse (ev)
23031 "Go to the Org-mode file which contains the item at the mouse click."
23032 (interactive "e")
23033 (mouse-set-point ev)
23034 (org-agenda-goto))
23036 (defun org-agenda-show ()
23037 "Display the Org-mode file which contains the item at point."
23038 (interactive)
23039 (let ((win (selected-window)))
23040 (org-agenda-goto t)
23041 (select-window win)))
23043 (defun org-agenda-recenter (arg)
23044 "Display the Org-mode file which contains the item at point and recenter."
23045 (interactive "P")
23046 (let ((win (selected-window)))
23047 (org-agenda-goto t)
23048 (recenter arg)
23049 (select-window win)))
23051 (defun org-agenda-show-mouse (ev)
23052 "Display the Org-mode file which contains the item at the mouse click."
23053 (interactive "e")
23054 (mouse-set-point ev)
23055 (org-agenda-show))
23057 (defun org-agenda-check-no-diary ()
23058 "Check if the entry is a diary link and abort if yes."
23059 (if (get-text-property (point) 'org-agenda-diary-link)
23060 (org-agenda-error)))
23062 (defun org-agenda-error ()
23063 (error "Command not allowed in this line"))
23065 (defun org-agenda-tree-to-indirect-buffer ()
23066 "Show the subtree corresponding to the current entry in an indirect buffer.
23067 This calls the command `org-tree-to-indirect-buffer' from the original
23068 Org-mode buffer.
23069 With numerical prefix arg ARG, go up to this level and then take that tree.
23070 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
23071 dedicated frame)."
23072 (interactive)
23073 (org-agenda-check-no-diary)
23074 (let* ((marker (or (get-text-property (point) 'org-marker)
23075 (org-agenda-error)))
23076 (buffer (marker-buffer marker))
23077 (pos (marker-position marker)))
23078 (with-current-buffer buffer
23079 (save-excursion
23080 (goto-char pos)
23081 (call-interactively 'org-tree-to-indirect-buffer)))))
23083 (defvar org-last-heading-marker (make-marker)
23084 "Marker pointing to the headline that last changed its TODO state
23085 by a remote command from the agenda.")
23087 (defun org-agenda-todo-nextset ()
23088 "Switch TODO entry to next sequence."
23089 (interactive)
23090 (org-agenda-todo 'nextset))
23092 (defun org-agenda-todo-previousset ()
23093 "Switch TODO entry to previous sequence."
23094 (interactive)
23095 (org-agenda-todo 'previousset))
23097 (defun org-agenda-todo (&optional arg)
23098 "Cycle TODO state of line at point, also in Org-mode file.
23099 This changes the line at point, all other lines in the agenda referring to
23100 the same tree node, and the headline of the tree node in the Org-mode file."
23101 (interactive "P")
23102 (org-agenda-check-no-diary)
23103 (let* ((col (current-column))
23104 (marker (or (get-text-property (point) 'org-marker)
23105 (org-agenda-error)))
23106 (buffer (marker-buffer marker))
23107 (pos (marker-position marker))
23108 (hdmarker (get-text-property (point) 'org-hd-marker))
23109 (inhibit-read-only t)
23110 newhead)
23111 (org-with-remote-undo buffer
23112 (with-current-buffer buffer
23113 (widen)
23114 (goto-char pos)
23115 (org-show-context 'agenda)
23116 (save-excursion
23117 (and (outline-next-heading)
23118 (org-flag-heading nil))) ; show the next heading
23119 (org-todo arg)
23120 (and (bolp) (forward-char 1))
23121 (setq newhead (org-get-heading))
23122 (save-excursion
23123 (org-back-to-heading)
23124 (move-marker org-last-heading-marker (point))))
23125 (beginning-of-line 1)
23126 (save-excursion
23127 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23128 (move-to-column col))))
23130 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23131 "Change all lines in the agenda buffer which match HDMARKER.
23132 The new content of the line will be NEWHEAD (as modified by
23133 `org-format-agenda-item'). HDMARKER is checked with
23134 `equal' against all `org-hd-marker' text properties in the file.
23135 If FIXFACE is non-nil, the face of each item is modified acording to
23136 the new TODO state."
23137 (let* ((inhibit-read-only t)
23138 props m pl undone-face done-face finish new dotime cat tags)
23139 (save-excursion
23140 (goto-char (point-max))
23141 (beginning-of-line 1)
23142 (while (not finish)
23143 (setq finish (bobp))
23144 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23145 (equal m hdmarker))
23146 (setq props (text-properties-at (point))
23147 dotime (get-text-property (point) 'dotime)
23148 cat (get-text-property (point) 'org-category)
23149 tags (get-text-property (point) 'tags)
23150 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23151 pl (get-text-property (point) 'prefix-length)
23152 undone-face (get-text-property (point) 'undone-face)
23153 done-face (get-text-property (point) 'done-face))
23154 (move-to-column pl)
23155 (cond
23156 ((equal new "")
23157 (beginning-of-line 1)
23158 (and (looking-at ".*\n?") (replace-match "")))
23159 ((looking-at ".*")
23160 (replace-match new t t)
23161 (beginning-of-line 1)
23162 (add-text-properties (point-at-bol) (point-at-eol) props)
23163 (when fixface
23164 (add-text-properties
23165 (point-at-bol) (point-at-eol)
23166 (list 'face
23167 (if org-last-todo-state-is-todo
23168 undone-face done-face))))
23169 (org-agenda-highlight-todo 'line)
23170 (beginning-of-line 1))
23171 (t (error "Line update did not work"))))
23172 (beginning-of-line 0)))
23173 (org-finalize-agenda)))
23175 (defun org-agenda-align-tags (&optional line)
23176 "Align all tags in agenda items to `org-agenda-tags-column'."
23177 (let ((inhibit-read-only t) l c)
23178 (save-excursion
23179 (goto-char (if line (point-at-bol) (point-min)))
23180 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23181 (if line (point-at-eol) nil) t)
23182 (add-text-properties
23183 (match-beginning 2) (match-end 2)
23184 (list 'face (delq nil (list 'org-tag (get-text-property
23185 (match-beginning 2) 'face)))))
23186 (setq l (- (match-end 2) (match-beginning 2))
23187 c (if (< org-agenda-tags-column 0)
23188 (- (abs org-agenda-tags-column) l)
23189 org-agenda-tags-column))
23190 (delete-region (match-beginning 1) (match-end 1))
23191 (goto-char (match-beginning 1))
23192 (insert (org-add-props
23193 (make-string (max 1 (- c (current-column))) ?\ )
23194 (text-properties-at (point))))))))
23196 (defun org-agenda-priority-up ()
23197 "Increase the priority of line at point, also in Org-mode file."
23198 (interactive)
23199 (org-agenda-priority 'up))
23201 (defun org-agenda-priority-down ()
23202 "Decrease the priority of line at point, also in Org-mode file."
23203 (interactive)
23204 (org-agenda-priority 'down))
23206 (defun org-agenda-priority (&optional force-direction)
23207 "Set the priority of line at point, also in Org-mode file.
23208 This changes the line at point, all other lines in the agenda referring to
23209 the same tree node, and the headline of the tree node in the Org-mode file."
23210 (interactive)
23211 (org-agenda-check-no-diary)
23212 (let* ((marker (or (get-text-property (point) 'org-marker)
23213 (org-agenda-error)))
23214 (hdmarker (get-text-property (point) 'org-hd-marker))
23215 (buffer (marker-buffer hdmarker))
23216 (pos (marker-position hdmarker))
23217 (inhibit-read-only t)
23218 newhead)
23219 (org-with-remote-undo buffer
23220 (with-current-buffer buffer
23221 (widen)
23222 (goto-char pos)
23223 (org-show-context 'agenda)
23224 (save-excursion
23225 (and (outline-next-heading)
23226 (org-flag-heading nil))) ; show the next heading
23227 (funcall 'org-priority force-direction)
23228 (end-of-line 1)
23229 (setq newhead (org-get-heading)))
23230 (org-agenda-change-all-lines newhead hdmarker)
23231 (beginning-of-line 1))))
23233 (defun org-get-tags-at (&optional pos)
23234 "Get a list of all headline tags applicable at POS.
23235 POS defaults to point. If tags are inherited, the list contains
23236 the targets in the same sequence as the headlines appear, i.e.
23237 the tags of the current headline come last."
23238 (interactive)
23239 (let (tags lastpos)
23240 (save-excursion
23241 (save-restriction
23242 (widen)
23243 (goto-char (or pos (point)))
23244 (save-match-data
23245 (org-back-to-heading t)
23246 (condition-case nil
23247 (while (not (equal lastpos (point)))
23248 (setq lastpos (point))
23249 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23250 (setq tags (append (org-split-string
23251 (org-match-string-no-properties 1) ":")
23252 tags)))
23253 (or org-use-tag-inheritance (error ""))
23254 (org-up-heading-all 1))
23255 (error nil))))
23256 tags)))
23258 ;; FIXME: should fix the tags property of the agenda line.
23259 (defun org-agenda-set-tags ()
23260 "Set tags for the current headline."
23261 (interactive)
23262 (org-agenda-check-no-diary)
23263 (if (and (org-region-active-p) (interactive-p))
23264 (call-interactively 'org-change-tag-in-region)
23265 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23266 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23267 (org-agenda-error)))
23268 (buffer (marker-buffer hdmarker))
23269 (pos (marker-position hdmarker))
23270 (inhibit-read-only t)
23271 newhead)
23272 (org-with-remote-undo buffer
23273 (with-current-buffer buffer
23274 (widen)
23275 (goto-char pos)
23276 (save-excursion
23277 (org-show-context 'agenda))
23278 (save-excursion
23279 (and (outline-next-heading)
23280 (org-flag-heading nil))) ; show the next heading
23281 (goto-char pos)
23282 (call-interactively 'org-set-tags)
23283 (end-of-line 1)
23284 (setq newhead (org-get-heading)))
23285 (org-agenda-change-all-lines newhead hdmarker)
23286 (beginning-of-line 1)))))
23288 (defun org-agenda-toggle-archive-tag ()
23289 "Toggle the archive tag for the current entry."
23290 (interactive)
23291 (org-agenda-check-no-diary)
23292 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23293 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23294 (org-agenda-error)))
23295 (buffer (marker-buffer hdmarker))
23296 (pos (marker-position hdmarker))
23297 (inhibit-read-only t)
23298 newhead)
23299 (org-with-remote-undo buffer
23300 (with-current-buffer buffer
23301 (widen)
23302 (goto-char pos)
23303 (org-show-context 'agenda)
23304 (save-excursion
23305 (and (outline-next-heading)
23306 (org-flag-heading nil))) ; show the next heading
23307 (call-interactively 'org-toggle-archive-tag)
23308 (end-of-line 1)
23309 (setq newhead (org-get-heading)))
23310 (org-agenda-change-all-lines newhead hdmarker)
23311 (beginning-of-line 1))))
23313 (defun org-agenda-date-later (arg &optional what)
23314 "Change the date of this item to one day later."
23315 (interactive "p")
23316 (org-agenda-check-type t 'agenda 'timeline)
23317 (org-agenda-check-no-diary)
23318 (let* ((marker (or (get-text-property (point) 'org-marker)
23319 (org-agenda-error)))
23320 (buffer (marker-buffer marker))
23321 (pos (marker-position marker)))
23322 (org-with-remote-undo buffer
23323 (with-current-buffer buffer
23324 (widen)
23325 (goto-char pos)
23326 (if (not (org-at-timestamp-p))
23327 (error "Cannot find time stamp"))
23328 (org-timestamp-change arg (or what 'day)))
23329 (org-agenda-show-new-time marker org-last-changed-timestamp))
23330 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23332 (defun org-agenda-date-earlier (arg &optional what)
23333 "Change the date of this item to one day earlier."
23334 (interactive "p")
23335 (org-agenda-date-later (- arg) what))
23337 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23338 "Show new date stamp via text properties."
23339 ;; We use text properties to make this undoable
23340 (let ((inhibit-read-only t))
23341 (setq stamp (concat " " prefix " => " stamp))
23342 (save-excursion
23343 (goto-char (point-max))
23344 (while (not (bobp))
23345 (when (equal marker (get-text-property (point) 'org-marker))
23346 (move-to-column (- (window-width) (length stamp)) t)
23347 (if (featurep 'xemacs)
23348 ;; Use `duplicable' property to trigger undo recording
23349 (let ((ex (make-extent nil nil))
23350 (gl (make-glyph stamp)))
23351 (set-glyph-face gl 'secondary-selection)
23352 (set-extent-properties
23353 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23354 (insert-extent ex (1- (point)) (point-at-eol)))
23355 (add-text-properties
23356 (1- (point)) (point-at-eol)
23357 (list 'display (org-add-props stamp nil
23358 'face 'secondary-selection))))
23359 (beginning-of-line 1))
23360 (beginning-of-line 0)))))
23362 (defun org-agenda-date-prompt (arg)
23363 "Change the date of this item. Date is prompted for, with default today.
23364 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23365 be used to request time specification in the time stamp."
23366 (interactive "P")
23367 (org-agenda-check-type t 'agenda 'timeline)
23368 (org-agenda-check-no-diary)
23369 (let* ((marker (or (get-text-property (point) 'org-marker)
23370 (org-agenda-error)))
23371 (buffer (marker-buffer marker))
23372 (pos (marker-position marker)))
23373 (org-with-remote-undo buffer
23374 (with-current-buffer buffer
23375 (widen)
23376 (goto-char pos)
23377 (if (not (org-at-timestamp-p))
23378 (error "Cannot find time stamp"))
23379 (org-time-stamp arg)
23380 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23382 (defun org-agenda-schedule (arg)
23383 "Schedule the item at point."
23384 (interactive "P")
23385 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23386 (org-agenda-check-no-diary)
23387 (let* ((marker (or (get-text-property (point) 'org-marker)
23388 (org-agenda-error)))
23389 (type (marker-insertion-type marker))
23390 (buffer (marker-buffer marker))
23391 (pos (marker-position marker))
23392 (org-insert-labeled-timestamps-at-point nil)
23394 (when type (message "%s" type) (sit-for 3))
23395 (set-marker-insertion-type marker t)
23396 (org-with-remote-undo buffer
23397 (with-current-buffer buffer
23398 (widen)
23399 (goto-char pos)
23400 (setq ts (org-schedule arg)))
23401 (org-agenda-show-new-time marker ts "S"))
23402 (message "Item scheduled for %s" ts)))
23404 (defun org-agenda-deadline (arg)
23405 "Schedule the item at point."
23406 (interactive "P")
23407 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23408 (org-agenda-check-no-diary)
23409 (let* ((marker (or (get-text-property (point) 'org-marker)
23410 (org-agenda-error)))
23411 (buffer (marker-buffer marker))
23412 (pos (marker-position marker))
23413 (org-insert-labeled-timestamps-at-point nil)
23415 (org-with-remote-undo buffer
23416 (with-current-buffer buffer
23417 (widen)
23418 (goto-char pos)
23419 (setq ts (org-deadline arg)))
23420 (org-agenda-show-new-time marker ts "S"))
23421 (message "Deadline for this item set to %s" ts)))
23423 (defun org-get-heading (&optional no-tags)
23424 "Return the heading of the current entry, without the stars."
23425 (save-excursion
23426 (org-back-to-heading t)
23427 (if (looking-at
23428 (if no-tags
23429 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23430 "\\*+[ \t]+\\([^\r\n]*\\)"))
23431 (match-string 1) "")))
23433 (defun org-agenda-clock-in (&optional arg)
23434 "Start the clock on the currently selected item."
23435 (interactive "P")
23436 (org-agenda-check-no-diary)
23437 (let* ((marker (or (get-text-property (point) 'org-marker)
23438 (org-agenda-error)))
23439 (pos (marker-position marker)))
23440 (org-with-remote-undo (marker-buffer marker)
23441 (with-current-buffer (marker-buffer marker)
23442 (widen)
23443 (goto-char pos)
23444 (org-clock-in)))))
23446 (defun org-agenda-clock-out (&optional arg)
23447 "Stop the currently running clock."
23448 (interactive "P")
23449 (unless (marker-buffer org-clock-marker)
23450 (error "No running clock"))
23451 (org-with-remote-undo (marker-buffer org-clock-marker)
23452 (org-clock-out)))
23454 (defun org-agenda-clock-cancel (&optional arg)
23455 "Cancel the currently running clock."
23456 (interactive "P")
23457 (unless (marker-buffer org-clock-marker)
23458 (error "No running clock"))
23459 (org-with-remote-undo (marker-buffer org-clock-marker)
23460 (org-clock-cancel)))
23462 (defun org-agenda-diary-entry ()
23463 "Make a diary entry, like the `i' command from the calendar.
23464 All the standard commands work: block, weekly etc."
23465 (interactive)
23466 (org-agenda-check-type t 'agenda 'timeline)
23467 (require 'diary-lib)
23468 (let* ((char (progn
23469 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23470 (read-char-exclusive)))
23471 (cmd (cdr (assoc char
23472 '((?d . insert-diary-entry)
23473 (?w . insert-weekly-diary-entry)
23474 (?m . insert-monthly-diary-entry)
23475 (?y . insert-yearly-diary-entry)
23476 (?a . insert-anniversary-diary-entry)
23477 (?b . insert-block-diary-entry)
23478 (?c . insert-cyclic-diary-entry)))))
23479 (oldf (symbol-function 'calendar-cursor-to-date))
23480 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23481 (point (point))
23482 (mark (or (mark t) (point))))
23483 (unless cmd
23484 (error "No command associated with <%c>" char))
23485 (unless (and (get-text-property point 'day)
23486 (or (not (equal ?b char))
23487 (get-text-property mark 'day)))
23488 (error "Don't know which date to use for diary entry"))
23489 ;; We implement this by hacking the `calendar-cursor-to-date' function
23490 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23491 (let ((calendar-mark-ring
23492 (list (calendar-gregorian-from-absolute
23493 (or (get-text-property mark 'day)
23494 (get-text-property point 'day))))))
23495 (unwind-protect
23496 (progn
23497 (fset 'calendar-cursor-to-date
23498 (lambda (&optional error)
23499 (calendar-gregorian-from-absolute
23500 (get-text-property point 'day))))
23501 (call-interactively cmd))
23502 (fset 'calendar-cursor-to-date oldf)))))
23505 (defun org-agenda-execute-calendar-command (cmd)
23506 "Execute a calendar command from the agenda, with the date associated to
23507 the cursor position."
23508 (org-agenda-check-type t 'agenda 'timeline)
23509 (require 'diary-lib)
23510 (unless (get-text-property (point) 'day)
23511 (error "Don't know which date to use for calendar command"))
23512 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23513 (point (point))
23514 (date (calendar-gregorian-from-absolute
23515 (get-text-property point 'day)))
23516 ;; the following 3 vars are needed in the calendar
23517 (displayed-day (extract-calendar-day date))
23518 (displayed-month (extract-calendar-month date))
23519 (displayed-year (extract-calendar-year date)))
23520 (unwind-protect
23521 (progn
23522 (fset 'calendar-cursor-to-date
23523 (lambda (&optional error)
23524 (calendar-gregorian-from-absolute
23525 (get-text-property point 'day))))
23526 (call-interactively cmd))
23527 (fset 'calendar-cursor-to-date oldf))))
23529 (defun org-agenda-phases-of-moon ()
23530 "Display the phases of the moon for the 3 months around the cursor date."
23531 (interactive)
23532 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23534 (defun org-agenda-holidays ()
23535 "Display the holidays for the 3 months around the cursor date."
23536 (interactive)
23537 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23539 (defun org-agenda-sunrise-sunset (arg)
23540 "Display sunrise and sunset for the cursor date.
23541 Latitude and longitude can be specified with the variables
23542 `calendar-latitude' and `calendar-longitude'. When called with prefix
23543 argument, latitude and longitude will be prompted for."
23544 (interactive "P")
23545 (let ((calendar-longitude (if arg nil calendar-longitude))
23546 (calendar-latitude (if arg nil calendar-latitude))
23547 (calendar-location-name
23548 (if arg "the given coordinates" calendar-location-name)))
23549 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23551 (defun org-agenda-goto-calendar ()
23552 "Open the Emacs calendar with the date at the cursor."
23553 (interactive)
23554 (org-agenda-check-type t 'agenda 'timeline)
23555 (let* ((day (or (get-text-property (point) 'day)
23556 (error "Don't know which date to open in calendar")))
23557 (date (calendar-gregorian-from-absolute day))
23558 (calendar-move-hook nil)
23559 (view-calendar-holidays-initially nil)
23560 (view-diary-entries-initially nil))
23561 (calendar)
23562 (calendar-goto-date date)))
23564 (defun org-calendar-goto-agenda ()
23565 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23566 This is a command that has to be installed in `calendar-mode-map'."
23567 (interactive)
23568 (org-agenda-list nil (calendar-absolute-from-gregorian
23569 (calendar-cursor-to-date))
23570 nil))
23572 (defun org-agenda-convert-date ()
23573 (interactive)
23574 (org-agenda-check-type t 'agenda 'timeline)
23575 (let ((day (get-text-property (point) 'day))
23576 date s)
23577 (unless day
23578 (error "Don't know which date to convert"))
23579 (setq date (calendar-gregorian-from-absolute day))
23580 (setq s (concat
23581 "Gregorian: " (calendar-date-string date) "\n"
23582 "ISO: " (calendar-iso-date-string date) "\n"
23583 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23584 "Julian: " (calendar-julian-date-string date) "\n"
23585 "Astron. JD: " (calendar-astro-date-string date)
23586 " (Julian date number at noon UTC)\n"
23587 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23588 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23589 "French: " (calendar-french-date-string date) "\n"
23590 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23591 "Mayan: " (calendar-mayan-date-string date) "\n"
23592 "Coptic: " (calendar-coptic-date-string date) "\n"
23593 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23594 "Persian: " (calendar-persian-date-string date) "\n"
23595 "Chinese: " (calendar-chinese-date-string date) "\n"))
23596 (with-output-to-temp-buffer "*Dates*"
23597 (princ s))
23598 (if (fboundp 'fit-window-to-buffer)
23599 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23602 ;;;; Embedded LaTeX
23604 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23605 "Keymap for the minor `org-cdlatex-mode'.")
23607 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23608 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23609 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23610 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23611 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23613 (defvar org-cdlatex-texmathp-advice-is-done nil
23614 "Flag remembering if we have applied the advice to texmathp already.")
23616 (define-minor-mode org-cdlatex-mode
23617 "Toggle the minor `org-cdlatex-mode'.
23618 This mode supports entering LaTeX environment and math in LaTeX fragments
23619 in Org-mode.
23620 \\{org-cdlatex-mode-map}"
23621 nil " OCDL" nil
23622 (when org-cdlatex-mode (require 'cdlatex))
23623 (unless org-cdlatex-texmathp-advice-is-done
23624 (setq org-cdlatex-texmathp-advice-is-done t)
23625 (defadvice texmathp (around org-math-always-on activate)
23626 "Always return t in org-mode buffers.
23627 This is because we want to insert math symbols without dollars even outside
23628 the LaTeX math segments. If Orgmode thinks that point is actually inside
23629 en embedded LaTeX fragement, let texmathp do its job.
23630 \\[org-cdlatex-mode-map]"
23631 (interactive)
23632 (let (p)
23633 (cond
23634 ((not (org-mode-p)) ad-do-it)
23635 ((eq this-command 'cdlatex-math-symbol)
23636 (setq ad-return-value t
23637 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23639 (let ((p (org-inside-LaTeX-fragment-p)))
23640 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23641 (setq ad-return-value t
23642 texmathp-why '("Org-mode embedded math" . 0))
23643 (if p ad-do-it)))))))))
23645 (defun turn-on-org-cdlatex ()
23646 "Unconditionally turn on `org-cdlatex-mode'."
23647 (org-cdlatex-mode 1))
23649 (defun org-inside-LaTeX-fragment-p ()
23650 "Test if point is inside a LaTeX fragment.
23651 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23652 sequence appearing also before point.
23653 Even though the matchers for math are configurable, this function assumes
23654 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23655 delimiters are skipped when they have been removed by customization.
23656 The return value is nil, or a cons cell with the delimiter and
23657 and the position of this delimiter.
23659 This function does a reasonably good job, but can locally be fooled by
23660 for example currency specifications. For example it will assume being in
23661 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23662 fragments that are properly closed, but during editing, we have to live
23663 with the uncertainty caused by missing closing delimiters. This function
23664 looks only before point, not after."
23665 (catch 'exit
23666 (let ((pos (point))
23667 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23668 (lim (progn
23669 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23670 (point)))
23671 dd-on str (start 0) m re)
23672 (goto-char pos)
23673 (when dodollar
23674 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23675 re (nth 1 (assoc "$" org-latex-regexps)))
23676 (while (string-match re str start)
23677 (cond
23678 ((= (match-end 0) (length str))
23679 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23680 ((= (match-end 0) (- (length str) 5))
23681 (throw 'exit nil))
23682 (t (setq start (match-end 0))))))
23683 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23684 (goto-char pos)
23685 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23686 (and (match-beginning 2) (throw 'exit nil))
23687 ;; count $$
23688 (while (re-search-backward "\\$\\$" lim t)
23689 (setq dd-on (not dd-on)))
23690 (goto-char pos)
23691 (if dd-on (cons "$$" m))))))
23694 (defun org-try-cdlatex-tab ()
23695 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23696 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23697 - inside a LaTeX fragment, or
23698 - after the first word in a line, where an abbreviation expansion could
23699 insert a LaTeX environment."
23700 (when org-cdlatex-mode
23701 (cond
23702 ((save-excursion
23703 (skip-chars-backward "a-zA-Z0-9*")
23704 (skip-chars-backward " \t")
23705 (bolp))
23706 (cdlatex-tab) t)
23707 ((org-inside-LaTeX-fragment-p)
23708 (cdlatex-tab) t)
23709 (t nil))))
23711 (defun org-cdlatex-underscore-caret (&optional arg)
23712 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23713 Revert to the normal definition outside of these fragments."
23714 (interactive "P")
23715 (if (org-inside-LaTeX-fragment-p)
23716 (call-interactively 'cdlatex-sub-superscript)
23717 (let (org-cdlatex-mode)
23718 (call-interactively (key-binding (vector last-input-event))))))
23720 (defun org-cdlatex-math-modify (&optional arg)
23721 "Execute `cdlatex-math-modify' in LaTeX fragments.
23722 Revert to the normal definition outside of these fragments."
23723 (interactive "P")
23724 (if (org-inside-LaTeX-fragment-p)
23725 (call-interactively 'cdlatex-math-modify)
23726 (let (org-cdlatex-mode)
23727 (call-interactively (key-binding (vector last-input-event))))))
23729 (defvar org-latex-fragment-image-overlays nil
23730 "List of overlays carrying the images of latex fragments.")
23731 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23733 (defun org-remove-latex-fragment-image-overlays ()
23734 "Remove all overlays with LaTeX fragment images in current buffer."
23735 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23736 (setq org-latex-fragment-image-overlays nil))
23738 (defun org-preview-latex-fragment (&optional subtree)
23739 "Preview the LaTeX fragment at point, or all locally or globally.
23740 If the cursor is in a LaTeX fragment, create the image and overlay
23741 it over the source code. If there is no fragment at point, display
23742 all fragments in the current text, from one headline to the next. With
23743 prefix SUBTREE, display all fragments in the current subtree. With a
23744 double prefix `C-u C-u', or when the cursor is before the first headline,
23745 display all fragments in the buffer.
23746 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23747 (interactive "P")
23748 (org-remove-latex-fragment-image-overlays)
23749 (save-excursion
23750 (save-restriction
23751 (let (beg end at msg)
23752 (cond
23753 ((or (equal subtree '(16))
23754 (not (save-excursion
23755 (re-search-backward (concat "^" outline-regexp) nil t))))
23756 (setq beg (point-min) end (point-max)
23757 msg "Creating images for buffer...%s"))
23758 ((equal subtree '(4))
23759 (org-back-to-heading)
23760 (setq beg (point) end (org-end-of-subtree t)
23761 msg "Creating images for subtree...%s"))
23763 (if (setq at (org-inside-LaTeX-fragment-p))
23764 (goto-char (max (point-min) (- (cdr at) 2)))
23765 (org-back-to-heading))
23766 (setq beg (point) end (progn (outline-next-heading) (point))
23767 msg (if at "Creating image...%s"
23768 "Creating images for entry...%s"))))
23769 (message msg "")
23770 (narrow-to-region beg end)
23771 (goto-char beg)
23772 (org-format-latex
23773 (concat "ltxpng/" (file-name-sans-extension
23774 (file-name-nondirectory
23775 buffer-file-name)))
23776 default-directory 'overlays msg at 'forbuffer)
23777 (message msg "done. Use `C-c C-c' to remove images.")))))
23779 (defvar org-latex-regexps
23780 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23781 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23782 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23783 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23784 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23785 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23786 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23787 "Regular expressions for matching embedded LaTeX.")
23789 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23790 "Replace LaTeX fragments with links to an image, and produce images."
23791 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23792 (let* ((prefixnodir (file-name-nondirectory prefix))
23793 (absprefix (expand-file-name prefix dir))
23794 (todir (file-name-directory absprefix))
23795 (opt org-format-latex-options)
23796 (matchers (plist-get opt :matchers))
23797 (re-list org-latex-regexps)
23798 (cnt 0) txt link beg end re e checkdir
23799 m n block linkfile movefile ov)
23800 ;; Check if there are old images files with this prefix, and remove them
23801 (when (file-directory-p todir)
23802 (mapc 'delete-file
23803 (directory-files
23804 todir 'full
23805 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23806 ;; Check the different regular expressions
23807 (while (setq e (pop re-list))
23808 (setq m (car e) re (nth 1 e) n (nth 2 e)
23809 block (if (nth 3 e) "\n\n" ""))
23810 (when (member m matchers)
23811 (goto-char (point-min))
23812 (while (re-search-forward re nil t)
23813 (when (or (not at) (equal (cdr at) (match-beginning n)))
23814 (setq txt (match-string n)
23815 beg (match-beginning n) end (match-end n)
23816 cnt (1+ cnt)
23817 linkfile (format "%s_%04d.png" prefix cnt)
23818 movefile (format "%s_%04d.png" absprefix cnt)
23819 link (concat block "[[file:" linkfile "]]" block))
23820 (if msg (message msg cnt))
23821 (goto-char beg)
23822 (unless checkdir ; make sure the directory exists
23823 (setq checkdir t)
23824 (or (file-directory-p todir) (make-directory todir)))
23825 (org-create-formula-image
23826 txt movefile opt forbuffer)
23827 (if overlays
23828 (progn
23829 (setq ov (org-make-overlay beg end))
23830 (if (featurep 'xemacs)
23831 (progn
23832 (org-overlay-put ov 'invisible t)
23833 (org-overlay-put
23834 ov 'end-glyph
23835 (make-glyph (vector 'png :file movefile))))
23836 (org-overlay-put
23837 ov 'display
23838 (list 'image :type 'png :file movefile :ascent 'center)))
23839 (push ov org-latex-fragment-image-overlays)
23840 (goto-char end))
23841 (delete-region beg end)
23842 (insert link))))))))
23844 ;; This function borrows from Ganesh Swami's latex2png.el
23845 (defun org-create-formula-image (string tofile options buffer)
23846 (let* ((tmpdir (if (featurep 'xemacs)
23847 (temp-directory)
23848 temporary-file-directory))
23849 (texfilebase (make-temp-name
23850 (expand-file-name "orgtex" tmpdir)))
23851 (texfile (concat texfilebase ".tex"))
23852 (dvifile (concat texfilebase ".dvi"))
23853 (pngfile (concat texfilebase ".png"))
23854 (fnh (face-attribute 'default :height nil))
23855 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23856 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23857 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23858 "Black"))
23859 (bg (or (plist-get options (if buffer :background :html-background))
23860 "Transparent")))
23861 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23862 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23863 (with-temp-file texfile
23864 (insert org-format-latex-header
23865 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23866 (let ((dir default-directory))
23867 (condition-case nil
23868 (progn
23869 (cd tmpdir)
23870 (call-process "latex" nil nil nil texfile))
23871 (error nil))
23872 (cd dir))
23873 (if (not (file-exists-p dvifile))
23874 (progn (message "Failed to create dvi file from %s" texfile) nil)
23875 (call-process "dvipng" nil nil nil
23876 "-E" "-fg" fg "-bg" bg
23877 "-D" dpi
23878 ;;"-x" scale "-y" scale
23879 "-T" "tight"
23880 "-o" pngfile
23881 dvifile)
23882 (if (not (file-exists-p pngfile))
23883 (progn (message "Failed to create png file from %s" texfile) nil)
23884 ;; Use the requested file name and clean up
23885 (copy-file pngfile tofile 'replace)
23886 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23887 (delete-file (concat texfilebase e)))
23888 pngfile))))
23890 (defun org-dvipng-color (attr)
23891 "Return an rgb color specification for dvipng."
23892 (apply 'format "rgb %s %s %s"
23893 (mapcar 'org-normalize-color
23894 (color-values (face-attribute 'default attr nil)))))
23896 (defun org-normalize-color (value)
23897 "Return string to be used as color value for an RGB component."
23898 (format "%g" (/ value 65535.0)))
23900 ;;;; Exporting
23902 ;;; Variables, constants, and parameter plists
23904 (defconst org-level-max 20)
23906 (defvar org-export-html-preamble nil
23907 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23908 (defvar org-export-html-postamble nil
23909 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23910 (defvar org-export-html-auto-preamble t
23911 "Should default preamble be inserted? Set by publishing functions.")
23912 (defvar org-export-html-auto-postamble t
23913 "Should default postamble be inserted? Set by publishing functions.")
23914 (defvar org-current-export-file nil) ; dynamically scoped parameter
23915 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23918 (defconst org-export-plist-vars
23919 '((:language . org-export-default-language)
23920 (:customtime . org-display-custom-times)
23921 (:headline-levels . org-export-headline-levels)
23922 (:section-numbers . org-export-with-section-numbers)
23923 (:table-of-contents . org-export-with-toc)
23924 (:preserve-breaks . org-export-preserve-breaks)
23925 (:archived-trees . org-export-with-archived-trees)
23926 (:emphasize . org-export-with-emphasize)
23927 (:sub-superscript . org-export-with-sub-superscripts)
23928 (:special-strings . org-export-with-special-strings)
23929 (:footnotes . org-export-with-footnotes)
23930 (:drawers . org-export-with-drawers)
23931 (:tags . org-export-with-tags)
23932 (:TeX-macros . org-export-with-TeX-macros)
23933 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23934 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23935 (:fixed-width . org-export-with-fixed-width)
23936 (:timestamps . org-export-with-timestamps)
23937 (:author-info . org-export-author-info)
23938 (:time-stamp-file . org-export-time-stamp-file)
23939 (:tables . org-export-with-tables)
23940 (:table-auto-headline . org-export-highlight-first-table-line)
23941 (:style . org-export-html-style)
23942 (:agenda-style . org-agenda-export-html-style)
23943 (:convert-org-links . org-export-html-link-org-files-as-html)
23944 (:inline-images . org-export-html-inline-images)
23945 (:html-extension . org-export-html-extension)
23946 (:html-table-tag . org-export-html-table-tag)
23947 (:expand-quoted-html . org-export-html-expand)
23948 (:timestamp . org-export-html-with-timestamp)
23949 (:publishing-directory . org-export-publishing-directory)
23950 (:preamble . org-export-html-preamble)
23951 (:postamble . org-export-html-postamble)
23952 (:auto-preamble . org-export-html-auto-preamble)
23953 (:auto-postamble . org-export-html-auto-postamble)
23954 (:author . user-full-name)
23955 (:email . user-mail-address)))
23957 (defun org-default-export-plist ()
23958 "Return the property list with default settings for the export variables."
23959 (let ((l org-export-plist-vars) rtn e)
23960 (while (setq e (pop l))
23961 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23962 rtn))
23964 (defun org-infile-export-plist ()
23965 "Return the property list with file-local settings for export."
23966 (save-excursion
23967 (save-restriction
23968 (widen)
23969 (goto-char 0)
23970 (let ((re (org-make-options-regexp
23971 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23972 p key val text options)
23973 (while (re-search-forward re nil t)
23974 (setq key (org-match-string-no-properties 1)
23975 val (org-match-string-no-properties 2))
23976 (cond
23977 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23978 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23979 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23980 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23981 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23982 ((string-equal key "TEXT")
23983 (setq text (if text (concat text "\n" val) val)))
23984 ((string-equal key "OPTIONS") (setq options val))))
23985 (setq p (plist-put p :text text))
23986 (when options
23987 (let ((op '(("H" . :headline-levels)
23988 ("num" . :section-numbers)
23989 ("toc" . :table-of-contents)
23990 ("\\n" . :preserve-breaks)
23991 ("@" . :expand-quoted-html)
23992 (":" . :fixed-width)
23993 ("|" . :tables)
23994 ("^" . :sub-superscript)
23995 ("-" . :special-strings)
23996 ("f" . :footnotes)
23997 ("d" . :drawers)
23998 ("tags" . :tags)
23999 ("*" . :emphasize)
24000 ("TeX" . :TeX-macros)
24001 ("LaTeX" . :LaTeX-fragments)
24002 ("skip" . :skip-before-1st-heading)
24003 ("author" . :author-info)
24004 ("timestamp" . :time-stamp-file)))
24006 (while (setq o (pop op))
24007 (if (string-match (concat (regexp-quote (car o))
24008 ":\\([^ \t\n\r;,.]*\\)")
24009 options)
24010 (setq p (plist-put p (cdr o)
24011 (car (read-from-string
24012 (match-string 1 options)))))))))
24013 p))))
24015 (defun org-export-directory (type plist)
24016 (let* ((val (plist-get plist :publishing-directory))
24017 (dir (if (listp val)
24018 (or (cdr (assoc type val)) ".")
24019 val)))
24020 dir))
24022 (defun org-skip-comments (lines)
24023 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
24024 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
24025 (re2 "^\\(\\*+\\)[ \t\n\r]")
24026 (case-fold-search nil)
24027 rtn line level)
24028 (while (setq line (pop lines))
24029 (cond
24030 ((and (string-match re1 line)
24031 (setq level (- (match-end 1) (match-beginning 1))))
24032 ;; Beginning of a COMMENT subtree. Skip it.
24033 (while (and (setq line (pop lines))
24034 (or (not (string-match re2 line))
24035 (> (- (match-end 1) (match-beginning 1)) level))))
24036 (setq lines (cons line lines)))
24037 ((string-match "^#" line)
24038 ;; an ordinary comment line
24040 ((and org-export-table-remove-special-lines
24041 (string-match "^[ \t]*|" line)
24042 (or (string-match "^[ \t]*| *[!_^] *|" line)
24043 (and (string-match "| *<[0-9]+> *|" line)
24044 (not (string-match "| *[^ <|]" line)))))
24045 ;; a special table line that should be removed
24047 (t (setq rtn (cons line rtn)))))
24048 (nreverse rtn)))
24050 (defun org-export (&optional arg)
24051 (interactive)
24052 (let ((help "[t] insert the export option template
24053 \[v] limit export to visible part of outline tree
24055 \[a] export as ASCII
24057 \[h] export as HTML
24058 \[H] export as HTML to temporary buffer
24059 \[R] export region as HTML
24060 \[b] export as HTML and browse immediately
24061 \[x] export as XOXO
24063 \[l] export as LaTeX
24064 \[L] export as LaTeX to temporary buffer
24066 \[i] export current file as iCalendar file
24067 \[I] export all agenda files as iCalendar files
24068 \[c] export agenda files into combined iCalendar file
24070 \[F] publish current file
24071 \[P] publish current project
24072 \[X] publish... (project will be prompted for)
24073 \[A] publish all projects")
24074 (cmds
24075 '((?t . org-insert-export-options-template)
24076 (?v . org-export-visible)
24077 (?a . org-export-as-ascii)
24078 (?h . org-export-as-html)
24079 (?b . org-export-as-html-and-open)
24080 (?H . org-export-as-html-to-buffer)
24081 (?R . org-export-region-as-html)
24082 (?x . org-export-as-xoxo)
24083 (?l . org-export-as-latex)
24084 (?L . org-export-as-latex-to-buffer)
24085 (?i . org-export-icalendar-this-file)
24086 (?I . org-export-icalendar-all-agenda-files)
24087 (?c . org-export-icalendar-combine-agenda-files)
24088 (?F . org-publish-current-file)
24089 (?P . org-publish-current-project)
24090 (?X . org-publish)
24091 (?A . org-publish-all)))
24092 r1 r2 ass)
24093 (save-window-excursion
24094 (delete-other-windows)
24095 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24096 (princ help))
24097 (message "Select command: ")
24098 (setq r1 (read-char-exclusive)))
24099 (setq r2 (if (< r1 27) (+ r1 96) r1))
24100 (if (setq ass (assq r2 cmds))
24101 (call-interactively (cdr ass))
24102 (error "No command associated with key %c" r1))))
24104 (defconst org-html-entities
24105 '(("nbsp")
24106 ("iexcl")
24107 ("cent")
24108 ("pound")
24109 ("curren")
24110 ("yen")
24111 ("brvbar")
24112 ("vert" . "&#124;")
24113 ("sect")
24114 ("uml")
24115 ("copy")
24116 ("ordf")
24117 ("laquo")
24118 ("not")
24119 ("shy")
24120 ("reg")
24121 ("macr")
24122 ("deg")
24123 ("plusmn")
24124 ("sup2")
24125 ("sup3")
24126 ("acute")
24127 ("micro")
24128 ("para")
24129 ("middot")
24130 ("odot"."o")
24131 ("star"."*")
24132 ("cedil")
24133 ("sup1")
24134 ("ordm")
24135 ("raquo")
24136 ("frac14")
24137 ("frac12")
24138 ("frac34")
24139 ("iquest")
24140 ("Agrave")
24141 ("Aacute")
24142 ("Acirc")
24143 ("Atilde")
24144 ("Auml")
24145 ("Aring") ("AA"."&Aring;")
24146 ("AElig")
24147 ("Ccedil")
24148 ("Egrave")
24149 ("Eacute")
24150 ("Ecirc")
24151 ("Euml")
24152 ("Igrave")
24153 ("Iacute")
24154 ("Icirc")
24155 ("Iuml")
24156 ("ETH")
24157 ("Ntilde")
24158 ("Ograve")
24159 ("Oacute")
24160 ("Ocirc")
24161 ("Otilde")
24162 ("Ouml")
24163 ("times")
24164 ("Oslash")
24165 ("Ugrave")
24166 ("Uacute")
24167 ("Ucirc")
24168 ("Uuml")
24169 ("Yacute")
24170 ("THORN")
24171 ("szlig")
24172 ("agrave")
24173 ("aacute")
24174 ("acirc")
24175 ("atilde")
24176 ("auml")
24177 ("aring")
24178 ("aelig")
24179 ("ccedil")
24180 ("egrave")
24181 ("eacute")
24182 ("ecirc")
24183 ("euml")
24184 ("igrave")
24185 ("iacute")
24186 ("icirc")
24187 ("iuml")
24188 ("eth")
24189 ("ntilde")
24190 ("ograve")
24191 ("oacute")
24192 ("ocirc")
24193 ("otilde")
24194 ("ouml")
24195 ("divide")
24196 ("oslash")
24197 ("ugrave")
24198 ("uacute")
24199 ("ucirc")
24200 ("uuml")
24201 ("yacute")
24202 ("thorn")
24203 ("yuml")
24204 ("fnof")
24205 ("Alpha")
24206 ("Beta")
24207 ("Gamma")
24208 ("Delta")
24209 ("Epsilon")
24210 ("Zeta")
24211 ("Eta")
24212 ("Theta")
24213 ("Iota")
24214 ("Kappa")
24215 ("Lambda")
24216 ("Mu")
24217 ("Nu")
24218 ("Xi")
24219 ("Omicron")
24220 ("Pi")
24221 ("Rho")
24222 ("Sigma")
24223 ("Tau")
24224 ("Upsilon")
24225 ("Phi")
24226 ("Chi")
24227 ("Psi")
24228 ("Omega")
24229 ("alpha")
24230 ("beta")
24231 ("gamma")
24232 ("delta")
24233 ("epsilon")
24234 ("varepsilon"."&epsilon;")
24235 ("zeta")
24236 ("eta")
24237 ("theta")
24238 ("iota")
24239 ("kappa")
24240 ("lambda")
24241 ("mu")
24242 ("nu")
24243 ("xi")
24244 ("omicron")
24245 ("pi")
24246 ("rho")
24247 ("sigmaf") ("varsigma"."&sigmaf;")
24248 ("sigma")
24249 ("tau")
24250 ("upsilon")
24251 ("phi")
24252 ("chi")
24253 ("psi")
24254 ("omega")
24255 ("thetasym") ("vartheta"."&thetasym;")
24256 ("upsih")
24257 ("piv")
24258 ("bull") ("bullet"."&bull;")
24259 ("hellip") ("dots"."&hellip;")
24260 ("prime")
24261 ("Prime")
24262 ("oline")
24263 ("frasl")
24264 ("weierp")
24265 ("image")
24266 ("real")
24267 ("trade")
24268 ("alefsym")
24269 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24270 ("uarr") ("uparrow"."&uarr;")
24271 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24272 ("darr")("downarrow"."&darr;")
24273 ("harr") ("leftrightarrow"."&harr;")
24274 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24275 ("lArr") ("Leftarrow"."&lArr;")
24276 ("uArr") ("Uparrow"."&uArr;")
24277 ("rArr") ("Rightarrow"."&rArr;")
24278 ("dArr") ("Downarrow"."&dArr;")
24279 ("hArr") ("Leftrightarrow"."&hArr;")
24280 ("forall")
24281 ("part") ("partial"."&part;")
24282 ("exist") ("exists"."&exist;")
24283 ("empty") ("emptyset"."&empty;")
24284 ("nabla")
24285 ("isin") ("in"."&isin;")
24286 ("notin")
24287 ("ni")
24288 ("prod")
24289 ("sum")
24290 ("minus")
24291 ("lowast") ("ast"."&lowast;")
24292 ("radic")
24293 ("prop") ("proptp"."&prop;")
24294 ("infin") ("infty"."&infin;")
24295 ("ang") ("angle"."&ang;")
24296 ("and") ("wedge"."&and;")
24297 ("or") ("vee"."&or;")
24298 ("cap")
24299 ("cup")
24300 ("int")
24301 ("there4")
24302 ("sim")
24303 ("cong") ("simeq"."&cong;")
24304 ("asymp")("approx"."&asymp;")
24305 ("ne") ("neq"."&ne;")
24306 ("equiv")
24307 ("le")
24308 ("ge")
24309 ("sub") ("subset"."&sub;")
24310 ("sup") ("supset"."&sup;")
24311 ("nsub")
24312 ("sube")
24313 ("supe")
24314 ("oplus")
24315 ("otimes")
24316 ("perp")
24317 ("sdot") ("cdot"."&sdot;")
24318 ("lceil")
24319 ("rceil")
24320 ("lfloor")
24321 ("rfloor")
24322 ("lang")
24323 ("rang")
24324 ("loz") ("Diamond"."&loz;")
24325 ("spades") ("spadesuit"."&spades;")
24326 ("clubs") ("clubsuit"."&clubs;")
24327 ("hearts") ("diamondsuit"."&hearts;")
24328 ("diams") ("diamondsuit"."&diams;")
24329 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24330 ("quot")
24331 ("amp")
24332 ("lt")
24333 ("gt")
24334 ("OElig")
24335 ("oelig")
24336 ("Scaron")
24337 ("scaron")
24338 ("Yuml")
24339 ("circ")
24340 ("tilde")
24341 ("ensp")
24342 ("emsp")
24343 ("thinsp")
24344 ("zwnj")
24345 ("zwj")
24346 ("lrm")
24347 ("rlm")
24348 ("ndash")
24349 ("mdash")
24350 ("lsquo")
24351 ("rsquo")
24352 ("sbquo")
24353 ("ldquo")
24354 ("rdquo")
24355 ("bdquo")
24356 ("dagger")
24357 ("Dagger")
24358 ("permil")
24359 ("lsaquo")
24360 ("rsaquo")
24361 ("euro")
24363 ("arccos"."arccos")
24364 ("arcsin"."arcsin")
24365 ("arctan"."arctan")
24366 ("arg"."arg")
24367 ("cos"."cos")
24368 ("cosh"."cosh")
24369 ("cot"."cot")
24370 ("coth"."coth")
24371 ("csc"."csc")
24372 ("deg"."deg")
24373 ("det"."det")
24374 ("dim"."dim")
24375 ("exp"."exp")
24376 ("gcd"."gcd")
24377 ("hom"."hom")
24378 ("inf"."inf")
24379 ("ker"."ker")
24380 ("lg"."lg")
24381 ("lim"."lim")
24382 ("liminf"."liminf")
24383 ("limsup"."limsup")
24384 ("ln"."ln")
24385 ("log"."log")
24386 ("max"."max")
24387 ("min"."min")
24388 ("Pr"."Pr")
24389 ("sec"."sec")
24390 ("sin"."sin")
24391 ("sinh"."sinh")
24392 ("sup"."sup")
24393 ("tan"."tan")
24394 ("tanh"."tanh")
24396 "Entities for TeX->HTML translation.
24397 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24398 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24399 In that case, \"\\ent\" will be translated to \"&other;\".
24400 The list contains HTML entities for Latin-1, Greek and other symbols.
24401 It is supplemented by a number of commonly used TeX macros with appropriate
24402 translations. There is currently no way for users to extend this.")
24404 ;;; General functions for all backends
24406 (defun org-cleaned-string-for-export (string &rest parameters)
24407 "Cleanup a buffer STRING so that links can be created safely."
24408 (interactive)
24409 (let* ((re-radio (and org-target-link-regexp
24410 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24411 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24412 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24413 (re-archive (concat ":" org-archive-tag ":"))
24414 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24415 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24416 (htmlp (plist-get parameters :for-html))
24417 (asciip (plist-get parameters :for-ascii))
24418 (latexp (plist-get parameters :for-LaTeX))
24419 (commentsp (plist-get parameters :comments))
24420 (archived-trees (plist-get parameters :archived-trees))
24421 (inhibit-read-only t)
24422 (drawers org-drawers)
24423 (exp-drawers (plist-get parameters :drawers))
24424 (outline-regexp "\\*+ ")
24425 a b xx
24426 rtn p)
24427 (with-current-buffer (get-buffer-create " org-mode-tmp")
24428 (erase-buffer)
24429 (insert string)
24430 ;; Remove license-to-kill stuff
24431 (while (setq p (text-property-any (point-min) (point-max)
24432 :org-license-to-kill t))
24433 (delete-region p (next-single-property-change p :org-license-to-kill)))
24435 (let ((org-inhibit-startup t)) (org-mode))
24436 (untabify (point-min) (point-max))
24438 ;; Get rid of drawers
24439 (unless (eq t exp-drawers)
24440 (goto-char (point-min))
24441 (let ((re (concat "^[ \t]*:\\("
24442 (mapconcat
24443 'identity
24444 (org-delete-all exp-drawers
24445 (copy-sequence drawers))
24446 "\\|")
24447 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24448 (while (re-search-forward re nil t)
24449 (replace-match ""))))
24451 ;; Get the correct stuff before the first headline
24452 (when (plist-get parameters :skip-before-1st-heading)
24453 (goto-char (point-min))
24454 (when (re-search-forward "^\\*+[ \t]" nil t)
24455 (delete-region (point-min) (match-beginning 0))
24456 (goto-char (point-min))
24457 (insert "\n")))
24458 (when (plist-get parameters :add-text)
24459 (goto-char (point-min))
24460 (insert (plist-get parameters :add-text) "\n"))
24462 ;; Get rid of archived trees
24463 (when (not (eq archived-trees t))
24464 (goto-char (point-min))
24465 (while (re-search-forward re-archive nil t)
24466 (if (not (org-on-heading-p t))
24467 (org-end-of-subtree t)
24468 (beginning-of-line 1)
24469 (setq a (if archived-trees
24470 (1+ (point-at-eol)) (point))
24471 b (org-end-of-subtree t))
24472 (if (> b a) (delete-region a b)))))
24474 ;; Find targets in comments and move them out of comments,
24475 ;; but mark them as targets that should be invisible
24476 (goto-char (point-min))
24477 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24478 (replace-match "\\1(INVISIBLE)"))
24480 ;; Protect backend specific stuff, throw away the others.
24481 (let ((formatters
24482 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24483 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24484 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24485 fmt)
24486 (goto-char (point-min))
24487 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24488 (goto-char (match-end 0))
24489 (while (not (looking-at "#\\+END_EXAMPLE"))
24490 (insert ": ")
24491 (beginning-of-line 2)))
24492 (goto-char (point-min))
24493 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24494 (add-text-properties (match-beginning 0) (match-end 0)
24495 '(org-protected t)))
24496 (while formatters
24497 (setq fmt (pop formatters))
24498 (when (car fmt)
24499 (goto-char (point-min))
24500 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24501 ":[ \t]*\\(.*\\)") nil t)
24502 (replace-match "\\1" t)
24503 (add-text-properties
24504 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24505 '(org-protected t))))
24506 (goto-char (point-min))
24507 (while (re-search-forward
24508 (concat "^#\\+"
24509 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24510 (cadddr fmt) "\\>.*\n?") nil t)
24511 (if (car fmt)
24512 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24513 '(org-protected t))
24514 (delete-region (match-beginning 0) (match-end 0))))))
24516 ;; Protect quoted subtrees
24517 (goto-char (point-min))
24518 (while (re-search-forward re-quote nil t)
24519 (goto-char (match-beginning 0))
24520 (end-of-line 1)
24521 (add-text-properties (point) (org-end-of-subtree t)
24522 '(org-protected t)))
24524 ;; Protect verbatim elements
24525 (goto-char (point-min))
24526 (while (re-search-forward org-verbatim-re nil t)
24527 (add-text-properties (match-beginning 4) (match-end 4)
24528 '(org-protected t))
24529 (goto-char (1+ (match-end 4))))
24531 ;; Remove subtrees that are commented
24532 (goto-char (point-min))
24533 (while (re-search-forward re-commented nil t)
24534 (goto-char (match-beginning 0))
24535 (delete-region (point) (org-end-of-subtree t)))
24537 ;; Remove special table lines
24538 (when org-export-table-remove-special-lines
24539 (goto-char (point-min))
24540 (while (re-search-forward "^[ \t]*|" nil t)
24541 (beginning-of-line 1)
24542 (if (or (looking-at "[ \t]*| *[!_^] *|")
24543 (and (looking-at ".*?| *<[0-9]+> *|")
24544 (not (looking-at ".*?| *[^ <|]"))))
24545 (delete-region (max (point-min) (1- (point-at-bol)))
24546 (point-at-eol))
24547 (end-of-line 1))))
24549 ;; Specific LaTeX stuff
24550 (when latexp
24551 (require 'org-export-latex nil)
24552 (org-export-latex-cleaned-string))
24554 (when asciip
24555 (org-export-ascii-clean-string))
24557 ;; Specific HTML stuff
24558 (when htmlp
24559 ;; Convert LaTeX fragments to images
24560 (when (plist-get parameters :LaTeX-fragments)
24561 (org-format-latex
24562 (concat "ltxpng/" (file-name-sans-extension
24563 (file-name-nondirectory
24564 org-current-export-file)))
24565 org-current-export-dir nil "Creating LaTeX image %s"))
24566 (message "Exporting..."))
24568 ;; Remove or replace comments
24569 (goto-char (point-min))
24570 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24571 (if commentsp
24572 (progn (add-text-properties
24573 (match-beginning 0) (match-end 0) '(org-protected t))
24574 (replace-match (format commentsp (match-string 1)) t t))
24575 (replace-match "")))
24577 ;; Find matches for radio targets and turn them into internal links
24578 (goto-char (point-min))
24579 (when re-radio
24580 (while (re-search-forward re-radio nil t)
24581 (org-if-unprotected
24582 (replace-match "\\1[[\\2]]"))))
24584 ;; Find all links that contain a newline and put them into a single line
24585 (goto-char (point-min))
24586 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24587 (org-if-unprotected
24588 (replace-match "\\1 \\3")
24589 (goto-char (match-beginning 0))))
24592 ;; Normalize links: Convert angle and plain links into bracket links
24593 ;; Expand link abbreviations
24594 (goto-char (point-min))
24595 (while (re-search-forward re-plain-link nil t)
24596 (goto-char (1- (match-end 0)))
24597 (org-if-unprotected
24598 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24599 ":" (match-string 3) "]]")))
24600 ;; added 'org-link face to links
24601 (put-text-property 0 (length s) 'face 'org-link s)
24602 (replace-match s t t))))
24603 (goto-char (point-min))
24604 (while (re-search-forward re-angle-link nil t)
24605 (goto-char (1- (match-end 0)))
24606 (org-if-unprotected
24607 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24608 ":" (match-string 3) "]]")))
24609 (put-text-property 0 (length s) 'face 'org-link s)
24610 (replace-match s t t))))
24611 (goto-char (point-min))
24612 (while (re-search-forward org-bracket-link-regexp nil t)
24613 (org-if-unprotected
24614 (let* ((s (concat "[[" (setq xx (save-match-data
24615 (org-link-expand-abbrev (match-string 1))))
24617 (if (match-end 3)
24618 (match-string 2)
24619 (concat "[" xx "]"))
24620 "]")))
24621 (put-text-property 0 (length s) 'face 'org-link s)
24622 (replace-match s t t))))
24624 ;; Find multiline emphasis and put them into single line
24625 (when (plist-get parameters :emph-multiline)
24626 (goto-char (point-min))
24627 (while (re-search-forward org-emph-re nil t)
24628 (if (not (= (char-after (match-beginning 3))
24629 (char-after (match-beginning 4))))
24630 (org-if-unprotected
24631 (subst-char-in-region (match-beginning 0) (match-end 0)
24632 ?\n ?\ t)
24633 (goto-char (1- (match-end 0))))
24634 (goto-char (1+ (match-beginning 0))))))
24636 (setq rtn (buffer-string)))
24637 (kill-buffer " org-mode-tmp")
24638 rtn))
24640 (defun org-export-grab-title-from-buffer ()
24641 "Get a title for the current document, from looking at the buffer."
24642 (let ((inhibit-read-only t))
24643 (save-excursion
24644 (goto-char (point-min))
24645 (let ((end (save-excursion (outline-next-heading) (point))))
24646 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24647 ;; Mark the line so that it will not be exported as normal text.
24648 (org-unmodified
24649 (add-text-properties (match-beginning 0) (match-end 0)
24650 (list :org-license-to-kill t)))
24651 ;; Return the title string
24652 (org-trim (match-string 0)))))))
24654 (defun org-export-get-title-from-subtree ()
24655 "Return subtree title and exclude it from export."
24656 (let (title (m (mark)))
24657 (save-excursion
24658 (goto-char (region-beginning))
24659 (when (and (org-at-heading-p)
24660 (>= (org-end-of-subtree t t) (region-end)))
24661 ;; This is a subtree, we take the title from the first heading
24662 (goto-char (region-beginning))
24663 (looking-at org-todo-line-regexp)
24664 (setq title (match-string 3))
24665 (org-unmodified
24666 (add-text-properties (point) (1+ (point-at-eol))
24667 (list :org-license-to-kill t)))))
24668 title))
24670 (defun org-solidify-link-text (s &optional alist)
24671 "Take link text and make a safe target out of it."
24672 (save-match-data
24673 (let* ((rtn
24674 (mapconcat
24675 'identity
24676 (org-split-string s "[ \t\r\n]+") "--"))
24677 (a (assoc rtn alist)))
24678 (or (cdr a) rtn))))
24680 (defun org-get-min-level (lines)
24681 "Get the minimum level in LINES."
24682 (let ((re "^\\(\\*+\\) ") l min)
24683 (catch 'exit
24684 (while (setq l (pop lines))
24685 (if (string-match re l)
24686 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24687 1)))
24689 ;; Variable holding the vector with section numbers
24690 (defvar org-section-numbers (make-vector org-level-max 0))
24692 (defun org-init-section-numbers ()
24693 "Initialize the vector for the section numbers."
24694 (let* ((level -1)
24695 (numbers (nreverse (org-split-string "" "\\.")))
24696 (depth (1- (length org-section-numbers)))
24697 (i depth) number-string)
24698 (while (>= i 0)
24699 (if (> i level)
24700 (aset org-section-numbers i 0)
24701 (setq number-string (or (car numbers) "0"))
24702 (if (string-match "\\`[A-Z]\\'" number-string)
24703 (aset org-section-numbers i
24704 (- (string-to-char number-string) ?A -1))
24705 (aset org-section-numbers i (string-to-number number-string)))
24706 (pop numbers))
24707 (setq i (1- i)))))
24709 (defun org-section-number (&optional level)
24710 "Return a string with the current section number.
24711 When LEVEL is non-nil, increase section numbers on that level."
24712 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24713 (when level
24714 (when (> level -1)
24715 (aset org-section-numbers
24716 level (1+ (aref org-section-numbers level))))
24717 (setq idx (1+ level))
24718 (while (<= idx depth)
24719 (if (not (= idx 1))
24720 (aset org-section-numbers idx 0))
24721 (setq idx (1+ idx))))
24722 (setq idx 0)
24723 (while (<= idx depth)
24724 (setq n (aref org-section-numbers idx))
24725 (setq string (concat string (if (not (string= string "")) "." "")
24726 (int-to-string n)))
24727 (setq idx (1+ idx)))
24728 (save-match-data
24729 (if (string-match "\\`\\([@0]\\.\\)+" string)
24730 (setq string (replace-match "" t nil string)))
24731 (if (string-match "\\(\\.0\\)+\\'" string)
24732 (setq string (replace-match "" t nil string))))
24733 string))
24735 ;;; ASCII export
24737 (defvar org-last-level nil) ; dynamically scoped variable
24738 (defvar org-min-level nil) ; dynamically scoped variable
24739 (defvar org-levels-open nil) ; dynamically scoped parameter
24740 (defvar org-ascii-current-indentation nil) ; For communication
24742 (defun org-export-as-ascii (arg)
24743 "Export the outline as a pretty ASCII file.
24744 If there is an active region, export only the region.
24745 The prefix ARG specifies how many levels of the outline should become
24746 underlined headlines. The default is 3."
24747 (interactive "P")
24748 (setq-default org-todo-line-regexp org-todo-line-regexp)
24749 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24750 (org-infile-export-plist)))
24751 (region-p (org-region-active-p))
24752 (subtree-p
24753 (when region-p
24754 (save-excursion
24755 (goto-char (region-beginning))
24756 (and (org-at-heading-p)
24757 (>= (org-end-of-subtree t t) (region-end))))))
24758 (custom-times org-display-custom-times)
24759 (org-ascii-current-indentation '(0 . 0))
24760 (level 0) line txt
24761 (umax nil)
24762 (umax-toc nil)
24763 (case-fold-search nil)
24764 (filename (concat (file-name-as-directory
24765 (org-export-directory :ascii opt-plist))
24766 (file-name-sans-extension
24767 (or (and subtree-p
24768 (org-entry-get (region-beginning)
24769 "EXPORT_FILE_NAME" t))
24770 (file-name-nondirectory buffer-file-name)))
24771 ".txt"))
24772 (filename (if (equal (file-truename filename)
24773 (file-truename buffer-file-name))
24774 (concat filename ".txt")
24775 filename))
24776 (buffer (find-file-noselect filename))
24777 (org-levels-open (make-vector org-level-max nil))
24778 (odd org-odd-levels-only)
24779 (date (plist-get opt-plist :date))
24780 (author (plist-get opt-plist :author))
24781 (title (or (and subtree-p (org-export-get-title-from-subtree))
24782 (plist-get opt-plist :title)
24783 (and (not
24784 (plist-get opt-plist :skip-before-1st-heading))
24785 (org-export-grab-title-from-buffer))
24786 (file-name-sans-extension
24787 (file-name-nondirectory buffer-file-name))))
24788 (email (plist-get opt-plist :email))
24789 (language (plist-get opt-plist :language))
24790 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24791 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24792 (todo nil)
24793 (lang-words nil)
24794 (region
24795 (buffer-substring
24796 (if (org-region-active-p) (region-beginning) (point-min))
24797 (if (org-region-active-p) (region-end) (point-max))))
24798 (lines (org-split-string
24799 (org-cleaned-string-for-export
24800 region
24801 :for-ascii t
24802 :skip-before-1st-heading
24803 (plist-get opt-plist :skip-before-1st-heading)
24804 :drawers (plist-get opt-plist :drawers)
24805 :verbatim-multiline t
24806 :archived-trees
24807 (plist-get opt-plist :archived-trees)
24808 :add-text (plist-get opt-plist :text))
24809 "\n"))
24810 thetoc have-headings first-heading-pos
24811 table-open table-buffer)
24813 (let ((inhibit-read-only t))
24814 (org-unmodified
24815 (remove-text-properties (point-min) (point-max)
24816 '(:org-license-to-kill t))))
24818 (setq org-min-level (org-get-min-level lines))
24819 (setq org-last-level org-min-level)
24820 (org-init-section-numbers)
24822 (find-file-noselect filename)
24824 (setq lang-words (or (assoc language org-export-language-setup)
24825 (assoc "en" org-export-language-setup)))
24826 (switch-to-buffer-other-window buffer)
24827 (erase-buffer)
24828 (fundamental-mode)
24829 ;; create local variables for all options, to make sure all called
24830 ;; functions get the correct information
24831 (mapc (lambda (x)
24832 (set (make-local-variable (cdr x))
24833 (plist-get opt-plist (car x))))
24834 org-export-plist-vars)
24835 (org-set-local 'org-odd-levels-only odd)
24836 (setq umax (if arg (prefix-numeric-value arg)
24837 org-export-headline-levels))
24838 (setq umax-toc (if (integerp org-export-with-toc)
24839 (min org-export-with-toc umax)
24840 umax))
24842 ;; File header
24843 (if title (org-insert-centered title ?=))
24844 (insert "\n")
24845 (if (and (or author email)
24846 org-export-author-info)
24847 (insert (concat (nth 1 lang-words) ": " (or author "")
24848 (if email (concat " <" email ">") "")
24849 "\n")))
24851 (cond
24852 ((and date (string-match "%" date))
24853 (setq date (format-time-string date (current-time))))
24854 (date)
24855 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24857 (if (and date org-export-time-stamp-file)
24858 (insert (concat (nth 2 lang-words) ": " date"\n")))
24860 (insert "\n\n")
24862 (if org-export-with-toc
24863 (progn
24864 (push (concat (nth 3 lang-words) "\n") thetoc)
24865 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24866 (mapc '(lambda (line)
24867 (if (string-match org-todo-line-regexp
24868 line)
24869 ;; This is a headline
24870 (progn
24871 (setq have-headings t)
24872 (setq level (- (match-end 1) (match-beginning 1))
24873 level (org-tr-level level)
24874 txt (match-string 3 line)
24875 todo
24876 (or (and org-export-mark-todo-in-toc
24877 (match-beginning 2)
24878 (not (member (match-string 2 line)
24879 org-done-keywords)))
24880 ; TODO, not DONE
24881 (and org-export-mark-todo-in-toc
24882 (= level umax-toc)
24883 (org-search-todo-below
24884 line lines level))))
24885 (setq txt (org-html-expand-for-ascii txt))
24887 (while (string-match org-bracket-link-regexp txt)
24888 (setq txt
24889 (replace-match
24890 (match-string (if (match-end 2) 3 1) txt)
24891 t t txt)))
24893 (if (and (memq org-export-with-tags '(not-in-toc nil))
24894 (string-match
24895 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24896 txt))
24897 (setq txt (replace-match "" t t txt)))
24898 (if (string-match quote-re0 txt)
24899 (setq txt (replace-match "" t t txt)))
24901 (if org-export-with-section-numbers
24902 (setq txt (concat (org-section-number level)
24903 " " txt)))
24904 (if (<= level umax-toc)
24905 (progn
24906 (push
24907 (concat
24908 (make-string
24909 (* (max 0 (- level org-min-level)) 4) ?\ )
24910 (format (if todo "%s (*)\n" "%s\n") txt))
24911 thetoc)
24912 (setq org-last-level level))
24913 ))))
24914 lines)
24915 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24917 (org-init-section-numbers)
24918 (while (setq line (pop lines))
24919 ;; Remove the quoted HTML tags.
24920 (setq line (org-html-expand-for-ascii line))
24921 ;; Remove targets
24922 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24923 (setq line (replace-match "" t t line)))
24924 ;; Replace internal links
24925 (while (string-match org-bracket-link-regexp line)
24926 (setq line (replace-match
24927 (if (match-end 3) "[\\3]" "[\\1]")
24928 t nil line)))
24929 (when custom-times
24930 (setq line (org-translate-time line)))
24931 (cond
24932 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24933 ;; a Headline
24934 (setq first-heading-pos (or first-heading-pos (point)))
24935 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24936 txt (match-string 2 line))
24937 (org-ascii-level-start level txt umax lines))
24939 ((and org-export-with-tables
24940 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24941 (if (not table-open)
24942 ;; New table starts
24943 (setq table-open t table-buffer nil))
24944 ;; Accumulate lines
24945 (setq table-buffer (cons line table-buffer))
24946 (when (or (not lines)
24947 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24948 (car lines))))
24949 (setq table-open nil
24950 table-buffer (nreverse table-buffer))
24951 (insert (mapconcat
24952 (lambda (x)
24953 (org-fix-indentation x org-ascii-current-indentation))
24954 (org-format-table-ascii table-buffer)
24955 "\n") "\n")))
24957 (setq line (org-fix-indentation line org-ascii-current-indentation))
24958 (if (and org-export-with-fixed-width
24959 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24960 (setq line (replace-match "\\1" nil nil line)))
24961 (insert line "\n"))))
24963 (normal-mode)
24965 ;; insert the table of contents
24966 (when thetoc
24967 (goto-char (point-min))
24968 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24969 (progn
24970 (goto-char (match-beginning 0))
24971 (replace-match ""))
24972 (goto-char first-heading-pos))
24973 (mapc 'insert thetoc)
24974 (or (looking-at "[ \t]*\n[ \t]*\n")
24975 (insert "\n\n")))
24977 ;; Convert whitespace place holders
24978 (goto-char (point-min))
24979 (let (beg end)
24980 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24981 (setq end (next-single-property-change beg 'org-whitespace))
24982 (goto-char beg)
24983 (delete-region beg end)
24984 (insert (make-string (- end beg) ?\ ))))
24986 (save-buffer)
24987 ;; remove display and invisible chars
24988 (let (beg end)
24989 (goto-char (point-min))
24990 (while (setq beg (next-single-property-change (point) 'display))
24991 (setq end (next-single-property-change beg 'display))
24992 (delete-region beg end)
24993 (goto-char beg)
24994 (insert "=>"))
24995 (goto-char (point-min))
24996 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24997 (setq end (next-single-property-change beg 'org-cwidth))
24998 (delete-region beg end)
24999 (goto-char beg)))
25000 (goto-char (point-min))))
25002 (defun org-export-ascii-clean-string ()
25003 "Do extra work for ASCII export"
25004 (goto-char (point-min))
25005 (while (re-search-forward org-verbatim-re nil t)
25006 (goto-char (match-end 2))
25007 (backward-delete-char 1) (insert "'")
25008 (goto-char (match-beginning 2))
25009 (delete-char 1) (insert "`")
25010 (goto-char (match-end 2))))
25012 (defun org-search-todo-below (line lines level)
25013 "Search the subtree below LINE for any TODO entries."
25014 (let ((rest (cdr (memq line lines)))
25015 (re org-todo-line-regexp)
25016 line lv todo)
25017 (catch 'exit
25018 (while (setq line (pop rest))
25019 (if (string-match re line)
25020 (progn
25021 (setq lv (- (match-end 1) (match-beginning 1))
25022 todo (and (match-beginning 2)
25023 (not (member (match-string 2 line)
25024 org-done-keywords))))
25025 ; TODO, not DONE
25026 (if (<= lv level) (throw 'exit nil))
25027 (if todo (throw 'exit t))))))))
25029 (defun org-html-expand-for-ascii (line)
25030 "Handle quoted HTML for ASCII export."
25031 (if org-export-html-expand
25032 (while (string-match "@<[^<>\n]*>" line)
25033 ;; We just remove the tags for now.
25034 (setq line (replace-match "" nil nil line))))
25035 line)
25037 (defun org-insert-centered (s &optional underline)
25038 "Insert the string S centered and underline it with character UNDERLINE."
25039 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
25040 (insert (make-string ind ?\ ) s "\n")
25041 (if underline
25042 (insert (make-string ind ?\ )
25043 (make-string (string-width s) underline)
25044 "\n"))))
25046 (defun org-ascii-level-start (level title umax &optional lines)
25047 "Insert a new level in ASCII export."
25048 (let (char (n (- level umax 1)) (ind 0))
25049 (if (> level umax)
25050 (progn
25051 (insert (make-string (* 2 n) ?\ )
25052 (char-to-string (nth (% n (length org-export-ascii-bullets))
25053 org-export-ascii-bullets))
25054 " " title "\n")
25055 ;; find the indentation of the next non-empty line
25056 (catch 'stop
25057 (while lines
25058 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
25059 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
25060 (throw 'stop (setq ind (org-get-indentation (car lines)))))
25061 (pop lines)))
25062 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
25063 (if (or (not (equal (char-before) ?\n))
25064 (not (equal (char-before (1- (point))) ?\n)))
25065 (insert "\n"))
25066 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
25067 (unless org-export-with-tags
25068 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25069 (setq title (replace-match "" t t title))))
25070 (if org-export-with-section-numbers
25071 (setq title (concat (org-section-number level) " " title)))
25072 (insert title "\n" (make-string (string-width title) char) "\n")
25073 (setq org-ascii-current-indentation '(0 . 0)))))
25075 (defun org-export-visible (type arg)
25076 "Create a copy of the visible part of the current buffer, and export it.
25077 The copy is created in a temporary buffer and removed after use.
25078 TYPE is the final key (as a string) that also select the export command in
25079 the `C-c C-e' export dispatcher.
25080 As a special case, if the you type SPC at the prompt, the temporary
25081 org-mode file will not be removed but presented to you so that you can
25082 continue to use it. The prefix arg ARG is passed through to the exporting
25083 command."
25084 (interactive
25085 (list (progn
25086 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25087 (read-char-exclusive))
25088 current-prefix-arg))
25089 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25090 (error "Invalid export key"))
25091 (let* ((binding (cdr (assoc type
25092 '((?a . org-export-as-ascii)
25093 (?\C-a . org-export-as-ascii)
25094 (?b . org-export-as-html-and-open)
25095 (?\C-b . org-export-as-html-and-open)
25096 (?h . org-export-as-html)
25097 (?H . org-export-as-html-to-buffer)
25098 (?R . org-export-region-as-html)
25099 (?x . org-export-as-xoxo)))))
25100 (keepp (equal type ?\ ))
25101 (file buffer-file-name)
25102 (buffer (get-buffer-create "*Org Export Visible*"))
25103 s e)
25104 ;; Need to hack the drawers here.
25105 (save-excursion
25106 (goto-char (point-min))
25107 (while (re-search-forward org-drawer-regexp nil t)
25108 (goto-char (match-beginning 1))
25109 (or (org-invisible-p) (org-flag-drawer nil))))
25110 (with-current-buffer buffer (erase-buffer))
25111 (save-excursion
25112 (setq s (goto-char (point-min)))
25113 (while (not (= (point) (point-max)))
25114 (goto-char (org-find-invisible))
25115 (append-to-buffer buffer s (point))
25116 (setq s (goto-char (org-find-visible))))
25117 (org-cycle-hide-drawers 'all)
25118 (goto-char (point-min))
25119 (unless keepp
25120 ;; Copy all comment lines to the end, to make sure #+ settings are
25121 ;; still available for the second export step. Kind of a hack, but
25122 ;; does do the trick.
25123 (if (looking-at "#[^\r\n]*")
25124 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25125 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25126 (append-to-buffer buffer (1+ (match-beginning 0))
25127 (min (point-max) (1+ (match-end 0))))))
25128 (set-buffer buffer)
25129 (let ((buffer-file-name file)
25130 (org-inhibit-startup t))
25131 (org-mode)
25132 (show-all)
25133 (unless keepp (funcall binding arg))))
25134 (if (not keepp)
25135 (kill-buffer buffer)
25136 (switch-to-buffer-other-window buffer)
25137 (goto-char (point-min)))))
25139 (defun org-find-visible ()
25140 (let ((s (point)))
25141 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25142 (get-char-property s 'invisible)))
25144 (defun org-find-invisible ()
25145 (let ((s (point)))
25146 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25147 (not (get-char-property s 'invisible))))
25150 ;;; HTML export
25152 (defun org-get-current-options ()
25153 "Return a string with current options as keyword options.
25154 Does include HTML export options as well as TODO and CATEGORY stuff."
25155 (format
25156 "#+TITLE: %s
25157 #+AUTHOR: %s
25158 #+EMAIL: %s
25159 #+LANGUAGE: %s
25160 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25161 #+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
25162 #+CATEGORY: %s
25163 #+SEQ_TODO: %s
25164 #+TYP_TODO: %s
25165 #+PRIORITIES: %c %c %c
25166 #+DRAWERS: %s
25167 #+STARTUP: %s %s %s %s %s
25168 #+TAGS: %s
25169 #+ARCHIVE: %s
25170 #+LINK: %s
25172 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25173 org-export-headline-levels
25174 org-export-with-section-numbers
25175 org-export-with-toc
25176 org-export-preserve-breaks
25177 org-export-html-expand
25178 org-export-with-fixed-width
25179 org-export-with-tables
25180 org-export-with-sub-superscripts
25181 org-export-with-special-strings
25182 org-export-with-footnotes
25183 org-export-with-emphasize
25184 org-export-with-TeX-macros
25185 org-export-with-LaTeX-fragments
25186 org-export-skip-text-before-1st-heading
25187 org-export-with-drawers
25188 org-export-with-tags
25189 (file-name-nondirectory buffer-file-name)
25190 "TODO FEEDBACK VERIFY DONE"
25191 "Me Jason Marie DONE"
25192 org-highest-priority org-lowest-priority org-default-priority
25193 (mapconcat 'identity org-drawers " ")
25194 (cdr (assoc org-startup-folded
25195 '((nil . "showall") (t . "overview") (content . "content"))))
25196 (if org-odd-levels-only "odd" "oddeven")
25197 (if org-hide-leading-stars "hidestars" "showstars")
25198 (if org-startup-align-all-tables "align" "noalign")
25199 (cond ((eq org-log-done t) "logdone")
25200 ((equal org-log-done 'note) "lognotedone")
25201 ((not org-log-done) "nologdone"))
25202 (or (mapconcat (lambda (x)
25203 (cond
25204 ((equal '(:startgroup) x) "{")
25205 ((equal '(:endgroup) x) "}")
25206 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25207 (t (car x))))
25208 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25209 org-archive-location
25210 "org file:~/org/%s.org"
25213 (defun org-insert-export-options-template ()
25214 "Insert into the buffer a template with information for exporting."
25215 (interactive)
25216 (if (not (bolp)) (newline))
25217 (let ((s (org-get-current-options)))
25218 (and (string-match "#\\+CATEGORY" s)
25219 (setq s (substring s 0 (match-beginning 0))))
25220 (insert s)))
25222 (defun org-toggle-fixed-width-section (arg)
25223 "Toggle the fixed-width export.
25224 If there is no active region, the QUOTE keyword at the current headline is
25225 inserted or removed. When present, it causes the text between this headline
25226 and the next to be exported as fixed-width text, and unmodified.
25227 If there is an active region, this command adds or removes a colon as the
25228 first character of this line. If the first character of a line is a colon,
25229 this line is also exported in fixed-width font."
25230 (interactive "P")
25231 (let* ((cc 0)
25232 (regionp (org-region-active-p))
25233 (beg (if regionp (region-beginning) (point)))
25234 (end (if regionp (region-end)))
25235 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25236 (case-fold-search nil)
25237 (re "[ \t]*\\(:\\)")
25238 off)
25239 (if regionp
25240 (save-excursion
25241 (goto-char beg)
25242 (setq cc (current-column))
25243 (beginning-of-line 1)
25244 (setq off (looking-at re))
25245 (while (> nlines 0)
25246 (setq nlines (1- nlines))
25247 (beginning-of-line 1)
25248 (cond
25249 (arg
25250 (move-to-column cc t)
25251 (insert ":\n")
25252 (forward-line -1))
25253 ((and off (looking-at re))
25254 (replace-match "" t t nil 1))
25255 ((not off) (move-to-column cc t) (insert ":")))
25256 (forward-line 1)))
25257 (save-excursion
25258 (org-back-to-heading)
25259 (if (looking-at (concat outline-regexp
25260 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25261 (replace-match "" t t nil 1)
25262 (if (looking-at outline-regexp)
25263 (progn
25264 (goto-char (match-end 0))
25265 (insert org-quote-string " "))))))))
25267 (defun org-export-as-html-and-open (arg)
25268 "Export the outline as HTML and immediately open it with a browser.
25269 If there is an active region, export only the region.
25270 The prefix ARG specifies how many levels of the outline should become
25271 headlines. The default is 3. Lower levels will become bulleted lists."
25272 (interactive "P")
25273 (org-export-as-html arg 'hidden)
25274 (org-open-file buffer-file-name))
25276 (defun org-export-as-html-batch ()
25277 "Call `org-export-as-html', may be used in batch processing as
25278 emacs --batch
25279 --load=$HOME/lib/emacs/org.el
25280 --eval \"(setq org-export-headline-levels 2)\"
25281 --visit=MyFile --funcall org-export-as-html-batch"
25282 (org-export-as-html org-export-headline-levels 'hidden))
25284 (defun org-export-as-html-to-buffer (arg)
25285 "Call `org-exort-as-html` with output to a temporary buffer.
25286 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25287 (interactive "P")
25288 (org-export-as-html arg nil nil "*Org HTML Export*")
25289 (switch-to-buffer-other-window "*Org HTML Export*"))
25291 (defun org-replace-region-by-html (beg end)
25292 "Assume the current region has org-mode syntax, and convert it to HTML.
25293 This can be used in any buffer. For example, you could write an
25294 itemized list in org-mode syntax in an HTML buffer and then use this
25295 command to convert it."
25296 (interactive "r")
25297 (let (reg html buf pop-up-frames)
25298 (save-window-excursion
25299 (if (org-mode-p)
25300 (setq html (org-export-region-as-html
25301 beg end t 'string))
25302 (setq reg (buffer-substring beg end)
25303 buf (get-buffer-create "*Org tmp*"))
25304 (with-current-buffer buf
25305 (erase-buffer)
25306 (insert reg)
25307 (org-mode)
25308 (setq html (org-export-region-as-html
25309 (point-min) (point-max) t 'string)))
25310 (kill-buffer buf)))
25311 (delete-region beg end)
25312 (insert html)))
25314 (defun org-export-region-as-html (beg end &optional body-only buffer)
25315 "Convert region from BEG to END in org-mode buffer to HTML.
25316 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25317 contents, and only produce the region of converted text, useful for
25318 cut-and-paste operations.
25319 If BUFFER is a buffer or a string, use/create that buffer as a target
25320 of the converted HTML. If BUFFER is the symbol `string', return the
25321 produced HTML as a string and leave not buffer behind. For example,
25322 a Lisp program could call this function in the following way:
25324 (setq html (org-export-region-as-html beg end t 'string))
25326 When called interactively, the output buffer is selected, and shown
25327 in a window. A non-interactive call will only retunr the buffer."
25328 (interactive "r\nP")
25329 (when (interactive-p)
25330 (setq buffer "*Org HTML Export*"))
25331 (let ((transient-mark-mode t) (zmacs-regions t)
25332 rtn)
25333 (goto-char end)
25334 (set-mark (point)) ;; to activate the region
25335 (goto-char beg)
25336 (setq rtn (org-export-as-html
25337 nil nil nil
25338 buffer body-only))
25339 (if (fboundp 'deactivate-mark) (deactivate-mark))
25340 (if (and (interactive-p) (bufferp rtn))
25341 (switch-to-buffer-other-window rtn)
25342 rtn)))
25344 (defvar html-table-tag nil) ; dynamically scoped into this.
25345 (defun org-export-as-html (arg &optional hidden ext-plist
25346 to-buffer body-only pub-dir)
25347 "Export the outline as a pretty HTML file.
25348 If there is an active region, export only the region. The prefix
25349 ARG specifies how many levels of the outline should become
25350 headlines. The default is 3. Lower levels will become bulleted
25351 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25352 EXT-PLIST is a property list with external parameters overriding
25353 org-mode's default settings, but still inferior to file-local
25354 settings. When TO-BUFFER is non-nil, create a buffer with that
25355 name and export to that buffer. If TO-BUFFER is the symbol
25356 `string', don't leave any buffer behind but just return the
25357 resulting HTML as a string. When BODY-ONLY is set, don't produce
25358 the file header and footer, simply return the content of
25359 <body>...</body>, without even the body tags themselves. When
25360 PUB-DIR is set, use this as the publishing directory."
25361 (interactive "P")
25363 ;; Make sure we have a file name when we need it.
25364 (when (and (not (or to-buffer body-only))
25365 (not buffer-file-name))
25366 (if (buffer-base-buffer)
25367 (org-set-local 'buffer-file-name
25368 (with-current-buffer (buffer-base-buffer)
25369 buffer-file-name))
25370 (error "Need a file name to be able to export.")))
25372 (message "Exporting...")
25373 (setq-default org-todo-line-regexp org-todo-line-regexp)
25374 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25375 (setq-default org-done-keywords org-done-keywords)
25376 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25377 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25378 ext-plist
25379 (org-infile-export-plist)))
25381 (style (plist-get opt-plist :style))
25382 (html-extension (plist-get opt-plist :html-extension))
25383 (link-validate (plist-get opt-plist :link-validation-function))
25384 valid thetoc have-headings first-heading-pos
25385 (odd org-odd-levels-only)
25386 (region-p (org-region-active-p))
25387 (subtree-p
25388 (when region-p
25389 (save-excursion
25390 (goto-char (region-beginning))
25391 (and (org-at-heading-p)
25392 (>= (org-end-of-subtree t t) (region-end))))))
25393 ;; The following two are dynamically scoped into other
25394 ;; routines below.
25395 (org-current-export-dir
25396 (or pub-dir (org-export-directory :html opt-plist)))
25397 (org-current-export-file buffer-file-name)
25398 (level 0) (line "") (origline "") txt todo
25399 (umax nil)
25400 (umax-toc nil)
25401 (filename (if to-buffer nil
25402 (expand-file-name
25403 (concat
25404 (file-name-sans-extension
25405 (or (and subtree-p
25406 (org-entry-get (region-beginning)
25407 "EXPORT_FILE_NAME" t))
25408 (file-name-nondirectory buffer-file-name)))
25409 "." html-extension)
25410 (file-name-as-directory
25411 (or pub-dir (org-export-directory :html opt-plist))))))
25412 (current-dir (if buffer-file-name
25413 (file-name-directory buffer-file-name)
25414 default-directory))
25415 (buffer (if to-buffer
25416 (cond
25417 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25418 (t (get-buffer-create to-buffer)))
25419 (find-file-noselect filename)))
25420 (org-levels-open (make-vector org-level-max nil))
25421 (date (plist-get opt-plist :date))
25422 (author (plist-get opt-plist :author))
25423 (title (or (and subtree-p (org-export-get-title-from-subtree))
25424 (plist-get opt-plist :title)
25425 (and (not
25426 (plist-get opt-plist :skip-before-1st-heading))
25427 (org-export-grab-title-from-buffer))
25428 (and buffer-file-name
25429 (file-name-sans-extension
25430 (file-name-nondirectory buffer-file-name)))
25431 "UNTITLED"))
25432 (html-table-tag (plist-get opt-plist :html-table-tag))
25433 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25434 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25435 (inquote nil)
25436 (infixed nil)
25437 (in-local-list nil)
25438 (local-list-num nil)
25439 (local-list-indent nil)
25440 (llt org-plain-list-ordered-item-terminator)
25441 (email (plist-get opt-plist :email))
25442 (language (plist-get opt-plist :language))
25443 (lang-words nil)
25444 (target-alist nil) tg
25445 (head-count 0) cnt
25446 (start 0)
25447 (coding-system (and (boundp 'buffer-file-coding-system)
25448 buffer-file-coding-system))
25449 (coding-system-for-write (or org-export-html-coding-system
25450 coding-system))
25451 (save-buffer-coding-system (or org-export-html-coding-system
25452 coding-system))
25453 (charset (and coding-system-for-write
25454 (fboundp 'coding-system-get)
25455 (coding-system-get coding-system-for-write
25456 'mime-charset)))
25457 (region
25458 (buffer-substring
25459 (if region-p (region-beginning) (point-min))
25460 (if region-p (region-end) (point-max))))
25461 (lines
25462 (org-split-string
25463 (org-cleaned-string-for-export
25464 region
25465 :emph-multiline t
25466 :for-html t
25467 :skip-before-1st-heading
25468 (plist-get opt-plist :skip-before-1st-heading)
25469 :drawers (plist-get opt-plist :drawers)
25470 :archived-trees
25471 (plist-get opt-plist :archived-trees)
25472 :add-text
25473 (plist-get opt-plist :text)
25474 :LaTeX-fragments
25475 (plist-get opt-plist :LaTeX-fragments))
25476 "[\r\n]"))
25477 table-open type
25478 table-buffer table-orig-buffer
25479 ind start-is-num starter didclose
25480 rpl path desc descp desc1 desc2 link
25483 (let ((inhibit-read-only t))
25484 (org-unmodified
25485 (remove-text-properties (point-min) (point-max)
25486 '(:org-license-to-kill t))))
25488 (message "Exporting...")
25490 (setq org-min-level (org-get-min-level lines))
25491 (setq org-last-level org-min-level)
25492 (org-init-section-numbers)
25494 (cond
25495 ((and date (string-match "%" date))
25496 (setq date (format-time-string date (current-time))))
25497 (date)
25498 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25500 ;; Get the language-dependent settings
25501 (setq lang-words (or (assoc language org-export-language-setup)
25502 (assoc "en" org-export-language-setup)))
25504 ;; Switch to the output buffer
25505 (set-buffer buffer)
25506 (let ((inhibit-read-only t)) (erase-buffer))
25507 (fundamental-mode)
25509 (and (fboundp 'set-buffer-file-coding-system)
25510 (set-buffer-file-coding-system coding-system-for-write))
25512 (let ((case-fold-search nil)
25513 (org-odd-levels-only odd))
25514 ;; create local variables for all options, to make sure all called
25515 ;; functions get the correct information
25516 (mapc (lambda (x)
25517 (set (make-local-variable (cdr x))
25518 (plist-get opt-plist (car x))))
25519 org-export-plist-vars)
25520 (setq umax (if arg (prefix-numeric-value arg)
25521 org-export-headline-levels))
25522 (setq umax-toc (if (integerp org-export-with-toc)
25523 (min org-export-with-toc umax)
25524 umax))
25525 (unless body-only
25526 ;; File header
25527 (insert (format
25528 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25529 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25530 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25531 lang=\"%s\" xml:lang=\"%s\">
25532 <head>
25533 <title>%s</title>
25534 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25535 <meta name=\"generator\" content=\"Org-mode\"/>
25536 <meta name=\"generated\" content=\"%s\"/>
25537 <meta name=\"author\" content=\"%s\"/>
25539 </head><body>
25541 language language (org-html-expand title)
25542 (or charset "iso-8859-1") date author style))
25544 (insert (or (plist-get opt-plist :preamble) ""))
25546 (when (plist-get opt-plist :auto-preamble)
25547 (if title (insert (format org-export-html-title-format
25548 (org-html-expand title))))))
25550 (if (and org-export-with-toc (not body-only))
25551 (progn
25552 (push (format "<h%d>%s</h%d>\n"
25553 org-export-html-toplevel-hlevel
25554 (nth 3 lang-words)
25555 org-export-html-toplevel-hlevel)
25556 thetoc)
25557 (push "<ul>\n<li>" thetoc)
25558 (setq lines
25559 (mapcar '(lambda (line)
25560 (if (string-match org-todo-line-regexp line)
25561 ;; This is a headline
25562 (progn
25563 (setq have-headings t)
25564 (setq level (- (match-end 1) (match-beginning 1))
25565 level (org-tr-level level)
25566 txt (save-match-data
25567 (org-html-expand
25568 (org-export-cleanup-toc-line
25569 (match-string 3 line))))
25570 todo
25571 (or (and org-export-mark-todo-in-toc
25572 (match-beginning 2)
25573 (not (member (match-string 2 line)
25574 org-done-keywords)))
25575 ; TODO, not DONE
25576 (and org-export-mark-todo-in-toc
25577 (= level umax-toc)
25578 (org-search-todo-below
25579 line lines level))))
25580 (if (string-match
25581 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25582 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25583 (if (string-match quote-re0 txt)
25584 (setq txt (replace-match "" t t txt)))
25585 (if org-export-with-section-numbers
25586 (setq txt (concat (org-section-number level)
25587 " " txt)))
25588 (if (<= level (max umax umax-toc))
25589 (setq head-count (+ head-count 1)))
25590 (if (<= level umax-toc)
25591 (progn
25592 (if (> level org-last-level)
25593 (progn
25594 (setq cnt (- level org-last-level))
25595 (while (>= (setq cnt (1- cnt)) 0)
25596 (push "\n<ul>\n<li>" thetoc))
25597 (push "\n" thetoc)))
25598 (if (< level org-last-level)
25599 (progn
25600 (setq cnt (- org-last-level level))
25601 (while (>= (setq cnt (1- cnt)) 0)
25602 (push "</li>\n</ul>" thetoc))
25603 (push "\n" thetoc)))
25604 ;; Check for targets
25605 (while (string-match org-target-regexp line)
25606 (setq tg (match-string 1 line)
25607 line (replace-match
25608 (concat "@<span class=\"target\">" tg "@</span> ")
25609 t t line))
25610 (push (cons (org-solidify-link-text tg)
25611 (format "sec-%d" head-count))
25612 target-alist))
25613 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25614 (setq txt (replace-match "" t t txt)))
25615 (push
25616 (format
25617 (if todo
25618 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25619 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25620 head-count txt) thetoc)
25622 (setq org-last-level level))
25624 line)
25625 lines))
25626 (while (> org-last-level (1- org-min-level))
25627 (setq org-last-level (1- org-last-level))
25628 (push "</li>\n</ul>\n" thetoc))
25629 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25631 (setq head-count 0)
25632 (org-init-section-numbers)
25634 (while (setq line (pop lines) origline line)
25635 (catch 'nextline
25637 ;; end of quote section?
25638 (when (and inquote (string-match "^\\*+ " line))
25639 (insert "</pre>\n")
25640 (setq inquote nil))
25641 ;; inside a quote section?
25642 (when inquote
25643 (insert (org-html-protect line) "\n")
25644 (throw 'nextline nil))
25646 ;; verbatim lines
25647 (when (and org-export-with-fixed-width
25648 (string-match "^[ \t]*:\\(.*\\)" line))
25649 (when (not infixed)
25650 (setq infixed t)
25651 (insert "<pre>\n"))
25652 (insert (org-html-protect (match-string 1 line)) "\n")
25653 (when (and lines
25654 (not (string-match "^[ \t]*\\(:.*\\)"
25655 (car lines))))
25656 (setq infixed nil)
25657 (insert "</pre>\n"))
25658 (throw 'nextline nil))
25660 ;; Protected HTML
25661 (when (get-text-property 0 'org-protected line)
25662 (let (par)
25663 (when (re-search-backward
25664 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25665 (setq par (match-string 1))
25666 (replace-match "\\2\n"))
25667 (insert line "\n")
25668 (while (and lines
25669 (or (= (length (car lines)) 0)
25670 (get-text-property 0 'org-protected (car lines))))
25671 (insert (pop lines) "\n"))
25672 (and par (insert "<p>\n")))
25673 (throw 'nextline nil))
25675 ;; Horizontal line
25676 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25677 (insert "\n<hr/>\n")
25678 (throw 'nextline nil))
25680 ;; make targets to anchors
25681 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25682 (cond
25683 ((match-end 2)
25684 (setq line (replace-match
25685 (concat "@<a name=\""
25686 (org-solidify-link-text (match-string 1 line))
25687 "\">\\nbsp@</a>")
25688 t t line)))
25689 ((and org-export-with-toc (equal (string-to-char line) ?*))
25690 (setq line (replace-match
25691 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25692 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25693 t t line)))
25695 (setq line (replace-match
25696 (concat "@<a name=\""
25697 (org-solidify-link-text (match-string 1 line))
25698 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25699 t t line)))))
25701 (setq line (org-html-handle-time-stamps line))
25703 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25704 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25705 ;; Also handle sub_superscripts and checkboxes
25706 (or (string-match org-table-hline-regexp line)
25707 (setq line (org-html-expand line)))
25709 ;; Format the links
25710 (setq start 0)
25711 (while (string-match org-bracket-link-analytic-regexp line start)
25712 (setq start (match-beginning 0))
25713 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25714 (setq path (match-string 3 line))
25715 (setq desc1 (if (match-end 5) (match-string 5 line))
25716 desc2 (if (match-end 2) (concat type ":" path) path)
25717 descp (and desc1 (not (equal desc1 desc2)))
25718 desc (or desc1 desc2))
25719 ;; Make an image out of the description if that is so wanted
25720 (when (and descp (org-file-image-p desc))
25721 (save-match-data
25722 (if (string-match "^file:" desc)
25723 (setq desc (substring desc (match-end 0)))))
25724 (setq desc (concat "<img src=\"" desc "\"/>")))
25725 ;; FIXME: do we need to unescape here somewhere?
25726 (cond
25727 ((equal type "internal")
25728 (setq rpl
25729 (concat
25730 "<a href=\"#"
25731 (org-solidify-link-text
25732 (save-match-data (org-link-unescape path)) target-alist)
25733 "\">" desc "</a>")))
25734 ((member type '("http" "https"))
25735 ;; standard URL, just check if we need to inline an image
25736 (if (and (or (eq t org-export-html-inline-images)
25737 (and org-export-html-inline-images (not descp)))
25738 (org-file-image-p path))
25739 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25740 (setq link (concat type ":" path))
25741 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25742 ((member type '("ftp" "mailto" "news"))
25743 ;; standard URL
25744 (setq link (concat type ":" path))
25745 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25746 ((string= type "file")
25747 ;; FILE link
25748 (let* ((filename path)
25749 (abs-p (file-name-absolute-p filename))
25750 thefile file-is-image-p search)
25751 (save-match-data
25752 (if (string-match "::\\(.*\\)" filename)
25753 (setq search (match-string 1 filename)
25754 filename (replace-match "" t nil filename)))
25755 (setq valid
25756 (if (functionp link-validate)
25757 (funcall link-validate filename current-dir)
25759 (setq file-is-image-p (org-file-image-p filename))
25760 (setq thefile (if abs-p (expand-file-name filename) filename))
25761 (when (and org-export-html-link-org-files-as-html
25762 (string-match "\\.org$" thefile))
25763 (setq thefile (concat (substring thefile 0
25764 (match-beginning 0))
25765 "." html-extension))
25766 (if (and search
25767 ;; make sure this is can be used as target search
25768 (not (string-match "^[0-9]*$" search))
25769 (not (string-match "^\\*" search))
25770 (not (string-match "^/.*/$" search)))
25771 (setq thefile (concat thefile "#"
25772 (org-solidify-link-text
25773 (org-link-unescape search)))))
25774 (when (string-match "^file:" desc)
25775 (setq desc (replace-match "" t t desc))
25776 (if (string-match "\\.org$" desc)
25777 (setq desc (replace-match "" t t desc))))))
25778 (setq rpl (if (and file-is-image-p
25779 (or (eq t org-export-html-inline-images)
25780 (and org-export-html-inline-images
25781 (not descp))))
25782 (concat "<img src=\"" thefile "\"/>")
25783 (concat "<a href=\"" thefile "\">" desc "</a>")))
25784 (if (not valid) (setq rpl desc))))
25785 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25786 (setq rpl (concat "<i>&lt;" type ":"
25787 (save-match-data (org-link-unescape path))
25788 "&gt;</i>"))))
25789 (setq line (replace-match rpl t t line)
25790 start (+ start (length rpl))))
25792 ;; TODO items
25793 (if (and (string-match org-todo-line-regexp line)
25794 (match-beginning 2))
25796 (setq line
25797 (concat (substring line 0 (match-beginning 2))
25798 "<span class=\""
25799 (if (member (match-string 2 line)
25800 org-done-keywords)
25801 "done" "todo")
25802 "\">" (match-string 2 line)
25803 "</span>" (substring line (match-end 2)))))
25805 ;; Does this contain a reference to a footnote?
25806 (when org-export-with-footnotes
25807 (setq start 0)
25808 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25809 (if (get-text-property (match-beginning 2) 'org-protected line)
25810 (setq start (match-end 2))
25811 (let ((n (match-string 2 line)))
25812 (setq line
25813 (replace-match
25814 (format
25815 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25816 (match-string 1 line) n n n)
25817 t t line))))))
25819 (cond
25820 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25821 ;; This is a headline
25822 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25823 txt (match-string 2 line))
25824 (if (string-match quote-re0 txt)
25825 (setq txt (replace-match "" t t txt)))
25826 (if (<= level (max umax umax-toc))
25827 (setq head-count (+ head-count 1)))
25828 (when in-local-list
25829 ;; Close any local lists before inserting a new header line
25830 (while local-list-num
25831 (org-close-li)
25832 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25833 (pop local-list-num))
25834 (setq local-list-indent nil
25835 in-local-list nil))
25836 (setq first-heading-pos (or first-heading-pos (point)))
25837 (org-html-level-start level txt umax
25838 (and org-export-with-toc (<= level umax))
25839 head-count)
25840 ;; QUOTES
25841 (when (string-match quote-re line)
25842 (insert "<pre>")
25843 (setq inquote t)))
25845 ((and org-export-with-tables
25846 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25847 (if (not table-open)
25848 ;; New table starts
25849 (setq table-open t table-buffer nil table-orig-buffer nil))
25850 ;; Accumulate lines
25851 (setq table-buffer (cons line table-buffer)
25852 table-orig-buffer (cons origline table-orig-buffer))
25853 (when (or (not lines)
25854 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25855 (car lines))))
25856 (setq table-open nil
25857 table-buffer (nreverse table-buffer)
25858 table-orig-buffer (nreverse table-orig-buffer))
25859 (org-close-par-maybe)
25860 (insert (org-format-table-html table-buffer table-orig-buffer))))
25862 ;; Normal lines
25863 (when (string-match
25864 (cond
25865 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25866 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25867 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25868 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25869 line)
25870 (setq ind (org-get-string-indentation line)
25871 start-is-num (match-beginning 4)
25872 starter (if (match-beginning 2)
25873 (substring (match-string 2 line) 0 -1))
25874 line (substring line (match-beginning 5)))
25875 (unless (string-match "[^ \t]" line)
25876 ;; empty line. Pretend indentation is large.
25877 (setq ind (if org-empty-line-terminates-plain-lists
25879 (1+ (or (car local-list-indent) 1)))))
25880 (setq didclose nil)
25881 (while (and in-local-list
25882 (or (and (= ind (car local-list-indent))
25883 (not starter))
25884 (< ind (car local-list-indent))))
25885 (setq didclose t)
25886 (org-close-li)
25887 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25888 (pop local-list-num) (pop local-list-indent)
25889 (setq in-local-list local-list-indent))
25890 (cond
25891 ((and starter
25892 (or (not in-local-list)
25893 (> ind (car local-list-indent))))
25894 ;; Start new (level of) list
25895 (org-close-par-maybe)
25896 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25897 (push start-is-num local-list-num)
25898 (push ind local-list-indent)
25899 (setq in-local-list t))
25900 (starter
25901 ;; continue current list
25902 (org-close-li)
25903 (insert "<li>\n"))
25904 (didclose
25905 ;; we did close a list, normal text follows: need <p>
25906 (org-open-par)))
25907 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25908 (setq line
25909 (replace-match
25910 (if (equal (match-string 1 line) "X")
25911 "<b>[X]</b>"
25912 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25913 t t line))))
25915 ;; Empty lines start a new paragraph. If hand-formatted lists
25916 ;; are not fully interpreted, lines starting with "-", "+", "*"
25917 ;; also start a new paragraph.
25918 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25920 ;; Is this the start of a footnote?
25921 (when org-export-with-footnotes
25922 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25923 (org-close-par-maybe)
25924 (let ((n (match-string 1 line)))
25925 (setq line (replace-match
25926 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25928 ;; Check if the line break needs to be conserved
25929 (cond
25930 ((string-match "\\\\\\\\[ \t]*$" line)
25931 (setq line (replace-match "<br/>" t t line)))
25932 (org-export-preserve-breaks
25933 (setq line (concat line "<br/>"))))
25935 (insert line "\n")))))
25937 ;; Properly close all local lists and other lists
25938 (when inquote (insert "</pre>\n"))
25939 (when in-local-list
25940 ;; Close any local lists before inserting a new header line
25941 (while local-list-num
25942 (org-close-li)
25943 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25944 (pop local-list-num))
25945 (setq local-list-indent nil
25946 in-local-list nil))
25947 (org-html-level-start 1 nil umax
25948 (and org-export-with-toc (<= level umax))
25949 head-count)
25951 (unless body-only
25952 (when (plist-get opt-plist :auto-postamble)
25953 (insert "<div id=\"postamble\">")
25954 (when (and org-export-author-info author)
25955 (insert "<p class=\"author\"> "
25956 (nth 1 lang-words) ": " author "\n")
25957 (when email
25958 (if (listp (split-string email ",+ *"))
25959 (mapc (lambda(e)
25960 (insert "<a href=\"mailto:" e "\">&lt;"
25961 e "&gt;</a>\n"))
25962 (split-string email ",+ *"))
25963 (insert "<a href=\"mailto:" email "\">&lt;"
25964 email "&gt;</a>\n")))
25965 (insert "</p>\n"))
25966 (when (and date org-export-time-stamp-file)
25967 (insert "<p class=\"date\"> "
25968 (nth 2 lang-words) ": "
25969 date "</p>\n"))
25970 (insert "</div>"))
25972 (if org-export-html-with-timestamp
25973 (insert org-export-html-html-helper-timestamp))
25974 (insert (or (plist-get opt-plist :postamble) ""))
25975 (insert "</body>\n</html>\n"))
25977 (normal-mode)
25978 (if (eq major-mode default-major-mode) (html-mode))
25980 ;; insert the table of contents
25981 (goto-char (point-min))
25982 (when thetoc
25983 (if (or (re-search-forward
25984 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25985 (re-search-forward
25986 "\\[TABLE-OF-CONTENTS\\]" nil t))
25987 (progn
25988 (goto-char (match-beginning 0))
25989 (replace-match ""))
25990 (goto-char first-heading-pos)
25991 (when (looking-at "\\s-*</p>")
25992 (goto-char (match-end 0))
25993 (insert "\n")))
25994 (insert "<div id=\"table-of-contents\">\n")
25995 (mapc 'insert thetoc)
25996 (insert "</div>\n"))
25997 ;; remove empty paragraphs and lists
25998 (goto-char (point-min))
25999 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
26000 (replace-match ""))
26001 (goto-char (point-min))
26002 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
26003 (replace-match ""))
26004 (goto-char (point-min))
26005 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
26006 (replace-match ""))
26007 ;; Convert whitespace place holders
26008 (goto-char (point-min))
26009 (let (beg end n)
26010 (while (setq beg (next-single-property-change (point) 'org-whitespace))
26011 (setq n (get-text-property beg 'org-whitespace)
26012 end (next-single-property-change beg 'org-whitespace))
26013 (goto-char beg)
26014 (delete-region beg end)
26015 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
26016 (make-string n ?x)))))
26018 (or to-buffer (progn (save-buffer) (kill-buffer (current-buffer))))
26019 (goto-char (point-min))
26020 (message "Exporting... done")
26021 (if (eq to-buffer 'string)
26022 (prog1 (buffer-substring (point-min) (point-max))
26023 (kill-buffer (current-buffer)))
26024 (current-buffer)))))
26026 (defvar org-table-colgroup-info nil)
26027 (defun org-format-table-ascii (lines)
26028 "Format a table for ascii export."
26029 (if (stringp lines)
26030 (setq lines (org-split-string lines "\n")))
26031 (if (not (string-match "^[ \t]*|" (car lines)))
26032 ;; Table made by table.el - test for spanning
26033 lines
26035 ;; A normal org table
26036 ;; Get rid of hlines at beginning and end
26037 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26038 (setq lines (nreverse lines))
26039 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26040 (setq lines (nreverse lines))
26041 (when org-export-table-remove-special-lines
26042 ;; Check if the table has a marking column. If yes remove the
26043 ;; column and the special lines
26044 (setq lines (org-table-clean-before-export lines)))
26045 ;; Get rid of the vertical lines except for grouping
26046 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
26047 rtn line vl1 start)
26048 (while (setq line (pop lines))
26049 (if (string-match org-table-hline-regexp line)
26050 (and (string-match "|\\(.*\\)|" line)
26051 (setq line (replace-match " \\1" t nil line)))
26052 (setq start 0 vl1 vl)
26053 (while (string-match "|" line start)
26054 (setq start (match-end 0))
26055 (or (pop vl1) (setq line (replace-match " " t t line)))))
26056 (push line rtn))
26057 (nreverse rtn))))
26059 (defun org-colgroup-info-to-vline-list (info)
26060 (let (vl new last)
26061 (while info
26062 (setq last new new (pop info))
26063 (if (or (memq last '(:end :startend))
26064 (memq new '(:start :startend)))
26065 (push t vl)
26066 (push nil vl)))
26067 (setq vl (nreverse vl))
26068 (and vl (setcar vl nil))
26069 vl))
26071 (defun org-format-table-html (lines olines)
26072 "Find out which HTML converter to use and return the HTML code."
26073 (if (stringp lines)
26074 (setq lines (org-split-string lines "\n")))
26075 (if (string-match "^[ \t]*|" (car lines))
26076 ;; A normal org table
26077 (org-format-org-table-html lines)
26078 ;; Table made by table.el - test for spanning
26079 (let* ((hlines (delq nil (mapcar
26080 (lambda (x)
26081 (if (string-match "^[ \t]*\\+-" x) x
26082 nil))
26083 lines)))
26084 (first (car hlines))
26085 (ll (and (string-match "\\S-+" first)
26086 (match-string 0 first)))
26087 (re (concat "^[ \t]*" (regexp-quote ll)))
26088 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26089 hlines))))
26090 (if (and (not spanning)
26091 (not org-export-prefer-native-exporter-for-tables))
26092 ;; We can use my own converter with HTML conversions
26093 (org-format-table-table-html lines)
26094 ;; Need to use the code generator in table.el, with the original text.
26095 (org-format-table-table-html-using-table-generate-source olines)))))
26097 (defun org-format-org-table-html (lines &optional splice)
26098 "Format a table into HTML."
26099 ;; Get rid of hlines at beginning and end
26100 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26101 (setq lines (nreverse lines))
26102 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26103 (setq lines (nreverse lines))
26104 (when org-export-table-remove-special-lines
26105 ;; Check if the table has a marking column. If yes remove the
26106 ;; column and the special lines
26107 (setq lines (org-table-clean-before-export lines)))
26109 (let ((head (and org-export-highlight-first-table-line
26110 (delq nil (mapcar
26111 (lambda (x) (string-match "^[ \t]*|-" x))
26112 (cdr lines)))))
26113 (nlines 0) fnum i
26114 tbopen line fields html gr colgropen)
26115 (if splice (setq head nil))
26116 (unless splice (push (if head "<thead>" "<tbody>") html))
26117 (setq tbopen t)
26118 (while (setq line (pop lines))
26119 (catch 'next-line
26120 (if (string-match "^[ \t]*|-" line)
26121 (progn
26122 (unless splice
26123 (push (if head "</thead>" "</tbody>") html)
26124 (if lines (push "<tbody>" html) (setq tbopen nil)))
26125 (setq head nil) ;; head ends here, first time around
26126 ;; ignore this line
26127 (throw 'next-line t)))
26128 ;; Break the line into fields
26129 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26130 (unless fnum (setq fnum (make-vector (length fields) 0)))
26131 (setq nlines (1+ nlines) i -1)
26132 (push (concat "<tr>"
26133 (mapconcat
26134 (lambda (x)
26135 (setq i (1+ i))
26136 (if (and (< i nlines)
26137 (string-match org-table-number-regexp x))
26138 (incf (aref fnum i)))
26139 (if head
26140 (concat (car org-export-table-header-tags) x
26141 (cdr org-export-table-header-tags))
26142 (concat (car org-export-table-data-tags) x
26143 (cdr org-export-table-data-tags))))
26144 fields "")
26145 "</tr>")
26146 html)))
26147 (unless splice (if tbopen (push "</tbody>" html)))
26148 (unless splice (push "</table>\n" html))
26149 (setq html (nreverse html))
26150 (unless splice
26151 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26152 (push (mapconcat
26153 (lambda (x)
26154 (setq gr (pop org-table-colgroup-info))
26155 (format "%s<col align=\"%s\"></col>%s"
26156 (if (memq gr '(:start :startend))
26157 (prog1
26158 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26159 (setq colgropen t))
26161 (if (> (/ (float x) nlines) org-table-number-fraction)
26162 "right" "left")
26163 (if (memq gr '(:end :startend))
26164 (progn (setq colgropen nil) "</colgroup>")
26165 "")))
26166 fnum "")
26167 html)
26168 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26169 (push html-table-tag html))
26170 (concat (mapconcat 'identity html "\n") "\n")))
26172 (defun org-table-clean-before-export (lines)
26173 "Check if the table has a marking column.
26174 If yes remove the column and the special lines."
26175 (setq org-table-colgroup-info nil)
26176 (if (memq nil
26177 (mapcar
26178 (lambda (x) (or (string-match "^[ \t]*|-" x)
26179 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26180 lines))
26181 (progn
26182 (setq org-table-clean-did-remove-column nil)
26183 (delq nil
26184 (mapcar
26185 (lambda (x)
26186 (cond
26187 ((string-match "^[ \t]*| */ *|" x)
26188 (setq org-table-colgroup-info
26189 (mapcar (lambda (x)
26190 (cond ((member x '("<" "&lt;")) :start)
26191 ((member x '(">" "&gt;")) :end)
26192 ((member x '("<>" "&lt;&gt;")) :startend)
26193 (t nil)))
26194 (org-split-string x "[ \t]*|[ \t]*")))
26195 nil)
26196 (t x)))
26197 lines)))
26198 (setq org-table-clean-did-remove-column t)
26199 (delq nil
26200 (mapcar
26201 (lambda (x)
26202 (cond
26203 ((string-match "^[ \t]*| */ *|" x)
26204 (setq org-table-colgroup-info
26205 (mapcar (lambda (x)
26206 (cond ((member x '("<" "&lt;")) :start)
26207 ((member x '(">" "&gt;")) :end)
26208 ((member x '("<>" "&lt;&gt;")) :startend)
26209 (t nil)))
26210 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26211 nil)
26212 ((string-match "^[ \t]*| *[!_^/] *|" x)
26213 nil) ; ignore this line
26214 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26215 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26216 ;; remove the first column
26217 (replace-match "\\1|" t nil x))))
26218 lines))))
26220 (defun org-format-table-table-html (lines)
26221 "Format a table generated by table.el into HTML.
26222 This conversion does *not* use `table-generate-source' from table.el.
26223 This has the advantage that Org-mode's HTML conversions can be used.
26224 But it has the disadvantage, that no cell- or row-spanning is allowed."
26225 (let (line field-buffer
26226 (head org-export-highlight-first-table-line)
26227 fields html empty)
26228 (setq html (concat html-table-tag "\n"))
26229 (while (setq line (pop lines))
26230 (setq empty "&nbsp;")
26231 (catch 'next-line
26232 (if (string-match "^[ \t]*\\+-" line)
26233 (progn
26234 (if field-buffer
26235 (progn
26236 (setq
26237 html
26238 (concat
26239 html
26240 "<tr>"
26241 (mapconcat
26242 (lambda (x)
26243 (if (equal x "") (setq x empty))
26244 (if head
26245 (concat (car org-export-table-header-tags) x
26246 (cdr org-export-table-header-tags))
26247 (concat (car org-export-table-data-tags) x
26248 (cdr org-export-table-data-tags))))
26249 field-buffer "\n")
26250 "</tr>\n"))
26251 (setq head nil)
26252 (setq field-buffer nil)))
26253 ;; Ignore this line
26254 (throw 'next-line t)))
26255 ;; Break the line into fields and store the fields
26256 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26257 (if field-buffer
26258 (setq field-buffer (mapcar
26259 (lambda (x)
26260 (concat x "<br/>" (pop fields)))
26261 field-buffer))
26262 (setq field-buffer fields))))
26263 (setq html (concat html "</table>\n"))
26264 html))
26266 (defun org-format-table-table-html-using-table-generate-source (lines)
26267 "Format a table into html, using `table-generate-source' from table.el.
26268 This has the advantage that cell- or row-spanning is allowed.
26269 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26270 (require 'table)
26271 (with-current-buffer (get-buffer-create " org-tmp1 ")
26272 (erase-buffer)
26273 (insert (mapconcat 'identity lines "\n"))
26274 (goto-char (point-min))
26275 (if (not (re-search-forward "|[^+]" nil t))
26276 (error "Error processing table"))
26277 (table-recognize-table)
26278 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26279 (table-generate-source 'html " org-tmp2 ")
26280 (set-buffer " org-tmp2 ")
26281 (buffer-substring (point-min) (point-max))))
26283 (defun org-html-handle-time-stamps (s)
26284 "Format time stamps in string S, or remove them."
26285 (catch 'exit
26286 (let (r b)
26287 (while (string-match org-maybe-keyword-time-regexp s)
26288 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26289 ;; never export CLOCK
26290 (throw 'exit ""))
26291 (or b (setq b (substring s 0 (match-beginning 0))))
26292 (if (not org-export-with-timestamps)
26293 (setq r (concat r (substring s 0 (match-beginning 0)))
26294 s (substring s (match-end 0)))
26295 (setq r (concat
26296 r (substring s 0 (match-beginning 0))
26297 (if (match-end 1)
26298 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26299 (match-string 1 s)))
26300 (format " @<span class=\"timestamp\">%s@</span>"
26301 (substring
26302 (org-translate-time (match-string 3 s)) 1 -1)))
26303 s (substring s (match-end 0)))))
26304 ;; Line break if line started and ended with time stamp stuff
26305 (if (not r)
26307 (setq r (concat r s))
26308 (unless (string-match "\\S-" (concat b s))
26309 (setq r (concat r "@<br/>")))
26310 r))))
26312 (defun org-html-protect (s)
26313 ;; convert & to &amp;, < to &lt; and > to &gt;
26314 (let ((start 0))
26315 (while (string-match "&" s start)
26316 (setq s (replace-match "&amp;" t t s)
26317 start (1+ (match-beginning 0))))
26318 (while (string-match "<" s)
26319 (setq s (replace-match "&lt;" t t s)))
26320 (while (string-match ">" s)
26321 (setq s (replace-match "&gt;" t t s))))
26324 (defun org-export-cleanup-toc-line (s)
26325 "Remove tags and time staps from lines going into the toc."
26326 (when (memq org-export-with-tags '(not-in-toc nil))
26327 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26328 (setq s (replace-match "" t t s))))
26329 (when org-export-remove-timestamps-from-toc
26330 (while (string-match org-maybe-keyword-time-regexp s)
26331 (setq s (replace-match "" t t s))))
26332 (while (string-match org-bracket-link-regexp s)
26333 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26334 t t s)))
26337 (defun org-html-expand (string)
26338 "Prepare STRING for HTML export. Applies all active conversions.
26339 If there are links in the string, don't modify these."
26340 (let* ((re (concat org-bracket-link-regexp "\\|"
26341 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26342 m s l res)
26343 (while (setq m (string-match re string))
26344 (setq s (substring string 0 m)
26345 l (match-string 0 string)
26346 string (substring string (match-end 0)))
26347 (push (org-html-do-expand s) res)
26348 (push l res))
26349 (push (org-html-do-expand string) res)
26350 (apply 'concat (nreverse res))))
26352 (defun org-html-do-expand (s)
26353 "Apply all active conversions to translate special ASCII to HTML."
26354 (setq s (org-html-protect s))
26355 (if org-export-html-expand
26356 (let ((start 0))
26357 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26358 (setq s (replace-match "<\\1>" t nil s)))))
26359 (if org-export-with-emphasize
26360 (setq s (org-export-html-convert-emphasize s)))
26361 (if org-export-with-special-strings
26362 (setq s (org-export-html-convert-special-strings s)))
26363 (if org-export-with-sub-superscripts
26364 (setq s (org-export-html-convert-sub-super s)))
26365 (if org-export-with-TeX-macros
26366 (let ((start 0) wd ass)
26367 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26368 (if (get-text-property (match-beginning 0) 'org-protected s)
26369 (setq start (match-end 0))
26370 (setq wd (match-string 1 s))
26371 (if (setq ass (assoc wd org-html-entities))
26372 (setq s (replace-match (or (cdr ass)
26373 (concat "&" (car ass) ";"))
26374 t t s))
26375 (setq start (+ start (length wd))))))))
26378 (defun org-create-multibrace-regexp (left right n)
26379 "Create a regular expression which will match a balanced sexp.
26380 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26381 as single character strings.
26382 The regexp returned will match the entire expression including the
26383 delimiters. It will also define a single group which contains the
26384 match except for the outermost delimiters. The maximum depth of
26385 stacked delimiters is N. Escaping delimiters is not possible."
26386 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26387 (or "\\|")
26388 (re nothing)
26389 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26390 (while (> n 1)
26391 (setq n (1- n)
26392 re (concat re or next)
26393 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26394 (concat left "\\(" re "\\)" right)))
26396 (defvar org-match-substring-regexp
26397 (concat
26398 "\\([^\\]\\)\\([_^]\\)\\("
26399 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26400 "\\|"
26401 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26402 "\\|"
26403 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26404 "The regular expression matching a sub- or superscript.")
26406 (defvar org-match-substring-with-braces-regexp
26407 (concat
26408 "\\([^\\]\\)\\([_^]\\)\\("
26409 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26410 "\\)")
26411 "The regular expression matching a sub- or superscript, forcing braces.")
26413 (defconst org-export-html-special-string-regexps
26414 '(("\\\\-" . "&shy;")
26415 ("---\\([^-]\\)" . "&mdash;\\1")
26416 ("--\\([^-]\\)" . "&ndash;\\1")
26417 ("\\.\\.\\." . "&hellip;"))
26418 "Regular expressions for special string conversion.")
26420 (defun org-export-html-convert-special-strings (string)
26421 "Convert special characters in STRING to HTML."
26422 (let ((all org-export-html-special-string-regexps)
26423 e a re rpl start)
26424 (while (setq a (pop all))
26425 (setq re (car a) rpl (cdr a) start 0)
26426 (while (string-match re string start)
26427 (if (get-text-property (match-beginning 0) 'org-protected string)
26428 (setq start (match-end 0))
26429 (setq string (replace-match rpl t nil string)))))
26430 string))
26432 (defun org-export-html-convert-sub-super (string)
26433 "Convert sub- and superscripts in STRING to HTML."
26434 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26435 (while (string-match org-match-substring-regexp string s)
26436 (cond
26437 ((and requireb (match-end 8)) (setq s (match-end 2)))
26438 ((get-text-property (match-beginning 2) 'org-protected string)
26439 (setq s (match-end 2)))
26441 (setq s (match-end 1)
26442 key (if (string= (match-string 2 string) "_") "sub" "sup")
26443 c (or (match-string 8 string)
26444 (match-string 6 string)
26445 (match-string 5 string))
26446 string (replace-match
26447 (concat (match-string 1 string)
26448 "<" key ">" c "</" key ">")
26449 t t string)))))
26450 (while (string-match "\\\\\\([_^]\\)" string)
26451 (setq string (replace-match (match-string 1 string) t t string)))
26452 string))
26454 (defun org-export-html-convert-emphasize (string)
26455 "Apply emphasis."
26456 (let ((s 0) rpl)
26457 (while (string-match org-emph-re string s)
26458 (if (not (equal
26459 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26460 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26461 (setq s (match-beginning 0)
26463 (concat
26464 (match-string 1 string)
26465 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26466 (match-string 4 string)
26467 (nth 3 (assoc (match-string 3 string)
26468 org-emphasis-alist))
26469 (match-string 5 string))
26470 string (replace-match rpl t t string)
26471 s (+ s (- (length rpl) 2)))
26472 (setq s (1+ s))))
26473 string))
26475 (defvar org-par-open nil)
26476 (defun org-open-par ()
26477 "Insert <p>, but first close previous paragraph if any."
26478 (org-close-par-maybe)
26479 (insert "\n<p>")
26480 (setq org-par-open t))
26481 (defun org-close-par-maybe ()
26482 "Close paragraph if there is one open."
26483 (when org-par-open
26484 (insert "</p>")
26485 (setq org-par-open nil)))
26486 (defun org-close-li ()
26487 "Close <li> if necessary."
26488 (org-close-par-maybe)
26489 (insert "</li>\n"))
26491 (defvar body-only) ; dynamically scoped into this.
26492 (defun org-html-level-start (level title umax with-toc head-count)
26493 "Insert a new level in HTML export.
26494 When TITLE is nil, just close all open levels."
26495 (org-close-par-maybe)
26496 (let ((l org-level-max))
26497 (while (>= l level)
26498 (if (aref org-levels-open (1- l))
26499 (progn
26500 (org-html-level-close l umax)
26501 (aset org-levels-open (1- l) nil)))
26502 (setq l (1- l)))
26503 (when title
26504 ;; If title is nil, this means this function is called to close
26505 ;; all levels, so the rest is done only if title is given
26506 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26507 (setq title (replace-match
26508 (if org-export-with-tags
26509 (save-match-data
26510 (concat
26511 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26512 (mapconcat 'identity (org-split-string
26513 (match-string 1 title) ":")
26514 "&nbsp;")
26515 "</span>"))
26517 t t title)))
26518 (if (> level umax)
26519 (progn
26520 (if (aref org-levels-open (1- level))
26521 (progn
26522 (org-close-li)
26523 (insert "<li>" title "<br/>\n"))
26524 (aset org-levels-open (1- level) t)
26525 (org-close-par-maybe)
26526 (insert "<ul>\n<li>" title "<br/>\n")))
26527 (aset org-levels-open (1- level) t)
26528 (if (and org-export-with-section-numbers (not body-only))
26529 (setq title (concat (org-section-number level) " " title)))
26530 (setq level (+ level org-export-html-toplevel-hlevel -1))
26531 (if with-toc
26532 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26533 level level head-count title level))
26534 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26535 (org-open-par)))))
26537 (defun org-html-level-close (level max-outline-level)
26538 "Terminate one level in HTML export."
26539 (if (<= level max-outline-level)
26540 (insert "</div>\n")
26541 (org-close-li)
26542 (insert "</ul>\n")))
26544 ;;; iCalendar export
26546 ;;;###autoload
26547 (defun org-export-icalendar-this-file ()
26548 "Export current file as an iCalendar file.
26549 The iCalendar file will be located in the same directory as the Org-mode
26550 file, but with extension `.ics'."
26551 (interactive)
26552 (org-export-icalendar nil buffer-file-name))
26554 ;;;###autoload
26555 (defun org-export-icalendar-all-agenda-files ()
26556 "Export all files in `org-agenda-files' to iCalendar .ics files.
26557 Each iCalendar file will be located in the same directory as the Org-mode
26558 file, but with extension `.ics'."
26559 (interactive)
26560 (apply 'org-export-icalendar nil (org-agenda-files t)))
26562 ;;;###autoload
26563 (defun org-export-icalendar-combine-agenda-files ()
26564 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26565 The file is stored under the name `org-combined-agenda-icalendar-file'."
26566 (interactive)
26567 (apply 'org-export-icalendar t (org-agenda-files t)))
26569 (defun org-export-icalendar (combine &rest files)
26570 "Create iCalendar files for all elements of FILES.
26571 If COMBINE is non-nil, combine all calendar entries into a single large
26572 file and store it under the name `org-combined-agenda-icalendar-file'."
26573 (save-excursion
26574 (org-prepare-agenda-buffers files)
26575 (let* ((dir (org-export-directory
26576 :ical (list :publishing-directory
26577 org-export-publishing-directory)))
26578 file ical-file ical-buffer category started org-agenda-new-buffers)
26580 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26581 (when combine
26582 (setq ical-file
26583 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26584 org-combined-agenda-icalendar-file
26585 (expand-file-name org-combined-agenda-icalendar-file dir))
26586 ical-buffer (org-get-agenda-file-buffer ical-file))
26587 (set-buffer ical-buffer) (erase-buffer))
26588 (while (setq file (pop files))
26589 (catch 'nextfile
26590 (org-check-agenda-file file)
26591 (set-buffer (org-get-agenda-file-buffer file))
26592 (unless combine
26593 (setq ical-file (concat (file-name-as-directory dir)
26594 (file-name-sans-extension
26595 (file-name-nondirectory buffer-file-name))
26596 ".ics"))
26597 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26598 (with-current-buffer ical-buffer (erase-buffer)))
26599 (setq category (or org-category
26600 (file-name-sans-extension
26601 (file-name-nondirectory buffer-file-name))))
26602 (if (symbolp category) (setq category (symbol-name category)))
26603 (let ((standard-output ical-buffer))
26604 (if combine
26605 (and (not started) (setq started t)
26606 (org-start-icalendar-file org-icalendar-combined-name))
26607 (org-start-icalendar-file category))
26608 (org-print-icalendar-entries combine)
26609 (when (or (and combine (not files)) (not combine))
26610 (org-finish-icalendar-file)
26611 (set-buffer ical-buffer)
26612 (save-buffer)
26613 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26614 (org-release-buffers org-agenda-new-buffers))))
26616 (defvar org-after-save-iCalendar-file-hook nil
26617 "Hook run after an iCalendar file has been saved.
26618 The iCalendar buffer is still current when this hook is run.
26619 A good way to use this is to tell a desktop calenndar application to re-read
26620 the iCalendar file.")
26622 (defun org-print-icalendar-entries (&optional combine)
26623 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26624 When COMBINE is non nil, add the category to each line."
26625 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26626 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26627 (dts (org-ical-ts-to-string
26628 (format-time-string (cdr org-time-stamp-formats) (current-time))
26629 "DTSTART"))
26630 hd ts ts2 state status (inc t) pos b sexp rrule
26631 scheduledp deadlinep tmp pri category entry location summary desc
26632 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26633 (org-refresh-category-properties)
26634 (save-excursion
26635 (goto-char (point-min))
26636 (while (re-search-forward re1 nil t)
26637 (catch :skip
26638 (org-agenda-skip)
26639 (setq pos (match-beginning 0)
26640 ts (match-string 0)
26641 inc t
26642 hd (org-get-heading)
26643 summary (org-icalendar-cleanup-string
26644 (org-entry-get nil "SUMMARY"))
26645 desc (org-icalendar-cleanup-string
26646 (or (org-entry-get nil "DESCRIPTION")
26647 (and org-icalendar-include-body (org-get-entry)))
26648 t org-icalendar-include-body)
26649 location (org-icalendar-cleanup-string
26650 (org-entry-get nil "LOCATION"))
26651 category (org-get-category))
26652 (if (looking-at re2)
26653 (progn
26654 (goto-char (match-end 0))
26655 (setq ts2 (match-string 1) inc nil))
26656 (setq tmp (buffer-substring (max (point-min)
26657 (- pos org-ds-keyword-length))
26658 pos)
26659 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26660 (progn
26661 (setq inc nil)
26662 (replace-match "\\1" t nil ts))
26664 deadlinep (string-match org-deadline-regexp tmp)
26665 scheduledp (string-match org-scheduled-regexp tmp)
26666 ;; donep (org-entry-is-done-p)
26668 (if (or (string-match org-tr-regexp hd)
26669 (string-match org-ts-regexp hd))
26670 (setq hd (replace-match "" t t hd)))
26671 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26672 (setq rrule
26673 (concat "\nRRULE:FREQ="
26674 (cdr (assoc
26675 (match-string 2 ts)
26676 '(("d" . "DAILY")("w" . "WEEKLY")
26677 ("m" . "MONTHLY")("y" . "YEARLY"))))
26678 ";INTERVAL=" (match-string 1 ts)))
26679 (setq rrule ""))
26680 (setq summary (or summary hd))
26681 (if (string-match org-bracket-link-regexp summary)
26682 (setq summary
26683 (replace-match (if (match-end 3)
26684 (match-string 3 summary)
26685 (match-string 1 summary))
26686 t t summary)))
26687 (if deadlinep (setq summary (concat "DL: " summary)))
26688 (if scheduledp (setq summary (concat "S: " summary)))
26689 (if (string-match "\\`<%%" ts)
26690 (with-current-buffer sexp-buffer
26691 (insert (substring ts 1 -1) " " summary "\n"))
26692 (princ (format "BEGIN:VEVENT
26694 %s%s
26695 SUMMARY:%s%s%s
26696 CATEGORIES:%s
26697 END:VEVENT\n"
26698 (org-ical-ts-to-string ts "DTSTART")
26699 (org-ical-ts-to-string ts2 "DTEND" inc)
26700 rrule summary
26701 (if (and desc (string-match "\\S-" desc))
26702 (concat "\nDESCRIPTION: " desc) "")
26703 (if (and location (string-match "\\S-" location))
26704 (concat "\nLOCATION: " location) "")
26705 category)))))
26707 (when (and org-icalendar-include-sexps
26708 (condition-case nil (require 'icalendar) (error nil))
26709 (fboundp 'icalendar-export-region))
26710 ;; Get all the literal sexps
26711 (goto-char (point-min))
26712 (while (re-search-forward "^&?%%(" nil t)
26713 (catch :skip
26714 (org-agenda-skip)
26715 (setq b (match-beginning 0))
26716 (goto-char (1- (match-end 0)))
26717 (forward-sexp 1)
26718 (end-of-line 1)
26719 (setq sexp (buffer-substring b (point)))
26720 (with-current-buffer sexp-buffer
26721 (insert sexp "\n"))
26722 (princ (org-diary-to-ical-string sexp-buffer)))))
26724 (when org-icalendar-include-todo
26725 (goto-char (point-min))
26726 (while (re-search-forward org-todo-line-regexp nil t)
26727 (catch :skip
26728 (org-agenda-skip)
26729 (setq state (match-string 2))
26730 (setq status (if (member state org-done-keywords)
26731 "COMPLETED" "NEEDS-ACTION"))
26732 (when (and state
26733 (or (not (member state org-done-keywords))
26734 (eq org-icalendar-include-todo 'all))
26735 (not (member org-archive-tag (org-get-tags-at)))
26737 (setq hd (match-string 3)
26738 summary (org-icalendar-cleanup-string
26739 (org-entry-get nil "SUMMARY"))
26740 desc (org-icalendar-cleanup-string
26741 (or (org-entry-get nil "DESCRIPTION")
26742 (and org-icalendar-include-body (org-get-entry)))
26743 t org-icalendar-include-body)
26744 location (org-icalendar-cleanup-string
26745 (org-entry-get nil "LOCATION")))
26746 (if (string-match org-bracket-link-regexp hd)
26747 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26748 (match-string 1 hd))
26749 t t hd)))
26750 (if (string-match org-priority-regexp hd)
26751 (setq pri (string-to-char (match-string 2 hd))
26752 hd (concat (substring hd 0 (match-beginning 1))
26753 (substring hd (match-end 1))))
26754 (setq pri org-default-priority))
26755 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26756 (- org-lowest-priority org-highest-priority))))))
26758 (princ (format "BEGIN:VTODO
26760 SUMMARY:%s%s%s
26761 CATEGORIES:%s
26762 SEQUENCE:1
26763 PRIORITY:%d
26764 STATUS:%s
26765 END:VTODO\n"
26767 (or summary hd)
26768 (if (and location (string-match "\\S-" location))
26769 (concat "\nLOCATION: " location) "")
26770 (if (and desc (string-match "\\S-" desc))
26771 (concat "\nDESCRIPTION: " desc) "")
26772 category pri status)))))))))
26774 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26775 "Take out stuff and quote what needs to be quoted.
26776 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26777 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26778 characters."
26779 (if (not s)
26781 (when is-body
26782 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26783 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26784 (while (string-match re s) (setq s (replace-match "" t t s)))
26785 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26786 (let ((start 0))
26787 (while (string-match "\\([,;\\]\\)" s start)
26788 (setq start (+ (match-beginning 0) 2)
26789 s (replace-match "\\\\\\1" nil nil s))))
26790 (when is-body
26791 (while (string-match "[ \t]*\n[ \t]*" s)
26792 (setq s (replace-match "\\n" t t s))))
26793 (setq s (org-trim s))
26794 (if is-body
26795 (if maxlength
26796 (if (and (numberp maxlength)
26797 (> (length s) maxlength))
26798 (setq s (substring s 0 maxlength)))))
26801 (defun org-get-entry ()
26802 "Clean-up description string."
26803 (save-excursion
26804 (org-back-to-heading t)
26805 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26807 (defun org-start-icalendar-file (name)
26808 "Start an iCalendar file by inserting the header."
26809 (let ((user user-full-name)
26810 (name (or name "unknown"))
26811 (timezone (cadr (current-time-zone))))
26812 (princ
26813 (format "BEGIN:VCALENDAR
26814 VERSION:2.0
26815 X-WR-CALNAME:%s
26816 PRODID:-//%s//Emacs with Org-mode//EN
26817 X-WR-TIMEZONE:%s
26818 CALSCALE:GREGORIAN\n" name user timezone))))
26820 (defun org-finish-icalendar-file ()
26821 "Finish an iCalendar file by inserting the END statement."
26822 (princ "END:VCALENDAR\n"))
26824 (defun org-ical-ts-to-string (s keyword &optional inc)
26825 "Take a time string S and convert it to iCalendar format.
26826 KEYWORD is added in front, to make a complete line like DTSTART....
26827 When INC is non-nil, increase the hour by two (if time string contains
26828 a time), or the day by one (if it does not contain a time)."
26829 (let ((t1 (org-parse-time-string s 'nodefault))
26830 t2 fmt have-time time)
26831 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26832 (setq t2 t1 have-time t)
26833 (setq t2 (org-parse-time-string s)))
26834 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26835 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26836 (when inc
26837 (if have-time
26838 (if org-agenda-default-appointment-duration
26839 (setq mi (+ org-agenda-default-appointment-duration mi))
26840 (setq h (+ 2 h)))
26841 (setq d (1+ d))))
26842 (setq time (encode-time s mi h d m y)))
26843 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26844 (concat keyword (format-time-string fmt time))))
26846 ;;; XOXO export
26848 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26849 (with-current-buffer buffer
26850 (apply 'insert output)))
26851 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26853 (defun org-export-as-xoxo (&optional buffer)
26854 "Export the org buffer as XOXO.
26855 The XOXO buffer is named *xoxo-<source buffer name>*"
26856 (interactive (list (current-buffer)))
26857 ;; A quickie abstraction
26859 ;; Output everything as XOXO
26860 (with-current-buffer (get-buffer buffer)
26861 (let* ((pos (point))
26862 (opt-plist (org-combine-plists (org-default-export-plist)
26863 (org-infile-export-plist)))
26864 (filename (concat (file-name-as-directory
26865 (org-export-directory :xoxo opt-plist))
26866 (file-name-sans-extension
26867 (file-name-nondirectory buffer-file-name))
26868 ".html"))
26869 (out (find-file-noselect filename))
26870 (last-level 1)
26871 (hanging-li nil))
26872 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26873 ;; Check the output buffer is empty.
26874 (with-current-buffer out (erase-buffer))
26875 ;; Kick off the output
26876 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26877 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26878 (let* ((hd (match-string-no-properties 1))
26879 (level (length hd))
26880 (text (concat
26881 (match-string-no-properties 2)
26882 (save-excursion
26883 (goto-char (match-end 0))
26884 (let ((str ""))
26885 (catch 'loop
26886 (while 't
26887 (forward-line)
26888 (if (looking-at "^[ \t]\\(.*\\)")
26889 (setq str (concat str (match-string-no-properties 1)))
26890 (throw 'loop str)))))))))
26892 ;; Handle level rendering
26893 (cond
26894 ((> level last-level)
26895 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26897 ((< level last-level)
26898 (dotimes (- (- last-level level) 1)
26899 (if hanging-li
26900 (org-export-as-xoxo-insert-into out "</li>\n"))
26901 (org-export-as-xoxo-insert-into out "</ol>\n"))
26902 (when hanging-li
26903 (org-export-as-xoxo-insert-into out "</li>\n")
26904 (setq hanging-li nil)))
26906 ((equal level last-level)
26907 (if hanging-li
26908 (org-export-as-xoxo-insert-into out "</li>\n")))
26911 (setq last-level level)
26913 ;; And output the new li
26914 (setq hanging-li 't)
26915 (if (equal ?+ (elt text 0))
26916 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26917 (org-export-as-xoxo-insert-into out "<li>" text))))
26919 ;; Finally finish off the ol
26920 (dotimes (- last-level 1)
26921 (if hanging-li
26922 (org-export-as-xoxo-insert-into out "</li>\n"))
26923 (org-export-as-xoxo-insert-into out "</ol>\n"))
26925 (goto-char pos)
26926 ;; Finish the buffer off and clean it up.
26927 (switch-to-buffer-other-window out)
26928 (indent-region (point-min) (point-max) nil)
26929 (save-buffer)
26930 (goto-char (point-min))
26934 ;;;; Key bindings
26936 ;; Make `C-c C-x' a prefix key
26937 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26939 ;; TAB key with modifiers
26940 (org-defkey org-mode-map "\C-i" 'org-cycle)
26941 (org-defkey org-mode-map [(tab)] 'org-cycle)
26942 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26943 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26944 (org-defkey org-mode-map "\M-\t" 'org-complete)
26945 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26946 ;; The following line is necessary under Suse GNU/Linux
26947 (unless (featurep 'xemacs)
26948 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26949 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26950 (define-key org-mode-map [backtab] 'org-shifttab)
26952 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26953 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26954 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26956 ;; Cursor keys with modifiers
26957 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26958 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26959 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26960 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26962 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26963 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26964 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26965 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26967 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26968 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26969 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26970 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26972 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26973 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26975 ;;; Extra keys for tty access.
26976 ;; We only set them when really needed because otherwise the
26977 ;; menus don't show the simple keys
26979 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26980 (not window-system))
26981 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26982 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26983 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26984 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26985 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26986 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26987 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26988 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26989 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26990 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26991 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26992 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26993 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26994 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26995 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26996 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26997 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26998 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26999 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
27000 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
27001 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
27002 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
27004 ;; All the other keys
27006 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
27007 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
27008 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
27009 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
27010 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
27011 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
27012 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
27013 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
27014 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
27015 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
27016 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
27017 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
27018 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
27019 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
27020 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
27021 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
27022 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
27023 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
27024 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
27025 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
27026 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
27027 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
27028 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
27029 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
27030 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
27031 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
27032 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
27033 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
27034 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
27035 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
27036 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
27037 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
27038 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
27039 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
27040 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
27041 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
27042 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
27043 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27044 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
27045 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
27046 (org-defkey org-mode-map "\C-c^" 'org-sort)
27047 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
27048 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
27049 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
27050 (org-defkey org-mode-map "\C-m" 'org-return)
27051 (org-defkey org-mode-map "\C-j" 'org-return-indent)
27052 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
27053 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
27054 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
27055 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
27056 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
27057 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
27058 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
27059 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
27060 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
27061 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
27062 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
27063 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
27064 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
27065 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
27066 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
27068 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
27069 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
27070 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
27071 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
27073 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
27074 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
27075 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
27076 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
27077 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
27078 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
27079 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
27080 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
27081 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
27082 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
27083 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27084 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27086 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27088 (when (featurep 'xemacs)
27089 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27091 (defsubst org-table-p () (org-at-table-p))
27093 (defun org-self-insert-command (N)
27094 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27095 If the cursor is in a table looking at whitespace, the whitespace is
27096 overwritten, and the table is not marked as requiring realignment."
27097 (interactive "p")
27098 (if (and (org-table-p)
27099 (progn
27100 ;; check if we blank the field, and if that triggers align
27101 (and org-table-auto-blank-field
27102 (member last-command
27103 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27104 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27105 ;; got extra space, this field does not determine column width
27106 (let (org-table-may-need-update) (org-table-blank-field))
27107 ;; no extra space, this field may determine column width
27108 (org-table-blank-field)))
27110 (eq N 1)
27111 (looking-at "[^|\n]* |"))
27112 (let (org-table-may-need-update)
27113 (goto-char (1- (match-end 0)))
27114 (delete-backward-char 1)
27115 (goto-char (match-beginning 0))
27116 (self-insert-command N))
27117 (setq org-table-may-need-update t)
27118 (self-insert-command N)
27119 (org-fix-tags-on-the-fly)))
27121 (defun org-fix-tags-on-the-fly ()
27122 (when (and (equal (char-after (point-at-bol)) ?*)
27123 (org-on-heading-p))
27124 (org-align-tags-here org-tags-column)))
27126 (defun org-delete-backward-char (N)
27127 "Like `delete-backward-char', insert whitespace at field end in tables.
27128 When deleting backwards, in tables this function will insert whitespace in
27129 front of the next \"|\" separator, to keep the table aligned. The table will
27130 still be marked for re-alignment if the field did fill the entire column,
27131 because, in this case the deletion might narrow the column."
27132 (interactive "p")
27133 (if (and (org-table-p)
27134 (eq N 1)
27135 (string-match "|" (buffer-substring (point-at-bol) (point)))
27136 (looking-at ".*?|"))
27137 (let ((pos (point))
27138 (noalign (looking-at "[^|\n\r]* |"))
27139 (c org-table-may-need-update))
27140 (backward-delete-char N)
27141 (skip-chars-forward "^|")
27142 (insert " ")
27143 (goto-char (1- pos))
27144 ;; noalign: if there were two spaces at the end, this field
27145 ;; does not determine the width of the column.
27146 (if noalign (setq org-table-may-need-update c)))
27147 (backward-delete-char N)
27148 (org-fix-tags-on-the-fly)))
27150 (defun org-delete-char (N)
27151 "Like `delete-char', but insert whitespace at field end in tables.
27152 When deleting characters, in tables this function will insert whitespace in
27153 front of the next \"|\" separator, to keep the table aligned. The table will
27154 still be marked for re-alignment if the field did fill the entire column,
27155 because, in this case the deletion might narrow the column."
27156 (interactive "p")
27157 (if (and (org-table-p)
27158 (not (bolp))
27159 (not (= (char-after) ?|))
27160 (eq N 1))
27161 (if (looking-at ".*?|")
27162 (let ((pos (point))
27163 (noalign (looking-at "[^|\n\r]* |"))
27164 (c org-table-may-need-update))
27165 (replace-match (concat
27166 (substring (match-string 0) 1 -1)
27167 " |"))
27168 (goto-char pos)
27169 ;; noalign: if there were two spaces at the end, this field
27170 ;; does not determine the width of the column.
27171 (if noalign (setq org-table-may-need-update c)))
27172 (delete-char N))
27173 (delete-char N)
27174 (org-fix-tags-on-the-fly)))
27176 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27177 (put 'org-self-insert-command 'delete-selection t)
27178 (put 'orgtbl-self-insert-command 'delete-selection t)
27179 (put 'org-delete-char 'delete-selection 'supersede)
27180 (put 'org-delete-backward-char 'delete-selection 'supersede)
27182 ;; Make `flyspell-mode' delay after some commands
27183 (put 'org-self-insert-command 'flyspell-delayed t)
27184 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27185 (put 'org-delete-char 'flyspell-delayed t)
27186 (put 'org-delete-backward-char 'flyspell-delayed t)
27188 ;; Make pabbrev-mode expand after org-mode commands
27189 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27190 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27192 ;; How to do this: Measure non-white length of current string
27193 ;; If equal to column width, we should realign.
27195 (defun org-remap (map &rest commands)
27196 "In MAP, remap the functions given in COMMANDS.
27197 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27198 (let (new old)
27199 (while commands
27200 (setq old (pop commands) new (pop commands))
27201 (if (fboundp 'command-remapping)
27202 (org-defkey map (vector 'remap old) new)
27203 (substitute-key-definition old new map global-map)))))
27205 (when (eq org-enable-table-editor 'optimized)
27206 ;; If the user wants maximum table support, we need to hijack
27207 ;; some standard editing functions
27208 (org-remap org-mode-map
27209 'self-insert-command 'org-self-insert-command
27210 'delete-char 'org-delete-char
27211 'delete-backward-char 'org-delete-backward-char)
27212 (org-defkey org-mode-map "|" 'org-force-self-insert))
27214 (defun org-shiftcursor-error ()
27215 "Throw an error because Shift-Cursor command was applied in wrong context."
27216 (error "This command is active in special context like tables, headlines or timestamps"))
27218 (defun org-shifttab (&optional arg)
27219 "Global visibility cycling or move to previous table field.
27220 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27221 on context.
27222 See the individual commands for more information."
27223 (interactive "P")
27224 (cond
27225 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27226 (arg (message "Content view to level: ")
27227 (org-content (prefix-numeric-value arg))
27228 (setq org-cycle-global-status 'overview))
27229 (t (call-interactively 'org-global-cycle))))
27231 (defun org-shiftmetaleft ()
27232 "Promote subtree or delete table column.
27233 Calls `org-promote-subtree', `org-outdent-item',
27234 or `org-table-delete-column', depending on context.
27235 See the individual commands for more information."
27236 (interactive)
27237 (cond
27238 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27239 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27240 ((org-at-item-p) (call-interactively 'org-outdent-item))
27241 (t (org-shiftcursor-error))))
27243 (defun org-shiftmetaright ()
27244 "Demote subtree or insert table column.
27245 Calls `org-demote-subtree', `org-indent-item',
27246 or `org-table-insert-column', depending on context.
27247 See the individual commands for more information."
27248 (interactive)
27249 (cond
27250 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27251 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27252 ((org-at-item-p) (call-interactively 'org-indent-item))
27253 (t (org-shiftcursor-error))))
27255 (defun org-shiftmetaup (&optional arg)
27256 "Move subtree up or kill table row.
27257 Calls `org-move-subtree-up' or `org-table-kill-row' or
27258 `org-move-item-up' depending on context. See the individual commands
27259 for more information."
27260 (interactive "P")
27261 (cond
27262 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27263 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27264 ((org-at-item-p) (call-interactively 'org-move-item-up))
27265 (t (org-shiftcursor-error))))
27266 (defun org-shiftmetadown (&optional arg)
27267 "Move subtree down or insert table row.
27268 Calls `org-move-subtree-down' or `org-table-insert-row' or
27269 `org-move-item-down', depending on context. See the individual
27270 commands for more information."
27271 (interactive "P")
27272 (cond
27273 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27274 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27275 ((org-at-item-p) (call-interactively 'org-move-item-down))
27276 (t (org-shiftcursor-error))))
27278 (defun org-metaleft (&optional arg)
27279 "Promote heading or move table column to left.
27280 Calls `org-do-promote' or `org-table-move-column', depending on context.
27281 With no specific context, calls the Emacs default `backward-word'.
27282 See the individual commands for more information."
27283 (interactive "P")
27284 (cond
27285 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27286 ((or (org-on-heading-p) (org-region-active-p))
27287 (call-interactively 'org-do-promote))
27288 ((org-at-item-p) (call-interactively 'org-outdent-item))
27289 (t (call-interactively 'backward-word))))
27291 (defun org-metaright (&optional arg)
27292 "Demote subtree or move table column to right.
27293 Calls `org-do-demote' or `org-table-move-column', depending on context.
27294 With no specific context, calls the Emacs default `forward-word'.
27295 See the individual commands for more information."
27296 (interactive "P")
27297 (cond
27298 ((org-at-table-p) (call-interactively 'org-table-move-column))
27299 ((or (org-on-heading-p) (org-region-active-p))
27300 (call-interactively 'org-do-demote))
27301 ((org-at-item-p) (call-interactively 'org-indent-item))
27302 (t (call-interactively 'forward-word))))
27304 (defun org-metaup (&optional arg)
27305 "Move subtree up or move table row up.
27306 Calls `org-move-subtree-up' or `org-table-move-row' or
27307 `org-move-item-up', depending on context. See the individual commands
27308 for more information."
27309 (interactive "P")
27310 (cond
27311 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27312 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27313 ((org-at-item-p) (call-interactively 'org-move-item-up))
27314 (t (transpose-lines 1) (beginning-of-line -1))))
27316 (defun org-metadown (&optional arg)
27317 "Move subtree down or move table row down.
27318 Calls `org-move-subtree-down' or `org-table-move-row' or
27319 `org-move-item-down', depending on context. See the individual
27320 commands for more information."
27321 (interactive "P")
27322 (cond
27323 ((org-at-table-p) (call-interactively 'org-table-move-row))
27324 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27325 ((org-at-item-p) (call-interactively 'org-move-item-down))
27326 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27328 (defun org-shiftup (&optional arg)
27329 "Increase item in timestamp or increase priority of current headline.
27330 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27331 depending on context. See the individual commands for more information."
27332 (interactive "P")
27333 (cond
27334 ((org-at-timestamp-p t)
27335 (call-interactively (if org-edit-timestamp-down-means-later
27336 'org-timestamp-down 'org-timestamp-up)))
27337 ((org-on-heading-p) (call-interactively 'org-priority-up))
27338 ((org-at-item-p) (call-interactively 'org-previous-item))
27339 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27341 (defun org-shiftdown (&optional arg)
27342 "Decrease item in timestamp or decrease priority of current headline.
27343 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27344 depending on context. See the individual commands for more information."
27345 (interactive "P")
27346 (cond
27347 ((org-at-timestamp-p t)
27348 (call-interactively (if org-edit-timestamp-down-means-later
27349 'org-timestamp-up 'org-timestamp-down)))
27350 ((org-on-heading-p) (call-interactively 'org-priority-down))
27351 (t (call-interactively 'org-next-item))))
27353 (defun org-shiftright ()
27354 "Next TODO keyword or timestamp one day later, depending on context."
27355 (interactive)
27356 (cond
27357 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27358 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27359 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27360 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27361 (t (org-shiftcursor-error))))
27363 (defun org-shiftleft ()
27364 "Previous TODO keyword or timestamp one day earlier, depending on context."
27365 (interactive)
27366 (cond
27367 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27368 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27369 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27370 ((org-at-property-p)
27371 (call-interactively 'org-property-previous-allowed-value))
27372 (t (org-shiftcursor-error))))
27374 (defun org-shiftcontrolright ()
27375 "Switch to next TODO set."
27376 (interactive)
27377 (cond
27378 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27379 (t (org-shiftcursor-error))))
27381 (defun org-shiftcontrolleft ()
27382 "Switch to previous TODO set."
27383 (interactive)
27384 (cond
27385 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27386 (t (org-shiftcursor-error))))
27388 (defun org-ctrl-c-ret ()
27389 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27390 (interactive)
27391 (cond
27392 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27393 (t (call-interactively 'org-insert-heading))))
27395 (defun org-copy-special ()
27396 "Copy region in table or copy current subtree.
27397 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27398 See the individual commands for more information."
27399 (interactive)
27400 (call-interactively
27401 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27403 (defun org-cut-special ()
27404 "Cut region in table or cut current subtree.
27405 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27406 See the individual commands for more information."
27407 (interactive)
27408 (call-interactively
27409 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27411 (defun org-paste-special (arg)
27412 "Paste rectangular region into table, or past subtree relative to level.
27413 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27414 See the individual commands for more information."
27415 (interactive "P")
27416 (if (org-at-table-p)
27417 (org-table-paste-rectangle)
27418 (org-paste-subtree arg)))
27420 (defun org-ctrl-c-ctrl-c (&optional arg)
27421 "Set tags in headline, or update according to changed information at point.
27423 This command does many different things, depending on context:
27425 - If the cursor is in a headline, prompt for tags and insert them
27426 into the current line, aligned to `org-tags-column'. When called
27427 with prefix arg, realign all tags in the current buffer.
27429 - If the cursor is in one of the special #+KEYWORD lines, this
27430 triggers scanning the buffer for these lines and updating the
27431 information.
27433 - If the cursor is inside a table, realign the table. This command
27434 works even if the automatic table editor has been turned off.
27436 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27437 the entire table.
27439 - If the cursor is a the beginning of a dynamic block, update it.
27441 - If the cursor is inside a table created by the table.el package,
27442 activate that table.
27444 - If the current buffer is a remember buffer, close note and file it.
27445 with a prefix argument, file it without further interaction to the default
27446 location.
27448 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27449 links in this buffer.
27451 - If the cursor is on a numbered item in a plain list, renumber the
27452 ordered list.
27454 - If the cursor is on a checkbox, toggle it."
27455 (interactive "P")
27456 (let ((org-enable-table-editor t))
27457 (cond
27458 ((or org-clock-overlays
27459 org-occur-highlights
27460 org-latex-fragment-image-overlays)
27461 (org-remove-clock-overlays)
27462 (org-remove-occur-highlights)
27463 (org-remove-latex-fragment-image-overlays)
27464 (message "Temporary highlights/overlays removed from current buffer"))
27465 ((and (local-variable-p 'org-finish-function (current-buffer))
27466 (fboundp org-finish-function))
27467 (funcall org-finish-function))
27468 ((org-at-property-p)
27469 (call-interactively 'org-property-action))
27470 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27471 ((org-on-heading-p) (call-interactively 'org-set-tags))
27472 ((org-at-table.el-p)
27473 (require 'table)
27474 (beginning-of-line 1)
27475 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27476 (call-interactively 'table-recognize-table))
27477 ((org-at-table-p)
27478 (org-table-maybe-eval-formula)
27479 (if arg
27480 (call-interactively 'org-table-recalculate)
27481 (org-table-maybe-recalculate-line))
27482 (call-interactively 'org-table-align))
27483 ((org-at-item-checkbox-p)
27484 (call-interactively 'org-toggle-checkbox))
27485 ((org-at-item-p)
27486 (call-interactively 'org-maybe-renumber-ordered-list))
27487 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27488 ;; Dynamic block
27489 (beginning-of-line 1)
27490 (org-update-dblock))
27491 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27492 (cond
27493 ((equal (match-string 1) "TBLFM")
27494 ;; Recalculate the table before this line
27495 (save-excursion
27496 (beginning-of-line 1)
27497 (skip-chars-backward " \r\n\t")
27498 (if (org-at-table-p)
27499 (org-call-with-arg 'org-table-recalculate t))))
27501 (call-interactively 'org-mode-restart))))
27502 (t (error "C-c C-c can do nothing useful at this location.")))))
27504 (defun org-mode-restart ()
27505 "Restart Org-mode, to scan again for special lines.
27506 Also updates the keyword regular expressions."
27507 (interactive)
27508 (let ((org-inhibit-startup t)) (org-mode))
27509 (message "Org-mode restarted to refresh keyword and special line setup"))
27511 (defun org-kill-note-or-show-branches ()
27512 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27513 (interactive)
27514 (if (not org-finish-function)
27515 (call-interactively 'show-branches)
27516 (let ((org-note-abort t))
27517 (funcall org-finish-function))))
27519 (defun org-return (&optional indent)
27520 "Goto next table row or insert a newline.
27521 Calls `org-table-next-row' or `newline', depending on context.
27522 See the individual commands for more information."
27523 (interactive)
27524 (cond
27525 ((bobp) (if indent (newline-and-indent) (newline)))
27526 ((and (org-at-heading-p)
27527 (looking-at
27528 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27529 (org-show-entry)
27530 (end-of-line 1)
27531 (newline))
27532 ((org-at-table-p)
27533 (org-table-justify-field-maybe)
27534 (call-interactively 'org-table-next-row))
27535 (t (if indent (newline-and-indent) (newline)))))
27537 (defun org-return-indent ()
27538 "Goto next table row or insert a newline and indent.
27539 Calls `org-table-next-row' or `newline-and-indent', depending on
27540 context. See the individual commands for more information."
27541 (interactive)
27542 (org-return t))
27544 (defun org-ctrl-c-star ()
27545 "Compute table, or change heading status of lines.
27546 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27547 depending on context. This will also turn a plain list item or a normal
27548 line into a subheading."
27549 (interactive)
27550 (cond
27551 ((org-at-table-p)
27552 (call-interactively 'org-table-recalculate))
27553 ((org-region-active-p)
27554 ;; Convert all lines in region to list items
27555 (call-interactively 'org-toggle-region-headings))
27556 ((org-on-heading-p)
27557 (org-toggle-region-headings (point-at-bol)
27558 (min (1+ (point-at-eol)) (point-max))))
27559 ((org-at-item-p)
27560 ;; Convert to heading
27561 ;; FIXME: not yet implemented
27563 (t (org-toggle-region-headings (point-at-bol)
27564 (min (1+ (point-at-eol)) (point-max))))))
27566 (defun org-ctrl-c-minus ()
27567 "Insert separator line in table or modify bullet status of line.
27568 Also turns a plain line or a region of lines into list items.
27569 Calls `org-table-insert-hline', `org-toggle-region-items', or
27570 `org-cycle-list-bullet', depending on context."
27571 (interactive)
27572 (cond
27573 ((org-at-table-p)
27574 (call-interactively 'org-table-insert-hline))
27575 ((org-on-heading-p)
27576 ;; Convert to item
27577 (save-excursion
27578 (beginning-of-line 1)
27579 (if (looking-at "\\*+ ")
27580 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27581 ((org-region-active-p)
27582 ;; Convert all lines in region to list items
27583 (call-interactively 'org-toggle-region-items))
27584 ((org-in-item-p)
27585 (call-interactively 'org-cycle-list-bullet))
27586 (t (org-toggle-region-items (point-at-bol)
27587 (min (1+ (point-at-eol)) (point-max))))))
27589 (defun org-toggle-region-items (beg end)
27590 "Convert all lines in region to list items.
27591 If the first line is already an item, convert all list items in the region
27592 to normal lines."
27593 (interactive "r")
27594 (let (l2 l)
27595 (save-excursion
27596 (goto-char end)
27597 (setq l2 (org-current-line))
27598 (goto-char beg)
27599 (beginning-of-line 1)
27600 (setq l (1- (org-current-line)))
27601 (if (org-at-item-p)
27602 ;; We already have items, de-itemize
27603 (while (< (setq l (1+ l)) l2)
27604 (when (org-at-item-p)
27605 (goto-char (match-beginning 2))
27606 (delete-region (match-beginning 2) (match-end 2))
27607 (and (looking-at "[ \t]+") (replace-match "")))
27608 (beginning-of-line 2))
27609 (while (< (setq l (1+ l)) l2)
27610 (unless (org-at-item-p)
27611 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27612 (replace-match "\\1- \\2")))
27613 (beginning-of-line 2))))))
27615 (defun org-toggle-region-headings (beg end)
27616 "Convert all lines in region to list items.
27617 If the first line is already an item, convert all list items in the region
27618 to normal lines."
27619 (interactive "r")
27620 (let (l2 l)
27621 (save-excursion
27622 (goto-char end)
27623 (setq l2 (org-current-line))
27624 (goto-char beg)
27625 (beginning-of-line 1)
27626 (setq l (1- (org-current-line)))
27627 (if (org-on-heading-p)
27628 ;; We already have headlines, de-star them
27629 (while (< (setq l (1+ l)) l2)
27630 (when (org-on-heading-p t)
27631 (and (looking-at outline-regexp) (replace-match "")))
27632 (beginning-of-line 2))
27633 (let* ((stars (save-excursion
27634 (re-search-backward org-complex-heading-regexp nil t)
27635 (or (match-string 1) "*")))
27636 (add-stars (if org-odd-levels-only "**" "*"))
27637 (rpl (concat stars add-stars " \\2")))
27638 (while (< (setq l (1+ l)) l2)
27639 (unless (org-on-heading-p)
27640 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27641 (replace-match rpl)))
27642 (beginning-of-line 2)))))))
27644 (defun org-meta-return (&optional arg)
27645 "Insert a new heading or wrap a region in a table.
27646 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27647 See the individual commands for more information."
27648 (interactive "P")
27649 (cond
27650 ((org-at-table-p)
27651 (call-interactively 'org-table-wrap-region))
27652 (t (call-interactively 'org-insert-heading))))
27654 ;;; Menu entries
27656 ;; Define the Org-mode menus
27657 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27658 '("Tbl"
27659 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27660 ["Next Field" org-cycle (org-at-table-p)]
27661 ["Previous Field" org-shifttab (org-at-table-p)]
27662 ["Next Row" org-return (org-at-table-p)]
27663 "--"
27664 ["Blank Field" org-table-blank-field (org-at-table-p)]
27665 ["Edit Field" org-table-edit-field (org-at-table-p)]
27666 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27667 "--"
27668 ("Column"
27669 ["Move Column Left" org-metaleft (org-at-table-p)]
27670 ["Move Column Right" org-metaright (org-at-table-p)]
27671 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27672 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27673 ("Row"
27674 ["Move Row Up" org-metaup (org-at-table-p)]
27675 ["Move Row Down" org-metadown (org-at-table-p)]
27676 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27677 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27678 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27679 "--"
27680 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27681 ("Rectangle"
27682 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27683 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27684 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27685 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27686 "--"
27687 ("Calculate"
27688 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27689 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27690 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27691 "--"
27692 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27693 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27694 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27695 "--"
27696 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27697 "--"
27698 ["Sum Column/Rectangle" org-table-sum
27699 (or (org-at-table-p) (org-region-active-p))]
27700 ["Which Column?" org-table-current-column (org-at-table-p)])
27701 ["Debug Formulas"
27702 org-table-toggle-formula-debugger
27703 :style toggle :selected org-table-formula-debug]
27704 ["Show Col/Row Numbers"
27705 org-table-toggle-coordinate-overlays
27706 :style toggle :selected org-table-overlay-coordinates]
27707 "--"
27708 ["Create" org-table-create (and (not (org-at-table-p))
27709 org-enable-table-editor)]
27710 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27711 ["Import from File" org-table-import (not (org-at-table-p))]
27712 ["Export to File" org-table-export (org-at-table-p)]
27713 "--"
27714 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27716 (easy-menu-define org-org-menu org-mode-map "Org menu"
27717 '("Org"
27718 ("Show/Hide"
27719 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27720 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27721 ["Sparse Tree" org-occur t]
27722 ["Reveal Context" org-reveal t]
27723 ["Show All" show-all t]
27724 "--"
27725 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27726 "--"
27727 ["New Heading" org-insert-heading t]
27728 ("Navigate Headings"
27729 ["Up" outline-up-heading t]
27730 ["Next" outline-next-visible-heading t]
27731 ["Previous" outline-previous-visible-heading t]
27732 ["Next Same Level" outline-forward-same-level t]
27733 ["Previous Same Level" outline-backward-same-level t]
27734 "--"
27735 ["Jump" org-goto t])
27736 ("Edit Structure"
27737 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27738 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27739 "--"
27740 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27741 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27742 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27743 "--"
27744 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27745 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27746 ["Demote Heading" org-metaright (not (org-at-table-p))]
27747 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27748 "--"
27749 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27750 "--"
27751 ["Convert to odd levels" org-convert-to-odd-levels t]
27752 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27753 ("Editing"
27754 ["Emphasis..." org-emphasize t])
27755 ("Archive"
27756 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27757 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27758 ; :active t :keys "C-u C-c C-x C-a"]
27759 ["Sparse trees open ARCHIVE trees"
27760 (setq org-sparse-tree-open-archived-trees
27761 (not org-sparse-tree-open-archived-trees))
27762 :style toggle :selected org-sparse-tree-open-archived-trees]
27763 ["Cycling opens ARCHIVE trees"
27764 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27765 :style toggle :selected org-cycle-open-archived-trees]
27766 ["Agenda includes ARCHIVE trees"
27767 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27768 :style toggle :selected (not org-agenda-skip-archived-trees)]
27769 "--"
27770 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27771 ; ["Check and Move Children" (org-archive-subtree '(4))
27772 ; :active t :keys "C-u C-c C-x C-s"]
27774 "--"
27775 ("TODO Lists"
27776 ["TODO/DONE/-" org-todo t]
27777 ("Select keyword"
27778 ["Next keyword" org-shiftright (org-on-heading-p)]
27779 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27780 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27781 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27782 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27783 ["Show TODO Tree" org-show-todo-tree t]
27784 ["Global TODO list" org-todo-list t]
27785 "--"
27786 ["Set Priority" org-priority t]
27787 ["Priority Up" org-shiftup t]
27788 ["Priority Down" org-shiftdown t])
27789 ("TAGS and Properties"
27790 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27791 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27792 "--"
27793 ["Set property" 'org-set-property t]
27794 ["Column view of properties" org-columns t]
27795 ["Insert Column View DBlock" org-insert-columns-dblock t])
27796 ("Dates and Scheduling"
27797 ["Timestamp" org-time-stamp t]
27798 ["Timestamp (inactive)" org-time-stamp-inactive t]
27799 ("Change Date"
27800 ["1 Day Later" org-shiftright t]
27801 ["1 Day Earlier" org-shiftleft t]
27802 ["1 ... Later" org-shiftup t]
27803 ["1 ... Earlier" org-shiftdown t])
27804 ["Compute Time Range" org-evaluate-time-range t]
27805 ["Schedule Item" org-schedule t]
27806 ["Deadline" org-deadline t]
27807 "--"
27808 ["Custom time format" org-toggle-time-stamp-overlays
27809 :style radio :selected org-display-custom-times]
27810 "--"
27811 ["Goto Calendar" org-goto-calendar t]
27812 ["Date from Calendar" org-date-from-calendar t])
27813 ("Logging work"
27814 ["Clock in" org-clock-in t]
27815 ["Clock out" org-clock-out t]
27816 ["Clock cancel" org-clock-cancel t]
27817 ["Goto running clock" org-clock-goto t]
27818 ["Display times" org-clock-display t]
27819 ["Create clock table" org-clock-report t]
27820 "--"
27821 ["Record DONE time"
27822 (progn (setq org-log-done (not org-log-done))
27823 (message "Switching to %s will %s record a timestamp"
27824 (car org-done-keywords)
27825 (if org-log-done "automatically" "not")))
27826 :style toggle :selected org-log-done])
27827 "--"
27828 ["Agenda Command..." org-agenda t]
27829 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27830 ("File List for Agenda")
27831 ("Special views current file"
27832 ["TODO Tree" org-show-todo-tree t]
27833 ["Check Deadlines" org-check-deadlines t]
27834 ["Timeline" org-timeline t]
27835 ["Tags Tree" org-tags-sparse-tree t])
27836 "--"
27837 ("Hyperlinks"
27838 ["Store Link (Global)" org-store-link t]
27839 ["Insert Link" org-insert-link t]
27840 ["Follow Link" org-open-at-point t]
27841 "--"
27842 ["Next link" org-next-link t]
27843 ["Previous link" org-previous-link t]
27844 "--"
27845 ["Descriptive Links"
27846 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27847 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27848 ["Literal Links"
27849 (progn
27850 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27851 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27852 "--"
27853 ["Export/Publish..." org-export t]
27854 ("LaTeX"
27855 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27856 :selected org-cdlatex-mode]
27857 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27858 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27859 ["Modify math symbol" org-cdlatex-math-modify
27860 (org-inside-LaTeX-fragment-p)]
27861 ["Export LaTeX fragments as images"
27862 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27863 :style toggle :selected org-export-with-LaTeX-fragments])
27864 "--"
27865 ("Documentation"
27866 ["Show Version" org-version t]
27867 ["Info Documentation" org-info t])
27868 ("Customize"
27869 ["Browse Org Group" org-customize t]
27870 "--"
27871 ["Expand This Menu" org-create-customize-menu
27872 (fboundp 'customize-menu-create)])
27873 "--"
27874 ["Refresh setup" org-mode-restart t]
27877 (defun org-info (&optional node)
27878 "Read documentation for Org-mode in the info system.
27879 With optional NODE, go directly to that node."
27880 (interactive)
27881 (info (format "(org)%s" (or node ""))))
27883 (defun org-install-agenda-files-menu ()
27884 (let ((bl (buffer-list)))
27885 (save-excursion
27886 (while bl
27887 (set-buffer (pop bl))
27888 (if (org-mode-p) (setq bl nil)))
27889 (when (org-mode-p)
27890 (easy-menu-change
27891 '("Org") "File List for Agenda"
27892 (append
27893 (list
27894 ["Edit File List" (org-edit-agenda-file-list) t]
27895 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27896 ["Remove Current File from List" org-remove-file t]
27897 ["Cycle through agenda files" org-cycle-agenda-files t]
27898 ["Occur in all agenda files" org-occur-in-agenda-files t]
27899 "--")
27900 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27902 ;;;; Documentation
27904 (defun org-customize ()
27905 "Call the customize function with org as argument."
27906 (interactive)
27907 (customize-browse 'org))
27909 (defun org-create-customize-menu ()
27910 "Create a full customization menu for Org-mode, insert it into the menu."
27911 (interactive)
27912 (if (fboundp 'customize-menu-create)
27913 (progn
27914 (easy-menu-change
27915 '("Org") "Customize"
27916 `(["Browse Org group" org-customize t]
27917 "--"
27918 ,(customize-menu-create 'org)
27919 ["Set" Custom-set t]
27920 ["Save" Custom-save t]
27921 ["Reset to Current" Custom-reset-current t]
27922 ["Reset to Saved" Custom-reset-saved t]
27923 ["Reset to Standard Settings" Custom-reset-standard t]))
27924 (message "\"Org\"-menu now contains full customization menu"))
27925 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27927 ;;;; Miscellaneous stuff
27930 ;;; Generally useful functions
27932 (defun org-context ()
27933 "Return a list of contexts of the current cursor position.
27934 If several contexts apply, all are returned.
27935 Each context entry is a list with a symbol naming the context, and
27936 two positions indicating start and end of the context. Possible
27937 contexts are:
27939 :headline anywhere in a headline
27940 :headline-stars on the leading stars in a headline
27941 :todo-keyword on a TODO keyword (including DONE) in a headline
27942 :tags on the TAGS in a headline
27943 :priority on the priority cookie in a headline
27944 :item on the first line of a plain list item
27945 :item-bullet on the bullet/number of a plain list item
27946 :checkbox on the checkbox in a plain list item
27947 :table in an org-mode table
27948 :table-special on a special filed in a table
27949 :table-table in a table.el table
27950 :link on a hyperlink
27951 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27952 :target on a <<target>>
27953 :radio-target on a <<<radio-target>>>
27954 :latex-fragment on a LaTeX fragment
27955 :latex-preview on a LaTeX fragment with overlayed preview image
27957 This function expects the position to be visible because it uses font-lock
27958 faces as a help to recognize the following contexts: :table-special, :link,
27959 and :keyword."
27960 (let* ((f (get-text-property (point) 'face))
27961 (faces (if (listp f) f (list f)))
27962 (p (point)) clist o)
27963 ;; First the large context
27964 (cond
27965 ((org-on-heading-p t)
27966 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27967 (when (progn
27968 (beginning-of-line 1)
27969 (looking-at org-todo-line-tags-regexp))
27970 (push (org-point-in-group p 1 :headline-stars) clist)
27971 (push (org-point-in-group p 2 :todo-keyword) clist)
27972 (push (org-point-in-group p 4 :tags) clist))
27973 (goto-char p)
27974 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27975 (if (looking-at "\\[#[A-Z0-9]\\]")
27976 (push (org-point-in-group p 0 :priority) clist)))
27978 ((org-at-item-p)
27979 (push (org-point-in-group p 2 :item-bullet) clist)
27980 (push (list :item (point-at-bol)
27981 (save-excursion (org-end-of-item) (point)))
27982 clist)
27983 (and (org-at-item-checkbox-p)
27984 (push (org-point-in-group p 0 :checkbox) clist)))
27986 ((org-at-table-p)
27987 (push (list :table (org-table-begin) (org-table-end)) clist)
27988 (if (memq 'org-formula faces)
27989 (push (list :table-special
27990 (previous-single-property-change p 'face)
27991 (next-single-property-change p 'face)) clist)))
27992 ((org-at-table-p 'any)
27993 (push (list :table-table) clist)))
27994 (goto-char p)
27996 ;; Now the small context
27997 (cond
27998 ((org-at-timestamp-p)
27999 (push (org-point-in-group p 0 :timestamp) clist))
28000 ((memq 'org-link faces)
28001 (push (list :link
28002 (previous-single-property-change p 'face)
28003 (next-single-property-change p 'face)) clist))
28004 ((memq 'org-special-keyword faces)
28005 (push (list :keyword
28006 (previous-single-property-change p 'face)
28007 (next-single-property-change p 'face)) clist))
28008 ((org-on-target-p)
28009 (push (org-point-in-group p 0 :target) clist)
28010 (goto-char (1- (match-beginning 0)))
28011 (if (looking-at org-radio-target-regexp)
28012 (push (org-point-in-group p 0 :radio-target) clist))
28013 (goto-char p))
28014 ((setq o (car (delq nil
28015 (mapcar
28016 (lambda (x)
28017 (if (memq x org-latex-fragment-image-overlays) x))
28018 (org-overlays-at (point))))))
28019 (push (list :latex-fragment
28020 (org-overlay-start o) (org-overlay-end o)) clist)
28021 (push (list :latex-preview
28022 (org-overlay-start o) (org-overlay-end o)) clist))
28023 ((org-inside-LaTeX-fragment-p)
28024 ;; FIXME: positions wrong.
28025 (push (list :latex-fragment (point) (point)) clist)))
28027 (setq clist (nreverse (delq nil clist)))
28028 clist))
28030 ;; FIXME: Compare with at-regexp-p Do we need both?
28031 (defun org-in-regexp (re &optional nlines visually)
28032 "Check if point is inside a match of regexp.
28033 Normally only the current line is checked, but you can include NLINES extra
28034 lines both before and after point into the search.
28035 If VISUALLY is set, require that the cursor is not after the match but
28036 really on, so that the block visually is on the match."
28037 (catch 'exit
28038 (let ((pos (point))
28039 (eol (point-at-eol (+ 1 (or nlines 0))))
28040 (inc (if visually 1 0)))
28041 (save-excursion
28042 (beginning-of-line (- 1 (or nlines 0)))
28043 (while (re-search-forward re eol t)
28044 (if (and (<= (match-beginning 0) pos)
28045 (>= (+ inc (match-end 0)) pos))
28046 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
28048 (defun org-at-regexp-p (regexp)
28049 "Is point inside a match of REGEXP in the current line?"
28050 (catch 'exit
28051 (save-excursion
28052 (let ((pos (point)) (end (point-at-eol)))
28053 (beginning-of-line 1)
28054 (while (re-search-forward regexp end t)
28055 (if (and (<= (match-beginning 0) pos)
28056 (>= (match-end 0) pos))
28057 (throw 'exit t)))
28058 nil))))
28060 (defun org-occur-in-agenda-files (regexp &optional nlines)
28061 "Call `multi-occur' with buffers for all agenda files."
28062 (interactive "sOrg-files matching: \np")
28063 (let* ((files (org-agenda-files))
28064 (tnames (mapcar 'file-truename files))
28065 (extra org-agenda-text-search-extra-files)
28067 (while (setq f (pop extra))
28068 (unless (member (file-truename f) tnames)
28069 (add-to-list 'files f 'append)
28070 (add-to-list 'tnames (file-truename f) 'append)))
28071 (multi-occur
28072 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
28073 regexp)))
28075 (if (boundp 'occur-mode-find-occurrence-hook)
28076 ;; Emacs 23
28077 (add-hook 'occur-mode-find-occurrence-hook
28078 (lambda ()
28079 (when (org-mode-p)
28080 (org-reveal))))
28081 ;; Emacs 22
28082 (defadvice occur-mode-goto-occurrence
28083 (after org-occur-reveal activate)
28084 (and (org-mode-p) (org-reveal)))
28085 (defadvice occur-mode-goto-occurrence-other-window
28086 (after org-occur-reveal activate)
28087 (and (org-mode-p) (org-reveal)))
28088 (defadvice occur-mode-display-occurrence
28089 (after org-occur-reveal activate)
28090 (when (org-mode-p)
28091 (let ((pos (occur-mode-find-occurrence)))
28092 (with-current-buffer (marker-buffer pos)
28093 (save-excursion
28094 (goto-char pos)
28095 (org-reveal)))))))
28097 (defun org-uniquify (list)
28098 "Remove duplicate elements from LIST."
28099 (let (res)
28100 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28101 res))
28103 (defun org-delete-all (elts list)
28104 "Remove all elements in ELTS from LIST."
28105 (while elts
28106 (setq list (delete (pop elts) list)))
28107 list)
28109 (defun org-back-over-empty-lines ()
28110 "Move backwards over witespace, to the beginning of the first empty line.
28111 Returns the number o empty lines passed."
28112 (let ((pos (point)))
28113 (skip-chars-backward " \t\n\r")
28114 (beginning-of-line 2)
28115 (goto-char (min (point) pos))
28116 (count-lines (point) pos)))
28118 (defun org-skip-whitespace ()
28119 (skip-chars-forward " \t\n\r"))
28121 (defun org-point-in-group (point group &optional context)
28122 "Check if POINT is in match-group GROUP.
28123 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28124 match. If the match group does ot exist or point is not inside it,
28125 return nil."
28126 (and (match-beginning group)
28127 (>= point (match-beginning group))
28128 (<= point (match-end group))
28129 (if context
28130 (list context (match-beginning group) (match-end group))
28131 t)))
28133 (defun org-switch-to-buffer-other-window (&rest args)
28134 "Switch to buffer in a second window on the current frame.
28135 In particular, do not allow pop-up frames."
28136 (let (pop-up-frames special-display-buffer-names special-display-regexps
28137 special-display-function)
28138 (apply 'switch-to-buffer-other-window args)))
28140 (defun org-combine-plists (&rest plists)
28141 "Create a single property list from all plists in PLISTS.
28142 The process starts by copying the first list, and then setting properties
28143 from the other lists. Settings in the last list are the most significant
28144 ones and overrule settings in the other lists."
28145 (let ((rtn (copy-sequence (pop plists)))
28146 p v ls)
28147 (while plists
28148 (setq ls (pop plists))
28149 (while ls
28150 (setq p (pop ls) v (pop ls))
28151 (setq rtn (plist-put rtn p v))))
28152 rtn))
28154 (defun org-move-line-down (arg)
28155 "Move the current line down. With prefix argument, move it past ARG lines."
28156 (interactive "p")
28157 (let ((col (current-column))
28158 beg end pos)
28159 (beginning-of-line 1) (setq beg (point))
28160 (beginning-of-line 2) (setq end (point))
28161 (beginning-of-line (+ 1 arg))
28162 (setq pos (move-marker (make-marker) (point)))
28163 (insert (delete-and-extract-region beg end))
28164 (goto-char pos)
28165 (move-to-column col)))
28167 (defun org-move-line-up (arg)
28168 "Move the current line up. With prefix argument, move it past ARG lines."
28169 (interactive "p")
28170 (let ((col (current-column))
28171 beg end pos)
28172 (beginning-of-line 1) (setq beg (point))
28173 (beginning-of-line 2) (setq end (point))
28174 (beginning-of-line (- arg))
28175 (setq pos (move-marker (make-marker) (point)))
28176 (insert (delete-and-extract-region beg end))
28177 (goto-char pos)
28178 (move-to-column col)))
28180 (defun org-replace-escapes (string table)
28181 "Replace %-escapes in STRING with values in TABLE.
28182 TABLE is an association list with keys like \"%a\" and string values.
28183 The sequences in STRING may contain normal field width and padding information,
28184 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28185 so values can contain further %-escapes if they are define later in TABLE."
28186 (let ((case-fold-search nil)
28187 e re rpl)
28188 (while (setq e (pop table))
28189 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28190 (while (string-match re string)
28191 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28192 (cdr e)))
28193 (setq string (replace-match rpl t t string))))
28194 string))
28197 (defun org-sublist (list start end)
28198 "Return a section of LIST, from START to END.
28199 Counting starts at 1."
28200 (let (rtn (c start))
28201 (setq list (nthcdr (1- start) list))
28202 (while (and list (<= c end))
28203 (push (pop list) rtn)
28204 (setq c (1+ c)))
28205 (nreverse rtn)))
28207 (defun org-find-base-buffer-visiting (file)
28208 "Like `find-buffer-visiting' but alway return the base buffer and
28209 not an indirect buffer"
28210 (let ((buf (find-buffer-visiting file)))
28211 (if buf
28212 (or (buffer-base-buffer buf) buf)
28213 nil)))
28215 (defun org-image-file-name-regexp ()
28216 "Return regexp matching the file names of images."
28217 (if (fboundp 'image-file-name-regexp)
28218 (image-file-name-regexp)
28219 (let ((image-file-name-extensions
28220 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28221 "xbm" "xpm" "pbm" "pgm" "ppm")))
28222 (concat "\\."
28223 (regexp-opt (nconc (mapcar 'upcase
28224 image-file-name-extensions)
28225 image-file-name-extensions)
28227 "\\'"))))
28229 (defun org-file-image-p (file)
28230 "Return non-nil if FILE is an image."
28231 (save-match-data
28232 (string-match (org-image-file-name-regexp) file)))
28234 ;;; Paragraph filling stuff.
28235 ;; We want this to be just right, so use the full arsenal.
28237 (defun org-indent-line-function ()
28238 "Indent line like previous, but further if previous was headline or item."
28239 (interactive)
28240 (let* ((pos (point))
28241 (itemp (org-at-item-p))
28242 column bpos bcol tpos tcol bullet btype bullet-type)
28243 ;; Find the previous relevant line
28244 (beginning-of-line 1)
28245 (cond
28246 ((looking-at "#") (setq column 0))
28247 ((looking-at "\\*+ ") (setq column 0))
28249 (beginning-of-line 0)
28250 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28251 (beginning-of-line 0))
28252 (cond
28253 ((looking-at "\\*+[ \t]+")
28254 (goto-char (match-end 0))
28255 (setq column (current-column)))
28256 ((org-in-item-p)
28257 (org-beginning-of-item)
28258 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28259 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28260 (setq bpos (match-beginning 1) tpos (match-end 0)
28261 bcol (progn (goto-char bpos) (current-column))
28262 tcol (progn (goto-char tpos) (current-column))
28263 bullet (match-string 1)
28264 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28265 (if (not itemp)
28266 (setq column tcol)
28267 (goto-char pos)
28268 (beginning-of-line 1)
28269 (if (looking-at "\\S-")
28270 (progn
28271 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28272 (setq bullet (match-string 1)
28273 btype (if (string-match "[0-9]" bullet) "n" bullet))
28274 (setq column (if (equal btype bullet-type) bcol tcol)))
28275 (setq column (org-get-indentation)))))
28276 (t (setq column (org-get-indentation))))))
28277 (goto-char pos)
28278 (if (<= (current-column) (current-indentation))
28279 (indent-line-to column)
28280 (save-excursion (indent-line-to column)))
28281 (setq column (current-column))
28282 (beginning-of-line 1)
28283 (if (looking-at
28284 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28285 (replace-match (concat "\\1" (format org-property-format
28286 (match-string 2) (match-string 3)))
28287 t nil))
28288 (move-to-column column)))
28290 (defun org-set-autofill-regexps ()
28291 (interactive)
28292 ;; In the paragraph separator we include headlines, because filling
28293 ;; text in a line directly attached to a headline would otherwise
28294 ;; fill the headline as well.
28295 (org-set-local 'comment-start-skip "^#+[ \t]*")
28296 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28297 ;; The paragraph starter includes hand-formatted lists.
28298 (org-set-local 'paragraph-start
28299 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28300 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28301 ;; But only if the user has not turned off tables or fixed-width regions
28302 (org-set-local
28303 'auto-fill-inhibit-regexp
28304 (concat "\\*+ \\|#\\+"
28305 "\\|[ \t]*" org-keyword-time-regexp
28306 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28307 (concat
28308 "\\|[ \t]*["
28309 (if org-enable-table-editor "|" "")
28310 (if org-enable-fixed-width-editor ":" "")
28311 "]"))))
28312 ;; We use our own fill-paragraph function, to make sure that tables
28313 ;; and fixed-width regions are not wrapped. That function will pass
28314 ;; through to `fill-paragraph' when appropriate.
28315 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28316 ; Adaptive filling: To get full control, first make sure that
28317 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28318 (org-set-local 'adaptive-fill-regexp "\000")
28319 (org-set-local 'adaptive-fill-function
28320 'org-adaptive-fill-function)
28321 (org-set-local
28322 'align-mode-rules-list
28323 '((org-in-buffer-settings
28324 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28325 (modes . '(org-mode))))))
28327 (defun org-fill-paragraph (&optional justify)
28328 "Re-align a table, pass through to fill-paragraph if no table."
28329 (let ((table-p (org-at-table-p))
28330 (table.el-p (org-at-table.el-p)))
28331 (cond ((and (equal (char-after (point-at-bol)) ?*)
28332 (save-excursion (goto-char (point-at-bol))
28333 (looking-at outline-regexp)))
28334 t) ; skip headlines
28335 (table.el-p t) ; skip table.el tables
28336 (table-p (org-table-align) t) ; align org-mode tables
28337 (t nil)))) ; call paragraph-fill
28339 ;; For reference, this is the default value of adaptive-fill-regexp
28340 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28342 (defun org-adaptive-fill-function ()
28343 "Return a fill prefix for org-mode files.
28344 In particular, this makes sure hanging paragraphs for hand-formatted lists
28345 work correctly."
28346 (cond ((looking-at "#[ \t]+")
28347 (match-string 0))
28348 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28349 (save-excursion
28350 (goto-char (match-end 0))
28351 (make-string (current-column) ?\ )))
28352 (t nil)))
28354 ;;;; Functions extending outline functionality
28357 (defun org-beginning-of-line (&optional arg)
28358 "Go to the beginning of the current line. If that is invisible, continue
28359 to a visible line beginning. This makes the function of C-a more intuitive.
28360 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28361 first attempt, and only move to after the tags when the cursor is already
28362 beyond the end of the headline."
28363 (interactive "P")
28364 (let ((pos (point)))
28365 (beginning-of-line 1)
28366 (if (bobp)
28368 (backward-char 1)
28369 (if (org-invisible-p)
28370 (while (and (not (bobp)) (org-invisible-p))
28371 (backward-char 1)
28372 (beginning-of-line 1))
28373 (forward-char 1)))
28374 (when org-special-ctrl-a/e
28375 (cond
28376 ((and (looking-at org-todo-line-regexp)
28377 (= (char-after (match-end 1)) ?\ ))
28378 (goto-char
28379 (if (eq org-special-ctrl-a/e t)
28380 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28381 ((= pos (point)) (match-beginning 3))
28382 (t (point)))
28383 (cond ((> pos (point)) (point))
28384 ((not (eq last-command this-command)) (point))
28385 (t (match-beginning 3))))))
28386 ((org-at-item-p)
28387 (goto-char
28388 (if (eq org-special-ctrl-a/e t)
28389 (cond ((> pos (match-end 4)) (match-end 4))
28390 ((= pos (point)) (match-end 4))
28391 (t (point)))
28392 (cond ((> pos (point)) (point))
28393 ((not (eq last-command this-command)) (point))
28394 (t (match-end 4))))))))))
28396 (defun org-end-of-line (&optional arg)
28397 "Go to the end of the line.
28398 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28399 first attempt, and only move to after the tags when the cursor is already
28400 beyond the end of the headline."
28401 (interactive "P")
28402 (if (or (not org-special-ctrl-a/e)
28403 (not (org-on-heading-p)))
28404 (end-of-line arg)
28405 (let ((pos (point)))
28406 (beginning-of-line 1)
28407 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28408 (if (eq org-special-ctrl-a/e t)
28409 (if (or (< pos (match-beginning 1))
28410 (= pos (match-end 0)))
28411 (goto-char (match-beginning 1))
28412 (goto-char (match-end 0)))
28413 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28414 (goto-char (match-end 0))
28415 (goto-char (match-beginning 1))))
28416 (end-of-line arg)))))
28418 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28419 (define-key org-mode-map "\C-e" 'org-end-of-line)
28421 (defun org-kill-line (&optional arg)
28422 "Kill line, to tags or end of line."
28423 (interactive "P")
28424 (cond
28425 ((or (not org-special-ctrl-k)
28426 (bolp)
28427 (not (org-on-heading-p)))
28428 (call-interactively 'kill-line))
28429 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28430 (kill-region (point) (match-beginning 1))
28431 (org-set-tags nil t))
28432 (t (kill-region (point) (point-at-eol)))))
28434 (define-key org-mode-map "\C-k" 'org-kill-line)
28436 (defun org-invisible-p ()
28437 "Check if point is at a character currently not visible."
28438 ;; Early versions of noutline don't have `outline-invisible-p'.
28439 (if (fboundp 'outline-invisible-p)
28440 (outline-invisible-p)
28441 (get-char-property (point) 'invisible)))
28443 (defun org-invisible-p2 ()
28444 "Check if point is at a character currently not visible."
28445 (save-excursion
28446 (if (and (eolp) (not (bobp))) (backward-char 1))
28447 ;; Early versions of noutline don't have `outline-invisible-p'.
28448 (if (fboundp 'outline-invisible-p)
28449 (outline-invisible-p)
28450 (get-char-property (point) 'invisible))))
28452 (defalias 'org-back-to-heading 'outline-back-to-heading)
28453 (defalias 'org-on-heading-p 'outline-on-heading-p)
28454 (defalias 'org-at-heading-p 'outline-on-heading-p)
28455 (defun org-at-heading-or-item-p ()
28456 (or (org-on-heading-p) (org-at-item-p)))
28458 (defun org-on-target-p ()
28459 (or (org-in-regexp org-radio-target-regexp)
28460 (org-in-regexp org-target-regexp)))
28462 (defun org-up-heading-all (arg)
28463 "Move to the heading line of which the present line is a subheading.
28464 This function considers both visible and invisible heading lines.
28465 With argument, move up ARG levels."
28466 (if (fboundp 'outline-up-heading-all)
28467 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28468 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28470 (defun org-up-heading-safe ()
28471 "Move to the heading line of which the present line is a subheading.
28472 This version will not throw an error. It will return the level of the
28473 headline found, or nil if no higher level is found."
28474 (let ((pos (point)) start-level level
28475 (re (concat "^" outline-regexp)))
28476 (catch 'exit
28477 (outline-back-to-heading t)
28478 (setq start-level (funcall outline-level))
28479 (if (equal start-level 1) (throw 'exit nil))
28480 (while (re-search-backward re nil t)
28481 (setq level (funcall outline-level))
28482 (if (< level start-level) (throw 'exit level)))
28483 nil)))
28485 (defun org-first-sibling-p ()
28486 "Is this heading the first child of its parents?"
28487 (interactive)
28488 (let ((re (concat "^" outline-regexp))
28489 level l)
28490 (unless (org-at-heading-p t)
28491 (error "Not at a heading"))
28492 (setq level (funcall outline-level))
28493 (save-excursion
28494 (if (not (re-search-backward re nil t))
28496 (setq l (funcall outline-level))
28497 (< l level)))))
28499 (defun org-goto-sibling (&optional previous)
28500 "Goto the next sibling, even if it is invisible.
28501 When PREVIOUS is set, go to the previous sibling instead. Returns t
28502 when a sibling was found. When none is found, return nil and don't
28503 move point."
28504 (let ((fun (if previous 're-search-backward 're-search-forward))
28505 (pos (point))
28506 (re (concat "^" outline-regexp))
28507 level l)
28508 (when (condition-case nil (org-back-to-heading t) (error nil))
28509 (setq level (funcall outline-level))
28510 (catch 'exit
28511 (or previous (forward-char 1))
28512 (while (funcall fun re nil t)
28513 (setq l (funcall outline-level))
28514 (when (< l level) (goto-char pos) (throw 'exit nil))
28515 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28516 (goto-char pos)
28517 nil))))
28519 (defun org-show-siblings ()
28520 "Show all siblings of the current headline."
28521 (save-excursion
28522 (while (org-goto-sibling) (org-flag-heading nil)))
28523 (save-excursion
28524 (while (org-goto-sibling 'previous)
28525 (org-flag-heading nil))))
28527 (defun org-show-hidden-entry ()
28528 "Show an entry where even the heading is hidden."
28529 (save-excursion
28530 (org-show-entry)))
28532 (defun org-flag-heading (flag &optional entry)
28533 "Flag the current heading. FLAG non-nil means make invisible.
28534 When ENTRY is non-nil, show the entire entry."
28535 (save-excursion
28536 (org-back-to-heading t)
28537 ;; Check if we should show the entire entry
28538 (if entry
28539 (progn
28540 (org-show-entry)
28541 (save-excursion
28542 (and (outline-next-heading)
28543 (org-flag-heading nil))))
28544 (outline-flag-region (max (point-min) (1- (point)))
28545 (save-excursion (outline-end-of-heading) (point))
28546 flag))))
28548 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28549 ;; This is an exact copy of the original function, but it uses
28550 ;; `org-back-to-heading', to make it work also in invisible
28551 ;; trees. And is uses an invisible-OK argument.
28552 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28553 (org-back-to-heading invisible-OK)
28554 (let ((first t)
28555 (level (funcall outline-level)))
28556 (while (and (not (eobp))
28557 (or first (> (funcall outline-level) level)))
28558 (setq first nil)
28559 (outline-next-heading))
28560 (unless to-heading
28561 (if (memq (preceding-char) '(?\n ?\^M))
28562 (progn
28563 ;; Go to end of line before heading
28564 (forward-char -1)
28565 (if (memq (preceding-char) '(?\n ?\^M))
28566 ;; leave blank line before heading
28567 (forward-char -1))))))
28568 (point))
28570 (defun org-show-subtree ()
28571 "Show everything after this heading at deeper levels."
28572 (outline-flag-region
28573 (point)
28574 (save-excursion
28575 (outline-end-of-subtree) (outline-next-heading) (point))
28576 nil))
28578 (defun org-show-entry ()
28579 "Show the body directly following this heading.
28580 Show the heading too, if it is currently invisible."
28581 (interactive)
28582 (save-excursion
28583 (condition-case nil
28584 (progn
28585 (org-back-to-heading t)
28586 (outline-flag-region
28587 (max (point-min) (1- (point)))
28588 (save-excursion
28589 (re-search-forward
28590 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28591 (or (match-beginning 1) (point-max)))
28592 nil))
28593 (error nil))))
28595 (defun org-make-options-regexp (kwds)
28596 "Make a regular expression for keyword lines."
28597 (concat
28599 "#?[ \t]*\\+\\("
28600 (mapconcat 'regexp-quote kwds "\\|")
28601 "\\):[ \t]*"
28602 "\\(.+\\)"))
28604 ;; Make isearch reveal the necessary context
28605 (defun org-isearch-end ()
28606 "Reveal context after isearch exits."
28607 (when isearch-success ; only if search was successful
28608 (if (featurep 'xemacs)
28609 ;; Under XEmacs, the hook is run in the correct place,
28610 ;; we directly show the context.
28611 (org-show-context 'isearch)
28612 ;; In Emacs the hook runs *before* restoring the overlays.
28613 ;; So we have to use a one-time post-command-hook to do this.
28614 ;; (Emacs 22 has a special variable, see function `org-mode')
28615 (unless (and (boundp 'isearch-mode-end-hook-quit)
28616 isearch-mode-end-hook-quit)
28617 ;; Only when the isearch was not quitted.
28618 (org-add-hook 'post-command-hook 'org-isearch-post-command
28619 'append 'local)))))
28621 (defun org-isearch-post-command ()
28622 "Remove self from hook, and show context."
28623 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28624 (org-show-context 'isearch))
28627 ;;;; Integration with and fixes for other packages
28629 ;;; Imenu support
28631 (defvar org-imenu-markers nil
28632 "All markers currently used by Imenu.")
28633 (make-variable-buffer-local 'org-imenu-markers)
28635 (defun org-imenu-new-marker (&optional pos)
28636 "Return a new marker for use by Imenu, and remember the marker."
28637 (let ((m (make-marker)))
28638 (move-marker m (or pos (point)))
28639 (push m org-imenu-markers)
28642 (defun org-imenu-get-tree ()
28643 "Produce the index for Imenu."
28644 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28645 (setq org-imenu-markers nil)
28646 (let* ((n org-imenu-depth)
28647 (re (concat "^" outline-regexp))
28648 (subs (make-vector (1+ n) nil))
28649 (last-level 0)
28650 m tree level head)
28651 (save-excursion
28652 (save-restriction
28653 (widen)
28654 (goto-char (point-max))
28655 (while (re-search-backward re nil t)
28656 (setq level (org-reduced-level (funcall outline-level)))
28657 (when (<= level n)
28658 (looking-at org-complex-heading-regexp)
28659 (setq head (org-match-string-no-properties 4)
28660 m (org-imenu-new-marker))
28661 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28662 (if (>= level last-level)
28663 (push (cons head m) (aref subs level))
28664 (push (cons head (aref subs (1+ level))) (aref subs level))
28665 (loop for i from (1+ level) to n do (aset subs i nil)))
28666 (setq last-level level)))))
28667 (aref subs 1)))
28669 (eval-after-load "imenu"
28670 '(progn
28671 (add-hook 'imenu-after-jump-hook
28672 (lambda () (org-show-context 'org-goto)))))
28674 ;; Speedbar support
28676 (defun org-speedbar-set-agenda-restriction ()
28677 "Restrict future agenda commands to the location at point in speedbar.
28678 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28679 (interactive)
28680 (let (p m tp np dir txt w)
28681 (cond
28682 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28683 'org-imenu t))
28684 (setq m (get-text-property p 'org-imenu-marker))
28685 (save-excursion
28686 (save-restriction
28687 (set-buffer (marker-buffer m))
28688 (goto-char m)
28689 (org-agenda-set-restriction-lock 'subtree))))
28690 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28691 'speedbar-function 'speedbar-find-file))
28692 (setq tp (previous-single-property-change
28693 (1+ p) 'speedbar-function)
28694 np (next-single-property-change
28695 tp 'speedbar-function)
28696 dir (speedbar-line-directory)
28697 txt (buffer-substring-no-properties (or tp (point-min))
28698 (or np (point-max))))
28699 (save-excursion
28700 (save-restriction
28701 (set-buffer (find-file-noselect
28702 (let ((default-directory dir))
28703 (expand-file-name txt))))
28704 (unless (org-mode-p)
28705 (error "Cannot restrict to non-Org-mode file"))
28706 (org-agenda-set-restriction-lock 'file))))
28707 (t (error "Don't know how to restrict Org-mode's agenda")))
28708 (org-move-overlay org-speedbar-restriction-lock-overlay
28709 (point-at-bol) (point-at-eol))
28710 (setq current-prefix-arg nil)
28711 (org-agenda-maybe-redo)))
28713 (eval-after-load "speedbar"
28714 '(progn
28715 (speedbar-add-supported-extension ".org")
28716 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28717 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28718 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28719 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28720 (add-hook 'speedbar-visiting-tag-hook
28721 (lambda () (org-show-context 'org-goto)))))
28724 ;;; Fixes and Hacks
28726 ;; Make flyspell not check words in links, to not mess up our keymap
28727 (defun org-mode-flyspell-verify ()
28728 "Don't let flyspell put overlays at active buttons."
28729 (not (get-text-property (point) 'keymap)))
28731 ;; Make `bookmark-jump' show the jump location if it was hidden.
28732 (eval-after-load "bookmark"
28733 '(if (boundp 'bookmark-after-jump-hook)
28734 ;; We can use the hook
28735 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28736 ;; Hook not available, use advice
28737 (defadvice bookmark-jump (after org-make-visible activate)
28738 "Make the position visible."
28739 (org-bookmark-jump-unhide))))
28741 (defun org-bookmark-jump-unhide ()
28742 "Unhide the current position, to show the bookmark location."
28743 (and (org-mode-p)
28744 (or (org-invisible-p)
28745 (save-excursion (goto-char (max (point-min) (1- (point))))
28746 (org-invisible-p)))
28747 (org-show-context 'bookmark-jump)))
28749 ;; Fix a bug in htmlize where there are text properties (face nil)
28750 (eval-after-load "htmlize"
28751 '(progn
28752 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28753 "Make sure there are no nil faces"
28754 (setq ad-return-value (delq nil ad-return-value)))))
28756 ;; Make session.el ignore our circular variable
28757 (eval-after-load "session"
28758 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28760 ;;;; Experimental code
28762 (defun org-closed-in-range ()
28763 "Sparse tree of items closed in a certain time range.
28764 Still experimental, may disappear in the future."
28765 (interactive)
28766 ;; Get the time interval from the user.
28767 (let* ((time1 (time-to-seconds
28768 (org-read-date nil 'to-time nil "Starting date: ")))
28769 (time2 (time-to-seconds
28770 (org-read-date nil 'to-time nil "End date:")))
28771 ;; callback function
28772 (callback (lambda ()
28773 (let ((time
28774 (time-to-seconds
28775 (apply 'encode-time
28776 (org-parse-time-string
28777 (match-string 1))))))
28778 ;; check if time in interval
28779 (and (>= time time1) (<= time time2))))))
28780 ;; make tree, check each match with the callback
28781 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28783 ;;;; Finish up
28785 (provide 'org)
28787 (run-hooks 'org-load-hook)
28789 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28790 ;;; org.el ends here